xref: /linux/kernel/bpf/verifier.c (revision e3d0dbb3b5e8983d3be780199af1e5134c8a9c17)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 enum bpf_features {
48 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 	BPF_FEAT_STREAMS	     = 1,
50 	__MAX_BPF_FEAT,
51 };
52 
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55 
56 /* bpf_check() is a static code analyzer that walks eBPF program
57  * instruction by instruction and updates register/stack state.
58  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59  *
60  * The first pass is depth-first-search to check that the program is a DAG.
61  * It rejects the following programs:
62  * - larger than BPF_MAXINSNS insns
63  * - if loop is present (detected via back-edge)
64  * - unreachable insns exist (shouldn't be a forest. program = one function)
65  * - out of bounds or malformed jumps
66  * The second pass is all possible path descent from the 1st insn.
67  * Since it's analyzing all paths through the program, the length of the
68  * analysis is limited to 64k insn, which may be hit even if total number of
69  * insn is less then 4K, but there are too many branches that change stack/regs.
70  * Number of 'branches to be analyzed' is limited to 1k
71  *
72  * On entry to each instruction, each register has a type, and the instruction
73  * changes the types of the registers depending on instruction semantics.
74  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75  * copied to R1.
76  *
77  * All registers are 64-bit.
78  * R0 - return register
79  * R1-R5 argument passing registers
80  * R6-R9 callee saved registers
81  * R10 - frame pointer read-only
82  *
83  * At the start of BPF program the register R1 contains a pointer to bpf_context
84  * and has type PTR_TO_CTX.
85  *
86  * Verifier tracks arithmetic operations on pointers in case:
87  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89  * 1st insn copies R10 (which has FRAME_PTR) type into R1
90  * and 2nd arithmetic instruction is pattern matched to recognize
91  * that it wants to construct a pointer to some element within stack.
92  * So after 2nd insn, the register R1 has type PTR_TO_STACK
93  * (and -20 constant is saved for further stack bounds checking).
94  * Meaning that this reg is a pointer to stack plus known immediate constant.
95  *
96  * Most of the time the registers have SCALAR_VALUE type, which
97  * means the register has some value, but it's not a valid pointer.
98  * (like pointer plus pointer becomes SCALAR_VALUE type)
99  *
100  * When verifier sees load or store instructions the type of base register
101  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102  * four pointer types recognized by check_mem_access() function.
103  *
104  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105  * and the range of [ptr, ptr + map's value_size) is accessible.
106  *
107  * registers used to pass values to function calls are checked against
108  * function argument constraints.
109  *
110  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111  * It means that the register type passed to this function must be
112  * PTR_TO_STACK and it will be used inside the function as
113  * 'pointer to map element key'
114  *
115  * For example the argument constraints for bpf_map_lookup_elem():
116  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117  *   .arg1_type = ARG_CONST_MAP_PTR,
118  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
119  *
120  * ret_type says that this function returns 'pointer to map elem value or null'
121  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122  * 2nd argument should be a pointer to stack, which will be used inside
123  * the helper function as a pointer to map element key.
124  *
125  * On the kernel side the helper function looks like:
126  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127  * {
128  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129  *    void *key = (void *) (unsigned long) r2;
130  *    void *value;
131  *
132  *    here kernel can access 'key' and 'map' pointers safely, knowing that
133  *    [key, key + map->key_size) bytes are valid and were initialized on
134  *    the stack of eBPF program.
135  * }
136  *
137  * Corresponding eBPF program may look like:
138  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
139  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
141  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142  * here verifier looks at prototype of map_lookup_elem() and sees:
143  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145  *
146  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148  * and were initialized prior to this call.
149  * If it's ok, then verifier allows this BPF_CALL insn and looks at
150  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152  * returns either pointer to map value or NULL.
153  *
154  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155  * insn, the register holding that pointer in the true branch changes state to
156  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157  * branch. See check_cond_jmp_op().
158  *
159  * After the call R0 is set to return type of the function and registers R1-R5
160  * are set to NOT_INIT to indicate that they are no longer readable.
161  *
162  * The following reference types represent a potential reference to a kernel
163  * resource which, after first being allocated, must be checked and freed by
164  * the BPF program:
165  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166  *
167  * When the verifier sees a helper call return a reference type, it allocates a
168  * pointer id for the reference and stores it in the current function state.
169  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171  * passes through a NULL-check conditional. For the branch wherein the state is
172  * changed to CONST_IMM, the verifier releases the reference.
173  *
174  * For each helper function that allocates a reference, such as
175  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176  * bpf_sk_release(). When a reference type passes into the release function,
177  * the verifier also releases the reference. If any unchecked or unreleased
178  * reference remains at the end of the program, the verifier rejects it.
179  */
180 
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 	/* verifier state is 'st'
184 	 * before processing instruction 'insn_idx'
185 	 * and after processing instruction 'prev_insn_idx'
186 	 */
187 	struct bpf_verifier_state st;
188 	int insn_idx;
189 	int prev_insn_idx;
190 	struct bpf_verifier_stack_elem *next;
191 	/* length of verifier log at the time this state was pushed on stack */
192 	u32 log_pos;
193 };
194 
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
196 #define BPF_COMPLEXITY_LIMIT_STATES	64
197 
198 #define BPF_MAP_KEY_POISON	(1ULL << 63)
199 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
200 
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
202 
203 #define BPF_PRIV_STACK_MIN_SIZE		64
204 
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 			      struct bpf_reg_state *reg);
212 static bool is_trusted_reg(const struct bpf_reg_state *reg);
213 
214 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
215 {
216 	return aux->map_ptr_state.poison;
217 }
218 
219 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
220 {
221 	return aux->map_ptr_state.unpriv;
222 }
223 
224 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
225 			      struct bpf_map *map,
226 			      bool unpriv, bool poison)
227 {
228 	unpriv |= bpf_map_ptr_unpriv(aux);
229 	aux->map_ptr_state.unpriv = unpriv;
230 	aux->map_ptr_state.poison = poison;
231 	aux->map_ptr_state.map_ptr = map;
232 }
233 
234 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
235 {
236 	return aux->map_key_state & BPF_MAP_KEY_POISON;
237 }
238 
239 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
240 {
241 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
242 }
243 
244 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
245 {
246 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
247 }
248 
249 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
250 {
251 	bool poisoned = bpf_map_key_poisoned(aux);
252 
253 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
254 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
255 }
256 
257 static bool bpf_helper_call(const struct bpf_insn *insn)
258 {
259 	return insn->code == (BPF_JMP | BPF_CALL) &&
260 	       insn->src_reg == 0;
261 }
262 
263 static bool bpf_pseudo_call(const struct bpf_insn *insn)
264 {
265 	return insn->code == (BPF_JMP | BPF_CALL) &&
266 	       insn->src_reg == BPF_PSEUDO_CALL;
267 }
268 
269 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
270 {
271 	return insn->code == (BPF_JMP | BPF_CALL) &&
272 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
273 }
274 
275 struct bpf_call_arg_meta {
276 	struct bpf_map *map_ptr;
277 	bool raw_mode;
278 	bool pkt_access;
279 	u8 release_regno;
280 	int regno;
281 	int access_size;
282 	int mem_size;
283 	u64 msize_max_value;
284 	int ref_obj_id;
285 	int dynptr_id;
286 	int map_uid;
287 	int func_id;
288 	struct btf *btf;
289 	u32 btf_id;
290 	struct btf *ret_btf;
291 	u32 ret_btf_id;
292 	u32 subprogno;
293 	struct btf_field *kptr_field;
294 	s64 const_map_key;
295 };
296 
297 struct bpf_kfunc_call_arg_meta {
298 	/* In parameters */
299 	struct btf *btf;
300 	u32 func_id;
301 	u32 kfunc_flags;
302 	const struct btf_type *func_proto;
303 	const char *func_name;
304 	/* Out parameters */
305 	u32 ref_obj_id;
306 	u8 release_regno;
307 	bool r0_rdonly;
308 	u32 ret_btf_id;
309 	u64 r0_size;
310 	u32 subprogno;
311 	struct {
312 		u64 value;
313 		bool found;
314 	} arg_constant;
315 
316 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
317 	 * generally to pass info about user-defined local kptr types to later
318 	 * verification logic
319 	 *   bpf_obj_drop/bpf_percpu_obj_drop
320 	 *     Record the local kptr type to be drop'd
321 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
322 	 *     Record the local kptr type to be refcount_incr'd and use
323 	 *     arg_owning_ref to determine whether refcount_acquire should be
324 	 *     fallible
325 	 */
326 	struct btf *arg_btf;
327 	u32 arg_btf_id;
328 	bool arg_owning_ref;
329 	bool arg_prog;
330 
331 	struct {
332 		struct btf_field *field;
333 	} arg_list_head;
334 	struct {
335 		struct btf_field *field;
336 	} arg_rbtree_root;
337 	struct {
338 		enum bpf_dynptr_type type;
339 		u32 id;
340 		u32 ref_obj_id;
341 	} initialized_dynptr;
342 	struct {
343 		u8 spi;
344 		u8 frameno;
345 	} iter;
346 	struct {
347 		struct bpf_map *ptr;
348 		int uid;
349 	} map;
350 	u64 mem_size;
351 };
352 
353 struct btf *btf_vmlinux;
354 
355 static const char *btf_type_name(const struct btf *btf, u32 id)
356 {
357 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
358 }
359 
360 static DEFINE_MUTEX(bpf_verifier_lock);
361 static DEFINE_MUTEX(bpf_percpu_ma_lock);
362 
363 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
364 {
365 	struct bpf_verifier_env *env = private_data;
366 	va_list args;
367 
368 	if (!bpf_verifier_log_needed(&env->log))
369 		return;
370 
371 	va_start(args, fmt);
372 	bpf_verifier_vlog(&env->log, fmt, args);
373 	va_end(args);
374 }
375 
376 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
377 				   struct bpf_reg_state *reg,
378 				   struct bpf_retval_range range, const char *ctx,
379 				   const char *reg_name)
380 {
381 	bool unknown = true;
382 
383 	verbose(env, "%s the register %s has", ctx, reg_name);
384 	if (reg->smin_value > S64_MIN) {
385 		verbose(env, " smin=%lld", reg->smin_value);
386 		unknown = false;
387 	}
388 	if (reg->smax_value < S64_MAX) {
389 		verbose(env, " smax=%lld", reg->smax_value);
390 		unknown = false;
391 	}
392 	if (unknown)
393 		verbose(env, " unknown scalar value");
394 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
395 }
396 
397 static bool reg_not_null(const struct bpf_reg_state *reg)
398 {
399 	enum bpf_reg_type type;
400 
401 	type = reg->type;
402 	if (type_may_be_null(type))
403 		return false;
404 
405 	type = base_type(type);
406 	return type == PTR_TO_SOCKET ||
407 		type == PTR_TO_TCP_SOCK ||
408 		type == PTR_TO_MAP_VALUE ||
409 		type == PTR_TO_MAP_KEY ||
410 		type == PTR_TO_SOCK_COMMON ||
411 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
412 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
413 		type == CONST_PTR_TO_MAP;
414 }
415 
416 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
417 {
418 	struct btf_record *rec = NULL;
419 	struct btf_struct_meta *meta;
420 
421 	if (reg->type == PTR_TO_MAP_VALUE) {
422 		rec = reg->map_ptr->record;
423 	} else if (type_is_ptr_alloc_obj(reg->type)) {
424 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
425 		if (meta)
426 			rec = meta->record;
427 	}
428 	return rec;
429 }
430 
431 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
434 
435 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
436 }
437 
438 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
439 {
440 	struct bpf_func_info *info;
441 
442 	if (!env->prog->aux->func_info)
443 		return "";
444 
445 	info = &env->prog->aux->func_info[subprog];
446 	return btf_type_name(env->prog->aux->btf, info->type_id);
447 }
448 
449 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
450 {
451 	struct bpf_subprog_info *info = subprog_info(env, subprog);
452 
453 	info->is_cb = true;
454 	info->is_async_cb = true;
455 	info->is_exception_cb = true;
456 }
457 
458 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
459 {
460 	return subprog_info(env, subprog)->is_exception_cb;
461 }
462 
463 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
464 {
465 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
466 }
467 
468 static bool type_is_rdonly_mem(u32 type)
469 {
470 	return type & MEM_RDONLY;
471 }
472 
473 static bool is_acquire_function(enum bpf_func_id func_id,
474 				const struct bpf_map *map)
475 {
476 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
477 
478 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
479 	    func_id == BPF_FUNC_sk_lookup_udp ||
480 	    func_id == BPF_FUNC_skc_lookup_tcp ||
481 	    func_id == BPF_FUNC_ringbuf_reserve ||
482 	    func_id == BPF_FUNC_kptr_xchg)
483 		return true;
484 
485 	if (func_id == BPF_FUNC_map_lookup_elem &&
486 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
487 	     map_type == BPF_MAP_TYPE_SOCKHASH))
488 		return true;
489 
490 	return false;
491 }
492 
493 static bool is_ptr_cast_function(enum bpf_func_id func_id)
494 {
495 	return func_id == BPF_FUNC_tcp_sock ||
496 		func_id == BPF_FUNC_sk_fullsock ||
497 		func_id == BPF_FUNC_skc_to_tcp_sock ||
498 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
499 		func_id == BPF_FUNC_skc_to_udp6_sock ||
500 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
501 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
502 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
503 }
504 
505 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
506 {
507 	return func_id == BPF_FUNC_dynptr_data;
508 }
509 
510 static bool is_sync_callback_calling_kfunc(u32 btf_id);
511 static bool is_async_callback_calling_kfunc(u32 btf_id);
512 static bool is_callback_calling_kfunc(u32 btf_id);
513 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
514 
515 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
516 static bool is_task_work_add_kfunc(u32 func_id);
517 
518 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
519 {
520 	return func_id == BPF_FUNC_for_each_map_elem ||
521 	       func_id == BPF_FUNC_find_vma ||
522 	       func_id == BPF_FUNC_loop ||
523 	       func_id == BPF_FUNC_user_ringbuf_drain;
524 }
525 
526 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_timer_set_callback;
529 }
530 
531 static bool is_callback_calling_function(enum bpf_func_id func_id)
532 {
533 	return is_sync_callback_calling_function(func_id) ||
534 	       is_async_callback_calling_function(func_id);
535 }
536 
537 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
538 {
539 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
540 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
541 }
542 
543 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
544 {
545 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
546 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
547 }
548 
549 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
550 {
551 	/* bpf_timer callbacks are never sleepable. */
552 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
553 		return false;
554 
555 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
556 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
557 	    (is_bpf_wq_set_callback_impl_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
558 		return true;
559 
560 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
561 	return false;
562 }
563 
564 static bool is_may_goto_insn(struct bpf_insn *insn)
565 {
566 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
567 }
568 
569 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
570 {
571 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
572 }
573 
574 static bool is_storage_get_function(enum bpf_func_id func_id)
575 {
576 	return func_id == BPF_FUNC_sk_storage_get ||
577 	       func_id == BPF_FUNC_inode_storage_get ||
578 	       func_id == BPF_FUNC_task_storage_get ||
579 	       func_id == BPF_FUNC_cgrp_storage_get;
580 }
581 
582 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
583 					const struct bpf_map *map)
584 {
585 	int ref_obj_uses = 0;
586 
587 	if (is_ptr_cast_function(func_id))
588 		ref_obj_uses++;
589 	if (is_acquire_function(func_id, map))
590 		ref_obj_uses++;
591 	if (is_dynptr_ref_function(func_id))
592 		ref_obj_uses++;
593 
594 	return ref_obj_uses > 1;
595 }
596 
597 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
598 {
599 	return BPF_CLASS(insn->code) == BPF_STX &&
600 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
601 	       insn->imm == BPF_CMPXCHG;
602 }
603 
604 static bool is_atomic_load_insn(const struct bpf_insn *insn)
605 {
606 	return BPF_CLASS(insn->code) == BPF_STX &&
607 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
608 	       insn->imm == BPF_LOAD_ACQ;
609 }
610 
611 static int __get_spi(s32 off)
612 {
613 	return (-off - 1) / BPF_REG_SIZE;
614 }
615 
616 static struct bpf_func_state *func(struct bpf_verifier_env *env,
617 				   const struct bpf_reg_state *reg)
618 {
619 	struct bpf_verifier_state *cur = env->cur_state;
620 
621 	return cur->frame[reg->frameno];
622 }
623 
624 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
625 {
626        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
627 
628        /* We need to check that slots between [spi - nr_slots + 1, spi] are
629 	* within [0, allocated_stack).
630 	*
631 	* Please note that the spi grows downwards. For example, a dynptr
632 	* takes the size of two stack slots; the first slot will be at
633 	* spi and the second slot will be at spi - 1.
634 	*/
635        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
636 }
637 
638 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
639 			          const char *obj_kind, int nr_slots)
640 {
641 	int off, spi;
642 
643 	if (!tnum_is_const(reg->var_off)) {
644 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
645 		return -EINVAL;
646 	}
647 
648 	off = reg->off + reg->var_off.value;
649 	if (off % BPF_REG_SIZE) {
650 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
651 		return -EINVAL;
652 	}
653 
654 	spi = __get_spi(off);
655 	if (spi + 1 < nr_slots) {
656 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
657 		return -EINVAL;
658 	}
659 
660 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
661 		return -ERANGE;
662 	return spi;
663 }
664 
665 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
666 {
667 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
668 }
669 
670 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
671 {
672 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
673 }
674 
675 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
676 {
677 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
678 }
679 
680 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
681 {
682 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
683 	case DYNPTR_TYPE_LOCAL:
684 		return BPF_DYNPTR_TYPE_LOCAL;
685 	case DYNPTR_TYPE_RINGBUF:
686 		return BPF_DYNPTR_TYPE_RINGBUF;
687 	case DYNPTR_TYPE_SKB:
688 		return BPF_DYNPTR_TYPE_SKB;
689 	case DYNPTR_TYPE_XDP:
690 		return BPF_DYNPTR_TYPE_XDP;
691 	case DYNPTR_TYPE_SKB_META:
692 		return BPF_DYNPTR_TYPE_SKB_META;
693 	case DYNPTR_TYPE_FILE:
694 		return BPF_DYNPTR_TYPE_FILE;
695 	default:
696 		return BPF_DYNPTR_TYPE_INVALID;
697 	}
698 }
699 
700 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
701 {
702 	switch (type) {
703 	case BPF_DYNPTR_TYPE_LOCAL:
704 		return DYNPTR_TYPE_LOCAL;
705 	case BPF_DYNPTR_TYPE_RINGBUF:
706 		return DYNPTR_TYPE_RINGBUF;
707 	case BPF_DYNPTR_TYPE_SKB:
708 		return DYNPTR_TYPE_SKB;
709 	case BPF_DYNPTR_TYPE_XDP:
710 		return DYNPTR_TYPE_XDP;
711 	case BPF_DYNPTR_TYPE_SKB_META:
712 		return DYNPTR_TYPE_SKB_META;
713 	case BPF_DYNPTR_TYPE_FILE:
714 		return DYNPTR_TYPE_FILE;
715 	default:
716 		return 0;
717 	}
718 }
719 
720 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
721 {
722 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
723 }
724 
725 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
726 			      enum bpf_dynptr_type type,
727 			      bool first_slot, int dynptr_id);
728 
729 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
730 				struct bpf_reg_state *reg);
731 
732 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
733 				   struct bpf_reg_state *sreg1,
734 				   struct bpf_reg_state *sreg2,
735 				   enum bpf_dynptr_type type)
736 {
737 	int id = ++env->id_gen;
738 
739 	__mark_dynptr_reg(sreg1, type, true, id);
740 	__mark_dynptr_reg(sreg2, type, false, id);
741 }
742 
743 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
744 			       struct bpf_reg_state *reg,
745 			       enum bpf_dynptr_type type)
746 {
747 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
748 }
749 
750 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
751 				        struct bpf_func_state *state, int spi);
752 
753 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
754 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
755 {
756 	struct bpf_func_state *state = func(env, reg);
757 	enum bpf_dynptr_type type;
758 	int spi, i, err;
759 
760 	spi = dynptr_get_spi(env, reg);
761 	if (spi < 0)
762 		return spi;
763 
764 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
765 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
766 	 * to ensure that for the following example:
767 	 *	[d1][d1][d2][d2]
768 	 * spi    3   2   1   0
769 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
770 	 * case they do belong to same dynptr, second call won't see slot_type
771 	 * as STACK_DYNPTR and will simply skip destruction.
772 	 */
773 	err = destroy_if_dynptr_stack_slot(env, state, spi);
774 	if (err)
775 		return err;
776 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
777 	if (err)
778 		return err;
779 
780 	for (i = 0; i < BPF_REG_SIZE; i++) {
781 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
782 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
783 	}
784 
785 	type = arg_to_dynptr_type(arg_type);
786 	if (type == BPF_DYNPTR_TYPE_INVALID)
787 		return -EINVAL;
788 
789 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
790 			       &state->stack[spi - 1].spilled_ptr, type);
791 
792 	if (dynptr_type_refcounted(type)) {
793 		/* The id is used to track proper releasing */
794 		int id;
795 
796 		if (clone_ref_obj_id)
797 			id = clone_ref_obj_id;
798 		else
799 			id = acquire_reference(env, insn_idx);
800 
801 		if (id < 0)
802 			return id;
803 
804 		state->stack[spi].spilled_ptr.ref_obj_id = id;
805 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
806 	}
807 
808 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
809 
810 	return 0;
811 }
812 
813 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
814 {
815 	int i;
816 
817 	for (i = 0; i < BPF_REG_SIZE; i++) {
818 		state->stack[spi].slot_type[i] = STACK_INVALID;
819 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
820 	}
821 
822 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
823 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
824 
825 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
826 }
827 
828 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
829 {
830 	struct bpf_func_state *state = func(env, reg);
831 	int spi, ref_obj_id, i;
832 
833 	/*
834 	 * This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
835 	 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
836 	 * is safe to do directly.
837 	 */
838 	if (reg->type == CONST_PTR_TO_DYNPTR) {
839 		verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
840 		return -EFAULT;
841 	}
842 	spi = dynptr_get_spi(env, reg);
843 	if (spi < 0)
844 		return spi;
845 
846 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
847 		invalidate_dynptr(env, state, spi);
848 		return 0;
849 	}
850 
851 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
852 
853 	/* If the dynptr has a ref_obj_id, then we need to invalidate
854 	 * two things:
855 	 *
856 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
857 	 * 2) Any slices derived from this dynptr.
858 	 */
859 
860 	/* Invalidate any slices associated with this dynptr */
861 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
862 
863 	/* Invalidate any dynptr clones */
864 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
865 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
866 			continue;
867 
868 		/* it should always be the case that if the ref obj id
869 		 * matches then the stack slot also belongs to a
870 		 * dynptr
871 		 */
872 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
873 			verifier_bug(env, "misconfigured ref_obj_id");
874 			return -EFAULT;
875 		}
876 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
877 			invalidate_dynptr(env, state, i);
878 	}
879 
880 	return 0;
881 }
882 
883 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
884 			       struct bpf_reg_state *reg);
885 
886 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
887 {
888 	if (!env->allow_ptr_leaks)
889 		__mark_reg_not_init(env, reg);
890 	else
891 		__mark_reg_unknown(env, reg);
892 }
893 
894 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
895 				        struct bpf_func_state *state, int spi)
896 {
897 	struct bpf_func_state *fstate;
898 	struct bpf_reg_state *dreg;
899 	int i, dynptr_id;
900 
901 	/* We always ensure that STACK_DYNPTR is never set partially,
902 	 * hence just checking for slot_type[0] is enough. This is
903 	 * different for STACK_SPILL, where it may be only set for
904 	 * 1 byte, so code has to use is_spilled_reg.
905 	 */
906 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
907 		return 0;
908 
909 	/* Reposition spi to first slot */
910 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
911 		spi = spi + 1;
912 
913 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
914 		verbose(env, "cannot overwrite referenced dynptr\n");
915 		return -EINVAL;
916 	}
917 
918 	mark_stack_slot_scratched(env, spi);
919 	mark_stack_slot_scratched(env, spi - 1);
920 
921 	/* Writing partially to one dynptr stack slot destroys both. */
922 	for (i = 0; i < BPF_REG_SIZE; i++) {
923 		state->stack[spi].slot_type[i] = STACK_INVALID;
924 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
925 	}
926 
927 	dynptr_id = state->stack[spi].spilled_ptr.id;
928 	/* Invalidate any slices associated with this dynptr */
929 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
930 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
931 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
932 			continue;
933 		if (dreg->dynptr_id == dynptr_id)
934 			mark_reg_invalid(env, dreg);
935 	}));
936 
937 	/* Do not release reference state, we are destroying dynptr on stack,
938 	 * not using some helper to release it. Just reset register.
939 	 */
940 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
941 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
942 
943 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
944 
945 	return 0;
946 }
947 
948 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
949 {
950 	int spi;
951 
952 	if (reg->type == CONST_PTR_TO_DYNPTR)
953 		return false;
954 
955 	spi = dynptr_get_spi(env, reg);
956 
957 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
958 	 * error because this just means the stack state hasn't been updated yet.
959 	 * We will do check_mem_access to check and update stack bounds later.
960 	 */
961 	if (spi < 0 && spi != -ERANGE)
962 		return false;
963 
964 	/* We don't need to check if the stack slots are marked by previous
965 	 * dynptr initializations because we allow overwriting existing unreferenced
966 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
967 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
968 	 * touching are completely destructed before we reinitialize them for a new
969 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
970 	 * instead of delaying it until the end where the user will get "Unreleased
971 	 * reference" error.
972 	 */
973 	return true;
974 }
975 
976 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
977 {
978 	struct bpf_func_state *state = func(env, reg);
979 	int i, spi;
980 
981 	/* This already represents first slot of initialized bpf_dynptr.
982 	 *
983 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
984 	 * check_func_arg_reg_off's logic, so we don't need to check its
985 	 * offset and alignment.
986 	 */
987 	if (reg->type == CONST_PTR_TO_DYNPTR)
988 		return true;
989 
990 	spi = dynptr_get_spi(env, reg);
991 	if (spi < 0)
992 		return false;
993 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
994 		return false;
995 
996 	for (i = 0; i < BPF_REG_SIZE; i++) {
997 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
998 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
999 			return false;
1000 	}
1001 
1002 	return true;
1003 }
1004 
1005 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1006 				    enum bpf_arg_type arg_type)
1007 {
1008 	struct bpf_func_state *state = func(env, reg);
1009 	enum bpf_dynptr_type dynptr_type;
1010 	int spi;
1011 
1012 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1013 	if (arg_type == ARG_PTR_TO_DYNPTR)
1014 		return true;
1015 
1016 	dynptr_type = arg_to_dynptr_type(arg_type);
1017 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1018 		return reg->dynptr.type == dynptr_type;
1019 	} else {
1020 		spi = dynptr_get_spi(env, reg);
1021 		if (spi < 0)
1022 			return false;
1023 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1024 	}
1025 }
1026 
1027 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1028 
1029 static bool in_rcu_cs(struct bpf_verifier_env *env);
1030 
1031 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1032 
1033 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1034 				 struct bpf_kfunc_call_arg_meta *meta,
1035 				 struct bpf_reg_state *reg, int insn_idx,
1036 				 struct btf *btf, u32 btf_id, int nr_slots)
1037 {
1038 	struct bpf_func_state *state = func(env, reg);
1039 	int spi, i, j, id;
1040 
1041 	spi = iter_get_spi(env, reg, nr_slots);
1042 	if (spi < 0)
1043 		return spi;
1044 
1045 	id = acquire_reference(env, insn_idx);
1046 	if (id < 0)
1047 		return id;
1048 
1049 	for (i = 0; i < nr_slots; i++) {
1050 		struct bpf_stack_state *slot = &state->stack[spi - i];
1051 		struct bpf_reg_state *st = &slot->spilled_ptr;
1052 
1053 		__mark_reg_known_zero(st);
1054 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1055 		if (is_kfunc_rcu_protected(meta)) {
1056 			if (in_rcu_cs(env))
1057 				st->type |= MEM_RCU;
1058 			else
1059 				st->type |= PTR_UNTRUSTED;
1060 		}
1061 		st->ref_obj_id = i == 0 ? id : 0;
1062 		st->iter.btf = btf;
1063 		st->iter.btf_id = btf_id;
1064 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1065 		st->iter.depth = 0;
1066 
1067 		for (j = 0; j < BPF_REG_SIZE; j++)
1068 			slot->slot_type[j] = STACK_ITER;
1069 
1070 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1071 		mark_stack_slot_scratched(env, spi - i);
1072 	}
1073 
1074 	return 0;
1075 }
1076 
1077 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1078 				   struct bpf_reg_state *reg, int nr_slots)
1079 {
1080 	struct bpf_func_state *state = func(env, reg);
1081 	int spi, i, j;
1082 
1083 	spi = iter_get_spi(env, reg, nr_slots);
1084 	if (spi < 0)
1085 		return spi;
1086 
1087 	for (i = 0; i < nr_slots; i++) {
1088 		struct bpf_stack_state *slot = &state->stack[spi - i];
1089 		struct bpf_reg_state *st = &slot->spilled_ptr;
1090 
1091 		if (i == 0)
1092 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1093 
1094 		__mark_reg_not_init(env, st);
1095 
1096 		for (j = 0; j < BPF_REG_SIZE; j++)
1097 			slot->slot_type[j] = STACK_INVALID;
1098 
1099 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1100 		mark_stack_slot_scratched(env, spi - i);
1101 	}
1102 
1103 	return 0;
1104 }
1105 
1106 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1107 				     struct bpf_reg_state *reg, int nr_slots)
1108 {
1109 	struct bpf_func_state *state = func(env, reg);
1110 	int spi, i, j;
1111 
1112 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1113 	 * will do check_mem_access to check and update stack bounds later, so
1114 	 * return true for that case.
1115 	 */
1116 	spi = iter_get_spi(env, reg, nr_slots);
1117 	if (spi == -ERANGE)
1118 		return true;
1119 	if (spi < 0)
1120 		return false;
1121 
1122 	for (i = 0; i < nr_slots; i++) {
1123 		struct bpf_stack_state *slot = &state->stack[spi - i];
1124 
1125 		for (j = 0; j < BPF_REG_SIZE; j++)
1126 			if (slot->slot_type[j] == STACK_ITER)
1127 				return false;
1128 	}
1129 
1130 	return true;
1131 }
1132 
1133 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1134 				   struct btf *btf, u32 btf_id, int nr_slots)
1135 {
1136 	struct bpf_func_state *state = func(env, reg);
1137 	int spi, i, j;
1138 
1139 	spi = iter_get_spi(env, reg, nr_slots);
1140 	if (spi < 0)
1141 		return -EINVAL;
1142 
1143 	for (i = 0; i < nr_slots; i++) {
1144 		struct bpf_stack_state *slot = &state->stack[spi - i];
1145 		struct bpf_reg_state *st = &slot->spilled_ptr;
1146 
1147 		if (st->type & PTR_UNTRUSTED)
1148 			return -EPROTO;
1149 		/* only main (first) slot has ref_obj_id set */
1150 		if (i == 0 && !st->ref_obj_id)
1151 			return -EINVAL;
1152 		if (i != 0 && st->ref_obj_id)
1153 			return -EINVAL;
1154 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1155 			return -EINVAL;
1156 
1157 		for (j = 0; j < BPF_REG_SIZE; j++)
1158 			if (slot->slot_type[j] != STACK_ITER)
1159 				return -EINVAL;
1160 	}
1161 
1162 	return 0;
1163 }
1164 
1165 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1166 static int release_irq_state(struct bpf_verifier_state *state, int id);
1167 
1168 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1169 				     struct bpf_kfunc_call_arg_meta *meta,
1170 				     struct bpf_reg_state *reg, int insn_idx,
1171 				     int kfunc_class)
1172 {
1173 	struct bpf_func_state *state = func(env, reg);
1174 	struct bpf_stack_state *slot;
1175 	struct bpf_reg_state *st;
1176 	int spi, i, id;
1177 
1178 	spi = irq_flag_get_spi(env, reg);
1179 	if (spi < 0)
1180 		return spi;
1181 
1182 	id = acquire_irq_state(env, insn_idx);
1183 	if (id < 0)
1184 		return id;
1185 
1186 	slot = &state->stack[spi];
1187 	st = &slot->spilled_ptr;
1188 
1189 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1190 	__mark_reg_known_zero(st);
1191 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1192 	st->ref_obj_id = id;
1193 	st->irq.kfunc_class = kfunc_class;
1194 
1195 	for (i = 0; i < BPF_REG_SIZE; i++)
1196 		slot->slot_type[i] = STACK_IRQ_FLAG;
1197 
1198 	mark_stack_slot_scratched(env, spi);
1199 	return 0;
1200 }
1201 
1202 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1203 				      int kfunc_class)
1204 {
1205 	struct bpf_func_state *state = func(env, reg);
1206 	struct bpf_stack_state *slot;
1207 	struct bpf_reg_state *st;
1208 	int spi, i, err;
1209 
1210 	spi = irq_flag_get_spi(env, reg);
1211 	if (spi < 0)
1212 		return spi;
1213 
1214 	slot = &state->stack[spi];
1215 	st = &slot->spilled_ptr;
1216 
1217 	if (st->irq.kfunc_class != kfunc_class) {
1218 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1219 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1220 
1221 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1222 			flag_kfunc, used_kfunc);
1223 		return -EINVAL;
1224 	}
1225 
1226 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1227 	WARN_ON_ONCE(err && err != -EACCES);
1228 	if (err) {
1229 		int insn_idx = 0;
1230 
1231 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1232 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1233 				insn_idx = env->cur_state->refs[i].insn_idx;
1234 				break;
1235 			}
1236 		}
1237 
1238 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1239 			env->cur_state->active_irq_id, insn_idx);
1240 		return err;
1241 	}
1242 
1243 	__mark_reg_not_init(env, st);
1244 
1245 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1246 
1247 	for (i = 0; i < BPF_REG_SIZE; i++)
1248 		slot->slot_type[i] = STACK_INVALID;
1249 
1250 	mark_stack_slot_scratched(env, spi);
1251 	return 0;
1252 }
1253 
1254 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1255 {
1256 	struct bpf_func_state *state = func(env, reg);
1257 	struct bpf_stack_state *slot;
1258 	int spi, i;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = irq_flag_get_spi(env, reg);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	slot = &state->stack[spi];
1271 
1272 	for (i = 0; i < BPF_REG_SIZE; i++)
1273 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1274 			return false;
1275 	return true;
1276 }
1277 
1278 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1279 {
1280 	struct bpf_func_state *state = func(env, reg);
1281 	struct bpf_stack_state *slot;
1282 	struct bpf_reg_state *st;
1283 	int spi, i;
1284 
1285 	spi = irq_flag_get_spi(env, reg);
1286 	if (spi < 0)
1287 		return -EINVAL;
1288 
1289 	slot = &state->stack[spi];
1290 	st = &slot->spilled_ptr;
1291 
1292 	if (!st->ref_obj_id)
1293 		return -EINVAL;
1294 
1295 	for (i = 0; i < BPF_REG_SIZE; i++)
1296 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1297 			return -EINVAL;
1298 	return 0;
1299 }
1300 
1301 /* Check if given stack slot is "special":
1302  *   - spilled register state (STACK_SPILL);
1303  *   - dynptr state (STACK_DYNPTR);
1304  *   - iter state (STACK_ITER).
1305  *   - irq flag state (STACK_IRQ_FLAG)
1306  */
1307 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1308 {
1309 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1310 
1311 	switch (type) {
1312 	case STACK_SPILL:
1313 	case STACK_DYNPTR:
1314 	case STACK_ITER:
1315 	case STACK_IRQ_FLAG:
1316 		return true;
1317 	case STACK_INVALID:
1318 	case STACK_MISC:
1319 	case STACK_ZERO:
1320 		return false;
1321 	default:
1322 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1323 		return true;
1324 	}
1325 }
1326 
1327 /* The reg state of a pointer or a bounded scalar was saved when
1328  * it was spilled to the stack.
1329  */
1330 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1331 {
1332 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1333 }
1334 
1335 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1336 {
1337 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1338 	       stack->spilled_ptr.type == SCALAR_VALUE;
1339 }
1340 
1341 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1342 {
1343 	return stack->slot_type[0] == STACK_SPILL &&
1344 	       stack->spilled_ptr.type == SCALAR_VALUE;
1345 }
1346 
1347 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1348  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1349  * more precise STACK_ZERO.
1350  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1351  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1352  * unnecessary as both are considered equivalent when loading data and pruning,
1353  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1354  * slots.
1355  */
1356 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1357 {
1358 	if (*stype == STACK_ZERO)
1359 		return;
1360 	if (*stype == STACK_INVALID)
1361 		return;
1362 	*stype = STACK_MISC;
1363 }
1364 
1365 static void scrub_spilled_slot(u8 *stype)
1366 {
1367 	if (*stype != STACK_INVALID)
1368 		*stype = STACK_MISC;
1369 }
1370 
1371 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1372  * small to hold src. This is different from krealloc since we don't want to preserve
1373  * the contents of dst.
1374  *
1375  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1376  * not be allocated.
1377  */
1378 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1379 {
1380 	size_t alloc_bytes;
1381 	void *orig = dst;
1382 	size_t bytes;
1383 
1384 	if (ZERO_OR_NULL_PTR(src))
1385 		goto out;
1386 
1387 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1388 		return NULL;
1389 
1390 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1391 	dst = krealloc(orig, alloc_bytes, flags);
1392 	if (!dst) {
1393 		kfree(orig);
1394 		return NULL;
1395 	}
1396 
1397 	memcpy(dst, src, bytes);
1398 out:
1399 	return dst ? dst : ZERO_SIZE_PTR;
1400 }
1401 
1402 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1403  * small to hold new_n items. new items are zeroed out if the array grows.
1404  *
1405  * Contrary to krealloc_array, does not free arr if new_n is zero.
1406  */
1407 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1408 {
1409 	size_t alloc_size;
1410 	void *new_arr;
1411 
1412 	if (!new_n || old_n == new_n)
1413 		goto out;
1414 
1415 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1416 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1417 	if (!new_arr) {
1418 		kfree(arr);
1419 		return NULL;
1420 	}
1421 	arr = new_arr;
1422 
1423 	if (new_n > old_n)
1424 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1425 
1426 out:
1427 	return arr ? arr : ZERO_SIZE_PTR;
1428 }
1429 
1430 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1431 {
1432 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1433 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1434 	if (!dst->refs)
1435 		return -ENOMEM;
1436 
1437 	dst->acquired_refs = src->acquired_refs;
1438 	dst->active_locks = src->active_locks;
1439 	dst->active_preempt_locks = src->active_preempt_locks;
1440 	dst->active_rcu_locks = src->active_rcu_locks;
1441 	dst->active_irq_id = src->active_irq_id;
1442 	dst->active_lock_id = src->active_lock_id;
1443 	dst->active_lock_ptr = src->active_lock_ptr;
1444 	return 0;
1445 }
1446 
1447 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1448 {
1449 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1450 
1451 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1452 				GFP_KERNEL_ACCOUNT);
1453 	if (!dst->stack)
1454 		return -ENOMEM;
1455 
1456 	dst->allocated_stack = src->allocated_stack;
1457 	return 0;
1458 }
1459 
1460 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1461 {
1462 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1463 				    sizeof(struct bpf_reference_state));
1464 	if (!state->refs)
1465 		return -ENOMEM;
1466 
1467 	state->acquired_refs = n;
1468 	return 0;
1469 }
1470 
1471 /* Possibly update state->allocated_stack to be at least size bytes. Also
1472  * possibly update the function's high-water mark in its bpf_subprog_info.
1473  */
1474 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1475 {
1476 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1477 
1478 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1479 	size = round_up(size, BPF_REG_SIZE);
1480 	n = size / BPF_REG_SIZE;
1481 
1482 	if (old_n >= n)
1483 		return 0;
1484 
1485 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1486 	if (!state->stack)
1487 		return -ENOMEM;
1488 
1489 	state->allocated_stack = size;
1490 
1491 	/* update known max for given subprogram */
1492 	if (env->subprog_info[state->subprogno].stack_depth < size)
1493 		env->subprog_info[state->subprogno].stack_depth = size;
1494 
1495 	return 0;
1496 }
1497 
1498 /* Acquire a pointer id from the env and update the state->refs to include
1499  * this new pointer reference.
1500  * On success, returns a valid pointer id to associate with the register
1501  * On failure, returns a negative errno.
1502  */
1503 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1504 {
1505 	struct bpf_verifier_state *state = env->cur_state;
1506 	int new_ofs = state->acquired_refs;
1507 	int err;
1508 
1509 	err = resize_reference_state(state, state->acquired_refs + 1);
1510 	if (err)
1511 		return NULL;
1512 	state->refs[new_ofs].insn_idx = insn_idx;
1513 
1514 	return &state->refs[new_ofs];
1515 }
1516 
1517 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1518 {
1519 	struct bpf_reference_state *s;
1520 
1521 	s = acquire_reference_state(env, insn_idx);
1522 	if (!s)
1523 		return -ENOMEM;
1524 	s->type = REF_TYPE_PTR;
1525 	s->id = ++env->id_gen;
1526 	return s->id;
1527 }
1528 
1529 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1530 			      int id, void *ptr)
1531 {
1532 	struct bpf_verifier_state *state = env->cur_state;
1533 	struct bpf_reference_state *s;
1534 
1535 	s = acquire_reference_state(env, insn_idx);
1536 	if (!s)
1537 		return -ENOMEM;
1538 	s->type = type;
1539 	s->id = id;
1540 	s->ptr = ptr;
1541 
1542 	state->active_locks++;
1543 	state->active_lock_id = id;
1544 	state->active_lock_ptr = ptr;
1545 	return 0;
1546 }
1547 
1548 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1549 {
1550 	struct bpf_verifier_state *state = env->cur_state;
1551 	struct bpf_reference_state *s;
1552 
1553 	s = acquire_reference_state(env, insn_idx);
1554 	if (!s)
1555 		return -ENOMEM;
1556 	s->type = REF_TYPE_IRQ;
1557 	s->id = ++env->id_gen;
1558 
1559 	state->active_irq_id = s->id;
1560 	return s->id;
1561 }
1562 
1563 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1564 {
1565 	int last_idx;
1566 	size_t rem;
1567 
1568 	/* IRQ state requires the relative ordering of elements remaining the
1569 	 * same, since it relies on the refs array to behave as a stack, so that
1570 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1571 	 * the array instead of swapping the final element into the deleted idx.
1572 	 */
1573 	last_idx = state->acquired_refs - 1;
1574 	rem = state->acquired_refs - idx - 1;
1575 	if (last_idx && idx != last_idx)
1576 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1577 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1578 	state->acquired_refs--;
1579 	return;
1580 }
1581 
1582 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1583 {
1584 	int i;
1585 
1586 	for (i = 0; i < state->acquired_refs; i++)
1587 		if (state->refs[i].id == ptr_id)
1588 			return true;
1589 
1590 	return false;
1591 }
1592 
1593 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1594 {
1595 	void *prev_ptr = NULL;
1596 	u32 prev_id = 0;
1597 	int i;
1598 
1599 	for (i = 0; i < state->acquired_refs; i++) {
1600 		if (state->refs[i].type == type && state->refs[i].id == id &&
1601 		    state->refs[i].ptr == ptr) {
1602 			release_reference_state(state, i);
1603 			state->active_locks--;
1604 			/* Reassign active lock (id, ptr). */
1605 			state->active_lock_id = prev_id;
1606 			state->active_lock_ptr = prev_ptr;
1607 			return 0;
1608 		}
1609 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1610 			prev_id = state->refs[i].id;
1611 			prev_ptr = state->refs[i].ptr;
1612 		}
1613 	}
1614 	return -EINVAL;
1615 }
1616 
1617 static int release_irq_state(struct bpf_verifier_state *state, int id)
1618 {
1619 	u32 prev_id = 0;
1620 	int i;
1621 
1622 	if (id != state->active_irq_id)
1623 		return -EACCES;
1624 
1625 	for (i = 0; i < state->acquired_refs; i++) {
1626 		if (state->refs[i].type != REF_TYPE_IRQ)
1627 			continue;
1628 		if (state->refs[i].id == id) {
1629 			release_reference_state(state, i);
1630 			state->active_irq_id = prev_id;
1631 			return 0;
1632 		} else {
1633 			prev_id = state->refs[i].id;
1634 		}
1635 	}
1636 	return -EINVAL;
1637 }
1638 
1639 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1640 						   int id, void *ptr)
1641 {
1642 	int i;
1643 
1644 	for (i = 0; i < state->acquired_refs; i++) {
1645 		struct bpf_reference_state *s = &state->refs[i];
1646 
1647 		if (!(s->type & type))
1648 			continue;
1649 
1650 		if (s->id == id && s->ptr == ptr)
1651 			return s;
1652 	}
1653 	return NULL;
1654 }
1655 
1656 static void update_peak_states(struct bpf_verifier_env *env)
1657 {
1658 	u32 cur_states;
1659 
1660 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1661 	env->peak_states = max(env->peak_states, cur_states);
1662 }
1663 
1664 static void free_func_state(struct bpf_func_state *state)
1665 {
1666 	if (!state)
1667 		return;
1668 	kfree(state->stack);
1669 	kfree(state);
1670 }
1671 
1672 static void clear_jmp_history(struct bpf_verifier_state *state)
1673 {
1674 	kfree(state->jmp_history);
1675 	state->jmp_history = NULL;
1676 	state->jmp_history_cnt = 0;
1677 }
1678 
1679 static void free_verifier_state(struct bpf_verifier_state *state,
1680 				bool free_self)
1681 {
1682 	int i;
1683 
1684 	for (i = 0; i <= state->curframe; i++) {
1685 		free_func_state(state->frame[i]);
1686 		state->frame[i] = NULL;
1687 	}
1688 	kfree(state->refs);
1689 	clear_jmp_history(state);
1690 	if (free_self)
1691 		kfree(state);
1692 }
1693 
1694 /* struct bpf_verifier_state->parent refers to states
1695  * that are in either of env->{expored_states,free_list}.
1696  * In both cases the state is contained in struct bpf_verifier_state_list.
1697  */
1698 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1699 {
1700 	if (st->parent)
1701 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1702 	return NULL;
1703 }
1704 
1705 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1706 				  struct bpf_verifier_state *st);
1707 
1708 /* A state can be freed if it is no longer referenced:
1709  * - is in the env->free_list;
1710  * - has no children states;
1711  */
1712 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1713 				      struct bpf_verifier_state_list *sl)
1714 {
1715 	if (!sl->in_free_list
1716 	    || sl->state.branches != 0
1717 	    || incomplete_read_marks(env, &sl->state))
1718 		return;
1719 	list_del(&sl->node);
1720 	free_verifier_state(&sl->state, false);
1721 	kfree(sl);
1722 	env->free_list_size--;
1723 }
1724 
1725 /* copy verifier state from src to dst growing dst stack space
1726  * when necessary to accommodate larger src stack
1727  */
1728 static int copy_func_state(struct bpf_func_state *dst,
1729 			   const struct bpf_func_state *src)
1730 {
1731 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1732 	return copy_stack_state(dst, src);
1733 }
1734 
1735 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1736 			       const struct bpf_verifier_state *src)
1737 {
1738 	struct bpf_func_state *dst;
1739 	int i, err;
1740 
1741 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1742 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1743 					  GFP_KERNEL_ACCOUNT);
1744 	if (!dst_state->jmp_history)
1745 		return -ENOMEM;
1746 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1747 
1748 	/* if dst has more stack frames then src frame, free them, this is also
1749 	 * necessary in case of exceptional exits using bpf_throw.
1750 	 */
1751 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752 		free_func_state(dst_state->frame[i]);
1753 		dst_state->frame[i] = NULL;
1754 	}
1755 	err = copy_reference_state(dst_state, src);
1756 	if (err)
1757 		return err;
1758 	dst_state->speculative = src->speculative;
1759 	dst_state->in_sleepable = src->in_sleepable;
1760 	dst_state->cleaned = src->cleaned;
1761 	dst_state->curframe = src->curframe;
1762 	dst_state->branches = src->branches;
1763 	dst_state->parent = src->parent;
1764 	dst_state->first_insn_idx = src->first_insn_idx;
1765 	dst_state->last_insn_idx = src->last_insn_idx;
1766 	dst_state->dfs_depth = src->dfs_depth;
1767 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1768 	dst_state->may_goto_depth = src->may_goto_depth;
1769 	dst_state->equal_state = src->equal_state;
1770 	for (i = 0; i <= src->curframe; i++) {
1771 		dst = dst_state->frame[i];
1772 		if (!dst) {
1773 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1774 			if (!dst)
1775 				return -ENOMEM;
1776 			dst_state->frame[i] = dst;
1777 		}
1778 		err = copy_func_state(dst, src->frame[i]);
1779 		if (err)
1780 			return err;
1781 	}
1782 	return 0;
1783 }
1784 
1785 static u32 state_htab_size(struct bpf_verifier_env *env)
1786 {
1787 	return env->prog->len;
1788 }
1789 
1790 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1791 {
1792 	struct bpf_verifier_state *cur = env->cur_state;
1793 	struct bpf_func_state *state = cur->frame[cur->curframe];
1794 
1795 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1796 }
1797 
1798 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1799 {
1800 	int fr;
1801 
1802 	if (a->curframe != b->curframe)
1803 		return false;
1804 
1805 	for (fr = a->curframe; fr >= 0; fr--)
1806 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1807 			return false;
1808 
1809 	return true;
1810 }
1811 
1812 /* Return IP for a given frame in a call stack */
1813 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1814 {
1815 	return frame == st->curframe
1816 	       ? st->insn_idx
1817 	       : st->frame[frame + 1]->callsite;
1818 }
1819 
1820 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1821  * if such frame exists form a corresponding @callchain as an array of
1822  * call sites leading to this frame and SCC id.
1823  * E.g.:
1824  *
1825  *    void foo()  { A: loop {... SCC#1 ...}; }
1826  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1827  *                  D: loop { E: foo(); ... SCC#3 ... } }
1828  *    void main() { F: bar(); }
1829  *
1830  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1831  * on @st frame call sites being (F,C,A) or (F,E,A).
1832  */
1833 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1834 				  struct bpf_verifier_state *st,
1835 				  struct bpf_scc_callchain *callchain)
1836 {
1837 	u32 i, scc, insn_idx;
1838 
1839 	memset(callchain, 0, sizeof(*callchain));
1840 	for (i = 0; i <= st->curframe; i++) {
1841 		insn_idx = frame_insn_idx(st, i);
1842 		scc = env->insn_aux_data[insn_idx].scc;
1843 		if (scc) {
1844 			callchain->scc = scc;
1845 			break;
1846 		} else if (i < st->curframe) {
1847 			callchain->callsites[i] = insn_idx;
1848 		} else {
1849 			return false;
1850 		}
1851 	}
1852 	return true;
1853 }
1854 
1855 /* Check if bpf_scc_visit instance for @callchain exists. */
1856 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1857 					      struct bpf_scc_callchain *callchain)
1858 {
1859 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1860 	struct bpf_scc_visit *visits = info->visits;
1861 	u32 i;
1862 
1863 	if (!info)
1864 		return NULL;
1865 	for (i = 0; i < info->num_visits; i++)
1866 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1867 			return &visits[i];
1868 	return NULL;
1869 }
1870 
1871 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1872  * Allocated instances are alive for a duration of the do_check_common()
1873  * call and are freed by free_states().
1874  */
1875 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1876 					     struct bpf_scc_callchain *callchain)
1877 {
1878 	struct bpf_scc_visit *visit;
1879 	struct bpf_scc_info *info;
1880 	u32 scc, num_visits;
1881 	u64 new_sz;
1882 
1883 	scc = callchain->scc;
1884 	info = env->scc_info[scc];
1885 	num_visits = info ? info->num_visits : 0;
1886 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1887 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1888 	if (!info)
1889 		return NULL;
1890 	env->scc_info[scc] = info;
1891 	info->num_visits = num_visits + 1;
1892 	visit = &info->visits[num_visits];
1893 	memset(visit, 0, sizeof(*visit));
1894 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1895 	return visit;
1896 }
1897 
1898 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
1899 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1900 {
1901 	char *buf = env->tmp_str_buf;
1902 	int i, delta = 0;
1903 
1904 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1905 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1906 		if (!callchain->callsites[i])
1907 			break;
1908 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1909 				  callchain->callsites[i]);
1910 	}
1911 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1912 	return env->tmp_str_buf;
1913 }
1914 
1915 /* If callchain for @st exists (@st is in some SCC), ensure that
1916  * bpf_scc_visit instance for this callchain exists.
1917  * If instance does not exist or is empty, assign visit->entry_state to @st.
1918  */
1919 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1920 {
1921 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1922 	struct bpf_scc_visit *visit;
1923 
1924 	if (!compute_scc_callchain(env, st, callchain))
1925 		return 0;
1926 	visit = scc_visit_lookup(env, callchain);
1927 	visit = visit ?: scc_visit_alloc(env, callchain);
1928 	if (!visit)
1929 		return -ENOMEM;
1930 	if (!visit->entry_state) {
1931 		visit->entry_state = st;
1932 		if (env->log.level & BPF_LOG_LEVEL2)
1933 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1934 	}
1935 	return 0;
1936 }
1937 
1938 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1939 
1940 /* If callchain for @st exists (@st is in some SCC), make it empty:
1941  * - set visit->entry_state to NULL;
1942  * - flush accumulated backedges.
1943  */
1944 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1945 {
1946 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1947 	struct bpf_scc_visit *visit;
1948 
1949 	if (!compute_scc_callchain(env, st, callchain))
1950 		return 0;
1951 	visit = scc_visit_lookup(env, callchain);
1952 	if (!visit) {
1953 		/*
1954 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1955 		 * must exist for non-speculative paths. For non-speculative paths
1956 		 * traversal stops when:
1957 		 * a. Verification error is found, maybe_exit_scc() is not called.
1958 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1959 		 *    of any SCC.
1960 		 * c. A checkpoint is reached and matched. Checkpoints are created by
1961 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
1962 		 *    bpf_scc_visit instances for checkpoints within SCCs.
1963 		 * (c) is the only case that can reach this point.
1964 		 */
1965 		if (!st->speculative) {
1966 			verifier_bug(env, "scc exit: no visit info for call chain %s",
1967 				     format_callchain(env, callchain));
1968 			return -EFAULT;
1969 		}
1970 		return 0;
1971 	}
1972 	if (visit->entry_state != st)
1973 		return 0;
1974 	if (env->log.level & BPF_LOG_LEVEL2)
1975 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1976 	visit->entry_state = NULL;
1977 	env->num_backedges -= visit->num_backedges;
1978 	visit->num_backedges = 0;
1979 	update_peak_states(env);
1980 	return propagate_backedges(env, visit);
1981 }
1982 
1983 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1984  * and add @backedge to visit->backedges. @st callchain must exist.
1985  */
1986 static int add_scc_backedge(struct bpf_verifier_env *env,
1987 			    struct bpf_verifier_state *st,
1988 			    struct bpf_scc_backedge *backedge)
1989 {
1990 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1991 	struct bpf_scc_visit *visit;
1992 
1993 	if (!compute_scc_callchain(env, st, callchain)) {
1994 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1995 			     st->insn_idx);
1996 		return -EFAULT;
1997 	}
1998 	visit = scc_visit_lookup(env, callchain);
1999 	if (!visit) {
2000 		verifier_bug(env, "add backedge: no visit info for call chain %s",
2001 			     format_callchain(env, callchain));
2002 		return -EFAULT;
2003 	}
2004 	if (env->log.level & BPF_LOG_LEVEL2)
2005 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
2006 	backedge->next = visit->backedges;
2007 	visit->backedges = backedge;
2008 	visit->num_backedges++;
2009 	env->num_backedges++;
2010 	update_peak_states(env);
2011 	return 0;
2012 }
2013 
2014 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
2015  * if state @st is in some SCC and not all execution paths starting at this
2016  * SCC are fully explored.
2017  */
2018 static bool incomplete_read_marks(struct bpf_verifier_env *env,
2019 				  struct bpf_verifier_state *st)
2020 {
2021 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
2022 	struct bpf_scc_visit *visit;
2023 
2024 	if (!compute_scc_callchain(env, st, callchain))
2025 		return false;
2026 	visit = scc_visit_lookup(env, callchain);
2027 	if (!visit)
2028 		return false;
2029 	return !!visit->backedges;
2030 }
2031 
2032 static void free_backedges(struct bpf_scc_visit *visit)
2033 {
2034 	struct bpf_scc_backedge *backedge, *next;
2035 
2036 	for (backedge = visit->backedges; backedge; backedge = next) {
2037 		free_verifier_state(&backedge->state, false);
2038 		next = backedge->next;
2039 		kfree(backedge);
2040 	}
2041 	visit->backedges = NULL;
2042 }
2043 
2044 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2045 {
2046 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2047 	struct bpf_verifier_state *parent;
2048 	int err;
2049 
2050 	while (st) {
2051 		u32 br = --st->branches;
2052 
2053 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2054 		 * but see comment in push_stack(), hence:
2055 		 */
2056 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2057 		if (br)
2058 			break;
2059 		err = maybe_exit_scc(env, st);
2060 		if (err)
2061 			return err;
2062 		parent = st->parent;
2063 		parent_sl = state_parent_as_list(st);
2064 		if (sl)
2065 			maybe_free_verifier_state(env, sl);
2066 		st = parent;
2067 		sl = parent_sl;
2068 	}
2069 	return 0;
2070 }
2071 
2072 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2073 		     int *insn_idx, bool pop_log)
2074 {
2075 	struct bpf_verifier_state *cur = env->cur_state;
2076 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2077 	int err;
2078 
2079 	if (env->head == NULL)
2080 		return -ENOENT;
2081 
2082 	if (cur) {
2083 		err = copy_verifier_state(cur, &head->st);
2084 		if (err)
2085 			return err;
2086 	}
2087 	if (pop_log)
2088 		bpf_vlog_reset(&env->log, head->log_pos);
2089 	if (insn_idx)
2090 		*insn_idx = head->insn_idx;
2091 	if (prev_insn_idx)
2092 		*prev_insn_idx = head->prev_insn_idx;
2093 	elem = head->next;
2094 	free_verifier_state(&head->st, false);
2095 	kfree(head);
2096 	env->head = elem;
2097 	env->stack_size--;
2098 	return 0;
2099 }
2100 
2101 static bool error_recoverable_with_nospec(int err)
2102 {
2103 	/* Should only return true for non-fatal errors that are allowed to
2104 	 * occur during speculative verification. For these we can insert a
2105 	 * nospec and the program might still be accepted. Do not include
2106 	 * something like ENOMEM because it is likely to re-occur for the next
2107 	 * architectural path once it has been recovered-from in all speculative
2108 	 * paths.
2109 	 */
2110 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2111 }
2112 
2113 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2114 					     int insn_idx, int prev_insn_idx,
2115 					     bool speculative)
2116 {
2117 	struct bpf_verifier_state *cur = env->cur_state;
2118 	struct bpf_verifier_stack_elem *elem;
2119 	int err;
2120 
2121 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2122 	if (!elem)
2123 		return ERR_PTR(-ENOMEM);
2124 
2125 	elem->insn_idx = insn_idx;
2126 	elem->prev_insn_idx = prev_insn_idx;
2127 	elem->next = env->head;
2128 	elem->log_pos = env->log.end_pos;
2129 	env->head = elem;
2130 	env->stack_size++;
2131 	err = copy_verifier_state(&elem->st, cur);
2132 	if (err)
2133 		return ERR_PTR(-ENOMEM);
2134 	elem->st.speculative |= speculative;
2135 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2136 		verbose(env, "The sequence of %d jumps is too complex.\n",
2137 			env->stack_size);
2138 		return ERR_PTR(-E2BIG);
2139 	}
2140 	if (elem->st.parent) {
2141 		++elem->st.parent->branches;
2142 		/* WARN_ON(branches > 2) technically makes sense here,
2143 		 * but
2144 		 * 1. speculative states will bump 'branches' for non-branch
2145 		 * instructions
2146 		 * 2. is_state_visited() heuristics may decide not to create
2147 		 * a new state for a sequence of branches and all such current
2148 		 * and cloned states will be pointing to a single parent state
2149 		 * which might have large 'branches' count.
2150 		 */
2151 	}
2152 	return &elem->st;
2153 }
2154 
2155 #define CALLER_SAVED_REGS 6
2156 static const int caller_saved[CALLER_SAVED_REGS] = {
2157 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2158 };
2159 
2160 /* This helper doesn't clear reg->id */
2161 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2162 {
2163 	reg->var_off = tnum_const(imm);
2164 	reg->smin_value = (s64)imm;
2165 	reg->smax_value = (s64)imm;
2166 	reg->umin_value = imm;
2167 	reg->umax_value = imm;
2168 
2169 	reg->s32_min_value = (s32)imm;
2170 	reg->s32_max_value = (s32)imm;
2171 	reg->u32_min_value = (u32)imm;
2172 	reg->u32_max_value = (u32)imm;
2173 }
2174 
2175 /* Mark the unknown part of a register (variable offset or scalar value) as
2176  * known to have the value @imm.
2177  */
2178 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2179 {
2180 	/* Clear off and union(map_ptr, range) */
2181 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2182 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2183 	reg->id = 0;
2184 	reg->ref_obj_id = 0;
2185 	___mark_reg_known(reg, imm);
2186 }
2187 
2188 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2189 {
2190 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2191 	reg->s32_min_value = (s32)imm;
2192 	reg->s32_max_value = (s32)imm;
2193 	reg->u32_min_value = (u32)imm;
2194 	reg->u32_max_value = (u32)imm;
2195 }
2196 
2197 /* Mark the 'variable offset' part of a register as zero.  This should be
2198  * used only on registers holding a pointer type.
2199  */
2200 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2201 {
2202 	__mark_reg_known(reg, 0);
2203 }
2204 
2205 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2206 {
2207 	__mark_reg_known(reg, 0);
2208 	reg->type = SCALAR_VALUE;
2209 	/* all scalars are assumed imprecise initially (unless unprivileged,
2210 	 * in which case everything is forced to be precise)
2211 	 */
2212 	reg->precise = !env->bpf_capable;
2213 }
2214 
2215 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2216 				struct bpf_reg_state *regs, u32 regno)
2217 {
2218 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2219 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2220 		/* Something bad happened, let's kill all regs */
2221 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2222 			__mark_reg_not_init(env, regs + regno);
2223 		return;
2224 	}
2225 	__mark_reg_known_zero(regs + regno);
2226 }
2227 
2228 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2229 			      bool first_slot, int dynptr_id)
2230 {
2231 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2232 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2233 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2234 	 */
2235 	__mark_reg_known_zero(reg);
2236 	reg->type = CONST_PTR_TO_DYNPTR;
2237 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2238 	reg->id = dynptr_id;
2239 	reg->dynptr.type = type;
2240 	reg->dynptr.first_slot = first_slot;
2241 }
2242 
2243 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2244 {
2245 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2246 		const struct bpf_map *map = reg->map_ptr;
2247 
2248 		if (map->inner_map_meta) {
2249 			reg->type = CONST_PTR_TO_MAP;
2250 			reg->map_ptr = map->inner_map_meta;
2251 			/* transfer reg's id which is unique for every map_lookup_elem
2252 			 * as UID of the inner map.
2253 			 */
2254 			if (btf_record_has_field(map->inner_map_meta->record,
2255 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2256 				reg->map_uid = reg->id;
2257 			}
2258 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2259 			reg->type = PTR_TO_XDP_SOCK;
2260 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2261 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2262 			reg->type = PTR_TO_SOCKET;
2263 		} else {
2264 			reg->type = PTR_TO_MAP_VALUE;
2265 		}
2266 		return;
2267 	}
2268 
2269 	reg->type &= ~PTR_MAYBE_NULL;
2270 }
2271 
2272 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2273 				struct btf_field_graph_root *ds_head)
2274 {
2275 	__mark_reg_known_zero(&regs[regno]);
2276 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2277 	regs[regno].btf = ds_head->btf;
2278 	regs[regno].btf_id = ds_head->value_btf_id;
2279 	regs[regno].off = ds_head->node_offset;
2280 }
2281 
2282 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2283 {
2284 	return type_is_pkt_pointer(reg->type);
2285 }
2286 
2287 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2288 {
2289 	return reg_is_pkt_pointer(reg) ||
2290 	       reg->type == PTR_TO_PACKET_END;
2291 }
2292 
2293 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2294 {
2295 	return base_type(reg->type) == PTR_TO_MEM &&
2296 	       (reg->type &
2297 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2298 }
2299 
2300 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2301 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2302 				    enum bpf_reg_type which)
2303 {
2304 	/* The register can already have a range from prior markings.
2305 	 * This is fine as long as it hasn't been advanced from its
2306 	 * origin.
2307 	 */
2308 	return reg->type == which &&
2309 	       reg->id == 0 &&
2310 	       reg->off == 0 &&
2311 	       tnum_equals_const(reg->var_off, 0);
2312 }
2313 
2314 /* Reset the min/max bounds of a register */
2315 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2316 {
2317 	reg->smin_value = S64_MIN;
2318 	reg->smax_value = S64_MAX;
2319 	reg->umin_value = 0;
2320 	reg->umax_value = U64_MAX;
2321 
2322 	reg->s32_min_value = S32_MIN;
2323 	reg->s32_max_value = S32_MAX;
2324 	reg->u32_min_value = 0;
2325 	reg->u32_max_value = U32_MAX;
2326 }
2327 
2328 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2329 {
2330 	reg->smin_value = S64_MIN;
2331 	reg->smax_value = S64_MAX;
2332 	reg->umin_value = 0;
2333 	reg->umax_value = U64_MAX;
2334 }
2335 
2336 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2337 {
2338 	reg->s32_min_value = S32_MIN;
2339 	reg->s32_max_value = S32_MAX;
2340 	reg->u32_min_value = 0;
2341 	reg->u32_max_value = U32_MAX;
2342 }
2343 
2344 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2345 {
2346 	struct tnum var32_off = tnum_subreg(reg->var_off);
2347 
2348 	/* min signed is max(sign bit) | min(other bits) */
2349 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2350 			var32_off.value | (var32_off.mask & S32_MIN));
2351 	/* max signed is min(sign bit) | max(other bits) */
2352 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2353 			var32_off.value | (var32_off.mask & S32_MAX));
2354 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2355 	reg->u32_max_value = min(reg->u32_max_value,
2356 				 (u32)(var32_off.value | var32_off.mask));
2357 }
2358 
2359 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2360 {
2361 	/* min signed is max(sign bit) | min(other bits) */
2362 	reg->smin_value = max_t(s64, reg->smin_value,
2363 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2364 	/* max signed is min(sign bit) | max(other bits) */
2365 	reg->smax_value = min_t(s64, reg->smax_value,
2366 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2367 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2368 	reg->umax_value = min(reg->umax_value,
2369 			      reg->var_off.value | reg->var_off.mask);
2370 }
2371 
2372 static void __update_reg_bounds(struct bpf_reg_state *reg)
2373 {
2374 	__update_reg32_bounds(reg);
2375 	__update_reg64_bounds(reg);
2376 }
2377 
2378 /* Uses signed min/max values to inform unsigned, and vice-versa */
2379 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2380 {
2381 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2382 	 * bits to improve our u32/s32 boundaries.
2383 	 *
2384 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2385 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2386 	 * [10, 20] range. But this property holds for any 64-bit range as
2387 	 * long as upper 32 bits in that entire range of values stay the same.
2388 	 *
2389 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2390 	 * in decimal) has the same upper 32 bits throughout all the values in
2391 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2392 	 * range.
2393 	 *
2394 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2395 	 * following the rules outlined below about u64/s64 correspondence
2396 	 * (which equally applies to u32 vs s32 correspondence). In general it
2397 	 * depends on actual hexadecimal values of 32-bit range. They can form
2398 	 * only valid u32, or only valid s32 ranges in some cases.
2399 	 *
2400 	 * So we use all these insights to derive bounds for subregisters here.
2401 	 */
2402 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2403 		/* u64 to u32 casting preserves validity of low 32 bits as
2404 		 * a range, if upper 32 bits are the same
2405 		 */
2406 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2407 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2408 
2409 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2410 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2411 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2412 		}
2413 	}
2414 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2415 		/* low 32 bits should form a proper u32 range */
2416 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2417 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2418 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2419 		}
2420 		/* low 32 bits should form a proper s32 range */
2421 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2422 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2423 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2424 		}
2425 	}
2426 	/* Special case where upper bits form a small sequence of two
2427 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2428 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2429 	 * going from negative numbers to positive numbers. E.g., let's say we
2430 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2431 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2432 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2433 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2434 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2435 	 * upper 32 bits. As a random example, s64 range
2436 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2437 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2438 	 */
2439 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2440 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2441 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2442 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2443 	}
2444 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2445 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2446 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2447 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2448 	}
2449 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2450 	 * try to learn from that
2451 	 */
2452 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2453 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2454 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2455 	}
2456 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2457 	 * are the same, so combine.  This works even in the negative case, e.g.
2458 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2459 	 */
2460 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2461 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2462 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2463 	}
2464 }
2465 
2466 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2467 {
2468 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2469 	 * try to learn from that. Let's do a bit of ASCII art to see when
2470 	 * this is happening. Let's take u64 range first:
2471 	 *
2472 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2473 	 * |-------------------------------|--------------------------------|
2474 	 *
2475 	 * Valid u64 range is formed when umin and umax are anywhere in the
2476 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2477 	 * straightforward. Let's see how s64 range maps onto the same range
2478 	 * of values, annotated below the line for comparison:
2479 	 *
2480 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2481 	 * |-------------------------------|--------------------------------|
2482 	 * 0                        S64_MAX S64_MIN                        -1
2483 	 *
2484 	 * So s64 values basically start in the middle and they are logically
2485 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2486 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2487 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2488 	 * more visually as mapped to sign-agnostic range of hex values.
2489 	 *
2490 	 *  u64 start                                               u64 end
2491 	 *  _______________________________________________________________
2492 	 * /                                                               \
2493 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2494 	 * |-------------------------------|--------------------------------|
2495 	 * 0                        S64_MAX S64_MIN                        -1
2496 	 *                                / \
2497 	 * >------------------------------   ------------------------------->
2498 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2499 	 *
2500 	 * What this means is that, in general, we can't always derive
2501 	 * something new about u64 from any random s64 range, and vice versa.
2502 	 *
2503 	 * But we can do that in two particular cases. One is when entire
2504 	 * u64/s64 range is *entirely* contained within left half of the above
2505 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2506 	 *
2507 	 * |-------------------------------|--------------------------------|
2508 	 *     ^                   ^            ^                 ^
2509 	 *     A                   B            C                 D
2510 	 *
2511 	 * [A, B] and [C, D] are contained entirely in their respective halves
2512 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2513 	 * will be non-negative both as u64 and s64 (and in fact it will be
2514 	 * identical ranges no matter the signedness). [C, D] treated as s64
2515 	 * will be a range of negative values, while in u64 it will be
2516 	 * non-negative range of values larger than 0x8000000000000000.
2517 	 *
2518 	 * Now, any other range here can't be represented in both u64 and s64
2519 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2520 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2521 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2522 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2523 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2524 	 * ranges as u64. Currently reg_state can't represent two segments per
2525 	 * numeric domain, so in such situations we can only derive maximal
2526 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2527 	 *
2528 	 * So we use these facts to derive umin/umax from smin/smax and vice
2529 	 * versa only if they stay within the same "half". This is equivalent
2530 	 * to checking sign bit: lower half will have sign bit as zero, upper
2531 	 * half have sign bit 1. Below in code we simplify this by just
2532 	 * casting umin/umax as smin/smax and checking if they form valid
2533 	 * range, and vice versa. Those are equivalent checks.
2534 	 */
2535 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2536 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2537 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2538 	}
2539 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2540 	 * are the same, so combine.  This works even in the negative case, e.g.
2541 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2542 	 */
2543 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2544 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2545 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2546 	} else {
2547 		/* If the s64 range crosses the sign boundary, then it's split
2548 		 * between the beginning and end of the U64 domain. In that
2549 		 * case, we can derive new bounds if the u64 range overlaps
2550 		 * with only one end of the s64 range.
2551 		 *
2552 		 * In the following example, the u64 range overlaps only with
2553 		 * positive portion of the s64 range.
2554 		 *
2555 		 * 0                                                   U64_MAX
2556 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2557 		 * |----------------------------|----------------------------|
2558 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2559 		 * 0                     S64_MAX S64_MIN                    -1
2560 		 *
2561 		 * We can thus derive the following new s64 and u64 ranges.
2562 		 *
2563 		 * 0                                                   U64_MAX
2564 		 * |  [xxxxxx u64 range xxxxx]                               |
2565 		 * |----------------------------|----------------------------|
2566 		 * |  [xxxxxx s64 range xxxxx]                               |
2567 		 * 0                     S64_MAX S64_MIN                    -1
2568 		 *
2569 		 * If they overlap in two places, we can't derive anything
2570 		 * because reg_state can't represent two ranges per numeric
2571 		 * domain.
2572 		 *
2573 		 * 0                                                   U64_MAX
2574 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2575 		 * |----------------------------|----------------------------|
2576 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2577 		 * 0                     S64_MAX S64_MIN                    -1
2578 		 *
2579 		 * The first condition below corresponds to the first diagram
2580 		 * above.
2581 		 */
2582 		if (reg->umax_value < (u64)reg->smin_value) {
2583 			reg->smin_value = (s64)reg->umin_value;
2584 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2585 		} else if ((u64)reg->smax_value < reg->umin_value) {
2586 			/* This second condition considers the case where the u64 range
2587 			 * overlaps with the negative portion of the s64 range:
2588 			 *
2589 			 * 0                                                   U64_MAX
2590 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2591 			 * |----------------------------|----------------------------|
2592 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2593 			 * 0                     S64_MAX S64_MIN                    -1
2594 			 */
2595 			reg->smax_value = (s64)reg->umax_value;
2596 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2597 		}
2598 	}
2599 }
2600 
2601 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2602 {
2603 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2604 	 * values on both sides of 64-bit range in hope to have tighter range.
2605 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2606 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2607 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2608 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2609 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2610 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2611 	 * We just need to make sure that derived bounds we are intersecting
2612 	 * with are well-formed ranges in respective s64 or u64 domain, just
2613 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2614 	 */
2615 	__u64 new_umin, new_umax;
2616 	__s64 new_smin, new_smax;
2617 
2618 	/* u32 -> u64 tightening, it's always well-formed */
2619 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2620 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2621 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2622 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2623 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2624 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2625 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2626 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2627 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2628 
2629 	/* Here we would like to handle a special case after sign extending load,
2630 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2631 	 *
2632 	 * Upper bits are all 1s when register is in a range:
2633 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2634 	 * Upper bits are all 0s when register is in a range:
2635 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2636 	 * Together this forms are continuous range:
2637 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2638 	 *
2639 	 * Now, suppose that register range is in fact tighter:
2640 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2641 	 * Also suppose that it's 32-bit range is positive,
2642 	 * meaning that lower 32-bits of the full 64-bit register
2643 	 * are in the range:
2644 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2645 	 *
2646 	 * If this happens, then any value in a range:
2647 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2648 	 * is smaller than a lowest bound of the range (R):
2649 	 *   0xffff_ffff_8000_0000
2650 	 * which means that upper bits of the full 64-bit register
2651 	 * can't be all 1s, when lower bits are in range (W).
2652 	 *
2653 	 * Note that:
2654 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2655 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2656 	 * These relations are used in the conditions below.
2657 	 */
2658 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2659 		reg->smin_value = reg->s32_min_value;
2660 		reg->smax_value = reg->s32_max_value;
2661 		reg->umin_value = reg->s32_min_value;
2662 		reg->umax_value = reg->s32_max_value;
2663 		reg->var_off = tnum_intersect(reg->var_off,
2664 					      tnum_range(reg->smin_value, reg->smax_value));
2665 	}
2666 }
2667 
2668 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2669 {
2670 	__reg32_deduce_bounds(reg);
2671 	__reg64_deduce_bounds(reg);
2672 	__reg_deduce_mixed_bounds(reg);
2673 }
2674 
2675 /* Attempts to improve var_off based on unsigned min/max information */
2676 static void __reg_bound_offset(struct bpf_reg_state *reg)
2677 {
2678 	struct tnum var64_off = tnum_intersect(reg->var_off,
2679 					       tnum_range(reg->umin_value,
2680 							  reg->umax_value));
2681 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2682 					       tnum_range(reg->u32_min_value,
2683 							  reg->u32_max_value));
2684 
2685 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2686 }
2687 
2688 static void reg_bounds_sync(struct bpf_reg_state *reg)
2689 {
2690 	/* We might have learned new bounds from the var_off. */
2691 	__update_reg_bounds(reg);
2692 	/* We might have learned something about the sign bit. */
2693 	__reg_deduce_bounds(reg);
2694 	__reg_deduce_bounds(reg);
2695 	__reg_deduce_bounds(reg);
2696 	/* We might have learned some bits from the bounds. */
2697 	__reg_bound_offset(reg);
2698 	/* Intersecting with the old var_off might have improved our bounds
2699 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2700 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2701 	 */
2702 	__update_reg_bounds(reg);
2703 }
2704 
2705 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2706 				   struct bpf_reg_state *reg, const char *ctx)
2707 {
2708 	const char *msg;
2709 
2710 	if (reg->umin_value > reg->umax_value ||
2711 	    reg->smin_value > reg->smax_value ||
2712 	    reg->u32_min_value > reg->u32_max_value ||
2713 	    reg->s32_min_value > reg->s32_max_value) {
2714 		    msg = "range bounds violation";
2715 		    goto out;
2716 	}
2717 
2718 	if (tnum_is_const(reg->var_off)) {
2719 		u64 uval = reg->var_off.value;
2720 		s64 sval = (s64)uval;
2721 
2722 		if (reg->umin_value != uval || reg->umax_value != uval ||
2723 		    reg->smin_value != sval || reg->smax_value != sval) {
2724 			msg = "const tnum out of sync with range bounds";
2725 			goto out;
2726 		}
2727 	}
2728 
2729 	if (tnum_subreg_is_const(reg->var_off)) {
2730 		u32 uval32 = tnum_subreg(reg->var_off).value;
2731 		s32 sval32 = (s32)uval32;
2732 
2733 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2734 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2735 			msg = "const subreg tnum out of sync with range bounds";
2736 			goto out;
2737 		}
2738 	}
2739 
2740 	return 0;
2741 out:
2742 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2743 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2744 		     ctx, msg, reg->umin_value, reg->umax_value,
2745 		     reg->smin_value, reg->smax_value,
2746 		     reg->u32_min_value, reg->u32_max_value,
2747 		     reg->s32_min_value, reg->s32_max_value,
2748 		     reg->var_off.value, reg->var_off.mask);
2749 	if (env->test_reg_invariants)
2750 		return -EFAULT;
2751 	__mark_reg_unbounded(reg);
2752 	return 0;
2753 }
2754 
2755 static bool __reg32_bound_s64(s32 a)
2756 {
2757 	return a >= 0 && a <= S32_MAX;
2758 }
2759 
2760 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2761 {
2762 	reg->umin_value = reg->u32_min_value;
2763 	reg->umax_value = reg->u32_max_value;
2764 
2765 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2766 	 * be positive otherwise set to worse case bounds and refine later
2767 	 * from tnum.
2768 	 */
2769 	if (__reg32_bound_s64(reg->s32_min_value) &&
2770 	    __reg32_bound_s64(reg->s32_max_value)) {
2771 		reg->smin_value = reg->s32_min_value;
2772 		reg->smax_value = reg->s32_max_value;
2773 	} else {
2774 		reg->smin_value = 0;
2775 		reg->smax_value = U32_MAX;
2776 	}
2777 }
2778 
2779 /* Mark a register as having a completely unknown (scalar) value. */
2780 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2781 {
2782 	/*
2783 	 * Clear type, off, and union(map_ptr, range) and
2784 	 * padding between 'type' and union
2785 	 */
2786 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2787 	reg->type = SCALAR_VALUE;
2788 	reg->id = 0;
2789 	reg->ref_obj_id = 0;
2790 	reg->var_off = tnum_unknown;
2791 	reg->frameno = 0;
2792 	reg->precise = false;
2793 	__mark_reg_unbounded(reg);
2794 }
2795 
2796 /* Mark a register as having a completely unknown (scalar) value,
2797  * initialize .precise as true when not bpf capable.
2798  */
2799 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2800 			       struct bpf_reg_state *reg)
2801 {
2802 	__mark_reg_unknown_imprecise(reg);
2803 	reg->precise = !env->bpf_capable;
2804 }
2805 
2806 static void mark_reg_unknown(struct bpf_verifier_env *env,
2807 			     struct bpf_reg_state *regs, u32 regno)
2808 {
2809 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2810 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2811 		/* Something bad happened, let's kill all regs except FP */
2812 		for (regno = 0; regno < BPF_REG_FP; regno++)
2813 			__mark_reg_not_init(env, regs + regno);
2814 		return;
2815 	}
2816 	__mark_reg_unknown(env, regs + regno);
2817 }
2818 
2819 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2820 				struct bpf_reg_state *regs,
2821 				u32 regno,
2822 				s32 s32_min,
2823 				s32 s32_max)
2824 {
2825 	struct bpf_reg_state *reg = regs + regno;
2826 
2827 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2828 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2829 
2830 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2831 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2832 
2833 	reg_bounds_sync(reg);
2834 
2835 	return reg_bounds_sanity_check(env, reg, "s32_range");
2836 }
2837 
2838 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2839 				struct bpf_reg_state *reg)
2840 {
2841 	__mark_reg_unknown(env, reg);
2842 	reg->type = NOT_INIT;
2843 }
2844 
2845 static void mark_reg_not_init(struct bpf_verifier_env *env,
2846 			      struct bpf_reg_state *regs, u32 regno)
2847 {
2848 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2849 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2850 		/* Something bad happened, let's kill all regs except FP */
2851 		for (regno = 0; regno < BPF_REG_FP; regno++)
2852 			__mark_reg_not_init(env, regs + regno);
2853 		return;
2854 	}
2855 	__mark_reg_not_init(env, regs + regno);
2856 }
2857 
2858 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2859 			   struct bpf_reg_state *regs, u32 regno,
2860 			   enum bpf_reg_type reg_type,
2861 			   struct btf *btf, u32 btf_id,
2862 			   enum bpf_type_flag flag)
2863 {
2864 	switch (reg_type) {
2865 	case SCALAR_VALUE:
2866 		mark_reg_unknown(env, regs, regno);
2867 		return 0;
2868 	case PTR_TO_BTF_ID:
2869 		mark_reg_known_zero(env, regs, regno);
2870 		regs[regno].type = PTR_TO_BTF_ID | flag;
2871 		regs[regno].btf = btf;
2872 		regs[regno].btf_id = btf_id;
2873 		if (type_may_be_null(flag))
2874 			regs[regno].id = ++env->id_gen;
2875 		return 0;
2876 	case PTR_TO_MEM:
2877 		mark_reg_known_zero(env, regs, regno);
2878 		regs[regno].type = PTR_TO_MEM | flag;
2879 		regs[regno].mem_size = 0;
2880 		return 0;
2881 	default:
2882 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2883 		return -EFAULT;
2884 	}
2885 }
2886 
2887 #define DEF_NOT_SUBREG	(0)
2888 static void init_reg_state(struct bpf_verifier_env *env,
2889 			   struct bpf_func_state *state)
2890 {
2891 	struct bpf_reg_state *regs = state->regs;
2892 	int i;
2893 
2894 	for (i = 0; i < MAX_BPF_REG; i++) {
2895 		mark_reg_not_init(env, regs, i);
2896 		regs[i].subreg_def = DEF_NOT_SUBREG;
2897 	}
2898 
2899 	/* frame pointer */
2900 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2901 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2902 	regs[BPF_REG_FP].frameno = state->frameno;
2903 }
2904 
2905 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2906 {
2907 	return (struct bpf_retval_range){ minval, maxval };
2908 }
2909 
2910 #define BPF_MAIN_FUNC (-1)
2911 static void init_func_state(struct bpf_verifier_env *env,
2912 			    struct bpf_func_state *state,
2913 			    int callsite, int frameno, int subprogno)
2914 {
2915 	state->callsite = callsite;
2916 	state->frameno = frameno;
2917 	state->subprogno = subprogno;
2918 	state->callback_ret_range = retval_range(0, 0);
2919 	init_reg_state(env, state);
2920 	mark_verifier_state_scratched(env);
2921 }
2922 
2923 /* Similar to push_stack(), but for async callbacks */
2924 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2925 						int insn_idx, int prev_insn_idx,
2926 						int subprog, bool is_sleepable)
2927 {
2928 	struct bpf_verifier_stack_elem *elem;
2929 	struct bpf_func_state *frame;
2930 
2931 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2932 	if (!elem)
2933 		return ERR_PTR(-ENOMEM);
2934 
2935 	elem->insn_idx = insn_idx;
2936 	elem->prev_insn_idx = prev_insn_idx;
2937 	elem->next = env->head;
2938 	elem->log_pos = env->log.end_pos;
2939 	env->head = elem;
2940 	env->stack_size++;
2941 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2942 		verbose(env,
2943 			"The sequence of %d jumps is too complex for async cb.\n",
2944 			env->stack_size);
2945 		return ERR_PTR(-E2BIG);
2946 	}
2947 	/* Unlike push_stack() do not copy_verifier_state().
2948 	 * The caller state doesn't matter.
2949 	 * This is async callback. It starts in a fresh stack.
2950 	 * Initialize it similar to do_check_common().
2951 	 */
2952 	elem->st.branches = 1;
2953 	elem->st.in_sleepable = is_sleepable;
2954 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2955 	if (!frame)
2956 		return ERR_PTR(-ENOMEM);
2957 	init_func_state(env, frame,
2958 			BPF_MAIN_FUNC /* callsite */,
2959 			0 /* frameno within this callchain */,
2960 			subprog /* subprog number within this prog */);
2961 	elem->st.frame[0] = frame;
2962 	return &elem->st;
2963 }
2964 
2965 
2966 enum reg_arg_type {
2967 	SRC_OP,		/* register is used as source operand */
2968 	DST_OP,		/* register is used as destination operand */
2969 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2970 };
2971 
2972 static int cmp_subprogs(const void *a, const void *b)
2973 {
2974 	return ((struct bpf_subprog_info *)a)->start -
2975 	       ((struct bpf_subprog_info *)b)->start;
2976 }
2977 
2978 /* Find subprogram that contains instruction at 'off' */
2979 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2980 {
2981 	struct bpf_subprog_info *vals = env->subprog_info;
2982 	int l, r, m;
2983 
2984 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2985 		return NULL;
2986 
2987 	l = 0;
2988 	r = env->subprog_cnt - 1;
2989 	while (l < r) {
2990 		m = l + (r - l + 1) / 2;
2991 		if (vals[m].start <= off)
2992 			l = m;
2993 		else
2994 			r = m - 1;
2995 	}
2996 	return &vals[l];
2997 }
2998 
2999 /* Find subprogram that starts exactly at 'off' */
3000 static int find_subprog(struct bpf_verifier_env *env, int off)
3001 {
3002 	struct bpf_subprog_info *p;
3003 
3004 	p = bpf_find_containing_subprog(env, off);
3005 	if (!p || p->start != off)
3006 		return -ENOENT;
3007 	return p - env->subprog_info;
3008 }
3009 
3010 static int add_subprog(struct bpf_verifier_env *env, int off)
3011 {
3012 	int insn_cnt = env->prog->len;
3013 	int ret;
3014 
3015 	if (off >= insn_cnt || off < 0) {
3016 		verbose(env, "call to invalid destination\n");
3017 		return -EINVAL;
3018 	}
3019 	ret = find_subprog(env, off);
3020 	if (ret >= 0)
3021 		return ret;
3022 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3023 		verbose(env, "too many subprograms\n");
3024 		return -E2BIG;
3025 	}
3026 	/* determine subprog starts. The end is one before the next starts */
3027 	env->subprog_info[env->subprog_cnt++].start = off;
3028 	sort(env->subprog_info, env->subprog_cnt,
3029 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3030 	return env->subprog_cnt - 1;
3031 }
3032 
3033 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3034 {
3035 	struct bpf_prog_aux *aux = env->prog->aux;
3036 	struct btf *btf = aux->btf;
3037 	const struct btf_type *t;
3038 	u32 main_btf_id, id;
3039 	const char *name;
3040 	int ret, i;
3041 
3042 	/* Non-zero func_info_cnt implies valid btf */
3043 	if (!aux->func_info_cnt)
3044 		return 0;
3045 	main_btf_id = aux->func_info[0].type_id;
3046 
3047 	t = btf_type_by_id(btf, main_btf_id);
3048 	if (!t) {
3049 		verbose(env, "invalid btf id for main subprog in func_info\n");
3050 		return -EINVAL;
3051 	}
3052 
3053 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3054 	if (IS_ERR(name)) {
3055 		ret = PTR_ERR(name);
3056 		/* If there is no tag present, there is no exception callback */
3057 		if (ret == -ENOENT)
3058 			ret = 0;
3059 		else if (ret == -EEXIST)
3060 			verbose(env, "multiple exception callback tags for main subprog\n");
3061 		return ret;
3062 	}
3063 
3064 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3065 	if (ret < 0) {
3066 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3067 		return ret;
3068 	}
3069 	id = ret;
3070 	t = btf_type_by_id(btf, id);
3071 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3072 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3073 		return -EINVAL;
3074 	}
3075 	ret = 0;
3076 	for (i = 0; i < aux->func_info_cnt; i++) {
3077 		if (aux->func_info[i].type_id != id)
3078 			continue;
3079 		ret = aux->func_info[i].insn_off;
3080 		/* Further func_info and subprog checks will also happen
3081 		 * later, so assume this is the right insn_off for now.
3082 		 */
3083 		if (!ret) {
3084 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3085 			ret = -EINVAL;
3086 		}
3087 	}
3088 	if (!ret) {
3089 		verbose(env, "exception callback type id not found in func_info\n");
3090 		ret = -EINVAL;
3091 	}
3092 	return ret;
3093 }
3094 
3095 #define MAX_KFUNC_DESCS 256
3096 #define MAX_KFUNC_BTFS	256
3097 
3098 struct bpf_kfunc_desc {
3099 	struct btf_func_model func_model;
3100 	u32 func_id;
3101 	s32 imm;
3102 	u16 offset;
3103 	unsigned long addr;
3104 };
3105 
3106 struct bpf_kfunc_btf {
3107 	struct btf *btf;
3108 	struct module *module;
3109 	u16 offset;
3110 };
3111 
3112 struct bpf_kfunc_desc_tab {
3113 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3114 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3115 	 * available, therefore at the end of verification do_misc_fixups()
3116 	 * sorts this by imm and offset.
3117 	 */
3118 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3119 	u32 nr_descs;
3120 };
3121 
3122 struct bpf_kfunc_btf_tab {
3123 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3124 	u32 nr_descs;
3125 };
3126 
3127 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
3128 			    int insn_idx);
3129 
3130 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3131 {
3132 	const struct bpf_kfunc_desc *d0 = a;
3133 	const struct bpf_kfunc_desc *d1 = b;
3134 
3135 	/* func_id is not greater than BTF_MAX_TYPE */
3136 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3137 }
3138 
3139 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3140 {
3141 	const struct bpf_kfunc_btf *d0 = a;
3142 	const struct bpf_kfunc_btf *d1 = b;
3143 
3144 	return d0->offset - d1->offset;
3145 }
3146 
3147 static struct bpf_kfunc_desc *
3148 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3149 {
3150 	struct bpf_kfunc_desc desc = {
3151 		.func_id = func_id,
3152 		.offset = offset,
3153 	};
3154 	struct bpf_kfunc_desc_tab *tab;
3155 
3156 	tab = prog->aux->kfunc_tab;
3157 	return bsearch(&desc, tab->descs, tab->nr_descs,
3158 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3159 }
3160 
3161 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3162 		       u16 btf_fd_idx, u8 **func_addr)
3163 {
3164 	const struct bpf_kfunc_desc *desc;
3165 
3166 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3167 	if (!desc)
3168 		return -EFAULT;
3169 
3170 	*func_addr = (u8 *)desc->addr;
3171 	return 0;
3172 }
3173 
3174 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3175 					 s16 offset)
3176 {
3177 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3178 	struct bpf_kfunc_btf_tab *tab;
3179 	struct bpf_kfunc_btf *b;
3180 	struct module *mod;
3181 	struct btf *btf;
3182 	int btf_fd;
3183 
3184 	tab = env->prog->aux->kfunc_btf_tab;
3185 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3186 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3187 	if (!b) {
3188 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3189 			verbose(env, "too many different module BTFs\n");
3190 			return ERR_PTR(-E2BIG);
3191 		}
3192 
3193 		if (bpfptr_is_null(env->fd_array)) {
3194 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3195 			return ERR_PTR(-EPROTO);
3196 		}
3197 
3198 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3199 					    offset * sizeof(btf_fd),
3200 					    sizeof(btf_fd)))
3201 			return ERR_PTR(-EFAULT);
3202 
3203 		btf = btf_get_by_fd(btf_fd);
3204 		if (IS_ERR(btf)) {
3205 			verbose(env, "invalid module BTF fd specified\n");
3206 			return btf;
3207 		}
3208 
3209 		if (!btf_is_module(btf)) {
3210 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3211 			btf_put(btf);
3212 			return ERR_PTR(-EINVAL);
3213 		}
3214 
3215 		mod = btf_try_get_module(btf);
3216 		if (!mod) {
3217 			btf_put(btf);
3218 			return ERR_PTR(-ENXIO);
3219 		}
3220 
3221 		b = &tab->descs[tab->nr_descs++];
3222 		b->btf = btf;
3223 		b->module = mod;
3224 		b->offset = offset;
3225 
3226 		/* sort() reorders entries by value, so b may no longer point
3227 		 * to the right entry after this
3228 		 */
3229 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3230 		     kfunc_btf_cmp_by_off, NULL);
3231 	} else {
3232 		btf = b->btf;
3233 	}
3234 
3235 	return btf;
3236 }
3237 
3238 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3239 {
3240 	if (!tab)
3241 		return;
3242 
3243 	while (tab->nr_descs--) {
3244 		module_put(tab->descs[tab->nr_descs].module);
3245 		btf_put(tab->descs[tab->nr_descs].btf);
3246 	}
3247 	kfree(tab);
3248 }
3249 
3250 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3251 {
3252 	if (offset) {
3253 		if (offset < 0) {
3254 			/* In the future, this can be allowed to increase limit
3255 			 * of fd index into fd_array, interpreted as u16.
3256 			 */
3257 			verbose(env, "negative offset disallowed for kernel module function call\n");
3258 			return ERR_PTR(-EINVAL);
3259 		}
3260 
3261 		return __find_kfunc_desc_btf(env, offset);
3262 	}
3263 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3264 }
3265 
3266 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3267 {
3268 	const struct btf_type *func, *func_proto;
3269 	struct bpf_kfunc_btf_tab *btf_tab;
3270 	struct btf_func_model func_model;
3271 	struct bpf_kfunc_desc_tab *tab;
3272 	struct bpf_prog_aux *prog_aux;
3273 	struct bpf_kfunc_desc *desc;
3274 	const char *func_name;
3275 	struct btf *desc_btf;
3276 	unsigned long addr;
3277 	int err;
3278 
3279 	prog_aux = env->prog->aux;
3280 	tab = prog_aux->kfunc_tab;
3281 	btf_tab = prog_aux->kfunc_btf_tab;
3282 	if (!tab) {
3283 		if (!btf_vmlinux) {
3284 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3285 			return -ENOTSUPP;
3286 		}
3287 
3288 		if (!env->prog->jit_requested) {
3289 			verbose(env, "JIT is required for calling kernel function\n");
3290 			return -ENOTSUPP;
3291 		}
3292 
3293 		if (!bpf_jit_supports_kfunc_call()) {
3294 			verbose(env, "JIT does not support calling kernel function\n");
3295 			return -ENOTSUPP;
3296 		}
3297 
3298 		if (!env->prog->gpl_compatible) {
3299 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3300 			return -EINVAL;
3301 		}
3302 
3303 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3304 		if (!tab)
3305 			return -ENOMEM;
3306 		prog_aux->kfunc_tab = tab;
3307 	}
3308 
3309 	/* func_id == 0 is always invalid, but instead of returning an error, be
3310 	 * conservative and wait until the code elimination pass before returning
3311 	 * error, so that invalid calls that get pruned out can be in BPF programs
3312 	 * loaded from userspace.  It is also required that offset be untouched
3313 	 * for such calls.
3314 	 */
3315 	if (!func_id && !offset)
3316 		return 0;
3317 
3318 	if (!btf_tab && offset) {
3319 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3320 		if (!btf_tab)
3321 			return -ENOMEM;
3322 		prog_aux->kfunc_btf_tab = btf_tab;
3323 	}
3324 
3325 	desc_btf = find_kfunc_desc_btf(env, offset);
3326 	if (IS_ERR(desc_btf)) {
3327 		verbose(env, "failed to find BTF for kernel function\n");
3328 		return PTR_ERR(desc_btf);
3329 	}
3330 
3331 	if (find_kfunc_desc(env->prog, func_id, offset))
3332 		return 0;
3333 
3334 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3335 		verbose(env, "too many different kernel function calls\n");
3336 		return -E2BIG;
3337 	}
3338 
3339 	func = btf_type_by_id(desc_btf, func_id);
3340 	if (!func || !btf_type_is_func(func)) {
3341 		verbose(env, "kernel btf_id %u is not a function\n",
3342 			func_id);
3343 		return -EINVAL;
3344 	}
3345 	func_proto = btf_type_by_id(desc_btf, func->type);
3346 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3347 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3348 			func_id);
3349 		return -EINVAL;
3350 	}
3351 
3352 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3353 	addr = kallsyms_lookup_name(func_name);
3354 	if (!addr) {
3355 		verbose(env, "cannot find address for kernel function %s\n",
3356 			func_name);
3357 		return -EINVAL;
3358 	}
3359 
3360 	if (bpf_dev_bound_kfunc_id(func_id)) {
3361 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3362 		if (err)
3363 			return err;
3364 	}
3365 
3366 	err = btf_distill_func_proto(&env->log, desc_btf,
3367 				     func_proto, func_name,
3368 				     &func_model);
3369 	if (err)
3370 		return err;
3371 
3372 	desc = &tab->descs[tab->nr_descs++];
3373 	desc->func_id = func_id;
3374 	desc->offset = offset;
3375 	desc->addr = addr;
3376 	desc->func_model = func_model;
3377 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3378 	     kfunc_desc_cmp_by_id_off, NULL);
3379 	return 0;
3380 }
3381 
3382 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3383 {
3384 	const struct bpf_kfunc_desc *d0 = a;
3385 	const struct bpf_kfunc_desc *d1 = b;
3386 
3387 	if (d0->imm != d1->imm)
3388 		return d0->imm < d1->imm ? -1 : 1;
3389 	if (d0->offset != d1->offset)
3390 		return d0->offset < d1->offset ? -1 : 1;
3391 	return 0;
3392 }
3393 
3394 static int set_kfunc_desc_imm(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
3395 {
3396 	unsigned long call_imm;
3397 
3398 	if (bpf_jit_supports_far_kfunc_call()) {
3399 		call_imm = desc->func_id;
3400 	} else {
3401 		call_imm = BPF_CALL_IMM(desc->addr);
3402 		/* Check whether the relative offset overflows desc->imm */
3403 		if ((unsigned long)(s32)call_imm != call_imm) {
3404 			verbose(env, "address of kernel func_id %u is out of range\n",
3405 				desc->func_id);
3406 			return -EINVAL;
3407 		}
3408 	}
3409 	desc->imm = call_imm;
3410 	return 0;
3411 }
3412 
3413 static int sort_kfunc_descs_by_imm_off(struct bpf_verifier_env *env)
3414 {
3415 	struct bpf_kfunc_desc_tab *tab;
3416 	int i, err;
3417 
3418 	tab = env->prog->aux->kfunc_tab;
3419 	if (!tab)
3420 		return 0;
3421 
3422 	for (i = 0; i < tab->nr_descs; i++) {
3423 		err = set_kfunc_desc_imm(env, &tab->descs[i]);
3424 		if (err)
3425 			return err;
3426 	}
3427 
3428 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3429 	     kfunc_desc_cmp_by_imm_off, NULL);
3430 	return 0;
3431 }
3432 
3433 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3434 {
3435 	return !!prog->aux->kfunc_tab;
3436 }
3437 
3438 const struct btf_func_model *
3439 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3440 			 const struct bpf_insn *insn)
3441 {
3442 	const struct bpf_kfunc_desc desc = {
3443 		.imm = insn->imm,
3444 		.offset = insn->off,
3445 	};
3446 	const struct bpf_kfunc_desc *res;
3447 	struct bpf_kfunc_desc_tab *tab;
3448 
3449 	tab = prog->aux->kfunc_tab;
3450 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3451 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3452 
3453 	return res ? &res->func_model : NULL;
3454 }
3455 
3456 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3457 			      struct bpf_insn *insn, int cnt)
3458 {
3459 	int i, ret;
3460 
3461 	for (i = 0; i < cnt; i++, insn++) {
3462 		if (bpf_pseudo_kfunc_call(insn)) {
3463 			ret = add_kfunc_call(env, insn->imm, insn->off);
3464 			if (ret < 0)
3465 				return ret;
3466 		}
3467 	}
3468 	return 0;
3469 }
3470 
3471 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3472 {
3473 	struct bpf_subprog_info *subprog = env->subprog_info;
3474 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3475 	struct bpf_insn *insn = env->prog->insnsi;
3476 
3477 	/* Add entry function. */
3478 	ret = add_subprog(env, 0);
3479 	if (ret)
3480 		return ret;
3481 
3482 	for (i = 0; i < insn_cnt; i++, insn++) {
3483 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3484 		    !bpf_pseudo_kfunc_call(insn))
3485 			continue;
3486 
3487 		if (!env->bpf_capable) {
3488 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3489 			return -EPERM;
3490 		}
3491 
3492 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3493 			ret = add_subprog(env, i + insn->imm + 1);
3494 		else
3495 			ret = add_kfunc_call(env, insn->imm, insn->off);
3496 
3497 		if (ret < 0)
3498 			return ret;
3499 	}
3500 
3501 	ret = bpf_find_exception_callback_insn_off(env);
3502 	if (ret < 0)
3503 		return ret;
3504 	ex_cb_insn = ret;
3505 
3506 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3507 	 * marked using BTF decl tag to serve as the exception callback.
3508 	 */
3509 	if (ex_cb_insn) {
3510 		ret = add_subprog(env, ex_cb_insn);
3511 		if (ret < 0)
3512 			return ret;
3513 		for (i = 1; i < env->subprog_cnt; i++) {
3514 			if (env->subprog_info[i].start != ex_cb_insn)
3515 				continue;
3516 			env->exception_callback_subprog = i;
3517 			mark_subprog_exc_cb(env, i);
3518 			break;
3519 		}
3520 	}
3521 
3522 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3523 	 * logic. 'subprog_cnt' should not be increased.
3524 	 */
3525 	subprog[env->subprog_cnt].start = insn_cnt;
3526 
3527 	if (env->log.level & BPF_LOG_LEVEL2)
3528 		for (i = 0; i < env->subprog_cnt; i++)
3529 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3530 
3531 	return 0;
3532 }
3533 
3534 static int check_subprogs(struct bpf_verifier_env *env)
3535 {
3536 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3537 	struct bpf_subprog_info *subprog = env->subprog_info;
3538 	struct bpf_insn *insn = env->prog->insnsi;
3539 	int insn_cnt = env->prog->len;
3540 
3541 	/* now check that all jumps are within the same subprog */
3542 	subprog_start = subprog[cur_subprog].start;
3543 	subprog_end = subprog[cur_subprog + 1].start;
3544 	for (i = 0; i < insn_cnt; i++) {
3545 		u8 code = insn[i].code;
3546 
3547 		if (code == (BPF_JMP | BPF_CALL) &&
3548 		    insn[i].src_reg == 0 &&
3549 		    insn[i].imm == BPF_FUNC_tail_call) {
3550 			subprog[cur_subprog].has_tail_call = true;
3551 			subprog[cur_subprog].tail_call_reachable = true;
3552 		}
3553 		if (BPF_CLASS(code) == BPF_LD &&
3554 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3555 			subprog[cur_subprog].has_ld_abs = true;
3556 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3557 			goto next;
3558 		if (BPF_OP(code) == BPF_CALL)
3559 			goto next;
3560 		if (BPF_OP(code) == BPF_EXIT) {
3561 			subprog[cur_subprog].exit_idx = i;
3562 			goto next;
3563 		}
3564 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3565 		if (off < subprog_start || off >= subprog_end) {
3566 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3567 			return -EINVAL;
3568 		}
3569 next:
3570 		if (i == subprog_end - 1) {
3571 			/* to avoid fall-through from one subprog into another
3572 			 * the last insn of the subprog should be either exit
3573 			 * or unconditional jump back or bpf_throw call
3574 			 */
3575 			if (code != (BPF_JMP | BPF_EXIT) &&
3576 			    code != (BPF_JMP32 | BPF_JA) &&
3577 			    code != (BPF_JMP | BPF_JA)) {
3578 				verbose(env, "last insn is not an exit or jmp\n");
3579 				return -EINVAL;
3580 			}
3581 			subprog_start = subprog_end;
3582 			cur_subprog++;
3583 			if (cur_subprog < env->subprog_cnt)
3584 				subprog_end = subprog[cur_subprog + 1].start;
3585 		}
3586 	}
3587 	return 0;
3588 }
3589 
3590 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3591 				    int spi, int nr_slots)
3592 {
3593 	int err, i;
3594 
3595 	for (i = 0; i < nr_slots; i++) {
3596 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3597 		if (err)
3598 			return err;
3599 		mark_stack_slot_scratched(env, spi - i);
3600 	}
3601 	return 0;
3602 }
3603 
3604 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3605 {
3606 	int spi;
3607 
3608 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3609 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3610 	 * check_kfunc_call.
3611 	 */
3612 	if (reg->type == CONST_PTR_TO_DYNPTR)
3613 		return 0;
3614 	spi = dynptr_get_spi(env, reg);
3615 	if (spi < 0)
3616 		return spi;
3617 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3618 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3619 	 * read.
3620 	 */
3621 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3622 }
3623 
3624 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3625 			  int spi, int nr_slots)
3626 {
3627 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3628 }
3629 
3630 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3631 {
3632 	int spi;
3633 
3634 	spi = irq_flag_get_spi(env, reg);
3635 	if (spi < 0)
3636 		return spi;
3637 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3638 }
3639 
3640 /* This function is supposed to be used by the following 32-bit optimization
3641  * code only. It returns TRUE if the source or destination register operates
3642  * on 64-bit, otherwise return FALSE.
3643  */
3644 static bool is_reg64(struct bpf_insn *insn,
3645 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3646 {
3647 	u8 code, class, op;
3648 
3649 	code = insn->code;
3650 	class = BPF_CLASS(code);
3651 	op = BPF_OP(code);
3652 	if (class == BPF_JMP) {
3653 		/* BPF_EXIT for "main" will reach here. Return TRUE
3654 		 * conservatively.
3655 		 */
3656 		if (op == BPF_EXIT)
3657 			return true;
3658 		if (op == BPF_CALL) {
3659 			/* BPF to BPF call will reach here because of marking
3660 			 * caller saved clobber with DST_OP_NO_MARK for which we
3661 			 * don't care the register def because they are anyway
3662 			 * marked as NOT_INIT already.
3663 			 */
3664 			if (insn->src_reg == BPF_PSEUDO_CALL)
3665 				return false;
3666 			/* Helper call will reach here because of arg type
3667 			 * check, conservatively return TRUE.
3668 			 */
3669 			if (t == SRC_OP)
3670 				return true;
3671 
3672 			return false;
3673 		}
3674 	}
3675 
3676 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3677 		return false;
3678 
3679 	if (class == BPF_ALU64 || class == BPF_JMP ||
3680 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3681 		return true;
3682 
3683 	if (class == BPF_ALU || class == BPF_JMP32)
3684 		return false;
3685 
3686 	if (class == BPF_LDX) {
3687 		if (t != SRC_OP)
3688 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3689 		/* LDX source must be ptr. */
3690 		return true;
3691 	}
3692 
3693 	if (class == BPF_STX) {
3694 		/* BPF_STX (including atomic variants) has one or more source
3695 		 * operands, one of which is a ptr. Check whether the caller is
3696 		 * asking about it.
3697 		 */
3698 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3699 			return true;
3700 		return BPF_SIZE(code) == BPF_DW;
3701 	}
3702 
3703 	if (class == BPF_LD) {
3704 		u8 mode = BPF_MODE(code);
3705 
3706 		/* LD_IMM64 */
3707 		if (mode == BPF_IMM)
3708 			return true;
3709 
3710 		/* Both LD_IND and LD_ABS return 32-bit data. */
3711 		if (t != SRC_OP)
3712 			return  false;
3713 
3714 		/* Implicit ctx ptr. */
3715 		if (regno == BPF_REG_6)
3716 			return true;
3717 
3718 		/* Explicit source could be any width. */
3719 		return true;
3720 	}
3721 
3722 	if (class == BPF_ST)
3723 		/* The only source register for BPF_ST is a ptr. */
3724 		return true;
3725 
3726 	/* Conservatively return true at default. */
3727 	return true;
3728 }
3729 
3730 /* Return the regno defined by the insn, or -1. */
3731 static int insn_def_regno(const struct bpf_insn *insn)
3732 {
3733 	switch (BPF_CLASS(insn->code)) {
3734 	case BPF_JMP:
3735 	case BPF_JMP32:
3736 	case BPF_ST:
3737 		return -1;
3738 	case BPF_STX:
3739 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3740 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3741 			if (insn->imm == BPF_CMPXCHG)
3742 				return BPF_REG_0;
3743 			else if (insn->imm == BPF_LOAD_ACQ)
3744 				return insn->dst_reg;
3745 			else if (insn->imm & BPF_FETCH)
3746 				return insn->src_reg;
3747 		}
3748 		return -1;
3749 	default:
3750 		return insn->dst_reg;
3751 	}
3752 }
3753 
3754 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3755 static bool insn_has_def32(struct bpf_insn *insn)
3756 {
3757 	int dst_reg = insn_def_regno(insn);
3758 
3759 	if (dst_reg == -1)
3760 		return false;
3761 
3762 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3763 }
3764 
3765 static void mark_insn_zext(struct bpf_verifier_env *env,
3766 			   struct bpf_reg_state *reg)
3767 {
3768 	s32 def_idx = reg->subreg_def;
3769 
3770 	if (def_idx == DEF_NOT_SUBREG)
3771 		return;
3772 
3773 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3774 	/* The dst will be zero extended, so won't be sub-register anymore. */
3775 	reg->subreg_def = DEF_NOT_SUBREG;
3776 }
3777 
3778 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3779 			   enum reg_arg_type t)
3780 {
3781 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3782 	struct bpf_reg_state *reg;
3783 	bool rw64;
3784 
3785 	if (regno >= MAX_BPF_REG) {
3786 		verbose(env, "R%d is invalid\n", regno);
3787 		return -EINVAL;
3788 	}
3789 
3790 	mark_reg_scratched(env, regno);
3791 
3792 	reg = &regs[regno];
3793 	rw64 = is_reg64(insn, regno, reg, t);
3794 	if (t == SRC_OP) {
3795 		/* check whether register used as source operand can be read */
3796 		if (reg->type == NOT_INIT) {
3797 			verbose(env, "R%d !read_ok\n", regno);
3798 			return -EACCES;
3799 		}
3800 		/* We don't need to worry about FP liveness because it's read-only */
3801 		if (regno == BPF_REG_FP)
3802 			return 0;
3803 
3804 		if (rw64)
3805 			mark_insn_zext(env, reg);
3806 
3807 		return 0;
3808 	} else {
3809 		/* check whether register used as dest operand can be written to */
3810 		if (regno == BPF_REG_FP) {
3811 			verbose(env, "frame pointer is read only\n");
3812 			return -EACCES;
3813 		}
3814 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3815 		if (t == DST_OP)
3816 			mark_reg_unknown(env, regs, regno);
3817 	}
3818 	return 0;
3819 }
3820 
3821 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3822 			 enum reg_arg_type t)
3823 {
3824 	struct bpf_verifier_state *vstate = env->cur_state;
3825 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3826 
3827 	return __check_reg_arg(env, state->regs, regno, t);
3828 }
3829 
3830 static int insn_stack_access_flags(int frameno, int spi)
3831 {
3832 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3833 }
3834 
3835 static int insn_stack_access_spi(int insn_flags)
3836 {
3837 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3838 }
3839 
3840 static int insn_stack_access_frameno(int insn_flags)
3841 {
3842 	return insn_flags & INSN_F_FRAMENO_MASK;
3843 }
3844 
3845 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3846 {
3847 	env->insn_aux_data[idx].jmp_point = true;
3848 }
3849 
3850 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3851 {
3852 	return env->insn_aux_data[insn_idx].jmp_point;
3853 }
3854 
3855 #define LR_FRAMENO_BITS	3
3856 #define LR_SPI_BITS	6
3857 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3858 #define LR_SIZE_BITS	4
3859 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3860 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3861 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3862 #define LR_SPI_OFF	LR_FRAMENO_BITS
3863 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3864 #define LINKED_REGS_MAX	6
3865 
3866 struct linked_reg {
3867 	u8 frameno;
3868 	union {
3869 		u8 spi;
3870 		u8 regno;
3871 	};
3872 	bool is_reg;
3873 };
3874 
3875 struct linked_regs {
3876 	int cnt;
3877 	struct linked_reg entries[LINKED_REGS_MAX];
3878 };
3879 
3880 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3881 {
3882 	if (s->cnt < LINKED_REGS_MAX)
3883 		return &s->entries[s->cnt++];
3884 
3885 	return NULL;
3886 }
3887 
3888 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3889  * number of elements currently in stack.
3890  * Pack one history entry for linked registers as 10 bits in the following format:
3891  * - 3-bits frameno
3892  * - 6-bits spi_or_reg
3893  * - 1-bit  is_reg
3894  */
3895 static u64 linked_regs_pack(struct linked_regs *s)
3896 {
3897 	u64 val = 0;
3898 	int i;
3899 
3900 	for (i = 0; i < s->cnt; ++i) {
3901 		struct linked_reg *e = &s->entries[i];
3902 		u64 tmp = 0;
3903 
3904 		tmp |= e->frameno;
3905 		tmp |= e->spi << LR_SPI_OFF;
3906 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3907 
3908 		val <<= LR_ENTRY_BITS;
3909 		val |= tmp;
3910 	}
3911 	val <<= LR_SIZE_BITS;
3912 	val |= s->cnt;
3913 	return val;
3914 }
3915 
3916 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3917 {
3918 	int i;
3919 
3920 	s->cnt = val & LR_SIZE_MASK;
3921 	val >>= LR_SIZE_BITS;
3922 
3923 	for (i = 0; i < s->cnt; ++i) {
3924 		struct linked_reg *e = &s->entries[i];
3925 
3926 		e->frameno =  val & LR_FRAMENO_MASK;
3927 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3928 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3929 		val >>= LR_ENTRY_BITS;
3930 	}
3931 }
3932 
3933 /* for any branch, call, exit record the history of jmps in the given state */
3934 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3935 			    int insn_flags, u64 linked_regs)
3936 {
3937 	u32 cnt = cur->jmp_history_cnt;
3938 	struct bpf_jmp_history_entry *p;
3939 	size_t alloc_size;
3940 
3941 	/* combine instruction flags if we already recorded this instruction */
3942 	if (env->cur_hist_ent) {
3943 		/* atomic instructions push insn_flags twice, for READ and
3944 		 * WRITE sides, but they should agree on stack slot
3945 		 */
3946 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3947 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3948 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3949 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3950 		env->cur_hist_ent->flags |= insn_flags;
3951 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3952 				"insn history: insn_idx %d linked_regs: %#llx",
3953 				env->insn_idx, env->cur_hist_ent->linked_regs);
3954 		env->cur_hist_ent->linked_regs = linked_regs;
3955 		return 0;
3956 	}
3957 
3958 	cnt++;
3959 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3960 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3961 	if (!p)
3962 		return -ENOMEM;
3963 	cur->jmp_history = p;
3964 
3965 	p = &cur->jmp_history[cnt - 1];
3966 	p->idx = env->insn_idx;
3967 	p->prev_idx = env->prev_insn_idx;
3968 	p->flags = insn_flags;
3969 	p->linked_regs = linked_regs;
3970 	cur->jmp_history_cnt = cnt;
3971 	env->cur_hist_ent = p;
3972 
3973 	return 0;
3974 }
3975 
3976 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3977 						        u32 hist_end, int insn_idx)
3978 {
3979 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3980 		return &st->jmp_history[hist_end - 1];
3981 	return NULL;
3982 }
3983 
3984 /* Backtrack one insn at a time. If idx is not at the top of recorded
3985  * history then previous instruction came from straight line execution.
3986  * Return -ENOENT if we exhausted all instructions within given state.
3987  *
3988  * It's legal to have a bit of a looping with the same starting and ending
3989  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3990  * instruction index is the same as state's first_idx doesn't mean we are
3991  * done. If there is still some jump history left, we should keep going. We
3992  * need to take into account that we might have a jump history between given
3993  * state's parent and itself, due to checkpointing. In this case, we'll have
3994  * history entry recording a jump from last instruction of parent state and
3995  * first instruction of given state.
3996  */
3997 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3998 			     u32 *history)
3999 {
4000 	u32 cnt = *history;
4001 
4002 	if (i == st->first_insn_idx) {
4003 		if (cnt == 0)
4004 			return -ENOENT;
4005 		if (cnt == 1 && st->jmp_history[0].idx == i)
4006 			return -ENOENT;
4007 	}
4008 
4009 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
4010 		i = st->jmp_history[cnt - 1].prev_idx;
4011 		(*history)--;
4012 	} else {
4013 		i--;
4014 	}
4015 	return i;
4016 }
4017 
4018 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4019 {
4020 	const struct btf_type *func;
4021 	struct btf *desc_btf;
4022 
4023 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4024 		return NULL;
4025 
4026 	desc_btf = find_kfunc_desc_btf(data, insn->off);
4027 	if (IS_ERR(desc_btf))
4028 		return "<error>";
4029 
4030 	func = btf_type_by_id(desc_btf, insn->imm);
4031 	return btf_name_by_offset(desc_btf, func->name_off);
4032 }
4033 
4034 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4035 {
4036 	const struct bpf_insn_cbs cbs = {
4037 		.cb_call	= disasm_kfunc_name,
4038 		.cb_print	= verbose,
4039 		.private_data	= env,
4040 	};
4041 
4042 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4043 }
4044 
4045 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4046 {
4047 	bt->frame = frame;
4048 }
4049 
4050 static inline void bt_reset(struct backtrack_state *bt)
4051 {
4052 	struct bpf_verifier_env *env = bt->env;
4053 
4054 	memset(bt, 0, sizeof(*bt));
4055 	bt->env = env;
4056 }
4057 
4058 static inline u32 bt_empty(struct backtrack_state *bt)
4059 {
4060 	u64 mask = 0;
4061 	int i;
4062 
4063 	for (i = 0; i <= bt->frame; i++)
4064 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4065 
4066 	return mask == 0;
4067 }
4068 
4069 static inline int bt_subprog_enter(struct backtrack_state *bt)
4070 {
4071 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4072 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4073 		return -EFAULT;
4074 	}
4075 	bt->frame++;
4076 	return 0;
4077 }
4078 
4079 static inline int bt_subprog_exit(struct backtrack_state *bt)
4080 {
4081 	if (bt->frame == 0) {
4082 		verifier_bug(bt->env, "subprog exit from frame 0");
4083 		return -EFAULT;
4084 	}
4085 	bt->frame--;
4086 	return 0;
4087 }
4088 
4089 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4090 {
4091 	bt->reg_masks[frame] |= 1 << reg;
4092 }
4093 
4094 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4095 {
4096 	bt->reg_masks[frame] &= ~(1 << reg);
4097 }
4098 
4099 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4100 {
4101 	bt_set_frame_reg(bt, bt->frame, reg);
4102 }
4103 
4104 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4105 {
4106 	bt_clear_frame_reg(bt, bt->frame, reg);
4107 }
4108 
4109 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4110 {
4111 	bt->stack_masks[frame] |= 1ull << slot;
4112 }
4113 
4114 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4115 {
4116 	bt->stack_masks[frame] &= ~(1ull << slot);
4117 }
4118 
4119 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4120 {
4121 	return bt->reg_masks[frame];
4122 }
4123 
4124 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4125 {
4126 	return bt->reg_masks[bt->frame];
4127 }
4128 
4129 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4130 {
4131 	return bt->stack_masks[frame];
4132 }
4133 
4134 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4135 {
4136 	return bt->stack_masks[bt->frame];
4137 }
4138 
4139 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4140 {
4141 	return bt->reg_masks[bt->frame] & (1 << reg);
4142 }
4143 
4144 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4145 {
4146 	return bt->reg_masks[frame] & (1 << reg);
4147 }
4148 
4149 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4150 {
4151 	return bt->stack_masks[frame] & (1ull << slot);
4152 }
4153 
4154 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
4155 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4156 {
4157 	DECLARE_BITMAP(mask, 64);
4158 	bool first = true;
4159 	int i, n;
4160 
4161 	buf[0] = '\0';
4162 
4163 	bitmap_from_u64(mask, reg_mask);
4164 	for_each_set_bit(i, mask, 32) {
4165 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4166 		first = false;
4167 		buf += n;
4168 		buf_sz -= n;
4169 		if (buf_sz < 0)
4170 			break;
4171 	}
4172 }
4173 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
4174 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4175 {
4176 	DECLARE_BITMAP(mask, 64);
4177 	bool first = true;
4178 	int i, n;
4179 
4180 	buf[0] = '\0';
4181 
4182 	bitmap_from_u64(mask, stack_mask);
4183 	for_each_set_bit(i, mask, 64) {
4184 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4185 		first = false;
4186 		buf += n;
4187 		buf_sz -= n;
4188 		if (buf_sz < 0)
4189 			break;
4190 	}
4191 }
4192 
4193 /* If any register R in hist->linked_regs is marked as precise in bt,
4194  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4195  */
4196 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4197 {
4198 	struct linked_regs linked_regs;
4199 	bool some_precise = false;
4200 	int i;
4201 
4202 	if (!hist || hist->linked_regs == 0)
4203 		return;
4204 
4205 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4206 	for (i = 0; i < linked_regs.cnt; ++i) {
4207 		struct linked_reg *e = &linked_regs.entries[i];
4208 
4209 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4210 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4211 			some_precise = true;
4212 			break;
4213 		}
4214 	}
4215 
4216 	if (!some_precise)
4217 		return;
4218 
4219 	for (i = 0; i < linked_regs.cnt; ++i) {
4220 		struct linked_reg *e = &linked_regs.entries[i];
4221 
4222 		if (e->is_reg)
4223 			bt_set_frame_reg(bt, e->frameno, e->regno);
4224 		else
4225 			bt_set_frame_slot(bt, e->frameno, e->spi);
4226 	}
4227 }
4228 
4229 /* For given verifier state backtrack_insn() is called from the last insn to
4230  * the first insn. Its purpose is to compute a bitmask of registers and
4231  * stack slots that needs precision in the parent verifier state.
4232  *
4233  * @idx is an index of the instruction we are currently processing;
4234  * @subseq_idx is an index of the subsequent instruction that:
4235  *   - *would be* executed next, if jump history is viewed in forward order;
4236  *   - *was* processed previously during backtracking.
4237  */
4238 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4239 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4240 {
4241 	struct bpf_insn *insn = env->prog->insnsi + idx;
4242 	u8 class = BPF_CLASS(insn->code);
4243 	u8 opcode = BPF_OP(insn->code);
4244 	u8 mode = BPF_MODE(insn->code);
4245 	u32 dreg = insn->dst_reg;
4246 	u32 sreg = insn->src_reg;
4247 	u32 spi, i, fr;
4248 
4249 	if (insn->code == 0)
4250 		return 0;
4251 	if (env->log.level & BPF_LOG_LEVEL2) {
4252 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4253 		verbose(env, "mark_precise: frame%d: regs=%s ",
4254 			bt->frame, env->tmp_str_buf);
4255 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4256 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4257 		verbose(env, "%d: ", idx);
4258 		verbose_insn(env, insn);
4259 	}
4260 
4261 	/* If there is a history record that some registers gained range at this insn,
4262 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4263 	 * accounts for these registers.
4264 	 */
4265 	bt_sync_linked_regs(bt, hist);
4266 
4267 	if (class == BPF_ALU || class == BPF_ALU64) {
4268 		if (!bt_is_reg_set(bt, dreg))
4269 			return 0;
4270 		if (opcode == BPF_END || opcode == BPF_NEG) {
4271 			/* sreg is reserved and unused
4272 			 * dreg still need precision before this insn
4273 			 */
4274 			return 0;
4275 		} else if (opcode == BPF_MOV) {
4276 			if (BPF_SRC(insn->code) == BPF_X) {
4277 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4278 				 * dreg needs precision after this insn
4279 				 * sreg needs precision before this insn
4280 				 */
4281 				bt_clear_reg(bt, dreg);
4282 				if (sreg != BPF_REG_FP)
4283 					bt_set_reg(bt, sreg);
4284 			} else {
4285 				/* dreg = K
4286 				 * dreg needs precision after this insn.
4287 				 * Corresponding register is already marked
4288 				 * as precise=true in this verifier state.
4289 				 * No further markings in parent are necessary
4290 				 */
4291 				bt_clear_reg(bt, dreg);
4292 			}
4293 		} else {
4294 			if (BPF_SRC(insn->code) == BPF_X) {
4295 				/* dreg += sreg
4296 				 * both dreg and sreg need precision
4297 				 * before this insn
4298 				 */
4299 				if (sreg != BPF_REG_FP)
4300 					bt_set_reg(bt, sreg);
4301 			} /* else dreg += K
4302 			   * dreg still needs precision before this insn
4303 			   */
4304 		}
4305 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4306 		if (!bt_is_reg_set(bt, dreg))
4307 			return 0;
4308 		bt_clear_reg(bt, dreg);
4309 
4310 		/* scalars can only be spilled into stack w/o losing precision.
4311 		 * Load from any other memory can be zero extended.
4312 		 * The desire to keep that precision is already indicated
4313 		 * by 'precise' mark in corresponding register of this state.
4314 		 * No further tracking necessary.
4315 		 */
4316 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4317 			return 0;
4318 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4319 		 * that [fp - off] slot contains scalar that needs to be
4320 		 * tracked with precision
4321 		 */
4322 		spi = insn_stack_access_spi(hist->flags);
4323 		fr = insn_stack_access_frameno(hist->flags);
4324 		bt_set_frame_slot(bt, fr, spi);
4325 	} else if (class == BPF_STX || class == BPF_ST) {
4326 		if (bt_is_reg_set(bt, dreg))
4327 			/* stx & st shouldn't be using _scalar_ dst_reg
4328 			 * to access memory. It means backtracking
4329 			 * encountered a case of pointer subtraction.
4330 			 */
4331 			return -ENOTSUPP;
4332 		/* scalars can only be spilled into stack */
4333 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4334 			return 0;
4335 		spi = insn_stack_access_spi(hist->flags);
4336 		fr = insn_stack_access_frameno(hist->flags);
4337 		if (!bt_is_frame_slot_set(bt, fr, spi))
4338 			return 0;
4339 		bt_clear_frame_slot(bt, fr, spi);
4340 		if (class == BPF_STX)
4341 			bt_set_reg(bt, sreg);
4342 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4343 		if (bpf_pseudo_call(insn)) {
4344 			int subprog_insn_idx, subprog;
4345 
4346 			subprog_insn_idx = idx + insn->imm + 1;
4347 			subprog = find_subprog(env, subprog_insn_idx);
4348 			if (subprog < 0)
4349 				return -EFAULT;
4350 
4351 			if (subprog_is_global(env, subprog)) {
4352 				/* check that jump history doesn't have any
4353 				 * extra instructions from subprog; the next
4354 				 * instruction after call to global subprog
4355 				 * should be literally next instruction in
4356 				 * caller program
4357 				 */
4358 				verifier_bug_if(idx + 1 != subseq_idx, env,
4359 						"extra insn from subprog");
4360 				/* r1-r5 are invalidated after subprog call,
4361 				 * so for global func call it shouldn't be set
4362 				 * anymore
4363 				 */
4364 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4365 					verifier_bug(env, "global subprog unexpected regs %x",
4366 						     bt_reg_mask(bt));
4367 					return -EFAULT;
4368 				}
4369 				/* global subprog always sets R0 */
4370 				bt_clear_reg(bt, BPF_REG_0);
4371 				return 0;
4372 			} else {
4373 				/* static subprog call instruction, which
4374 				 * means that we are exiting current subprog,
4375 				 * so only r1-r5 could be still requested as
4376 				 * precise, r0 and r6-r10 or any stack slot in
4377 				 * the current frame should be zero by now
4378 				 */
4379 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4380 					verifier_bug(env, "static subprog unexpected regs %x",
4381 						     bt_reg_mask(bt));
4382 					return -EFAULT;
4383 				}
4384 				/* we are now tracking register spills correctly,
4385 				 * so any instance of leftover slots is a bug
4386 				 */
4387 				if (bt_stack_mask(bt) != 0) {
4388 					verifier_bug(env,
4389 						     "static subprog leftover stack slots %llx",
4390 						     bt_stack_mask(bt));
4391 					return -EFAULT;
4392 				}
4393 				/* propagate r1-r5 to the caller */
4394 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4395 					if (bt_is_reg_set(bt, i)) {
4396 						bt_clear_reg(bt, i);
4397 						bt_set_frame_reg(bt, bt->frame - 1, i);
4398 					}
4399 				}
4400 				if (bt_subprog_exit(bt))
4401 					return -EFAULT;
4402 				return 0;
4403 			}
4404 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4405 			/* exit from callback subprog to callback-calling helper or
4406 			 * kfunc call. Use idx/subseq_idx check to discern it from
4407 			 * straight line code backtracking.
4408 			 * Unlike the subprog call handling above, we shouldn't
4409 			 * propagate precision of r1-r5 (if any requested), as they are
4410 			 * not actually arguments passed directly to callback subprogs
4411 			 */
4412 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4413 				verifier_bug(env, "callback unexpected regs %x",
4414 					     bt_reg_mask(bt));
4415 				return -EFAULT;
4416 			}
4417 			if (bt_stack_mask(bt) != 0) {
4418 				verifier_bug(env, "callback leftover stack slots %llx",
4419 					     bt_stack_mask(bt));
4420 				return -EFAULT;
4421 			}
4422 			/* clear r1-r5 in callback subprog's mask */
4423 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4424 				bt_clear_reg(bt, i);
4425 			if (bt_subprog_exit(bt))
4426 				return -EFAULT;
4427 			return 0;
4428 		} else if (opcode == BPF_CALL) {
4429 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4430 			 * catch this error later. Make backtracking conservative
4431 			 * with ENOTSUPP.
4432 			 */
4433 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4434 				return -ENOTSUPP;
4435 			/* regular helper call sets R0 */
4436 			bt_clear_reg(bt, BPF_REG_0);
4437 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4438 				/* if backtracking was looking for registers R1-R5
4439 				 * they should have been found already.
4440 				 */
4441 				verifier_bug(env, "backtracking call unexpected regs %x",
4442 					     bt_reg_mask(bt));
4443 				return -EFAULT;
4444 			}
4445 			if (insn->src_reg == BPF_REG_0 && insn->imm == BPF_FUNC_tail_call
4446 			    && subseq_idx - idx != 1) {
4447 				if (bt_subprog_enter(bt))
4448 					return -EFAULT;
4449 			}
4450 		} else if (opcode == BPF_EXIT) {
4451 			bool r0_precise;
4452 
4453 			/* Backtracking to a nested function call, 'idx' is a part of
4454 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4455 			 * In case of a regular function call, instructions giving
4456 			 * precision to registers R1-R5 should have been found already.
4457 			 * In case of a callback, it is ok to have R1-R5 marked for
4458 			 * backtracking, as these registers are set by the function
4459 			 * invoking callback.
4460 			 */
4461 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4462 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4463 					bt_clear_reg(bt, i);
4464 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4465 				verifier_bug(env, "backtracking exit unexpected regs %x",
4466 					     bt_reg_mask(bt));
4467 				return -EFAULT;
4468 			}
4469 
4470 			/* BPF_EXIT in subprog or callback always returns
4471 			 * right after the call instruction, so by checking
4472 			 * whether the instruction at subseq_idx-1 is subprog
4473 			 * call or not we can distinguish actual exit from
4474 			 * *subprog* from exit from *callback*. In the former
4475 			 * case, we need to propagate r0 precision, if
4476 			 * necessary. In the former we never do that.
4477 			 */
4478 			r0_precise = subseq_idx - 1 >= 0 &&
4479 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4480 				     bt_is_reg_set(bt, BPF_REG_0);
4481 
4482 			bt_clear_reg(bt, BPF_REG_0);
4483 			if (bt_subprog_enter(bt))
4484 				return -EFAULT;
4485 
4486 			if (r0_precise)
4487 				bt_set_reg(bt, BPF_REG_0);
4488 			/* r6-r9 and stack slots will stay set in caller frame
4489 			 * bitmasks until we return back from callee(s)
4490 			 */
4491 			return 0;
4492 		} else if (BPF_SRC(insn->code) == BPF_X) {
4493 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4494 				return 0;
4495 			/* dreg <cond> sreg
4496 			 * Both dreg and sreg need precision before
4497 			 * this insn. If only sreg was marked precise
4498 			 * before it would be equally necessary to
4499 			 * propagate it to dreg.
4500 			 */
4501 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4502 				bt_set_reg(bt, sreg);
4503 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4504 				bt_set_reg(bt, dreg);
4505 		} else if (BPF_SRC(insn->code) == BPF_K) {
4506 			 /* dreg <cond> K
4507 			  * Only dreg still needs precision before
4508 			  * this insn, so for the K-based conditional
4509 			  * there is nothing new to be marked.
4510 			  */
4511 		}
4512 	} else if (class == BPF_LD) {
4513 		if (!bt_is_reg_set(bt, dreg))
4514 			return 0;
4515 		bt_clear_reg(bt, dreg);
4516 		/* It's ld_imm64 or ld_abs or ld_ind.
4517 		 * For ld_imm64 no further tracking of precision
4518 		 * into parent is necessary
4519 		 */
4520 		if (mode == BPF_IND || mode == BPF_ABS)
4521 			/* to be analyzed */
4522 			return -ENOTSUPP;
4523 	}
4524 	/* Propagate precision marks to linked registers, to account for
4525 	 * registers marked as precise in this function.
4526 	 */
4527 	bt_sync_linked_regs(bt, hist);
4528 	return 0;
4529 }
4530 
4531 /* the scalar precision tracking algorithm:
4532  * . at the start all registers have precise=false.
4533  * . scalar ranges are tracked as normal through alu and jmp insns.
4534  * . once precise value of the scalar register is used in:
4535  *   .  ptr + scalar alu
4536  *   . if (scalar cond K|scalar)
4537  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4538  *   backtrack through the verifier states and mark all registers and
4539  *   stack slots with spilled constants that these scalar registers
4540  *   should be precise.
4541  * . during state pruning two registers (or spilled stack slots)
4542  *   are equivalent if both are not precise.
4543  *
4544  * Note the verifier cannot simply walk register parentage chain,
4545  * since many different registers and stack slots could have been
4546  * used to compute single precise scalar.
4547  *
4548  * The approach of starting with precise=true for all registers and then
4549  * backtrack to mark a register as not precise when the verifier detects
4550  * that program doesn't care about specific value (e.g., when helper
4551  * takes register as ARG_ANYTHING parameter) is not safe.
4552  *
4553  * It's ok to walk single parentage chain of the verifier states.
4554  * It's possible that this backtracking will go all the way till 1st insn.
4555  * All other branches will be explored for needing precision later.
4556  *
4557  * The backtracking needs to deal with cases like:
4558  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
4559  * r9 -= r8
4560  * r5 = r9
4561  * if r5 > 0x79f goto pc+7
4562  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4563  * r5 += 1
4564  * ...
4565  * call bpf_perf_event_output#25
4566  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4567  *
4568  * and this case:
4569  * r6 = 1
4570  * call foo // uses callee's r6 inside to compute r0
4571  * r0 += r6
4572  * if r0 == 0 goto
4573  *
4574  * to track above reg_mask/stack_mask needs to be independent for each frame.
4575  *
4576  * Also if parent's curframe > frame where backtracking started,
4577  * the verifier need to mark registers in both frames, otherwise callees
4578  * may incorrectly prune callers. This is similar to
4579  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4580  *
4581  * For now backtracking falls back into conservative marking.
4582  */
4583 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4584 				     struct bpf_verifier_state *st)
4585 {
4586 	struct bpf_func_state *func;
4587 	struct bpf_reg_state *reg;
4588 	int i, j;
4589 
4590 	if (env->log.level & BPF_LOG_LEVEL2) {
4591 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4592 			st->curframe);
4593 	}
4594 
4595 	/* big hammer: mark all scalars precise in this path.
4596 	 * pop_stack may still get !precise scalars.
4597 	 * We also skip current state and go straight to first parent state,
4598 	 * because precision markings in current non-checkpointed state are
4599 	 * not needed. See why in the comment in __mark_chain_precision below.
4600 	 */
4601 	for (st = st->parent; st; st = st->parent) {
4602 		for (i = 0; i <= st->curframe; i++) {
4603 			func = st->frame[i];
4604 			for (j = 0; j < BPF_REG_FP; j++) {
4605 				reg = &func->regs[j];
4606 				if (reg->type != SCALAR_VALUE || reg->precise)
4607 					continue;
4608 				reg->precise = true;
4609 				if (env->log.level & BPF_LOG_LEVEL2) {
4610 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4611 						i, j);
4612 				}
4613 			}
4614 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4615 				if (!is_spilled_reg(&func->stack[j]))
4616 					continue;
4617 				reg = &func->stack[j].spilled_ptr;
4618 				if (reg->type != SCALAR_VALUE || reg->precise)
4619 					continue;
4620 				reg->precise = true;
4621 				if (env->log.level & BPF_LOG_LEVEL2) {
4622 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4623 						i, -(j + 1) * 8);
4624 				}
4625 			}
4626 		}
4627 	}
4628 }
4629 
4630 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4631 {
4632 	struct bpf_func_state *func;
4633 	struct bpf_reg_state *reg;
4634 	int i, j;
4635 
4636 	for (i = 0; i <= st->curframe; i++) {
4637 		func = st->frame[i];
4638 		for (j = 0; j < BPF_REG_FP; j++) {
4639 			reg = &func->regs[j];
4640 			if (reg->type != SCALAR_VALUE)
4641 				continue;
4642 			reg->precise = false;
4643 		}
4644 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4645 			if (!is_spilled_reg(&func->stack[j]))
4646 				continue;
4647 			reg = &func->stack[j].spilled_ptr;
4648 			if (reg->type != SCALAR_VALUE)
4649 				continue;
4650 			reg->precise = false;
4651 		}
4652 	}
4653 }
4654 
4655 /*
4656  * __mark_chain_precision() backtracks BPF program instruction sequence and
4657  * chain of verifier states making sure that register *regno* (if regno >= 0)
4658  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4659  * SCALARS, as well as any other registers and slots that contribute to
4660  * a tracked state of given registers/stack slots, depending on specific BPF
4661  * assembly instructions (see backtrack_insns() for exact instruction handling
4662  * logic). This backtracking relies on recorded jmp_history and is able to
4663  * traverse entire chain of parent states. This process ends only when all the
4664  * necessary registers/slots and their transitive dependencies are marked as
4665  * precise.
4666  *
4667  * One important and subtle aspect is that precise marks *do not matter* in
4668  * the currently verified state (current state). It is important to understand
4669  * why this is the case.
4670  *
4671  * First, note that current state is the state that is not yet "checkpointed",
4672  * i.e., it is not yet put into env->explored_states, and it has no children
4673  * states as well. It's ephemeral, and can end up either a) being discarded if
4674  * compatible explored state is found at some point or BPF_EXIT instruction is
4675  * reached or b) checkpointed and put into env->explored_states, branching out
4676  * into one or more children states.
4677  *
4678  * In the former case, precise markings in current state are completely
4679  * ignored by state comparison code (see regsafe() for details). Only
4680  * checkpointed ("old") state precise markings are important, and if old
4681  * state's register/slot is precise, regsafe() assumes current state's
4682  * register/slot as precise and checks value ranges exactly and precisely. If
4683  * states turn out to be compatible, current state's necessary precise
4684  * markings and any required parent states' precise markings are enforced
4685  * after the fact with propagate_precision() logic, after the fact. But it's
4686  * important to realize that in this case, even after marking current state
4687  * registers/slots as precise, we immediately discard current state. So what
4688  * actually matters is any of the precise markings propagated into current
4689  * state's parent states, which are always checkpointed (due to b) case above).
4690  * As such, for scenario a) it doesn't matter if current state has precise
4691  * markings set or not.
4692  *
4693  * Now, for the scenario b), checkpointing and forking into child(ren)
4694  * state(s). Note that before current state gets to checkpointing step, any
4695  * processed instruction always assumes precise SCALAR register/slot
4696  * knowledge: if precise value or range is useful to prune jump branch, BPF
4697  * verifier takes this opportunity enthusiastically. Similarly, when
4698  * register's value is used to calculate offset or memory address, exact
4699  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4700  * what we mentioned above about state comparison ignoring precise markings
4701  * during state comparison, BPF verifier ignores and also assumes precise
4702  * markings *at will* during instruction verification process. But as verifier
4703  * assumes precision, it also propagates any precision dependencies across
4704  * parent states, which are not yet finalized, so can be further restricted
4705  * based on new knowledge gained from restrictions enforced by their children
4706  * states. This is so that once those parent states are finalized, i.e., when
4707  * they have no more active children state, state comparison logic in
4708  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4709  * required for correctness.
4710  *
4711  * To build a bit more intuition, note also that once a state is checkpointed,
4712  * the path we took to get to that state is not important. This is crucial
4713  * property for state pruning. When state is checkpointed and finalized at
4714  * some instruction index, it can be correctly and safely used to "short
4715  * circuit" any *compatible* state that reaches exactly the same instruction
4716  * index. I.e., if we jumped to that instruction from a completely different
4717  * code path than original finalized state was derived from, it doesn't
4718  * matter, current state can be discarded because from that instruction
4719  * forward having a compatible state will ensure we will safely reach the
4720  * exit. States describe preconditions for further exploration, but completely
4721  * forget the history of how we got here.
4722  *
4723  * This also means that even if we needed precise SCALAR range to get to
4724  * finalized state, but from that point forward *that same* SCALAR register is
4725  * never used in a precise context (i.e., it's precise value is not needed for
4726  * correctness), it's correct and safe to mark such register as "imprecise"
4727  * (i.e., precise marking set to false). This is what we rely on when we do
4728  * not set precise marking in current state. If no child state requires
4729  * precision for any given SCALAR register, it's safe to dictate that it can
4730  * be imprecise. If any child state does require this register to be precise,
4731  * we'll mark it precise later retroactively during precise markings
4732  * propagation from child state to parent states.
4733  *
4734  * Skipping precise marking setting in current state is a mild version of
4735  * relying on the above observation. But we can utilize this property even
4736  * more aggressively by proactively forgetting any precise marking in the
4737  * current state (which we inherited from the parent state), right before we
4738  * checkpoint it and branch off into new child state. This is done by
4739  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4740  * finalized states which help in short circuiting more future states.
4741  */
4742 static int __mark_chain_precision(struct bpf_verifier_env *env,
4743 				  struct bpf_verifier_state *starting_state,
4744 				  int regno,
4745 				  bool *changed)
4746 {
4747 	struct bpf_verifier_state *st = starting_state;
4748 	struct backtrack_state *bt = &env->bt;
4749 	int first_idx = st->first_insn_idx;
4750 	int last_idx = starting_state->insn_idx;
4751 	int subseq_idx = -1;
4752 	struct bpf_func_state *func;
4753 	bool tmp, skip_first = true;
4754 	struct bpf_reg_state *reg;
4755 	int i, fr, err;
4756 
4757 	if (!env->bpf_capable)
4758 		return 0;
4759 
4760 	changed = changed ?: &tmp;
4761 	/* set frame number from which we are starting to backtrack */
4762 	bt_init(bt, starting_state->curframe);
4763 
4764 	/* Do sanity checks against current state of register and/or stack
4765 	 * slot, but don't set precise flag in current state, as precision
4766 	 * tracking in the current state is unnecessary.
4767 	 */
4768 	func = st->frame[bt->frame];
4769 	if (regno >= 0) {
4770 		reg = &func->regs[regno];
4771 		if (reg->type != SCALAR_VALUE) {
4772 			verifier_bug(env, "backtracking misuse");
4773 			return -EFAULT;
4774 		}
4775 		bt_set_reg(bt, regno);
4776 	}
4777 
4778 	if (bt_empty(bt))
4779 		return 0;
4780 
4781 	for (;;) {
4782 		DECLARE_BITMAP(mask, 64);
4783 		u32 history = st->jmp_history_cnt;
4784 		struct bpf_jmp_history_entry *hist;
4785 
4786 		if (env->log.level & BPF_LOG_LEVEL2) {
4787 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4788 				bt->frame, last_idx, first_idx, subseq_idx);
4789 		}
4790 
4791 		if (last_idx < 0) {
4792 			/* we are at the entry into subprog, which
4793 			 * is expected for global funcs, but only if
4794 			 * requested precise registers are R1-R5
4795 			 * (which are global func's input arguments)
4796 			 */
4797 			if (st->curframe == 0 &&
4798 			    st->frame[0]->subprogno > 0 &&
4799 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4800 			    bt_stack_mask(bt) == 0 &&
4801 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4802 				bitmap_from_u64(mask, bt_reg_mask(bt));
4803 				for_each_set_bit(i, mask, 32) {
4804 					reg = &st->frame[0]->regs[i];
4805 					bt_clear_reg(bt, i);
4806 					if (reg->type == SCALAR_VALUE) {
4807 						reg->precise = true;
4808 						*changed = true;
4809 					}
4810 				}
4811 				return 0;
4812 			}
4813 
4814 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4815 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4816 			return -EFAULT;
4817 		}
4818 
4819 		for (i = last_idx;;) {
4820 			if (skip_first) {
4821 				err = 0;
4822 				skip_first = false;
4823 			} else {
4824 				hist = get_jmp_hist_entry(st, history, i);
4825 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4826 			}
4827 			if (err == -ENOTSUPP) {
4828 				mark_all_scalars_precise(env, starting_state);
4829 				bt_reset(bt);
4830 				return 0;
4831 			} else if (err) {
4832 				return err;
4833 			}
4834 			if (bt_empty(bt))
4835 				/* Found assignment(s) into tracked register in this state.
4836 				 * Since this state is already marked, just return.
4837 				 * Nothing to be tracked further in the parent state.
4838 				 */
4839 				return 0;
4840 			subseq_idx = i;
4841 			i = get_prev_insn_idx(st, i, &history);
4842 			if (i == -ENOENT)
4843 				break;
4844 			if (i >= env->prog->len) {
4845 				/* This can happen if backtracking reached insn 0
4846 				 * and there are still reg_mask or stack_mask
4847 				 * to backtrack.
4848 				 * It means the backtracking missed the spot where
4849 				 * particular register was initialized with a constant.
4850 				 */
4851 				verifier_bug(env, "backtracking idx %d", i);
4852 				return -EFAULT;
4853 			}
4854 		}
4855 		st = st->parent;
4856 		if (!st)
4857 			break;
4858 
4859 		for (fr = bt->frame; fr >= 0; fr--) {
4860 			func = st->frame[fr];
4861 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4862 			for_each_set_bit(i, mask, 32) {
4863 				reg = &func->regs[i];
4864 				if (reg->type != SCALAR_VALUE) {
4865 					bt_clear_frame_reg(bt, fr, i);
4866 					continue;
4867 				}
4868 				if (reg->precise) {
4869 					bt_clear_frame_reg(bt, fr, i);
4870 				} else {
4871 					reg->precise = true;
4872 					*changed = true;
4873 				}
4874 			}
4875 
4876 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4877 			for_each_set_bit(i, mask, 64) {
4878 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4879 						    env, "stack slot %d, total slots %d",
4880 						    i, func->allocated_stack / BPF_REG_SIZE))
4881 					return -EFAULT;
4882 
4883 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4884 					bt_clear_frame_slot(bt, fr, i);
4885 					continue;
4886 				}
4887 				reg = &func->stack[i].spilled_ptr;
4888 				if (reg->precise) {
4889 					bt_clear_frame_slot(bt, fr, i);
4890 				} else {
4891 					reg->precise = true;
4892 					*changed = true;
4893 				}
4894 			}
4895 			if (env->log.level & BPF_LOG_LEVEL2) {
4896 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4897 					     bt_frame_reg_mask(bt, fr));
4898 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4899 					fr, env->tmp_str_buf);
4900 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4901 					       bt_frame_stack_mask(bt, fr));
4902 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4903 				print_verifier_state(env, st, fr, true);
4904 			}
4905 		}
4906 
4907 		if (bt_empty(bt))
4908 			return 0;
4909 
4910 		subseq_idx = first_idx;
4911 		last_idx = st->last_insn_idx;
4912 		first_idx = st->first_insn_idx;
4913 	}
4914 
4915 	/* if we still have requested precise regs or slots, we missed
4916 	 * something (e.g., stack access through non-r10 register), so
4917 	 * fallback to marking all precise
4918 	 */
4919 	if (!bt_empty(bt)) {
4920 		mark_all_scalars_precise(env, starting_state);
4921 		bt_reset(bt);
4922 	}
4923 
4924 	return 0;
4925 }
4926 
4927 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4928 {
4929 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4930 }
4931 
4932 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4933  * desired reg and stack masks across all relevant frames
4934  */
4935 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4936 				      struct bpf_verifier_state *starting_state)
4937 {
4938 	return __mark_chain_precision(env, starting_state, -1, NULL);
4939 }
4940 
4941 static bool is_spillable_regtype(enum bpf_reg_type type)
4942 {
4943 	switch (base_type(type)) {
4944 	case PTR_TO_MAP_VALUE:
4945 	case PTR_TO_STACK:
4946 	case PTR_TO_CTX:
4947 	case PTR_TO_PACKET:
4948 	case PTR_TO_PACKET_META:
4949 	case PTR_TO_PACKET_END:
4950 	case PTR_TO_FLOW_KEYS:
4951 	case CONST_PTR_TO_MAP:
4952 	case PTR_TO_SOCKET:
4953 	case PTR_TO_SOCK_COMMON:
4954 	case PTR_TO_TCP_SOCK:
4955 	case PTR_TO_XDP_SOCK:
4956 	case PTR_TO_BTF_ID:
4957 	case PTR_TO_BUF:
4958 	case PTR_TO_MEM:
4959 	case PTR_TO_FUNC:
4960 	case PTR_TO_MAP_KEY:
4961 	case PTR_TO_ARENA:
4962 		return true;
4963 	default:
4964 		return false;
4965 	}
4966 }
4967 
4968 /* Does this register contain a constant zero? */
4969 static bool register_is_null(struct bpf_reg_state *reg)
4970 {
4971 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4972 }
4973 
4974 /* check if register is a constant scalar value */
4975 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4976 {
4977 	return reg->type == SCALAR_VALUE &&
4978 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4979 }
4980 
4981 /* assuming is_reg_const() is true, return constant value of a register */
4982 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4983 {
4984 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4985 }
4986 
4987 static bool __is_pointer_value(bool allow_ptr_leaks,
4988 			       const struct bpf_reg_state *reg)
4989 {
4990 	if (allow_ptr_leaks)
4991 		return false;
4992 
4993 	return reg->type != SCALAR_VALUE;
4994 }
4995 
4996 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4997 					struct bpf_reg_state *src_reg)
4998 {
4999 	if (src_reg->type != SCALAR_VALUE)
5000 		return;
5001 
5002 	if (src_reg->id & BPF_ADD_CONST) {
5003 		/*
5004 		 * The verifier is processing rX = rY insn and
5005 		 * rY->id has special linked register already.
5006 		 * Cleared it, since multiple rX += const are not supported.
5007 		 */
5008 		src_reg->id = 0;
5009 		src_reg->off = 0;
5010 	}
5011 
5012 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5013 		/* Ensure that src_reg has a valid ID that will be copied to
5014 		 * dst_reg and then will be used by sync_linked_regs() to
5015 		 * propagate min/max range.
5016 		 */
5017 		src_reg->id = ++env->id_gen;
5018 }
5019 
5020 /* Copy src state preserving dst->parent and dst->live fields */
5021 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5022 {
5023 	*dst = *src;
5024 }
5025 
5026 static void save_register_state(struct bpf_verifier_env *env,
5027 				struct bpf_func_state *state,
5028 				int spi, struct bpf_reg_state *reg,
5029 				int size)
5030 {
5031 	int i;
5032 
5033 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
5034 
5035 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5036 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5037 
5038 	/* size < 8 bytes spill */
5039 	for (; i; i--)
5040 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5041 }
5042 
5043 static bool is_bpf_st_mem(struct bpf_insn *insn)
5044 {
5045 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5046 }
5047 
5048 static int get_reg_width(struct bpf_reg_state *reg)
5049 {
5050 	return fls64(reg->umax_value);
5051 }
5052 
5053 /* See comment for mark_fastcall_pattern_for_call() */
5054 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5055 					  struct bpf_func_state *state, int insn_idx, int off)
5056 {
5057 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5058 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5059 	int i;
5060 
5061 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5062 		return;
5063 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5064 	 * from something that is not a part of the fastcall pattern,
5065 	 * disable fastcall rewrites for current subprogram by setting
5066 	 * fastcall_stack_off to a value smaller than any possible offset.
5067 	 */
5068 	subprog->fastcall_stack_off = S16_MIN;
5069 	/* reset fastcall aux flags within subprogram,
5070 	 * happens at most once per subprogram
5071 	 */
5072 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5073 		aux[i].fastcall_spills_num = 0;
5074 		aux[i].fastcall_pattern = 0;
5075 	}
5076 }
5077 
5078 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5079  * stack boundary and alignment are checked in check_mem_access()
5080  */
5081 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5082 				       /* stack frame we're writing to */
5083 				       struct bpf_func_state *state,
5084 				       int off, int size, int value_regno,
5085 				       int insn_idx)
5086 {
5087 	struct bpf_func_state *cur; /* state of the current function */
5088 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5089 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5090 	struct bpf_reg_state *reg = NULL;
5091 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5092 
5093 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5094 	 * so it's aligned access and [off, off + size) are within stack limits
5095 	 */
5096 	if (!env->allow_ptr_leaks &&
5097 	    is_spilled_reg(&state->stack[spi]) &&
5098 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5099 	    size != BPF_REG_SIZE) {
5100 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5101 		return -EACCES;
5102 	}
5103 
5104 	cur = env->cur_state->frame[env->cur_state->curframe];
5105 	if (value_regno >= 0)
5106 		reg = &cur->regs[value_regno];
5107 	if (!env->bypass_spec_v4) {
5108 		bool sanitize = reg && is_spillable_regtype(reg->type);
5109 
5110 		for (i = 0; i < size; i++) {
5111 			u8 type = state->stack[spi].slot_type[i];
5112 
5113 			if (type != STACK_MISC && type != STACK_ZERO) {
5114 				sanitize = true;
5115 				break;
5116 			}
5117 		}
5118 
5119 		if (sanitize)
5120 			env->insn_aux_data[insn_idx].nospec_result = true;
5121 	}
5122 
5123 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5124 	if (err)
5125 		return err;
5126 
5127 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5128 		/* only mark the slot as written if all 8 bytes were written
5129 		 * otherwise read propagation may incorrectly stop too soon
5130 		 * when stack slots are partially written.
5131 		 * This heuristic means that read propagation will be
5132 		 * conservative, since it will add reg_live_read marks
5133 		 * to stack slots all the way to first state when programs
5134 		 * writes+reads less than 8 bytes
5135 		 */
5136 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5137 	}
5138 
5139 	check_fastcall_stack_contract(env, state, insn_idx, off);
5140 	mark_stack_slot_scratched(env, spi);
5141 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5142 		bool reg_value_fits;
5143 
5144 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5145 		/* Make sure that reg had an ID to build a relation on spill. */
5146 		if (reg_value_fits)
5147 			assign_scalar_id_before_mov(env, reg);
5148 		save_register_state(env, state, spi, reg, size);
5149 		/* Break the relation on a narrowing spill. */
5150 		if (!reg_value_fits)
5151 			state->stack[spi].spilled_ptr.id = 0;
5152 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5153 		   env->bpf_capable) {
5154 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5155 
5156 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5157 		__mark_reg_known(tmp_reg, insn->imm);
5158 		tmp_reg->type = SCALAR_VALUE;
5159 		save_register_state(env, state, spi, tmp_reg, size);
5160 	} else if (reg && is_spillable_regtype(reg->type)) {
5161 		/* register containing pointer is being spilled into stack */
5162 		if (size != BPF_REG_SIZE) {
5163 			verbose_linfo(env, insn_idx, "; ");
5164 			verbose(env, "invalid size of register spill\n");
5165 			return -EACCES;
5166 		}
5167 		if (state != cur && reg->type == PTR_TO_STACK) {
5168 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5169 			return -EINVAL;
5170 		}
5171 		save_register_state(env, state, spi, reg, size);
5172 	} else {
5173 		u8 type = STACK_MISC;
5174 
5175 		/* regular write of data into stack destroys any spilled ptr */
5176 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5177 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5178 		if (is_stack_slot_special(&state->stack[spi]))
5179 			for (i = 0; i < BPF_REG_SIZE; i++)
5180 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5181 
5182 		/* when we zero initialize stack slots mark them as such */
5183 		if ((reg && register_is_null(reg)) ||
5184 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5185 			/* STACK_ZERO case happened because register spill
5186 			 * wasn't properly aligned at the stack slot boundary,
5187 			 * so it's not a register spill anymore; force
5188 			 * originating register to be precise to make
5189 			 * STACK_ZERO correct for subsequent states
5190 			 */
5191 			err = mark_chain_precision(env, value_regno);
5192 			if (err)
5193 				return err;
5194 			type = STACK_ZERO;
5195 		}
5196 
5197 		/* Mark slots affected by this stack write. */
5198 		for (i = 0; i < size; i++)
5199 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5200 		insn_flags = 0; /* not a register spill */
5201 	}
5202 
5203 	if (insn_flags)
5204 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5205 	return 0;
5206 }
5207 
5208 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5209  * known to contain a variable offset.
5210  * This function checks whether the write is permitted and conservatively
5211  * tracks the effects of the write, considering that each stack slot in the
5212  * dynamic range is potentially written to.
5213  *
5214  * 'off' includes 'regno->off'.
5215  * 'value_regno' can be -1, meaning that an unknown value is being written to
5216  * the stack.
5217  *
5218  * Spilled pointers in range are not marked as written because we don't know
5219  * what's going to be actually written. This means that read propagation for
5220  * future reads cannot be terminated by this write.
5221  *
5222  * For privileged programs, uninitialized stack slots are considered
5223  * initialized by this write (even though we don't know exactly what offsets
5224  * are going to be written to). The idea is that we don't want the verifier to
5225  * reject future reads that access slots written to through variable offsets.
5226  */
5227 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5228 				     /* func where register points to */
5229 				     struct bpf_func_state *state,
5230 				     int ptr_regno, int off, int size,
5231 				     int value_regno, int insn_idx)
5232 {
5233 	struct bpf_func_state *cur; /* state of the current function */
5234 	int min_off, max_off;
5235 	int i, err;
5236 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5237 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5238 	bool writing_zero = false;
5239 	/* set if the fact that we're writing a zero is used to let any
5240 	 * stack slots remain STACK_ZERO
5241 	 */
5242 	bool zero_used = false;
5243 
5244 	cur = env->cur_state->frame[env->cur_state->curframe];
5245 	ptr_reg = &cur->regs[ptr_regno];
5246 	min_off = ptr_reg->smin_value + off;
5247 	max_off = ptr_reg->smax_value + off + size;
5248 	if (value_regno >= 0)
5249 		value_reg = &cur->regs[value_regno];
5250 	if ((value_reg && register_is_null(value_reg)) ||
5251 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5252 		writing_zero = true;
5253 
5254 	for (i = min_off; i < max_off; i++) {
5255 		int spi;
5256 
5257 		spi = __get_spi(i);
5258 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5259 		if (err)
5260 			return err;
5261 	}
5262 
5263 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5264 	/* Variable offset writes destroy any spilled pointers in range. */
5265 	for (i = min_off; i < max_off; i++) {
5266 		u8 new_type, *stype;
5267 		int slot, spi;
5268 
5269 		slot = -i - 1;
5270 		spi = slot / BPF_REG_SIZE;
5271 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5272 		mark_stack_slot_scratched(env, spi);
5273 
5274 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5275 			/* Reject the write if range we may write to has not
5276 			 * been initialized beforehand. If we didn't reject
5277 			 * here, the ptr status would be erased below (even
5278 			 * though not all slots are actually overwritten),
5279 			 * possibly opening the door to leaks.
5280 			 *
5281 			 * We do however catch STACK_INVALID case below, and
5282 			 * only allow reading possibly uninitialized memory
5283 			 * later for CAP_PERFMON, as the write may not happen to
5284 			 * that slot.
5285 			 */
5286 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5287 				insn_idx, i);
5288 			return -EINVAL;
5289 		}
5290 
5291 		/* If writing_zero and the spi slot contains a spill of value 0,
5292 		 * maintain the spill type.
5293 		 */
5294 		if (writing_zero && *stype == STACK_SPILL &&
5295 		    is_spilled_scalar_reg(&state->stack[spi])) {
5296 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5297 
5298 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5299 				zero_used = true;
5300 				continue;
5301 			}
5302 		}
5303 
5304 		/* Erase all other spilled pointers. */
5305 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5306 
5307 		/* Update the slot type. */
5308 		new_type = STACK_MISC;
5309 		if (writing_zero && *stype == STACK_ZERO) {
5310 			new_type = STACK_ZERO;
5311 			zero_used = true;
5312 		}
5313 		/* If the slot is STACK_INVALID, we check whether it's OK to
5314 		 * pretend that it will be initialized by this write. The slot
5315 		 * might not actually be written to, and so if we mark it as
5316 		 * initialized future reads might leak uninitialized memory.
5317 		 * For privileged programs, we will accept such reads to slots
5318 		 * that may or may not be written because, if we're reject
5319 		 * them, the error would be too confusing.
5320 		 */
5321 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5322 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5323 					insn_idx, i);
5324 			return -EINVAL;
5325 		}
5326 		*stype = new_type;
5327 	}
5328 	if (zero_used) {
5329 		/* backtracking doesn't work for STACK_ZERO yet. */
5330 		err = mark_chain_precision(env, value_regno);
5331 		if (err)
5332 			return err;
5333 	}
5334 	return 0;
5335 }
5336 
5337 /* When register 'dst_regno' is assigned some values from stack[min_off,
5338  * max_off), we set the register's type according to the types of the
5339  * respective stack slots. If all the stack values are known to be zeros, then
5340  * so is the destination reg. Otherwise, the register is considered to be
5341  * SCALAR. This function does not deal with register filling; the caller must
5342  * ensure that all spilled registers in the stack range have been marked as
5343  * read.
5344  */
5345 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5346 				/* func where src register points to */
5347 				struct bpf_func_state *ptr_state,
5348 				int min_off, int max_off, int dst_regno)
5349 {
5350 	struct bpf_verifier_state *vstate = env->cur_state;
5351 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5352 	int i, slot, spi;
5353 	u8 *stype;
5354 	int zeros = 0;
5355 
5356 	for (i = min_off; i < max_off; i++) {
5357 		slot = -i - 1;
5358 		spi = slot / BPF_REG_SIZE;
5359 		mark_stack_slot_scratched(env, spi);
5360 		stype = ptr_state->stack[spi].slot_type;
5361 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5362 			break;
5363 		zeros++;
5364 	}
5365 	if (zeros == max_off - min_off) {
5366 		/* Any access_size read into register is zero extended,
5367 		 * so the whole register == const_zero.
5368 		 */
5369 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5370 	} else {
5371 		/* have read misc data from the stack */
5372 		mark_reg_unknown(env, state->regs, dst_regno);
5373 	}
5374 }
5375 
5376 /* Read the stack at 'off' and put the results into the register indicated by
5377  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5378  * spilled reg.
5379  *
5380  * 'dst_regno' can be -1, meaning that the read value is not going to a
5381  * register.
5382  *
5383  * The access is assumed to be within the current stack bounds.
5384  */
5385 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5386 				      /* func where src register points to */
5387 				      struct bpf_func_state *reg_state,
5388 				      int off, int size, int dst_regno)
5389 {
5390 	struct bpf_verifier_state *vstate = env->cur_state;
5391 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5392 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5393 	struct bpf_reg_state *reg;
5394 	u8 *stype, type;
5395 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5396 	int err;
5397 
5398 	stype = reg_state->stack[spi].slot_type;
5399 	reg = &reg_state->stack[spi].spilled_ptr;
5400 
5401 	mark_stack_slot_scratched(env, spi);
5402 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5403 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5404 	if (err)
5405 		return err;
5406 
5407 	if (is_spilled_reg(&reg_state->stack[spi])) {
5408 		u8 spill_size = 1;
5409 
5410 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5411 			spill_size++;
5412 
5413 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5414 			if (reg->type != SCALAR_VALUE) {
5415 				verbose_linfo(env, env->insn_idx, "; ");
5416 				verbose(env, "invalid size of register fill\n");
5417 				return -EACCES;
5418 			}
5419 
5420 			if (dst_regno < 0)
5421 				return 0;
5422 
5423 			if (size <= spill_size &&
5424 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5425 				/* The earlier check_reg_arg() has decided the
5426 				 * subreg_def for this insn.  Save it first.
5427 				 */
5428 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5429 
5430 				copy_register_state(&state->regs[dst_regno], reg);
5431 				state->regs[dst_regno].subreg_def = subreg_def;
5432 
5433 				/* Break the relation on a narrowing fill.
5434 				 * coerce_reg_to_size will adjust the boundaries.
5435 				 */
5436 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5437 					state->regs[dst_regno].id = 0;
5438 			} else {
5439 				int spill_cnt = 0, zero_cnt = 0;
5440 
5441 				for (i = 0; i < size; i++) {
5442 					type = stype[(slot - i) % BPF_REG_SIZE];
5443 					if (type == STACK_SPILL) {
5444 						spill_cnt++;
5445 						continue;
5446 					}
5447 					if (type == STACK_MISC)
5448 						continue;
5449 					if (type == STACK_ZERO) {
5450 						zero_cnt++;
5451 						continue;
5452 					}
5453 					if (type == STACK_INVALID && env->allow_uninit_stack)
5454 						continue;
5455 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5456 						off, i, size);
5457 					return -EACCES;
5458 				}
5459 
5460 				if (spill_cnt == size &&
5461 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5462 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5463 					/* this IS register fill, so keep insn_flags */
5464 				} else if (zero_cnt == size) {
5465 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5466 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5467 					insn_flags = 0; /* not restoring original register state */
5468 				} else {
5469 					mark_reg_unknown(env, state->regs, dst_regno);
5470 					insn_flags = 0; /* not restoring original register state */
5471 				}
5472 			}
5473 		} else if (dst_regno >= 0) {
5474 			/* restore register state from stack */
5475 			copy_register_state(&state->regs[dst_regno], reg);
5476 			/* mark reg as written since spilled pointer state likely
5477 			 * has its liveness marks cleared by is_state_visited()
5478 			 * which resets stack/reg liveness for state transitions
5479 			 */
5480 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5481 			/* If dst_regno==-1, the caller is asking us whether
5482 			 * it is acceptable to use this value as a SCALAR_VALUE
5483 			 * (e.g. for XADD).
5484 			 * We must not allow unprivileged callers to do that
5485 			 * with spilled pointers.
5486 			 */
5487 			verbose(env, "leaking pointer from stack off %d\n",
5488 				off);
5489 			return -EACCES;
5490 		}
5491 	} else {
5492 		for (i = 0; i < size; i++) {
5493 			type = stype[(slot - i) % BPF_REG_SIZE];
5494 			if (type == STACK_MISC)
5495 				continue;
5496 			if (type == STACK_ZERO)
5497 				continue;
5498 			if (type == STACK_INVALID && env->allow_uninit_stack)
5499 				continue;
5500 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5501 				off, i, size);
5502 			return -EACCES;
5503 		}
5504 		if (dst_regno >= 0)
5505 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5506 		insn_flags = 0; /* we are not restoring spilled register */
5507 	}
5508 	if (insn_flags)
5509 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5510 	return 0;
5511 }
5512 
5513 enum bpf_access_src {
5514 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5515 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5516 };
5517 
5518 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5519 					 int regno, int off, int access_size,
5520 					 bool zero_size_allowed,
5521 					 enum bpf_access_type type,
5522 					 struct bpf_call_arg_meta *meta);
5523 
5524 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5525 {
5526 	return cur_regs(env) + regno;
5527 }
5528 
5529 /* Read the stack at 'ptr_regno + off' and put the result into the register
5530  * 'dst_regno'.
5531  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5532  * but not its variable offset.
5533  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5534  *
5535  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5536  * filling registers (i.e. reads of spilled register cannot be detected when
5537  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5538  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5539  * offset; for a fixed offset check_stack_read_fixed_off should be used
5540  * instead.
5541  */
5542 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5543 				    int ptr_regno, int off, int size, int dst_regno)
5544 {
5545 	/* The state of the source register. */
5546 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5547 	struct bpf_func_state *ptr_state = func(env, reg);
5548 	int err;
5549 	int min_off, max_off;
5550 
5551 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5552 	 */
5553 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5554 					    false, BPF_READ, NULL);
5555 	if (err)
5556 		return err;
5557 
5558 	min_off = reg->smin_value + off;
5559 	max_off = reg->smax_value + off;
5560 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5561 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5562 	return 0;
5563 }
5564 
5565 /* check_stack_read dispatches to check_stack_read_fixed_off or
5566  * check_stack_read_var_off.
5567  *
5568  * The caller must ensure that the offset falls within the allocated stack
5569  * bounds.
5570  *
5571  * 'dst_regno' is a register which will receive the value from the stack. It
5572  * can be -1, meaning that the read value is not going to a register.
5573  */
5574 static int check_stack_read(struct bpf_verifier_env *env,
5575 			    int ptr_regno, int off, int size,
5576 			    int dst_regno)
5577 {
5578 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5579 	struct bpf_func_state *state = func(env, reg);
5580 	int err;
5581 	/* Some accesses are only permitted with a static offset. */
5582 	bool var_off = !tnum_is_const(reg->var_off);
5583 
5584 	/* The offset is required to be static when reads don't go to a
5585 	 * register, in order to not leak pointers (see
5586 	 * check_stack_read_fixed_off).
5587 	 */
5588 	if (dst_regno < 0 && var_off) {
5589 		char tn_buf[48];
5590 
5591 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5592 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5593 			tn_buf, off, size);
5594 		return -EACCES;
5595 	}
5596 	/* Variable offset is prohibited for unprivileged mode for simplicity
5597 	 * since it requires corresponding support in Spectre masking for stack
5598 	 * ALU. See also retrieve_ptr_limit(). The check in
5599 	 * check_stack_access_for_ptr_arithmetic() called by
5600 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5601 	 * with variable offsets, therefore no check is required here. Further,
5602 	 * just checking it here would be insufficient as speculative stack
5603 	 * writes could still lead to unsafe speculative behaviour.
5604 	 */
5605 	if (!var_off) {
5606 		off += reg->var_off.value;
5607 		err = check_stack_read_fixed_off(env, state, off, size,
5608 						 dst_regno);
5609 	} else {
5610 		/* Variable offset stack reads need more conservative handling
5611 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5612 		 * branch.
5613 		 */
5614 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5615 					       dst_regno);
5616 	}
5617 	return err;
5618 }
5619 
5620 
5621 /* check_stack_write dispatches to check_stack_write_fixed_off or
5622  * check_stack_write_var_off.
5623  *
5624  * 'ptr_regno' is the register used as a pointer into the stack.
5625  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5626  * 'value_regno' is the register whose value we're writing to the stack. It can
5627  * be -1, meaning that we're not writing from a register.
5628  *
5629  * The caller must ensure that the offset falls within the maximum stack size.
5630  */
5631 static int check_stack_write(struct bpf_verifier_env *env,
5632 			     int ptr_regno, int off, int size,
5633 			     int value_regno, int insn_idx)
5634 {
5635 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5636 	struct bpf_func_state *state = func(env, reg);
5637 	int err;
5638 
5639 	if (tnum_is_const(reg->var_off)) {
5640 		off += reg->var_off.value;
5641 		err = check_stack_write_fixed_off(env, state, off, size,
5642 						  value_regno, insn_idx);
5643 	} else {
5644 		/* Variable offset stack reads need more conservative handling
5645 		 * than fixed offset ones.
5646 		 */
5647 		err = check_stack_write_var_off(env, state,
5648 						ptr_regno, off, size,
5649 						value_regno, insn_idx);
5650 	}
5651 	return err;
5652 }
5653 
5654 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5655 				 int off, int size, enum bpf_access_type type)
5656 {
5657 	struct bpf_reg_state *reg = reg_state(env, regno);
5658 	struct bpf_map *map = reg->map_ptr;
5659 	u32 cap = bpf_map_flags_to_cap(map);
5660 
5661 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5662 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5663 			map->value_size, off, size);
5664 		return -EACCES;
5665 	}
5666 
5667 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5668 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5669 			map->value_size, off, size);
5670 		return -EACCES;
5671 	}
5672 
5673 	return 0;
5674 }
5675 
5676 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5677 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5678 			      int off, int size, u32 mem_size,
5679 			      bool zero_size_allowed)
5680 {
5681 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5682 	struct bpf_reg_state *reg;
5683 
5684 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5685 		return 0;
5686 
5687 	reg = &cur_regs(env)[regno];
5688 	switch (reg->type) {
5689 	case PTR_TO_MAP_KEY:
5690 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5691 			mem_size, off, size);
5692 		break;
5693 	case PTR_TO_MAP_VALUE:
5694 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5695 			mem_size, off, size);
5696 		break;
5697 	case PTR_TO_PACKET:
5698 	case PTR_TO_PACKET_META:
5699 	case PTR_TO_PACKET_END:
5700 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5701 			off, size, regno, reg->id, off, mem_size);
5702 		break;
5703 	case PTR_TO_MEM:
5704 	default:
5705 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5706 			mem_size, off, size);
5707 	}
5708 
5709 	return -EACCES;
5710 }
5711 
5712 /* check read/write into a memory region with possible variable offset */
5713 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5714 				   int off, int size, u32 mem_size,
5715 				   bool zero_size_allowed)
5716 {
5717 	struct bpf_verifier_state *vstate = env->cur_state;
5718 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5719 	struct bpf_reg_state *reg = &state->regs[regno];
5720 	int err;
5721 
5722 	/* We may have adjusted the register pointing to memory region, so we
5723 	 * need to try adding each of min_value and max_value to off
5724 	 * to make sure our theoretical access will be safe.
5725 	 *
5726 	 * The minimum value is only important with signed
5727 	 * comparisons where we can't assume the floor of a
5728 	 * value is 0.  If we are using signed variables for our
5729 	 * index'es we need to make sure that whatever we use
5730 	 * will have a set floor within our range.
5731 	 */
5732 	if (reg->smin_value < 0 &&
5733 	    (reg->smin_value == S64_MIN ||
5734 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5735 	      reg->smin_value + off < 0)) {
5736 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5737 			regno);
5738 		return -EACCES;
5739 	}
5740 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5741 				 mem_size, zero_size_allowed);
5742 	if (err) {
5743 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5744 			regno);
5745 		return err;
5746 	}
5747 
5748 	/* If we haven't set a max value then we need to bail since we can't be
5749 	 * sure we won't do bad things.
5750 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5751 	 */
5752 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5753 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5754 			regno);
5755 		return -EACCES;
5756 	}
5757 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5758 				 mem_size, zero_size_allowed);
5759 	if (err) {
5760 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5761 			regno);
5762 		return err;
5763 	}
5764 
5765 	return 0;
5766 }
5767 
5768 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5769 			       const struct bpf_reg_state *reg, int regno,
5770 			       bool fixed_off_ok)
5771 {
5772 	/* Access to this pointer-typed register or passing it to a helper
5773 	 * is only allowed in its original, unmodified form.
5774 	 */
5775 
5776 	if (reg->off < 0) {
5777 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5778 			reg_type_str(env, reg->type), regno, reg->off);
5779 		return -EACCES;
5780 	}
5781 
5782 	if (!fixed_off_ok && reg->off) {
5783 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5784 			reg_type_str(env, reg->type), regno, reg->off);
5785 		return -EACCES;
5786 	}
5787 
5788 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5789 		char tn_buf[48];
5790 
5791 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5792 		verbose(env, "variable %s access var_off=%s disallowed\n",
5793 			reg_type_str(env, reg->type), tn_buf);
5794 		return -EACCES;
5795 	}
5796 
5797 	return 0;
5798 }
5799 
5800 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5801 		             const struct bpf_reg_state *reg, int regno)
5802 {
5803 	return __check_ptr_off_reg(env, reg, regno, false);
5804 }
5805 
5806 static int map_kptr_match_type(struct bpf_verifier_env *env,
5807 			       struct btf_field *kptr_field,
5808 			       struct bpf_reg_state *reg, u32 regno)
5809 {
5810 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5811 	int perm_flags;
5812 	const char *reg_name = "";
5813 
5814 	if (btf_is_kernel(reg->btf)) {
5815 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5816 
5817 		/* Only unreferenced case accepts untrusted pointers */
5818 		if (kptr_field->type == BPF_KPTR_UNREF)
5819 			perm_flags |= PTR_UNTRUSTED;
5820 	} else {
5821 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5822 		if (kptr_field->type == BPF_KPTR_PERCPU)
5823 			perm_flags |= MEM_PERCPU;
5824 	}
5825 
5826 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5827 		goto bad_type;
5828 
5829 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5830 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5831 
5832 	/* For ref_ptr case, release function check should ensure we get one
5833 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5834 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5835 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5836 	 * reg->off and reg->ref_obj_id are not needed here.
5837 	 */
5838 	if (__check_ptr_off_reg(env, reg, regno, true))
5839 		return -EACCES;
5840 
5841 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5842 	 * we also need to take into account the reg->off.
5843 	 *
5844 	 * We want to support cases like:
5845 	 *
5846 	 * struct foo {
5847 	 *         struct bar br;
5848 	 *         struct baz bz;
5849 	 * };
5850 	 *
5851 	 * struct foo *v;
5852 	 * v = func();	      // PTR_TO_BTF_ID
5853 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5854 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5855 	 *                    // first member type of struct after comparison fails
5856 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5857 	 *                    // to match type
5858 	 *
5859 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5860 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5861 	 * the struct to match type against first member of struct, i.e. reject
5862 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5863 	 * strict mode to true for type match.
5864 	 */
5865 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5866 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5867 				  kptr_field->type != BPF_KPTR_UNREF))
5868 		goto bad_type;
5869 	return 0;
5870 bad_type:
5871 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5872 		reg_type_str(env, reg->type), reg_name);
5873 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5874 	if (kptr_field->type == BPF_KPTR_UNREF)
5875 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5876 			targ_name);
5877 	else
5878 		verbose(env, "\n");
5879 	return -EINVAL;
5880 }
5881 
5882 static bool in_sleepable(struct bpf_verifier_env *env)
5883 {
5884 	return env->cur_state->in_sleepable;
5885 }
5886 
5887 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5888  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5889  */
5890 static bool in_rcu_cs(struct bpf_verifier_env *env)
5891 {
5892 	return env->cur_state->active_rcu_locks ||
5893 	       env->cur_state->active_locks ||
5894 	       !in_sleepable(env);
5895 }
5896 
5897 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5898 BTF_SET_START(rcu_protected_types)
5899 #ifdef CONFIG_NET
5900 BTF_ID(struct, prog_test_ref_kfunc)
5901 #endif
5902 #ifdef CONFIG_CGROUPS
5903 BTF_ID(struct, cgroup)
5904 #endif
5905 #ifdef CONFIG_BPF_JIT
5906 BTF_ID(struct, bpf_cpumask)
5907 #endif
5908 BTF_ID(struct, task_struct)
5909 #ifdef CONFIG_CRYPTO
5910 BTF_ID(struct, bpf_crypto_ctx)
5911 #endif
5912 BTF_SET_END(rcu_protected_types)
5913 
5914 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5915 {
5916 	if (!btf_is_kernel(btf))
5917 		return true;
5918 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5919 }
5920 
5921 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5922 {
5923 	struct btf_struct_meta *meta;
5924 
5925 	if (btf_is_kernel(kptr_field->kptr.btf))
5926 		return NULL;
5927 
5928 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5929 				    kptr_field->kptr.btf_id);
5930 
5931 	return meta ? meta->record : NULL;
5932 }
5933 
5934 static bool rcu_safe_kptr(const struct btf_field *field)
5935 {
5936 	const struct btf_field_kptr *kptr = &field->kptr;
5937 
5938 	return field->type == BPF_KPTR_PERCPU ||
5939 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5940 }
5941 
5942 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5943 {
5944 	struct btf_record *rec;
5945 	u32 ret;
5946 
5947 	ret = PTR_MAYBE_NULL;
5948 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5949 		ret |= MEM_RCU;
5950 		if (kptr_field->type == BPF_KPTR_PERCPU)
5951 			ret |= MEM_PERCPU;
5952 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5953 			ret |= MEM_ALLOC;
5954 
5955 		rec = kptr_pointee_btf_record(kptr_field);
5956 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5957 			ret |= NON_OWN_REF;
5958 	} else {
5959 		ret |= PTR_UNTRUSTED;
5960 	}
5961 
5962 	return ret;
5963 }
5964 
5965 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5966 			    struct btf_field *field)
5967 {
5968 	struct bpf_reg_state *reg;
5969 	const struct btf_type *t;
5970 
5971 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5972 	mark_reg_known_zero(env, cur_regs(env), regno);
5973 	reg = reg_state(env, regno);
5974 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5975 	reg->mem_size = t->size;
5976 	reg->id = ++env->id_gen;
5977 
5978 	return 0;
5979 }
5980 
5981 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5982 				 int value_regno, int insn_idx,
5983 				 struct btf_field *kptr_field)
5984 {
5985 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5986 	int class = BPF_CLASS(insn->code);
5987 	struct bpf_reg_state *val_reg;
5988 	int ret;
5989 
5990 	/* Things we already checked for in check_map_access and caller:
5991 	 *  - Reject cases where variable offset may touch kptr
5992 	 *  - size of access (must be BPF_DW)
5993 	 *  - tnum_is_const(reg->var_off)
5994 	 *  - kptr_field->offset == off + reg->var_off.value
5995 	 */
5996 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5997 	if (BPF_MODE(insn->code) != BPF_MEM) {
5998 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5999 		return -EACCES;
6000 	}
6001 
6002 	/* We only allow loading referenced kptr, since it will be marked as
6003 	 * untrusted, similar to unreferenced kptr.
6004 	 */
6005 	if (class != BPF_LDX &&
6006 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6007 		verbose(env, "store to referenced kptr disallowed\n");
6008 		return -EACCES;
6009 	}
6010 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6011 		verbose(env, "store to uptr disallowed\n");
6012 		return -EACCES;
6013 	}
6014 
6015 	if (class == BPF_LDX) {
6016 		if (kptr_field->type == BPF_UPTR)
6017 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
6018 
6019 		/* We can simply mark the value_regno receiving the pointer
6020 		 * value from map as PTR_TO_BTF_ID, with the correct type.
6021 		 */
6022 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6023 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6024 				      btf_ld_kptr_type(env, kptr_field));
6025 		if (ret < 0)
6026 			return ret;
6027 	} else if (class == BPF_STX) {
6028 		val_reg = reg_state(env, value_regno);
6029 		if (!register_is_null(val_reg) &&
6030 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6031 			return -EACCES;
6032 	} else if (class == BPF_ST) {
6033 		if (insn->imm) {
6034 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6035 				kptr_field->offset);
6036 			return -EACCES;
6037 		}
6038 	} else {
6039 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6040 		return -EACCES;
6041 	}
6042 	return 0;
6043 }
6044 
6045 /*
6046  * Return the size of the memory region accessible from a pointer to map value.
6047  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
6048  */
6049 static u32 map_mem_size(const struct bpf_map *map)
6050 {
6051 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6052 		return map->max_entries * sizeof(long);
6053 
6054 	return map->value_size;
6055 }
6056 
6057 /* check read/write into a map element with possible variable offset */
6058 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6059 			    int off, int size, bool zero_size_allowed,
6060 			    enum bpf_access_src src)
6061 {
6062 	struct bpf_verifier_state *vstate = env->cur_state;
6063 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6064 	struct bpf_reg_state *reg = &state->regs[regno];
6065 	struct bpf_map *map = reg->map_ptr;
6066 	u32 mem_size = map_mem_size(map);
6067 	struct btf_record *rec;
6068 	int err, i;
6069 
6070 	err = check_mem_region_access(env, regno, off, size, mem_size, zero_size_allowed);
6071 	if (err)
6072 		return err;
6073 
6074 	if (IS_ERR_OR_NULL(map->record))
6075 		return 0;
6076 	rec = map->record;
6077 	for (i = 0; i < rec->cnt; i++) {
6078 		struct btf_field *field = &rec->fields[i];
6079 		u32 p = field->offset;
6080 
6081 		/* If any part of a field  can be touched by load/store, reject
6082 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6083 		 * it is sufficient to check x1 < y2 && y1 < x2.
6084 		 */
6085 		if (reg->smin_value + off < p + field->size &&
6086 		    p < reg->umax_value + off + size) {
6087 			switch (field->type) {
6088 			case BPF_KPTR_UNREF:
6089 			case BPF_KPTR_REF:
6090 			case BPF_KPTR_PERCPU:
6091 			case BPF_UPTR:
6092 				if (src != ACCESS_DIRECT) {
6093 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6094 						btf_field_type_name(field->type));
6095 					return -EACCES;
6096 				}
6097 				if (!tnum_is_const(reg->var_off)) {
6098 					verbose(env, "%s access cannot have variable offset\n",
6099 						btf_field_type_name(field->type));
6100 					return -EACCES;
6101 				}
6102 				if (p != off + reg->var_off.value) {
6103 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6104 						btf_field_type_name(field->type),
6105 						p, off + reg->var_off.value);
6106 					return -EACCES;
6107 				}
6108 				if (size != bpf_size_to_bytes(BPF_DW)) {
6109 					verbose(env, "%s access size must be BPF_DW\n",
6110 						btf_field_type_name(field->type));
6111 					return -EACCES;
6112 				}
6113 				break;
6114 			default:
6115 				verbose(env, "%s cannot be accessed directly by load/store\n",
6116 					btf_field_type_name(field->type));
6117 				return -EACCES;
6118 			}
6119 		}
6120 	}
6121 	return 0;
6122 }
6123 
6124 #define MAX_PACKET_OFF 0xffff
6125 
6126 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6127 				       const struct bpf_call_arg_meta *meta,
6128 				       enum bpf_access_type t)
6129 {
6130 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6131 
6132 	switch (prog_type) {
6133 	/* Program types only with direct read access go here! */
6134 	case BPF_PROG_TYPE_LWT_IN:
6135 	case BPF_PROG_TYPE_LWT_OUT:
6136 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6137 	case BPF_PROG_TYPE_SK_REUSEPORT:
6138 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6139 	case BPF_PROG_TYPE_CGROUP_SKB:
6140 		if (t == BPF_WRITE)
6141 			return false;
6142 		fallthrough;
6143 
6144 	/* Program types with direct read + write access go here! */
6145 	case BPF_PROG_TYPE_SCHED_CLS:
6146 	case BPF_PROG_TYPE_SCHED_ACT:
6147 	case BPF_PROG_TYPE_XDP:
6148 	case BPF_PROG_TYPE_LWT_XMIT:
6149 	case BPF_PROG_TYPE_SK_SKB:
6150 	case BPF_PROG_TYPE_SK_MSG:
6151 		if (meta)
6152 			return meta->pkt_access;
6153 
6154 		env->seen_direct_write = true;
6155 		return true;
6156 
6157 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6158 		if (t == BPF_WRITE)
6159 			env->seen_direct_write = true;
6160 
6161 		return true;
6162 
6163 	default:
6164 		return false;
6165 	}
6166 }
6167 
6168 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6169 			       int size, bool zero_size_allowed)
6170 {
6171 	struct bpf_reg_state *reg = reg_state(env, regno);
6172 	int err;
6173 
6174 	/* We may have added a variable offset to the packet pointer; but any
6175 	 * reg->range we have comes after that.  We are only checking the fixed
6176 	 * offset.
6177 	 */
6178 
6179 	/* We don't allow negative numbers, because we aren't tracking enough
6180 	 * detail to prove they're safe.
6181 	 */
6182 	if (reg->smin_value < 0) {
6183 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6184 			regno);
6185 		return -EACCES;
6186 	}
6187 
6188 	err = reg->range < 0 ? -EINVAL :
6189 	      __check_mem_access(env, regno, off, size, reg->range,
6190 				 zero_size_allowed);
6191 	if (err) {
6192 		verbose(env, "R%d offset is outside of the packet\n", regno);
6193 		return err;
6194 	}
6195 
6196 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6197 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6198 	 * otherwise find_good_pkt_pointers would have refused to set range info
6199 	 * that __check_mem_access would have rejected this pkt access.
6200 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6201 	 */
6202 	env->prog->aux->max_pkt_offset =
6203 		max_t(u32, env->prog->aux->max_pkt_offset,
6204 		      off + reg->umax_value + size - 1);
6205 
6206 	return err;
6207 }
6208 
6209 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
6210 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6211 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6212 {
6213 	if (env->ops->is_valid_access &&
6214 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6215 		/* A non zero info.ctx_field_size indicates that this field is a
6216 		 * candidate for later verifier transformation to load the whole
6217 		 * field and then apply a mask when accessed with a narrower
6218 		 * access than actual ctx access size. A zero info.ctx_field_size
6219 		 * will only allow for whole field access and rejects any other
6220 		 * type of narrower access.
6221 		 */
6222 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6223 			if (info->ref_obj_id &&
6224 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6225 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6226 					off);
6227 				return -EACCES;
6228 			}
6229 		} else {
6230 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6231 		}
6232 		/* remember the offset of last byte accessed in ctx */
6233 		if (env->prog->aux->max_ctx_offset < off + size)
6234 			env->prog->aux->max_ctx_offset = off + size;
6235 		return 0;
6236 	}
6237 
6238 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6239 	return -EACCES;
6240 }
6241 
6242 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6243 				  int size)
6244 {
6245 	if (size < 0 || off < 0 ||
6246 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6247 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6248 			off, size);
6249 		return -EACCES;
6250 	}
6251 	return 0;
6252 }
6253 
6254 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6255 			     u32 regno, int off, int size,
6256 			     enum bpf_access_type t)
6257 {
6258 	struct bpf_reg_state *reg = reg_state(env, regno);
6259 	struct bpf_insn_access_aux info = {};
6260 	bool valid;
6261 
6262 	if (reg->smin_value < 0) {
6263 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6264 			regno);
6265 		return -EACCES;
6266 	}
6267 
6268 	switch (reg->type) {
6269 	case PTR_TO_SOCK_COMMON:
6270 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6271 		break;
6272 	case PTR_TO_SOCKET:
6273 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6274 		break;
6275 	case PTR_TO_TCP_SOCK:
6276 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6277 		break;
6278 	case PTR_TO_XDP_SOCK:
6279 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6280 		break;
6281 	default:
6282 		valid = false;
6283 	}
6284 
6285 
6286 	if (valid) {
6287 		env->insn_aux_data[insn_idx].ctx_field_size =
6288 			info.ctx_field_size;
6289 		return 0;
6290 	}
6291 
6292 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6293 		regno, reg_type_str(env, reg->type), off, size);
6294 
6295 	return -EACCES;
6296 }
6297 
6298 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6299 {
6300 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6301 }
6302 
6303 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6304 {
6305 	const struct bpf_reg_state *reg = reg_state(env, regno);
6306 
6307 	return reg->type == PTR_TO_CTX;
6308 }
6309 
6310 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6311 {
6312 	const struct bpf_reg_state *reg = reg_state(env, regno);
6313 
6314 	return type_is_sk_pointer(reg->type);
6315 }
6316 
6317 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6318 {
6319 	const struct bpf_reg_state *reg = reg_state(env, regno);
6320 
6321 	return type_is_pkt_pointer(reg->type);
6322 }
6323 
6324 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6325 {
6326 	const struct bpf_reg_state *reg = reg_state(env, regno);
6327 
6328 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6329 	return reg->type == PTR_TO_FLOW_KEYS;
6330 }
6331 
6332 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6333 {
6334 	const struct bpf_reg_state *reg = reg_state(env, regno);
6335 
6336 	return reg->type == PTR_TO_ARENA;
6337 }
6338 
6339 /* Return false if @regno contains a pointer whose type isn't supported for
6340  * atomic instruction @insn.
6341  */
6342 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6343 			       struct bpf_insn *insn)
6344 {
6345 	if (is_ctx_reg(env, regno))
6346 		return false;
6347 	if (is_pkt_reg(env, regno))
6348 		return false;
6349 	if (is_flow_key_reg(env, regno))
6350 		return false;
6351 	if (is_sk_reg(env, regno))
6352 		return false;
6353 	if (is_arena_reg(env, regno))
6354 		return bpf_jit_supports_insn(insn, true);
6355 
6356 	return true;
6357 }
6358 
6359 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6360 #ifdef CONFIG_NET
6361 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6362 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6363 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6364 #endif
6365 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6366 };
6367 
6368 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6369 {
6370 	/* A referenced register is always trusted. */
6371 	if (reg->ref_obj_id)
6372 		return true;
6373 
6374 	/* Types listed in the reg2btf_ids are always trusted */
6375 	if (reg2btf_ids[base_type(reg->type)] &&
6376 	    !bpf_type_has_unsafe_modifiers(reg->type))
6377 		return true;
6378 
6379 	/* If a register is not referenced, it is trusted if it has the
6380 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6381 	 * other type modifiers may be safe, but we elect to take an opt-in
6382 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6383 	 * not.
6384 	 *
6385 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6386 	 * for whether a register is trusted.
6387 	 */
6388 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6389 	       !bpf_type_has_unsafe_modifiers(reg->type);
6390 }
6391 
6392 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6393 {
6394 	return reg->type & MEM_RCU;
6395 }
6396 
6397 static void clear_trusted_flags(enum bpf_type_flag *flag)
6398 {
6399 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6400 }
6401 
6402 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6403 				   const struct bpf_reg_state *reg,
6404 				   int off, int size, bool strict)
6405 {
6406 	struct tnum reg_off;
6407 	int ip_align;
6408 
6409 	/* Byte size accesses are always allowed. */
6410 	if (!strict || size == 1)
6411 		return 0;
6412 
6413 	/* For platforms that do not have a Kconfig enabling
6414 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6415 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6416 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6417 	 * to this code only in strict mode where we want to emulate
6418 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6419 	 * unconditional IP align value of '2'.
6420 	 */
6421 	ip_align = 2;
6422 
6423 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6424 	if (!tnum_is_aligned(reg_off, size)) {
6425 		char tn_buf[48];
6426 
6427 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6428 		verbose(env,
6429 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6430 			ip_align, tn_buf, reg->off, off, size);
6431 		return -EACCES;
6432 	}
6433 
6434 	return 0;
6435 }
6436 
6437 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6438 				       const struct bpf_reg_state *reg,
6439 				       const char *pointer_desc,
6440 				       int off, int size, bool strict)
6441 {
6442 	struct tnum reg_off;
6443 
6444 	/* Byte size accesses are always allowed. */
6445 	if (!strict || size == 1)
6446 		return 0;
6447 
6448 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6449 	if (!tnum_is_aligned(reg_off, size)) {
6450 		char tn_buf[48];
6451 
6452 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6453 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6454 			pointer_desc, tn_buf, reg->off, off, size);
6455 		return -EACCES;
6456 	}
6457 
6458 	return 0;
6459 }
6460 
6461 static int check_ptr_alignment(struct bpf_verifier_env *env,
6462 			       const struct bpf_reg_state *reg, int off,
6463 			       int size, bool strict_alignment_once)
6464 {
6465 	bool strict = env->strict_alignment || strict_alignment_once;
6466 	const char *pointer_desc = "";
6467 
6468 	switch (reg->type) {
6469 	case PTR_TO_PACKET:
6470 	case PTR_TO_PACKET_META:
6471 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6472 		 * right in front, treat it the very same way.
6473 		 */
6474 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6475 	case PTR_TO_FLOW_KEYS:
6476 		pointer_desc = "flow keys ";
6477 		break;
6478 	case PTR_TO_MAP_KEY:
6479 		pointer_desc = "key ";
6480 		break;
6481 	case PTR_TO_MAP_VALUE:
6482 		pointer_desc = "value ";
6483 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6484 			strict = true;
6485 		break;
6486 	case PTR_TO_CTX:
6487 		pointer_desc = "context ";
6488 		break;
6489 	case PTR_TO_STACK:
6490 		pointer_desc = "stack ";
6491 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6492 		 * and check_stack_read_fixed_off() relies on stack accesses being
6493 		 * aligned.
6494 		 */
6495 		strict = true;
6496 		break;
6497 	case PTR_TO_SOCKET:
6498 		pointer_desc = "sock ";
6499 		break;
6500 	case PTR_TO_SOCK_COMMON:
6501 		pointer_desc = "sock_common ";
6502 		break;
6503 	case PTR_TO_TCP_SOCK:
6504 		pointer_desc = "tcp_sock ";
6505 		break;
6506 	case PTR_TO_XDP_SOCK:
6507 		pointer_desc = "xdp_sock ";
6508 		break;
6509 	case PTR_TO_ARENA:
6510 		return 0;
6511 	default:
6512 		break;
6513 	}
6514 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6515 					   strict);
6516 }
6517 
6518 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6519 {
6520 	if (!bpf_jit_supports_private_stack())
6521 		return NO_PRIV_STACK;
6522 
6523 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6524 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6525 	 * explicitly.
6526 	 */
6527 	switch (prog->type) {
6528 	case BPF_PROG_TYPE_KPROBE:
6529 	case BPF_PROG_TYPE_TRACEPOINT:
6530 	case BPF_PROG_TYPE_PERF_EVENT:
6531 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6532 		return PRIV_STACK_ADAPTIVE;
6533 	case BPF_PROG_TYPE_TRACING:
6534 	case BPF_PROG_TYPE_LSM:
6535 	case BPF_PROG_TYPE_STRUCT_OPS:
6536 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6537 			return PRIV_STACK_ADAPTIVE;
6538 		fallthrough;
6539 	default:
6540 		break;
6541 	}
6542 
6543 	return NO_PRIV_STACK;
6544 }
6545 
6546 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6547 {
6548 	if (env->prog->jit_requested)
6549 		return round_up(stack_depth, 16);
6550 
6551 	/* round up to 32-bytes, since this is granularity
6552 	 * of interpreter stack size
6553 	 */
6554 	return round_up(max_t(u32, stack_depth, 1), 32);
6555 }
6556 
6557 /* starting from main bpf function walk all instructions of the function
6558  * and recursively walk all callees that given function can call.
6559  * Ignore jump and exit insns.
6560  * Since recursion is prevented by check_cfg() this algorithm
6561  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6562  */
6563 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6564 					 bool priv_stack_supported)
6565 {
6566 	struct bpf_subprog_info *subprog = env->subprog_info;
6567 	struct bpf_insn *insn = env->prog->insnsi;
6568 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6569 	bool tail_call_reachable = false;
6570 	int ret_insn[MAX_CALL_FRAMES];
6571 	int ret_prog[MAX_CALL_FRAMES];
6572 	int j;
6573 
6574 	i = subprog[idx].start;
6575 	if (!priv_stack_supported)
6576 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6577 process_func:
6578 	/* protect against potential stack overflow that might happen when
6579 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6580 	 * depth for such case down to 256 so that the worst case scenario
6581 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6582 	 * 8k).
6583 	 *
6584 	 * To get the idea what might happen, see an example:
6585 	 * func1 -> sub rsp, 128
6586 	 *  subfunc1 -> sub rsp, 256
6587 	 *  tailcall1 -> add rsp, 256
6588 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6589 	 *   subfunc2 -> sub rsp, 64
6590 	 *   subfunc22 -> sub rsp, 128
6591 	 *   tailcall2 -> add rsp, 128
6592 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6593 	 *
6594 	 * tailcall will unwind the current stack frame but it will not get rid
6595 	 * of caller's stack as shown on the example above.
6596 	 */
6597 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6598 		verbose(env,
6599 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6600 			depth);
6601 		return -EACCES;
6602 	}
6603 
6604 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6605 	if (priv_stack_supported) {
6606 		/* Request private stack support only if the subprog stack
6607 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6608 		 * avoid jit penalty if the stack usage is small.
6609 		 */
6610 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6611 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6612 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6613 	}
6614 
6615 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6616 		if (subprog_depth > MAX_BPF_STACK) {
6617 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6618 				idx, subprog_depth);
6619 			return -EACCES;
6620 		}
6621 	} else {
6622 		depth += subprog_depth;
6623 		if (depth > MAX_BPF_STACK) {
6624 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6625 				frame + 1, depth);
6626 			return -EACCES;
6627 		}
6628 	}
6629 continue_func:
6630 	subprog_end = subprog[idx + 1].start;
6631 	for (; i < subprog_end; i++) {
6632 		int next_insn, sidx;
6633 
6634 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6635 			bool err = false;
6636 
6637 			if (!is_bpf_throw_kfunc(insn + i))
6638 				continue;
6639 			if (subprog[idx].is_cb)
6640 				err = true;
6641 			for (int c = 0; c < frame && !err; c++) {
6642 				if (subprog[ret_prog[c]].is_cb) {
6643 					err = true;
6644 					break;
6645 				}
6646 			}
6647 			if (!err)
6648 				continue;
6649 			verbose(env,
6650 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6651 				i, idx);
6652 			return -EINVAL;
6653 		}
6654 
6655 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6656 			continue;
6657 		/* remember insn and function to return to */
6658 		ret_insn[frame] = i + 1;
6659 		ret_prog[frame] = idx;
6660 
6661 		/* find the callee */
6662 		next_insn = i + insn[i].imm + 1;
6663 		sidx = find_subprog(env, next_insn);
6664 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6665 			return -EFAULT;
6666 		if (subprog[sidx].is_async_cb) {
6667 			if (subprog[sidx].has_tail_call) {
6668 				verifier_bug(env, "subprog has tail_call and async cb");
6669 				return -EFAULT;
6670 			}
6671 			/* async callbacks don't increase bpf prog stack size unless called directly */
6672 			if (!bpf_pseudo_call(insn + i))
6673 				continue;
6674 			if (subprog[sidx].is_exception_cb) {
6675 				verbose(env, "insn %d cannot call exception cb directly", i);
6676 				return -EINVAL;
6677 			}
6678 		}
6679 		i = next_insn;
6680 		idx = sidx;
6681 		if (!priv_stack_supported)
6682 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6683 
6684 		if (subprog[idx].has_tail_call)
6685 			tail_call_reachable = true;
6686 
6687 		frame++;
6688 		if (frame >= MAX_CALL_FRAMES) {
6689 			verbose(env, "the call stack of %d frames is too deep !\n",
6690 				frame);
6691 			return -E2BIG;
6692 		}
6693 		goto process_func;
6694 	}
6695 	/* if tail call got detected across bpf2bpf calls then mark each of the
6696 	 * currently present subprog frames as tail call reachable subprogs;
6697 	 * this info will be utilized by JIT so that we will be preserving the
6698 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6699 	 */
6700 	if (tail_call_reachable)
6701 		for (j = 0; j < frame; j++) {
6702 			if (subprog[ret_prog[j]].is_exception_cb) {
6703 				verbose(env, "cannot tail call within exception cb\n");
6704 				return -EINVAL;
6705 			}
6706 			subprog[ret_prog[j]].tail_call_reachable = true;
6707 		}
6708 	if (subprog[0].tail_call_reachable)
6709 		env->prog->aux->tail_call_reachable = true;
6710 
6711 	/* end of for() loop means the last insn of the 'subprog'
6712 	 * was reached. Doesn't matter whether it was JA or EXIT
6713 	 */
6714 	if (frame == 0)
6715 		return 0;
6716 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6717 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6718 	frame--;
6719 	i = ret_insn[frame];
6720 	idx = ret_prog[frame];
6721 	goto continue_func;
6722 }
6723 
6724 static int check_max_stack_depth(struct bpf_verifier_env *env)
6725 {
6726 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6727 	struct bpf_subprog_info *si = env->subprog_info;
6728 	bool priv_stack_supported;
6729 	int ret;
6730 
6731 	for (int i = 0; i < env->subprog_cnt; i++) {
6732 		if (si[i].has_tail_call) {
6733 			priv_stack_mode = NO_PRIV_STACK;
6734 			break;
6735 		}
6736 	}
6737 
6738 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6739 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6740 
6741 	/* All async_cb subprogs use normal kernel stack. If a particular
6742 	 * subprog appears in both main prog and async_cb subtree, that
6743 	 * subprog will use normal kernel stack to avoid potential nesting.
6744 	 * The reverse subprog traversal ensures when main prog subtree is
6745 	 * checked, the subprogs appearing in async_cb subtrees are already
6746 	 * marked as using normal kernel stack, so stack size checking can
6747 	 * be done properly.
6748 	 */
6749 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6750 		if (!i || si[i].is_async_cb) {
6751 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6752 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6753 			if (ret < 0)
6754 				return ret;
6755 		}
6756 	}
6757 
6758 	for (int i = 0; i < env->subprog_cnt; i++) {
6759 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6760 			env->prog->aux->jits_use_priv_stack = true;
6761 			break;
6762 		}
6763 	}
6764 
6765 	return 0;
6766 }
6767 
6768 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6769 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6770 				  const struct bpf_insn *insn, int idx)
6771 {
6772 	int start = idx + insn->imm + 1, subprog;
6773 
6774 	subprog = find_subprog(env, start);
6775 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6776 		return -EFAULT;
6777 	return env->subprog_info[subprog].stack_depth;
6778 }
6779 #endif
6780 
6781 static int __check_buffer_access(struct bpf_verifier_env *env,
6782 				 const char *buf_info,
6783 				 const struct bpf_reg_state *reg,
6784 				 int regno, int off, int size)
6785 {
6786 	if (off < 0) {
6787 		verbose(env,
6788 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6789 			regno, buf_info, off, size);
6790 		return -EACCES;
6791 	}
6792 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6793 		char tn_buf[48];
6794 
6795 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6796 		verbose(env,
6797 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6798 			regno, off, tn_buf);
6799 		return -EACCES;
6800 	}
6801 
6802 	return 0;
6803 }
6804 
6805 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6806 				  const struct bpf_reg_state *reg,
6807 				  int regno, int off, int size)
6808 {
6809 	int err;
6810 
6811 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6812 	if (err)
6813 		return err;
6814 
6815 	if (off + size > env->prog->aux->max_tp_access)
6816 		env->prog->aux->max_tp_access = off + size;
6817 
6818 	return 0;
6819 }
6820 
6821 static int check_buffer_access(struct bpf_verifier_env *env,
6822 			       const struct bpf_reg_state *reg,
6823 			       int regno, int off, int size,
6824 			       bool zero_size_allowed,
6825 			       u32 *max_access)
6826 {
6827 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6828 	int err;
6829 
6830 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6831 	if (err)
6832 		return err;
6833 
6834 	if (off + size > *max_access)
6835 		*max_access = off + size;
6836 
6837 	return 0;
6838 }
6839 
6840 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6841 static void zext_32_to_64(struct bpf_reg_state *reg)
6842 {
6843 	reg->var_off = tnum_subreg(reg->var_off);
6844 	__reg_assign_32_into_64(reg);
6845 }
6846 
6847 /* truncate register to smaller size (in bytes)
6848  * must be called with size < BPF_REG_SIZE
6849  */
6850 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6851 {
6852 	u64 mask;
6853 
6854 	/* clear high bits in bit representation */
6855 	reg->var_off = tnum_cast(reg->var_off, size);
6856 
6857 	/* fix arithmetic bounds */
6858 	mask = ((u64)1 << (size * 8)) - 1;
6859 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6860 		reg->umin_value &= mask;
6861 		reg->umax_value &= mask;
6862 	} else {
6863 		reg->umin_value = 0;
6864 		reg->umax_value = mask;
6865 	}
6866 	reg->smin_value = reg->umin_value;
6867 	reg->smax_value = reg->umax_value;
6868 
6869 	/* If size is smaller than 32bit register the 32bit register
6870 	 * values are also truncated so we push 64-bit bounds into
6871 	 * 32-bit bounds. Above were truncated < 32-bits already.
6872 	 */
6873 	if (size < 4)
6874 		__mark_reg32_unbounded(reg);
6875 
6876 	reg_bounds_sync(reg);
6877 }
6878 
6879 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6880 {
6881 	if (size == 1) {
6882 		reg->smin_value = reg->s32_min_value = S8_MIN;
6883 		reg->smax_value = reg->s32_max_value = S8_MAX;
6884 	} else if (size == 2) {
6885 		reg->smin_value = reg->s32_min_value = S16_MIN;
6886 		reg->smax_value = reg->s32_max_value = S16_MAX;
6887 	} else {
6888 		/* size == 4 */
6889 		reg->smin_value = reg->s32_min_value = S32_MIN;
6890 		reg->smax_value = reg->s32_max_value = S32_MAX;
6891 	}
6892 	reg->umin_value = reg->u32_min_value = 0;
6893 	reg->umax_value = U64_MAX;
6894 	reg->u32_max_value = U32_MAX;
6895 	reg->var_off = tnum_unknown;
6896 }
6897 
6898 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6899 {
6900 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6901 	u64 top_smax_value, top_smin_value;
6902 	u64 num_bits = size * 8;
6903 
6904 	if (tnum_is_const(reg->var_off)) {
6905 		u64_cval = reg->var_off.value;
6906 		if (size == 1)
6907 			reg->var_off = tnum_const((s8)u64_cval);
6908 		else if (size == 2)
6909 			reg->var_off = tnum_const((s16)u64_cval);
6910 		else
6911 			/* size == 4 */
6912 			reg->var_off = tnum_const((s32)u64_cval);
6913 
6914 		u64_cval = reg->var_off.value;
6915 		reg->smax_value = reg->smin_value = u64_cval;
6916 		reg->umax_value = reg->umin_value = u64_cval;
6917 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6918 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6919 		return;
6920 	}
6921 
6922 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6923 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6924 
6925 	if (top_smax_value != top_smin_value)
6926 		goto out;
6927 
6928 	/* find the s64_min and s64_min after sign extension */
6929 	if (size == 1) {
6930 		init_s64_max = (s8)reg->smax_value;
6931 		init_s64_min = (s8)reg->smin_value;
6932 	} else if (size == 2) {
6933 		init_s64_max = (s16)reg->smax_value;
6934 		init_s64_min = (s16)reg->smin_value;
6935 	} else {
6936 		init_s64_max = (s32)reg->smax_value;
6937 		init_s64_min = (s32)reg->smin_value;
6938 	}
6939 
6940 	s64_max = max(init_s64_max, init_s64_min);
6941 	s64_min = min(init_s64_max, init_s64_min);
6942 
6943 	/* both of s64_max/s64_min positive or negative */
6944 	if ((s64_max >= 0) == (s64_min >= 0)) {
6945 		reg->s32_min_value = reg->smin_value = s64_min;
6946 		reg->s32_max_value = reg->smax_value = s64_max;
6947 		reg->u32_min_value = reg->umin_value = s64_min;
6948 		reg->u32_max_value = reg->umax_value = s64_max;
6949 		reg->var_off = tnum_range(s64_min, s64_max);
6950 		return;
6951 	}
6952 
6953 out:
6954 	set_sext64_default_val(reg, size);
6955 }
6956 
6957 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6958 {
6959 	if (size == 1) {
6960 		reg->s32_min_value = S8_MIN;
6961 		reg->s32_max_value = S8_MAX;
6962 	} else {
6963 		/* size == 2 */
6964 		reg->s32_min_value = S16_MIN;
6965 		reg->s32_max_value = S16_MAX;
6966 	}
6967 	reg->u32_min_value = 0;
6968 	reg->u32_max_value = U32_MAX;
6969 	reg->var_off = tnum_subreg(tnum_unknown);
6970 }
6971 
6972 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6973 {
6974 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6975 	u32 top_smax_value, top_smin_value;
6976 	u32 num_bits = size * 8;
6977 
6978 	if (tnum_is_const(reg->var_off)) {
6979 		u32_val = reg->var_off.value;
6980 		if (size == 1)
6981 			reg->var_off = tnum_const((s8)u32_val);
6982 		else
6983 			reg->var_off = tnum_const((s16)u32_val);
6984 
6985 		u32_val = reg->var_off.value;
6986 		reg->s32_min_value = reg->s32_max_value = u32_val;
6987 		reg->u32_min_value = reg->u32_max_value = u32_val;
6988 		return;
6989 	}
6990 
6991 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6992 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6993 
6994 	if (top_smax_value != top_smin_value)
6995 		goto out;
6996 
6997 	/* find the s32_min and s32_min after sign extension */
6998 	if (size == 1) {
6999 		init_s32_max = (s8)reg->s32_max_value;
7000 		init_s32_min = (s8)reg->s32_min_value;
7001 	} else {
7002 		/* size == 2 */
7003 		init_s32_max = (s16)reg->s32_max_value;
7004 		init_s32_min = (s16)reg->s32_min_value;
7005 	}
7006 	s32_max = max(init_s32_max, init_s32_min);
7007 	s32_min = min(init_s32_max, init_s32_min);
7008 
7009 	if ((s32_min >= 0) == (s32_max >= 0)) {
7010 		reg->s32_min_value = s32_min;
7011 		reg->s32_max_value = s32_max;
7012 		reg->u32_min_value = (u32)s32_min;
7013 		reg->u32_max_value = (u32)s32_max;
7014 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7015 		return;
7016 	}
7017 
7018 out:
7019 	set_sext32_default_val(reg, size);
7020 }
7021 
7022 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7023 {
7024 	/* A map is considered read-only if the following condition are true:
7025 	 *
7026 	 * 1) BPF program side cannot change any of the map content. The
7027 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7028 	 *    and was set at map creation time.
7029 	 * 2) The map value(s) have been initialized from user space by a
7030 	 *    loader and then "frozen", such that no new map update/delete
7031 	 *    operations from syscall side are possible for the rest of
7032 	 *    the map's lifetime from that point onwards.
7033 	 * 3) Any parallel/pending map update/delete operations from syscall
7034 	 *    side have been completed. Only after that point, it's safe to
7035 	 *    assume that map value(s) are immutable.
7036 	 */
7037 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
7038 	       READ_ONCE(map->frozen) &&
7039 	       !bpf_map_write_active(map);
7040 }
7041 
7042 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7043 			       bool is_ldsx)
7044 {
7045 	void *ptr;
7046 	u64 addr;
7047 	int err;
7048 
7049 	err = map->ops->map_direct_value_addr(map, &addr, off);
7050 	if (err)
7051 		return err;
7052 	ptr = (void *)(long)addr + off;
7053 
7054 	switch (size) {
7055 	case sizeof(u8):
7056 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7057 		break;
7058 	case sizeof(u16):
7059 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7060 		break;
7061 	case sizeof(u32):
7062 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7063 		break;
7064 	case sizeof(u64):
7065 		*val = *(u64 *)ptr;
7066 		break;
7067 	default:
7068 		return -EINVAL;
7069 	}
7070 	return 0;
7071 }
7072 
7073 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7074 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7075 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7076 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7077 
7078 /*
7079  * Allow list few fields as RCU trusted or full trusted.
7080  * This logic doesn't allow mix tagging and will be removed once GCC supports
7081  * btf_type_tag.
7082  */
7083 
7084 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
7085 BTF_TYPE_SAFE_RCU(struct task_struct) {
7086 	const cpumask_t *cpus_ptr;
7087 	struct css_set __rcu *cgroups;
7088 	struct task_struct __rcu *real_parent;
7089 	struct task_struct *group_leader;
7090 };
7091 
7092 BTF_TYPE_SAFE_RCU(struct cgroup) {
7093 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7094 	struct kernfs_node *kn;
7095 };
7096 
7097 BTF_TYPE_SAFE_RCU(struct css_set) {
7098 	struct cgroup *dfl_cgrp;
7099 };
7100 
7101 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7102 	struct cgroup *cgroup;
7103 };
7104 
7105 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
7106 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7107 	struct file __rcu *exe_file;
7108 #ifdef CONFIG_MEMCG
7109 	struct task_struct __rcu *owner;
7110 #endif
7111 };
7112 
7113 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7114  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7115  */
7116 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7117 	struct sock *sk;
7118 };
7119 
7120 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7121 	struct sock *sk;
7122 };
7123 
7124 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
7125 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7126 	struct seq_file *seq;
7127 };
7128 
7129 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7130 	struct bpf_iter_meta *meta;
7131 	struct task_struct *task;
7132 };
7133 
7134 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7135 	struct file *file;
7136 };
7137 
7138 BTF_TYPE_SAFE_TRUSTED(struct file) {
7139 	struct inode *f_inode;
7140 };
7141 
7142 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7143 	struct inode *d_inode;
7144 };
7145 
7146 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7147 	struct sock *sk;
7148 };
7149 
7150 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
7151 	struct mm_struct *vm_mm;
7152 	struct file *vm_file;
7153 };
7154 
7155 static bool type_is_rcu(struct bpf_verifier_env *env,
7156 			struct bpf_reg_state *reg,
7157 			const char *field_name, u32 btf_id)
7158 {
7159 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7160 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7161 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7162 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7163 
7164 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7165 }
7166 
7167 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7168 				struct bpf_reg_state *reg,
7169 				const char *field_name, u32 btf_id)
7170 {
7171 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7172 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7173 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7174 
7175 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7176 }
7177 
7178 static bool type_is_trusted(struct bpf_verifier_env *env,
7179 			    struct bpf_reg_state *reg,
7180 			    const char *field_name, u32 btf_id)
7181 {
7182 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7183 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7184 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7185 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7186 
7187 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7188 }
7189 
7190 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7191 				    struct bpf_reg_state *reg,
7192 				    const char *field_name, u32 btf_id)
7193 {
7194 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7195 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7196 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
7197 
7198 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7199 					  "__safe_trusted_or_null");
7200 }
7201 
7202 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7203 				   struct bpf_reg_state *regs,
7204 				   int regno, int off, int size,
7205 				   enum bpf_access_type atype,
7206 				   int value_regno)
7207 {
7208 	struct bpf_reg_state *reg = regs + regno;
7209 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7210 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7211 	const char *field_name = NULL;
7212 	enum bpf_type_flag flag = 0;
7213 	u32 btf_id = 0;
7214 	int ret;
7215 
7216 	if (!env->allow_ptr_leaks) {
7217 		verbose(env,
7218 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7219 			tname);
7220 		return -EPERM;
7221 	}
7222 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7223 		verbose(env,
7224 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7225 			tname);
7226 		return -EINVAL;
7227 	}
7228 	if (off < 0) {
7229 		verbose(env,
7230 			"R%d is ptr_%s invalid negative access: off=%d\n",
7231 			regno, tname, off);
7232 		return -EACCES;
7233 	}
7234 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7235 		char tn_buf[48];
7236 
7237 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7238 		verbose(env,
7239 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7240 			regno, tname, off, tn_buf);
7241 		return -EACCES;
7242 	}
7243 
7244 	if (reg->type & MEM_USER) {
7245 		verbose(env,
7246 			"R%d is ptr_%s access user memory: off=%d\n",
7247 			regno, tname, off);
7248 		return -EACCES;
7249 	}
7250 
7251 	if (reg->type & MEM_PERCPU) {
7252 		verbose(env,
7253 			"R%d is ptr_%s access percpu memory: off=%d\n",
7254 			regno, tname, off);
7255 		return -EACCES;
7256 	}
7257 
7258 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7259 		if (!btf_is_kernel(reg->btf)) {
7260 			verifier_bug(env, "reg->btf must be kernel btf");
7261 			return -EFAULT;
7262 		}
7263 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7264 	} else {
7265 		/* Writes are permitted with default btf_struct_access for
7266 		 * program allocated objects (which always have ref_obj_id > 0),
7267 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7268 		 */
7269 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7270 			verbose(env, "only read is supported\n");
7271 			return -EACCES;
7272 		}
7273 
7274 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7275 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7276 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7277 			return -EFAULT;
7278 		}
7279 
7280 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7281 	}
7282 
7283 	if (ret < 0)
7284 		return ret;
7285 
7286 	if (ret != PTR_TO_BTF_ID) {
7287 		/* just mark; */
7288 
7289 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7290 		/* If this is an untrusted pointer, all pointers formed by walking it
7291 		 * also inherit the untrusted flag.
7292 		 */
7293 		flag = PTR_UNTRUSTED;
7294 
7295 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7296 		/* By default any pointer obtained from walking a trusted pointer is no
7297 		 * longer trusted, unless the field being accessed has explicitly been
7298 		 * marked as inheriting its parent's state of trust (either full or RCU).
7299 		 * For example:
7300 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7301 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7302 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7303 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7304 		 *
7305 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7306 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7307 		 */
7308 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7309 			flag |= PTR_TRUSTED;
7310 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7311 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7312 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7313 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7314 				/* ignore __rcu tag and mark it MEM_RCU */
7315 				flag |= MEM_RCU;
7316 			} else if (flag & MEM_RCU ||
7317 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7318 				/* __rcu tagged pointers can be NULL */
7319 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7320 
7321 				/* We always trust them */
7322 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7323 				    flag & PTR_UNTRUSTED)
7324 					flag &= ~PTR_UNTRUSTED;
7325 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7326 				/* keep as-is */
7327 			} else {
7328 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7329 				clear_trusted_flags(&flag);
7330 			}
7331 		} else {
7332 			/*
7333 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7334 			 * aggressively mark as untrusted otherwise such
7335 			 * pointers will be plain PTR_TO_BTF_ID without flags
7336 			 * and will be allowed to be passed into helpers for
7337 			 * compat reasons.
7338 			 */
7339 			flag = PTR_UNTRUSTED;
7340 		}
7341 	} else {
7342 		/* Old compat. Deprecated */
7343 		clear_trusted_flags(&flag);
7344 	}
7345 
7346 	if (atype == BPF_READ && value_regno >= 0) {
7347 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7348 		if (ret < 0)
7349 			return ret;
7350 	}
7351 
7352 	return 0;
7353 }
7354 
7355 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7356 				   struct bpf_reg_state *regs,
7357 				   int regno, int off, int size,
7358 				   enum bpf_access_type atype,
7359 				   int value_regno)
7360 {
7361 	struct bpf_reg_state *reg = regs + regno;
7362 	struct bpf_map *map = reg->map_ptr;
7363 	struct bpf_reg_state map_reg;
7364 	enum bpf_type_flag flag = 0;
7365 	const struct btf_type *t;
7366 	const char *tname;
7367 	u32 btf_id;
7368 	int ret;
7369 
7370 	if (!btf_vmlinux) {
7371 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7372 		return -ENOTSUPP;
7373 	}
7374 
7375 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7376 		verbose(env, "map_ptr access not supported for map type %d\n",
7377 			map->map_type);
7378 		return -ENOTSUPP;
7379 	}
7380 
7381 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7382 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7383 
7384 	if (!env->allow_ptr_leaks) {
7385 		verbose(env,
7386 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7387 			tname);
7388 		return -EPERM;
7389 	}
7390 
7391 	if (off < 0) {
7392 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7393 			regno, tname, off);
7394 		return -EACCES;
7395 	}
7396 
7397 	if (atype != BPF_READ) {
7398 		verbose(env, "only read from %s is supported\n", tname);
7399 		return -EACCES;
7400 	}
7401 
7402 	/* Simulate access to a PTR_TO_BTF_ID */
7403 	memset(&map_reg, 0, sizeof(map_reg));
7404 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7405 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7406 	if (ret < 0)
7407 		return ret;
7408 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7409 	if (ret < 0)
7410 		return ret;
7411 
7412 	if (value_regno >= 0) {
7413 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7414 		if (ret < 0)
7415 			return ret;
7416 	}
7417 
7418 	return 0;
7419 }
7420 
7421 /* Check that the stack access at the given offset is within bounds. The
7422  * maximum valid offset is -1.
7423  *
7424  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7425  * -state->allocated_stack for reads.
7426  */
7427 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7428                                           s64 off,
7429                                           struct bpf_func_state *state,
7430                                           enum bpf_access_type t)
7431 {
7432 	int min_valid_off;
7433 
7434 	if (t == BPF_WRITE || env->allow_uninit_stack)
7435 		min_valid_off = -MAX_BPF_STACK;
7436 	else
7437 		min_valid_off = -state->allocated_stack;
7438 
7439 	if (off < min_valid_off || off > -1)
7440 		return -EACCES;
7441 	return 0;
7442 }
7443 
7444 /* Check that the stack access at 'regno + off' falls within the maximum stack
7445  * bounds.
7446  *
7447  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7448  */
7449 static int check_stack_access_within_bounds(
7450 		struct bpf_verifier_env *env,
7451 		int regno, int off, int access_size,
7452 		enum bpf_access_type type)
7453 {
7454 	struct bpf_reg_state *reg = reg_state(env, regno);
7455 	struct bpf_func_state *state = func(env, reg);
7456 	s64 min_off, max_off;
7457 	int err;
7458 	char *err_extra;
7459 
7460 	if (type == BPF_READ)
7461 		err_extra = " read from";
7462 	else
7463 		err_extra = " write to";
7464 
7465 	if (tnum_is_const(reg->var_off)) {
7466 		min_off = (s64)reg->var_off.value + off;
7467 		max_off = min_off + access_size;
7468 	} else {
7469 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7470 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7471 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7472 				err_extra, regno);
7473 			return -EACCES;
7474 		}
7475 		min_off = reg->smin_value + off;
7476 		max_off = reg->smax_value + off + access_size;
7477 	}
7478 
7479 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7480 	if (!err && max_off > 0)
7481 		err = -EINVAL; /* out of stack access into non-negative offsets */
7482 	if (!err && access_size < 0)
7483 		/* access_size should not be negative (or overflow an int); others checks
7484 		 * along the way should have prevented such an access.
7485 		 */
7486 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7487 
7488 	if (err) {
7489 		if (tnum_is_const(reg->var_off)) {
7490 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7491 				err_extra, regno, off, access_size);
7492 		} else {
7493 			char tn_buf[48];
7494 
7495 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7496 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7497 				err_extra, regno, tn_buf, off, access_size);
7498 		}
7499 		return err;
7500 	}
7501 
7502 	/* Note that there is no stack access with offset zero, so the needed stack
7503 	 * size is -min_off, not -min_off+1.
7504 	 */
7505 	return grow_stack_state(env, state, -min_off /* size */);
7506 }
7507 
7508 static bool get_func_retval_range(struct bpf_prog *prog,
7509 				  struct bpf_retval_range *range)
7510 {
7511 	if (prog->type == BPF_PROG_TYPE_LSM &&
7512 		prog->expected_attach_type == BPF_LSM_MAC &&
7513 		!bpf_lsm_get_retval_range(prog, range)) {
7514 		return true;
7515 	}
7516 	return false;
7517 }
7518 
7519 /* check whether memory at (regno + off) is accessible for t = (read | write)
7520  * if t==write, value_regno is a register which value is stored into memory
7521  * if t==read, value_regno is a register which will receive the value from memory
7522  * if t==write && value_regno==-1, some unknown value is stored into memory
7523  * if t==read && value_regno==-1, don't care what we read from memory
7524  */
7525 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7526 			    int off, int bpf_size, enum bpf_access_type t,
7527 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7528 {
7529 	struct bpf_reg_state *regs = cur_regs(env);
7530 	struct bpf_reg_state *reg = regs + regno;
7531 	int size, err = 0;
7532 
7533 	size = bpf_size_to_bytes(bpf_size);
7534 	if (size < 0)
7535 		return size;
7536 
7537 	/* alignment checks will add in reg->off themselves */
7538 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7539 	if (err)
7540 		return err;
7541 
7542 	/* for access checks, reg->off is just part of off */
7543 	off += reg->off;
7544 
7545 	if (reg->type == PTR_TO_MAP_KEY) {
7546 		if (t == BPF_WRITE) {
7547 			verbose(env, "write to change key R%d not allowed\n", regno);
7548 			return -EACCES;
7549 		}
7550 
7551 		err = check_mem_region_access(env, regno, off, size,
7552 					      reg->map_ptr->key_size, false);
7553 		if (err)
7554 			return err;
7555 		if (value_regno >= 0)
7556 			mark_reg_unknown(env, regs, value_regno);
7557 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7558 		struct btf_field *kptr_field = NULL;
7559 
7560 		if (t == BPF_WRITE && value_regno >= 0 &&
7561 		    is_pointer_value(env, value_regno)) {
7562 			verbose(env, "R%d leaks addr into map\n", value_regno);
7563 			return -EACCES;
7564 		}
7565 		err = check_map_access_type(env, regno, off, size, t);
7566 		if (err)
7567 			return err;
7568 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7569 		if (err)
7570 			return err;
7571 		if (tnum_is_const(reg->var_off))
7572 			kptr_field = btf_record_find(reg->map_ptr->record,
7573 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7574 		if (kptr_field) {
7575 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7576 		} else if (t == BPF_READ && value_regno >= 0) {
7577 			struct bpf_map *map = reg->map_ptr;
7578 
7579 			/*
7580 			 * If map is read-only, track its contents as scalars,
7581 			 * unless it is an insn array (see the special case below)
7582 			 */
7583 			if (tnum_is_const(reg->var_off) &&
7584 			    bpf_map_is_rdonly(map) &&
7585 			    map->ops->map_direct_value_addr &&
7586 			    map->map_type != BPF_MAP_TYPE_INSN_ARRAY) {
7587 				int map_off = off + reg->var_off.value;
7588 				u64 val = 0;
7589 
7590 				err = bpf_map_direct_read(map, map_off, size,
7591 							  &val, is_ldsx);
7592 				if (err)
7593 					return err;
7594 
7595 				regs[value_regno].type = SCALAR_VALUE;
7596 				__mark_reg_known(&regs[value_regno], val);
7597 			} else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
7598 				if (bpf_size != BPF_DW) {
7599 					verbose(env, "Invalid read of %d bytes from insn_array\n",
7600 						     size);
7601 					return -EACCES;
7602 				}
7603 				copy_register_state(&regs[value_regno], reg);
7604 				regs[value_regno].type = PTR_TO_INSN;
7605 			} else {
7606 				mark_reg_unknown(env, regs, value_regno);
7607 			}
7608 		}
7609 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7610 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7611 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7612 
7613 		if (type_may_be_null(reg->type)) {
7614 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7615 				reg_type_str(env, reg->type));
7616 			return -EACCES;
7617 		}
7618 
7619 		if (t == BPF_WRITE && rdonly_mem) {
7620 			verbose(env, "R%d cannot write into %s\n",
7621 				regno, reg_type_str(env, reg->type));
7622 			return -EACCES;
7623 		}
7624 
7625 		if (t == BPF_WRITE && value_regno >= 0 &&
7626 		    is_pointer_value(env, value_regno)) {
7627 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7628 			return -EACCES;
7629 		}
7630 
7631 		/*
7632 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7633 		 * instructions, hence no need to check bounds in that case.
7634 		 */
7635 		if (!rdonly_untrusted)
7636 			err = check_mem_region_access(env, regno, off, size,
7637 						      reg->mem_size, false);
7638 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7639 			mark_reg_unknown(env, regs, value_regno);
7640 	} else if (reg->type == PTR_TO_CTX) {
7641 		struct bpf_retval_range range;
7642 		struct bpf_insn_access_aux info = {
7643 			.reg_type = SCALAR_VALUE,
7644 			.is_ldsx = is_ldsx,
7645 			.log = &env->log,
7646 		};
7647 
7648 		if (t == BPF_WRITE && value_regno >= 0 &&
7649 		    is_pointer_value(env, value_regno)) {
7650 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7651 			return -EACCES;
7652 		}
7653 
7654 		err = check_ptr_off_reg(env, reg, regno);
7655 		if (err < 0)
7656 			return err;
7657 
7658 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7659 		if (err)
7660 			verbose_linfo(env, insn_idx, "; ");
7661 		if (!err && t == BPF_READ && value_regno >= 0) {
7662 			/* ctx access returns either a scalar, or a
7663 			 * PTR_TO_PACKET[_META,_END]. In the latter
7664 			 * case, we know the offset is zero.
7665 			 */
7666 			if (info.reg_type == SCALAR_VALUE) {
7667 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7668 					err = __mark_reg_s32_range(env, regs, value_regno,
7669 								   range.minval, range.maxval);
7670 					if (err)
7671 						return err;
7672 				} else {
7673 					mark_reg_unknown(env, regs, value_regno);
7674 				}
7675 			} else {
7676 				mark_reg_known_zero(env, regs,
7677 						    value_regno);
7678 				if (type_may_be_null(info.reg_type))
7679 					regs[value_regno].id = ++env->id_gen;
7680 				/* A load of ctx field could have different
7681 				 * actual load size with the one encoded in the
7682 				 * insn. When the dst is PTR, it is for sure not
7683 				 * a sub-register.
7684 				 */
7685 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7686 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7687 					regs[value_regno].btf = info.btf;
7688 					regs[value_regno].btf_id = info.btf_id;
7689 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7690 				}
7691 			}
7692 			regs[value_regno].type = info.reg_type;
7693 		}
7694 
7695 	} else if (reg->type == PTR_TO_STACK) {
7696 		/* Basic bounds checks. */
7697 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7698 		if (err)
7699 			return err;
7700 
7701 		if (t == BPF_READ)
7702 			err = check_stack_read(env, regno, off, size,
7703 					       value_regno);
7704 		else
7705 			err = check_stack_write(env, regno, off, size,
7706 						value_regno, insn_idx);
7707 	} else if (reg_is_pkt_pointer(reg)) {
7708 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7709 			verbose(env, "cannot write into packet\n");
7710 			return -EACCES;
7711 		}
7712 		if (t == BPF_WRITE && value_regno >= 0 &&
7713 		    is_pointer_value(env, value_regno)) {
7714 			verbose(env, "R%d leaks addr into packet\n",
7715 				value_regno);
7716 			return -EACCES;
7717 		}
7718 		err = check_packet_access(env, regno, off, size, false);
7719 		if (!err && t == BPF_READ && value_regno >= 0)
7720 			mark_reg_unknown(env, regs, value_regno);
7721 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7722 		if (t == BPF_WRITE && value_regno >= 0 &&
7723 		    is_pointer_value(env, value_regno)) {
7724 			verbose(env, "R%d leaks addr into flow keys\n",
7725 				value_regno);
7726 			return -EACCES;
7727 		}
7728 
7729 		err = check_flow_keys_access(env, off, size);
7730 		if (!err && t == BPF_READ && value_regno >= 0)
7731 			mark_reg_unknown(env, regs, value_regno);
7732 	} else if (type_is_sk_pointer(reg->type)) {
7733 		if (t == BPF_WRITE) {
7734 			verbose(env, "R%d cannot write into %s\n",
7735 				regno, reg_type_str(env, reg->type));
7736 			return -EACCES;
7737 		}
7738 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7739 		if (!err && value_regno >= 0)
7740 			mark_reg_unknown(env, regs, value_regno);
7741 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7742 		err = check_tp_buffer_access(env, reg, regno, off, size);
7743 		if (!err && t == BPF_READ && value_regno >= 0)
7744 			mark_reg_unknown(env, regs, value_regno);
7745 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7746 		   !type_may_be_null(reg->type)) {
7747 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7748 					      value_regno);
7749 	} else if (reg->type == CONST_PTR_TO_MAP) {
7750 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7751 					      value_regno);
7752 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7753 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7754 		u32 *max_access;
7755 
7756 		if (rdonly_mem) {
7757 			if (t == BPF_WRITE) {
7758 				verbose(env, "R%d cannot write into %s\n",
7759 					regno, reg_type_str(env, reg->type));
7760 				return -EACCES;
7761 			}
7762 			max_access = &env->prog->aux->max_rdonly_access;
7763 		} else {
7764 			max_access = &env->prog->aux->max_rdwr_access;
7765 		}
7766 
7767 		err = check_buffer_access(env, reg, regno, off, size, false,
7768 					  max_access);
7769 
7770 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7771 			mark_reg_unknown(env, regs, value_regno);
7772 	} else if (reg->type == PTR_TO_ARENA) {
7773 		if (t == BPF_READ && value_regno >= 0)
7774 			mark_reg_unknown(env, regs, value_regno);
7775 	} else {
7776 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7777 			reg_type_str(env, reg->type));
7778 		return -EACCES;
7779 	}
7780 
7781 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7782 	    regs[value_regno].type == SCALAR_VALUE) {
7783 		if (!is_ldsx)
7784 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7785 			coerce_reg_to_size(&regs[value_regno], size);
7786 		else
7787 			coerce_reg_to_size_sx(&regs[value_regno], size);
7788 	}
7789 	return err;
7790 }
7791 
7792 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7793 			     bool allow_trust_mismatch);
7794 
7795 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7796 			  bool strict_alignment_once, bool is_ldsx,
7797 			  bool allow_trust_mismatch, const char *ctx)
7798 {
7799 	struct bpf_reg_state *regs = cur_regs(env);
7800 	enum bpf_reg_type src_reg_type;
7801 	int err;
7802 
7803 	/* check src operand */
7804 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7805 	if (err)
7806 		return err;
7807 
7808 	/* check dst operand */
7809 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7810 	if (err)
7811 		return err;
7812 
7813 	src_reg_type = regs[insn->src_reg].type;
7814 
7815 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7816 	 * updated by this call.
7817 	 */
7818 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7819 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7820 			       strict_alignment_once, is_ldsx);
7821 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7822 				       allow_trust_mismatch);
7823 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7824 
7825 	return err;
7826 }
7827 
7828 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7829 			   bool strict_alignment_once)
7830 {
7831 	struct bpf_reg_state *regs = cur_regs(env);
7832 	enum bpf_reg_type dst_reg_type;
7833 	int err;
7834 
7835 	/* check src1 operand */
7836 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7837 	if (err)
7838 		return err;
7839 
7840 	/* check src2 operand */
7841 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7842 	if (err)
7843 		return err;
7844 
7845 	dst_reg_type = regs[insn->dst_reg].type;
7846 
7847 	/* Check if (dst_reg + off) is writeable. */
7848 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7849 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7850 			       strict_alignment_once, false);
7851 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7852 
7853 	return err;
7854 }
7855 
7856 static int check_atomic_rmw(struct bpf_verifier_env *env,
7857 			    struct bpf_insn *insn)
7858 {
7859 	int load_reg;
7860 	int err;
7861 
7862 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7863 		verbose(env, "invalid atomic operand size\n");
7864 		return -EINVAL;
7865 	}
7866 
7867 	/* check src1 operand */
7868 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7869 	if (err)
7870 		return err;
7871 
7872 	/* check src2 operand */
7873 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7874 	if (err)
7875 		return err;
7876 
7877 	if (insn->imm == BPF_CMPXCHG) {
7878 		/* Check comparison of R0 with memory location */
7879 		const u32 aux_reg = BPF_REG_0;
7880 
7881 		err = check_reg_arg(env, aux_reg, SRC_OP);
7882 		if (err)
7883 			return err;
7884 
7885 		if (is_pointer_value(env, aux_reg)) {
7886 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7887 			return -EACCES;
7888 		}
7889 	}
7890 
7891 	if (is_pointer_value(env, insn->src_reg)) {
7892 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7893 		return -EACCES;
7894 	}
7895 
7896 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7897 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7898 			insn->dst_reg,
7899 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7900 		return -EACCES;
7901 	}
7902 
7903 	if (insn->imm & BPF_FETCH) {
7904 		if (insn->imm == BPF_CMPXCHG)
7905 			load_reg = BPF_REG_0;
7906 		else
7907 			load_reg = insn->src_reg;
7908 
7909 		/* check and record load of old value */
7910 		err = check_reg_arg(env, load_reg, DST_OP);
7911 		if (err)
7912 			return err;
7913 	} else {
7914 		/* This instruction accesses a memory location but doesn't
7915 		 * actually load it into a register.
7916 		 */
7917 		load_reg = -1;
7918 	}
7919 
7920 	/* Check whether we can read the memory, with second call for fetch
7921 	 * case to simulate the register fill.
7922 	 */
7923 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7924 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7925 	if (!err && load_reg >= 0)
7926 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7927 				       insn->off, BPF_SIZE(insn->code),
7928 				       BPF_READ, load_reg, true, false);
7929 	if (err)
7930 		return err;
7931 
7932 	if (is_arena_reg(env, insn->dst_reg)) {
7933 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7934 		if (err)
7935 			return err;
7936 	}
7937 	/* Check whether we can write into the same memory. */
7938 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7939 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7940 	if (err)
7941 		return err;
7942 	return 0;
7943 }
7944 
7945 static int check_atomic_load(struct bpf_verifier_env *env,
7946 			     struct bpf_insn *insn)
7947 {
7948 	int err;
7949 
7950 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7951 	if (err)
7952 		return err;
7953 
7954 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7955 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7956 			insn->src_reg,
7957 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7958 		return -EACCES;
7959 	}
7960 
7961 	return 0;
7962 }
7963 
7964 static int check_atomic_store(struct bpf_verifier_env *env,
7965 			      struct bpf_insn *insn)
7966 {
7967 	int err;
7968 
7969 	err = check_store_reg(env, insn, true);
7970 	if (err)
7971 		return err;
7972 
7973 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7974 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7975 			insn->dst_reg,
7976 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7977 		return -EACCES;
7978 	}
7979 
7980 	return 0;
7981 }
7982 
7983 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7984 {
7985 	switch (insn->imm) {
7986 	case BPF_ADD:
7987 	case BPF_ADD | BPF_FETCH:
7988 	case BPF_AND:
7989 	case BPF_AND | BPF_FETCH:
7990 	case BPF_OR:
7991 	case BPF_OR | BPF_FETCH:
7992 	case BPF_XOR:
7993 	case BPF_XOR | BPF_FETCH:
7994 	case BPF_XCHG:
7995 	case BPF_CMPXCHG:
7996 		return check_atomic_rmw(env, insn);
7997 	case BPF_LOAD_ACQ:
7998 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7999 			verbose(env,
8000 				"64-bit load-acquires are only supported on 64-bit arches\n");
8001 			return -EOPNOTSUPP;
8002 		}
8003 		return check_atomic_load(env, insn);
8004 	case BPF_STORE_REL:
8005 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8006 			verbose(env,
8007 				"64-bit store-releases are only supported on 64-bit arches\n");
8008 			return -EOPNOTSUPP;
8009 		}
8010 		return check_atomic_store(env, insn);
8011 	default:
8012 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8013 			insn->imm);
8014 		return -EINVAL;
8015 	}
8016 }
8017 
8018 /* When register 'regno' is used to read the stack (either directly or through
8019  * a helper function) make sure that it's within stack boundary and, depending
8020  * on the access type and privileges, that all elements of the stack are
8021  * initialized.
8022  *
8023  * 'off' includes 'regno->off', but not its dynamic part (if any).
8024  *
8025  * All registers that have been spilled on the stack in the slots within the
8026  * read offsets are marked as read.
8027  */
8028 static int check_stack_range_initialized(
8029 		struct bpf_verifier_env *env, int regno, int off,
8030 		int access_size, bool zero_size_allowed,
8031 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8032 {
8033 	struct bpf_reg_state *reg = reg_state(env, regno);
8034 	struct bpf_func_state *state = func(env, reg);
8035 	int err, min_off, max_off, i, j, slot, spi;
8036 	/* Some accesses can write anything into the stack, others are
8037 	 * read-only.
8038 	 */
8039 	bool clobber = false;
8040 
8041 	if (access_size == 0 && !zero_size_allowed) {
8042 		verbose(env, "invalid zero-sized read\n");
8043 		return -EACCES;
8044 	}
8045 
8046 	if (type == BPF_WRITE)
8047 		clobber = true;
8048 
8049 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8050 	if (err)
8051 		return err;
8052 
8053 
8054 	if (tnum_is_const(reg->var_off)) {
8055 		min_off = max_off = reg->var_off.value + off;
8056 	} else {
8057 		/* Variable offset is prohibited for unprivileged mode for
8058 		 * simplicity since it requires corresponding support in
8059 		 * Spectre masking for stack ALU.
8060 		 * See also retrieve_ptr_limit().
8061 		 */
8062 		if (!env->bypass_spec_v1) {
8063 			char tn_buf[48];
8064 
8065 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8066 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8067 				regno, tn_buf);
8068 			return -EACCES;
8069 		}
8070 		/* Only initialized buffer on stack is allowed to be accessed
8071 		 * with variable offset. With uninitialized buffer it's hard to
8072 		 * guarantee that whole memory is marked as initialized on
8073 		 * helper return since specific bounds are unknown what may
8074 		 * cause uninitialized stack leaking.
8075 		 */
8076 		if (meta && meta->raw_mode)
8077 			meta = NULL;
8078 
8079 		min_off = reg->smin_value + off;
8080 		max_off = reg->smax_value + off;
8081 	}
8082 
8083 	if (meta && meta->raw_mode) {
8084 		/* Ensure we won't be overwriting dynptrs when simulating byte
8085 		 * by byte access in check_helper_call using meta.access_size.
8086 		 * This would be a problem if we have a helper in the future
8087 		 * which takes:
8088 		 *
8089 		 *	helper(uninit_mem, len, dynptr)
8090 		 *
8091 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8092 		 * may end up writing to dynptr itself when touching memory from
8093 		 * arg 1. This can be relaxed on a case by case basis for known
8094 		 * safe cases, but reject due to the possibilitiy of aliasing by
8095 		 * default.
8096 		 */
8097 		for (i = min_off; i < max_off + access_size; i++) {
8098 			int stack_off = -i - 1;
8099 
8100 			spi = __get_spi(i);
8101 			/* raw_mode may write past allocated_stack */
8102 			if (state->allocated_stack <= stack_off)
8103 				continue;
8104 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8105 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8106 				return -EACCES;
8107 			}
8108 		}
8109 		meta->access_size = access_size;
8110 		meta->regno = regno;
8111 		return 0;
8112 	}
8113 
8114 	for (i = min_off; i < max_off + access_size; i++) {
8115 		u8 *stype;
8116 
8117 		slot = -i - 1;
8118 		spi = slot / BPF_REG_SIZE;
8119 		if (state->allocated_stack <= slot) {
8120 			verbose(env, "allocated_stack too small\n");
8121 			return -EFAULT;
8122 		}
8123 
8124 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8125 		if (*stype == STACK_MISC)
8126 			goto mark;
8127 		if ((*stype == STACK_ZERO) ||
8128 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8129 			if (clobber) {
8130 				/* helper can write anything into the stack */
8131 				*stype = STACK_MISC;
8132 			}
8133 			goto mark;
8134 		}
8135 
8136 		if (is_spilled_reg(&state->stack[spi]) &&
8137 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8138 		     env->allow_ptr_leaks)) {
8139 			if (clobber) {
8140 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8141 				for (j = 0; j < BPF_REG_SIZE; j++)
8142 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8143 			}
8144 			goto mark;
8145 		}
8146 
8147 		if (tnum_is_const(reg->var_off)) {
8148 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8149 				regno, min_off, i - min_off, access_size);
8150 		} else {
8151 			char tn_buf[48];
8152 
8153 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8154 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8155 				regno, tn_buf, i - min_off, access_size);
8156 		}
8157 		return -EACCES;
8158 mark:
8159 		/* reading any byte out of 8-byte 'spill_slot' will cause
8160 		 * the whole slot to be marked as 'read'
8161 		 */
8162 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8163 		if (err)
8164 			return err;
8165 		/* We do not call bpf_mark_stack_write(), as we can not
8166 		 * be sure that whether stack slot is written to or not. Hence,
8167 		 * we must still conservatively propagate reads upwards even if
8168 		 * helper may write to the entire memory range.
8169 		 */
8170 	}
8171 	return 0;
8172 }
8173 
8174 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8175 				   int access_size, enum bpf_access_type access_type,
8176 				   bool zero_size_allowed,
8177 				   struct bpf_call_arg_meta *meta)
8178 {
8179 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8180 	u32 *max_access;
8181 
8182 	switch (base_type(reg->type)) {
8183 	case PTR_TO_PACKET:
8184 	case PTR_TO_PACKET_META:
8185 		return check_packet_access(env, regno, reg->off, access_size,
8186 					   zero_size_allowed);
8187 	case PTR_TO_MAP_KEY:
8188 		if (access_type == BPF_WRITE) {
8189 			verbose(env, "R%d cannot write into %s\n", regno,
8190 				reg_type_str(env, reg->type));
8191 			return -EACCES;
8192 		}
8193 		return check_mem_region_access(env, regno, reg->off, access_size,
8194 					       reg->map_ptr->key_size, false);
8195 	case PTR_TO_MAP_VALUE:
8196 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8197 			return -EACCES;
8198 		return check_map_access(env, regno, reg->off, access_size,
8199 					zero_size_allowed, ACCESS_HELPER);
8200 	case PTR_TO_MEM:
8201 		if (type_is_rdonly_mem(reg->type)) {
8202 			if (access_type == BPF_WRITE) {
8203 				verbose(env, "R%d cannot write into %s\n", regno,
8204 					reg_type_str(env, reg->type));
8205 				return -EACCES;
8206 			}
8207 		}
8208 		return check_mem_region_access(env, regno, reg->off,
8209 					       access_size, reg->mem_size,
8210 					       zero_size_allowed);
8211 	case PTR_TO_BUF:
8212 		if (type_is_rdonly_mem(reg->type)) {
8213 			if (access_type == BPF_WRITE) {
8214 				verbose(env, "R%d cannot write into %s\n", regno,
8215 					reg_type_str(env, reg->type));
8216 				return -EACCES;
8217 			}
8218 
8219 			max_access = &env->prog->aux->max_rdonly_access;
8220 		} else {
8221 			max_access = &env->prog->aux->max_rdwr_access;
8222 		}
8223 		return check_buffer_access(env, reg, regno, reg->off,
8224 					   access_size, zero_size_allowed,
8225 					   max_access);
8226 	case PTR_TO_STACK:
8227 		return check_stack_range_initialized(
8228 				env,
8229 				regno, reg->off, access_size,
8230 				zero_size_allowed, access_type, meta);
8231 	case PTR_TO_BTF_ID:
8232 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8233 					       access_size, BPF_READ, -1);
8234 	case PTR_TO_CTX:
8235 		/* in case the function doesn't know how to access the context,
8236 		 * (because we are in a program of type SYSCALL for example), we
8237 		 * can not statically check its size.
8238 		 * Dynamically check it now.
8239 		 */
8240 		if (!env->ops->convert_ctx_access) {
8241 			int offset = access_size - 1;
8242 
8243 			/* Allow zero-byte read from PTR_TO_CTX */
8244 			if (access_size == 0)
8245 				return zero_size_allowed ? 0 : -EACCES;
8246 
8247 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8248 						access_type, -1, false, false);
8249 		}
8250 
8251 		fallthrough;
8252 	default: /* scalar_value or invalid ptr */
8253 		/* Allow zero-byte read from NULL, regardless of pointer type */
8254 		if (zero_size_allowed && access_size == 0 &&
8255 		    register_is_null(reg))
8256 			return 0;
8257 
8258 		verbose(env, "R%d type=%s ", regno,
8259 			reg_type_str(env, reg->type));
8260 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8261 		return -EACCES;
8262 	}
8263 }
8264 
8265 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8266  * size.
8267  *
8268  * @regno is the register containing the access size. regno-1 is the register
8269  * containing the pointer.
8270  */
8271 static int check_mem_size_reg(struct bpf_verifier_env *env,
8272 			      struct bpf_reg_state *reg, u32 regno,
8273 			      enum bpf_access_type access_type,
8274 			      bool zero_size_allowed,
8275 			      struct bpf_call_arg_meta *meta)
8276 {
8277 	int err;
8278 
8279 	/* This is used to refine r0 return value bounds for helpers
8280 	 * that enforce this value as an upper bound on return values.
8281 	 * See do_refine_retval_range() for helpers that can refine
8282 	 * the return value. C type of helper is u32 so we pull register
8283 	 * bound from umax_value however, if negative verifier errors
8284 	 * out. Only upper bounds can be learned because retval is an
8285 	 * int type and negative retvals are allowed.
8286 	 */
8287 	meta->msize_max_value = reg->umax_value;
8288 
8289 	/* The register is SCALAR_VALUE; the access check happens using
8290 	 * its boundaries. For unprivileged variable accesses, disable
8291 	 * raw mode so that the program is required to initialize all
8292 	 * the memory that the helper could just partially fill up.
8293 	 */
8294 	if (!tnum_is_const(reg->var_off))
8295 		meta = NULL;
8296 
8297 	if (reg->smin_value < 0) {
8298 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8299 			regno);
8300 		return -EACCES;
8301 	}
8302 
8303 	if (reg->umin_value == 0 && !zero_size_allowed) {
8304 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8305 			regno, reg->umin_value, reg->umax_value);
8306 		return -EACCES;
8307 	}
8308 
8309 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8310 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8311 			regno);
8312 		return -EACCES;
8313 	}
8314 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8315 				      access_type, zero_size_allowed, meta);
8316 	if (!err)
8317 		err = mark_chain_precision(env, regno);
8318 	return err;
8319 }
8320 
8321 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8322 			 u32 regno, u32 mem_size)
8323 {
8324 	bool may_be_null = type_may_be_null(reg->type);
8325 	struct bpf_reg_state saved_reg;
8326 	int err;
8327 
8328 	if (register_is_null(reg))
8329 		return 0;
8330 
8331 	/* Assuming that the register contains a value check if the memory
8332 	 * access is safe. Temporarily save and restore the register's state as
8333 	 * the conversion shouldn't be visible to a caller.
8334 	 */
8335 	if (may_be_null) {
8336 		saved_reg = *reg;
8337 		mark_ptr_not_null_reg(reg);
8338 	}
8339 
8340 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8341 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8342 
8343 	if (may_be_null)
8344 		*reg = saved_reg;
8345 
8346 	return err;
8347 }
8348 
8349 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8350 				    u32 regno)
8351 {
8352 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8353 	bool may_be_null = type_may_be_null(mem_reg->type);
8354 	struct bpf_reg_state saved_reg;
8355 	struct bpf_call_arg_meta meta;
8356 	int err;
8357 
8358 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8359 
8360 	memset(&meta, 0, sizeof(meta));
8361 
8362 	if (may_be_null) {
8363 		saved_reg = *mem_reg;
8364 		mark_ptr_not_null_reg(mem_reg);
8365 	}
8366 
8367 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8368 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8369 
8370 	if (may_be_null)
8371 		*mem_reg = saved_reg;
8372 
8373 	return err;
8374 }
8375 
8376 enum {
8377 	PROCESS_SPIN_LOCK = (1 << 0),
8378 	PROCESS_RES_LOCK  = (1 << 1),
8379 	PROCESS_LOCK_IRQ  = (1 << 2),
8380 };
8381 
8382 /* Implementation details:
8383  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8384  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8385  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8386  * Two separate bpf_obj_new will also have different reg->id.
8387  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8388  * clears reg->id after value_or_null->value transition, since the verifier only
8389  * cares about the range of access to valid map value pointer and doesn't care
8390  * about actual address of the map element.
8391  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8392  * reg->id > 0 after value_or_null->value transition. By doing so
8393  * two bpf_map_lookups will be considered two different pointers that
8394  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8395  * returned from bpf_obj_new.
8396  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8397  * dead-locks.
8398  * Since only one bpf_spin_lock is allowed the checks are simpler than
8399  * reg_is_refcounted() logic. The verifier needs to remember only
8400  * one spin_lock instead of array of acquired_refs.
8401  * env->cur_state->active_locks remembers which map value element or allocated
8402  * object got locked and clears it after bpf_spin_unlock.
8403  */
8404 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8405 {
8406 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8407 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8408 	struct bpf_reg_state *reg = reg_state(env, regno);
8409 	struct bpf_verifier_state *cur = env->cur_state;
8410 	bool is_const = tnum_is_const(reg->var_off);
8411 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8412 	u64 val = reg->var_off.value;
8413 	struct bpf_map *map = NULL;
8414 	struct btf *btf = NULL;
8415 	struct btf_record *rec;
8416 	u32 spin_lock_off;
8417 	int err;
8418 
8419 	if (!is_const) {
8420 		verbose(env,
8421 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8422 			regno, lock_str);
8423 		return -EINVAL;
8424 	}
8425 	if (reg->type == PTR_TO_MAP_VALUE) {
8426 		map = reg->map_ptr;
8427 		if (!map->btf) {
8428 			verbose(env,
8429 				"map '%s' has to have BTF in order to use %s_lock\n",
8430 				map->name, lock_str);
8431 			return -EINVAL;
8432 		}
8433 	} else {
8434 		btf = reg->btf;
8435 	}
8436 
8437 	rec = reg_btf_record(reg);
8438 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8439 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8440 			map ? map->name : "kptr", lock_str);
8441 		return -EINVAL;
8442 	}
8443 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8444 	if (spin_lock_off != val + reg->off) {
8445 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8446 			val + reg->off, lock_str, spin_lock_off);
8447 		return -EINVAL;
8448 	}
8449 	if (is_lock) {
8450 		void *ptr;
8451 		int type;
8452 
8453 		if (map)
8454 			ptr = map;
8455 		else
8456 			ptr = btf;
8457 
8458 		if (!is_res_lock && cur->active_locks) {
8459 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8460 				verbose(env,
8461 					"Locking two bpf_spin_locks are not allowed\n");
8462 				return -EINVAL;
8463 			}
8464 		} else if (is_res_lock && cur->active_locks) {
8465 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8466 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8467 				return -EINVAL;
8468 			}
8469 		}
8470 
8471 		if (is_res_lock && is_irq)
8472 			type = REF_TYPE_RES_LOCK_IRQ;
8473 		else if (is_res_lock)
8474 			type = REF_TYPE_RES_LOCK;
8475 		else
8476 			type = REF_TYPE_LOCK;
8477 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8478 		if (err < 0) {
8479 			verbose(env, "Failed to acquire lock state\n");
8480 			return err;
8481 		}
8482 	} else {
8483 		void *ptr;
8484 		int type;
8485 
8486 		if (map)
8487 			ptr = map;
8488 		else
8489 			ptr = btf;
8490 
8491 		if (!cur->active_locks) {
8492 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8493 			return -EINVAL;
8494 		}
8495 
8496 		if (is_res_lock && is_irq)
8497 			type = REF_TYPE_RES_LOCK_IRQ;
8498 		else if (is_res_lock)
8499 			type = REF_TYPE_RES_LOCK;
8500 		else
8501 			type = REF_TYPE_LOCK;
8502 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8503 			verbose(env, "%s_unlock of different lock\n", lock_str);
8504 			return -EINVAL;
8505 		}
8506 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8507 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8508 			return -EINVAL;
8509 		}
8510 		if (release_lock_state(cur, type, reg->id, ptr)) {
8511 			verbose(env, "%s_unlock of different lock\n", lock_str);
8512 			return -EINVAL;
8513 		}
8514 
8515 		invalidate_non_owning_refs(env);
8516 	}
8517 	return 0;
8518 }
8519 
8520 /* Check if @regno is a pointer to a specific field in a map value */
8521 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8522 				   enum btf_field_type field_type)
8523 {
8524 	struct bpf_reg_state *reg = reg_state(env, regno);
8525 	bool is_const = tnum_is_const(reg->var_off);
8526 	struct bpf_map *map = reg->map_ptr;
8527 	u64 val = reg->var_off.value;
8528 	const char *struct_name = btf_field_type_name(field_type);
8529 	int field_off = -1;
8530 
8531 	if (!is_const) {
8532 		verbose(env,
8533 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8534 			regno, struct_name);
8535 		return -EINVAL;
8536 	}
8537 	if (!map->btf) {
8538 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8539 			struct_name);
8540 		return -EINVAL;
8541 	}
8542 	if (!btf_record_has_field(map->record, field_type)) {
8543 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8544 		return -EINVAL;
8545 	}
8546 	switch (field_type) {
8547 	case BPF_TIMER:
8548 		field_off = map->record->timer_off;
8549 		break;
8550 	case BPF_TASK_WORK:
8551 		field_off = map->record->task_work_off;
8552 		break;
8553 	case BPF_WORKQUEUE:
8554 		field_off = map->record->wq_off;
8555 		break;
8556 	default:
8557 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8558 		return -EINVAL;
8559 	}
8560 	if (field_off != val + reg->off) {
8561 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8562 			val + reg->off, struct_name, field_off);
8563 		return -EINVAL;
8564 	}
8565 	return 0;
8566 }
8567 
8568 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8569 			      struct bpf_call_arg_meta *meta)
8570 {
8571 	struct bpf_reg_state *reg = reg_state(env, regno);
8572 	struct bpf_map *map = reg->map_ptr;
8573 	int err;
8574 
8575 	err = check_map_field_pointer(env, regno, BPF_TIMER);
8576 	if (err)
8577 		return err;
8578 
8579 	if (meta->map_ptr) {
8580 		verifier_bug(env, "Two map pointers in a timer helper");
8581 		return -EFAULT;
8582 	}
8583 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8584 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8585 		return -EOPNOTSUPP;
8586 	}
8587 	meta->map_uid = reg->map_uid;
8588 	meta->map_ptr = map;
8589 	return 0;
8590 }
8591 
8592 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8593 			   struct bpf_kfunc_call_arg_meta *meta)
8594 {
8595 	struct bpf_reg_state *reg = reg_state(env, regno);
8596 	struct bpf_map *map = reg->map_ptr;
8597 	int err;
8598 
8599 	err = check_map_field_pointer(env, regno, BPF_WORKQUEUE);
8600 	if (err)
8601 		return err;
8602 
8603 	if (meta->map.ptr) {
8604 		verifier_bug(env, "Two map pointers in a bpf_wq helper");
8605 		return -EFAULT;
8606 	}
8607 
8608 	meta->map.uid = reg->map_uid;
8609 	meta->map.ptr = map;
8610 	return 0;
8611 }
8612 
8613 static int process_task_work_func(struct bpf_verifier_env *env, int regno,
8614 				  struct bpf_kfunc_call_arg_meta *meta)
8615 {
8616 	struct bpf_reg_state *reg = reg_state(env, regno);
8617 	struct bpf_map *map = reg->map_ptr;
8618 	int err;
8619 
8620 	err = check_map_field_pointer(env, regno, BPF_TASK_WORK);
8621 	if (err)
8622 		return err;
8623 
8624 	if (meta->map.ptr) {
8625 		verifier_bug(env, "Two map pointers in a bpf_task_work helper");
8626 		return -EFAULT;
8627 	}
8628 	meta->map.uid = reg->map_uid;
8629 	meta->map.ptr = map;
8630 	return 0;
8631 }
8632 
8633 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8634 			     struct bpf_call_arg_meta *meta)
8635 {
8636 	struct bpf_reg_state *reg = reg_state(env, regno);
8637 	struct btf_field *kptr_field;
8638 	struct bpf_map *map_ptr;
8639 	struct btf_record *rec;
8640 	u32 kptr_off;
8641 
8642 	if (type_is_ptr_alloc_obj(reg->type)) {
8643 		rec = reg_btf_record(reg);
8644 	} else { /* PTR_TO_MAP_VALUE */
8645 		map_ptr = reg->map_ptr;
8646 		if (!map_ptr->btf) {
8647 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8648 				map_ptr->name);
8649 			return -EINVAL;
8650 		}
8651 		rec = map_ptr->record;
8652 		meta->map_ptr = map_ptr;
8653 	}
8654 
8655 	if (!tnum_is_const(reg->var_off)) {
8656 		verbose(env,
8657 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8658 			regno);
8659 		return -EINVAL;
8660 	}
8661 
8662 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8663 		verbose(env, "R%d has no valid kptr\n", regno);
8664 		return -EINVAL;
8665 	}
8666 
8667 	kptr_off = reg->off + reg->var_off.value;
8668 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8669 	if (!kptr_field) {
8670 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8671 		return -EACCES;
8672 	}
8673 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8674 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8675 		return -EACCES;
8676 	}
8677 	meta->kptr_field = kptr_field;
8678 	return 0;
8679 }
8680 
8681 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8682  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8683  *
8684  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8685  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8686  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8687  *
8688  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8689  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8690  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8691  * mutate the view of the dynptr and also possibly destroy it. In the latter
8692  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8693  * memory that dynptr points to.
8694  *
8695  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8696  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8697  * readonly dynptr view yet, hence only the first case is tracked and checked.
8698  *
8699  * This is consistent with how C applies the const modifier to a struct object,
8700  * where the pointer itself inside bpf_dynptr becomes const but not what it
8701  * points to.
8702  *
8703  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8704  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8705  */
8706 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8707 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8708 {
8709 	struct bpf_reg_state *reg = reg_state(env, regno);
8710 	int err;
8711 
8712 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8713 		verbose(env,
8714 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8715 			regno - 1);
8716 		return -EINVAL;
8717 	}
8718 
8719 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8720 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8721 	 */
8722 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8723 		verifier_bug(env, "misconfigured dynptr helper type flags");
8724 		return -EFAULT;
8725 	}
8726 
8727 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8728 	 *		 constructing a mutable bpf_dynptr object.
8729 	 *
8730 	 *		 Currently, this is only possible with PTR_TO_STACK
8731 	 *		 pointing to a region of at least 16 bytes which doesn't
8732 	 *		 contain an existing bpf_dynptr.
8733 	 *
8734 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8735 	 *		 mutated or destroyed. However, the memory it points to
8736 	 *		 may be mutated.
8737 	 *
8738 	 *  None       - Points to a initialized dynptr that can be mutated and
8739 	 *		 destroyed, including mutation of the memory it points
8740 	 *		 to.
8741 	 */
8742 	if (arg_type & MEM_UNINIT) {
8743 		int i;
8744 
8745 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8746 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8747 			return -EINVAL;
8748 		}
8749 
8750 		/* we write BPF_DW bits (8 bytes) at a time */
8751 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8752 			err = check_mem_access(env, insn_idx, regno,
8753 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8754 			if (err)
8755 				return err;
8756 		}
8757 
8758 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8759 	} else /* MEM_RDONLY and None case from above */ {
8760 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8761 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8762 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8763 			return -EINVAL;
8764 		}
8765 
8766 		if (!is_dynptr_reg_valid_init(env, reg)) {
8767 			verbose(env,
8768 				"Expected an initialized dynptr as arg #%d\n",
8769 				regno - 1);
8770 			return -EINVAL;
8771 		}
8772 
8773 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8774 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8775 			verbose(env,
8776 				"Expected a dynptr of type %s as arg #%d\n",
8777 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8778 			return -EINVAL;
8779 		}
8780 
8781 		err = mark_dynptr_read(env, reg);
8782 	}
8783 	return err;
8784 }
8785 
8786 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8787 {
8788 	struct bpf_func_state *state = func(env, reg);
8789 
8790 	return state->stack[spi].spilled_ptr.ref_obj_id;
8791 }
8792 
8793 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8794 {
8795 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8796 }
8797 
8798 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8799 {
8800 	return meta->kfunc_flags & KF_ITER_NEW;
8801 }
8802 
8803 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8804 {
8805 	return meta->kfunc_flags & KF_ITER_NEXT;
8806 }
8807 
8808 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8809 {
8810 	return meta->kfunc_flags & KF_ITER_DESTROY;
8811 }
8812 
8813 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8814 			      const struct btf_param *arg)
8815 {
8816 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8817 	 * kfunc is iter state pointer
8818 	 */
8819 	if (is_iter_kfunc(meta))
8820 		return arg_idx == 0;
8821 
8822 	/* iter passed as an argument to a generic kfunc */
8823 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8824 }
8825 
8826 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8827 			    struct bpf_kfunc_call_arg_meta *meta)
8828 {
8829 	struct bpf_reg_state *reg = reg_state(env, regno);
8830 	const struct btf_type *t;
8831 	int spi, err, i, nr_slots, btf_id;
8832 
8833 	if (reg->type != PTR_TO_STACK) {
8834 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8835 		return -EINVAL;
8836 	}
8837 
8838 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8839 	 * ensures struct convention, so we wouldn't need to do any BTF
8840 	 * validation here. But given iter state can be passed as a parameter
8841 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8842 	 * conservative here.
8843 	 */
8844 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8845 	if (btf_id < 0) {
8846 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8847 		return -EINVAL;
8848 	}
8849 	t = btf_type_by_id(meta->btf, btf_id);
8850 	nr_slots = t->size / BPF_REG_SIZE;
8851 
8852 	if (is_iter_new_kfunc(meta)) {
8853 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8854 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8855 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8856 				iter_type_str(meta->btf, btf_id), regno - 1);
8857 			return -EINVAL;
8858 		}
8859 
8860 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8861 			err = check_mem_access(env, insn_idx, regno,
8862 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8863 			if (err)
8864 				return err;
8865 		}
8866 
8867 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8868 		if (err)
8869 			return err;
8870 	} else {
8871 		/* iter_next() or iter_destroy(), as well as any kfunc
8872 		 * accepting iter argument, expect initialized iter state
8873 		 */
8874 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8875 		switch (err) {
8876 		case 0:
8877 			break;
8878 		case -EINVAL:
8879 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8880 				iter_type_str(meta->btf, btf_id), regno - 1);
8881 			return err;
8882 		case -EPROTO:
8883 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8884 			return err;
8885 		default:
8886 			return err;
8887 		}
8888 
8889 		spi = iter_get_spi(env, reg, nr_slots);
8890 		if (spi < 0)
8891 			return spi;
8892 
8893 		err = mark_iter_read(env, reg, spi, nr_slots);
8894 		if (err)
8895 			return err;
8896 
8897 		/* remember meta->iter info for process_iter_next_call() */
8898 		meta->iter.spi = spi;
8899 		meta->iter.frameno = reg->frameno;
8900 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8901 
8902 		if (is_iter_destroy_kfunc(meta)) {
8903 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8904 			if (err)
8905 				return err;
8906 		}
8907 	}
8908 
8909 	return 0;
8910 }
8911 
8912 /* Look for a previous loop entry at insn_idx: nearest parent state
8913  * stopped at insn_idx with callsites matching those in cur->frame.
8914  */
8915 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8916 						  struct bpf_verifier_state *cur,
8917 						  int insn_idx)
8918 {
8919 	struct bpf_verifier_state_list *sl;
8920 	struct bpf_verifier_state *st;
8921 	struct list_head *pos, *head;
8922 
8923 	/* Explored states are pushed in stack order, most recent states come first */
8924 	head = explored_state(env, insn_idx);
8925 	list_for_each(pos, head) {
8926 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8927 		/* If st->branches != 0 state is a part of current DFS verification path,
8928 		 * hence cur & st for a loop.
8929 		 */
8930 		st = &sl->state;
8931 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8932 		    st->dfs_depth < cur->dfs_depth)
8933 			return st;
8934 	}
8935 
8936 	return NULL;
8937 }
8938 
8939 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8940 static bool regs_exact(const struct bpf_reg_state *rold,
8941 		       const struct bpf_reg_state *rcur,
8942 		       struct bpf_idmap *idmap);
8943 
8944 static void maybe_widen_reg(struct bpf_verifier_env *env,
8945 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8946 			    struct bpf_idmap *idmap)
8947 {
8948 	if (rold->type != SCALAR_VALUE)
8949 		return;
8950 	if (rold->type != rcur->type)
8951 		return;
8952 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8953 		return;
8954 	__mark_reg_unknown(env, rcur);
8955 }
8956 
8957 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8958 				   struct bpf_verifier_state *old,
8959 				   struct bpf_verifier_state *cur)
8960 {
8961 	struct bpf_func_state *fold, *fcur;
8962 	int i, fr, num_slots;
8963 
8964 	reset_idmap_scratch(env);
8965 	for (fr = old->curframe; fr >= 0; fr--) {
8966 		fold = old->frame[fr];
8967 		fcur = cur->frame[fr];
8968 
8969 		for (i = 0; i < MAX_BPF_REG; i++)
8970 			maybe_widen_reg(env,
8971 					&fold->regs[i],
8972 					&fcur->regs[i],
8973 					&env->idmap_scratch);
8974 
8975 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
8976 				fcur->allocated_stack / BPF_REG_SIZE);
8977 		for (i = 0; i < num_slots; i++) {
8978 			if (!is_spilled_reg(&fold->stack[i]) ||
8979 			    !is_spilled_reg(&fcur->stack[i]))
8980 				continue;
8981 
8982 			maybe_widen_reg(env,
8983 					&fold->stack[i].spilled_ptr,
8984 					&fcur->stack[i].spilled_ptr,
8985 					&env->idmap_scratch);
8986 		}
8987 	}
8988 	return 0;
8989 }
8990 
8991 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8992 						 struct bpf_kfunc_call_arg_meta *meta)
8993 {
8994 	int iter_frameno = meta->iter.frameno;
8995 	int iter_spi = meta->iter.spi;
8996 
8997 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8998 }
8999 
9000 /* process_iter_next_call() is called when verifier gets to iterator's next
9001  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
9002  * to it as just "iter_next()" in comments below.
9003  *
9004  * BPF verifier relies on a crucial contract for any iter_next()
9005  * implementation: it should *eventually* return NULL, and once that happens
9006  * it should keep returning NULL. That is, once iterator exhausts elements to
9007  * iterate, it should never reset or spuriously return new elements.
9008  *
9009  * With the assumption of such contract, process_iter_next_call() simulates
9010  * a fork in the verifier state to validate loop logic correctness and safety
9011  * without having to simulate infinite amount of iterations.
9012  *
9013  * In current state, we first assume that iter_next() returned NULL and
9014  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
9015  * conditions we should not form an infinite loop and should eventually reach
9016  * exit.
9017  *
9018  * Besides that, we also fork current state and enqueue it for later
9019  * verification. In a forked state we keep iterator state as ACTIVE
9020  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
9021  * also bump iteration depth to prevent erroneous infinite loop detection
9022  * later on (see iter_active_depths_differ() comment for details). In this
9023  * state we assume that we'll eventually loop back to another iter_next()
9024  * calls (it could be in exactly same location or in some other instruction,
9025  * it doesn't matter, we don't make any unnecessary assumptions about this,
9026  * everything revolves around iterator state in a stack slot, not which
9027  * instruction is calling iter_next()). When that happens, we either will come
9028  * to iter_next() with equivalent state and can conclude that next iteration
9029  * will proceed in exactly the same way as we just verified, so it's safe to
9030  * assume that loop converges. If not, we'll go on another iteration
9031  * simulation with a different input state, until all possible starting states
9032  * are validated or we reach maximum number of instructions limit.
9033  *
9034  * This way, we will either exhaustively discover all possible input states
9035  * that iterator loop can start with and eventually will converge, or we'll
9036  * effectively regress into bounded loop simulation logic and either reach
9037  * maximum number of instructions if loop is not provably convergent, or there
9038  * is some statically known limit on number of iterations (e.g., if there is
9039  * an explicit `if n > 100 then break;` statement somewhere in the loop).
9040  *
9041  * Iteration convergence logic in is_state_visited() relies on exact
9042  * states comparison, which ignores read and precision marks.
9043  * This is necessary because read and precision marks are not finalized
9044  * while in the loop. Exact comparison might preclude convergence for
9045  * simple programs like below:
9046  *
9047  *     i = 0;
9048  *     while(iter_next(&it))
9049  *       i++;
9050  *
9051  * At each iteration step i++ would produce a new distinct state and
9052  * eventually instruction processing limit would be reached.
9053  *
9054  * To avoid such behavior speculatively forget (widen) range for
9055  * imprecise scalar registers, if those registers were not precise at the
9056  * end of the previous iteration and do not match exactly.
9057  *
9058  * This is a conservative heuristic that allows to verify wide range of programs,
9059  * however it precludes verification of programs that conjure an
9060  * imprecise value on the first loop iteration and use it as precise on a second.
9061  * For example, the following safe program would fail to verify:
9062  *
9063  *     struct bpf_num_iter it;
9064  *     int arr[10];
9065  *     int i = 0, a = 0;
9066  *     bpf_iter_num_new(&it, 0, 10);
9067  *     while (bpf_iter_num_next(&it)) {
9068  *       if (a == 0) {
9069  *         a = 1;
9070  *         i = 7; // Because i changed verifier would forget
9071  *                // it's range on second loop entry.
9072  *       } else {
9073  *         arr[i] = 42; // This would fail to verify.
9074  *       }
9075  *     }
9076  *     bpf_iter_num_destroy(&it);
9077  */
9078 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9079 				  struct bpf_kfunc_call_arg_meta *meta)
9080 {
9081 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9082 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9083 	struct bpf_reg_state *cur_iter, *queued_iter;
9084 
9085 	BTF_TYPE_EMIT(struct bpf_iter);
9086 
9087 	cur_iter = get_iter_from_state(cur_st, meta);
9088 
9089 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9090 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9091 		verifier_bug(env, "unexpected iterator state %d (%s)",
9092 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9093 		return -EFAULT;
9094 	}
9095 
9096 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9097 		/* Because iter_next() call is a checkpoint is_state_visitied()
9098 		 * should guarantee parent state with same call sites and insn_idx.
9099 		 */
9100 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9101 		    !same_callsites(cur_st->parent, cur_st)) {
9102 			verifier_bug(env, "bad parent state for iter next call");
9103 			return -EFAULT;
9104 		}
9105 		/* Note cur_st->parent in the call below, it is necessary to skip
9106 		 * checkpoint created for cur_st by is_state_visited()
9107 		 * right at this instruction.
9108 		 */
9109 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9110 		/* branch out active iter state */
9111 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9112 		if (IS_ERR(queued_st))
9113 			return PTR_ERR(queued_st);
9114 
9115 		queued_iter = get_iter_from_state(queued_st, meta);
9116 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9117 		queued_iter->iter.depth++;
9118 		if (prev_st)
9119 			widen_imprecise_scalars(env, prev_st, queued_st);
9120 
9121 		queued_fr = queued_st->frame[queued_st->curframe];
9122 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9123 	}
9124 
9125 	/* switch to DRAINED state, but keep the depth unchanged */
9126 	/* mark current iter state as drained and assume returned NULL */
9127 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9128 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9129 
9130 	return 0;
9131 }
9132 
9133 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9134 {
9135 	return type == ARG_CONST_SIZE ||
9136 	       type == ARG_CONST_SIZE_OR_ZERO;
9137 }
9138 
9139 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9140 {
9141 	return base_type(type) == ARG_PTR_TO_MEM &&
9142 	       type & MEM_UNINIT;
9143 }
9144 
9145 static bool arg_type_is_release(enum bpf_arg_type type)
9146 {
9147 	return type & OBJ_RELEASE;
9148 }
9149 
9150 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9151 {
9152 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9153 }
9154 
9155 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9156 				 const struct bpf_call_arg_meta *meta,
9157 				 enum bpf_arg_type *arg_type)
9158 {
9159 	if (!meta->map_ptr) {
9160 		/* kernel subsystem misconfigured verifier */
9161 		verifier_bug(env, "invalid map_ptr to access map->type");
9162 		return -EFAULT;
9163 	}
9164 
9165 	switch (meta->map_ptr->map_type) {
9166 	case BPF_MAP_TYPE_SOCKMAP:
9167 	case BPF_MAP_TYPE_SOCKHASH:
9168 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9169 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9170 		} else {
9171 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9172 			return -EINVAL;
9173 		}
9174 		break;
9175 	case BPF_MAP_TYPE_BLOOM_FILTER:
9176 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9177 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9178 		break;
9179 	default:
9180 		break;
9181 	}
9182 	return 0;
9183 }
9184 
9185 struct bpf_reg_types {
9186 	const enum bpf_reg_type types[10];
9187 	u32 *btf_id;
9188 };
9189 
9190 static const struct bpf_reg_types sock_types = {
9191 	.types = {
9192 		PTR_TO_SOCK_COMMON,
9193 		PTR_TO_SOCKET,
9194 		PTR_TO_TCP_SOCK,
9195 		PTR_TO_XDP_SOCK,
9196 	},
9197 };
9198 
9199 #ifdef CONFIG_NET
9200 static const struct bpf_reg_types btf_id_sock_common_types = {
9201 	.types = {
9202 		PTR_TO_SOCK_COMMON,
9203 		PTR_TO_SOCKET,
9204 		PTR_TO_TCP_SOCK,
9205 		PTR_TO_XDP_SOCK,
9206 		PTR_TO_BTF_ID,
9207 		PTR_TO_BTF_ID | PTR_TRUSTED,
9208 	},
9209 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9210 };
9211 #endif
9212 
9213 static const struct bpf_reg_types mem_types = {
9214 	.types = {
9215 		PTR_TO_STACK,
9216 		PTR_TO_PACKET,
9217 		PTR_TO_PACKET_META,
9218 		PTR_TO_MAP_KEY,
9219 		PTR_TO_MAP_VALUE,
9220 		PTR_TO_MEM,
9221 		PTR_TO_MEM | MEM_RINGBUF,
9222 		PTR_TO_BUF,
9223 		PTR_TO_BTF_ID | PTR_TRUSTED,
9224 	},
9225 };
9226 
9227 static const struct bpf_reg_types spin_lock_types = {
9228 	.types = {
9229 		PTR_TO_MAP_VALUE,
9230 		PTR_TO_BTF_ID | MEM_ALLOC,
9231 	}
9232 };
9233 
9234 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9235 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9236 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9237 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9238 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9239 static const struct bpf_reg_types btf_ptr_types = {
9240 	.types = {
9241 		PTR_TO_BTF_ID,
9242 		PTR_TO_BTF_ID | PTR_TRUSTED,
9243 		PTR_TO_BTF_ID | MEM_RCU,
9244 	},
9245 };
9246 static const struct bpf_reg_types percpu_btf_ptr_types = {
9247 	.types = {
9248 		PTR_TO_BTF_ID | MEM_PERCPU,
9249 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9250 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9251 	}
9252 };
9253 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9254 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9255 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9256 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9257 static const struct bpf_reg_types kptr_xchg_dest_types = {
9258 	.types = {
9259 		PTR_TO_MAP_VALUE,
9260 		PTR_TO_BTF_ID | MEM_ALLOC
9261 	}
9262 };
9263 static const struct bpf_reg_types dynptr_types = {
9264 	.types = {
9265 		PTR_TO_STACK,
9266 		CONST_PTR_TO_DYNPTR,
9267 	}
9268 };
9269 
9270 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9271 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9272 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9273 	[ARG_CONST_SIZE]		= &scalar_types,
9274 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9275 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9276 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9277 	[ARG_PTR_TO_CTX]		= &context_types,
9278 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9279 #ifdef CONFIG_NET
9280 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9281 #endif
9282 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9283 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9284 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9285 	[ARG_PTR_TO_MEM]		= &mem_types,
9286 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9287 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9288 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9289 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9290 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9291 	[ARG_PTR_TO_TIMER]		= &timer_types,
9292 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9293 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9294 };
9295 
9296 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9297 			  enum bpf_arg_type arg_type,
9298 			  const u32 *arg_btf_id,
9299 			  struct bpf_call_arg_meta *meta)
9300 {
9301 	struct bpf_reg_state *reg = reg_state(env, regno);
9302 	enum bpf_reg_type expected, type = reg->type;
9303 	const struct bpf_reg_types *compatible;
9304 	int i, j;
9305 
9306 	compatible = compatible_reg_types[base_type(arg_type)];
9307 	if (!compatible) {
9308 		verifier_bug(env, "unsupported arg type %d", arg_type);
9309 		return -EFAULT;
9310 	}
9311 
9312 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9313 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9314 	 *
9315 	 * Same for MAYBE_NULL:
9316 	 *
9317 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9318 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9319 	 *
9320 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9321 	 *
9322 	 * Therefore we fold these flags depending on the arg_type before comparison.
9323 	 */
9324 	if (arg_type & MEM_RDONLY)
9325 		type &= ~MEM_RDONLY;
9326 	if (arg_type & PTR_MAYBE_NULL)
9327 		type &= ~PTR_MAYBE_NULL;
9328 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9329 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9330 
9331 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9332 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9333 		type &= ~MEM_ALLOC;
9334 		type &= ~MEM_PERCPU;
9335 	}
9336 
9337 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9338 		expected = compatible->types[i];
9339 		if (expected == NOT_INIT)
9340 			break;
9341 
9342 		if (type == expected)
9343 			goto found;
9344 	}
9345 
9346 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9347 	for (j = 0; j + 1 < i; j++)
9348 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9349 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9350 	return -EACCES;
9351 
9352 found:
9353 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9354 		return 0;
9355 
9356 	if (compatible == &mem_types) {
9357 		if (!(arg_type & MEM_RDONLY)) {
9358 			verbose(env,
9359 				"%s() may write into memory pointed by R%d type=%s\n",
9360 				func_id_name(meta->func_id),
9361 				regno, reg_type_str(env, reg->type));
9362 			return -EACCES;
9363 		}
9364 		return 0;
9365 	}
9366 
9367 	switch ((int)reg->type) {
9368 	case PTR_TO_BTF_ID:
9369 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9370 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9371 	case PTR_TO_BTF_ID | MEM_RCU:
9372 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9373 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9374 	{
9375 		/* For bpf_sk_release, it needs to match against first member
9376 		 * 'struct sock_common', hence make an exception for it. This
9377 		 * allows bpf_sk_release to work for multiple socket types.
9378 		 */
9379 		bool strict_type_match = arg_type_is_release(arg_type) &&
9380 					 meta->func_id != BPF_FUNC_sk_release;
9381 
9382 		if (type_may_be_null(reg->type) &&
9383 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9384 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9385 			return -EACCES;
9386 		}
9387 
9388 		if (!arg_btf_id) {
9389 			if (!compatible->btf_id) {
9390 				verifier_bug(env, "missing arg compatible BTF ID");
9391 				return -EFAULT;
9392 			}
9393 			arg_btf_id = compatible->btf_id;
9394 		}
9395 
9396 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9397 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9398 				return -EACCES;
9399 		} else {
9400 			if (arg_btf_id == BPF_PTR_POISON) {
9401 				verbose(env, "verifier internal error:");
9402 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9403 					regno);
9404 				return -EACCES;
9405 			}
9406 
9407 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9408 						  btf_vmlinux, *arg_btf_id,
9409 						  strict_type_match)) {
9410 				verbose(env, "R%d is of type %s but %s is expected\n",
9411 					regno, btf_type_name(reg->btf, reg->btf_id),
9412 					btf_type_name(btf_vmlinux, *arg_btf_id));
9413 				return -EACCES;
9414 			}
9415 		}
9416 		break;
9417 	}
9418 	case PTR_TO_BTF_ID | MEM_ALLOC:
9419 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9420 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9421 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9422 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9423 			return -EFAULT;
9424 		}
9425 		/* Check if local kptr in src arg matches kptr in dst arg */
9426 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9427 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9428 				return -EACCES;
9429 		}
9430 		break;
9431 	case PTR_TO_BTF_ID | MEM_PERCPU:
9432 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9433 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9434 		/* Handled by helper specific checks */
9435 		break;
9436 	default:
9437 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9438 		return -EFAULT;
9439 	}
9440 	return 0;
9441 }
9442 
9443 static struct btf_field *
9444 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9445 {
9446 	struct btf_field *field;
9447 	struct btf_record *rec;
9448 
9449 	rec = reg_btf_record(reg);
9450 	if (!rec)
9451 		return NULL;
9452 
9453 	field = btf_record_find(rec, off, fields);
9454 	if (!field)
9455 		return NULL;
9456 
9457 	return field;
9458 }
9459 
9460 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9461 				  const struct bpf_reg_state *reg, int regno,
9462 				  enum bpf_arg_type arg_type)
9463 {
9464 	u32 type = reg->type;
9465 
9466 	/* When referenced register is passed to release function, its fixed
9467 	 * offset must be 0.
9468 	 *
9469 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9470 	 * meta->release_regno.
9471 	 */
9472 	if (arg_type_is_release(arg_type)) {
9473 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9474 		 * may not directly point to the object being released, but to
9475 		 * dynptr pointing to such object, which might be at some offset
9476 		 * on the stack. In that case, we simply to fallback to the
9477 		 * default handling.
9478 		 */
9479 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9480 			return 0;
9481 
9482 		/* Doing check_ptr_off_reg check for the offset will catch this
9483 		 * because fixed_off_ok is false, but checking here allows us
9484 		 * to give the user a better error message.
9485 		 */
9486 		if (reg->off) {
9487 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9488 				regno);
9489 			return -EINVAL;
9490 		}
9491 		return __check_ptr_off_reg(env, reg, regno, false);
9492 	}
9493 
9494 	switch (type) {
9495 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9496 	case PTR_TO_STACK:
9497 	case PTR_TO_PACKET:
9498 	case PTR_TO_PACKET_META:
9499 	case PTR_TO_MAP_KEY:
9500 	case PTR_TO_MAP_VALUE:
9501 	case PTR_TO_MEM:
9502 	case PTR_TO_MEM | MEM_RDONLY:
9503 	case PTR_TO_MEM | MEM_RINGBUF:
9504 	case PTR_TO_BUF:
9505 	case PTR_TO_BUF | MEM_RDONLY:
9506 	case PTR_TO_ARENA:
9507 	case SCALAR_VALUE:
9508 		return 0;
9509 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9510 	 * fixed offset.
9511 	 */
9512 	case PTR_TO_BTF_ID:
9513 	case PTR_TO_BTF_ID | MEM_ALLOC:
9514 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9515 	case PTR_TO_BTF_ID | MEM_RCU:
9516 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9517 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9518 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9519 		 * its fixed offset must be 0. In the other cases, fixed offset
9520 		 * can be non-zero. This was already checked above. So pass
9521 		 * fixed_off_ok as true to allow fixed offset for all other
9522 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9523 		 * still need to do checks instead of returning.
9524 		 */
9525 		return __check_ptr_off_reg(env, reg, regno, true);
9526 	default:
9527 		return __check_ptr_off_reg(env, reg, regno, false);
9528 	}
9529 }
9530 
9531 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9532 						const struct bpf_func_proto *fn,
9533 						struct bpf_reg_state *regs)
9534 {
9535 	struct bpf_reg_state *state = NULL;
9536 	int i;
9537 
9538 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9539 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9540 			if (state) {
9541 				verbose(env, "verifier internal error: multiple dynptr args\n");
9542 				return NULL;
9543 			}
9544 			state = &regs[BPF_REG_1 + i];
9545 		}
9546 
9547 	if (!state)
9548 		verbose(env, "verifier internal error: no dynptr arg found\n");
9549 
9550 	return state;
9551 }
9552 
9553 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9554 {
9555 	struct bpf_func_state *state = func(env, reg);
9556 	int spi;
9557 
9558 	if (reg->type == CONST_PTR_TO_DYNPTR)
9559 		return reg->id;
9560 	spi = dynptr_get_spi(env, reg);
9561 	if (spi < 0)
9562 		return spi;
9563 	return state->stack[spi].spilled_ptr.id;
9564 }
9565 
9566 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9567 {
9568 	struct bpf_func_state *state = func(env, reg);
9569 	int spi;
9570 
9571 	if (reg->type == CONST_PTR_TO_DYNPTR)
9572 		return reg->ref_obj_id;
9573 	spi = dynptr_get_spi(env, reg);
9574 	if (spi < 0)
9575 		return spi;
9576 	return state->stack[spi].spilled_ptr.ref_obj_id;
9577 }
9578 
9579 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9580 					    struct bpf_reg_state *reg)
9581 {
9582 	struct bpf_func_state *state = func(env, reg);
9583 	int spi;
9584 
9585 	if (reg->type == CONST_PTR_TO_DYNPTR)
9586 		return reg->dynptr.type;
9587 
9588 	spi = __get_spi(reg->off);
9589 	if (spi < 0) {
9590 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9591 		return BPF_DYNPTR_TYPE_INVALID;
9592 	}
9593 
9594 	return state->stack[spi].spilled_ptr.dynptr.type;
9595 }
9596 
9597 static int check_reg_const_str(struct bpf_verifier_env *env,
9598 			       struct bpf_reg_state *reg, u32 regno)
9599 {
9600 	struct bpf_map *map = reg->map_ptr;
9601 	int err;
9602 	int map_off;
9603 	u64 map_addr;
9604 	char *str_ptr;
9605 
9606 	if (reg->type != PTR_TO_MAP_VALUE)
9607 		return -EINVAL;
9608 
9609 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9610 		verbose(env, "R%d points to insn_array map which cannot be used as const string\n", regno);
9611 		return -EACCES;
9612 	}
9613 
9614 	if (!bpf_map_is_rdonly(map)) {
9615 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9616 		return -EACCES;
9617 	}
9618 
9619 	if (!tnum_is_const(reg->var_off)) {
9620 		verbose(env, "R%d is not a constant address'\n", regno);
9621 		return -EACCES;
9622 	}
9623 
9624 	if (!map->ops->map_direct_value_addr) {
9625 		verbose(env, "no direct value access support for this map type\n");
9626 		return -EACCES;
9627 	}
9628 
9629 	err = check_map_access(env, regno, reg->off,
9630 			       map->value_size - reg->off, false,
9631 			       ACCESS_HELPER);
9632 	if (err)
9633 		return err;
9634 
9635 	map_off = reg->off + reg->var_off.value;
9636 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9637 	if (err) {
9638 		verbose(env, "direct value access on string failed\n");
9639 		return err;
9640 	}
9641 
9642 	str_ptr = (char *)(long)(map_addr);
9643 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9644 		verbose(env, "string is not zero-terminated\n");
9645 		return -EINVAL;
9646 	}
9647 	return 0;
9648 }
9649 
9650 /* Returns constant key value in `value` if possible, else negative error */
9651 static int get_constant_map_key(struct bpf_verifier_env *env,
9652 				struct bpf_reg_state *key,
9653 				u32 key_size,
9654 				s64 *value)
9655 {
9656 	struct bpf_func_state *state = func(env, key);
9657 	struct bpf_reg_state *reg;
9658 	int slot, spi, off;
9659 	int spill_size = 0;
9660 	int zero_size = 0;
9661 	int stack_off;
9662 	int i, err;
9663 	u8 *stype;
9664 
9665 	if (!env->bpf_capable)
9666 		return -EOPNOTSUPP;
9667 	if (key->type != PTR_TO_STACK)
9668 		return -EOPNOTSUPP;
9669 	if (!tnum_is_const(key->var_off))
9670 		return -EOPNOTSUPP;
9671 
9672 	stack_off = key->off + key->var_off.value;
9673 	slot = -stack_off - 1;
9674 	spi = slot / BPF_REG_SIZE;
9675 	off = slot % BPF_REG_SIZE;
9676 	stype = state->stack[spi].slot_type;
9677 
9678 	/* First handle precisely tracked STACK_ZERO */
9679 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9680 		zero_size++;
9681 	if (zero_size >= key_size) {
9682 		*value = 0;
9683 		return 0;
9684 	}
9685 
9686 	/* Check that stack contains a scalar spill of expected size */
9687 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9688 		return -EOPNOTSUPP;
9689 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9690 		spill_size++;
9691 	if (spill_size != key_size)
9692 		return -EOPNOTSUPP;
9693 
9694 	reg = &state->stack[spi].spilled_ptr;
9695 	if (!tnum_is_const(reg->var_off))
9696 		/* Stack value not statically known */
9697 		return -EOPNOTSUPP;
9698 
9699 	/* We are relying on a constant value. So mark as precise
9700 	 * to prevent pruning on it.
9701 	 */
9702 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9703 	err = mark_chain_precision_batch(env, env->cur_state);
9704 	if (err < 0)
9705 		return err;
9706 
9707 	*value = reg->var_off.value;
9708 	return 0;
9709 }
9710 
9711 static bool can_elide_value_nullness(enum bpf_map_type type);
9712 
9713 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9714 			  struct bpf_call_arg_meta *meta,
9715 			  const struct bpf_func_proto *fn,
9716 			  int insn_idx)
9717 {
9718 	u32 regno = BPF_REG_1 + arg;
9719 	struct bpf_reg_state *reg = reg_state(env, regno);
9720 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9721 	enum bpf_reg_type type = reg->type;
9722 	u32 *arg_btf_id = NULL;
9723 	u32 key_size;
9724 	int err = 0;
9725 
9726 	if (arg_type == ARG_DONTCARE)
9727 		return 0;
9728 
9729 	err = check_reg_arg(env, regno, SRC_OP);
9730 	if (err)
9731 		return err;
9732 
9733 	if (arg_type == ARG_ANYTHING) {
9734 		if (is_pointer_value(env, regno)) {
9735 			verbose(env, "R%d leaks addr into helper function\n",
9736 				regno);
9737 			return -EACCES;
9738 		}
9739 		return 0;
9740 	}
9741 
9742 	if (type_is_pkt_pointer(type) &&
9743 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9744 		verbose(env, "helper access to the packet is not allowed\n");
9745 		return -EACCES;
9746 	}
9747 
9748 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9749 		err = resolve_map_arg_type(env, meta, &arg_type);
9750 		if (err)
9751 			return err;
9752 	}
9753 
9754 	if (register_is_null(reg) && type_may_be_null(arg_type))
9755 		/* A NULL register has a SCALAR_VALUE type, so skip
9756 		 * type checking.
9757 		 */
9758 		goto skip_type_check;
9759 
9760 	/* arg_btf_id and arg_size are in a union. */
9761 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9762 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9763 		arg_btf_id = fn->arg_btf_id[arg];
9764 
9765 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9766 	if (err)
9767 		return err;
9768 
9769 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9770 	if (err)
9771 		return err;
9772 
9773 skip_type_check:
9774 	if (arg_type_is_release(arg_type)) {
9775 		if (arg_type_is_dynptr(arg_type)) {
9776 			struct bpf_func_state *state = func(env, reg);
9777 			int spi;
9778 
9779 			/* Only dynptr created on stack can be released, thus
9780 			 * the get_spi and stack state checks for spilled_ptr
9781 			 * should only be done before process_dynptr_func for
9782 			 * PTR_TO_STACK.
9783 			 */
9784 			if (reg->type == PTR_TO_STACK) {
9785 				spi = dynptr_get_spi(env, reg);
9786 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9787 					verbose(env, "arg %d is an unacquired reference\n", regno);
9788 					return -EINVAL;
9789 				}
9790 			} else {
9791 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9792 				return -EINVAL;
9793 			}
9794 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9795 			verbose(env, "R%d must be referenced when passed to release function\n",
9796 				regno);
9797 			return -EINVAL;
9798 		}
9799 		if (meta->release_regno) {
9800 			verifier_bug(env, "more than one release argument");
9801 			return -EFAULT;
9802 		}
9803 		meta->release_regno = regno;
9804 	}
9805 
9806 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9807 		if (meta->ref_obj_id) {
9808 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9809 				regno, reg->ref_obj_id,
9810 				meta->ref_obj_id);
9811 			return -EACCES;
9812 		}
9813 		meta->ref_obj_id = reg->ref_obj_id;
9814 	}
9815 
9816 	switch (base_type(arg_type)) {
9817 	case ARG_CONST_MAP_PTR:
9818 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9819 		if (meta->map_ptr) {
9820 			/* Use map_uid (which is unique id of inner map) to reject:
9821 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9822 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9823 			 * if (inner_map1 && inner_map2) {
9824 			 *     timer = bpf_map_lookup_elem(inner_map1);
9825 			 *     if (timer)
9826 			 *         // mismatch would have been allowed
9827 			 *         bpf_timer_init(timer, inner_map2);
9828 			 * }
9829 			 *
9830 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9831 			 */
9832 			if (meta->map_ptr != reg->map_ptr ||
9833 			    meta->map_uid != reg->map_uid) {
9834 				verbose(env,
9835 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9836 					meta->map_uid, reg->map_uid);
9837 				return -EINVAL;
9838 			}
9839 		}
9840 		meta->map_ptr = reg->map_ptr;
9841 		meta->map_uid = reg->map_uid;
9842 		break;
9843 	case ARG_PTR_TO_MAP_KEY:
9844 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9845 		 * check that [key, key + map->key_size) are within
9846 		 * stack limits and initialized
9847 		 */
9848 		if (!meta->map_ptr) {
9849 			/* in function declaration map_ptr must come before
9850 			 * map_key, so that it's verified and known before
9851 			 * we have to check map_key here. Otherwise it means
9852 			 * that kernel subsystem misconfigured verifier
9853 			 */
9854 			verifier_bug(env, "invalid map_ptr to access map->key");
9855 			return -EFAULT;
9856 		}
9857 		key_size = meta->map_ptr->key_size;
9858 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9859 		if (err)
9860 			return err;
9861 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9862 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9863 			if (err < 0) {
9864 				meta->const_map_key = -1;
9865 				if (err == -EOPNOTSUPP)
9866 					err = 0;
9867 				else
9868 					return err;
9869 			}
9870 		}
9871 		break;
9872 	case ARG_PTR_TO_MAP_VALUE:
9873 		if (type_may_be_null(arg_type) && register_is_null(reg))
9874 			return 0;
9875 
9876 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9877 		 * check [value, value + map->value_size) validity
9878 		 */
9879 		if (!meta->map_ptr) {
9880 			/* kernel subsystem misconfigured verifier */
9881 			verifier_bug(env, "invalid map_ptr to access map->value");
9882 			return -EFAULT;
9883 		}
9884 		meta->raw_mode = arg_type & MEM_UNINIT;
9885 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9886 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9887 					      false, meta);
9888 		break;
9889 	case ARG_PTR_TO_PERCPU_BTF_ID:
9890 		if (!reg->btf_id) {
9891 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9892 			return -EACCES;
9893 		}
9894 		meta->ret_btf = reg->btf;
9895 		meta->ret_btf_id = reg->btf_id;
9896 		break;
9897 	case ARG_PTR_TO_SPIN_LOCK:
9898 		if (in_rbtree_lock_required_cb(env)) {
9899 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9900 			return -EACCES;
9901 		}
9902 		if (meta->func_id == BPF_FUNC_spin_lock) {
9903 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9904 			if (err)
9905 				return err;
9906 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9907 			err = process_spin_lock(env, regno, 0);
9908 			if (err)
9909 				return err;
9910 		} else {
9911 			verifier_bug(env, "spin lock arg on unexpected helper");
9912 			return -EFAULT;
9913 		}
9914 		break;
9915 	case ARG_PTR_TO_TIMER:
9916 		err = process_timer_func(env, regno, meta);
9917 		if (err)
9918 			return err;
9919 		break;
9920 	case ARG_PTR_TO_FUNC:
9921 		meta->subprogno = reg->subprogno;
9922 		break;
9923 	case ARG_PTR_TO_MEM:
9924 		/* The access to this pointer is only checked when we hit the
9925 		 * next is_mem_size argument below.
9926 		 */
9927 		meta->raw_mode = arg_type & MEM_UNINIT;
9928 		if (arg_type & MEM_FIXED_SIZE) {
9929 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9930 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9931 						      false, meta);
9932 			if (err)
9933 				return err;
9934 			if (arg_type & MEM_ALIGNED)
9935 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9936 		}
9937 		break;
9938 	case ARG_CONST_SIZE:
9939 		err = check_mem_size_reg(env, reg, regno,
9940 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9941 					 BPF_WRITE : BPF_READ,
9942 					 false, meta);
9943 		break;
9944 	case ARG_CONST_SIZE_OR_ZERO:
9945 		err = check_mem_size_reg(env, reg, regno,
9946 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9947 					 BPF_WRITE : BPF_READ,
9948 					 true, meta);
9949 		break;
9950 	case ARG_PTR_TO_DYNPTR:
9951 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9952 		if (err)
9953 			return err;
9954 		break;
9955 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9956 		if (!tnum_is_const(reg->var_off)) {
9957 			verbose(env, "R%d is not a known constant'\n",
9958 				regno);
9959 			return -EACCES;
9960 		}
9961 		meta->mem_size = reg->var_off.value;
9962 		err = mark_chain_precision(env, regno);
9963 		if (err)
9964 			return err;
9965 		break;
9966 	case ARG_PTR_TO_CONST_STR:
9967 	{
9968 		err = check_reg_const_str(env, reg, regno);
9969 		if (err)
9970 			return err;
9971 		break;
9972 	}
9973 	case ARG_KPTR_XCHG_DEST:
9974 		err = process_kptr_func(env, regno, meta);
9975 		if (err)
9976 			return err;
9977 		break;
9978 	}
9979 
9980 	return err;
9981 }
9982 
9983 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9984 {
9985 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9986 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9987 
9988 	if (func_id != BPF_FUNC_map_update_elem &&
9989 	    func_id != BPF_FUNC_map_delete_elem)
9990 		return false;
9991 
9992 	/* It's not possible to get access to a locked struct sock in these
9993 	 * contexts, so updating is safe.
9994 	 */
9995 	switch (type) {
9996 	case BPF_PROG_TYPE_TRACING:
9997 		if (eatype == BPF_TRACE_ITER)
9998 			return true;
9999 		break;
10000 	case BPF_PROG_TYPE_SOCK_OPS:
10001 		/* map_update allowed only via dedicated helpers with event type checks */
10002 		if (func_id == BPF_FUNC_map_delete_elem)
10003 			return true;
10004 		break;
10005 	case BPF_PROG_TYPE_SOCKET_FILTER:
10006 	case BPF_PROG_TYPE_SCHED_CLS:
10007 	case BPF_PROG_TYPE_SCHED_ACT:
10008 	case BPF_PROG_TYPE_XDP:
10009 	case BPF_PROG_TYPE_SK_REUSEPORT:
10010 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
10011 	case BPF_PROG_TYPE_SK_LOOKUP:
10012 		return true;
10013 	default:
10014 		break;
10015 	}
10016 
10017 	verbose(env, "cannot update sockmap in this context\n");
10018 	return false;
10019 }
10020 
10021 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10022 {
10023 	return env->prog->jit_requested &&
10024 	       bpf_jit_supports_subprog_tailcalls();
10025 }
10026 
10027 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10028 					struct bpf_map *map, int func_id)
10029 {
10030 	if (!map)
10031 		return 0;
10032 
10033 	/* We need a two way check, first is from map perspective ... */
10034 	switch (map->map_type) {
10035 	case BPF_MAP_TYPE_PROG_ARRAY:
10036 		if (func_id != BPF_FUNC_tail_call)
10037 			goto error;
10038 		break;
10039 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10040 		if (func_id != BPF_FUNC_perf_event_read &&
10041 		    func_id != BPF_FUNC_perf_event_output &&
10042 		    func_id != BPF_FUNC_skb_output &&
10043 		    func_id != BPF_FUNC_perf_event_read_value &&
10044 		    func_id != BPF_FUNC_xdp_output)
10045 			goto error;
10046 		break;
10047 	case BPF_MAP_TYPE_RINGBUF:
10048 		if (func_id != BPF_FUNC_ringbuf_output &&
10049 		    func_id != BPF_FUNC_ringbuf_reserve &&
10050 		    func_id != BPF_FUNC_ringbuf_query &&
10051 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10052 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10053 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10054 			goto error;
10055 		break;
10056 	case BPF_MAP_TYPE_USER_RINGBUF:
10057 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10058 			goto error;
10059 		break;
10060 	case BPF_MAP_TYPE_STACK_TRACE:
10061 		if (func_id != BPF_FUNC_get_stackid)
10062 			goto error;
10063 		break;
10064 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10065 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10066 		    func_id != BPF_FUNC_current_task_under_cgroup)
10067 			goto error;
10068 		break;
10069 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10070 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10071 		if (func_id != BPF_FUNC_get_local_storage)
10072 			goto error;
10073 		break;
10074 	case BPF_MAP_TYPE_DEVMAP:
10075 	case BPF_MAP_TYPE_DEVMAP_HASH:
10076 		if (func_id != BPF_FUNC_redirect_map &&
10077 		    func_id != BPF_FUNC_map_lookup_elem)
10078 			goto error;
10079 		break;
10080 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10081 	 * appear.
10082 	 */
10083 	case BPF_MAP_TYPE_CPUMAP:
10084 		if (func_id != BPF_FUNC_redirect_map)
10085 			goto error;
10086 		break;
10087 	case BPF_MAP_TYPE_XSKMAP:
10088 		if (func_id != BPF_FUNC_redirect_map &&
10089 		    func_id != BPF_FUNC_map_lookup_elem)
10090 			goto error;
10091 		break;
10092 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10093 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10094 		if (func_id != BPF_FUNC_map_lookup_elem)
10095 			goto error;
10096 		break;
10097 	case BPF_MAP_TYPE_SOCKMAP:
10098 		if (func_id != BPF_FUNC_sk_redirect_map &&
10099 		    func_id != BPF_FUNC_sock_map_update &&
10100 		    func_id != BPF_FUNC_msg_redirect_map &&
10101 		    func_id != BPF_FUNC_sk_select_reuseport &&
10102 		    func_id != BPF_FUNC_map_lookup_elem &&
10103 		    !may_update_sockmap(env, func_id))
10104 			goto error;
10105 		break;
10106 	case BPF_MAP_TYPE_SOCKHASH:
10107 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10108 		    func_id != BPF_FUNC_sock_hash_update &&
10109 		    func_id != BPF_FUNC_msg_redirect_hash &&
10110 		    func_id != BPF_FUNC_sk_select_reuseport &&
10111 		    func_id != BPF_FUNC_map_lookup_elem &&
10112 		    !may_update_sockmap(env, func_id))
10113 			goto error;
10114 		break;
10115 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10116 		if (func_id != BPF_FUNC_sk_select_reuseport)
10117 			goto error;
10118 		break;
10119 	case BPF_MAP_TYPE_QUEUE:
10120 	case BPF_MAP_TYPE_STACK:
10121 		if (func_id != BPF_FUNC_map_peek_elem &&
10122 		    func_id != BPF_FUNC_map_pop_elem &&
10123 		    func_id != BPF_FUNC_map_push_elem)
10124 			goto error;
10125 		break;
10126 	case BPF_MAP_TYPE_SK_STORAGE:
10127 		if (func_id != BPF_FUNC_sk_storage_get &&
10128 		    func_id != BPF_FUNC_sk_storage_delete &&
10129 		    func_id != BPF_FUNC_kptr_xchg)
10130 			goto error;
10131 		break;
10132 	case BPF_MAP_TYPE_INODE_STORAGE:
10133 		if (func_id != BPF_FUNC_inode_storage_get &&
10134 		    func_id != BPF_FUNC_inode_storage_delete &&
10135 		    func_id != BPF_FUNC_kptr_xchg)
10136 			goto error;
10137 		break;
10138 	case BPF_MAP_TYPE_TASK_STORAGE:
10139 		if (func_id != BPF_FUNC_task_storage_get &&
10140 		    func_id != BPF_FUNC_task_storage_delete &&
10141 		    func_id != BPF_FUNC_kptr_xchg)
10142 			goto error;
10143 		break;
10144 	case BPF_MAP_TYPE_CGRP_STORAGE:
10145 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10146 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10147 		    func_id != BPF_FUNC_kptr_xchg)
10148 			goto error;
10149 		break;
10150 	case BPF_MAP_TYPE_BLOOM_FILTER:
10151 		if (func_id != BPF_FUNC_map_peek_elem &&
10152 		    func_id != BPF_FUNC_map_push_elem)
10153 			goto error;
10154 		break;
10155 	case BPF_MAP_TYPE_INSN_ARRAY:
10156 		goto error;
10157 	default:
10158 		break;
10159 	}
10160 
10161 	/* ... and second from the function itself. */
10162 	switch (func_id) {
10163 	case BPF_FUNC_tail_call:
10164 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10165 			goto error;
10166 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10167 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10168 			return -EINVAL;
10169 		}
10170 		break;
10171 	case BPF_FUNC_perf_event_read:
10172 	case BPF_FUNC_perf_event_output:
10173 	case BPF_FUNC_perf_event_read_value:
10174 	case BPF_FUNC_skb_output:
10175 	case BPF_FUNC_xdp_output:
10176 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10177 			goto error;
10178 		break;
10179 	case BPF_FUNC_ringbuf_output:
10180 	case BPF_FUNC_ringbuf_reserve:
10181 	case BPF_FUNC_ringbuf_query:
10182 	case BPF_FUNC_ringbuf_reserve_dynptr:
10183 	case BPF_FUNC_ringbuf_submit_dynptr:
10184 	case BPF_FUNC_ringbuf_discard_dynptr:
10185 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10186 			goto error;
10187 		break;
10188 	case BPF_FUNC_user_ringbuf_drain:
10189 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10190 			goto error;
10191 		break;
10192 	case BPF_FUNC_get_stackid:
10193 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10194 			goto error;
10195 		break;
10196 	case BPF_FUNC_current_task_under_cgroup:
10197 	case BPF_FUNC_skb_under_cgroup:
10198 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10199 			goto error;
10200 		break;
10201 	case BPF_FUNC_redirect_map:
10202 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10203 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10204 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10205 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10206 			goto error;
10207 		break;
10208 	case BPF_FUNC_sk_redirect_map:
10209 	case BPF_FUNC_msg_redirect_map:
10210 	case BPF_FUNC_sock_map_update:
10211 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10212 			goto error;
10213 		break;
10214 	case BPF_FUNC_sk_redirect_hash:
10215 	case BPF_FUNC_msg_redirect_hash:
10216 	case BPF_FUNC_sock_hash_update:
10217 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10218 			goto error;
10219 		break;
10220 	case BPF_FUNC_get_local_storage:
10221 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10222 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10223 			goto error;
10224 		break;
10225 	case BPF_FUNC_sk_select_reuseport:
10226 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10227 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10228 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10229 			goto error;
10230 		break;
10231 	case BPF_FUNC_map_pop_elem:
10232 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10233 		    map->map_type != BPF_MAP_TYPE_STACK)
10234 			goto error;
10235 		break;
10236 	case BPF_FUNC_map_peek_elem:
10237 	case BPF_FUNC_map_push_elem:
10238 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10239 		    map->map_type != BPF_MAP_TYPE_STACK &&
10240 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10241 			goto error;
10242 		break;
10243 	case BPF_FUNC_map_lookup_percpu_elem:
10244 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10245 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10246 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10247 			goto error;
10248 		break;
10249 	case BPF_FUNC_sk_storage_get:
10250 	case BPF_FUNC_sk_storage_delete:
10251 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10252 			goto error;
10253 		break;
10254 	case BPF_FUNC_inode_storage_get:
10255 	case BPF_FUNC_inode_storage_delete:
10256 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10257 			goto error;
10258 		break;
10259 	case BPF_FUNC_task_storage_get:
10260 	case BPF_FUNC_task_storage_delete:
10261 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10262 			goto error;
10263 		break;
10264 	case BPF_FUNC_cgrp_storage_get:
10265 	case BPF_FUNC_cgrp_storage_delete:
10266 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10267 			goto error;
10268 		break;
10269 	default:
10270 		break;
10271 	}
10272 
10273 	return 0;
10274 error:
10275 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10276 		map->map_type, func_id_name(func_id), func_id);
10277 	return -EINVAL;
10278 }
10279 
10280 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10281 {
10282 	int count = 0;
10283 
10284 	if (arg_type_is_raw_mem(fn->arg1_type))
10285 		count++;
10286 	if (arg_type_is_raw_mem(fn->arg2_type))
10287 		count++;
10288 	if (arg_type_is_raw_mem(fn->arg3_type))
10289 		count++;
10290 	if (arg_type_is_raw_mem(fn->arg4_type))
10291 		count++;
10292 	if (arg_type_is_raw_mem(fn->arg5_type))
10293 		count++;
10294 
10295 	/* We only support one arg being in raw mode at the moment,
10296 	 * which is sufficient for the helper functions we have
10297 	 * right now.
10298 	 */
10299 	return count <= 1;
10300 }
10301 
10302 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10303 {
10304 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10305 	bool has_size = fn->arg_size[arg] != 0;
10306 	bool is_next_size = false;
10307 
10308 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10309 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10310 
10311 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10312 		return is_next_size;
10313 
10314 	return has_size == is_next_size || is_next_size == is_fixed;
10315 }
10316 
10317 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10318 {
10319 	/* bpf_xxx(..., buf, len) call will access 'len'
10320 	 * bytes from memory 'buf'. Both arg types need
10321 	 * to be paired, so make sure there's no buggy
10322 	 * helper function specification.
10323 	 */
10324 	if (arg_type_is_mem_size(fn->arg1_type) ||
10325 	    check_args_pair_invalid(fn, 0) ||
10326 	    check_args_pair_invalid(fn, 1) ||
10327 	    check_args_pair_invalid(fn, 2) ||
10328 	    check_args_pair_invalid(fn, 3) ||
10329 	    check_args_pair_invalid(fn, 4))
10330 		return false;
10331 
10332 	return true;
10333 }
10334 
10335 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10336 {
10337 	int i;
10338 
10339 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10340 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10341 			return !!fn->arg_btf_id[i];
10342 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10343 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10344 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10345 		    /* arg_btf_id and arg_size are in a union. */
10346 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10347 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10348 			return false;
10349 	}
10350 
10351 	return true;
10352 }
10353 
10354 static int check_func_proto(const struct bpf_func_proto *fn)
10355 {
10356 	return check_raw_mode_ok(fn) &&
10357 	       check_arg_pair_ok(fn) &&
10358 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10359 }
10360 
10361 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10362  * are now invalid, so turn them into unknown SCALAR_VALUE.
10363  *
10364  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10365  * since these slices point to packet data.
10366  */
10367 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10368 {
10369 	struct bpf_func_state *state;
10370 	struct bpf_reg_state *reg;
10371 
10372 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10373 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10374 			mark_reg_invalid(env, reg);
10375 	}));
10376 }
10377 
10378 enum {
10379 	AT_PKT_END = -1,
10380 	BEYOND_PKT_END = -2,
10381 };
10382 
10383 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10384 {
10385 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10386 	struct bpf_reg_state *reg = &state->regs[regn];
10387 
10388 	if (reg->type != PTR_TO_PACKET)
10389 		/* PTR_TO_PACKET_META is not supported yet */
10390 		return;
10391 
10392 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10393 	 * How far beyond pkt_end it goes is unknown.
10394 	 * if (!range_open) it's the case of pkt >= pkt_end
10395 	 * if (range_open) it's the case of pkt > pkt_end
10396 	 * hence this pointer is at least 1 byte bigger than pkt_end
10397 	 */
10398 	if (range_open)
10399 		reg->range = BEYOND_PKT_END;
10400 	else
10401 		reg->range = AT_PKT_END;
10402 }
10403 
10404 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10405 {
10406 	int i;
10407 
10408 	for (i = 0; i < state->acquired_refs; i++) {
10409 		if (state->refs[i].type != REF_TYPE_PTR)
10410 			continue;
10411 		if (state->refs[i].id == ref_obj_id) {
10412 			release_reference_state(state, i);
10413 			return 0;
10414 		}
10415 	}
10416 	return -EINVAL;
10417 }
10418 
10419 /* The pointer with the specified id has released its reference to kernel
10420  * resources. Identify all copies of the same pointer and clear the reference.
10421  *
10422  * This is the release function corresponding to acquire_reference(). Idempotent.
10423  */
10424 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10425 {
10426 	struct bpf_verifier_state *vstate = env->cur_state;
10427 	struct bpf_func_state *state;
10428 	struct bpf_reg_state *reg;
10429 	int err;
10430 
10431 	err = release_reference_nomark(vstate, ref_obj_id);
10432 	if (err)
10433 		return err;
10434 
10435 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10436 		if (reg->ref_obj_id == ref_obj_id)
10437 			mark_reg_invalid(env, reg);
10438 	}));
10439 
10440 	return 0;
10441 }
10442 
10443 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10444 {
10445 	struct bpf_func_state *unused;
10446 	struct bpf_reg_state *reg;
10447 
10448 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10449 		if (type_is_non_owning_ref(reg->type))
10450 			mark_reg_invalid(env, reg);
10451 	}));
10452 }
10453 
10454 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10455 				    struct bpf_reg_state *regs)
10456 {
10457 	int i;
10458 
10459 	/* after the call registers r0 - r5 were scratched */
10460 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10461 		mark_reg_not_init(env, regs, caller_saved[i]);
10462 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10463 	}
10464 }
10465 
10466 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10467 				   struct bpf_func_state *caller,
10468 				   struct bpf_func_state *callee,
10469 				   int insn_idx);
10470 
10471 static int set_callee_state(struct bpf_verifier_env *env,
10472 			    struct bpf_func_state *caller,
10473 			    struct bpf_func_state *callee, int insn_idx);
10474 
10475 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10476 			    set_callee_state_fn set_callee_state_cb,
10477 			    struct bpf_verifier_state *state)
10478 {
10479 	struct bpf_func_state *caller, *callee;
10480 	int err;
10481 
10482 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10483 		verbose(env, "the call stack of %d frames is too deep\n",
10484 			state->curframe + 2);
10485 		return -E2BIG;
10486 	}
10487 
10488 	if (state->frame[state->curframe + 1]) {
10489 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10490 		return -EFAULT;
10491 	}
10492 
10493 	caller = state->frame[state->curframe];
10494 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10495 	if (!callee)
10496 		return -ENOMEM;
10497 	state->frame[state->curframe + 1] = callee;
10498 
10499 	/* callee cannot access r0, r6 - r9 for reading and has to write
10500 	 * into its own stack before reading from it.
10501 	 * callee can read/write into caller's stack
10502 	 */
10503 	init_func_state(env, callee,
10504 			/* remember the callsite, it will be used by bpf_exit */
10505 			callsite,
10506 			state->curframe + 1 /* frameno within this callchain */,
10507 			subprog /* subprog number within this prog */);
10508 	err = set_callee_state_cb(env, caller, callee, callsite);
10509 	if (err)
10510 		goto err_out;
10511 
10512 	/* only increment it after check_reg_arg() finished */
10513 	state->curframe++;
10514 
10515 	return 0;
10516 
10517 err_out:
10518 	free_func_state(callee);
10519 	state->frame[state->curframe + 1] = NULL;
10520 	return err;
10521 }
10522 
10523 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10524 				    const struct btf *btf,
10525 				    struct bpf_reg_state *regs)
10526 {
10527 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10528 	struct bpf_verifier_log *log = &env->log;
10529 	u32 i;
10530 	int ret;
10531 
10532 	ret = btf_prepare_func_args(env, subprog);
10533 	if (ret)
10534 		return ret;
10535 
10536 	/* check that BTF function arguments match actual types that the
10537 	 * verifier sees.
10538 	 */
10539 	for (i = 0; i < sub->arg_cnt; i++) {
10540 		u32 regno = i + 1;
10541 		struct bpf_reg_state *reg = &regs[regno];
10542 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10543 
10544 		if (arg->arg_type == ARG_ANYTHING) {
10545 			if (reg->type != SCALAR_VALUE) {
10546 				bpf_log(log, "R%d is not a scalar\n", regno);
10547 				return -EINVAL;
10548 			}
10549 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10550 			/*
10551 			 * Anything is allowed for untrusted arguments, as these are
10552 			 * read-only and probe read instructions would protect against
10553 			 * invalid memory access.
10554 			 */
10555 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10556 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10557 			if (ret < 0)
10558 				return ret;
10559 			/* If function expects ctx type in BTF check that caller
10560 			 * is passing PTR_TO_CTX.
10561 			 */
10562 			if (reg->type != PTR_TO_CTX) {
10563 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10564 				return -EINVAL;
10565 			}
10566 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10567 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10568 			if (ret < 0)
10569 				return ret;
10570 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10571 				return -EINVAL;
10572 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10573 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10574 				return -EINVAL;
10575 			}
10576 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10577 			/*
10578 			 * Can pass any value and the kernel won't crash, but
10579 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10580 			 * else is a bug in the bpf program. Point it out to
10581 			 * the user at the verification time instead of
10582 			 * run-time debug nightmare.
10583 			 */
10584 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10585 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10586 				return -EINVAL;
10587 			}
10588 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10589 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10590 			if (ret)
10591 				return ret;
10592 
10593 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10594 			if (ret)
10595 				return ret;
10596 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10597 			struct bpf_call_arg_meta meta;
10598 			int err;
10599 
10600 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10601 				continue;
10602 
10603 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10604 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10605 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10606 			if (err)
10607 				return err;
10608 		} else {
10609 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10610 			return -EFAULT;
10611 		}
10612 	}
10613 
10614 	return 0;
10615 }
10616 
10617 /* Compare BTF of a function call with given bpf_reg_state.
10618  * Returns:
10619  * EFAULT - there is a verifier bug. Abort verification.
10620  * EINVAL - there is a type mismatch or BTF is not available.
10621  * 0 - BTF matches with what bpf_reg_state expects.
10622  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10623  */
10624 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10625 				  struct bpf_reg_state *regs)
10626 {
10627 	struct bpf_prog *prog = env->prog;
10628 	struct btf *btf = prog->aux->btf;
10629 	u32 btf_id;
10630 	int err;
10631 
10632 	if (!prog->aux->func_info)
10633 		return -EINVAL;
10634 
10635 	btf_id = prog->aux->func_info[subprog].type_id;
10636 	if (!btf_id)
10637 		return -EFAULT;
10638 
10639 	if (prog->aux->func_info_aux[subprog].unreliable)
10640 		return -EINVAL;
10641 
10642 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10643 	/* Compiler optimizations can remove arguments from static functions
10644 	 * or mismatched type can be passed into a global function.
10645 	 * In such cases mark the function as unreliable from BTF point of view.
10646 	 */
10647 	if (err)
10648 		prog->aux->func_info_aux[subprog].unreliable = true;
10649 	return err;
10650 }
10651 
10652 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10653 			      int insn_idx, int subprog,
10654 			      set_callee_state_fn set_callee_state_cb)
10655 {
10656 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10657 	struct bpf_func_state *caller, *callee;
10658 	int err;
10659 
10660 	caller = state->frame[state->curframe];
10661 	err = btf_check_subprog_call(env, subprog, caller->regs);
10662 	if (err == -EFAULT)
10663 		return err;
10664 
10665 	/* set_callee_state is used for direct subprog calls, but we are
10666 	 * interested in validating only BPF helpers that can call subprogs as
10667 	 * callbacks
10668 	 */
10669 	env->subprog_info[subprog].is_cb = true;
10670 	if (bpf_pseudo_kfunc_call(insn) &&
10671 	    !is_callback_calling_kfunc(insn->imm)) {
10672 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10673 			     func_id_name(insn->imm), insn->imm);
10674 		return -EFAULT;
10675 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10676 		   !is_callback_calling_function(insn->imm)) { /* helper */
10677 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10678 			     func_id_name(insn->imm), insn->imm);
10679 		return -EFAULT;
10680 	}
10681 
10682 	if (is_async_callback_calling_insn(insn)) {
10683 		struct bpf_verifier_state *async_cb;
10684 
10685 		/* there is no real recursion here. timer and workqueue callbacks are async */
10686 		env->subprog_info[subprog].is_async_cb = true;
10687 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10688 					 insn_idx, subprog,
10689 					 is_async_cb_sleepable(env, insn));
10690 		if (IS_ERR(async_cb))
10691 			return PTR_ERR(async_cb);
10692 		callee = async_cb->frame[0];
10693 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10694 
10695 		/* Convert bpf_timer_set_callback() args into timer callback args */
10696 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10697 		if (err)
10698 			return err;
10699 
10700 		return 0;
10701 	}
10702 
10703 	/* for callback functions enqueue entry to callback and
10704 	 * proceed with next instruction within current frame.
10705 	 */
10706 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10707 	if (IS_ERR(callback_state))
10708 		return PTR_ERR(callback_state);
10709 
10710 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10711 			       callback_state);
10712 	if (err)
10713 		return err;
10714 
10715 	callback_state->callback_unroll_depth++;
10716 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10717 	caller->callback_depth = 0;
10718 	return 0;
10719 }
10720 
10721 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10722 			   int *insn_idx)
10723 {
10724 	struct bpf_verifier_state *state = env->cur_state;
10725 	struct bpf_func_state *caller;
10726 	int err, subprog, target_insn;
10727 
10728 	target_insn = *insn_idx + insn->imm + 1;
10729 	subprog = find_subprog(env, target_insn);
10730 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10731 			    target_insn))
10732 		return -EFAULT;
10733 
10734 	caller = state->frame[state->curframe];
10735 	err = btf_check_subprog_call(env, subprog, caller->regs);
10736 	if (err == -EFAULT)
10737 		return err;
10738 	if (subprog_is_global(env, subprog)) {
10739 		const char *sub_name = subprog_name(env, subprog);
10740 
10741 		if (env->cur_state->active_locks) {
10742 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10743 				     "use static function instead\n");
10744 			return -EINVAL;
10745 		}
10746 
10747 		if (env->subprog_info[subprog].might_sleep &&
10748 		    (env->cur_state->active_rcu_locks || env->cur_state->active_preempt_locks ||
10749 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10750 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10751 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10752 				     "a non-sleepable BPF program context\n");
10753 			return -EINVAL;
10754 		}
10755 
10756 		if (err) {
10757 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10758 				subprog, sub_name);
10759 			return err;
10760 		}
10761 
10762 		if (env->log.level & BPF_LOG_LEVEL)
10763 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10764 				subprog, sub_name);
10765 		if (env->subprog_info[subprog].changes_pkt_data)
10766 			clear_all_pkt_pointers(env);
10767 		/* mark global subprog for verifying after main prog */
10768 		subprog_aux(env, subprog)->called = true;
10769 		clear_caller_saved_regs(env, caller->regs);
10770 
10771 		/* All global functions return a 64-bit SCALAR_VALUE */
10772 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10773 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10774 
10775 		/* continue with next insn after call */
10776 		return 0;
10777 	}
10778 
10779 	/* for regular function entry setup new frame and continue
10780 	 * from that frame.
10781 	 */
10782 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10783 	if (err)
10784 		return err;
10785 
10786 	clear_caller_saved_regs(env, caller->regs);
10787 
10788 	/* and go analyze first insn of the callee */
10789 	*insn_idx = env->subprog_info[subprog].start - 1;
10790 
10791 	bpf_reset_live_stack_callchain(env);
10792 
10793 	if (env->log.level & BPF_LOG_LEVEL) {
10794 		verbose(env, "caller:\n");
10795 		print_verifier_state(env, state, caller->frameno, true);
10796 		verbose(env, "callee:\n");
10797 		print_verifier_state(env, state, state->curframe, true);
10798 	}
10799 
10800 	return 0;
10801 }
10802 
10803 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10804 				   struct bpf_func_state *caller,
10805 				   struct bpf_func_state *callee)
10806 {
10807 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10808 	 *      void *callback_ctx, u64 flags);
10809 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10810 	 *      void *callback_ctx);
10811 	 */
10812 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10813 
10814 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10815 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10816 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10817 
10818 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10819 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10820 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10821 
10822 	/* pointer to stack or null */
10823 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10824 
10825 	/* unused */
10826 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10827 	return 0;
10828 }
10829 
10830 static int set_callee_state(struct bpf_verifier_env *env,
10831 			    struct bpf_func_state *caller,
10832 			    struct bpf_func_state *callee, int insn_idx)
10833 {
10834 	int i;
10835 
10836 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10837 	 * pointers, which connects us up to the liveness chain
10838 	 */
10839 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10840 		callee->regs[i] = caller->regs[i];
10841 	return 0;
10842 }
10843 
10844 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10845 				       struct bpf_func_state *caller,
10846 				       struct bpf_func_state *callee,
10847 				       int insn_idx)
10848 {
10849 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10850 	struct bpf_map *map;
10851 	int err;
10852 
10853 	/* valid map_ptr and poison value does not matter */
10854 	map = insn_aux->map_ptr_state.map_ptr;
10855 	if (!map->ops->map_set_for_each_callback_args ||
10856 	    !map->ops->map_for_each_callback) {
10857 		verbose(env, "callback function not allowed for map\n");
10858 		return -ENOTSUPP;
10859 	}
10860 
10861 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10862 	if (err)
10863 		return err;
10864 
10865 	callee->in_callback_fn = true;
10866 	callee->callback_ret_range = retval_range(0, 1);
10867 	return 0;
10868 }
10869 
10870 static int set_loop_callback_state(struct bpf_verifier_env *env,
10871 				   struct bpf_func_state *caller,
10872 				   struct bpf_func_state *callee,
10873 				   int insn_idx)
10874 {
10875 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10876 	 *	    u64 flags);
10877 	 * callback_fn(u64 index, void *callback_ctx);
10878 	 */
10879 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10880 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10881 
10882 	/* unused */
10883 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10884 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10885 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10886 
10887 	callee->in_callback_fn = true;
10888 	callee->callback_ret_range = retval_range(0, 1);
10889 	return 0;
10890 }
10891 
10892 static int set_timer_callback_state(struct bpf_verifier_env *env,
10893 				    struct bpf_func_state *caller,
10894 				    struct bpf_func_state *callee,
10895 				    int insn_idx)
10896 {
10897 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10898 
10899 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10900 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10901 	 */
10902 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10903 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10904 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10905 
10906 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10907 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10908 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10909 
10910 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10911 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10912 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10913 
10914 	/* unused */
10915 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10916 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10917 	callee->in_async_callback_fn = true;
10918 	callee->callback_ret_range = retval_range(0, 0);
10919 	return 0;
10920 }
10921 
10922 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10923 				       struct bpf_func_state *caller,
10924 				       struct bpf_func_state *callee,
10925 				       int insn_idx)
10926 {
10927 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10928 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10929 	 * (callback_fn)(struct task_struct *task,
10930 	 *               struct vm_area_struct *vma, void *callback_ctx);
10931 	 */
10932 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10933 
10934 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10935 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10936 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10937 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10938 
10939 	/* pointer to stack or null */
10940 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10941 
10942 	/* unused */
10943 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10944 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10945 	callee->in_callback_fn = true;
10946 	callee->callback_ret_range = retval_range(0, 1);
10947 	return 0;
10948 }
10949 
10950 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10951 					   struct bpf_func_state *caller,
10952 					   struct bpf_func_state *callee,
10953 					   int insn_idx)
10954 {
10955 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10956 	 *			  callback_ctx, u64 flags);
10957 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10958 	 */
10959 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10960 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10961 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10962 
10963 	/* unused */
10964 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10965 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10966 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10967 
10968 	callee->in_callback_fn = true;
10969 	callee->callback_ret_range = retval_range(0, 1);
10970 	return 0;
10971 }
10972 
10973 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10974 					 struct bpf_func_state *caller,
10975 					 struct bpf_func_state *callee,
10976 					 int insn_idx)
10977 {
10978 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10979 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10980 	 *
10981 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10982 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10983 	 * by this point, so look at 'root'
10984 	 */
10985 	struct btf_field *field;
10986 
10987 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10988 				      BPF_RB_ROOT);
10989 	if (!field || !field->graph_root.value_btf_id)
10990 		return -EFAULT;
10991 
10992 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10993 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10994 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10995 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10996 
10997 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10998 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10999 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11000 	callee->in_callback_fn = true;
11001 	callee->callback_ret_range = retval_range(0, 1);
11002 	return 0;
11003 }
11004 
11005 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11006 						 struct bpf_func_state *caller,
11007 						 struct bpf_func_state *callee,
11008 						 int insn_idx)
11009 {
11010 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11011 
11012 	/*
11013 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11014 	 */
11015 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11016 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11017 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11018 
11019 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11020 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11021 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11022 
11023 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11024 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11025 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11026 
11027 	/* unused */
11028 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11029 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11030 	callee->in_async_callback_fn = true;
11031 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11032 	return 0;
11033 }
11034 
11035 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11036 
11037 /* Are we currently verifying the callback for a rbtree helper that must
11038  * be called with lock held? If so, no need to complain about unreleased
11039  * lock
11040  */
11041 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11042 {
11043 	struct bpf_verifier_state *state = env->cur_state;
11044 	struct bpf_insn *insn = env->prog->insnsi;
11045 	struct bpf_func_state *callee;
11046 	int kfunc_btf_id;
11047 
11048 	if (!state->curframe)
11049 		return false;
11050 
11051 	callee = state->frame[state->curframe];
11052 
11053 	if (!callee->in_callback_fn)
11054 		return false;
11055 
11056 	kfunc_btf_id = insn[callee->callsite].imm;
11057 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
11058 }
11059 
11060 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
11061 				bool return_32bit)
11062 {
11063 	if (return_32bit)
11064 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
11065 	else
11066 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
11067 }
11068 
11069 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11070 {
11071 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
11072 	struct bpf_func_state *caller, *callee;
11073 	struct bpf_reg_state *r0;
11074 	bool in_callback_fn;
11075 	int err;
11076 
11077 	err = bpf_update_live_stack(env);
11078 	if (err)
11079 		return err;
11080 
11081 	callee = state->frame[state->curframe];
11082 	r0 = &callee->regs[BPF_REG_0];
11083 	if (r0->type == PTR_TO_STACK) {
11084 		/* technically it's ok to return caller's stack pointer
11085 		 * (or caller's caller's pointer) back to the caller,
11086 		 * since these pointers are valid. Only current stack
11087 		 * pointer will be invalid as soon as function exits,
11088 		 * but let's be conservative
11089 		 */
11090 		verbose(env, "cannot return stack pointer to the caller\n");
11091 		return -EINVAL;
11092 	}
11093 
11094 	caller = state->frame[state->curframe - 1];
11095 	if (callee->in_callback_fn) {
11096 		if (r0->type != SCALAR_VALUE) {
11097 			verbose(env, "R0 not a scalar value\n");
11098 			return -EACCES;
11099 		}
11100 
11101 		/* we are going to rely on register's precise value */
11102 		err = mark_chain_precision(env, BPF_REG_0);
11103 		if (err)
11104 			return err;
11105 
11106 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11107 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11108 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11109 					       "At callback return", "R0");
11110 			return -EINVAL;
11111 		}
11112 		if (!bpf_calls_callback(env, callee->callsite)) {
11113 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11114 				     *insn_idx, callee->callsite);
11115 			return -EFAULT;
11116 		}
11117 	} else {
11118 		/* return to the caller whatever r0 had in the callee */
11119 		caller->regs[BPF_REG_0] = *r0;
11120 	}
11121 
11122 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11123 	 * there function call logic would reschedule callback visit. If iteration
11124 	 * converges is_state_visited() would prune that visit eventually.
11125 	 */
11126 	in_callback_fn = callee->in_callback_fn;
11127 	if (in_callback_fn)
11128 		*insn_idx = callee->callsite;
11129 	else
11130 		*insn_idx = callee->callsite + 1;
11131 
11132 	if (env->log.level & BPF_LOG_LEVEL) {
11133 		verbose(env, "returning from callee:\n");
11134 		print_verifier_state(env, state, callee->frameno, true);
11135 		verbose(env, "to caller at %d:\n", *insn_idx);
11136 		print_verifier_state(env, state, caller->frameno, true);
11137 	}
11138 	/* clear everything in the callee. In case of exceptional exits using
11139 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11140 	free_func_state(callee);
11141 	state->frame[state->curframe--] = NULL;
11142 
11143 	/* for callbacks widen imprecise scalars to make programs like below verify:
11144 	 *
11145 	 *   struct ctx { int i; }
11146 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11147 	 *   ...
11148 	 *   struct ctx = { .i = 0; }
11149 	 *   bpf_loop(100, cb, &ctx, 0);
11150 	 *
11151 	 * This is similar to what is done in process_iter_next_call() for open
11152 	 * coded iterators.
11153 	 */
11154 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11155 	if (prev_st) {
11156 		err = widen_imprecise_scalars(env, prev_st, state);
11157 		if (err)
11158 			return err;
11159 	}
11160 	return 0;
11161 }
11162 
11163 static int do_refine_retval_range(struct bpf_verifier_env *env,
11164 				  struct bpf_reg_state *regs, int ret_type,
11165 				  int func_id,
11166 				  struct bpf_call_arg_meta *meta)
11167 {
11168 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11169 
11170 	if (ret_type != RET_INTEGER)
11171 		return 0;
11172 
11173 	switch (func_id) {
11174 	case BPF_FUNC_get_stack:
11175 	case BPF_FUNC_get_task_stack:
11176 	case BPF_FUNC_probe_read_str:
11177 	case BPF_FUNC_probe_read_kernel_str:
11178 	case BPF_FUNC_probe_read_user_str:
11179 		ret_reg->smax_value = meta->msize_max_value;
11180 		ret_reg->s32_max_value = meta->msize_max_value;
11181 		ret_reg->smin_value = -MAX_ERRNO;
11182 		ret_reg->s32_min_value = -MAX_ERRNO;
11183 		reg_bounds_sync(ret_reg);
11184 		break;
11185 	case BPF_FUNC_get_smp_processor_id:
11186 		ret_reg->umax_value = nr_cpu_ids - 1;
11187 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11188 		ret_reg->smax_value = nr_cpu_ids - 1;
11189 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11190 		ret_reg->umin_value = 0;
11191 		ret_reg->u32_min_value = 0;
11192 		ret_reg->smin_value = 0;
11193 		ret_reg->s32_min_value = 0;
11194 		reg_bounds_sync(ret_reg);
11195 		break;
11196 	}
11197 
11198 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11199 }
11200 
11201 static int
11202 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11203 		int func_id, int insn_idx)
11204 {
11205 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11206 	struct bpf_map *map = meta->map_ptr;
11207 
11208 	if (func_id != BPF_FUNC_tail_call &&
11209 	    func_id != BPF_FUNC_map_lookup_elem &&
11210 	    func_id != BPF_FUNC_map_update_elem &&
11211 	    func_id != BPF_FUNC_map_delete_elem &&
11212 	    func_id != BPF_FUNC_map_push_elem &&
11213 	    func_id != BPF_FUNC_map_pop_elem &&
11214 	    func_id != BPF_FUNC_map_peek_elem &&
11215 	    func_id != BPF_FUNC_for_each_map_elem &&
11216 	    func_id != BPF_FUNC_redirect_map &&
11217 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11218 		return 0;
11219 
11220 	if (map == NULL) {
11221 		verifier_bug(env, "expected map for helper call");
11222 		return -EFAULT;
11223 	}
11224 
11225 	/* In case of read-only, some additional restrictions
11226 	 * need to be applied in order to prevent altering the
11227 	 * state of the map from program side.
11228 	 */
11229 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11230 	    (func_id == BPF_FUNC_map_delete_elem ||
11231 	     func_id == BPF_FUNC_map_update_elem ||
11232 	     func_id == BPF_FUNC_map_push_elem ||
11233 	     func_id == BPF_FUNC_map_pop_elem)) {
11234 		verbose(env, "write into map forbidden\n");
11235 		return -EACCES;
11236 	}
11237 
11238 	if (!aux->map_ptr_state.map_ptr)
11239 		bpf_map_ptr_store(aux, meta->map_ptr,
11240 				  !meta->map_ptr->bypass_spec_v1, false);
11241 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11242 		bpf_map_ptr_store(aux, meta->map_ptr,
11243 				  !meta->map_ptr->bypass_spec_v1, true);
11244 	return 0;
11245 }
11246 
11247 static int
11248 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11249 		int func_id, int insn_idx)
11250 {
11251 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11252 	struct bpf_reg_state *reg;
11253 	struct bpf_map *map = meta->map_ptr;
11254 	u64 val, max;
11255 	int err;
11256 
11257 	if (func_id != BPF_FUNC_tail_call)
11258 		return 0;
11259 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11260 		verbose(env, "expected prog array map for tail call");
11261 		return -EINVAL;
11262 	}
11263 
11264 	reg = reg_state(env, BPF_REG_3);
11265 	val = reg->var_off.value;
11266 	max = map->max_entries;
11267 
11268 	if (!(is_reg_const(reg, false) && val < max)) {
11269 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11270 		return 0;
11271 	}
11272 
11273 	err = mark_chain_precision(env, BPF_REG_3);
11274 	if (err)
11275 		return err;
11276 	if (bpf_map_key_unseen(aux))
11277 		bpf_map_key_store(aux, val);
11278 	else if (!bpf_map_key_poisoned(aux) &&
11279 		  bpf_map_key_immediate(aux) != val)
11280 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11281 	return 0;
11282 }
11283 
11284 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11285 {
11286 	struct bpf_verifier_state *state = env->cur_state;
11287 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11288 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11289 	bool refs_lingering = false;
11290 	int i;
11291 
11292 	if (!exception_exit && cur_func(env)->frameno)
11293 		return 0;
11294 
11295 	for (i = 0; i < state->acquired_refs; i++) {
11296 		if (state->refs[i].type != REF_TYPE_PTR)
11297 			continue;
11298 		/* Allow struct_ops programs to return a referenced kptr back to
11299 		 * kernel. Type checks are performed later in check_return_code.
11300 		 */
11301 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11302 		    reg->ref_obj_id == state->refs[i].id)
11303 			continue;
11304 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11305 			state->refs[i].id, state->refs[i].insn_idx);
11306 		refs_lingering = true;
11307 	}
11308 	return refs_lingering ? -EINVAL : 0;
11309 }
11310 
11311 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11312 {
11313 	int err;
11314 
11315 	if (check_lock && env->cur_state->active_locks) {
11316 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11317 		return -EINVAL;
11318 	}
11319 
11320 	err = check_reference_leak(env, exception_exit);
11321 	if (err) {
11322 		verbose(env, "%s would lead to reference leak\n", prefix);
11323 		return err;
11324 	}
11325 
11326 	if (check_lock && env->cur_state->active_irq_id) {
11327 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11328 		return -EINVAL;
11329 	}
11330 
11331 	if (check_lock && env->cur_state->active_rcu_locks) {
11332 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11333 		return -EINVAL;
11334 	}
11335 
11336 	if (check_lock && env->cur_state->active_preempt_locks) {
11337 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11338 		return -EINVAL;
11339 	}
11340 
11341 	return 0;
11342 }
11343 
11344 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11345 				   struct bpf_reg_state *regs)
11346 {
11347 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11348 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11349 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11350 	struct bpf_bprintf_data data = {};
11351 	int err, fmt_map_off, num_args;
11352 	u64 fmt_addr;
11353 	char *fmt;
11354 
11355 	/* data must be an array of u64 */
11356 	if (data_len_reg->var_off.value % 8)
11357 		return -EINVAL;
11358 	num_args = data_len_reg->var_off.value / 8;
11359 
11360 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11361 	 * and map_direct_value_addr is set.
11362 	 */
11363 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11364 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11365 						  fmt_map_off);
11366 	if (err) {
11367 		verbose(env, "failed to retrieve map value address\n");
11368 		return -EFAULT;
11369 	}
11370 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11371 
11372 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11373 	 * can focus on validating the format specifiers.
11374 	 */
11375 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11376 	if (err < 0)
11377 		verbose(env, "Invalid format string\n");
11378 
11379 	return err;
11380 }
11381 
11382 static int check_get_func_ip(struct bpf_verifier_env *env)
11383 {
11384 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11385 	int func_id = BPF_FUNC_get_func_ip;
11386 
11387 	if (type == BPF_PROG_TYPE_TRACING) {
11388 		if (!bpf_prog_has_trampoline(env->prog)) {
11389 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11390 				func_id_name(func_id), func_id);
11391 			return -ENOTSUPP;
11392 		}
11393 		return 0;
11394 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11395 		return 0;
11396 	}
11397 
11398 	verbose(env, "func %s#%d not supported for program type %d\n",
11399 		func_id_name(func_id), func_id, type);
11400 	return -ENOTSUPP;
11401 }
11402 
11403 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11404 {
11405 	return &env->insn_aux_data[env->insn_idx];
11406 }
11407 
11408 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11409 {
11410 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
11411 	bool reg_is_null = register_is_null(reg);
11412 
11413 	if (reg_is_null)
11414 		mark_chain_precision(env, BPF_REG_4);
11415 
11416 	return reg_is_null;
11417 }
11418 
11419 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11420 {
11421 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11422 
11423 	if (!state->initialized) {
11424 		state->initialized = 1;
11425 		state->fit_for_inline = loop_flag_is_zero(env);
11426 		state->callback_subprogno = subprogno;
11427 		return;
11428 	}
11429 
11430 	if (!state->fit_for_inline)
11431 		return;
11432 
11433 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11434 				 state->callback_subprogno == subprogno);
11435 }
11436 
11437 /* Returns whether or not the given map type can potentially elide
11438  * lookup return value nullness check. This is possible if the key
11439  * is statically known.
11440  */
11441 static bool can_elide_value_nullness(enum bpf_map_type type)
11442 {
11443 	switch (type) {
11444 	case BPF_MAP_TYPE_ARRAY:
11445 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11446 		return true;
11447 	default:
11448 		return false;
11449 	}
11450 }
11451 
11452 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11453 			    const struct bpf_func_proto **ptr)
11454 {
11455 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11456 		return -ERANGE;
11457 
11458 	if (!env->ops->get_func_proto)
11459 		return -EINVAL;
11460 
11461 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11462 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11463 }
11464 
11465 /* Check if we're in a sleepable context. */
11466 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
11467 {
11468 	return !env->cur_state->active_rcu_locks &&
11469 	       !env->cur_state->active_preempt_locks &&
11470 	       !env->cur_state->active_locks &&
11471 	       !env->cur_state->active_irq_id &&
11472 	       in_sleepable(env);
11473 }
11474 
11475 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11476 			     int *insn_idx_p)
11477 {
11478 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11479 	bool returns_cpu_specific_alloc_ptr = false;
11480 	const struct bpf_func_proto *fn = NULL;
11481 	enum bpf_return_type ret_type;
11482 	enum bpf_type_flag ret_flag;
11483 	struct bpf_reg_state *regs;
11484 	struct bpf_call_arg_meta meta;
11485 	int insn_idx = *insn_idx_p;
11486 	bool changes_data;
11487 	int i, err, func_id;
11488 
11489 	/* find function prototype */
11490 	func_id = insn->imm;
11491 	err = get_helper_proto(env, insn->imm, &fn);
11492 	if (err == -ERANGE) {
11493 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11494 		return -EINVAL;
11495 	}
11496 
11497 	if (err) {
11498 		verbose(env, "program of this type cannot use helper %s#%d\n",
11499 			func_id_name(func_id), func_id);
11500 		return err;
11501 	}
11502 
11503 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11504 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11505 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11506 		return -EINVAL;
11507 	}
11508 
11509 	if (fn->allowed && !fn->allowed(env->prog)) {
11510 		verbose(env, "helper call is not allowed in probe\n");
11511 		return -EINVAL;
11512 	}
11513 
11514 	if (!in_sleepable(env) && fn->might_sleep) {
11515 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11516 		return -EINVAL;
11517 	}
11518 
11519 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11520 	changes_data = bpf_helper_changes_pkt_data(func_id);
11521 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11522 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11523 		return -EFAULT;
11524 	}
11525 
11526 	memset(&meta, 0, sizeof(meta));
11527 	meta.pkt_access = fn->pkt_access;
11528 
11529 	err = check_func_proto(fn);
11530 	if (err) {
11531 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11532 		return err;
11533 	}
11534 
11535 	if (env->cur_state->active_rcu_locks) {
11536 		if (fn->might_sleep) {
11537 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11538 				func_id_name(func_id), func_id);
11539 			return -EINVAL;
11540 		}
11541 	}
11542 
11543 	if (env->cur_state->active_preempt_locks) {
11544 		if (fn->might_sleep) {
11545 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11546 				func_id_name(func_id), func_id);
11547 			return -EINVAL;
11548 		}
11549 	}
11550 
11551 	if (env->cur_state->active_irq_id) {
11552 		if (fn->might_sleep) {
11553 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11554 				func_id_name(func_id), func_id);
11555 			return -EINVAL;
11556 		}
11557 	}
11558 
11559 	/* Track non-sleepable context for helpers. */
11560 	if (!in_sleepable_context(env))
11561 		env->insn_aux_data[insn_idx].non_sleepable = true;
11562 
11563 	meta.func_id = func_id;
11564 	/* check args */
11565 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11566 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11567 		if (err)
11568 			return err;
11569 	}
11570 
11571 	err = record_func_map(env, &meta, func_id, insn_idx);
11572 	if (err)
11573 		return err;
11574 
11575 	err = record_func_key(env, &meta, func_id, insn_idx);
11576 	if (err)
11577 		return err;
11578 
11579 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11580 	 * is inferred from register state.
11581 	 */
11582 	for (i = 0; i < meta.access_size; i++) {
11583 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11584 				       BPF_WRITE, -1, false, false);
11585 		if (err)
11586 			return err;
11587 	}
11588 
11589 	regs = cur_regs(env);
11590 
11591 	if (meta.release_regno) {
11592 		err = -EINVAL;
11593 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11594 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11595 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11596 			u32 ref_obj_id = meta.ref_obj_id;
11597 			bool in_rcu = in_rcu_cs(env);
11598 			struct bpf_func_state *state;
11599 			struct bpf_reg_state *reg;
11600 
11601 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11602 			if (!err) {
11603 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11604 					if (reg->ref_obj_id == ref_obj_id) {
11605 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11606 							reg->ref_obj_id = 0;
11607 							reg->type &= ~MEM_ALLOC;
11608 							reg->type |= MEM_RCU;
11609 						} else {
11610 							mark_reg_invalid(env, reg);
11611 						}
11612 					}
11613 				}));
11614 			}
11615 		} else if (meta.ref_obj_id) {
11616 			err = release_reference(env, meta.ref_obj_id);
11617 		} else if (register_is_null(&regs[meta.release_regno])) {
11618 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11619 			 * released is NULL, which must be > R0.
11620 			 */
11621 			err = 0;
11622 		}
11623 		if (err) {
11624 			verbose(env, "func %s#%d reference has not been acquired before\n",
11625 				func_id_name(func_id), func_id);
11626 			return err;
11627 		}
11628 	}
11629 
11630 	switch (func_id) {
11631 	case BPF_FUNC_tail_call:
11632 		err = check_resource_leak(env, false, true, "tail_call");
11633 		if (err)
11634 			return err;
11635 		break;
11636 	case BPF_FUNC_get_local_storage:
11637 		/* check that flags argument in get_local_storage(map, flags) is 0,
11638 		 * this is required because get_local_storage() can't return an error.
11639 		 */
11640 		if (!register_is_null(&regs[BPF_REG_2])) {
11641 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11642 			return -EINVAL;
11643 		}
11644 		break;
11645 	case BPF_FUNC_for_each_map_elem:
11646 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11647 					 set_map_elem_callback_state);
11648 		break;
11649 	case BPF_FUNC_timer_set_callback:
11650 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11651 					 set_timer_callback_state);
11652 		break;
11653 	case BPF_FUNC_find_vma:
11654 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11655 					 set_find_vma_callback_state);
11656 		break;
11657 	case BPF_FUNC_snprintf:
11658 		err = check_bpf_snprintf_call(env, regs);
11659 		break;
11660 	case BPF_FUNC_loop:
11661 		update_loop_inline_state(env, meta.subprogno);
11662 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11663 		 * is finished, thus mark it precise.
11664 		 */
11665 		err = mark_chain_precision(env, BPF_REG_1);
11666 		if (err)
11667 			return err;
11668 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11669 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11670 						 set_loop_callback_state);
11671 		} else {
11672 			cur_func(env)->callback_depth = 0;
11673 			if (env->log.level & BPF_LOG_LEVEL2)
11674 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11675 					env->cur_state->curframe);
11676 		}
11677 		break;
11678 	case BPF_FUNC_dynptr_from_mem:
11679 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11680 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11681 				reg_type_str(env, regs[BPF_REG_1].type));
11682 			return -EACCES;
11683 		}
11684 		break;
11685 	case BPF_FUNC_set_retval:
11686 		if (prog_type == BPF_PROG_TYPE_LSM &&
11687 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11688 			if (!env->prog->aux->attach_func_proto->type) {
11689 				/* Make sure programs that attach to void
11690 				 * hooks don't try to modify return value.
11691 				 */
11692 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11693 				return -EINVAL;
11694 			}
11695 		}
11696 		break;
11697 	case BPF_FUNC_dynptr_data:
11698 	{
11699 		struct bpf_reg_state *reg;
11700 		int id, ref_obj_id;
11701 
11702 		reg = get_dynptr_arg_reg(env, fn, regs);
11703 		if (!reg)
11704 			return -EFAULT;
11705 
11706 
11707 		if (meta.dynptr_id) {
11708 			verifier_bug(env, "meta.dynptr_id already set");
11709 			return -EFAULT;
11710 		}
11711 		if (meta.ref_obj_id) {
11712 			verifier_bug(env, "meta.ref_obj_id already set");
11713 			return -EFAULT;
11714 		}
11715 
11716 		id = dynptr_id(env, reg);
11717 		if (id < 0) {
11718 			verifier_bug(env, "failed to obtain dynptr id");
11719 			return id;
11720 		}
11721 
11722 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11723 		if (ref_obj_id < 0) {
11724 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11725 			return ref_obj_id;
11726 		}
11727 
11728 		meta.dynptr_id = id;
11729 		meta.ref_obj_id = ref_obj_id;
11730 
11731 		break;
11732 	}
11733 	case BPF_FUNC_dynptr_write:
11734 	{
11735 		enum bpf_dynptr_type dynptr_type;
11736 		struct bpf_reg_state *reg;
11737 
11738 		reg = get_dynptr_arg_reg(env, fn, regs);
11739 		if (!reg)
11740 			return -EFAULT;
11741 
11742 		dynptr_type = dynptr_get_type(env, reg);
11743 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11744 			return -EFAULT;
11745 
11746 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11747 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11748 			/* this will trigger clear_all_pkt_pointers(), which will
11749 			 * invalidate all dynptr slices associated with the skb
11750 			 */
11751 			changes_data = true;
11752 
11753 		break;
11754 	}
11755 	case BPF_FUNC_per_cpu_ptr:
11756 	case BPF_FUNC_this_cpu_ptr:
11757 	{
11758 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11759 		const struct btf_type *type;
11760 
11761 		if (reg->type & MEM_RCU) {
11762 			type = btf_type_by_id(reg->btf, reg->btf_id);
11763 			if (!type || !btf_type_is_struct(type)) {
11764 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11765 				return -EFAULT;
11766 			}
11767 			returns_cpu_specific_alloc_ptr = true;
11768 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11769 		}
11770 		break;
11771 	}
11772 	case BPF_FUNC_user_ringbuf_drain:
11773 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11774 					 set_user_ringbuf_callback_state);
11775 		break;
11776 	}
11777 
11778 	if (err)
11779 		return err;
11780 
11781 	/* reset caller saved regs */
11782 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11783 		mark_reg_not_init(env, regs, caller_saved[i]);
11784 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11785 	}
11786 
11787 	/* helper call returns 64-bit value. */
11788 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11789 
11790 	/* update return register (already marked as written above) */
11791 	ret_type = fn->ret_type;
11792 	ret_flag = type_flag(ret_type);
11793 
11794 	switch (base_type(ret_type)) {
11795 	case RET_INTEGER:
11796 		/* sets type to SCALAR_VALUE */
11797 		mark_reg_unknown(env, regs, BPF_REG_0);
11798 		break;
11799 	case RET_VOID:
11800 		regs[BPF_REG_0].type = NOT_INIT;
11801 		break;
11802 	case RET_PTR_TO_MAP_VALUE:
11803 		/* There is no offset yet applied, variable or fixed */
11804 		mark_reg_known_zero(env, regs, BPF_REG_0);
11805 		/* remember map_ptr, so that check_map_access()
11806 		 * can check 'value_size' boundary of memory access
11807 		 * to map element returned from bpf_map_lookup_elem()
11808 		 */
11809 		if (meta.map_ptr == NULL) {
11810 			verifier_bug(env, "unexpected null map_ptr");
11811 			return -EFAULT;
11812 		}
11813 
11814 		if (func_id == BPF_FUNC_map_lookup_elem &&
11815 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11816 		    meta.const_map_key >= 0 &&
11817 		    meta.const_map_key < meta.map_ptr->max_entries)
11818 			ret_flag &= ~PTR_MAYBE_NULL;
11819 
11820 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11821 		regs[BPF_REG_0].map_uid = meta.map_uid;
11822 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11823 		if (!type_may_be_null(ret_flag) &&
11824 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11825 			regs[BPF_REG_0].id = ++env->id_gen;
11826 		}
11827 		break;
11828 	case RET_PTR_TO_SOCKET:
11829 		mark_reg_known_zero(env, regs, BPF_REG_0);
11830 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11831 		break;
11832 	case RET_PTR_TO_SOCK_COMMON:
11833 		mark_reg_known_zero(env, regs, BPF_REG_0);
11834 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11835 		break;
11836 	case RET_PTR_TO_TCP_SOCK:
11837 		mark_reg_known_zero(env, regs, BPF_REG_0);
11838 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11839 		break;
11840 	case RET_PTR_TO_MEM:
11841 		mark_reg_known_zero(env, regs, BPF_REG_0);
11842 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11843 		regs[BPF_REG_0].mem_size = meta.mem_size;
11844 		break;
11845 	case RET_PTR_TO_MEM_OR_BTF_ID:
11846 	{
11847 		const struct btf_type *t;
11848 
11849 		mark_reg_known_zero(env, regs, BPF_REG_0);
11850 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11851 		if (!btf_type_is_struct(t)) {
11852 			u32 tsize;
11853 			const struct btf_type *ret;
11854 			const char *tname;
11855 
11856 			/* resolve the type size of ksym. */
11857 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11858 			if (IS_ERR(ret)) {
11859 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11860 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11861 					tname, PTR_ERR(ret));
11862 				return -EINVAL;
11863 			}
11864 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11865 			regs[BPF_REG_0].mem_size = tsize;
11866 		} else {
11867 			if (returns_cpu_specific_alloc_ptr) {
11868 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11869 			} else {
11870 				/* MEM_RDONLY may be carried from ret_flag, but it
11871 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11872 				 * it will confuse the check of PTR_TO_BTF_ID in
11873 				 * check_mem_access().
11874 				 */
11875 				ret_flag &= ~MEM_RDONLY;
11876 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11877 			}
11878 
11879 			regs[BPF_REG_0].btf = meta.ret_btf;
11880 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11881 		}
11882 		break;
11883 	}
11884 	case RET_PTR_TO_BTF_ID:
11885 	{
11886 		struct btf *ret_btf;
11887 		int ret_btf_id;
11888 
11889 		mark_reg_known_zero(env, regs, BPF_REG_0);
11890 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11891 		if (func_id == BPF_FUNC_kptr_xchg) {
11892 			ret_btf = meta.kptr_field->kptr.btf;
11893 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11894 			if (!btf_is_kernel(ret_btf)) {
11895 				regs[BPF_REG_0].type |= MEM_ALLOC;
11896 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11897 					regs[BPF_REG_0].type |= MEM_PERCPU;
11898 			}
11899 		} else {
11900 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11901 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11902 					     func_id_name(func_id));
11903 				return -EFAULT;
11904 			}
11905 			ret_btf = btf_vmlinux;
11906 			ret_btf_id = *fn->ret_btf_id;
11907 		}
11908 		if (ret_btf_id == 0) {
11909 			verbose(env, "invalid return type %u of func %s#%d\n",
11910 				base_type(ret_type), func_id_name(func_id),
11911 				func_id);
11912 			return -EINVAL;
11913 		}
11914 		regs[BPF_REG_0].btf = ret_btf;
11915 		regs[BPF_REG_0].btf_id = ret_btf_id;
11916 		break;
11917 	}
11918 	default:
11919 		verbose(env, "unknown return type %u of func %s#%d\n",
11920 			base_type(ret_type), func_id_name(func_id), func_id);
11921 		return -EINVAL;
11922 	}
11923 
11924 	if (type_may_be_null(regs[BPF_REG_0].type))
11925 		regs[BPF_REG_0].id = ++env->id_gen;
11926 
11927 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11928 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11929 			     func_id_name(func_id), func_id);
11930 		return -EFAULT;
11931 	}
11932 
11933 	if (is_dynptr_ref_function(func_id))
11934 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11935 
11936 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11937 		/* For release_reference() */
11938 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11939 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11940 		int id = acquire_reference(env, insn_idx);
11941 
11942 		if (id < 0)
11943 			return id;
11944 		/* For mark_ptr_or_null_reg() */
11945 		regs[BPF_REG_0].id = id;
11946 		/* For release_reference() */
11947 		regs[BPF_REG_0].ref_obj_id = id;
11948 	}
11949 
11950 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11951 	if (err)
11952 		return err;
11953 
11954 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11955 	if (err)
11956 		return err;
11957 
11958 	if ((func_id == BPF_FUNC_get_stack ||
11959 	     func_id == BPF_FUNC_get_task_stack) &&
11960 	    !env->prog->has_callchain_buf) {
11961 		const char *err_str;
11962 
11963 #ifdef CONFIG_PERF_EVENTS
11964 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11965 		err_str = "cannot get callchain buffer for func %s#%d\n";
11966 #else
11967 		err = -ENOTSUPP;
11968 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11969 #endif
11970 		if (err) {
11971 			verbose(env, err_str, func_id_name(func_id), func_id);
11972 			return err;
11973 		}
11974 
11975 		env->prog->has_callchain_buf = true;
11976 	}
11977 
11978 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11979 		env->prog->call_get_stack = true;
11980 
11981 	if (func_id == BPF_FUNC_get_func_ip) {
11982 		if (check_get_func_ip(env))
11983 			return -ENOTSUPP;
11984 		env->prog->call_get_func_ip = true;
11985 	}
11986 
11987 	if (func_id == BPF_FUNC_tail_call) {
11988 		if (env->cur_state->curframe) {
11989 			struct bpf_verifier_state *branch;
11990 
11991 			mark_reg_scratched(env, BPF_REG_0);
11992 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
11993 			if (IS_ERR(branch))
11994 				return PTR_ERR(branch);
11995 			clear_all_pkt_pointers(env);
11996 			mark_reg_unknown(env, regs, BPF_REG_0);
11997 			err = prepare_func_exit(env, &env->insn_idx);
11998 			if (err)
11999 				return err;
12000 			env->insn_idx--;
12001 		} else {
12002 			changes_data = false;
12003 		}
12004 	}
12005 
12006 	if (changes_data)
12007 		clear_all_pkt_pointers(env);
12008 	return 0;
12009 }
12010 
12011 /* mark_btf_func_reg_size() is used when the reg size is determined by
12012  * the BTF func_proto's return value size and argument.
12013  */
12014 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
12015 				     u32 regno, size_t reg_size)
12016 {
12017 	struct bpf_reg_state *reg = &regs[regno];
12018 
12019 	if (regno == BPF_REG_0) {
12020 		/* Function return value */
12021 		reg->subreg_def = reg_size == sizeof(u64) ?
12022 			DEF_NOT_SUBREG : env->insn_idx + 1;
12023 	} else if (reg_size == sizeof(u64)) {
12024 		/* Function argument */
12025 		mark_insn_zext(env, reg);
12026 	}
12027 }
12028 
12029 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
12030 				   size_t reg_size)
12031 {
12032 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
12033 }
12034 
12035 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
12036 {
12037 	return meta->kfunc_flags & KF_ACQUIRE;
12038 }
12039 
12040 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
12041 {
12042 	return meta->kfunc_flags & KF_RELEASE;
12043 }
12044 
12045 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
12046 {
12047 	return meta->kfunc_flags & KF_SLEEPABLE;
12048 }
12049 
12050 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
12051 {
12052 	return meta->kfunc_flags & KF_DESTRUCTIVE;
12053 }
12054 
12055 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
12056 {
12057 	return meta->kfunc_flags & KF_RCU;
12058 }
12059 
12060 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
12061 {
12062 	return meta->kfunc_flags & KF_RCU_PROTECTED;
12063 }
12064 
12065 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12066 				  const struct btf_param *arg,
12067 				  const struct bpf_reg_state *reg)
12068 {
12069 	const struct btf_type *t;
12070 
12071 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12072 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12073 		return false;
12074 
12075 	return btf_param_match_suffix(btf, arg, "__sz");
12076 }
12077 
12078 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12079 					const struct btf_param *arg,
12080 					const struct bpf_reg_state *reg)
12081 {
12082 	const struct btf_type *t;
12083 
12084 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12085 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12086 		return false;
12087 
12088 	return btf_param_match_suffix(btf, arg, "__szk");
12089 }
12090 
12091 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12092 {
12093 	return btf_param_match_suffix(btf, arg, "__k");
12094 }
12095 
12096 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12097 {
12098 	return btf_param_match_suffix(btf, arg, "__ign");
12099 }
12100 
12101 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12102 {
12103 	return btf_param_match_suffix(btf, arg, "__map");
12104 }
12105 
12106 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12107 {
12108 	return btf_param_match_suffix(btf, arg, "__alloc");
12109 }
12110 
12111 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12112 {
12113 	return btf_param_match_suffix(btf, arg, "__uninit");
12114 }
12115 
12116 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12117 {
12118 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12119 }
12120 
12121 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12122 {
12123 	return btf_param_match_suffix(btf, arg, "__nullable");
12124 }
12125 
12126 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12127 {
12128 	return btf_param_match_suffix(btf, arg, "__str");
12129 }
12130 
12131 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12132 {
12133 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12134 }
12135 
12136 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12137 {
12138 	return btf_param_match_suffix(btf, arg, "__prog");
12139 }
12140 
12141 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12142 					  const struct btf_param *arg,
12143 					  const char *name)
12144 {
12145 	int len, target_len = strlen(name);
12146 	const char *param_name;
12147 
12148 	param_name = btf_name_by_offset(btf, arg->name_off);
12149 	if (str_is_empty(param_name))
12150 		return false;
12151 	len = strlen(param_name);
12152 	if (len != target_len)
12153 		return false;
12154 	if (strcmp(param_name, name))
12155 		return false;
12156 
12157 	return true;
12158 }
12159 
12160 enum {
12161 	KF_ARG_DYNPTR_ID,
12162 	KF_ARG_LIST_HEAD_ID,
12163 	KF_ARG_LIST_NODE_ID,
12164 	KF_ARG_RB_ROOT_ID,
12165 	KF_ARG_RB_NODE_ID,
12166 	KF_ARG_WORKQUEUE_ID,
12167 	KF_ARG_RES_SPIN_LOCK_ID,
12168 	KF_ARG_TASK_WORK_ID,
12169 };
12170 
12171 BTF_ID_LIST(kf_arg_btf_ids)
12172 BTF_ID(struct, bpf_dynptr)
12173 BTF_ID(struct, bpf_list_head)
12174 BTF_ID(struct, bpf_list_node)
12175 BTF_ID(struct, bpf_rb_root)
12176 BTF_ID(struct, bpf_rb_node)
12177 BTF_ID(struct, bpf_wq)
12178 BTF_ID(struct, bpf_res_spin_lock)
12179 BTF_ID(struct, bpf_task_work)
12180 
12181 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12182 				    const struct btf_param *arg, int type)
12183 {
12184 	const struct btf_type *t;
12185 	u32 res_id;
12186 
12187 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12188 	if (!t)
12189 		return false;
12190 	if (!btf_type_is_ptr(t))
12191 		return false;
12192 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12193 	if (!t)
12194 		return false;
12195 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12196 }
12197 
12198 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12199 {
12200 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12201 }
12202 
12203 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12204 {
12205 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12206 }
12207 
12208 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12209 {
12210 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12211 }
12212 
12213 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12214 {
12215 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12216 }
12217 
12218 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12219 {
12220 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12221 }
12222 
12223 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12224 {
12225 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12226 }
12227 
12228 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12229 {
12230 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12231 }
12232 
12233 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12234 {
12235 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12236 }
12237 
12238 static bool is_rbtree_node_type(const struct btf_type *t)
12239 {
12240 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12241 }
12242 
12243 static bool is_list_node_type(const struct btf_type *t)
12244 {
12245 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12246 }
12247 
12248 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12249 				  const struct btf_param *arg)
12250 {
12251 	const struct btf_type *t;
12252 
12253 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12254 	if (!t)
12255 		return false;
12256 
12257 	return true;
12258 }
12259 
12260 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
12261 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12262 					const struct btf *btf,
12263 					const struct btf_type *t, int rec)
12264 {
12265 	const struct btf_type *member_type;
12266 	const struct btf_member *member;
12267 	u32 i;
12268 
12269 	if (!btf_type_is_struct(t))
12270 		return false;
12271 
12272 	for_each_member(i, t, member) {
12273 		const struct btf_array *array;
12274 
12275 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12276 		if (btf_type_is_struct(member_type)) {
12277 			if (rec >= 3) {
12278 				verbose(env, "max struct nesting depth exceeded\n");
12279 				return false;
12280 			}
12281 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12282 				return false;
12283 			continue;
12284 		}
12285 		if (btf_type_is_array(member_type)) {
12286 			array = btf_array(member_type);
12287 			if (!array->nelems)
12288 				return false;
12289 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12290 			if (!btf_type_is_scalar(member_type))
12291 				return false;
12292 			continue;
12293 		}
12294 		if (!btf_type_is_scalar(member_type))
12295 			return false;
12296 	}
12297 	return true;
12298 }
12299 
12300 enum kfunc_ptr_arg_type {
12301 	KF_ARG_PTR_TO_CTX,
12302 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12303 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12304 	KF_ARG_PTR_TO_DYNPTR,
12305 	KF_ARG_PTR_TO_ITER,
12306 	KF_ARG_PTR_TO_LIST_HEAD,
12307 	KF_ARG_PTR_TO_LIST_NODE,
12308 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12309 	KF_ARG_PTR_TO_MEM,
12310 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12311 	KF_ARG_PTR_TO_CALLBACK,
12312 	KF_ARG_PTR_TO_RB_ROOT,
12313 	KF_ARG_PTR_TO_RB_NODE,
12314 	KF_ARG_PTR_TO_NULL,
12315 	KF_ARG_PTR_TO_CONST_STR,
12316 	KF_ARG_PTR_TO_MAP,
12317 	KF_ARG_PTR_TO_WORKQUEUE,
12318 	KF_ARG_PTR_TO_IRQ_FLAG,
12319 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12320 	KF_ARG_PTR_TO_TASK_WORK,
12321 };
12322 
12323 enum special_kfunc_type {
12324 	KF_bpf_obj_new_impl,
12325 	KF_bpf_obj_drop_impl,
12326 	KF_bpf_refcount_acquire_impl,
12327 	KF_bpf_list_push_front_impl,
12328 	KF_bpf_list_push_back_impl,
12329 	KF_bpf_list_pop_front,
12330 	KF_bpf_list_pop_back,
12331 	KF_bpf_list_front,
12332 	KF_bpf_list_back,
12333 	KF_bpf_cast_to_kern_ctx,
12334 	KF_bpf_rdonly_cast,
12335 	KF_bpf_rcu_read_lock,
12336 	KF_bpf_rcu_read_unlock,
12337 	KF_bpf_rbtree_remove,
12338 	KF_bpf_rbtree_add_impl,
12339 	KF_bpf_rbtree_first,
12340 	KF_bpf_rbtree_root,
12341 	KF_bpf_rbtree_left,
12342 	KF_bpf_rbtree_right,
12343 	KF_bpf_dynptr_from_skb,
12344 	KF_bpf_dynptr_from_xdp,
12345 	KF_bpf_dynptr_from_skb_meta,
12346 	KF_bpf_xdp_pull_data,
12347 	KF_bpf_dynptr_slice,
12348 	KF_bpf_dynptr_slice_rdwr,
12349 	KF_bpf_dynptr_clone,
12350 	KF_bpf_percpu_obj_new_impl,
12351 	KF_bpf_percpu_obj_drop_impl,
12352 	KF_bpf_throw,
12353 	KF_bpf_wq_set_callback_impl,
12354 	KF_bpf_preempt_disable,
12355 	KF_bpf_preempt_enable,
12356 	KF_bpf_iter_css_task_new,
12357 	KF_bpf_session_cookie,
12358 	KF_bpf_get_kmem_cache,
12359 	KF_bpf_local_irq_save,
12360 	KF_bpf_local_irq_restore,
12361 	KF_bpf_iter_num_new,
12362 	KF_bpf_iter_num_next,
12363 	KF_bpf_iter_num_destroy,
12364 	KF_bpf_set_dentry_xattr,
12365 	KF_bpf_remove_dentry_xattr,
12366 	KF_bpf_res_spin_lock,
12367 	KF_bpf_res_spin_unlock,
12368 	KF_bpf_res_spin_lock_irqsave,
12369 	KF_bpf_res_spin_unlock_irqrestore,
12370 	KF_bpf_dynptr_from_file,
12371 	KF_bpf_dynptr_file_discard,
12372 	KF___bpf_trap,
12373 	KF_bpf_task_work_schedule_signal_impl,
12374 	KF_bpf_task_work_schedule_resume_impl,
12375 	KF_bpf_arena_alloc_pages,
12376 	KF_bpf_arena_free_pages,
12377 	KF_bpf_arena_reserve_pages,
12378 };
12379 
12380 BTF_ID_LIST(special_kfunc_list)
12381 BTF_ID(func, bpf_obj_new_impl)
12382 BTF_ID(func, bpf_obj_drop_impl)
12383 BTF_ID(func, bpf_refcount_acquire_impl)
12384 BTF_ID(func, bpf_list_push_front_impl)
12385 BTF_ID(func, bpf_list_push_back_impl)
12386 BTF_ID(func, bpf_list_pop_front)
12387 BTF_ID(func, bpf_list_pop_back)
12388 BTF_ID(func, bpf_list_front)
12389 BTF_ID(func, bpf_list_back)
12390 BTF_ID(func, bpf_cast_to_kern_ctx)
12391 BTF_ID(func, bpf_rdonly_cast)
12392 BTF_ID(func, bpf_rcu_read_lock)
12393 BTF_ID(func, bpf_rcu_read_unlock)
12394 BTF_ID(func, bpf_rbtree_remove)
12395 BTF_ID(func, bpf_rbtree_add_impl)
12396 BTF_ID(func, bpf_rbtree_first)
12397 BTF_ID(func, bpf_rbtree_root)
12398 BTF_ID(func, bpf_rbtree_left)
12399 BTF_ID(func, bpf_rbtree_right)
12400 #ifdef CONFIG_NET
12401 BTF_ID(func, bpf_dynptr_from_skb)
12402 BTF_ID(func, bpf_dynptr_from_xdp)
12403 BTF_ID(func, bpf_dynptr_from_skb_meta)
12404 BTF_ID(func, bpf_xdp_pull_data)
12405 #else
12406 BTF_ID_UNUSED
12407 BTF_ID_UNUSED
12408 BTF_ID_UNUSED
12409 BTF_ID_UNUSED
12410 #endif
12411 BTF_ID(func, bpf_dynptr_slice)
12412 BTF_ID(func, bpf_dynptr_slice_rdwr)
12413 BTF_ID(func, bpf_dynptr_clone)
12414 BTF_ID(func, bpf_percpu_obj_new_impl)
12415 BTF_ID(func, bpf_percpu_obj_drop_impl)
12416 BTF_ID(func, bpf_throw)
12417 BTF_ID(func, bpf_wq_set_callback_impl)
12418 BTF_ID(func, bpf_preempt_disable)
12419 BTF_ID(func, bpf_preempt_enable)
12420 #ifdef CONFIG_CGROUPS
12421 BTF_ID(func, bpf_iter_css_task_new)
12422 #else
12423 BTF_ID_UNUSED
12424 #endif
12425 #ifdef CONFIG_BPF_EVENTS
12426 BTF_ID(func, bpf_session_cookie)
12427 #else
12428 BTF_ID_UNUSED
12429 #endif
12430 BTF_ID(func, bpf_get_kmem_cache)
12431 BTF_ID(func, bpf_local_irq_save)
12432 BTF_ID(func, bpf_local_irq_restore)
12433 BTF_ID(func, bpf_iter_num_new)
12434 BTF_ID(func, bpf_iter_num_next)
12435 BTF_ID(func, bpf_iter_num_destroy)
12436 #ifdef CONFIG_BPF_LSM
12437 BTF_ID(func, bpf_set_dentry_xattr)
12438 BTF_ID(func, bpf_remove_dentry_xattr)
12439 #else
12440 BTF_ID_UNUSED
12441 BTF_ID_UNUSED
12442 #endif
12443 BTF_ID(func, bpf_res_spin_lock)
12444 BTF_ID(func, bpf_res_spin_unlock)
12445 BTF_ID(func, bpf_res_spin_lock_irqsave)
12446 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12447 BTF_ID(func, bpf_dynptr_from_file)
12448 BTF_ID(func, bpf_dynptr_file_discard)
12449 BTF_ID(func, __bpf_trap)
12450 BTF_ID(func, bpf_task_work_schedule_signal_impl)
12451 BTF_ID(func, bpf_task_work_schedule_resume_impl)
12452 BTF_ID(func, bpf_arena_alloc_pages)
12453 BTF_ID(func, bpf_arena_free_pages)
12454 BTF_ID(func, bpf_arena_reserve_pages)
12455 
12456 static bool is_task_work_add_kfunc(u32 func_id)
12457 {
12458 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal_impl] ||
12459 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume_impl];
12460 }
12461 
12462 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12463 {
12464 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12465 	    meta->arg_owning_ref) {
12466 		return false;
12467 	}
12468 
12469 	return meta->kfunc_flags & KF_RET_NULL;
12470 }
12471 
12472 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12473 {
12474 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12475 }
12476 
12477 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12478 {
12479 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12480 }
12481 
12482 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12483 {
12484 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12485 }
12486 
12487 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12488 {
12489 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12490 }
12491 
12492 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12493 {
12494 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12495 }
12496 
12497 static enum kfunc_ptr_arg_type
12498 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12499 		       struct bpf_kfunc_call_arg_meta *meta,
12500 		       const struct btf_type *t, const struct btf_type *ref_t,
12501 		       const char *ref_tname, const struct btf_param *args,
12502 		       int argno, int nargs)
12503 {
12504 	u32 regno = argno + 1;
12505 	struct bpf_reg_state *regs = cur_regs(env);
12506 	struct bpf_reg_state *reg = &regs[regno];
12507 	bool arg_mem_size = false;
12508 
12509 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12510 		return KF_ARG_PTR_TO_CTX;
12511 
12512 	if (argno + 1 < nargs &&
12513 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12514 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12515 		arg_mem_size = true;
12516 
12517 	/* In this function, we verify the kfunc's BTF as per the argument type,
12518 	 * leaving the rest of the verification with respect to the register
12519 	 * type to our caller. When a set of conditions hold in the BTF type of
12520 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12521 	 */
12522 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12523 		return KF_ARG_PTR_TO_CTX;
12524 
12525 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg) &&
12526 	    !arg_mem_size)
12527 		return KF_ARG_PTR_TO_NULL;
12528 
12529 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12530 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12531 
12532 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12533 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12534 
12535 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12536 		return KF_ARG_PTR_TO_DYNPTR;
12537 
12538 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12539 		return KF_ARG_PTR_TO_ITER;
12540 
12541 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12542 		return KF_ARG_PTR_TO_LIST_HEAD;
12543 
12544 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12545 		return KF_ARG_PTR_TO_LIST_NODE;
12546 
12547 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12548 		return KF_ARG_PTR_TO_RB_ROOT;
12549 
12550 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12551 		return KF_ARG_PTR_TO_RB_NODE;
12552 
12553 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12554 		return KF_ARG_PTR_TO_CONST_STR;
12555 
12556 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12557 		return KF_ARG_PTR_TO_MAP;
12558 
12559 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12560 		return KF_ARG_PTR_TO_WORKQUEUE;
12561 
12562 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12563 		return KF_ARG_PTR_TO_TASK_WORK;
12564 
12565 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12566 		return KF_ARG_PTR_TO_IRQ_FLAG;
12567 
12568 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12569 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12570 
12571 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12572 		if (!btf_type_is_struct(ref_t)) {
12573 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12574 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12575 			return -EINVAL;
12576 		}
12577 		return KF_ARG_PTR_TO_BTF_ID;
12578 	}
12579 
12580 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12581 		return KF_ARG_PTR_TO_CALLBACK;
12582 
12583 	/* This is the catch all argument type of register types supported by
12584 	 * check_helper_mem_access. However, we only allow when argument type is
12585 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12586 	 * arg_mem_size is true, the pointer can be void *.
12587 	 */
12588 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12589 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12590 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12591 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12592 		return -EINVAL;
12593 	}
12594 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12595 }
12596 
12597 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12598 					struct bpf_reg_state *reg,
12599 					const struct btf_type *ref_t,
12600 					const char *ref_tname, u32 ref_id,
12601 					struct bpf_kfunc_call_arg_meta *meta,
12602 					int argno)
12603 {
12604 	const struct btf_type *reg_ref_t;
12605 	bool strict_type_match = false;
12606 	const struct btf *reg_btf;
12607 	const char *reg_ref_tname;
12608 	bool taking_projection;
12609 	bool struct_same;
12610 	u32 reg_ref_id;
12611 
12612 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12613 		reg_btf = reg->btf;
12614 		reg_ref_id = reg->btf_id;
12615 	} else {
12616 		reg_btf = btf_vmlinux;
12617 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12618 	}
12619 
12620 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12621 	 * or releasing a reference, or are no-cast aliases. We do _not_
12622 	 * enforce strict matching for kfuncs by default,
12623 	 * as we want to enable BPF programs to pass types that are bitwise
12624 	 * equivalent without forcing them to explicitly cast with something
12625 	 * like bpf_cast_to_kern_ctx().
12626 	 *
12627 	 * For example, say we had a type like the following:
12628 	 *
12629 	 * struct bpf_cpumask {
12630 	 *	cpumask_t cpumask;
12631 	 *	refcount_t usage;
12632 	 * };
12633 	 *
12634 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12635 	 * to a struct cpumask, so it would be safe to pass a struct
12636 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12637 	 *
12638 	 * The philosophy here is similar to how we allow scalars of different
12639 	 * types to be passed to kfuncs as long as the size is the same. The
12640 	 * only difference here is that we're simply allowing
12641 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12642 	 * resolve types.
12643 	 */
12644 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12645 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12646 		strict_type_match = true;
12647 
12648 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12649 		     (reg->off || !tnum_is_const(reg->var_off) ||
12650 		      reg->var_off.value));
12651 
12652 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12653 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12654 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12655 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12656 	 * actually use it -- it must cast to the underlying type. So we allow
12657 	 * caller to pass in the underlying type.
12658 	 */
12659 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12660 	if (!taking_projection && !struct_same) {
12661 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12662 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12663 			btf_type_str(reg_ref_t), reg_ref_tname);
12664 		return -EINVAL;
12665 	}
12666 	return 0;
12667 }
12668 
12669 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12670 			     struct bpf_kfunc_call_arg_meta *meta)
12671 {
12672 	struct bpf_reg_state *reg = reg_state(env, regno);
12673 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12674 	bool irq_save;
12675 
12676 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12677 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12678 		irq_save = true;
12679 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12680 			kfunc_class = IRQ_LOCK_KFUNC;
12681 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12682 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12683 		irq_save = false;
12684 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12685 			kfunc_class = IRQ_LOCK_KFUNC;
12686 	} else {
12687 		verifier_bug(env, "unknown irq flags kfunc");
12688 		return -EFAULT;
12689 	}
12690 
12691 	if (irq_save) {
12692 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12693 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12694 			return -EINVAL;
12695 		}
12696 
12697 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12698 		if (err)
12699 			return err;
12700 
12701 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12702 		if (err)
12703 			return err;
12704 	} else {
12705 		err = is_irq_flag_reg_valid_init(env, reg);
12706 		if (err) {
12707 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12708 			return err;
12709 		}
12710 
12711 		err = mark_irq_flag_read(env, reg);
12712 		if (err)
12713 			return err;
12714 
12715 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12716 		if (err)
12717 			return err;
12718 	}
12719 	return 0;
12720 }
12721 
12722 
12723 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12724 {
12725 	struct btf_record *rec = reg_btf_record(reg);
12726 
12727 	if (!env->cur_state->active_locks) {
12728 		verifier_bug(env, "%s w/o active lock", __func__);
12729 		return -EFAULT;
12730 	}
12731 
12732 	if (type_flag(reg->type) & NON_OWN_REF) {
12733 		verifier_bug(env, "NON_OWN_REF already set");
12734 		return -EFAULT;
12735 	}
12736 
12737 	reg->type |= NON_OWN_REF;
12738 	if (rec->refcount_off >= 0)
12739 		reg->type |= MEM_RCU;
12740 
12741 	return 0;
12742 }
12743 
12744 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12745 {
12746 	struct bpf_verifier_state *state = env->cur_state;
12747 	struct bpf_func_state *unused;
12748 	struct bpf_reg_state *reg;
12749 	int i;
12750 
12751 	if (!ref_obj_id) {
12752 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12753 		return -EFAULT;
12754 	}
12755 
12756 	for (i = 0; i < state->acquired_refs; i++) {
12757 		if (state->refs[i].id != ref_obj_id)
12758 			continue;
12759 
12760 		/* Clear ref_obj_id here so release_reference doesn't clobber
12761 		 * the whole reg
12762 		 */
12763 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12764 			if (reg->ref_obj_id == ref_obj_id) {
12765 				reg->ref_obj_id = 0;
12766 				ref_set_non_owning(env, reg);
12767 			}
12768 		}));
12769 		return 0;
12770 	}
12771 
12772 	verifier_bug(env, "ref state missing for ref_obj_id");
12773 	return -EFAULT;
12774 }
12775 
12776 /* Implementation details:
12777  *
12778  * Each register points to some region of memory, which we define as an
12779  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12780  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12781  * allocation. The lock and the data it protects are colocated in the same
12782  * memory region.
12783  *
12784  * Hence, everytime a register holds a pointer value pointing to such
12785  * allocation, the verifier preserves a unique reg->id for it.
12786  *
12787  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12788  * bpf_spin_lock is called.
12789  *
12790  * To enable this, lock state in the verifier captures two values:
12791  *	active_lock.ptr = Register's type specific pointer
12792  *	active_lock.id  = A unique ID for each register pointer value
12793  *
12794  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12795  * supported register types.
12796  *
12797  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12798  * allocated objects is the reg->btf pointer.
12799  *
12800  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12801  * can establish the provenance of the map value statically for each distinct
12802  * lookup into such maps. They always contain a single map value hence unique
12803  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12804  *
12805  * So, in case of global variables, they use array maps with max_entries = 1,
12806  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12807  * into the same map value as max_entries is 1, as described above).
12808  *
12809  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12810  * outer map pointer (in verifier context), but each lookup into an inner map
12811  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12812  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12813  * will get different reg->id assigned to each lookup, hence different
12814  * active_lock.id.
12815  *
12816  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12817  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12818  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12819  */
12820 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12821 {
12822 	struct bpf_reference_state *s;
12823 	void *ptr;
12824 	u32 id;
12825 
12826 	switch ((int)reg->type) {
12827 	case PTR_TO_MAP_VALUE:
12828 		ptr = reg->map_ptr;
12829 		break;
12830 	case PTR_TO_BTF_ID | MEM_ALLOC:
12831 		ptr = reg->btf;
12832 		break;
12833 	default:
12834 		verifier_bug(env, "unknown reg type for lock check");
12835 		return -EFAULT;
12836 	}
12837 	id = reg->id;
12838 
12839 	if (!env->cur_state->active_locks)
12840 		return -EINVAL;
12841 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12842 	if (!s) {
12843 		verbose(env, "held lock and object are not in the same allocation\n");
12844 		return -EINVAL;
12845 	}
12846 	return 0;
12847 }
12848 
12849 static bool is_bpf_list_api_kfunc(u32 btf_id)
12850 {
12851 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12852 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12853 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12854 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12855 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12856 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12857 }
12858 
12859 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12860 {
12861 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12862 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12863 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12864 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12865 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12866 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12867 }
12868 
12869 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12870 {
12871 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12872 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12873 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12874 }
12875 
12876 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12877 {
12878 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12879 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12880 }
12881 
12882 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12883 {
12884 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12885 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12886 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12887 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12888 }
12889 
12890 static bool is_bpf_arena_kfunc(u32 btf_id)
12891 {
12892 	return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] ||
12893 	       btf_id == special_kfunc_list[KF_bpf_arena_free_pages] ||
12894 	       btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages];
12895 }
12896 
12897 static bool kfunc_spin_allowed(u32 btf_id)
12898 {
12899 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12900 	       is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id);
12901 }
12902 
12903 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12904 {
12905 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12906 }
12907 
12908 static bool is_async_callback_calling_kfunc(u32 btf_id)
12909 {
12910 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12911 	       is_task_work_add_kfunc(btf_id);
12912 }
12913 
12914 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12915 {
12916 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12917 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12918 }
12919 
12920 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12921 {
12922 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12923 }
12924 
12925 static bool is_callback_calling_kfunc(u32 btf_id)
12926 {
12927 	return is_sync_callback_calling_kfunc(btf_id) ||
12928 	       is_async_callback_calling_kfunc(btf_id);
12929 }
12930 
12931 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12932 {
12933 	return is_bpf_rbtree_api_kfunc(btf_id);
12934 }
12935 
12936 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12937 					  enum btf_field_type head_field_type,
12938 					  u32 kfunc_btf_id)
12939 {
12940 	bool ret;
12941 
12942 	switch (head_field_type) {
12943 	case BPF_LIST_HEAD:
12944 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12945 		break;
12946 	case BPF_RB_ROOT:
12947 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12948 		break;
12949 	default:
12950 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12951 			btf_field_type_name(head_field_type));
12952 		return false;
12953 	}
12954 
12955 	if (!ret)
12956 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12957 			btf_field_type_name(head_field_type));
12958 	return ret;
12959 }
12960 
12961 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12962 					  enum btf_field_type node_field_type,
12963 					  u32 kfunc_btf_id)
12964 {
12965 	bool ret;
12966 
12967 	switch (node_field_type) {
12968 	case BPF_LIST_NODE:
12969 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12970 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12971 		break;
12972 	case BPF_RB_NODE:
12973 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12974 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12975 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12976 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12977 		break;
12978 	default:
12979 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12980 			btf_field_type_name(node_field_type));
12981 		return false;
12982 	}
12983 
12984 	if (!ret)
12985 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12986 			btf_field_type_name(node_field_type));
12987 	return ret;
12988 }
12989 
12990 static int
12991 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12992 				   struct bpf_reg_state *reg, u32 regno,
12993 				   struct bpf_kfunc_call_arg_meta *meta,
12994 				   enum btf_field_type head_field_type,
12995 				   struct btf_field **head_field)
12996 {
12997 	const char *head_type_name;
12998 	struct btf_field *field;
12999 	struct btf_record *rec;
13000 	u32 head_off;
13001 
13002 	if (meta->btf != btf_vmlinux) {
13003 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13004 		return -EFAULT;
13005 	}
13006 
13007 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
13008 		return -EFAULT;
13009 
13010 	head_type_name = btf_field_type_name(head_field_type);
13011 	if (!tnum_is_const(reg->var_off)) {
13012 		verbose(env,
13013 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13014 			regno, head_type_name);
13015 		return -EINVAL;
13016 	}
13017 
13018 	rec = reg_btf_record(reg);
13019 	head_off = reg->off + reg->var_off.value;
13020 	field = btf_record_find(rec, head_off, head_field_type);
13021 	if (!field) {
13022 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
13023 		return -EINVAL;
13024 	}
13025 
13026 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
13027 	if (check_reg_allocation_locked(env, reg)) {
13028 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
13029 			rec->spin_lock_off, head_type_name);
13030 		return -EINVAL;
13031 	}
13032 
13033 	if (*head_field) {
13034 		verifier_bug(env, "repeating %s arg", head_type_name);
13035 		return -EFAULT;
13036 	}
13037 	*head_field = field;
13038 	return 0;
13039 }
13040 
13041 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
13042 					   struct bpf_reg_state *reg, u32 regno,
13043 					   struct bpf_kfunc_call_arg_meta *meta)
13044 {
13045 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
13046 							  &meta->arg_list_head.field);
13047 }
13048 
13049 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
13050 					     struct bpf_reg_state *reg, u32 regno,
13051 					     struct bpf_kfunc_call_arg_meta *meta)
13052 {
13053 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
13054 							  &meta->arg_rbtree_root.field);
13055 }
13056 
13057 static int
13058 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
13059 				   struct bpf_reg_state *reg, u32 regno,
13060 				   struct bpf_kfunc_call_arg_meta *meta,
13061 				   enum btf_field_type head_field_type,
13062 				   enum btf_field_type node_field_type,
13063 				   struct btf_field **node_field)
13064 {
13065 	const char *node_type_name;
13066 	const struct btf_type *et, *t;
13067 	struct btf_field *field;
13068 	u32 node_off;
13069 
13070 	if (meta->btf != btf_vmlinux) {
13071 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
13072 		return -EFAULT;
13073 	}
13074 
13075 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
13076 		return -EFAULT;
13077 
13078 	node_type_name = btf_field_type_name(node_field_type);
13079 	if (!tnum_is_const(reg->var_off)) {
13080 		verbose(env,
13081 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
13082 			regno, node_type_name);
13083 		return -EINVAL;
13084 	}
13085 
13086 	node_off = reg->off + reg->var_off.value;
13087 	field = reg_find_field_offset(reg, node_off, node_field_type);
13088 	if (!field) {
13089 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
13090 		return -EINVAL;
13091 	}
13092 
13093 	field = *node_field;
13094 
13095 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
13096 	t = btf_type_by_id(reg->btf, reg->btf_id);
13097 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
13098 				  field->graph_root.value_btf_id, true)) {
13099 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
13100 			"in struct %s, but arg is at offset=%d in struct %s\n",
13101 			btf_field_type_name(head_field_type),
13102 			btf_field_type_name(node_field_type),
13103 			field->graph_root.node_offset,
13104 			btf_name_by_offset(field->graph_root.btf, et->name_off),
13105 			node_off, btf_name_by_offset(reg->btf, t->name_off));
13106 		return -EINVAL;
13107 	}
13108 	meta->arg_btf = reg->btf;
13109 	meta->arg_btf_id = reg->btf_id;
13110 
13111 	if (node_off != field->graph_root.node_offset) {
13112 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
13113 			node_off, btf_field_type_name(node_field_type),
13114 			field->graph_root.node_offset,
13115 			btf_name_by_offset(field->graph_root.btf, et->name_off));
13116 		return -EINVAL;
13117 	}
13118 
13119 	return 0;
13120 }
13121 
13122 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
13123 					   struct bpf_reg_state *reg, u32 regno,
13124 					   struct bpf_kfunc_call_arg_meta *meta)
13125 {
13126 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13127 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13128 						  &meta->arg_list_head.field);
13129 }
13130 
13131 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13132 					     struct bpf_reg_state *reg, u32 regno,
13133 					     struct bpf_kfunc_call_arg_meta *meta)
13134 {
13135 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13136 						  BPF_RB_ROOT, BPF_RB_NODE,
13137 						  &meta->arg_rbtree_root.field);
13138 }
13139 
13140 /*
13141  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13142  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13143  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13144  * them can only be attached to some specific hook points.
13145  */
13146 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13147 {
13148 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13149 
13150 	switch (prog_type) {
13151 	case BPF_PROG_TYPE_LSM:
13152 		return true;
13153 	case BPF_PROG_TYPE_TRACING:
13154 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13155 			return true;
13156 		fallthrough;
13157 	default:
13158 		return in_sleepable(env);
13159 	}
13160 }
13161 
13162 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13163 			    int insn_idx)
13164 {
13165 	const char *func_name = meta->func_name, *ref_tname;
13166 	const struct btf *btf = meta->btf;
13167 	const struct btf_param *args;
13168 	struct btf_record *rec;
13169 	u32 i, nargs;
13170 	int ret;
13171 
13172 	args = (const struct btf_param *)(meta->func_proto + 1);
13173 	nargs = btf_type_vlen(meta->func_proto);
13174 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13175 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13176 			MAX_BPF_FUNC_REG_ARGS);
13177 		return -EINVAL;
13178 	}
13179 
13180 	/* Check that BTF function arguments match actual types that the
13181 	 * verifier sees.
13182 	 */
13183 	for (i = 0; i < nargs; i++) {
13184 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13185 		const struct btf_type *t, *ref_t, *resolve_ret;
13186 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13187 		u32 regno = i + 1, ref_id, type_size;
13188 		bool is_ret_buf_sz = false;
13189 		int kf_arg_type;
13190 
13191 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13192 
13193 		if (is_kfunc_arg_ignore(btf, &args[i]))
13194 			continue;
13195 
13196 		if (is_kfunc_arg_prog(btf, &args[i])) {
13197 			/* Used to reject repeated use of __prog. */
13198 			if (meta->arg_prog) {
13199 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13200 				return -EFAULT;
13201 			}
13202 			meta->arg_prog = true;
13203 			cur_aux(env)->arg_prog = regno;
13204 			continue;
13205 		}
13206 
13207 		if (btf_type_is_scalar(t)) {
13208 			if (reg->type != SCALAR_VALUE) {
13209 				verbose(env, "R%d is not a scalar\n", regno);
13210 				return -EINVAL;
13211 			}
13212 
13213 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13214 				if (meta->arg_constant.found) {
13215 					verifier_bug(env, "only one constant argument permitted");
13216 					return -EFAULT;
13217 				}
13218 				if (!tnum_is_const(reg->var_off)) {
13219 					verbose(env, "R%d must be a known constant\n", regno);
13220 					return -EINVAL;
13221 				}
13222 				ret = mark_chain_precision(env, regno);
13223 				if (ret < 0)
13224 					return ret;
13225 				meta->arg_constant.found = true;
13226 				meta->arg_constant.value = reg->var_off.value;
13227 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13228 				meta->r0_rdonly = true;
13229 				is_ret_buf_sz = true;
13230 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13231 				is_ret_buf_sz = true;
13232 			}
13233 
13234 			if (is_ret_buf_sz) {
13235 				if (meta->r0_size) {
13236 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13237 					return -EINVAL;
13238 				}
13239 
13240 				if (!tnum_is_const(reg->var_off)) {
13241 					verbose(env, "R%d is not a const\n", regno);
13242 					return -EINVAL;
13243 				}
13244 
13245 				meta->r0_size = reg->var_off.value;
13246 				ret = mark_chain_precision(env, regno);
13247 				if (ret)
13248 					return ret;
13249 			}
13250 			continue;
13251 		}
13252 
13253 		if (!btf_type_is_ptr(t)) {
13254 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13255 			return -EINVAL;
13256 		}
13257 
13258 		if ((register_is_null(reg) || type_may_be_null(reg->type)) &&
13259 		    !is_kfunc_arg_nullable(meta->btf, &args[i])) {
13260 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13261 			return -EACCES;
13262 		}
13263 
13264 		if (reg->ref_obj_id) {
13265 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13266 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13267 					     regno, reg->ref_obj_id,
13268 					     meta->ref_obj_id);
13269 				return -EFAULT;
13270 			}
13271 			meta->ref_obj_id = reg->ref_obj_id;
13272 			if (is_kfunc_release(meta))
13273 				meta->release_regno = regno;
13274 		}
13275 
13276 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13277 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13278 
13279 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13280 		if (kf_arg_type < 0)
13281 			return kf_arg_type;
13282 
13283 		switch (kf_arg_type) {
13284 		case KF_ARG_PTR_TO_NULL:
13285 			continue;
13286 		case KF_ARG_PTR_TO_MAP:
13287 			if (!reg->map_ptr) {
13288 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13289 				return -EINVAL;
13290 			}
13291 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13292 					      reg->map_ptr->record->task_work_off >= 0)) {
13293 				/* Use map_uid (which is unique id of inner map) to reject:
13294 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13295 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13296 				 * if (inner_map1 && inner_map2) {
13297 				 *     wq = bpf_map_lookup_elem(inner_map1);
13298 				 *     if (wq)
13299 				 *         // mismatch would have been allowed
13300 				 *         bpf_wq_init(wq, inner_map2);
13301 				 * }
13302 				 *
13303 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13304 				 */
13305 				if (meta->map.ptr != reg->map_ptr ||
13306 				    meta->map.uid != reg->map_uid) {
13307 					if (reg->map_ptr->record->task_work_off >= 0) {
13308 						verbose(env,
13309 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13310 							meta->map.uid, reg->map_uid);
13311 						return -EINVAL;
13312 					}
13313 					verbose(env,
13314 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13315 						meta->map.uid, reg->map_uid);
13316 					return -EINVAL;
13317 				}
13318 			}
13319 			meta->map.ptr = reg->map_ptr;
13320 			meta->map.uid = reg->map_uid;
13321 			fallthrough;
13322 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13323 		case KF_ARG_PTR_TO_BTF_ID:
13324 			if (!is_trusted_reg(reg)) {
13325 				if (!is_kfunc_rcu(meta)) {
13326 					verbose(env, "R%d must be referenced or trusted\n", regno);
13327 					return -EINVAL;
13328 				}
13329 				if (!is_rcu_reg(reg)) {
13330 					verbose(env, "R%d must be a rcu pointer\n", regno);
13331 					return -EINVAL;
13332 				}
13333 			}
13334 			fallthrough;
13335 		case KF_ARG_PTR_TO_CTX:
13336 		case KF_ARG_PTR_TO_DYNPTR:
13337 		case KF_ARG_PTR_TO_ITER:
13338 		case KF_ARG_PTR_TO_LIST_HEAD:
13339 		case KF_ARG_PTR_TO_LIST_NODE:
13340 		case KF_ARG_PTR_TO_RB_ROOT:
13341 		case KF_ARG_PTR_TO_RB_NODE:
13342 		case KF_ARG_PTR_TO_MEM:
13343 		case KF_ARG_PTR_TO_MEM_SIZE:
13344 		case KF_ARG_PTR_TO_CALLBACK:
13345 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13346 		case KF_ARG_PTR_TO_CONST_STR:
13347 		case KF_ARG_PTR_TO_WORKQUEUE:
13348 		case KF_ARG_PTR_TO_TASK_WORK:
13349 		case KF_ARG_PTR_TO_IRQ_FLAG:
13350 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13351 			break;
13352 		default:
13353 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13354 			return -EFAULT;
13355 		}
13356 
13357 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13358 			arg_type |= OBJ_RELEASE;
13359 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13360 		if (ret < 0)
13361 			return ret;
13362 
13363 		switch (kf_arg_type) {
13364 		case KF_ARG_PTR_TO_CTX:
13365 			if (reg->type != PTR_TO_CTX) {
13366 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13367 					i, reg_type_str(env, reg->type));
13368 				return -EINVAL;
13369 			}
13370 
13371 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13372 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13373 				if (ret < 0)
13374 					return -EINVAL;
13375 				meta->ret_btf_id  = ret;
13376 			}
13377 			break;
13378 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13379 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13380 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13381 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13382 					return -EINVAL;
13383 				}
13384 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13385 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13386 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13387 					return -EINVAL;
13388 				}
13389 			} else {
13390 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13391 				return -EINVAL;
13392 			}
13393 			if (!reg->ref_obj_id) {
13394 				verbose(env, "allocated object must be referenced\n");
13395 				return -EINVAL;
13396 			}
13397 			if (meta->btf == btf_vmlinux) {
13398 				meta->arg_btf = reg->btf;
13399 				meta->arg_btf_id = reg->btf_id;
13400 			}
13401 			break;
13402 		case KF_ARG_PTR_TO_DYNPTR:
13403 		{
13404 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13405 			int clone_ref_obj_id = 0;
13406 
13407 			if (reg->type == CONST_PTR_TO_DYNPTR)
13408 				dynptr_arg_type |= MEM_RDONLY;
13409 
13410 			if (is_kfunc_arg_uninit(btf, &args[i]))
13411 				dynptr_arg_type |= MEM_UNINIT;
13412 
13413 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13414 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13415 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13416 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13417 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13418 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13419 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
13420 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13421 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
13422 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
13423 				meta->release_regno = regno;
13424 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13425 				   (dynptr_arg_type & MEM_UNINIT)) {
13426 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13427 
13428 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13429 					verifier_bug(env, "no dynptr type for parent of clone");
13430 					return -EFAULT;
13431 				}
13432 
13433 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13434 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13435 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13436 					verifier_bug(env, "missing ref obj id for parent of clone");
13437 					return -EFAULT;
13438 				}
13439 			}
13440 
13441 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13442 			if (ret < 0)
13443 				return ret;
13444 
13445 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13446 				int id = dynptr_id(env, reg);
13447 
13448 				if (id < 0) {
13449 					verifier_bug(env, "failed to obtain dynptr id");
13450 					return id;
13451 				}
13452 				meta->initialized_dynptr.id = id;
13453 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13454 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13455 			}
13456 
13457 			break;
13458 		}
13459 		case KF_ARG_PTR_TO_ITER:
13460 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13461 				if (!check_css_task_iter_allowlist(env)) {
13462 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13463 					return -EINVAL;
13464 				}
13465 			}
13466 			ret = process_iter_arg(env, regno, insn_idx, meta);
13467 			if (ret < 0)
13468 				return ret;
13469 			break;
13470 		case KF_ARG_PTR_TO_LIST_HEAD:
13471 			if (reg->type != PTR_TO_MAP_VALUE &&
13472 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13473 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13474 				return -EINVAL;
13475 			}
13476 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13477 				verbose(env, "allocated object must be referenced\n");
13478 				return -EINVAL;
13479 			}
13480 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13481 			if (ret < 0)
13482 				return ret;
13483 			break;
13484 		case KF_ARG_PTR_TO_RB_ROOT:
13485 			if (reg->type != PTR_TO_MAP_VALUE &&
13486 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13487 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13488 				return -EINVAL;
13489 			}
13490 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13491 				verbose(env, "allocated object must be referenced\n");
13492 				return -EINVAL;
13493 			}
13494 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13495 			if (ret < 0)
13496 				return ret;
13497 			break;
13498 		case KF_ARG_PTR_TO_LIST_NODE:
13499 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13500 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13501 				return -EINVAL;
13502 			}
13503 			if (!reg->ref_obj_id) {
13504 				verbose(env, "allocated object must be referenced\n");
13505 				return -EINVAL;
13506 			}
13507 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13508 			if (ret < 0)
13509 				return ret;
13510 			break;
13511 		case KF_ARG_PTR_TO_RB_NODE:
13512 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13513 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13514 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13515 					return -EINVAL;
13516 				}
13517 				if (!reg->ref_obj_id) {
13518 					verbose(env, "allocated object must be referenced\n");
13519 					return -EINVAL;
13520 				}
13521 			} else {
13522 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13523 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13524 					return -EINVAL;
13525 				}
13526 				if (in_rbtree_lock_required_cb(env)) {
13527 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13528 					return -EINVAL;
13529 				}
13530 			}
13531 
13532 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13533 			if (ret < 0)
13534 				return ret;
13535 			break;
13536 		case KF_ARG_PTR_TO_MAP:
13537 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13538 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13539 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13540 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13541 			fallthrough;
13542 		case KF_ARG_PTR_TO_BTF_ID:
13543 			/* Only base_type is checked, further checks are done here */
13544 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13545 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13546 			    !reg2btf_ids[base_type(reg->type)]) {
13547 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13548 				verbose(env, "expected %s or socket\n",
13549 					reg_type_str(env, base_type(reg->type) |
13550 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13551 				return -EINVAL;
13552 			}
13553 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13554 			if (ret < 0)
13555 				return ret;
13556 			break;
13557 		case KF_ARG_PTR_TO_MEM:
13558 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13559 			if (IS_ERR(resolve_ret)) {
13560 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13561 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13562 				return -EINVAL;
13563 			}
13564 			ret = check_mem_reg(env, reg, regno, type_size);
13565 			if (ret < 0)
13566 				return ret;
13567 			break;
13568 		case KF_ARG_PTR_TO_MEM_SIZE:
13569 		{
13570 			struct bpf_reg_state *buff_reg = &regs[regno];
13571 			const struct btf_param *buff_arg = &args[i];
13572 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13573 			const struct btf_param *size_arg = &args[i + 1];
13574 
13575 			if (!register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) {
13576 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13577 				if (ret < 0) {
13578 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13579 					return ret;
13580 				}
13581 			}
13582 
13583 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13584 				if (meta->arg_constant.found) {
13585 					verifier_bug(env, "only one constant argument permitted");
13586 					return -EFAULT;
13587 				}
13588 				if (!tnum_is_const(size_reg->var_off)) {
13589 					verbose(env, "R%d must be a known constant\n", regno + 1);
13590 					return -EINVAL;
13591 				}
13592 				meta->arg_constant.found = true;
13593 				meta->arg_constant.value = size_reg->var_off.value;
13594 			}
13595 
13596 			/* Skip next '__sz' or '__szk' argument */
13597 			i++;
13598 			break;
13599 		}
13600 		case KF_ARG_PTR_TO_CALLBACK:
13601 			if (reg->type != PTR_TO_FUNC) {
13602 				verbose(env, "arg%d expected pointer to func\n", i);
13603 				return -EINVAL;
13604 			}
13605 			meta->subprogno = reg->subprogno;
13606 			break;
13607 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13608 			if (!type_is_ptr_alloc_obj(reg->type)) {
13609 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13610 				return -EINVAL;
13611 			}
13612 			if (!type_is_non_owning_ref(reg->type))
13613 				meta->arg_owning_ref = true;
13614 
13615 			rec = reg_btf_record(reg);
13616 			if (!rec) {
13617 				verifier_bug(env, "Couldn't find btf_record");
13618 				return -EFAULT;
13619 			}
13620 
13621 			if (rec->refcount_off < 0) {
13622 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13623 				return -EINVAL;
13624 			}
13625 
13626 			meta->arg_btf = reg->btf;
13627 			meta->arg_btf_id = reg->btf_id;
13628 			break;
13629 		case KF_ARG_PTR_TO_CONST_STR:
13630 			if (reg->type != PTR_TO_MAP_VALUE) {
13631 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13632 				return -EINVAL;
13633 			}
13634 			ret = check_reg_const_str(env, reg, regno);
13635 			if (ret)
13636 				return ret;
13637 			break;
13638 		case KF_ARG_PTR_TO_WORKQUEUE:
13639 			if (reg->type != PTR_TO_MAP_VALUE) {
13640 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13641 				return -EINVAL;
13642 			}
13643 			ret = process_wq_func(env, regno, meta);
13644 			if (ret < 0)
13645 				return ret;
13646 			break;
13647 		case KF_ARG_PTR_TO_TASK_WORK:
13648 			if (reg->type != PTR_TO_MAP_VALUE) {
13649 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13650 				return -EINVAL;
13651 			}
13652 			ret = process_task_work_func(env, regno, meta);
13653 			if (ret < 0)
13654 				return ret;
13655 			break;
13656 		case KF_ARG_PTR_TO_IRQ_FLAG:
13657 			if (reg->type != PTR_TO_STACK) {
13658 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13659 				return -EINVAL;
13660 			}
13661 			ret = process_irq_flag(env, regno, meta);
13662 			if (ret < 0)
13663 				return ret;
13664 			break;
13665 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13666 		{
13667 			int flags = PROCESS_RES_LOCK;
13668 
13669 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13670 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13671 				return -EINVAL;
13672 			}
13673 
13674 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13675 				return -EFAULT;
13676 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13677 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13678 				flags |= PROCESS_SPIN_LOCK;
13679 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13680 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13681 				flags |= PROCESS_LOCK_IRQ;
13682 			ret = process_spin_lock(env, regno, flags);
13683 			if (ret < 0)
13684 				return ret;
13685 			break;
13686 		}
13687 		}
13688 	}
13689 
13690 	if (is_kfunc_release(meta) && !meta->release_regno) {
13691 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13692 			func_name);
13693 		return -EINVAL;
13694 	}
13695 
13696 	return 0;
13697 }
13698 
13699 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13700 			    struct bpf_insn *insn,
13701 			    struct bpf_kfunc_call_arg_meta *meta,
13702 			    const char **kfunc_name)
13703 {
13704 	const struct btf_type *func, *func_proto;
13705 	u32 func_id, *kfunc_flags;
13706 	const char *func_name;
13707 	struct btf *desc_btf;
13708 
13709 	if (kfunc_name)
13710 		*kfunc_name = NULL;
13711 
13712 	if (!insn->imm)
13713 		return -EINVAL;
13714 
13715 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13716 	if (IS_ERR(desc_btf))
13717 		return PTR_ERR(desc_btf);
13718 
13719 	func_id = insn->imm;
13720 	func = btf_type_by_id(desc_btf, func_id);
13721 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13722 	if (kfunc_name)
13723 		*kfunc_name = func_name;
13724 	func_proto = btf_type_by_id(desc_btf, func->type);
13725 
13726 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13727 	if (!kfunc_flags) {
13728 		return -EACCES;
13729 	}
13730 
13731 	memset(meta, 0, sizeof(*meta));
13732 	meta->btf = desc_btf;
13733 	meta->func_id = func_id;
13734 	meta->kfunc_flags = *kfunc_flags;
13735 	meta->func_proto = func_proto;
13736 	meta->func_name = func_name;
13737 
13738 	return 0;
13739 }
13740 
13741 /* check special kfuncs and return:
13742  *  1  - not fall-through to 'else' branch, continue verification
13743  *  0  - fall-through to 'else' branch
13744  * < 0 - not fall-through to 'else' branch, return error
13745  */
13746 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13747 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13748 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13749 {
13750 	const struct btf_type *ret_t;
13751 	int err = 0;
13752 
13753 	if (meta->btf != btf_vmlinux)
13754 		return 0;
13755 
13756 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13757 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13758 		struct btf_struct_meta *struct_meta;
13759 		struct btf *ret_btf;
13760 		u32 ret_btf_id;
13761 
13762 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13763 			return -ENOMEM;
13764 
13765 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13766 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13767 			return -EINVAL;
13768 		}
13769 
13770 		ret_btf = env->prog->aux->btf;
13771 		ret_btf_id = meta->arg_constant.value;
13772 
13773 		/* This may be NULL due to user not supplying a BTF */
13774 		if (!ret_btf) {
13775 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13776 			return -EINVAL;
13777 		}
13778 
13779 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13780 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13781 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13782 			return -EINVAL;
13783 		}
13784 
13785 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13786 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13787 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13788 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13789 				return -EINVAL;
13790 			}
13791 
13792 			if (!bpf_global_percpu_ma_set) {
13793 				mutex_lock(&bpf_percpu_ma_lock);
13794 				if (!bpf_global_percpu_ma_set) {
13795 					/* Charge memory allocated with bpf_global_percpu_ma to
13796 					 * root memcg. The obj_cgroup for root memcg is NULL.
13797 					 */
13798 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13799 					if (!err)
13800 						bpf_global_percpu_ma_set = true;
13801 				}
13802 				mutex_unlock(&bpf_percpu_ma_lock);
13803 				if (err)
13804 					return err;
13805 			}
13806 
13807 			mutex_lock(&bpf_percpu_ma_lock);
13808 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13809 			mutex_unlock(&bpf_percpu_ma_lock);
13810 			if (err)
13811 				return err;
13812 		}
13813 
13814 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13815 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13816 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13817 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13818 				return -EINVAL;
13819 			}
13820 
13821 			if (struct_meta) {
13822 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13823 				return -EINVAL;
13824 			}
13825 		}
13826 
13827 		mark_reg_known_zero(env, regs, BPF_REG_0);
13828 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13829 		regs[BPF_REG_0].btf = ret_btf;
13830 		regs[BPF_REG_0].btf_id = ret_btf_id;
13831 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13832 			regs[BPF_REG_0].type |= MEM_PERCPU;
13833 
13834 		insn_aux->obj_new_size = ret_t->size;
13835 		insn_aux->kptr_struct_meta = struct_meta;
13836 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13837 		mark_reg_known_zero(env, regs, BPF_REG_0);
13838 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13839 		regs[BPF_REG_0].btf = meta->arg_btf;
13840 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13841 
13842 		insn_aux->kptr_struct_meta =
13843 			btf_find_struct_meta(meta->arg_btf,
13844 					     meta->arg_btf_id);
13845 	} else if (is_list_node_type(ptr_type)) {
13846 		struct btf_field *field = meta->arg_list_head.field;
13847 
13848 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13849 	} else if (is_rbtree_node_type(ptr_type)) {
13850 		struct btf_field *field = meta->arg_rbtree_root.field;
13851 
13852 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13853 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13854 		mark_reg_known_zero(env, regs, BPF_REG_0);
13855 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13856 		regs[BPF_REG_0].btf = desc_btf;
13857 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13858 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13859 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13860 		if (!ret_t) {
13861 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13862 				meta->arg_constant.value);
13863 			return -EINVAL;
13864 		} else if (btf_type_is_struct(ret_t)) {
13865 			mark_reg_known_zero(env, regs, BPF_REG_0);
13866 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13867 			regs[BPF_REG_0].btf = desc_btf;
13868 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13869 		} else if (btf_type_is_void(ret_t)) {
13870 			mark_reg_known_zero(env, regs, BPF_REG_0);
13871 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13872 			regs[BPF_REG_0].mem_size = 0;
13873 		} else {
13874 			verbose(env,
13875 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13876 			return -EINVAL;
13877 		}
13878 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13879 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13880 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13881 
13882 		mark_reg_known_zero(env, regs, BPF_REG_0);
13883 
13884 		if (!meta->arg_constant.found) {
13885 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13886 			return -EFAULT;
13887 		}
13888 
13889 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13890 
13891 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13892 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13893 
13894 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13895 			regs[BPF_REG_0].type |= MEM_RDONLY;
13896 		} else {
13897 			/* this will set env->seen_direct_write to true */
13898 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13899 				verbose(env, "the prog does not allow writes to packet data\n");
13900 				return -EINVAL;
13901 			}
13902 		}
13903 
13904 		if (!meta->initialized_dynptr.id) {
13905 			verifier_bug(env, "no dynptr id");
13906 			return -EFAULT;
13907 		}
13908 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13909 
13910 		/* we don't need to set BPF_REG_0's ref obj id
13911 		 * because packet slices are not refcounted (see
13912 		 * dynptr_type_refcounted)
13913 		 */
13914 	} else {
13915 		return 0;
13916 	}
13917 
13918 	return 1;
13919 }
13920 
13921 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13922 
13923 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13924 			    int *insn_idx_p)
13925 {
13926 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13927 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13928 	struct bpf_reg_state *regs = cur_regs(env);
13929 	const char *func_name, *ptr_type_name;
13930 	const struct btf_type *t, *ptr_type;
13931 	struct bpf_kfunc_call_arg_meta meta;
13932 	struct bpf_insn_aux_data *insn_aux;
13933 	int err, insn_idx = *insn_idx_p;
13934 	const struct btf_param *args;
13935 	struct btf *desc_btf;
13936 
13937 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13938 	if (!insn->imm)
13939 		return 0;
13940 
13941 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13942 	if (err == -EACCES && func_name)
13943 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13944 	if (err)
13945 		return err;
13946 	desc_btf = meta.btf;
13947 	insn_aux = &env->insn_aux_data[insn_idx];
13948 
13949 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13950 
13951 	if (!insn->off &&
13952 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13953 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13954 		struct bpf_verifier_state *branch;
13955 		struct bpf_reg_state *regs;
13956 
13957 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13958 		if (IS_ERR(branch)) {
13959 			verbose(env, "failed to push state for failed lock acquisition\n");
13960 			return PTR_ERR(branch);
13961 		}
13962 
13963 		regs = branch->frame[branch->curframe]->regs;
13964 
13965 		/* Clear r0-r5 registers in forked state */
13966 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13967 			mark_reg_not_init(env, regs, caller_saved[i]);
13968 
13969 		mark_reg_unknown(env, regs, BPF_REG_0);
13970 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13971 		if (err) {
13972 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13973 			return err;
13974 		}
13975 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13976 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13977 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13978 		return -EFAULT;
13979 	}
13980 
13981 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13982 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13983 		return -EACCES;
13984 	}
13985 
13986 	sleepable = is_kfunc_sleepable(&meta);
13987 	if (sleepable && !in_sleepable(env)) {
13988 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13989 		return -EACCES;
13990 	}
13991 
13992 	/* Track non-sleepable context for kfuncs, same as for helpers. */
13993 	if (!in_sleepable_context(env))
13994 		insn_aux->non_sleepable = true;
13995 
13996 	/* Check the arguments */
13997 	err = check_kfunc_args(env, &meta, insn_idx);
13998 	if (err < 0)
13999 		return err;
14000 
14001 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14002 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14003 					 set_rbtree_add_callback_state);
14004 		if (err) {
14005 			verbose(env, "kfunc %s#%d failed callback verification\n",
14006 				func_name, meta.func_id);
14007 			return err;
14008 		}
14009 	}
14010 
14011 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
14012 		meta.r0_size = sizeof(u64);
14013 		meta.r0_rdonly = false;
14014 	}
14015 
14016 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
14017 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14018 					 set_timer_callback_state);
14019 		if (err) {
14020 			verbose(env, "kfunc %s#%d failed callback verification\n",
14021 				func_name, meta.func_id);
14022 			return err;
14023 		}
14024 	}
14025 
14026 	if (is_task_work_add_kfunc(meta.func_id)) {
14027 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14028 					 set_task_work_schedule_callback_state);
14029 		if (err) {
14030 			verbose(env, "kfunc %s#%d failed callback verification\n",
14031 				func_name, meta.func_id);
14032 			return err;
14033 		}
14034 	}
14035 
14036 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
14037 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
14038 
14039 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
14040 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
14041 
14042 	if (rcu_lock) {
14043 		env->cur_state->active_rcu_locks++;
14044 	} else if (rcu_unlock) {
14045 		struct bpf_func_state *state;
14046 		struct bpf_reg_state *reg;
14047 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
14048 
14049 		if (env->cur_state->active_rcu_locks == 0) {
14050 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
14051 			return -EINVAL;
14052 		}
14053 		if (--env->cur_state->active_rcu_locks == 0) {
14054 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
14055 				if (reg->type & MEM_RCU) {
14056 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
14057 					reg->type |= PTR_UNTRUSTED;
14058 				}
14059 			}));
14060 		}
14061 	} else if (sleepable && env->cur_state->active_rcu_locks) {
14062 		verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
14063 		return -EACCES;
14064 	}
14065 
14066 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
14067 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
14068 		return -EACCES;
14069 	}
14070 
14071 	if (env->cur_state->active_preempt_locks) {
14072 		if (preempt_disable) {
14073 			env->cur_state->active_preempt_locks++;
14074 		} else if (preempt_enable) {
14075 			env->cur_state->active_preempt_locks--;
14076 		} else if (sleepable) {
14077 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
14078 			return -EACCES;
14079 		}
14080 	} else if (preempt_disable) {
14081 		env->cur_state->active_preempt_locks++;
14082 	} else if (preempt_enable) {
14083 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
14084 		return -EINVAL;
14085 	}
14086 
14087 	if (env->cur_state->active_irq_id && sleepable) {
14088 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
14089 		return -EACCES;
14090 	}
14091 
14092 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
14093 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
14094 		return -EACCES;
14095 	}
14096 
14097 	/* In case of release function, we get register number of refcounted
14098 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
14099 	 */
14100 	if (meta.release_regno) {
14101 		struct bpf_reg_state *reg = &regs[meta.release_regno];
14102 
14103 		if (meta.initialized_dynptr.ref_obj_id) {
14104 			err = unmark_stack_slots_dynptr(env, reg);
14105 		} else {
14106 			err = release_reference(env, reg->ref_obj_id);
14107 			if (err)
14108 				verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14109 					func_name, meta.func_id);
14110 		}
14111 		if (err)
14112 			return err;
14113 	}
14114 
14115 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
14116 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
14117 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14118 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
14119 		insn_aux->insert_off = regs[BPF_REG_2].off;
14120 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
14121 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
14122 		if (err) {
14123 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
14124 				func_name, meta.func_id);
14125 			return err;
14126 		}
14127 
14128 		err = release_reference(env, release_ref_obj_id);
14129 		if (err) {
14130 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14131 				func_name, meta.func_id);
14132 			return err;
14133 		}
14134 	}
14135 
14136 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14137 		if (!bpf_jit_supports_exceptions()) {
14138 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14139 				func_name, meta.func_id);
14140 			return -ENOTSUPP;
14141 		}
14142 		env->seen_exception = true;
14143 
14144 		/* In the case of the default callback, the cookie value passed
14145 		 * to bpf_throw becomes the return value of the program.
14146 		 */
14147 		if (!env->exception_callback_subprog) {
14148 			err = check_return_code(env, BPF_REG_1, "R1");
14149 			if (err < 0)
14150 				return err;
14151 		}
14152 	}
14153 
14154 	for (i = 0; i < CALLER_SAVED_REGS; i++)
14155 		mark_reg_not_init(env, regs, caller_saved[i]);
14156 
14157 	/* Check return type */
14158 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14159 
14160 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14161 		/* Only exception is bpf_obj_new_impl */
14162 		if (meta.btf != btf_vmlinux ||
14163 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14164 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14165 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14166 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14167 			return -EINVAL;
14168 		}
14169 	}
14170 
14171 	if (btf_type_is_scalar(t)) {
14172 		mark_reg_unknown(env, regs, BPF_REG_0);
14173 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14174 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14175 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14176 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14177 	} else if (btf_type_is_ptr(t)) {
14178 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14179 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14180 		if (err) {
14181 			if (err < 0)
14182 				return err;
14183 		} else if (btf_type_is_void(ptr_type)) {
14184 			/* kfunc returning 'void *' is equivalent to returning scalar */
14185 			mark_reg_unknown(env, regs, BPF_REG_0);
14186 		} else if (!__btf_type_is_struct(ptr_type)) {
14187 			if (!meta.r0_size) {
14188 				__u32 sz;
14189 
14190 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14191 					meta.r0_size = sz;
14192 					meta.r0_rdonly = true;
14193 				}
14194 			}
14195 			if (!meta.r0_size) {
14196 				ptr_type_name = btf_name_by_offset(desc_btf,
14197 								   ptr_type->name_off);
14198 				verbose(env,
14199 					"kernel function %s returns pointer type %s %s is not supported\n",
14200 					func_name,
14201 					btf_type_str(ptr_type),
14202 					ptr_type_name);
14203 				return -EINVAL;
14204 			}
14205 
14206 			mark_reg_known_zero(env, regs, BPF_REG_0);
14207 			regs[BPF_REG_0].type = PTR_TO_MEM;
14208 			regs[BPF_REG_0].mem_size = meta.r0_size;
14209 
14210 			if (meta.r0_rdonly)
14211 				regs[BPF_REG_0].type |= MEM_RDONLY;
14212 
14213 			/* Ensures we don't access the memory after a release_reference() */
14214 			if (meta.ref_obj_id)
14215 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14216 
14217 			if (is_kfunc_rcu_protected(&meta))
14218 				regs[BPF_REG_0].type |= MEM_RCU;
14219 		} else {
14220 			enum bpf_reg_type type = PTR_TO_BTF_ID;
14221 
14222 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14223 				type |= PTR_UNTRUSTED;
14224 			else if (is_kfunc_rcu_protected(&meta) ||
14225 				 (is_iter_next_kfunc(&meta) &&
14226 				  (get_iter_from_state(env->cur_state, &meta)
14227 					   ->type & MEM_RCU))) {
14228 				/*
14229 				 * If the iterator's constructor (the _new
14230 				 * function e.g., bpf_iter_task_new) has been
14231 				 * annotated with BPF kfunc flag
14232 				 * KF_RCU_PROTECTED and was called within a RCU
14233 				 * read-side critical section, also propagate
14234 				 * the MEM_RCU flag to the pointer returned from
14235 				 * the iterator's next function (e.g.,
14236 				 * bpf_iter_task_next).
14237 				 */
14238 				type |= MEM_RCU;
14239 			} else {
14240 				/*
14241 				 * Any PTR_TO_BTF_ID that is returned from a BPF
14242 				 * kfunc should by default be treated as
14243 				 * implicitly trusted.
14244 				 */
14245 				type |= PTR_TRUSTED;
14246 			}
14247 
14248 			mark_reg_known_zero(env, regs, BPF_REG_0);
14249 			regs[BPF_REG_0].btf = desc_btf;
14250 			regs[BPF_REG_0].type = type;
14251 			regs[BPF_REG_0].btf_id = ptr_type_id;
14252 		}
14253 
14254 		if (is_kfunc_ret_null(&meta)) {
14255 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14256 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14257 			regs[BPF_REG_0].id = ++env->id_gen;
14258 		}
14259 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14260 		if (is_kfunc_acquire(&meta)) {
14261 			int id = acquire_reference(env, insn_idx);
14262 
14263 			if (id < 0)
14264 				return id;
14265 			if (is_kfunc_ret_null(&meta))
14266 				regs[BPF_REG_0].id = id;
14267 			regs[BPF_REG_0].ref_obj_id = id;
14268 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14269 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14270 		}
14271 
14272 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14273 			regs[BPF_REG_0].id = ++env->id_gen;
14274 	} else if (btf_type_is_void(t)) {
14275 		if (meta.btf == btf_vmlinux) {
14276 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14277 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14278 				insn_aux->kptr_struct_meta =
14279 					btf_find_struct_meta(meta.arg_btf,
14280 							     meta.arg_btf_id);
14281 			}
14282 		}
14283 	}
14284 
14285 	if (is_kfunc_pkt_changing(&meta))
14286 		clear_all_pkt_pointers(env);
14287 
14288 	nargs = btf_type_vlen(meta.func_proto);
14289 	args = (const struct btf_param *)(meta.func_proto + 1);
14290 	for (i = 0; i < nargs; i++) {
14291 		u32 regno = i + 1;
14292 
14293 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14294 		if (btf_type_is_ptr(t))
14295 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14296 		else
14297 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14298 			mark_btf_func_reg_size(env, regno, t->size);
14299 	}
14300 
14301 	if (is_iter_next_kfunc(&meta)) {
14302 		err = process_iter_next_call(env, insn_idx, &meta);
14303 		if (err)
14304 			return err;
14305 	}
14306 
14307 	return 0;
14308 }
14309 
14310 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14311 				  const struct bpf_reg_state *reg,
14312 				  enum bpf_reg_type type)
14313 {
14314 	bool known = tnum_is_const(reg->var_off);
14315 	s64 val = reg->var_off.value;
14316 	s64 smin = reg->smin_value;
14317 
14318 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14319 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14320 			reg_type_str(env, type), val);
14321 		return false;
14322 	}
14323 
14324 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14325 		verbose(env, "%s pointer offset %d is not allowed\n",
14326 			reg_type_str(env, type), reg->off);
14327 		return false;
14328 	}
14329 
14330 	if (smin == S64_MIN) {
14331 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14332 			reg_type_str(env, type));
14333 		return false;
14334 	}
14335 
14336 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14337 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14338 			smin, reg_type_str(env, type));
14339 		return false;
14340 	}
14341 
14342 	return true;
14343 }
14344 
14345 enum {
14346 	REASON_BOUNDS	= -1,
14347 	REASON_TYPE	= -2,
14348 	REASON_PATHS	= -3,
14349 	REASON_LIMIT	= -4,
14350 	REASON_STACK	= -5,
14351 };
14352 
14353 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14354 			      u32 *alu_limit, bool mask_to_left)
14355 {
14356 	u32 max = 0, ptr_limit = 0;
14357 
14358 	switch (ptr_reg->type) {
14359 	case PTR_TO_STACK:
14360 		/* Offset 0 is out-of-bounds, but acceptable start for the
14361 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14362 		 * offset where we would need to deal with min/max bounds is
14363 		 * currently prohibited for unprivileged.
14364 		 */
14365 		max = MAX_BPF_STACK + mask_to_left;
14366 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14367 		break;
14368 	case PTR_TO_MAP_VALUE:
14369 		max = ptr_reg->map_ptr->value_size;
14370 		ptr_limit = (mask_to_left ?
14371 			     ptr_reg->smin_value :
14372 			     ptr_reg->umax_value) + ptr_reg->off;
14373 		break;
14374 	default:
14375 		return REASON_TYPE;
14376 	}
14377 
14378 	if (ptr_limit >= max)
14379 		return REASON_LIMIT;
14380 	*alu_limit = ptr_limit;
14381 	return 0;
14382 }
14383 
14384 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14385 				    const struct bpf_insn *insn)
14386 {
14387 	return env->bypass_spec_v1 ||
14388 		BPF_SRC(insn->code) == BPF_K ||
14389 		cur_aux(env)->nospec;
14390 }
14391 
14392 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14393 				       u32 alu_state, u32 alu_limit)
14394 {
14395 	/* If we arrived here from different branches with different
14396 	 * state or limits to sanitize, then this won't work.
14397 	 */
14398 	if (aux->alu_state &&
14399 	    (aux->alu_state != alu_state ||
14400 	     aux->alu_limit != alu_limit))
14401 		return REASON_PATHS;
14402 
14403 	/* Corresponding fixup done in do_misc_fixups(). */
14404 	aux->alu_state = alu_state;
14405 	aux->alu_limit = alu_limit;
14406 	return 0;
14407 }
14408 
14409 static int sanitize_val_alu(struct bpf_verifier_env *env,
14410 			    struct bpf_insn *insn)
14411 {
14412 	struct bpf_insn_aux_data *aux = cur_aux(env);
14413 
14414 	if (can_skip_alu_sanitation(env, insn))
14415 		return 0;
14416 
14417 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14418 }
14419 
14420 static bool sanitize_needed(u8 opcode)
14421 {
14422 	return opcode == BPF_ADD || opcode == BPF_SUB;
14423 }
14424 
14425 struct bpf_sanitize_info {
14426 	struct bpf_insn_aux_data aux;
14427 	bool mask_to_left;
14428 };
14429 
14430 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14431 				     const struct bpf_insn *insn,
14432 				     u32 next_idx, u32 curr_idx)
14433 {
14434 	struct bpf_verifier_state *branch;
14435 	struct bpf_reg_state *regs;
14436 
14437 	branch = push_stack(env, next_idx, curr_idx, true);
14438 	if (!IS_ERR(branch) && insn) {
14439 		regs = branch->frame[branch->curframe]->regs;
14440 		if (BPF_SRC(insn->code) == BPF_K) {
14441 			mark_reg_unknown(env, regs, insn->dst_reg);
14442 		} else if (BPF_SRC(insn->code) == BPF_X) {
14443 			mark_reg_unknown(env, regs, insn->dst_reg);
14444 			mark_reg_unknown(env, regs, insn->src_reg);
14445 		}
14446 	}
14447 	return PTR_ERR_OR_ZERO(branch);
14448 }
14449 
14450 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14451 			    struct bpf_insn *insn,
14452 			    const struct bpf_reg_state *ptr_reg,
14453 			    const struct bpf_reg_state *off_reg,
14454 			    struct bpf_reg_state *dst_reg,
14455 			    struct bpf_sanitize_info *info,
14456 			    const bool commit_window)
14457 {
14458 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14459 	struct bpf_verifier_state *vstate = env->cur_state;
14460 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14461 	bool off_is_neg = off_reg->smin_value < 0;
14462 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14463 	u8 opcode = BPF_OP(insn->code);
14464 	u32 alu_state, alu_limit;
14465 	struct bpf_reg_state tmp;
14466 	int err;
14467 
14468 	if (can_skip_alu_sanitation(env, insn))
14469 		return 0;
14470 
14471 	/* We already marked aux for masking from non-speculative
14472 	 * paths, thus we got here in the first place. We only care
14473 	 * to explore bad access from here.
14474 	 */
14475 	if (vstate->speculative)
14476 		goto do_sim;
14477 
14478 	if (!commit_window) {
14479 		if (!tnum_is_const(off_reg->var_off) &&
14480 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14481 			return REASON_BOUNDS;
14482 
14483 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14484 				     (opcode == BPF_SUB && !off_is_neg);
14485 	}
14486 
14487 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14488 	if (err < 0)
14489 		return err;
14490 
14491 	if (commit_window) {
14492 		/* In commit phase we narrow the masking window based on
14493 		 * the observed pointer move after the simulated operation.
14494 		 */
14495 		alu_state = info->aux.alu_state;
14496 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14497 	} else {
14498 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14499 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14500 		alu_state |= ptr_is_dst_reg ?
14501 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14502 
14503 		/* Limit pruning on unknown scalars to enable deep search for
14504 		 * potential masking differences from other program paths.
14505 		 */
14506 		if (!off_is_imm)
14507 			env->explore_alu_limits = true;
14508 	}
14509 
14510 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14511 	if (err < 0)
14512 		return err;
14513 do_sim:
14514 	/* If we're in commit phase, we're done here given we already
14515 	 * pushed the truncated dst_reg into the speculative verification
14516 	 * stack.
14517 	 *
14518 	 * Also, when register is a known constant, we rewrite register-based
14519 	 * operation to immediate-based, and thus do not need masking (and as
14520 	 * a consequence, do not need to simulate the zero-truncation either).
14521 	 */
14522 	if (commit_window || off_is_imm)
14523 		return 0;
14524 
14525 	/* Simulate and find potential out-of-bounds access under
14526 	 * speculative execution from truncation as a result of
14527 	 * masking when off was not within expected range. If off
14528 	 * sits in dst, then we temporarily need to move ptr there
14529 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14530 	 * for cases where we use K-based arithmetic in one direction
14531 	 * and truncated reg-based in the other in order to explore
14532 	 * bad access.
14533 	 */
14534 	if (!ptr_is_dst_reg) {
14535 		tmp = *dst_reg;
14536 		copy_register_state(dst_reg, ptr_reg);
14537 	}
14538 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14539 	if (err < 0)
14540 		return REASON_STACK;
14541 	if (!ptr_is_dst_reg)
14542 		*dst_reg = tmp;
14543 	return 0;
14544 }
14545 
14546 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14547 {
14548 	struct bpf_verifier_state *vstate = env->cur_state;
14549 
14550 	/* If we simulate paths under speculation, we don't update the
14551 	 * insn as 'seen' such that when we verify unreachable paths in
14552 	 * the non-speculative domain, sanitize_dead_code() can still
14553 	 * rewrite/sanitize them.
14554 	 */
14555 	if (!vstate->speculative)
14556 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14557 }
14558 
14559 static int sanitize_err(struct bpf_verifier_env *env,
14560 			const struct bpf_insn *insn, int reason,
14561 			const struct bpf_reg_state *off_reg,
14562 			const struct bpf_reg_state *dst_reg)
14563 {
14564 	static const char *err = "pointer arithmetic with it prohibited for !root";
14565 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14566 	u32 dst = insn->dst_reg, src = insn->src_reg;
14567 
14568 	switch (reason) {
14569 	case REASON_BOUNDS:
14570 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14571 			off_reg == dst_reg ? dst : src, err);
14572 		break;
14573 	case REASON_TYPE:
14574 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14575 			off_reg == dst_reg ? src : dst, err);
14576 		break;
14577 	case REASON_PATHS:
14578 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14579 			dst, op, err);
14580 		break;
14581 	case REASON_LIMIT:
14582 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14583 			dst, op, err);
14584 		break;
14585 	case REASON_STACK:
14586 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14587 			dst, err);
14588 		return -ENOMEM;
14589 	default:
14590 		verifier_bug(env, "unknown reason (%d)", reason);
14591 		break;
14592 	}
14593 
14594 	return -EACCES;
14595 }
14596 
14597 /* check that stack access falls within stack limits and that 'reg' doesn't
14598  * have a variable offset.
14599  *
14600  * Variable offset is prohibited for unprivileged mode for simplicity since it
14601  * requires corresponding support in Spectre masking for stack ALU.  See also
14602  * retrieve_ptr_limit().
14603  *
14604  *
14605  * 'off' includes 'reg->off'.
14606  */
14607 static int check_stack_access_for_ptr_arithmetic(
14608 				struct bpf_verifier_env *env,
14609 				int regno,
14610 				const struct bpf_reg_state *reg,
14611 				int off)
14612 {
14613 	if (!tnum_is_const(reg->var_off)) {
14614 		char tn_buf[48];
14615 
14616 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14617 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14618 			regno, tn_buf, off);
14619 		return -EACCES;
14620 	}
14621 
14622 	if (off >= 0 || off < -MAX_BPF_STACK) {
14623 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14624 			"prohibited for !root; off=%d\n", regno, off);
14625 		return -EACCES;
14626 	}
14627 
14628 	return 0;
14629 }
14630 
14631 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14632 				 const struct bpf_insn *insn,
14633 				 const struct bpf_reg_state *dst_reg)
14634 {
14635 	u32 dst = insn->dst_reg;
14636 
14637 	/* For unprivileged we require that resulting offset must be in bounds
14638 	 * in order to be able to sanitize access later on.
14639 	 */
14640 	if (env->bypass_spec_v1)
14641 		return 0;
14642 
14643 	switch (dst_reg->type) {
14644 	case PTR_TO_STACK:
14645 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14646 					dst_reg->off + dst_reg->var_off.value))
14647 			return -EACCES;
14648 		break;
14649 	case PTR_TO_MAP_VALUE:
14650 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14651 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14652 				"prohibited for !root\n", dst);
14653 			return -EACCES;
14654 		}
14655 		break;
14656 	default:
14657 		return -EOPNOTSUPP;
14658 	}
14659 
14660 	return 0;
14661 }
14662 
14663 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14664  * Caller should also handle BPF_MOV case separately.
14665  * If we return -EACCES, caller may want to try again treating pointer as a
14666  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14667  */
14668 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14669 				   struct bpf_insn *insn,
14670 				   const struct bpf_reg_state *ptr_reg,
14671 				   const struct bpf_reg_state *off_reg)
14672 {
14673 	struct bpf_verifier_state *vstate = env->cur_state;
14674 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14675 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14676 	bool known = tnum_is_const(off_reg->var_off);
14677 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14678 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14679 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14680 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14681 	struct bpf_sanitize_info info = {};
14682 	u8 opcode = BPF_OP(insn->code);
14683 	u32 dst = insn->dst_reg;
14684 	int ret, bounds_ret;
14685 
14686 	dst_reg = &regs[dst];
14687 
14688 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14689 	    smin_val > smax_val || umin_val > umax_val) {
14690 		/* Taint dst register if offset had invalid bounds derived from
14691 		 * e.g. dead branches.
14692 		 */
14693 		__mark_reg_unknown(env, dst_reg);
14694 		return 0;
14695 	}
14696 
14697 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14698 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14699 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14700 			__mark_reg_unknown(env, dst_reg);
14701 			return 0;
14702 		}
14703 
14704 		verbose(env,
14705 			"R%d 32-bit pointer arithmetic prohibited\n",
14706 			dst);
14707 		return -EACCES;
14708 	}
14709 
14710 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14711 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14712 			dst, reg_type_str(env, ptr_reg->type));
14713 		return -EACCES;
14714 	}
14715 
14716 	/*
14717 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14718 	 * instructions, hence no need to track offsets.
14719 	 */
14720 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14721 		return 0;
14722 
14723 	switch (base_type(ptr_reg->type)) {
14724 	case PTR_TO_CTX:
14725 	case PTR_TO_MAP_VALUE:
14726 	case PTR_TO_MAP_KEY:
14727 	case PTR_TO_STACK:
14728 	case PTR_TO_PACKET_META:
14729 	case PTR_TO_PACKET:
14730 	case PTR_TO_TP_BUFFER:
14731 	case PTR_TO_BTF_ID:
14732 	case PTR_TO_MEM:
14733 	case PTR_TO_BUF:
14734 	case PTR_TO_FUNC:
14735 	case CONST_PTR_TO_DYNPTR:
14736 		break;
14737 	case PTR_TO_FLOW_KEYS:
14738 		if (known)
14739 			break;
14740 		fallthrough;
14741 	case CONST_PTR_TO_MAP:
14742 		/* smin_val represents the known value */
14743 		if (known && smin_val == 0 && opcode == BPF_ADD)
14744 			break;
14745 		fallthrough;
14746 	default:
14747 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14748 			dst, reg_type_str(env, ptr_reg->type));
14749 		return -EACCES;
14750 	}
14751 
14752 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14753 	 * The id may be overwritten later if we create a new variable offset.
14754 	 */
14755 	dst_reg->type = ptr_reg->type;
14756 	dst_reg->id = ptr_reg->id;
14757 
14758 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14759 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14760 		return -EINVAL;
14761 
14762 	/* pointer types do not carry 32-bit bounds at the moment. */
14763 	__mark_reg32_unbounded(dst_reg);
14764 
14765 	if (sanitize_needed(opcode)) {
14766 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14767 				       &info, false);
14768 		if (ret < 0)
14769 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14770 	}
14771 
14772 	switch (opcode) {
14773 	case BPF_ADD:
14774 		/* We can take a fixed offset as long as it doesn't overflow
14775 		 * the s32 'off' field
14776 		 */
14777 		if (known && (ptr_reg->off + smin_val ==
14778 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14779 			/* pointer += K.  Accumulate it into fixed offset */
14780 			dst_reg->smin_value = smin_ptr;
14781 			dst_reg->smax_value = smax_ptr;
14782 			dst_reg->umin_value = umin_ptr;
14783 			dst_reg->umax_value = umax_ptr;
14784 			dst_reg->var_off = ptr_reg->var_off;
14785 			dst_reg->off = ptr_reg->off + smin_val;
14786 			dst_reg->raw = ptr_reg->raw;
14787 			break;
14788 		}
14789 		/* A new variable offset is created.  Note that off_reg->off
14790 		 * == 0, since it's a scalar.
14791 		 * dst_reg gets the pointer type and since some positive
14792 		 * integer value was added to the pointer, give it a new 'id'
14793 		 * if it's a PTR_TO_PACKET.
14794 		 * this creates a new 'base' pointer, off_reg (variable) gets
14795 		 * added into the variable offset, and we copy the fixed offset
14796 		 * from ptr_reg.
14797 		 */
14798 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14799 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14800 			dst_reg->smin_value = S64_MIN;
14801 			dst_reg->smax_value = S64_MAX;
14802 		}
14803 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14804 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14805 			dst_reg->umin_value = 0;
14806 			dst_reg->umax_value = U64_MAX;
14807 		}
14808 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14809 		dst_reg->off = ptr_reg->off;
14810 		dst_reg->raw = ptr_reg->raw;
14811 		if (reg_is_pkt_pointer(ptr_reg)) {
14812 			dst_reg->id = ++env->id_gen;
14813 			/* something was added to pkt_ptr, set range to zero */
14814 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14815 		}
14816 		break;
14817 	case BPF_SUB:
14818 		if (dst_reg == off_reg) {
14819 			/* scalar -= pointer.  Creates an unknown scalar */
14820 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14821 				dst);
14822 			return -EACCES;
14823 		}
14824 		/* We don't allow subtraction from FP, because (according to
14825 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14826 		 * be able to deal with it.
14827 		 */
14828 		if (ptr_reg->type == PTR_TO_STACK) {
14829 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14830 				dst);
14831 			return -EACCES;
14832 		}
14833 		if (known && (ptr_reg->off - smin_val ==
14834 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14835 			/* pointer -= K.  Subtract it from fixed offset */
14836 			dst_reg->smin_value = smin_ptr;
14837 			dst_reg->smax_value = smax_ptr;
14838 			dst_reg->umin_value = umin_ptr;
14839 			dst_reg->umax_value = umax_ptr;
14840 			dst_reg->var_off = ptr_reg->var_off;
14841 			dst_reg->id = ptr_reg->id;
14842 			dst_reg->off = ptr_reg->off - smin_val;
14843 			dst_reg->raw = ptr_reg->raw;
14844 			break;
14845 		}
14846 		/* A new variable offset is created.  If the subtrahend is known
14847 		 * nonnegative, then any reg->range we had before is still good.
14848 		 */
14849 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14850 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14851 			/* Overflow possible, we know nothing */
14852 			dst_reg->smin_value = S64_MIN;
14853 			dst_reg->smax_value = S64_MAX;
14854 		}
14855 		if (umin_ptr < umax_val) {
14856 			/* Overflow possible, we know nothing */
14857 			dst_reg->umin_value = 0;
14858 			dst_reg->umax_value = U64_MAX;
14859 		} else {
14860 			/* Cannot overflow (as long as bounds are consistent) */
14861 			dst_reg->umin_value = umin_ptr - umax_val;
14862 			dst_reg->umax_value = umax_ptr - umin_val;
14863 		}
14864 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14865 		dst_reg->off = ptr_reg->off;
14866 		dst_reg->raw = ptr_reg->raw;
14867 		if (reg_is_pkt_pointer(ptr_reg)) {
14868 			dst_reg->id = ++env->id_gen;
14869 			/* something was added to pkt_ptr, set range to zero */
14870 			if (smin_val < 0)
14871 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14872 		}
14873 		break;
14874 	case BPF_AND:
14875 	case BPF_OR:
14876 	case BPF_XOR:
14877 		/* bitwise ops on pointers are troublesome, prohibit. */
14878 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14879 			dst, bpf_alu_string[opcode >> 4]);
14880 		return -EACCES;
14881 	default:
14882 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14883 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14884 			dst, bpf_alu_string[opcode >> 4]);
14885 		return -EACCES;
14886 	}
14887 
14888 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14889 		return -EINVAL;
14890 	reg_bounds_sync(dst_reg);
14891 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14892 	if (bounds_ret == -EACCES)
14893 		return bounds_ret;
14894 	if (sanitize_needed(opcode)) {
14895 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14896 				       &info, true);
14897 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14898 				    && !env->cur_state->speculative
14899 				    && bounds_ret
14900 				    && !ret,
14901 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14902 			return -EFAULT;
14903 		}
14904 		if (ret < 0)
14905 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14906 	}
14907 
14908 	return 0;
14909 }
14910 
14911 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14912 				 struct bpf_reg_state *src_reg)
14913 {
14914 	s32 *dst_smin = &dst_reg->s32_min_value;
14915 	s32 *dst_smax = &dst_reg->s32_max_value;
14916 	u32 *dst_umin = &dst_reg->u32_min_value;
14917 	u32 *dst_umax = &dst_reg->u32_max_value;
14918 	u32 umin_val = src_reg->u32_min_value;
14919 	u32 umax_val = src_reg->u32_max_value;
14920 	bool min_overflow, max_overflow;
14921 
14922 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14923 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14924 		*dst_smin = S32_MIN;
14925 		*dst_smax = S32_MAX;
14926 	}
14927 
14928 	/* If either all additions overflow or no additions overflow, then
14929 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14930 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14931 	 * the output bounds to unbounded.
14932 	 */
14933 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14934 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14935 
14936 	if (!min_overflow && max_overflow) {
14937 		*dst_umin = 0;
14938 		*dst_umax = U32_MAX;
14939 	}
14940 }
14941 
14942 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14943 			       struct bpf_reg_state *src_reg)
14944 {
14945 	s64 *dst_smin = &dst_reg->smin_value;
14946 	s64 *dst_smax = &dst_reg->smax_value;
14947 	u64 *dst_umin = &dst_reg->umin_value;
14948 	u64 *dst_umax = &dst_reg->umax_value;
14949 	u64 umin_val = src_reg->umin_value;
14950 	u64 umax_val = src_reg->umax_value;
14951 	bool min_overflow, max_overflow;
14952 
14953 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14954 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14955 		*dst_smin = S64_MIN;
14956 		*dst_smax = S64_MAX;
14957 	}
14958 
14959 	/* If either all additions overflow or no additions overflow, then
14960 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14961 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14962 	 * the output bounds to unbounded.
14963 	 */
14964 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14965 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14966 
14967 	if (!min_overflow && max_overflow) {
14968 		*dst_umin = 0;
14969 		*dst_umax = U64_MAX;
14970 	}
14971 }
14972 
14973 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14974 				 struct bpf_reg_state *src_reg)
14975 {
14976 	s32 *dst_smin = &dst_reg->s32_min_value;
14977 	s32 *dst_smax = &dst_reg->s32_max_value;
14978 	u32 *dst_umin = &dst_reg->u32_min_value;
14979 	u32 *dst_umax = &dst_reg->u32_max_value;
14980 	u32 umin_val = src_reg->u32_min_value;
14981 	u32 umax_val = src_reg->u32_max_value;
14982 	bool min_underflow, max_underflow;
14983 
14984 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14985 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14986 		/* Overflow possible, we know nothing */
14987 		*dst_smin = S32_MIN;
14988 		*dst_smax = S32_MAX;
14989 	}
14990 
14991 	/* If either all subtractions underflow or no subtractions
14992 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14993 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14994 	 * underflow), set the output bounds to unbounded.
14995 	 */
14996 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14997 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14998 
14999 	if (min_underflow && !max_underflow) {
15000 		*dst_umin = 0;
15001 		*dst_umax = U32_MAX;
15002 	}
15003 }
15004 
15005 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
15006 			       struct bpf_reg_state *src_reg)
15007 {
15008 	s64 *dst_smin = &dst_reg->smin_value;
15009 	s64 *dst_smax = &dst_reg->smax_value;
15010 	u64 *dst_umin = &dst_reg->umin_value;
15011 	u64 *dst_umax = &dst_reg->umax_value;
15012 	u64 umin_val = src_reg->umin_value;
15013 	u64 umax_val = src_reg->umax_value;
15014 	bool min_underflow, max_underflow;
15015 
15016 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
15017 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
15018 		/* Overflow possible, we know nothing */
15019 		*dst_smin = S64_MIN;
15020 		*dst_smax = S64_MAX;
15021 	}
15022 
15023 	/* If either all subtractions underflow or no subtractions
15024 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15025 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15026 	 * underflow), set the output bounds to unbounded.
15027 	 */
15028 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15029 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15030 
15031 	if (min_underflow && !max_underflow) {
15032 		*dst_umin = 0;
15033 		*dst_umax = U64_MAX;
15034 	}
15035 }
15036 
15037 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
15038 				 struct bpf_reg_state *src_reg)
15039 {
15040 	s32 *dst_smin = &dst_reg->s32_min_value;
15041 	s32 *dst_smax = &dst_reg->s32_max_value;
15042 	u32 *dst_umin = &dst_reg->u32_min_value;
15043 	u32 *dst_umax = &dst_reg->u32_max_value;
15044 	s32 tmp_prod[4];
15045 
15046 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
15047 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
15048 		/* Overflow possible, we know nothing */
15049 		*dst_umin = 0;
15050 		*dst_umax = U32_MAX;
15051 	}
15052 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
15053 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
15054 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
15055 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
15056 		/* Overflow possible, we know nothing */
15057 		*dst_smin = S32_MIN;
15058 		*dst_smax = S32_MAX;
15059 	} else {
15060 		*dst_smin = min_array(tmp_prod, 4);
15061 		*dst_smax = max_array(tmp_prod, 4);
15062 	}
15063 }
15064 
15065 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
15066 			       struct bpf_reg_state *src_reg)
15067 {
15068 	s64 *dst_smin = &dst_reg->smin_value;
15069 	s64 *dst_smax = &dst_reg->smax_value;
15070 	u64 *dst_umin = &dst_reg->umin_value;
15071 	u64 *dst_umax = &dst_reg->umax_value;
15072 	s64 tmp_prod[4];
15073 
15074 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
15075 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
15076 		/* Overflow possible, we know nothing */
15077 		*dst_umin = 0;
15078 		*dst_umax = U64_MAX;
15079 	}
15080 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
15081 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
15082 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
15083 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
15084 		/* Overflow possible, we know nothing */
15085 		*dst_smin = S64_MIN;
15086 		*dst_smax = S64_MAX;
15087 	} else {
15088 		*dst_smin = min_array(tmp_prod, 4);
15089 		*dst_smax = max_array(tmp_prod, 4);
15090 	}
15091 }
15092 
15093 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15094 				 struct bpf_reg_state *src_reg)
15095 {
15096 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15097 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15098 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15099 	u32 umax_val = src_reg->u32_max_value;
15100 
15101 	if (src_known && dst_known) {
15102 		__mark_reg32_known(dst_reg, var32_off.value);
15103 		return;
15104 	}
15105 
15106 	/* We get our minimum from the var_off, since that's inherently
15107 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15108 	 */
15109 	dst_reg->u32_min_value = var32_off.value;
15110 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
15111 
15112 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15113 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15114 	 */
15115 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15116 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15117 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15118 	} else {
15119 		dst_reg->s32_min_value = S32_MIN;
15120 		dst_reg->s32_max_value = S32_MAX;
15121 	}
15122 }
15123 
15124 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15125 			       struct bpf_reg_state *src_reg)
15126 {
15127 	bool src_known = tnum_is_const(src_reg->var_off);
15128 	bool dst_known = tnum_is_const(dst_reg->var_off);
15129 	u64 umax_val = src_reg->umax_value;
15130 
15131 	if (src_known && dst_known) {
15132 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15133 		return;
15134 	}
15135 
15136 	/* We get our minimum from the var_off, since that's inherently
15137 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15138 	 */
15139 	dst_reg->umin_value = dst_reg->var_off.value;
15140 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
15141 
15142 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15143 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15144 	 */
15145 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15146 		dst_reg->smin_value = dst_reg->umin_value;
15147 		dst_reg->smax_value = dst_reg->umax_value;
15148 	} else {
15149 		dst_reg->smin_value = S64_MIN;
15150 		dst_reg->smax_value = S64_MAX;
15151 	}
15152 	/* We may learn something more from the var_off */
15153 	__update_reg_bounds(dst_reg);
15154 }
15155 
15156 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15157 				struct bpf_reg_state *src_reg)
15158 {
15159 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15160 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15161 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15162 	u32 umin_val = src_reg->u32_min_value;
15163 
15164 	if (src_known && dst_known) {
15165 		__mark_reg32_known(dst_reg, var32_off.value);
15166 		return;
15167 	}
15168 
15169 	/* We get our maximum from the var_off, and our minimum is the
15170 	 * maximum of the operands' minima
15171 	 */
15172 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15173 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15174 
15175 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15176 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15177 	 */
15178 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15179 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15180 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15181 	} else {
15182 		dst_reg->s32_min_value = S32_MIN;
15183 		dst_reg->s32_max_value = S32_MAX;
15184 	}
15185 }
15186 
15187 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15188 			      struct bpf_reg_state *src_reg)
15189 {
15190 	bool src_known = tnum_is_const(src_reg->var_off);
15191 	bool dst_known = tnum_is_const(dst_reg->var_off);
15192 	u64 umin_val = src_reg->umin_value;
15193 
15194 	if (src_known && dst_known) {
15195 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15196 		return;
15197 	}
15198 
15199 	/* We get our maximum from the var_off, and our minimum is the
15200 	 * maximum of the operands' minima
15201 	 */
15202 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15203 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15204 
15205 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15206 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15207 	 */
15208 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15209 		dst_reg->smin_value = dst_reg->umin_value;
15210 		dst_reg->smax_value = dst_reg->umax_value;
15211 	} else {
15212 		dst_reg->smin_value = S64_MIN;
15213 		dst_reg->smax_value = S64_MAX;
15214 	}
15215 	/* We may learn something more from the var_off */
15216 	__update_reg_bounds(dst_reg);
15217 }
15218 
15219 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15220 				 struct bpf_reg_state *src_reg)
15221 {
15222 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15223 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15224 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15225 
15226 	if (src_known && dst_known) {
15227 		__mark_reg32_known(dst_reg, var32_off.value);
15228 		return;
15229 	}
15230 
15231 	/* We get both minimum and maximum from the var32_off. */
15232 	dst_reg->u32_min_value = var32_off.value;
15233 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15234 
15235 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15236 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15237 	 */
15238 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15239 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15240 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15241 	} else {
15242 		dst_reg->s32_min_value = S32_MIN;
15243 		dst_reg->s32_max_value = S32_MAX;
15244 	}
15245 }
15246 
15247 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15248 			       struct bpf_reg_state *src_reg)
15249 {
15250 	bool src_known = tnum_is_const(src_reg->var_off);
15251 	bool dst_known = tnum_is_const(dst_reg->var_off);
15252 
15253 	if (src_known && dst_known) {
15254 		/* dst_reg->var_off.value has been updated earlier */
15255 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15256 		return;
15257 	}
15258 
15259 	/* We get both minimum and maximum from the var_off. */
15260 	dst_reg->umin_value = dst_reg->var_off.value;
15261 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15262 
15263 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15264 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15265 	 */
15266 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15267 		dst_reg->smin_value = dst_reg->umin_value;
15268 		dst_reg->smax_value = dst_reg->umax_value;
15269 	} else {
15270 		dst_reg->smin_value = S64_MIN;
15271 		dst_reg->smax_value = S64_MAX;
15272 	}
15273 
15274 	__update_reg_bounds(dst_reg);
15275 }
15276 
15277 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15278 				   u64 umin_val, u64 umax_val)
15279 {
15280 	/* We lose all sign bit information (except what we can pick
15281 	 * up from var_off)
15282 	 */
15283 	dst_reg->s32_min_value = S32_MIN;
15284 	dst_reg->s32_max_value = S32_MAX;
15285 	/* If we might shift our top bit out, then we know nothing */
15286 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15287 		dst_reg->u32_min_value = 0;
15288 		dst_reg->u32_max_value = U32_MAX;
15289 	} else {
15290 		dst_reg->u32_min_value <<= umin_val;
15291 		dst_reg->u32_max_value <<= umax_val;
15292 	}
15293 }
15294 
15295 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15296 				 struct bpf_reg_state *src_reg)
15297 {
15298 	u32 umax_val = src_reg->u32_max_value;
15299 	u32 umin_val = src_reg->u32_min_value;
15300 	/* u32 alu operation will zext upper bits */
15301 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15302 
15303 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15304 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15305 	/* Not required but being careful mark reg64 bounds as unknown so
15306 	 * that we are forced to pick them up from tnum and zext later and
15307 	 * if some path skips this step we are still safe.
15308 	 */
15309 	__mark_reg64_unbounded(dst_reg);
15310 	__update_reg32_bounds(dst_reg);
15311 }
15312 
15313 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15314 				   u64 umin_val, u64 umax_val)
15315 {
15316 	/* Special case <<32 because it is a common compiler pattern to sign
15317 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
15318 	 * because s32 bounds don't flip sign when shifting to the left by
15319 	 * 32bits.
15320 	 */
15321 	if (umin_val == 32 && umax_val == 32) {
15322 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15323 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15324 	} else {
15325 		dst_reg->smax_value = S64_MAX;
15326 		dst_reg->smin_value = S64_MIN;
15327 	}
15328 
15329 	/* If we might shift our top bit out, then we know nothing */
15330 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15331 		dst_reg->umin_value = 0;
15332 		dst_reg->umax_value = U64_MAX;
15333 	} else {
15334 		dst_reg->umin_value <<= umin_val;
15335 		dst_reg->umax_value <<= umax_val;
15336 	}
15337 }
15338 
15339 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15340 			       struct bpf_reg_state *src_reg)
15341 {
15342 	u64 umax_val = src_reg->umax_value;
15343 	u64 umin_val = src_reg->umin_value;
15344 
15345 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15346 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15347 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15348 
15349 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15350 	/* We may learn something more from the var_off */
15351 	__update_reg_bounds(dst_reg);
15352 }
15353 
15354 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15355 				 struct bpf_reg_state *src_reg)
15356 {
15357 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15358 	u32 umax_val = src_reg->u32_max_value;
15359 	u32 umin_val = src_reg->u32_min_value;
15360 
15361 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15362 	 * be negative, then either:
15363 	 * 1) src_reg might be zero, so the sign bit of the result is
15364 	 *    unknown, so we lose our signed bounds
15365 	 * 2) it's known negative, thus the unsigned bounds capture the
15366 	 *    signed bounds
15367 	 * 3) the signed bounds cross zero, so they tell us nothing
15368 	 *    about the result
15369 	 * If the value in dst_reg is known nonnegative, then again the
15370 	 * unsigned bounds capture the signed bounds.
15371 	 * Thus, in all cases it suffices to blow away our signed bounds
15372 	 * and rely on inferring new ones from the unsigned bounds and
15373 	 * var_off of the result.
15374 	 */
15375 	dst_reg->s32_min_value = S32_MIN;
15376 	dst_reg->s32_max_value = S32_MAX;
15377 
15378 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15379 	dst_reg->u32_min_value >>= umax_val;
15380 	dst_reg->u32_max_value >>= umin_val;
15381 
15382 	__mark_reg64_unbounded(dst_reg);
15383 	__update_reg32_bounds(dst_reg);
15384 }
15385 
15386 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15387 			       struct bpf_reg_state *src_reg)
15388 {
15389 	u64 umax_val = src_reg->umax_value;
15390 	u64 umin_val = src_reg->umin_value;
15391 
15392 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15393 	 * be negative, then either:
15394 	 * 1) src_reg might be zero, so the sign bit of the result is
15395 	 *    unknown, so we lose our signed bounds
15396 	 * 2) it's known negative, thus the unsigned bounds capture the
15397 	 *    signed bounds
15398 	 * 3) the signed bounds cross zero, so they tell us nothing
15399 	 *    about the result
15400 	 * If the value in dst_reg is known nonnegative, then again the
15401 	 * unsigned bounds capture the signed bounds.
15402 	 * Thus, in all cases it suffices to blow away our signed bounds
15403 	 * and rely on inferring new ones from the unsigned bounds and
15404 	 * var_off of the result.
15405 	 */
15406 	dst_reg->smin_value = S64_MIN;
15407 	dst_reg->smax_value = S64_MAX;
15408 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15409 	dst_reg->umin_value >>= umax_val;
15410 	dst_reg->umax_value >>= umin_val;
15411 
15412 	/* Its not easy to operate on alu32 bounds here because it depends
15413 	 * on bits being shifted in. Take easy way out and mark unbounded
15414 	 * so we can recalculate later from tnum.
15415 	 */
15416 	__mark_reg32_unbounded(dst_reg);
15417 	__update_reg_bounds(dst_reg);
15418 }
15419 
15420 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15421 				  struct bpf_reg_state *src_reg)
15422 {
15423 	u64 umin_val = src_reg->u32_min_value;
15424 
15425 	/* Upon reaching here, src_known is true and
15426 	 * umax_val is equal to umin_val.
15427 	 */
15428 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15429 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15430 
15431 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15432 
15433 	/* blow away the dst_reg umin_value/umax_value and rely on
15434 	 * dst_reg var_off to refine the result.
15435 	 */
15436 	dst_reg->u32_min_value = 0;
15437 	dst_reg->u32_max_value = U32_MAX;
15438 
15439 	__mark_reg64_unbounded(dst_reg);
15440 	__update_reg32_bounds(dst_reg);
15441 }
15442 
15443 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15444 				struct bpf_reg_state *src_reg)
15445 {
15446 	u64 umin_val = src_reg->umin_value;
15447 
15448 	/* Upon reaching here, src_known is true and umax_val is equal
15449 	 * to umin_val.
15450 	 */
15451 	dst_reg->smin_value >>= umin_val;
15452 	dst_reg->smax_value >>= umin_val;
15453 
15454 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15455 
15456 	/* blow away the dst_reg umin_value/umax_value and rely on
15457 	 * dst_reg var_off to refine the result.
15458 	 */
15459 	dst_reg->umin_value = 0;
15460 	dst_reg->umax_value = U64_MAX;
15461 
15462 	/* Its not easy to operate on alu32 bounds here because it depends
15463 	 * on bits being shifted in from upper 32-bits. Take easy way out
15464 	 * and mark unbounded so we can recalculate later from tnum.
15465 	 */
15466 	__mark_reg32_unbounded(dst_reg);
15467 	__update_reg_bounds(dst_reg);
15468 }
15469 
15470 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15471 					     const struct bpf_reg_state *src_reg)
15472 {
15473 	bool src_is_const = false;
15474 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15475 
15476 	if (insn_bitness == 32) {
15477 		if (tnum_subreg_is_const(src_reg->var_off)
15478 		    && src_reg->s32_min_value == src_reg->s32_max_value
15479 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15480 			src_is_const = true;
15481 	} else {
15482 		if (tnum_is_const(src_reg->var_off)
15483 		    && src_reg->smin_value == src_reg->smax_value
15484 		    && src_reg->umin_value == src_reg->umax_value)
15485 			src_is_const = true;
15486 	}
15487 
15488 	switch (BPF_OP(insn->code)) {
15489 	case BPF_ADD:
15490 	case BPF_SUB:
15491 	case BPF_NEG:
15492 	case BPF_AND:
15493 	case BPF_XOR:
15494 	case BPF_OR:
15495 	case BPF_MUL:
15496 		return true;
15497 
15498 	/* Shift operators range is only computable if shift dimension operand
15499 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15500 	 * includes shifts by a negative number.
15501 	 */
15502 	case BPF_LSH:
15503 	case BPF_RSH:
15504 	case BPF_ARSH:
15505 		return (src_is_const && src_reg->umax_value < insn_bitness);
15506 	default:
15507 		return false;
15508 	}
15509 }
15510 
15511 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
15512 			      struct bpf_reg_state *dst_reg)
15513 {
15514 	struct bpf_verifier_state *branch;
15515 	struct bpf_reg_state *regs;
15516 	bool alu32;
15517 
15518 	if (dst_reg->smin_value == -1 && dst_reg->smax_value == 0)
15519 		alu32 = false;
15520 	else if (dst_reg->s32_min_value == -1 && dst_reg->s32_max_value == 0)
15521 		alu32 = true;
15522 	else
15523 		return 0;
15524 
15525 	branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
15526 	if (IS_ERR(branch))
15527 		return PTR_ERR(branch);
15528 
15529 	regs = branch->frame[branch->curframe]->regs;
15530 	if (alu32) {
15531 		__mark_reg32_known(&regs[insn->dst_reg], 0);
15532 		__mark_reg32_known(dst_reg, -1ull);
15533 	} else {
15534 		__mark_reg_known(&regs[insn->dst_reg], 0);
15535 		__mark_reg_known(dst_reg, -1ull);
15536 	}
15537 	return 0;
15538 }
15539 
15540 /* WARNING: This function does calculations on 64-bit values, but the actual
15541  * execution may occur on 32-bit values. Therefore, things like bitshifts
15542  * need extra checks in the 32-bit case.
15543  */
15544 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15545 				      struct bpf_insn *insn,
15546 				      struct bpf_reg_state *dst_reg,
15547 				      struct bpf_reg_state src_reg)
15548 {
15549 	u8 opcode = BPF_OP(insn->code);
15550 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15551 	int ret;
15552 
15553 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15554 		__mark_reg_unknown(env, dst_reg);
15555 		return 0;
15556 	}
15557 
15558 	if (sanitize_needed(opcode)) {
15559 		ret = sanitize_val_alu(env, insn);
15560 		if (ret < 0)
15561 			return sanitize_err(env, insn, ret, NULL, NULL);
15562 	}
15563 
15564 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15565 	 * There are two classes of instructions: The first class we track both
15566 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15567 	 * greatest amount of precision when alu operations are mixed with jmp32
15568 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15569 	 * and BPF_OR. This is possible because these ops have fairly easy to
15570 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15571 	 * See alu32 verifier tests for examples. The second class of
15572 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15573 	 * with regards to tracking sign/unsigned bounds because the bits may
15574 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15575 	 * the reg unbounded in the subreg bound space and use the resulting
15576 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15577 	 */
15578 	switch (opcode) {
15579 	case BPF_ADD:
15580 		scalar32_min_max_add(dst_reg, &src_reg);
15581 		scalar_min_max_add(dst_reg, &src_reg);
15582 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15583 		break;
15584 	case BPF_SUB:
15585 		scalar32_min_max_sub(dst_reg, &src_reg);
15586 		scalar_min_max_sub(dst_reg, &src_reg);
15587 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15588 		break;
15589 	case BPF_NEG:
15590 		env->fake_reg[0] = *dst_reg;
15591 		__mark_reg_known(dst_reg, 0);
15592 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15593 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15594 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15595 		break;
15596 	case BPF_MUL:
15597 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15598 		scalar32_min_max_mul(dst_reg, &src_reg);
15599 		scalar_min_max_mul(dst_reg, &src_reg);
15600 		break;
15601 	case BPF_AND:
15602 		if (tnum_is_const(src_reg.var_off)) {
15603 			ret = maybe_fork_scalars(env, insn, dst_reg);
15604 			if (ret)
15605 				return ret;
15606 		}
15607 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15608 		scalar32_min_max_and(dst_reg, &src_reg);
15609 		scalar_min_max_and(dst_reg, &src_reg);
15610 		break;
15611 	case BPF_OR:
15612 		if (tnum_is_const(src_reg.var_off)) {
15613 			ret = maybe_fork_scalars(env, insn, dst_reg);
15614 			if (ret)
15615 				return ret;
15616 		}
15617 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15618 		scalar32_min_max_or(dst_reg, &src_reg);
15619 		scalar_min_max_or(dst_reg, &src_reg);
15620 		break;
15621 	case BPF_XOR:
15622 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15623 		scalar32_min_max_xor(dst_reg, &src_reg);
15624 		scalar_min_max_xor(dst_reg, &src_reg);
15625 		break;
15626 	case BPF_LSH:
15627 		if (alu32)
15628 			scalar32_min_max_lsh(dst_reg, &src_reg);
15629 		else
15630 			scalar_min_max_lsh(dst_reg, &src_reg);
15631 		break;
15632 	case BPF_RSH:
15633 		if (alu32)
15634 			scalar32_min_max_rsh(dst_reg, &src_reg);
15635 		else
15636 			scalar_min_max_rsh(dst_reg, &src_reg);
15637 		break;
15638 	case BPF_ARSH:
15639 		if (alu32)
15640 			scalar32_min_max_arsh(dst_reg, &src_reg);
15641 		else
15642 			scalar_min_max_arsh(dst_reg, &src_reg);
15643 		break;
15644 	default:
15645 		break;
15646 	}
15647 
15648 	/* ALU32 ops are zero extended into 64bit register */
15649 	if (alu32)
15650 		zext_32_to_64(dst_reg);
15651 	reg_bounds_sync(dst_reg);
15652 	return 0;
15653 }
15654 
15655 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15656  * and var_off.
15657  */
15658 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15659 				   struct bpf_insn *insn)
15660 {
15661 	struct bpf_verifier_state *vstate = env->cur_state;
15662 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15663 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15664 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15665 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15666 	u8 opcode = BPF_OP(insn->code);
15667 	int err;
15668 
15669 	dst_reg = &regs[insn->dst_reg];
15670 	src_reg = NULL;
15671 
15672 	if (dst_reg->type == PTR_TO_ARENA) {
15673 		struct bpf_insn_aux_data *aux = cur_aux(env);
15674 
15675 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15676 			/*
15677 			 * 32-bit operations zero upper bits automatically.
15678 			 * 64-bit operations need to be converted to 32.
15679 			 */
15680 			aux->needs_zext = true;
15681 
15682 		/* Any arithmetic operations are allowed on arena pointers */
15683 		return 0;
15684 	}
15685 
15686 	if (dst_reg->type != SCALAR_VALUE)
15687 		ptr_reg = dst_reg;
15688 
15689 	if (BPF_SRC(insn->code) == BPF_X) {
15690 		src_reg = &regs[insn->src_reg];
15691 		if (src_reg->type != SCALAR_VALUE) {
15692 			if (dst_reg->type != SCALAR_VALUE) {
15693 				/* Combining two pointers by any ALU op yields
15694 				 * an arbitrary scalar. Disallow all math except
15695 				 * pointer subtraction
15696 				 */
15697 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15698 					mark_reg_unknown(env, regs, insn->dst_reg);
15699 					return 0;
15700 				}
15701 				verbose(env, "R%d pointer %s pointer prohibited\n",
15702 					insn->dst_reg,
15703 					bpf_alu_string[opcode >> 4]);
15704 				return -EACCES;
15705 			} else {
15706 				/* scalar += pointer
15707 				 * This is legal, but we have to reverse our
15708 				 * src/dest handling in computing the range
15709 				 */
15710 				err = mark_chain_precision(env, insn->dst_reg);
15711 				if (err)
15712 					return err;
15713 				return adjust_ptr_min_max_vals(env, insn,
15714 							       src_reg, dst_reg);
15715 			}
15716 		} else if (ptr_reg) {
15717 			/* pointer += scalar */
15718 			err = mark_chain_precision(env, insn->src_reg);
15719 			if (err)
15720 				return err;
15721 			return adjust_ptr_min_max_vals(env, insn,
15722 						       dst_reg, src_reg);
15723 		} else if (dst_reg->precise) {
15724 			/* if dst_reg is precise, src_reg should be precise as well */
15725 			err = mark_chain_precision(env, insn->src_reg);
15726 			if (err)
15727 				return err;
15728 		}
15729 	} else {
15730 		/* Pretend the src is a reg with a known value, since we only
15731 		 * need to be able to read from this state.
15732 		 */
15733 		off_reg.type = SCALAR_VALUE;
15734 		__mark_reg_known(&off_reg, insn->imm);
15735 		src_reg = &off_reg;
15736 		if (ptr_reg) /* pointer += K */
15737 			return adjust_ptr_min_max_vals(env, insn,
15738 						       ptr_reg, src_reg);
15739 	}
15740 
15741 	/* Got here implies adding two SCALAR_VALUEs */
15742 	if (WARN_ON_ONCE(ptr_reg)) {
15743 		print_verifier_state(env, vstate, vstate->curframe, true);
15744 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15745 		return -EFAULT;
15746 	}
15747 	if (WARN_ON(!src_reg)) {
15748 		print_verifier_state(env, vstate, vstate->curframe, true);
15749 		verbose(env, "verifier internal error: no src_reg\n");
15750 		return -EFAULT;
15751 	}
15752 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15753 	if (err)
15754 		return err;
15755 	/*
15756 	 * Compilers can generate the code
15757 	 * r1 = r2
15758 	 * r1 += 0x1
15759 	 * if r2 < 1000 goto ...
15760 	 * use r1 in memory access
15761 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15762 	 * update r1 after 'if' condition.
15763 	 */
15764 	if (env->bpf_capable &&
15765 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15766 	    dst_reg->id && is_reg_const(src_reg, false)) {
15767 		u64 val = reg_const_value(src_reg, false);
15768 
15769 		if ((dst_reg->id & BPF_ADD_CONST) ||
15770 		    /* prevent overflow in sync_linked_regs() later */
15771 		    val > (u32)S32_MAX) {
15772 			/*
15773 			 * If the register already went through rX += val
15774 			 * we cannot accumulate another val into rx->off.
15775 			 */
15776 			dst_reg->off = 0;
15777 			dst_reg->id = 0;
15778 		} else {
15779 			dst_reg->id |= BPF_ADD_CONST;
15780 			dst_reg->off = val;
15781 		}
15782 	} else {
15783 		/*
15784 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15785 		 * incorrectly propagated into other registers by sync_linked_regs()
15786 		 */
15787 		dst_reg->id = 0;
15788 	}
15789 	return 0;
15790 }
15791 
15792 /* check validity of 32-bit and 64-bit arithmetic operations */
15793 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15794 {
15795 	struct bpf_reg_state *regs = cur_regs(env);
15796 	u8 opcode = BPF_OP(insn->code);
15797 	int err;
15798 
15799 	if (opcode == BPF_END || opcode == BPF_NEG) {
15800 		if (opcode == BPF_NEG) {
15801 			if (BPF_SRC(insn->code) != BPF_K ||
15802 			    insn->src_reg != BPF_REG_0 ||
15803 			    insn->off != 0 || insn->imm != 0) {
15804 				verbose(env, "BPF_NEG uses reserved fields\n");
15805 				return -EINVAL;
15806 			}
15807 		} else {
15808 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15809 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15810 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15811 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15812 				verbose(env, "BPF_END uses reserved fields\n");
15813 				return -EINVAL;
15814 			}
15815 		}
15816 
15817 		/* check src operand */
15818 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15819 		if (err)
15820 			return err;
15821 
15822 		if (is_pointer_value(env, insn->dst_reg)) {
15823 			verbose(env, "R%d pointer arithmetic prohibited\n",
15824 				insn->dst_reg);
15825 			return -EACCES;
15826 		}
15827 
15828 		/* check dest operand */
15829 		if (opcode == BPF_NEG &&
15830 		    regs[insn->dst_reg].type == SCALAR_VALUE) {
15831 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15832 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15833 							 &regs[insn->dst_reg],
15834 							 regs[insn->dst_reg]);
15835 		} else {
15836 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15837 		}
15838 		if (err)
15839 			return err;
15840 
15841 	} else if (opcode == BPF_MOV) {
15842 
15843 		if (BPF_SRC(insn->code) == BPF_X) {
15844 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15845 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15846 				    insn->imm) {
15847 					verbose(env, "BPF_MOV uses reserved fields\n");
15848 					return -EINVAL;
15849 				}
15850 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15851 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15852 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15853 					return -EINVAL;
15854 				}
15855 				if (!env->prog->aux->arena) {
15856 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15857 					return -EINVAL;
15858 				}
15859 			} else {
15860 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15861 				     insn->off != 32) || insn->imm) {
15862 					verbose(env, "BPF_MOV uses reserved fields\n");
15863 					return -EINVAL;
15864 				}
15865 			}
15866 
15867 			/* check src operand */
15868 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15869 			if (err)
15870 				return err;
15871 		} else {
15872 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15873 				verbose(env, "BPF_MOV uses reserved fields\n");
15874 				return -EINVAL;
15875 			}
15876 		}
15877 
15878 		/* check dest operand, mark as required later */
15879 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15880 		if (err)
15881 			return err;
15882 
15883 		if (BPF_SRC(insn->code) == BPF_X) {
15884 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15885 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15886 
15887 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15888 				if (insn->imm) {
15889 					/* off == BPF_ADDR_SPACE_CAST */
15890 					mark_reg_unknown(env, regs, insn->dst_reg);
15891 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15892 						dst_reg->type = PTR_TO_ARENA;
15893 						/* PTR_TO_ARENA is 32-bit */
15894 						dst_reg->subreg_def = env->insn_idx + 1;
15895 					}
15896 				} else if (insn->off == 0) {
15897 					/* case: R1 = R2
15898 					 * copy register state to dest reg
15899 					 */
15900 					assign_scalar_id_before_mov(env, src_reg);
15901 					copy_register_state(dst_reg, src_reg);
15902 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15903 				} else {
15904 					/* case: R1 = (s8, s16 s32)R2 */
15905 					if (is_pointer_value(env, insn->src_reg)) {
15906 						verbose(env,
15907 							"R%d sign-extension part of pointer\n",
15908 							insn->src_reg);
15909 						return -EACCES;
15910 					} else if (src_reg->type == SCALAR_VALUE) {
15911 						bool no_sext;
15912 
15913 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15914 						if (no_sext)
15915 							assign_scalar_id_before_mov(env, src_reg);
15916 						copy_register_state(dst_reg, src_reg);
15917 						if (!no_sext)
15918 							dst_reg->id = 0;
15919 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15920 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15921 					} else {
15922 						mark_reg_unknown(env, regs, insn->dst_reg);
15923 					}
15924 				}
15925 			} else {
15926 				/* R1 = (u32) R2 */
15927 				if (is_pointer_value(env, insn->src_reg)) {
15928 					verbose(env,
15929 						"R%d partial copy of pointer\n",
15930 						insn->src_reg);
15931 					return -EACCES;
15932 				} else if (src_reg->type == SCALAR_VALUE) {
15933 					if (insn->off == 0) {
15934 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15935 
15936 						if (is_src_reg_u32)
15937 							assign_scalar_id_before_mov(env, src_reg);
15938 						copy_register_state(dst_reg, src_reg);
15939 						/* Make sure ID is cleared if src_reg is not in u32
15940 						 * range otherwise dst_reg min/max could be incorrectly
15941 						 * propagated into src_reg by sync_linked_regs()
15942 						 */
15943 						if (!is_src_reg_u32)
15944 							dst_reg->id = 0;
15945 						dst_reg->subreg_def = env->insn_idx + 1;
15946 					} else {
15947 						/* case: W1 = (s8, s16)W2 */
15948 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15949 
15950 						if (no_sext)
15951 							assign_scalar_id_before_mov(env, src_reg);
15952 						copy_register_state(dst_reg, src_reg);
15953 						if (!no_sext)
15954 							dst_reg->id = 0;
15955 						dst_reg->subreg_def = env->insn_idx + 1;
15956 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15957 					}
15958 				} else {
15959 					mark_reg_unknown(env, regs,
15960 							 insn->dst_reg);
15961 				}
15962 				zext_32_to_64(dst_reg);
15963 				reg_bounds_sync(dst_reg);
15964 			}
15965 		} else {
15966 			/* case: R = imm
15967 			 * remember the value we stored into this reg
15968 			 */
15969 			/* clear any state __mark_reg_known doesn't set */
15970 			mark_reg_unknown(env, regs, insn->dst_reg);
15971 			regs[insn->dst_reg].type = SCALAR_VALUE;
15972 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15973 				__mark_reg_known(regs + insn->dst_reg,
15974 						 insn->imm);
15975 			} else {
15976 				__mark_reg_known(regs + insn->dst_reg,
15977 						 (u32)insn->imm);
15978 			}
15979 		}
15980 
15981 	} else if (opcode > BPF_END) {
15982 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15983 		return -EINVAL;
15984 
15985 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15986 
15987 		if (BPF_SRC(insn->code) == BPF_X) {
15988 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
15989 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15990 				verbose(env, "BPF_ALU uses reserved fields\n");
15991 				return -EINVAL;
15992 			}
15993 			/* check src1 operand */
15994 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15995 			if (err)
15996 				return err;
15997 		} else {
15998 			if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
15999 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
16000 				verbose(env, "BPF_ALU uses reserved fields\n");
16001 				return -EINVAL;
16002 			}
16003 		}
16004 
16005 		/* check src2 operand */
16006 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16007 		if (err)
16008 			return err;
16009 
16010 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
16011 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
16012 			verbose(env, "div by zero\n");
16013 			return -EINVAL;
16014 		}
16015 
16016 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
16017 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
16018 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
16019 
16020 			if (insn->imm < 0 || insn->imm >= size) {
16021 				verbose(env, "invalid shift %d\n", insn->imm);
16022 				return -EINVAL;
16023 			}
16024 		}
16025 
16026 		/* check dest operand */
16027 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16028 		err = err ?: adjust_reg_min_max_vals(env, insn);
16029 		if (err)
16030 			return err;
16031 	}
16032 
16033 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
16034 }
16035 
16036 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
16037 				   struct bpf_reg_state *dst_reg,
16038 				   enum bpf_reg_type type,
16039 				   bool range_right_open)
16040 {
16041 	struct bpf_func_state *state;
16042 	struct bpf_reg_state *reg;
16043 	int new_range;
16044 
16045 	if (dst_reg->off < 0 ||
16046 	    (dst_reg->off == 0 && range_right_open))
16047 		/* This doesn't give us any range */
16048 		return;
16049 
16050 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
16051 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
16052 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
16053 		 * than pkt_end, but that's because it's also less than pkt.
16054 		 */
16055 		return;
16056 
16057 	new_range = dst_reg->off;
16058 	if (range_right_open)
16059 		new_range++;
16060 
16061 	/* Examples for register markings:
16062 	 *
16063 	 * pkt_data in dst register:
16064 	 *
16065 	 *   r2 = r3;
16066 	 *   r2 += 8;
16067 	 *   if (r2 > pkt_end) goto <handle exception>
16068 	 *   <access okay>
16069 	 *
16070 	 *   r2 = r3;
16071 	 *   r2 += 8;
16072 	 *   if (r2 < pkt_end) goto <access okay>
16073 	 *   <handle exception>
16074 	 *
16075 	 *   Where:
16076 	 *     r2 == dst_reg, pkt_end == src_reg
16077 	 *     r2=pkt(id=n,off=8,r=0)
16078 	 *     r3=pkt(id=n,off=0,r=0)
16079 	 *
16080 	 * pkt_data in src register:
16081 	 *
16082 	 *   r2 = r3;
16083 	 *   r2 += 8;
16084 	 *   if (pkt_end >= r2) goto <access okay>
16085 	 *   <handle exception>
16086 	 *
16087 	 *   r2 = r3;
16088 	 *   r2 += 8;
16089 	 *   if (pkt_end <= r2) goto <handle exception>
16090 	 *   <access okay>
16091 	 *
16092 	 *   Where:
16093 	 *     pkt_end == dst_reg, r2 == src_reg
16094 	 *     r2=pkt(id=n,off=8,r=0)
16095 	 *     r3=pkt(id=n,off=0,r=0)
16096 	 *
16097 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16098 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16099 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
16100 	 * the check.
16101 	 */
16102 
16103 	/* If our ids match, then we must have the same max_value.  And we
16104 	 * don't care about the other reg's fixed offset, since if it's too big
16105 	 * the range won't allow anything.
16106 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
16107 	 */
16108 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16109 		if (reg->type == type && reg->id == dst_reg->id)
16110 			/* keep the maximum range already checked */
16111 			reg->range = max(reg->range, new_range);
16112 	}));
16113 }
16114 
16115 /*
16116  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16117  */
16118 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16119 				  u8 opcode, bool is_jmp32)
16120 {
16121 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16122 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16123 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
16124 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
16125 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
16126 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
16127 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
16128 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
16129 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
16130 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
16131 
16132 	if (reg1 == reg2) {
16133 		switch (opcode) {
16134 		case BPF_JGE:
16135 		case BPF_JLE:
16136 		case BPF_JSGE:
16137 		case BPF_JSLE:
16138 		case BPF_JEQ:
16139 			return 1;
16140 		case BPF_JGT:
16141 		case BPF_JLT:
16142 		case BPF_JSGT:
16143 		case BPF_JSLT:
16144 		case BPF_JNE:
16145 			return 0;
16146 		case BPF_JSET:
16147 			if (tnum_is_const(t1))
16148 				return t1.value != 0;
16149 			else
16150 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16151 		default:
16152 			return -1;
16153 		}
16154 	}
16155 
16156 	switch (opcode) {
16157 	case BPF_JEQ:
16158 		/* constants, umin/umax and smin/smax checks would be
16159 		 * redundant in this case because they all should match
16160 		 */
16161 		if (tnum_is_const(t1) && tnum_is_const(t2))
16162 			return t1.value == t2.value;
16163 		if (!tnum_overlap(t1, t2))
16164 			return 0;
16165 		/* non-overlapping ranges */
16166 		if (umin1 > umax2 || umax1 < umin2)
16167 			return 0;
16168 		if (smin1 > smax2 || smax1 < smin2)
16169 			return 0;
16170 		if (!is_jmp32) {
16171 			/* if 64-bit ranges are inconclusive, see if we can
16172 			 * utilize 32-bit subrange knowledge to eliminate
16173 			 * branches that can't be taken a priori
16174 			 */
16175 			if (reg1->u32_min_value > reg2->u32_max_value ||
16176 			    reg1->u32_max_value < reg2->u32_min_value)
16177 				return 0;
16178 			if (reg1->s32_min_value > reg2->s32_max_value ||
16179 			    reg1->s32_max_value < reg2->s32_min_value)
16180 				return 0;
16181 		}
16182 		break;
16183 	case BPF_JNE:
16184 		/* constants, umin/umax and smin/smax checks would be
16185 		 * redundant in this case because they all should match
16186 		 */
16187 		if (tnum_is_const(t1) && tnum_is_const(t2))
16188 			return t1.value != t2.value;
16189 		if (!tnum_overlap(t1, t2))
16190 			return 1;
16191 		/* non-overlapping ranges */
16192 		if (umin1 > umax2 || umax1 < umin2)
16193 			return 1;
16194 		if (smin1 > smax2 || smax1 < smin2)
16195 			return 1;
16196 		if (!is_jmp32) {
16197 			/* if 64-bit ranges are inconclusive, see if we can
16198 			 * utilize 32-bit subrange knowledge to eliminate
16199 			 * branches that can't be taken a priori
16200 			 */
16201 			if (reg1->u32_min_value > reg2->u32_max_value ||
16202 			    reg1->u32_max_value < reg2->u32_min_value)
16203 				return 1;
16204 			if (reg1->s32_min_value > reg2->s32_max_value ||
16205 			    reg1->s32_max_value < reg2->s32_min_value)
16206 				return 1;
16207 		}
16208 		break;
16209 	case BPF_JSET:
16210 		if (!is_reg_const(reg2, is_jmp32)) {
16211 			swap(reg1, reg2);
16212 			swap(t1, t2);
16213 		}
16214 		if (!is_reg_const(reg2, is_jmp32))
16215 			return -1;
16216 		if ((~t1.mask & t1.value) & t2.value)
16217 			return 1;
16218 		if (!((t1.mask | t1.value) & t2.value))
16219 			return 0;
16220 		break;
16221 	case BPF_JGT:
16222 		if (umin1 > umax2)
16223 			return 1;
16224 		else if (umax1 <= umin2)
16225 			return 0;
16226 		break;
16227 	case BPF_JSGT:
16228 		if (smin1 > smax2)
16229 			return 1;
16230 		else if (smax1 <= smin2)
16231 			return 0;
16232 		break;
16233 	case BPF_JLT:
16234 		if (umax1 < umin2)
16235 			return 1;
16236 		else if (umin1 >= umax2)
16237 			return 0;
16238 		break;
16239 	case BPF_JSLT:
16240 		if (smax1 < smin2)
16241 			return 1;
16242 		else if (smin1 >= smax2)
16243 			return 0;
16244 		break;
16245 	case BPF_JGE:
16246 		if (umin1 >= umax2)
16247 			return 1;
16248 		else if (umax1 < umin2)
16249 			return 0;
16250 		break;
16251 	case BPF_JSGE:
16252 		if (smin1 >= smax2)
16253 			return 1;
16254 		else if (smax1 < smin2)
16255 			return 0;
16256 		break;
16257 	case BPF_JLE:
16258 		if (umax1 <= umin2)
16259 			return 1;
16260 		else if (umin1 > umax2)
16261 			return 0;
16262 		break;
16263 	case BPF_JSLE:
16264 		if (smax1 <= smin2)
16265 			return 1;
16266 		else if (smin1 > smax2)
16267 			return 0;
16268 		break;
16269 	}
16270 
16271 	return -1;
16272 }
16273 
16274 static int flip_opcode(u32 opcode)
16275 {
16276 	/* How can we transform "a <op> b" into "b <op> a"? */
16277 	static const u8 opcode_flip[16] = {
16278 		/* these stay the same */
16279 		[BPF_JEQ  >> 4] = BPF_JEQ,
16280 		[BPF_JNE  >> 4] = BPF_JNE,
16281 		[BPF_JSET >> 4] = BPF_JSET,
16282 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16283 		[BPF_JGE  >> 4] = BPF_JLE,
16284 		[BPF_JGT  >> 4] = BPF_JLT,
16285 		[BPF_JLE  >> 4] = BPF_JGE,
16286 		[BPF_JLT  >> 4] = BPF_JGT,
16287 		[BPF_JSGE >> 4] = BPF_JSLE,
16288 		[BPF_JSGT >> 4] = BPF_JSLT,
16289 		[BPF_JSLE >> 4] = BPF_JSGE,
16290 		[BPF_JSLT >> 4] = BPF_JSGT
16291 	};
16292 	return opcode_flip[opcode >> 4];
16293 }
16294 
16295 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16296 				   struct bpf_reg_state *src_reg,
16297 				   u8 opcode)
16298 {
16299 	struct bpf_reg_state *pkt;
16300 
16301 	if (src_reg->type == PTR_TO_PACKET_END) {
16302 		pkt = dst_reg;
16303 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16304 		pkt = src_reg;
16305 		opcode = flip_opcode(opcode);
16306 	} else {
16307 		return -1;
16308 	}
16309 
16310 	if (pkt->range >= 0)
16311 		return -1;
16312 
16313 	switch (opcode) {
16314 	case BPF_JLE:
16315 		/* pkt <= pkt_end */
16316 		fallthrough;
16317 	case BPF_JGT:
16318 		/* pkt > pkt_end */
16319 		if (pkt->range == BEYOND_PKT_END)
16320 			/* pkt has at last one extra byte beyond pkt_end */
16321 			return opcode == BPF_JGT;
16322 		break;
16323 	case BPF_JLT:
16324 		/* pkt < pkt_end */
16325 		fallthrough;
16326 	case BPF_JGE:
16327 		/* pkt >= pkt_end */
16328 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16329 			return opcode == BPF_JGE;
16330 		break;
16331 	}
16332 	return -1;
16333 }
16334 
16335 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16336  * and return:
16337  *  1 - branch will be taken and "goto target" will be executed
16338  *  0 - branch will not be taken and fall-through to next insn
16339  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16340  *      range [0,10]
16341  */
16342 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16343 			   u8 opcode, bool is_jmp32)
16344 {
16345 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16346 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16347 
16348 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16349 		u64 val;
16350 
16351 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16352 		if (!is_reg_const(reg2, is_jmp32)) {
16353 			opcode = flip_opcode(opcode);
16354 			swap(reg1, reg2);
16355 		}
16356 		/* and ensure that reg2 is a constant */
16357 		if (!is_reg_const(reg2, is_jmp32))
16358 			return -1;
16359 
16360 		if (!reg_not_null(reg1))
16361 			return -1;
16362 
16363 		/* If pointer is valid tests against zero will fail so we can
16364 		 * use this to direct branch taken.
16365 		 */
16366 		val = reg_const_value(reg2, is_jmp32);
16367 		if (val != 0)
16368 			return -1;
16369 
16370 		switch (opcode) {
16371 		case BPF_JEQ:
16372 			return 0;
16373 		case BPF_JNE:
16374 			return 1;
16375 		default:
16376 			return -1;
16377 		}
16378 	}
16379 
16380 	/* now deal with two scalars, but not necessarily constants */
16381 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16382 }
16383 
16384 /* Opcode that corresponds to a *false* branch condition.
16385  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16386  */
16387 static u8 rev_opcode(u8 opcode)
16388 {
16389 	switch (opcode) {
16390 	case BPF_JEQ:		return BPF_JNE;
16391 	case BPF_JNE:		return BPF_JEQ;
16392 	/* JSET doesn't have it's reverse opcode in BPF, so add
16393 	 * BPF_X flag to denote the reverse of that operation
16394 	 */
16395 	case BPF_JSET:		return BPF_JSET | BPF_X;
16396 	case BPF_JSET | BPF_X:	return BPF_JSET;
16397 	case BPF_JGE:		return BPF_JLT;
16398 	case BPF_JGT:		return BPF_JLE;
16399 	case BPF_JLE:		return BPF_JGT;
16400 	case BPF_JLT:		return BPF_JGE;
16401 	case BPF_JSGE:		return BPF_JSLT;
16402 	case BPF_JSGT:		return BPF_JSLE;
16403 	case BPF_JSLE:		return BPF_JSGT;
16404 	case BPF_JSLT:		return BPF_JSGE;
16405 	default:		return 0;
16406 	}
16407 }
16408 
16409 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16410 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16411 				u8 opcode, bool is_jmp32)
16412 {
16413 	struct tnum t;
16414 	u64 val;
16415 
16416 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16417 	switch (opcode) {
16418 	case BPF_JGE:
16419 	case BPF_JGT:
16420 	case BPF_JSGE:
16421 	case BPF_JSGT:
16422 		opcode = flip_opcode(opcode);
16423 		swap(reg1, reg2);
16424 		break;
16425 	default:
16426 		break;
16427 	}
16428 
16429 	switch (opcode) {
16430 	case BPF_JEQ:
16431 		if (is_jmp32) {
16432 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16433 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16434 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16435 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16436 			reg2->u32_min_value = reg1->u32_min_value;
16437 			reg2->u32_max_value = reg1->u32_max_value;
16438 			reg2->s32_min_value = reg1->s32_min_value;
16439 			reg2->s32_max_value = reg1->s32_max_value;
16440 
16441 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16442 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16443 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16444 		} else {
16445 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16446 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16447 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16448 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16449 			reg2->umin_value = reg1->umin_value;
16450 			reg2->umax_value = reg1->umax_value;
16451 			reg2->smin_value = reg1->smin_value;
16452 			reg2->smax_value = reg1->smax_value;
16453 
16454 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16455 			reg2->var_off = reg1->var_off;
16456 		}
16457 		break;
16458 	case BPF_JNE:
16459 		if (!is_reg_const(reg2, is_jmp32))
16460 			swap(reg1, reg2);
16461 		if (!is_reg_const(reg2, is_jmp32))
16462 			break;
16463 
16464 		/* try to recompute the bound of reg1 if reg2 is a const and
16465 		 * is exactly the edge of reg1.
16466 		 */
16467 		val = reg_const_value(reg2, is_jmp32);
16468 		if (is_jmp32) {
16469 			/* u32_min_value is not equal to 0xffffffff at this point,
16470 			 * because otherwise u32_max_value is 0xffffffff as well,
16471 			 * in such a case both reg1 and reg2 would be constants,
16472 			 * jump would be predicted and reg_set_min_max() won't
16473 			 * be called.
16474 			 *
16475 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16476 			 * below.
16477 			 */
16478 			if (reg1->u32_min_value == (u32)val)
16479 				reg1->u32_min_value++;
16480 			if (reg1->u32_max_value == (u32)val)
16481 				reg1->u32_max_value--;
16482 			if (reg1->s32_min_value == (s32)val)
16483 				reg1->s32_min_value++;
16484 			if (reg1->s32_max_value == (s32)val)
16485 				reg1->s32_max_value--;
16486 		} else {
16487 			if (reg1->umin_value == (u64)val)
16488 				reg1->umin_value++;
16489 			if (reg1->umax_value == (u64)val)
16490 				reg1->umax_value--;
16491 			if (reg1->smin_value == (s64)val)
16492 				reg1->smin_value++;
16493 			if (reg1->smax_value == (s64)val)
16494 				reg1->smax_value--;
16495 		}
16496 		break;
16497 	case BPF_JSET:
16498 		if (!is_reg_const(reg2, is_jmp32))
16499 			swap(reg1, reg2);
16500 		if (!is_reg_const(reg2, is_jmp32))
16501 			break;
16502 		val = reg_const_value(reg2, is_jmp32);
16503 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16504 		 * requires single bit to learn something useful. E.g., if we
16505 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16506 		 * are actually set? We can learn something definite only if
16507 		 * it's a single-bit value to begin with.
16508 		 *
16509 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16510 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16511 		 * bit 1 is set, which we can readily use in adjustments.
16512 		 */
16513 		if (!is_power_of_2(val))
16514 			break;
16515 		if (is_jmp32) {
16516 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16517 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16518 		} else {
16519 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16520 		}
16521 		break;
16522 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16523 		if (!is_reg_const(reg2, is_jmp32))
16524 			swap(reg1, reg2);
16525 		if (!is_reg_const(reg2, is_jmp32))
16526 			break;
16527 		val = reg_const_value(reg2, is_jmp32);
16528 		/* Forget the ranges before narrowing tnums, to avoid invariant
16529 		 * violations if we're on a dead branch.
16530 		 */
16531 		__mark_reg_unbounded(reg1);
16532 		if (is_jmp32) {
16533 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16534 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16535 		} else {
16536 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16537 		}
16538 		break;
16539 	case BPF_JLE:
16540 		if (is_jmp32) {
16541 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16542 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16543 		} else {
16544 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16545 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16546 		}
16547 		break;
16548 	case BPF_JLT:
16549 		if (is_jmp32) {
16550 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16551 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16552 		} else {
16553 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16554 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16555 		}
16556 		break;
16557 	case BPF_JSLE:
16558 		if (is_jmp32) {
16559 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16560 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16561 		} else {
16562 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16563 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16564 		}
16565 		break;
16566 	case BPF_JSLT:
16567 		if (is_jmp32) {
16568 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16569 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16570 		} else {
16571 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16572 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16573 		}
16574 		break;
16575 	default:
16576 		return;
16577 	}
16578 }
16579 
16580 /* Adjusts the register min/max values in the case that the dst_reg and
16581  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16582  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16583  * Technically we can do similar adjustments for pointers to the same object,
16584  * but we don't support that right now.
16585  */
16586 static int reg_set_min_max(struct bpf_verifier_env *env,
16587 			   struct bpf_reg_state *true_reg1,
16588 			   struct bpf_reg_state *true_reg2,
16589 			   struct bpf_reg_state *false_reg1,
16590 			   struct bpf_reg_state *false_reg2,
16591 			   u8 opcode, bool is_jmp32)
16592 {
16593 	int err;
16594 
16595 	/* If either register is a pointer, we can't learn anything about its
16596 	 * variable offset from the compare (unless they were a pointer into
16597 	 * the same object, but we don't bother with that).
16598 	 */
16599 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16600 		return 0;
16601 
16602 	/* We compute branch direction for same SCALAR_VALUE registers in
16603 	 * is_scalar_branch_taken(). For unknown branch directions (e.g., BPF_JSET)
16604 	 * on the same registers, we don't need to adjust the min/max values.
16605 	 */
16606 	if (false_reg1 == false_reg2)
16607 		return 0;
16608 
16609 	/* fallthrough (FALSE) branch */
16610 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16611 	reg_bounds_sync(false_reg1);
16612 	reg_bounds_sync(false_reg2);
16613 
16614 	/* jump (TRUE) branch */
16615 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16616 	reg_bounds_sync(true_reg1);
16617 	reg_bounds_sync(true_reg2);
16618 
16619 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16620 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16621 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16622 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16623 	return err;
16624 }
16625 
16626 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16627 				 struct bpf_reg_state *reg, u32 id,
16628 				 bool is_null)
16629 {
16630 	if (type_may_be_null(reg->type) && reg->id == id &&
16631 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16632 		/* Old offset (both fixed and variable parts) should have been
16633 		 * known-zero, because we don't allow pointer arithmetic on
16634 		 * pointers that might be NULL. If we see this happening, don't
16635 		 * convert the register.
16636 		 *
16637 		 * But in some cases, some helpers that return local kptrs
16638 		 * advance offset for the returned pointer. In those cases, it
16639 		 * is fine to expect to see reg->off.
16640 		 */
16641 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16642 			return;
16643 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16644 		    WARN_ON_ONCE(reg->off))
16645 			return;
16646 
16647 		if (is_null) {
16648 			reg->type = SCALAR_VALUE;
16649 			/* We don't need id and ref_obj_id from this point
16650 			 * onwards anymore, thus we should better reset it,
16651 			 * so that state pruning has chances to take effect.
16652 			 */
16653 			reg->id = 0;
16654 			reg->ref_obj_id = 0;
16655 
16656 			return;
16657 		}
16658 
16659 		mark_ptr_not_null_reg(reg);
16660 
16661 		if (!reg_may_point_to_spin_lock(reg)) {
16662 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16663 			 * in release_reference().
16664 			 *
16665 			 * reg->id is still used by spin_lock ptr. Other
16666 			 * than spin_lock ptr type, reg->id can be reset.
16667 			 */
16668 			reg->id = 0;
16669 		}
16670 	}
16671 }
16672 
16673 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16674  * be folded together at some point.
16675  */
16676 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16677 				  bool is_null)
16678 {
16679 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16680 	struct bpf_reg_state *regs = state->regs, *reg;
16681 	u32 ref_obj_id = regs[regno].ref_obj_id;
16682 	u32 id = regs[regno].id;
16683 
16684 	if (ref_obj_id && ref_obj_id == id && is_null)
16685 		/* regs[regno] is in the " == NULL" branch.
16686 		 * No one could have freed the reference state before
16687 		 * doing the NULL check.
16688 		 */
16689 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16690 
16691 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16692 		mark_ptr_or_null_reg(state, reg, id, is_null);
16693 	}));
16694 }
16695 
16696 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16697 				   struct bpf_reg_state *dst_reg,
16698 				   struct bpf_reg_state *src_reg,
16699 				   struct bpf_verifier_state *this_branch,
16700 				   struct bpf_verifier_state *other_branch)
16701 {
16702 	if (BPF_SRC(insn->code) != BPF_X)
16703 		return false;
16704 
16705 	/* Pointers are always 64-bit. */
16706 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16707 		return false;
16708 
16709 	switch (BPF_OP(insn->code)) {
16710 	case BPF_JGT:
16711 		if ((dst_reg->type == PTR_TO_PACKET &&
16712 		     src_reg->type == PTR_TO_PACKET_END) ||
16713 		    (dst_reg->type == PTR_TO_PACKET_META &&
16714 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16715 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16716 			find_good_pkt_pointers(this_branch, dst_reg,
16717 					       dst_reg->type, false);
16718 			mark_pkt_end(other_branch, insn->dst_reg, true);
16719 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16720 			    src_reg->type == PTR_TO_PACKET) ||
16721 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16722 			    src_reg->type == PTR_TO_PACKET_META)) {
16723 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16724 			find_good_pkt_pointers(other_branch, src_reg,
16725 					       src_reg->type, true);
16726 			mark_pkt_end(this_branch, insn->src_reg, false);
16727 		} else {
16728 			return false;
16729 		}
16730 		break;
16731 	case BPF_JLT:
16732 		if ((dst_reg->type == PTR_TO_PACKET &&
16733 		     src_reg->type == PTR_TO_PACKET_END) ||
16734 		    (dst_reg->type == PTR_TO_PACKET_META &&
16735 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16736 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16737 			find_good_pkt_pointers(other_branch, dst_reg,
16738 					       dst_reg->type, true);
16739 			mark_pkt_end(this_branch, insn->dst_reg, false);
16740 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16741 			    src_reg->type == PTR_TO_PACKET) ||
16742 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16743 			    src_reg->type == PTR_TO_PACKET_META)) {
16744 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16745 			find_good_pkt_pointers(this_branch, src_reg,
16746 					       src_reg->type, false);
16747 			mark_pkt_end(other_branch, insn->src_reg, true);
16748 		} else {
16749 			return false;
16750 		}
16751 		break;
16752 	case BPF_JGE:
16753 		if ((dst_reg->type == PTR_TO_PACKET &&
16754 		     src_reg->type == PTR_TO_PACKET_END) ||
16755 		    (dst_reg->type == PTR_TO_PACKET_META &&
16756 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16757 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16758 			find_good_pkt_pointers(this_branch, dst_reg,
16759 					       dst_reg->type, true);
16760 			mark_pkt_end(other_branch, insn->dst_reg, false);
16761 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16762 			    src_reg->type == PTR_TO_PACKET) ||
16763 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16764 			    src_reg->type == PTR_TO_PACKET_META)) {
16765 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16766 			find_good_pkt_pointers(other_branch, src_reg,
16767 					       src_reg->type, false);
16768 			mark_pkt_end(this_branch, insn->src_reg, true);
16769 		} else {
16770 			return false;
16771 		}
16772 		break;
16773 	case BPF_JLE:
16774 		if ((dst_reg->type == PTR_TO_PACKET &&
16775 		     src_reg->type == PTR_TO_PACKET_END) ||
16776 		    (dst_reg->type == PTR_TO_PACKET_META &&
16777 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16778 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16779 			find_good_pkt_pointers(other_branch, dst_reg,
16780 					       dst_reg->type, false);
16781 			mark_pkt_end(this_branch, insn->dst_reg, true);
16782 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16783 			    src_reg->type == PTR_TO_PACKET) ||
16784 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16785 			    src_reg->type == PTR_TO_PACKET_META)) {
16786 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16787 			find_good_pkt_pointers(this_branch, src_reg,
16788 					       src_reg->type, true);
16789 			mark_pkt_end(other_branch, insn->src_reg, false);
16790 		} else {
16791 			return false;
16792 		}
16793 		break;
16794 	default:
16795 		return false;
16796 	}
16797 
16798 	return true;
16799 }
16800 
16801 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16802 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16803 {
16804 	struct linked_reg *e;
16805 
16806 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16807 		return;
16808 
16809 	e = linked_regs_push(reg_set);
16810 	if (e) {
16811 		e->frameno = frameno;
16812 		e->is_reg = is_reg;
16813 		e->regno = spi_or_reg;
16814 	} else {
16815 		reg->id = 0;
16816 	}
16817 }
16818 
16819 /* For all R being scalar registers or spilled scalar registers
16820  * in verifier state, save R in linked_regs if R->id == id.
16821  * If there are too many Rs sharing same id, reset id for leftover Rs.
16822  */
16823 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16824 				struct linked_regs *linked_regs)
16825 {
16826 	struct bpf_func_state *func;
16827 	struct bpf_reg_state *reg;
16828 	int i, j;
16829 
16830 	id = id & ~BPF_ADD_CONST;
16831 	for (i = vstate->curframe; i >= 0; i--) {
16832 		func = vstate->frame[i];
16833 		for (j = 0; j < BPF_REG_FP; j++) {
16834 			reg = &func->regs[j];
16835 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16836 		}
16837 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16838 			if (!is_spilled_reg(&func->stack[j]))
16839 				continue;
16840 			reg = &func->stack[j].spilled_ptr;
16841 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16842 		}
16843 	}
16844 }
16845 
16846 /* For all R in linked_regs, copy known_reg range into R
16847  * if R->id == known_reg->id.
16848  */
16849 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16850 			     struct linked_regs *linked_regs)
16851 {
16852 	struct bpf_reg_state fake_reg;
16853 	struct bpf_reg_state *reg;
16854 	struct linked_reg *e;
16855 	int i;
16856 
16857 	for (i = 0; i < linked_regs->cnt; ++i) {
16858 		e = &linked_regs->entries[i];
16859 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16860 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16861 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16862 			continue;
16863 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16864 			continue;
16865 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16866 		    reg->off == known_reg->off) {
16867 			s32 saved_subreg_def = reg->subreg_def;
16868 
16869 			copy_register_state(reg, known_reg);
16870 			reg->subreg_def = saved_subreg_def;
16871 		} else {
16872 			s32 saved_subreg_def = reg->subreg_def;
16873 			s32 saved_off = reg->off;
16874 
16875 			fake_reg.type = SCALAR_VALUE;
16876 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16877 
16878 			/* reg = known_reg; reg += delta */
16879 			copy_register_state(reg, known_reg);
16880 			/*
16881 			 * Must preserve off, id and add_const flag,
16882 			 * otherwise another sync_linked_regs() will be incorrect.
16883 			 */
16884 			reg->off = saved_off;
16885 			reg->subreg_def = saved_subreg_def;
16886 
16887 			scalar32_min_max_add(reg, &fake_reg);
16888 			scalar_min_max_add(reg, &fake_reg);
16889 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16890 		}
16891 	}
16892 }
16893 
16894 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16895 			     struct bpf_insn *insn, int *insn_idx)
16896 {
16897 	struct bpf_verifier_state *this_branch = env->cur_state;
16898 	struct bpf_verifier_state *other_branch;
16899 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16900 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16901 	struct bpf_reg_state *eq_branch_regs;
16902 	struct linked_regs linked_regs = {};
16903 	u8 opcode = BPF_OP(insn->code);
16904 	int insn_flags = 0;
16905 	bool is_jmp32;
16906 	int pred = -1;
16907 	int err;
16908 
16909 	/* Only conditional jumps are expected to reach here. */
16910 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16911 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16912 		return -EINVAL;
16913 	}
16914 
16915 	if (opcode == BPF_JCOND) {
16916 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16917 		int idx = *insn_idx;
16918 
16919 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16920 		    insn->src_reg != BPF_MAY_GOTO ||
16921 		    insn->dst_reg || insn->imm) {
16922 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16923 			return -EINVAL;
16924 		}
16925 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16926 
16927 		/* branch out 'fallthrough' insn as a new state to explore */
16928 		queued_st = push_stack(env, idx + 1, idx, false);
16929 		if (IS_ERR(queued_st))
16930 			return PTR_ERR(queued_st);
16931 
16932 		queued_st->may_goto_depth++;
16933 		if (prev_st)
16934 			widen_imprecise_scalars(env, prev_st, queued_st);
16935 		*insn_idx += insn->off;
16936 		return 0;
16937 	}
16938 
16939 	/* check src2 operand */
16940 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16941 	if (err)
16942 		return err;
16943 
16944 	dst_reg = &regs[insn->dst_reg];
16945 	if (BPF_SRC(insn->code) == BPF_X) {
16946 		if (insn->imm != 0) {
16947 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16948 			return -EINVAL;
16949 		}
16950 
16951 		/* check src1 operand */
16952 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16953 		if (err)
16954 			return err;
16955 
16956 		src_reg = &regs[insn->src_reg];
16957 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16958 		    is_pointer_value(env, insn->src_reg)) {
16959 			verbose(env, "R%d pointer comparison prohibited\n",
16960 				insn->src_reg);
16961 			return -EACCES;
16962 		}
16963 
16964 		if (src_reg->type == PTR_TO_STACK)
16965 			insn_flags |= INSN_F_SRC_REG_STACK;
16966 		if (dst_reg->type == PTR_TO_STACK)
16967 			insn_flags |= INSN_F_DST_REG_STACK;
16968 	} else {
16969 		if (insn->src_reg != BPF_REG_0) {
16970 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16971 			return -EINVAL;
16972 		}
16973 		src_reg = &env->fake_reg[0];
16974 		memset(src_reg, 0, sizeof(*src_reg));
16975 		src_reg->type = SCALAR_VALUE;
16976 		__mark_reg_known(src_reg, insn->imm);
16977 
16978 		if (dst_reg->type == PTR_TO_STACK)
16979 			insn_flags |= INSN_F_DST_REG_STACK;
16980 	}
16981 
16982 	if (insn_flags) {
16983 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16984 		if (err)
16985 			return err;
16986 	}
16987 
16988 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16989 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16990 	if (pred >= 0) {
16991 		/* If we get here with a dst_reg pointer type it is because
16992 		 * above is_branch_taken() special cased the 0 comparison.
16993 		 */
16994 		if (!__is_pointer_value(false, dst_reg))
16995 			err = mark_chain_precision(env, insn->dst_reg);
16996 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16997 		    !__is_pointer_value(false, src_reg))
16998 			err = mark_chain_precision(env, insn->src_reg);
16999 		if (err)
17000 			return err;
17001 	}
17002 
17003 	if (pred == 1) {
17004 		/* Only follow the goto, ignore fall-through. If needed, push
17005 		 * the fall-through branch for simulation under speculative
17006 		 * execution.
17007 		 */
17008 		if (!env->bypass_spec_v1) {
17009 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
17010 			if (err < 0)
17011 				return err;
17012 		}
17013 		if (env->log.level & BPF_LOG_LEVEL)
17014 			print_insn_state(env, this_branch, this_branch->curframe);
17015 		*insn_idx += insn->off;
17016 		return 0;
17017 	} else if (pred == 0) {
17018 		/* Only follow the fall-through branch, since that's where the
17019 		 * program will go. If needed, push the goto branch for
17020 		 * simulation under speculative execution.
17021 		 */
17022 		if (!env->bypass_spec_v1) {
17023 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
17024 							*insn_idx);
17025 			if (err < 0)
17026 				return err;
17027 		}
17028 		if (env->log.level & BPF_LOG_LEVEL)
17029 			print_insn_state(env, this_branch, this_branch->curframe);
17030 		return 0;
17031 	}
17032 
17033 	/* Push scalar registers sharing same ID to jump history,
17034 	 * do this before creating 'other_branch', so that both
17035 	 * 'this_branch' and 'other_branch' share this history
17036 	 * if parent state is created.
17037 	 */
17038 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
17039 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
17040 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
17041 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
17042 	if (linked_regs.cnt > 1) {
17043 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
17044 		if (err)
17045 			return err;
17046 	}
17047 
17048 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17049 	if (IS_ERR(other_branch))
17050 		return PTR_ERR(other_branch);
17051 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17052 
17053 	if (BPF_SRC(insn->code) == BPF_X) {
17054 		err = reg_set_min_max(env,
17055 				      &other_branch_regs[insn->dst_reg],
17056 				      &other_branch_regs[insn->src_reg],
17057 				      dst_reg, src_reg, opcode, is_jmp32);
17058 	} else /* BPF_SRC(insn->code) == BPF_K */ {
17059 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
17060 		 * so that these are two different memory locations. The
17061 		 * src_reg is not used beyond here in context of K.
17062 		 */
17063 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
17064 		       sizeof(env->fake_reg[0]));
17065 		err = reg_set_min_max(env,
17066 				      &other_branch_regs[insn->dst_reg],
17067 				      &env->fake_reg[0],
17068 				      dst_reg, &env->fake_reg[1],
17069 				      opcode, is_jmp32);
17070 	}
17071 	if (err)
17072 		return err;
17073 
17074 	if (BPF_SRC(insn->code) == BPF_X &&
17075 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
17076 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17077 		sync_linked_regs(this_branch, src_reg, &linked_regs);
17078 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
17079 	}
17080 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17081 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17082 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
17083 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
17084 	}
17085 
17086 	/* if one pointer register is compared to another pointer
17087 	 * register check if PTR_MAYBE_NULL could be lifted.
17088 	 * E.g. register A - maybe null
17089 	 *      register B - not null
17090 	 * for JNE A, B, ... - A is not null in the false branch;
17091 	 * for JEQ A, B, ... - A is not null in the true branch.
17092 	 *
17093 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
17094 	 * not need to be null checked by the BPF program, i.e.,
17095 	 * could be null even without PTR_MAYBE_NULL marking, so
17096 	 * only propagate nullness when neither reg is that type.
17097 	 */
17098 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17099 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17100 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
17101 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
17102 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17103 		eq_branch_regs = NULL;
17104 		switch (opcode) {
17105 		case BPF_JEQ:
17106 			eq_branch_regs = other_branch_regs;
17107 			break;
17108 		case BPF_JNE:
17109 			eq_branch_regs = regs;
17110 			break;
17111 		default:
17112 			/* do nothing */
17113 			break;
17114 		}
17115 		if (eq_branch_regs) {
17116 			if (type_may_be_null(src_reg->type))
17117 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17118 			else
17119 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17120 		}
17121 	}
17122 
17123 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17124 	 * NOTE: these optimizations below are related with pointer comparison
17125 	 *       which will never be JMP32.
17126 	 */
17127 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
17128 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17129 	    type_may_be_null(dst_reg->type)) {
17130 		/* Mark all identical registers in each branch as either
17131 		 * safe or unknown depending R == 0 or R != 0 conditional.
17132 		 */
17133 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17134 				      opcode == BPF_JNE);
17135 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17136 				      opcode == BPF_JEQ);
17137 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
17138 					   this_branch, other_branch) &&
17139 		   is_pointer_value(env, insn->dst_reg)) {
17140 		verbose(env, "R%d pointer comparison prohibited\n",
17141 			insn->dst_reg);
17142 		return -EACCES;
17143 	}
17144 	if (env->log.level & BPF_LOG_LEVEL)
17145 		print_insn_state(env, this_branch, this_branch->curframe);
17146 	return 0;
17147 }
17148 
17149 /* verify BPF_LD_IMM64 instruction */
17150 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17151 {
17152 	struct bpf_insn_aux_data *aux = cur_aux(env);
17153 	struct bpf_reg_state *regs = cur_regs(env);
17154 	struct bpf_reg_state *dst_reg;
17155 	struct bpf_map *map;
17156 	int err;
17157 
17158 	if (BPF_SIZE(insn->code) != BPF_DW) {
17159 		verbose(env, "invalid BPF_LD_IMM insn\n");
17160 		return -EINVAL;
17161 	}
17162 	if (insn->off != 0) {
17163 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17164 		return -EINVAL;
17165 	}
17166 
17167 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
17168 	if (err)
17169 		return err;
17170 
17171 	dst_reg = &regs[insn->dst_reg];
17172 	if (insn->src_reg == 0) {
17173 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17174 
17175 		dst_reg->type = SCALAR_VALUE;
17176 		__mark_reg_known(&regs[insn->dst_reg], imm);
17177 		return 0;
17178 	}
17179 
17180 	/* All special src_reg cases are listed below. From this point onwards
17181 	 * we either succeed and assign a corresponding dst_reg->type after
17182 	 * zeroing the offset, or fail and reject the program.
17183 	 */
17184 	mark_reg_known_zero(env, regs, insn->dst_reg);
17185 
17186 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17187 		dst_reg->type = aux->btf_var.reg_type;
17188 		switch (base_type(dst_reg->type)) {
17189 		case PTR_TO_MEM:
17190 			dst_reg->mem_size = aux->btf_var.mem_size;
17191 			break;
17192 		case PTR_TO_BTF_ID:
17193 			dst_reg->btf = aux->btf_var.btf;
17194 			dst_reg->btf_id = aux->btf_var.btf_id;
17195 			break;
17196 		default:
17197 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17198 			return -EFAULT;
17199 		}
17200 		return 0;
17201 	}
17202 
17203 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
17204 		struct bpf_prog_aux *aux = env->prog->aux;
17205 		u32 subprogno = find_subprog(env,
17206 					     env->insn_idx + insn->imm + 1);
17207 
17208 		if (!aux->func_info) {
17209 			verbose(env, "missing btf func_info\n");
17210 			return -EINVAL;
17211 		}
17212 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17213 			verbose(env, "callback function not static\n");
17214 			return -EINVAL;
17215 		}
17216 
17217 		dst_reg->type = PTR_TO_FUNC;
17218 		dst_reg->subprogno = subprogno;
17219 		return 0;
17220 	}
17221 
17222 	map = env->used_maps[aux->map_index];
17223 	dst_reg->map_ptr = map;
17224 
17225 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17226 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17227 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17228 			__mark_reg_unknown(env, dst_reg);
17229 			return 0;
17230 		}
17231 		dst_reg->type = PTR_TO_MAP_VALUE;
17232 		dst_reg->off = aux->map_off;
17233 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17234 			     map->max_entries != 1);
17235 		/* We want reg->id to be same (0) as map_value is not distinct */
17236 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17237 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17238 		dst_reg->type = CONST_PTR_TO_MAP;
17239 	} else {
17240 		verifier_bug(env, "unexpected src reg value for ldimm64");
17241 		return -EFAULT;
17242 	}
17243 
17244 	return 0;
17245 }
17246 
17247 static bool may_access_skb(enum bpf_prog_type type)
17248 {
17249 	switch (type) {
17250 	case BPF_PROG_TYPE_SOCKET_FILTER:
17251 	case BPF_PROG_TYPE_SCHED_CLS:
17252 	case BPF_PROG_TYPE_SCHED_ACT:
17253 		return true;
17254 	default:
17255 		return false;
17256 	}
17257 }
17258 
17259 /* verify safety of LD_ABS|LD_IND instructions:
17260  * - they can only appear in the programs where ctx == skb
17261  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17262  *   preserve R6-R9, and store return value into R0
17263  *
17264  * Implicit input:
17265  *   ctx == skb == R6 == CTX
17266  *
17267  * Explicit input:
17268  *   SRC == any register
17269  *   IMM == 32-bit immediate
17270  *
17271  * Output:
17272  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17273  */
17274 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17275 {
17276 	struct bpf_reg_state *regs = cur_regs(env);
17277 	static const int ctx_reg = BPF_REG_6;
17278 	u8 mode = BPF_MODE(insn->code);
17279 	int i, err;
17280 
17281 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17282 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17283 		return -EINVAL;
17284 	}
17285 
17286 	if (!env->ops->gen_ld_abs) {
17287 		verifier_bug(env, "gen_ld_abs is null");
17288 		return -EFAULT;
17289 	}
17290 
17291 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17292 	    BPF_SIZE(insn->code) == BPF_DW ||
17293 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17294 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17295 		return -EINVAL;
17296 	}
17297 
17298 	/* check whether implicit source operand (register R6) is readable */
17299 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17300 	if (err)
17301 		return err;
17302 
17303 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17304 	 * gen_ld_abs() may terminate the program at runtime, leading to
17305 	 * reference leak.
17306 	 */
17307 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17308 	if (err)
17309 		return err;
17310 
17311 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17312 		verbose(env,
17313 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17314 		return -EINVAL;
17315 	}
17316 
17317 	if (mode == BPF_IND) {
17318 		/* check explicit source operand */
17319 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17320 		if (err)
17321 			return err;
17322 	}
17323 
17324 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17325 	if (err < 0)
17326 		return err;
17327 
17328 	/* reset caller saved regs to unreadable */
17329 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17330 		mark_reg_not_init(env, regs, caller_saved[i]);
17331 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17332 	}
17333 
17334 	/* mark destination R0 register as readable, since it contains
17335 	 * the value fetched from the packet.
17336 	 * Already marked as written above.
17337 	 */
17338 	mark_reg_unknown(env, regs, BPF_REG_0);
17339 	/* ld_abs load up to 32-bit skb data. */
17340 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17341 	return 0;
17342 }
17343 
17344 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17345 {
17346 	const char *exit_ctx = "At program exit";
17347 	struct tnum enforce_attach_type_range = tnum_unknown;
17348 	const struct bpf_prog *prog = env->prog;
17349 	struct bpf_reg_state *reg = reg_state(env, regno);
17350 	struct bpf_retval_range range = retval_range(0, 1);
17351 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17352 	int err;
17353 	struct bpf_func_state *frame = env->cur_state->frame[0];
17354 	const bool is_subprog = frame->subprogno;
17355 	bool return_32bit = false;
17356 	const struct btf_type *reg_type, *ret_type = NULL;
17357 
17358 	/* LSM and struct_ops func-ptr's return type could be "void" */
17359 	if (!is_subprog || frame->in_exception_callback_fn) {
17360 		switch (prog_type) {
17361 		case BPF_PROG_TYPE_LSM:
17362 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17363 				/* See below, can be 0 or 0-1 depending on hook. */
17364 				break;
17365 			if (!prog->aux->attach_func_proto->type)
17366 				return 0;
17367 			break;
17368 		case BPF_PROG_TYPE_STRUCT_OPS:
17369 			if (!prog->aux->attach_func_proto->type)
17370 				return 0;
17371 
17372 			if (frame->in_exception_callback_fn)
17373 				break;
17374 
17375 			/* Allow a struct_ops program to return a referenced kptr if it
17376 			 * matches the operator's return type and is in its unmodified
17377 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17378 			 */
17379 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17380 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17381 							prog->aux->attach_func_proto->type,
17382 							NULL);
17383 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17384 				return __check_ptr_off_reg(env, reg, regno, false);
17385 			break;
17386 		default:
17387 			break;
17388 		}
17389 	}
17390 
17391 	/* eBPF calling convention is such that R0 is used
17392 	 * to return the value from eBPF program.
17393 	 * Make sure that it's readable at this time
17394 	 * of bpf_exit, which means that program wrote
17395 	 * something into it earlier
17396 	 */
17397 	err = check_reg_arg(env, regno, SRC_OP);
17398 	if (err)
17399 		return err;
17400 
17401 	if (is_pointer_value(env, regno)) {
17402 		verbose(env, "R%d leaks addr as return value\n", regno);
17403 		return -EACCES;
17404 	}
17405 
17406 	if (frame->in_async_callback_fn) {
17407 		exit_ctx = "At async callback return";
17408 		range = frame->callback_ret_range;
17409 		goto enforce_retval;
17410 	}
17411 
17412 	if (is_subprog && !frame->in_exception_callback_fn) {
17413 		if (reg->type != SCALAR_VALUE) {
17414 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17415 				regno, reg_type_str(env, reg->type));
17416 			return -EINVAL;
17417 		}
17418 		return 0;
17419 	}
17420 
17421 	switch (prog_type) {
17422 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17423 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17424 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17425 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17426 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17427 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17428 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17429 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17430 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17431 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17432 			range = retval_range(1, 1);
17433 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17434 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17435 			range = retval_range(0, 3);
17436 		break;
17437 	case BPF_PROG_TYPE_CGROUP_SKB:
17438 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17439 			range = retval_range(0, 3);
17440 			enforce_attach_type_range = tnum_range(2, 3);
17441 		}
17442 		break;
17443 	case BPF_PROG_TYPE_CGROUP_SOCK:
17444 	case BPF_PROG_TYPE_SOCK_OPS:
17445 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17446 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17447 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17448 		break;
17449 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17450 		if (!env->prog->aux->attach_btf_id)
17451 			return 0;
17452 		range = retval_range(0, 0);
17453 		break;
17454 	case BPF_PROG_TYPE_TRACING:
17455 		switch (env->prog->expected_attach_type) {
17456 		case BPF_TRACE_FENTRY:
17457 		case BPF_TRACE_FEXIT:
17458 			range = retval_range(0, 0);
17459 			break;
17460 		case BPF_TRACE_RAW_TP:
17461 		case BPF_MODIFY_RETURN:
17462 			return 0;
17463 		case BPF_TRACE_ITER:
17464 			break;
17465 		default:
17466 			return -ENOTSUPP;
17467 		}
17468 		break;
17469 	case BPF_PROG_TYPE_KPROBE:
17470 		switch (env->prog->expected_attach_type) {
17471 		case BPF_TRACE_KPROBE_SESSION:
17472 		case BPF_TRACE_UPROBE_SESSION:
17473 			range = retval_range(0, 1);
17474 			break;
17475 		default:
17476 			return 0;
17477 		}
17478 		break;
17479 	case BPF_PROG_TYPE_SK_LOOKUP:
17480 		range = retval_range(SK_DROP, SK_PASS);
17481 		break;
17482 
17483 	case BPF_PROG_TYPE_LSM:
17484 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17485 			/* no range found, any return value is allowed */
17486 			if (!get_func_retval_range(env->prog, &range))
17487 				return 0;
17488 			/* no restricted range, any return value is allowed */
17489 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17490 				return 0;
17491 			return_32bit = true;
17492 		} else if (!env->prog->aux->attach_func_proto->type) {
17493 			/* Make sure programs that attach to void
17494 			 * hooks don't try to modify return value.
17495 			 */
17496 			range = retval_range(1, 1);
17497 		}
17498 		break;
17499 
17500 	case BPF_PROG_TYPE_NETFILTER:
17501 		range = retval_range(NF_DROP, NF_ACCEPT);
17502 		break;
17503 	case BPF_PROG_TYPE_STRUCT_OPS:
17504 		if (!ret_type)
17505 			return 0;
17506 		range = retval_range(0, 0);
17507 		break;
17508 	case BPF_PROG_TYPE_EXT:
17509 		/* freplace program can return anything as its return value
17510 		 * depends on the to-be-replaced kernel func or bpf program.
17511 		 */
17512 	default:
17513 		return 0;
17514 	}
17515 
17516 enforce_retval:
17517 	if (reg->type != SCALAR_VALUE) {
17518 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17519 			exit_ctx, regno, reg_type_str(env, reg->type));
17520 		return -EINVAL;
17521 	}
17522 
17523 	err = mark_chain_precision(env, regno);
17524 	if (err)
17525 		return err;
17526 
17527 	if (!retval_range_within(range, reg, return_32bit)) {
17528 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17529 		if (!is_subprog &&
17530 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17531 		    prog_type == BPF_PROG_TYPE_LSM &&
17532 		    !prog->aux->attach_func_proto->type)
17533 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17534 		return -EINVAL;
17535 	}
17536 
17537 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17538 	    tnum_in(enforce_attach_type_range, reg->var_off))
17539 		env->prog->enforce_expected_attach_type = 1;
17540 	return 0;
17541 }
17542 
17543 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17544 {
17545 	struct bpf_subprog_info *subprog;
17546 
17547 	subprog = bpf_find_containing_subprog(env, off);
17548 	subprog->changes_pkt_data = true;
17549 }
17550 
17551 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17552 {
17553 	struct bpf_subprog_info *subprog;
17554 
17555 	subprog = bpf_find_containing_subprog(env, off);
17556 	subprog->might_sleep = true;
17557 }
17558 
17559 /* 't' is an index of a call-site.
17560  * 'w' is a callee entry point.
17561  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17562  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17563  * callee's change_pkt_data marks would be correct at that moment.
17564  */
17565 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17566 {
17567 	struct bpf_subprog_info *caller, *callee;
17568 
17569 	caller = bpf_find_containing_subprog(env, t);
17570 	callee = bpf_find_containing_subprog(env, w);
17571 	caller->changes_pkt_data |= callee->changes_pkt_data;
17572 	caller->might_sleep |= callee->might_sleep;
17573 }
17574 
17575 /* non-recursive DFS pseudo code
17576  * 1  procedure DFS-iterative(G,v):
17577  * 2      label v as discovered
17578  * 3      let S be a stack
17579  * 4      S.push(v)
17580  * 5      while S is not empty
17581  * 6            t <- S.peek()
17582  * 7            if t is what we're looking for:
17583  * 8                return t
17584  * 9            for all edges e in G.adjacentEdges(t) do
17585  * 10               if edge e is already labelled
17586  * 11                   continue with the next edge
17587  * 12               w <- G.adjacentVertex(t,e)
17588  * 13               if vertex w is not discovered and not explored
17589  * 14                   label e as tree-edge
17590  * 15                   label w as discovered
17591  * 16                   S.push(w)
17592  * 17                   continue at 5
17593  * 18               else if vertex w is discovered
17594  * 19                   label e as back-edge
17595  * 20               else
17596  * 21                   // vertex w is explored
17597  * 22                   label e as forward- or cross-edge
17598  * 23           label t as explored
17599  * 24           S.pop()
17600  *
17601  * convention:
17602  * 0x10 - discovered
17603  * 0x11 - discovered and fall-through edge labelled
17604  * 0x12 - discovered and fall-through and branch edges labelled
17605  * 0x20 - explored
17606  */
17607 
17608 enum {
17609 	DISCOVERED = 0x10,
17610 	EXPLORED = 0x20,
17611 	FALLTHROUGH = 1,
17612 	BRANCH = 2,
17613 };
17614 
17615 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17616 {
17617 	env->insn_aux_data[idx].prune_point = true;
17618 }
17619 
17620 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17621 {
17622 	return env->insn_aux_data[insn_idx].prune_point;
17623 }
17624 
17625 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17626 {
17627 	env->insn_aux_data[idx].force_checkpoint = true;
17628 }
17629 
17630 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17631 {
17632 	return env->insn_aux_data[insn_idx].force_checkpoint;
17633 }
17634 
17635 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17636 {
17637 	env->insn_aux_data[idx].calls_callback = true;
17638 }
17639 
17640 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17641 {
17642 	return env->insn_aux_data[insn_idx].calls_callback;
17643 }
17644 
17645 enum {
17646 	DONE_EXPLORING = 0,
17647 	KEEP_EXPLORING = 1,
17648 };
17649 
17650 /* t, w, e - match pseudo-code above:
17651  * t - index of current instruction
17652  * w - next instruction
17653  * e - edge
17654  */
17655 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17656 {
17657 	int *insn_stack = env->cfg.insn_stack;
17658 	int *insn_state = env->cfg.insn_state;
17659 
17660 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17661 		return DONE_EXPLORING;
17662 
17663 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17664 		return DONE_EXPLORING;
17665 
17666 	if (w < 0 || w >= env->prog->len) {
17667 		verbose_linfo(env, t, "%d: ", t);
17668 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17669 		return -EINVAL;
17670 	}
17671 
17672 	if (e == BRANCH) {
17673 		/* mark branch target for state pruning */
17674 		mark_prune_point(env, w);
17675 		mark_jmp_point(env, w);
17676 	}
17677 
17678 	if (insn_state[w] == 0) {
17679 		/* tree-edge */
17680 		insn_state[t] = DISCOVERED | e;
17681 		insn_state[w] = DISCOVERED;
17682 		if (env->cfg.cur_stack >= env->prog->len)
17683 			return -E2BIG;
17684 		insn_stack[env->cfg.cur_stack++] = w;
17685 		return KEEP_EXPLORING;
17686 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17687 		if (env->bpf_capable)
17688 			return DONE_EXPLORING;
17689 		verbose_linfo(env, t, "%d: ", t);
17690 		verbose_linfo(env, w, "%d: ", w);
17691 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17692 		return -EINVAL;
17693 	} else if (insn_state[w] == EXPLORED) {
17694 		/* forward- or cross-edge */
17695 		insn_state[t] = DISCOVERED | e;
17696 	} else {
17697 		verifier_bug(env, "insn state internal bug");
17698 		return -EFAULT;
17699 	}
17700 	return DONE_EXPLORING;
17701 }
17702 
17703 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17704 				struct bpf_verifier_env *env,
17705 				bool visit_callee)
17706 {
17707 	int ret, insn_sz;
17708 	int w;
17709 
17710 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17711 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17712 	if (ret)
17713 		return ret;
17714 
17715 	mark_prune_point(env, t + insn_sz);
17716 	/* when we exit from subprog, we need to record non-linear history */
17717 	mark_jmp_point(env, t + insn_sz);
17718 
17719 	if (visit_callee) {
17720 		w = t + insns[t].imm + 1;
17721 		mark_prune_point(env, t);
17722 		merge_callee_effects(env, t, w);
17723 		ret = push_insn(t, w, BRANCH, env);
17724 	}
17725 	return ret;
17726 }
17727 
17728 /* Bitmask with 1s for all caller saved registers */
17729 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17730 
17731 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17732  * replacement patch is presumed to follow bpf_fastcall contract
17733  * (see mark_fastcall_pattern_for_call() below).
17734  */
17735 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17736 {
17737 	switch (imm) {
17738 #ifdef CONFIG_X86_64
17739 	case BPF_FUNC_get_smp_processor_id:
17740 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17741 #endif
17742 	default:
17743 		return false;
17744 	}
17745 }
17746 
17747 struct call_summary {
17748 	u8 num_params;
17749 	bool is_void;
17750 	bool fastcall;
17751 };
17752 
17753 /* If @call is a kfunc or helper call, fills @cs and returns true,
17754  * otherwise returns false.
17755  */
17756 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17757 			     struct call_summary *cs)
17758 {
17759 	struct bpf_kfunc_call_arg_meta meta;
17760 	const struct bpf_func_proto *fn;
17761 	int i;
17762 
17763 	if (bpf_helper_call(call)) {
17764 
17765 		if (get_helper_proto(env, call->imm, &fn) < 0)
17766 			/* error would be reported later */
17767 			return false;
17768 		cs->fastcall = fn->allow_fastcall &&
17769 			       (verifier_inlines_helper_call(env, call->imm) ||
17770 				bpf_jit_inlines_helper_call(call->imm));
17771 		cs->is_void = fn->ret_type == RET_VOID;
17772 		cs->num_params = 0;
17773 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17774 			if (fn->arg_type[i] == ARG_DONTCARE)
17775 				break;
17776 			cs->num_params++;
17777 		}
17778 		return true;
17779 	}
17780 
17781 	if (bpf_pseudo_kfunc_call(call)) {
17782 		int err;
17783 
17784 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17785 		if (err < 0)
17786 			/* error would be reported later */
17787 			return false;
17788 		cs->num_params = btf_type_vlen(meta.func_proto);
17789 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17790 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17791 		return true;
17792 	}
17793 
17794 	return false;
17795 }
17796 
17797 /* LLVM define a bpf_fastcall function attribute.
17798  * This attribute means that function scratches only some of
17799  * the caller saved registers defined by ABI.
17800  * For BPF the set of such registers could be defined as follows:
17801  * - R0 is scratched only if function is non-void;
17802  * - R1-R5 are scratched only if corresponding parameter type is defined
17803  *   in the function prototype.
17804  *
17805  * The contract between kernel and clang allows to simultaneously use
17806  * such functions and maintain backwards compatibility with old
17807  * kernels that don't understand bpf_fastcall calls:
17808  *
17809  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17810  *   registers are not scratched by the call;
17811  *
17812  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17813  *   spill/fill for every live r0-r5;
17814  *
17815  * - stack offsets used for the spill/fill are allocated as lowest
17816  *   stack offsets in whole function and are not used for any other
17817  *   purposes;
17818  *
17819  * - when kernel loads a program, it looks for such patterns
17820  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17821  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17822  *
17823  * - if so, and if verifier or current JIT inlines the call to the
17824  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17825  *   spill/fill pairs;
17826  *
17827  * - when old kernel loads a program, presence of spill/fill pairs
17828  *   keeps BPF program valid, albeit slightly less efficient.
17829  *
17830  * For example:
17831  *
17832  *   r1 = 1;
17833  *   r2 = 2;
17834  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17835  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17836  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17837  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17838  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17839  *   r0 = r1;                            exit;
17840  *   r0 += r2;
17841  *   exit;
17842  *
17843  * The purpose of mark_fastcall_pattern_for_call is to:
17844  * - look for such patterns;
17845  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17846  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17847  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17848  *   at which bpf_fastcall spill/fill stack slots start;
17849  * - update env->subprog_info[*]->keep_fastcall_stack.
17850  *
17851  * The .fastcall_pattern and .fastcall_stack_off are used by
17852  * check_fastcall_stack_contract() to check if every stack access to
17853  * fastcall spill/fill stack slot originates from spill/fill
17854  * instructions, members of fastcall patterns.
17855  *
17856  * If such condition holds true for a subprogram, fastcall patterns could
17857  * be rewritten by remove_fastcall_spills_fills().
17858  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17859  * (code, presumably, generated by an older clang version).
17860  *
17861  * For example, it is *not* safe to remove spill/fill below:
17862  *
17863  *   r1 = 1;
17864  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17865  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17866  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17867  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17868  *   r0 += r1;                           exit;
17869  *   exit;
17870  */
17871 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17872 					   struct bpf_subprog_info *subprog,
17873 					   int insn_idx, s16 lowest_off)
17874 {
17875 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17876 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17877 	u32 clobbered_regs_mask;
17878 	struct call_summary cs;
17879 	u32 expected_regs_mask;
17880 	s16 off;
17881 	int i;
17882 
17883 	if (!get_call_summary(env, call, &cs))
17884 		return;
17885 
17886 	/* A bitmask specifying which caller saved registers are clobbered
17887 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17888 	 * bpf_fastcall contract:
17889 	 * - includes R0 if function is non-void;
17890 	 * - includes R1-R5 if corresponding parameter has is described
17891 	 *   in the function prototype.
17892 	 */
17893 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17894 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17895 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17896 
17897 	/* match pairs of form:
17898 	 *
17899 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17900 	 * ...
17901 	 * call %[to_be_inlined]
17902 	 * ...
17903 	 * rX = *(u64 *)(r10 - Y)
17904 	 */
17905 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17906 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17907 			break;
17908 		stx = &insns[insn_idx - i];
17909 		ldx = &insns[insn_idx + i];
17910 		/* must be a stack spill/fill pair */
17911 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17912 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17913 		    stx->dst_reg != BPF_REG_10 ||
17914 		    ldx->src_reg != BPF_REG_10)
17915 			break;
17916 		/* must be a spill/fill for the same reg */
17917 		if (stx->src_reg != ldx->dst_reg)
17918 			break;
17919 		/* must be one of the previously unseen registers */
17920 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17921 			break;
17922 		/* must be a spill/fill for the same expected offset,
17923 		 * no need to check offset alignment, BPF_DW stack access
17924 		 * is always 8-byte aligned.
17925 		 */
17926 		if (stx->off != off || ldx->off != off)
17927 			break;
17928 		expected_regs_mask &= ~BIT(stx->src_reg);
17929 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17930 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17931 	}
17932 	if (i == 1)
17933 		return;
17934 
17935 	/* Conditionally set 'fastcall_spills_num' to allow forward
17936 	 * compatibility when more helper functions are marked as
17937 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17938 	 *
17939 	 *   1: *(u64 *)(r10 - 8) = r1
17940 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17941 	 *   3: r1 = *(u64 *)(r10 - 8)
17942 	 *   4: *(u64 *)(r10 - 8) = r1
17943 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17944 	 *   6: r1 = *(u64 *)(r10 - 8)
17945 	 *
17946 	 * There is no need to block bpf_fastcall rewrite for such program.
17947 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17948 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17949 	 * does not remove spill/fill pair {4,6}.
17950 	 */
17951 	if (cs.fastcall)
17952 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17953 	else
17954 		subprog->keep_fastcall_stack = 1;
17955 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17956 }
17957 
17958 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17959 {
17960 	struct bpf_subprog_info *subprog = env->subprog_info;
17961 	struct bpf_insn *insn;
17962 	s16 lowest_off;
17963 	int s, i;
17964 
17965 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17966 		/* find lowest stack spill offset used in this subprog */
17967 		lowest_off = 0;
17968 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17969 			insn = env->prog->insnsi + i;
17970 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17971 			    insn->dst_reg != BPF_REG_10)
17972 				continue;
17973 			lowest_off = min(lowest_off, insn->off);
17974 		}
17975 		/* use this offset to find fastcall patterns */
17976 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17977 			insn = env->prog->insnsi + i;
17978 			if (insn->code != (BPF_JMP | BPF_CALL))
17979 				continue;
17980 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17981 		}
17982 	}
17983 	return 0;
17984 }
17985 
17986 static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
17987 {
17988 	size_t new_size = sizeof(struct bpf_iarray) + n_elem * sizeof(old->items[0]);
17989 	struct bpf_iarray *new;
17990 
17991 	new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
17992 	if (!new) {
17993 		/* this is what callers always want, so simplify the call site */
17994 		kvfree(old);
17995 		return NULL;
17996 	}
17997 
17998 	new->cnt = n_elem;
17999 	return new;
18000 }
18001 
18002 static int copy_insn_array(struct bpf_map *map, u32 start, u32 end, u32 *items)
18003 {
18004 	struct bpf_insn_array_value *value;
18005 	u32 i;
18006 
18007 	for (i = start; i <= end; i++) {
18008 		value = map->ops->map_lookup_elem(map, &i);
18009 		/*
18010 		 * map_lookup_elem of an array map will never return an error,
18011 		 * but not checking it makes some static analysers to worry
18012 		 */
18013 		if (IS_ERR(value))
18014 			return PTR_ERR(value);
18015 		else if (!value)
18016 			return -EINVAL;
18017 		items[i - start] = value->xlated_off;
18018 	}
18019 	return 0;
18020 }
18021 
18022 static int cmp_ptr_to_u32(const void *a, const void *b)
18023 {
18024 	return *(u32 *)a - *(u32 *)b;
18025 }
18026 
18027 static int sort_insn_array_uniq(u32 *items, int cnt)
18028 {
18029 	int unique = 1;
18030 	int i;
18031 
18032 	sort(items, cnt, sizeof(items[0]), cmp_ptr_to_u32, NULL);
18033 
18034 	for (i = 1; i < cnt; i++)
18035 		if (items[i] != items[unique - 1])
18036 			items[unique++] = items[i];
18037 
18038 	return unique;
18039 }
18040 
18041 /*
18042  * sort_unique({map[start], ..., map[end]}) into off
18043  */
18044 static int copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off)
18045 {
18046 	u32 n = end - start + 1;
18047 	int err;
18048 
18049 	err = copy_insn_array(map, start, end, off);
18050 	if (err)
18051 		return err;
18052 
18053 	return sort_insn_array_uniq(off, n);
18054 }
18055 
18056 /*
18057  * Copy all unique offsets from the map
18058  */
18059 static struct bpf_iarray *jt_from_map(struct bpf_map *map)
18060 {
18061 	struct bpf_iarray *jt;
18062 	int err;
18063 	int n;
18064 
18065 	jt = iarray_realloc(NULL, map->max_entries);
18066 	if (!jt)
18067 		return ERR_PTR(-ENOMEM);
18068 
18069 	n = copy_insn_array_uniq(map, 0, map->max_entries - 1, jt->items);
18070 	if (n < 0) {
18071 		err = n;
18072 		goto err_free;
18073 	}
18074 	if (n == 0) {
18075 		err = -EINVAL;
18076 		goto err_free;
18077 	}
18078 	jt->cnt = n;
18079 	return jt;
18080 
18081 err_free:
18082 	kvfree(jt);
18083 	return ERR_PTR(err);
18084 }
18085 
18086 /*
18087  * Find and collect all maps which fit in the subprog. Return the result as one
18088  * combined jump table in jt->items (allocated with kvcalloc)
18089  */
18090 static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
18091 					  int subprog_start, int subprog_end)
18092 {
18093 	struct bpf_iarray *jt = NULL;
18094 	struct bpf_map *map;
18095 	struct bpf_iarray *jt_cur;
18096 	int i;
18097 
18098 	for (i = 0; i < env->insn_array_map_cnt; i++) {
18099 		/*
18100 		 * TODO (when needed): collect only jump tables, not static keys
18101 		 * or maps for indirect calls
18102 		 */
18103 		map = env->insn_array_maps[i];
18104 
18105 		jt_cur = jt_from_map(map);
18106 		if (IS_ERR(jt_cur)) {
18107 			kvfree(jt);
18108 			return jt_cur;
18109 		}
18110 
18111 		/*
18112 		 * This is enough to check one element. The full table is
18113 		 * checked to fit inside the subprog later in create_jt()
18114 		 */
18115 		if (jt_cur->items[0] >= subprog_start && jt_cur->items[0] < subprog_end) {
18116 			u32 old_cnt = jt ? jt->cnt : 0;
18117 			jt = iarray_realloc(jt, old_cnt + jt_cur->cnt);
18118 			if (!jt) {
18119 				kvfree(jt_cur);
18120 				return ERR_PTR(-ENOMEM);
18121 			}
18122 			memcpy(jt->items + old_cnt, jt_cur->items, jt_cur->cnt << 2);
18123 		}
18124 
18125 		kvfree(jt_cur);
18126 	}
18127 
18128 	if (!jt) {
18129 		verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
18130 		return ERR_PTR(-EINVAL);
18131 	}
18132 
18133 	jt->cnt = sort_insn_array_uniq(jt->items, jt->cnt);
18134 	return jt;
18135 }
18136 
18137 static struct bpf_iarray *
18138 create_jt(int t, struct bpf_verifier_env *env)
18139 {
18140 	static struct bpf_subprog_info *subprog;
18141 	int subprog_start, subprog_end;
18142 	struct bpf_iarray *jt;
18143 	int i;
18144 
18145 	subprog = bpf_find_containing_subprog(env, t);
18146 	subprog_start = subprog->start;
18147 	subprog_end = (subprog + 1)->start;
18148 	jt = jt_from_subprog(env, subprog_start, subprog_end);
18149 	if (IS_ERR(jt))
18150 		return jt;
18151 
18152 	/* Check that the every element of the jump table fits within the given subprogram */
18153 	for (i = 0; i < jt->cnt; i++) {
18154 		if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
18155 			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
18156 					t, subprog_start, subprog_end);
18157 			kvfree(jt);
18158 			return ERR_PTR(-EINVAL);
18159 		}
18160 	}
18161 
18162 	return jt;
18163 }
18164 
18165 /* "conditional jump with N edges" */
18166 static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
18167 {
18168 	int *insn_stack = env->cfg.insn_stack;
18169 	int *insn_state = env->cfg.insn_state;
18170 	bool keep_exploring = false;
18171 	struct bpf_iarray *jt;
18172 	int i, w;
18173 
18174 	jt = env->insn_aux_data[t].jt;
18175 	if (!jt) {
18176 		jt = create_jt(t, env);
18177 		if (IS_ERR(jt))
18178 			return PTR_ERR(jt);
18179 
18180 		env->insn_aux_data[t].jt = jt;
18181 	}
18182 
18183 	mark_prune_point(env, t);
18184 	for (i = 0; i < jt->cnt; i++) {
18185 		w = jt->items[i];
18186 		if (w < 0 || w >= env->prog->len) {
18187 			verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
18188 			return -EINVAL;
18189 		}
18190 
18191 		mark_jmp_point(env, w);
18192 
18193 		/* EXPLORED || DISCOVERED */
18194 		if (insn_state[w])
18195 			continue;
18196 
18197 		if (env->cfg.cur_stack >= env->prog->len)
18198 			return -E2BIG;
18199 
18200 		insn_stack[env->cfg.cur_stack++] = w;
18201 		insn_state[w] |= DISCOVERED;
18202 		keep_exploring = true;
18203 	}
18204 
18205 	return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
18206 }
18207 
18208 static int visit_tailcall_insn(struct bpf_verifier_env *env, int t)
18209 {
18210 	static struct bpf_subprog_info *subprog;
18211 	struct bpf_iarray *jt;
18212 
18213 	if (env->insn_aux_data[t].jt)
18214 		return 0;
18215 
18216 	jt = iarray_realloc(NULL, 2);
18217 	if (!jt)
18218 		return -ENOMEM;
18219 
18220 	subprog = bpf_find_containing_subprog(env, t);
18221 	jt->items[0] = t + 1;
18222 	jt->items[1] = subprog->exit_idx;
18223 	env->insn_aux_data[t].jt = jt;
18224 	return 0;
18225 }
18226 
18227 /* Visits the instruction at index t and returns one of the following:
18228  *  < 0 - an error occurred
18229  *  DONE_EXPLORING - the instruction was fully explored
18230  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
18231  */
18232 static int visit_insn(int t, struct bpf_verifier_env *env)
18233 {
18234 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
18235 	int ret, off, insn_sz;
18236 
18237 	if (bpf_pseudo_func(insn))
18238 		return visit_func_call_insn(t, insns, env, true);
18239 
18240 	/* All non-branch instructions have a single fall-through edge. */
18241 	if (BPF_CLASS(insn->code) != BPF_JMP &&
18242 	    BPF_CLASS(insn->code) != BPF_JMP32) {
18243 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
18244 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
18245 	}
18246 
18247 	switch (BPF_OP(insn->code)) {
18248 	case BPF_EXIT:
18249 		return DONE_EXPLORING;
18250 
18251 	case BPF_CALL:
18252 		if (is_async_callback_calling_insn(insn))
18253 			/* Mark this call insn as a prune point to trigger
18254 			 * is_state_visited() check before call itself is
18255 			 * processed by __check_func_call(). Otherwise new
18256 			 * async state will be pushed for further exploration.
18257 			 */
18258 			mark_prune_point(env, t);
18259 		/* For functions that invoke callbacks it is not known how many times
18260 		 * callback would be called. Verifier models callback calling functions
18261 		 * by repeatedly visiting callback bodies and returning to origin call
18262 		 * instruction.
18263 		 * In order to stop such iteration verifier needs to identify when a
18264 		 * state identical some state from a previous iteration is reached.
18265 		 * Check below forces creation of checkpoint before callback calling
18266 		 * instruction to allow search for such identical states.
18267 		 */
18268 		if (is_sync_callback_calling_insn(insn)) {
18269 			mark_calls_callback(env, t);
18270 			mark_force_checkpoint(env, t);
18271 			mark_prune_point(env, t);
18272 			mark_jmp_point(env, t);
18273 		}
18274 		if (bpf_helper_call(insn)) {
18275 			const struct bpf_func_proto *fp;
18276 
18277 			ret = get_helper_proto(env, insn->imm, &fp);
18278 			/* If called in a non-sleepable context program will be
18279 			 * rejected anyway, so we should end up with precise
18280 			 * sleepable marks on subprogs, except for dead code
18281 			 * elimination.
18282 			 */
18283 			if (ret == 0 && fp->might_sleep)
18284 				mark_subprog_might_sleep(env, t);
18285 			if (bpf_helper_changes_pkt_data(insn->imm))
18286 				mark_subprog_changes_pkt_data(env, t);
18287 			if (insn->imm == BPF_FUNC_tail_call)
18288 				visit_tailcall_insn(env, t);
18289 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18290 			struct bpf_kfunc_call_arg_meta meta;
18291 
18292 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
18293 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
18294 				mark_prune_point(env, t);
18295 				/* Checking and saving state checkpoints at iter_next() call
18296 				 * is crucial for fast convergence of open-coded iterator loop
18297 				 * logic, so we need to force it. If we don't do that,
18298 				 * is_state_visited() might skip saving a checkpoint, causing
18299 				 * unnecessarily long sequence of not checkpointed
18300 				 * instructions and jumps, leading to exhaustion of jump
18301 				 * history buffer, and potentially other undesired outcomes.
18302 				 * It is expected that with correct open-coded iterators
18303 				 * convergence will happen quickly, so we don't run a risk of
18304 				 * exhausting memory.
18305 				 */
18306 				mark_force_checkpoint(env, t);
18307 			}
18308 			/* Same as helpers, if called in a non-sleepable context
18309 			 * program will be rejected anyway, so we should end up
18310 			 * with precise sleepable marks on subprogs, except for
18311 			 * dead code elimination.
18312 			 */
18313 			if (ret == 0 && is_kfunc_sleepable(&meta))
18314 				mark_subprog_might_sleep(env, t);
18315 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
18316 				mark_subprog_changes_pkt_data(env, t);
18317 		}
18318 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
18319 
18320 	case BPF_JA:
18321 		if (BPF_SRC(insn->code) == BPF_X)
18322 			return visit_gotox_insn(t, env);
18323 
18324 		if (BPF_CLASS(insn->code) == BPF_JMP)
18325 			off = insn->off;
18326 		else
18327 			off = insn->imm;
18328 
18329 		/* unconditional jump with single edge */
18330 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
18331 		if (ret)
18332 			return ret;
18333 
18334 		mark_prune_point(env, t + off + 1);
18335 		mark_jmp_point(env, t + off + 1);
18336 
18337 		return ret;
18338 
18339 	default:
18340 		/* conditional jump with two edges */
18341 		mark_prune_point(env, t);
18342 		if (is_may_goto_insn(insn))
18343 			mark_force_checkpoint(env, t);
18344 
18345 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
18346 		if (ret)
18347 			return ret;
18348 
18349 		return push_insn(t, t + insn->off + 1, BRANCH, env);
18350 	}
18351 }
18352 
18353 /* non-recursive depth-first-search to detect loops in BPF program
18354  * loop == back-edge in directed graph
18355  */
18356 static int check_cfg(struct bpf_verifier_env *env)
18357 {
18358 	int insn_cnt = env->prog->len;
18359 	int *insn_stack, *insn_state;
18360 	int ex_insn_beg, i, ret = 0;
18361 
18362 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18363 	if (!insn_state)
18364 		return -ENOMEM;
18365 
18366 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18367 	if (!insn_stack) {
18368 		kvfree(insn_state);
18369 		return -ENOMEM;
18370 	}
18371 
18372 	ex_insn_beg = env->exception_callback_subprog
18373 		      ? env->subprog_info[env->exception_callback_subprog].start
18374 		      : 0;
18375 
18376 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
18377 	insn_stack[0] = 0; /* 0 is the first instruction */
18378 	env->cfg.cur_stack = 1;
18379 
18380 walk_cfg:
18381 	while (env->cfg.cur_stack > 0) {
18382 		int t = insn_stack[env->cfg.cur_stack - 1];
18383 
18384 		ret = visit_insn(t, env);
18385 		switch (ret) {
18386 		case DONE_EXPLORING:
18387 			insn_state[t] = EXPLORED;
18388 			env->cfg.cur_stack--;
18389 			break;
18390 		case KEEP_EXPLORING:
18391 			break;
18392 		default:
18393 			if (ret > 0) {
18394 				verifier_bug(env, "visit_insn internal bug");
18395 				ret = -EFAULT;
18396 			}
18397 			goto err_free;
18398 		}
18399 	}
18400 
18401 	if (env->cfg.cur_stack < 0) {
18402 		verifier_bug(env, "pop stack internal bug");
18403 		ret = -EFAULT;
18404 		goto err_free;
18405 	}
18406 
18407 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
18408 		insn_state[ex_insn_beg] = DISCOVERED;
18409 		insn_stack[0] = ex_insn_beg;
18410 		env->cfg.cur_stack = 1;
18411 		goto walk_cfg;
18412 	}
18413 
18414 	for (i = 0; i < insn_cnt; i++) {
18415 		struct bpf_insn *insn = &env->prog->insnsi[i];
18416 
18417 		if (insn_state[i] != EXPLORED) {
18418 			verbose(env, "unreachable insn %d\n", i);
18419 			ret = -EINVAL;
18420 			goto err_free;
18421 		}
18422 		if (bpf_is_ldimm64(insn)) {
18423 			if (insn_state[i + 1] != 0) {
18424 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
18425 				ret = -EINVAL;
18426 				goto err_free;
18427 			}
18428 			i++; /* skip second half of ldimm64 */
18429 		}
18430 	}
18431 	ret = 0; /* cfg looks good */
18432 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
18433 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
18434 
18435 err_free:
18436 	kvfree(insn_state);
18437 	kvfree(insn_stack);
18438 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
18439 	return ret;
18440 }
18441 
18442 /*
18443  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
18444  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
18445  * with indices of 'i' instructions in postorder.
18446  */
18447 static int compute_postorder(struct bpf_verifier_env *env)
18448 {
18449 	u32 cur_postorder, i, top, stack_sz, s;
18450 	int *stack = NULL, *postorder = NULL, *state = NULL;
18451 	struct bpf_iarray *succ;
18452 
18453 	postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18454 	state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18455 	stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18456 	if (!postorder || !state || !stack) {
18457 		kvfree(postorder);
18458 		kvfree(state);
18459 		kvfree(stack);
18460 		return -ENOMEM;
18461 	}
18462 	cur_postorder = 0;
18463 	for (i = 0; i < env->subprog_cnt; i++) {
18464 		env->subprog_info[i].postorder_start = cur_postorder;
18465 		stack[0] = env->subprog_info[i].start;
18466 		stack_sz = 1;
18467 		do {
18468 			top = stack[stack_sz - 1];
18469 			state[top] |= DISCOVERED;
18470 			if (state[top] & EXPLORED) {
18471 				postorder[cur_postorder++] = top;
18472 				stack_sz--;
18473 				continue;
18474 			}
18475 			succ = bpf_insn_successors(env, top);
18476 			for (s = 0; s < succ->cnt; ++s) {
18477 				if (!state[succ->items[s]]) {
18478 					stack[stack_sz++] = succ->items[s];
18479 					state[succ->items[s]] |= DISCOVERED;
18480 				}
18481 			}
18482 			state[top] |= EXPLORED;
18483 		} while (stack_sz);
18484 	}
18485 	env->subprog_info[i].postorder_start = cur_postorder;
18486 	env->cfg.insn_postorder = postorder;
18487 	env->cfg.cur_postorder = cur_postorder;
18488 	kvfree(stack);
18489 	kvfree(state);
18490 	return 0;
18491 }
18492 
18493 static int check_abnormal_return(struct bpf_verifier_env *env)
18494 {
18495 	int i;
18496 
18497 	for (i = 1; i < env->subprog_cnt; i++) {
18498 		if (env->subprog_info[i].has_ld_abs) {
18499 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18500 			return -EINVAL;
18501 		}
18502 		if (env->subprog_info[i].has_tail_call) {
18503 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18504 			return -EINVAL;
18505 		}
18506 	}
18507 	return 0;
18508 }
18509 
18510 /* The minimum supported BTF func info size */
18511 #define MIN_BPF_FUNCINFO_SIZE	8
18512 #define MAX_FUNCINFO_REC_SIZE	252
18513 
18514 static int check_btf_func_early(struct bpf_verifier_env *env,
18515 				const union bpf_attr *attr,
18516 				bpfptr_t uattr)
18517 {
18518 	u32 krec_size = sizeof(struct bpf_func_info);
18519 	const struct btf_type *type, *func_proto;
18520 	u32 i, nfuncs, urec_size, min_size;
18521 	struct bpf_func_info *krecord;
18522 	struct bpf_prog *prog;
18523 	const struct btf *btf;
18524 	u32 prev_offset = 0;
18525 	bpfptr_t urecord;
18526 	int ret = -ENOMEM;
18527 
18528 	nfuncs = attr->func_info_cnt;
18529 	if (!nfuncs) {
18530 		if (check_abnormal_return(env))
18531 			return -EINVAL;
18532 		return 0;
18533 	}
18534 
18535 	urec_size = attr->func_info_rec_size;
18536 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18537 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
18538 	    urec_size % sizeof(u32)) {
18539 		verbose(env, "invalid func info rec size %u\n", urec_size);
18540 		return -EINVAL;
18541 	}
18542 
18543 	prog = env->prog;
18544 	btf = prog->aux->btf;
18545 
18546 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18547 	min_size = min_t(u32, krec_size, urec_size);
18548 
18549 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18550 	if (!krecord)
18551 		return -ENOMEM;
18552 
18553 	for (i = 0; i < nfuncs; i++) {
18554 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18555 		if (ret) {
18556 			if (ret == -E2BIG) {
18557 				verbose(env, "nonzero tailing record in func info");
18558 				/* set the size kernel expects so loader can zero
18559 				 * out the rest of the record.
18560 				 */
18561 				if (copy_to_bpfptr_offset(uattr,
18562 							  offsetof(union bpf_attr, func_info_rec_size),
18563 							  &min_size, sizeof(min_size)))
18564 					ret = -EFAULT;
18565 			}
18566 			goto err_free;
18567 		}
18568 
18569 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18570 			ret = -EFAULT;
18571 			goto err_free;
18572 		}
18573 
18574 		/* check insn_off */
18575 		ret = -EINVAL;
18576 		if (i == 0) {
18577 			if (krecord[i].insn_off) {
18578 				verbose(env,
18579 					"nonzero insn_off %u for the first func info record",
18580 					krecord[i].insn_off);
18581 				goto err_free;
18582 			}
18583 		} else if (krecord[i].insn_off <= prev_offset) {
18584 			verbose(env,
18585 				"same or smaller insn offset (%u) than previous func info record (%u)",
18586 				krecord[i].insn_off, prev_offset);
18587 			goto err_free;
18588 		}
18589 
18590 		/* check type_id */
18591 		type = btf_type_by_id(btf, krecord[i].type_id);
18592 		if (!type || !btf_type_is_func(type)) {
18593 			verbose(env, "invalid type id %d in func info",
18594 				krecord[i].type_id);
18595 			goto err_free;
18596 		}
18597 
18598 		func_proto = btf_type_by_id(btf, type->type);
18599 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18600 			/* btf_func_check() already verified it during BTF load */
18601 			goto err_free;
18602 
18603 		prev_offset = krecord[i].insn_off;
18604 		bpfptr_add(&urecord, urec_size);
18605 	}
18606 
18607 	prog->aux->func_info = krecord;
18608 	prog->aux->func_info_cnt = nfuncs;
18609 	return 0;
18610 
18611 err_free:
18612 	kvfree(krecord);
18613 	return ret;
18614 }
18615 
18616 static int check_btf_func(struct bpf_verifier_env *env,
18617 			  const union bpf_attr *attr,
18618 			  bpfptr_t uattr)
18619 {
18620 	const struct btf_type *type, *func_proto, *ret_type;
18621 	u32 i, nfuncs, urec_size;
18622 	struct bpf_func_info *krecord;
18623 	struct bpf_func_info_aux *info_aux = NULL;
18624 	struct bpf_prog *prog;
18625 	const struct btf *btf;
18626 	bpfptr_t urecord;
18627 	bool scalar_return;
18628 	int ret = -ENOMEM;
18629 
18630 	nfuncs = attr->func_info_cnt;
18631 	if (!nfuncs) {
18632 		if (check_abnormal_return(env))
18633 			return -EINVAL;
18634 		return 0;
18635 	}
18636 	if (nfuncs != env->subprog_cnt) {
18637 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18638 		return -EINVAL;
18639 	}
18640 
18641 	urec_size = attr->func_info_rec_size;
18642 
18643 	prog = env->prog;
18644 	btf = prog->aux->btf;
18645 
18646 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18647 
18648 	krecord = prog->aux->func_info;
18649 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18650 	if (!info_aux)
18651 		return -ENOMEM;
18652 
18653 	for (i = 0; i < nfuncs; i++) {
18654 		/* check insn_off */
18655 		ret = -EINVAL;
18656 
18657 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18658 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18659 			goto err_free;
18660 		}
18661 
18662 		/* Already checked type_id */
18663 		type = btf_type_by_id(btf, krecord[i].type_id);
18664 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18665 		/* Already checked func_proto */
18666 		func_proto = btf_type_by_id(btf, type->type);
18667 
18668 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18669 		scalar_return =
18670 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18671 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18672 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18673 			goto err_free;
18674 		}
18675 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18676 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18677 			goto err_free;
18678 		}
18679 
18680 		bpfptr_add(&urecord, urec_size);
18681 	}
18682 
18683 	prog->aux->func_info_aux = info_aux;
18684 	return 0;
18685 
18686 err_free:
18687 	kfree(info_aux);
18688 	return ret;
18689 }
18690 
18691 static void adjust_btf_func(struct bpf_verifier_env *env)
18692 {
18693 	struct bpf_prog_aux *aux = env->prog->aux;
18694 	int i;
18695 
18696 	if (!aux->func_info)
18697 		return;
18698 
18699 	/* func_info is not available for hidden subprogs */
18700 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18701 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18702 }
18703 
18704 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18705 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18706 
18707 static int check_btf_line(struct bpf_verifier_env *env,
18708 			  const union bpf_attr *attr,
18709 			  bpfptr_t uattr)
18710 {
18711 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18712 	struct bpf_subprog_info *sub;
18713 	struct bpf_line_info *linfo;
18714 	struct bpf_prog *prog;
18715 	const struct btf *btf;
18716 	bpfptr_t ulinfo;
18717 	int err;
18718 
18719 	nr_linfo = attr->line_info_cnt;
18720 	if (!nr_linfo)
18721 		return 0;
18722 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18723 		return -EINVAL;
18724 
18725 	rec_size = attr->line_info_rec_size;
18726 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18727 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18728 	    rec_size & (sizeof(u32) - 1))
18729 		return -EINVAL;
18730 
18731 	/* Need to zero it in case the userspace may
18732 	 * pass in a smaller bpf_line_info object.
18733 	 */
18734 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18735 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18736 	if (!linfo)
18737 		return -ENOMEM;
18738 
18739 	prog = env->prog;
18740 	btf = prog->aux->btf;
18741 
18742 	s = 0;
18743 	sub = env->subprog_info;
18744 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18745 	expected_size = sizeof(struct bpf_line_info);
18746 	ncopy = min_t(u32, expected_size, rec_size);
18747 	for (i = 0; i < nr_linfo; i++) {
18748 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18749 		if (err) {
18750 			if (err == -E2BIG) {
18751 				verbose(env, "nonzero tailing record in line_info");
18752 				if (copy_to_bpfptr_offset(uattr,
18753 							  offsetof(union bpf_attr, line_info_rec_size),
18754 							  &expected_size, sizeof(expected_size)))
18755 					err = -EFAULT;
18756 			}
18757 			goto err_free;
18758 		}
18759 
18760 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18761 			err = -EFAULT;
18762 			goto err_free;
18763 		}
18764 
18765 		/*
18766 		 * Check insn_off to ensure
18767 		 * 1) strictly increasing AND
18768 		 * 2) bounded by prog->len
18769 		 *
18770 		 * The linfo[0].insn_off == 0 check logically falls into
18771 		 * the later "missing bpf_line_info for func..." case
18772 		 * because the first linfo[0].insn_off must be the
18773 		 * first sub also and the first sub must have
18774 		 * subprog_info[0].start == 0.
18775 		 */
18776 		if ((i && linfo[i].insn_off <= prev_offset) ||
18777 		    linfo[i].insn_off >= prog->len) {
18778 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18779 				i, linfo[i].insn_off, prev_offset,
18780 				prog->len);
18781 			err = -EINVAL;
18782 			goto err_free;
18783 		}
18784 
18785 		if (!prog->insnsi[linfo[i].insn_off].code) {
18786 			verbose(env,
18787 				"Invalid insn code at line_info[%u].insn_off\n",
18788 				i);
18789 			err = -EINVAL;
18790 			goto err_free;
18791 		}
18792 
18793 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18794 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18795 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18796 			err = -EINVAL;
18797 			goto err_free;
18798 		}
18799 
18800 		if (s != env->subprog_cnt) {
18801 			if (linfo[i].insn_off == sub[s].start) {
18802 				sub[s].linfo_idx = i;
18803 				s++;
18804 			} else if (sub[s].start < linfo[i].insn_off) {
18805 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18806 				err = -EINVAL;
18807 				goto err_free;
18808 			}
18809 		}
18810 
18811 		prev_offset = linfo[i].insn_off;
18812 		bpfptr_add(&ulinfo, rec_size);
18813 	}
18814 
18815 	if (s != env->subprog_cnt) {
18816 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18817 			env->subprog_cnt - s, s);
18818 		err = -EINVAL;
18819 		goto err_free;
18820 	}
18821 
18822 	prog->aux->linfo = linfo;
18823 	prog->aux->nr_linfo = nr_linfo;
18824 
18825 	return 0;
18826 
18827 err_free:
18828 	kvfree(linfo);
18829 	return err;
18830 }
18831 
18832 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18833 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18834 
18835 static int check_core_relo(struct bpf_verifier_env *env,
18836 			   const union bpf_attr *attr,
18837 			   bpfptr_t uattr)
18838 {
18839 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18840 	struct bpf_core_relo core_relo = {};
18841 	struct bpf_prog *prog = env->prog;
18842 	const struct btf *btf = prog->aux->btf;
18843 	struct bpf_core_ctx ctx = {
18844 		.log = &env->log,
18845 		.btf = btf,
18846 	};
18847 	bpfptr_t u_core_relo;
18848 	int err;
18849 
18850 	nr_core_relo = attr->core_relo_cnt;
18851 	if (!nr_core_relo)
18852 		return 0;
18853 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18854 		return -EINVAL;
18855 
18856 	rec_size = attr->core_relo_rec_size;
18857 	if (rec_size < MIN_CORE_RELO_SIZE ||
18858 	    rec_size > MAX_CORE_RELO_SIZE ||
18859 	    rec_size % sizeof(u32))
18860 		return -EINVAL;
18861 
18862 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18863 	expected_size = sizeof(struct bpf_core_relo);
18864 	ncopy = min_t(u32, expected_size, rec_size);
18865 
18866 	/* Unlike func_info and line_info, copy and apply each CO-RE
18867 	 * relocation record one at a time.
18868 	 */
18869 	for (i = 0; i < nr_core_relo; i++) {
18870 		/* future proofing when sizeof(bpf_core_relo) changes */
18871 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18872 		if (err) {
18873 			if (err == -E2BIG) {
18874 				verbose(env, "nonzero tailing record in core_relo");
18875 				if (copy_to_bpfptr_offset(uattr,
18876 							  offsetof(union bpf_attr, core_relo_rec_size),
18877 							  &expected_size, sizeof(expected_size)))
18878 					err = -EFAULT;
18879 			}
18880 			break;
18881 		}
18882 
18883 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18884 			err = -EFAULT;
18885 			break;
18886 		}
18887 
18888 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18889 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18890 				i, core_relo.insn_off, prog->len);
18891 			err = -EINVAL;
18892 			break;
18893 		}
18894 
18895 		err = bpf_core_apply(&ctx, &core_relo, i,
18896 				     &prog->insnsi[core_relo.insn_off / 8]);
18897 		if (err)
18898 			break;
18899 		bpfptr_add(&u_core_relo, rec_size);
18900 	}
18901 	return err;
18902 }
18903 
18904 static int check_btf_info_early(struct bpf_verifier_env *env,
18905 				const union bpf_attr *attr,
18906 				bpfptr_t uattr)
18907 {
18908 	struct btf *btf;
18909 	int err;
18910 
18911 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18912 		if (check_abnormal_return(env))
18913 			return -EINVAL;
18914 		return 0;
18915 	}
18916 
18917 	btf = btf_get_by_fd(attr->prog_btf_fd);
18918 	if (IS_ERR(btf))
18919 		return PTR_ERR(btf);
18920 	if (btf_is_kernel(btf)) {
18921 		btf_put(btf);
18922 		return -EACCES;
18923 	}
18924 	env->prog->aux->btf = btf;
18925 
18926 	err = check_btf_func_early(env, attr, uattr);
18927 	if (err)
18928 		return err;
18929 	return 0;
18930 }
18931 
18932 static int check_btf_info(struct bpf_verifier_env *env,
18933 			  const union bpf_attr *attr,
18934 			  bpfptr_t uattr)
18935 {
18936 	int err;
18937 
18938 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18939 		if (check_abnormal_return(env))
18940 			return -EINVAL;
18941 		return 0;
18942 	}
18943 
18944 	err = check_btf_func(env, attr, uattr);
18945 	if (err)
18946 		return err;
18947 
18948 	err = check_btf_line(env, attr, uattr);
18949 	if (err)
18950 		return err;
18951 
18952 	err = check_core_relo(env, attr, uattr);
18953 	if (err)
18954 		return err;
18955 
18956 	return 0;
18957 }
18958 
18959 /* check %cur's range satisfies %old's */
18960 static bool range_within(const struct bpf_reg_state *old,
18961 			 const struct bpf_reg_state *cur)
18962 {
18963 	return old->umin_value <= cur->umin_value &&
18964 	       old->umax_value >= cur->umax_value &&
18965 	       old->smin_value <= cur->smin_value &&
18966 	       old->smax_value >= cur->smax_value &&
18967 	       old->u32_min_value <= cur->u32_min_value &&
18968 	       old->u32_max_value >= cur->u32_max_value &&
18969 	       old->s32_min_value <= cur->s32_min_value &&
18970 	       old->s32_max_value >= cur->s32_max_value;
18971 }
18972 
18973 /* If in the old state two registers had the same id, then they need to have
18974  * the same id in the new state as well.  But that id could be different from
18975  * the old state, so we need to track the mapping from old to new ids.
18976  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18977  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18978  * regs with a different old id could still have new id 9, we don't care about
18979  * that.
18980  * So we look through our idmap to see if this old id has been seen before.  If
18981  * so, we require the new id to match; otherwise, we add the id pair to the map.
18982  */
18983 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18984 {
18985 	struct bpf_id_pair *map = idmap->map;
18986 	unsigned int i;
18987 
18988 	/* either both IDs should be set or both should be zero */
18989 	if (!!old_id != !!cur_id)
18990 		return false;
18991 
18992 	if (old_id == 0) /* cur_id == 0 as well */
18993 		return true;
18994 
18995 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18996 		if (!map[i].old) {
18997 			/* Reached an empty slot; haven't seen this id before */
18998 			map[i].old = old_id;
18999 			map[i].cur = cur_id;
19000 			return true;
19001 		}
19002 		if (map[i].old == old_id)
19003 			return map[i].cur == cur_id;
19004 		if (map[i].cur == cur_id)
19005 			return false;
19006 	}
19007 	/* We ran out of idmap slots, which should be impossible */
19008 	WARN_ON_ONCE(1);
19009 	return false;
19010 }
19011 
19012 /* Similar to check_ids(), but allocate a unique temporary ID
19013  * for 'old_id' or 'cur_id' of zero.
19014  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
19015  */
19016 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
19017 {
19018 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
19019 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
19020 
19021 	return check_ids(old_id, cur_id, idmap);
19022 }
19023 
19024 static void clean_func_state(struct bpf_verifier_env *env,
19025 			     struct bpf_func_state *st,
19026 			     u32 ip)
19027 {
19028 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
19029 	int i, j;
19030 
19031 	for (i = 0; i < BPF_REG_FP; i++) {
19032 		/* liveness must not touch this register anymore */
19033 		if (!(live_regs & BIT(i)))
19034 			/* since the register is unused, clear its state
19035 			 * to make further comparison simpler
19036 			 */
19037 			__mark_reg_not_init(env, &st->regs[i]);
19038 	}
19039 
19040 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
19041 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
19042 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
19043 			for (j = 0; j < BPF_REG_SIZE; j++)
19044 				st->stack[i].slot_type[j] = STACK_INVALID;
19045 		}
19046 	}
19047 }
19048 
19049 static void clean_verifier_state(struct bpf_verifier_env *env,
19050 				 struct bpf_verifier_state *st)
19051 {
19052 	int i, ip;
19053 
19054 	bpf_live_stack_query_init(env, st);
19055 	st->cleaned = true;
19056 	for (i = 0; i <= st->curframe; i++) {
19057 		ip = frame_insn_idx(st, i);
19058 		clean_func_state(env, st->frame[i], ip);
19059 	}
19060 }
19061 
19062 /* the parentage chains form a tree.
19063  * the verifier states are added to state lists at given insn and
19064  * pushed into state stack for future exploration.
19065  * when the verifier reaches bpf_exit insn some of the verifier states
19066  * stored in the state lists have their final liveness state already,
19067  * but a lot of states will get revised from liveness point of view when
19068  * the verifier explores other branches.
19069  * Example:
19070  * 1: *(u64)(r10 - 8) = 1
19071  * 2: if r1 == 100 goto pc+1
19072  * 3: *(u64)(r10 - 8) = 2
19073  * 4: r0 = *(u64)(r10 - 8)
19074  * 5: exit
19075  * when the verifier reaches exit insn the stack slot -8 in the state list of
19076  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
19077  * of insn 2 and goes exploring further. After the insn 4 read, liveness
19078  * analysis would propagate read mark for -8 at insn 2.
19079  *
19080  * Since the verifier pushes the branch states as it sees them while exploring
19081  * the program the condition of walking the branch instruction for the second
19082  * time means that all states below this branch were already explored and
19083  * their final liveness marks are already propagated.
19084  * Hence when the verifier completes the search of state list in is_state_visited()
19085  * we can call this clean_live_states() function to clear dead the registers and stack
19086  * slots to simplify state merging.
19087  *
19088  * Important note here that walking the same branch instruction in the callee
19089  * doesn't meant that the states are DONE. The verifier has to compare
19090  * the callsites
19091  */
19092 static void clean_live_states(struct bpf_verifier_env *env, int insn,
19093 			      struct bpf_verifier_state *cur)
19094 {
19095 	struct bpf_verifier_state_list *sl;
19096 	struct list_head *pos, *head;
19097 
19098 	head = explored_state(env, insn);
19099 	list_for_each(pos, head) {
19100 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19101 		if (sl->state.branches)
19102 			continue;
19103 		if (sl->state.insn_idx != insn ||
19104 		    !same_callsites(&sl->state, cur))
19105 			continue;
19106 		if (sl->state.cleaned)
19107 			/* all regs in this state in all frames were already marked */
19108 			continue;
19109 		if (incomplete_read_marks(env, &sl->state))
19110 			continue;
19111 		clean_verifier_state(env, &sl->state);
19112 	}
19113 }
19114 
19115 static bool regs_exact(const struct bpf_reg_state *rold,
19116 		       const struct bpf_reg_state *rcur,
19117 		       struct bpf_idmap *idmap)
19118 {
19119 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19120 	       check_ids(rold->id, rcur->id, idmap) &&
19121 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19122 }
19123 
19124 enum exact_level {
19125 	NOT_EXACT,
19126 	EXACT,
19127 	RANGE_WITHIN
19128 };
19129 
19130 /* Returns true if (rold safe implies rcur safe) */
19131 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
19132 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
19133 		    enum exact_level exact)
19134 {
19135 	if (exact == EXACT)
19136 		return regs_exact(rold, rcur, idmap);
19137 
19138 	if (rold->type == NOT_INIT)
19139 		/* explored state can't have used this */
19140 		return true;
19141 
19142 	/* Enforce that register types have to match exactly, including their
19143 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
19144 	 * rule.
19145 	 *
19146 	 * One can make a point that using a pointer register as unbounded
19147 	 * SCALAR would be technically acceptable, but this could lead to
19148 	 * pointer leaks because scalars are allowed to leak while pointers
19149 	 * are not. We could make this safe in special cases if root is
19150 	 * calling us, but it's probably not worth the hassle.
19151 	 *
19152 	 * Also, register types that are *not* MAYBE_NULL could technically be
19153 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
19154 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
19155 	 * to the same map).
19156 	 * However, if the old MAYBE_NULL register then got NULL checked,
19157 	 * doing so could have affected others with the same id, and we can't
19158 	 * check for that because we lost the id when we converted to
19159 	 * a non-MAYBE_NULL variant.
19160 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
19161 	 * non-MAYBE_NULL registers as well.
19162 	 */
19163 	if (rold->type != rcur->type)
19164 		return false;
19165 
19166 	switch (base_type(rold->type)) {
19167 	case SCALAR_VALUE:
19168 		if (env->explore_alu_limits) {
19169 			/* explore_alu_limits disables tnum_in() and range_within()
19170 			 * logic and requires everything to be strict
19171 			 */
19172 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19173 			       check_scalar_ids(rold->id, rcur->id, idmap);
19174 		}
19175 		if (!rold->precise && exact == NOT_EXACT)
19176 			return true;
19177 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
19178 			return false;
19179 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
19180 			return false;
19181 		/* Why check_ids() for scalar registers?
19182 		 *
19183 		 * Consider the following BPF code:
19184 		 *   1: r6 = ... unbound scalar, ID=a ...
19185 		 *   2: r7 = ... unbound scalar, ID=b ...
19186 		 *   3: if (r6 > r7) goto +1
19187 		 *   4: r6 = r7
19188 		 *   5: if (r6 > X) goto ...
19189 		 *   6: ... memory operation using r7 ...
19190 		 *
19191 		 * First verification path is [1-6]:
19192 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
19193 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
19194 		 *   r7 <= X, because r6 and r7 share same id.
19195 		 * Next verification path is [1-4, 6].
19196 		 *
19197 		 * Instruction (6) would be reached in two states:
19198 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
19199 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
19200 		 *
19201 		 * Use check_ids() to distinguish these states.
19202 		 * ---
19203 		 * Also verify that new value satisfies old value range knowledge.
19204 		 */
19205 		return range_within(rold, rcur) &&
19206 		       tnum_in(rold->var_off, rcur->var_off) &&
19207 		       check_scalar_ids(rold->id, rcur->id, idmap);
19208 	case PTR_TO_MAP_KEY:
19209 	case PTR_TO_MAP_VALUE:
19210 	case PTR_TO_MEM:
19211 	case PTR_TO_BUF:
19212 	case PTR_TO_TP_BUFFER:
19213 		/* If the new min/max/var_off satisfy the old ones and
19214 		 * everything else matches, we are OK.
19215 		 */
19216 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19217 		       range_within(rold, rcur) &&
19218 		       tnum_in(rold->var_off, rcur->var_off) &&
19219 		       check_ids(rold->id, rcur->id, idmap) &&
19220 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19221 	case PTR_TO_PACKET_META:
19222 	case PTR_TO_PACKET:
19223 		/* We must have at least as much range as the old ptr
19224 		 * did, so that any accesses which were safe before are
19225 		 * still safe.  This is true even if old range < old off,
19226 		 * since someone could have accessed through (ptr - k), or
19227 		 * even done ptr -= k in a register, to get a safe access.
19228 		 */
19229 		if (rold->range > rcur->range)
19230 			return false;
19231 		/* If the offsets don't match, we can't trust our alignment;
19232 		 * nor can we be sure that we won't fall out of range.
19233 		 */
19234 		if (rold->off != rcur->off)
19235 			return false;
19236 		/* id relations must be preserved */
19237 		if (!check_ids(rold->id, rcur->id, idmap))
19238 			return false;
19239 		/* new val must satisfy old val knowledge */
19240 		return range_within(rold, rcur) &&
19241 		       tnum_in(rold->var_off, rcur->var_off);
19242 	case PTR_TO_STACK:
19243 		/* two stack pointers are equal only if they're pointing to
19244 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
19245 		 */
19246 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
19247 	case PTR_TO_ARENA:
19248 		return true;
19249 	case PTR_TO_INSN:
19250 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19251 			rold->off == rcur->off && range_within(rold, rcur) &&
19252 			tnum_in(rold->var_off, rcur->var_off);
19253 	default:
19254 		return regs_exact(rold, rcur, idmap);
19255 	}
19256 }
19257 
19258 static struct bpf_reg_state unbound_reg;
19259 
19260 static __init int unbound_reg_init(void)
19261 {
19262 	__mark_reg_unknown_imprecise(&unbound_reg);
19263 	return 0;
19264 }
19265 late_initcall(unbound_reg_init);
19266 
19267 static bool is_stack_all_misc(struct bpf_verifier_env *env,
19268 			      struct bpf_stack_state *stack)
19269 {
19270 	u32 i;
19271 
19272 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
19273 		if ((stack->slot_type[i] == STACK_MISC) ||
19274 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
19275 			continue;
19276 		return false;
19277 	}
19278 
19279 	return true;
19280 }
19281 
19282 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
19283 						  struct bpf_stack_state *stack)
19284 {
19285 	if (is_spilled_scalar_reg64(stack))
19286 		return &stack->spilled_ptr;
19287 
19288 	if (is_stack_all_misc(env, stack))
19289 		return &unbound_reg;
19290 
19291 	return NULL;
19292 }
19293 
19294 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
19295 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
19296 		      enum exact_level exact)
19297 {
19298 	int i, spi;
19299 
19300 	/* walk slots of the explored stack and ignore any additional
19301 	 * slots in the current stack, since explored(safe) state
19302 	 * didn't use them
19303 	 */
19304 	for (i = 0; i < old->allocated_stack; i++) {
19305 		struct bpf_reg_state *old_reg, *cur_reg;
19306 
19307 		spi = i / BPF_REG_SIZE;
19308 
19309 		if (exact == EXACT &&
19310 		    (i >= cur->allocated_stack ||
19311 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19312 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
19313 			return false;
19314 
19315 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
19316 			continue;
19317 
19318 		if (env->allow_uninit_stack &&
19319 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
19320 			continue;
19321 
19322 		/* explored stack has more populated slots than current stack
19323 		 * and these slots were used
19324 		 */
19325 		if (i >= cur->allocated_stack)
19326 			return false;
19327 
19328 		/* 64-bit scalar spill vs all slots MISC and vice versa.
19329 		 * Load from all slots MISC produces unbound scalar.
19330 		 * Construct a fake register for such stack and call
19331 		 * regsafe() to ensure scalar ids are compared.
19332 		 */
19333 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
19334 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
19335 		if (old_reg && cur_reg) {
19336 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
19337 				return false;
19338 			i += BPF_REG_SIZE - 1;
19339 			continue;
19340 		}
19341 
19342 		/* if old state was safe with misc data in the stack
19343 		 * it will be safe with zero-initialized stack.
19344 		 * The opposite is not true
19345 		 */
19346 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
19347 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
19348 			continue;
19349 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19350 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
19351 			/* Ex: old explored (safe) state has STACK_SPILL in
19352 			 * this stack slot, but current has STACK_MISC ->
19353 			 * this verifier states are not equivalent,
19354 			 * return false to continue verification of this path
19355 			 */
19356 			return false;
19357 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
19358 			continue;
19359 		/* Both old and cur are having same slot_type */
19360 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
19361 		case STACK_SPILL:
19362 			/* when explored and current stack slot are both storing
19363 			 * spilled registers, check that stored pointers types
19364 			 * are the same as well.
19365 			 * Ex: explored safe path could have stored
19366 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
19367 			 * but current path has stored:
19368 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
19369 			 * such verifier states are not equivalent.
19370 			 * return false to continue verification of this path
19371 			 */
19372 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
19373 				     &cur->stack[spi].spilled_ptr, idmap, exact))
19374 				return false;
19375 			break;
19376 		case STACK_DYNPTR:
19377 			old_reg = &old->stack[spi].spilled_ptr;
19378 			cur_reg = &cur->stack[spi].spilled_ptr;
19379 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
19380 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
19381 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19382 				return false;
19383 			break;
19384 		case STACK_ITER:
19385 			old_reg = &old->stack[spi].spilled_ptr;
19386 			cur_reg = &cur->stack[spi].spilled_ptr;
19387 			/* iter.depth is not compared between states as it
19388 			 * doesn't matter for correctness and would otherwise
19389 			 * prevent convergence; we maintain it only to prevent
19390 			 * infinite loop check triggering, see
19391 			 * iter_active_depths_differ()
19392 			 */
19393 			if (old_reg->iter.btf != cur_reg->iter.btf ||
19394 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
19395 			    old_reg->iter.state != cur_reg->iter.state ||
19396 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
19397 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19398 				return false;
19399 			break;
19400 		case STACK_IRQ_FLAG:
19401 			old_reg = &old->stack[spi].spilled_ptr;
19402 			cur_reg = &cur->stack[spi].spilled_ptr;
19403 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
19404 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
19405 				return false;
19406 			break;
19407 		case STACK_MISC:
19408 		case STACK_ZERO:
19409 		case STACK_INVALID:
19410 			continue;
19411 		/* Ensure that new unhandled slot types return false by default */
19412 		default:
19413 			return false;
19414 		}
19415 	}
19416 	return true;
19417 }
19418 
19419 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
19420 		    struct bpf_idmap *idmap)
19421 {
19422 	int i;
19423 
19424 	if (old->acquired_refs != cur->acquired_refs)
19425 		return false;
19426 
19427 	if (old->active_locks != cur->active_locks)
19428 		return false;
19429 
19430 	if (old->active_preempt_locks != cur->active_preempt_locks)
19431 		return false;
19432 
19433 	if (old->active_rcu_locks != cur->active_rcu_locks)
19434 		return false;
19435 
19436 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
19437 		return false;
19438 
19439 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
19440 	    old->active_lock_ptr != cur->active_lock_ptr)
19441 		return false;
19442 
19443 	for (i = 0; i < old->acquired_refs; i++) {
19444 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
19445 		    old->refs[i].type != cur->refs[i].type)
19446 			return false;
19447 		switch (old->refs[i].type) {
19448 		case REF_TYPE_PTR:
19449 		case REF_TYPE_IRQ:
19450 			break;
19451 		case REF_TYPE_LOCK:
19452 		case REF_TYPE_RES_LOCK:
19453 		case REF_TYPE_RES_LOCK_IRQ:
19454 			if (old->refs[i].ptr != cur->refs[i].ptr)
19455 				return false;
19456 			break;
19457 		default:
19458 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
19459 			return false;
19460 		}
19461 	}
19462 
19463 	return true;
19464 }
19465 
19466 /* compare two verifier states
19467  *
19468  * all states stored in state_list are known to be valid, since
19469  * verifier reached 'bpf_exit' instruction through them
19470  *
19471  * this function is called when verifier exploring different branches of
19472  * execution popped from the state stack. If it sees an old state that has
19473  * more strict register state and more strict stack state then this execution
19474  * branch doesn't need to be explored further, since verifier already
19475  * concluded that more strict state leads to valid finish.
19476  *
19477  * Therefore two states are equivalent if register state is more conservative
19478  * and explored stack state is more conservative than the current one.
19479  * Example:
19480  *       explored                   current
19481  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19482  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19483  *
19484  * In other words if current stack state (one being explored) has more
19485  * valid slots than old one that already passed validation, it means
19486  * the verifier can stop exploring and conclude that current state is valid too
19487  *
19488  * Similarly with registers. If explored state has register type as invalid
19489  * whereas register type in current state is meaningful, it means that
19490  * the current state will reach 'bpf_exit' instruction safely
19491  */
19492 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19493 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19494 {
19495 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19496 	u16 i;
19497 
19498 	if (old->callback_depth > cur->callback_depth)
19499 		return false;
19500 
19501 	for (i = 0; i < MAX_BPF_REG; i++)
19502 		if (((1 << i) & live_regs) &&
19503 		    !regsafe(env, &old->regs[i], &cur->regs[i],
19504 			     &env->idmap_scratch, exact))
19505 			return false;
19506 
19507 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19508 		return false;
19509 
19510 	return true;
19511 }
19512 
19513 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19514 {
19515 	env->idmap_scratch.tmp_id_gen = env->id_gen;
19516 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19517 }
19518 
19519 static bool states_equal(struct bpf_verifier_env *env,
19520 			 struct bpf_verifier_state *old,
19521 			 struct bpf_verifier_state *cur,
19522 			 enum exact_level exact)
19523 {
19524 	u32 insn_idx;
19525 	int i;
19526 
19527 	if (old->curframe != cur->curframe)
19528 		return false;
19529 
19530 	reset_idmap_scratch(env);
19531 
19532 	/* Verification state from speculative execution simulation
19533 	 * must never prune a non-speculative execution one.
19534 	 */
19535 	if (old->speculative && !cur->speculative)
19536 		return false;
19537 
19538 	if (old->in_sleepable != cur->in_sleepable)
19539 		return false;
19540 
19541 	if (!refsafe(old, cur, &env->idmap_scratch))
19542 		return false;
19543 
19544 	/* for states to be equal callsites have to be the same
19545 	 * and all frame states need to be equivalent
19546 	 */
19547 	for (i = 0; i <= old->curframe; i++) {
19548 		insn_idx = frame_insn_idx(old, i);
19549 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
19550 			return false;
19551 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19552 			return false;
19553 	}
19554 	return true;
19555 }
19556 
19557 /* find precise scalars in the previous equivalent state and
19558  * propagate them into the current state
19559  */
19560 static int propagate_precision(struct bpf_verifier_env *env,
19561 			       const struct bpf_verifier_state *old,
19562 			       struct bpf_verifier_state *cur,
19563 			       bool *changed)
19564 {
19565 	struct bpf_reg_state *state_reg;
19566 	struct bpf_func_state *state;
19567 	int i, err = 0, fr;
19568 	bool first;
19569 
19570 	for (fr = old->curframe; fr >= 0; fr--) {
19571 		state = old->frame[fr];
19572 		state_reg = state->regs;
19573 		first = true;
19574 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19575 			if (state_reg->type != SCALAR_VALUE ||
19576 			    !state_reg->precise)
19577 				continue;
19578 			if (env->log.level & BPF_LOG_LEVEL2) {
19579 				if (first)
19580 					verbose(env, "frame %d: propagating r%d", fr, i);
19581 				else
19582 					verbose(env, ",r%d", i);
19583 			}
19584 			bt_set_frame_reg(&env->bt, fr, i);
19585 			first = false;
19586 		}
19587 
19588 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19589 			if (!is_spilled_reg(&state->stack[i]))
19590 				continue;
19591 			state_reg = &state->stack[i].spilled_ptr;
19592 			if (state_reg->type != SCALAR_VALUE ||
19593 			    !state_reg->precise)
19594 				continue;
19595 			if (env->log.level & BPF_LOG_LEVEL2) {
19596 				if (first)
19597 					verbose(env, "frame %d: propagating fp%d",
19598 						fr, (-i - 1) * BPF_REG_SIZE);
19599 				else
19600 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19601 			}
19602 			bt_set_frame_slot(&env->bt, fr, i);
19603 			first = false;
19604 		}
19605 		if (!first && (env->log.level & BPF_LOG_LEVEL2))
19606 			verbose(env, "\n");
19607 	}
19608 
19609 	err = __mark_chain_precision(env, cur, -1, changed);
19610 	if (err < 0)
19611 		return err;
19612 
19613 	return 0;
19614 }
19615 
19616 #define MAX_BACKEDGE_ITERS 64
19617 
19618 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19619  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19620  * then free visit->backedges.
19621  * After execution of this function incomplete_read_marks() will return false
19622  * for all states corresponding to @visit->callchain.
19623  */
19624 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19625 {
19626 	struct bpf_scc_backedge *backedge;
19627 	struct bpf_verifier_state *st;
19628 	bool changed;
19629 	int i, err;
19630 
19631 	i = 0;
19632 	do {
19633 		if (i++ > MAX_BACKEDGE_ITERS) {
19634 			if (env->log.level & BPF_LOG_LEVEL2)
19635 				verbose(env, "%s: too many iterations\n", __func__);
19636 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19637 				mark_all_scalars_precise(env, &backedge->state);
19638 			break;
19639 		}
19640 		changed = false;
19641 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19642 			st = &backedge->state;
19643 			err = propagate_precision(env, st->equal_state, st, &changed);
19644 			if (err)
19645 				return err;
19646 		}
19647 	} while (changed);
19648 
19649 	free_backedges(visit);
19650 	return 0;
19651 }
19652 
19653 static bool states_maybe_looping(struct bpf_verifier_state *old,
19654 				 struct bpf_verifier_state *cur)
19655 {
19656 	struct bpf_func_state *fold, *fcur;
19657 	int i, fr = cur->curframe;
19658 
19659 	if (old->curframe != fr)
19660 		return false;
19661 
19662 	fold = old->frame[fr];
19663 	fcur = cur->frame[fr];
19664 	for (i = 0; i < MAX_BPF_REG; i++)
19665 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19666 			   offsetof(struct bpf_reg_state, frameno)))
19667 			return false;
19668 	return true;
19669 }
19670 
19671 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19672 {
19673 	return env->insn_aux_data[insn_idx].is_iter_next;
19674 }
19675 
19676 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19677  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19678  * states to match, which otherwise would look like an infinite loop. So while
19679  * iter_next() calls are taken care of, we still need to be careful and
19680  * prevent erroneous and too eager declaration of "infinite loop", when
19681  * iterators are involved.
19682  *
19683  * Here's a situation in pseudo-BPF assembly form:
19684  *
19685  *   0: again:                          ; set up iter_next() call args
19686  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19687  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19688  *   3:   if r0 == 0 goto done
19689  *   4:   ... something useful here ...
19690  *   5:   goto again                    ; another iteration
19691  *   6: done:
19692  *   7:   r1 = &it
19693  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19694  *   9:   exit
19695  *
19696  * This is a typical loop. Let's assume that we have a prune point at 1:,
19697  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19698  * again`, assuming other heuristics don't get in a way).
19699  *
19700  * When we first time come to 1:, let's say we have some state X. We proceed
19701  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19702  * Now we come back to validate that forked ACTIVE state. We proceed through
19703  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19704  * are converging. But the problem is that we don't know that yet, as this
19705  * convergence has to happen at iter_next() call site only. So if nothing is
19706  * done, at 1: verifier will use bounded loop logic and declare infinite
19707  * looping (and would be *technically* correct, if not for iterator's
19708  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19709  * don't want that. So what we do in process_iter_next_call() when we go on
19710  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19711  * a different iteration. So when we suspect an infinite loop, we additionally
19712  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19713  * pretend we are not looping and wait for next iter_next() call.
19714  *
19715  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19716  * loop, because that would actually mean infinite loop, as DRAINED state is
19717  * "sticky", and so we'll keep returning into the same instruction with the
19718  * same state (at least in one of possible code paths).
19719  *
19720  * This approach allows to keep infinite loop heuristic even in the face of
19721  * active iterator. E.g., C snippet below is and will be detected as
19722  * infinitely looping:
19723  *
19724  *   struct bpf_iter_num it;
19725  *   int *p, x;
19726  *
19727  *   bpf_iter_num_new(&it, 0, 10);
19728  *   while ((p = bpf_iter_num_next(&t))) {
19729  *       x = p;
19730  *       while (x--) {} // <<-- infinite loop here
19731  *   }
19732  *
19733  */
19734 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19735 {
19736 	struct bpf_reg_state *slot, *cur_slot;
19737 	struct bpf_func_state *state;
19738 	int i, fr;
19739 
19740 	for (fr = old->curframe; fr >= 0; fr--) {
19741 		state = old->frame[fr];
19742 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19743 			if (state->stack[i].slot_type[0] != STACK_ITER)
19744 				continue;
19745 
19746 			slot = &state->stack[i].spilled_ptr;
19747 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19748 				continue;
19749 
19750 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19751 			if (cur_slot->iter.depth != slot->iter.depth)
19752 				return true;
19753 		}
19754 	}
19755 	return false;
19756 }
19757 
19758 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19759 {
19760 	struct bpf_verifier_state_list *new_sl;
19761 	struct bpf_verifier_state_list *sl;
19762 	struct bpf_verifier_state *cur = env->cur_state, *new;
19763 	bool force_new_state, add_new_state, loop;
19764 	int n, err, states_cnt = 0;
19765 	struct list_head *pos, *tmp, *head;
19766 
19767 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19768 			  /* Avoid accumulating infinitely long jmp history */
19769 			  cur->jmp_history_cnt > 40;
19770 
19771 	/* bpf progs typically have pruning point every 4 instructions
19772 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19773 	 * Do not add new state for future pruning if the verifier hasn't seen
19774 	 * at least 2 jumps and at least 8 instructions.
19775 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19776 	 * In tests that amounts to up to 50% reduction into total verifier
19777 	 * memory consumption and 20% verifier time speedup.
19778 	 */
19779 	add_new_state = force_new_state;
19780 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19781 	    env->insn_processed - env->prev_insn_processed >= 8)
19782 		add_new_state = true;
19783 
19784 	clean_live_states(env, insn_idx, cur);
19785 
19786 	loop = false;
19787 	head = explored_state(env, insn_idx);
19788 	list_for_each_safe(pos, tmp, head) {
19789 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19790 		states_cnt++;
19791 		if (sl->state.insn_idx != insn_idx)
19792 			continue;
19793 
19794 		if (sl->state.branches) {
19795 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19796 
19797 			if (frame->in_async_callback_fn &&
19798 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19799 				/* Different async_entry_cnt means that the verifier is
19800 				 * processing another entry into async callback.
19801 				 * Seeing the same state is not an indication of infinite
19802 				 * loop or infinite recursion.
19803 				 * But finding the same state doesn't mean that it's safe
19804 				 * to stop processing the current state. The previous state
19805 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19806 				 * Checking in_async_callback_fn alone is not enough either.
19807 				 * Since the verifier still needs to catch infinite loops
19808 				 * inside async callbacks.
19809 				 */
19810 				goto skip_inf_loop_check;
19811 			}
19812 			/* BPF open-coded iterators loop detection is special.
19813 			 * states_maybe_looping() logic is too simplistic in detecting
19814 			 * states that *might* be equivalent, because it doesn't know
19815 			 * about ID remapping, so don't even perform it.
19816 			 * See process_iter_next_call() and iter_active_depths_differ()
19817 			 * for overview of the logic. When current and one of parent
19818 			 * states are detected as equivalent, it's a good thing: we prove
19819 			 * convergence and can stop simulating further iterations.
19820 			 * It's safe to assume that iterator loop will finish, taking into
19821 			 * account iter_next() contract of eventually returning
19822 			 * sticky NULL result.
19823 			 *
19824 			 * Note, that states have to be compared exactly in this case because
19825 			 * read and precision marks might not be finalized inside the loop.
19826 			 * E.g. as in the program below:
19827 			 *
19828 			 *     1. r7 = -16
19829 			 *     2. r6 = bpf_get_prandom_u32()
19830 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19831 			 *     4.   if (r6 != 42) {
19832 			 *     5.     r7 = -32
19833 			 *     6.     r6 = bpf_get_prandom_u32()
19834 			 *     7.     continue
19835 			 *     8.   }
19836 			 *     9.   r0 = r10
19837 			 *    10.   r0 += r7
19838 			 *    11.   r8 = *(u64 *)(r0 + 0)
19839 			 *    12.   r6 = bpf_get_prandom_u32()
19840 			 *    13. }
19841 			 *
19842 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19843 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19844 			 * not have read or precision mark for r7 yet, thus inexact states
19845 			 * comparison would discard current state with r7=-32
19846 			 * => unsafe memory access at 11 would not be caught.
19847 			 */
19848 			if (is_iter_next_insn(env, insn_idx)) {
19849 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19850 					struct bpf_func_state *cur_frame;
19851 					struct bpf_reg_state *iter_state, *iter_reg;
19852 					int spi;
19853 
19854 					cur_frame = cur->frame[cur->curframe];
19855 					/* btf_check_iter_kfuncs() enforces that
19856 					 * iter state pointer is always the first arg
19857 					 */
19858 					iter_reg = &cur_frame->regs[BPF_REG_1];
19859 					/* current state is valid due to states_equal(),
19860 					 * so we can assume valid iter and reg state,
19861 					 * no need for extra (re-)validations
19862 					 */
19863 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19864 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19865 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19866 						loop = true;
19867 						goto hit;
19868 					}
19869 				}
19870 				goto skip_inf_loop_check;
19871 			}
19872 			if (is_may_goto_insn_at(env, insn_idx)) {
19873 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19874 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19875 					loop = true;
19876 					goto hit;
19877 				}
19878 			}
19879 			if (bpf_calls_callback(env, insn_idx)) {
19880 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19881 					loop = true;
19882 					goto hit;
19883 				}
19884 				goto skip_inf_loop_check;
19885 			}
19886 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19887 			if (states_maybe_looping(&sl->state, cur) &&
19888 			    states_equal(env, &sl->state, cur, EXACT) &&
19889 			    !iter_active_depths_differ(&sl->state, cur) &&
19890 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19891 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19892 				verbose_linfo(env, insn_idx, "; ");
19893 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19894 				verbose(env, "cur state:");
19895 				print_verifier_state(env, cur, cur->curframe, true);
19896 				verbose(env, "old state:");
19897 				print_verifier_state(env, &sl->state, cur->curframe, true);
19898 				return -EINVAL;
19899 			}
19900 			/* if the verifier is processing a loop, avoid adding new state
19901 			 * too often, since different loop iterations have distinct
19902 			 * states and may not help future pruning.
19903 			 * This threshold shouldn't be too low to make sure that
19904 			 * a loop with large bound will be rejected quickly.
19905 			 * The most abusive loop will be:
19906 			 * r1 += 1
19907 			 * if r1 < 1000000 goto pc-2
19908 			 * 1M insn_procssed limit / 100 == 10k peak states.
19909 			 * This threshold shouldn't be too high either, since states
19910 			 * at the end of the loop are likely to be useful in pruning.
19911 			 */
19912 skip_inf_loop_check:
19913 			if (!force_new_state &&
19914 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19915 			    env->insn_processed - env->prev_insn_processed < 100)
19916 				add_new_state = false;
19917 			goto miss;
19918 		}
19919 		/* See comments for mark_all_regs_read_and_precise() */
19920 		loop = incomplete_read_marks(env, &sl->state);
19921 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19922 hit:
19923 			sl->hit_cnt++;
19924 
19925 			/* if previous state reached the exit with precision and
19926 			 * current state is equivalent to it (except precision marks)
19927 			 * the precision needs to be propagated back in
19928 			 * the current state.
19929 			 */
19930 			err = 0;
19931 			if (is_jmp_point(env, env->insn_idx))
19932 				err = push_jmp_history(env, cur, 0, 0);
19933 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19934 			if (err)
19935 				return err;
19936 			/* When processing iterator based loops above propagate_liveness and
19937 			 * propagate_precision calls are not sufficient to transfer all relevant
19938 			 * read and precision marks. E.g. consider the following case:
19939 			 *
19940 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19941 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19942 			 *  |   v   v  At this point, state C is not processed yet, so state A
19943 			 *  '-- B   C  has not received any read or precision marks from C.
19944 			 *             Thus, marks propagated from A to B are incomplete.
19945 			 *
19946 			 * The verifier mitigates this by performing the following steps:
19947 			 *
19948 			 * - Prior to the main verification pass, strongly connected components
19949 			 *   (SCCs) are computed over the program's control flow graph,
19950 			 *   intraprocedurally.
19951 			 *
19952 			 * - During the main verification pass, `maybe_enter_scc()` checks
19953 			 *   whether the current verifier state is entering an SCC. If so, an
19954 			 *   instance of a `bpf_scc_visit` object is created, and the state
19955 			 *   entering the SCC is recorded as the entry state.
19956 			 *
19957 			 * - This instance is associated not with the SCC itself, but with a
19958 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19959 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19960 			 *
19961 			 * - When a verification path encounters a `states_equal(...,
19962 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19963 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19964 			 *   of the current state is created and added to
19965 			 *   `bpf_scc_visit->backedges`.
19966 			 *
19967 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19968 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19969 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19970 			 *   instance. If it is, this indicates that all paths originating from
19971 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19972 			 *   called, which propagates read and precision marks through the
19973 			 *   backedges until a fixed point is reached.
19974 			 *   (In the earlier example, this would propagate marks from A to B,
19975 			 *    from C to A, and then again from A to B.)
19976 			 *
19977 			 * A note on callchains
19978 			 * --------------------
19979 			 *
19980 			 * Consider the following example:
19981 			 *
19982 			 *     void foo() { loop { ... SCC#1 ... } }
19983 			 *     void main() {
19984 			 *       A: foo();
19985 			 *       B: ...
19986 			 *       C: foo();
19987 			 *     }
19988 			 *
19989 			 * Here, there are two distinct callchains leading to SCC#1:
19990 			 * - (A, SCC#1)
19991 			 * - (C, SCC#1)
19992 			 *
19993 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19994 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19995 			 * functions traverse the parent state of each backedge state, which
19996 			 * means these parent states must remain valid (i.e., not freed) while
19997 			 * the corresponding `bpf_scc_visit` instance exists.
19998 			 *
19999 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
20000 			 * callchains would break this invariant:
20001 			 * - States explored during `C: foo()` would contribute backedges to
20002 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
20003 			 *   `A: foo()` completes.
20004 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
20005 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
20006 			 *   links for states from `C: foo()` to become invalid.
20007 			 */
20008 			if (loop) {
20009 				struct bpf_scc_backedge *backedge;
20010 
20011 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
20012 				if (!backedge)
20013 					return -ENOMEM;
20014 				err = copy_verifier_state(&backedge->state, cur);
20015 				backedge->state.equal_state = &sl->state;
20016 				backedge->state.insn_idx = insn_idx;
20017 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
20018 				if (err) {
20019 					free_verifier_state(&backedge->state, false);
20020 					kfree(backedge);
20021 					return err;
20022 				}
20023 			}
20024 			return 1;
20025 		}
20026 miss:
20027 		/* when new state is not going to be added do not increase miss count.
20028 		 * Otherwise several loop iterations will remove the state
20029 		 * recorded earlier. The goal of these heuristics is to have
20030 		 * states from some iterations of the loop (some in the beginning
20031 		 * and some at the end) to help pruning.
20032 		 */
20033 		if (add_new_state)
20034 			sl->miss_cnt++;
20035 		/* heuristic to determine whether this state is beneficial
20036 		 * to keep checking from state equivalence point of view.
20037 		 * Higher numbers increase max_states_per_insn and verification time,
20038 		 * but do not meaningfully decrease insn_processed.
20039 		 * 'n' controls how many times state could miss before eviction.
20040 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
20041 		 * too early would hinder iterator convergence.
20042 		 */
20043 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
20044 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
20045 			/* the state is unlikely to be useful. Remove it to
20046 			 * speed up verification
20047 			 */
20048 			sl->in_free_list = true;
20049 			list_del(&sl->node);
20050 			list_add(&sl->node, &env->free_list);
20051 			env->free_list_size++;
20052 			env->explored_states_size--;
20053 			maybe_free_verifier_state(env, sl);
20054 		}
20055 	}
20056 
20057 	if (env->max_states_per_insn < states_cnt)
20058 		env->max_states_per_insn = states_cnt;
20059 
20060 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
20061 		return 0;
20062 
20063 	if (!add_new_state)
20064 		return 0;
20065 
20066 	/* There were no equivalent states, remember the current one.
20067 	 * Technically the current state is not proven to be safe yet,
20068 	 * but it will either reach outer most bpf_exit (which means it's safe)
20069 	 * or it will be rejected. When there are no loops the verifier won't be
20070 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
20071 	 * again on the way to bpf_exit.
20072 	 * When looping the sl->state.branches will be > 0 and this state
20073 	 * will not be considered for equivalence until branches == 0.
20074 	 */
20075 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
20076 	if (!new_sl)
20077 		return -ENOMEM;
20078 	env->total_states++;
20079 	env->explored_states_size++;
20080 	update_peak_states(env);
20081 	env->prev_jmps_processed = env->jmps_processed;
20082 	env->prev_insn_processed = env->insn_processed;
20083 
20084 	/* forget precise markings we inherited, see __mark_chain_precision */
20085 	if (env->bpf_capable)
20086 		mark_all_scalars_imprecise(env, cur);
20087 
20088 	/* add new state to the head of linked list */
20089 	new = &new_sl->state;
20090 	err = copy_verifier_state(new, cur);
20091 	if (err) {
20092 		free_verifier_state(new, false);
20093 		kfree(new_sl);
20094 		return err;
20095 	}
20096 	new->insn_idx = insn_idx;
20097 	verifier_bug_if(new->branches != 1, env,
20098 			"%s:branches_to_explore=%d insn %d",
20099 			__func__, new->branches, insn_idx);
20100 	err = maybe_enter_scc(env, new);
20101 	if (err) {
20102 		free_verifier_state(new, false);
20103 		kfree(new_sl);
20104 		return err;
20105 	}
20106 
20107 	cur->parent = new;
20108 	cur->first_insn_idx = insn_idx;
20109 	cur->dfs_depth = new->dfs_depth + 1;
20110 	clear_jmp_history(cur);
20111 	list_add(&new_sl->node, head);
20112 	return 0;
20113 }
20114 
20115 /* Return true if it's OK to have the same insn return a different type. */
20116 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20117 {
20118 	switch (base_type(type)) {
20119 	case PTR_TO_CTX:
20120 	case PTR_TO_SOCKET:
20121 	case PTR_TO_SOCK_COMMON:
20122 	case PTR_TO_TCP_SOCK:
20123 	case PTR_TO_XDP_SOCK:
20124 	case PTR_TO_BTF_ID:
20125 	case PTR_TO_ARENA:
20126 		return false;
20127 	default:
20128 		return true;
20129 	}
20130 }
20131 
20132 /* If an instruction was previously used with particular pointer types, then we
20133  * need to be careful to avoid cases such as the below, where it may be ok
20134  * for one branch accessing the pointer, but not ok for the other branch:
20135  *
20136  * R1 = sock_ptr
20137  * goto X;
20138  * ...
20139  * R1 = some_other_valid_ptr;
20140  * goto X;
20141  * ...
20142  * R2 = *(u32 *)(R1 + 0);
20143  */
20144 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20145 {
20146 	return src != prev && (!reg_type_mismatch_ok(src) ||
20147 			       !reg_type_mismatch_ok(prev));
20148 }
20149 
20150 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
20151 {
20152 	switch (base_type(type)) {
20153 	case PTR_TO_MEM:
20154 	case PTR_TO_BTF_ID:
20155 		return true;
20156 	default:
20157 		return false;
20158 	}
20159 }
20160 
20161 static bool is_ptr_to_mem(enum bpf_reg_type type)
20162 {
20163 	return base_type(type) == PTR_TO_MEM;
20164 }
20165 
20166 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20167 			     bool allow_trust_mismatch)
20168 {
20169 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20170 	enum bpf_reg_type merged_type;
20171 
20172 	if (*prev_type == NOT_INIT) {
20173 		/* Saw a valid insn
20174 		 * dst_reg = *(u32 *)(src_reg + off)
20175 		 * save type to validate intersecting paths
20176 		 */
20177 		*prev_type = type;
20178 	} else if (reg_type_mismatch(type, *prev_type)) {
20179 		/* Abuser program is trying to use the same insn
20180 		 * dst_reg = *(u32*) (src_reg + off)
20181 		 * with different pointer types:
20182 		 * src_reg == ctx in one branch and
20183 		 * src_reg == stack|map in some other branch.
20184 		 * Reject it.
20185 		 */
20186 		if (allow_trust_mismatch &&
20187 		    is_ptr_to_mem_or_btf_id(type) &&
20188 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
20189 			/*
20190 			 * Have to support a use case when one path through
20191 			 * the program yields TRUSTED pointer while another
20192 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
20193 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
20194 			 * Same behavior of MEM_RDONLY flag.
20195 			 */
20196 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
20197 				merged_type = PTR_TO_MEM;
20198 			else
20199 				merged_type = PTR_TO_BTF_ID;
20200 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
20201 				merged_type |= PTR_UNTRUSTED;
20202 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
20203 				merged_type |= MEM_RDONLY;
20204 			*prev_type = merged_type;
20205 		} else {
20206 			verbose(env, "same insn cannot be used with different pointers\n");
20207 			return -EINVAL;
20208 		}
20209 	}
20210 
20211 	return 0;
20212 }
20213 
20214 enum {
20215 	PROCESS_BPF_EXIT = 1
20216 };
20217 
20218 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20219 				 bool *do_print_state,
20220 				 bool exception_exit)
20221 {
20222 	/* We must do check_reference_leak here before
20223 	 * prepare_func_exit to handle the case when
20224 	 * state->curframe > 0, it may be a callback function,
20225 	 * for which reference_state must match caller reference
20226 	 * state when it exits.
20227 	 */
20228 	int err = check_resource_leak(env, exception_exit,
20229 				      !env->cur_state->curframe,
20230 				      "BPF_EXIT instruction in main prog");
20231 	if (err)
20232 		return err;
20233 
20234 	/* The side effect of the prepare_func_exit which is
20235 	 * being skipped is that it frees bpf_func_state.
20236 	 * Typically, process_bpf_exit will only be hit with
20237 	 * outermost exit. copy_verifier_state in pop_stack will
20238 	 * handle freeing of any extra bpf_func_state left over
20239 	 * from not processing all nested function exits. We
20240 	 * also skip return code checks as they are not needed
20241 	 * for exceptional exits.
20242 	 */
20243 	if (exception_exit)
20244 		return PROCESS_BPF_EXIT;
20245 
20246 	if (env->cur_state->curframe) {
20247 		/* exit from nested function */
20248 		err = prepare_func_exit(env, &env->insn_idx);
20249 		if (err)
20250 			return err;
20251 		*do_print_state = true;
20252 		return 0;
20253 	}
20254 
20255 	err = check_return_code(env, BPF_REG_0, "R0");
20256 	if (err)
20257 		return err;
20258 	return PROCESS_BPF_EXIT;
20259 }
20260 
20261 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20262 				       int regno,
20263 				       struct bpf_map *map,
20264 				       u32 *pmin_index, u32 *pmax_index)
20265 {
20266 	struct bpf_reg_state *reg = reg_state(env, regno);
20267 	u64 min_index, max_index;
20268 	const u32 size = 8;
20269 
20270 	if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
20271 		(min_index > (u64) U32_MAX * size)) {
20272 		verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
20273 			     regno, reg->umin_value, reg->off);
20274 		return -ERANGE;
20275 	}
20276 	if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
20277 		(max_index > (u64) U32_MAX * size)) {
20278 		verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
20279 			     regno, reg->umax_value, reg->off);
20280 		return -ERANGE;
20281 	}
20282 
20283 	min_index /= size;
20284 	max_index /= size;
20285 
20286 	if (max_index >= map->max_entries) {
20287 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20288 			     regno, min_index, max_index, map->max_entries);
20289 		return -EINVAL;
20290 	}
20291 
20292 	*pmin_index = min_index;
20293 	*pmax_index = max_index;
20294 	return 0;
20295 }
20296 
20297 /* gotox *dst_reg */
20298 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20299 {
20300 	struct bpf_verifier_state *other_branch;
20301 	struct bpf_reg_state *dst_reg;
20302 	struct bpf_map *map;
20303 	u32 min_index, max_index;
20304 	int err = 0;
20305 	int n;
20306 	int i;
20307 
20308 	dst_reg = reg_state(env, insn->dst_reg);
20309 	if (dst_reg->type != PTR_TO_INSN) {
20310 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20311 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
20312 		return -EINVAL;
20313 	}
20314 
20315 	map = dst_reg->map_ptr;
20316 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20317 		return -EFAULT;
20318 
20319 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20320 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20321 		return -EFAULT;
20322 
20323 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20324 	if (err)
20325 		return err;
20326 
20327 	/* Ensure that the buffer is large enough */
20328 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20329 		env->gotox_tmp_buf = iarray_realloc(env->gotox_tmp_buf,
20330 						    max_index - min_index + 1);
20331 		if (!env->gotox_tmp_buf)
20332 			return -ENOMEM;
20333 	}
20334 
20335 	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20336 	if (n < 0)
20337 		return n;
20338 	if (n == 0) {
20339 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20340 			     insn->dst_reg, map->id);
20341 		return -EINVAL;
20342 	}
20343 
20344 	for (i = 0; i < n - 1; i++) {
20345 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20346 					  env->insn_idx, env->cur_state->speculative);
20347 		if (IS_ERR(other_branch))
20348 			return PTR_ERR(other_branch);
20349 	}
20350 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
20351 	return 0;
20352 }
20353 
20354 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20355 {
20356 	int err;
20357 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20358 	u8 class = BPF_CLASS(insn->code);
20359 
20360 	if (class == BPF_ALU || class == BPF_ALU64) {
20361 		err = check_alu_op(env, insn);
20362 		if (err)
20363 			return err;
20364 
20365 	} else if (class == BPF_LDX) {
20366 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
20367 
20368 		/* Check for reserved fields is already done in
20369 		 * resolve_pseudo_ldimm64().
20370 		 */
20371 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
20372 		if (err)
20373 			return err;
20374 	} else if (class == BPF_STX) {
20375 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
20376 			err = check_atomic(env, insn);
20377 			if (err)
20378 				return err;
20379 			env->insn_idx++;
20380 			return 0;
20381 		}
20382 
20383 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
20384 			verbose(env, "BPF_STX uses reserved fields\n");
20385 			return -EINVAL;
20386 		}
20387 
20388 		err = check_store_reg(env, insn, false);
20389 		if (err)
20390 			return err;
20391 	} else if (class == BPF_ST) {
20392 		enum bpf_reg_type dst_reg_type;
20393 
20394 		if (BPF_MODE(insn->code) != BPF_MEM ||
20395 		    insn->src_reg != BPF_REG_0) {
20396 			verbose(env, "BPF_ST uses reserved fields\n");
20397 			return -EINVAL;
20398 		}
20399 		/* check src operand */
20400 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
20401 		if (err)
20402 			return err;
20403 
20404 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
20405 
20406 		/* check that memory (dst_reg + off) is writeable */
20407 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
20408 				       insn->off, BPF_SIZE(insn->code),
20409 				       BPF_WRITE, -1, false, false);
20410 		if (err)
20411 			return err;
20412 
20413 		err = save_aux_ptr_type(env, dst_reg_type, false);
20414 		if (err)
20415 			return err;
20416 	} else if (class == BPF_JMP || class == BPF_JMP32) {
20417 		u8 opcode = BPF_OP(insn->code);
20418 
20419 		env->jmps_processed++;
20420 		if (opcode == BPF_CALL) {
20421 			if (BPF_SRC(insn->code) != BPF_K ||
20422 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
20423 			     insn->off != 0) ||
20424 			    (insn->src_reg != BPF_REG_0 &&
20425 			     insn->src_reg != BPF_PSEUDO_CALL &&
20426 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
20427 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
20428 				verbose(env, "BPF_CALL uses reserved fields\n");
20429 				return -EINVAL;
20430 			}
20431 
20432 			if (env->cur_state->active_locks) {
20433 				if ((insn->src_reg == BPF_REG_0 &&
20434 				     insn->imm != BPF_FUNC_spin_unlock) ||
20435 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
20436 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
20437 					verbose(env,
20438 						"function calls are not allowed while holding a lock\n");
20439 					return -EINVAL;
20440 				}
20441 			}
20442 			if (insn->src_reg == BPF_PSEUDO_CALL) {
20443 				err = check_func_call(env, insn, &env->insn_idx);
20444 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20445 				err = check_kfunc_call(env, insn, &env->insn_idx);
20446 				if (!err && is_bpf_throw_kfunc(insn))
20447 					return process_bpf_exit_full(env, do_print_state, true);
20448 			} else {
20449 				err = check_helper_call(env, insn, &env->insn_idx);
20450 			}
20451 			if (err)
20452 				return err;
20453 
20454 			mark_reg_scratched(env, BPF_REG_0);
20455 		} else if (opcode == BPF_JA) {
20456 			if (BPF_SRC(insn->code) == BPF_X) {
20457 				if (insn->src_reg != BPF_REG_0 ||
20458 				    insn->imm != 0 || insn->off != 0) {
20459 					verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
20460 					return -EINVAL;
20461 				}
20462 				return check_indirect_jump(env, insn);
20463 			}
20464 
20465 			if (BPF_SRC(insn->code) != BPF_K ||
20466 			    insn->src_reg != BPF_REG_0 ||
20467 			    insn->dst_reg != BPF_REG_0 ||
20468 			    (class == BPF_JMP && insn->imm != 0) ||
20469 			    (class == BPF_JMP32 && insn->off != 0)) {
20470 				verbose(env, "BPF_JA uses reserved fields\n");
20471 				return -EINVAL;
20472 			}
20473 
20474 			if (class == BPF_JMP)
20475 				env->insn_idx += insn->off + 1;
20476 			else
20477 				env->insn_idx += insn->imm + 1;
20478 			return 0;
20479 		} else if (opcode == BPF_EXIT) {
20480 			if (BPF_SRC(insn->code) != BPF_K ||
20481 			    insn->imm != 0 ||
20482 			    insn->src_reg != BPF_REG_0 ||
20483 			    insn->dst_reg != BPF_REG_0 ||
20484 			    class == BPF_JMP32) {
20485 				verbose(env, "BPF_EXIT uses reserved fields\n");
20486 				return -EINVAL;
20487 			}
20488 			return process_bpf_exit_full(env, do_print_state, false);
20489 		} else {
20490 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
20491 			if (err)
20492 				return err;
20493 		}
20494 	} else if (class == BPF_LD) {
20495 		u8 mode = BPF_MODE(insn->code);
20496 
20497 		if (mode == BPF_ABS || mode == BPF_IND) {
20498 			err = check_ld_abs(env, insn);
20499 			if (err)
20500 				return err;
20501 
20502 		} else if (mode == BPF_IMM) {
20503 			err = check_ld_imm(env, insn);
20504 			if (err)
20505 				return err;
20506 
20507 			env->insn_idx++;
20508 			sanitize_mark_insn_seen(env);
20509 		} else {
20510 			verbose(env, "invalid BPF_LD mode\n");
20511 			return -EINVAL;
20512 		}
20513 	} else {
20514 		verbose(env, "unknown insn class %d\n", class);
20515 		return -EINVAL;
20516 	}
20517 
20518 	env->insn_idx++;
20519 	return 0;
20520 }
20521 
20522 static int do_check(struct bpf_verifier_env *env)
20523 {
20524 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20525 	struct bpf_verifier_state *state = env->cur_state;
20526 	struct bpf_insn *insns = env->prog->insnsi;
20527 	int insn_cnt = env->prog->len;
20528 	bool do_print_state = false;
20529 	int prev_insn_idx = -1;
20530 
20531 	for (;;) {
20532 		struct bpf_insn *insn;
20533 		struct bpf_insn_aux_data *insn_aux;
20534 		int err, marks_err;
20535 
20536 		/* reset current history entry on each new instruction */
20537 		env->cur_hist_ent = NULL;
20538 
20539 		env->prev_insn_idx = prev_insn_idx;
20540 		if (env->insn_idx >= insn_cnt) {
20541 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20542 				env->insn_idx, insn_cnt);
20543 			return -EFAULT;
20544 		}
20545 
20546 		insn = &insns[env->insn_idx];
20547 		insn_aux = &env->insn_aux_data[env->insn_idx];
20548 
20549 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20550 			verbose(env,
20551 				"BPF program is too large. Processed %d insn\n",
20552 				env->insn_processed);
20553 			return -E2BIG;
20554 		}
20555 
20556 		state->last_insn_idx = env->prev_insn_idx;
20557 		state->insn_idx = env->insn_idx;
20558 
20559 		if (is_prune_point(env, env->insn_idx)) {
20560 			err = is_state_visited(env, env->insn_idx);
20561 			if (err < 0)
20562 				return err;
20563 			if (err == 1) {
20564 				/* found equivalent state, can prune the search */
20565 				if (env->log.level & BPF_LOG_LEVEL) {
20566 					if (do_print_state)
20567 						verbose(env, "\nfrom %d to %d%s: safe\n",
20568 							env->prev_insn_idx, env->insn_idx,
20569 							env->cur_state->speculative ?
20570 							" (speculative execution)" : "");
20571 					else
20572 						verbose(env, "%d: safe\n", env->insn_idx);
20573 				}
20574 				goto process_bpf_exit;
20575 			}
20576 		}
20577 
20578 		if (is_jmp_point(env, env->insn_idx)) {
20579 			err = push_jmp_history(env, state, 0, 0);
20580 			if (err)
20581 				return err;
20582 		}
20583 
20584 		if (signal_pending(current))
20585 			return -EAGAIN;
20586 
20587 		if (need_resched())
20588 			cond_resched();
20589 
20590 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20591 			verbose(env, "\nfrom %d to %d%s:",
20592 				env->prev_insn_idx, env->insn_idx,
20593 				env->cur_state->speculative ?
20594 				" (speculative execution)" : "");
20595 			print_verifier_state(env, state, state->curframe, true);
20596 			do_print_state = false;
20597 		}
20598 
20599 		if (env->log.level & BPF_LOG_LEVEL) {
20600 			if (verifier_state_scratched(env))
20601 				print_insn_state(env, state, state->curframe);
20602 
20603 			verbose_linfo(env, env->insn_idx, "; ");
20604 			env->prev_log_pos = env->log.end_pos;
20605 			verbose(env, "%d: ", env->insn_idx);
20606 			verbose_insn(env, insn);
20607 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20608 			env->prev_log_pos = env->log.end_pos;
20609 		}
20610 
20611 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20612 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20613 							   env->prev_insn_idx);
20614 			if (err)
20615 				return err;
20616 		}
20617 
20618 		sanitize_mark_insn_seen(env);
20619 		prev_insn_idx = env->insn_idx;
20620 
20621 		/* Reduce verification complexity by stopping speculative path
20622 		 * verification when a nospec is encountered.
20623 		 */
20624 		if (state->speculative && insn_aux->nospec)
20625 			goto process_bpf_exit;
20626 
20627 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
20628 		if (err)
20629 			return err;
20630 		err = do_check_insn(env, &do_print_state);
20631 		if (err >= 0 || error_recoverable_with_nospec(err)) {
20632 			marks_err = bpf_commit_stack_write_marks(env);
20633 			if (marks_err)
20634 				return marks_err;
20635 		}
20636 		if (error_recoverable_with_nospec(err) && state->speculative) {
20637 			/* Prevent this speculative path from ever reaching the
20638 			 * insn that would have been unsafe to execute.
20639 			 */
20640 			insn_aux->nospec = true;
20641 			/* If it was an ADD/SUB insn, potentially remove any
20642 			 * markings for alu sanitization.
20643 			 */
20644 			insn_aux->alu_state = 0;
20645 			goto process_bpf_exit;
20646 		} else if (err < 0) {
20647 			return err;
20648 		} else if (err == PROCESS_BPF_EXIT) {
20649 			goto process_bpf_exit;
20650 		}
20651 		WARN_ON_ONCE(err);
20652 
20653 		if (state->speculative && insn_aux->nospec_result) {
20654 			/* If we are on a path that performed a jump-op, this
20655 			 * may skip a nospec patched-in after the jump. This can
20656 			 * currently never happen because nospec_result is only
20657 			 * used for the write-ops
20658 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20659 			 * never skip the following insn. Still, add a warning
20660 			 * to document this in case nospec_result is used
20661 			 * elsewhere in the future.
20662 			 *
20663 			 * All non-branch instructions have a single
20664 			 * fall-through edge. For these, nospec_result should
20665 			 * already work.
20666 			 */
20667 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20668 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20669 					    "speculation barrier after jump instruction may not have the desired effect"))
20670 				return -EFAULT;
20671 process_bpf_exit:
20672 			mark_verifier_state_scratched(env);
20673 			err = update_branch_counts(env, env->cur_state);
20674 			if (err)
20675 				return err;
20676 			err = bpf_update_live_stack(env);
20677 			if (err)
20678 				return err;
20679 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20680 					pop_log);
20681 			if (err < 0) {
20682 				if (err != -ENOENT)
20683 					return err;
20684 				break;
20685 			} else {
20686 				do_print_state = true;
20687 				continue;
20688 			}
20689 		}
20690 	}
20691 
20692 	return 0;
20693 }
20694 
20695 static int find_btf_percpu_datasec(struct btf *btf)
20696 {
20697 	const struct btf_type *t;
20698 	const char *tname;
20699 	int i, n;
20700 
20701 	/*
20702 	 * Both vmlinux and module each have their own ".data..percpu"
20703 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20704 	 * types to look at only module's own BTF types.
20705 	 */
20706 	n = btf_nr_types(btf);
20707 	for (i = btf_named_start_id(btf, true); i < n; i++) {
20708 		t = btf_type_by_id(btf, i);
20709 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20710 			continue;
20711 
20712 		tname = btf_name_by_offset(btf, t->name_off);
20713 		if (!strcmp(tname, ".data..percpu"))
20714 			return i;
20715 	}
20716 
20717 	return -ENOENT;
20718 }
20719 
20720 /*
20721  * Add btf to the used_btfs array and return the index. (If the btf was
20722  * already added, then just return the index.) Upon successful insertion
20723  * increase btf refcnt, and, if present, also refcount the corresponding
20724  * kernel module.
20725  */
20726 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20727 {
20728 	struct btf_mod_pair *btf_mod;
20729 	int i;
20730 
20731 	/* check whether we recorded this BTF (and maybe module) already */
20732 	for (i = 0; i < env->used_btf_cnt; i++)
20733 		if (env->used_btfs[i].btf == btf)
20734 			return i;
20735 
20736 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20737 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20738 			MAX_USED_BTFS);
20739 		return -E2BIG;
20740 	}
20741 
20742 	btf_get(btf);
20743 
20744 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20745 	btf_mod->btf = btf;
20746 	btf_mod->module = NULL;
20747 
20748 	/* if we reference variables from kernel module, bump its refcount */
20749 	if (btf_is_module(btf)) {
20750 		btf_mod->module = btf_try_get_module(btf);
20751 		if (!btf_mod->module) {
20752 			btf_put(btf);
20753 			return -ENXIO;
20754 		}
20755 	}
20756 
20757 	return env->used_btf_cnt++;
20758 }
20759 
20760 /* replace pseudo btf_id with kernel symbol address */
20761 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20762 				 struct bpf_insn *insn,
20763 				 struct bpf_insn_aux_data *aux,
20764 				 struct btf *btf)
20765 {
20766 	const struct btf_var_secinfo *vsi;
20767 	const struct btf_type *datasec;
20768 	const struct btf_type *t;
20769 	const char *sym_name;
20770 	bool percpu = false;
20771 	u32 type, id = insn->imm;
20772 	s32 datasec_id;
20773 	u64 addr;
20774 	int i;
20775 
20776 	t = btf_type_by_id(btf, id);
20777 	if (!t) {
20778 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20779 		return -ENOENT;
20780 	}
20781 
20782 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20783 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20784 		return -EINVAL;
20785 	}
20786 
20787 	sym_name = btf_name_by_offset(btf, t->name_off);
20788 	addr = kallsyms_lookup_name(sym_name);
20789 	if (!addr) {
20790 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20791 			sym_name);
20792 		return -ENOENT;
20793 	}
20794 	insn[0].imm = (u32)addr;
20795 	insn[1].imm = addr >> 32;
20796 
20797 	if (btf_type_is_func(t)) {
20798 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20799 		aux->btf_var.mem_size = 0;
20800 		return 0;
20801 	}
20802 
20803 	datasec_id = find_btf_percpu_datasec(btf);
20804 	if (datasec_id > 0) {
20805 		datasec = btf_type_by_id(btf, datasec_id);
20806 		for_each_vsi(i, datasec, vsi) {
20807 			if (vsi->type == id) {
20808 				percpu = true;
20809 				break;
20810 			}
20811 		}
20812 	}
20813 
20814 	type = t->type;
20815 	t = btf_type_skip_modifiers(btf, type, NULL);
20816 	if (percpu) {
20817 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20818 		aux->btf_var.btf = btf;
20819 		aux->btf_var.btf_id = type;
20820 	} else if (!btf_type_is_struct(t)) {
20821 		const struct btf_type *ret;
20822 		const char *tname;
20823 		u32 tsize;
20824 
20825 		/* resolve the type size of ksym. */
20826 		ret = btf_resolve_size(btf, t, &tsize);
20827 		if (IS_ERR(ret)) {
20828 			tname = btf_name_by_offset(btf, t->name_off);
20829 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20830 				tname, PTR_ERR(ret));
20831 			return -EINVAL;
20832 		}
20833 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20834 		aux->btf_var.mem_size = tsize;
20835 	} else {
20836 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20837 		aux->btf_var.btf = btf;
20838 		aux->btf_var.btf_id = type;
20839 	}
20840 
20841 	return 0;
20842 }
20843 
20844 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20845 			       struct bpf_insn *insn,
20846 			       struct bpf_insn_aux_data *aux)
20847 {
20848 	struct btf *btf;
20849 	int btf_fd;
20850 	int err;
20851 
20852 	btf_fd = insn[1].imm;
20853 	if (btf_fd) {
20854 		CLASS(fd, f)(btf_fd);
20855 
20856 		btf = __btf_get_by_fd(f);
20857 		if (IS_ERR(btf)) {
20858 			verbose(env, "invalid module BTF object FD specified.\n");
20859 			return -EINVAL;
20860 		}
20861 	} else {
20862 		if (!btf_vmlinux) {
20863 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20864 			return -EINVAL;
20865 		}
20866 		btf = btf_vmlinux;
20867 	}
20868 
20869 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20870 	if (err)
20871 		return err;
20872 
20873 	err = __add_used_btf(env, btf);
20874 	if (err < 0)
20875 		return err;
20876 	return 0;
20877 }
20878 
20879 static bool is_tracing_prog_type(enum bpf_prog_type type)
20880 {
20881 	switch (type) {
20882 	case BPF_PROG_TYPE_KPROBE:
20883 	case BPF_PROG_TYPE_TRACEPOINT:
20884 	case BPF_PROG_TYPE_PERF_EVENT:
20885 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20886 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20887 		return true;
20888 	default:
20889 		return false;
20890 	}
20891 }
20892 
20893 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20894 {
20895 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20896 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20897 }
20898 
20899 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20900 					struct bpf_map *map,
20901 					struct bpf_prog *prog)
20902 
20903 {
20904 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20905 
20906 	if (map->excl_prog_sha &&
20907 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20908 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20909 		return -EACCES;
20910 	}
20911 
20912 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20913 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20914 		if (is_tracing_prog_type(prog_type)) {
20915 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20916 			return -EINVAL;
20917 		}
20918 	}
20919 
20920 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20921 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20922 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20923 			return -EINVAL;
20924 		}
20925 
20926 		if (is_tracing_prog_type(prog_type)) {
20927 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20928 			return -EINVAL;
20929 		}
20930 	}
20931 
20932 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20933 		if (is_tracing_prog_type(prog_type)) {
20934 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20935 			return -EINVAL;
20936 		}
20937 	}
20938 
20939 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20940 		if (is_tracing_prog_type(prog_type)) {
20941 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20942 			return -EINVAL;
20943 		}
20944 	}
20945 
20946 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20947 	    !bpf_offload_prog_map_match(prog, map)) {
20948 		verbose(env, "offload device mismatch between prog and map\n");
20949 		return -EINVAL;
20950 	}
20951 
20952 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20953 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20954 		return -EINVAL;
20955 	}
20956 
20957 	if (prog->sleepable)
20958 		switch (map->map_type) {
20959 		case BPF_MAP_TYPE_HASH:
20960 		case BPF_MAP_TYPE_LRU_HASH:
20961 		case BPF_MAP_TYPE_ARRAY:
20962 		case BPF_MAP_TYPE_PERCPU_HASH:
20963 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20964 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20965 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20966 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20967 		case BPF_MAP_TYPE_RINGBUF:
20968 		case BPF_MAP_TYPE_USER_RINGBUF:
20969 		case BPF_MAP_TYPE_INODE_STORAGE:
20970 		case BPF_MAP_TYPE_SK_STORAGE:
20971 		case BPF_MAP_TYPE_TASK_STORAGE:
20972 		case BPF_MAP_TYPE_CGRP_STORAGE:
20973 		case BPF_MAP_TYPE_QUEUE:
20974 		case BPF_MAP_TYPE_STACK:
20975 		case BPF_MAP_TYPE_ARENA:
20976 		case BPF_MAP_TYPE_INSN_ARRAY:
20977 			break;
20978 		default:
20979 			verbose(env,
20980 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20981 			return -EINVAL;
20982 		}
20983 
20984 	if (bpf_map_is_cgroup_storage(map) &&
20985 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20986 		verbose(env, "only one cgroup storage of each type is allowed\n");
20987 		return -EBUSY;
20988 	}
20989 
20990 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20991 		if (env->prog->aux->arena) {
20992 			verbose(env, "Only one arena per program\n");
20993 			return -EBUSY;
20994 		}
20995 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20996 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20997 			return -EPERM;
20998 		}
20999 		if (!env->prog->jit_requested) {
21000 			verbose(env, "JIT is required to use arena\n");
21001 			return -EOPNOTSUPP;
21002 		}
21003 		if (!bpf_jit_supports_arena()) {
21004 			verbose(env, "JIT doesn't support arena\n");
21005 			return -EOPNOTSUPP;
21006 		}
21007 		env->prog->aux->arena = (void *)map;
21008 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
21009 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
21010 			return -EINVAL;
21011 		}
21012 	}
21013 
21014 	return 0;
21015 }
21016 
21017 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
21018 {
21019 	int i, err;
21020 
21021 	/* check whether we recorded this map already */
21022 	for (i = 0; i < env->used_map_cnt; i++)
21023 		if (env->used_maps[i] == map)
21024 			return i;
21025 
21026 	if (env->used_map_cnt >= MAX_USED_MAPS) {
21027 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
21028 			MAX_USED_MAPS);
21029 		return -E2BIG;
21030 	}
21031 
21032 	err = check_map_prog_compatibility(env, map, env->prog);
21033 	if (err)
21034 		return err;
21035 
21036 	if (env->prog->sleepable)
21037 		atomic64_inc(&map->sleepable_refcnt);
21038 
21039 	/* hold the map. If the program is rejected by verifier,
21040 	 * the map will be released by release_maps() or it
21041 	 * will be used by the valid program until it's unloaded
21042 	 * and all maps are released in bpf_free_used_maps()
21043 	 */
21044 	bpf_map_inc(map);
21045 
21046 	env->used_maps[env->used_map_cnt++] = map;
21047 
21048 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
21049 		err = bpf_insn_array_init(map, env->prog);
21050 		if (err) {
21051 			verbose(env, "Failed to properly initialize insn array\n");
21052 			return err;
21053 		}
21054 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
21055 	}
21056 
21057 	return env->used_map_cnt - 1;
21058 }
21059 
21060 /* Add map behind fd to used maps list, if it's not already there, and return
21061  * its index.
21062  * Returns <0 on error, or >= 0 index, on success.
21063  */
21064 static int add_used_map(struct bpf_verifier_env *env, int fd)
21065 {
21066 	struct bpf_map *map;
21067 	CLASS(fd, f)(fd);
21068 
21069 	map = __bpf_map_get(f);
21070 	if (IS_ERR(map)) {
21071 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21072 		return PTR_ERR(map);
21073 	}
21074 
21075 	return __add_used_map(env, map);
21076 }
21077 
21078 /* find and rewrite pseudo imm in ld_imm64 instructions:
21079  *
21080  * 1. if it accesses map FD, replace it with actual map pointer.
21081  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21082  *
21083  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21084  */
21085 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
21086 {
21087 	struct bpf_insn *insn = env->prog->insnsi;
21088 	int insn_cnt = env->prog->len;
21089 	int i, err;
21090 
21091 	err = bpf_prog_calc_tag(env->prog);
21092 	if (err)
21093 		return err;
21094 
21095 	for (i = 0; i < insn_cnt; i++, insn++) {
21096 		if (BPF_CLASS(insn->code) == BPF_LDX &&
21097 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21098 		    insn->imm != 0)) {
21099 			verbose(env, "BPF_LDX uses reserved fields\n");
21100 			return -EINVAL;
21101 		}
21102 
21103 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21104 			struct bpf_insn_aux_data *aux;
21105 			struct bpf_map *map;
21106 			int map_idx;
21107 			u64 addr;
21108 			u32 fd;
21109 
21110 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21111 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21112 			    insn[1].off != 0) {
21113 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21114 				return -EINVAL;
21115 			}
21116 
21117 			if (insn[0].src_reg == 0)
21118 				/* valid generic load 64-bit imm */
21119 				goto next_insn;
21120 
21121 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21122 				aux = &env->insn_aux_data[i];
21123 				err = check_pseudo_btf_id(env, insn, aux);
21124 				if (err)
21125 					return err;
21126 				goto next_insn;
21127 			}
21128 
21129 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21130 				aux = &env->insn_aux_data[i];
21131 				aux->ptr_type = PTR_TO_FUNC;
21132 				goto next_insn;
21133 			}
21134 
21135 			/* In final convert_pseudo_ld_imm64() step, this is
21136 			 * converted into regular 64-bit imm load insn.
21137 			 */
21138 			switch (insn[0].src_reg) {
21139 			case BPF_PSEUDO_MAP_VALUE:
21140 			case BPF_PSEUDO_MAP_IDX_VALUE:
21141 				break;
21142 			case BPF_PSEUDO_MAP_FD:
21143 			case BPF_PSEUDO_MAP_IDX:
21144 				if (insn[1].imm == 0)
21145 					break;
21146 				fallthrough;
21147 			default:
21148 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21149 				return -EINVAL;
21150 			}
21151 
21152 			switch (insn[0].src_reg) {
21153 			case BPF_PSEUDO_MAP_IDX_VALUE:
21154 			case BPF_PSEUDO_MAP_IDX:
21155 				if (bpfptr_is_null(env->fd_array)) {
21156 					verbose(env, "fd_idx without fd_array is invalid\n");
21157 					return -EPROTO;
21158 				}
21159 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
21160 							    insn[0].imm * sizeof(fd),
21161 							    sizeof(fd)))
21162 					return -EFAULT;
21163 				break;
21164 			default:
21165 				fd = insn[0].imm;
21166 				break;
21167 			}
21168 
21169 			map_idx = add_used_map(env, fd);
21170 			if (map_idx < 0)
21171 				return map_idx;
21172 			map = env->used_maps[map_idx];
21173 
21174 			aux = &env->insn_aux_data[i];
21175 			aux->map_index = map_idx;
21176 
21177 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21178 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21179 				addr = (unsigned long)map;
21180 			} else {
21181 				u32 off = insn[1].imm;
21182 
21183 				if (!map->ops->map_direct_value_addr) {
21184 					verbose(env, "no direct value access support for this map type\n");
21185 					return -EINVAL;
21186 				}
21187 
21188 				err = map->ops->map_direct_value_addr(map, &addr, off);
21189 				if (err) {
21190 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21191 						map->value_size, off);
21192 					return err;
21193 				}
21194 
21195 				aux->map_off = off;
21196 				addr += off;
21197 			}
21198 
21199 			insn[0].imm = (u32)addr;
21200 			insn[1].imm = addr >> 32;
21201 
21202 next_insn:
21203 			insn++;
21204 			i++;
21205 			continue;
21206 		}
21207 
21208 		/* Basic sanity check before we invest more work here. */
21209 		if (!bpf_opcode_in_insntable(insn->code)) {
21210 			verbose(env, "unknown opcode %02x\n", insn->code);
21211 			return -EINVAL;
21212 		}
21213 	}
21214 
21215 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21216 	 * 'struct bpf_map *' into a register instead of user map_fd.
21217 	 * These pointers will be used later by verifier to validate map access.
21218 	 */
21219 	return 0;
21220 }
21221 
21222 /* drop refcnt of maps used by the rejected program */
21223 static void release_maps(struct bpf_verifier_env *env)
21224 {
21225 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21226 			     env->used_map_cnt);
21227 }
21228 
21229 /* drop refcnt of maps used by the rejected program */
21230 static void release_btfs(struct bpf_verifier_env *env)
21231 {
21232 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21233 }
21234 
21235 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21236 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21237 {
21238 	struct bpf_insn *insn = env->prog->insnsi;
21239 	int insn_cnt = env->prog->len;
21240 	int i;
21241 
21242 	for (i = 0; i < insn_cnt; i++, insn++) {
21243 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21244 			continue;
21245 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21246 			continue;
21247 		insn->src_reg = 0;
21248 	}
21249 }
21250 
21251 /* single env->prog->insni[off] instruction was replaced with the range
21252  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
21253  * [0, off) and [off, end) to new locations, so the patched range stays zero
21254  */
21255 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
21256 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
21257 {
21258 	struct bpf_insn_aux_data *data = env->insn_aux_data;
21259 	struct bpf_insn *insn = new_prog->insnsi;
21260 	u32 old_seen = data[off].seen;
21261 	u32 prog_len;
21262 	int i;
21263 
21264 	/* aux info at OFF always needs adjustment, no matter fast path
21265 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
21266 	 * original insn at old prog.
21267 	 */
21268 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
21269 
21270 	if (cnt == 1)
21271 		return;
21272 	prog_len = new_prog->len;
21273 
21274 	memmove(data + off + cnt - 1, data + off,
21275 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
21276 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
21277 	for (i = off; i < off + cnt - 1; i++) {
21278 		/* Expand insni[off]'s seen count to the patched range. */
21279 		data[i].seen = old_seen;
21280 		data[i].zext_dst = insn_has_def32(insn + i);
21281 	}
21282 }
21283 
21284 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
21285 {
21286 	int i;
21287 
21288 	if (len == 1)
21289 		return;
21290 	/* NOTE: fake 'exit' subprog should be updated as well. */
21291 	for (i = 0; i <= env->subprog_cnt; i++) {
21292 		if (env->subprog_info[i].start <= off)
21293 			continue;
21294 		env->subprog_info[i].start += len - 1;
21295 	}
21296 }
21297 
21298 static void release_insn_arrays(struct bpf_verifier_env *env)
21299 {
21300 	int i;
21301 
21302 	for (i = 0; i < env->insn_array_map_cnt; i++)
21303 		bpf_insn_array_release(env->insn_array_maps[i]);
21304 }
21305 
21306 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 off, u32 len)
21307 {
21308 	int i;
21309 
21310 	if (len == 1)
21311 		return;
21312 
21313 	for (i = 0; i < env->insn_array_map_cnt; i++)
21314 		bpf_insn_array_adjust(env->insn_array_maps[i], off, len);
21315 }
21316 
21317 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
21318 {
21319 	int i;
21320 
21321 	for (i = 0; i < env->insn_array_map_cnt; i++)
21322 		bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
21323 }
21324 
21325 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
21326 {
21327 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
21328 	int i, sz = prog->aux->size_poke_tab;
21329 	struct bpf_jit_poke_descriptor *desc;
21330 
21331 	for (i = 0; i < sz; i++) {
21332 		desc = &tab[i];
21333 		if (desc->insn_idx <= off)
21334 			continue;
21335 		desc->insn_idx += len - 1;
21336 	}
21337 }
21338 
21339 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
21340 					    const struct bpf_insn *patch, u32 len)
21341 {
21342 	struct bpf_prog *new_prog;
21343 	struct bpf_insn_aux_data *new_data = NULL;
21344 
21345 	if (len > 1) {
21346 		new_data = vrealloc(env->insn_aux_data,
21347 				    array_size(env->prog->len + len - 1,
21348 					       sizeof(struct bpf_insn_aux_data)),
21349 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21350 		if (!new_data)
21351 			return NULL;
21352 
21353 		env->insn_aux_data = new_data;
21354 	}
21355 
21356 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
21357 	if (IS_ERR(new_prog)) {
21358 		if (PTR_ERR(new_prog) == -ERANGE)
21359 			verbose(env,
21360 				"insn %d cannot be patched due to 16-bit range\n",
21361 				env->insn_aux_data[off].orig_idx);
21362 		return NULL;
21363 	}
21364 	adjust_insn_aux_data(env, new_prog, off, len);
21365 	adjust_subprog_starts(env, off, len);
21366 	adjust_insn_arrays(env, off, len);
21367 	adjust_poke_descs(new_prog, off, len);
21368 	return new_prog;
21369 }
21370 
21371 /*
21372  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
21373  * jump offset by 'delta'.
21374  */
21375 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
21376 {
21377 	struct bpf_insn *insn = prog->insnsi;
21378 	u32 insn_cnt = prog->len, i;
21379 	s32 imm;
21380 	s16 off;
21381 
21382 	for (i = 0; i < insn_cnt; i++, insn++) {
21383 		u8 code = insn->code;
21384 
21385 		if (tgt_idx <= i && i < tgt_idx + delta)
21386 			continue;
21387 
21388 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
21389 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
21390 			continue;
21391 
21392 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
21393 			if (i + 1 + insn->imm != tgt_idx)
21394 				continue;
21395 			if (check_add_overflow(insn->imm, delta, &imm))
21396 				return -ERANGE;
21397 			insn->imm = imm;
21398 		} else {
21399 			if (i + 1 + insn->off != tgt_idx)
21400 				continue;
21401 			if (check_add_overflow(insn->off, delta, &off))
21402 				return -ERANGE;
21403 			insn->off = off;
21404 		}
21405 	}
21406 	return 0;
21407 }
21408 
21409 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
21410 					      u32 off, u32 cnt)
21411 {
21412 	int i, j;
21413 
21414 	/* find first prog starting at or after off (first to remove) */
21415 	for (i = 0; i < env->subprog_cnt; i++)
21416 		if (env->subprog_info[i].start >= off)
21417 			break;
21418 	/* find first prog starting at or after off + cnt (first to stay) */
21419 	for (j = i; j < env->subprog_cnt; j++)
21420 		if (env->subprog_info[j].start >= off + cnt)
21421 			break;
21422 	/* if j doesn't start exactly at off + cnt, we are just removing
21423 	 * the front of previous prog
21424 	 */
21425 	if (env->subprog_info[j].start != off + cnt)
21426 		j--;
21427 
21428 	if (j > i) {
21429 		struct bpf_prog_aux *aux = env->prog->aux;
21430 		int move;
21431 
21432 		/* move fake 'exit' subprog as well */
21433 		move = env->subprog_cnt + 1 - j;
21434 
21435 		memmove(env->subprog_info + i,
21436 			env->subprog_info + j,
21437 			sizeof(*env->subprog_info) * move);
21438 		env->subprog_cnt -= j - i;
21439 
21440 		/* remove func_info */
21441 		if (aux->func_info) {
21442 			move = aux->func_info_cnt - j;
21443 
21444 			memmove(aux->func_info + i,
21445 				aux->func_info + j,
21446 				sizeof(*aux->func_info) * move);
21447 			aux->func_info_cnt -= j - i;
21448 			/* func_info->insn_off is set after all code rewrites,
21449 			 * in adjust_btf_func() - no need to adjust
21450 			 */
21451 		}
21452 	} else {
21453 		/* convert i from "first prog to remove" to "first to adjust" */
21454 		if (env->subprog_info[i].start == off)
21455 			i++;
21456 	}
21457 
21458 	/* update fake 'exit' subprog as well */
21459 	for (; i <= env->subprog_cnt; i++)
21460 		env->subprog_info[i].start -= cnt;
21461 
21462 	return 0;
21463 }
21464 
21465 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
21466 				      u32 cnt)
21467 {
21468 	struct bpf_prog *prog = env->prog;
21469 	u32 i, l_off, l_cnt, nr_linfo;
21470 	struct bpf_line_info *linfo;
21471 
21472 	nr_linfo = prog->aux->nr_linfo;
21473 	if (!nr_linfo)
21474 		return 0;
21475 
21476 	linfo = prog->aux->linfo;
21477 
21478 	/* find first line info to remove, count lines to be removed */
21479 	for (i = 0; i < nr_linfo; i++)
21480 		if (linfo[i].insn_off >= off)
21481 			break;
21482 
21483 	l_off = i;
21484 	l_cnt = 0;
21485 	for (; i < nr_linfo; i++)
21486 		if (linfo[i].insn_off < off + cnt)
21487 			l_cnt++;
21488 		else
21489 			break;
21490 
21491 	/* First live insn doesn't match first live linfo, it needs to "inherit"
21492 	 * last removed linfo.  prog is already modified, so prog->len == off
21493 	 * means no live instructions after (tail of the program was removed).
21494 	 */
21495 	if (prog->len != off && l_cnt &&
21496 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
21497 		l_cnt--;
21498 		linfo[--i].insn_off = off + cnt;
21499 	}
21500 
21501 	/* remove the line info which refer to the removed instructions */
21502 	if (l_cnt) {
21503 		memmove(linfo + l_off, linfo + i,
21504 			sizeof(*linfo) * (nr_linfo - i));
21505 
21506 		prog->aux->nr_linfo -= l_cnt;
21507 		nr_linfo = prog->aux->nr_linfo;
21508 	}
21509 
21510 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
21511 	for (i = l_off; i < nr_linfo; i++)
21512 		linfo[i].insn_off -= cnt;
21513 
21514 	/* fix up all subprogs (incl. 'exit') which start >= off */
21515 	for (i = 0; i <= env->subprog_cnt; i++)
21516 		if (env->subprog_info[i].linfo_idx > l_off) {
21517 			/* program may have started in the removed region but
21518 			 * may not be fully removed
21519 			 */
21520 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
21521 				env->subprog_info[i].linfo_idx -= l_cnt;
21522 			else
21523 				env->subprog_info[i].linfo_idx = l_off;
21524 		}
21525 
21526 	return 0;
21527 }
21528 
21529 /*
21530  * Clean up dynamically allocated fields of aux data for instructions [start, ...]
21531  */
21532 static void clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
21533 {
21534 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21535 	struct bpf_insn *insns = env->prog->insnsi;
21536 	int end = start + len;
21537 	int i;
21538 
21539 	for (i = start; i < end; i++) {
21540 		if (aux_data[i].jt) {
21541 			kvfree(aux_data[i].jt);
21542 			aux_data[i].jt = NULL;
21543 		}
21544 
21545 		if (bpf_is_ldimm64(&insns[i]))
21546 			i++;
21547 	}
21548 }
21549 
21550 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
21551 {
21552 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21553 	unsigned int orig_prog_len = env->prog->len;
21554 	int err;
21555 
21556 	if (bpf_prog_is_offloaded(env->prog->aux))
21557 		bpf_prog_offload_remove_insns(env, off, cnt);
21558 
21559 	/* Should be called before bpf_remove_insns, as it uses prog->insnsi */
21560 	clear_insn_aux_data(env, off, cnt);
21561 
21562 	err = bpf_remove_insns(env->prog, off, cnt);
21563 	if (err)
21564 		return err;
21565 
21566 	err = adjust_subprog_starts_after_remove(env, off, cnt);
21567 	if (err)
21568 		return err;
21569 
21570 	err = bpf_adj_linfo_after_remove(env, off, cnt);
21571 	if (err)
21572 		return err;
21573 
21574 	adjust_insn_arrays_after_remove(env, off, cnt);
21575 
21576 	memmove(aux_data + off,	aux_data + off + cnt,
21577 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
21578 
21579 	return 0;
21580 }
21581 
21582 /* The verifier does more data flow analysis than llvm and will not
21583  * explore branches that are dead at run time. Malicious programs can
21584  * have dead code too. Therefore replace all dead at-run-time code
21585  * with 'ja -1'.
21586  *
21587  * Just nops are not optimal, e.g. if they would sit at the end of the
21588  * program and through another bug we would manage to jump there, then
21589  * we'd execute beyond program memory otherwise. Returning exception
21590  * code also wouldn't work since we can have subprogs where the dead
21591  * code could be located.
21592  */
21593 static void sanitize_dead_code(struct bpf_verifier_env *env)
21594 {
21595 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21596 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21597 	struct bpf_insn *insn = env->prog->insnsi;
21598 	const int insn_cnt = env->prog->len;
21599 	int i;
21600 
21601 	for (i = 0; i < insn_cnt; i++) {
21602 		if (aux_data[i].seen)
21603 			continue;
21604 		memcpy(insn + i, &trap, sizeof(trap));
21605 		aux_data[i].zext_dst = false;
21606 	}
21607 }
21608 
21609 static bool insn_is_cond_jump(u8 code)
21610 {
21611 	u8 op;
21612 
21613 	op = BPF_OP(code);
21614 	if (BPF_CLASS(code) == BPF_JMP32)
21615 		return op != BPF_JA;
21616 
21617 	if (BPF_CLASS(code) != BPF_JMP)
21618 		return false;
21619 
21620 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21621 }
21622 
21623 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21624 {
21625 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21626 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21627 	struct bpf_insn *insn = env->prog->insnsi;
21628 	const int insn_cnt = env->prog->len;
21629 	int i;
21630 
21631 	for (i = 0; i < insn_cnt; i++, insn++) {
21632 		if (!insn_is_cond_jump(insn->code))
21633 			continue;
21634 
21635 		if (!aux_data[i + 1].seen)
21636 			ja.off = insn->off;
21637 		else if (!aux_data[i + 1 + insn->off].seen)
21638 			ja.off = 0;
21639 		else
21640 			continue;
21641 
21642 		if (bpf_prog_is_offloaded(env->prog->aux))
21643 			bpf_prog_offload_replace_insn(env, i, &ja);
21644 
21645 		memcpy(insn, &ja, sizeof(ja));
21646 	}
21647 }
21648 
21649 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21650 {
21651 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21652 	int insn_cnt = env->prog->len;
21653 	int i, err;
21654 
21655 	for (i = 0; i < insn_cnt; i++) {
21656 		int j;
21657 
21658 		j = 0;
21659 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21660 			j++;
21661 		if (!j)
21662 			continue;
21663 
21664 		err = verifier_remove_insns(env, i, j);
21665 		if (err)
21666 			return err;
21667 		insn_cnt = env->prog->len;
21668 	}
21669 
21670 	return 0;
21671 }
21672 
21673 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21674 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21675 
21676 static int opt_remove_nops(struct bpf_verifier_env *env)
21677 {
21678 	struct bpf_insn *insn = env->prog->insnsi;
21679 	int insn_cnt = env->prog->len;
21680 	bool is_may_goto_0, is_ja;
21681 	int i, err;
21682 
21683 	for (i = 0; i < insn_cnt; i++) {
21684 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21685 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21686 
21687 		if (!is_may_goto_0 && !is_ja)
21688 			continue;
21689 
21690 		err = verifier_remove_insns(env, i, 1);
21691 		if (err)
21692 			return err;
21693 		insn_cnt--;
21694 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21695 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21696 	}
21697 
21698 	return 0;
21699 }
21700 
21701 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21702 					 const union bpf_attr *attr)
21703 {
21704 	struct bpf_insn *patch;
21705 	/* use env->insn_buf as two independent buffers */
21706 	struct bpf_insn *zext_patch = env->insn_buf;
21707 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21708 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21709 	int i, patch_len, delta = 0, len = env->prog->len;
21710 	struct bpf_insn *insns = env->prog->insnsi;
21711 	struct bpf_prog *new_prog;
21712 	bool rnd_hi32;
21713 
21714 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21715 	zext_patch[1] = BPF_ZEXT_REG(0);
21716 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21717 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21718 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21719 	for (i = 0; i < len; i++) {
21720 		int adj_idx = i + delta;
21721 		struct bpf_insn insn;
21722 		int load_reg;
21723 
21724 		insn = insns[adj_idx];
21725 		load_reg = insn_def_regno(&insn);
21726 		if (!aux[adj_idx].zext_dst) {
21727 			u8 code, class;
21728 			u32 imm_rnd;
21729 
21730 			if (!rnd_hi32)
21731 				continue;
21732 
21733 			code = insn.code;
21734 			class = BPF_CLASS(code);
21735 			if (load_reg == -1)
21736 				continue;
21737 
21738 			/* NOTE: arg "reg" (the fourth one) is only used for
21739 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21740 			 *       here.
21741 			 */
21742 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21743 				if (class == BPF_LD &&
21744 				    BPF_MODE(code) == BPF_IMM)
21745 					i++;
21746 				continue;
21747 			}
21748 
21749 			/* ctx load could be transformed into wider load. */
21750 			if (class == BPF_LDX &&
21751 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21752 				continue;
21753 
21754 			imm_rnd = get_random_u32();
21755 			rnd_hi32_patch[0] = insn;
21756 			rnd_hi32_patch[1].imm = imm_rnd;
21757 			rnd_hi32_patch[3].dst_reg = load_reg;
21758 			patch = rnd_hi32_patch;
21759 			patch_len = 4;
21760 			goto apply_patch_buffer;
21761 		}
21762 
21763 		/* Add in an zero-extend instruction if a) the JIT has requested
21764 		 * it or b) it's a CMPXCHG.
21765 		 *
21766 		 * The latter is because: BPF_CMPXCHG always loads a value into
21767 		 * R0, therefore always zero-extends. However some archs'
21768 		 * equivalent instruction only does this load when the
21769 		 * comparison is successful. This detail of CMPXCHG is
21770 		 * orthogonal to the general zero-extension behaviour of the
21771 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21772 		 */
21773 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21774 			continue;
21775 
21776 		/* Zero-extension is done by the caller. */
21777 		if (bpf_pseudo_kfunc_call(&insn))
21778 			continue;
21779 
21780 		if (verifier_bug_if(load_reg == -1, env,
21781 				    "zext_dst is set, but no reg is defined"))
21782 			return -EFAULT;
21783 
21784 		zext_patch[0] = insn;
21785 		zext_patch[1].dst_reg = load_reg;
21786 		zext_patch[1].src_reg = load_reg;
21787 		patch = zext_patch;
21788 		patch_len = 2;
21789 apply_patch_buffer:
21790 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21791 		if (!new_prog)
21792 			return -ENOMEM;
21793 		env->prog = new_prog;
21794 		insns = new_prog->insnsi;
21795 		aux = env->insn_aux_data;
21796 		delta += patch_len - 1;
21797 	}
21798 
21799 	return 0;
21800 }
21801 
21802 /* convert load instructions that access fields of a context type into a
21803  * sequence of instructions that access fields of the underlying structure:
21804  *     struct __sk_buff    -> struct sk_buff
21805  *     struct bpf_sock_ops -> struct sock
21806  */
21807 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21808 {
21809 	struct bpf_subprog_info *subprogs = env->subprog_info;
21810 	const struct bpf_verifier_ops *ops = env->ops;
21811 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21812 	const int insn_cnt = env->prog->len;
21813 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21814 	struct bpf_insn *insn_buf = env->insn_buf;
21815 	struct bpf_insn *insn;
21816 	u32 target_size, size_default, off;
21817 	struct bpf_prog *new_prog;
21818 	enum bpf_access_type type;
21819 	bool is_narrower_load;
21820 	int epilogue_idx = 0;
21821 
21822 	if (ops->gen_epilogue) {
21823 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21824 						 -(subprogs[0].stack_depth + 8));
21825 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21826 			verifier_bug(env, "epilogue is too long");
21827 			return -EFAULT;
21828 		} else if (epilogue_cnt) {
21829 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21830 			cnt = 0;
21831 			subprogs[0].stack_depth += 8;
21832 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21833 						      -subprogs[0].stack_depth);
21834 			insn_buf[cnt++] = env->prog->insnsi[0];
21835 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21836 			if (!new_prog)
21837 				return -ENOMEM;
21838 			env->prog = new_prog;
21839 			delta += cnt - 1;
21840 
21841 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21842 			if (ret < 0)
21843 				return ret;
21844 		}
21845 	}
21846 
21847 	if (ops->gen_prologue || env->seen_direct_write) {
21848 		if (!ops->gen_prologue) {
21849 			verifier_bug(env, "gen_prologue is null");
21850 			return -EFAULT;
21851 		}
21852 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21853 					env->prog);
21854 		if (cnt >= INSN_BUF_SIZE) {
21855 			verifier_bug(env, "prologue is too long");
21856 			return -EFAULT;
21857 		} else if (cnt) {
21858 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21859 			if (!new_prog)
21860 				return -ENOMEM;
21861 
21862 			env->prog = new_prog;
21863 			delta += cnt - 1;
21864 
21865 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21866 			if (ret < 0)
21867 				return ret;
21868 		}
21869 	}
21870 
21871 	if (delta)
21872 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21873 
21874 	if (bpf_prog_is_offloaded(env->prog->aux))
21875 		return 0;
21876 
21877 	insn = env->prog->insnsi + delta;
21878 
21879 	for (i = 0; i < insn_cnt; i++, insn++) {
21880 		bpf_convert_ctx_access_t convert_ctx_access;
21881 		u8 mode;
21882 
21883 		if (env->insn_aux_data[i + delta].nospec) {
21884 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21885 			struct bpf_insn *patch = insn_buf;
21886 
21887 			*patch++ = BPF_ST_NOSPEC();
21888 			*patch++ = *insn;
21889 			cnt = patch - insn_buf;
21890 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21891 			if (!new_prog)
21892 				return -ENOMEM;
21893 
21894 			delta    += cnt - 1;
21895 			env->prog = new_prog;
21896 			insn      = new_prog->insnsi + i + delta;
21897 			/* This can not be easily merged with the
21898 			 * nospec_result-case, because an insn may require a
21899 			 * nospec before and after itself. Therefore also do not
21900 			 * 'continue' here but potentially apply further
21901 			 * patching to insn. *insn should equal patch[1] now.
21902 			 */
21903 		}
21904 
21905 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21906 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21907 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21908 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21909 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21910 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21911 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21912 			type = BPF_READ;
21913 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21914 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21915 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21916 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21917 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21918 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21919 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21920 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21921 			type = BPF_WRITE;
21922 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21923 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21924 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21925 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21926 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21927 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21928 			env->prog->aux->num_exentries++;
21929 			continue;
21930 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21931 			   epilogue_cnt &&
21932 			   i + delta < subprogs[1].start) {
21933 			/* Generate epilogue for the main prog */
21934 			if (epilogue_idx) {
21935 				/* jump back to the earlier generated epilogue */
21936 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21937 				cnt = 1;
21938 			} else {
21939 				memcpy(insn_buf, epilogue_buf,
21940 				       epilogue_cnt * sizeof(*epilogue_buf));
21941 				cnt = epilogue_cnt;
21942 				/* epilogue_idx cannot be 0. It must have at
21943 				 * least one ctx ptr saving insn before the
21944 				 * epilogue.
21945 				 */
21946 				epilogue_idx = i + delta;
21947 			}
21948 			goto patch_insn_buf;
21949 		} else {
21950 			continue;
21951 		}
21952 
21953 		if (type == BPF_WRITE &&
21954 		    env->insn_aux_data[i + delta].nospec_result) {
21955 			/* nospec_result is only used to mitigate Spectre v4 and
21956 			 * to limit verification-time for Spectre v1.
21957 			 */
21958 			struct bpf_insn *patch = insn_buf;
21959 
21960 			*patch++ = *insn;
21961 			*patch++ = BPF_ST_NOSPEC();
21962 			cnt = patch - insn_buf;
21963 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21964 			if (!new_prog)
21965 				return -ENOMEM;
21966 
21967 			delta    += cnt - 1;
21968 			env->prog = new_prog;
21969 			insn      = new_prog->insnsi + i + delta;
21970 			continue;
21971 		}
21972 
21973 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21974 		case PTR_TO_CTX:
21975 			if (!ops->convert_ctx_access)
21976 				continue;
21977 			convert_ctx_access = ops->convert_ctx_access;
21978 			break;
21979 		case PTR_TO_SOCKET:
21980 		case PTR_TO_SOCK_COMMON:
21981 			convert_ctx_access = bpf_sock_convert_ctx_access;
21982 			break;
21983 		case PTR_TO_TCP_SOCK:
21984 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21985 			break;
21986 		case PTR_TO_XDP_SOCK:
21987 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21988 			break;
21989 		case PTR_TO_BTF_ID:
21990 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21991 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21992 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21993 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21994 		 * any faults for loads into such types. BPF_WRITE is disallowed
21995 		 * for this case.
21996 		 */
21997 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21998 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21999 			if (type == BPF_READ) {
22000 				if (BPF_MODE(insn->code) == BPF_MEM)
22001 					insn->code = BPF_LDX | BPF_PROBE_MEM |
22002 						     BPF_SIZE((insn)->code);
22003 				else
22004 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
22005 						     BPF_SIZE((insn)->code);
22006 				env->prog->aux->num_exentries++;
22007 			}
22008 			continue;
22009 		case PTR_TO_ARENA:
22010 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
22011 				if (!bpf_jit_supports_insn(insn, true)) {
22012 					verbose(env, "sign extending loads from arena are not supported yet\n");
22013 					return -EOPNOTSUPP;
22014 				}
22015 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
22016 			} else {
22017 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
22018 			}
22019 			env->prog->aux->num_exentries++;
22020 			continue;
22021 		default:
22022 			continue;
22023 		}
22024 
22025 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
22026 		size = BPF_LDST_BYTES(insn);
22027 		mode = BPF_MODE(insn->code);
22028 
22029 		/* If the read access is a narrower load of the field,
22030 		 * convert to a 4/8-byte load, to minimum program type specific
22031 		 * convert_ctx_access changes. If conversion is successful,
22032 		 * we will apply proper mask to the result.
22033 		 */
22034 		is_narrower_load = size < ctx_field_size;
22035 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
22036 		off = insn->off;
22037 		if (is_narrower_load) {
22038 			u8 size_code;
22039 
22040 			if (type == BPF_WRITE) {
22041 				verifier_bug(env, "narrow ctx access misconfigured");
22042 				return -EFAULT;
22043 			}
22044 
22045 			size_code = BPF_H;
22046 			if (ctx_field_size == 4)
22047 				size_code = BPF_W;
22048 			else if (ctx_field_size == 8)
22049 				size_code = BPF_DW;
22050 
22051 			insn->off = off & ~(size_default - 1);
22052 			insn->code = BPF_LDX | BPF_MEM | size_code;
22053 		}
22054 
22055 		target_size = 0;
22056 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
22057 					 &target_size);
22058 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
22059 		    (ctx_field_size && !target_size)) {
22060 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
22061 			return -EFAULT;
22062 		}
22063 
22064 		if (is_narrower_load && size < target_size) {
22065 			u8 shift = bpf_ctx_narrow_access_offset(
22066 				off, size, size_default) * 8;
22067 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
22068 				verifier_bug(env, "narrow ctx load misconfigured");
22069 				return -EFAULT;
22070 			}
22071 			if (ctx_field_size <= 4) {
22072 				if (shift)
22073 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
22074 									insn->dst_reg,
22075 									shift);
22076 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22077 								(1 << size * 8) - 1);
22078 			} else {
22079 				if (shift)
22080 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
22081 									insn->dst_reg,
22082 									shift);
22083 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22084 								(1ULL << size * 8) - 1);
22085 			}
22086 		}
22087 		if (mode == BPF_MEMSX)
22088 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
22089 						       insn->dst_reg, insn->dst_reg,
22090 						       size * 8, 0);
22091 
22092 patch_insn_buf:
22093 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22094 		if (!new_prog)
22095 			return -ENOMEM;
22096 
22097 		delta += cnt - 1;
22098 
22099 		/* keep walking new program and skip insns we just inserted */
22100 		env->prog = new_prog;
22101 		insn      = new_prog->insnsi + i + delta;
22102 	}
22103 
22104 	return 0;
22105 }
22106 
22107 static int jit_subprogs(struct bpf_verifier_env *env)
22108 {
22109 	struct bpf_prog *prog = env->prog, **func, *tmp;
22110 	int i, j, subprog_start, subprog_end = 0, len, subprog;
22111 	struct bpf_map *map_ptr;
22112 	struct bpf_insn *insn;
22113 	void *old_bpf_func;
22114 	int err, num_exentries;
22115 	int old_len, subprog_start_adjustment = 0;
22116 
22117 	if (env->subprog_cnt <= 1)
22118 		return 0;
22119 
22120 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22121 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
22122 			continue;
22123 
22124 		/* Upon error here we cannot fall back to interpreter but
22125 		 * need a hard reject of the program. Thus -EFAULT is
22126 		 * propagated in any case.
22127 		 */
22128 		subprog = find_subprog(env, i + insn->imm + 1);
22129 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
22130 				    i + insn->imm + 1))
22131 			return -EFAULT;
22132 		/* temporarily remember subprog id inside insn instead of
22133 		 * aux_data, since next loop will split up all insns into funcs
22134 		 */
22135 		insn->off = subprog;
22136 		/* remember original imm in case JIT fails and fallback
22137 		 * to interpreter will be needed
22138 		 */
22139 		env->insn_aux_data[i].call_imm = insn->imm;
22140 		/* point imm to __bpf_call_base+1 from JITs point of view */
22141 		insn->imm = 1;
22142 		if (bpf_pseudo_func(insn)) {
22143 #if defined(MODULES_VADDR)
22144 			u64 addr = MODULES_VADDR;
22145 #else
22146 			u64 addr = VMALLOC_START;
22147 #endif
22148 			/* jit (e.g. x86_64) may emit fewer instructions
22149 			 * if it learns a u32 imm is the same as a u64 imm.
22150 			 * Set close enough to possible prog address.
22151 			 */
22152 			insn[0].imm = (u32)addr;
22153 			insn[1].imm = addr >> 32;
22154 		}
22155 	}
22156 
22157 	err = bpf_prog_alloc_jited_linfo(prog);
22158 	if (err)
22159 		goto out_undo_insn;
22160 
22161 	err = -ENOMEM;
22162 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
22163 	if (!func)
22164 		goto out_undo_insn;
22165 
22166 	for (i = 0; i < env->subprog_cnt; i++) {
22167 		subprog_start = subprog_end;
22168 		subprog_end = env->subprog_info[i + 1].start;
22169 
22170 		len = subprog_end - subprog_start;
22171 		/* bpf_prog_run() doesn't call subprogs directly,
22172 		 * hence main prog stats include the runtime of subprogs.
22173 		 * subprogs don't have IDs and not reachable via prog_get_next_id
22174 		 * func[i]->stats will never be accessed and stays NULL
22175 		 */
22176 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
22177 		if (!func[i])
22178 			goto out_free;
22179 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
22180 		       len * sizeof(struct bpf_insn));
22181 		func[i]->type = prog->type;
22182 		func[i]->len = len;
22183 		if (bpf_prog_calc_tag(func[i]))
22184 			goto out_free;
22185 		func[i]->is_func = 1;
22186 		func[i]->sleepable = prog->sleepable;
22187 		func[i]->aux->func_idx = i;
22188 		/* Below members will be freed only at prog->aux */
22189 		func[i]->aux->btf = prog->aux->btf;
22190 		func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
22191 		func[i]->aux->func_info = prog->aux->func_info;
22192 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
22193 		func[i]->aux->poke_tab = prog->aux->poke_tab;
22194 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
22195 		func[i]->aux->main_prog_aux = prog->aux;
22196 
22197 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
22198 			struct bpf_jit_poke_descriptor *poke;
22199 
22200 			poke = &prog->aux->poke_tab[j];
22201 			if (poke->insn_idx < subprog_end &&
22202 			    poke->insn_idx >= subprog_start)
22203 				poke->aux = func[i]->aux;
22204 		}
22205 
22206 		func[i]->aux->name[0] = 'F';
22207 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
22208 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
22209 			func[i]->aux->jits_use_priv_stack = true;
22210 
22211 		func[i]->jit_requested = 1;
22212 		func[i]->blinding_requested = prog->blinding_requested;
22213 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
22214 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
22215 		func[i]->aux->linfo = prog->aux->linfo;
22216 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
22217 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
22218 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
22219 		func[i]->aux->arena = prog->aux->arena;
22220 		func[i]->aux->used_maps = env->used_maps;
22221 		func[i]->aux->used_map_cnt = env->used_map_cnt;
22222 		num_exentries = 0;
22223 		insn = func[i]->insnsi;
22224 		for (j = 0; j < func[i]->len; j++, insn++) {
22225 			if (BPF_CLASS(insn->code) == BPF_LDX &&
22226 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22227 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
22228 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
22229 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
22230 				num_exentries++;
22231 			if ((BPF_CLASS(insn->code) == BPF_STX ||
22232 			     BPF_CLASS(insn->code) == BPF_ST) &&
22233 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
22234 				num_exentries++;
22235 			if (BPF_CLASS(insn->code) == BPF_STX &&
22236 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
22237 				num_exentries++;
22238 		}
22239 		func[i]->aux->num_exentries = num_exentries;
22240 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
22241 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
22242 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
22243 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
22244 		if (!i)
22245 			func[i]->aux->exception_boundary = env->seen_exception;
22246 
22247 		/*
22248 		 * To properly pass the absolute subprog start to jit
22249 		 * all instruction adjustments should be accumulated
22250 		 */
22251 		old_len = func[i]->len;
22252 		func[i] = bpf_int_jit_compile(func[i]);
22253 		subprog_start_adjustment += func[i]->len - old_len;
22254 
22255 		if (!func[i]->jited) {
22256 			err = -ENOTSUPP;
22257 			goto out_free;
22258 		}
22259 		cond_resched();
22260 	}
22261 
22262 	/* at this point all bpf functions were successfully JITed
22263 	 * now populate all bpf_calls with correct addresses and
22264 	 * run last pass of JIT
22265 	 */
22266 	for (i = 0; i < env->subprog_cnt; i++) {
22267 		insn = func[i]->insnsi;
22268 		for (j = 0; j < func[i]->len; j++, insn++) {
22269 			if (bpf_pseudo_func(insn)) {
22270 				subprog = insn->off;
22271 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
22272 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
22273 				continue;
22274 			}
22275 			if (!bpf_pseudo_call(insn))
22276 				continue;
22277 			subprog = insn->off;
22278 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
22279 		}
22280 
22281 		/* we use the aux data to keep a list of the start addresses
22282 		 * of the JITed images for each function in the program
22283 		 *
22284 		 * for some architectures, such as powerpc64, the imm field
22285 		 * might not be large enough to hold the offset of the start
22286 		 * address of the callee's JITed image from __bpf_call_base
22287 		 *
22288 		 * in such cases, we can lookup the start address of a callee
22289 		 * by using its subprog id, available from the off field of
22290 		 * the call instruction, as an index for this list
22291 		 */
22292 		func[i]->aux->func = func;
22293 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22294 		func[i]->aux->real_func_cnt = env->subprog_cnt;
22295 	}
22296 	for (i = 0; i < env->subprog_cnt; i++) {
22297 		old_bpf_func = func[i]->bpf_func;
22298 		tmp = bpf_int_jit_compile(func[i]);
22299 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
22300 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
22301 			err = -ENOTSUPP;
22302 			goto out_free;
22303 		}
22304 		cond_resched();
22305 	}
22306 
22307 	/*
22308 	 * Cleanup func[i]->aux fields which aren't required
22309 	 * or can become invalid in future
22310 	 */
22311 	for (i = 0; i < env->subprog_cnt; i++) {
22312 		func[i]->aux->used_maps = NULL;
22313 		func[i]->aux->used_map_cnt = 0;
22314 	}
22315 
22316 	/* finally lock prog and jit images for all functions and
22317 	 * populate kallsysm. Begin at the first subprogram, since
22318 	 * bpf_prog_load will add the kallsyms for the main program.
22319 	 */
22320 	for (i = 1; i < env->subprog_cnt; i++) {
22321 		err = bpf_prog_lock_ro(func[i]);
22322 		if (err)
22323 			goto out_free;
22324 	}
22325 
22326 	for (i = 1; i < env->subprog_cnt; i++)
22327 		bpf_prog_kallsyms_add(func[i]);
22328 
22329 	/* Last step: make now unused interpreter insns from main
22330 	 * prog consistent for later dump requests, so they can
22331 	 * later look the same as if they were interpreted only.
22332 	 */
22333 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22334 		if (bpf_pseudo_func(insn)) {
22335 			insn[0].imm = env->insn_aux_data[i].call_imm;
22336 			insn[1].imm = insn->off;
22337 			insn->off = 0;
22338 			continue;
22339 		}
22340 		if (!bpf_pseudo_call(insn))
22341 			continue;
22342 		insn->off = env->insn_aux_data[i].call_imm;
22343 		subprog = find_subprog(env, i + insn->off + 1);
22344 		insn->imm = subprog;
22345 	}
22346 
22347 	prog->jited = 1;
22348 	prog->bpf_func = func[0]->bpf_func;
22349 	prog->jited_len = func[0]->jited_len;
22350 	prog->aux->extable = func[0]->aux->extable;
22351 	prog->aux->num_exentries = func[0]->aux->num_exentries;
22352 	prog->aux->func = func;
22353 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22354 	prog->aux->real_func_cnt = env->subprog_cnt;
22355 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
22356 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
22357 	bpf_prog_jit_attempt_done(prog);
22358 	return 0;
22359 out_free:
22360 	/* We failed JIT'ing, so at this point we need to unregister poke
22361 	 * descriptors from subprogs, so that kernel is not attempting to
22362 	 * patch it anymore as we're freeing the subprog JIT memory.
22363 	 */
22364 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22365 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22366 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
22367 	}
22368 	/* At this point we're guaranteed that poke descriptors are not
22369 	 * live anymore. We can just unlink its descriptor table as it's
22370 	 * released with the main prog.
22371 	 */
22372 	for (i = 0; i < env->subprog_cnt; i++) {
22373 		if (!func[i])
22374 			continue;
22375 		func[i]->aux->poke_tab = NULL;
22376 		bpf_jit_free(func[i]);
22377 	}
22378 	kfree(func);
22379 out_undo_insn:
22380 	/* cleanup main prog to be interpreted */
22381 	prog->jit_requested = 0;
22382 	prog->blinding_requested = 0;
22383 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22384 		if (!bpf_pseudo_call(insn))
22385 			continue;
22386 		insn->off = 0;
22387 		insn->imm = env->insn_aux_data[i].call_imm;
22388 	}
22389 	bpf_prog_jit_attempt_done(prog);
22390 	return err;
22391 }
22392 
22393 static int fixup_call_args(struct bpf_verifier_env *env)
22394 {
22395 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22396 	struct bpf_prog *prog = env->prog;
22397 	struct bpf_insn *insn = prog->insnsi;
22398 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
22399 	int i, depth;
22400 #endif
22401 	int err = 0;
22402 
22403 	if (env->prog->jit_requested &&
22404 	    !bpf_prog_is_offloaded(env->prog->aux)) {
22405 		err = jit_subprogs(env);
22406 		if (err == 0)
22407 			return 0;
22408 		if (err == -EFAULT)
22409 			return err;
22410 	}
22411 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22412 	if (has_kfunc_call) {
22413 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
22414 		return -EINVAL;
22415 	}
22416 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
22417 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
22418 		 * have to be rejected, since interpreter doesn't support them yet.
22419 		 */
22420 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
22421 		return -EINVAL;
22422 	}
22423 	for (i = 0; i < prog->len; i++, insn++) {
22424 		if (bpf_pseudo_func(insn)) {
22425 			/* When JIT fails the progs with callback calls
22426 			 * have to be rejected, since interpreter doesn't support them yet.
22427 			 */
22428 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
22429 			return -EINVAL;
22430 		}
22431 
22432 		if (!bpf_pseudo_call(insn))
22433 			continue;
22434 		depth = get_callee_stack_depth(env, insn, i);
22435 		if (depth < 0)
22436 			return depth;
22437 		bpf_patch_call_args(insn, depth);
22438 	}
22439 	err = 0;
22440 #endif
22441 	return err;
22442 }
22443 
22444 /* replace a generic kfunc with a specialized version if necessary */
22445 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
22446 {
22447 	struct bpf_prog *prog = env->prog;
22448 	bool seen_direct_write;
22449 	void *xdp_kfunc;
22450 	bool is_rdonly;
22451 	u32 func_id = desc->func_id;
22452 	u16 offset = desc->offset;
22453 	unsigned long addr = desc->addr;
22454 
22455 	if (offset) /* return if module BTF is used */
22456 		return 0;
22457 
22458 	if (bpf_dev_bound_kfunc_id(func_id)) {
22459 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
22460 		if (xdp_kfunc)
22461 			addr = (unsigned long)xdp_kfunc;
22462 		/* fallback to default kfunc when not supported by netdev */
22463 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
22464 		seen_direct_write = env->seen_direct_write;
22465 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
22466 
22467 		if (is_rdonly)
22468 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
22469 
22470 		/* restore env->seen_direct_write to its original value, since
22471 		 * may_access_direct_pkt_data mutates it
22472 		 */
22473 		env->seen_direct_write = seen_direct_write;
22474 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
22475 		if (bpf_lsm_has_d_inode_locked(prog))
22476 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
22477 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
22478 		if (bpf_lsm_has_d_inode_locked(prog))
22479 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
22480 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
22481 		if (!env->insn_aux_data[insn_idx].non_sleepable)
22482 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
22483 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
22484 		if (env->insn_aux_data[insn_idx].non_sleepable)
22485 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
22486 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
22487 		if (env->insn_aux_data[insn_idx].non_sleepable)
22488 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
22489 	}
22490 	desc->addr = addr;
22491 	return 0;
22492 }
22493 
22494 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
22495 					    u16 struct_meta_reg,
22496 					    u16 node_offset_reg,
22497 					    struct bpf_insn *insn,
22498 					    struct bpf_insn *insn_buf,
22499 					    int *cnt)
22500 {
22501 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
22502 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
22503 
22504 	insn_buf[0] = addr[0];
22505 	insn_buf[1] = addr[1];
22506 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
22507 	insn_buf[3] = *insn;
22508 	*cnt = 4;
22509 }
22510 
22511 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
22512 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
22513 {
22514 	struct bpf_kfunc_desc *desc;
22515 	int err;
22516 
22517 	if (!insn->imm) {
22518 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
22519 		return -EINVAL;
22520 	}
22521 
22522 	*cnt = 0;
22523 
22524 	/* insn->imm has the btf func_id. Replace it with an offset relative to
22525 	 * __bpf_call_base, unless the JIT needs to call functions that are
22526 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
22527 	 */
22528 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
22529 	if (!desc) {
22530 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
22531 			     insn->imm);
22532 		return -EFAULT;
22533 	}
22534 
22535 	err = specialize_kfunc(env, desc, insn_idx);
22536 	if (err)
22537 		return err;
22538 
22539 	if (!bpf_jit_supports_far_kfunc_call())
22540 		insn->imm = BPF_CALL_IMM(desc->addr);
22541 
22542 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
22543 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
22544 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22545 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22546 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
22547 
22548 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
22549 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22550 				     insn_idx);
22551 			return -EFAULT;
22552 		}
22553 
22554 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
22555 		insn_buf[1] = addr[0];
22556 		insn_buf[2] = addr[1];
22557 		insn_buf[3] = *insn;
22558 		*cnt = 4;
22559 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
22560 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
22561 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
22562 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22563 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22564 
22565 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
22566 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22567 				     insn_idx);
22568 			return -EFAULT;
22569 		}
22570 
22571 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
22572 		    !kptr_struct_meta) {
22573 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22574 				     insn_idx);
22575 			return -EFAULT;
22576 		}
22577 
22578 		insn_buf[0] = addr[0];
22579 		insn_buf[1] = addr[1];
22580 		insn_buf[2] = *insn;
22581 		*cnt = 3;
22582 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
22583 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
22584 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22585 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22586 		int struct_meta_reg = BPF_REG_3;
22587 		int node_offset_reg = BPF_REG_4;
22588 
22589 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
22590 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22591 			struct_meta_reg = BPF_REG_4;
22592 			node_offset_reg = BPF_REG_5;
22593 		}
22594 
22595 		if (!kptr_struct_meta) {
22596 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22597 				     insn_idx);
22598 			return -EFAULT;
22599 		}
22600 
22601 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
22602 						node_offset_reg, insn, insn_buf, cnt);
22603 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
22604 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
22605 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22606 		*cnt = 1;
22607 	}
22608 
22609 	if (env->insn_aux_data[insn_idx].arg_prog) {
22610 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
22611 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
22612 		int idx = *cnt;
22613 
22614 		insn_buf[idx++] = ld_addrs[0];
22615 		insn_buf[idx++] = ld_addrs[1];
22616 		insn_buf[idx++] = *insn;
22617 		*cnt = idx;
22618 	}
22619 	return 0;
22620 }
22621 
22622 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
22623 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
22624 {
22625 	struct bpf_subprog_info *info = env->subprog_info;
22626 	int cnt = env->subprog_cnt;
22627 	struct bpf_prog *prog;
22628 
22629 	/* We only reserve one slot for hidden subprogs in subprog_info. */
22630 	if (env->hidden_subprog_cnt) {
22631 		verifier_bug(env, "only one hidden subprog supported");
22632 		return -EFAULT;
22633 	}
22634 	/* We're not patching any existing instruction, just appending the new
22635 	 * ones for the hidden subprog. Hence all of the adjustment operations
22636 	 * in bpf_patch_insn_data are no-ops.
22637 	 */
22638 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
22639 	if (!prog)
22640 		return -ENOMEM;
22641 	env->prog = prog;
22642 	info[cnt + 1].start = info[cnt].start;
22643 	info[cnt].start = prog->len - len + 1;
22644 	env->subprog_cnt++;
22645 	env->hidden_subprog_cnt++;
22646 	return 0;
22647 }
22648 
22649 /* Do various post-verification rewrites in a single program pass.
22650  * These rewrites simplify JIT and interpreter implementations.
22651  */
22652 static int do_misc_fixups(struct bpf_verifier_env *env)
22653 {
22654 	struct bpf_prog *prog = env->prog;
22655 	enum bpf_attach_type eatype = prog->expected_attach_type;
22656 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22657 	struct bpf_insn *insn = prog->insnsi;
22658 	const struct bpf_func_proto *fn;
22659 	const int insn_cnt = prog->len;
22660 	const struct bpf_map_ops *ops;
22661 	struct bpf_insn_aux_data *aux;
22662 	struct bpf_insn *insn_buf = env->insn_buf;
22663 	struct bpf_prog *new_prog;
22664 	struct bpf_map *map_ptr;
22665 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22666 	struct bpf_subprog_info *subprogs = env->subprog_info;
22667 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22668 	u16 stack_depth_extra = 0;
22669 
22670 	if (env->seen_exception && !env->exception_callback_subprog) {
22671 		struct bpf_insn *patch = insn_buf;
22672 
22673 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22674 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22675 		*patch++ = BPF_EXIT_INSN();
22676 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22677 		if (ret < 0)
22678 			return ret;
22679 		prog = env->prog;
22680 		insn = prog->insnsi;
22681 
22682 		env->exception_callback_subprog = env->subprog_cnt - 1;
22683 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22684 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22685 	}
22686 
22687 	for (i = 0; i < insn_cnt;) {
22688 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22689 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22690 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22691 				/* convert to 32-bit mov that clears upper 32-bit */
22692 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22693 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22694 				insn->off = 0;
22695 				insn->imm = 0;
22696 			} /* cast from as(0) to as(1) should be handled by JIT */
22697 			goto next_insn;
22698 		}
22699 
22700 		if (env->insn_aux_data[i + delta].needs_zext)
22701 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22702 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22703 
22704 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22705 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22706 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22707 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22708 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22709 		    insn->off == 1 && insn->imm == -1) {
22710 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22711 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22712 			struct bpf_insn *patch = insn_buf;
22713 
22714 			if (isdiv)
22715 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22716 							BPF_NEG | BPF_K, insn->dst_reg,
22717 							0, 0, 0);
22718 			else
22719 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22720 
22721 			cnt = patch - insn_buf;
22722 
22723 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22724 			if (!new_prog)
22725 				return -ENOMEM;
22726 
22727 			delta    += cnt - 1;
22728 			env->prog = prog = new_prog;
22729 			insn      = new_prog->insnsi + i + delta;
22730 			goto next_insn;
22731 		}
22732 
22733 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22734 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22735 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22736 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22737 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22738 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22739 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22740 			bool is_sdiv = isdiv && insn->off == 1;
22741 			bool is_smod = !isdiv && insn->off == 1;
22742 			struct bpf_insn *patch = insn_buf;
22743 
22744 			if (is_sdiv) {
22745 				/* [R,W]x sdiv 0 -> 0
22746 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22747 				 * INT_MIN sdiv -1 -> INT_MIN
22748 				 */
22749 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22750 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22751 							BPF_ADD | BPF_K, BPF_REG_AX,
22752 							0, 0, 1);
22753 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22754 							BPF_JGT | BPF_K, BPF_REG_AX,
22755 							0, 4, 1);
22756 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22757 							BPF_JEQ | BPF_K, BPF_REG_AX,
22758 							0, 1, 0);
22759 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22760 							BPF_MOV | BPF_K, insn->dst_reg,
22761 							0, 0, 0);
22762 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22763 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22764 							BPF_NEG | BPF_K, insn->dst_reg,
22765 							0, 0, 0);
22766 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22767 				*patch++ = *insn;
22768 				cnt = patch - insn_buf;
22769 			} else if (is_smod) {
22770 				/* [R,W]x mod 0 -> [R,W]x */
22771 				/* [R,W]x mod -1 -> 0 */
22772 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22773 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22774 							BPF_ADD | BPF_K, BPF_REG_AX,
22775 							0, 0, 1);
22776 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22777 							BPF_JGT | BPF_K, BPF_REG_AX,
22778 							0, 3, 1);
22779 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22780 							BPF_JEQ | BPF_K, BPF_REG_AX,
22781 							0, 3 + (is64 ? 0 : 1), 1);
22782 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22783 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22784 				*patch++ = *insn;
22785 
22786 				if (!is64) {
22787 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22788 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22789 				}
22790 				cnt = patch - insn_buf;
22791 			} else if (isdiv) {
22792 				/* [R,W]x div 0 -> 0 */
22793 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22794 							BPF_JNE | BPF_K, insn->src_reg,
22795 							0, 2, 0);
22796 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22797 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22798 				*patch++ = *insn;
22799 				cnt = patch - insn_buf;
22800 			} else {
22801 				/* [R,W]x mod 0 -> [R,W]x */
22802 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22803 							BPF_JEQ | BPF_K, insn->src_reg,
22804 							0, 1 + (is64 ? 0 : 1), 0);
22805 				*patch++ = *insn;
22806 
22807 				if (!is64) {
22808 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22809 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22810 				}
22811 				cnt = patch - insn_buf;
22812 			}
22813 
22814 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22815 			if (!new_prog)
22816 				return -ENOMEM;
22817 
22818 			delta    += cnt - 1;
22819 			env->prog = prog = new_prog;
22820 			insn      = new_prog->insnsi + i + delta;
22821 			goto next_insn;
22822 		}
22823 
22824 		/* Make it impossible to de-reference a userspace address */
22825 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22826 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22827 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22828 			struct bpf_insn *patch = insn_buf;
22829 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22830 
22831 			if (!uaddress_limit)
22832 				goto next_insn;
22833 
22834 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22835 			if (insn->off)
22836 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22837 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22838 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22839 			*patch++ = *insn;
22840 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22841 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22842 
22843 			cnt = patch - insn_buf;
22844 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22845 			if (!new_prog)
22846 				return -ENOMEM;
22847 
22848 			delta    += cnt - 1;
22849 			env->prog = prog = new_prog;
22850 			insn      = new_prog->insnsi + i + delta;
22851 			goto next_insn;
22852 		}
22853 
22854 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22855 		if (BPF_CLASS(insn->code) == BPF_LD &&
22856 		    (BPF_MODE(insn->code) == BPF_ABS ||
22857 		     BPF_MODE(insn->code) == BPF_IND)) {
22858 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22859 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22860 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22861 				return -EFAULT;
22862 			}
22863 
22864 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22865 			if (!new_prog)
22866 				return -ENOMEM;
22867 
22868 			delta    += cnt - 1;
22869 			env->prog = prog = new_prog;
22870 			insn      = new_prog->insnsi + i + delta;
22871 			goto next_insn;
22872 		}
22873 
22874 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22875 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22876 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22877 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22878 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22879 			struct bpf_insn *patch = insn_buf;
22880 			bool issrc, isneg, isimm;
22881 			u32 off_reg;
22882 
22883 			aux = &env->insn_aux_data[i + delta];
22884 			if (!aux->alu_state ||
22885 			    aux->alu_state == BPF_ALU_NON_POINTER)
22886 				goto next_insn;
22887 
22888 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22889 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22890 				BPF_ALU_SANITIZE_SRC;
22891 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22892 
22893 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22894 			if (isimm) {
22895 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22896 			} else {
22897 				if (isneg)
22898 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22899 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22900 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22901 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22902 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22903 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22904 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22905 			}
22906 			if (!issrc)
22907 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22908 			insn->src_reg = BPF_REG_AX;
22909 			if (isneg)
22910 				insn->code = insn->code == code_add ?
22911 					     code_sub : code_add;
22912 			*patch++ = *insn;
22913 			if (issrc && isneg && !isimm)
22914 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22915 			cnt = patch - insn_buf;
22916 
22917 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22918 			if (!new_prog)
22919 				return -ENOMEM;
22920 
22921 			delta    += cnt - 1;
22922 			env->prog = prog = new_prog;
22923 			insn      = new_prog->insnsi + i + delta;
22924 			goto next_insn;
22925 		}
22926 
22927 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22928 			int stack_off_cnt = -stack_depth - 16;
22929 
22930 			/*
22931 			 * Two 8 byte slots, depth-16 stores the count, and
22932 			 * depth-8 stores the start timestamp of the loop.
22933 			 *
22934 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22935 			 * (0xffff).  Every iteration loads it and subs it by 1,
22936 			 * until the value becomes 0 in AX (thus, 1 in stack),
22937 			 * after which we call arch_bpf_timed_may_goto, which
22938 			 * either sets AX to 0xffff to keep looping, or to 0
22939 			 * upon timeout. AX is then stored into the stack. In
22940 			 * the next iteration, we either see 0 and break out, or
22941 			 * continue iterating until the next time value is 0
22942 			 * after subtraction, rinse and repeat.
22943 			 */
22944 			stack_depth_extra = 16;
22945 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22946 			if (insn->off >= 0)
22947 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22948 			else
22949 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22950 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22951 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22952 			/*
22953 			 * AX is used as an argument to pass in stack_off_cnt
22954 			 * (to add to r10/fp), and also as the return value of
22955 			 * the call to arch_bpf_timed_may_goto.
22956 			 */
22957 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22958 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22959 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22960 			cnt = 7;
22961 
22962 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22963 			if (!new_prog)
22964 				return -ENOMEM;
22965 
22966 			delta += cnt - 1;
22967 			env->prog = prog = new_prog;
22968 			insn = new_prog->insnsi + i + delta;
22969 			goto next_insn;
22970 		} else if (is_may_goto_insn(insn)) {
22971 			int stack_off = -stack_depth - 8;
22972 
22973 			stack_depth_extra = 8;
22974 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22975 			if (insn->off >= 0)
22976 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22977 			else
22978 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22979 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22980 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22981 			cnt = 4;
22982 
22983 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22984 			if (!new_prog)
22985 				return -ENOMEM;
22986 
22987 			delta += cnt - 1;
22988 			env->prog = prog = new_prog;
22989 			insn = new_prog->insnsi + i + delta;
22990 			goto next_insn;
22991 		}
22992 
22993 		if (insn->code != (BPF_JMP | BPF_CALL))
22994 			goto next_insn;
22995 		if (insn->src_reg == BPF_PSEUDO_CALL)
22996 			goto next_insn;
22997 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22998 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22999 			if (ret)
23000 				return ret;
23001 			if (cnt == 0)
23002 				goto next_insn;
23003 
23004 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23005 			if (!new_prog)
23006 				return -ENOMEM;
23007 
23008 			delta	 += cnt - 1;
23009 			env->prog = prog = new_prog;
23010 			insn	  = new_prog->insnsi + i + delta;
23011 			goto next_insn;
23012 		}
23013 
23014 		/* Skip inlining the helper call if the JIT does it. */
23015 		if (bpf_jit_inlines_helper_call(insn->imm))
23016 			goto next_insn;
23017 
23018 		if (insn->imm == BPF_FUNC_get_route_realm)
23019 			prog->dst_needed = 1;
23020 		if (insn->imm == BPF_FUNC_get_prandom_u32)
23021 			bpf_user_rnd_init_once();
23022 		if (insn->imm == BPF_FUNC_override_return)
23023 			prog->kprobe_override = 1;
23024 		if (insn->imm == BPF_FUNC_tail_call) {
23025 			/* If we tail call into other programs, we
23026 			 * cannot make any assumptions since they can
23027 			 * be replaced dynamically during runtime in
23028 			 * the program array.
23029 			 */
23030 			prog->cb_access = 1;
23031 			if (!allow_tail_call_in_subprogs(env))
23032 				prog->aux->stack_depth = MAX_BPF_STACK;
23033 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
23034 
23035 			/* mark bpf_tail_call as different opcode to avoid
23036 			 * conditional branch in the interpreter for every normal
23037 			 * call and to prevent accidental JITing by JIT compiler
23038 			 * that doesn't support bpf_tail_call yet
23039 			 */
23040 			insn->imm = 0;
23041 			insn->code = BPF_JMP | BPF_TAIL_CALL;
23042 
23043 			aux = &env->insn_aux_data[i + delta];
23044 			if (env->bpf_capable && !prog->blinding_requested &&
23045 			    prog->jit_requested &&
23046 			    !bpf_map_key_poisoned(aux) &&
23047 			    !bpf_map_ptr_poisoned(aux) &&
23048 			    !bpf_map_ptr_unpriv(aux)) {
23049 				struct bpf_jit_poke_descriptor desc = {
23050 					.reason = BPF_POKE_REASON_TAIL_CALL,
23051 					.tail_call.map = aux->map_ptr_state.map_ptr,
23052 					.tail_call.key = bpf_map_key_immediate(aux),
23053 					.insn_idx = i + delta,
23054 				};
23055 
23056 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
23057 				if (ret < 0) {
23058 					verbose(env, "adding tail call poke descriptor failed\n");
23059 					return ret;
23060 				}
23061 
23062 				insn->imm = ret + 1;
23063 				goto next_insn;
23064 			}
23065 
23066 			if (!bpf_map_ptr_unpriv(aux))
23067 				goto next_insn;
23068 
23069 			/* instead of changing every JIT dealing with tail_call
23070 			 * emit two extra insns:
23071 			 * if (index >= max_entries) goto out;
23072 			 * index &= array->index_mask;
23073 			 * to avoid out-of-bounds cpu speculation
23074 			 */
23075 			if (bpf_map_ptr_poisoned(aux)) {
23076 				verbose(env, "tail_call abusing map_ptr\n");
23077 				return -EINVAL;
23078 			}
23079 
23080 			map_ptr = aux->map_ptr_state.map_ptr;
23081 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
23082 						  map_ptr->max_entries, 2);
23083 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
23084 						    container_of(map_ptr,
23085 								 struct bpf_array,
23086 								 map)->index_mask);
23087 			insn_buf[2] = *insn;
23088 			cnt = 3;
23089 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23090 			if (!new_prog)
23091 				return -ENOMEM;
23092 
23093 			delta    += cnt - 1;
23094 			env->prog = prog = new_prog;
23095 			insn      = new_prog->insnsi + i + delta;
23096 			goto next_insn;
23097 		}
23098 
23099 		if (insn->imm == BPF_FUNC_timer_set_callback) {
23100 			/* The verifier will process callback_fn as many times as necessary
23101 			 * with different maps and the register states prepared by
23102 			 * set_timer_callback_state will be accurate.
23103 			 *
23104 			 * The following use case is valid:
23105 			 *   map1 is shared by prog1, prog2, prog3.
23106 			 *   prog1 calls bpf_timer_init for some map1 elements
23107 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
23108 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
23109 			 *   prog3 calls bpf_timer_start for some map1 elements.
23110 			 *     Those that were not both bpf_timer_init-ed and
23111 			 *     bpf_timer_set_callback-ed will return -EINVAL.
23112 			 */
23113 			struct bpf_insn ld_addrs[2] = {
23114 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
23115 			};
23116 
23117 			insn_buf[0] = ld_addrs[0];
23118 			insn_buf[1] = ld_addrs[1];
23119 			insn_buf[2] = *insn;
23120 			cnt = 3;
23121 
23122 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23123 			if (!new_prog)
23124 				return -ENOMEM;
23125 
23126 			delta    += cnt - 1;
23127 			env->prog = prog = new_prog;
23128 			insn      = new_prog->insnsi + i + delta;
23129 			goto patch_call_imm;
23130 		}
23131 
23132 		if (is_storage_get_function(insn->imm)) {
23133 			if (env->insn_aux_data[i + delta].non_sleepable)
23134 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
23135 			else
23136 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
23137 			insn_buf[1] = *insn;
23138 			cnt = 2;
23139 
23140 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23141 			if (!new_prog)
23142 				return -ENOMEM;
23143 
23144 			delta += cnt - 1;
23145 			env->prog = prog = new_prog;
23146 			insn = new_prog->insnsi + i + delta;
23147 			goto patch_call_imm;
23148 		}
23149 
23150 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
23151 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
23152 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
23153 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
23154 			 */
23155 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
23156 			insn_buf[1] = *insn;
23157 			cnt = 2;
23158 
23159 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23160 			if (!new_prog)
23161 				return -ENOMEM;
23162 
23163 			delta += cnt - 1;
23164 			env->prog = prog = new_prog;
23165 			insn = new_prog->insnsi + i + delta;
23166 			goto patch_call_imm;
23167 		}
23168 
23169 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
23170 		 * and other inlining handlers are currently limited to 64 bit
23171 		 * only.
23172 		 */
23173 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23174 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
23175 		     insn->imm == BPF_FUNC_map_update_elem ||
23176 		     insn->imm == BPF_FUNC_map_delete_elem ||
23177 		     insn->imm == BPF_FUNC_map_push_elem   ||
23178 		     insn->imm == BPF_FUNC_map_pop_elem    ||
23179 		     insn->imm == BPF_FUNC_map_peek_elem   ||
23180 		     insn->imm == BPF_FUNC_redirect_map    ||
23181 		     insn->imm == BPF_FUNC_for_each_map_elem ||
23182 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
23183 			aux = &env->insn_aux_data[i + delta];
23184 			if (bpf_map_ptr_poisoned(aux))
23185 				goto patch_call_imm;
23186 
23187 			map_ptr = aux->map_ptr_state.map_ptr;
23188 			ops = map_ptr->ops;
23189 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
23190 			    ops->map_gen_lookup) {
23191 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
23192 				if (cnt == -EOPNOTSUPP)
23193 					goto patch_map_ops_generic;
23194 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
23195 					verifier_bug(env, "%d insns generated for map lookup", cnt);
23196 					return -EFAULT;
23197 				}
23198 
23199 				new_prog = bpf_patch_insn_data(env, i + delta,
23200 							       insn_buf, cnt);
23201 				if (!new_prog)
23202 					return -ENOMEM;
23203 
23204 				delta    += cnt - 1;
23205 				env->prog = prog = new_prog;
23206 				insn      = new_prog->insnsi + i + delta;
23207 				goto next_insn;
23208 			}
23209 
23210 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
23211 				     (void *(*)(struct bpf_map *map, void *key))NULL));
23212 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
23213 				     (long (*)(struct bpf_map *map, void *key))NULL));
23214 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
23215 				     (long (*)(struct bpf_map *map, void *key, void *value,
23216 					      u64 flags))NULL));
23217 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
23218 				     (long (*)(struct bpf_map *map, void *value,
23219 					      u64 flags))NULL));
23220 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
23221 				     (long (*)(struct bpf_map *map, void *value))NULL));
23222 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
23223 				     (long (*)(struct bpf_map *map, void *value))NULL));
23224 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
23225 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
23226 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
23227 				     (long (*)(struct bpf_map *map,
23228 					      bpf_callback_t callback_fn,
23229 					      void *callback_ctx,
23230 					      u64 flags))NULL));
23231 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
23232 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
23233 
23234 patch_map_ops_generic:
23235 			switch (insn->imm) {
23236 			case BPF_FUNC_map_lookup_elem:
23237 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
23238 				goto next_insn;
23239 			case BPF_FUNC_map_update_elem:
23240 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
23241 				goto next_insn;
23242 			case BPF_FUNC_map_delete_elem:
23243 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
23244 				goto next_insn;
23245 			case BPF_FUNC_map_push_elem:
23246 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
23247 				goto next_insn;
23248 			case BPF_FUNC_map_pop_elem:
23249 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
23250 				goto next_insn;
23251 			case BPF_FUNC_map_peek_elem:
23252 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
23253 				goto next_insn;
23254 			case BPF_FUNC_redirect_map:
23255 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
23256 				goto next_insn;
23257 			case BPF_FUNC_for_each_map_elem:
23258 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
23259 				goto next_insn;
23260 			case BPF_FUNC_map_lookup_percpu_elem:
23261 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
23262 				goto next_insn;
23263 			}
23264 
23265 			goto patch_call_imm;
23266 		}
23267 
23268 		/* Implement bpf_jiffies64 inline. */
23269 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23270 		    insn->imm == BPF_FUNC_jiffies64) {
23271 			struct bpf_insn ld_jiffies_addr[2] = {
23272 				BPF_LD_IMM64(BPF_REG_0,
23273 					     (unsigned long)&jiffies),
23274 			};
23275 
23276 			insn_buf[0] = ld_jiffies_addr[0];
23277 			insn_buf[1] = ld_jiffies_addr[1];
23278 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
23279 						  BPF_REG_0, 0);
23280 			cnt = 3;
23281 
23282 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
23283 						       cnt);
23284 			if (!new_prog)
23285 				return -ENOMEM;
23286 
23287 			delta    += cnt - 1;
23288 			env->prog = prog = new_prog;
23289 			insn      = new_prog->insnsi + i + delta;
23290 			goto next_insn;
23291 		}
23292 
23293 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
23294 		/* Implement bpf_get_smp_processor_id() inline. */
23295 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
23296 		    verifier_inlines_helper_call(env, insn->imm)) {
23297 			/* BPF_FUNC_get_smp_processor_id inlining is an
23298 			 * optimization, so if cpu_number is ever
23299 			 * changed in some incompatible and hard to support
23300 			 * way, it's fine to back out this inlining logic
23301 			 */
23302 #ifdef CONFIG_SMP
23303 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
23304 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23305 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
23306 			cnt = 3;
23307 #else
23308 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
23309 			cnt = 1;
23310 #endif
23311 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23312 			if (!new_prog)
23313 				return -ENOMEM;
23314 
23315 			delta    += cnt - 1;
23316 			env->prog = prog = new_prog;
23317 			insn      = new_prog->insnsi + i + delta;
23318 			goto next_insn;
23319 		}
23320 #endif
23321 		/* Implement bpf_get_func_arg inline. */
23322 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23323 		    insn->imm == BPF_FUNC_get_func_arg) {
23324 			/* Load nr_args from ctx - 8 */
23325 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23326 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
23327 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
23328 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
23329 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
23330 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23331 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
23332 			insn_buf[7] = BPF_JMP_A(1);
23333 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23334 			cnt = 9;
23335 
23336 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23337 			if (!new_prog)
23338 				return -ENOMEM;
23339 
23340 			delta    += cnt - 1;
23341 			env->prog = prog = new_prog;
23342 			insn      = new_prog->insnsi + i + delta;
23343 			goto next_insn;
23344 		}
23345 
23346 		/* Implement bpf_get_func_ret inline. */
23347 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23348 		    insn->imm == BPF_FUNC_get_func_ret) {
23349 			if (eatype == BPF_TRACE_FEXIT ||
23350 			    eatype == BPF_MODIFY_RETURN) {
23351 				/* Load nr_args from ctx - 8 */
23352 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23353 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23354 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
23355 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23356 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
23357 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
23358 				cnt = 6;
23359 			} else {
23360 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
23361 				cnt = 1;
23362 			}
23363 
23364 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23365 			if (!new_prog)
23366 				return -ENOMEM;
23367 
23368 			delta    += cnt - 1;
23369 			env->prog = prog = new_prog;
23370 			insn      = new_prog->insnsi + i + delta;
23371 			goto next_insn;
23372 		}
23373 
23374 		/* Implement get_func_arg_cnt inline. */
23375 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23376 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
23377 			/* Load nr_args from ctx - 8 */
23378 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23379 
23380 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23381 			if (!new_prog)
23382 				return -ENOMEM;
23383 
23384 			env->prog = prog = new_prog;
23385 			insn      = new_prog->insnsi + i + delta;
23386 			goto next_insn;
23387 		}
23388 
23389 		/* Implement bpf_get_func_ip inline. */
23390 		if (prog_type == BPF_PROG_TYPE_TRACING &&
23391 		    insn->imm == BPF_FUNC_get_func_ip) {
23392 			/* Load IP address from ctx - 16 */
23393 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
23394 
23395 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23396 			if (!new_prog)
23397 				return -ENOMEM;
23398 
23399 			env->prog = prog = new_prog;
23400 			insn      = new_prog->insnsi + i + delta;
23401 			goto next_insn;
23402 		}
23403 
23404 		/* Implement bpf_get_branch_snapshot inline. */
23405 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
23406 		    prog->jit_requested && BITS_PER_LONG == 64 &&
23407 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
23408 			/* We are dealing with the following func protos:
23409 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
23410 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
23411 			 */
23412 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
23413 
23414 			/* struct perf_branch_entry is part of UAPI and is
23415 			 * used as an array element, so extremely unlikely to
23416 			 * ever grow or shrink
23417 			 */
23418 			BUILD_BUG_ON(br_entry_size != 24);
23419 
23420 			/* if (unlikely(flags)) return -EINVAL */
23421 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
23422 
23423 			/* Transform size (bytes) into number of entries (cnt = size / 24).
23424 			 * But to avoid expensive division instruction, we implement
23425 			 * divide-by-3 through multiplication, followed by further
23426 			 * division by 8 through 3-bit right shift.
23427 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
23428 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
23429 			 *
23430 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
23431 			 */
23432 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
23433 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
23434 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
23435 
23436 			/* call perf_snapshot_branch_stack implementation */
23437 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
23438 			/* if (entry_cnt == 0) return -ENOENT */
23439 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
23440 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
23441 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
23442 			insn_buf[7] = BPF_JMP_A(3);
23443 			/* return -EINVAL; */
23444 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23445 			insn_buf[9] = BPF_JMP_A(1);
23446 			/* return -ENOENT; */
23447 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
23448 			cnt = 11;
23449 
23450 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23451 			if (!new_prog)
23452 				return -ENOMEM;
23453 
23454 			delta    += cnt - 1;
23455 			env->prog = prog = new_prog;
23456 			insn      = new_prog->insnsi + i + delta;
23457 			goto next_insn;
23458 		}
23459 
23460 		/* Implement bpf_kptr_xchg inline */
23461 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
23462 		    insn->imm == BPF_FUNC_kptr_xchg &&
23463 		    bpf_jit_supports_ptr_xchg()) {
23464 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
23465 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
23466 			cnt = 2;
23467 
23468 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23469 			if (!new_prog)
23470 				return -ENOMEM;
23471 
23472 			delta    += cnt - 1;
23473 			env->prog = prog = new_prog;
23474 			insn      = new_prog->insnsi + i + delta;
23475 			goto next_insn;
23476 		}
23477 patch_call_imm:
23478 		fn = env->ops->get_func_proto(insn->imm, env->prog);
23479 		/* all functions that have prototype and verifier allowed
23480 		 * programs to call them, must be real in-kernel functions
23481 		 */
23482 		if (!fn->func) {
23483 			verifier_bug(env,
23484 				     "not inlined functions %s#%d is missing func",
23485 				     func_id_name(insn->imm), insn->imm);
23486 			return -EFAULT;
23487 		}
23488 		insn->imm = fn->func - __bpf_call_base;
23489 next_insn:
23490 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23491 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23492 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
23493 
23494 			stack_depth = subprogs[cur_subprog].stack_depth;
23495 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
23496 				verbose(env, "stack size %d(extra %d) is too large\n",
23497 					stack_depth, stack_depth_extra);
23498 				return -EINVAL;
23499 			}
23500 			cur_subprog++;
23501 			stack_depth = subprogs[cur_subprog].stack_depth;
23502 			stack_depth_extra = 0;
23503 		}
23504 		i++;
23505 		insn++;
23506 	}
23507 
23508 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
23509 	for (i = 0; i < env->subprog_cnt; i++) {
23510 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
23511 		int subprog_start = subprogs[i].start;
23512 		int stack_slots = subprogs[i].stack_extra / 8;
23513 		int slots = delta, cnt = 0;
23514 
23515 		if (!stack_slots)
23516 			continue;
23517 		/* We need two slots in case timed may_goto is supported. */
23518 		if (stack_slots > slots) {
23519 			verifier_bug(env, "stack_slots supports may_goto only");
23520 			return -EFAULT;
23521 		}
23522 
23523 		stack_depth = subprogs[i].stack_depth;
23524 		if (bpf_jit_supports_timed_may_goto()) {
23525 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23526 						     BPF_MAX_TIMED_LOOPS);
23527 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
23528 		} else {
23529 			/* Add ST insn to subprog prologue to init extra stack */
23530 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23531 						     BPF_MAX_LOOPS);
23532 		}
23533 		/* Copy first actual insn to preserve it */
23534 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
23535 
23536 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
23537 		if (!new_prog)
23538 			return -ENOMEM;
23539 		env->prog = prog = new_prog;
23540 		/*
23541 		 * If may_goto is a first insn of a prog there could be a jmp
23542 		 * insn that points to it, hence adjust all such jmps to point
23543 		 * to insn after BPF_ST that inits may_goto count.
23544 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
23545 		 */
23546 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
23547 	}
23548 
23549 	/* Since poke tab is now finalized, publish aux to tracker. */
23550 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
23551 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
23552 		if (!map_ptr->ops->map_poke_track ||
23553 		    !map_ptr->ops->map_poke_untrack ||
23554 		    !map_ptr->ops->map_poke_run) {
23555 			verifier_bug(env, "poke tab is misconfigured");
23556 			return -EFAULT;
23557 		}
23558 
23559 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
23560 		if (ret < 0) {
23561 			verbose(env, "tracking tail call prog failed\n");
23562 			return ret;
23563 		}
23564 	}
23565 
23566 	ret = sort_kfunc_descs_by_imm_off(env);
23567 	if (ret)
23568 		return ret;
23569 
23570 	return 0;
23571 }
23572 
23573 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
23574 					int position,
23575 					s32 stack_base,
23576 					u32 callback_subprogno,
23577 					u32 *total_cnt)
23578 {
23579 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
23580 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
23581 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
23582 	int reg_loop_max = BPF_REG_6;
23583 	int reg_loop_cnt = BPF_REG_7;
23584 	int reg_loop_ctx = BPF_REG_8;
23585 
23586 	struct bpf_insn *insn_buf = env->insn_buf;
23587 	struct bpf_prog *new_prog;
23588 	u32 callback_start;
23589 	u32 call_insn_offset;
23590 	s32 callback_offset;
23591 	u32 cnt = 0;
23592 
23593 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
23594 	 * be careful to modify this code in sync.
23595 	 */
23596 
23597 	/* Return error and jump to the end of the patch if
23598 	 * expected number of iterations is too big.
23599 	 */
23600 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
23601 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
23602 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
23603 	/* spill R6, R7, R8 to use these as loop vars */
23604 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
23605 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
23606 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
23607 	/* initialize loop vars */
23608 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
23609 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
23610 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
23611 	/* loop header,
23612 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
23613 	 */
23614 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
23615 	/* callback call,
23616 	 * correct callback offset would be set after patching
23617 	 */
23618 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
23619 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
23620 	insn_buf[cnt++] = BPF_CALL_REL(0);
23621 	/* increment loop counter */
23622 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
23623 	/* jump to loop header if callback returned 0 */
23624 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
23625 	/* return value of bpf_loop,
23626 	 * set R0 to the number of iterations
23627 	 */
23628 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
23629 	/* restore original values of R6, R7, R8 */
23630 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
23631 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
23632 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
23633 
23634 	*total_cnt = cnt;
23635 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
23636 	if (!new_prog)
23637 		return new_prog;
23638 
23639 	/* callback start is known only after patching */
23640 	callback_start = env->subprog_info[callback_subprogno].start;
23641 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
23642 	call_insn_offset = position + 12;
23643 	callback_offset = callback_start - call_insn_offset - 1;
23644 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
23645 
23646 	return new_prog;
23647 }
23648 
23649 static bool is_bpf_loop_call(struct bpf_insn *insn)
23650 {
23651 	return insn->code == (BPF_JMP | BPF_CALL) &&
23652 		insn->src_reg == 0 &&
23653 		insn->imm == BPF_FUNC_loop;
23654 }
23655 
23656 /* For all sub-programs in the program (including main) check
23657  * insn_aux_data to see if there are bpf_loop calls that require
23658  * inlining. If such calls are found the calls are replaced with a
23659  * sequence of instructions produced by `inline_bpf_loop` function and
23660  * subprog stack_depth is increased by the size of 3 registers.
23661  * This stack space is used to spill values of the R6, R7, R8.  These
23662  * registers are used to store the loop bound, counter and context
23663  * variables.
23664  */
23665 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23666 {
23667 	struct bpf_subprog_info *subprogs = env->subprog_info;
23668 	int i, cur_subprog = 0, cnt, delta = 0;
23669 	struct bpf_insn *insn = env->prog->insnsi;
23670 	int insn_cnt = env->prog->len;
23671 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23672 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23673 	u16 stack_depth_extra = 0;
23674 
23675 	for (i = 0; i < insn_cnt; i++, insn++) {
23676 		struct bpf_loop_inline_state *inline_state =
23677 			&env->insn_aux_data[i + delta].loop_inline_state;
23678 
23679 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23680 			struct bpf_prog *new_prog;
23681 
23682 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23683 			new_prog = inline_bpf_loop(env,
23684 						   i + delta,
23685 						   -(stack_depth + stack_depth_extra),
23686 						   inline_state->callback_subprogno,
23687 						   &cnt);
23688 			if (!new_prog)
23689 				return -ENOMEM;
23690 
23691 			delta     += cnt - 1;
23692 			env->prog  = new_prog;
23693 			insn       = new_prog->insnsi + i + delta;
23694 		}
23695 
23696 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23697 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23698 			cur_subprog++;
23699 			stack_depth = subprogs[cur_subprog].stack_depth;
23700 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23701 			stack_depth_extra = 0;
23702 		}
23703 	}
23704 
23705 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23706 
23707 	return 0;
23708 }
23709 
23710 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23711  * adjust subprograms stack depth when possible.
23712  */
23713 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23714 {
23715 	struct bpf_subprog_info *subprog = env->subprog_info;
23716 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23717 	struct bpf_insn *insn = env->prog->insnsi;
23718 	int insn_cnt = env->prog->len;
23719 	u32 spills_num;
23720 	bool modified = false;
23721 	int i, j;
23722 
23723 	for (i = 0; i < insn_cnt; i++, insn++) {
23724 		if (aux[i].fastcall_spills_num > 0) {
23725 			spills_num = aux[i].fastcall_spills_num;
23726 			/* NOPs would be removed by opt_remove_nops() */
23727 			for (j = 1; j <= spills_num; ++j) {
23728 				*(insn - j) = NOP;
23729 				*(insn + j) = NOP;
23730 			}
23731 			modified = true;
23732 		}
23733 		if ((subprog + 1)->start == i + 1) {
23734 			if (modified && !subprog->keep_fastcall_stack)
23735 				subprog->stack_depth = -subprog->fastcall_stack_off;
23736 			subprog++;
23737 			modified = false;
23738 		}
23739 	}
23740 
23741 	return 0;
23742 }
23743 
23744 static void free_states(struct bpf_verifier_env *env)
23745 {
23746 	struct bpf_verifier_state_list *sl;
23747 	struct list_head *head, *pos, *tmp;
23748 	struct bpf_scc_info *info;
23749 	int i, j;
23750 
23751 	free_verifier_state(env->cur_state, true);
23752 	env->cur_state = NULL;
23753 	while (!pop_stack(env, NULL, NULL, false));
23754 
23755 	list_for_each_safe(pos, tmp, &env->free_list) {
23756 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23757 		free_verifier_state(&sl->state, false);
23758 		kfree(sl);
23759 	}
23760 	INIT_LIST_HEAD(&env->free_list);
23761 
23762 	for (i = 0; i < env->scc_cnt; ++i) {
23763 		info = env->scc_info[i];
23764 		if (!info)
23765 			continue;
23766 		for (j = 0; j < info->num_visits; j++)
23767 			free_backedges(&info->visits[j]);
23768 		kvfree(info);
23769 		env->scc_info[i] = NULL;
23770 	}
23771 
23772 	if (!env->explored_states)
23773 		return;
23774 
23775 	for (i = 0; i < state_htab_size(env); i++) {
23776 		head = &env->explored_states[i];
23777 
23778 		list_for_each_safe(pos, tmp, head) {
23779 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23780 			free_verifier_state(&sl->state, false);
23781 			kfree(sl);
23782 		}
23783 		INIT_LIST_HEAD(&env->explored_states[i]);
23784 	}
23785 }
23786 
23787 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23788 {
23789 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23790 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23791 	struct bpf_prog_aux *aux = env->prog->aux;
23792 	struct bpf_verifier_state *state;
23793 	struct bpf_reg_state *regs;
23794 	int ret, i;
23795 
23796 	env->prev_linfo = NULL;
23797 	env->pass_cnt++;
23798 
23799 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23800 	if (!state)
23801 		return -ENOMEM;
23802 	state->curframe = 0;
23803 	state->speculative = false;
23804 	state->branches = 1;
23805 	state->in_sleepable = env->prog->sleepable;
23806 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23807 	if (!state->frame[0]) {
23808 		kfree(state);
23809 		return -ENOMEM;
23810 	}
23811 	env->cur_state = state;
23812 	init_func_state(env, state->frame[0],
23813 			BPF_MAIN_FUNC /* callsite */,
23814 			0 /* frameno */,
23815 			subprog);
23816 	state->first_insn_idx = env->subprog_info[subprog].start;
23817 	state->last_insn_idx = -1;
23818 
23819 	regs = state->frame[state->curframe]->regs;
23820 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23821 		const char *sub_name = subprog_name(env, subprog);
23822 		struct bpf_subprog_arg_info *arg;
23823 		struct bpf_reg_state *reg;
23824 
23825 		if (env->log.level & BPF_LOG_LEVEL)
23826 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23827 		ret = btf_prepare_func_args(env, subprog);
23828 		if (ret)
23829 			goto out;
23830 
23831 		if (subprog_is_exc_cb(env, subprog)) {
23832 			state->frame[0]->in_exception_callback_fn = true;
23833 			/* We have already ensured that the callback returns an integer, just
23834 			 * like all global subprogs. We need to determine it only has a single
23835 			 * scalar argument.
23836 			 */
23837 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23838 				verbose(env, "exception cb only supports single integer argument\n");
23839 				ret = -EINVAL;
23840 				goto out;
23841 			}
23842 		}
23843 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23844 			arg = &sub->args[i - BPF_REG_1];
23845 			reg = &regs[i];
23846 
23847 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23848 				reg->type = PTR_TO_CTX;
23849 				mark_reg_known_zero(env, regs, i);
23850 			} else if (arg->arg_type == ARG_ANYTHING) {
23851 				reg->type = SCALAR_VALUE;
23852 				mark_reg_unknown(env, regs, i);
23853 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23854 				/* assume unspecial LOCAL dynptr type */
23855 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23856 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23857 				reg->type = PTR_TO_MEM;
23858 				reg->type |= arg->arg_type &
23859 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23860 				mark_reg_known_zero(env, regs, i);
23861 				reg->mem_size = arg->mem_size;
23862 				if (arg->arg_type & PTR_MAYBE_NULL)
23863 					reg->id = ++env->id_gen;
23864 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23865 				reg->type = PTR_TO_BTF_ID;
23866 				if (arg->arg_type & PTR_MAYBE_NULL)
23867 					reg->type |= PTR_MAYBE_NULL;
23868 				if (arg->arg_type & PTR_UNTRUSTED)
23869 					reg->type |= PTR_UNTRUSTED;
23870 				if (arg->arg_type & PTR_TRUSTED)
23871 					reg->type |= PTR_TRUSTED;
23872 				mark_reg_known_zero(env, regs, i);
23873 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23874 				reg->btf_id = arg->btf_id;
23875 				reg->id = ++env->id_gen;
23876 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23877 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23878 				mark_reg_unknown(env, regs, i);
23879 			} else {
23880 				verifier_bug(env, "unhandled arg#%d type %d",
23881 					     i - BPF_REG_1, arg->arg_type);
23882 				ret = -EFAULT;
23883 				goto out;
23884 			}
23885 		}
23886 	} else {
23887 		/* if main BPF program has associated BTF info, validate that
23888 		 * it's matching expected signature, and otherwise mark BTF
23889 		 * info for main program as unreliable
23890 		 */
23891 		if (env->prog->aux->func_info_aux) {
23892 			ret = btf_prepare_func_args(env, 0);
23893 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23894 				env->prog->aux->func_info_aux[0].unreliable = true;
23895 		}
23896 
23897 		/* 1st arg to a function */
23898 		regs[BPF_REG_1].type = PTR_TO_CTX;
23899 		mark_reg_known_zero(env, regs, BPF_REG_1);
23900 	}
23901 
23902 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23903 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23904 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23905 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23906 							  acquire_reference(env, 0) : 0;
23907 	}
23908 
23909 	ret = do_check(env);
23910 out:
23911 	if (!ret && pop_log)
23912 		bpf_vlog_reset(&env->log, 0);
23913 	free_states(env);
23914 	return ret;
23915 }
23916 
23917 /* Lazily verify all global functions based on their BTF, if they are called
23918  * from main BPF program or any of subprograms transitively.
23919  * BPF global subprogs called from dead code are not validated.
23920  * All callable global functions must pass verification.
23921  * Otherwise the whole program is rejected.
23922  * Consider:
23923  * int bar(int);
23924  * int foo(int f)
23925  * {
23926  *    return bar(f);
23927  * }
23928  * int bar(int b)
23929  * {
23930  *    ...
23931  * }
23932  * foo() will be verified first for R1=any_scalar_value. During verification it
23933  * will be assumed that bar() already verified successfully and call to bar()
23934  * from foo() will be checked for type match only. Later bar() will be verified
23935  * independently to check that it's safe for R1=any_scalar_value.
23936  */
23937 static int do_check_subprogs(struct bpf_verifier_env *env)
23938 {
23939 	struct bpf_prog_aux *aux = env->prog->aux;
23940 	struct bpf_func_info_aux *sub_aux;
23941 	int i, ret, new_cnt;
23942 
23943 	if (!aux->func_info)
23944 		return 0;
23945 
23946 	/* exception callback is presumed to be always called */
23947 	if (env->exception_callback_subprog)
23948 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23949 
23950 again:
23951 	new_cnt = 0;
23952 	for (i = 1; i < env->subprog_cnt; i++) {
23953 		if (!subprog_is_global(env, i))
23954 			continue;
23955 
23956 		sub_aux = subprog_aux(env, i);
23957 		if (!sub_aux->called || sub_aux->verified)
23958 			continue;
23959 
23960 		env->insn_idx = env->subprog_info[i].start;
23961 		WARN_ON_ONCE(env->insn_idx == 0);
23962 		ret = do_check_common(env, i);
23963 		if (ret) {
23964 			return ret;
23965 		} else if (env->log.level & BPF_LOG_LEVEL) {
23966 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23967 				i, subprog_name(env, i));
23968 		}
23969 
23970 		/* We verified new global subprog, it might have called some
23971 		 * more global subprogs that we haven't verified yet, so we
23972 		 * need to do another pass over subprogs to verify those.
23973 		 */
23974 		sub_aux->verified = true;
23975 		new_cnt++;
23976 	}
23977 
23978 	/* We can't loop forever as we verify at least one global subprog on
23979 	 * each pass.
23980 	 */
23981 	if (new_cnt)
23982 		goto again;
23983 
23984 	return 0;
23985 }
23986 
23987 static int do_check_main(struct bpf_verifier_env *env)
23988 {
23989 	int ret;
23990 
23991 	env->insn_idx = 0;
23992 	ret = do_check_common(env, 0);
23993 	if (!ret)
23994 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23995 	return ret;
23996 }
23997 
23998 
23999 static void print_verification_stats(struct bpf_verifier_env *env)
24000 {
24001 	int i;
24002 
24003 	if (env->log.level & BPF_LOG_STATS) {
24004 		verbose(env, "verification time %lld usec\n",
24005 			div_u64(env->verification_time, 1000));
24006 		verbose(env, "stack depth ");
24007 		for (i = 0; i < env->subprog_cnt; i++) {
24008 			u32 depth = env->subprog_info[i].stack_depth;
24009 
24010 			verbose(env, "%d", depth);
24011 			if (i + 1 < env->subprog_cnt)
24012 				verbose(env, "+");
24013 		}
24014 		verbose(env, "\n");
24015 	}
24016 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
24017 		"total_states %d peak_states %d mark_read %d\n",
24018 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
24019 		env->max_states_per_insn, env->total_states,
24020 		env->peak_states, env->longest_mark_read_walk);
24021 }
24022 
24023 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
24024 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
24025 {
24026 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
24027 	prog->aux->ctx_arg_info_size = cnt;
24028 
24029 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
24030 }
24031 
24032 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
24033 {
24034 	const struct btf_type *t, *func_proto;
24035 	const struct bpf_struct_ops_desc *st_ops_desc;
24036 	const struct bpf_struct_ops *st_ops;
24037 	const struct btf_member *member;
24038 	struct bpf_prog *prog = env->prog;
24039 	bool has_refcounted_arg = false;
24040 	u32 btf_id, member_idx, member_off;
24041 	struct btf *btf;
24042 	const char *mname;
24043 	int i, err;
24044 
24045 	if (!prog->gpl_compatible) {
24046 		verbose(env, "struct ops programs must have a GPL compatible license\n");
24047 		return -EINVAL;
24048 	}
24049 
24050 	if (!prog->aux->attach_btf_id)
24051 		return -ENOTSUPP;
24052 
24053 	btf = prog->aux->attach_btf;
24054 	if (btf_is_module(btf)) {
24055 		/* Make sure st_ops is valid through the lifetime of env */
24056 		env->attach_btf_mod = btf_try_get_module(btf);
24057 		if (!env->attach_btf_mod) {
24058 			verbose(env, "struct_ops module %s is not found\n",
24059 				btf_get_name(btf));
24060 			return -ENOTSUPP;
24061 		}
24062 	}
24063 
24064 	btf_id = prog->aux->attach_btf_id;
24065 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
24066 	if (!st_ops_desc) {
24067 		verbose(env, "attach_btf_id %u is not a supported struct\n",
24068 			btf_id);
24069 		return -ENOTSUPP;
24070 	}
24071 	st_ops = st_ops_desc->st_ops;
24072 
24073 	t = st_ops_desc->type;
24074 	member_idx = prog->expected_attach_type;
24075 	if (member_idx >= btf_type_vlen(t)) {
24076 		verbose(env, "attach to invalid member idx %u of struct %s\n",
24077 			member_idx, st_ops->name);
24078 		return -EINVAL;
24079 	}
24080 
24081 	member = &btf_type_member(t)[member_idx];
24082 	mname = btf_name_by_offset(btf, member->name_off);
24083 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
24084 					       NULL);
24085 	if (!func_proto) {
24086 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
24087 			mname, member_idx, st_ops->name);
24088 		return -EINVAL;
24089 	}
24090 
24091 	member_off = __btf_member_bit_offset(t, member) / 8;
24092 	err = bpf_struct_ops_supported(st_ops, member_off);
24093 	if (err) {
24094 		verbose(env, "attach to unsupported member %s of struct %s\n",
24095 			mname, st_ops->name);
24096 		return err;
24097 	}
24098 
24099 	if (st_ops->check_member) {
24100 		err = st_ops->check_member(t, member, prog);
24101 
24102 		if (err) {
24103 			verbose(env, "attach to unsupported member %s of struct %s\n",
24104 				mname, st_ops->name);
24105 			return err;
24106 		}
24107 	}
24108 
24109 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
24110 		verbose(env, "Private stack not supported by jit\n");
24111 		return -EACCES;
24112 	}
24113 
24114 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
24115 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
24116 			has_refcounted_arg = true;
24117 			break;
24118 		}
24119 	}
24120 
24121 	/* Tail call is not allowed for programs with refcounted arguments since we
24122 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
24123 	 */
24124 	for (i = 0; i < env->subprog_cnt; i++) {
24125 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
24126 			verbose(env, "program with __ref argument cannot tail call\n");
24127 			return -EINVAL;
24128 		}
24129 	}
24130 
24131 	prog->aux->st_ops = st_ops;
24132 	prog->aux->attach_st_ops_member_off = member_off;
24133 
24134 	prog->aux->attach_func_proto = func_proto;
24135 	prog->aux->attach_func_name = mname;
24136 	env->ops = st_ops->verifier_ops;
24137 
24138 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
24139 					  st_ops_desc->arg_info[member_idx].cnt);
24140 }
24141 #define SECURITY_PREFIX "security_"
24142 
24143 static int check_attach_modify_return(unsigned long addr, const char *func_name)
24144 {
24145 	if (within_error_injection_list(addr) ||
24146 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
24147 		return 0;
24148 
24149 	return -EINVAL;
24150 }
24151 
24152 /* list of non-sleepable functions that are otherwise on
24153  * ALLOW_ERROR_INJECTION list
24154  */
24155 BTF_SET_START(btf_non_sleepable_error_inject)
24156 /* Three functions below can be called from sleepable and non-sleepable context.
24157  * Assume non-sleepable from bpf safety point of view.
24158  */
24159 BTF_ID(func, __filemap_add_folio)
24160 #ifdef CONFIG_FAIL_PAGE_ALLOC
24161 BTF_ID(func, should_fail_alloc_page)
24162 #endif
24163 #ifdef CONFIG_FAILSLAB
24164 BTF_ID(func, should_failslab)
24165 #endif
24166 BTF_SET_END(btf_non_sleepable_error_inject)
24167 
24168 static int check_non_sleepable_error_inject(u32 btf_id)
24169 {
24170 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
24171 }
24172 
24173 int bpf_check_attach_target(struct bpf_verifier_log *log,
24174 			    const struct bpf_prog *prog,
24175 			    const struct bpf_prog *tgt_prog,
24176 			    u32 btf_id,
24177 			    struct bpf_attach_target_info *tgt_info)
24178 {
24179 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
24180 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
24181 	char trace_symbol[KSYM_SYMBOL_LEN];
24182 	const char prefix[] = "btf_trace_";
24183 	struct bpf_raw_event_map *btp;
24184 	int ret = 0, subprog = -1, i;
24185 	const struct btf_type *t;
24186 	bool conservative = true;
24187 	const char *tname, *fname;
24188 	struct btf *btf;
24189 	long addr = 0;
24190 	struct module *mod = NULL;
24191 
24192 	if (!btf_id) {
24193 		bpf_log(log, "Tracing programs must provide btf_id\n");
24194 		return -EINVAL;
24195 	}
24196 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
24197 	if (!btf) {
24198 		bpf_log(log,
24199 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
24200 		return -EINVAL;
24201 	}
24202 	t = btf_type_by_id(btf, btf_id);
24203 	if (!t) {
24204 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
24205 		return -EINVAL;
24206 	}
24207 	tname = btf_name_by_offset(btf, t->name_off);
24208 	if (!tname) {
24209 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
24210 		return -EINVAL;
24211 	}
24212 	if (tgt_prog) {
24213 		struct bpf_prog_aux *aux = tgt_prog->aux;
24214 		bool tgt_changes_pkt_data;
24215 		bool tgt_might_sleep;
24216 
24217 		if (bpf_prog_is_dev_bound(prog->aux) &&
24218 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
24219 			bpf_log(log, "Target program bound device mismatch");
24220 			return -EINVAL;
24221 		}
24222 
24223 		for (i = 0; i < aux->func_info_cnt; i++)
24224 			if (aux->func_info[i].type_id == btf_id) {
24225 				subprog = i;
24226 				break;
24227 			}
24228 		if (subprog == -1) {
24229 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
24230 			return -EINVAL;
24231 		}
24232 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
24233 			bpf_log(log,
24234 				"%s programs cannot attach to exception callback\n",
24235 				prog_extension ? "Extension" : "FENTRY/FEXIT");
24236 			return -EINVAL;
24237 		}
24238 		conservative = aux->func_info_aux[subprog].unreliable;
24239 		if (prog_extension) {
24240 			if (conservative) {
24241 				bpf_log(log,
24242 					"Cannot replace static functions\n");
24243 				return -EINVAL;
24244 			}
24245 			if (!prog->jit_requested) {
24246 				bpf_log(log,
24247 					"Extension programs should be JITed\n");
24248 				return -EINVAL;
24249 			}
24250 			tgt_changes_pkt_data = aux->func
24251 					       ? aux->func[subprog]->aux->changes_pkt_data
24252 					       : aux->changes_pkt_data;
24253 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
24254 				bpf_log(log,
24255 					"Extension program changes packet data, while original does not\n");
24256 				return -EINVAL;
24257 			}
24258 
24259 			tgt_might_sleep = aux->func
24260 					  ? aux->func[subprog]->aux->might_sleep
24261 					  : aux->might_sleep;
24262 			if (prog->aux->might_sleep && !tgt_might_sleep) {
24263 				bpf_log(log,
24264 					"Extension program may sleep, while original does not\n");
24265 				return -EINVAL;
24266 			}
24267 		}
24268 		if (!tgt_prog->jited) {
24269 			bpf_log(log, "Can attach to only JITed progs\n");
24270 			return -EINVAL;
24271 		}
24272 		if (prog_tracing) {
24273 			if (aux->attach_tracing_prog) {
24274 				/*
24275 				 * Target program is an fentry/fexit which is already attached
24276 				 * to another tracing program. More levels of nesting
24277 				 * attachment are not allowed.
24278 				 */
24279 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
24280 				return -EINVAL;
24281 			}
24282 		} else if (tgt_prog->type == prog->type) {
24283 			/*
24284 			 * To avoid potential call chain cycles, prevent attaching of a
24285 			 * program extension to another extension. It's ok to attach
24286 			 * fentry/fexit to extension program.
24287 			 */
24288 			bpf_log(log, "Cannot recursively attach\n");
24289 			return -EINVAL;
24290 		}
24291 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
24292 		    prog_extension &&
24293 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
24294 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
24295 			/* Program extensions can extend all program types
24296 			 * except fentry/fexit. The reason is the following.
24297 			 * The fentry/fexit programs are used for performance
24298 			 * analysis, stats and can be attached to any program
24299 			 * type. When extension program is replacing XDP function
24300 			 * it is necessary to allow performance analysis of all
24301 			 * functions. Both original XDP program and its program
24302 			 * extension. Hence attaching fentry/fexit to
24303 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
24304 			 * fentry/fexit was allowed it would be possible to create
24305 			 * long call chain fentry->extension->fentry->extension
24306 			 * beyond reasonable stack size. Hence extending fentry
24307 			 * is not allowed.
24308 			 */
24309 			bpf_log(log, "Cannot extend fentry/fexit\n");
24310 			return -EINVAL;
24311 		}
24312 	} else {
24313 		if (prog_extension) {
24314 			bpf_log(log, "Cannot replace kernel functions\n");
24315 			return -EINVAL;
24316 		}
24317 	}
24318 
24319 	switch (prog->expected_attach_type) {
24320 	case BPF_TRACE_RAW_TP:
24321 		if (tgt_prog) {
24322 			bpf_log(log,
24323 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
24324 			return -EINVAL;
24325 		}
24326 		if (!btf_type_is_typedef(t)) {
24327 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
24328 				btf_id);
24329 			return -EINVAL;
24330 		}
24331 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
24332 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
24333 				btf_id, tname);
24334 			return -EINVAL;
24335 		}
24336 		tname += sizeof(prefix) - 1;
24337 
24338 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
24339 		 * names. Thus using bpf_raw_event_map to get argument names.
24340 		 */
24341 		btp = bpf_get_raw_tracepoint(tname);
24342 		if (!btp)
24343 			return -EINVAL;
24344 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
24345 					trace_symbol);
24346 		bpf_put_raw_tracepoint(btp);
24347 
24348 		if (fname)
24349 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
24350 
24351 		if (!fname || ret < 0) {
24352 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
24353 				prefix, tname);
24354 			t = btf_type_by_id(btf, t->type);
24355 			if (!btf_type_is_ptr(t))
24356 				/* should never happen in valid vmlinux build */
24357 				return -EINVAL;
24358 		} else {
24359 			t = btf_type_by_id(btf, ret);
24360 			if (!btf_type_is_func(t))
24361 				/* should never happen in valid vmlinux build */
24362 				return -EINVAL;
24363 		}
24364 
24365 		t = btf_type_by_id(btf, t->type);
24366 		if (!btf_type_is_func_proto(t))
24367 			/* should never happen in valid vmlinux build */
24368 			return -EINVAL;
24369 
24370 		break;
24371 	case BPF_TRACE_ITER:
24372 		if (!btf_type_is_func(t)) {
24373 			bpf_log(log, "attach_btf_id %u is not a function\n",
24374 				btf_id);
24375 			return -EINVAL;
24376 		}
24377 		t = btf_type_by_id(btf, t->type);
24378 		if (!btf_type_is_func_proto(t))
24379 			return -EINVAL;
24380 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24381 		if (ret)
24382 			return ret;
24383 		break;
24384 	default:
24385 		if (!prog_extension)
24386 			return -EINVAL;
24387 		fallthrough;
24388 	case BPF_MODIFY_RETURN:
24389 	case BPF_LSM_MAC:
24390 	case BPF_LSM_CGROUP:
24391 	case BPF_TRACE_FENTRY:
24392 	case BPF_TRACE_FEXIT:
24393 		if (!btf_type_is_func(t)) {
24394 			bpf_log(log, "attach_btf_id %u is not a function\n",
24395 				btf_id);
24396 			return -EINVAL;
24397 		}
24398 		if (prog_extension &&
24399 		    btf_check_type_match(log, prog, btf, t))
24400 			return -EINVAL;
24401 		t = btf_type_by_id(btf, t->type);
24402 		if (!btf_type_is_func_proto(t))
24403 			return -EINVAL;
24404 
24405 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
24406 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
24407 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
24408 			return -EINVAL;
24409 
24410 		if (tgt_prog && conservative)
24411 			t = NULL;
24412 
24413 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24414 		if (ret < 0)
24415 			return ret;
24416 
24417 		if (tgt_prog) {
24418 			if (subprog == 0)
24419 				addr = (long) tgt_prog->bpf_func;
24420 			else
24421 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
24422 		} else {
24423 			if (btf_is_module(btf)) {
24424 				mod = btf_try_get_module(btf);
24425 				if (mod)
24426 					addr = find_kallsyms_symbol_value(mod, tname);
24427 				else
24428 					addr = 0;
24429 			} else {
24430 				addr = kallsyms_lookup_name(tname);
24431 			}
24432 			if (!addr) {
24433 				module_put(mod);
24434 				bpf_log(log,
24435 					"The address of function %s cannot be found\n",
24436 					tname);
24437 				return -ENOENT;
24438 			}
24439 		}
24440 
24441 		if (prog->sleepable) {
24442 			ret = -EINVAL;
24443 			switch (prog->type) {
24444 			case BPF_PROG_TYPE_TRACING:
24445 
24446 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
24447 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
24448 				 */
24449 				if (!check_non_sleepable_error_inject(btf_id) &&
24450 				    within_error_injection_list(addr))
24451 					ret = 0;
24452 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
24453 				 * in the fmodret id set with the KF_SLEEPABLE flag.
24454 				 */
24455 				else {
24456 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
24457 										prog);
24458 
24459 					if (flags && (*flags & KF_SLEEPABLE))
24460 						ret = 0;
24461 				}
24462 				break;
24463 			case BPF_PROG_TYPE_LSM:
24464 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
24465 				 * Only some of them are sleepable.
24466 				 */
24467 				if (bpf_lsm_is_sleepable_hook(btf_id))
24468 					ret = 0;
24469 				break;
24470 			default:
24471 				break;
24472 			}
24473 			if (ret) {
24474 				module_put(mod);
24475 				bpf_log(log, "%s is not sleepable\n", tname);
24476 				return ret;
24477 			}
24478 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
24479 			if (tgt_prog) {
24480 				module_put(mod);
24481 				bpf_log(log, "can't modify return codes of BPF programs\n");
24482 				return -EINVAL;
24483 			}
24484 			ret = -EINVAL;
24485 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
24486 			    !check_attach_modify_return(addr, tname))
24487 				ret = 0;
24488 			if (ret) {
24489 				module_put(mod);
24490 				bpf_log(log, "%s() is not modifiable\n", tname);
24491 				return ret;
24492 			}
24493 		}
24494 
24495 		break;
24496 	}
24497 	tgt_info->tgt_addr = addr;
24498 	tgt_info->tgt_name = tname;
24499 	tgt_info->tgt_type = t;
24500 	tgt_info->tgt_mod = mod;
24501 	return 0;
24502 }
24503 
24504 BTF_SET_START(btf_id_deny)
24505 BTF_ID_UNUSED
24506 #ifdef CONFIG_SMP
24507 BTF_ID(func, ___migrate_enable)
24508 BTF_ID(func, migrate_disable)
24509 BTF_ID(func, migrate_enable)
24510 #endif
24511 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
24512 BTF_ID(func, rcu_read_unlock_strict)
24513 #endif
24514 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
24515 BTF_ID(func, preempt_count_add)
24516 BTF_ID(func, preempt_count_sub)
24517 #endif
24518 #ifdef CONFIG_PREEMPT_RCU
24519 BTF_ID(func, __rcu_read_lock)
24520 BTF_ID(func, __rcu_read_unlock)
24521 #endif
24522 BTF_SET_END(btf_id_deny)
24523 
24524 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
24525  * Currently, we must manually list all __noreturn functions here. Once a more
24526  * robust solution is implemented, this workaround can be removed.
24527  */
24528 BTF_SET_START(noreturn_deny)
24529 #ifdef CONFIG_IA32_EMULATION
24530 BTF_ID(func, __ia32_sys_exit)
24531 BTF_ID(func, __ia32_sys_exit_group)
24532 #endif
24533 #ifdef CONFIG_KUNIT
24534 BTF_ID(func, __kunit_abort)
24535 BTF_ID(func, kunit_try_catch_throw)
24536 #endif
24537 #ifdef CONFIG_MODULES
24538 BTF_ID(func, __module_put_and_kthread_exit)
24539 #endif
24540 #ifdef CONFIG_X86_64
24541 BTF_ID(func, __x64_sys_exit)
24542 BTF_ID(func, __x64_sys_exit_group)
24543 #endif
24544 BTF_ID(func, do_exit)
24545 BTF_ID(func, do_group_exit)
24546 BTF_ID(func, kthread_complete_and_exit)
24547 BTF_ID(func, kthread_exit)
24548 BTF_ID(func, make_task_dead)
24549 BTF_SET_END(noreturn_deny)
24550 
24551 static bool can_be_sleepable(struct bpf_prog *prog)
24552 {
24553 	if (prog->type == BPF_PROG_TYPE_TRACING) {
24554 		switch (prog->expected_attach_type) {
24555 		case BPF_TRACE_FENTRY:
24556 		case BPF_TRACE_FEXIT:
24557 		case BPF_MODIFY_RETURN:
24558 		case BPF_TRACE_ITER:
24559 			return true;
24560 		default:
24561 			return false;
24562 		}
24563 	}
24564 	return prog->type == BPF_PROG_TYPE_LSM ||
24565 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
24566 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
24567 }
24568 
24569 static int check_attach_btf_id(struct bpf_verifier_env *env)
24570 {
24571 	struct bpf_prog *prog = env->prog;
24572 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
24573 	struct bpf_attach_target_info tgt_info = {};
24574 	u32 btf_id = prog->aux->attach_btf_id;
24575 	struct bpf_trampoline *tr;
24576 	int ret;
24577 	u64 key;
24578 
24579 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
24580 		if (prog->sleepable)
24581 			/* attach_btf_id checked to be zero already */
24582 			return 0;
24583 		verbose(env, "Syscall programs can only be sleepable\n");
24584 		return -EINVAL;
24585 	}
24586 
24587 	if (prog->sleepable && !can_be_sleepable(prog)) {
24588 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
24589 		return -EINVAL;
24590 	}
24591 
24592 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
24593 		return check_struct_ops_btf_id(env);
24594 
24595 	if (prog->type != BPF_PROG_TYPE_TRACING &&
24596 	    prog->type != BPF_PROG_TYPE_LSM &&
24597 	    prog->type != BPF_PROG_TYPE_EXT)
24598 		return 0;
24599 
24600 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
24601 	if (ret)
24602 		return ret;
24603 
24604 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
24605 		/* to make freplace equivalent to their targets, they need to
24606 		 * inherit env->ops and expected_attach_type for the rest of the
24607 		 * verification
24608 		 */
24609 		env->ops = bpf_verifier_ops[tgt_prog->type];
24610 		prog->expected_attach_type = tgt_prog->expected_attach_type;
24611 	}
24612 
24613 	/* store info about the attachment target that will be used later */
24614 	prog->aux->attach_func_proto = tgt_info.tgt_type;
24615 	prog->aux->attach_func_name = tgt_info.tgt_name;
24616 	prog->aux->mod = tgt_info.tgt_mod;
24617 
24618 	if (tgt_prog) {
24619 		prog->aux->saved_dst_prog_type = tgt_prog->type;
24620 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
24621 	}
24622 
24623 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
24624 		prog->aux->attach_btf_trace = true;
24625 		return 0;
24626 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
24627 		return bpf_iter_prog_supported(prog);
24628 	}
24629 
24630 	if (prog->type == BPF_PROG_TYPE_LSM) {
24631 		ret = bpf_lsm_verify_prog(&env->log, prog);
24632 		if (ret < 0)
24633 			return ret;
24634 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
24635 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
24636 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
24637 			tgt_info.tgt_name);
24638 		return -EINVAL;
24639 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
24640 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
24641 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
24642 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
24643 			tgt_info.tgt_name);
24644 		return -EINVAL;
24645 	}
24646 
24647 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
24648 	tr = bpf_trampoline_get(key, &tgt_info);
24649 	if (!tr)
24650 		return -ENOMEM;
24651 
24652 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24653 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24654 
24655 	prog->aux->dst_trampoline = tr;
24656 	return 0;
24657 }
24658 
24659 struct btf *bpf_get_btf_vmlinux(void)
24660 {
24661 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24662 		mutex_lock(&bpf_verifier_lock);
24663 		if (!btf_vmlinux)
24664 			btf_vmlinux = btf_parse_vmlinux();
24665 		mutex_unlock(&bpf_verifier_lock);
24666 	}
24667 	return btf_vmlinux;
24668 }
24669 
24670 /*
24671  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24672  * this case expect that every file descriptor in the array is either a map or
24673  * a BTF. Everything else is considered to be trash.
24674  */
24675 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24676 {
24677 	struct bpf_map *map;
24678 	struct btf *btf;
24679 	CLASS(fd, f)(fd);
24680 	int err;
24681 
24682 	map = __bpf_map_get(f);
24683 	if (!IS_ERR(map)) {
24684 		err = __add_used_map(env, map);
24685 		if (err < 0)
24686 			return err;
24687 		return 0;
24688 	}
24689 
24690 	btf = __btf_get_by_fd(f);
24691 	if (!IS_ERR(btf)) {
24692 		err = __add_used_btf(env, btf);
24693 		if (err < 0)
24694 			return err;
24695 		return 0;
24696 	}
24697 
24698 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24699 	return PTR_ERR(map);
24700 }
24701 
24702 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24703 {
24704 	size_t size = sizeof(int);
24705 	int ret;
24706 	int fd;
24707 	u32 i;
24708 
24709 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24710 
24711 	/*
24712 	 * The only difference between old (no fd_array_cnt is given) and new
24713 	 * APIs is that in the latter case the fd_array is expected to be
24714 	 * continuous and is scanned for map fds right away
24715 	 */
24716 	if (!attr->fd_array_cnt)
24717 		return 0;
24718 
24719 	/* Check for integer overflow */
24720 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24721 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24722 		return -EINVAL;
24723 	}
24724 
24725 	for (i = 0; i < attr->fd_array_cnt; i++) {
24726 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24727 			return -EFAULT;
24728 
24729 		ret = add_fd_from_fd_array(env, fd);
24730 		if (ret)
24731 			return ret;
24732 	}
24733 
24734 	return 0;
24735 }
24736 
24737 /* Each field is a register bitmask */
24738 struct insn_live_regs {
24739 	u16 use;	/* registers read by instruction */
24740 	u16 def;	/* registers written by instruction */
24741 	u16 in;		/* registers that may be alive before instruction */
24742 	u16 out;	/* registers that may be alive after instruction */
24743 };
24744 
24745 /* Bitmask with 1s for all caller saved registers */
24746 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24747 
24748 /* Compute info->{use,def} fields for the instruction */
24749 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24750 				   struct bpf_insn *insn,
24751 				   struct insn_live_regs *info)
24752 {
24753 	struct call_summary cs;
24754 	u8 class = BPF_CLASS(insn->code);
24755 	u8 code = BPF_OP(insn->code);
24756 	u8 mode = BPF_MODE(insn->code);
24757 	u16 src = BIT(insn->src_reg);
24758 	u16 dst = BIT(insn->dst_reg);
24759 	u16 r0  = BIT(0);
24760 	u16 def = 0;
24761 	u16 use = 0xffff;
24762 
24763 	switch (class) {
24764 	case BPF_LD:
24765 		switch (mode) {
24766 		case BPF_IMM:
24767 			if (BPF_SIZE(insn->code) == BPF_DW) {
24768 				def = dst;
24769 				use = 0;
24770 			}
24771 			break;
24772 		case BPF_LD | BPF_ABS:
24773 		case BPF_LD | BPF_IND:
24774 			/* stick with defaults */
24775 			break;
24776 		}
24777 		break;
24778 	case BPF_LDX:
24779 		switch (mode) {
24780 		case BPF_MEM:
24781 		case BPF_MEMSX:
24782 			def = dst;
24783 			use = src;
24784 			break;
24785 		}
24786 		break;
24787 	case BPF_ST:
24788 		switch (mode) {
24789 		case BPF_MEM:
24790 			def = 0;
24791 			use = dst;
24792 			break;
24793 		}
24794 		break;
24795 	case BPF_STX:
24796 		switch (mode) {
24797 		case BPF_MEM:
24798 			def = 0;
24799 			use = dst | src;
24800 			break;
24801 		case BPF_ATOMIC:
24802 			switch (insn->imm) {
24803 			case BPF_CMPXCHG:
24804 				use = r0 | dst | src;
24805 				def = r0;
24806 				break;
24807 			case BPF_LOAD_ACQ:
24808 				def = dst;
24809 				use = src;
24810 				break;
24811 			case BPF_STORE_REL:
24812 				def = 0;
24813 				use = dst | src;
24814 				break;
24815 			default:
24816 				use = dst | src;
24817 				if (insn->imm & BPF_FETCH)
24818 					def = src;
24819 				else
24820 					def = 0;
24821 			}
24822 			break;
24823 		}
24824 		break;
24825 	case BPF_ALU:
24826 	case BPF_ALU64:
24827 		switch (code) {
24828 		case BPF_END:
24829 			use = dst;
24830 			def = dst;
24831 			break;
24832 		case BPF_MOV:
24833 			def = dst;
24834 			if (BPF_SRC(insn->code) == BPF_K)
24835 				use = 0;
24836 			else
24837 				use = src;
24838 			break;
24839 		default:
24840 			def = dst;
24841 			if (BPF_SRC(insn->code) == BPF_K)
24842 				use = dst;
24843 			else
24844 				use = dst | src;
24845 		}
24846 		break;
24847 	case BPF_JMP:
24848 	case BPF_JMP32:
24849 		switch (code) {
24850 		case BPF_JA:
24851 		case BPF_JCOND:
24852 			def = 0;
24853 			use = 0;
24854 			break;
24855 		case BPF_EXIT:
24856 			def = 0;
24857 			use = r0;
24858 			break;
24859 		case BPF_CALL:
24860 			def = ALL_CALLER_SAVED_REGS;
24861 			use = def & ~BIT(BPF_REG_0);
24862 			if (get_call_summary(env, insn, &cs))
24863 				use = GENMASK(cs.num_params, 1);
24864 			break;
24865 		default:
24866 			def = 0;
24867 			if (BPF_SRC(insn->code) == BPF_K)
24868 				use = dst;
24869 			else
24870 				use = dst | src;
24871 		}
24872 		break;
24873 	}
24874 
24875 	info->def = def;
24876 	info->use = use;
24877 }
24878 
24879 /* Compute may-live registers after each instruction in the program.
24880  * The register is live after the instruction I if it is read by some
24881  * instruction S following I during program execution and is not
24882  * overwritten between I and S.
24883  *
24884  * Store result in env->insn_aux_data[i].live_regs.
24885  */
24886 static int compute_live_registers(struct bpf_verifier_env *env)
24887 {
24888 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24889 	struct bpf_insn *insns = env->prog->insnsi;
24890 	struct insn_live_regs *state;
24891 	int insn_cnt = env->prog->len;
24892 	int err = 0, i, j;
24893 	bool changed;
24894 
24895 	/* Use the following algorithm:
24896 	 * - define the following:
24897 	 *   - I.use : a set of all registers read by instruction I;
24898 	 *   - I.def : a set of all registers written by instruction I;
24899 	 *   - I.in  : a set of all registers that may be alive before I execution;
24900 	 *   - I.out : a set of all registers that may be alive after I execution;
24901 	 *   - insn_successors(I): a set of instructions S that might immediately
24902 	 *                         follow I for some program execution;
24903 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24904 	 * - visit each instruction in a postorder and update
24905 	 *   state[i].in, state[i].out as follows:
24906 	 *
24907 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24908 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24909 	 *
24910 	 *   (where U stands for set union, / stands for set difference)
24911 	 * - repeat the computation while {in,out} fields changes for
24912 	 *   any instruction.
24913 	 */
24914 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24915 	if (!state) {
24916 		err = -ENOMEM;
24917 		goto out;
24918 	}
24919 
24920 	for (i = 0; i < insn_cnt; ++i)
24921 		compute_insn_live_regs(env, &insns[i], &state[i]);
24922 
24923 	changed = true;
24924 	while (changed) {
24925 		changed = false;
24926 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24927 			int insn_idx = env->cfg.insn_postorder[i];
24928 			struct insn_live_regs *live = &state[insn_idx];
24929 			struct bpf_iarray *succ;
24930 			u16 new_out = 0;
24931 			u16 new_in = 0;
24932 
24933 			succ = bpf_insn_successors(env, insn_idx);
24934 			for (int s = 0; s < succ->cnt; ++s)
24935 				new_out |= state[succ->items[s]].in;
24936 			new_in = (new_out & ~live->def) | live->use;
24937 			if (new_out != live->out || new_in != live->in) {
24938 				live->in = new_in;
24939 				live->out = new_out;
24940 				changed = true;
24941 			}
24942 		}
24943 	}
24944 
24945 	for (i = 0; i < insn_cnt; ++i)
24946 		insn_aux[i].live_regs_before = state[i].in;
24947 
24948 	if (env->log.level & BPF_LOG_LEVEL2) {
24949 		verbose(env, "Live regs before insn:\n");
24950 		for (i = 0; i < insn_cnt; ++i) {
24951 			if (env->insn_aux_data[i].scc)
24952 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24953 			else
24954 				verbose(env, "    ");
24955 			verbose(env, "%3d: ", i);
24956 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24957 				if (insn_aux[i].live_regs_before & BIT(j))
24958 					verbose(env, "%d", j);
24959 				else
24960 					verbose(env, ".");
24961 			verbose(env, " ");
24962 			verbose_insn(env, &insns[i]);
24963 			if (bpf_is_ldimm64(&insns[i]))
24964 				i++;
24965 		}
24966 	}
24967 
24968 out:
24969 	kvfree(state);
24970 	return err;
24971 }
24972 
24973 /*
24974  * Compute strongly connected components (SCCs) on the CFG.
24975  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24976  * If instruction is a sole member of its SCC and there are no self edges,
24977  * assign it SCC number of zero.
24978  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24979  */
24980 static int compute_scc(struct bpf_verifier_env *env)
24981 {
24982 	const u32 NOT_ON_STACK = U32_MAX;
24983 
24984 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24985 	const u32 insn_cnt = env->prog->len;
24986 	int stack_sz, dfs_sz, err = 0;
24987 	u32 *stack, *pre, *low, *dfs;
24988 	u32 i, j, t, w;
24989 	u32 next_preorder_num;
24990 	u32 next_scc_id;
24991 	bool assign_scc;
24992 	struct bpf_iarray *succ;
24993 
24994 	next_preorder_num = 1;
24995 	next_scc_id = 1;
24996 	/*
24997 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24998 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24999 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
25000 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
25001 	 */
25002 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25003 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25004 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
25005 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
25006 	if (!stack || !pre || !low || !dfs) {
25007 		err = -ENOMEM;
25008 		goto exit;
25009 	}
25010 	/*
25011 	 * References:
25012 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
25013 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
25014 	 *
25015 	 * The algorithm maintains the following invariant:
25016 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
25017 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
25018 	 *
25019 	 * Consequently:
25020 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
25021 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
25022 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
25023 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
25024 	 *   and 'v' can be considered the root of some SCC.
25025 	 *
25026 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
25027 	 *
25028 	 *    NOT_ON_STACK = insn_cnt + 1
25029 	 *    pre = [0] * insn_cnt
25030 	 *    low = [0] * insn_cnt
25031 	 *    scc = [0] * insn_cnt
25032 	 *    stack = []
25033 	 *
25034 	 *    next_preorder_num = 1
25035 	 *    next_scc_id = 1
25036 	 *
25037 	 *    def recur(w):
25038 	 *        nonlocal next_preorder_num
25039 	 *        nonlocal next_scc_id
25040 	 *
25041 	 *        pre[w] = next_preorder_num
25042 	 *        low[w] = next_preorder_num
25043 	 *        next_preorder_num += 1
25044 	 *        stack.append(w)
25045 	 *        for s in successors(w):
25046 	 *            # Note: for classic algorithm the block below should look as:
25047 	 *            #
25048 	 *            # if pre[s] == 0:
25049 	 *            #     recur(s)
25050 	 *            #	    low[w] = min(low[w], low[s])
25051 	 *            # elif low[s] != NOT_ON_STACK:
25052 	 *            #     low[w] = min(low[w], pre[s])
25053 	 *            #
25054 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
25055 	 *            # does not break the invariant and makes itartive version of the algorithm
25056 	 *            # simpler. See 'Algorithm #3' from [2].
25057 	 *
25058 	 *            # 's' not yet visited
25059 	 *            if pre[s] == 0:
25060 	 *                recur(s)
25061 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
25062 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
25063 	 *            # so 'min' would be a noop.
25064 	 *            low[w] = min(low[w], low[s])
25065 	 *
25066 	 *        if low[w] == pre[w]:
25067 	 *            # 'w' is the root of an SCC, pop all vertices
25068 	 *            # below 'w' on stack and assign same SCC to them.
25069 	 *            while True:
25070 	 *                t = stack.pop()
25071 	 *                low[t] = NOT_ON_STACK
25072 	 *                scc[t] = next_scc_id
25073 	 *                if t == w:
25074 	 *                    break
25075 	 *            next_scc_id += 1
25076 	 *
25077 	 *    for i in range(0, insn_cnt):
25078 	 *        if pre[i] == 0:
25079 	 *            recur(i)
25080 	 *
25081 	 * Below implementation replaces explicit recursion with array 'dfs'.
25082 	 */
25083 	for (i = 0; i < insn_cnt; i++) {
25084 		if (pre[i])
25085 			continue;
25086 		stack_sz = 0;
25087 		dfs_sz = 1;
25088 		dfs[0] = i;
25089 dfs_continue:
25090 		while (dfs_sz) {
25091 			w = dfs[dfs_sz - 1];
25092 			if (pre[w] == 0) {
25093 				low[w] = next_preorder_num;
25094 				pre[w] = next_preorder_num;
25095 				next_preorder_num++;
25096 				stack[stack_sz++] = w;
25097 			}
25098 			/* Visit 'w' successors */
25099 			succ = bpf_insn_successors(env, w);
25100 			for (j = 0; j < succ->cnt; ++j) {
25101 				if (pre[succ->items[j]]) {
25102 					low[w] = min(low[w], low[succ->items[j]]);
25103 				} else {
25104 					dfs[dfs_sz++] = succ->items[j];
25105 					goto dfs_continue;
25106 				}
25107 			}
25108 			/*
25109 			 * Preserve the invariant: if some vertex above in the stack
25110 			 * is reachable from 'w', keep 'w' on the stack.
25111 			 */
25112 			if (low[w] < pre[w]) {
25113 				dfs_sz--;
25114 				goto dfs_continue;
25115 			}
25116 			/*
25117 			 * Assign SCC number only if component has two or more elements,
25118 			 * or if component has a self reference, or if instruction is a
25119 			 * callback calling function (implicit loop).
25120 			 */
25121 			assign_scc = stack[stack_sz - 1] != w;	/* two or more elements? */
25122 			for (j = 0; j < succ->cnt; ++j) {	/* self reference? */
25123 				if (succ->items[j] == w) {
25124 					assign_scc = true;
25125 					break;
25126 				}
25127 			}
25128 			if (bpf_calls_callback(env, w)) /* implicit loop? */
25129 				assign_scc = true;
25130 			/* Pop component elements from stack */
25131 			do {
25132 				t = stack[--stack_sz];
25133 				low[t] = NOT_ON_STACK;
25134 				if (assign_scc)
25135 					aux[t].scc = next_scc_id;
25136 			} while (t != w);
25137 			if (assign_scc)
25138 				next_scc_id++;
25139 			dfs_sz--;
25140 		}
25141 	}
25142 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
25143 	if (!env->scc_info) {
25144 		err = -ENOMEM;
25145 		goto exit;
25146 	}
25147 	env->scc_cnt = next_scc_id;
25148 exit:
25149 	kvfree(stack);
25150 	kvfree(pre);
25151 	kvfree(low);
25152 	kvfree(dfs);
25153 	return err;
25154 }
25155 
25156 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
25157 {
25158 	u64 start_time = ktime_get_ns();
25159 	struct bpf_verifier_env *env;
25160 	int i, len, ret = -EINVAL, err;
25161 	u32 log_true_size;
25162 	bool is_priv;
25163 
25164 	BTF_TYPE_EMIT(enum bpf_features);
25165 
25166 	/* no program is valid */
25167 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
25168 		return -EINVAL;
25169 
25170 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
25171 	 * allocate/free it every time bpf_check() is called
25172 	 */
25173 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
25174 	if (!env)
25175 		return -ENOMEM;
25176 
25177 	env->bt.env = env;
25178 
25179 	len = (*prog)->len;
25180 	env->insn_aux_data =
25181 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
25182 	ret = -ENOMEM;
25183 	if (!env->insn_aux_data)
25184 		goto err_free_env;
25185 	for (i = 0; i < len; i++)
25186 		env->insn_aux_data[i].orig_idx = i;
25187 	env->succ = iarray_realloc(NULL, 2);
25188 	if (!env->succ)
25189 		goto err_free_env;
25190 	env->prog = *prog;
25191 	env->ops = bpf_verifier_ops[env->prog->type];
25192 
25193 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
25194 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
25195 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
25196 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
25197 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
25198 
25199 	bpf_get_btf_vmlinux();
25200 
25201 	/* grab the mutex to protect few globals used by verifier */
25202 	if (!is_priv)
25203 		mutex_lock(&bpf_verifier_lock);
25204 
25205 	/* user could have requested verbose verifier output
25206 	 * and supplied buffer to store the verification trace
25207 	 */
25208 	ret = bpf_vlog_init(&env->log, attr->log_level,
25209 			    (char __user *) (unsigned long) attr->log_buf,
25210 			    attr->log_size);
25211 	if (ret)
25212 		goto err_unlock;
25213 
25214 	ret = process_fd_array(env, attr, uattr);
25215 	if (ret)
25216 		goto skip_full_check;
25217 
25218 	mark_verifier_state_clean(env);
25219 
25220 	if (IS_ERR(btf_vmlinux)) {
25221 		/* Either gcc or pahole or kernel are broken. */
25222 		verbose(env, "in-kernel BTF is malformed\n");
25223 		ret = PTR_ERR(btf_vmlinux);
25224 		goto skip_full_check;
25225 	}
25226 
25227 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
25228 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
25229 		env->strict_alignment = true;
25230 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
25231 		env->strict_alignment = false;
25232 
25233 	if (is_priv)
25234 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
25235 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
25236 
25237 	env->explored_states = kvcalloc(state_htab_size(env),
25238 				       sizeof(struct list_head),
25239 				       GFP_KERNEL_ACCOUNT);
25240 	ret = -ENOMEM;
25241 	if (!env->explored_states)
25242 		goto skip_full_check;
25243 
25244 	for (i = 0; i < state_htab_size(env); i++)
25245 		INIT_LIST_HEAD(&env->explored_states[i]);
25246 	INIT_LIST_HEAD(&env->free_list);
25247 
25248 	ret = check_btf_info_early(env, attr, uattr);
25249 	if (ret < 0)
25250 		goto skip_full_check;
25251 
25252 	ret = add_subprog_and_kfunc(env);
25253 	if (ret < 0)
25254 		goto skip_full_check;
25255 
25256 	ret = check_subprogs(env);
25257 	if (ret < 0)
25258 		goto skip_full_check;
25259 
25260 	ret = check_btf_info(env, attr, uattr);
25261 	if (ret < 0)
25262 		goto skip_full_check;
25263 
25264 	ret = resolve_pseudo_ldimm64(env);
25265 	if (ret < 0)
25266 		goto skip_full_check;
25267 
25268 	if (bpf_prog_is_offloaded(env->prog->aux)) {
25269 		ret = bpf_prog_offload_verifier_prep(env->prog);
25270 		if (ret)
25271 			goto skip_full_check;
25272 	}
25273 
25274 	ret = check_cfg(env);
25275 	if (ret < 0)
25276 		goto skip_full_check;
25277 
25278 	ret = compute_postorder(env);
25279 	if (ret < 0)
25280 		goto skip_full_check;
25281 
25282 	ret = bpf_stack_liveness_init(env);
25283 	if (ret)
25284 		goto skip_full_check;
25285 
25286 	ret = check_attach_btf_id(env);
25287 	if (ret)
25288 		goto skip_full_check;
25289 
25290 	ret = compute_scc(env);
25291 	if (ret < 0)
25292 		goto skip_full_check;
25293 
25294 	ret = compute_live_registers(env);
25295 	if (ret < 0)
25296 		goto skip_full_check;
25297 
25298 	ret = mark_fastcall_patterns(env);
25299 	if (ret < 0)
25300 		goto skip_full_check;
25301 
25302 	ret = do_check_main(env);
25303 	ret = ret ?: do_check_subprogs(env);
25304 
25305 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
25306 		ret = bpf_prog_offload_finalize(env);
25307 
25308 skip_full_check:
25309 	kvfree(env->explored_states);
25310 
25311 	/* might decrease stack depth, keep it before passes that
25312 	 * allocate additional slots.
25313 	 */
25314 	if (ret == 0)
25315 		ret = remove_fastcall_spills_fills(env);
25316 
25317 	if (ret == 0)
25318 		ret = check_max_stack_depth(env);
25319 
25320 	/* instruction rewrites happen after this point */
25321 	if (ret == 0)
25322 		ret = optimize_bpf_loop(env);
25323 
25324 	if (is_priv) {
25325 		if (ret == 0)
25326 			opt_hard_wire_dead_code_branches(env);
25327 		if (ret == 0)
25328 			ret = opt_remove_dead_code(env);
25329 		if (ret == 0)
25330 			ret = opt_remove_nops(env);
25331 	} else {
25332 		if (ret == 0)
25333 			sanitize_dead_code(env);
25334 	}
25335 
25336 	if (ret == 0)
25337 		/* program is valid, convert *(u32*)(ctx + off) accesses */
25338 		ret = convert_ctx_accesses(env);
25339 
25340 	if (ret == 0)
25341 		ret = do_misc_fixups(env);
25342 
25343 	/* do 32-bit optimization after insn patching has done so those patched
25344 	 * insns could be handled correctly.
25345 	 */
25346 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
25347 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
25348 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
25349 								     : false;
25350 	}
25351 
25352 	if (ret == 0)
25353 		ret = fixup_call_args(env);
25354 
25355 	env->verification_time = ktime_get_ns() - start_time;
25356 	print_verification_stats(env);
25357 	env->prog->aux->verified_insns = env->insn_processed;
25358 
25359 	/* preserve original error even if log finalization is successful */
25360 	err = bpf_vlog_finalize(&env->log, &log_true_size);
25361 	if (err)
25362 		ret = err;
25363 
25364 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
25365 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
25366 				  &log_true_size, sizeof(log_true_size))) {
25367 		ret = -EFAULT;
25368 		goto err_release_maps;
25369 	}
25370 
25371 	if (ret)
25372 		goto err_release_maps;
25373 
25374 	if (env->used_map_cnt) {
25375 		/* if program passed verifier, update used_maps in bpf_prog_info */
25376 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
25377 							  sizeof(env->used_maps[0]),
25378 							  GFP_KERNEL_ACCOUNT);
25379 
25380 		if (!env->prog->aux->used_maps) {
25381 			ret = -ENOMEM;
25382 			goto err_release_maps;
25383 		}
25384 
25385 		memcpy(env->prog->aux->used_maps, env->used_maps,
25386 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
25387 		env->prog->aux->used_map_cnt = env->used_map_cnt;
25388 	}
25389 	if (env->used_btf_cnt) {
25390 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
25391 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
25392 							  sizeof(env->used_btfs[0]),
25393 							  GFP_KERNEL_ACCOUNT);
25394 		if (!env->prog->aux->used_btfs) {
25395 			ret = -ENOMEM;
25396 			goto err_release_maps;
25397 		}
25398 
25399 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
25400 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
25401 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
25402 	}
25403 	if (env->used_map_cnt || env->used_btf_cnt) {
25404 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
25405 		 * bpf_ld_imm64 instructions
25406 		 */
25407 		convert_pseudo_ld_imm64(env);
25408 	}
25409 
25410 	adjust_btf_func(env);
25411 
25412 err_release_maps:
25413 	if (ret)
25414 		release_insn_arrays(env);
25415 	if (!env->prog->aux->used_maps)
25416 		/* if we didn't copy map pointers into bpf_prog_info, release
25417 		 * them now. Otherwise free_used_maps() will release them.
25418 		 */
25419 		release_maps(env);
25420 	if (!env->prog->aux->used_btfs)
25421 		release_btfs(env);
25422 
25423 	/* extension progs temporarily inherit the attach_type of their targets
25424 	   for verification purposes, so set it back to zero before returning
25425 	 */
25426 	if (env->prog->type == BPF_PROG_TYPE_EXT)
25427 		env->prog->expected_attach_type = 0;
25428 
25429 	*prog = env->prog;
25430 
25431 	module_put(env->attach_btf_mod);
25432 err_unlock:
25433 	if (!is_priv)
25434 		mutex_unlock(&bpf_verifier_lock);
25435 	clear_insn_aux_data(env, 0, env->prog->len);
25436 	vfree(env->insn_aux_data);
25437 err_free_env:
25438 	bpf_stack_liveness_free(env);
25439 	kvfree(env->cfg.insn_postorder);
25440 	kvfree(env->scc_info);
25441 	kvfree(env->succ);
25442 	kvfree(env->gotox_tmp_buf);
25443 	kvfree(env);
25444 	return ret;
25445 }
25446