xref: /openbmc/linux/kernel/bpf/verifier.c (revision c1e0230e)
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 <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_callback_calling_kfunc(u32 btf_id);
546 
547 static bool is_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_timer_set_callback ||
551 	       func_id == BPF_FUNC_find_vma ||
552 	       func_id == BPF_FUNC_loop ||
553 	       func_id == BPF_FUNC_user_ringbuf_drain;
554 }
555 
556 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
557 {
558 	return func_id == BPF_FUNC_timer_set_callback;
559 }
560 
561 static bool is_storage_get_function(enum bpf_func_id func_id)
562 {
563 	return func_id == BPF_FUNC_sk_storage_get ||
564 	       func_id == BPF_FUNC_inode_storage_get ||
565 	       func_id == BPF_FUNC_task_storage_get ||
566 	       func_id == BPF_FUNC_cgrp_storage_get;
567 }
568 
569 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
570 					const struct bpf_map *map)
571 {
572 	int ref_obj_uses = 0;
573 
574 	if (is_ptr_cast_function(func_id))
575 		ref_obj_uses++;
576 	if (is_acquire_function(func_id, map))
577 		ref_obj_uses++;
578 	if (is_dynptr_ref_function(func_id))
579 		ref_obj_uses++;
580 
581 	return ref_obj_uses > 1;
582 }
583 
584 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
585 {
586 	return BPF_CLASS(insn->code) == BPF_STX &&
587 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
588 	       insn->imm == BPF_CMPXCHG;
589 }
590 
591 /* string representation of 'enum bpf_reg_type'
592  *
593  * Note that reg_type_str() can not appear more than once in a single verbose()
594  * statement.
595  */
596 static const char *reg_type_str(struct bpf_verifier_env *env,
597 				enum bpf_reg_type type)
598 {
599 	char postfix[16] = {0}, prefix[64] = {0};
600 	static const char * const str[] = {
601 		[NOT_INIT]		= "?",
602 		[SCALAR_VALUE]		= "scalar",
603 		[PTR_TO_CTX]		= "ctx",
604 		[CONST_PTR_TO_MAP]	= "map_ptr",
605 		[PTR_TO_MAP_VALUE]	= "map_value",
606 		[PTR_TO_STACK]		= "fp",
607 		[PTR_TO_PACKET]		= "pkt",
608 		[PTR_TO_PACKET_META]	= "pkt_meta",
609 		[PTR_TO_PACKET_END]	= "pkt_end",
610 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
611 		[PTR_TO_SOCKET]		= "sock",
612 		[PTR_TO_SOCK_COMMON]	= "sock_common",
613 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
614 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
615 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
616 		[PTR_TO_BTF_ID]		= "ptr_",
617 		[PTR_TO_MEM]		= "mem",
618 		[PTR_TO_BUF]		= "buf",
619 		[PTR_TO_FUNC]		= "func",
620 		[PTR_TO_MAP_KEY]	= "map_key",
621 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
622 	};
623 
624 	if (type & PTR_MAYBE_NULL) {
625 		if (base_type(type) == PTR_TO_BTF_ID)
626 			strncpy(postfix, "or_null_", 16);
627 		else
628 			strncpy(postfix, "_or_null", 16);
629 	}
630 
631 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
632 		 type & MEM_RDONLY ? "rdonly_" : "",
633 		 type & MEM_RINGBUF ? "ringbuf_" : "",
634 		 type & MEM_USER ? "user_" : "",
635 		 type & MEM_PERCPU ? "percpu_" : "",
636 		 type & MEM_RCU ? "rcu_" : "",
637 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
638 		 type & PTR_TRUSTED ? "trusted_" : ""
639 	);
640 
641 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
642 		 prefix, str[base_type(type)], postfix);
643 	return env->tmp_str_buf;
644 }
645 
646 static char slot_type_char[] = {
647 	[STACK_INVALID]	= '?',
648 	[STACK_SPILL]	= 'r',
649 	[STACK_MISC]	= 'm',
650 	[STACK_ZERO]	= '0',
651 	[STACK_DYNPTR]	= 'd',
652 	[STACK_ITER]	= 'i',
653 };
654 
655 static void print_liveness(struct bpf_verifier_env *env,
656 			   enum bpf_reg_liveness live)
657 {
658 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
659 	    verbose(env, "_");
660 	if (live & REG_LIVE_READ)
661 		verbose(env, "r");
662 	if (live & REG_LIVE_WRITTEN)
663 		verbose(env, "w");
664 	if (live & REG_LIVE_DONE)
665 		verbose(env, "D");
666 }
667 
668 static int __get_spi(s32 off)
669 {
670 	return (-off - 1) / BPF_REG_SIZE;
671 }
672 
673 static struct bpf_func_state *func(struct bpf_verifier_env *env,
674 				   const struct bpf_reg_state *reg)
675 {
676 	struct bpf_verifier_state *cur = env->cur_state;
677 
678 	return cur->frame[reg->frameno];
679 }
680 
681 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
682 {
683        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
684 
685        /* We need to check that slots between [spi - nr_slots + 1, spi] are
686 	* within [0, allocated_stack).
687 	*
688 	* Please note that the spi grows downwards. For example, a dynptr
689 	* takes the size of two stack slots; the first slot will be at
690 	* spi and the second slot will be at spi - 1.
691 	*/
692        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
693 }
694 
695 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
696 			          const char *obj_kind, int nr_slots)
697 {
698 	int off, spi;
699 
700 	if (!tnum_is_const(reg->var_off)) {
701 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
702 		return -EINVAL;
703 	}
704 
705 	off = reg->off + reg->var_off.value;
706 	if (off % BPF_REG_SIZE) {
707 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
708 		return -EINVAL;
709 	}
710 
711 	spi = __get_spi(off);
712 	if (spi + 1 < nr_slots) {
713 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
714 		return -EINVAL;
715 	}
716 
717 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
718 		return -ERANGE;
719 	return spi;
720 }
721 
722 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
723 {
724 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
725 }
726 
727 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
728 {
729 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
730 }
731 
732 static const char *btf_type_name(const struct btf *btf, u32 id)
733 {
734 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
735 }
736 
737 static const char *dynptr_type_str(enum bpf_dynptr_type type)
738 {
739 	switch (type) {
740 	case BPF_DYNPTR_TYPE_LOCAL:
741 		return "local";
742 	case BPF_DYNPTR_TYPE_RINGBUF:
743 		return "ringbuf";
744 	case BPF_DYNPTR_TYPE_SKB:
745 		return "skb";
746 	case BPF_DYNPTR_TYPE_XDP:
747 		return "xdp";
748 	case BPF_DYNPTR_TYPE_INVALID:
749 		return "<invalid>";
750 	default:
751 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
752 		return "<unknown>";
753 	}
754 }
755 
756 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
757 {
758 	if (!btf || btf_id == 0)
759 		return "<invalid>";
760 
761 	/* we already validated that type is valid and has conforming name */
762 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
763 }
764 
765 static const char *iter_state_str(enum bpf_iter_state state)
766 {
767 	switch (state) {
768 	case BPF_ITER_STATE_ACTIVE:
769 		return "active";
770 	case BPF_ITER_STATE_DRAINED:
771 		return "drained";
772 	case BPF_ITER_STATE_INVALID:
773 		return "<invalid>";
774 	default:
775 		WARN_ONCE(1, "unknown iter state %d\n", state);
776 		return "<unknown>";
777 	}
778 }
779 
780 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
781 {
782 	env->scratched_regs |= 1U << regno;
783 }
784 
785 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
786 {
787 	env->scratched_stack_slots |= 1ULL << spi;
788 }
789 
790 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
791 {
792 	return (env->scratched_regs >> regno) & 1;
793 }
794 
795 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
796 {
797 	return (env->scratched_stack_slots >> regno) & 1;
798 }
799 
800 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
801 {
802 	return env->scratched_regs || env->scratched_stack_slots;
803 }
804 
805 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
806 {
807 	env->scratched_regs = 0U;
808 	env->scratched_stack_slots = 0ULL;
809 }
810 
811 /* Used for printing the entire verifier state. */
812 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
813 {
814 	env->scratched_regs = ~0U;
815 	env->scratched_stack_slots = ~0ULL;
816 }
817 
818 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
819 {
820 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
821 	case DYNPTR_TYPE_LOCAL:
822 		return BPF_DYNPTR_TYPE_LOCAL;
823 	case DYNPTR_TYPE_RINGBUF:
824 		return BPF_DYNPTR_TYPE_RINGBUF;
825 	case DYNPTR_TYPE_SKB:
826 		return BPF_DYNPTR_TYPE_SKB;
827 	case DYNPTR_TYPE_XDP:
828 		return BPF_DYNPTR_TYPE_XDP;
829 	default:
830 		return BPF_DYNPTR_TYPE_INVALID;
831 	}
832 }
833 
834 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
835 {
836 	switch (type) {
837 	case BPF_DYNPTR_TYPE_LOCAL:
838 		return DYNPTR_TYPE_LOCAL;
839 	case BPF_DYNPTR_TYPE_RINGBUF:
840 		return DYNPTR_TYPE_RINGBUF;
841 	case BPF_DYNPTR_TYPE_SKB:
842 		return DYNPTR_TYPE_SKB;
843 	case BPF_DYNPTR_TYPE_XDP:
844 		return DYNPTR_TYPE_XDP;
845 	default:
846 		return 0;
847 	}
848 }
849 
850 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
851 {
852 	return type == BPF_DYNPTR_TYPE_RINGBUF;
853 }
854 
855 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
856 			      enum bpf_dynptr_type type,
857 			      bool first_slot, int dynptr_id);
858 
859 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
860 				struct bpf_reg_state *reg);
861 
862 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
863 				   struct bpf_reg_state *sreg1,
864 				   struct bpf_reg_state *sreg2,
865 				   enum bpf_dynptr_type type)
866 {
867 	int id = ++env->id_gen;
868 
869 	__mark_dynptr_reg(sreg1, type, true, id);
870 	__mark_dynptr_reg(sreg2, type, false, id);
871 }
872 
873 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
874 			       struct bpf_reg_state *reg,
875 			       enum bpf_dynptr_type type)
876 {
877 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
878 }
879 
880 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
881 				        struct bpf_func_state *state, int spi);
882 
883 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
884 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
885 {
886 	struct bpf_func_state *state = func(env, reg);
887 	enum bpf_dynptr_type type;
888 	int spi, i, err;
889 
890 	spi = dynptr_get_spi(env, reg);
891 	if (spi < 0)
892 		return spi;
893 
894 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
895 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
896 	 * to ensure that for the following example:
897 	 *	[d1][d1][d2][d2]
898 	 * spi    3   2   1   0
899 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
900 	 * case they do belong to same dynptr, second call won't see slot_type
901 	 * as STACK_DYNPTR and will simply skip destruction.
902 	 */
903 	err = destroy_if_dynptr_stack_slot(env, state, spi);
904 	if (err)
905 		return err;
906 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
907 	if (err)
908 		return err;
909 
910 	for (i = 0; i < BPF_REG_SIZE; i++) {
911 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
912 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
913 	}
914 
915 	type = arg_to_dynptr_type(arg_type);
916 	if (type == BPF_DYNPTR_TYPE_INVALID)
917 		return -EINVAL;
918 
919 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
920 			       &state->stack[spi - 1].spilled_ptr, type);
921 
922 	if (dynptr_type_refcounted(type)) {
923 		/* The id is used to track proper releasing */
924 		int id;
925 
926 		if (clone_ref_obj_id)
927 			id = clone_ref_obj_id;
928 		else
929 			id = acquire_reference_state(env, insn_idx);
930 
931 		if (id < 0)
932 			return id;
933 
934 		state->stack[spi].spilled_ptr.ref_obj_id = id;
935 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
936 	}
937 
938 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
939 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
940 
941 	return 0;
942 }
943 
944 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
945 {
946 	int i;
947 
948 	for (i = 0; i < BPF_REG_SIZE; i++) {
949 		state->stack[spi].slot_type[i] = STACK_INVALID;
950 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
951 	}
952 
953 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
954 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
955 
956 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
957 	 *
958 	 * While we don't allow reading STACK_INVALID, it is still possible to
959 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
960 	 * helpers or insns can do partial read of that part without failing,
961 	 * but check_stack_range_initialized, check_stack_read_var_off, and
962 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
963 	 * the slot conservatively. Hence we need to prevent those liveness
964 	 * marking walks.
965 	 *
966 	 * This was not a problem before because STACK_INVALID is only set by
967 	 * default (where the default reg state has its reg->parent as NULL), or
968 	 * in clean_live_states after REG_LIVE_DONE (at which point
969 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
970 	 * verifier state exploration (like we did above). Hence, for our case
971 	 * parentage chain will still be live (i.e. reg->parent may be
972 	 * non-NULL), while earlier reg->parent was NULL, so we need
973 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
974 	 * done later on reads or by mark_dynptr_read as well to unnecessary
975 	 * mark registers in verifier state.
976 	 */
977 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
978 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
979 }
980 
981 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
982 {
983 	struct bpf_func_state *state = func(env, reg);
984 	int spi, ref_obj_id, i;
985 
986 	spi = dynptr_get_spi(env, reg);
987 	if (spi < 0)
988 		return spi;
989 
990 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
991 		invalidate_dynptr(env, state, spi);
992 		return 0;
993 	}
994 
995 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
996 
997 	/* If the dynptr has a ref_obj_id, then we need to invalidate
998 	 * two things:
999 	 *
1000 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1001 	 * 2) Any slices derived from this dynptr.
1002 	 */
1003 
1004 	/* Invalidate any slices associated with this dynptr */
1005 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1006 
1007 	/* Invalidate any dynptr clones */
1008 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1009 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1010 			continue;
1011 
1012 		/* it should always be the case that if the ref obj id
1013 		 * matches then the stack slot also belongs to a
1014 		 * dynptr
1015 		 */
1016 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1017 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1018 			return -EFAULT;
1019 		}
1020 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1021 			invalidate_dynptr(env, state, i);
1022 	}
1023 
1024 	return 0;
1025 }
1026 
1027 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1028 			       struct bpf_reg_state *reg);
1029 
1030 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1031 {
1032 	if (!env->allow_ptr_leaks)
1033 		__mark_reg_not_init(env, reg);
1034 	else
1035 		__mark_reg_unknown(env, reg);
1036 }
1037 
1038 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1039 				        struct bpf_func_state *state, int spi)
1040 {
1041 	struct bpf_func_state *fstate;
1042 	struct bpf_reg_state *dreg;
1043 	int i, dynptr_id;
1044 
1045 	/* We always ensure that STACK_DYNPTR is never set partially,
1046 	 * hence just checking for slot_type[0] is enough. This is
1047 	 * different for STACK_SPILL, where it may be only set for
1048 	 * 1 byte, so code has to use is_spilled_reg.
1049 	 */
1050 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1051 		return 0;
1052 
1053 	/* Reposition spi to first slot */
1054 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1055 		spi = spi + 1;
1056 
1057 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1058 		verbose(env, "cannot overwrite referenced dynptr\n");
1059 		return -EINVAL;
1060 	}
1061 
1062 	mark_stack_slot_scratched(env, spi);
1063 	mark_stack_slot_scratched(env, spi - 1);
1064 
1065 	/* Writing partially to one dynptr stack slot destroys both. */
1066 	for (i = 0; i < BPF_REG_SIZE; i++) {
1067 		state->stack[spi].slot_type[i] = STACK_INVALID;
1068 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1069 	}
1070 
1071 	dynptr_id = state->stack[spi].spilled_ptr.id;
1072 	/* Invalidate any slices associated with this dynptr */
1073 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1074 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1075 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1076 			continue;
1077 		if (dreg->dynptr_id == dynptr_id)
1078 			mark_reg_invalid(env, dreg);
1079 	}));
1080 
1081 	/* Do not release reference state, we are destroying dynptr on stack,
1082 	 * not using some helper to release it. Just reset register.
1083 	 */
1084 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1085 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1086 
1087 	/* Same reason as unmark_stack_slots_dynptr above */
1088 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1090 
1091 	return 0;
1092 }
1093 
1094 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1095 {
1096 	int spi;
1097 
1098 	if (reg->type == CONST_PTR_TO_DYNPTR)
1099 		return false;
1100 
1101 	spi = dynptr_get_spi(env, reg);
1102 
1103 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1104 	 * error because this just means the stack state hasn't been updated yet.
1105 	 * We will do check_mem_access to check and update stack bounds later.
1106 	 */
1107 	if (spi < 0 && spi != -ERANGE)
1108 		return false;
1109 
1110 	/* We don't need to check if the stack slots are marked by previous
1111 	 * dynptr initializations because we allow overwriting existing unreferenced
1112 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1113 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1114 	 * touching are completely destructed before we reinitialize them for a new
1115 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1116 	 * instead of delaying it until the end where the user will get "Unreleased
1117 	 * reference" error.
1118 	 */
1119 	return true;
1120 }
1121 
1122 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1123 {
1124 	struct bpf_func_state *state = func(env, reg);
1125 	int i, spi;
1126 
1127 	/* This already represents first slot of initialized bpf_dynptr.
1128 	 *
1129 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1130 	 * check_func_arg_reg_off's logic, so we don't need to check its
1131 	 * offset and alignment.
1132 	 */
1133 	if (reg->type == CONST_PTR_TO_DYNPTR)
1134 		return true;
1135 
1136 	spi = dynptr_get_spi(env, reg);
1137 	if (spi < 0)
1138 		return false;
1139 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1140 		return false;
1141 
1142 	for (i = 0; i < BPF_REG_SIZE; i++) {
1143 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1144 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1145 			return false;
1146 	}
1147 
1148 	return true;
1149 }
1150 
1151 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1152 				    enum bpf_arg_type arg_type)
1153 {
1154 	struct bpf_func_state *state = func(env, reg);
1155 	enum bpf_dynptr_type dynptr_type;
1156 	int spi;
1157 
1158 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1159 	if (arg_type == ARG_PTR_TO_DYNPTR)
1160 		return true;
1161 
1162 	dynptr_type = arg_to_dynptr_type(arg_type);
1163 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1164 		return reg->dynptr.type == dynptr_type;
1165 	} else {
1166 		spi = dynptr_get_spi(env, reg);
1167 		if (spi < 0)
1168 			return false;
1169 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1170 	}
1171 }
1172 
1173 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1174 
1175 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1176 				 struct bpf_reg_state *reg, int insn_idx,
1177 				 struct btf *btf, u32 btf_id, int nr_slots)
1178 {
1179 	struct bpf_func_state *state = func(env, reg);
1180 	int spi, i, j, id;
1181 
1182 	spi = iter_get_spi(env, reg, nr_slots);
1183 	if (spi < 0)
1184 		return spi;
1185 
1186 	id = acquire_reference_state(env, insn_idx);
1187 	if (id < 0)
1188 		return id;
1189 
1190 	for (i = 0; i < nr_slots; i++) {
1191 		struct bpf_stack_state *slot = &state->stack[spi - i];
1192 		struct bpf_reg_state *st = &slot->spilled_ptr;
1193 
1194 		__mark_reg_known_zero(st);
1195 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1196 		st->live |= REG_LIVE_WRITTEN;
1197 		st->ref_obj_id = i == 0 ? id : 0;
1198 		st->iter.btf = btf;
1199 		st->iter.btf_id = btf_id;
1200 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1201 		st->iter.depth = 0;
1202 
1203 		for (j = 0; j < BPF_REG_SIZE; j++)
1204 			slot->slot_type[j] = STACK_ITER;
1205 
1206 		mark_stack_slot_scratched(env, spi - i);
1207 	}
1208 
1209 	return 0;
1210 }
1211 
1212 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1213 				   struct bpf_reg_state *reg, int nr_slots)
1214 {
1215 	struct bpf_func_state *state = func(env, reg);
1216 	int spi, i, j;
1217 
1218 	spi = iter_get_spi(env, reg, nr_slots);
1219 	if (spi < 0)
1220 		return spi;
1221 
1222 	for (i = 0; i < nr_slots; i++) {
1223 		struct bpf_stack_state *slot = &state->stack[spi - i];
1224 		struct bpf_reg_state *st = &slot->spilled_ptr;
1225 
1226 		if (i == 0)
1227 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1228 
1229 		__mark_reg_not_init(env, st);
1230 
1231 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1232 		st->live |= REG_LIVE_WRITTEN;
1233 
1234 		for (j = 0; j < BPF_REG_SIZE; j++)
1235 			slot->slot_type[j] = STACK_INVALID;
1236 
1237 		mark_stack_slot_scratched(env, spi - i);
1238 	}
1239 
1240 	return 0;
1241 }
1242 
1243 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1244 				     struct bpf_reg_state *reg, int nr_slots)
1245 {
1246 	struct bpf_func_state *state = func(env, reg);
1247 	int spi, i, j;
1248 
1249 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1250 	 * will do check_mem_access to check and update stack bounds later, so
1251 	 * return true for that case.
1252 	 */
1253 	spi = iter_get_spi(env, reg, nr_slots);
1254 	if (spi == -ERANGE)
1255 		return true;
1256 	if (spi < 0)
1257 		return false;
1258 
1259 	for (i = 0; i < nr_slots; i++) {
1260 		struct bpf_stack_state *slot = &state->stack[spi - i];
1261 
1262 		for (j = 0; j < BPF_REG_SIZE; j++)
1263 			if (slot->slot_type[j] == STACK_ITER)
1264 				return false;
1265 	}
1266 
1267 	return true;
1268 }
1269 
1270 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1271 				   struct btf *btf, u32 btf_id, int nr_slots)
1272 {
1273 	struct bpf_func_state *state = func(env, reg);
1274 	int spi, i, j;
1275 
1276 	spi = iter_get_spi(env, reg, nr_slots);
1277 	if (spi < 0)
1278 		return false;
1279 
1280 	for (i = 0; i < nr_slots; i++) {
1281 		struct bpf_stack_state *slot = &state->stack[spi - i];
1282 		struct bpf_reg_state *st = &slot->spilled_ptr;
1283 
1284 		/* only main (first) slot has ref_obj_id set */
1285 		if (i == 0 && !st->ref_obj_id)
1286 			return false;
1287 		if (i != 0 && st->ref_obj_id)
1288 			return false;
1289 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1290 			return false;
1291 
1292 		for (j = 0; j < BPF_REG_SIZE; j++)
1293 			if (slot->slot_type[j] != STACK_ITER)
1294 				return false;
1295 	}
1296 
1297 	return true;
1298 }
1299 
1300 /* Check if given stack slot is "special":
1301  *   - spilled register state (STACK_SPILL);
1302  *   - dynptr state (STACK_DYNPTR);
1303  *   - iter state (STACK_ITER).
1304  */
1305 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1306 {
1307 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1308 
1309 	switch (type) {
1310 	case STACK_SPILL:
1311 	case STACK_DYNPTR:
1312 	case STACK_ITER:
1313 		return true;
1314 	case STACK_INVALID:
1315 	case STACK_MISC:
1316 	case STACK_ZERO:
1317 		return false;
1318 	default:
1319 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1320 		return true;
1321 	}
1322 }
1323 
1324 /* The reg state of a pointer or a bounded scalar was saved when
1325  * it was spilled to the stack.
1326  */
1327 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1328 {
1329 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1330 }
1331 
1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1333 {
1334 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1335 	       stack->spilled_ptr.type == SCALAR_VALUE;
1336 }
1337 
1338 static void scrub_spilled_slot(u8 *stype)
1339 {
1340 	if (*stype != STACK_INVALID)
1341 		*stype = STACK_MISC;
1342 }
1343 
1344 static void print_verifier_state(struct bpf_verifier_env *env,
1345 				 const struct bpf_func_state *state,
1346 				 bool print_all)
1347 {
1348 	const struct bpf_reg_state *reg;
1349 	enum bpf_reg_type t;
1350 	int i;
1351 
1352 	if (state->frameno)
1353 		verbose(env, " frame%d:", state->frameno);
1354 	for (i = 0; i < MAX_BPF_REG; i++) {
1355 		reg = &state->regs[i];
1356 		t = reg->type;
1357 		if (t == NOT_INIT)
1358 			continue;
1359 		if (!print_all && !reg_scratched(env, i))
1360 			continue;
1361 		verbose(env, " R%d", i);
1362 		print_liveness(env, reg->live);
1363 		verbose(env, "=");
1364 		if (t == SCALAR_VALUE && reg->precise)
1365 			verbose(env, "P");
1366 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1367 		    tnum_is_const(reg->var_off)) {
1368 			/* reg->off should be 0 for SCALAR_VALUE */
1369 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1370 			verbose(env, "%lld", reg->var_off.value + reg->off);
1371 		} else {
1372 			const char *sep = "";
1373 
1374 			verbose(env, "%s", reg_type_str(env, t));
1375 			if (base_type(t) == PTR_TO_BTF_ID)
1376 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1377 			verbose(env, "(");
1378 /*
1379  * _a stands for append, was shortened to avoid multiline statements below.
1380  * This macro is used to output a comma separated list of attributes.
1381  */
1382 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1383 
1384 			if (reg->id)
1385 				verbose_a("id=%d", reg->id);
1386 			if (reg->ref_obj_id)
1387 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1388 			if (type_is_non_owning_ref(reg->type))
1389 				verbose_a("%s", "non_own_ref");
1390 			if (t != SCALAR_VALUE)
1391 				verbose_a("off=%d", reg->off);
1392 			if (type_is_pkt_pointer(t))
1393 				verbose_a("r=%d", reg->range);
1394 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1395 				 base_type(t) == PTR_TO_MAP_KEY ||
1396 				 base_type(t) == PTR_TO_MAP_VALUE)
1397 				verbose_a("ks=%d,vs=%d",
1398 					  reg->map_ptr->key_size,
1399 					  reg->map_ptr->value_size);
1400 			if (tnum_is_const(reg->var_off)) {
1401 				/* Typically an immediate SCALAR_VALUE, but
1402 				 * could be a pointer whose offset is too big
1403 				 * for reg->off
1404 				 */
1405 				verbose_a("imm=%llx", reg->var_off.value);
1406 			} else {
1407 				if (reg->smin_value != reg->umin_value &&
1408 				    reg->smin_value != S64_MIN)
1409 					verbose_a("smin=%lld", (long long)reg->smin_value);
1410 				if (reg->smax_value != reg->umax_value &&
1411 				    reg->smax_value != S64_MAX)
1412 					verbose_a("smax=%lld", (long long)reg->smax_value);
1413 				if (reg->umin_value != 0)
1414 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1415 				if (reg->umax_value != U64_MAX)
1416 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1417 				if (!tnum_is_unknown(reg->var_off)) {
1418 					char tn_buf[48];
1419 
1420 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1421 					verbose_a("var_off=%s", tn_buf);
1422 				}
1423 				if (reg->s32_min_value != reg->smin_value &&
1424 				    reg->s32_min_value != S32_MIN)
1425 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1426 				if (reg->s32_max_value != reg->smax_value &&
1427 				    reg->s32_max_value != S32_MAX)
1428 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1429 				if (reg->u32_min_value != reg->umin_value &&
1430 				    reg->u32_min_value != U32_MIN)
1431 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1432 				if (reg->u32_max_value != reg->umax_value &&
1433 				    reg->u32_max_value != U32_MAX)
1434 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1435 			}
1436 #undef verbose_a
1437 
1438 			verbose(env, ")");
1439 		}
1440 	}
1441 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1442 		char types_buf[BPF_REG_SIZE + 1];
1443 		bool valid = false;
1444 		int j;
1445 
1446 		for (j = 0; j < BPF_REG_SIZE; j++) {
1447 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1448 				valid = true;
1449 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1450 		}
1451 		types_buf[BPF_REG_SIZE] = 0;
1452 		if (!valid)
1453 			continue;
1454 		if (!print_all && !stack_slot_scratched(env, i))
1455 			continue;
1456 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1457 		case STACK_SPILL:
1458 			reg = &state->stack[i].spilled_ptr;
1459 			t = reg->type;
1460 
1461 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1462 			print_liveness(env, reg->live);
1463 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1464 			if (t == SCALAR_VALUE && reg->precise)
1465 				verbose(env, "P");
1466 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1467 				verbose(env, "%lld", reg->var_off.value + reg->off);
1468 			break;
1469 		case STACK_DYNPTR:
1470 			i += BPF_DYNPTR_NR_SLOTS - 1;
1471 			reg = &state->stack[i].spilled_ptr;
1472 
1473 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1474 			print_liveness(env, reg->live);
1475 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1476 			if (reg->ref_obj_id)
1477 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1478 			break;
1479 		case STACK_ITER:
1480 			/* only main slot has ref_obj_id set; skip others */
1481 			reg = &state->stack[i].spilled_ptr;
1482 			if (!reg->ref_obj_id)
1483 				continue;
1484 
1485 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1486 			print_liveness(env, reg->live);
1487 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1488 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1489 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1490 				reg->iter.depth);
1491 			break;
1492 		case STACK_MISC:
1493 		case STACK_ZERO:
1494 		default:
1495 			reg = &state->stack[i].spilled_ptr;
1496 
1497 			for (j = 0; j < BPF_REG_SIZE; j++)
1498 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1499 			types_buf[BPF_REG_SIZE] = 0;
1500 
1501 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1502 			print_liveness(env, reg->live);
1503 			verbose(env, "=%s", types_buf);
1504 			break;
1505 		}
1506 	}
1507 	if (state->acquired_refs && state->refs[0].id) {
1508 		verbose(env, " refs=%d", state->refs[0].id);
1509 		for (i = 1; i < state->acquired_refs; i++)
1510 			if (state->refs[i].id)
1511 				verbose(env, ",%d", state->refs[i].id);
1512 	}
1513 	if (state->in_callback_fn)
1514 		verbose(env, " cb");
1515 	if (state->in_async_callback_fn)
1516 		verbose(env, " async_cb");
1517 	verbose(env, "\n");
1518 	mark_verifier_state_clean(env);
1519 }
1520 
1521 static inline u32 vlog_alignment(u32 pos)
1522 {
1523 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1524 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1525 }
1526 
1527 static void print_insn_state(struct bpf_verifier_env *env,
1528 			     const struct bpf_func_state *state)
1529 {
1530 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1531 		/* remove new line character */
1532 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1533 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1534 	} else {
1535 		verbose(env, "%d:", env->insn_idx);
1536 	}
1537 	print_verifier_state(env, state, false);
1538 }
1539 
1540 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1541  * small to hold src. This is different from krealloc since we don't want to preserve
1542  * the contents of dst.
1543  *
1544  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1545  * not be allocated.
1546  */
1547 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1548 {
1549 	size_t alloc_bytes;
1550 	void *orig = dst;
1551 	size_t bytes;
1552 
1553 	if (ZERO_OR_NULL_PTR(src))
1554 		goto out;
1555 
1556 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1557 		return NULL;
1558 
1559 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1560 	dst = krealloc(orig, alloc_bytes, flags);
1561 	if (!dst) {
1562 		kfree(orig);
1563 		return NULL;
1564 	}
1565 
1566 	memcpy(dst, src, bytes);
1567 out:
1568 	return dst ? dst : ZERO_SIZE_PTR;
1569 }
1570 
1571 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1572  * small to hold new_n items. new items are zeroed out if the array grows.
1573  *
1574  * Contrary to krealloc_array, does not free arr if new_n is zero.
1575  */
1576 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1577 {
1578 	size_t alloc_size;
1579 	void *new_arr;
1580 
1581 	if (!new_n || old_n == new_n)
1582 		goto out;
1583 
1584 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1585 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1586 	if (!new_arr) {
1587 		kfree(arr);
1588 		return NULL;
1589 	}
1590 	arr = new_arr;
1591 
1592 	if (new_n > old_n)
1593 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1594 
1595 out:
1596 	return arr ? arr : ZERO_SIZE_PTR;
1597 }
1598 
1599 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1600 {
1601 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1602 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1603 	if (!dst->refs)
1604 		return -ENOMEM;
1605 
1606 	dst->acquired_refs = src->acquired_refs;
1607 	return 0;
1608 }
1609 
1610 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1611 {
1612 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1613 
1614 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1615 				GFP_KERNEL);
1616 	if (!dst->stack)
1617 		return -ENOMEM;
1618 
1619 	dst->allocated_stack = src->allocated_stack;
1620 	return 0;
1621 }
1622 
1623 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1624 {
1625 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1626 				    sizeof(struct bpf_reference_state));
1627 	if (!state->refs)
1628 		return -ENOMEM;
1629 
1630 	state->acquired_refs = n;
1631 	return 0;
1632 }
1633 
1634 static int grow_stack_state(struct bpf_func_state *state, int size)
1635 {
1636 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1637 
1638 	if (old_n >= n)
1639 		return 0;
1640 
1641 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1642 	if (!state->stack)
1643 		return -ENOMEM;
1644 
1645 	state->allocated_stack = size;
1646 	return 0;
1647 }
1648 
1649 /* Acquire a pointer id from the env and update the state->refs to include
1650  * this new pointer reference.
1651  * On success, returns a valid pointer id to associate with the register
1652  * On failure, returns a negative errno.
1653  */
1654 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1655 {
1656 	struct bpf_func_state *state = cur_func(env);
1657 	int new_ofs = state->acquired_refs;
1658 	int id, err;
1659 
1660 	err = resize_reference_state(state, state->acquired_refs + 1);
1661 	if (err)
1662 		return err;
1663 	id = ++env->id_gen;
1664 	state->refs[new_ofs].id = id;
1665 	state->refs[new_ofs].insn_idx = insn_idx;
1666 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1667 
1668 	return id;
1669 }
1670 
1671 /* release function corresponding to acquire_reference_state(). Idempotent. */
1672 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1673 {
1674 	int i, last_idx;
1675 
1676 	last_idx = state->acquired_refs - 1;
1677 	for (i = 0; i < state->acquired_refs; i++) {
1678 		if (state->refs[i].id == ptr_id) {
1679 			/* Cannot release caller references in callbacks */
1680 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1681 				return -EINVAL;
1682 			if (last_idx && i != last_idx)
1683 				memcpy(&state->refs[i], &state->refs[last_idx],
1684 				       sizeof(*state->refs));
1685 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1686 			state->acquired_refs--;
1687 			return 0;
1688 		}
1689 	}
1690 	return -EINVAL;
1691 }
1692 
1693 static void free_func_state(struct bpf_func_state *state)
1694 {
1695 	if (!state)
1696 		return;
1697 	kfree(state->refs);
1698 	kfree(state->stack);
1699 	kfree(state);
1700 }
1701 
1702 static void clear_jmp_history(struct bpf_verifier_state *state)
1703 {
1704 	kfree(state->jmp_history);
1705 	state->jmp_history = NULL;
1706 	state->jmp_history_cnt = 0;
1707 }
1708 
1709 static void free_verifier_state(struct bpf_verifier_state *state,
1710 				bool free_self)
1711 {
1712 	int i;
1713 
1714 	for (i = 0; i <= state->curframe; i++) {
1715 		free_func_state(state->frame[i]);
1716 		state->frame[i] = NULL;
1717 	}
1718 	clear_jmp_history(state);
1719 	if (free_self)
1720 		kfree(state);
1721 }
1722 
1723 /* copy verifier state from src to dst growing dst stack space
1724  * when necessary to accommodate larger src stack
1725  */
1726 static int copy_func_state(struct bpf_func_state *dst,
1727 			   const struct bpf_func_state *src)
1728 {
1729 	int err;
1730 
1731 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1732 	err = copy_reference_state(dst, src);
1733 	if (err)
1734 		return err;
1735 	return copy_stack_state(dst, src);
1736 }
1737 
1738 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1739 			       const struct bpf_verifier_state *src)
1740 {
1741 	struct bpf_func_state *dst;
1742 	int i, err;
1743 
1744 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1745 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1746 					    GFP_USER);
1747 	if (!dst_state->jmp_history)
1748 		return -ENOMEM;
1749 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1750 
1751 	/* if dst has more stack frames then src frame, free them */
1752 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1753 		free_func_state(dst_state->frame[i]);
1754 		dst_state->frame[i] = NULL;
1755 	}
1756 	dst_state->speculative = src->speculative;
1757 	dst_state->active_rcu_lock = src->active_rcu_lock;
1758 	dst_state->curframe = src->curframe;
1759 	dst_state->active_lock.ptr = src->active_lock.ptr;
1760 	dst_state->active_lock.id = src->active_lock.id;
1761 	dst_state->branches = src->branches;
1762 	dst_state->parent = src->parent;
1763 	dst_state->first_insn_idx = src->first_insn_idx;
1764 	dst_state->last_insn_idx = src->last_insn_idx;
1765 	for (i = 0; i <= src->curframe; i++) {
1766 		dst = dst_state->frame[i];
1767 		if (!dst) {
1768 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1769 			if (!dst)
1770 				return -ENOMEM;
1771 			dst_state->frame[i] = dst;
1772 		}
1773 		err = copy_func_state(dst, src->frame[i]);
1774 		if (err)
1775 			return err;
1776 	}
1777 	return 0;
1778 }
1779 
1780 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1781 {
1782 	while (st) {
1783 		u32 br = --st->branches;
1784 
1785 		/* WARN_ON(br > 1) technically makes sense here,
1786 		 * but see comment in push_stack(), hence:
1787 		 */
1788 		WARN_ONCE((int)br < 0,
1789 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1790 			  br);
1791 		if (br)
1792 			break;
1793 		st = st->parent;
1794 	}
1795 }
1796 
1797 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1798 		     int *insn_idx, bool pop_log)
1799 {
1800 	struct bpf_verifier_state *cur = env->cur_state;
1801 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1802 	int err;
1803 
1804 	if (env->head == NULL)
1805 		return -ENOENT;
1806 
1807 	if (cur) {
1808 		err = copy_verifier_state(cur, &head->st);
1809 		if (err)
1810 			return err;
1811 	}
1812 	if (pop_log)
1813 		bpf_vlog_reset(&env->log, head->log_pos);
1814 	if (insn_idx)
1815 		*insn_idx = head->insn_idx;
1816 	if (prev_insn_idx)
1817 		*prev_insn_idx = head->prev_insn_idx;
1818 	elem = head->next;
1819 	free_verifier_state(&head->st, false);
1820 	kfree(head);
1821 	env->head = elem;
1822 	env->stack_size--;
1823 	return 0;
1824 }
1825 
1826 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1827 					     int insn_idx, int prev_insn_idx,
1828 					     bool speculative)
1829 {
1830 	struct bpf_verifier_state *cur = env->cur_state;
1831 	struct bpf_verifier_stack_elem *elem;
1832 	int err;
1833 
1834 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1835 	if (!elem)
1836 		goto err;
1837 
1838 	elem->insn_idx = insn_idx;
1839 	elem->prev_insn_idx = prev_insn_idx;
1840 	elem->next = env->head;
1841 	elem->log_pos = env->log.end_pos;
1842 	env->head = elem;
1843 	env->stack_size++;
1844 	err = copy_verifier_state(&elem->st, cur);
1845 	if (err)
1846 		goto err;
1847 	elem->st.speculative |= speculative;
1848 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1849 		verbose(env, "The sequence of %d jumps is too complex.\n",
1850 			env->stack_size);
1851 		goto err;
1852 	}
1853 	if (elem->st.parent) {
1854 		++elem->st.parent->branches;
1855 		/* WARN_ON(branches > 2) technically makes sense here,
1856 		 * but
1857 		 * 1. speculative states will bump 'branches' for non-branch
1858 		 * instructions
1859 		 * 2. is_state_visited() heuristics may decide not to create
1860 		 * a new state for a sequence of branches and all such current
1861 		 * and cloned states will be pointing to a single parent state
1862 		 * which might have large 'branches' count.
1863 		 */
1864 	}
1865 	return &elem->st;
1866 err:
1867 	free_verifier_state(env->cur_state, true);
1868 	env->cur_state = NULL;
1869 	/* pop all elements and return */
1870 	while (!pop_stack(env, NULL, NULL, false));
1871 	return NULL;
1872 }
1873 
1874 #define CALLER_SAVED_REGS 6
1875 static const int caller_saved[CALLER_SAVED_REGS] = {
1876 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1877 };
1878 
1879 /* This helper doesn't clear reg->id */
1880 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1881 {
1882 	reg->var_off = tnum_const(imm);
1883 	reg->smin_value = (s64)imm;
1884 	reg->smax_value = (s64)imm;
1885 	reg->umin_value = imm;
1886 	reg->umax_value = imm;
1887 
1888 	reg->s32_min_value = (s32)imm;
1889 	reg->s32_max_value = (s32)imm;
1890 	reg->u32_min_value = (u32)imm;
1891 	reg->u32_max_value = (u32)imm;
1892 }
1893 
1894 /* Mark the unknown part of a register (variable offset or scalar value) as
1895  * known to have the value @imm.
1896  */
1897 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1898 {
1899 	/* Clear off and union(map_ptr, range) */
1900 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1901 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1902 	reg->id = 0;
1903 	reg->ref_obj_id = 0;
1904 	___mark_reg_known(reg, imm);
1905 }
1906 
1907 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1908 {
1909 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1910 	reg->s32_min_value = (s32)imm;
1911 	reg->s32_max_value = (s32)imm;
1912 	reg->u32_min_value = (u32)imm;
1913 	reg->u32_max_value = (u32)imm;
1914 }
1915 
1916 /* Mark the 'variable offset' part of a register as zero.  This should be
1917  * used only on registers holding a pointer type.
1918  */
1919 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1920 {
1921 	__mark_reg_known(reg, 0);
1922 }
1923 
1924 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1925 {
1926 	__mark_reg_known(reg, 0);
1927 	reg->type = SCALAR_VALUE;
1928 }
1929 
1930 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1931 				struct bpf_reg_state *regs, u32 regno)
1932 {
1933 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1934 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1935 		/* Something bad happened, let's kill all regs */
1936 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1937 			__mark_reg_not_init(env, regs + regno);
1938 		return;
1939 	}
1940 	__mark_reg_known_zero(regs + regno);
1941 }
1942 
1943 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1944 			      bool first_slot, int dynptr_id)
1945 {
1946 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1947 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1948 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1949 	 */
1950 	__mark_reg_known_zero(reg);
1951 	reg->type = CONST_PTR_TO_DYNPTR;
1952 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1953 	reg->id = dynptr_id;
1954 	reg->dynptr.type = type;
1955 	reg->dynptr.first_slot = first_slot;
1956 }
1957 
1958 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1959 {
1960 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1961 		const struct bpf_map *map = reg->map_ptr;
1962 
1963 		if (map->inner_map_meta) {
1964 			reg->type = CONST_PTR_TO_MAP;
1965 			reg->map_ptr = map->inner_map_meta;
1966 			/* transfer reg's id which is unique for every map_lookup_elem
1967 			 * as UID of the inner map.
1968 			 */
1969 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1970 				reg->map_uid = reg->id;
1971 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1972 			reg->type = PTR_TO_XDP_SOCK;
1973 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1974 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1975 			reg->type = PTR_TO_SOCKET;
1976 		} else {
1977 			reg->type = PTR_TO_MAP_VALUE;
1978 		}
1979 		return;
1980 	}
1981 
1982 	reg->type &= ~PTR_MAYBE_NULL;
1983 }
1984 
1985 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1986 				struct btf_field_graph_root *ds_head)
1987 {
1988 	__mark_reg_known_zero(&regs[regno]);
1989 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1990 	regs[regno].btf = ds_head->btf;
1991 	regs[regno].btf_id = ds_head->value_btf_id;
1992 	regs[regno].off = ds_head->node_offset;
1993 }
1994 
1995 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1996 {
1997 	return type_is_pkt_pointer(reg->type);
1998 }
1999 
2000 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2001 {
2002 	return reg_is_pkt_pointer(reg) ||
2003 	       reg->type == PTR_TO_PACKET_END;
2004 }
2005 
2006 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2007 {
2008 	return base_type(reg->type) == PTR_TO_MEM &&
2009 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2010 }
2011 
2012 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2013 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2014 				    enum bpf_reg_type which)
2015 {
2016 	/* The register can already have a range from prior markings.
2017 	 * This is fine as long as it hasn't been advanced from its
2018 	 * origin.
2019 	 */
2020 	return reg->type == which &&
2021 	       reg->id == 0 &&
2022 	       reg->off == 0 &&
2023 	       tnum_equals_const(reg->var_off, 0);
2024 }
2025 
2026 /* Reset the min/max bounds of a register */
2027 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2028 {
2029 	reg->smin_value = S64_MIN;
2030 	reg->smax_value = S64_MAX;
2031 	reg->umin_value = 0;
2032 	reg->umax_value = U64_MAX;
2033 
2034 	reg->s32_min_value = S32_MIN;
2035 	reg->s32_max_value = S32_MAX;
2036 	reg->u32_min_value = 0;
2037 	reg->u32_max_value = U32_MAX;
2038 }
2039 
2040 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2041 {
2042 	reg->smin_value = S64_MIN;
2043 	reg->smax_value = S64_MAX;
2044 	reg->umin_value = 0;
2045 	reg->umax_value = U64_MAX;
2046 }
2047 
2048 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2049 {
2050 	reg->s32_min_value = S32_MIN;
2051 	reg->s32_max_value = S32_MAX;
2052 	reg->u32_min_value = 0;
2053 	reg->u32_max_value = U32_MAX;
2054 }
2055 
2056 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2057 {
2058 	struct tnum var32_off = tnum_subreg(reg->var_off);
2059 
2060 	/* min signed is max(sign bit) | min(other bits) */
2061 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2062 			var32_off.value | (var32_off.mask & S32_MIN));
2063 	/* max signed is min(sign bit) | max(other bits) */
2064 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2065 			var32_off.value | (var32_off.mask & S32_MAX));
2066 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2067 	reg->u32_max_value = min(reg->u32_max_value,
2068 				 (u32)(var32_off.value | var32_off.mask));
2069 }
2070 
2071 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2072 {
2073 	/* min signed is max(sign bit) | min(other bits) */
2074 	reg->smin_value = max_t(s64, reg->smin_value,
2075 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2076 	/* max signed is min(sign bit) | max(other bits) */
2077 	reg->smax_value = min_t(s64, reg->smax_value,
2078 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2079 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2080 	reg->umax_value = min(reg->umax_value,
2081 			      reg->var_off.value | reg->var_off.mask);
2082 }
2083 
2084 static void __update_reg_bounds(struct bpf_reg_state *reg)
2085 {
2086 	__update_reg32_bounds(reg);
2087 	__update_reg64_bounds(reg);
2088 }
2089 
2090 /* Uses signed min/max values to inform unsigned, and vice-versa */
2091 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2092 {
2093 	/* Learn sign from signed bounds.
2094 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2095 	 * are the same, so combine.  This works even in the negative case, e.g.
2096 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2097 	 */
2098 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2099 		reg->s32_min_value = reg->u32_min_value =
2100 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2101 		reg->s32_max_value = reg->u32_max_value =
2102 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2103 		return;
2104 	}
2105 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2106 	 * boundary, so we must be careful.
2107 	 */
2108 	if ((s32)reg->u32_max_value >= 0) {
2109 		/* Positive.  We can't learn anything from the smin, but smax
2110 		 * is positive, hence safe.
2111 		 */
2112 		reg->s32_min_value = reg->u32_min_value;
2113 		reg->s32_max_value = reg->u32_max_value =
2114 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2115 	} else if ((s32)reg->u32_min_value < 0) {
2116 		/* Negative.  We can't learn anything from the smax, but smin
2117 		 * is negative, hence safe.
2118 		 */
2119 		reg->s32_min_value = reg->u32_min_value =
2120 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2121 		reg->s32_max_value = reg->u32_max_value;
2122 	}
2123 }
2124 
2125 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2126 {
2127 	/* Learn sign from signed bounds.
2128 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2129 	 * are the same, so combine.  This works even in the negative case, e.g.
2130 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2131 	 */
2132 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2133 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2134 							  reg->umin_value);
2135 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2136 							  reg->umax_value);
2137 		return;
2138 	}
2139 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2140 	 * boundary, so we must be careful.
2141 	 */
2142 	if ((s64)reg->umax_value >= 0) {
2143 		/* Positive.  We can't learn anything from the smin, but smax
2144 		 * is positive, hence safe.
2145 		 */
2146 		reg->smin_value = reg->umin_value;
2147 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2148 							  reg->umax_value);
2149 	} else if ((s64)reg->umin_value < 0) {
2150 		/* Negative.  We can't learn anything from the smax, but smin
2151 		 * is negative, hence safe.
2152 		 */
2153 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2154 							  reg->umin_value);
2155 		reg->smax_value = reg->umax_value;
2156 	}
2157 }
2158 
2159 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2160 {
2161 	__reg32_deduce_bounds(reg);
2162 	__reg64_deduce_bounds(reg);
2163 }
2164 
2165 /* Attempts to improve var_off based on unsigned min/max information */
2166 static void __reg_bound_offset(struct bpf_reg_state *reg)
2167 {
2168 	struct tnum var64_off = tnum_intersect(reg->var_off,
2169 					       tnum_range(reg->umin_value,
2170 							  reg->umax_value));
2171 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2172 					       tnum_range(reg->u32_min_value,
2173 							  reg->u32_max_value));
2174 
2175 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2176 }
2177 
2178 static void reg_bounds_sync(struct bpf_reg_state *reg)
2179 {
2180 	/* We might have learned new bounds from the var_off. */
2181 	__update_reg_bounds(reg);
2182 	/* We might have learned something about the sign bit. */
2183 	__reg_deduce_bounds(reg);
2184 	/* We might have learned some bits from the bounds. */
2185 	__reg_bound_offset(reg);
2186 	/* Intersecting with the old var_off might have improved our bounds
2187 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2188 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2189 	 */
2190 	__update_reg_bounds(reg);
2191 }
2192 
2193 static bool __reg32_bound_s64(s32 a)
2194 {
2195 	return a >= 0 && a <= S32_MAX;
2196 }
2197 
2198 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2199 {
2200 	reg->umin_value = reg->u32_min_value;
2201 	reg->umax_value = reg->u32_max_value;
2202 
2203 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2204 	 * be positive otherwise set to worse case bounds and refine later
2205 	 * from tnum.
2206 	 */
2207 	if (__reg32_bound_s64(reg->s32_min_value) &&
2208 	    __reg32_bound_s64(reg->s32_max_value)) {
2209 		reg->smin_value = reg->s32_min_value;
2210 		reg->smax_value = reg->s32_max_value;
2211 	} else {
2212 		reg->smin_value = 0;
2213 		reg->smax_value = U32_MAX;
2214 	}
2215 }
2216 
2217 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2218 {
2219 	/* special case when 64-bit register has upper 32-bit register
2220 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2221 	 * allowing us to use 32-bit bounds directly,
2222 	 */
2223 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2224 		__reg_assign_32_into_64(reg);
2225 	} else {
2226 		/* Otherwise the best we can do is push lower 32bit known and
2227 		 * unknown bits into register (var_off set from jmp logic)
2228 		 * then learn as much as possible from the 64-bit tnum
2229 		 * known and unknown bits. The previous smin/smax bounds are
2230 		 * invalid here because of jmp32 compare so mark them unknown
2231 		 * so they do not impact tnum bounds calculation.
2232 		 */
2233 		__mark_reg64_unbounded(reg);
2234 	}
2235 	reg_bounds_sync(reg);
2236 }
2237 
2238 static bool __reg64_bound_s32(s64 a)
2239 {
2240 	return a >= S32_MIN && a <= S32_MAX;
2241 }
2242 
2243 static bool __reg64_bound_u32(u64 a)
2244 {
2245 	return a >= U32_MIN && a <= U32_MAX;
2246 }
2247 
2248 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2249 {
2250 	__mark_reg32_unbounded(reg);
2251 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2252 		reg->s32_min_value = (s32)reg->smin_value;
2253 		reg->s32_max_value = (s32)reg->smax_value;
2254 	}
2255 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2256 		reg->u32_min_value = (u32)reg->umin_value;
2257 		reg->u32_max_value = (u32)reg->umax_value;
2258 	}
2259 	reg_bounds_sync(reg);
2260 }
2261 
2262 /* Mark a register as having a completely unknown (scalar) value. */
2263 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2264 			       struct bpf_reg_state *reg)
2265 {
2266 	/*
2267 	 * Clear type, off, and union(map_ptr, range) and
2268 	 * padding between 'type' and union
2269 	 */
2270 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2271 	reg->type = SCALAR_VALUE;
2272 	reg->id = 0;
2273 	reg->ref_obj_id = 0;
2274 	reg->var_off = tnum_unknown;
2275 	reg->frameno = 0;
2276 	reg->precise = !env->bpf_capable;
2277 	__mark_reg_unbounded(reg);
2278 }
2279 
2280 static void mark_reg_unknown(struct bpf_verifier_env *env,
2281 			     struct bpf_reg_state *regs, u32 regno)
2282 {
2283 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2284 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2285 		/* Something bad happened, let's kill all regs except FP */
2286 		for (regno = 0; regno < BPF_REG_FP; regno++)
2287 			__mark_reg_not_init(env, regs + regno);
2288 		return;
2289 	}
2290 	__mark_reg_unknown(env, regs + regno);
2291 }
2292 
2293 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2294 				struct bpf_reg_state *reg)
2295 {
2296 	__mark_reg_unknown(env, reg);
2297 	reg->type = NOT_INIT;
2298 }
2299 
2300 static void mark_reg_not_init(struct bpf_verifier_env *env,
2301 			      struct bpf_reg_state *regs, u32 regno)
2302 {
2303 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2304 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2305 		/* Something bad happened, let's kill all regs except FP */
2306 		for (regno = 0; regno < BPF_REG_FP; regno++)
2307 			__mark_reg_not_init(env, regs + regno);
2308 		return;
2309 	}
2310 	__mark_reg_not_init(env, regs + regno);
2311 }
2312 
2313 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2314 			    struct bpf_reg_state *regs, u32 regno,
2315 			    enum bpf_reg_type reg_type,
2316 			    struct btf *btf, u32 btf_id,
2317 			    enum bpf_type_flag flag)
2318 {
2319 	if (reg_type == SCALAR_VALUE) {
2320 		mark_reg_unknown(env, regs, regno);
2321 		return;
2322 	}
2323 	mark_reg_known_zero(env, regs, regno);
2324 	regs[regno].type = PTR_TO_BTF_ID | flag;
2325 	regs[regno].btf = btf;
2326 	regs[regno].btf_id = btf_id;
2327 }
2328 
2329 #define DEF_NOT_SUBREG	(0)
2330 static void init_reg_state(struct bpf_verifier_env *env,
2331 			   struct bpf_func_state *state)
2332 {
2333 	struct bpf_reg_state *regs = state->regs;
2334 	int i;
2335 
2336 	for (i = 0; i < MAX_BPF_REG; i++) {
2337 		mark_reg_not_init(env, regs, i);
2338 		regs[i].live = REG_LIVE_NONE;
2339 		regs[i].parent = NULL;
2340 		regs[i].subreg_def = DEF_NOT_SUBREG;
2341 	}
2342 
2343 	/* frame pointer */
2344 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2345 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2346 	regs[BPF_REG_FP].frameno = state->frameno;
2347 }
2348 
2349 #define BPF_MAIN_FUNC (-1)
2350 static void init_func_state(struct bpf_verifier_env *env,
2351 			    struct bpf_func_state *state,
2352 			    int callsite, int frameno, int subprogno)
2353 {
2354 	state->callsite = callsite;
2355 	state->frameno = frameno;
2356 	state->subprogno = subprogno;
2357 	state->callback_ret_range = tnum_range(0, 0);
2358 	init_reg_state(env, state);
2359 	mark_verifier_state_scratched(env);
2360 }
2361 
2362 /* Similar to push_stack(), but for async callbacks */
2363 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2364 						int insn_idx, int prev_insn_idx,
2365 						int subprog)
2366 {
2367 	struct bpf_verifier_stack_elem *elem;
2368 	struct bpf_func_state *frame;
2369 
2370 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2371 	if (!elem)
2372 		goto err;
2373 
2374 	elem->insn_idx = insn_idx;
2375 	elem->prev_insn_idx = prev_insn_idx;
2376 	elem->next = env->head;
2377 	elem->log_pos = env->log.end_pos;
2378 	env->head = elem;
2379 	env->stack_size++;
2380 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2381 		verbose(env,
2382 			"The sequence of %d jumps is too complex for async cb.\n",
2383 			env->stack_size);
2384 		goto err;
2385 	}
2386 	/* Unlike push_stack() do not copy_verifier_state().
2387 	 * The caller state doesn't matter.
2388 	 * This is async callback. It starts in a fresh stack.
2389 	 * Initialize it similar to do_check_common().
2390 	 */
2391 	elem->st.branches = 1;
2392 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2393 	if (!frame)
2394 		goto err;
2395 	init_func_state(env, frame,
2396 			BPF_MAIN_FUNC /* callsite */,
2397 			0 /* frameno within this callchain */,
2398 			subprog /* subprog number within this prog */);
2399 	elem->st.frame[0] = frame;
2400 	return &elem->st;
2401 err:
2402 	free_verifier_state(env->cur_state, true);
2403 	env->cur_state = NULL;
2404 	/* pop all elements and return */
2405 	while (!pop_stack(env, NULL, NULL, false));
2406 	return NULL;
2407 }
2408 
2409 
2410 enum reg_arg_type {
2411 	SRC_OP,		/* register is used as source operand */
2412 	DST_OP,		/* register is used as destination operand */
2413 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2414 };
2415 
2416 static int cmp_subprogs(const void *a, const void *b)
2417 {
2418 	return ((struct bpf_subprog_info *)a)->start -
2419 	       ((struct bpf_subprog_info *)b)->start;
2420 }
2421 
2422 static int find_subprog(struct bpf_verifier_env *env, int off)
2423 {
2424 	struct bpf_subprog_info *p;
2425 
2426 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2427 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2428 	if (!p)
2429 		return -ENOENT;
2430 	return p - env->subprog_info;
2431 
2432 }
2433 
2434 static int add_subprog(struct bpf_verifier_env *env, int off)
2435 {
2436 	int insn_cnt = env->prog->len;
2437 	int ret;
2438 
2439 	if (off >= insn_cnt || off < 0) {
2440 		verbose(env, "call to invalid destination\n");
2441 		return -EINVAL;
2442 	}
2443 	ret = find_subprog(env, off);
2444 	if (ret >= 0)
2445 		return ret;
2446 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2447 		verbose(env, "too many subprograms\n");
2448 		return -E2BIG;
2449 	}
2450 	/* determine subprog starts. The end is one before the next starts */
2451 	env->subprog_info[env->subprog_cnt++].start = off;
2452 	sort(env->subprog_info, env->subprog_cnt,
2453 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2454 	return env->subprog_cnt - 1;
2455 }
2456 
2457 #define MAX_KFUNC_DESCS 256
2458 #define MAX_KFUNC_BTFS	256
2459 
2460 struct bpf_kfunc_desc {
2461 	struct btf_func_model func_model;
2462 	u32 func_id;
2463 	s32 imm;
2464 	u16 offset;
2465 	unsigned long addr;
2466 };
2467 
2468 struct bpf_kfunc_btf {
2469 	struct btf *btf;
2470 	struct module *module;
2471 	u16 offset;
2472 };
2473 
2474 struct bpf_kfunc_desc_tab {
2475 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2476 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2477 	 * available, therefore at the end of verification do_misc_fixups()
2478 	 * sorts this by imm and offset.
2479 	 */
2480 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2481 	u32 nr_descs;
2482 };
2483 
2484 struct bpf_kfunc_btf_tab {
2485 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2486 	u32 nr_descs;
2487 };
2488 
2489 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2490 {
2491 	const struct bpf_kfunc_desc *d0 = a;
2492 	const struct bpf_kfunc_desc *d1 = b;
2493 
2494 	/* func_id is not greater than BTF_MAX_TYPE */
2495 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2496 }
2497 
2498 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2499 {
2500 	const struct bpf_kfunc_btf *d0 = a;
2501 	const struct bpf_kfunc_btf *d1 = b;
2502 
2503 	return d0->offset - d1->offset;
2504 }
2505 
2506 static const struct bpf_kfunc_desc *
2507 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2508 {
2509 	struct bpf_kfunc_desc desc = {
2510 		.func_id = func_id,
2511 		.offset = offset,
2512 	};
2513 	struct bpf_kfunc_desc_tab *tab;
2514 
2515 	tab = prog->aux->kfunc_tab;
2516 	return bsearch(&desc, tab->descs, tab->nr_descs,
2517 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2518 }
2519 
2520 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2521 		       u16 btf_fd_idx, u8 **func_addr)
2522 {
2523 	const struct bpf_kfunc_desc *desc;
2524 
2525 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2526 	if (!desc)
2527 		return -EFAULT;
2528 
2529 	*func_addr = (u8 *)desc->addr;
2530 	return 0;
2531 }
2532 
2533 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2534 					 s16 offset)
2535 {
2536 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2537 	struct bpf_kfunc_btf_tab *tab;
2538 	struct bpf_kfunc_btf *b;
2539 	struct module *mod;
2540 	struct btf *btf;
2541 	int btf_fd;
2542 
2543 	tab = env->prog->aux->kfunc_btf_tab;
2544 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2545 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2546 	if (!b) {
2547 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2548 			verbose(env, "too many different module BTFs\n");
2549 			return ERR_PTR(-E2BIG);
2550 		}
2551 
2552 		if (bpfptr_is_null(env->fd_array)) {
2553 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2554 			return ERR_PTR(-EPROTO);
2555 		}
2556 
2557 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2558 					    offset * sizeof(btf_fd),
2559 					    sizeof(btf_fd)))
2560 			return ERR_PTR(-EFAULT);
2561 
2562 		btf = btf_get_by_fd(btf_fd);
2563 		if (IS_ERR(btf)) {
2564 			verbose(env, "invalid module BTF fd specified\n");
2565 			return btf;
2566 		}
2567 
2568 		if (!btf_is_module(btf)) {
2569 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2570 			btf_put(btf);
2571 			return ERR_PTR(-EINVAL);
2572 		}
2573 
2574 		mod = btf_try_get_module(btf);
2575 		if (!mod) {
2576 			btf_put(btf);
2577 			return ERR_PTR(-ENXIO);
2578 		}
2579 
2580 		b = &tab->descs[tab->nr_descs++];
2581 		b->btf = btf;
2582 		b->module = mod;
2583 		b->offset = offset;
2584 
2585 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2586 		     kfunc_btf_cmp_by_off, NULL);
2587 	}
2588 	return b->btf;
2589 }
2590 
2591 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2592 {
2593 	if (!tab)
2594 		return;
2595 
2596 	while (tab->nr_descs--) {
2597 		module_put(tab->descs[tab->nr_descs].module);
2598 		btf_put(tab->descs[tab->nr_descs].btf);
2599 	}
2600 	kfree(tab);
2601 }
2602 
2603 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2604 {
2605 	if (offset) {
2606 		if (offset < 0) {
2607 			/* In the future, this can be allowed to increase limit
2608 			 * of fd index into fd_array, interpreted as u16.
2609 			 */
2610 			verbose(env, "negative offset disallowed for kernel module function call\n");
2611 			return ERR_PTR(-EINVAL);
2612 		}
2613 
2614 		return __find_kfunc_desc_btf(env, offset);
2615 	}
2616 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2617 }
2618 
2619 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2620 {
2621 	const struct btf_type *func, *func_proto;
2622 	struct bpf_kfunc_btf_tab *btf_tab;
2623 	struct bpf_kfunc_desc_tab *tab;
2624 	struct bpf_prog_aux *prog_aux;
2625 	struct bpf_kfunc_desc *desc;
2626 	const char *func_name;
2627 	struct btf *desc_btf;
2628 	unsigned long call_imm;
2629 	unsigned long addr;
2630 	int err;
2631 
2632 	prog_aux = env->prog->aux;
2633 	tab = prog_aux->kfunc_tab;
2634 	btf_tab = prog_aux->kfunc_btf_tab;
2635 	if (!tab) {
2636 		if (!btf_vmlinux) {
2637 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2638 			return -ENOTSUPP;
2639 		}
2640 
2641 		if (!env->prog->jit_requested) {
2642 			verbose(env, "JIT is required for calling kernel function\n");
2643 			return -ENOTSUPP;
2644 		}
2645 
2646 		if (!bpf_jit_supports_kfunc_call()) {
2647 			verbose(env, "JIT does not support calling kernel function\n");
2648 			return -ENOTSUPP;
2649 		}
2650 
2651 		if (!env->prog->gpl_compatible) {
2652 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2653 			return -EINVAL;
2654 		}
2655 
2656 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2657 		if (!tab)
2658 			return -ENOMEM;
2659 		prog_aux->kfunc_tab = tab;
2660 	}
2661 
2662 	/* func_id == 0 is always invalid, but instead of returning an error, be
2663 	 * conservative and wait until the code elimination pass before returning
2664 	 * error, so that invalid calls that get pruned out can be in BPF programs
2665 	 * loaded from userspace.  It is also required that offset be untouched
2666 	 * for such calls.
2667 	 */
2668 	if (!func_id && !offset)
2669 		return 0;
2670 
2671 	if (!btf_tab && offset) {
2672 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2673 		if (!btf_tab)
2674 			return -ENOMEM;
2675 		prog_aux->kfunc_btf_tab = btf_tab;
2676 	}
2677 
2678 	desc_btf = find_kfunc_desc_btf(env, offset);
2679 	if (IS_ERR(desc_btf)) {
2680 		verbose(env, "failed to find BTF for kernel function\n");
2681 		return PTR_ERR(desc_btf);
2682 	}
2683 
2684 	if (find_kfunc_desc(env->prog, func_id, offset))
2685 		return 0;
2686 
2687 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2688 		verbose(env, "too many different kernel function calls\n");
2689 		return -E2BIG;
2690 	}
2691 
2692 	func = btf_type_by_id(desc_btf, func_id);
2693 	if (!func || !btf_type_is_func(func)) {
2694 		verbose(env, "kernel btf_id %u is not a function\n",
2695 			func_id);
2696 		return -EINVAL;
2697 	}
2698 	func_proto = btf_type_by_id(desc_btf, func->type);
2699 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2700 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2701 			func_id);
2702 		return -EINVAL;
2703 	}
2704 
2705 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2706 	addr = kallsyms_lookup_name(func_name);
2707 	if (!addr) {
2708 		verbose(env, "cannot find address for kernel function %s\n",
2709 			func_name);
2710 		return -EINVAL;
2711 	}
2712 	specialize_kfunc(env, func_id, offset, &addr);
2713 
2714 	if (bpf_jit_supports_far_kfunc_call()) {
2715 		call_imm = func_id;
2716 	} else {
2717 		call_imm = BPF_CALL_IMM(addr);
2718 		/* Check whether the relative offset overflows desc->imm */
2719 		if ((unsigned long)(s32)call_imm != call_imm) {
2720 			verbose(env, "address of kernel function %s is out of range\n",
2721 				func_name);
2722 			return -EINVAL;
2723 		}
2724 	}
2725 
2726 	if (bpf_dev_bound_kfunc_id(func_id)) {
2727 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2728 		if (err)
2729 			return err;
2730 	}
2731 
2732 	desc = &tab->descs[tab->nr_descs++];
2733 	desc->func_id = func_id;
2734 	desc->imm = call_imm;
2735 	desc->offset = offset;
2736 	desc->addr = addr;
2737 	err = btf_distill_func_proto(&env->log, desc_btf,
2738 				     func_proto, func_name,
2739 				     &desc->func_model);
2740 	if (!err)
2741 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2742 		     kfunc_desc_cmp_by_id_off, NULL);
2743 	return err;
2744 }
2745 
2746 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2747 {
2748 	const struct bpf_kfunc_desc *d0 = a;
2749 	const struct bpf_kfunc_desc *d1 = b;
2750 
2751 	if (d0->imm != d1->imm)
2752 		return d0->imm < d1->imm ? -1 : 1;
2753 	if (d0->offset != d1->offset)
2754 		return d0->offset < d1->offset ? -1 : 1;
2755 	return 0;
2756 }
2757 
2758 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2759 {
2760 	struct bpf_kfunc_desc_tab *tab;
2761 
2762 	tab = prog->aux->kfunc_tab;
2763 	if (!tab)
2764 		return;
2765 
2766 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2767 	     kfunc_desc_cmp_by_imm_off, NULL);
2768 }
2769 
2770 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2771 {
2772 	return !!prog->aux->kfunc_tab;
2773 }
2774 
2775 const struct btf_func_model *
2776 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2777 			 const struct bpf_insn *insn)
2778 {
2779 	const struct bpf_kfunc_desc desc = {
2780 		.imm = insn->imm,
2781 		.offset = insn->off,
2782 	};
2783 	const struct bpf_kfunc_desc *res;
2784 	struct bpf_kfunc_desc_tab *tab;
2785 
2786 	tab = prog->aux->kfunc_tab;
2787 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2788 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2789 
2790 	return res ? &res->func_model : NULL;
2791 }
2792 
2793 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2794 {
2795 	struct bpf_subprog_info *subprog = env->subprog_info;
2796 	struct bpf_insn *insn = env->prog->insnsi;
2797 	int i, ret, insn_cnt = env->prog->len;
2798 
2799 	/* Add entry function. */
2800 	ret = add_subprog(env, 0);
2801 	if (ret)
2802 		return ret;
2803 
2804 	for (i = 0; i < insn_cnt; i++, insn++) {
2805 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2806 		    !bpf_pseudo_kfunc_call(insn))
2807 			continue;
2808 
2809 		if (!env->bpf_capable) {
2810 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2811 			return -EPERM;
2812 		}
2813 
2814 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2815 			ret = add_subprog(env, i + insn->imm + 1);
2816 		else
2817 			ret = add_kfunc_call(env, insn->imm, insn->off);
2818 
2819 		if (ret < 0)
2820 			return ret;
2821 	}
2822 
2823 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2824 	 * logic. 'subprog_cnt' should not be increased.
2825 	 */
2826 	subprog[env->subprog_cnt].start = insn_cnt;
2827 
2828 	if (env->log.level & BPF_LOG_LEVEL2)
2829 		for (i = 0; i < env->subprog_cnt; i++)
2830 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2831 
2832 	return 0;
2833 }
2834 
2835 static int check_subprogs(struct bpf_verifier_env *env)
2836 {
2837 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2838 	struct bpf_subprog_info *subprog = env->subprog_info;
2839 	struct bpf_insn *insn = env->prog->insnsi;
2840 	int insn_cnt = env->prog->len;
2841 
2842 	/* now check that all jumps are within the same subprog */
2843 	subprog_start = subprog[cur_subprog].start;
2844 	subprog_end = subprog[cur_subprog + 1].start;
2845 	for (i = 0; i < insn_cnt; i++) {
2846 		u8 code = insn[i].code;
2847 
2848 		if (code == (BPF_JMP | BPF_CALL) &&
2849 		    insn[i].src_reg == 0 &&
2850 		    insn[i].imm == BPF_FUNC_tail_call)
2851 			subprog[cur_subprog].has_tail_call = true;
2852 		if (BPF_CLASS(code) == BPF_LD &&
2853 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2854 			subprog[cur_subprog].has_ld_abs = true;
2855 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2856 			goto next;
2857 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2858 			goto next;
2859 		if (code == (BPF_JMP32 | BPF_JA))
2860 			off = i + insn[i].imm + 1;
2861 		else
2862 			off = i + insn[i].off + 1;
2863 		if (off < subprog_start || off >= subprog_end) {
2864 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2865 			return -EINVAL;
2866 		}
2867 next:
2868 		if (i == subprog_end - 1) {
2869 			/* to avoid fall-through from one subprog into another
2870 			 * the last insn of the subprog should be either exit
2871 			 * or unconditional jump back
2872 			 */
2873 			if (code != (BPF_JMP | BPF_EXIT) &&
2874 			    code != (BPF_JMP32 | BPF_JA) &&
2875 			    code != (BPF_JMP | BPF_JA)) {
2876 				verbose(env, "last insn is not an exit or jmp\n");
2877 				return -EINVAL;
2878 			}
2879 			subprog_start = subprog_end;
2880 			cur_subprog++;
2881 			if (cur_subprog < env->subprog_cnt)
2882 				subprog_end = subprog[cur_subprog + 1].start;
2883 		}
2884 	}
2885 	return 0;
2886 }
2887 
2888 /* Parentage chain of this register (or stack slot) should take care of all
2889  * issues like callee-saved registers, stack slot allocation time, etc.
2890  */
2891 static int mark_reg_read(struct bpf_verifier_env *env,
2892 			 const struct bpf_reg_state *state,
2893 			 struct bpf_reg_state *parent, u8 flag)
2894 {
2895 	bool writes = parent == state->parent; /* Observe write marks */
2896 	int cnt = 0;
2897 
2898 	while (parent) {
2899 		/* if read wasn't screened by an earlier write ... */
2900 		if (writes && state->live & REG_LIVE_WRITTEN)
2901 			break;
2902 		if (parent->live & REG_LIVE_DONE) {
2903 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2904 				reg_type_str(env, parent->type),
2905 				parent->var_off.value, parent->off);
2906 			return -EFAULT;
2907 		}
2908 		/* The first condition is more likely to be true than the
2909 		 * second, checked it first.
2910 		 */
2911 		if ((parent->live & REG_LIVE_READ) == flag ||
2912 		    parent->live & REG_LIVE_READ64)
2913 			/* The parentage chain never changes and
2914 			 * this parent was already marked as LIVE_READ.
2915 			 * There is no need to keep walking the chain again and
2916 			 * keep re-marking all parents as LIVE_READ.
2917 			 * This case happens when the same register is read
2918 			 * multiple times without writes into it in-between.
2919 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2920 			 * then no need to set the weak REG_LIVE_READ32.
2921 			 */
2922 			break;
2923 		/* ... then we depend on parent's value */
2924 		parent->live |= flag;
2925 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2926 		if (flag == REG_LIVE_READ64)
2927 			parent->live &= ~REG_LIVE_READ32;
2928 		state = parent;
2929 		parent = state->parent;
2930 		writes = true;
2931 		cnt++;
2932 	}
2933 
2934 	if (env->longest_mark_read_walk < cnt)
2935 		env->longest_mark_read_walk = cnt;
2936 	return 0;
2937 }
2938 
2939 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2940 {
2941 	struct bpf_func_state *state = func(env, reg);
2942 	int spi, ret;
2943 
2944 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2945 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2946 	 * check_kfunc_call.
2947 	 */
2948 	if (reg->type == CONST_PTR_TO_DYNPTR)
2949 		return 0;
2950 	spi = dynptr_get_spi(env, reg);
2951 	if (spi < 0)
2952 		return spi;
2953 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2954 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2955 	 * read.
2956 	 */
2957 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2958 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2959 	if (ret)
2960 		return ret;
2961 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2962 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2963 }
2964 
2965 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2966 			  int spi, int nr_slots)
2967 {
2968 	struct bpf_func_state *state = func(env, reg);
2969 	int err, i;
2970 
2971 	for (i = 0; i < nr_slots; i++) {
2972 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2973 
2974 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2975 		if (err)
2976 			return err;
2977 
2978 		mark_stack_slot_scratched(env, spi - i);
2979 	}
2980 
2981 	return 0;
2982 }
2983 
2984 /* This function is supposed to be used by the following 32-bit optimization
2985  * code only. It returns TRUE if the source or destination register operates
2986  * on 64-bit, otherwise return FALSE.
2987  */
2988 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2989 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2990 {
2991 	u8 code, class, op;
2992 
2993 	code = insn->code;
2994 	class = BPF_CLASS(code);
2995 	op = BPF_OP(code);
2996 	if (class == BPF_JMP) {
2997 		/* BPF_EXIT for "main" will reach here. Return TRUE
2998 		 * conservatively.
2999 		 */
3000 		if (op == BPF_EXIT)
3001 			return true;
3002 		if (op == BPF_CALL) {
3003 			/* BPF to BPF call will reach here because of marking
3004 			 * caller saved clobber with DST_OP_NO_MARK for which we
3005 			 * don't care the register def because they are anyway
3006 			 * marked as NOT_INIT already.
3007 			 */
3008 			if (insn->src_reg == BPF_PSEUDO_CALL)
3009 				return false;
3010 			/* Helper call will reach here because of arg type
3011 			 * check, conservatively return TRUE.
3012 			 */
3013 			if (t == SRC_OP)
3014 				return true;
3015 
3016 			return false;
3017 		}
3018 	}
3019 
3020 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3021 		return false;
3022 
3023 	if (class == BPF_ALU64 || class == BPF_JMP ||
3024 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3025 		return true;
3026 
3027 	if (class == BPF_ALU || class == BPF_JMP32)
3028 		return false;
3029 
3030 	if (class == BPF_LDX) {
3031 		if (t != SRC_OP)
3032 			return BPF_SIZE(code) == BPF_DW;
3033 		/* LDX source must be ptr. */
3034 		return true;
3035 	}
3036 
3037 	if (class == BPF_STX) {
3038 		/* BPF_STX (including atomic variants) has multiple source
3039 		 * operands, one of which is a ptr. Check whether the caller is
3040 		 * asking about it.
3041 		 */
3042 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3043 			return true;
3044 		return BPF_SIZE(code) == BPF_DW;
3045 	}
3046 
3047 	if (class == BPF_LD) {
3048 		u8 mode = BPF_MODE(code);
3049 
3050 		/* LD_IMM64 */
3051 		if (mode == BPF_IMM)
3052 			return true;
3053 
3054 		/* Both LD_IND and LD_ABS return 32-bit data. */
3055 		if (t != SRC_OP)
3056 			return  false;
3057 
3058 		/* Implicit ctx ptr. */
3059 		if (regno == BPF_REG_6)
3060 			return true;
3061 
3062 		/* Explicit source could be any width. */
3063 		return true;
3064 	}
3065 
3066 	if (class == BPF_ST)
3067 		/* The only source register for BPF_ST is a ptr. */
3068 		return true;
3069 
3070 	/* Conservatively return true at default. */
3071 	return true;
3072 }
3073 
3074 /* Return the regno defined by the insn, or -1. */
3075 static int insn_def_regno(const struct bpf_insn *insn)
3076 {
3077 	switch (BPF_CLASS(insn->code)) {
3078 	case BPF_JMP:
3079 	case BPF_JMP32:
3080 	case BPF_ST:
3081 		return -1;
3082 	case BPF_STX:
3083 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3084 		    (insn->imm & BPF_FETCH)) {
3085 			if (insn->imm == BPF_CMPXCHG)
3086 				return BPF_REG_0;
3087 			else
3088 				return insn->src_reg;
3089 		} else {
3090 			return -1;
3091 		}
3092 	default:
3093 		return insn->dst_reg;
3094 	}
3095 }
3096 
3097 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3098 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3099 {
3100 	int dst_reg = insn_def_regno(insn);
3101 
3102 	if (dst_reg == -1)
3103 		return false;
3104 
3105 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3106 }
3107 
3108 static void mark_insn_zext(struct bpf_verifier_env *env,
3109 			   struct bpf_reg_state *reg)
3110 {
3111 	s32 def_idx = reg->subreg_def;
3112 
3113 	if (def_idx == DEF_NOT_SUBREG)
3114 		return;
3115 
3116 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3117 	/* The dst will be zero extended, so won't be sub-register anymore. */
3118 	reg->subreg_def = DEF_NOT_SUBREG;
3119 }
3120 
3121 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3122 			 enum reg_arg_type t)
3123 {
3124 	struct bpf_verifier_state *vstate = env->cur_state;
3125 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3126 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3127 	struct bpf_reg_state *reg, *regs = state->regs;
3128 	bool rw64;
3129 
3130 	if (regno >= MAX_BPF_REG) {
3131 		verbose(env, "R%d is invalid\n", regno);
3132 		return -EINVAL;
3133 	}
3134 
3135 	mark_reg_scratched(env, regno);
3136 
3137 	reg = &regs[regno];
3138 	rw64 = is_reg64(env, insn, regno, reg, t);
3139 	if (t == SRC_OP) {
3140 		/* check whether register used as source operand can be read */
3141 		if (reg->type == NOT_INIT) {
3142 			verbose(env, "R%d !read_ok\n", regno);
3143 			return -EACCES;
3144 		}
3145 		/* We don't need to worry about FP liveness because it's read-only */
3146 		if (regno == BPF_REG_FP)
3147 			return 0;
3148 
3149 		if (rw64)
3150 			mark_insn_zext(env, reg);
3151 
3152 		return mark_reg_read(env, reg, reg->parent,
3153 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3154 	} else {
3155 		/* check whether register used as dest operand can be written to */
3156 		if (regno == BPF_REG_FP) {
3157 			verbose(env, "frame pointer is read only\n");
3158 			return -EACCES;
3159 		}
3160 		reg->live |= REG_LIVE_WRITTEN;
3161 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3162 		if (t == DST_OP)
3163 			mark_reg_unknown(env, regs, regno);
3164 	}
3165 	return 0;
3166 }
3167 
3168 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3169 {
3170 	env->insn_aux_data[idx].jmp_point = true;
3171 }
3172 
3173 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3174 {
3175 	return env->insn_aux_data[insn_idx].jmp_point;
3176 }
3177 
3178 /* for any branch, call, exit record the history of jmps in the given state */
3179 static int push_jmp_history(struct bpf_verifier_env *env,
3180 			    struct bpf_verifier_state *cur)
3181 {
3182 	u32 cnt = cur->jmp_history_cnt;
3183 	struct bpf_idx_pair *p;
3184 	size_t alloc_size;
3185 
3186 	if (!is_jmp_point(env, env->insn_idx))
3187 		return 0;
3188 
3189 	cnt++;
3190 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3191 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3192 	if (!p)
3193 		return -ENOMEM;
3194 	p[cnt - 1].idx = env->insn_idx;
3195 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3196 	cur->jmp_history = p;
3197 	cur->jmp_history_cnt = cnt;
3198 	return 0;
3199 }
3200 
3201 /* Backtrack one insn at a time. If idx is not at the top of recorded
3202  * history then previous instruction came from straight line execution.
3203  */
3204 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3205 			     u32 *history)
3206 {
3207 	u32 cnt = *history;
3208 
3209 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3210 		i = st->jmp_history[cnt - 1].prev_idx;
3211 		(*history)--;
3212 	} else {
3213 		i--;
3214 	}
3215 	return i;
3216 }
3217 
3218 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3219 {
3220 	const struct btf_type *func;
3221 	struct btf *desc_btf;
3222 
3223 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3224 		return NULL;
3225 
3226 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3227 	if (IS_ERR(desc_btf))
3228 		return "<error>";
3229 
3230 	func = btf_type_by_id(desc_btf, insn->imm);
3231 	return btf_name_by_offset(desc_btf, func->name_off);
3232 }
3233 
3234 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3235 {
3236 	bt->frame = frame;
3237 }
3238 
3239 static inline void bt_reset(struct backtrack_state *bt)
3240 {
3241 	struct bpf_verifier_env *env = bt->env;
3242 
3243 	memset(bt, 0, sizeof(*bt));
3244 	bt->env = env;
3245 }
3246 
3247 static inline u32 bt_empty(struct backtrack_state *bt)
3248 {
3249 	u64 mask = 0;
3250 	int i;
3251 
3252 	for (i = 0; i <= bt->frame; i++)
3253 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3254 
3255 	return mask == 0;
3256 }
3257 
3258 static inline int bt_subprog_enter(struct backtrack_state *bt)
3259 {
3260 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3261 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3262 		WARN_ONCE(1, "verifier backtracking bug");
3263 		return -EFAULT;
3264 	}
3265 	bt->frame++;
3266 	return 0;
3267 }
3268 
3269 static inline int bt_subprog_exit(struct backtrack_state *bt)
3270 {
3271 	if (bt->frame == 0) {
3272 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3273 		WARN_ONCE(1, "verifier backtracking bug");
3274 		return -EFAULT;
3275 	}
3276 	bt->frame--;
3277 	return 0;
3278 }
3279 
3280 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3281 {
3282 	bt->reg_masks[frame] |= 1 << reg;
3283 }
3284 
3285 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3286 {
3287 	bt->reg_masks[frame] &= ~(1 << reg);
3288 }
3289 
3290 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3291 {
3292 	bt_set_frame_reg(bt, bt->frame, reg);
3293 }
3294 
3295 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3296 {
3297 	bt_clear_frame_reg(bt, bt->frame, reg);
3298 }
3299 
3300 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3301 {
3302 	bt->stack_masks[frame] |= 1ull << slot;
3303 }
3304 
3305 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3306 {
3307 	bt->stack_masks[frame] &= ~(1ull << slot);
3308 }
3309 
3310 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3311 {
3312 	bt_set_frame_slot(bt, bt->frame, slot);
3313 }
3314 
3315 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3316 {
3317 	bt_clear_frame_slot(bt, bt->frame, slot);
3318 }
3319 
3320 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3321 {
3322 	return bt->reg_masks[frame];
3323 }
3324 
3325 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3326 {
3327 	return bt->reg_masks[bt->frame];
3328 }
3329 
3330 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3331 {
3332 	return bt->stack_masks[frame];
3333 }
3334 
3335 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3336 {
3337 	return bt->stack_masks[bt->frame];
3338 }
3339 
3340 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3341 {
3342 	return bt->reg_masks[bt->frame] & (1 << reg);
3343 }
3344 
3345 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3346 {
3347 	return bt->stack_masks[bt->frame] & (1ull << slot);
3348 }
3349 
3350 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3351 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3352 {
3353 	DECLARE_BITMAP(mask, 64);
3354 	bool first = true;
3355 	int i, n;
3356 
3357 	buf[0] = '\0';
3358 
3359 	bitmap_from_u64(mask, reg_mask);
3360 	for_each_set_bit(i, mask, 32) {
3361 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3362 		first = false;
3363 		buf += n;
3364 		buf_sz -= n;
3365 		if (buf_sz < 0)
3366 			break;
3367 	}
3368 }
3369 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3370 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3371 {
3372 	DECLARE_BITMAP(mask, 64);
3373 	bool first = true;
3374 	int i, n;
3375 
3376 	buf[0] = '\0';
3377 
3378 	bitmap_from_u64(mask, stack_mask);
3379 	for_each_set_bit(i, mask, 64) {
3380 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3381 		first = false;
3382 		buf += n;
3383 		buf_sz -= n;
3384 		if (buf_sz < 0)
3385 			break;
3386 	}
3387 }
3388 
3389 /* For given verifier state backtrack_insn() is called from the last insn to
3390  * the first insn. Its purpose is to compute a bitmask of registers and
3391  * stack slots that needs precision in the parent verifier state.
3392  *
3393  * @idx is an index of the instruction we are currently processing;
3394  * @subseq_idx is an index of the subsequent instruction that:
3395  *   - *would be* executed next, if jump history is viewed in forward order;
3396  *   - *was* processed previously during backtracking.
3397  */
3398 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3399 			  struct backtrack_state *bt)
3400 {
3401 	const struct bpf_insn_cbs cbs = {
3402 		.cb_call	= disasm_kfunc_name,
3403 		.cb_print	= verbose,
3404 		.private_data	= env,
3405 	};
3406 	struct bpf_insn *insn = env->prog->insnsi + idx;
3407 	u8 class = BPF_CLASS(insn->code);
3408 	u8 opcode = BPF_OP(insn->code);
3409 	u8 mode = BPF_MODE(insn->code);
3410 	u32 dreg = insn->dst_reg;
3411 	u32 sreg = insn->src_reg;
3412 	u32 spi, i;
3413 
3414 	if (insn->code == 0)
3415 		return 0;
3416 	if (env->log.level & BPF_LOG_LEVEL2) {
3417 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3418 		verbose(env, "mark_precise: frame%d: regs=%s ",
3419 			bt->frame, env->tmp_str_buf);
3420 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3421 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3422 		verbose(env, "%d: ", idx);
3423 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3424 	}
3425 
3426 	if (class == BPF_ALU || class == BPF_ALU64) {
3427 		if (!bt_is_reg_set(bt, dreg))
3428 			return 0;
3429 		if (opcode == BPF_MOV) {
3430 			if (BPF_SRC(insn->code) == BPF_X) {
3431 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3432 				 * dreg needs precision after this insn
3433 				 * sreg needs precision before this insn
3434 				 */
3435 				bt_clear_reg(bt, dreg);
3436 				bt_set_reg(bt, sreg);
3437 			} else {
3438 				/* dreg = K
3439 				 * dreg needs precision after this insn.
3440 				 * Corresponding register is already marked
3441 				 * as precise=true in this verifier state.
3442 				 * No further markings in parent are necessary
3443 				 */
3444 				bt_clear_reg(bt, dreg);
3445 			}
3446 		} else {
3447 			if (BPF_SRC(insn->code) == BPF_X) {
3448 				/* dreg += sreg
3449 				 * both dreg and sreg need precision
3450 				 * before this insn
3451 				 */
3452 				bt_set_reg(bt, sreg);
3453 			} /* else dreg += K
3454 			   * dreg still needs precision before this insn
3455 			   */
3456 		}
3457 	} else if (class == BPF_LDX) {
3458 		if (!bt_is_reg_set(bt, dreg))
3459 			return 0;
3460 		bt_clear_reg(bt, dreg);
3461 
3462 		/* scalars can only be spilled into stack w/o losing precision.
3463 		 * Load from any other memory can be zero extended.
3464 		 * The desire to keep that precision is already indicated
3465 		 * by 'precise' mark in corresponding register of this state.
3466 		 * No further tracking necessary.
3467 		 */
3468 		if (insn->src_reg != BPF_REG_FP)
3469 			return 0;
3470 
3471 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3472 		 * that [fp - off] slot contains scalar that needs to be
3473 		 * tracked with precision
3474 		 */
3475 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3476 		if (spi >= 64) {
3477 			verbose(env, "BUG spi %d\n", spi);
3478 			WARN_ONCE(1, "verifier backtracking bug");
3479 			return -EFAULT;
3480 		}
3481 		bt_set_slot(bt, spi);
3482 	} else if (class == BPF_STX || class == BPF_ST) {
3483 		if (bt_is_reg_set(bt, dreg))
3484 			/* stx & st shouldn't be using _scalar_ dst_reg
3485 			 * to access memory. It means backtracking
3486 			 * encountered a case of pointer subtraction.
3487 			 */
3488 			return -ENOTSUPP;
3489 		/* scalars can only be spilled into stack */
3490 		if (insn->dst_reg != BPF_REG_FP)
3491 			return 0;
3492 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3493 		if (spi >= 64) {
3494 			verbose(env, "BUG spi %d\n", spi);
3495 			WARN_ONCE(1, "verifier backtracking bug");
3496 			return -EFAULT;
3497 		}
3498 		if (!bt_is_slot_set(bt, spi))
3499 			return 0;
3500 		bt_clear_slot(bt, spi);
3501 		if (class == BPF_STX)
3502 			bt_set_reg(bt, sreg);
3503 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3504 		if (bpf_pseudo_call(insn)) {
3505 			int subprog_insn_idx, subprog;
3506 
3507 			subprog_insn_idx = idx + insn->imm + 1;
3508 			subprog = find_subprog(env, subprog_insn_idx);
3509 			if (subprog < 0)
3510 				return -EFAULT;
3511 
3512 			if (subprog_is_global(env, subprog)) {
3513 				/* check that jump history doesn't have any
3514 				 * extra instructions from subprog; the next
3515 				 * instruction after call to global subprog
3516 				 * should be literally next instruction in
3517 				 * caller program
3518 				 */
3519 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3520 				/* r1-r5 are invalidated after subprog call,
3521 				 * so for global func call it shouldn't be set
3522 				 * anymore
3523 				 */
3524 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3525 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3526 					WARN_ONCE(1, "verifier backtracking bug");
3527 					return -EFAULT;
3528 				}
3529 				/* global subprog always sets R0 */
3530 				bt_clear_reg(bt, BPF_REG_0);
3531 				return 0;
3532 			} else {
3533 				/* static subprog call instruction, which
3534 				 * means that we are exiting current subprog,
3535 				 * so only r1-r5 could be still requested as
3536 				 * precise, r0 and r6-r10 or any stack slot in
3537 				 * the current frame should be zero by now
3538 				 */
3539 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3540 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3541 					WARN_ONCE(1, "verifier backtracking bug");
3542 					return -EFAULT;
3543 				}
3544 				/* we don't track register spills perfectly,
3545 				 * so fallback to force-precise instead of failing */
3546 				if (bt_stack_mask(bt) != 0)
3547 					return -ENOTSUPP;
3548 				/* propagate r1-r5 to the caller */
3549 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3550 					if (bt_is_reg_set(bt, i)) {
3551 						bt_clear_reg(bt, i);
3552 						bt_set_frame_reg(bt, bt->frame - 1, i);
3553 					}
3554 				}
3555 				if (bt_subprog_exit(bt))
3556 					return -EFAULT;
3557 				return 0;
3558 			}
3559 		} else if ((bpf_helper_call(insn) &&
3560 			    is_callback_calling_function(insn->imm) &&
3561 			    !is_async_callback_calling_function(insn->imm)) ||
3562 			   (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3563 			/* callback-calling helper or kfunc call, which means
3564 			 * we are exiting from subprog, but unlike the subprog
3565 			 * call handling above, we shouldn't propagate
3566 			 * precision of r1-r5 (if any requested), as they are
3567 			 * not actually arguments passed directly to callback
3568 			 * subprogs
3569 			 */
3570 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3571 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3572 				WARN_ONCE(1, "verifier backtracking bug");
3573 				return -EFAULT;
3574 			}
3575 			if (bt_stack_mask(bt) != 0)
3576 				return -ENOTSUPP;
3577 			/* clear r1-r5 in callback subprog's mask */
3578 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3579 				bt_clear_reg(bt, i);
3580 			if (bt_subprog_exit(bt))
3581 				return -EFAULT;
3582 			return 0;
3583 		} else if (opcode == BPF_CALL) {
3584 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3585 			 * catch this error later. Make backtracking conservative
3586 			 * with ENOTSUPP.
3587 			 */
3588 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3589 				return -ENOTSUPP;
3590 			/* regular helper call sets R0 */
3591 			bt_clear_reg(bt, BPF_REG_0);
3592 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3593 				/* if backtracing was looking for registers R1-R5
3594 				 * they should have been found already.
3595 				 */
3596 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3597 				WARN_ONCE(1, "verifier backtracking bug");
3598 				return -EFAULT;
3599 			}
3600 		} else if (opcode == BPF_EXIT) {
3601 			bool r0_precise;
3602 
3603 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3604 				/* if backtracing was looking for registers R1-R5
3605 				 * they should have been found already.
3606 				 */
3607 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3608 				WARN_ONCE(1, "verifier backtracking bug");
3609 				return -EFAULT;
3610 			}
3611 
3612 			/* BPF_EXIT in subprog or callback always returns
3613 			 * right after the call instruction, so by checking
3614 			 * whether the instruction at subseq_idx-1 is subprog
3615 			 * call or not we can distinguish actual exit from
3616 			 * *subprog* from exit from *callback*. In the former
3617 			 * case, we need to propagate r0 precision, if
3618 			 * necessary. In the former we never do that.
3619 			 */
3620 			r0_precise = subseq_idx - 1 >= 0 &&
3621 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3622 				     bt_is_reg_set(bt, BPF_REG_0);
3623 
3624 			bt_clear_reg(bt, BPF_REG_0);
3625 			if (bt_subprog_enter(bt))
3626 				return -EFAULT;
3627 
3628 			if (r0_precise)
3629 				bt_set_reg(bt, BPF_REG_0);
3630 			/* r6-r9 and stack slots will stay set in caller frame
3631 			 * bitmasks until we return back from callee(s)
3632 			 */
3633 			return 0;
3634 		} else if (BPF_SRC(insn->code) == BPF_X) {
3635 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3636 				return 0;
3637 			/* dreg <cond> sreg
3638 			 * Both dreg and sreg need precision before
3639 			 * this insn. If only sreg was marked precise
3640 			 * before it would be equally necessary to
3641 			 * propagate it to dreg.
3642 			 */
3643 			bt_set_reg(bt, dreg);
3644 			bt_set_reg(bt, sreg);
3645 			 /* else dreg <cond> K
3646 			  * Only dreg still needs precision before
3647 			  * this insn, so for the K-based conditional
3648 			  * there is nothing new to be marked.
3649 			  */
3650 		}
3651 	} else if (class == BPF_LD) {
3652 		if (!bt_is_reg_set(bt, dreg))
3653 			return 0;
3654 		bt_clear_reg(bt, dreg);
3655 		/* It's ld_imm64 or ld_abs or ld_ind.
3656 		 * For ld_imm64 no further tracking of precision
3657 		 * into parent is necessary
3658 		 */
3659 		if (mode == BPF_IND || mode == BPF_ABS)
3660 			/* to be analyzed */
3661 			return -ENOTSUPP;
3662 	}
3663 	return 0;
3664 }
3665 
3666 /* the scalar precision tracking algorithm:
3667  * . at the start all registers have precise=false.
3668  * . scalar ranges are tracked as normal through alu and jmp insns.
3669  * . once precise value of the scalar register is used in:
3670  *   .  ptr + scalar alu
3671  *   . if (scalar cond K|scalar)
3672  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3673  *   backtrack through the verifier states and mark all registers and
3674  *   stack slots with spilled constants that these scalar regisers
3675  *   should be precise.
3676  * . during state pruning two registers (or spilled stack slots)
3677  *   are equivalent if both are not precise.
3678  *
3679  * Note the verifier cannot simply walk register parentage chain,
3680  * since many different registers and stack slots could have been
3681  * used to compute single precise scalar.
3682  *
3683  * The approach of starting with precise=true for all registers and then
3684  * backtrack to mark a register as not precise when the verifier detects
3685  * that program doesn't care about specific value (e.g., when helper
3686  * takes register as ARG_ANYTHING parameter) is not safe.
3687  *
3688  * It's ok to walk single parentage chain of the verifier states.
3689  * It's possible that this backtracking will go all the way till 1st insn.
3690  * All other branches will be explored for needing precision later.
3691  *
3692  * The backtracking needs to deal with cases like:
3693  *   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)
3694  * r9 -= r8
3695  * r5 = r9
3696  * if r5 > 0x79f goto pc+7
3697  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3698  * r5 += 1
3699  * ...
3700  * call bpf_perf_event_output#25
3701  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3702  *
3703  * and this case:
3704  * r6 = 1
3705  * call foo // uses callee's r6 inside to compute r0
3706  * r0 += r6
3707  * if r0 == 0 goto
3708  *
3709  * to track above reg_mask/stack_mask needs to be independent for each frame.
3710  *
3711  * Also if parent's curframe > frame where backtracking started,
3712  * the verifier need to mark registers in both frames, otherwise callees
3713  * may incorrectly prune callers. This is similar to
3714  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3715  *
3716  * For now backtracking falls back into conservative marking.
3717  */
3718 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3719 				     struct bpf_verifier_state *st)
3720 {
3721 	struct bpf_func_state *func;
3722 	struct bpf_reg_state *reg;
3723 	int i, j;
3724 
3725 	if (env->log.level & BPF_LOG_LEVEL2) {
3726 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3727 			st->curframe);
3728 	}
3729 
3730 	/* big hammer: mark all scalars precise in this path.
3731 	 * pop_stack may still get !precise scalars.
3732 	 * We also skip current state and go straight to first parent state,
3733 	 * because precision markings in current non-checkpointed state are
3734 	 * not needed. See why in the comment in __mark_chain_precision below.
3735 	 */
3736 	for (st = st->parent; st; st = st->parent) {
3737 		for (i = 0; i <= st->curframe; i++) {
3738 			func = st->frame[i];
3739 			for (j = 0; j < BPF_REG_FP; j++) {
3740 				reg = &func->regs[j];
3741 				if (reg->type != SCALAR_VALUE || reg->precise)
3742 					continue;
3743 				reg->precise = true;
3744 				if (env->log.level & BPF_LOG_LEVEL2) {
3745 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3746 						i, j);
3747 				}
3748 			}
3749 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3750 				if (!is_spilled_reg(&func->stack[j]))
3751 					continue;
3752 				reg = &func->stack[j].spilled_ptr;
3753 				if (reg->type != SCALAR_VALUE || reg->precise)
3754 					continue;
3755 				reg->precise = true;
3756 				if (env->log.level & BPF_LOG_LEVEL2) {
3757 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3758 						i, -(j + 1) * 8);
3759 				}
3760 			}
3761 		}
3762 	}
3763 }
3764 
3765 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3766 {
3767 	struct bpf_func_state *func;
3768 	struct bpf_reg_state *reg;
3769 	int i, j;
3770 
3771 	for (i = 0; i <= st->curframe; i++) {
3772 		func = st->frame[i];
3773 		for (j = 0; j < BPF_REG_FP; j++) {
3774 			reg = &func->regs[j];
3775 			if (reg->type != SCALAR_VALUE)
3776 				continue;
3777 			reg->precise = false;
3778 		}
3779 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3780 			if (!is_spilled_reg(&func->stack[j]))
3781 				continue;
3782 			reg = &func->stack[j].spilled_ptr;
3783 			if (reg->type != SCALAR_VALUE)
3784 				continue;
3785 			reg->precise = false;
3786 		}
3787 	}
3788 }
3789 
3790 static bool idset_contains(struct bpf_idset *s, u32 id)
3791 {
3792 	u32 i;
3793 
3794 	for (i = 0; i < s->count; ++i)
3795 		if (s->ids[i] == id)
3796 			return true;
3797 
3798 	return false;
3799 }
3800 
3801 static int idset_push(struct bpf_idset *s, u32 id)
3802 {
3803 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3804 		return -EFAULT;
3805 	s->ids[s->count++] = id;
3806 	return 0;
3807 }
3808 
3809 static void idset_reset(struct bpf_idset *s)
3810 {
3811 	s->count = 0;
3812 }
3813 
3814 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3815  * Mark all registers with these IDs as precise.
3816  */
3817 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3818 {
3819 	struct bpf_idset *precise_ids = &env->idset_scratch;
3820 	struct backtrack_state *bt = &env->bt;
3821 	struct bpf_func_state *func;
3822 	struct bpf_reg_state *reg;
3823 	DECLARE_BITMAP(mask, 64);
3824 	int i, fr;
3825 
3826 	idset_reset(precise_ids);
3827 
3828 	for (fr = bt->frame; fr >= 0; fr--) {
3829 		func = st->frame[fr];
3830 
3831 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3832 		for_each_set_bit(i, mask, 32) {
3833 			reg = &func->regs[i];
3834 			if (!reg->id || reg->type != SCALAR_VALUE)
3835 				continue;
3836 			if (idset_push(precise_ids, reg->id))
3837 				return -EFAULT;
3838 		}
3839 
3840 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3841 		for_each_set_bit(i, mask, 64) {
3842 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3843 				break;
3844 			if (!is_spilled_scalar_reg(&func->stack[i]))
3845 				continue;
3846 			reg = &func->stack[i].spilled_ptr;
3847 			if (!reg->id)
3848 				continue;
3849 			if (idset_push(precise_ids, reg->id))
3850 				return -EFAULT;
3851 		}
3852 	}
3853 
3854 	for (fr = 0; fr <= st->curframe; ++fr) {
3855 		func = st->frame[fr];
3856 
3857 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3858 			reg = &func->regs[i];
3859 			if (!reg->id)
3860 				continue;
3861 			if (!idset_contains(precise_ids, reg->id))
3862 				continue;
3863 			bt_set_frame_reg(bt, fr, i);
3864 		}
3865 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3866 			if (!is_spilled_scalar_reg(&func->stack[i]))
3867 				continue;
3868 			reg = &func->stack[i].spilled_ptr;
3869 			if (!reg->id)
3870 				continue;
3871 			if (!idset_contains(precise_ids, reg->id))
3872 				continue;
3873 			bt_set_frame_slot(bt, fr, i);
3874 		}
3875 	}
3876 
3877 	return 0;
3878 }
3879 
3880 /*
3881  * __mark_chain_precision() backtracks BPF program instruction sequence and
3882  * chain of verifier states making sure that register *regno* (if regno >= 0)
3883  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3884  * SCALARS, as well as any other registers and slots that contribute to
3885  * a tracked state of given registers/stack slots, depending on specific BPF
3886  * assembly instructions (see backtrack_insns() for exact instruction handling
3887  * logic). This backtracking relies on recorded jmp_history and is able to
3888  * traverse entire chain of parent states. This process ends only when all the
3889  * necessary registers/slots and their transitive dependencies are marked as
3890  * precise.
3891  *
3892  * One important and subtle aspect is that precise marks *do not matter* in
3893  * the currently verified state (current state). It is important to understand
3894  * why this is the case.
3895  *
3896  * First, note that current state is the state that is not yet "checkpointed",
3897  * i.e., it is not yet put into env->explored_states, and it has no children
3898  * states as well. It's ephemeral, and can end up either a) being discarded if
3899  * compatible explored state is found at some point or BPF_EXIT instruction is
3900  * reached or b) checkpointed and put into env->explored_states, branching out
3901  * into one or more children states.
3902  *
3903  * In the former case, precise markings in current state are completely
3904  * ignored by state comparison code (see regsafe() for details). Only
3905  * checkpointed ("old") state precise markings are important, and if old
3906  * state's register/slot is precise, regsafe() assumes current state's
3907  * register/slot as precise and checks value ranges exactly and precisely. If
3908  * states turn out to be compatible, current state's necessary precise
3909  * markings and any required parent states' precise markings are enforced
3910  * after the fact with propagate_precision() logic, after the fact. But it's
3911  * important to realize that in this case, even after marking current state
3912  * registers/slots as precise, we immediately discard current state. So what
3913  * actually matters is any of the precise markings propagated into current
3914  * state's parent states, which are always checkpointed (due to b) case above).
3915  * As such, for scenario a) it doesn't matter if current state has precise
3916  * markings set or not.
3917  *
3918  * Now, for the scenario b), checkpointing and forking into child(ren)
3919  * state(s). Note that before current state gets to checkpointing step, any
3920  * processed instruction always assumes precise SCALAR register/slot
3921  * knowledge: if precise value or range is useful to prune jump branch, BPF
3922  * verifier takes this opportunity enthusiastically. Similarly, when
3923  * register's value is used to calculate offset or memory address, exact
3924  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3925  * what we mentioned above about state comparison ignoring precise markings
3926  * during state comparison, BPF verifier ignores and also assumes precise
3927  * markings *at will* during instruction verification process. But as verifier
3928  * assumes precision, it also propagates any precision dependencies across
3929  * parent states, which are not yet finalized, so can be further restricted
3930  * based on new knowledge gained from restrictions enforced by their children
3931  * states. This is so that once those parent states are finalized, i.e., when
3932  * they have no more active children state, state comparison logic in
3933  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3934  * required for correctness.
3935  *
3936  * To build a bit more intuition, note also that once a state is checkpointed,
3937  * the path we took to get to that state is not important. This is crucial
3938  * property for state pruning. When state is checkpointed and finalized at
3939  * some instruction index, it can be correctly and safely used to "short
3940  * circuit" any *compatible* state that reaches exactly the same instruction
3941  * index. I.e., if we jumped to that instruction from a completely different
3942  * code path than original finalized state was derived from, it doesn't
3943  * matter, current state can be discarded because from that instruction
3944  * forward having a compatible state will ensure we will safely reach the
3945  * exit. States describe preconditions for further exploration, but completely
3946  * forget the history of how we got here.
3947  *
3948  * This also means that even if we needed precise SCALAR range to get to
3949  * finalized state, but from that point forward *that same* SCALAR register is
3950  * never used in a precise context (i.e., it's precise value is not needed for
3951  * correctness), it's correct and safe to mark such register as "imprecise"
3952  * (i.e., precise marking set to false). This is what we rely on when we do
3953  * not set precise marking in current state. If no child state requires
3954  * precision for any given SCALAR register, it's safe to dictate that it can
3955  * be imprecise. If any child state does require this register to be precise,
3956  * we'll mark it precise later retroactively during precise markings
3957  * propagation from child state to parent states.
3958  *
3959  * Skipping precise marking setting in current state is a mild version of
3960  * relying on the above observation. But we can utilize this property even
3961  * more aggressively by proactively forgetting any precise marking in the
3962  * current state (which we inherited from the parent state), right before we
3963  * checkpoint it and branch off into new child state. This is done by
3964  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3965  * finalized states which help in short circuiting more future states.
3966  */
3967 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3968 {
3969 	struct backtrack_state *bt = &env->bt;
3970 	struct bpf_verifier_state *st = env->cur_state;
3971 	int first_idx = st->first_insn_idx;
3972 	int last_idx = env->insn_idx;
3973 	int subseq_idx = -1;
3974 	struct bpf_func_state *func;
3975 	struct bpf_reg_state *reg;
3976 	bool skip_first = true;
3977 	int i, fr, err;
3978 
3979 	if (!env->bpf_capable)
3980 		return 0;
3981 
3982 	/* set frame number from which we are starting to backtrack */
3983 	bt_init(bt, env->cur_state->curframe);
3984 
3985 	/* Do sanity checks against current state of register and/or stack
3986 	 * slot, but don't set precise flag in current state, as precision
3987 	 * tracking in the current state is unnecessary.
3988 	 */
3989 	func = st->frame[bt->frame];
3990 	if (regno >= 0) {
3991 		reg = &func->regs[regno];
3992 		if (reg->type != SCALAR_VALUE) {
3993 			WARN_ONCE(1, "backtracing misuse");
3994 			return -EFAULT;
3995 		}
3996 		bt_set_reg(bt, regno);
3997 	}
3998 
3999 	if (bt_empty(bt))
4000 		return 0;
4001 
4002 	for (;;) {
4003 		DECLARE_BITMAP(mask, 64);
4004 		u32 history = st->jmp_history_cnt;
4005 
4006 		if (env->log.level & BPF_LOG_LEVEL2) {
4007 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4008 				bt->frame, last_idx, first_idx, subseq_idx);
4009 		}
4010 
4011 		/* If some register with scalar ID is marked as precise,
4012 		 * make sure that all registers sharing this ID are also precise.
4013 		 * This is needed to estimate effect of find_equal_scalars().
4014 		 * Do this at the last instruction of each state,
4015 		 * bpf_reg_state::id fields are valid for these instructions.
4016 		 *
4017 		 * Allows to track precision in situation like below:
4018 		 *
4019 		 *     r2 = unknown value
4020 		 *     ...
4021 		 *   --- state #0 ---
4022 		 *     ...
4023 		 *     r1 = r2                 // r1 and r2 now share the same ID
4024 		 *     ...
4025 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4026 		 *     ...
4027 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4028 		 *     ...
4029 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4030 		 *     r3 = r10
4031 		 *     r3 += r1                // need to mark both r1 and r2
4032 		 */
4033 		if (mark_precise_scalar_ids(env, st))
4034 			return -EFAULT;
4035 
4036 		if (last_idx < 0) {
4037 			/* we are at the entry into subprog, which
4038 			 * is expected for global funcs, but only if
4039 			 * requested precise registers are R1-R5
4040 			 * (which are global func's input arguments)
4041 			 */
4042 			if (st->curframe == 0 &&
4043 			    st->frame[0]->subprogno > 0 &&
4044 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4045 			    bt_stack_mask(bt) == 0 &&
4046 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4047 				bitmap_from_u64(mask, bt_reg_mask(bt));
4048 				for_each_set_bit(i, mask, 32) {
4049 					reg = &st->frame[0]->regs[i];
4050 					if (reg->type != SCALAR_VALUE) {
4051 						bt_clear_reg(bt, i);
4052 						continue;
4053 					}
4054 					reg->precise = true;
4055 				}
4056 				return 0;
4057 			}
4058 
4059 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4060 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4061 			WARN_ONCE(1, "verifier backtracking bug");
4062 			return -EFAULT;
4063 		}
4064 
4065 		for (i = last_idx;;) {
4066 			if (skip_first) {
4067 				err = 0;
4068 				skip_first = false;
4069 			} else {
4070 				err = backtrack_insn(env, i, subseq_idx, bt);
4071 			}
4072 			if (err == -ENOTSUPP) {
4073 				mark_all_scalars_precise(env, env->cur_state);
4074 				bt_reset(bt);
4075 				return 0;
4076 			} else if (err) {
4077 				return err;
4078 			}
4079 			if (bt_empty(bt))
4080 				/* Found assignment(s) into tracked register in this state.
4081 				 * Since this state is already marked, just return.
4082 				 * Nothing to be tracked further in the parent state.
4083 				 */
4084 				return 0;
4085 			if (i == first_idx)
4086 				break;
4087 			subseq_idx = i;
4088 			i = get_prev_insn_idx(st, i, &history);
4089 			if (i >= env->prog->len) {
4090 				/* This can happen if backtracking reached insn 0
4091 				 * and there are still reg_mask or stack_mask
4092 				 * to backtrack.
4093 				 * It means the backtracking missed the spot where
4094 				 * particular register was initialized with a constant.
4095 				 */
4096 				verbose(env, "BUG backtracking idx %d\n", i);
4097 				WARN_ONCE(1, "verifier backtracking bug");
4098 				return -EFAULT;
4099 			}
4100 		}
4101 		st = st->parent;
4102 		if (!st)
4103 			break;
4104 
4105 		for (fr = bt->frame; fr >= 0; fr--) {
4106 			func = st->frame[fr];
4107 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4108 			for_each_set_bit(i, mask, 32) {
4109 				reg = &func->regs[i];
4110 				if (reg->type != SCALAR_VALUE) {
4111 					bt_clear_frame_reg(bt, fr, i);
4112 					continue;
4113 				}
4114 				if (reg->precise)
4115 					bt_clear_frame_reg(bt, fr, i);
4116 				else
4117 					reg->precise = true;
4118 			}
4119 
4120 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4121 			for_each_set_bit(i, mask, 64) {
4122 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4123 					/* the sequence of instructions:
4124 					 * 2: (bf) r3 = r10
4125 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4126 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4127 					 * doesn't contain jmps. It's backtracked
4128 					 * as a single block.
4129 					 * During backtracking insn 3 is not recognized as
4130 					 * stack access, so at the end of backtracking
4131 					 * stack slot fp-8 is still marked in stack_mask.
4132 					 * However the parent state may not have accessed
4133 					 * fp-8 and it's "unallocated" stack space.
4134 					 * In such case fallback to conservative.
4135 					 */
4136 					mark_all_scalars_precise(env, env->cur_state);
4137 					bt_reset(bt);
4138 					return 0;
4139 				}
4140 
4141 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4142 					bt_clear_frame_slot(bt, fr, i);
4143 					continue;
4144 				}
4145 				reg = &func->stack[i].spilled_ptr;
4146 				if (reg->precise)
4147 					bt_clear_frame_slot(bt, fr, i);
4148 				else
4149 					reg->precise = true;
4150 			}
4151 			if (env->log.level & BPF_LOG_LEVEL2) {
4152 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4153 					     bt_frame_reg_mask(bt, fr));
4154 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4155 					fr, env->tmp_str_buf);
4156 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4157 					       bt_frame_stack_mask(bt, fr));
4158 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4159 				print_verifier_state(env, func, true);
4160 			}
4161 		}
4162 
4163 		if (bt_empty(bt))
4164 			return 0;
4165 
4166 		subseq_idx = first_idx;
4167 		last_idx = st->last_insn_idx;
4168 		first_idx = st->first_insn_idx;
4169 	}
4170 
4171 	/* if we still have requested precise regs or slots, we missed
4172 	 * something (e.g., stack access through non-r10 register), so
4173 	 * fallback to marking all precise
4174 	 */
4175 	if (!bt_empty(bt)) {
4176 		mark_all_scalars_precise(env, env->cur_state);
4177 		bt_reset(bt);
4178 	}
4179 
4180 	return 0;
4181 }
4182 
4183 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4184 {
4185 	return __mark_chain_precision(env, regno);
4186 }
4187 
4188 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4189  * desired reg and stack masks across all relevant frames
4190  */
4191 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4192 {
4193 	return __mark_chain_precision(env, -1);
4194 }
4195 
4196 static bool is_spillable_regtype(enum bpf_reg_type type)
4197 {
4198 	switch (base_type(type)) {
4199 	case PTR_TO_MAP_VALUE:
4200 	case PTR_TO_STACK:
4201 	case PTR_TO_CTX:
4202 	case PTR_TO_PACKET:
4203 	case PTR_TO_PACKET_META:
4204 	case PTR_TO_PACKET_END:
4205 	case PTR_TO_FLOW_KEYS:
4206 	case CONST_PTR_TO_MAP:
4207 	case PTR_TO_SOCKET:
4208 	case PTR_TO_SOCK_COMMON:
4209 	case PTR_TO_TCP_SOCK:
4210 	case PTR_TO_XDP_SOCK:
4211 	case PTR_TO_BTF_ID:
4212 	case PTR_TO_BUF:
4213 	case PTR_TO_MEM:
4214 	case PTR_TO_FUNC:
4215 	case PTR_TO_MAP_KEY:
4216 		return true;
4217 	default:
4218 		return false;
4219 	}
4220 }
4221 
4222 /* Does this register contain a constant zero? */
4223 static bool register_is_null(struct bpf_reg_state *reg)
4224 {
4225 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4226 }
4227 
4228 static bool register_is_const(struct bpf_reg_state *reg)
4229 {
4230 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4231 }
4232 
4233 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4234 {
4235 	return tnum_is_unknown(reg->var_off) &&
4236 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4237 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4238 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4239 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4240 }
4241 
4242 static bool register_is_bounded(struct bpf_reg_state *reg)
4243 {
4244 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4245 }
4246 
4247 static bool __is_pointer_value(bool allow_ptr_leaks,
4248 			       const struct bpf_reg_state *reg)
4249 {
4250 	if (allow_ptr_leaks)
4251 		return false;
4252 
4253 	return reg->type != SCALAR_VALUE;
4254 }
4255 
4256 /* Copy src state preserving dst->parent and dst->live fields */
4257 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4258 {
4259 	struct bpf_reg_state *parent = dst->parent;
4260 	enum bpf_reg_liveness live = dst->live;
4261 
4262 	*dst = *src;
4263 	dst->parent = parent;
4264 	dst->live = live;
4265 }
4266 
4267 static void save_register_state(struct bpf_func_state *state,
4268 				int spi, struct bpf_reg_state *reg,
4269 				int size)
4270 {
4271 	int i;
4272 
4273 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4274 	if (size == BPF_REG_SIZE)
4275 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4276 
4277 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4278 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4279 
4280 	/* size < 8 bytes spill */
4281 	for (; i; i--)
4282 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4283 }
4284 
4285 static bool is_bpf_st_mem(struct bpf_insn *insn)
4286 {
4287 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4288 }
4289 
4290 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4291  * stack boundary and alignment are checked in check_mem_access()
4292  */
4293 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4294 				       /* stack frame we're writing to */
4295 				       struct bpf_func_state *state,
4296 				       int off, int size, int value_regno,
4297 				       int insn_idx)
4298 {
4299 	struct bpf_func_state *cur; /* state of the current function */
4300 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4301 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4302 	struct bpf_reg_state *reg = NULL;
4303 	u32 dst_reg = insn->dst_reg;
4304 
4305 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4306 	if (err)
4307 		return err;
4308 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4309 	 * so it's aligned access and [off, off + size) are within stack limits
4310 	 */
4311 	if (!env->allow_ptr_leaks &&
4312 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
4313 	    size != BPF_REG_SIZE) {
4314 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4315 		return -EACCES;
4316 	}
4317 
4318 	cur = env->cur_state->frame[env->cur_state->curframe];
4319 	if (value_regno >= 0)
4320 		reg = &cur->regs[value_regno];
4321 	if (!env->bypass_spec_v4) {
4322 		bool sanitize = reg && is_spillable_regtype(reg->type);
4323 
4324 		for (i = 0; i < size; i++) {
4325 			u8 type = state->stack[spi].slot_type[i];
4326 
4327 			if (type != STACK_MISC && type != STACK_ZERO) {
4328 				sanitize = true;
4329 				break;
4330 			}
4331 		}
4332 
4333 		if (sanitize)
4334 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4335 	}
4336 
4337 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4338 	if (err)
4339 		return err;
4340 
4341 	mark_stack_slot_scratched(env, spi);
4342 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4343 	    !register_is_null(reg) && env->bpf_capable) {
4344 		if (dst_reg != BPF_REG_FP) {
4345 			/* The backtracking logic can only recognize explicit
4346 			 * stack slot address like [fp - 8]. Other spill of
4347 			 * scalar via different register has to be conservative.
4348 			 * Backtrack from here and mark all registers as precise
4349 			 * that contributed into 'reg' being a constant.
4350 			 */
4351 			err = mark_chain_precision(env, value_regno);
4352 			if (err)
4353 				return err;
4354 		}
4355 		save_register_state(state, spi, reg, size);
4356 		/* Break the relation on a narrowing spill. */
4357 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4358 			state->stack[spi].spilled_ptr.id = 0;
4359 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4360 		   insn->imm != 0 && env->bpf_capable) {
4361 		struct bpf_reg_state fake_reg = {};
4362 
4363 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4364 		fake_reg.type = SCALAR_VALUE;
4365 		save_register_state(state, spi, &fake_reg, size);
4366 	} else if (reg && is_spillable_regtype(reg->type)) {
4367 		/* register containing pointer is being spilled into stack */
4368 		if (size != BPF_REG_SIZE) {
4369 			verbose_linfo(env, insn_idx, "; ");
4370 			verbose(env, "invalid size of register spill\n");
4371 			return -EACCES;
4372 		}
4373 		if (state != cur && reg->type == PTR_TO_STACK) {
4374 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4375 			return -EINVAL;
4376 		}
4377 		save_register_state(state, spi, reg, size);
4378 	} else {
4379 		u8 type = STACK_MISC;
4380 
4381 		/* regular write of data into stack destroys any spilled ptr */
4382 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4383 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4384 		if (is_stack_slot_special(&state->stack[spi]))
4385 			for (i = 0; i < BPF_REG_SIZE; i++)
4386 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4387 
4388 		/* only mark the slot as written if all 8 bytes were written
4389 		 * otherwise read propagation may incorrectly stop too soon
4390 		 * when stack slots are partially written.
4391 		 * This heuristic means that read propagation will be
4392 		 * conservative, since it will add reg_live_read marks
4393 		 * to stack slots all the way to first state when programs
4394 		 * writes+reads less than 8 bytes
4395 		 */
4396 		if (size == BPF_REG_SIZE)
4397 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4398 
4399 		/* when we zero initialize stack slots mark them as such */
4400 		if ((reg && register_is_null(reg)) ||
4401 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4402 			/* backtracking doesn't work for STACK_ZERO yet. */
4403 			err = mark_chain_precision(env, value_regno);
4404 			if (err)
4405 				return err;
4406 			type = STACK_ZERO;
4407 		}
4408 
4409 		/* Mark slots affected by this stack write. */
4410 		for (i = 0; i < size; i++)
4411 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4412 				type;
4413 	}
4414 	return 0;
4415 }
4416 
4417 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4418  * known to contain a variable offset.
4419  * This function checks whether the write is permitted and conservatively
4420  * tracks the effects of the write, considering that each stack slot in the
4421  * dynamic range is potentially written to.
4422  *
4423  * 'off' includes 'regno->off'.
4424  * 'value_regno' can be -1, meaning that an unknown value is being written to
4425  * the stack.
4426  *
4427  * Spilled pointers in range are not marked as written because we don't know
4428  * what's going to be actually written. This means that read propagation for
4429  * future reads cannot be terminated by this write.
4430  *
4431  * For privileged programs, uninitialized stack slots are considered
4432  * initialized by this write (even though we don't know exactly what offsets
4433  * are going to be written to). The idea is that we don't want the verifier to
4434  * reject future reads that access slots written to through variable offsets.
4435  */
4436 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4437 				     /* func where register points to */
4438 				     struct bpf_func_state *state,
4439 				     int ptr_regno, int off, int size,
4440 				     int value_regno, int insn_idx)
4441 {
4442 	struct bpf_func_state *cur; /* state of the current function */
4443 	int min_off, max_off;
4444 	int i, err;
4445 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4446 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4447 	bool writing_zero = false;
4448 	/* set if the fact that we're writing a zero is used to let any
4449 	 * stack slots remain STACK_ZERO
4450 	 */
4451 	bool zero_used = false;
4452 
4453 	cur = env->cur_state->frame[env->cur_state->curframe];
4454 	ptr_reg = &cur->regs[ptr_regno];
4455 	min_off = ptr_reg->smin_value + off;
4456 	max_off = ptr_reg->smax_value + off + size;
4457 	if (value_regno >= 0)
4458 		value_reg = &cur->regs[value_regno];
4459 	if ((value_reg && register_is_null(value_reg)) ||
4460 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4461 		writing_zero = true;
4462 
4463 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4464 	if (err)
4465 		return err;
4466 
4467 	for (i = min_off; i < max_off; i++) {
4468 		int spi;
4469 
4470 		spi = __get_spi(i);
4471 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4472 		if (err)
4473 			return err;
4474 	}
4475 
4476 	/* Variable offset writes destroy any spilled pointers in range. */
4477 	for (i = min_off; i < max_off; i++) {
4478 		u8 new_type, *stype;
4479 		int slot, spi;
4480 
4481 		slot = -i - 1;
4482 		spi = slot / BPF_REG_SIZE;
4483 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4484 		mark_stack_slot_scratched(env, spi);
4485 
4486 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4487 			/* Reject the write if range we may write to has not
4488 			 * been initialized beforehand. If we didn't reject
4489 			 * here, the ptr status would be erased below (even
4490 			 * though not all slots are actually overwritten),
4491 			 * possibly opening the door to leaks.
4492 			 *
4493 			 * We do however catch STACK_INVALID case below, and
4494 			 * only allow reading possibly uninitialized memory
4495 			 * later for CAP_PERFMON, as the write may not happen to
4496 			 * that slot.
4497 			 */
4498 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4499 				insn_idx, i);
4500 			return -EINVAL;
4501 		}
4502 
4503 		/* Erase all spilled pointers. */
4504 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4505 
4506 		/* Update the slot type. */
4507 		new_type = STACK_MISC;
4508 		if (writing_zero && *stype == STACK_ZERO) {
4509 			new_type = STACK_ZERO;
4510 			zero_used = true;
4511 		}
4512 		/* If the slot is STACK_INVALID, we check whether it's OK to
4513 		 * pretend that it will be initialized by this write. The slot
4514 		 * might not actually be written to, and so if we mark it as
4515 		 * initialized future reads might leak uninitialized memory.
4516 		 * For privileged programs, we will accept such reads to slots
4517 		 * that may or may not be written because, if we're reject
4518 		 * them, the error would be too confusing.
4519 		 */
4520 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4521 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4522 					insn_idx, i);
4523 			return -EINVAL;
4524 		}
4525 		*stype = new_type;
4526 	}
4527 	if (zero_used) {
4528 		/* backtracking doesn't work for STACK_ZERO yet. */
4529 		err = mark_chain_precision(env, value_regno);
4530 		if (err)
4531 			return err;
4532 	}
4533 	return 0;
4534 }
4535 
4536 /* When register 'dst_regno' is assigned some values from stack[min_off,
4537  * max_off), we set the register's type according to the types of the
4538  * respective stack slots. If all the stack values are known to be zeros, then
4539  * so is the destination reg. Otherwise, the register is considered to be
4540  * SCALAR. This function does not deal with register filling; the caller must
4541  * ensure that all spilled registers in the stack range have been marked as
4542  * read.
4543  */
4544 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4545 				/* func where src register points to */
4546 				struct bpf_func_state *ptr_state,
4547 				int min_off, int max_off, int dst_regno)
4548 {
4549 	struct bpf_verifier_state *vstate = env->cur_state;
4550 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4551 	int i, slot, spi;
4552 	u8 *stype;
4553 	int zeros = 0;
4554 
4555 	for (i = min_off; i < max_off; i++) {
4556 		slot = -i - 1;
4557 		spi = slot / BPF_REG_SIZE;
4558 		mark_stack_slot_scratched(env, spi);
4559 		stype = ptr_state->stack[spi].slot_type;
4560 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4561 			break;
4562 		zeros++;
4563 	}
4564 	if (zeros == max_off - min_off) {
4565 		/* any access_size read into register is zero extended,
4566 		 * so the whole register == const_zero
4567 		 */
4568 		__mark_reg_const_zero(&state->regs[dst_regno]);
4569 		/* backtracking doesn't support STACK_ZERO yet,
4570 		 * so mark it precise here, so that later
4571 		 * backtracking can stop here.
4572 		 * Backtracking may not need this if this register
4573 		 * doesn't participate in pointer adjustment.
4574 		 * Forward propagation of precise flag is not
4575 		 * necessary either. This mark is only to stop
4576 		 * backtracking. Any register that contributed
4577 		 * to const 0 was marked precise before spill.
4578 		 */
4579 		state->regs[dst_regno].precise = true;
4580 	} else {
4581 		/* have read misc data from the stack */
4582 		mark_reg_unknown(env, state->regs, dst_regno);
4583 	}
4584 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4585 }
4586 
4587 /* Read the stack at 'off' and put the results into the register indicated by
4588  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4589  * spilled reg.
4590  *
4591  * 'dst_regno' can be -1, meaning that the read value is not going to a
4592  * register.
4593  *
4594  * The access is assumed to be within the current stack bounds.
4595  */
4596 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4597 				      /* func where src register points to */
4598 				      struct bpf_func_state *reg_state,
4599 				      int off, int size, int dst_regno)
4600 {
4601 	struct bpf_verifier_state *vstate = env->cur_state;
4602 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4603 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4604 	struct bpf_reg_state *reg;
4605 	u8 *stype, type;
4606 
4607 	stype = reg_state->stack[spi].slot_type;
4608 	reg = &reg_state->stack[spi].spilled_ptr;
4609 
4610 	mark_stack_slot_scratched(env, spi);
4611 
4612 	if (is_spilled_reg(&reg_state->stack[spi])) {
4613 		u8 spill_size = 1;
4614 
4615 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4616 			spill_size++;
4617 
4618 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4619 			if (reg->type != SCALAR_VALUE) {
4620 				verbose_linfo(env, env->insn_idx, "; ");
4621 				verbose(env, "invalid size of register fill\n");
4622 				return -EACCES;
4623 			}
4624 
4625 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4626 			if (dst_regno < 0)
4627 				return 0;
4628 
4629 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4630 				/* The earlier check_reg_arg() has decided the
4631 				 * subreg_def for this insn.  Save it first.
4632 				 */
4633 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4634 
4635 				copy_register_state(&state->regs[dst_regno], reg);
4636 				state->regs[dst_regno].subreg_def = subreg_def;
4637 			} else {
4638 				for (i = 0; i < size; i++) {
4639 					type = stype[(slot - i) % BPF_REG_SIZE];
4640 					if (type == STACK_SPILL)
4641 						continue;
4642 					if (type == STACK_MISC)
4643 						continue;
4644 					if (type == STACK_INVALID && env->allow_uninit_stack)
4645 						continue;
4646 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4647 						off, i, size);
4648 					return -EACCES;
4649 				}
4650 				mark_reg_unknown(env, state->regs, dst_regno);
4651 			}
4652 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4653 			return 0;
4654 		}
4655 
4656 		if (dst_regno >= 0) {
4657 			/* restore register state from stack */
4658 			copy_register_state(&state->regs[dst_regno], reg);
4659 			/* mark reg as written since spilled pointer state likely
4660 			 * has its liveness marks cleared by is_state_visited()
4661 			 * which resets stack/reg liveness for state transitions
4662 			 */
4663 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4664 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4665 			/* If dst_regno==-1, the caller is asking us whether
4666 			 * it is acceptable to use this value as a SCALAR_VALUE
4667 			 * (e.g. for XADD).
4668 			 * We must not allow unprivileged callers to do that
4669 			 * with spilled pointers.
4670 			 */
4671 			verbose(env, "leaking pointer from stack off %d\n",
4672 				off);
4673 			return -EACCES;
4674 		}
4675 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4676 	} else {
4677 		for (i = 0; i < size; i++) {
4678 			type = stype[(slot - i) % BPF_REG_SIZE];
4679 			if (type == STACK_MISC)
4680 				continue;
4681 			if (type == STACK_ZERO)
4682 				continue;
4683 			if (type == STACK_INVALID && env->allow_uninit_stack)
4684 				continue;
4685 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4686 				off, i, size);
4687 			return -EACCES;
4688 		}
4689 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4690 		if (dst_regno >= 0)
4691 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4692 	}
4693 	return 0;
4694 }
4695 
4696 enum bpf_access_src {
4697 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4698 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4699 };
4700 
4701 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4702 					 int regno, int off, int access_size,
4703 					 bool zero_size_allowed,
4704 					 enum bpf_access_src type,
4705 					 struct bpf_call_arg_meta *meta);
4706 
4707 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4708 {
4709 	return cur_regs(env) + regno;
4710 }
4711 
4712 /* Read the stack at 'ptr_regno + off' and put the result into the register
4713  * 'dst_regno'.
4714  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4715  * but not its variable offset.
4716  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4717  *
4718  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4719  * filling registers (i.e. reads of spilled register cannot be detected when
4720  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4721  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4722  * offset; for a fixed offset check_stack_read_fixed_off should be used
4723  * instead.
4724  */
4725 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4726 				    int ptr_regno, int off, int size, int dst_regno)
4727 {
4728 	/* The state of the source register. */
4729 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4730 	struct bpf_func_state *ptr_state = func(env, reg);
4731 	int err;
4732 	int min_off, max_off;
4733 
4734 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4735 	 */
4736 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4737 					    false, ACCESS_DIRECT, NULL);
4738 	if (err)
4739 		return err;
4740 
4741 	min_off = reg->smin_value + off;
4742 	max_off = reg->smax_value + off;
4743 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4744 	return 0;
4745 }
4746 
4747 /* check_stack_read dispatches to check_stack_read_fixed_off or
4748  * check_stack_read_var_off.
4749  *
4750  * The caller must ensure that the offset falls within the allocated stack
4751  * bounds.
4752  *
4753  * 'dst_regno' is a register which will receive the value from the stack. It
4754  * can be -1, meaning that the read value is not going to a register.
4755  */
4756 static int check_stack_read(struct bpf_verifier_env *env,
4757 			    int ptr_regno, int off, int size,
4758 			    int dst_regno)
4759 {
4760 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4761 	struct bpf_func_state *state = func(env, reg);
4762 	int err;
4763 	/* Some accesses are only permitted with a static offset. */
4764 	bool var_off = !tnum_is_const(reg->var_off);
4765 
4766 	/* The offset is required to be static when reads don't go to a
4767 	 * register, in order to not leak pointers (see
4768 	 * check_stack_read_fixed_off).
4769 	 */
4770 	if (dst_regno < 0 && var_off) {
4771 		char tn_buf[48];
4772 
4773 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4774 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4775 			tn_buf, off, size);
4776 		return -EACCES;
4777 	}
4778 	/* Variable offset is prohibited for unprivileged mode for simplicity
4779 	 * since it requires corresponding support in Spectre masking for stack
4780 	 * ALU. See also retrieve_ptr_limit(). The check in
4781 	 * check_stack_access_for_ptr_arithmetic() called by
4782 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4783 	 * with variable offsets, therefore no check is required here. Further,
4784 	 * just checking it here would be insufficient as speculative stack
4785 	 * writes could still lead to unsafe speculative behaviour.
4786 	 */
4787 	if (!var_off) {
4788 		off += reg->var_off.value;
4789 		err = check_stack_read_fixed_off(env, state, off, size,
4790 						 dst_regno);
4791 	} else {
4792 		/* Variable offset stack reads need more conservative handling
4793 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4794 		 * branch.
4795 		 */
4796 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4797 					       dst_regno);
4798 	}
4799 	return err;
4800 }
4801 
4802 
4803 /* check_stack_write dispatches to check_stack_write_fixed_off or
4804  * check_stack_write_var_off.
4805  *
4806  * 'ptr_regno' is the register used as a pointer into the stack.
4807  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4808  * 'value_regno' is the register whose value we're writing to the stack. It can
4809  * be -1, meaning that we're not writing from a register.
4810  *
4811  * The caller must ensure that the offset falls within the maximum stack size.
4812  */
4813 static int check_stack_write(struct bpf_verifier_env *env,
4814 			     int ptr_regno, int off, int size,
4815 			     int value_regno, int insn_idx)
4816 {
4817 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4818 	struct bpf_func_state *state = func(env, reg);
4819 	int err;
4820 
4821 	if (tnum_is_const(reg->var_off)) {
4822 		off += reg->var_off.value;
4823 		err = check_stack_write_fixed_off(env, state, off, size,
4824 						  value_regno, insn_idx);
4825 	} else {
4826 		/* Variable offset stack reads need more conservative handling
4827 		 * than fixed offset ones.
4828 		 */
4829 		err = check_stack_write_var_off(env, state,
4830 						ptr_regno, off, size,
4831 						value_regno, insn_idx);
4832 	}
4833 	return err;
4834 }
4835 
4836 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4837 				 int off, int size, enum bpf_access_type type)
4838 {
4839 	struct bpf_reg_state *regs = cur_regs(env);
4840 	struct bpf_map *map = regs[regno].map_ptr;
4841 	u32 cap = bpf_map_flags_to_cap(map);
4842 
4843 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4844 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4845 			map->value_size, off, size);
4846 		return -EACCES;
4847 	}
4848 
4849 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4850 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4851 			map->value_size, off, size);
4852 		return -EACCES;
4853 	}
4854 
4855 	return 0;
4856 }
4857 
4858 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4859 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4860 			      int off, int size, u32 mem_size,
4861 			      bool zero_size_allowed)
4862 {
4863 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4864 	struct bpf_reg_state *reg;
4865 
4866 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4867 		return 0;
4868 
4869 	reg = &cur_regs(env)[regno];
4870 	switch (reg->type) {
4871 	case PTR_TO_MAP_KEY:
4872 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4873 			mem_size, off, size);
4874 		break;
4875 	case PTR_TO_MAP_VALUE:
4876 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4877 			mem_size, off, size);
4878 		break;
4879 	case PTR_TO_PACKET:
4880 	case PTR_TO_PACKET_META:
4881 	case PTR_TO_PACKET_END:
4882 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4883 			off, size, regno, reg->id, off, mem_size);
4884 		break;
4885 	case PTR_TO_MEM:
4886 	default:
4887 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4888 			mem_size, off, size);
4889 	}
4890 
4891 	return -EACCES;
4892 }
4893 
4894 /* check read/write into a memory region with possible variable offset */
4895 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4896 				   int off, int size, u32 mem_size,
4897 				   bool zero_size_allowed)
4898 {
4899 	struct bpf_verifier_state *vstate = env->cur_state;
4900 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4901 	struct bpf_reg_state *reg = &state->regs[regno];
4902 	int err;
4903 
4904 	/* We may have adjusted the register pointing to memory region, so we
4905 	 * need to try adding each of min_value and max_value to off
4906 	 * to make sure our theoretical access will be safe.
4907 	 *
4908 	 * The minimum value is only important with signed
4909 	 * comparisons where we can't assume the floor of a
4910 	 * value is 0.  If we are using signed variables for our
4911 	 * index'es we need to make sure that whatever we use
4912 	 * will have a set floor within our range.
4913 	 */
4914 	if (reg->smin_value < 0 &&
4915 	    (reg->smin_value == S64_MIN ||
4916 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4917 	      reg->smin_value + off < 0)) {
4918 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4919 			regno);
4920 		return -EACCES;
4921 	}
4922 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4923 				 mem_size, zero_size_allowed);
4924 	if (err) {
4925 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4926 			regno);
4927 		return err;
4928 	}
4929 
4930 	/* If we haven't set a max value then we need to bail since we can't be
4931 	 * sure we won't do bad things.
4932 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4933 	 */
4934 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4935 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4936 			regno);
4937 		return -EACCES;
4938 	}
4939 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4940 				 mem_size, zero_size_allowed);
4941 	if (err) {
4942 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4943 			regno);
4944 		return err;
4945 	}
4946 
4947 	return 0;
4948 }
4949 
4950 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4951 			       const struct bpf_reg_state *reg, int regno,
4952 			       bool fixed_off_ok)
4953 {
4954 	/* Access to this pointer-typed register or passing it to a helper
4955 	 * is only allowed in its original, unmodified form.
4956 	 */
4957 
4958 	if (reg->off < 0) {
4959 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4960 			reg_type_str(env, reg->type), regno, reg->off);
4961 		return -EACCES;
4962 	}
4963 
4964 	if (!fixed_off_ok && reg->off) {
4965 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4966 			reg_type_str(env, reg->type), regno, reg->off);
4967 		return -EACCES;
4968 	}
4969 
4970 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4971 		char tn_buf[48];
4972 
4973 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4974 		verbose(env, "variable %s access var_off=%s disallowed\n",
4975 			reg_type_str(env, reg->type), tn_buf);
4976 		return -EACCES;
4977 	}
4978 
4979 	return 0;
4980 }
4981 
4982 int check_ptr_off_reg(struct bpf_verifier_env *env,
4983 		      const struct bpf_reg_state *reg, int regno)
4984 {
4985 	return __check_ptr_off_reg(env, reg, regno, false);
4986 }
4987 
4988 static int map_kptr_match_type(struct bpf_verifier_env *env,
4989 			       struct btf_field *kptr_field,
4990 			       struct bpf_reg_state *reg, u32 regno)
4991 {
4992 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4993 	int perm_flags;
4994 	const char *reg_name = "";
4995 
4996 	if (btf_is_kernel(reg->btf)) {
4997 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4998 
4999 		/* Only unreferenced case accepts untrusted pointers */
5000 		if (kptr_field->type == BPF_KPTR_UNREF)
5001 			perm_flags |= PTR_UNTRUSTED;
5002 	} else {
5003 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5004 	}
5005 
5006 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5007 		goto bad_type;
5008 
5009 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5010 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5011 
5012 	/* For ref_ptr case, release function check should ensure we get one
5013 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5014 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5015 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5016 	 * reg->off and reg->ref_obj_id are not needed here.
5017 	 */
5018 	if (__check_ptr_off_reg(env, reg, regno, true))
5019 		return -EACCES;
5020 
5021 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5022 	 * we also need to take into account the reg->off.
5023 	 *
5024 	 * We want to support cases like:
5025 	 *
5026 	 * struct foo {
5027 	 *         struct bar br;
5028 	 *         struct baz bz;
5029 	 * };
5030 	 *
5031 	 * struct foo *v;
5032 	 * v = func();	      // PTR_TO_BTF_ID
5033 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5034 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5035 	 *                    // first member type of struct after comparison fails
5036 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5037 	 *                    // to match type
5038 	 *
5039 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5040 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5041 	 * the struct to match type against first member of struct, i.e. reject
5042 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5043 	 * strict mode to true for type match.
5044 	 */
5045 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5046 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5047 				  kptr_field->type == BPF_KPTR_REF))
5048 		goto bad_type;
5049 	return 0;
5050 bad_type:
5051 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5052 		reg_type_str(env, reg->type), reg_name);
5053 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5054 	if (kptr_field->type == BPF_KPTR_UNREF)
5055 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5056 			targ_name);
5057 	else
5058 		verbose(env, "\n");
5059 	return -EINVAL;
5060 }
5061 
5062 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5063  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5064  */
5065 static bool in_rcu_cs(struct bpf_verifier_env *env)
5066 {
5067 	return env->cur_state->active_rcu_lock ||
5068 	       env->cur_state->active_lock.ptr ||
5069 	       !env->prog->aux->sleepable;
5070 }
5071 
5072 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5073 BTF_SET_START(rcu_protected_types)
5074 BTF_ID(struct, prog_test_ref_kfunc)
5075 BTF_ID(struct, cgroup)
5076 BTF_ID(struct, bpf_cpumask)
5077 BTF_ID(struct, task_struct)
5078 BTF_SET_END(rcu_protected_types)
5079 
5080 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5081 {
5082 	if (!btf_is_kernel(btf))
5083 		return false;
5084 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5085 }
5086 
5087 static bool rcu_safe_kptr(const struct btf_field *field)
5088 {
5089 	const struct btf_field_kptr *kptr = &field->kptr;
5090 
5091 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5092 }
5093 
5094 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5095 				 int value_regno, int insn_idx,
5096 				 struct btf_field *kptr_field)
5097 {
5098 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5099 	int class = BPF_CLASS(insn->code);
5100 	struct bpf_reg_state *val_reg;
5101 
5102 	/* Things we already checked for in check_map_access and caller:
5103 	 *  - Reject cases where variable offset may touch kptr
5104 	 *  - size of access (must be BPF_DW)
5105 	 *  - tnum_is_const(reg->var_off)
5106 	 *  - kptr_field->offset == off + reg->var_off.value
5107 	 */
5108 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5109 	if (BPF_MODE(insn->code) != BPF_MEM) {
5110 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5111 		return -EACCES;
5112 	}
5113 
5114 	/* We only allow loading referenced kptr, since it will be marked as
5115 	 * untrusted, similar to unreferenced kptr.
5116 	 */
5117 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5118 		verbose(env, "store to referenced kptr disallowed\n");
5119 		return -EACCES;
5120 	}
5121 
5122 	if (class == BPF_LDX) {
5123 		val_reg = reg_state(env, value_regno);
5124 		/* We can simply mark the value_regno receiving the pointer
5125 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5126 		 */
5127 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5128 				kptr_field->kptr.btf_id,
5129 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5130 				PTR_MAYBE_NULL | MEM_RCU :
5131 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5132 		/* For mark_ptr_or_null_reg */
5133 		val_reg->id = ++env->id_gen;
5134 	} else if (class == BPF_STX) {
5135 		val_reg = reg_state(env, value_regno);
5136 		if (!register_is_null(val_reg) &&
5137 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5138 			return -EACCES;
5139 	} else if (class == BPF_ST) {
5140 		if (insn->imm) {
5141 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5142 				kptr_field->offset);
5143 			return -EACCES;
5144 		}
5145 	} else {
5146 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5147 		return -EACCES;
5148 	}
5149 	return 0;
5150 }
5151 
5152 /* check read/write into a map element with possible variable offset */
5153 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5154 			    int off, int size, bool zero_size_allowed,
5155 			    enum bpf_access_src src)
5156 {
5157 	struct bpf_verifier_state *vstate = env->cur_state;
5158 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5159 	struct bpf_reg_state *reg = &state->regs[regno];
5160 	struct bpf_map *map = reg->map_ptr;
5161 	struct btf_record *rec;
5162 	int err, i;
5163 
5164 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5165 				      zero_size_allowed);
5166 	if (err)
5167 		return err;
5168 
5169 	if (IS_ERR_OR_NULL(map->record))
5170 		return 0;
5171 	rec = map->record;
5172 	for (i = 0; i < rec->cnt; i++) {
5173 		struct btf_field *field = &rec->fields[i];
5174 		u32 p = field->offset;
5175 
5176 		/* If any part of a field  can be touched by load/store, reject
5177 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5178 		 * it is sufficient to check x1 < y2 && y1 < x2.
5179 		 */
5180 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5181 		    p < reg->umax_value + off + size) {
5182 			switch (field->type) {
5183 			case BPF_KPTR_UNREF:
5184 			case BPF_KPTR_REF:
5185 				if (src != ACCESS_DIRECT) {
5186 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5187 					return -EACCES;
5188 				}
5189 				if (!tnum_is_const(reg->var_off)) {
5190 					verbose(env, "kptr access cannot have variable offset\n");
5191 					return -EACCES;
5192 				}
5193 				if (p != off + reg->var_off.value) {
5194 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5195 						p, off + reg->var_off.value);
5196 					return -EACCES;
5197 				}
5198 				if (size != bpf_size_to_bytes(BPF_DW)) {
5199 					verbose(env, "kptr access size must be BPF_DW\n");
5200 					return -EACCES;
5201 				}
5202 				break;
5203 			default:
5204 				verbose(env, "%s cannot be accessed directly by load/store\n",
5205 					btf_field_type_name(field->type));
5206 				return -EACCES;
5207 			}
5208 		}
5209 	}
5210 	return 0;
5211 }
5212 
5213 #define MAX_PACKET_OFF 0xffff
5214 
5215 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5216 				       const struct bpf_call_arg_meta *meta,
5217 				       enum bpf_access_type t)
5218 {
5219 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5220 
5221 	switch (prog_type) {
5222 	/* Program types only with direct read access go here! */
5223 	case BPF_PROG_TYPE_LWT_IN:
5224 	case BPF_PROG_TYPE_LWT_OUT:
5225 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5226 	case BPF_PROG_TYPE_SK_REUSEPORT:
5227 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5228 	case BPF_PROG_TYPE_CGROUP_SKB:
5229 		if (t == BPF_WRITE)
5230 			return false;
5231 		fallthrough;
5232 
5233 	/* Program types with direct read + write access go here! */
5234 	case BPF_PROG_TYPE_SCHED_CLS:
5235 	case BPF_PROG_TYPE_SCHED_ACT:
5236 	case BPF_PROG_TYPE_XDP:
5237 	case BPF_PROG_TYPE_LWT_XMIT:
5238 	case BPF_PROG_TYPE_SK_SKB:
5239 	case BPF_PROG_TYPE_SK_MSG:
5240 		if (meta)
5241 			return meta->pkt_access;
5242 
5243 		env->seen_direct_write = true;
5244 		return true;
5245 
5246 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5247 		if (t == BPF_WRITE)
5248 			env->seen_direct_write = true;
5249 
5250 		return true;
5251 
5252 	default:
5253 		return false;
5254 	}
5255 }
5256 
5257 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5258 			       int size, bool zero_size_allowed)
5259 {
5260 	struct bpf_reg_state *regs = cur_regs(env);
5261 	struct bpf_reg_state *reg = &regs[regno];
5262 	int err;
5263 
5264 	/* We may have added a variable offset to the packet pointer; but any
5265 	 * reg->range we have comes after that.  We are only checking the fixed
5266 	 * offset.
5267 	 */
5268 
5269 	/* We don't allow negative numbers, because we aren't tracking enough
5270 	 * detail to prove they're safe.
5271 	 */
5272 	if (reg->smin_value < 0) {
5273 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5274 			regno);
5275 		return -EACCES;
5276 	}
5277 
5278 	err = reg->range < 0 ? -EINVAL :
5279 	      __check_mem_access(env, regno, off, size, reg->range,
5280 				 zero_size_allowed);
5281 	if (err) {
5282 		verbose(env, "R%d offset is outside of the packet\n", regno);
5283 		return err;
5284 	}
5285 
5286 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5287 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5288 	 * otherwise find_good_pkt_pointers would have refused to set range info
5289 	 * that __check_mem_access would have rejected this pkt access.
5290 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5291 	 */
5292 	env->prog->aux->max_pkt_offset =
5293 		max_t(u32, env->prog->aux->max_pkt_offset,
5294 		      off + reg->umax_value + size - 1);
5295 
5296 	return err;
5297 }
5298 
5299 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5300 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5301 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5302 			    struct btf **btf, u32 *btf_id)
5303 {
5304 	struct bpf_insn_access_aux info = {
5305 		.reg_type = *reg_type,
5306 		.log = &env->log,
5307 	};
5308 
5309 	if (env->ops->is_valid_access &&
5310 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5311 		/* A non zero info.ctx_field_size indicates that this field is a
5312 		 * candidate for later verifier transformation to load the whole
5313 		 * field and then apply a mask when accessed with a narrower
5314 		 * access than actual ctx access size. A zero info.ctx_field_size
5315 		 * will only allow for whole field access and rejects any other
5316 		 * type of narrower access.
5317 		 */
5318 		*reg_type = info.reg_type;
5319 
5320 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5321 			*btf = info.btf;
5322 			*btf_id = info.btf_id;
5323 		} else {
5324 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5325 		}
5326 		/* remember the offset of last byte accessed in ctx */
5327 		if (env->prog->aux->max_ctx_offset < off + size)
5328 			env->prog->aux->max_ctx_offset = off + size;
5329 		return 0;
5330 	}
5331 
5332 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5333 	return -EACCES;
5334 }
5335 
5336 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5337 				  int size)
5338 {
5339 	if (size < 0 || off < 0 ||
5340 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5341 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5342 			off, size);
5343 		return -EACCES;
5344 	}
5345 	return 0;
5346 }
5347 
5348 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5349 			     u32 regno, int off, int size,
5350 			     enum bpf_access_type t)
5351 {
5352 	struct bpf_reg_state *regs = cur_regs(env);
5353 	struct bpf_reg_state *reg = &regs[regno];
5354 	struct bpf_insn_access_aux info = {};
5355 	bool valid;
5356 
5357 	if (reg->smin_value < 0) {
5358 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5359 			regno);
5360 		return -EACCES;
5361 	}
5362 
5363 	switch (reg->type) {
5364 	case PTR_TO_SOCK_COMMON:
5365 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5366 		break;
5367 	case PTR_TO_SOCKET:
5368 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5369 		break;
5370 	case PTR_TO_TCP_SOCK:
5371 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5372 		break;
5373 	case PTR_TO_XDP_SOCK:
5374 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5375 		break;
5376 	default:
5377 		valid = false;
5378 	}
5379 
5380 
5381 	if (valid) {
5382 		env->insn_aux_data[insn_idx].ctx_field_size =
5383 			info.ctx_field_size;
5384 		return 0;
5385 	}
5386 
5387 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5388 		regno, reg_type_str(env, reg->type), off, size);
5389 
5390 	return -EACCES;
5391 }
5392 
5393 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5394 {
5395 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5396 }
5397 
5398 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5399 {
5400 	const struct bpf_reg_state *reg = reg_state(env, regno);
5401 
5402 	return reg->type == PTR_TO_CTX;
5403 }
5404 
5405 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5406 {
5407 	const struct bpf_reg_state *reg = reg_state(env, regno);
5408 
5409 	return type_is_sk_pointer(reg->type);
5410 }
5411 
5412 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5413 {
5414 	const struct bpf_reg_state *reg = reg_state(env, regno);
5415 
5416 	return type_is_pkt_pointer(reg->type);
5417 }
5418 
5419 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5420 {
5421 	const struct bpf_reg_state *reg = reg_state(env, regno);
5422 
5423 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5424 	return reg->type == PTR_TO_FLOW_KEYS;
5425 }
5426 
5427 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5428 #ifdef CONFIG_NET
5429 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5430 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5431 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5432 #endif
5433 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5434 };
5435 
5436 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5437 {
5438 	/* A referenced register is always trusted. */
5439 	if (reg->ref_obj_id)
5440 		return true;
5441 
5442 	/* Types listed in the reg2btf_ids are always trusted */
5443 	if (reg2btf_ids[base_type(reg->type)])
5444 		return true;
5445 
5446 	/* If a register is not referenced, it is trusted if it has the
5447 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5448 	 * other type modifiers may be safe, but we elect to take an opt-in
5449 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5450 	 * not.
5451 	 *
5452 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5453 	 * for whether a register is trusted.
5454 	 */
5455 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5456 	       !bpf_type_has_unsafe_modifiers(reg->type);
5457 }
5458 
5459 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5460 {
5461 	return reg->type & MEM_RCU;
5462 }
5463 
5464 static void clear_trusted_flags(enum bpf_type_flag *flag)
5465 {
5466 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5467 }
5468 
5469 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5470 				   const struct bpf_reg_state *reg,
5471 				   int off, int size, bool strict)
5472 {
5473 	struct tnum reg_off;
5474 	int ip_align;
5475 
5476 	/* Byte size accesses are always allowed. */
5477 	if (!strict || size == 1)
5478 		return 0;
5479 
5480 	/* For platforms that do not have a Kconfig enabling
5481 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5482 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5483 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5484 	 * to this code only in strict mode where we want to emulate
5485 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5486 	 * unconditional IP align value of '2'.
5487 	 */
5488 	ip_align = 2;
5489 
5490 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5491 	if (!tnum_is_aligned(reg_off, size)) {
5492 		char tn_buf[48];
5493 
5494 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5495 		verbose(env,
5496 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5497 			ip_align, tn_buf, reg->off, off, size);
5498 		return -EACCES;
5499 	}
5500 
5501 	return 0;
5502 }
5503 
5504 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5505 				       const struct bpf_reg_state *reg,
5506 				       const char *pointer_desc,
5507 				       int off, int size, bool strict)
5508 {
5509 	struct tnum reg_off;
5510 
5511 	/* Byte size accesses are always allowed. */
5512 	if (!strict || size == 1)
5513 		return 0;
5514 
5515 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5516 	if (!tnum_is_aligned(reg_off, size)) {
5517 		char tn_buf[48];
5518 
5519 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5520 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5521 			pointer_desc, tn_buf, reg->off, off, size);
5522 		return -EACCES;
5523 	}
5524 
5525 	return 0;
5526 }
5527 
5528 static int check_ptr_alignment(struct bpf_verifier_env *env,
5529 			       const struct bpf_reg_state *reg, int off,
5530 			       int size, bool strict_alignment_once)
5531 {
5532 	bool strict = env->strict_alignment || strict_alignment_once;
5533 	const char *pointer_desc = "";
5534 
5535 	switch (reg->type) {
5536 	case PTR_TO_PACKET:
5537 	case PTR_TO_PACKET_META:
5538 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5539 		 * right in front, treat it the very same way.
5540 		 */
5541 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5542 	case PTR_TO_FLOW_KEYS:
5543 		pointer_desc = "flow keys ";
5544 		break;
5545 	case PTR_TO_MAP_KEY:
5546 		pointer_desc = "key ";
5547 		break;
5548 	case PTR_TO_MAP_VALUE:
5549 		pointer_desc = "value ";
5550 		break;
5551 	case PTR_TO_CTX:
5552 		pointer_desc = "context ";
5553 		break;
5554 	case PTR_TO_STACK:
5555 		pointer_desc = "stack ";
5556 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5557 		 * and check_stack_read_fixed_off() relies on stack accesses being
5558 		 * aligned.
5559 		 */
5560 		strict = true;
5561 		break;
5562 	case PTR_TO_SOCKET:
5563 		pointer_desc = "sock ";
5564 		break;
5565 	case PTR_TO_SOCK_COMMON:
5566 		pointer_desc = "sock_common ";
5567 		break;
5568 	case PTR_TO_TCP_SOCK:
5569 		pointer_desc = "tcp_sock ";
5570 		break;
5571 	case PTR_TO_XDP_SOCK:
5572 		pointer_desc = "xdp_sock ";
5573 		break;
5574 	default:
5575 		break;
5576 	}
5577 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5578 					   strict);
5579 }
5580 
5581 static int update_stack_depth(struct bpf_verifier_env *env,
5582 			      const struct bpf_func_state *func,
5583 			      int off)
5584 {
5585 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5586 
5587 	if (stack >= -off)
5588 		return 0;
5589 
5590 	/* update known max for given subprogram */
5591 	env->subprog_info[func->subprogno].stack_depth = -off;
5592 	return 0;
5593 }
5594 
5595 /* starting from main bpf function walk all instructions of the function
5596  * and recursively walk all callees that given function can call.
5597  * Ignore jump and exit insns.
5598  * Since recursion is prevented by check_cfg() this algorithm
5599  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5600  */
5601 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5602 {
5603 	struct bpf_subprog_info *subprog = env->subprog_info;
5604 	struct bpf_insn *insn = env->prog->insnsi;
5605 	int depth = 0, frame = 0, i, subprog_end;
5606 	bool tail_call_reachable = false;
5607 	int ret_insn[MAX_CALL_FRAMES];
5608 	int ret_prog[MAX_CALL_FRAMES];
5609 	int j;
5610 
5611 	i = subprog[idx].start;
5612 process_func:
5613 	/* protect against potential stack overflow that might happen when
5614 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5615 	 * depth for such case down to 256 so that the worst case scenario
5616 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5617 	 * 8k).
5618 	 *
5619 	 * To get the idea what might happen, see an example:
5620 	 * func1 -> sub rsp, 128
5621 	 *  subfunc1 -> sub rsp, 256
5622 	 *  tailcall1 -> add rsp, 256
5623 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5624 	 *   subfunc2 -> sub rsp, 64
5625 	 *   subfunc22 -> sub rsp, 128
5626 	 *   tailcall2 -> add rsp, 128
5627 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5628 	 *
5629 	 * tailcall will unwind the current stack frame but it will not get rid
5630 	 * of caller's stack as shown on the example above.
5631 	 */
5632 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5633 		verbose(env,
5634 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5635 			depth);
5636 		return -EACCES;
5637 	}
5638 	/* round up to 32-bytes, since this is granularity
5639 	 * of interpreter stack size
5640 	 */
5641 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5642 	if (depth > MAX_BPF_STACK) {
5643 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5644 			frame + 1, depth);
5645 		return -EACCES;
5646 	}
5647 continue_func:
5648 	subprog_end = subprog[idx + 1].start;
5649 	for (; i < subprog_end; i++) {
5650 		int next_insn, sidx;
5651 
5652 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5653 			continue;
5654 		/* remember insn and function to return to */
5655 		ret_insn[frame] = i + 1;
5656 		ret_prog[frame] = idx;
5657 
5658 		/* find the callee */
5659 		next_insn = i + insn[i].imm + 1;
5660 		sidx = find_subprog(env, next_insn);
5661 		if (sidx < 0) {
5662 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5663 				  next_insn);
5664 			return -EFAULT;
5665 		}
5666 		if (subprog[sidx].is_async_cb) {
5667 			if (subprog[sidx].has_tail_call) {
5668 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5669 				return -EFAULT;
5670 			}
5671 			/* async callbacks don't increase bpf prog stack size unless called directly */
5672 			if (!bpf_pseudo_call(insn + i))
5673 				continue;
5674 		}
5675 		i = next_insn;
5676 		idx = sidx;
5677 
5678 		if (subprog[idx].has_tail_call)
5679 			tail_call_reachable = true;
5680 
5681 		frame++;
5682 		if (frame >= MAX_CALL_FRAMES) {
5683 			verbose(env, "the call stack of %d frames is too deep !\n",
5684 				frame);
5685 			return -E2BIG;
5686 		}
5687 		goto process_func;
5688 	}
5689 	/* if tail call got detected across bpf2bpf calls then mark each of the
5690 	 * currently present subprog frames as tail call reachable subprogs;
5691 	 * this info will be utilized by JIT so that we will be preserving the
5692 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5693 	 */
5694 	if (tail_call_reachable)
5695 		for (j = 0; j < frame; j++)
5696 			subprog[ret_prog[j]].tail_call_reachable = true;
5697 	if (subprog[0].tail_call_reachable)
5698 		env->prog->aux->tail_call_reachable = true;
5699 
5700 	/* end of for() loop means the last insn of the 'subprog'
5701 	 * was reached. Doesn't matter whether it was JA or EXIT
5702 	 */
5703 	if (frame == 0)
5704 		return 0;
5705 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5706 	frame--;
5707 	i = ret_insn[frame];
5708 	idx = ret_prog[frame];
5709 	goto continue_func;
5710 }
5711 
5712 static int check_max_stack_depth(struct bpf_verifier_env *env)
5713 {
5714 	struct bpf_subprog_info *si = env->subprog_info;
5715 	int ret;
5716 
5717 	for (int i = 0; i < env->subprog_cnt; i++) {
5718 		if (!i || si[i].is_async_cb) {
5719 			ret = check_max_stack_depth_subprog(env, i);
5720 			if (ret < 0)
5721 				return ret;
5722 		}
5723 		continue;
5724 	}
5725 	return 0;
5726 }
5727 
5728 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5729 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5730 				  const struct bpf_insn *insn, int idx)
5731 {
5732 	int start = idx + insn->imm + 1, subprog;
5733 
5734 	subprog = find_subprog(env, start);
5735 	if (subprog < 0) {
5736 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5737 			  start);
5738 		return -EFAULT;
5739 	}
5740 	return env->subprog_info[subprog].stack_depth;
5741 }
5742 #endif
5743 
5744 static int __check_buffer_access(struct bpf_verifier_env *env,
5745 				 const char *buf_info,
5746 				 const struct bpf_reg_state *reg,
5747 				 int regno, int off, int size)
5748 {
5749 	if (off < 0) {
5750 		verbose(env,
5751 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5752 			regno, buf_info, off, size);
5753 		return -EACCES;
5754 	}
5755 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5756 		char tn_buf[48];
5757 
5758 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5759 		verbose(env,
5760 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5761 			regno, off, tn_buf);
5762 		return -EACCES;
5763 	}
5764 
5765 	return 0;
5766 }
5767 
5768 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5769 				  const struct bpf_reg_state *reg,
5770 				  int regno, int off, int size)
5771 {
5772 	int err;
5773 
5774 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5775 	if (err)
5776 		return err;
5777 
5778 	if (off + size > env->prog->aux->max_tp_access)
5779 		env->prog->aux->max_tp_access = off + size;
5780 
5781 	return 0;
5782 }
5783 
5784 static int check_buffer_access(struct bpf_verifier_env *env,
5785 			       const struct bpf_reg_state *reg,
5786 			       int regno, int off, int size,
5787 			       bool zero_size_allowed,
5788 			       u32 *max_access)
5789 {
5790 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5791 	int err;
5792 
5793 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5794 	if (err)
5795 		return err;
5796 
5797 	if (off + size > *max_access)
5798 		*max_access = off + size;
5799 
5800 	return 0;
5801 }
5802 
5803 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5804 static void zext_32_to_64(struct bpf_reg_state *reg)
5805 {
5806 	reg->var_off = tnum_subreg(reg->var_off);
5807 	__reg_assign_32_into_64(reg);
5808 }
5809 
5810 /* truncate register to smaller size (in bytes)
5811  * must be called with size < BPF_REG_SIZE
5812  */
5813 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5814 {
5815 	u64 mask;
5816 
5817 	/* clear high bits in bit representation */
5818 	reg->var_off = tnum_cast(reg->var_off, size);
5819 
5820 	/* fix arithmetic bounds */
5821 	mask = ((u64)1 << (size * 8)) - 1;
5822 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5823 		reg->umin_value &= mask;
5824 		reg->umax_value &= mask;
5825 	} else {
5826 		reg->umin_value = 0;
5827 		reg->umax_value = mask;
5828 	}
5829 	reg->smin_value = reg->umin_value;
5830 	reg->smax_value = reg->umax_value;
5831 
5832 	/* If size is smaller than 32bit register the 32bit register
5833 	 * values are also truncated so we push 64-bit bounds into
5834 	 * 32-bit bounds. Above were truncated < 32-bits already.
5835 	 */
5836 	if (size >= 4)
5837 		return;
5838 	__reg_combine_64_into_32(reg);
5839 }
5840 
5841 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5842 {
5843 	if (size == 1) {
5844 		reg->smin_value = reg->s32_min_value = S8_MIN;
5845 		reg->smax_value = reg->s32_max_value = S8_MAX;
5846 	} else if (size == 2) {
5847 		reg->smin_value = reg->s32_min_value = S16_MIN;
5848 		reg->smax_value = reg->s32_max_value = S16_MAX;
5849 	} else {
5850 		/* size == 4 */
5851 		reg->smin_value = reg->s32_min_value = S32_MIN;
5852 		reg->smax_value = reg->s32_max_value = S32_MAX;
5853 	}
5854 	reg->umin_value = reg->u32_min_value = 0;
5855 	reg->umax_value = U64_MAX;
5856 	reg->u32_max_value = U32_MAX;
5857 	reg->var_off = tnum_unknown;
5858 }
5859 
5860 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5861 {
5862 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5863 	u64 top_smax_value, top_smin_value;
5864 	u64 num_bits = size * 8;
5865 
5866 	if (tnum_is_const(reg->var_off)) {
5867 		u64_cval = reg->var_off.value;
5868 		if (size == 1)
5869 			reg->var_off = tnum_const((s8)u64_cval);
5870 		else if (size == 2)
5871 			reg->var_off = tnum_const((s16)u64_cval);
5872 		else
5873 			/* size == 4 */
5874 			reg->var_off = tnum_const((s32)u64_cval);
5875 
5876 		u64_cval = reg->var_off.value;
5877 		reg->smax_value = reg->smin_value = u64_cval;
5878 		reg->umax_value = reg->umin_value = u64_cval;
5879 		reg->s32_max_value = reg->s32_min_value = u64_cval;
5880 		reg->u32_max_value = reg->u32_min_value = u64_cval;
5881 		return;
5882 	}
5883 
5884 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5885 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5886 
5887 	if (top_smax_value != top_smin_value)
5888 		goto out;
5889 
5890 	/* find the s64_min and s64_min after sign extension */
5891 	if (size == 1) {
5892 		init_s64_max = (s8)reg->smax_value;
5893 		init_s64_min = (s8)reg->smin_value;
5894 	} else if (size == 2) {
5895 		init_s64_max = (s16)reg->smax_value;
5896 		init_s64_min = (s16)reg->smin_value;
5897 	} else {
5898 		init_s64_max = (s32)reg->smax_value;
5899 		init_s64_min = (s32)reg->smin_value;
5900 	}
5901 
5902 	s64_max = max(init_s64_max, init_s64_min);
5903 	s64_min = min(init_s64_max, init_s64_min);
5904 
5905 	/* both of s64_max/s64_min positive or negative */
5906 	if ((s64_max >= 0) == (s64_min >= 0)) {
5907 		reg->smin_value = reg->s32_min_value = s64_min;
5908 		reg->smax_value = reg->s32_max_value = s64_max;
5909 		reg->umin_value = reg->u32_min_value = s64_min;
5910 		reg->umax_value = reg->u32_max_value = s64_max;
5911 		reg->var_off = tnum_range(s64_min, s64_max);
5912 		return;
5913 	}
5914 
5915 out:
5916 	set_sext64_default_val(reg, size);
5917 }
5918 
5919 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5920 {
5921 	if (size == 1) {
5922 		reg->s32_min_value = S8_MIN;
5923 		reg->s32_max_value = S8_MAX;
5924 	} else {
5925 		/* size == 2 */
5926 		reg->s32_min_value = S16_MIN;
5927 		reg->s32_max_value = S16_MAX;
5928 	}
5929 	reg->u32_min_value = 0;
5930 	reg->u32_max_value = U32_MAX;
5931 }
5932 
5933 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5934 {
5935 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5936 	u32 top_smax_value, top_smin_value;
5937 	u32 num_bits = size * 8;
5938 
5939 	if (tnum_is_const(reg->var_off)) {
5940 		u32_val = reg->var_off.value;
5941 		if (size == 1)
5942 			reg->var_off = tnum_const((s8)u32_val);
5943 		else
5944 			reg->var_off = tnum_const((s16)u32_val);
5945 
5946 		u32_val = reg->var_off.value;
5947 		reg->s32_min_value = reg->s32_max_value = u32_val;
5948 		reg->u32_min_value = reg->u32_max_value = u32_val;
5949 		return;
5950 	}
5951 
5952 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5953 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5954 
5955 	if (top_smax_value != top_smin_value)
5956 		goto out;
5957 
5958 	/* find the s32_min and s32_min after sign extension */
5959 	if (size == 1) {
5960 		init_s32_max = (s8)reg->s32_max_value;
5961 		init_s32_min = (s8)reg->s32_min_value;
5962 	} else {
5963 		/* size == 2 */
5964 		init_s32_max = (s16)reg->s32_max_value;
5965 		init_s32_min = (s16)reg->s32_min_value;
5966 	}
5967 	s32_max = max(init_s32_max, init_s32_min);
5968 	s32_min = min(init_s32_max, init_s32_min);
5969 
5970 	if ((s32_min >= 0) == (s32_max >= 0)) {
5971 		reg->s32_min_value = s32_min;
5972 		reg->s32_max_value = s32_max;
5973 		reg->u32_min_value = (u32)s32_min;
5974 		reg->u32_max_value = (u32)s32_max;
5975 		return;
5976 	}
5977 
5978 out:
5979 	set_sext32_default_val(reg, size);
5980 }
5981 
5982 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5983 {
5984 	/* A map is considered read-only if the following condition are true:
5985 	 *
5986 	 * 1) BPF program side cannot change any of the map content. The
5987 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5988 	 *    and was set at map creation time.
5989 	 * 2) The map value(s) have been initialized from user space by a
5990 	 *    loader and then "frozen", such that no new map update/delete
5991 	 *    operations from syscall side are possible for the rest of
5992 	 *    the map's lifetime from that point onwards.
5993 	 * 3) Any parallel/pending map update/delete operations from syscall
5994 	 *    side have been completed. Only after that point, it's safe to
5995 	 *    assume that map value(s) are immutable.
5996 	 */
5997 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5998 	       READ_ONCE(map->frozen) &&
5999 	       !bpf_map_write_active(map);
6000 }
6001 
6002 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6003 			       bool is_ldsx)
6004 {
6005 	void *ptr;
6006 	u64 addr;
6007 	int err;
6008 
6009 	err = map->ops->map_direct_value_addr(map, &addr, off);
6010 	if (err)
6011 		return err;
6012 	ptr = (void *)(long)addr + off;
6013 
6014 	switch (size) {
6015 	case sizeof(u8):
6016 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6017 		break;
6018 	case sizeof(u16):
6019 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6020 		break;
6021 	case sizeof(u32):
6022 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6023 		break;
6024 	case sizeof(u64):
6025 		*val = *(u64 *)ptr;
6026 		break;
6027 	default:
6028 		return -EINVAL;
6029 	}
6030 	return 0;
6031 }
6032 
6033 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6034 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6035 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6036 
6037 /*
6038  * Allow list few fields as RCU trusted or full trusted.
6039  * This logic doesn't allow mix tagging and will be removed once GCC supports
6040  * btf_type_tag.
6041  */
6042 
6043 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6044 BTF_TYPE_SAFE_RCU(struct task_struct) {
6045 	const cpumask_t *cpus_ptr;
6046 	struct css_set __rcu *cgroups;
6047 	struct task_struct __rcu *real_parent;
6048 	struct task_struct *group_leader;
6049 };
6050 
6051 BTF_TYPE_SAFE_RCU(struct cgroup) {
6052 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6053 	struct kernfs_node *kn;
6054 };
6055 
6056 BTF_TYPE_SAFE_RCU(struct css_set) {
6057 	struct cgroup *dfl_cgrp;
6058 };
6059 
6060 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6061 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6062 	struct file __rcu *exe_file;
6063 };
6064 
6065 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6066  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6067  */
6068 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6069 	struct sock *sk;
6070 };
6071 
6072 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6073 	struct sock *sk;
6074 };
6075 
6076 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6077 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6078 	struct seq_file *seq;
6079 };
6080 
6081 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6082 	struct bpf_iter_meta *meta;
6083 	struct task_struct *task;
6084 };
6085 
6086 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6087 	struct file *file;
6088 };
6089 
6090 BTF_TYPE_SAFE_TRUSTED(struct file) {
6091 	struct inode *f_inode;
6092 };
6093 
6094 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6095 	/* no negative dentry-s in places where bpf can see it */
6096 	struct inode *d_inode;
6097 };
6098 
6099 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6100 	struct sock *sk;
6101 };
6102 
6103 static bool type_is_rcu(struct bpf_verifier_env *env,
6104 			struct bpf_reg_state *reg,
6105 			const char *field_name, u32 btf_id)
6106 {
6107 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6108 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6109 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6110 
6111 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6112 }
6113 
6114 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6115 				struct bpf_reg_state *reg,
6116 				const char *field_name, u32 btf_id)
6117 {
6118 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6119 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6120 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6121 
6122 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6123 }
6124 
6125 static bool type_is_trusted(struct bpf_verifier_env *env,
6126 			    struct bpf_reg_state *reg,
6127 			    const char *field_name, u32 btf_id)
6128 {
6129 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6130 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6131 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6132 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6133 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6134 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6135 
6136 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6137 }
6138 
6139 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6140 				   struct bpf_reg_state *regs,
6141 				   int regno, int off, int size,
6142 				   enum bpf_access_type atype,
6143 				   int value_regno)
6144 {
6145 	struct bpf_reg_state *reg = regs + regno;
6146 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6147 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6148 	const char *field_name = NULL;
6149 	enum bpf_type_flag flag = 0;
6150 	u32 btf_id = 0;
6151 	int ret;
6152 
6153 	if (!env->allow_ptr_leaks) {
6154 		verbose(env,
6155 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6156 			tname);
6157 		return -EPERM;
6158 	}
6159 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6160 		verbose(env,
6161 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6162 			tname);
6163 		return -EINVAL;
6164 	}
6165 	if (off < 0) {
6166 		verbose(env,
6167 			"R%d is ptr_%s invalid negative access: off=%d\n",
6168 			regno, tname, off);
6169 		return -EACCES;
6170 	}
6171 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6172 		char tn_buf[48];
6173 
6174 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6175 		verbose(env,
6176 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6177 			regno, tname, off, tn_buf);
6178 		return -EACCES;
6179 	}
6180 
6181 	if (reg->type & MEM_USER) {
6182 		verbose(env,
6183 			"R%d is ptr_%s access user memory: off=%d\n",
6184 			regno, tname, off);
6185 		return -EACCES;
6186 	}
6187 
6188 	if (reg->type & MEM_PERCPU) {
6189 		verbose(env,
6190 			"R%d is ptr_%s access percpu memory: off=%d\n",
6191 			regno, tname, off);
6192 		return -EACCES;
6193 	}
6194 
6195 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6196 		if (!btf_is_kernel(reg->btf)) {
6197 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6198 			return -EFAULT;
6199 		}
6200 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6201 	} else {
6202 		/* Writes are permitted with default btf_struct_access for
6203 		 * program allocated objects (which always have ref_obj_id > 0),
6204 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6205 		 */
6206 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6207 			verbose(env, "only read is supported\n");
6208 			return -EACCES;
6209 		}
6210 
6211 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6212 		    !reg->ref_obj_id) {
6213 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6214 			return -EFAULT;
6215 		}
6216 
6217 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6218 	}
6219 
6220 	if (ret < 0)
6221 		return ret;
6222 
6223 	if (ret != PTR_TO_BTF_ID) {
6224 		/* just mark; */
6225 
6226 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6227 		/* If this is an untrusted pointer, all pointers formed by walking it
6228 		 * also inherit the untrusted flag.
6229 		 */
6230 		flag = PTR_UNTRUSTED;
6231 
6232 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6233 		/* By default any pointer obtained from walking a trusted pointer is no
6234 		 * longer trusted, unless the field being accessed has explicitly been
6235 		 * marked as inheriting its parent's state of trust (either full or RCU).
6236 		 * For example:
6237 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6238 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6239 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6240 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6241 		 *
6242 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6243 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6244 		 */
6245 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6246 			flag |= PTR_TRUSTED;
6247 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6248 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6249 				/* ignore __rcu tag and mark it MEM_RCU */
6250 				flag |= MEM_RCU;
6251 			} else if (flag & MEM_RCU ||
6252 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6253 				/* __rcu tagged pointers can be NULL */
6254 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6255 
6256 				/* We always trust them */
6257 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6258 				    flag & PTR_UNTRUSTED)
6259 					flag &= ~PTR_UNTRUSTED;
6260 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6261 				/* keep as-is */
6262 			} else {
6263 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6264 				clear_trusted_flags(&flag);
6265 			}
6266 		} else {
6267 			/*
6268 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6269 			 * aggressively mark as untrusted otherwise such
6270 			 * pointers will be plain PTR_TO_BTF_ID without flags
6271 			 * and will be allowed to be passed into helpers for
6272 			 * compat reasons.
6273 			 */
6274 			flag = PTR_UNTRUSTED;
6275 		}
6276 	} else {
6277 		/* Old compat. Deprecated */
6278 		clear_trusted_flags(&flag);
6279 	}
6280 
6281 	if (atype == BPF_READ && value_regno >= 0)
6282 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6283 
6284 	return 0;
6285 }
6286 
6287 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6288 				   struct bpf_reg_state *regs,
6289 				   int regno, int off, int size,
6290 				   enum bpf_access_type atype,
6291 				   int value_regno)
6292 {
6293 	struct bpf_reg_state *reg = regs + regno;
6294 	struct bpf_map *map = reg->map_ptr;
6295 	struct bpf_reg_state map_reg;
6296 	enum bpf_type_flag flag = 0;
6297 	const struct btf_type *t;
6298 	const char *tname;
6299 	u32 btf_id;
6300 	int ret;
6301 
6302 	if (!btf_vmlinux) {
6303 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6304 		return -ENOTSUPP;
6305 	}
6306 
6307 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6308 		verbose(env, "map_ptr access not supported for map type %d\n",
6309 			map->map_type);
6310 		return -ENOTSUPP;
6311 	}
6312 
6313 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6314 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6315 
6316 	if (!env->allow_ptr_leaks) {
6317 		verbose(env,
6318 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6319 			tname);
6320 		return -EPERM;
6321 	}
6322 
6323 	if (off < 0) {
6324 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6325 			regno, tname, off);
6326 		return -EACCES;
6327 	}
6328 
6329 	if (atype != BPF_READ) {
6330 		verbose(env, "only read from %s is supported\n", tname);
6331 		return -EACCES;
6332 	}
6333 
6334 	/* Simulate access to a PTR_TO_BTF_ID */
6335 	memset(&map_reg, 0, sizeof(map_reg));
6336 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6337 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6338 	if (ret < 0)
6339 		return ret;
6340 
6341 	if (value_regno >= 0)
6342 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6343 
6344 	return 0;
6345 }
6346 
6347 /* Check that the stack access at the given offset is within bounds. The
6348  * maximum valid offset is -1.
6349  *
6350  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6351  * -state->allocated_stack for reads.
6352  */
6353 static int check_stack_slot_within_bounds(int off,
6354 					  struct bpf_func_state *state,
6355 					  enum bpf_access_type t)
6356 {
6357 	int min_valid_off;
6358 
6359 	if (t == BPF_WRITE)
6360 		min_valid_off = -MAX_BPF_STACK;
6361 	else
6362 		min_valid_off = -state->allocated_stack;
6363 
6364 	if (off < min_valid_off || off > -1)
6365 		return -EACCES;
6366 	return 0;
6367 }
6368 
6369 /* Check that the stack access at 'regno + off' falls within the maximum stack
6370  * bounds.
6371  *
6372  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6373  */
6374 static int check_stack_access_within_bounds(
6375 		struct bpf_verifier_env *env,
6376 		int regno, int off, int access_size,
6377 		enum bpf_access_src src, enum bpf_access_type type)
6378 {
6379 	struct bpf_reg_state *regs = cur_regs(env);
6380 	struct bpf_reg_state *reg = regs + regno;
6381 	struct bpf_func_state *state = func(env, reg);
6382 	int min_off, max_off;
6383 	int err;
6384 	char *err_extra;
6385 
6386 	if (src == ACCESS_HELPER)
6387 		/* We don't know if helpers are reading or writing (or both). */
6388 		err_extra = " indirect access to";
6389 	else if (type == BPF_READ)
6390 		err_extra = " read from";
6391 	else
6392 		err_extra = " write to";
6393 
6394 	if (tnum_is_const(reg->var_off)) {
6395 		min_off = reg->var_off.value + off;
6396 		if (access_size > 0)
6397 			max_off = min_off + access_size - 1;
6398 		else
6399 			max_off = min_off;
6400 	} else {
6401 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6402 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6403 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6404 				err_extra, regno);
6405 			return -EACCES;
6406 		}
6407 		min_off = reg->smin_value + off;
6408 		if (access_size > 0)
6409 			max_off = reg->smax_value + off + access_size - 1;
6410 		else
6411 			max_off = min_off;
6412 	}
6413 
6414 	err = check_stack_slot_within_bounds(min_off, state, type);
6415 	if (!err)
6416 		err = check_stack_slot_within_bounds(max_off, state, type);
6417 
6418 	if (err) {
6419 		if (tnum_is_const(reg->var_off)) {
6420 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6421 				err_extra, regno, off, access_size);
6422 		} else {
6423 			char tn_buf[48];
6424 
6425 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6426 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6427 				err_extra, regno, tn_buf, access_size);
6428 		}
6429 	}
6430 	return err;
6431 }
6432 
6433 /* check whether memory at (regno + off) is accessible for t = (read | write)
6434  * if t==write, value_regno is a register which value is stored into memory
6435  * if t==read, value_regno is a register which will receive the value from memory
6436  * if t==write && value_regno==-1, some unknown value is stored into memory
6437  * if t==read && value_regno==-1, don't care what we read from memory
6438  */
6439 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6440 			    int off, int bpf_size, enum bpf_access_type t,
6441 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6442 {
6443 	struct bpf_reg_state *regs = cur_regs(env);
6444 	struct bpf_reg_state *reg = regs + regno;
6445 	struct bpf_func_state *state;
6446 	int size, err = 0;
6447 
6448 	size = bpf_size_to_bytes(bpf_size);
6449 	if (size < 0)
6450 		return size;
6451 
6452 	/* alignment checks will add in reg->off themselves */
6453 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6454 	if (err)
6455 		return err;
6456 
6457 	/* for access checks, reg->off is just part of off */
6458 	off += reg->off;
6459 
6460 	if (reg->type == PTR_TO_MAP_KEY) {
6461 		if (t == BPF_WRITE) {
6462 			verbose(env, "write to change key R%d not allowed\n", regno);
6463 			return -EACCES;
6464 		}
6465 
6466 		err = check_mem_region_access(env, regno, off, size,
6467 					      reg->map_ptr->key_size, false);
6468 		if (err)
6469 			return err;
6470 		if (value_regno >= 0)
6471 			mark_reg_unknown(env, regs, value_regno);
6472 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6473 		struct btf_field *kptr_field = NULL;
6474 
6475 		if (t == BPF_WRITE && value_regno >= 0 &&
6476 		    is_pointer_value(env, value_regno)) {
6477 			verbose(env, "R%d leaks addr into map\n", value_regno);
6478 			return -EACCES;
6479 		}
6480 		err = check_map_access_type(env, regno, off, size, t);
6481 		if (err)
6482 			return err;
6483 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6484 		if (err)
6485 			return err;
6486 		if (tnum_is_const(reg->var_off))
6487 			kptr_field = btf_record_find(reg->map_ptr->record,
6488 						     off + reg->var_off.value, BPF_KPTR);
6489 		if (kptr_field) {
6490 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6491 		} else if (t == BPF_READ && value_regno >= 0) {
6492 			struct bpf_map *map = reg->map_ptr;
6493 
6494 			/* if map is read-only, track its contents as scalars */
6495 			if (tnum_is_const(reg->var_off) &&
6496 			    bpf_map_is_rdonly(map) &&
6497 			    map->ops->map_direct_value_addr) {
6498 				int map_off = off + reg->var_off.value;
6499 				u64 val = 0;
6500 
6501 				err = bpf_map_direct_read(map, map_off, size,
6502 							  &val, is_ldsx);
6503 				if (err)
6504 					return err;
6505 
6506 				regs[value_regno].type = SCALAR_VALUE;
6507 				__mark_reg_known(&regs[value_regno], val);
6508 			} else {
6509 				mark_reg_unknown(env, regs, value_regno);
6510 			}
6511 		}
6512 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6513 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6514 
6515 		if (type_may_be_null(reg->type)) {
6516 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6517 				reg_type_str(env, reg->type));
6518 			return -EACCES;
6519 		}
6520 
6521 		if (t == BPF_WRITE && rdonly_mem) {
6522 			verbose(env, "R%d cannot write into %s\n",
6523 				regno, reg_type_str(env, reg->type));
6524 			return -EACCES;
6525 		}
6526 
6527 		if (t == BPF_WRITE && value_regno >= 0 &&
6528 		    is_pointer_value(env, value_regno)) {
6529 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6530 			return -EACCES;
6531 		}
6532 
6533 		err = check_mem_region_access(env, regno, off, size,
6534 					      reg->mem_size, false);
6535 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6536 			mark_reg_unknown(env, regs, value_regno);
6537 	} else if (reg->type == PTR_TO_CTX) {
6538 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6539 		struct btf *btf = NULL;
6540 		u32 btf_id = 0;
6541 
6542 		if (t == BPF_WRITE && value_regno >= 0 &&
6543 		    is_pointer_value(env, value_regno)) {
6544 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6545 			return -EACCES;
6546 		}
6547 
6548 		err = check_ptr_off_reg(env, reg, regno);
6549 		if (err < 0)
6550 			return err;
6551 
6552 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6553 				       &btf_id);
6554 		if (err)
6555 			verbose_linfo(env, insn_idx, "; ");
6556 		if (!err && t == BPF_READ && value_regno >= 0) {
6557 			/* ctx access returns either a scalar, or a
6558 			 * PTR_TO_PACKET[_META,_END]. In the latter
6559 			 * case, we know the offset is zero.
6560 			 */
6561 			if (reg_type == SCALAR_VALUE) {
6562 				mark_reg_unknown(env, regs, value_regno);
6563 			} else {
6564 				mark_reg_known_zero(env, regs,
6565 						    value_regno);
6566 				if (type_may_be_null(reg_type))
6567 					regs[value_regno].id = ++env->id_gen;
6568 				/* A load of ctx field could have different
6569 				 * actual load size with the one encoded in the
6570 				 * insn. When the dst is PTR, it is for sure not
6571 				 * a sub-register.
6572 				 */
6573 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6574 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6575 					regs[value_regno].btf = btf;
6576 					regs[value_regno].btf_id = btf_id;
6577 				}
6578 			}
6579 			regs[value_regno].type = reg_type;
6580 		}
6581 
6582 	} else if (reg->type == PTR_TO_STACK) {
6583 		/* Basic bounds checks. */
6584 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6585 		if (err)
6586 			return err;
6587 
6588 		state = func(env, reg);
6589 		err = update_stack_depth(env, state, off);
6590 		if (err)
6591 			return err;
6592 
6593 		if (t == BPF_READ)
6594 			err = check_stack_read(env, regno, off, size,
6595 					       value_regno);
6596 		else
6597 			err = check_stack_write(env, regno, off, size,
6598 						value_regno, insn_idx);
6599 	} else if (reg_is_pkt_pointer(reg)) {
6600 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6601 			verbose(env, "cannot write into packet\n");
6602 			return -EACCES;
6603 		}
6604 		if (t == BPF_WRITE && value_regno >= 0 &&
6605 		    is_pointer_value(env, value_regno)) {
6606 			verbose(env, "R%d leaks addr into packet\n",
6607 				value_regno);
6608 			return -EACCES;
6609 		}
6610 		err = check_packet_access(env, regno, off, size, false);
6611 		if (!err && t == BPF_READ && value_regno >= 0)
6612 			mark_reg_unknown(env, regs, value_regno);
6613 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6614 		if (t == BPF_WRITE && value_regno >= 0 &&
6615 		    is_pointer_value(env, value_regno)) {
6616 			verbose(env, "R%d leaks addr into flow keys\n",
6617 				value_regno);
6618 			return -EACCES;
6619 		}
6620 
6621 		err = check_flow_keys_access(env, off, size);
6622 		if (!err && t == BPF_READ && value_regno >= 0)
6623 			mark_reg_unknown(env, regs, value_regno);
6624 	} else if (type_is_sk_pointer(reg->type)) {
6625 		if (t == BPF_WRITE) {
6626 			verbose(env, "R%d cannot write into %s\n",
6627 				regno, reg_type_str(env, reg->type));
6628 			return -EACCES;
6629 		}
6630 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6631 		if (!err && value_regno >= 0)
6632 			mark_reg_unknown(env, regs, value_regno);
6633 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6634 		err = check_tp_buffer_access(env, reg, regno, off, size);
6635 		if (!err && t == BPF_READ && value_regno >= 0)
6636 			mark_reg_unknown(env, regs, value_regno);
6637 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6638 		   !type_may_be_null(reg->type)) {
6639 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6640 					      value_regno);
6641 	} else if (reg->type == CONST_PTR_TO_MAP) {
6642 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6643 					      value_regno);
6644 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6645 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6646 		u32 *max_access;
6647 
6648 		if (rdonly_mem) {
6649 			if (t == BPF_WRITE) {
6650 				verbose(env, "R%d cannot write into %s\n",
6651 					regno, reg_type_str(env, reg->type));
6652 				return -EACCES;
6653 			}
6654 			max_access = &env->prog->aux->max_rdonly_access;
6655 		} else {
6656 			max_access = &env->prog->aux->max_rdwr_access;
6657 		}
6658 
6659 		err = check_buffer_access(env, reg, regno, off, size, false,
6660 					  max_access);
6661 
6662 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6663 			mark_reg_unknown(env, regs, value_regno);
6664 	} else {
6665 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6666 			reg_type_str(env, reg->type));
6667 		return -EACCES;
6668 	}
6669 
6670 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6671 	    regs[value_regno].type == SCALAR_VALUE) {
6672 		if (!is_ldsx)
6673 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6674 			coerce_reg_to_size(&regs[value_regno], size);
6675 		else
6676 			coerce_reg_to_size_sx(&regs[value_regno], size);
6677 	}
6678 	return err;
6679 }
6680 
6681 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6682 {
6683 	int load_reg;
6684 	int err;
6685 
6686 	switch (insn->imm) {
6687 	case BPF_ADD:
6688 	case BPF_ADD | BPF_FETCH:
6689 	case BPF_AND:
6690 	case BPF_AND | BPF_FETCH:
6691 	case BPF_OR:
6692 	case BPF_OR | BPF_FETCH:
6693 	case BPF_XOR:
6694 	case BPF_XOR | BPF_FETCH:
6695 	case BPF_XCHG:
6696 	case BPF_CMPXCHG:
6697 		break;
6698 	default:
6699 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6700 		return -EINVAL;
6701 	}
6702 
6703 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6704 		verbose(env, "invalid atomic operand size\n");
6705 		return -EINVAL;
6706 	}
6707 
6708 	/* check src1 operand */
6709 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6710 	if (err)
6711 		return err;
6712 
6713 	/* check src2 operand */
6714 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6715 	if (err)
6716 		return err;
6717 
6718 	if (insn->imm == BPF_CMPXCHG) {
6719 		/* Check comparison of R0 with memory location */
6720 		const u32 aux_reg = BPF_REG_0;
6721 
6722 		err = check_reg_arg(env, aux_reg, SRC_OP);
6723 		if (err)
6724 			return err;
6725 
6726 		if (is_pointer_value(env, aux_reg)) {
6727 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6728 			return -EACCES;
6729 		}
6730 	}
6731 
6732 	if (is_pointer_value(env, insn->src_reg)) {
6733 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6734 		return -EACCES;
6735 	}
6736 
6737 	if (is_ctx_reg(env, insn->dst_reg) ||
6738 	    is_pkt_reg(env, insn->dst_reg) ||
6739 	    is_flow_key_reg(env, insn->dst_reg) ||
6740 	    is_sk_reg(env, insn->dst_reg)) {
6741 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6742 			insn->dst_reg,
6743 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6744 		return -EACCES;
6745 	}
6746 
6747 	if (insn->imm & BPF_FETCH) {
6748 		if (insn->imm == BPF_CMPXCHG)
6749 			load_reg = BPF_REG_0;
6750 		else
6751 			load_reg = insn->src_reg;
6752 
6753 		/* check and record load of old value */
6754 		err = check_reg_arg(env, load_reg, DST_OP);
6755 		if (err)
6756 			return err;
6757 	} else {
6758 		/* This instruction accesses a memory location but doesn't
6759 		 * actually load it into a register.
6760 		 */
6761 		load_reg = -1;
6762 	}
6763 
6764 	/* Check whether we can read the memory, with second call for fetch
6765 	 * case to simulate the register fill.
6766 	 */
6767 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6768 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6769 	if (!err && load_reg >= 0)
6770 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6771 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6772 				       true, false);
6773 	if (err)
6774 		return err;
6775 
6776 	/* Check whether we can write into the same memory. */
6777 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6778 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6779 	if (err)
6780 		return err;
6781 
6782 	return 0;
6783 }
6784 
6785 /* When register 'regno' is used to read the stack (either directly or through
6786  * a helper function) make sure that it's within stack boundary and, depending
6787  * on the access type, that all elements of the stack are initialized.
6788  *
6789  * 'off' includes 'regno->off', but not its dynamic part (if any).
6790  *
6791  * All registers that have been spilled on the stack in the slots within the
6792  * read offsets are marked as read.
6793  */
6794 static int check_stack_range_initialized(
6795 		struct bpf_verifier_env *env, int regno, int off,
6796 		int access_size, bool zero_size_allowed,
6797 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6798 {
6799 	struct bpf_reg_state *reg = reg_state(env, regno);
6800 	struct bpf_func_state *state = func(env, reg);
6801 	int err, min_off, max_off, i, j, slot, spi;
6802 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6803 	enum bpf_access_type bounds_check_type;
6804 	/* Some accesses can write anything into the stack, others are
6805 	 * read-only.
6806 	 */
6807 	bool clobber = false;
6808 
6809 	if (access_size == 0 && !zero_size_allowed) {
6810 		verbose(env, "invalid zero-sized read\n");
6811 		return -EACCES;
6812 	}
6813 
6814 	if (type == ACCESS_HELPER) {
6815 		/* The bounds checks for writes are more permissive than for
6816 		 * reads. However, if raw_mode is not set, we'll do extra
6817 		 * checks below.
6818 		 */
6819 		bounds_check_type = BPF_WRITE;
6820 		clobber = true;
6821 	} else {
6822 		bounds_check_type = BPF_READ;
6823 	}
6824 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6825 					       type, bounds_check_type);
6826 	if (err)
6827 		return err;
6828 
6829 
6830 	if (tnum_is_const(reg->var_off)) {
6831 		min_off = max_off = reg->var_off.value + off;
6832 	} else {
6833 		/* Variable offset is prohibited for unprivileged mode for
6834 		 * simplicity since it requires corresponding support in
6835 		 * Spectre masking for stack ALU.
6836 		 * See also retrieve_ptr_limit().
6837 		 */
6838 		if (!env->bypass_spec_v1) {
6839 			char tn_buf[48];
6840 
6841 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6842 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6843 				regno, err_extra, tn_buf);
6844 			return -EACCES;
6845 		}
6846 		/* Only initialized buffer on stack is allowed to be accessed
6847 		 * with variable offset. With uninitialized buffer it's hard to
6848 		 * guarantee that whole memory is marked as initialized on
6849 		 * helper return since specific bounds are unknown what may
6850 		 * cause uninitialized stack leaking.
6851 		 */
6852 		if (meta && meta->raw_mode)
6853 			meta = NULL;
6854 
6855 		min_off = reg->smin_value + off;
6856 		max_off = reg->smax_value + off;
6857 	}
6858 
6859 	if (meta && meta->raw_mode) {
6860 		/* Ensure we won't be overwriting dynptrs when simulating byte
6861 		 * by byte access in check_helper_call using meta.access_size.
6862 		 * This would be a problem if we have a helper in the future
6863 		 * which takes:
6864 		 *
6865 		 *	helper(uninit_mem, len, dynptr)
6866 		 *
6867 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6868 		 * may end up writing to dynptr itself when touching memory from
6869 		 * arg 1. This can be relaxed on a case by case basis for known
6870 		 * safe cases, but reject due to the possibilitiy of aliasing by
6871 		 * default.
6872 		 */
6873 		for (i = min_off; i < max_off + access_size; i++) {
6874 			int stack_off = -i - 1;
6875 
6876 			spi = __get_spi(i);
6877 			/* raw_mode may write past allocated_stack */
6878 			if (state->allocated_stack <= stack_off)
6879 				continue;
6880 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6881 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6882 				return -EACCES;
6883 			}
6884 		}
6885 		meta->access_size = access_size;
6886 		meta->regno = regno;
6887 		return 0;
6888 	}
6889 
6890 	for (i = min_off; i < max_off + access_size; i++) {
6891 		u8 *stype;
6892 
6893 		slot = -i - 1;
6894 		spi = slot / BPF_REG_SIZE;
6895 		if (state->allocated_stack <= slot)
6896 			goto err;
6897 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6898 		if (*stype == STACK_MISC)
6899 			goto mark;
6900 		if ((*stype == STACK_ZERO) ||
6901 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6902 			if (clobber) {
6903 				/* helper can write anything into the stack */
6904 				*stype = STACK_MISC;
6905 			}
6906 			goto mark;
6907 		}
6908 
6909 		if (is_spilled_reg(&state->stack[spi]) &&
6910 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6911 		     env->allow_ptr_leaks)) {
6912 			if (clobber) {
6913 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6914 				for (j = 0; j < BPF_REG_SIZE; j++)
6915 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6916 			}
6917 			goto mark;
6918 		}
6919 
6920 err:
6921 		if (tnum_is_const(reg->var_off)) {
6922 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6923 				err_extra, regno, min_off, i - min_off, access_size);
6924 		} else {
6925 			char tn_buf[48];
6926 
6927 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6928 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6929 				err_extra, regno, tn_buf, i - min_off, access_size);
6930 		}
6931 		return -EACCES;
6932 mark:
6933 		/* reading any byte out of 8-byte 'spill_slot' will cause
6934 		 * the whole slot to be marked as 'read'
6935 		 */
6936 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6937 			      state->stack[spi].spilled_ptr.parent,
6938 			      REG_LIVE_READ64);
6939 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6940 		 * be sure that whether stack slot is written to or not. Hence,
6941 		 * we must still conservatively propagate reads upwards even if
6942 		 * helper may write to the entire memory range.
6943 		 */
6944 	}
6945 	return update_stack_depth(env, state, min_off);
6946 }
6947 
6948 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6949 				   int access_size, bool zero_size_allowed,
6950 				   struct bpf_call_arg_meta *meta)
6951 {
6952 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6953 	u32 *max_access;
6954 
6955 	switch (base_type(reg->type)) {
6956 	case PTR_TO_PACKET:
6957 	case PTR_TO_PACKET_META:
6958 		return check_packet_access(env, regno, reg->off, access_size,
6959 					   zero_size_allowed);
6960 	case PTR_TO_MAP_KEY:
6961 		if (meta && meta->raw_mode) {
6962 			verbose(env, "R%d cannot write into %s\n", regno,
6963 				reg_type_str(env, reg->type));
6964 			return -EACCES;
6965 		}
6966 		return check_mem_region_access(env, regno, reg->off, access_size,
6967 					       reg->map_ptr->key_size, false);
6968 	case PTR_TO_MAP_VALUE:
6969 		if (check_map_access_type(env, regno, reg->off, access_size,
6970 					  meta && meta->raw_mode ? BPF_WRITE :
6971 					  BPF_READ))
6972 			return -EACCES;
6973 		return check_map_access(env, regno, reg->off, access_size,
6974 					zero_size_allowed, ACCESS_HELPER);
6975 	case PTR_TO_MEM:
6976 		if (type_is_rdonly_mem(reg->type)) {
6977 			if (meta && meta->raw_mode) {
6978 				verbose(env, "R%d cannot write into %s\n", regno,
6979 					reg_type_str(env, reg->type));
6980 				return -EACCES;
6981 			}
6982 		}
6983 		return check_mem_region_access(env, regno, reg->off,
6984 					       access_size, reg->mem_size,
6985 					       zero_size_allowed);
6986 	case PTR_TO_BUF:
6987 		if (type_is_rdonly_mem(reg->type)) {
6988 			if (meta && meta->raw_mode) {
6989 				verbose(env, "R%d cannot write into %s\n", regno,
6990 					reg_type_str(env, reg->type));
6991 				return -EACCES;
6992 			}
6993 
6994 			max_access = &env->prog->aux->max_rdonly_access;
6995 		} else {
6996 			max_access = &env->prog->aux->max_rdwr_access;
6997 		}
6998 		return check_buffer_access(env, reg, regno, reg->off,
6999 					   access_size, zero_size_allowed,
7000 					   max_access);
7001 	case PTR_TO_STACK:
7002 		return check_stack_range_initialized(
7003 				env,
7004 				regno, reg->off, access_size,
7005 				zero_size_allowed, ACCESS_HELPER, meta);
7006 	case PTR_TO_BTF_ID:
7007 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7008 					       access_size, BPF_READ, -1);
7009 	case PTR_TO_CTX:
7010 		/* in case the function doesn't know how to access the context,
7011 		 * (because we are in a program of type SYSCALL for example), we
7012 		 * can not statically check its size.
7013 		 * Dynamically check it now.
7014 		 */
7015 		if (!env->ops->convert_ctx_access) {
7016 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7017 			int offset = access_size - 1;
7018 
7019 			/* Allow zero-byte read from PTR_TO_CTX */
7020 			if (access_size == 0)
7021 				return zero_size_allowed ? 0 : -EACCES;
7022 
7023 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7024 						atype, -1, false, false);
7025 		}
7026 
7027 		fallthrough;
7028 	default: /* scalar_value or invalid ptr */
7029 		/* Allow zero-byte read from NULL, regardless of pointer type */
7030 		if (zero_size_allowed && access_size == 0 &&
7031 		    register_is_null(reg))
7032 			return 0;
7033 
7034 		verbose(env, "R%d type=%s ", regno,
7035 			reg_type_str(env, reg->type));
7036 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7037 		return -EACCES;
7038 	}
7039 }
7040 
7041 static int check_mem_size_reg(struct bpf_verifier_env *env,
7042 			      struct bpf_reg_state *reg, u32 regno,
7043 			      bool zero_size_allowed,
7044 			      struct bpf_call_arg_meta *meta)
7045 {
7046 	int err;
7047 
7048 	/* This is used to refine r0 return value bounds for helpers
7049 	 * that enforce this value as an upper bound on return values.
7050 	 * See do_refine_retval_range() for helpers that can refine
7051 	 * the return value. C type of helper is u32 so we pull register
7052 	 * bound from umax_value however, if negative verifier errors
7053 	 * out. Only upper bounds can be learned because retval is an
7054 	 * int type and negative retvals are allowed.
7055 	 */
7056 	meta->msize_max_value = reg->umax_value;
7057 
7058 	/* The register is SCALAR_VALUE; the access check
7059 	 * happens using its boundaries.
7060 	 */
7061 	if (!tnum_is_const(reg->var_off))
7062 		/* For unprivileged variable accesses, disable raw
7063 		 * mode so that the program is required to
7064 		 * initialize all the memory that the helper could
7065 		 * just partially fill up.
7066 		 */
7067 		meta = NULL;
7068 
7069 	if (reg->smin_value < 0) {
7070 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7071 			regno);
7072 		return -EACCES;
7073 	}
7074 
7075 	if (reg->umin_value == 0) {
7076 		err = check_helper_mem_access(env, regno - 1, 0,
7077 					      zero_size_allowed,
7078 					      meta);
7079 		if (err)
7080 			return err;
7081 	}
7082 
7083 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7084 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7085 			regno);
7086 		return -EACCES;
7087 	}
7088 	err = check_helper_mem_access(env, regno - 1,
7089 				      reg->umax_value,
7090 				      zero_size_allowed, meta);
7091 	if (!err)
7092 		err = mark_chain_precision(env, regno);
7093 	return err;
7094 }
7095 
7096 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7097 		   u32 regno, u32 mem_size)
7098 {
7099 	bool may_be_null = type_may_be_null(reg->type);
7100 	struct bpf_reg_state saved_reg;
7101 	struct bpf_call_arg_meta meta;
7102 	int err;
7103 
7104 	if (register_is_null(reg))
7105 		return 0;
7106 
7107 	memset(&meta, 0, sizeof(meta));
7108 	/* Assuming that the register contains a value check if the memory
7109 	 * access is safe. Temporarily save and restore the register's state as
7110 	 * the conversion shouldn't be visible to a caller.
7111 	 */
7112 	if (may_be_null) {
7113 		saved_reg = *reg;
7114 		mark_ptr_not_null_reg(reg);
7115 	}
7116 
7117 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7118 	/* Check access for BPF_WRITE */
7119 	meta.raw_mode = true;
7120 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7121 
7122 	if (may_be_null)
7123 		*reg = saved_reg;
7124 
7125 	return err;
7126 }
7127 
7128 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7129 				    u32 regno)
7130 {
7131 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7132 	bool may_be_null = type_may_be_null(mem_reg->type);
7133 	struct bpf_reg_state saved_reg;
7134 	struct bpf_call_arg_meta meta;
7135 	int err;
7136 
7137 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7138 
7139 	memset(&meta, 0, sizeof(meta));
7140 
7141 	if (may_be_null) {
7142 		saved_reg = *mem_reg;
7143 		mark_ptr_not_null_reg(mem_reg);
7144 	}
7145 
7146 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7147 	/* Check access for BPF_WRITE */
7148 	meta.raw_mode = true;
7149 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7150 
7151 	if (may_be_null)
7152 		*mem_reg = saved_reg;
7153 	return err;
7154 }
7155 
7156 /* Implementation details:
7157  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7158  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7159  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7160  * Two separate bpf_obj_new will also have different reg->id.
7161  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7162  * clears reg->id after value_or_null->value transition, since the verifier only
7163  * cares about the range of access to valid map value pointer and doesn't care
7164  * about actual address of the map element.
7165  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7166  * reg->id > 0 after value_or_null->value transition. By doing so
7167  * two bpf_map_lookups will be considered two different pointers that
7168  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7169  * returned from bpf_obj_new.
7170  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7171  * dead-locks.
7172  * Since only one bpf_spin_lock is allowed the checks are simpler than
7173  * reg_is_refcounted() logic. The verifier needs to remember only
7174  * one spin_lock instead of array of acquired_refs.
7175  * cur_state->active_lock remembers which map value element or allocated
7176  * object got locked and clears it after bpf_spin_unlock.
7177  */
7178 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7179 			     bool is_lock)
7180 {
7181 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7182 	struct bpf_verifier_state *cur = env->cur_state;
7183 	bool is_const = tnum_is_const(reg->var_off);
7184 	u64 val = reg->var_off.value;
7185 	struct bpf_map *map = NULL;
7186 	struct btf *btf = NULL;
7187 	struct btf_record *rec;
7188 
7189 	if (!is_const) {
7190 		verbose(env,
7191 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7192 			regno);
7193 		return -EINVAL;
7194 	}
7195 	if (reg->type == PTR_TO_MAP_VALUE) {
7196 		map = reg->map_ptr;
7197 		if (!map->btf) {
7198 			verbose(env,
7199 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7200 				map->name);
7201 			return -EINVAL;
7202 		}
7203 	} else {
7204 		btf = reg->btf;
7205 	}
7206 
7207 	rec = reg_btf_record(reg);
7208 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7209 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7210 			map ? map->name : "kptr");
7211 		return -EINVAL;
7212 	}
7213 	if (rec->spin_lock_off != val + reg->off) {
7214 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7215 			val + reg->off, rec->spin_lock_off);
7216 		return -EINVAL;
7217 	}
7218 	if (is_lock) {
7219 		if (cur->active_lock.ptr) {
7220 			verbose(env,
7221 				"Locking two bpf_spin_locks are not allowed\n");
7222 			return -EINVAL;
7223 		}
7224 		if (map)
7225 			cur->active_lock.ptr = map;
7226 		else
7227 			cur->active_lock.ptr = btf;
7228 		cur->active_lock.id = reg->id;
7229 	} else {
7230 		void *ptr;
7231 
7232 		if (map)
7233 			ptr = map;
7234 		else
7235 			ptr = btf;
7236 
7237 		if (!cur->active_lock.ptr) {
7238 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7239 			return -EINVAL;
7240 		}
7241 		if (cur->active_lock.ptr != ptr ||
7242 		    cur->active_lock.id != reg->id) {
7243 			verbose(env, "bpf_spin_unlock of different lock\n");
7244 			return -EINVAL;
7245 		}
7246 
7247 		invalidate_non_owning_refs(env);
7248 
7249 		cur->active_lock.ptr = NULL;
7250 		cur->active_lock.id = 0;
7251 	}
7252 	return 0;
7253 }
7254 
7255 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7256 			      struct bpf_call_arg_meta *meta)
7257 {
7258 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7259 	bool is_const = tnum_is_const(reg->var_off);
7260 	struct bpf_map *map = reg->map_ptr;
7261 	u64 val = reg->var_off.value;
7262 
7263 	if (!is_const) {
7264 		verbose(env,
7265 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7266 			regno);
7267 		return -EINVAL;
7268 	}
7269 	if (!map->btf) {
7270 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7271 			map->name);
7272 		return -EINVAL;
7273 	}
7274 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7275 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7276 		return -EINVAL;
7277 	}
7278 	if (map->record->timer_off != val + reg->off) {
7279 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7280 			val + reg->off, map->record->timer_off);
7281 		return -EINVAL;
7282 	}
7283 	if (meta->map_ptr) {
7284 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7285 		return -EFAULT;
7286 	}
7287 	meta->map_uid = reg->map_uid;
7288 	meta->map_ptr = map;
7289 	return 0;
7290 }
7291 
7292 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7293 			     struct bpf_call_arg_meta *meta)
7294 {
7295 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7296 	struct bpf_map *map_ptr = reg->map_ptr;
7297 	struct btf_field *kptr_field;
7298 	u32 kptr_off;
7299 
7300 	if (!tnum_is_const(reg->var_off)) {
7301 		verbose(env,
7302 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7303 			regno);
7304 		return -EINVAL;
7305 	}
7306 	if (!map_ptr->btf) {
7307 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7308 			map_ptr->name);
7309 		return -EINVAL;
7310 	}
7311 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7312 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7313 		return -EINVAL;
7314 	}
7315 
7316 	meta->map_ptr = map_ptr;
7317 	kptr_off = reg->off + reg->var_off.value;
7318 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7319 	if (!kptr_field) {
7320 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7321 		return -EACCES;
7322 	}
7323 	if (kptr_field->type != BPF_KPTR_REF) {
7324 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7325 		return -EACCES;
7326 	}
7327 	meta->kptr_field = kptr_field;
7328 	return 0;
7329 }
7330 
7331 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7332  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7333  *
7334  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7335  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7336  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7337  *
7338  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7339  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7340  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7341  * mutate the view of the dynptr and also possibly destroy it. In the latter
7342  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7343  * memory that dynptr points to.
7344  *
7345  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7346  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7347  * readonly dynptr view yet, hence only the first case is tracked and checked.
7348  *
7349  * This is consistent with how C applies the const modifier to a struct object,
7350  * where the pointer itself inside bpf_dynptr becomes const but not what it
7351  * points to.
7352  *
7353  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7354  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7355  */
7356 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7357 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7358 {
7359 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7360 	int err;
7361 
7362 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7363 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7364 	 */
7365 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7366 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7367 		return -EFAULT;
7368 	}
7369 
7370 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7371 	 *		 constructing a mutable bpf_dynptr object.
7372 	 *
7373 	 *		 Currently, this is only possible with PTR_TO_STACK
7374 	 *		 pointing to a region of at least 16 bytes which doesn't
7375 	 *		 contain an existing bpf_dynptr.
7376 	 *
7377 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7378 	 *		 mutated or destroyed. However, the memory it points to
7379 	 *		 may be mutated.
7380 	 *
7381 	 *  None       - Points to a initialized dynptr that can be mutated and
7382 	 *		 destroyed, including mutation of the memory it points
7383 	 *		 to.
7384 	 */
7385 	if (arg_type & MEM_UNINIT) {
7386 		int i;
7387 
7388 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7389 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7390 			return -EINVAL;
7391 		}
7392 
7393 		/* we write BPF_DW bits (8 bytes) at a time */
7394 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7395 			err = check_mem_access(env, insn_idx, regno,
7396 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7397 			if (err)
7398 				return err;
7399 		}
7400 
7401 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7402 	} else /* MEM_RDONLY and None case from above */ {
7403 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7404 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7405 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7406 			return -EINVAL;
7407 		}
7408 
7409 		if (!is_dynptr_reg_valid_init(env, reg)) {
7410 			verbose(env,
7411 				"Expected an initialized dynptr as arg #%d\n",
7412 				regno);
7413 			return -EINVAL;
7414 		}
7415 
7416 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7417 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7418 			verbose(env,
7419 				"Expected a dynptr of type %s as arg #%d\n",
7420 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7421 			return -EINVAL;
7422 		}
7423 
7424 		err = mark_dynptr_read(env, reg);
7425 	}
7426 	return err;
7427 }
7428 
7429 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7430 {
7431 	struct bpf_func_state *state = func(env, reg);
7432 
7433 	return state->stack[spi].spilled_ptr.ref_obj_id;
7434 }
7435 
7436 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7437 {
7438 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7439 }
7440 
7441 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7442 {
7443 	return meta->kfunc_flags & KF_ITER_NEW;
7444 }
7445 
7446 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7447 {
7448 	return meta->kfunc_flags & KF_ITER_NEXT;
7449 }
7450 
7451 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7452 {
7453 	return meta->kfunc_flags & KF_ITER_DESTROY;
7454 }
7455 
7456 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7457 {
7458 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7459 	 * kfunc is iter state pointer
7460 	 */
7461 	return arg == 0 && is_iter_kfunc(meta);
7462 }
7463 
7464 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7465 			    struct bpf_kfunc_call_arg_meta *meta)
7466 {
7467 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7468 	const struct btf_type *t;
7469 	const struct btf_param *arg;
7470 	int spi, err, i, nr_slots;
7471 	u32 btf_id;
7472 
7473 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7474 	arg = &btf_params(meta->func_proto)[0];
7475 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7476 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7477 	nr_slots = t->size / BPF_REG_SIZE;
7478 
7479 	if (is_iter_new_kfunc(meta)) {
7480 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7481 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7482 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7483 				iter_type_str(meta->btf, btf_id), regno);
7484 			return -EINVAL;
7485 		}
7486 
7487 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7488 			err = check_mem_access(env, insn_idx, regno,
7489 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7490 			if (err)
7491 				return err;
7492 		}
7493 
7494 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7495 		if (err)
7496 			return err;
7497 	} else {
7498 		/* iter_next() or iter_destroy() expect initialized iter state*/
7499 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7500 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7501 				iter_type_str(meta->btf, btf_id), regno);
7502 			return -EINVAL;
7503 		}
7504 
7505 		spi = iter_get_spi(env, reg, nr_slots);
7506 		if (spi < 0)
7507 			return spi;
7508 
7509 		err = mark_iter_read(env, reg, spi, nr_slots);
7510 		if (err)
7511 			return err;
7512 
7513 		/* remember meta->iter info for process_iter_next_call() */
7514 		meta->iter.spi = spi;
7515 		meta->iter.frameno = reg->frameno;
7516 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7517 
7518 		if (is_iter_destroy_kfunc(meta)) {
7519 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7520 			if (err)
7521 				return err;
7522 		}
7523 	}
7524 
7525 	return 0;
7526 }
7527 
7528 /* process_iter_next_call() is called when verifier gets to iterator's next
7529  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7530  * to it as just "iter_next()" in comments below.
7531  *
7532  * BPF verifier relies on a crucial contract for any iter_next()
7533  * implementation: it should *eventually* return NULL, and once that happens
7534  * it should keep returning NULL. That is, once iterator exhausts elements to
7535  * iterate, it should never reset or spuriously return new elements.
7536  *
7537  * With the assumption of such contract, process_iter_next_call() simulates
7538  * a fork in the verifier state to validate loop logic correctness and safety
7539  * without having to simulate infinite amount of iterations.
7540  *
7541  * In current state, we first assume that iter_next() returned NULL and
7542  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7543  * conditions we should not form an infinite loop and should eventually reach
7544  * exit.
7545  *
7546  * Besides that, we also fork current state and enqueue it for later
7547  * verification. In a forked state we keep iterator state as ACTIVE
7548  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7549  * also bump iteration depth to prevent erroneous infinite loop detection
7550  * later on (see iter_active_depths_differ() comment for details). In this
7551  * state we assume that we'll eventually loop back to another iter_next()
7552  * calls (it could be in exactly same location or in some other instruction,
7553  * it doesn't matter, we don't make any unnecessary assumptions about this,
7554  * everything revolves around iterator state in a stack slot, not which
7555  * instruction is calling iter_next()). When that happens, we either will come
7556  * to iter_next() with equivalent state and can conclude that next iteration
7557  * will proceed in exactly the same way as we just verified, so it's safe to
7558  * assume that loop converges. If not, we'll go on another iteration
7559  * simulation with a different input state, until all possible starting states
7560  * are validated or we reach maximum number of instructions limit.
7561  *
7562  * This way, we will either exhaustively discover all possible input states
7563  * that iterator loop can start with and eventually will converge, or we'll
7564  * effectively regress into bounded loop simulation logic and either reach
7565  * maximum number of instructions if loop is not provably convergent, or there
7566  * is some statically known limit on number of iterations (e.g., if there is
7567  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7568  *
7569  * One very subtle but very important aspect is that we *always* simulate NULL
7570  * condition first (as the current state) before we simulate non-NULL case.
7571  * This has to do with intricacies of scalar precision tracking. By simulating
7572  * "exit condition" of iter_next() returning NULL first, we make sure all the
7573  * relevant precision marks *that will be set **after** we exit iterator loop*
7574  * are propagated backwards to common parent state of NULL and non-NULL
7575  * branches. Thanks to that, state equivalence checks done later in forked
7576  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7577  * precision marks are finalized and won't change. Because simulating another
7578  * ACTIVE iterator iteration won't change them (because given same input
7579  * states we'll end up with exactly same output states which we are currently
7580  * comparing; and verification after the loop already propagated back what
7581  * needs to be **additionally** tracked as precise). It's subtle, grok
7582  * precision tracking for more intuitive understanding.
7583  */
7584 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7585 				  struct bpf_kfunc_call_arg_meta *meta)
7586 {
7587 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7588 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7589 	struct bpf_reg_state *cur_iter, *queued_iter;
7590 	int iter_frameno = meta->iter.frameno;
7591 	int iter_spi = meta->iter.spi;
7592 
7593 	BTF_TYPE_EMIT(struct bpf_iter);
7594 
7595 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7596 
7597 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7598 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7599 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7600 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7601 		return -EFAULT;
7602 	}
7603 
7604 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7605 		/* branch out active iter state */
7606 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7607 		if (!queued_st)
7608 			return -ENOMEM;
7609 
7610 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7611 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7612 		queued_iter->iter.depth++;
7613 
7614 		queued_fr = queued_st->frame[queued_st->curframe];
7615 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7616 	}
7617 
7618 	/* switch to DRAINED state, but keep the depth unchanged */
7619 	/* mark current iter state as drained and assume returned NULL */
7620 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7621 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7622 
7623 	return 0;
7624 }
7625 
7626 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7627 {
7628 	return type == ARG_CONST_SIZE ||
7629 	       type == ARG_CONST_SIZE_OR_ZERO;
7630 }
7631 
7632 static bool arg_type_is_release(enum bpf_arg_type type)
7633 {
7634 	return type & OBJ_RELEASE;
7635 }
7636 
7637 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7638 {
7639 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7640 }
7641 
7642 static int int_ptr_type_to_size(enum bpf_arg_type type)
7643 {
7644 	if (type == ARG_PTR_TO_INT)
7645 		return sizeof(u32);
7646 	else if (type == ARG_PTR_TO_LONG)
7647 		return sizeof(u64);
7648 
7649 	return -EINVAL;
7650 }
7651 
7652 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7653 				 const struct bpf_call_arg_meta *meta,
7654 				 enum bpf_arg_type *arg_type)
7655 {
7656 	if (!meta->map_ptr) {
7657 		/* kernel subsystem misconfigured verifier */
7658 		verbose(env, "invalid map_ptr to access map->type\n");
7659 		return -EACCES;
7660 	}
7661 
7662 	switch (meta->map_ptr->map_type) {
7663 	case BPF_MAP_TYPE_SOCKMAP:
7664 	case BPF_MAP_TYPE_SOCKHASH:
7665 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7666 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7667 		} else {
7668 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7669 			return -EINVAL;
7670 		}
7671 		break;
7672 	case BPF_MAP_TYPE_BLOOM_FILTER:
7673 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7674 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7675 		break;
7676 	default:
7677 		break;
7678 	}
7679 	return 0;
7680 }
7681 
7682 struct bpf_reg_types {
7683 	const enum bpf_reg_type types[10];
7684 	u32 *btf_id;
7685 };
7686 
7687 static const struct bpf_reg_types sock_types = {
7688 	.types = {
7689 		PTR_TO_SOCK_COMMON,
7690 		PTR_TO_SOCKET,
7691 		PTR_TO_TCP_SOCK,
7692 		PTR_TO_XDP_SOCK,
7693 	},
7694 };
7695 
7696 #ifdef CONFIG_NET
7697 static const struct bpf_reg_types btf_id_sock_common_types = {
7698 	.types = {
7699 		PTR_TO_SOCK_COMMON,
7700 		PTR_TO_SOCKET,
7701 		PTR_TO_TCP_SOCK,
7702 		PTR_TO_XDP_SOCK,
7703 		PTR_TO_BTF_ID,
7704 		PTR_TO_BTF_ID | PTR_TRUSTED,
7705 	},
7706 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7707 };
7708 #endif
7709 
7710 static const struct bpf_reg_types mem_types = {
7711 	.types = {
7712 		PTR_TO_STACK,
7713 		PTR_TO_PACKET,
7714 		PTR_TO_PACKET_META,
7715 		PTR_TO_MAP_KEY,
7716 		PTR_TO_MAP_VALUE,
7717 		PTR_TO_MEM,
7718 		PTR_TO_MEM | MEM_RINGBUF,
7719 		PTR_TO_BUF,
7720 		PTR_TO_BTF_ID | PTR_TRUSTED,
7721 	},
7722 };
7723 
7724 static const struct bpf_reg_types int_ptr_types = {
7725 	.types = {
7726 		PTR_TO_STACK,
7727 		PTR_TO_PACKET,
7728 		PTR_TO_PACKET_META,
7729 		PTR_TO_MAP_KEY,
7730 		PTR_TO_MAP_VALUE,
7731 	},
7732 };
7733 
7734 static const struct bpf_reg_types spin_lock_types = {
7735 	.types = {
7736 		PTR_TO_MAP_VALUE,
7737 		PTR_TO_BTF_ID | MEM_ALLOC,
7738 	}
7739 };
7740 
7741 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7742 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7743 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7744 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7745 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7746 static const struct bpf_reg_types btf_ptr_types = {
7747 	.types = {
7748 		PTR_TO_BTF_ID,
7749 		PTR_TO_BTF_ID | PTR_TRUSTED,
7750 		PTR_TO_BTF_ID | MEM_RCU,
7751 	},
7752 };
7753 static const struct bpf_reg_types percpu_btf_ptr_types = {
7754 	.types = {
7755 		PTR_TO_BTF_ID | MEM_PERCPU,
7756 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7757 	}
7758 };
7759 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7760 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7761 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7762 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7763 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7764 static const struct bpf_reg_types dynptr_types = {
7765 	.types = {
7766 		PTR_TO_STACK,
7767 		CONST_PTR_TO_DYNPTR,
7768 	}
7769 };
7770 
7771 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7772 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7773 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7774 	[ARG_CONST_SIZE]		= &scalar_types,
7775 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7776 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7777 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7778 	[ARG_PTR_TO_CTX]		= &context_types,
7779 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7780 #ifdef CONFIG_NET
7781 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7782 #endif
7783 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7784 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7785 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7786 	[ARG_PTR_TO_MEM]		= &mem_types,
7787 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7788 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7789 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7790 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7791 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7792 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7793 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7794 	[ARG_PTR_TO_TIMER]		= &timer_types,
7795 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7796 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7797 };
7798 
7799 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7800 			  enum bpf_arg_type arg_type,
7801 			  const u32 *arg_btf_id,
7802 			  struct bpf_call_arg_meta *meta)
7803 {
7804 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7805 	enum bpf_reg_type expected, type = reg->type;
7806 	const struct bpf_reg_types *compatible;
7807 	int i, j;
7808 
7809 	compatible = compatible_reg_types[base_type(arg_type)];
7810 	if (!compatible) {
7811 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7812 		return -EFAULT;
7813 	}
7814 
7815 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7816 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7817 	 *
7818 	 * Same for MAYBE_NULL:
7819 	 *
7820 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7821 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7822 	 *
7823 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7824 	 *
7825 	 * Therefore we fold these flags depending on the arg_type before comparison.
7826 	 */
7827 	if (arg_type & MEM_RDONLY)
7828 		type &= ~MEM_RDONLY;
7829 	if (arg_type & PTR_MAYBE_NULL)
7830 		type &= ~PTR_MAYBE_NULL;
7831 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7832 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7833 
7834 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7835 		type &= ~MEM_ALLOC;
7836 
7837 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7838 		expected = compatible->types[i];
7839 		if (expected == NOT_INIT)
7840 			break;
7841 
7842 		if (type == expected)
7843 			goto found;
7844 	}
7845 
7846 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7847 	for (j = 0; j + 1 < i; j++)
7848 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7849 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7850 	return -EACCES;
7851 
7852 found:
7853 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7854 		return 0;
7855 
7856 	if (compatible == &mem_types) {
7857 		if (!(arg_type & MEM_RDONLY)) {
7858 			verbose(env,
7859 				"%s() may write into memory pointed by R%d type=%s\n",
7860 				func_id_name(meta->func_id),
7861 				regno, reg_type_str(env, reg->type));
7862 			return -EACCES;
7863 		}
7864 		return 0;
7865 	}
7866 
7867 	switch ((int)reg->type) {
7868 	case PTR_TO_BTF_ID:
7869 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7870 	case PTR_TO_BTF_ID | MEM_RCU:
7871 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7872 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7873 	{
7874 		/* For bpf_sk_release, it needs to match against first member
7875 		 * 'struct sock_common', hence make an exception for it. This
7876 		 * allows bpf_sk_release to work for multiple socket types.
7877 		 */
7878 		bool strict_type_match = arg_type_is_release(arg_type) &&
7879 					 meta->func_id != BPF_FUNC_sk_release;
7880 
7881 		if (type_may_be_null(reg->type) &&
7882 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7883 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7884 			return -EACCES;
7885 		}
7886 
7887 		if (!arg_btf_id) {
7888 			if (!compatible->btf_id) {
7889 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7890 				return -EFAULT;
7891 			}
7892 			arg_btf_id = compatible->btf_id;
7893 		}
7894 
7895 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7896 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7897 				return -EACCES;
7898 		} else {
7899 			if (arg_btf_id == BPF_PTR_POISON) {
7900 				verbose(env, "verifier internal error:");
7901 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7902 					regno);
7903 				return -EACCES;
7904 			}
7905 
7906 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7907 						  btf_vmlinux, *arg_btf_id,
7908 						  strict_type_match)) {
7909 				verbose(env, "R%d is of type %s but %s is expected\n",
7910 					regno, btf_type_name(reg->btf, reg->btf_id),
7911 					btf_type_name(btf_vmlinux, *arg_btf_id));
7912 				return -EACCES;
7913 			}
7914 		}
7915 		break;
7916 	}
7917 	case PTR_TO_BTF_ID | MEM_ALLOC:
7918 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7919 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7920 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7921 			return -EFAULT;
7922 		}
7923 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7924 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7925 				return -EACCES;
7926 		}
7927 		break;
7928 	case PTR_TO_BTF_ID | MEM_PERCPU:
7929 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7930 		/* Handled by helper specific checks */
7931 		break;
7932 	default:
7933 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7934 		return -EFAULT;
7935 	}
7936 	return 0;
7937 }
7938 
7939 static struct btf_field *
7940 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7941 {
7942 	struct btf_field *field;
7943 	struct btf_record *rec;
7944 
7945 	rec = reg_btf_record(reg);
7946 	if (!rec)
7947 		return NULL;
7948 
7949 	field = btf_record_find(rec, off, fields);
7950 	if (!field)
7951 		return NULL;
7952 
7953 	return field;
7954 }
7955 
7956 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7957 			   const struct bpf_reg_state *reg, int regno,
7958 			   enum bpf_arg_type arg_type)
7959 {
7960 	u32 type = reg->type;
7961 
7962 	/* When referenced register is passed to release function, its fixed
7963 	 * offset must be 0.
7964 	 *
7965 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7966 	 * meta->release_regno.
7967 	 */
7968 	if (arg_type_is_release(arg_type)) {
7969 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7970 		 * may not directly point to the object being released, but to
7971 		 * dynptr pointing to such object, which might be at some offset
7972 		 * on the stack. In that case, we simply to fallback to the
7973 		 * default handling.
7974 		 */
7975 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7976 			return 0;
7977 
7978 		/* Doing check_ptr_off_reg check for the offset will catch this
7979 		 * because fixed_off_ok is false, but checking here allows us
7980 		 * to give the user a better error message.
7981 		 */
7982 		if (reg->off) {
7983 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7984 				regno);
7985 			return -EINVAL;
7986 		}
7987 		return __check_ptr_off_reg(env, reg, regno, false);
7988 	}
7989 
7990 	switch (type) {
7991 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7992 	case PTR_TO_STACK:
7993 	case PTR_TO_PACKET:
7994 	case PTR_TO_PACKET_META:
7995 	case PTR_TO_MAP_KEY:
7996 	case PTR_TO_MAP_VALUE:
7997 	case PTR_TO_MEM:
7998 	case PTR_TO_MEM | MEM_RDONLY:
7999 	case PTR_TO_MEM | MEM_RINGBUF:
8000 	case PTR_TO_BUF:
8001 	case PTR_TO_BUF | MEM_RDONLY:
8002 	case SCALAR_VALUE:
8003 		return 0;
8004 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8005 	 * fixed offset.
8006 	 */
8007 	case PTR_TO_BTF_ID:
8008 	case PTR_TO_BTF_ID | MEM_ALLOC:
8009 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8010 	case PTR_TO_BTF_ID | MEM_RCU:
8011 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8012 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8013 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8014 		 * its fixed offset must be 0. In the other cases, fixed offset
8015 		 * can be non-zero. This was already checked above. So pass
8016 		 * fixed_off_ok as true to allow fixed offset for all other
8017 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8018 		 * still need to do checks instead of returning.
8019 		 */
8020 		return __check_ptr_off_reg(env, reg, regno, true);
8021 	default:
8022 		return __check_ptr_off_reg(env, reg, regno, false);
8023 	}
8024 }
8025 
8026 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8027 						const struct bpf_func_proto *fn,
8028 						struct bpf_reg_state *regs)
8029 {
8030 	struct bpf_reg_state *state = NULL;
8031 	int i;
8032 
8033 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8034 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8035 			if (state) {
8036 				verbose(env, "verifier internal error: multiple dynptr args\n");
8037 				return NULL;
8038 			}
8039 			state = &regs[BPF_REG_1 + i];
8040 		}
8041 
8042 	if (!state)
8043 		verbose(env, "verifier internal error: no dynptr arg found\n");
8044 
8045 	return state;
8046 }
8047 
8048 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8049 {
8050 	struct bpf_func_state *state = func(env, reg);
8051 	int spi;
8052 
8053 	if (reg->type == CONST_PTR_TO_DYNPTR)
8054 		return reg->id;
8055 	spi = dynptr_get_spi(env, reg);
8056 	if (spi < 0)
8057 		return spi;
8058 	return state->stack[spi].spilled_ptr.id;
8059 }
8060 
8061 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8062 {
8063 	struct bpf_func_state *state = func(env, reg);
8064 	int spi;
8065 
8066 	if (reg->type == CONST_PTR_TO_DYNPTR)
8067 		return reg->ref_obj_id;
8068 	spi = dynptr_get_spi(env, reg);
8069 	if (spi < 0)
8070 		return spi;
8071 	return state->stack[spi].spilled_ptr.ref_obj_id;
8072 }
8073 
8074 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8075 					    struct bpf_reg_state *reg)
8076 {
8077 	struct bpf_func_state *state = func(env, reg);
8078 	int spi;
8079 
8080 	if (reg->type == CONST_PTR_TO_DYNPTR)
8081 		return reg->dynptr.type;
8082 
8083 	spi = __get_spi(reg->off);
8084 	if (spi < 0) {
8085 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8086 		return BPF_DYNPTR_TYPE_INVALID;
8087 	}
8088 
8089 	return state->stack[spi].spilled_ptr.dynptr.type;
8090 }
8091 
8092 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8093 			  struct bpf_call_arg_meta *meta,
8094 			  const struct bpf_func_proto *fn,
8095 			  int insn_idx)
8096 {
8097 	u32 regno = BPF_REG_1 + arg;
8098 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8099 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8100 	enum bpf_reg_type type = reg->type;
8101 	u32 *arg_btf_id = NULL;
8102 	int err = 0;
8103 
8104 	if (arg_type == ARG_DONTCARE)
8105 		return 0;
8106 
8107 	err = check_reg_arg(env, regno, SRC_OP);
8108 	if (err)
8109 		return err;
8110 
8111 	if (arg_type == ARG_ANYTHING) {
8112 		if (is_pointer_value(env, regno)) {
8113 			verbose(env, "R%d leaks addr into helper function\n",
8114 				regno);
8115 			return -EACCES;
8116 		}
8117 		return 0;
8118 	}
8119 
8120 	if (type_is_pkt_pointer(type) &&
8121 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8122 		verbose(env, "helper access to the packet is not allowed\n");
8123 		return -EACCES;
8124 	}
8125 
8126 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8127 		err = resolve_map_arg_type(env, meta, &arg_type);
8128 		if (err)
8129 			return err;
8130 	}
8131 
8132 	if (register_is_null(reg) && type_may_be_null(arg_type))
8133 		/* A NULL register has a SCALAR_VALUE type, so skip
8134 		 * type checking.
8135 		 */
8136 		goto skip_type_check;
8137 
8138 	/* arg_btf_id and arg_size are in a union. */
8139 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8140 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8141 		arg_btf_id = fn->arg_btf_id[arg];
8142 
8143 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8144 	if (err)
8145 		return err;
8146 
8147 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8148 	if (err)
8149 		return err;
8150 
8151 skip_type_check:
8152 	if (arg_type_is_release(arg_type)) {
8153 		if (arg_type_is_dynptr(arg_type)) {
8154 			struct bpf_func_state *state = func(env, reg);
8155 			int spi;
8156 
8157 			/* Only dynptr created on stack can be released, thus
8158 			 * the get_spi and stack state checks for spilled_ptr
8159 			 * should only be done before process_dynptr_func for
8160 			 * PTR_TO_STACK.
8161 			 */
8162 			if (reg->type == PTR_TO_STACK) {
8163 				spi = dynptr_get_spi(env, reg);
8164 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8165 					verbose(env, "arg %d is an unacquired reference\n", regno);
8166 					return -EINVAL;
8167 				}
8168 			} else {
8169 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8170 				return -EINVAL;
8171 			}
8172 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8173 			verbose(env, "R%d must be referenced when passed to release function\n",
8174 				regno);
8175 			return -EINVAL;
8176 		}
8177 		if (meta->release_regno) {
8178 			verbose(env, "verifier internal error: more than one release argument\n");
8179 			return -EFAULT;
8180 		}
8181 		meta->release_regno = regno;
8182 	}
8183 
8184 	if (reg->ref_obj_id) {
8185 		if (meta->ref_obj_id) {
8186 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8187 				regno, reg->ref_obj_id,
8188 				meta->ref_obj_id);
8189 			return -EFAULT;
8190 		}
8191 		meta->ref_obj_id = reg->ref_obj_id;
8192 	}
8193 
8194 	switch (base_type(arg_type)) {
8195 	case ARG_CONST_MAP_PTR:
8196 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8197 		if (meta->map_ptr) {
8198 			/* Use map_uid (which is unique id of inner map) to reject:
8199 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8200 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8201 			 * if (inner_map1 && inner_map2) {
8202 			 *     timer = bpf_map_lookup_elem(inner_map1);
8203 			 *     if (timer)
8204 			 *         // mismatch would have been allowed
8205 			 *         bpf_timer_init(timer, inner_map2);
8206 			 * }
8207 			 *
8208 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8209 			 */
8210 			if (meta->map_ptr != reg->map_ptr ||
8211 			    meta->map_uid != reg->map_uid) {
8212 				verbose(env,
8213 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8214 					meta->map_uid, reg->map_uid);
8215 				return -EINVAL;
8216 			}
8217 		}
8218 		meta->map_ptr = reg->map_ptr;
8219 		meta->map_uid = reg->map_uid;
8220 		break;
8221 	case ARG_PTR_TO_MAP_KEY:
8222 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8223 		 * check that [key, key + map->key_size) are within
8224 		 * stack limits and initialized
8225 		 */
8226 		if (!meta->map_ptr) {
8227 			/* in function declaration map_ptr must come before
8228 			 * map_key, so that it's verified and known before
8229 			 * we have to check map_key here. Otherwise it means
8230 			 * that kernel subsystem misconfigured verifier
8231 			 */
8232 			verbose(env, "invalid map_ptr to access map->key\n");
8233 			return -EACCES;
8234 		}
8235 		err = check_helper_mem_access(env, regno,
8236 					      meta->map_ptr->key_size, false,
8237 					      NULL);
8238 		break;
8239 	case ARG_PTR_TO_MAP_VALUE:
8240 		if (type_may_be_null(arg_type) && register_is_null(reg))
8241 			return 0;
8242 
8243 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8244 		 * check [value, value + map->value_size) validity
8245 		 */
8246 		if (!meta->map_ptr) {
8247 			/* kernel subsystem misconfigured verifier */
8248 			verbose(env, "invalid map_ptr to access map->value\n");
8249 			return -EACCES;
8250 		}
8251 		meta->raw_mode = arg_type & MEM_UNINIT;
8252 		err = check_helper_mem_access(env, regno,
8253 					      meta->map_ptr->value_size, false,
8254 					      meta);
8255 		break;
8256 	case ARG_PTR_TO_PERCPU_BTF_ID:
8257 		if (!reg->btf_id) {
8258 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8259 			return -EACCES;
8260 		}
8261 		meta->ret_btf = reg->btf;
8262 		meta->ret_btf_id = reg->btf_id;
8263 		break;
8264 	case ARG_PTR_TO_SPIN_LOCK:
8265 		if (in_rbtree_lock_required_cb(env)) {
8266 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8267 			return -EACCES;
8268 		}
8269 		if (meta->func_id == BPF_FUNC_spin_lock) {
8270 			err = process_spin_lock(env, regno, true);
8271 			if (err)
8272 				return err;
8273 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8274 			err = process_spin_lock(env, regno, false);
8275 			if (err)
8276 				return err;
8277 		} else {
8278 			verbose(env, "verifier internal error\n");
8279 			return -EFAULT;
8280 		}
8281 		break;
8282 	case ARG_PTR_TO_TIMER:
8283 		err = process_timer_func(env, regno, meta);
8284 		if (err)
8285 			return err;
8286 		break;
8287 	case ARG_PTR_TO_FUNC:
8288 		meta->subprogno = reg->subprogno;
8289 		break;
8290 	case ARG_PTR_TO_MEM:
8291 		/* The access to this pointer is only checked when we hit the
8292 		 * next is_mem_size argument below.
8293 		 */
8294 		meta->raw_mode = arg_type & MEM_UNINIT;
8295 		if (arg_type & MEM_FIXED_SIZE) {
8296 			err = check_helper_mem_access(env, regno,
8297 						      fn->arg_size[arg], false,
8298 						      meta);
8299 		}
8300 		break;
8301 	case ARG_CONST_SIZE:
8302 		err = check_mem_size_reg(env, reg, regno, false, meta);
8303 		break;
8304 	case ARG_CONST_SIZE_OR_ZERO:
8305 		err = check_mem_size_reg(env, reg, regno, true, meta);
8306 		break;
8307 	case ARG_PTR_TO_DYNPTR:
8308 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8309 		if (err)
8310 			return err;
8311 		break;
8312 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8313 		if (!tnum_is_const(reg->var_off)) {
8314 			verbose(env, "R%d is not a known constant'\n",
8315 				regno);
8316 			return -EACCES;
8317 		}
8318 		meta->mem_size = reg->var_off.value;
8319 		err = mark_chain_precision(env, regno);
8320 		if (err)
8321 			return err;
8322 		break;
8323 	case ARG_PTR_TO_INT:
8324 	case ARG_PTR_TO_LONG:
8325 	{
8326 		int size = int_ptr_type_to_size(arg_type);
8327 
8328 		err = check_helper_mem_access(env, regno, size, false, meta);
8329 		if (err)
8330 			return err;
8331 		err = check_ptr_alignment(env, reg, 0, size, true);
8332 		break;
8333 	}
8334 	case ARG_PTR_TO_CONST_STR:
8335 	{
8336 		struct bpf_map *map = reg->map_ptr;
8337 		int map_off;
8338 		u64 map_addr;
8339 		char *str_ptr;
8340 
8341 		if (!bpf_map_is_rdonly(map)) {
8342 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8343 			return -EACCES;
8344 		}
8345 
8346 		if (!tnum_is_const(reg->var_off)) {
8347 			verbose(env, "R%d is not a constant address'\n", regno);
8348 			return -EACCES;
8349 		}
8350 
8351 		if (!map->ops->map_direct_value_addr) {
8352 			verbose(env, "no direct value access support for this map type\n");
8353 			return -EACCES;
8354 		}
8355 
8356 		err = check_map_access(env, regno, reg->off,
8357 				       map->value_size - reg->off, false,
8358 				       ACCESS_HELPER);
8359 		if (err)
8360 			return err;
8361 
8362 		map_off = reg->off + reg->var_off.value;
8363 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8364 		if (err) {
8365 			verbose(env, "direct value access on string failed\n");
8366 			return err;
8367 		}
8368 
8369 		str_ptr = (char *)(long)(map_addr);
8370 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8371 			verbose(env, "string is not zero-terminated\n");
8372 			return -EINVAL;
8373 		}
8374 		break;
8375 	}
8376 	case ARG_PTR_TO_KPTR:
8377 		err = process_kptr_func(env, regno, meta);
8378 		if (err)
8379 			return err;
8380 		break;
8381 	}
8382 
8383 	return err;
8384 }
8385 
8386 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8387 {
8388 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8389 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8390 
8391 	if (func_id != BPF_FUNC_map_update_elem)
8392 		return false;
8393 
8394 	/* It's not possible to get access to a locked struct sock in these
8395 	 * contexts, so updating is safe.
8396 	 */
8397 	switch (type) {
8398 	case BPF_PROG_TYPE_TRACING:
8399 		if (eatype == BPF_TRACE_ITER)
8400 			return true;
8401 		break;
8402 	case BPF_PROG_TYPE_SOCKET_FILTER:
8403 	case BPF_PROG_TYPE_SCHED_CLS:
8404 	case BPF_PROG_TYPE_SCHED_ACT:
8405 	case BPF_PROG_TYPE_XDP:
8406 	case BPF_PROG_TYPE_SK_REUSEPORT:
8407 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8408 	case BPF_PROG_TYPE_SK_LOOKUP:
8409 		return true;
8410 	default:
8411 		break;
8412 	}
8413 
8414 	verbose(env, "cannot update sockmap in this context\n");
8415 	return false;
8416 }
8417 
8418 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8419 {
8420 	return env->prog->jit_requested &&
8421 	       bpf_jit_supports_subprog_tailcalls();
8422 }
8423 
8424 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8425 					struct bpf_map *map, int func_id)
8426 {
8427 	if (!map)
8428 		return 0;
8429 
8430 	/* We need a two way check, first is from map perspective ... */
8431 	switch (map->map_type) {
8432 	case BPF_MAP_TYPE_PROG_ARRAY:
8433 		if (func_id != BPF_FUNC_tail_call)
8434 			goto error;
8435 		break;
8436 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8437 		if (func_id != BPF_FUNC_perf_event_read &&
8438 		    func_id != BPF_FUNC_perf_event_output &&
8439 		    func_id != BPF_FUNC_skb_output &&
8440 		    func_id != BPF_FUNC_perf_event_read_value &&
8441 		    func_id != BPF_FUNC_xdp_output)
8442 			goto error;
8443 		break;
8444 	case BPF_MAP_TYPE_RINGBUF:
8445 		if (func_id != BPF_FUNC_ringbuf_output &&
8446 		    func_id != BPF_FUNC_ringbuf_reserve &&
8447 		    func_id != BPF_FUNC_ringbuf_query &&
8448 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8449 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8450 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8451 			goto error;
8452 		break;
8453 	case BPF_MAP_TYPE_USER_RINGBUF:
8454 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8455 			goto error;
8456 		break;
8457 	case BPF_MAP_TYPE_STACK_TRACE:
8458 		if (func_id != BPF_FUNC_get_stackid)
8459 			goto error;
8460 		break;
8461 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8462 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8463 		    func_id != BPF_FUNC_current_task_under_cgroup)
8464 			goto error;
8465 		break;
8466 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8467 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8468 		if (func_id != BPF_FUNC_get_local_storage)
8469 			goto error;
8470 		break;
8471 	case BPF_MAP_TYPE_DEVMAP:
8472 	case BPF_MAP_TYPE_DEVMAP_HASH:
8473 		if (func_id != BPF_FUNC_redirect_map &&
8474 		    func_id != BPF_FUNC_map_lookup_elem)
8475 			goto error;
8476 		break;
8477 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8478 	 * appear.
8479 	 */
8480 	case BPF_MAP_TYPE_CPUMAP:
8481 		if (func_id != BPF_FUNC_redirect_map)
8482 			goto error;
8483 		break;
8484 	case BPF_MAP_TYPE_XSKMAP:
8485 		if (func_id != BPF_FUNC_redirect_map &&
8486 		    func_id != BPF_FUNC_map_lookup_elem)
8487 			goto error;
8488 		break;
8489 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8490 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8491 		if (func_id != BPF_FUNC_map_lookup_elem)
8492 			goto error;
8493 		break;
8494 	case BPF_MAP_TYPE_SOCKMAP:
8495 		if (func_id != BPF_FUNC_sk_redirect_map &&
8496 		    func_id != BPF_FUNC_sock_map_update &&
8497 		    func_id != BPF_FUNC_map_delete_elem &&
8498 		    func_id != BPF_FUNC_msg_redirect_map &&
8499 		    func_id != BPF_FUNC_sk_select_reuseport &&
8500 		    func_id != BPF_FUNC_map_lookup_elem &&
8501 		    !may_update_sockmap(env, func_id))
8502 			goto error;
8503 		break;
8504 	case BPF_MAP_TYPE_SOCKHASH:
8505 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8506 		    func_id != BPF_FUNC_sock_hash_update &&
8507 		    func_id != BPF_FUNC_map_delete_elem &&
8508 		    func_id != BPF_FUNC_msg_redirect_hash &&
8509 		    func_id != BPF_FUNC_sk_select_reuseport &&
8510 		    func_id != BPF_FUNC_map_lookup_elem &&
8511 		    !may_update_sockmap(env, func_id))
8512 			goto error;
8513 		break;
8514 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8515 		if (func_id != BPF_FUNC_sk_select_reuseport)
8516 			goto error;
8517 		break;
8518 	case BPF_MAP_TYPE_QUEUE:
8519 	case BPF_MAP_TYPE_STACK:
8520 		if (func_id != BPF_FUNC_map_peek_elem &&
8521 		    func_id != BPF_FUNC_map_pop_elem &&
8522 		    func_id != BPF_FUNC_map_push_elem)
8523 			goto error;
8524 		break;
8525 	case BPF_MAP_TYPE_SK_STORAGE:
8526 		if (func_id != BPF_FUNC_sk_storage_get &&
8527 		    func_id != BPF_FUNC_sk_storage_delete &&
8528 		    func_id != BPF_FUNC_kptr_xchg)
8529 			goto error;
8530 		break;
8531 	case BPF_MAP_TYPE_INODE_STORAGE:
8532 		if (func_id != BPF_FUNC_inode_storage_get &&
8533 		    func_id != BPF_FUNC_inode_storage_delete &&
8534 		    func_id != BPF_FUNC_kptr_xchg)
8535 			goto error;
8536 		break;
8537 	case BPF_MAP_TYPE_TASK_STORAGE:
8538 		if (func_id != BPF_FUNC_task_storage_get &&
8539 		    func_id != BPF_FUNC_task_storage_delete &&
8540 		    func_id != BPF_FUNC_kptr_xchg)
8541 			goto error;
8542 		break;
8543 	case BPF_MAP_TYPE_CGRP_STORAGE:
8544 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8545 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8546 		    func_id != BPF_FUNC_kptr_xchg)
8547 			goto error;
8548 		break;
8549 	case BPF_MAP_TYPE_BLOOM_FILTER:
8550 		if (func_id != BPF_FUNC_map_peek_elem &&
8551 		    func_id != BPF_FUNC_map_push_elem)
8552 			goto error;
8553 		break;
8554 	default:
8555 		break;
8556 	}
8557 
8558 	/* ... and second from the function itself. */
8559 	switch (func_id) {
8560 	case BPF_FUNC_tail_call:
8561 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8562 			goto error;
8563 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8564 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8565 			return -EINVAL;
8566 		}
8567 		break;
8568 	case BPF_FUNC_perf_event_read:
8569 	case BPF_FUNC_perf_event_output:
8570 	case BPF_FUNC_perf_event_read_value:
8571 	case BPF_FUNC_skb_output:
8572 	case BPF_FUNC_xdp_output:
8573 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8574 			goto error;
8575 		break;
8576 	case BPF_FUNC_ringbuf_output:
8577 	case BPF_FUNC_ringbuf_reserve:
8578 	case BPF_FUNC_ringbuf_query:
8579 	case BPF_FUNC_ringbuf_reserve_dynptr:
8580 	case BPF_FUNC_ringbuf_submit_dynptr:
8581 	case BPF_FUNC_ringbuf_discard_dynptr:
8582 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8583 			goto error;
8584 		break;
8585 	case BPF_FUNC_user_ringbuf_drain:
8586 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8587 			goto error;
8588 		break;
8589 	case BPF_FUNC_get_stackid:
8590 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8591 			goto error;
8592 		break;
8593 	case BPF_FUNC_current_task_under_cgroup:
8594 	case BPF_FUNC_skb_under_cgroup:
8595 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8596 			goto error;
8597 		break;
8598 	case BPF_FUNC_redirect_map:
8599 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8600 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8601 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8602 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8603 			goto error;
8604 		break;
8605 	case BPF_FUNC_sk_redirect_map:
8606 	case BPF_FUNC_msg_redirect_map:
8607 	case BPF_FUNC_sock_map_update:
8608 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8609 			goto error;
8610 		break;
8611 	case BPF_FUNC_sk_redirect_hash:
8612 	case BPF_FUNC_msg_redirect_hash:
8613 	case BPF_FUNC_sock_hash_update:
8614 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8615 			goto error;
8616 		break;
8617 	case BPF_FUNC_get_local_storage:
8618 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8619 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8620 			goto error;
8621 		break;
8622 	case BPF_FUNC_sk_select_reuseport:
8623 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8624 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8625 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8626 			goto error;
8627 		break;
8628 	case BPF_FUNC_map_pop_elem:
8629 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8630 		    map->map_type != BPF_MAP_TYPE_STACK)
8631 			goto error;
8632 		break;
8633 	case BPF_FUNC_map_peek_elem:
8634 	case BPF_FUNC_map_push_elem:
8635 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8636 		    map->map_type != BPF_MAP_TYPE_STACK &&
8637 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8638 			goto error;
8639 		break;
8640 	case BPF_FUNC_map_lookup_percpu_elem:
8641 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8642 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8643 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8644 			goto error;
8645 		break;
8646 	case BPF_FUNC_sk_storage_get:
8647 	case BPF_FUNC_sk_storage_delete:
8648 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8649 			goto error;
8650 		break;
8651 	case BPF_FUNC_inode_storage_get:
8652 	case BPF_FUNC_inode_storage_delete:
8653 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8654 			goto error;
8655 		break;
8656 	case BPF_FUNC_task_storage_get:
8657 	case BPF_FUNC_task_storage_delete:
8658 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8659 			goto error;
8660 		break;
8661 	case BPF_FUNC_cgrp_storage_get:
8662 	case BPF_FUNC_cgrp_storage_delete:
8663 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8664 			goto error;
8665 		break;
8666 	default:
8667 		break;
8668 	}
8669 
8670 	return 0;
8671 error:
8672 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8673 		map->map_type, func_id_name(func_id), func_id);
8674 	return -EINVAL;
8675 }
8676 
8677 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8678 {
8679 	int count = 0;
8680 
8681 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8682 		count++;
8683 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8684 		count++;
8685 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8686 		count++;
8687 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8688 		count++;
8689 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8690 		count++;
8691 
8692 	/* We only support one arg being in raw mode at the moment,
8693 	 * which is sufficient for the helper functions we have
8694 	 * right now.
8695 	 */
8696 	return count <= 1;
8697 }
8698 
8699 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8700 {
8701 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8702 	bool has_size = fn->arg_size[arg] != 0;
8703 	bool is_next_size = false;
8704 
8705 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8706 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8707 
8708 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8709 		return is_next_size;
8710 
8711 	return has_size == is_next_size || is_next_size == is_fixed;
8712 }
8713 
8714 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8715 {
8716 	/* bpf_xxx(..., buf, len) call will access 'len'
8717 	 * bytes from memory 'buf'. Both arg types need
8718 	 * to be paired, so make sure there's no buggy
8719 	 * helper function specification.
8720 	 */
8721 	if (arg_type_is_mem_size(fn->arg1_type) ||
8722 	    check_args_pair_invalid(fn, 0) ||
8723 	    check_args_pair_invalid(fn, 1) ||
8724 	    check_args_pair_invalid(fn, 2) ||
8725 	    check_args_pair_invalid(fn, 3) ||
8726 	    check_args_pair_invalid(fn, 4))
8727 		return false;
8728 
8729 	return true;
8730 }
8731 
8732 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8733 {
8734 	int i;
8735 
8736 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8737 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8738 			return !!fn->arg_btf_id[i];
8739 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8740 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8741 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8742 		    /* arg_btf_id and arg_size are in a union. */
8743 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8744 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8745 			return false;
8746 	}
8747 
8748 	return true;
8749 }
8750 
8751 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8752 {
8753 	return check_raw_mode_ok(fn) &&
8754 	       check_arg_pair_ok(fn) &&
8755 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8756 }
8757 
8758 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8759  * are now invalid, so turn them into unknown SCALAR_VALUE.
8760  *
8761  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8762  * since these slices point to packet data.
8763  */
8764 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8765 {
8766 	struct bpf_func_state *state;
8767 	struct bpf_reg_state *reg;
8768 
8769 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8770 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8771 			mark_reg_invalid(env, reg);
8772 	}));
8773 }
8774 
8775 enum {
8776 	AT_PKT_END = -1,
8777 	BEYOND_PKT_END = -2,
8778 };
8779 
8780 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8781 {
8782 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8783 	struct bpf_reg_state *reg = &state->regs[regn];
8784 
8785 	if (reg->type != PTR_TO_PACKET)
8786 		/* PTR_TO_PACKET_META is not supported yet */
8787 		return;
8788 
8789 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8790 	 * How far beyond pkt_end it goes is unknown.
8791 	 * if (!range_open) it's the case of pkt >= pkt_end
8792 	 * if (range_open) it's the case of pkt > pkt_end
8793 	 * hence this pointer is at least 1 byte bigger than pkt_end
8794 	 */
8795 	if (range_open)
8796 		reg->range = BEYOND_PKT_END;
8797 	else
8798 		reg->range = AT_PKT_END;
8799 }
8800 
8801 /* The pointer with the specified id has released its reference to kernel
8802  * resources. Identify all copies of the same pointer and clear the reference.
8803  */
8804 static int release_reference(struct bpf_verifier_env *env,
8805 			     int ref_obj_id)
8806 {
8807 	struct bpf_func_state *state;
8808 	struct bpf_reg_state *reg;
8809 	int err;
8810 
8811 	err = release_reference_state(cur_func(env), ref_obj_id);
8812 	if (err)
8813 		return err;
8814 
8815 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8816 		if (reg->ref_obj_id == ref_obj_id)
8817 			mark_reg_invalid(env, reg);
8818 	}));
8819 
8820 	return 0;
8821 }
8822 
8823 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8824 {
8825 	struct bpf_func_state *unused;
8826 	struct bpf_reg_state *reg;
8827 
8828 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8829 		if (type_is_non_owning_ref(reg->type))
8830 			mark_reg_invalid(env, reg);
8831 	}));
8832 }
8833 
8834 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8835 				    struct bpf_reg_state *regs)
8836 {
8837 	int i;
8838 
8839 	/* after the call registers r0 - r5 were scratched */
8840 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8841 		mark_reg_not_init(env, regs, caller_saved[i]);
8842 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8843 	}
8844 }
8845 
8846 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8847 				   struct bpf_func_state *caller,
8848 				   struct bpf_func_state *callee,
8849 				   int insn_idx);
8850 
8851 static int set_callee_state(struct bpf_verifier_env *env,
8852 			    struct bpf_func_state *caller,
8853 			    struct bpf_func_state *callee, int insn_idx);
8854 
8855 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8856 			     int *insn_idx, int subprog,
8857 			     set_callee_state_fn set_callee_state_cb)
8858 {
8859 	struct bpf_verifier_state *state = env->cur_state;
8860 	struct bpf_func_state *caller, *callee;
8861 	int err;
8862 
8863 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8864 		verbose(env, "the call stack of %d frames is too deep\n",
8865 			state->curframe + 2);
8866 		return -E2BIG;
8867 	}
8868 
8869 	caller = state->frame[state->curframe];
8870 	if (state->frame[state->curframe + 1]) {
8871 		verbose(env, "verifier bug. Frame %d already allocated\n",
8872 			state->curframe + 1);
8873 		return -EFAULT;
8874 	}
8875 
8876 	err = btf_check_subprog_call(env, subprog, caller->regs);
8877 	if (err == -EFAULT)
8878 		return err;
8879 	if (subprog_is_global(env, subprog)) {
8880 		if (err) {
8881 			verbose(env, "Caller passes invalid args into func#%d\n",
8882 				subprog);
8883 			return err;
8884 		} else {
8885 			if (env->log.level & BPF_LOG_LEVEL)
8886 				verbose(env,
8887 					"Func#%d is global and valid. Skipping.\n",
8888 					subprog);
8889 			clear_caller_saved_regs(env, caller->regs);
8890 
8891 			/* All global functions return a 64-bit SCALAR_VALUE */
8892 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8893 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8894 
8895 			/* continue with next insn after call */
8896 			return 0;
8897 		}
8898 	}
8899 
8900 	/* set_callee_state is used for direct subprog calls, but we are
8901 	 * interested in validating only BPF helpers that can call subprogs as
8902 	 * callbacks
8903 	 */
8904 	if (set_callee_state_cb != set_callee_state) {
8905 		if (bpf_pseudo_kfunc_call(insn) &&
8906 		    !is_callback_calling_kfunc(insn->imm)) {
8907 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8908 				func_id_name(insn->imm), insn->imm);
8909 			return -EFAULT;
8910 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8911 			   !is_callback_calling_function(insn->imm)) { /* helper */
8912 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8913 				func_id_name(insn->imm), insn->imm);
8914 			return -EFAULT;
8915 		}
8916 	}
8917 
8918 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8919 	    insn->src_reg == 0 &&
8920 	    insn->imm == BPF_FUNC_timer_set_callback) {
8921 		struct bpf_verifier_state *async_cb;
8922 
8923 		/* there is no real recursion here. timer callbacks are async */
8924 		env->subprog_info[subprog].is_async_cb = true;
8925 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8926 					 *insn_idx, subprog);
8927 		if (!async_cb)
8928 			return -EFAULT;
8929 		callee = async_cb->frame[0];
8930 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8931 
8932 		/* Convert bpf_timer_set_callback() args into timer callback args */
8933 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8934 		if (err)
8935 			return err;
8936 
8937 		clear_caller_saved_regs(env, caller->regs);
8938 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8939 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8940 		/* continue with next insn after call */
8941 		return 0;
8942 	}
8943 
8944 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8945 	if (!callee)
8946 		return -ENOMEM;
8947 	state->frame[state->curframe + 1] = callee;
8948 
8949 	/* callee cannot access r0, r6 - r9 for reading and has to write
8950 	 * into its own stack before reading from it.
8951 	 * callee can read/write into caller's stack
8952 	 */
8953 	init_func_state(env, callee,
8954 			/* remember the callsite, it will be used by bpf_exit */
8955 			*insn_idx /* callsite */,
8956 			state->curframe + 1 /* frameno within this callchain */,
8957 			subprog /* subprog number within this prog */);
8958 
8959 	/* Transfer references to the callee */
8960 	err = copy_reference_state(callee, caller);
8961 	if (err)
8962 		goto err_out;
8963 
8964 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8965 	if (err)
8966 		goto err_out;
8967 
8968 	clear_caller_saved_regs(env, caller->regs);
8969 
8970 	/* only increment it after check_reg_arg() finished */
8971 	state->curframe++;
8972 
8973 	/* and go analyze first insn of the callee */
8974 	*insn_idx = env->subprog_info[subprog].start - 1;
8975 
8976 	if (env->log.level & BPF_LOG_LEVEL) {
8977 		verbose(env, "caller:\n");
8978 		print_verifier_state(env, caller, true);
8979 		verbose(env, "callee:\n");
8980 		print_verifier_state(env, callee, true);
8981 	}
8982 	return 0;
8983 
8984 err_out:
8985 	free_func_state(callee);
8986 	state->frame[state->curframe + 1] = NULL;
8987 	return err;
8988 }
8989 
8990 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8991 				   struct bpf_func_state *caller,
8992 				   struct bpf_func_state *callee)
8993 {
8994 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8995 	 *      void *callback_ctx, u64 flags);
8996 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8997 	 *      void *callback_ctx);
8998 	 */
8999 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9000 
9001 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9002 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9003 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9004 
9005 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9006 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9007 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9008 
9009 	/* pointer to stack or null */
9010 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9011 
9012 	/* unused */
9013 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9014 	return 0;
9015 }
9016 
9017 static int set_callee_state(struct bpf_verifier_env *env,
9018 			    struct bpf_func_state *caller,
9019 			    struct bpf_func_state *callee, int insn_idx)
9020 {
9021 	int i;
9022 
9023 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9024 	 * pointers, which connects us up to the liveness chain
9025 	 */
9026 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9027 		callee->regs[i] = caller->regs[i];
9028 	return 0;
9029 }
9030 
9031 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9032 			   int *insn_idx)
9033 {
9034 	int subprog, target_insn;
9035 
9036 	target_insn = *insn_idx + insn->imm + 1;
9037 	subprog = find_subprog(env, target_insn);
9038 	if (subprog < 0) {
9039 		verbose(env, "verifier bug. No program starts at insn %d\n",
9040 			target_insn);
9041 		return -EFAULT;
9042 	}
9043 
9044 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9045 }
9046 
9047 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9048 				       struct bpf_func_state *caller,
9049 				       struct bpf_func_state *callee,
9050 				       int insn_idx)
9051 {
9052 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9053 	struct bpf_map *map;
9054 	int err;
9055 
9056 	if (bpf_map_ptr_poisoned(insn_aux)) {
9057 		verbose(env, "tail_call abusing map_ptr\n");
9058 		return -EINVAL;
9059 	}
9060 
9061 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9062 	if (!map->ops->map_set_for_each_callback_args ||
9063 	    !map->ops->map_for_each_callback) {
9064 		verbose(env, "callback function not allowed for map\n");
9065 		return -ENOTSUPP;
9066 	}
9067 
9068 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9069 	if (err)
9070 		return err;
9071 
9072 	callee->in_callback_fn = true;
9073 	callee->callback_ret_range = tnum_range(0, 1);
9074 	return 0;
9075 }
9076 
9077 static int set_loop_callback_state(struct bpf_verifier_env *env,
9078 				   struct bpf_func_state *caller,
9079 				   struct bpf_func_state *callee,
9080 				   int insn_idx)
9081 {
9082 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9083 	 *	    u64 flags);
9084 	 * callback_fn(u32 index, void *callback_ctx);
9085 	 */
9086 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9087 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9088 
9089 	/* unused */
9090 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9091 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9092 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9093 
9094 	callee->in_callback_fn = true;
9095 	callee->callback_ret_range = tnum_range(0, 1);
9096 	return 0;
9097 }
9098 
9099 static int set_timer_callback_state(struct bpf_verifier_env *env,
9100 				    struct bpf_func_state *caller,
9101 				    struct bpf_func_state *callee,
9102 				    int insn_idx)
9103 {
9104 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9105 
9106 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9107 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9108 	 */
9109 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9110 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9111 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9112 
9113 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9114 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9115 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9116 
9117 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9118 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9119 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9120 
9121 	/* unused */
9122 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9123 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9124 	callee->in_async_callback_fn = true;
9125 	callee->callback_ret_range = tnum_range(0, 1);
9126 	return 0;
9127 }
9128 
9129 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9130 				       struct bpf_func_state *caller,
9131 				       struct bpf_func_state *callee,
9132 				       int insn_idx)
9133 {
9134 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9135 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9136 	 * (callback_fn)(struct task_struct *task,
9137 	 *               struct vm_area_struct *vma, void *callback_ctx);
9138 	 */
9139 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9140 
9141 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9142 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9143 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9144 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9145 
9146 	/* pointer to stack or null */
9147 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9148 
9149 	/* unused */
9150 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9151 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9152 	callee->in_callback_fn = true;
9153 	callee->callback_ret_range = tnum_range(0, 1);
9154 	return 0;
9155 }
9156 
9157 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9158 					   struct bpf_func_state *caller,
9159 					   struct bpf_func_state *callee,
9160 					   int insn_idx)
9161 {
9162 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9163 	 *			  callback_ctx, u64 flags);
9164 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9165 	 */
9166 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9167 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9168 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9169 
9170 	/* unused */
9171 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9172 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9173 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9174 
9175 	callee->in_callback_fn = true;
9176 	callee->callback_ret_range = tnum_range(0, 1);
9177 	return 0;
9178 }
9179 
9180 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9181 					 struct bpf_func_state *caller,
9182 					 struct bpf_func_state *callee,
9183 					 int insn_idx)
9184 {
9185 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9186 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9187 	 *
9188 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9189 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9190 	 * by this point, so look at 'root'
9191 	 */
9192 	struct btf_field *field;
9193 
9194 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9195 				      BPF_RB_ROOT);
9196 	if (!field || !field->graph_root.value_btf_id)
9197 		return -EFAULT;
9198 
9199 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9200 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9201 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9202 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9203 
9204 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9205 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9206 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9207 	callee->in_callback_fn = true;
9208 	callee->callback_ret_range = tnum_range(0, 1);
9209 	return 0;
9210 }
9211 
9212 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9213 
9214 /* Are we currently verifying the callback for a rbtree helper that must
9215  * be called with lock held? If so, no need to complain about unreleased
9216  * lock
9217  */
9218 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9219 {
9220 	struct bpf_verifier_state *state = env->cur_state;
9221 	struct bpf_insn *insn = env->prog->insnsi;
9222 	struct bpf_func_state *callee;
9223 	int kfunc_btf_id;
9224 
9225 	if (!state->curframe)
9226 		return false;
9227 
9228 	callee = state->frame[state->curframe];
9229 
9230 	if (!callee->in_callback_fn)
9231 		return false;
9232 
9233 	kfunc_btf_id = insn[callee->callsite].imm;
9234 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9235 }
9236 
9237 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9238 {
9239 	struct bpf_verifier_state *state = env->cur_state;
9240 	struct bpf_func_state *caller, *callee;
9241 	struct bpf_reg_state *r0;
9242 	int err;
9243 
9244 	callee = state->frame[state->curframe];
9245 	r0 = &callee->regs[BPF_REG_0];
9246 	if (r0->type == PTR_TO_STACK) {
9247 		/* technically it's ok to return caller's stack pointer
9248 		 * (or caller's caller's pointer) back to the caller,
9249 		 * since these pointers are valid. Only current stack
9250 		 * pointer will be invalid as soon as function exits,
9251 		 * but let's be conservative
9252 		 */
9253 		verbose(env, "cannot return stack pointer to the caller\n");
9254 		return -EINVAL;
9255 	}
9256 
9257 	caller = state->frame[state->curframe - 1];
9258 	if (callee->in_callback_fn) {
9259 		/* enforce R0 return value range [0, 1]. */
9260 		struct tnum range = callee->callback_ret_range;
9261 
9262 		if (r0->type != SCALAR_VALUE) {
9263 			verbose(env, "R0 not a scalar value\n");
9264 			return -EACCES;
9265 		}
9266 		if (!tnum_in(range, r0->var_off)) {
9267 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9268 			return -EINVAL;
9269 		}
9270 	} else {
9271 		/* return to the caller whatever r0 had in the callee */
9272 		caller->regs[BPF_REG_0] = *r0;
9273 	}
9274 
9275 	/* callback_fn frame should have released its own additions to parent's
9276 	 * reference state at this point, or check_reference_leak would
9277 	 * complain, hence it must be the same as the caller. There is no need
9278 	 * to copy it back.
9279 	 */
9280 	if (!callee->in_callback_fn) {
9281 		/* Transfer references to the caller */
9282 		err = copy_reference_state(caller, callee);
9283 		if (err)
9284 			return err;
9285 	}
9286 
9287 	*insn_idx = callee->callsite + 1;
9288 	if (env->log.level & BPF_LOG_LEVEL) {
9289 		verbose(env, "returning from callee:\n");
9290 		print_verifier_state(env, callee, true);
9291 		verbose(env, "to caller at %d:\n", *insn_idx);
9292 		print_verifier_state(env, caller, true);
9293 	}
9294 	/* clear everything in the callee */
9295 	free_func_state(callee);
9296 	state->frame[state->curframe--] = NULL;
9297 	return 0;
9298 }
9299 
9300 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9301 				   int func_id,
9302 				   struct bpf_call_arg_meta *meta)
9303 {
9304 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9305 
9306 	if (ret_type != RET_INTEGER)
9307 		return;
9308 
9309 	switch (func_id) {
9310 	case BPF_FUNC_get_stack:
9311 	case BPF_FUNC_get_task_stack:
9312 	case BPF_FUNC_probe_read_str:
9313 	case BPF_FUNC_probe_read_kernel_str:
9314 	case BPF_FUNC_probe_read_user_str:
9315 		ret_reg->smax_value = meta->msize_max_value;
9316 		ret_reg->s32_max_value = meta->msize_max_value;
9317 		ret_reg->smin_value = -MAX_ERRNO;
9318 		ret_reg->s32_min_value = -MAX_ERRNO;
9319 		reg_bounds_sync(ret_reg);
9320 		break;
9321 	case BPF_FUNC_get_smp_processor_id:
9322 		ret_reg->umax_value = nr_cpu_ids - 1;
9323 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9324 		ret_reg->smax_value = nr_cpu_ids - 1;
9325 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9326 		ret_reg->umin_value = 0;
9327 		ret_reg->u32_min_value = 0;
9328 		ret_reg->smin_value = 0;
9329 		ret_reg->s32_min_value = 0;
9330 		reg_bounds_sync(ret_reg);
9331 		break;
9332 	}
9333 }
9334 
9335 static int
9336 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9337 		int func_id, int insn_idx)
9338 {
9339 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9340 	struct bpf_map *map = meta->map_ptr;
9341 
9342 	if (func_id != BPF_FUNC_tail_call &&
9343 	    func_id != BPF_FUNC_map_lookup_elem &&
9344 	    func_id != BPF_FUNC_map_update_elem &&
9345 	    func_id != BPF_FUNC_map_delete_elem &&
9346 	    func_id != BPF_FUNC_map_push_elem &&
9347 	    func_id != BPF_FUNC_map_pop_elem &&
9348 	    func_id != BPF_FUNC_map_peek_elem &&
9349 	    func_id != BPF_FUNC_for_each_map_elem &&
9350 	    func_id != BPF_FUNC_redirect_map &&
9351 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9352 		return 0;
9353 
9354 	if (map == NULL) {
9355 		verbose(env, "kernel subsystem misconfigured verifier\n");
9356 		return -EINVAL;
9357 	}
9358 
9359 	/* In case of read-only, some additional restrictions
9360 	 * need to be applied in order to prevent altering the
9361 	 * state of the map from program side.
9362 	 */
9363 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9364 	    (func_id == BPF_FUNC_map_delete_elem ||
9365 	     func_id == BPF_FUNC_map_update_elem ||
9366 	     func_id == BPF_FUNC_map_push_elem ||
9367 	     func_id == BPF_FUNC_map_pop_elem)) {
9368 		verbose(env, "write into map forbidden\n");
9369 		return -EACCES;
9370 	}
9371 
9372 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9373 		bpf_map_ptr_store(aux, meta->map_ptr,
9374 				  !meta->map_ptr->bypass_spec_v1);
9375 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9376 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9377 				  !meta->map_ptr->bypass_spec_v1);
9378 	return 0;
9379 }
9380 
9381 static int
9382 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9383 		int func_id, int insn_idx)
9384 {
9385 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9386 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9387 	struct bpf_map *map = meta->map_ptr;
9388 	u64 val, max;
9389 	int err;
9390 
9391 	if (func_id != BPF_FUNC_tail_call)
9392 		return 0;
9393 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9394 		verbose(env, "kernel subsystem misconfigured verifier\n");
9395 		return -EINVAL;
9396 	}
9397 
9398 	reg = &regs[BPF_REG_3];
9399 	val = reg->var_off.value;
9400 	max = map->max_entries;
9401 
9402 	if (!(register_is_const(reg) && val < max)) {
9403 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9404 		return 0;
9405 	}
9406 
9407 	err = mark_chain_precision(env, BPF_REG_3);
9408 	if (err)
9409 		return err;
9410 	if (bpf_map_key_unseen(aux))
9411 		bpf_map_key_store(aux, val);
9412 	else if (!bpf_map_key_poisoned(aux) &&
9413 		  bpf_map_key_immediate(aux) != val)
9414 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9415 	return 0;
9416 }
9417 
9418 static int check_reference_leak(struct bpf_verifier_env *env)
9419 {
9420 	struct bpf_func_state *state = cur_func(env);
9421 	bool refs_lingering = false;
9422 	int i;
9423 
9424 	if (state->frameno && !state->in_callback_fn)
9425 		return 0;
9426 
9427 	for (i = 0; i < state->acquired_refs; i++) {
9428 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9429 			continue;
9430 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9431 			state->refs[i].id, state->refs[i].insn_idx);
9432 		refs_lingering = true;
9433 	}
9434 	return refs_lingering ? -EINVAL : 0;
9435 }
9436 
9437 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9438 				   struct bpf_reg_state *regs)
9439 {
9440 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9441 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9442 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9443 	struct bpf_bprintf_data data = {};
9444 	int err, fmt_map_off, num_args;
9445 	u64 fmt_addr;
9446 	char *fmt;
9447 
9448 	/* data must be an array of u64 */
9449 	if (data_len_reg->var_off.value % 8)
9450 		return -EINVAL;
9451 	num_args = data_len_reg->var_off.value / 8;
9452 
9453 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9454 	 * and map_direct_value_addr is set.
9455 	 */
9456 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9457 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9458 						  fmt_map_off);
9459 	if (err) {
9460 		verbose(env, "verifier bug\n");
9461 		return -EFAULT;
9462 	}
9463 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9464 
9465 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9466 	 * can focus on validating the format specifiers.
9467 	 */
9468 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9469 	if (err < 0)
9470 		verbose(env, "Invalid format string\n");
9471 
9472 	return err;
9473 }
9474 
9475 static int check_get_func_ip(struct bpf_verifier_env *env)
9476 {
9477 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9478 	int func_id = BPF_FUNC_get_func_ip;
9479 
9480 	if (type == BPF_PROG_TYPE_TRACING) {
9481 		if (!bpf_prog_has_trampoline(env->prog)) {
9482 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9483 				func_id_name(func_id), func_id);
9484 			return -ENOTSUPP;
9485 		}
9486 		return 0;
9487 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9488 		return 0;
9489 	}
9490 
9491 	verbose(env, "func %s#%d not supported for program type %d\n",
9492 		func_id_name(func_id), func_id, type);
9493 	return -ENOTSUPP;
9494 }
9495 
9496 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9497 {
9498 	return &env->insn_aux_data[env->insn_idx];
9499 }
9500 
9501 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9502 {
9503 	struct bpf_reg_state *regs = cur_regs(env);
9504 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9505 	bool reg_is_null = register_is_null(reg);
9506 
9507 	if (reg_is_null)
9508 		mark_chain_precision(env, BPF_REG_4);
9509 
9510 	return reg_is_null;
9511 }
9512 
9513 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9514 {
9515 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9516 
9517 	if (!state->initialized) {
9518 		state->initialized = 1;
9519 		state->fit_for_inline = loop_flag_is_zero(env);
9520 		state->callback_subprogno = subprogno;
9521 		return;
9522 	}
9523 
9524 	if (!state->fit_for_inline)
9525 		return;
9526 
9527 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9528 				 state->callback_subprogno == subprogno);
9529 }
9530 
9531 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9532 			     int *insn_idx_p)
9533 {
9534 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9535 	const struct bpf_func_proto *fn = NULL;
9536 	enum bpf_return_type ret_type;
9537 	enum bpf_type_flag ret_flag;
9538 	struct bpf_reg_state *regs;
9539 	struct bpf_call_arg_meta meta;
9540 	int insn_idx = *insn_idx_p;
9541 	bool changes_data;
9542 	int i, err, func_id;
9543 
9544 	/* find function prototype */
9545 	func_id = insn->imm;
9546 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9547 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9548 			func_id);
9549 		return -EINVAL;
9550 	}
9551 
9552 	if (env->ops->get_func_proto)
9553 		fn = env->ops->get_func_proto(func_id, env->prog);
9554 	if (!fn) {
9555 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9556 			func_id);
9557 		return -EINVAL;
9558 	}
9559 
9560 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9561 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9562 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9563 		return -EINVAL;
9564 	}
9565 
9566 	if (fn->allowed && !fn->allowed(env->prog)) {
9567 		verbose(env, "helper call is not allowed in probe\n");
9568 		return -EINVAL;
9569 	}
9570 
9571 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9572 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9573 		return -EINVAL;
9574 	}
9575 
9576 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9577 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9578 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9579 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9580 			func_id_name(func_id), func_id);
9581 		return -EINVAL;
9582 	}
9583 
9584 	memset(&meta, 0, sizeof(meta));
9585 	meta.pkt_access = fn->pkt_access;
9586 
9587 	err = check_func_proto(fn, func_id);
9588 	if (err) {
9589 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9590 			func_id_name(func_id), func_id);
9591 		return err;
9592 	}
9593 
9594 	if (env->cur_state->active_rcu_lock) {
9595 		if (fn->might_sleep) {
9596 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9597 				func_id_name(func_id), func_id);
9598 			return -EINVAL;
9599 		}
9600 
9601 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9602 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9603 	}
9604 
9605 	meta.func_id = func_id;
9606 	/* check args */
9607 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9608 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9609 		if (err)
9610 			return err;
9611 	}
9612 
9613 	err = record_func_map(env, &meta, func_id, insn_idx);
9614 	if (err)
9615 		return err;
9616 
9617 	err = record_func_key(env, &meta, func_id, insn_idx);
9618 	if (err)
9619 		return err;
9620 
9621 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9622 	 * is inferred from register state.
9623 	 */
9624 	for (i = 0; i < meta.access_size; i++) {
9625 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9626 				       BPF_WRITE, -1, false, false);
9627 		if (err)
9628 			return err;
9629 	}
9630 
9631 	regs = cur_regs(env);
9632 
9633 	if (meta.release_regno) {
9634 		err = -EINVAL;
9635 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9636 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9637 		 * is safe to do directly.
9638 		 */
9639 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9640 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9641 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9642 				return -EFAULT;
9643 			}
9644 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9645 		} else if (meta.ref_obj_id) {
9646 			err = release_reference(env, meta.ref_obj_id);
9647 		} else if (register_is_null(&regs[meta.release_regno])) {
9648 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9649 			 * released is NULL, which must be > R0.
9650 			 */
9651 			err = 0;
9652 		}
9653 		if (err) {
9654 			verbose(env, "func %s#%d reference has not been acquired before\n",
9655 				func_id_name(func_id), func_id);
9656 			return err;
9657 		}
9658 	}
9659 
9660 	switch (func_id) {
9661 	case BPF_FUNC_tail_call:
9662 		err = check_reference_leak(env);
9663 		if (err) {
9664 			verbose(env, "tail_call would lead to reference leak\n");
9665 			return err;
9666 		}
9667 		break;
9668 	case BPF_FUNC_get_local_storage:
9669 		/* check that flags argument in get_local_storage(map, flags) is 0,
9670 		 * this is required because get_local_storage() can't return an error.
9671 		 */
9672 		if (!register_is_null(&regs[BPF_REG_2])) {
9673 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9674 			return -EINVAL;
9675 		}
9676 		break;
9677 	case BPF_FUNC_for_each_map_elem:
9678 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9679 					set_map_elem_callback_state);
9680 		break;
9681 	case BPF_FUNC_timer_set_callback:
9682 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9683 					set_timer_callback_state);
9684 		break;
9685 	case BPF_FUNC_find_vma:
9686 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9687 					set_find_vma_callback_state);
9688 		break;
9689 	case BPF_FUNC_snprintf:
9690 		err = check_bpf_snprintf_call(env, regs);
9691 		break;
9692 	case BPF_FUNC_loop:
9693 		update_loop_inline_state(env, meta.subprogno);
9694 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9695 					set_loop_callback_state);
9696 		break;
9697 	case BPF_FUNC_dynptr_from_mem:
9698 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9699 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9700 				reg_type_str(env, regs[BPF_REG_1].type));
9701 			return -EACCES;
9702 		}
9703 		break;
9704 	case BPF_FUNC_set_retval:
9705 		if (prog_type == BPF_PROG_TYPE_LSM &&
9706 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9707 			if (!env->prog->aux->attach_func_proto->type) {
9708 				/* Make sure programs that attach to void
9709 				 * hooks don't try to modify return value.
9710 				 */
9711 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9712 				return -EINVAL;
9713 			}
9714 		}
9715 		break;
9716 	case BPF_FUNC_dynptr_data:
9717 	{
9718 		struct bpf_reg_state *reg;
9719 		int id, ref_obj_id;
9720 
9721 		reg = get_dynptr_arg_reg(env, fn, regs);
9722 		if (!reg)
9723 			return -EFAULT;
9724 
9725 
9726 		if (meta.dynptr_id) {
9727 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9728 			return -EFAULT;
9729 		}
9730 		if (meta.ref_obj_id) {
9731 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9732 			return -EFAULT;
9733 		}
9734 
9735 		id = dynptr_id(env, reg);
9736 		if (id < 0) {
9737 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9738 			return id;
9739 		}
9740 
9741 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9742 		if (ref_obj_id < 0) {
9743 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9744 			return ref_obj_id;
9745 		}
9746 
9747 		meta.dynptr_id = id;
9748 		meta.ref_obj_id = ref_obj_id;
9749 
9750 		break;
9751 	}
9752 	case BPF_FUNC_dynptr_write:
9753 	{
9754 		enum bpf_dynptr_type dynptr_type;
9755 		struct bpf_reg_state *reg;
9756 
9757 		reg = get_dynptr_arg_reg(env, fn, regs);
9758 		if (!reg)
9759 			return -EFAULT;
9760 
9761 		dynptr_type = dynptr_get_type(env, reg);
9762 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9763 			return -EFAULT;
9764 
9765 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9766 			/* this will trigger clear_all_pkt_pointers(), which will
9767 			 * invalidate all dynptr slices associated with the skb
9768 			 */
9769 			changes_data = true;
9770 
9771 		break;
9772 	}
9773 	case BPF_FUNC_user_ringbuf_drain:
9774 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9775 					set_user_ringbuf_callback_state);
9776 		break;
9777 	}
9778 
9779 	if (err)
9780 		return err;
9781 
9782 	/* reset caller saved regs */
9783 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9784 		mark_reg_not_init(env, regs, caller_saved[i]);
9785 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9786 	}
9787 
9788 	/* helper call returns 64-bit value. */
9789 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9790 
9791 	/* update return register (already marked as written above) */
9792 	ret_type = fn->ret_type;
9793 	ret_flag = type_flag(ret_type);
9794 
9795 	switch (base_type(ret_type)) {
9796 	case RET_INTEGER:
9797 		/* sets type to SCALAR_VALUE */
9798 		mark_reg_unknown(env, regs, BPF_REG_0);
9799 		break;
9800 	case RET_VOID:
9801 		regs[BPF_REG_0].type = NOT_INIT;
9802 		break;
9803 	case RET_PTR_TO_MAP_VALUE:
9804 		/* There is no offset yet applied, variable or fixed */
9805 		mark_reg_known_zero(env, regs, BPF_REG_0);
9806 		/* remember map_ptr, so that check_map_access()
9807 		 * can check 'value_size' boundary of memory access
9808 		 * to map element returned from bpf_map_lookup_elem()
9809 		 */
9810 		if (meta.map_ptr == NULL) {
9811 			verbose(env,
9812 				"kernel subsystem misconfigured verifier\n");
9813 			return -EINVAL;
9814 		}
9815 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9816 		regs[BPF_REG_0].map_uid = meta.map_uid;
9817 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9818 		if (!type_may_be_null(ret_type) &&
9819 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9820 			regs[BPF_REG_0].id = ++env->id_gen;
9821 		}
9822 		break;
9823 	case RET_PTR_TO_SOCKET:
9824 		mark_reg_known_zero(env, regs, BPF_REG_0);
9825 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9826 		break;
9827 	case RET_PTR_TO_SOCK_COMMON:
9828 		mark_reg_known_zero(env, regs, BPF_REG_0);
9829 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9830 		break;
9831 	case RET_PTR_TO_TCP_SOCK:
9832 		mark_reg_known_zero(env, regs, BPF_REG_0);
9833 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9834 		break;
9835 	case RET_PTR_TO_MEM:
9836 		mark_reg_known_zero(env, regs, BPF_REG_0);
9837 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9838 		regs[BPF_REG_0].mem_size = meta.mem_size;
9839 		break;
9840 	case RET_PTR_TO_MEM_OR_BTF_ID:
9841 	{
9842 		const struct btf_type *t;
9843 
9844 		mark_reg_known_zero(env, regs, BPF_REG_0);
9845 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9846 		if (!btf_type_is_struct(t)) {
9847 			u32 tsize;
9848 			const struct btf_type *ret;
9849 			const char *tname;
9850 
9851 			/* resolve the type size of ksym. */
9852 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9853 			if (IS_ERR(ret)) {
9854 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9855 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9856 					tname, PTR_ERR(ret));
9857 				return -EINVAL;
9858 			}
9859 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9860 			regs[BPF_REG_0].mem_size = tsize;
9861 		} else {
9862 			/* MEM_RDONLY may be carried from ret_flag, but it
9863 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9864 			 * it will confuse the check of PTR_TO_BTF_ID in
9865 			 * check_mem_access().
9866 			 */
9867 			ret_flag &= ~MEM_RDONLY;
9868 
9869 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9870 			regs[BPF_REG_0].btf = meta.ret_btf;
9871 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9872 		}
9873 		break;
9874 	}
9875 	case RET_PTR_TO_BTF_ID:
9876 	{
9877 		struct btf *ret_btf;
9878 		int ret_btf_id;
9879 
9880 		mark_reg_known_zero(env, regs, BPF_REG_0);
9881 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9882 		if (func_id == BPF_FUNC_kptr_xchg) {
9883 			ret_btf = meta.kptr_field->kptr.btf;
9884 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9885 			if (!btf_is_kernel(ret_btf))
9886 				regs[BPF_REG_0].type |= MEM_ALLOC;
9887 		} else {
9888 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9889 				verbose(env, "verifier internal error:");
9890 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9891 					func_id_name(func_id));
9892 				return -EINVAL;
9893 			}
9894 			ret_btf = btf_vmlinux;
9895 			ret_btf_id = *fn->ret_btf_id;
9896 		}
9897 		if (ret_btf_id == 0) {
9898 			verbose(env, "invalid return type %u of func %s#%d\n",
9899 				base_type(ret_type), func_id_name(func_id),
9900 				func_id);
9901 			return -EINVAL;
9902 		}
9903 		regs[BPF_REG_0].btf = ret_btf;
9904 		regs[BPF_REG_0].btf_id = ret_btf_id;
9905 		break;
9906 	}
9907 	default:
9908 		verbose(env, "unknown return type %u of func %s#%d\n",
9909 			base_type(ret_type), func_id_name(func_id), func_id);
9910 		return -EINVAL;
9911 	}
9912 
9913 	if (type_may_be_null(regs[BPF_REG_0].type))
9914 		regs[BPF_REG_0].id = ++env->id_gen;
9915 
9916 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9917 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9918 			func_id_name(func_id), func_id);
9919 		return -EFAULT;
9920 	}
9921 
9922 	if (is_dynptr_ref_function(func_id))
9923 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9924 
9925 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9926 		/* For release_reference() */
9927 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9928 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9929 		int id = acquire_reference_state(env, insn_idx);
9930 
9931 		if (id < 0)
9932 			return id;
9933 		/* For mark_ptr_or_null_reg() */
9934 		regs[BPF_REG_0].id = id;
9935 		/* For release_reference() */
9936 		regs[BPF_REG_0].ref_obj_id = id;
9937 	}
9938 
9939 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9940 
9941 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9942 	if (err)
9943 		return err;
9944 
9945 	if ((func_id == BPF_FUNC_get_stack ||
9946 	     func_id == BPF_FUNC_get_task_stack) &&
9947 	    !env->prog->has_callchain_buf) {
9948 		const char *err_str;
9949 
9950 #ifdef CONFIG_PERF_EVENTS
9951 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9952 		err_str = "cannot get callchain buffer for func %s#%d\n";
9953 #else
9954 		err = -ENOTSUPP;
9955 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9956 #endif
9957 		if (err) {
9958 			verbose(env, err_str, func_id_name(func_id), func_id);
9959 			return err;
9960 		}
9961 
9962 		env->prog->has_callchain_buf = true;
9963 	}
9964 
9965 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9966 		env->prog->call_get_stack = true;
9967 
9968 	if (func_id == BPF_FUNC_get_func_ip) {
9969 		if (check_get_func_ip(env))
9970 			return -ENOTSUPP;
9971 		env->prog->call_get_func_ip = true;
9972 	}
9973 
9974 	if (changes_data)
9975 		clear_all_pkt_pointers(env);
9976 	return 0;
9977 }
9978 
9979 /* mark_btf_func_reg_size() is used when the reg size is determined by
9980  * the BTF func_proto's return value size and argument.
9981  */
9982 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9983 				   size_t reg_size)
9984 {
9985 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9986 
9987 	if (regno == BPF_REG_0) {
9988 		/* Function return value */
9989 		reg->live |= REG_LIVE_WRITTEN;
9990 		reg->subreg_def = reg_size == sizeof(u64) ?
9991 			DEF_NOT_SUBREG : env->insn_idx + 1;
9992 	} else {
9993 		/* Function argument */
9994 		if (reg_size == sizeof(u64)) {
9995 			mark_insn_zext(env, reg);
9996 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9997 		} else {
9998 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9999 		}
10000 	}
10001 }
10002 
10003 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10004 {
10005 	return meta->kfunc_flags & KF_ACQUIRE;
10006 }
10007 
10008 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10009 {
10010 	return meta->kfunc_flags & KF_RELEASE;
10011 }
10012 
10013 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10014 {
10015 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10016 }
10017 
10018 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10019 {
10020 	return meta->kfunc_flags & KF_SLEEPABLE;
10021 }
10022 
10023 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10024 {
10025 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10026 }
10027 
10028 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10029 {
10030 	return meta->kfunc_flags & KF_RCU;
10031 }
10032 
10033 static bool __kfunc_param_match_suffix(const struct btf *btf,
10034 				       const struct btf_param *arg,
10035 				       const char *suffix)
10036 {
10037 	int suffix_len = strlen(suffix), len;
10038 	const char *param_name;
10039 
10040 	/* In the future, this can be ported to use BTF tagging */
10041 	param_name = btf_name_by_offset(btf, arg->name_off);
10042 	if (str_is_empty(param_name))
10043 		return false;
10044 	len = strlen(param_name);
10045 	if (len < suffix_len)
10046 		return false;
10047 	param_name += len - suffix_len;
10048 	return !strncmp(param_name, suffix, suffix_len);
10049 }
10050 
10051 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10052 				  const struct btf_param *arg,
10053 				  const struct bpf_reg_state *reg)
10054 {
10055 	const struct btf_type *t;
10056 
10057 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10058 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10059 		return false;
10060 
10061 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10062 }
10063 
10064 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10065 					const struct btf_param *arg,
10066 					const struct bpf_reg_state *reg)
10067 {
10068 	const struct btf_type *t;
10069 
10070 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10071 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10072 		return false;
10073 
10074 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10075 }
10076 
10077 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10078 {
10079 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10080 }
10081 
10082 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10083 {
10084 	return __kfunc_param_match_suffix(btf, arg, "__k");
10085 }
10086 
10087 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10088 {
10089 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10090 }
10091 
10092 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10093 {
10094 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10095 }
10096 
10097 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10098 {
10099 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10100 }
10101 
10102 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10103 {
10104 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10105 }
10106 
10107 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10108 					  const struct btf_param *arg,
10109 					  const char *name)
10110 {
10111 	int len, target_len = strlen(name);
10112 	const char *param_name;
10113 
10114 	param_name = btf_name_by_offset(btf, arg->name_off);
10115 	if (str_is_empty(param_name))
10116 		return false;
10117 	len = strlen(param_name);
10118 	if (len != target_len)
10119 		return false;
10120 	if (strcmp(param_name, name))
10121 		return false;
10122 
10123 	return true;
10124 }
10125 
10126 enum {
10127 	KF_ARG_DYNPTR_ID,
10128 	KF_ARG_LIST_HEAD_ID,
10129 	KF_ARG_LIST_NODE_ID,
10130 	KF_ARG_RB_ROOT_ID,
10131 	KF_ARG_RB_NODE_ID,
10132 };
10133 
10134 BTF_ID_LIST(kf_arg_btf_ids)
10135 BTF_ID(struct, bpf_dynptr_kern)
10136 BTF_ID(struct, bpf_list_head)
10137 BTF_ID(struct, bpf_list_node)
10138 BTF_ID(struct, bpf_rb_root)
10139 BTF_ID(struct, bpf_rb_node)
10140 
10141 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10142 				    const struct btf_param *arg, int type)
10143 {
10144 	const struct btf_type *t;
10145 	u32 res_id;
10146 
10147 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10148 	if (!t)
10149 		return false;
10150 	if (!btf_type_is_ptr(t))
10151 		return false;
10152 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10153 	if (!t)
10154 		return false;
10155 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10156 }
10157 
10158 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10159 {
10160 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10161 }
10162 
10163 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10164 {
10165 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10166 }
10167 
10168 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10169 {
10170 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10171 }
10172 
10173 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10174 {
10175 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10176 }
10177 
10178 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10179 {
10180 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10181 }
10182 
10183 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10184 				  const struct btf_param *arg)
10185 {
10186 	const struct btf_type *t;
10187 
10188 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10189 	if (!t)
10190 		return false;
10191 
10192 	return true;
10193 }
10194 
10195 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10196 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10197 					const struct btf *btf,
10198 					const struct btf_type *t, int rec)
10199 {
10200 	const struct btf_type *member_type;
10201 	const struct btf_member *member;
10202 	u32 i;
10203 
10204 	if (!btf_type_is_struct(t))
10205 		return false;
10206 
10207 	for_each_member(i, t, member) {
10208 		const struct btf_array *array;
10209 
10210 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10211 		if (btf_type_is_struct(member_type)) {
10212 			if (rec >= 3) {
10213 				verbose(env, "max struct nesting depth exceeded\n");
10214 				return false;
10215 			}
10216 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10217 				return false;
10218 			continue;
10219 		}
10220 		if (btf_type_is_array(member_type)) {
10221 			array = btf_array(member_type);
10222 			if (!array->nelems)
10223 				return false;
10224 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10225 			if (!btf_type_is_scalar(member_type))
10226 				return false;
10227 			continue;
10228 		}
10229 		if (!btf_type_is_scalar(member_type))
10230 			return false;
10231 	}
10232 	return true;
10233 }
10234 
10235 enum kfunc_ptr_arg_type {
10236 	KF_ARG_PTR_TO_CTX,
10237 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10238 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10239 	KF_ARG_PTR_TO_DYNPTR,
10240 	KF_ARG_PTR_TO_ITER,
10241 	KF_ARG_PTR_TO_LIST_HEAD,
10242 	KF_ARG_PTR_TO_LIST_NODE,
10243 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10244 	KF_ARG_PTR_TO_MEM,
10245 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10246 	KF_ARG_PTR_TO_CALLBACK,
10247 	KF_ARG_PTR_TO_RB_ROOT,
10248 	KF_ARG_PTR_TO_RB_NODE,
10249 };
10250 
10251 enum special_kfunc_type {
10252 	KF_bpf_obj_new_impl,
10253 	KF_bpf_obj_drop_impl,
10254 	KF_bpf_refcount_acquire_impl,
10255 	KF_bpf_list_push_front_impl,
10256 	KF_bpf_list_push_back_impl,
10257 	KF_bpf_list_pop_front,
10258 	KF_bpf_list_pop_back,
10259 	KF_bpf_cast_to_kern_ctx,
10260 	KF_bpf_rdonly_cast,
10261 	KF_bpf_rcu_read_lock,
10262 	KF_bpf_rcu_read_unlock,
10263 	KF_bpf_rbtree_remove,
10264 	KF_bpf_rbtree_add_impl,
10265 	KF_bpf_rbtree_first,
10266 	KF_bpf_dynptr_from_skb,
10267 	KF_bpf_dynptr_from_xdp,
10268 	KF_bpf_dynptr_slice,
10269 	KF_bpf_dynptr_slice_rdwr,
10270 	KF_bpf_dynptr_clone,
10271 };
10272 
10273 BTF_SET_START(special_kfunc_set)
10274 BTF_ID(func, bpf_obj_new_impl)
10275 BTF_ID(func, bpf_obj_drop_impl)
10276 BTF_ID(func, bpf_refcount_acquire_impl)
10277 BTF_ID(func, bpf_list_push_front_impl)
10278 BTF_ID(func, bpf_list_push_back_impl)
10279 BTF_ID(func, bpf_list_pop_front)
10280 BTF_ID(func, bpf_list_pop_back)
10281 BTF_ID(func, bpf_cast_to_kern_ctx)
10282 BTF_ID(func, bpf_rdonly_cast)
10283 BTF_ID(func, bpf_rbtree_remove)
10284 BTF_ID(func, bpf_rbtree_add_impl)
10285 BTF_ID(func, bpf_rbtree_first)
10286 BTF_ID(func, bpf_dynptr_from_skb)
10287 BTF_ID(func, bpf_dynptr_from_xdp)
10288 BTF_ID(func, bpf_dynptr_slice)
10289 BTF_ID(func, bpf_dynptr_slice_rdwr)
10290 BTF_ID(func, bpf_dynptr_clone)
10291 BTF_SET_END(special_kfunc_set)
10292 
10293 BTF_ID_LIST(special_kfunc_list)
10294 BTF_ID(func, bpf_obj_new_impl)
10295 BTF_ID(func, bpf_obj_drop_impl)
10296 BTF_ID(func, bpf_refcount_acquire_impl)
10297 BTF_ID(func, bpf_list_push_front_impl)
10298 BTF_ID(func, bpf_list_push_back_impl)
10299 BTF_ID(func, bpf_list_pop_front)
10300 BTF_ID(func, bpf_list_pop_back)
10301 BTF_ID(func, bpf_cast_to_kern_ctx)
10302 BTF_ID(func, bpf_rdonly_cast)
10303 BTF_ID(func, bpf_rcu_read_lock)
10304 BTF_ID(func, bpf_rcu_read_unlock)
10305 BTF_ID(func, bpf_rbtree_remove)
10306 BTF_ID(func, bpf_rbtree_add_impl)
10307 BTF_ID(func, bpf_rbtree_first)
10308 BTF_ID(func, bpf_dynptr_from_skb)
10309 BTF_ID(func, bpf_dynptr_from_xdp)
10310 BTF_ID(func, bpf_dynptr_slice)
10311 BTF_ID(func, bpf_dynptr_slice_rdwr)
10312 BTF_ID(func, bpf_dynptr_clone)
10313 
10314 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10315 {
10316 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10317 	    meta->arg_owning_ref) {
10318 		return false;
10319 	}
10320 
10321 	return meta->kfunc_flags & KF_RET_NULL;
10322 }
10323 
10324 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10325 {
10326 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10327 }
10328 
10329 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10330 {
10331 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10332 }
10333 
10334 static enum kfunc_ptr_arg_type
10335 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10336 		       struct bpf_kfunc_call_arg_meta *meta,
10337 		       const struct btf_type *t, const struct btf_type *ref_t,
10338 		       const char *ref_tname, const struct btf_param *args,
10339 		       int argno, int nargs)
10340 {
10341 	u32 regno = argno + 1;
10342 	struct bpf_reg_state *regs = cur_regs(env);
10343 	struct bpf_reg_state *reg = &regs[regno];
10344 	bool arg_mem_size = false;
10345 
10346 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10347 		return KF_ARG_PTR_TO_CTX;
10348 
10349 	/* In this function, we verify the kfunc's BTF as per the argument type,
10350 	 * leaving the rest of the verification with respect to the register
10351 	 * type to our caller. When a set of conditions hold in the BTF type of
10352 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10353 	 */
10354 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10355 		return KF_ARG_PTR_TO_CTX;
10356 
10357 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10358 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10359 
10360 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10361 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10362 
10363 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10364 		return KF_ARG_PTR_TO_DYNPTR;
10365 
10366 	if (is_kfunc_arg_iter(meta, argno))
10367 		return KF_ARG_PTR_TO_ITER;
10368 
10369 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10370 		return KF_ARG_PTR_TO_LIST_HEAD;
10371 
10372 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10373 		return KF_ARG_PTR_TO_LIST_NODE;
10374 
10375 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10376 		return KF_ARG_PTR_TO_RB_ROOT;
10377 
10378 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10379 		return KF_ARG_PTR_TO_RB_NODE;
10380 
10381 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10382 		if (!btf_type_is_struct(ref_t)) {
10383 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10384 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10385 			return -EINVAL;
10386 		}
10387 		return KF_ARG_PTR_TO_BTF_ID;
10388 	}
10389 
10390 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10391 		return KF_ARG_PTR_TO_CALLBACK;
10392 
10393 
10394 	if (argno + 1 < nargs &&
10395 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10396 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10397 		arg_mem_size = true;
10398 
10399 	/* This is the catch all argument type of register types supported by
10400 	 * check_helper_mem_access. However, we only allow when argument type is
10401 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10402 	 * arg_mem_size is true, the pointer can be void *.
10403 	 */
10404 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10405 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10406 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10407 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10408 		return -EINVAL;
10409 	}
10410 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10411 }
10412 
10413 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10414 					struct bpf_reg_state *reg,
10415 					const struct btf_type *ref_t,
10416 					const char *ref_tname, u32 ref_id,
10417 					struct bpf_kfunc_call_arg_meta *meta,
10418 					int argno)
10419 {
10420 	const struct btf_type *reg_ref_t;
10421 	bool strict_type_match = false;
10422 	const struct btf *reg_btf;
10423 	const char *reg_ref_tname;
10424 	u32 reg_ref_id;
10425 
10426 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10427 		reg_btf = reg->btf;
10428 		reg_ref_id = reg->btf_id;
10429 	} else {
10430 		reg_btf = btf_vmlinux;
10431 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10432 	}
10433 
10434 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10435 	 * or releasing a reference, or are no-cast aliases. We do _not_
10436 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10437 	 * as we want to enable BPF programs to pass types that are bitwise
10438 	 * equivalent without forcing them to explicitly cast with something
10439 	 * like bpf_cast_to_kern_ctx().
10440 	 *
10441 	 * For example, say we had a type like the following:
10442 	 *
10443 	 * struct bpf_cpumask {
10444 	 *	cpumask_t cpumask;
10445 	 *	refcount_t usage;
10446 	 * };
10447 	 *
10448 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10449 	 * to a struct cpumask, so it would be safe to pass a struct
10450 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10451 	 *
10452 	 * The philosophy here is similar to how we allow scalars of different
10453 	 * types to be passed to kfuncs as long as the size is the same. The
10454 	 * only difference here is that we're simply allowing
10455 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10456 	 * resolve types.
10457 	 */
10458 	if (is_kfunc_acquire(meta) ||
10459 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10460 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10461 		strict_type_match = true;
10462 
10463 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10464 
10465 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10466 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10467 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10468 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10469 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10470 			btf_type_str(reg_ref_t), reg_ref_tname);
10471 		return -EINVAL;
10472 	}
10473 	return 0;
10474 }
10475 
10476 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10477 {
10478 	struct bpf_verifier_state *state = env->cur_state;
10479 	struct btf_record *rec = reg_btf_record(reg);
10480 
10481 	if (!state->active_lock.ptr) {
10482 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10483 		return -EFAULT;
10484 	}
10485 
10486 	if (type_flag(reg->type) & NON_OWN_REF) {
10487 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10488 		return -EFAULT;
10489 	}
10490 
10491 	reg->type |= NON_OWN_REF;
10492 	if (rec->refcount_off >= 0)
10493 		reg->type |= MEM_RCU;
10494 
10495 	return 0;
10496 }
10497 
10498 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10499 {
10500 	struct bpf_func_state *state, *unused;
10501 	struct bpf_reg_state *reg;
10502 	int i;
10503 
10504 	state = cur_func(env);
10505 
10506 	if (!ref_obj_id) {
10507 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10508 			     "owning -> non-owning conversion\n");
10509 		return -EFAULT;
10510 	}
10511 
10512 	for (i = 0; i < state->acquired_refs; i++) {
10513 		if (state->refs[i].id != ref_obj_id)
10514 			continue;
10515 
10516 		/* Clear ref_obj_id here so release_reference doesn't clobber
10517 		 * the whole reg
10518 		 */
10519 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10520 			if (reg->ref_obj_id == ref_obj_id) {
10521 				reg->ref_obj_id = 0;
10522 				ref_set_non_owning(env, reg);
10523 			}
10524 		}));
10525 		return 0;
10526 	}
10527 
10528 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10529 	return -EFAULT;
10530 }
10531 
10532 /* Implementation details:
10533  *
10534  * Each register points to some region of memory, which we define as an
10535  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10536  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10537  * allocation. The lock and the data it protects are colocated in the same
10538  * memory region.
10539  *
10540  * Hence, everytime a register holds a pointer value pointing to such
10541  * allocation, the verifier preserves a unique reg->id for it.
10542  *
10543  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10544  * bpf_spin_lock is called.
10545  *
10546  * To enable this, lock state in the verifier captures two values:
10547  *	active_lock.ptr = Register's type specific pointer
10548  *	active_lock.id  = A unique ID for each register pointer value
10549  *
10550  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10551  * supported register types.
10552  *
10553  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10554  * allocated objects is the reg->btf pointer.
10555  *
10556  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10557  * can establish the provenance of the map value statically for each distinct
10558  * lookup into such maps. They always contain a single map value hence unique
10559  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10560  *
10561  * So, in case of global variables, they use array maps with max_entries = 1,
10562  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10563  * into the same map value as max_entries is 1, as described above).
10564  *
10565  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10566  * outer map pointer (in verifier context), but each lookup into an inner map
10567  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10568  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10569  * will get different reg->id assigned to each lookup, hence different
10570  * active_lock.id.
10571  *
10572  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10573  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10574  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10575  */
10576 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10577 {
10578 	void *ptr;
10579 	u32 id;
10580 
10581 	switch ((int)reg->type) {
10582 	case PTR_TO_MAP_VALUE:
10583 		ptr = reg->map_ptr;
10584 		break;
10585 	case PTR_TO_BTF_ID | MEM_ALLOC:
10586 		ptr = reg->btf;
10587 		break;
10588 	default:
10589 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10590 		return -EFAULT;
10591 	}
10592 	id = reg->id;
10593 
10594 	if (!env->cur_state->active_lock.ptr)
10595 		return -EINVAL;
10596 	if (env->cur_state->active_lock.ptr != ptr ||
10597 	    env->cur_state->active_lock.id != id) {
10598 		verbose(env, "held lock and object are not in the same allocation\n");
10599 		return -EINVAL;
10600 	}
10601 	return 0;
10602 }
10603 
10604 static bool is_bpf_list_api_kfunc(u32 btf_id)
10605 {
10606 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10607 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10608 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10609 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10610 }
10611 
10612 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10613 {
10614 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10615 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10616 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10617 }
10618 
10619 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10620 {
10621 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10622 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10623 }
10624 
10625 static bool is_callback_calling_kfunc(u32 btf_id)
10626 {
10627 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10628 }
10629 
10630 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10631 {
10632 	return is_bpf_rbtree_api_kfunc(btf_id);
10633 }
10634 
10635 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10636 					  enum btf_field_type head_field_type,
10637 					  u32 kfunc_btf_id)
10638 {
10639 	bool ret;
10640 
10641 	switch (head_field_type) {
10642 	case BPF_LIST_HEAD:
10643 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10644 		break;
10645 	case BPF_RB_ROOT:
10646 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10647 		break;
10648 	default:
10649 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10650 			btf_field_type_name(head_field_type));
10651 		return false;
10652 	}
10653 
10654 	if (!ret)
10655 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10656 			btf_field_type_name(head_field_type));
10657 	return ret;
10658 }
10659 
10660 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10661 					  enum btf_field_type node_field_type,
10662 					  u32 kfunc_btf_id)
10663 {
10664 	bool ret;
10665 
10666 	switch (node_field_type) {
10667 	case BPF_LIST_NODE:
10668 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10669 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10670 		break;
10671 	case BPF_RB_NODE:
10672 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10673 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10674 		break;
10675 	default:
10676 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10677 			btf_field_type_name(node_field_type));
10678 		return false;
10679 	}
10680 
10681 	if (!ret)
10682 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10683 			btf_field_type_name(node_field_type));
10684 	return ret;
10685 }
10686 
10687 static int
10688 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10689 				   struct bpf_reg_state *reg, u32 regno,
10690 				   struct bpf_kfunc_call_arg_meta *meta,
10691 				   enum btf_field_type head_field_type,
10692 				   struct btf_field **head_field)
10693 {
10694 	const char *head_type_name;
10695 	struct btf_field *field;
10696 	struct btf_record *rec;
10697 	u32 head_off;
10698 
10699 	if (meta->btf != btf_vmlinux) {
10700 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10701 		return -EFAULT;
10702 	}
10703 
10704 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10705 		return -EFAULT;
10706 
10707 	head_type_name = btf_field_type_name(head_field_type);
10708 	if (!tnum_is_const(reg->var_off)) {
10709 		verbose(env,
10710 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10711 			regno, head_type_name);
10712 		return -EINVAL;
10713 	}
10714 
10715 	rec = reg_btf_record(reg);
10716 	head_off = reg->off + reg->var_off.value;
10717 	field = btf_record_find(rec, head_off, head_field_type);
10718 	if (!field) {
10719 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10720 		return -EINVAL;
10721 	}
10722 
10723 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10724 	if (check_reg_allocation_locked(env, reg)) {
10725 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10726 			rec->spin_lock_off, head_type_name);
10727 		return -EINVAL;
10728 	}
10729 
10730 	if (*head_field) {
10731 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10732 		return -EFAULT;
10733 	}
10734 	*head_field = field;
10735 	return 0;
10736 }
10737 
10738 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10739 					   struct bpf_reg_state *reg, u32 regno,
10740 					   struct bpf_kfunc_call_arg_meta *meta)
10741 {
10742 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10743 							  &meta->arg_list_head.field);
10744 }
10745 
10746 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10747 					     struct bpf_reg_state *reg, u32 regno,
10748 					     struct bpf_kfunc_call_arg_meta *meta)
10749 {
10750 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10751 							  &meta->arg_rbtree_root.field);
10752 }
10753 
10754 static int
10755 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10756 				   struct bpf_reg_state *reg, u32 regno,
10757 				   struct bpf_kfunc_call_arg_meta *meta,
10758 				   enum btf_field_type head_field_type,
10759 				   enum btf_field_type node_field_type,
10760 				   struct btf_field **node_field)
10761 {
10762 	const char *node_type_name;
10763 	const struct btf_type *et, *t;
10764 	struct btf_field *field;
10765 	u32 node_off;
10766 
10767 	if (meta->btf != btf_vmlinux) {
10768 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10769 		return -EFAULT;
10770 	}
10771 
10772 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10773 		return -EFAULT;
10774 
10775 	node_type_name = btf_field_type_name(node_field_type);
10776 	if (!tnum_is_const(reg->var_off)) {
10777 		verbose(env,
10778 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10779 			regno, node_type_name);
10780 		return -EINVAL;
10781 	}
10782 
10783 	node_off = reg->off + reg->var_off.value;
10784 	field = reg_find_field_offset(reg, node_off, node_field_type);
10785 	if (!field || field->offset != node_off) {
10786 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10787 		return -EINVAL;
10788 	}
10789 
10790 	field = *node_field;
10791 
10792 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10793 	t = btf_type_by_id(reg->btf, reg->btf_id);
10794 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10795 				  field->graph_root.value_btf_id, true)) {
10796 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10797 			"in struct %s, but arg is at offset=%d in struct %s\n",
10798 			btf_field_type_name(head_field_type),
10799 			btf_field_type_name(node_field_type),
10800 			field->graph_root.node_offset,
10801 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10802 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10803 		return -EINVAL;
10804 	}
10805 	meta->arg_btf = reg->btf;
10806 	meta->arg_btf_id = reg->btf_id;
10807 
10808 	if (node_off != field->graph_root.node_offset) {
10809 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10810 			node_off, btf_field_type_name(node_field_type),
10811 			field->graph_root.node_offset,
10812 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10813 		return -EINVAL;
10814 	}
10815 
10816 	return 0;
10817 }
10818 
10819 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10820 					   struct bpf_reg_state *reg, u32 regno,
10821 					   struct bpf_kfunc_call_arg_meta *meta)
10822 {
10823 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10824 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10825 						  &meta->arg_list_head.field);
10826 }
10827 
10828 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10829 					     struct bpf_reg_state *reg, u32 regno,
10830 					     struct bpf_kfunc_call_arg_meta *meta)
10831 {
10832 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10833 						  BPF_RB_ROOT, BPF_RB_NODE,
10834 						  &meta->arg_rbtree_root.field);
10835 }
10836 
10837 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10838 			    int insn_idx)
10839 {
10840 	const char *func_name = meta->func_name, *ref_tname;
10841 	const struct btf *btf = meta->btf;
10842 	const struct btf_param *args;
10843 	struct btf_record *rec;
10844 	u32 i, nargs;
10845 	int ret;
10846 
10847 	args = (const struct btf_param *)(meta->func_proto + 1);
10848 	nargs = btf_type_vlen(meta->func_proto);
10849 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10850 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10851 			MAX_BPF_FUNC_REG_ARGS);
10852 		return -EINVAL;
10853 	}
10854 
10855 	/* Check that BTF function arguments match actual types that the
10856 	 * verifier sees.
10857 	 */
10858 	for (i = 0; i < nargs; i++) {
10859 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10860 		const struct btf_type *t, *ref_t, *resolve_ret;
10861 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10862 		u32 regno = i + 1, ref_id, type_size;
10863 		bool is_ret_buf_sz = false;
10864 		int kf_arg_type;
10865 
10866 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10867 
10868 		if (is_kfunc_arg_ignore(btf, &args[i]))
10869 			continue;
10870 
10871 		if (btf_type_is_scalar(t)) {
10872 			if (reg->type != SCALAR_VALUE) {
10873 				verbose(env, "R%d is not a scalar\n", regno);
10874 				return -EINVAL;
10875 			}
10876 
10877 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10878 				if (meta->arg_constant.found) {
10879 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10880 					return -EFAULT;
10881 				}
10882 				if (!tnum_is_const(reg->var_off)) {
10883 					verbose(env, "R%d must be a known constant\n", regno);
10884 					return -EINVAL;
10885 				}
10886 				ret = mark_chain_precision(env, regno);
10887 				if (ret < 0)
10888 					return ret;
10889 				meta->arg_constant.found = true;
10890 				meta->arg_constant.value = reg->var_off.value;
10891 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10892 				meta->r0_rdonly = true;
10893 				is_ret_buf_sz = true;
10894 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10895 				is_ret_buf_sz = true;
10896 			}
10897 
10898 			if (is_ret_buf_sz) {
10899 				if (meta->r0_size) {
10900 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10901 					return -EINVAL;
10902 				}
10903 
10904 				if (!tnum_is_const(reg->var_off)) {
10905 					verbose(env, "R%d is not a const\n", regno);
10906 					return -EINVAL;
10907 				}
10908 
10909 				meta->r0_size = reg->var_off.value;
10910 				ret = mark_chain_precision(env, regno);
10911 				if (ret)
10912 					return ret;
10913 			}
10914 			continue;
10915 		}
10916 
10917 		if (!btf_type_is_ptr(t)) {
10918 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10919 			return -EINVAL;
10920 		}
10921 
10922 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10923 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10924 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10925 			return -EACCES;
10926 		}
10927 
10928 		if (reg->ref_obj_id) {
10929 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10930 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10931 					regno, reg->ref_obj_id,
10932 					meta->ref_obj_id);
10933 				return -EFAULT;
10934 			}
10935 			meta->ref_obj_id = reg->ref_obj_id;
10936 			if (is_kfunc_release(meta))
10937 				meta->release_regno = regno;
10938 		}
10939 
10940 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10941 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10942 
10943 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10944 		if (kf_arg_type < 0)
10945 			return kf_arg_type;
10946 
10947 		switch (kf_arg_type) {
10948 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10949 		case KF_ARG_PTR_TO_BTF_ID:
10950 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10951 				break;
10952 
10953 			if (!is_trusted_reg(reg)) {
10954 				if (!is_kfunc_rcu(meta)) {
10955 					verbose(env, "R%d must be referenced or trusted\n", regno);
10956 					return -EINVAL;
10957 				}
10958 				if (!is_rcu_reg(reg)) {
10959 					verbose(env, "R%d must be a rcu pointer\n", regno);
10960 					return -EINVAL;
10961 				}
10962 			}
10963 
10964 			fallthrough;
10965 		case KF_ARG_PTR_TO_CTX:
10966 			/* Trusted arguments have the same offset checks as release arguments */
10967 			arg_type |= OBJ_RELEASE;
10968 			break;
10969 		case KF_ARG_PTR_TO_DYNPTR:
10970 		case KF_ARG_PTR_TO_ITER:
10971 		case KF_ARG_PTR_TO_LIST_HEAD:
10972 		case KF_ARG_PTR_TO_LIST_NODE:
10973 		case KF_ARG_PTR_TO_RB_ROOT:
10974 		case KF_ARG_PTR_TO_RB_NODE:
10975 		case KF_ARG_PTR_TO_MEM:
10976 		case KF_ARG_PTR_TO_MEM_SIZE:
10977 		case KF_ARG_PTR_TO_CALLBACK:
10978 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10979 			/* Trusted by default */
10980 			break;
10981 		default:
10982 			WARN_ON_ONCE(1);
10983 			return -EFAULT;
10984 		}
10985 
10986 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10987 			arg_type |= OBJ_RELEASE;
10988 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10989 		if (ret < 0)
10990 			return ret;
10991 
10992 		switch (kf_arg_type) {
10993 		case KF_ARG_PTR_TO_CTX:
10994 			if (reg->type != PTR_TO_CTX) {
10995 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10996 				return -EINVAL;
10997 			}
10998 
10999 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11000 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11001 				if (ret < 0)
11002 					return -EINVAL;
11003 				meta->ret_btf_id  = ret;
11004 			}
11005 			break;
11006 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11007 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11008 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11009 				return -EINVAL;
11010 			}
11011 			if (!reg->ref_obj_id) {
11012 				verbose(env, "allocated object must be referenced\n");
11013 				return -EINVAL;
11014 			}
11015 			if (meta->btf == btf_vmlinux &&
11016 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11017 				meta->arg_btf = reg->btf;
11018 				meta->arg_btf_id = reg->btf_id;
11019 			}
11020 			break;
11021 		case KF_ARG_PTR_TO_DYNPTR:
11022 		{
11023 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11024 			int clone_ref_obj_id = 0;
11025 
11026 			if (reg->type != PTR_TO_STACK &&
11027 			    reg->type != CONST_PTR_TO_DYNPTR) {
11028 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11029 				return -EINVAL;
11030 			}
11031 
11032 			if (reg->type == CONST_PTR_TO_DYNPTR)
11033 				dynptr_arg_type |= MEM_RDONLY;
11034 
11035 			if (is_kfunc_arg_uninit(btf, &args[i]))
11036 				dynptr_arg_type |= MEM_UNINIT;
11037 
11038 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11039 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11040 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11041 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11042 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11043 				   (dynptr_arg_type & MEM_UNINIT)) {
11044 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11045 
11046 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11047 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11048 					return -EFAULT;
11049 				}
11050 
11051 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11052 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11053 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11054 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11055 					return -EFAULT;
11056 				}
11057 			}
11058 
11059 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11060 			if (ret < 0)
11061 				return ret;
11062 
11063 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11064 				int id = dynptr_id(env, reg);
11065 
11066 				if (id < 0) {
11067 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11068 					return id;
11069 				}
11070 				meta->initialized_dynptr.id = id;
11071 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11072 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11073 			}
11074 
11075 			break;
11076 		}
11077 		case KF_ARG_PTR_TO_ITER:
11078 			ret = process_iter_arg(env, regno, insn_idx, meta);
11079 			if (ret < 0)
11080 				return ret;
11081 			break;
11082 		case KF_ARG_PTR_TO_LIST_HEAD:
11083 			if (reg->type != PTR_TO_MAP_VALUE &&
11084 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11085 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11086 				return -EINVAL;
11087 			}
11088 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11089 				verbose(env, "allocated object must be referenced\n");
11090 				return -EINVAL;
11091 			}
11092 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11093 			if (ret < 0)
11094 				return ret;
11095 			break;
11096 		case KF_ARG_PTR_TO_RB_ROOT:
11097 			if (reg->type != PTR_TO_MAP_VALUE &&
11098 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11099 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11100 				return -EINVAL;
11101 			}
11102 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11103 				verbose(env, "allocated object must be referenced\n");
11104 				return -EINVAL;
11105 			}
11106 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11107 			if (ret < 0)
11108 				return ret;
11109 			break;
11110 		case KF_ARG_PTR_TO_LIST_NODE:
11111 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11112 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11113 				return -EINVAL;
11114 			}
11115 			if (!reg->ref_obj_id) {
11116 				verbose(env, "allocated object must be referenced\n");
11117 				return -EINVAL;
11118 			}
11119 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11120 			if (ret < 0)
11121 				return ret;
11122 			break;
11123 		case KF_ARG_PTR_TO_RB_NODE:
11124 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11125 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11126 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11127 					return -EINVAL;
11128 				}
11129 				if (in_rbtree_lock_required_cb(env)) {
11130 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11131 					return -EINVAL;
11132 				}
11133 			} else {
11134 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11135 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11136 					return -EINVAL;
11137 				}
11138 				if (!reg->ref_obj_id) {
11139 					verbose(env, "allocated object must be referenced\n");
11140 					return -EINVAL;
11141 				}
11142 			}
11143 
11144 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11145 			if (ret < 0)
11146 				return ret;
11147 			break;
11148 		case KF_ARG_PTR_TO_BTF_ID:
11149 			/* Only base_type is checked, further checks are done here */
11150 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11151 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11152 			    !reg2btf_ids[base_type(reg->type)]) {
11153 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11154 				verbose(env, "expected %s or socket\n",
11155 					reg_type_str(env, base_type(reg->type) |
11156 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11157 				return -EINVAL;
11158 			}
11159 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11160 			if (ret < 0)
11161 				return ret;
11162 			break;
11163 		case KF_ARG_PTR_TO_MEM:
11164 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11165 			if (IS_ERR(resolve_ret)) {
11166 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11167 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11168 				return -EINVAL;
11169 			}
11170 			ret = check_mem_reg(env, reg, regno, type_size);
11171 			if (ret < 0)
11172 				return ret;
11173 			break;
11174 		case KF_ARG_PTR_TO_MEM_SIZE:
11175 		{
11176 			struct bpf_reg_state *buff_reg = &regs[regno];
11177 			const struct btf_param *buff_arg = &args[i];
11178 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11179 			const struct btf_param *size_arg = &args[i + 1];
11180 
11181 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11182 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11183 				if (ret < 0) {
11184 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11185 					return ret;
11186 				}
11187 			}
11188 
11189 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11190 				if (meta->arg_constant.found) {
11191 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11192 					return -EFAULT;
11193 				}
11194 				if (!tnum_is_const(size_reg->var_off)) {
11195 					verbose(env, "R%d must be a known constant\n", regno + 1);
11196 					return -EINVAL;
11197 				}
11198 				meta->arg_constant.found = true;
11199 				meta->arg_constant.value = size_reg->var_off.value;
11200 			}
11201 
11202 			/* Skip next '__sz' or '__szk' argument */
11203 			i++;
11204 			break;
11205 		}
11206 		case KF_ARG_PTR_TO_CALLBACK:
11207 			meta->subprogno = reg->subprogno;
11208 			break;
11209 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11210 			if (!type_is_ptr_alloc_obj(reg->type)) {
11211 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11212 				return -EINVAL;
11213 			}
11214 			if (!type_is_non_owning_ref(reg->type))
11215 				meta->arg_owning_ref = true;
11216 
11217 			rec = reg_btf_record(reg);
11218 			if (!rec) {
11219 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11220 				return -EFAULT;
11221 			}
11222 
11223 			if (rec->refcount_off < 0) {
11224 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11225 				return -EINVAL;
11226 			}
11227 
11228 			meta->arg_btf = reg->btf;
11229 			meta->arg_btf_id = reg->btf_id;
11230 			break;
11231 		}
11232 	}
11233 
11234 	if (is_kfunc_release(meta) && !meta->release_regno) {
11235 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11236 			func_name);
11237 		return -EINVAL;
11238 	}
11239 
11240 	return 0;
11241 }
11242 
11243 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11244 			    struct bpf_insn *insn,
11245 			    struct bpf_kfunc_call_arg_meta *meta,
11246 			    const char **kfunc_name)
11247 {
11248 	const struct btf_type *func, *func_proto;
11249 	u32 func_id, *kfunc_flags;
11250 	const char *func_name;
11251 	struct btf *desc_btf;
11252 
11253 	if (kfunc_name)
11254 		*kfunc_name = NULL;
11255 
11256 	if (!insn->imm)
11257 		return -EINVAL;
11258 
11259 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11260 	if (IS_ERR(desc_btf))
11261 		return PTR_ERR(desc_btf);
11262 
11263 	func_id = insn->imm;
11264 	func = btf_type_by_id(desc_btf, func_id);
11265 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11266 	if (kfunc_name)
11267 		*kfunc_name = func_name;
11268 	func_proto = btf_type_by_id(desc_btf, func->type);
11269 
11270 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11271 	if (!kfunc_flags) {
11272 		return -EACCES;
11273 	}
11274 
11275 	memset(meta, 0, sizeof(*meta));
11276 	meta->btf = desc_btf;
11277 	meta->func_id = func_id;
11278 	meta->kfunc_flags = *kfunc_flags;
11279 	meta->func_proto = func_proto;
11280 	meta->func_name = func_name;
11281 
11282 	return 0;
11283 }
11284 
11285 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11286 			    int *insn_idx_p)
11287 {
11288 	const struct btf_type *t, *ptr_type;
11289 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11290 	struct bpf_reg_state *regs = cur_regs(env);
11291 	const char *func_name, *ptr_type_name;
11292 	bool sleepable, rcu_lock, rcu_unlock;
11293 	struct bpf_kfunc_call_arg_meta meta;
11294 	struct bpf_insn_aux_data *insn_aux;
11295 	int err, insn_idx = *insn_idx_p;
11296 	const struct btf_param *args;
11297 	const struct btf_type *ret_t;
11298 	struct btf *desc_btf;
11299 
11300 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11301 	if (!insn->imm)
11302 		return 0;
11303 
11304 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11305 	if (err == -EACCES && func_name)
11306 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11307 	if (err)
11308 		return err;
11309 	desc_btf = meta.btf;
11310 	insn_aux = &env->insn_aux_data[insn_idx];
11311 
11312 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11313 
11314 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11315 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11316 		return -EACCES;
11317 	}
11318 
11319 	sleepable = is_kfunc_sleepable(&meta);
11320 	if (sleepable && !env->prog->aux->sleepable) {
11321 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11322 		return -EACCES;
11323 	}
11324 
11325 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11326 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11327 
11328 	if (env->cur_state->active_rcu_lock) {
11329 		struct bpf_func_state *state;
11330 		struct bpf_reg_state *reg;
11331 
11332 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11333 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11334 			return -EACCES;
11335 		}
11336 
11337 		if (rcu_lock) {
11338 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11339 			return -EINVAL;
11340 		} else if (rcu_unlock) {
11341 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11342 				if (reg->type & MEM_RCU) {
11343 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11344 					reg->type |= PTR_UNTRUSTED;
11345 				}
11346 			}));
11347 			env->cur_state->active_rcu_lock = false;
11348 		} else if (sleepable) {
11349 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11350 			return -EACCES;
11351 		}
11352 	} else if (rcu_lock) {
11353 		env->cur_state->active_rcu_lock = true;
11354 	} else if (rcu_unlock) {
11355 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11356 		return -EINVAL;
11357 	}
11358 
11359 	/* Check the arguments */
11360 	err = check_kfunc_args(env, &meta, insn_idx);
11361 	if (err < 0)
11362 		return err;
11363 	/* In case of release function, we get register number of refcounted
11364 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11365 	 */
11366 	if (meta.release_regno) {
11367 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11368 		if (err) {
11369 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11370 				func_name, meta.func_id);
11371 			return err;
11372 		}
11373 	}
11374 
11375 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11376 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11377 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11378 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11379 		insn_aux->insert_off = regs[BPF_REG_2].off;
11380 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11381 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11382 		if (err) {
11383 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11384 				func_name, meta.func_id);
11385 			return err;
11386 		}
11387 
11388 		err = release_reference(env, release_ref_obj_id);
11389 		if (err) {
11390 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11391 				func_name, meta.func_id);
11392 			return err;
11393 		}
11394 	}
11395 
11396 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11397 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11398 					set_rbtree_add_callback_state);
11399 		if (err) {
11400 			verbose(env, "kfunc %s#%d failed callback verification\n",
11401 				func_name, meta.func_id);
11402 			return err;
11403 		}
11404 	}
11405 
11406 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11407 		mark_reg_not_init(env, regs, caller_saved[i]);
11408 
11409 	/* Check return type */
11410 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11411 
11412 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11413 		/* Only exception is bpf_obj_new_impl */
11414 		if (meta.btf != btf_vmlinux ||
11415 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11416 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11417 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11418 			return -EINVAL;
11419 		}
11420 	}
11421 
11422 	if (btf_type_is_scalar(t)) {
11423 		mark_reg_unknown(env, regs, BPF_REG_0);
11424 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11425 	} else if (btf_type_is_ptr(t)) {
11426 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11427 
11428 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11429 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11430 				struct btf *ret_btf;
11431 				u32 ret_btf_id;
11432 
11433 				if (unlikely(!bpf_global_ma_set))
11434 					return -ENOMEM;
11435 
11436 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11437 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11438 					return -EINVAL;
11439 				}
11440 
11441 				ret_btf = env->prog->aux->btf;
11442 				ret_btf_id = meta.arg_constant.value;
11443 
11444 				/* This may be NULL due to user not supplying a BTF */
11445 				if (!ret_btf) {
11446 					verbose(env, "bpf_obj_new requires prog BTF\n");
11447 					return -EINVAL;
11448 				}
11449 
11450 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11451 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11452 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11453 					return -EINVAL;
11454 				}
11455 
11456 				mark_reg_known_zero(env, regs, BPF_REG_0);
11457 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11458 				regs[BPF_REG_0].btf = ret_btf;
11459 				regs[BPF_REG_0].btf_id = ret_btf_id;
11460 
11461 				insn_aux->obj_new_size = ret_t->size;
11462 				insn_aux->kptr_struct_meta =
11463 					btf_find_struct_meta(ret_btf, ret_btf_id);
11464 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11465 				mark_reg_known_zero(env, regs, BPF_REG_0);
11466 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11467 				regs[BPF_REG_0].btf = meta.arg_btf;
11468 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11469 
11470 				insn_aux->kptr_struct_meta =
11471 					btf_find_struct_meta(meta.arg_btf,
11472 							     meta.arg_btf_id);
11473 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11474 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11475 				struct btf_field *field = meta.arg_list_head.field;
11476 
11477 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11478 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11479 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11480 				struct btf_field *field = meta.arg_rbtree_root.field;
11481 
11482 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11483 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11484 				mark_reg_known_zero(env, regs, BPF_REG_0);
11485 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11486 				regs[BPF_REG_0].btf = desc_btf;
11487 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11488 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11489 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11490 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11491 					verbose(env,
11492 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11493 					return -EINVAL;
11494 				}
11495 
11496 				mark_reg_known_zero(env, regs, BPF_REG_0);
11497 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11498 				regs[BPF_REG_0].btf = desc_btf;
11499 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11500 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11501 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11502 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11503 
11504 				mark_reg_known_zero(env, regs, BPF_REG_0);
11505 
11506 				if (!meta.arg_constant.found) {
11507 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11508 					return -EFAULT;
11509 				}
11510 
11511 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11512 
11513 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11514 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11515 
11516 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11517 					regs[BPF_REG_0].type |= MEM_RDONLY;
11518 				} else {
11519 					/* this will set env->seen_direct_write to true */
11520 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11521 						verbose(env, "the prog does not allow writes to packet data\n");
11522 						return -EINVAL;
11523 					}
11524 				}
11525 
11526 				if (!meta.initialized_dynptr.id) {
11527 					verbose(env, "verifier internal error: no dynptr id\n");
11528 					return -EFAULT;
11529 				}
11530 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11531 
11532 				/* we don't need to set BPF_REG_0's ref obj id
11533 				 * because packet slices are not refcounted (see
11534 				 * dynptr_type_refcounted)
11535 				 */
11536 			} else {
11537 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11538 					meta.func_name);
11539 				return -EFAULT;
11540 			}
11541 		} else if (!__btf_type_is_struct(ptr_type)) {
11542 			if (!meta.r0_size) {
11543 				__u32 sz;
11544 
11545 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11546 					meta.r0_size = sz;
11547 					meta.r0_rdonly = true;
11548 				}
11549 			}
11550 			if (!meta.r0_size) {
11551 				ptr_type_name = btf_name_by_offset(desc_btf,
11552 								   ptr_type->name_off);
11553 				verbose(env,
11554 					"kernel function %s returns pointer type %s %s is not supported\n",
11555 					func_name,
11556 					btf_type_str(ptr_type),
11557 					ptr_type_name);
11558 				return -EINVAL;
11559 			}
11560 
11561 			mark_reg_known_zero(env, regs, BPF_REG_0);
11562 			regs[BPF_REG_0].type = PTR_TO_MEM;
11563 			regs[BPF_REG_0].mem_size = meta.r0_size;
11564 
11565 			if (meta.r0_rdonly)
11566 				regs[BPF_REG_0].type |= MEM_RDONLY;
11567 
11568 			/* Ensures we don't access the memory after a release_reference() */
11569 			if (meta.ref_obj_id)
11570 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11571 		} else {
11572 			mark_reg_known_zero(env, regs, BPF_REG_0);
11573 			regs[BPF_REG_0].btf = desc_btf;
11574 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11575 			regs[BPF_REG_0].btf_id = ptr_type_id;
11576 		}
11577 
11578 		if (is_kfunc_ret_null(&meta)) {
11579 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11580 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11581 			regs[BPF_REG_0].id = ++env->id_gen;
11582 		}
11583 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11584 		if (is_kfunc_acquire(&meta)) {
11585 			int id = acquire_reference_state(env, insn_idx);
11586 
11587 			if (id < 0)
11588 				return id;
11589 			if (is_kfunc_ret_null(&meta))
11590 				regs[BPF_REG_0].id = id;
11591 			regs[BPF_REG_0].ref_obj_id = id;
11592 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11593 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11594 		}
11595 
11596 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11597 			regs[BPF_REG_0].id = ++env->id_gen;
11598 	} else if (btf_type_is_void(t)) {
11599 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11600 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11601 				insn_aux->kptr_struct_meta =
11602 					btf_find_struct_meta(meta.arg_btf,
11603 							     meta.arg_btf_id);
11604 			}
11605 		}
11606 	}
11607 
11608 	nargs = btf_type_vlen(meta.func_proto);
11609 	args = (const struct btf_param *)(meta.func_proto + 1);
11610 	for (i = 0; i < nargs; i++) {
11611 		u32 regno = i + 1;
11612 
11613 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11614 		if (btf_type_is_ptr(t))
11615 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11616 		else
11617 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11618 			mark_btf_func_reg_size(env, regno, t->size);
11619 	}
11620 
11621 	if (is_iter_next_kfunc(&meta)) {
11622 		err = process_iter_next_call(env, insn_idx, &meta);
11623 		if (err)
11624 			return err;
11625 	}
11626 
11627 	return 0;
11628 }
11629 
11630 static bool signed_add_overflows(s64 a, s64 b)
11631 {
11632 	/* Do the add in u64, where overflow is well-defined */
11633 	s64 res = (s64)((u64)a + (u64)b);
11634 
11635 	if (b < 0)
11636 		return res > a;
11637 	return res < a;
11638 }
11639 
11640 static bool signed_add32_overflows(s32 a, s32 b)
11641 {
11642 	/* Do the add in u32, where overflow is well-defined */
11643 	s32 res = (s32)((u32)a + (u32)b);
11644 
11645 	if (b < 0)
11646 		return res > a;
11647 	return res < a;
11648 }
11649 
11650 static bool signed_sub_overflows(s64 a, s64 b)
11651 {
11652 	/* Do the sub in u64, where overflow is well-defined */
11653 	s64 res = (s64)((u64)a - (u64)b);
11654 
11655 	if (b < 0)
11656 		return res < a;
11657 	return res > a;
11658 }
11659 
11660 static bool signed_sub32_overflows(s32 a, s32 b)
11661 {
11662 	/* Do the sub in u32, where overflow is well-defined */
11663 	s32 res = (s32)((u32)a - (u32)b);
11664 
11665 	if (b < 0)
11666 		return res < a;
11667 	return res > a;
11668 }
11669 
11670 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11671 				  const struct bpf_reg_state *reg,
11672 				  enum bpf_reg_type type)
11673 {
11674 	bool known = tnum_is_const(reg->var_off);
11675 	s64 val = reg->var_off.value;
11676 	s64 smin = reg->smin_value;
11677 
11678 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11679 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11680 			reg_type_str(env, type), val);
11681 		return false;
11682 	}
11683 
11684 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11685 		verbose(env, "%s pointer offset %d is not allowed\n",
11686 			reg_type_str(env, type), reg->off);
11687 		return false;
11688 	}
11689 
11690 	if (smin == S64_MIN) {
11691 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11692 			reg_type_str(env, type));
11693 		return false;
11694 	}
11695 
11696 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11697 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11698 			smin, reg_type_str(env, type));
11699 		return false;
11700 	}
11701 
11702 	return true;
11703 }
11704 
11705 enum {
11706 	REASON_BOUNDS	= -1,
11707 	REASON_TYPE	= -2,
11708 	REASON_PATHS	= -3,
11709 	REASON_LIMIT	= -4,
11710 	REASON_STACK	= -5,
11711 };
11712 
11713 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11714 			      u32 *alu_limit, bool mask_to_left)
11715 {
11716 	u32 max = 0, ptr_limit = 0;
11717 
11718 	switch (ptr_reg->type) {
11719 	case PTR_TO_STACK:
11720 		/* Offset 0 is out-of-bounds, but acceptable start for the
11721 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11722 		 * offset where we would need to deal with min/max bounds is
11723 		 * currently prohibited for unprivileged.
11724 		 */
11725 		max = MAX_BPF_STACK + mask_to_left;
11726 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11727 		break;
11728 	case PTR_TO_MAP_VALUE:
11729 		max = ptr_reg->map_ptr->value_size;
11730 		ptr_limit = (mask_to_left ?
11731 			     ptr_reg->smin_value :
11732 			     ptr_reg->umax_value) + ptr_reg->off;
11733 		break;
11734 	default:
11735 		return REASON_TYPE;
11736 	}
11737 
11738 	if (ptr_limit >= max)
11739 		return REASON_LIMIT;
11740 	*alu_limit = ptr_limit;
11741 	return 0;
11742 }
11743 
11744 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11745 				    const struct bpf_insn *insn)
11746 {
11747 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11748 }
11749 
11750 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11751 				       u32 alu_state, u32 alu_limit)
11752 {
11753 	/* If we arrived here from different branches with different
11754 	 * state or limits to sanitize, then this won't work.
11755 	 */
11756 	if (aux->alu_state &&
11757 	    (aux->alu_state != alu_state ||
11758 	     aux->alu_limit != alu_limit))
11759 		return REASON_PATHS;
11760 
11761 	/* Corresponding fixup done in do_misc_fixups(). */
11762 	aux->alu_state = alu_state;
11763 	aux->alu_limit = alu_limit;
11764 	return 0;
11765 }
11766 
11767 static int sanitize_val_alu(struct bpf_verifier_env *env,
11768 			    struct bpf_insn *insn)
11769 {
11770 	struct bpf_insn_aux_data *aux = cur_aux(env);
11771 
11772 	if (can_skip_alu_sanitation(env, insn))
11773 		return 0;
11774 
11775 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11776 }
11777 
11778 static bool sanitize_needed(u8 opcode)
11779 {
11780 	return opcode == BPF_ADD || opcode == BPF_SUB;
11781 }
11782 
11783 struct bpf_sanitize_info {
11784 	struct bpf_insn_aux_data aux;
11785 	bool mask_to_left;
11786 };
11787 
11788 static struct bpf_verifier_state *
11789 sanitize_speculative_path(struct bpf_verifier_env *env,
11790 			  const struct bpf_insn *insn,
11791 			  u32 next_idx, u32 curr_idx)
11792 {
11793 	struct bpf_verifier_state *branch;
11794 	struct bpf_reg_state *regs;
11795 
11796 	branch = push_stack(env, next_idx, curr_idx, true);
11797 	if (branch && insn) {
11798 		regs = branch->frame[branch->curframe]->regs;
11799 		if (BPF_SRC(insn->code) == BPF_K) {
11800 			mark_reg_unknown(env, regs, insn->dst_reg);
11801 		} else if (BPF_SRC(insn->code) == BPF_X) {
11802 			mark_reg_unknown(env, regs, insn->dst_reg);
11803 			mark_reg_unknown(env, regs, insn->src_reg);
11804 		}
11805 	}
11806 	return branch;
11807 }
11808 
11809 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11810 			    struct bpf_insn *insn,
11811 			    const struct bpf_reg_state *ptr_reg,
11812 			    const struct bpf_reg_state *off_reg,
11813 			    struct bpf_reg_state *dst_reg,
11814 			    struct bpf_sanitize_info *info,
11815 			    const bool commit_window)
11816 {
11817 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11818 	struct bpf_verifier_state *vstate = env->cur_state;
11819 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11820 	bool off_is_neg = off_reg->smin_value < 0;
11821 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11822 	u8 opcode = BPF_OP(insn->code);
11823 	u32 alu_state, alu_limit;
11824 	struct bpf_reg_state tmp;
11825 	bool ret;
11826 	int err;
11827 
11828 	if (can_skip_alu_sanitation(env, insn))
11829 		return 0;
11830 
11831 	/* We already marked aux for masking from non-speculative
11832 	 * paths, thus we got here in the first place. We only care
11833 	 * to explore bad access from here.
11834 	 */
11835 	if (vstate->speculative)
11836 		goto do_sim;
11837 
11838 	if (!commit_window) {
11839 		if (!tnum_is_const(off_reg->var_off) &&
11840 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11841 			return REASON_BOUNDS;
11842 
11843 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11844 				     (opcode == BPF_SUB && !off_is_neg);
11845 	}
11846 
11847 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11848 	if (err < 0)
11849 		return err;
11850 
11851 	if (commit_window) {
11852 		/* In commit phase we narrow the masking window based on
11853 		 * the observed pointer move after the simulated operation.
11854 		 */
11855 		alu_state = info->aux.alu_state;
11856 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11857 	} else {
11858 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11859 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11860 		alu_state |= ptr_is_dst_reg ?
11861 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11862 
11863 		/* Limit pruning on unknown scalars to enable deep search for
11864 		 * potential masking differences from other program paths.
11865 		 */
11866 		if (!off_is_imm)
11867 			env->explore_alu_limits = true;
11868 	}
11869 
11870 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11871 	if (err < 0)
11872 		return err;
11873 do_sim:
11874 	/* If we're in commit phase, we're done here given we already
11875 	 * pushed the truncated dst_reg into the speculative verification
11876 	 * stack.
11877 	 *
11878 	 * Also, when register is a known constant, we rewrite register-based
11879 	 * operation to immediate-based, and thus do not need masking (and as
11880 	 * a consequence, do not need to simulate the zero-truncation either).
11881 	 */
11882 	if (commit_window || off_is_imm)
11883 		return 0;
11884 
11885 	/* Simulate and find potential out-of-bounds access under
11886 	 * speculative execution from truncation as a result of
11887 	 * masking when off was not within expected range. If off
11888 	 * sits in dst, then we temporarily need to move ptr there
11889 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11890 	 * for cases where we use K-based arithmetic in one direction
11891 	 * and truncated reg-based in the other in order to explore
11892 	 * bad access.
11893 	 */
11894 	if (!ptr_is_dst_reg) {
11895 		tmp = *dst_reg;
11896 		copy_register_state(dst_reg, ptr_reg);
11897 	}
11898 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11899 					env->insn_idx);
11900 	if (!ptr_is_dst_reg && ret)
11901 		*dst_reg = tmp;
11902 	return !ret ? REASON_STACK : 0;
11903 }
11904 
11905 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11906 {
11907 	struct bpf_verifier_state *vstate = env->cur_state;
11908 
11909 	/* If we simulate paths under speculation, we don't update the
11910 	 * insn as 'seen' such that when we verify unreachable paths in
11911 	 * the non-speculative domain, sanitize_dead_code() can still
11912 	 * rewrite/sanitize them.
11913 	 */
11914 	if (!vstate->speculative)
11915 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11916 }
11917 
11918 static int sanitize_err(struct bpf_verifier_env *env,
11919 			const struct bpf_insn *insn, int reason,
11920 			const struct bpf_reg_state *off_reg,
11921 			const struct bpf_reg_state *dst_reg)
11922 {
11923 	static const char *err = "pointer arithmetic with it prohibited for !root";
11924 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11925 	u32 dst = insn->dst_reg, src = insn->src_reg;
11926 
11927 	switch (reason) {
11928 	case REASON_BOUNDS:
11929 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11930 			off_reg == dst_reg ? dst : src, err);
11931 		break;
11932 	case REASON_TYPE:
11933 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11934 			off_reg == dst_reg ? src : dst, err);
11935 		break;
11936 	case REASON_PATHS:
11937 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11938 			dst, op, err);
11939 		break;
11940 	case REASON_LIMIT:
11941 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11942 			dst, op, err);
11943 		break;
11944 	case REASON_STACK:
11945 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11946 			dst, err);
11947 		break;
11948 	default:
11949 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11950 			reason);
11951 		break;
11952 	}
11953 
11954 	return -EACCES;
11955 }
11956 
11957 /* check that stack access falls within stack limits and that 'reg' doesn't
11958  * have a variable offset.
11959  *
11960  * Variable offset is prohibited for unprivileged mode for simplicity since it
11961  * requires corresponding support in Spectre masking for stack ALU.  See also
11962  * retrieve_ptr_limit().
11963  *
11964  *
11965  * 'off' includes 'reg->off'.
11966  */
11967 static int check_stack_access_for_ptr_arithmetic(
11968 				struct bpf_verifier_env *env,
11969 				int regno,
11970 				const struct bpf_reg_state *reg,
11971 				int off)
11972 {
11973 	if (!tnum_is_const(reg->var_off)) {
11974 		char tn_buf[48];
11975 
11976 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11977 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11978 			regno, tn_buf, off);
11979 		return -EACCES;
11980 	}
11981 
11982 	if (off >= 0 || off < -MAX_BPF_STACK) {
11983 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11984 			"prohibited for !root; off=%d\n", regno, off);
11985 		return -EACCES;
11986 	}
11987 
11988 	return 0;
11989 }
11990 
11991 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11992 				 const struct bpf_insn *insn,
11993 				 const struct bpf_reg_state *dst_reg)
11994 {
11995 	u32 dst = insn->dst_reg;
11996 
11997 	/* For unprivileged we require that resulting offset must be in bounds
11998 	 * in order to be able to sanitize access later on.
11999 	 */
12000 	if (env->bypass_spec_v1)
12001 		return 0;
12002 
12003 	switch (dst_reg->type) {
12004 	case PTR_TO_STACK:
12005 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12006 					dst_reg->off + dst_reg->var_off.value))
12007 			return -EACCES;
12008 		break;
12009 	case PTR_TO_MAP_VALUE:
12010 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12011 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12012 				"prohibited for !root\n", dst);
12013 			return -EACCES;
12014 		}
12015 		break;
12016 	default:
12017 		break;
12018 	}
12019 
12020 	return 0;
12021 }
12022 
12023 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12024  * Caller should also handle BPF_MOV case separately.
12025  * If we return -EACCES, caller may want to try again treating pointer as a
12026  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12027  */
12028 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12029 				   struct bpf_insn *insn,
12030 				   const struct bpf_reg_state *ptr_reg,
12031 				   const struct bpf_reg_state *off_reg)
12032 {
12033 	struct bpf_verifier_state *vstate = env->cur_state;
12034 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12035 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12036 	bool known = tnum_is_const(off_reg->var_off);
12037 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12038 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12039 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12040 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12041 	struct bpf_sanitize_info info = {};
12042 	u8 opcode = BPF_OP(insn->code);
12043 	u32 dst = insn->dst_reg;
12044 	int ret;
12045 
12046 	dst_reg = &regs[dst];
12047 
12048 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12049 	    smin_val > smax_val || umin_val > umax_val) {
12050 		/* Taint dst register if offset had invalid bounds derived from
12051 		 * e.g. dead branches.
12052 		 */
12053 		__mark_reg_unknown(env, dst_reg);
12054 		return 0;
12055 	}
12056 
12057 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12058 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12059 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12060 			__mark_reg_unknown(env, dst_reg);
12061 			return 0;
12062 		}
12063 
12064 		verbose(env,
12065 			"R%d 32-bit pointer arithmetic prohibited\n",
12066 			dst);
12067 		return -EACCES;
12068 	}
12069 
12070 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12071 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12072 			dst, reg_type_str(env, ptr_reg->type));
12073 		return -EACCES;
12074 	}
12075 
12076 	switch (base_type(ptr_reg->type)) {
12077 	case CONST_PTR_TO_MAP:
12078 		/* smin_val represents the known value */
12079 		if (known && smin_val == 0 && opcode == BPF_ADD)
12080 			break;
12081 		fallthrough;
12082 	case PTR_TO_PACKET_END:
12083 	case PTR_TO_SOCKET:
12084 	case PTR_TO_SOCK_COMMON:
12085 	case PTR_TO_TCP_SOCK:
12086 	case PTR_TO_XDP_SOCK:
12087 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12088 			dst, reg_type_str(env, ptr_reg->type));
12089 		return -EACCES;
12090 	default:
12091 		break;
12092 	}
12093 
12094 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12095 	 * The id may be overwritten later if we create a new variable offset.
12096 	 */
12097 	dst_reg->type = ptr_reg->type;
12098 	dst_reg->id = ptr_reg->id;
12099 
12100 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12101 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12102 		return -EINVAL;
12103 
12104 	/* pointer types do not carry 32-bit bounds at the moment. */
12105 	__mark_reg32_unbounded(dst_reg);
12106 
12107 	if (sanitize_needed(opcode)) {
12108 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12109 				       &info, false);
12110 		if (ret < 0)
12111 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12112 	}
12113 
12114 	switch (opcode) {
12115 	case BPF_ADD:
12116 		/* We can take a fixed offset as long as it doesn't overflow
12117 		 * the s32 'off' field
12118 		 */
12119 		if (known && (ptr_reg->off + smin_val ==
12120 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12121 			/* pointer += K.  Accumulate it into fixed offset */
12122 			dst_reg->smin_value = smin_ptr;
12123 			dst_reg->smax_value = smax_ptr;
12124 			dst_reg->umin_value = umin_ptr;
12125 			dst_reg->umax_value = umax_ptr;
12126 			dst_reg->var_off = ptr_reg->var_off;
12127 			dst_reg->off = ptr_reg->off + smin_val;
12128 			dst_reg->raw = ptr_reg->raw;
12129 			break;
12130 		}
12131 		/* A new variable offset is created.  Note that off_reg->off
12132 		 * == 0, since it's a scalar.
12133 		 * dst_reg gets the pointer type and since some positive
12134 		 * integer value was added to the pointer, give it a new 'id'
12135 		 * if it's a PTR_TO_PACKET.
12136 		 * this creates a new 'base' pointer, off_reg (variable) gets
12137 		 * added into the variable offset, and we copy the fixed offset
12138 		 * from ptr_reg.
12139 		 */
12140 		if (signed_add_overflows(smin_ptr, smin_val) ||
12141 		    signed_add_overflows(smax_ptr, smax_val)) {
12142 			dst_reg->smin_value = S64_MIN;
12143 			dst_reg->smax_value = S64_MAX;
12144 		} else {
12145 			dst_reg->smin_value = smin_ptr + smin_val;
12146 			dst_reg->smax_value = smax_ptr + smax_val;
12147 		}
12148 		if (umin_ptr + umin_val < umin_ptr ||
12149 		    umax_ptr + umax_val < umax_ptr) {
12150 			dst_reg->umin_value = 0;
12151 			dst_reg->umax_value = U64_MAX;
12152 		} else {
12153 			dst_reg->umin_value = umin_ptr + umin_val;
12154 			dst_reg->umax_value = umax_ptr + umax_val;
12155 		}
12156 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12157 		dst_reg->off = ptr_reg->off;
12158 		dst_reg->raw = ptr_reg->raw;
12159 		if (reg_is_pkt_pointer(ptr_reg)) {
12160 			dst_reg->id = ++env->id_gen;
12161 			/* something was added to pkt_ptr, set range to zero */
12162 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12163 		}
12164 		break;
12165 	case BPF_SUB:
12166 		if (dst_reg == off_reg) {
12167 			/* scalar -= pointer.  Creates an unknown scalar */
12168 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12169 				dst);
12170 			return -EACCES;
12171 		}
12172 		/* We don't allow subtraction from FP, because (according to
12173 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12174 		 * be able to deal with it.
12175 		 */
12176 		if (ptr_reg->type == PTR_TO_STACK) {
12177 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12178 				dst);
12179 			return -EACCES;
12180 		}
12181 		if (known && (ptr_reg->off - smin_val ==
12182 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12183 			/* pointer -= K.  Subtract it from fixed offset */
12184 			dst_reg->smin_value = smin_ptr;
12185 			dst_reg->smax_value = smax_ptr;
12186 			dst_reg->umin_value = umin_ptr;
12187 			dst_reg->umax_value = umax_ptr;
12188 			dst_reg->var_off = ptr_reg->var_off;
12189 			dst_reg->id = ptr_reg->id;
12190 			dst_reg->off = ptr_reg->off - smin_val;
12191 			dst_reg->raw = ptr_reg->raw;
12192 			break;
12193 		}
12194 		/* A new variable offset is created.  If the subtrahend is known
12195 		 * nonnegative, then any reg->range we had before is still good.
12196 		 */
12197 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12198 		    signed_sub_overflows(smax_ptr, smin_val)) {
12199 			/* Overflow possible, we know nothing */
12200 			dst_reg->smin_value = S64_MIN;
12201 			dst_reg->smax_value = S64_MAX;
12202 		} else {
12203 			dst_reg->smin_value = smin_ptr - smax_val;
12204 			dst_reg->smax_value = smax_ptr - smin_val;
12205 		}
12206 		if (umin_ptr < umax_val) {
12207 			/* Overflow possible, we know nothing */
12208 			dst_reg->umin_value = 0;
12209 			dst_reg->umax_value = U64_MAX;
12210 		} else {
12211 			/* Cannot overflow (as long as bounds are consistent) */
12212 			dst_reg->umin_value = umin_ptr - umax_val;
12213 			dst_reg->umax_value = umax_ptr - umin_val;
12214 		}
12215 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12216 		dst_reg->off = ptr_reg->off;
12217 		dst_reg->raw = ptr_reg->raw;
12218 		if (reg_is_pkt_pointer(ptr_reg)) {
12219 			dst_reg->id = ++env->id_gen;
12220 			/* something was added to pkt_ptr, set range to zero */
12221 			if (smin_val < 0)
12222 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12223 		}
12224 		break;
12225 	case BPF_AND:
12226 	case BPF_OR:
12227 	case BPF_XOR:
12228 		/* bitwise ops on pointers are troublesome, prohibit. */
12229 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12230 			dst, bpf_alu_string[opcode >> 4]);
12231 		return -EACCES;
12232 	default:
12233 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12234 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12235 			dst, bpf_alu_string[opcode >> 4]);
12236 		return -EACCES;
12237 	}
12238 
12239 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12240 		return -EINVAL;
12241 	reg_bounds_sync(dst_reg);
12242 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12243 		return -EACCES;
12244 	if (sanitize_needed(opcode)) {
12245 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12246 				       &info, true);
12247 		if (ret < 0)
12248 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12249 	}
12250 
12251 	return 0;
12252 }
12253 
12254 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12255 				 struct bpf_reg_state *src_reg)
12256 {
12257 	s32 smin_val = src_reg->s32_min_value;
12258 	s32 smax_val = src_reg->s32_max_value;
12259 	u32 umin_val = src_reg->u32_min_value;
12260 	u32 umax_val = src_reg->u32_max_value;
12261 
12262 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12263 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12264 		dst_reg->s32_min_value = S32_MIN;
12265 		dst_reg->s32_max_value = S32_MAX;
12266 	} else {
12267 		dst_reg->s32_min_value += smin_val;
12268 		dst_reg->s32_max_value += smax_val;
12269 	}
12270 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12271 	    dst_reg->u32_max_value + umax_val < umax_val) {
12272 		dst_reg->u32_min_value = 0;
12273 		dst_reg->u32_max_value = U32_MAX;
12274 	} else {
12275 		dst_reg->u32_min_value += umin_val;
12276 		dst_reg->u32_max_value += umax_val;
12277 	}
12278 }
12279 
12280 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12281 			       struct bpf_reg_state *src_reg)
12282 {
12283 	s64 smin_val = src_reg->smin_value;
12284 	s64 smax_val = src_reg->smax_value;
12285 	u64 umin_val = src_reg->umin_value;
12286 	u64 umax_val = src_reg->umax_value;
12287 
12288 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12289 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12290 		dst_reg->smin_value = S64_MIN;
12291 		dst_reg->smax_value = S64_MAX;
12292 	} else {
12293 		dst_reg->smin_value += smin_val;
12294 		dst_reg->smax_value += smax_val;
12295 	}
12296 	if (dst_reg->umin_value + umin_val < umin_val ||
12297 	    dst_reg->umax_value + umax_val < umax_val) {
12298 		dst_reg->umin_value = 0;
12299 		dst_reg->umax_value = U64_MAX;
12300 	} else {
12301 		dst_reg->umin_value += umin_val;
12302 		dst_reg->umax_value += umax_val;
12303 	}
12304 }
12305 
12306 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12307 				 struct bpf_reg_state *src_reg)
12308 {
12309 	s32 smin_val = src_reg->s32_min_value;
12310 	s32 smax_val = src_reg->s32_max_value;
12311 	u32 umin_val = src_reg->u32_min_value;
12312 	u32 umax_val = src_reg->u32_max_value;
12313 
12314 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12315 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12316 		/* Overflow possible, we know nothing */
12317 		dst_reg->s32_min_value = S32_MIN;
12318 		dst_reg->s32_max_value = S32_MAX;
12319 	} else {
12320 		dst_reg->s32_min_value -= smax_val;
12321 		dst_reg->s32_max_value -= smin_val;
12322 	}
12323 	if (dst_reg->u32_min_value < umax_val) {
12324 		/* Overflow possible, we know nothing */
12325 		dst_reg->u32_min_value = 0;
12326 		dst_reg->u32_max_value = U32_MAX;
12327 	} else {
12328 		/* Cannot overflow (as long as bounds are consistent) */
12329 		dst_reg->u32_min_value -= umax_val;
12330 		dst_reg->u32_max_value -= umin_val;
12331 	}
12332 }
12333 
12334 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12335 			       struct bpf_reg_state *src_reg)
12336 {
12337 	s64 smin_val = src_reg->smin_value;
12338 	s64 smax_val = src_reg->smax_value;
12339 	u64 umin_val = src_reg->umin_value;
12340 	u64 umax_val = src_reg->umax_value;
12341 
12342 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12343 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12344 		/* Overflow possible, we know nothing */
12345 		dst_reg->smin_value = S64_MIN;
12346 		dst_reg->smax_value = S64_MAX;
12347 	} else {
12348 		dst_reg->smin_value -= smax_val;
12349 		dst_reg->smax_value -= smin_val;
12350 	}
12351 	if (dst_reg->umin_value < umax_val) {
12352 		/* Overflow possible, we know nothing */
12353 		dst_reg->umin_value = 0;
12354 		dst_reg->umax_value = U64_MAX;
12355 	} else {
12356 		/* Cannot overflow (as long as bounds are consistent) */
12357 		dst_reg->umin_value -= umax_val;
12358 		dst_reg->umax_value -= umin_val;
12359 	}
12360 }
12361 
12362 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12363 				 struct bpf_reg_state *src_reg)
12364 {
12365 	s32 smin_val = src_reg->s32_min_value;
12366 	u32 umin_val = src_reg->u32_min_value;
12367 	u32 umax_val = src_reg->u32_max_value;
12368 
12369 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12370 		/* Ain't nobody got time to multiply that sign */
12371 		__mark_reg32_unbounded(dst_reg);
12372 		return;
12373 	}
12374 	/* Both values are positive, so we can work with unsigned and
12375 	 * copy the result to signed (unless it exceeds S32_MAX).
12376 	 */
12377 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12378 		/* Potential overflow, we know nothing */
12379 		__mark_reg32_unbounded(dst_reg);
12380 		return;
12381 	}
12382 	dst_reg->u32_min_value *= umin_val;
12383 	dst_reg->u32_max_value *= umax_val;
12384 	if (dst_reg->u32_max_value > S32_MAX) {
12385 		/* Overflow possible, we know nothing */
12386 		dst_reg->s32_min_value = S32_MIN;
12387 		dst_reg->s32_max_value = S32_MAX;
12388 	} else {
12389 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12390 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12391 	}
12392 }
12393 
12394 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12395 			       struct bpf_reg_state *src_reg)
12396 {
12397 	s64 smin_val = src_reg->smin_value;
12398 	u64 umin_val = src_reg->umin_value;
12399 	u64 umax_val = src_reg->umax_value;
12400 
12401 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12402 		/* Ain't nobody got time to multiply that sign */
12403 		__mark_reg64_unbounded(dst_reg);
12404 		return;
12405 	}
12406 	/* Both values are positive, so we can work with unsigned and
12407 	 * copy the result to signed (unless it exceeds S64_MAX).
12408 	 */
12409 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12410 		/* Potential overflow, we know nothing */
12411 		__mark_reg64_unbounded(dst_reg);
12412 		return;
12413 	}
12414 	dst_reg->umin_value *= umin_val;
12415 	dst_reg->umax_value *= umax_val;
12416 	if (dst_reg->umax_value > S64_MAX) {
12417 		/* Overflow possible, we know nothing */
12418 		dst_reg->smin_value = S64_MIN;
12419 		dst_reg->smax_value = S64_MAX;
12420 	} else {
12421 		dst_reg->smin_value = dst_reg->umin_value;
12422 		dst_reg->smax_value = dst_reg->umax_value;
12423 	}
12424 }
12425 
12426 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12427 				 struct bpf_reg_state *src_reg)
12428 {
12429 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12430 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12431 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12432 	s32 smin_val = src_reg->s32_min_value;
12433 	u32 umax_val = src_reg->u32_max_value;
12434 
12435 	if (src_known && dst_known) {
12436 		__mark_reg32_known(dst_reg, var32_off.value);
12437 		return;
12438 	}
12439 
12440 	/* We get our minimum from the var_off, since that's inherently
12441 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12442 	 */
12443 	dst_reg->u32_min_value = var32_off.value;
12444 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12445 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12446 		/* Lose signed bounds when ANDing negative numbers,
12447 		 * ain't nobody got time for that.
12448 		 */
12449 		dst_reg->s32_min_value = S32_MIN;
12450 		dst_reg->s32_max_value = S32_MAX;
12451 	} else {
12452 		/* ANDing two positives gives a positive, so safe to
12453 		 * cast result into s64.
12454 		 */
12455 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12456 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12457 	}
12458 }
12459 
12460 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12461 			       struct bpf_reg_state *src_reg)
12462 {
12463 	bool src_known = tnum_is_const(src_reg->var_off);
12464 	bool dst_known = tnum_is_const(dst_reg->var_off);
12465 	s64 smin_val = src_reg->smin_value;
12466 	u64 umax_val = src_reg->umax_value;
12467 
12468 	if (src_known && dst_known) {
12469 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12470 		return;
12471 	}
12472 
12473 	/* We get our minimum from the var_off, since that's inherently
12474 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12475 	 */
12476 	dst_reg->umin_value = dst_reg->var_off.value;
12477 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12478 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12479 		/* Lose signed bounds when ANDing negative numbers,
12480 		 * ain't nobody got time for that.
12481 		 */
12482 		dst_reg->smin_value = S64_MIN;
12483 		dst_reg->smax_value = S64_MAX;
12484 	} else {
12485 		/* ANDing two positives gives a positive, so safe to
12486 		 * cast result into s64.
12487 		 */
12488 		dst_reg->smin_value = dst_reg->umin_value;
12489 		dst_reg->smax_value = dst_reg->umax_value;
12490 	}
12491 	/* We may learn something more from the var_off */
12492 	__update_reg_bounds(dst_reg);
12493 }
12494 
12495 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12496 				struct bpf_reg_state *src_reg)
12497 {
12498 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12499 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12500 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12501 	s32 smin_val = src_reg->s32_min_value;
12502 	u32 umin_val = src_reg->u32_min_value;
12503 
12504 	if (src_known && dst_known) {
12505 		__mark_reg32_known(dst_reg, var32_off.value);
12506 		return;
12507 	}
12508 
12509 	/* We get our maximum from the var_off, and our minimum is the
12510 	 * maximum of the operands' minima
12511 	 */
12512 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12513 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12514 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12515 		/* Lose signed bounds when ORing negative numbers,
12516 		 * ain't nobody got time for that.
12517 		 */
12518 		dst_reg->s32_min_value = S32_MIN;
12519 		dst_reg->s32_max_value = S32_MAX;
12520 	} else {
12521 		/* ORing two positives gives a positive, so safe to
12522 		 * cast result into s64.
12523 		 */
12524 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12525 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12526 	}
12527 }
12528 
12529 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12530 			      struct bpf_reg_state *src_reg)
12531 {
12532 	bool src_known = tnum_is_const(src_reg->var_off);
12533 	bool dst_known = tnum_is_const(dst_reg->var_off);
12534 	s64 smin_val = src_reg->smin_value;
12535 	u64 umin_val = src_reg->umin_value;
12536 
12537 	if (src_known && dst_known) {
12538 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12539 		return;
12540 	}
12541 
12542 	/* We get our maximum from the var_off, and our minimum is the
12543 	 * maximum of the operands' minima
12544 	 */
12545 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12546 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12547 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12548 		/* Lose signed bounds when ORing negative numbers,
12549 		 * ain't nobody got time for that.
12550 		 */
12551 		dst_reg->smin_value = S64_MIN;
12552 		dst_reg->smax_value = S64_MAX;
12553 	} else {
12554 		/* ORing two positives gives a positive, so safe to
12555 		 * cast result into s64.
12556 		 */
12557 		dst_reg->smin_value = dst_reg->umin_value;
12558 		dst_reg->smax_value = dst_reg->umax_value;
12559 	}
12560 	/* We may learn something more from the var_off */
12561 	__update_reg_bounds(dst_reg);
12562 }
12563 
12564 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12565 				 struct bpf_reg_state *src_reg)
12566 {
12567 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12568 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12569 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12570 	s32 smin_val = src_reg->s32_min_value;
12571 
12572 	if (src_known && dst_known) {
12573 		__mark_reg32_known(dst_reg, var32_off.value);
12574 		return;
12575 	}
12576 
12577 	/* We get both minimum and maximum from the var32_off. */
12578 	dst_reg->u32_min_value = var32_off.value;
12579 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12580 
12581 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12582 		/* XORing two positive sign numbers gives a positive,
12583 		 * so safe to cast u32 result into s32.
12584 		 */
12585 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12586 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12587 	} else {
12588 		dst_reg->s32_min_value = S32_MIN;
12589 		dst_reg->s32_max_value = S32_MAX;
12590 	}
12591 }
12592 
12593 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12594 			       struct bpf_reg_state *src_reg)
12595 {
12596 	bool src_known = tnum_is_const(src_reg->var_off);
12597 	bool dst_known = tnum_is_const(dst_reg->var_off);
12598 	s64 smin_val = src_reg->smin_value;
12599 
12600 	if (src_known && dst_known) {
12601 		/* dst_reg->var_off.value has been updated earlier */
12602 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12603 		return;
12604 	}
12605 
12606 	/* We get both minimum and maximum from the var_off. */
12607 	dst_reg->umin_value = dst_reg->var_off.value;
12608 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12609 
12610 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12611 		/* XORing two positive sign numbers gives a positive,
12612 		 * so safe to cast u64 result into s64.
12613 		 */
12614 		dst_reg->smin_value = dst_reg->umin_value;
12615 		dst_reg->smax_value = dst_reg->umax_value;
12616 	} else {
12617 		dst_reg->smin_value = S64_MIN;
12618 		dst_reg->smax_value = S64_MAX;
12619 	}
12620 
12621 	__update_reg_bounds(dst_reg);
12622 }
12623 
12624 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12625 				   u64 umin_val, u64 umax_val)
12626 {
12627 	/* We lose all sign bit information (except what we can pick
12628 	 * up from var_off)
12629 	 */
12630 	dst_reg->s32_min_value = S32_MIN;
12631 	dst_reg->s32_max_value = S32_MAX;
12632 	/* If we might shift our top bit out, then we know nothing */
12633 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12634 		dst_reg->u32_min_value = 0;
12635 		dst_reg->u32_max_value = U32_MAX;
12636 	} else {
12637 		dst_reg->u32_min_value <<= umin_val;
12638 		dst_reg->u32_max_value <<= umax_val;
12639 	}
12640 }
12641 
12642 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12643 				 struct bpf_reg_state *src_reg)
12644 {
12645 	u32 umax_val = src_reg->u32_max_value;
12646 	u32 umin_val = src_reg->u32_min_value;
12647 	/* u32 alu operation will zext upper bits */
12648 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12649 
12650 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12651 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12652 	/* Not required but being careful mark reg64 bounds as unknown so
12653 	 * that we are forced to pick them up from tnum and zext later and
12654 	 * if some path skips this step we are still safe.
12655 	 */
12656 	__mark_reg64_unbounded(dst_reg);
12657 	__update_reg32_bounds(dst_reg);
12658 }
12659 
12660 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12661 				   u64 umin_val, u64 umax_val)
12662 {
12663 	/* Special case <<32 because it is a common compiler pattern to sign
12664 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12665 	 * positive we know this shift will also be positive so we can track
12666 	 * bounds correctly. Otherwise we lose all sign bit information except
12667 	 * what we can pick up from var_off. Perhaps we can generalize this
12668 	 * later to shifts of any length.
12669 	 */
12670 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12671 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12672 	else
12673 		dst_reg->smax_value = S64_MAX;
12674 
12675 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12676 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12677 	else
12678 		dst_reg->smin_value = S64_MIN;
12679 
12680 	/* If we might shift our top bit out, then we know nothing */
12681 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12682 		dst_reg->umin_value = 0;
12683 		dst_reg->umax_value = U64_MAX;
12684 	} else {
12685 		dst_reg->umin_value <<= umin_val;
12686 		dst_reg->umax_value <<= umax_val;
12687 	}
12688 }
12689 
12690 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12691 			       struct bpf_reg_state *src_reg)
12692 {
12693 	u64 umax_val = src_reg->umax_value;
12694 	u64 umin_val = src_reg->umin_value;
12695 
12696 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12697 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12698 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12699 
12700 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12701 	/* We may learn something more from the var_off */
12702 	__update_reg_bounds(dst_reg);
12703 }
12704 
12705 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12706 				 struct bpf_reg_state *src_reg)
12707 {
12708 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12709 	u32 umax_val = src_reg->u32_max_value;
12710 	u32 umin_val = src_reg->u32_min_value;
12711 
12712 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12713 	 * be negative, then either:
12714 	 * 1) src_reg might be zero, so the sign bit of the result is
12715 	 *    unknown, so we lose our signed bounds
12716 	 * 2) it's known negative, thus the unsigned bounds capture the
12717 	 *    signed bounds
12718 	 * 3) the signed bounds cross zero, so they tell us nothing
12719 	 *    about the result
12720 	 * If the value in dst_reg is known nonnegative, then again the
12721 	 * unsigned bounds capture the signed bounds.
12722 	 * Thus, in all cases it suffices to blow away our signed bounds
12723 	 * and rely on inferring new ones from the unsigned bounds and
12724 	 * var_off of the result.
12725 	 */
12726 	dst_reg->s32_min_value = S32_MIN;
12727 	dst_reg->s32_max_value = S32_MAX;
12728 
12729 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12730 	dst_reg->u32_min_value >>= umax_val;
12731 	dst_reg->u32_max_value >>= umin_val;
12732 
12733 	__mark_reg64_unbounded(dst_reg);
12734 	__update_reg32_bounds(dst_reg);
12735 }
12736 
12737 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12738 			       struct bpf_reg_state *src_reg)
12739 {
12740 	u64 umax_val = src_reg->umax_value;
12741 	u64 umin_val = src_reg->umin_value;
12742 
12743 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12744 	 * be negative, then either:
12745 	 * 1) src_reg might be zero, so the sign bit of the result is
12746 	 *    unknown, so we lose our signed bounds
12747 	 * 2) it's known negative, thus the unsigned bounds capture the
12748 	 *    signed bounds
12749 	 * 3) the signed bounds cross zero, so they tell us nothing
12750 	 *    about the result
12751 	 * If the value in dst_reg is known nonnegative, then again the
12752 	 * unsigned bounds capture the signed bounds.
12753 	 * Thus, in all cases it suffices to blow away our signed bounds
12754 	 * and rely on inferring new ones from the unsigned bounds and
12755 	 * var_off of the result.
12756 	 */
12757 	dst_reg->smin_value = S64_MIN;
12758 	dst_reg->smax_value = S64_MAX;
12759 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12760 	dst_reg->umin_value >>= umax_val;
12761 	dst_reg->umax_value >>= umin_val;
12762 
12763 	/* Its not easy to operate on alu32 bounds here because it depends
12764 	 * on bits being shifted in. Take easy way out and mark unbounded
12765 	 * so we can recalculate later from tnum.
12766 	 */
12767 	__mark_reg32_unbounded(dst_reg);
12768 	__update_reg_bounds(dst_reg);
12769 }
12770 
12771 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12772 				  struct bpf_reg_state *src_reg)
12773 {
12774 	u64 umin_val = src_reg->u32_min_value;
12775 
12776 	/* Upon reaching here, src_known is true and
12777 	 * umax_val is equal to umin_val.
12778 	 */
12779 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12780 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12781 
12782 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12783 
12784 	/* blow away the dst_reg umin_value/umax_value and rely on
12785 	 * dst_reg var_off to refine the result.
12786 	 */
12787 	dst_reg->u32_min_value = 0;
12788 	dst_reg->u32_max_value = U32_MAX;
12789 
12790 	__mark_reg64_unbounded(dst_reg);
12791 	__update_reg32_bounds(dst_reg);
12792 }
12793 
12794 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12795 				struct bpf_reg_state *src_reg)
12796 {
12797 	u64 umin_val = src_reg->umin_value;
12798 
12799 	/* Upon reaching here, src_known is true and umax_val is equal
12800 	 * to umin_val.
12801 	 */
12802 	dst_reg->smin_value >>= umin_val;
12803 	dst_reg->smax_value >>= umin_val;
12804 
12805 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12806 
12807 	/* blow away the dst_reg umin_value/umax_value and rely on
12808 	 * dst_reg var_off to refine the result.
12809 	 */
12810 	dst_reg->umin_value = 0;
12811 	dst_reg->umax_value = U64_MAX;
12812 
12813 	/* Its not easy to operate on alu32 bounds here because it depends
12814 	 * on bits being shifted in from upper 32-bits. Take easy way out
12815 	 * and mark unbounded so we can recalculate later from tnum.
12816 	 */
12817 	__mark_reg32_unbounded(dst_reg);
12818 	__update_reg_bounds(dst_reg);
12819 }
12820 
12821 /* WARNING: This function does calculations on 64-bit values, but the actual
12822  * execution may occur on 32-bit values. Therefore, things like bitshifts
12823  * need extra checks in the 32-bit case.
12824  */
12825 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12826 				      struct bpf_insn *insn,
12827 				      struct bpf_reg_state *dst_reg,
12828 				      struct bpf_reg_state src_reg)
12829 {
12830 	struct bpf_reg_state *regs = cur_regs(env);
12831 	u8 opcode = BPF_OP(insn->code);
12832 	bool src_known;
12833 	s64 smin_val, smax_val;
12834 	u64 umin_val, umax_val;
12835 	s32 s32_min_val, s32_max_val;
12836 	u32 u32_min_val, u32_max_val;
12837 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12838 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12839 	int ret;
12840 
12841 	smin_val = src_reg.smin_value;
12842 	smax_val = src_reg.smax_value;
12843 	umin_val = src_reg.umin_value;
12844 	umax_val = src_reg.umax_value;
12845 
12846 	s32_min_val = src_reg.s32_min_value;
12847 	s32_max_val = src_reg.s32_max_value;
12848 	u32_min_val = src_reg.u32_min_value;
12849 	u32_max_val = src_reg.u32_max_value;
12850 
12851 	if (alu32) {
12852 		src_known = tnum_subreg_is_const(src_reg.var_off);
12853 		if ((src_known &&
12854 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12855 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12856 			/* Taint dst register if offset had invalid bounds
12857 			 * derived from e.g. dead branches.
12858 			 */
12859 			__mark_reg_unknown(env, dst_reg);
12860 			return 0;
12861 		}
12862 	} else {
12863 		src_known = tnum_is_const(src_reg.var_off);
12864 		if ((src_known &&
12865 		     (smin_val != smax_val || umin_val != umax_val)) ||
12866 		    smin_val > smax_val || umin_val > umax_val) {
12867 			/* Taint dst register if offset had invalid bounds
12868 			 * derived from e.g. dead branches.
12869 			 */
12870 			__mark_reg_unknown(env, dst_reg);
12871 			return 0;
12872 		}
12873 	}
12874 
12875 	if (!src_known &&
12876 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12877 		__mark_reg_unknown(env, dst_reg);
12878 		return 0;
12879 	}
12880 
12881 	if (sanitize_needed(opcode)) {
12882 		ret = sanitize_val_alu(env, insn);
12883 		if (ret < 0)
12884 			return sanitize_err(env, insn, ret, NULL, NULL);
12885 	}
12886 
12887 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12888 	 * There are two classes of instructions: The first class we track both
12889 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12890 	 * greatest amount of precision when alu operations are mixed with jmp32
12891 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12892 	 * and BPF_OR. This is possible because these ops have fairly easy to
12893 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12894 	 * See alu32 verifier tests for examples. The second class of
12895 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12896 	 * with regards to tracking sign/unsigned bounds because the bits may
12897 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12898 	 * the reg unbounded in the subreg bound space and use the resulting
12899 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12900 	 */
12901 	switch (opcode) {
12902 	case BPF_ADD:
12903 		scalar32_min_max_add(dst_reg, &src_reg);
12904 		scalar_min_max_add(dst_reg, &src_reg);
12905 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12906 		break;
12907 	case BPF_SUB:
12908 		scalar32_min_max_sub(dst_reg, &src_reg);
12909 		scalar_min_max_sub(dst_reg, &src_reg);
12910 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12911 		break;
12912 	case BPF_MUL:
12913 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12914 		scalar32_min_max_mul(dst_reg, &src_reg);
12915 		scalar_min_max_mul(dst_reg, &src_reg);
12916 		break;
12917 	case BPF_AND:
12918 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12919 		scalar32_min_max_and(dst_reg, &src_reg);
12920 		scalar_min_max_and(dst_reg, &src_reg);
12921 		break;
12922 	case BPF_OR:
12923 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12924 		scalar32_min_max_or(dst_reg, &src_reg);
12925 		scalar_min_max_or(dst_reg, &src_reg);
12926 		break;
12927 	case BPF_XOR:
12928 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12929 		scalar32_min_max_xor(dst_reg, &src_reg);
12930 		scalar_min_max_xor(dst_reg, &src_reg);
12931 		break;
12932 	case BPF_LSH:
12933 		if (umax_val >= insn_bitness) {
12934 			/* Shifts greater than 31 or 63 are undefined.
12935 			 * This includes shifts by a negative number.
12936 			 */
12937 			mark_reg_unknown(env, regs, insn->dst_reg);
12938 			break;
12939 		}
12940 		if (alu32)
12941 			scalar32_min_max_lsh(dst_reg, &src_reg);
12942 		else
12943 			scalar_min_max_lsh(dst_reg, &src_reg);
12944 		break;
12945 	case BPF_RSH:
12946 		if (umax_val >= insn_bitness) {
12947 			/* Shifts greater than 31 or 63 are undefined.
12948 			 * This includes shifts by a negative number.
12949 			 */
12950 			mark_reg_unknown(env, regs, insn->dst_reg);
12951 			break;
12952 		}
12953 		if (alu32)
12954 			scalar32_min_max_rsh(dst_reg, &src_reg);
12955 		else
12956 			scalar_min_max_rsh(dst_reg, &src_reg);
12957 		break;
12958 	case BPF_ARSH:
12959 		if (umax_val >= insn_bitness) {
12960 			/* Shifts greater than 31 or 63 are undefined.
12961 			 * This includes shifts by a negative number.
12962 			 */
12963 			mark_reg_unknown(env, regs, insn->dst_reg);
12964 			break;
12965 		}
12966 		if (alu32)
12967 			scalar32_min_max_arsh(dst_reg, &src_reg);
12968 		else
12969 			scalar_min_max_arsh(dst_reg, &src_reg);
12970 		break;
12971 	default:
12972 		mark_reg_unknown(env, regs, insn->dst_reg);
12973 		break;
12974 	}
12975 
12976 	/* ALU32 ops are zero extended into 64bit register */
12977 	if (alu32)
12978 		zext_32_to_64(dst_reg);
12979 	reg_bounds_sync(dst_reg);
12980 	return 0;
12981 }
12982 
12983 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12984  * and var_off.
12985  */
12986 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12987 				   struct bpf_insn *insn)
12988 {
12989 	struct bpf_verifier_state *vstate = env->cur_state;
12990 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12991 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12992 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12993 	u8 opcode = BPF_OP(insn->code);
12994 	int err;
12995 
12996 	dst_reg = &regs[insn->dst_reg];
12997 	src_reg = NULL;
12998 	if (dst_reg->type != SCALAR_VALUE)
12999 		ptr_reg = dst_reg;
13000 	else
13001 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13002 		 * incorrectly propagated into other registers by find_equal_scalars()
13003 		 */
13004 		dst_reg->id = 0;
13005 	if (BPF_SRC(insn->code) == BPF_X) {
13006 		src_reg = &regs[insn->src_reg];
13007 		if (src_reg->type != SCALAR_VALUE) {
13008 			if (dst_reg->type != SCALAR_VALUE) {
13009 				/* Combining two pointers by any ALU op yields
13010 				 * an arbitrary scalar. Disallow all math except
13011 				 * pointer subtraction
13012 				 */
13013 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13014 					mark_reg_unknown(env, regs, insn->dst_reg);
13015 					return 0;
13016 				}
13017 				verbose(env, "R%d pointer %s pointer prohibited\n",
13018 					insn->dst_reg,
13019 					bpf_alu_string[opcode >> 4]);
13020 				return -EACCES;
13021 			} else {
13022 				/* scalar += pointer
13023 				 * This is legal, but we have to reverse our
13024 				 * src/dest handling in computing the range
13025 				 */
13026 				err = mark_chain_precision(env, insn->dst_reg);
13027 				if (err)
13028 					return err;
13029 				return adjust_ptr_min_max_vals(env, insn,
13030 							       src_reg, dst_reg);
13031 			}
13032 		} else if (ptr_reg) {
13033 			/* pointer += scalar */
13034 			err = mark_chain_precision(env, insn->src_reg);
13035 			if (err)
13036 				return err;
13037 			return adjust_ptr_min_max_vals(env, insn,
13038 						       dst_reg, src_reg);
13039 		} else if (dst_reg->precise) {
13040 			/* if dst_reg is precise, src_reg should be precise as well */
13041 			err = mark_chain_precision(env, insn->src_reg);
13042 			if (err)
13043 				return err;
13044 		}
13045 	} else {
13046 		/* Pretend the src is a reg with a known value, since we only
13047 		 * need to be able to read from this state.
13048 		 */
13049 		off_reg.type = SCALAR_VALUE;
13050 		__mark_reg_known(&off_reg, insn->imm);
13051 		src_reg = &off_reg;
13052 		if (ptr_reg) /* pointer += K */
13053 			return adjust_ptr_min_max_vals(env, insn,
13054 						       ptr_reg, src_reg);
13055 	}
13056 
13057 	/* Got here implies adding two SCALAR_VALUEs */
13058 	if (WARN_ON_ONCE(ptr_reg)) {
13059 		print_verifier_state(env, state, true);
13060 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13061 		return -EINVAL;
13062 	}
13063 	if (WARN_ON(!src_reg)) {
13064 		print_verifier_state(env, state, true);
13065 		verbose(env, "verifier internal error: no src_reg\n");
13066 		return -EINVAL;
13067 	}
13068 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13069 }
13070 
13071 /* check validity of 32-bit and 64-bit arithmetic operations */
13072 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13073 {
13074 	struct bpf_reg_state *regs = cur_regs(env);
13075 	u8 opcode = BPF_OP(insn->code);
13076 	int err;
13077 
13078 	if (opcode == BPF_END || opcode == BPF_NEG) {
13079 		if (opcode == BPF_NEG) {
13080 			if (BPF_SRC(insn->code) != BPF_K ||
13081 			    insn->src_reg != BPF_REG_0 ||
13082 			    insn->off != 0 || insn->imm != 0) {
13083 				verbose(env, "BPF_NEG uses reserved fields\n");
13084 				return -EINVAL;
13085 			}
13086 		} else {
13087 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13088 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13089 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13090 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13091 				verbose(env, "BPF_END uses reserved fields\n");
13092 				return -EINVAL;
13093 			}
13094 		}
13095 
13096 		/* check src operand */
13097 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13098 		if (err)
13099 			return err;
13100 
13101 		if (is_pointer_value(env, insn->dst_reg)) {
13102 			verbose(env, "R%d pointer arithmetic prohibited\n",
13103 				insn->dst_reg);
13104 			return -EACCES;
13105 		}
13106 
13107 		/* check dest operand */
13108 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13109 		if (err)
13110 			return err;
13111 
13112 	} else if (opcode == BPF_MOV) {
13113 
13114 		if (BPF_SRC(insn->code) == BPF_X) {
13115 			if (insn->imm != 0) {
13116 				verbose(env, "BPF_MOV uses reserved fields\n");
13117 				return -EINVAL;
13118 			}
13119 
13120 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13121 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13122 					verbose(env, "BPF_MOV uses reserved fields\n");
13123 					return -EINVAL;
13124 				}
13125 			} else {
13126 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13127 				    insn->off != 32) {
13128 					verbose(env, "BPF_MOV uses reserved fields\n");
13129 					return -EINVAL;
13130 				}
13131 			}
13132 
13133 			/* check src operand */
13134 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13135 			if (err)
13136 				return err;
13137 		} else {
13138 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13139 				verbose(env, "BPF_MOV uses reserved fields\n");
13140 				return -EINVAL;
13141 			}
13142 		}
13143 
13144 		/* check dest operand, mark as required later */
13145 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13146 		if (err)
13147 			return err;
13148 
13149 		if (BPF_SRC(insn->code) == BPF_X) {
13150 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13151 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13152 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13153 				       !tnum_is_const(src_reg->var_off);
13154 
13155 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13156 				if (insn->off == 0) {
13157 					/* case: R1 = R2
13158 					 * copy register state to dest reg
13159 					 */
13160 					if (need_id)
13161 						/* Assign src and dst registers the same ID
13162 						 * that will be used by find_equal_scalars()
13163 						 * to propagate min/max range.
13164 						 */
13165 						src_reg->id = ++env->id_gen;
13166 					copy_register_state(dst_reg, src_reg);
13167 					dst_reg->live |= REG_LIVE_WRITTEN;
13168 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13169 				} else {
13170 					/* case: R1 = (s8, s16 s32)R2 */
13171 					if (is_pointer_value(env, insn->src_reg)) {
13172 						verbose(env,
13173 							"R%d sign-extension part of pointer\n",
13174 							insn->src_reg);
13175 						return -EACCES;
13176 					} else if (src_reg->type == SCALAR_VALUE) {
13177 						bool no_sext;
13178 
13179 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13180 						if (no_sext && need_id)
13181 							src_reg->id = ++env->id_gen;
13182 						copy_register_state(dst_reg, src_reg);
13183 						if (!no_sext)
13184 							dst_reg->id = 0;
13185 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13186 						dst_reg->live |= REG_LIVE_WRITTEN;
13187 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13188 					} else {
13189 						mark_reg_unknown(env, regs, insn->dst_reg);
13190 					}
13191 				}
13192 			} else {
13193 				/* R1 = (u32) R2 */
13194 				if (is_pointer_value(env, insn->src_reg)) {
13195 					verbose(env,
13196 						"R%d partial copy of pointer\n",
13197 						insn->src_reg);
13198 					return -EACCES;
13199 				} else if (src_reg->type == SCALAR_VALUE) {
13200 					if (insn->off == 0) {
13201 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13202 
13203 						if (is_src_reg_u32 && need_id)
13204 							src_reg->id = ++env->id_gen;
13205 						copy_register_state(dst_reg, src_reg);
13206 						/* Make sure ID is cleared if src_reg is not in u32
13207 						 * range otherwise dst_reg min/max could be incorrectly
13208 						 * propagated into src_reg by find_equal_scalars()
13209 						 */
13210 						if (!is_src_reg_u32)
13211 							dst_reg->id = 0;
13212 						dst_reg->live |= REG_LIVE_WRITTEN;
13213 						dst_reg->subreg_def = env->insn_idx + 1;
13214 					} else {
13215 						/* case: W1 = (s8, s16)W2 */
13216 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13217 
13218 						if (no_sext && need_id)
13219 							src_reg->id = ++env->id_gen;
13220 						copy_register_state(dst_reg, src_reg);
13221 						if (!no_sext)
13222 							dst_reg->id = 0;
13223 						dst_reg->live |= REG_LIVE_WRITTEN;
13224 						dst_reg->subreg_def = env->insn_idx + 1;
13225 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13226 					}
13227 				} else {
13228 					mark_reg_unknown(env, regs,
13229 							 insn->dst_reg);
13230 				}
13231 				zext_32_to_64(dst_reg);
13232 				reg_bounds_sync(dst_reg);
13233 			}
13234 		} else {
13235 			/* case: R = imm
13236 			 * remember the value we stored into this reg
13237 			 */
13238 			/* clear any state __mark_reg_known doesn't set */
13239 			mark_reg_unknown(env, regs, insn->dst_reg);
13240 			regs[insn->dst_reg].type = SCALAR_VALUE;
13241 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13242 				__mark_reg_known(regs + insn->dst_reg,
13243 						 insn->imm);
13244 			} else {
13245 				__mark_reg_known(regs + insn->dst_reg,
13246 						 (u32)insn->imm);
13247 			}
13248 		}
13249 
13250 	} else if (opcode > BPF_END) {
13251 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13252 		return -EINVAL;
13253 
13254 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13255 
13256 		if (BPF_SRC(insn->code) == BPF_X) {
13257 			if (insn->imm != 0 || insn->off > 1 ||
13258 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13259 				verbose(env, "BPF_ALU uses reserved fields\n");
13260 				return -EINVAL;
13261 			}
13262 			/* check src1 operand */
13263 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13264 			if (err)
13265 				return err;
13266 		} else {
13267 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13268 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13269 				verbose(env, "BPF_ALU uses reserved fields\n");
13270 				return -EINVAL;
13271 			}
13272 		}
13273 
13274 		/* check src2 operand */
13275 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13276 		if (err)
13277 			return err;
13278 
13279 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13280 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13281 			verbose(env, "div by zero\n");
13282 			return -EINVAL;
13283 		}
13284 
13285 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13286 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13287 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13288 
13289 			if (insn->imm < 0 || insn->imm >= size) {
13290 				verbose(env, "invalid shift %d\n", insn->imm);
13291 				return -EINVAL;
13292 			}
13293 		}
13294 
13295 		/* check dest operand */
13296 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13297 		if (err)
13298 			return err;
13299 
13300 		return adjust_reg_min_max_vals(env, insn);
13301 	}
13302 
13303 	return 0;
13304 }
13305 
13306 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13307 				   struct bpf_reg_state *dst_reg,
13308 				   enum bpf_reg_type type,
13309 				   bool range_right_open)
13310 {
13311 	struct bpf_func_state *state;
13312 	struct bpf_reg_state *reg;
13313 	int new_range;
13314 
13315 	if (dst_reg->off < 0 ||
13316 	    (dst_reg->off == 0 && range_right_open))
13317 		/* This doesn't give us any range */
13318 		return;
13319 
13320 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13321 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13322 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13323 		 * than pkt_end, but that's because it's also less than pkt.
13324 		 */
13325 		return;
13326 
13327 	new_range = dst_reg->off;
13328 	if (range_right_open)
13329 		new_range++;
13330 
13331 	/* Examples for register markings:
13332 	 *
13333 	 * pkt_data in dst register:
13334 	 *
13335 	 *   r2 = r3;
13336 	 *   r2 += 8;
13337 	 *   if (r2 > pkt_end) goto <handle exception>
13338 	 *   <access okay>
13339 	 *
13340 	 *   r2 = r3;
13341 	 *   r2 += 8;
13342 	 *   if (r2 < pkt_end) goto <access okay>
13343 	 *   <handle exception>
13344 	 *
13345 	 *   Where:
13346 	 *     r2 == dst_reg, pkt_end == src_reg
13347 	 *     r2=pkt(id=n,off=8,r=0)
13348 	 *     r3=pkt(id=n,off=0,r=0)
13349 	 *
13350 	 * pkt_data in src register:
13351 	 *
13352 	 *   r2 = r3;
13353 	 *   r2 += 8;
13354 	 *   if (pkt_end >= r2) goto <access okay>
13355 	 *   <handle exception>
13356 	 *
13357 	 *   r2 = r3;
13358 	 *   r2 += 8;
13359 	 *   if (pkt_end <= r2) goto <handle exception>
13360 	 *   <access okay>
13361 	 *
13362 	 *   Where:
13363 	 *     pkt_end == dst_reg, r2 == src_reg
13364 	 *     r2=pkt(id=n,off=8,r=0)
13365 	 *     r3=pkt(id=n,off=0,r=0)
13366 	 *
13367 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13368 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13369 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13370 	 * the check.
13371 	 */
13372 
13373 	/* If our ids match, then we must have the same max_value.  And we
13374 	 * don't care about the other reg's fixed offset, since if it's too big
13375 	 * the range won't allow anything.
13376 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13377 	 */
13378 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13379 		if (reg->type == type && reg->id == dst_reg->id)
13380 			/* keep the maximum range already checked */
13381 			reg->range = max(reg->range, new_range);
13382 	}));
13383 }
13384 
13385 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13386 {
13387 	struct tnum subreg = tnum_subreg(reg->var_off);
13388 	s32 sval = (s32)val;
13389 
13390 	switch (opcode) {
13391 	case BPF_JEQ:
13392 		if (tnum_is_const(subreg))
13393 			return !!tnum_equals_const(subreg, val);
13394 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13395 			return 0;
13396 		break;
13397 	case BPF_JNE:
13398 		if (tnum_is_const(subreg))
13399 			return !tnum_equals_const(subreg, val);
13400 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13401 			return 1;
13402 		break;
13403 	case BPF_JSET:
13404 		if ((~subreg.mask & subreg.value) & val)
13405 			return 1;
13406 		if (!((subreg.mask | subreg.value) & val))
13407 			return 0;
13408 		break;
13409 	case BPF_JGT:
13410 		if (reg->u32_min_value > val)
13411 			return 1;
13412 		else if (reg->u32_max_value <= val)
13413 			return 0;
13414 		break;
13415 	case BPF_JSGT:
13416 		if (reg->s32_min_value > sval)
13417 			return 1;
13418 		else if (reg->s32_max_value <= sval)
13419 			return 0;
13420 		break;
13421 	case BPF_JLT:
13422 		if (reg->u32_max_value < val)
13423 			return 1;
13424 		else if (reg->u32_min_value >= val)
13425 			return 0;
13426 		break;
13427 	case BPF_JSLT:
13428 		if (reg->s32_max_value < sval)
13429 			return 1;
13430 		else if (reg->s32_min_value >= sval)
13431 			return 0;
13432 		break;
13433 	case BPF_JGE:
13434 		if (reg->u32_min_value >= val)
13435 			return 1;
13436 		else if (reg->u32_max_value < val)
13437 			return 0;
13438 		break;
13439 	case BPF_JSGE:
13440 		if (reg->s32_min_value >= sval)
13441 			return 1;
13442 		else if (reg->s32_max_value < sval)
13443 			return 0;
13444 		break;
13445 	case BPF_JLE:
13446 		if (reg->u32_max_value <= val)
13447 			return 1;
13448 		else if (reg->u32_min_value > val)
13449 			return 0;
13450 		break;
13451 	case BPF_JSLE:
13452 		if (reg->s32_max_value <= sval)
13453 			return 1;
13454 		else if (reg->s32_min_value > sval)
13455 			return 0;
13456 		break;
13457 	}
13458 
13459 	return -1;
13460 }
13461 
13462 
13463 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13464 {
13465 	s64 sval = (s64)val;
13466 
13467 	switch (opcode) {
13468 	case BPF_JEQ:
13469 		if (tnum_is_const(reg->var_off))
13470 			return !!tnum_equals_const(reg->var_off, val);
13471 		else if (val < reg->umin_value || val > reg->umax_value)
13472 			return 0;
13473 		break;
13474 	case BPF_JNE:
13475 		if (tnum_is_const(reg->var_off))
13476 			return !tnum_equals_const(reg->var_off, val);
13477 		else if (val < reg->umin_value || val > reg->umax_value)
13478 			return 1;
13479 		break;
13480 	case BPF_JSET:
13481 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13482 			return 1;
13483 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13484 			return 0;
13485 		break;
13486 	case BPF_JGT:
13487 		if (reg->umin_value > val)
13488 			return 1;
13489 		else if (reg->umax_value <= val)
13490 			return 0;
13491 		break;
13492 	case BPF_JSGT:
13493 		if (reg->smin_value > sval)
13494 			return 1;
13495 		else if (reg->smax_value <= sval)
13496 			return 0;
13497 		break;
13498 	case BPF_JLT:
13499 		if (reg->umax_value < val)
13500 			return 1;
13501 		else if (reg->umin_value >= val)
13502 			return 0;
13503 		break;
13504 	case BPF_JSLT:
13505 		if (reg->smax_value < sval)
13506 			return 1;
13507 		else if (reg->smin_value >= sval)
13508 			return 0;
13509 		break;
13510 	case BPF_JGE:
13511 		if (reg->umin_value >= val)
13512 			return 1;
13513 		else if (reg->umax_value < val)
13514 			return 0;
13515 		break;
13516 	case BPF_JSGE:
13517 		if (reg->smin_value >= sval)
13518 			return 1;
13519 		else if (reg->smax_value < sval)
13520 			return 0;
13521 		break;
13522 	case BPF_JLE:
13523 		if (reg->umax_value <= val)
13524 			return 1;
13525 		else if (reg->umin_value > val)
13526 			return 0;
13527 		break;
13528 	case BPF_JSLE:
13529 		if (reg->smax_value <= sval)
13530 			return 1;
13531 		else if (reg->smin_value > sval)
13532 			return 0;
13533 		break;
13534 	}
13535 
13536 	return -1;
13537 }
13538 
13539 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13540  * and return:
13541  *  1 - branch will be taken and "goto target" will be executed
13542  *  0 - branch will not be taken and fall-through to next insn
13543  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13544  *      range [0,10]
13545  */
13546 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13547 			   bool is_jmp32)
13548 {
13549 	if (__is_pointer_value(false, reg)) {
13550 		if (!reg_not_null(reg))
13551 			return -1;
13552 
13553 		/* If pointer is valid tests against zero will fail so we can
13554 		 * use this to direct branch taken.
13555 		 */
13556 		if (val != 0)
13557 			return -1;
13558 
13559 		switch (opcode) {
13560 		case BPF_JEQ:
13561 			return 0;
13562 		case BPF_JNE:
13563 			return 1;
13564 		default:
13565 			return -1;
13566 		}
13567 	}
13568 
13569 	if (is_jmp32)
13570 		return is_branch32_taken(reg, val, opcode);
13571 	return is_branch64_taken(reg, val, opcode);
13572 }
13573 
13574 static int flip_opcode(u32 opcode)
13575 {
13576 	/* How can we transform "a <op> b" into "b <op> a"? */
13577 	static const u8 opcode_flip[16] = {
13578 		/* these stay the same */
13579 		[BPF_JEQ  >> 4] = BPF_JEQ,
13580 		[BPF_JNE  >> 4] = BPF_JNE,
13581 		[BPF_JSET >> 4] = BPF_JSET,
13582 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13583 		[BPF_JGE  >> 4] = BPF_JLE,
13584 		[BPF_JGT  >> 4] = BPF_JLT,
13585 		[BPF_JLE  >> 4] = BPF_JGE,
13586 		[BPF_JLT  >> 4] = BPF_JGT,
13587 		[BPF_JSGE >> 4] = BPF_JSLE,
13588 		[BPF_JSGT >> 4] = BPF_JSLT,
13589 		[BPF_JSLE >> 4] = BPF_JSGE,
13590 		[BPF_JSLT >> 4] = BPF_JSGT
13591 	};
13592 	return opcode_flip[opcode >> 4];
13593 }
13594 
13595 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13596 				   struct bpf_reg_state *src_reg,
13597 				   u8 opcode)
13598 {
13599 	struct bpf_reg_state *pkt;
13600 
13601 	if (src_reg->type == PTR_TO_PACKET_END) {
13602 		pkt = dst_reg;
13603 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13604 		pkt = src_reg;
13605 		opcode = flip_opcode(opcode);
13606 	} else {
13607 		return -1;
13608 	}
13609 
13610 	if (pkt->range >= 0)
13611 		return -1;
13612 
13613 	switch (opcode) {
13614 	case BPF_JLE:
13615 		/* pkt <= pkt_end */
13616 		fallthrough;
13617 	case BPF_JGT:
13618 		/* pkt > pkt_end */
13619 		if (pkt->range == BEYOND_PKT_END)
13620 			/* pkt has at last one extra byte beyond pkt_end */
13621 			return opcode == BPF_JGT;
13622 		break;
13623 	case BPF_JLT:
13624 		/* pkt < pkt_end */
13625 		fallthrough;
13626 	case BPF_JGE:
13627 		/* pkt >= pkt_end */
13628 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13629 			return opcode == BPF_JGE;
13630 		break;
13631 	}
13632 	return -1;
13633 }
13634 
13635 /* Adjusts the register min/max values in the case that the dst_reg is the
13636  * variable register that we are working on, and src_reg is a constant or we're
13637  * simply doing a BPF_K check.
13638  * In JEQ/JNE cases we also adjust the var_off values.
13639  */
13640 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13641 			    struct bpf_reg_state *false_reg,
13642 			    u64 val, u32 val32,
13643 			    u8 opcode, bool is_jmp32)
13644 {
13645 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13646 	struct tnum false_64off = false_reg->var_off;
13647 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13648 	struct tnum true_64off = true_reg->var_off;
13649 	s64 sval = (s64)val;
13650 	s32 sval32 = (s32)val32;
13651 
13652 	/* If the dst_reg is a pointer, we can't learn anything about its
13653 	 * variable offset from the compare (unless src_reg were a pointer into
13654 	 * the same object, but we don't bother with that.
13655 	 * Since false_reg and true_reg have the same type by construction, we
13656 	 * only need to check one of them for pointerness.
13657 	 */
13658 	if (__is_pointer_value(false, false_reg))
13659 		return;
13660 
13661 	switch (opcode) {
13662 	/* JEQ/JNE comparison doesn't change the register equivalence.
13663 	 *
13664 	 * r1 = r2;
13665 	 * if (r1 == 42) goto label;
13666 	 * ...
13667 	 * label: // here both r1 and r2 are known to be 42.
13668 	 *
13669 	 * Hence when marking register as known preserve it's ID.
13670 	 */
13671 	case BPF_JEQ:
13672 		if (is_jmp32) {
13673 			__mark_reg32_known(true_reg, val32);
13674 			true_32off = tnum_subreg(true_reg->var_off);
13675 		} else {
13676 			___mark_reg_known(true_reg, val);
13677 			true_64off = true_reg->var_off;
13678 		}
13679 		break;
13680 	case BPF_JNE:
13681 		if (is_jmp32) {
13682 			__mark_reg32_known(false_reg, val32);
13683 			false_32off = tnum_subreg(false_reg->var_off);
13684 		} else {
13685 			___mark_reg_known(false_reg, val);
13686 			false_64off = false_reg->var_off;
13687 		}
13688 		break;
13689 	case BPF_JSET:
13690 		if (is_jmp32) {
13691 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13692 			if (is_power_of_2(val32))
13693 				true_32off = tnum_or(true_32off,
13694 						     tnum_const(val32));
13695 		} else {
13696 			false_64off = tnum_and(false_64off, tnum_const(~val));
13697 			if (is_power_of_2(val))
13698 				true_64off = tnum_or(true_64off,
13699 						     tnum_const(val));
13700 		}
13701 		break;
13702 	case BPF_JGE:
13703 	case BPF_JGT:
13704 	{
13705 		if (is_jmp32) {
13706 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13707 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13708 
13709 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13710 						       false_umax);
13711 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13712 						      true_umin);
13713 		} else {
13714 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13715 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13716 
13717 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13718 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13719 		}
13720 		break;
13721 	}
13722 	case BPF_JSGE:
13723 	case BPF_JSGT:
13724 	{
13725 		if (is_jmp32) {
13726 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13727 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13728 
13729 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13730 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13731 		} else {
13732 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13733 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13734 
13735 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13736 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13737 		}
13738 		break;
13739 	}
13740 	case BPF_JLE:
13741 	case BPF_JLT:
13742 	{
13743 		if (is_jmp32) {
13744 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13745 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13746 
13747 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13748 						       false_umin);
13749 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13750 						      true_umax);
13751 		} else {
13752 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13753 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13754 
13755 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13756 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13757 		}
13758 		break;
13759 	}
13760 	case BPF_JSLE:
13761 	case BPF_JSLT:
13762 	{
13763 		if (is_jmp32) {
13764 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13765 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13766 
13767 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13768 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13769 		} else {
13770 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13771 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13772 
13773 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13774 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13775 		}
13776 		break;
13777 	}
13778 	default:
13779 		return;
13780 	}
13781 
13782 	if (is_jmp32) {
13783 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13784 					     tnum_subreg(false_32off));
13785 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13786 					    tnum_subreg(true_32off));
13787 		__reg_combine_32_into_64(false_reg);
13788 		__reg_combine_32_into_64(true_reg);
13789 	} else {
13790 		false_reg->var_off = false_64off;
13791 		true_reg->var_off = true_64off;
13792 		__reg_combine_64_into_32(false_reg);
13793 		__reg_combine_64_into_32(true_reg);
13794 	}
13795 }
13796 
13797 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13798  * the variable reg.
13799  */
13800 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13801 				struct bpf_reg_state *false_reg,
13802 				u64 val, u32 val32,
13803 				u8 opcode, bool is_jmp32)
13804 {
13805 	opcode = flip_opcode(opcode);
13806 	/* This uses zero as "not present in table"; luckily the zero opcode,
13807 	 * BPF_JA, can't get here.
13808 	 */
13809 	if (opcode)
13810 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13811 }
13812 
13813 /* Regs are known to be equal, so intersect their min/max/var_off */
13814 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13815 				  struct bpf_reg_state *dst_reg)
13816 {
13817 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13818 							dst_reg->umin_value);
13819 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13820 							dst_reg->umax_value);
13821 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13822 							dst_reg->smin_value);
13823 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13824 							dst_reg->smax_value);
13825 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13826 							     dst_reg->var_off);
13827 	reg_bounds_sync(src_reg);
13828 	reg_bounds_sync(dst_reg);
13829 }
13830 
13831 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13832 				struct bpf_reg_state *true_dst,
13833 				struct bpf_reg_state *false_src,
13834 				struct bpf_reg_state *false_dst,
13835 				u8 opcode)
13836 {
13837 	switch (opcode) {
13838 	case BPF_JEQ:
13839 		__reg_combine_min_max(true_src, true_dst);
13840 		break;
13841 	case BPF_JNE:
13842 		__reg_combine_min_max(false_src, false_dst);
13843 		break;
13844 	}
13845 }
13846 
13847 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13848 				 struct bpf_reg_state *reg, u32 id,
13849 				 bool is_null)
13850 {
13851 	if (type_may_be_null(reg->type) && reg->id == id &&
13852 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13853 		/* Old offset (both fixed and variable parts) should have been
13854 		 * known-zero, because we don't allow pointer arithmetic on
13855 		 * pointers that might be NULL. If we see this happening, don't
13856 		 * convert the register.
13857 		 *
13858 		 * But in some cases, some helpers that return local kptrs
13859 		 * advance offset for the returned pointer. In those cases, it
13860 		 * is fine to expect to see reg->off.
13861 		 */
13862 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13863 			return;
13864 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13865 		    WARN_ON_ONCE(reg->off))
13866 			return;
13867 
13868 		if (is_null) {
13869 			reg->type = SCALAR_VALUE;
13870 			/* We don't need id and ref_obj_id from this point
13871 			 * onwards anymore, thus we should better reset it,
13872 			 * so that state pruning has chances to take effect.
13873 			 */
13874 			reg->id = 0;
13875 			reg->ref_obj_id = 0;
13876 
13877 			return;
13878 		}
13879 
13880 		mark_ptr_not_null_reg(reg);
13881 
13882 		if (!reg_may_point_to_spin_lock(reg)) {
13883 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13884 			 * in release_reference().
13885 			 *
13886 			 * reg->id is still used by spin_lock ptr. Other
13887 			 * than spin_lock ptr type, reg->id can be reset.
13888 			 */
13889 			reg->id = 0;
13890 		}
13891 	}
13892 }
13893 
13894 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13895  * be folded together at some point.
13896  */
13897 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13898 				  bool is_null)
13899 {
13900 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13901 	struct bpf_reg_state *regs = state->regs, *reg;
13902 	u32 ref_obj_id = regs[regno].ref_obj_id;
13903 	u32 id = regs[regno].id;
13904 
13905 	if (ref_obj_id && ref_obj_id == id && is_null)
13906 		/* regs[regno] is in the " == NULL" branch.
13907 		 * No one could have freed the reference state before
13908 		 * doing the NULL check.
13909 		 */
13910 		WARN_ON_ONCE(release_reference_state(state, id));
13911 
13912 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13913 		mark_ptr_or_null_reg(state, reg, id, is_null);
13914 	}));
13915 }
13916 
13917 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13918 				   struct bpf_reg_state *dst_reg,
13919 				   struct bpf_reg_state *src_reg,
13920 				   struct bpf_verifier_state *this_branch,
13921 				   struct bpf_verifier_state *other_branch)
13922 {
13923 	if (BPF_SRC(insn->code) != BPF_X)
13924 		return false;
13925 
13926 	/* Pointers are always 64-bit. */
13927 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13928 		return false;
13929 
13930 	switch (BPF_OP(insn->code)) {
13931 	case BPF_JGT:
13932 		if ((dst_reg->type == PTR_TO_PACKET &&
13933 		     src_reg->type == PTR_TO_PACKET_END) ||
13934 		    (dst_reg->type == PTR_TO_PACKET_META &&
13935 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13936 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13937 			find_good_pkt_pointers(this_branch, dst_reg,
13938 					       dst_reg->type, false);
13939 			mark_pkt_end(other_branch, insn->dst_reg, true);
13940 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13941 			    src_reg->type == PTR_TO_PACKET) ||
13942 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13943 			    src_reg->type == PTR_TO_PACKET_META)) {
13944 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13945 			find_good_pkt_pointers(other_branch, src_reg,
13946 					       src_reg->type, true);
13947 			mark_pkt_end(this_branch, insn->src_reg, false);
13948 		} else {
13949 			return false;
13950 		}
13951 		break;
13952 	case BPF_JLT:
13953 		if ((dst_reg->type == PTR_TO_PACKET &&
13954 		     src_reg->type == PTR_TO_PACKET_END) ||
13955 		    (dst_reg->type == PTR_TO_PACKET_META &&
13956 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13957 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13958 			find_good_pkt_pointers(other_branch, dst_reg,
13959 					       dst_reg->type, true);
13960 			mark_pkt_end(this_branch, insn->dst_reg, false);
13961 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13962 			    src_reg->type == PTR_TO_PACKET) ||
13963 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13964 			    src_reg->type == PTR_TO_PACKET_META)) {
13965 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13966 			find_good_pkt_pointers(this_branch, src_reg,
13967 					       src_reg->type, false);
13968 			mark_pkt_end(other_branch, insn->src_reg, true);
13969 		} else {
13970 			return false;
13971 		}
13972 		break;
13973 	case BPF_JGE:
13974 		if ((dst_reg->type == PTR_TO_PACKET &&
13975 		     src_reg->type == PTR_TO_PACKET_END) ||
13976 		    (dst_reg->type == PTR_TO_PACKET_META &&
13977 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13978 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13979 			find_good_pkt_pointers(this_branch, dst_reg,
13980 					       dst_reg->type, true);
13981 			mark_pkt_end(other_branch, insn->dst_reg, false);
13982 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13983 			    src_reg->type == PTR_TO_PACKET) ||
13984 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13985 			    src_reg->type == PTR_TO_PACKET_META)) {
13986 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13987 			find_good_pkt_pointers(other_branch, src_reg,
13988 					       src_reg->type, false);
13989 			mark_pkt_end(this_branch, insn->src_reg, true);
13990 		} else {
13991 			return false;
13992 		}
13993 		break;
13994 	case BPF_JLE:
13995 		if ((dst_reg->type == PTR_TO_PACKET &&
13996 		     src_reg->type == PTR_TO_PACKET_END) ||
13997 		    (dst_reg->type == PTR_TO_PACKET_META &&
13998 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13999 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14000 			find_good_pkt_pointers(other_branch, dst_reg,
14001 					       dst_reg->type, false);
14002 			mark_pkt_end(this_branch, insn->dst_reg, true);
14003 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14004 			    src_reg->type == PTR_TO_PACKET) ||
14005 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14006 			    src_reg->type == PTR_TO_PACKET_META)) {
14007 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14008 			find_good_pkt_pointers(this_branch, src_reg,
14009 					       src_reg->type, true);
14010 			mark_pkt_end(other_branch, insn->src_reg, false);
14011 		} else {
14012 			return false;
14013 		}
14014 		break;
14015 	default:
14016 		return false;
14017 	}
14018 
14019 	return true;
14020 }
14021 
14022 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14023 			       struct bpf_reg_state *known_reg)
14024 {
14025 	struct bpf_func_state *state;
14026 	struct bpf_reg_state *reg;
14027 
14028 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14029 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14030 			copy_register_state(reg, known_reg);
14031 	}));
14032 }
14033 
14034 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14035 			     struct bpf_insn *insn, int *insn_idx)
14036 {
14037 	struct bpf_verifier_state *this_branch = env->cur_state;
14038 	struct bpf_verifier_state *other_branch;
14039 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14040 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14041 	struct bpf_reg_state *eq_branch_regs;
14042 	u8 opcode = BPF_OP(insn->code);
14043 	bool is_jmp32;
14044 	int pred = -1;
14045 	int err;
14046 
14047 	/* Only conditional jumps are expected to reach here. */
14048 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14049 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14050 		return -EINVAL;
14051 	}
14052 
14053 	/* check src2 operand */
14054 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14055 	if (err)
14056 		return err;
14057 
14058 	dst_reg = &regs[insn->dst_reg];
14059 	if (BPF_SRC(insn->code) == BPF_X) {
14060 		if (insn->imm != 0) {
14061 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14062 			return -EINVAL;
14063 		}
14064 
14065 		/* check src1 operand */
14066 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14067 		if (err)
14068 			return err;
14069 
14070 		src_reg = &regs[insn->src_reg];
14071 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14072 		    is_pointer_value(env, insn->src_reg)) {
14073 			verbose(env, "R%d pointer comparison prohibited\n",
14074 				insn->src_reg);
14075 			return -EACCES;
14076 		}
14077 	} else {
14078 		if (insn->src_reg != BPF_REG_0) {
14079 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14080 			return -EINVAL;
14081 		}
14082 	}
14083 
14084 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14085 
14086 	if (BPF_SRC(insn->code) == BPF_K) {
14087 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14088 	} else if (src_reg->type == SCALAR_VALUE &&
14089 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14090 		pred = is_branch_taken(dst_reg,
14091 				       tnum_subreg(src_reg->var_off).value,
14092 				       opcode,
14093 				       is_jmp32);
14094 	} else if (src_reg->type == SCALAR_VALUE &&
14095 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14096 		pred = is_branch_taken(dst_reg,
14097 				       src_reg->var_off.value,
14098 				       opcode,
14099 				       is_jmp32);
14100 	} else if (dst_reg->type == SCALAR_VALUE &&
14101 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14102 		pred = is_branch_taken(src_reg,
14103 				       tnum_subreg(dst_reg->var_off).value,
14104 				       flip_opcode(opcode),
14105 				       is_jmp32);
14106 	} else if (dst_reg->type == SCALAR_VALUE &&
14107 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14108 		pred = is_branch_taken(src_reg,
14109 				       dst_reg->var_off.value,
14110 				       flip_opcode(opcode),
14111 				       is_jmp32);
14112 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14113 		   reg_is_pkt_pointer_any(src_reg) &&
14114 		   !is_jmp32) {
14115 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14116 	}
14117 
14118 	if (pred >= 0) {
14119 		/* If we get here with a dst_reg pointer type it is because
14120 		 * above is_branch_taken() special cased the 0 comparison.
14121 		 */
14122 		if (!__is_pointer_value(false, dst_reg))
14123 			err = mark_chain_precision(env, insn->dst_reg);
14124 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14125 		    !__is_pointer_value(false, src_reg))
14126 			err = mark_chain_precision(env, insn->src_reg);
14127 		if (err)
14128 			return err;
14129 	}
14130 
14131 	if (pred == 1) {
14132 		/* Only follow the goto, ignore fall-through. If needed, push
14133 		 * the fall-through branch for simulation under speculative
14134 		 * execution.
14135 		 */
14136 		if (!env->bypass_spec_v1 &&
14137 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14138 					       *insn_idx))
14139 			return -EFAULT;
14140 		*insn_idx += insn->off;
14141 		return 0;
14142 	} else if (pred == 0) {
14143 		/* Only follow the fall-through branch, since that's where the
14144 		 * program will go. If needed, push the goto branch for
14145 		 * simulation under speculative execution.
14146 		 */
14147 		if (!env->bypass_spec_v1 &&
14148 		    !sanitize_speculative_path(env, insn,
14149 					       *insn_idx + insn->off + 1,
14150 					       *insn_idx))
14151 			return -EFAULT;
14152 		return 0;
14153 	}
14154 
14155 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14156 				  false);
14157 	if (!other_branch)
14158 		return -EFAULT;
14159 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14160 
14161 	/* detect if we are comparing against a constant value so we can adjust
14162 	 * our min/max values for our dst register.
14163 	 * this is only legit if both are scalars (or pointers to the same
14164 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14165 	 * because otherwise the different base pointers mean the offsets aren't
14166 	 * comparable.
14167 	 */
14168 	if (BPF_SRC(insn->code) == BPF_X) {
14169 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14170 
14171 		if (dst_reg->type == SCALAR_VALUE &&
14172 		    src_reg->type == SCALAR_VALUE) {
14173 			if (tnum_is_const(src_reg->var_off) ||
14174 			    (is_jmp32 &&
14175 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14176 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14177 						dst_reg,
14178 						src_reg->var_off.value,
14179 						tnum_subreg(src_reg->var_off).value,
14180 						opcode, is_jmp32);
14181 			else if (tnum_is_const(dst_reg->var_off) ||
14182 				 (is_jmp32 &&
14183 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14184 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14185 						    src_reg,
14186 						    dst_reg->var_off.value,
14187 						    tnum_subreg(dst_reg->var_off).value,
14188 						    opcode, is_jmp32);
14189 			else if (!is_jmp32 &&
14190 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14191 				/* Comparing for equality, we can combine knowledge */
14192 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14193 						    &other_branch_regs[insn->dst_reg],
14194 						    src_reg, dst_reg, opcode);
14195 			if (src_reg->id &&
14196 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14197 				find_equal_scalars(this_branch, src_reg);
14198 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14199 			}
14200 
14201 		}
14202 	} else if (dst_reg->type == SCALAR_VALUE) {
14203 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14204 					dst_reg, insn->imm, (u32)insn->imm,
14205 					opcode, is_jmp32);
14206 	}
14207 
14208 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14209 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14210 		find_equal_scalars(this_branch, dst_reg);
14211 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14212 	}
14213 
14214 	/* if one pointer register is compared to another pointer
14215 	 * register check if PTR_MAYBE_NULL could be lifted.
14216 	 * E.g. register A - maybe null
14217 	 *      register B - not null
14218 	 * for JNE A, B, ... - A is not null in the false branch;
14219 	 * for JEQ A, B, ... - A is not null in the true branch.
14220 	 *
14221 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14222 	 * not need to be null checked by the BPF program, i.e.,
14223 	 * could be null even without PTR_MAYBE_NULL marking, so
14224 	 * only propagate nullness when neither reg is that type.
14225 	 */
14226 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14227 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14228 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14229 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14230 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14231 		eq_branch_regs = NULL;
14232 		switch (opcode) {
14233 		case BPF_JEQ:
14234 			eq_branch_regs = other_branch_regs;
14235 			break;
14236 		case BPF_JNE:
14237 			eq_branch_regs = regs;
14238 			break;
14239 		default:
14240 			/* do nothing */
14241 			break;
14242 		}
14243 		if (eq_branch_regs) {
14244 			if (type_may_be_null(src_reg->type))
14245 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14246 			else
14247 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14248 		}
14249 	}
14250 
14251 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14252 	 * NOTE: these optimizations below are related with pointer comparison
14253 	 *       which will never be JMP32.
14254 	 */
14255 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14256 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14257 	    type_may_be_null(dst_reg->type)) {
14258 		/* Mark all identical registers in each branch as either
14259 		 * safe or unknown depending R == 0 or R != 0 conditional.
14260 		 */
14261 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14262 				      opcode == BPF_JNE);
14263 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14264 				      opcode == BPF_JEQ);
14265 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14266 					   this_branch, other_branch) &&
14267 		   is_pointer_value(env, insn->dst_reg)) {
14268 		verbose(env, "R%d pointer comparison prohibited\n",
14269 			insn->dst_reg);
14270 		return -EACCES;
14271 	}
14272 	if (env->log.level & BPF_LOG_LEVEL)
14273 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14274 	return 0;
14275 }
14276 
14277 /* verify BPF_LD_IMM64 instruction */
14278 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14279 {
14280 	struct bpf_insn_aux_data *aux = cur_aux(env);
14281 	struct bpf_reg_state *regs = cur_regs(env);
14282 	struct bpf_reg_state *dst_reg;
14283 	struct bpf_map *map;
14284 	int err;
14285 
14286 	if (BPF_SIZE(insn->code) != BPF_DW) {
14287 		verbose(env, "invalid BPF_LD_IMM insn\n");
14288 		return -EINVAL;
14289 	}
14290 	if (insn->off != 0) {
14291 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14292 		return -EINVAL;
14293 	}
14294 
14295 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14296 	if (err)
14297 		return err;
14298 
14299 	dst_reg = &regs[insn->dst_reg];
14300 	if (insn->src_reg == 0) {
14301 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14302 
14303 		dst_reg->type = SCALAR_VALUE;
14304 		__mark_reg_known(&regs[insn->dst_reg], imm);
14305 		return 0;
14306 	}
14307 
14308 	/* All special src_reg cases are listed below. From this point onwards
14309 	 * we either succeed and assign a corresponding dst_reg->type after
14310 	 * zeroing the offset, or fail and reject the program.
14311 	 */
14312 	mark_reg_known_zero(env, regs, insn->dst_reg);
14313 
14314 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14315 		dst_reg->type = aux->btf_var.reg_type;
14316 		switch (base_type(dst_reg->type)) {
14317 		case PTR_TO_MEM:
14318 			dst_reg->mem_size = aux->btf_var.mem_size;
14319 			break;
14320 		case PTR_TO_BTF_ID:
14321 			dst_reg->btf = aux->btf_var.btf;
14322 			dst_reg->btf_id = aux->btf_var.btf_id;
14323 			break;
14324 		default:
14325 			verbose(env, "bpf verifier is misconfigured\n");
14326 			return -EFAULT;
14327 		}
14328 		return 0;
14329 	}
14330 
14331 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14332 		struct bpf_prog_aux *aux = env->prog->aux;
14333 		u32 subprogno = find_subprog(env,
14334 					     env->insn_idx + insn->imm + 1);
14335 
14336 		if (!aux->func_info) {
14337 			verbose(env, "missing btf func_info\n");
14338 			return -EINVAL;
14339 		}
14340 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14341 			verbose(env, "callback function not static\n");
14342 			return -EINVAL;
14343 		}
14344 
14345 		dst_reg->type = PTR_TO_FUNC;
14346 		dst_reg->subprogno = subprogno;
14347 		return 0;
14348 	}
14349 
14350 	map = env->used_maps[aux->map_index];
14351 	dst_reg->map_ptr = map;
14352 
14353 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14354 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14355 		dst_reg->type = PTR_TO_MAP_VALUE;
14356 		dst_reg->off = aux->map_off;
14357 		WARN_ON_ONCE(map->max_entries != 1);
14358 		/* We want reg->id to be same (0) as map_value is not distinct */
14359 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14360 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14361 		dst_reg->type = CONST_PTR_TO_MAP;
14362 	} else {
14363 		verbose(env, "bpf verifier is misconfigured\n");
14364 		return -EINVAL;
14365 	}
14366 
14367 	return 0;
14368 }
14369 
14370 static bool may_access_skb(enum bpf_prog_type type)
14371 {
14372 	switch (type) {
14373 	case BPF_PROG_TYPE_SOCKET_FILTER:
14374 	case BPF_PROG_TYPE_SCHED_CLS:
14375 	case BPF_PROG_TYPE_SCHED_ACT:
14376 		return true;
14377 	default:
14378 		return false;
14379 	}
14380 }
14381 
14382 /* verify safety of LD_ABS|LD_IND instructions:
14383  * - they can only appear in the programs where ctx == skb
14384  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14385  *   preserve R6-R9, and store return value into R0
14386  *
14387  * Implicit input:
14388  *   ctx == skb == R6 == CTX
14389  *
14390  * Explicit input:
14391  *   SRC == any register
14392  *   IMM == 32-bit immediate
14393  *
14394  * Output:
14395  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14396  */
14397 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14398 {
14399 	struct bpf_reg_state *regs = cur_regs(env);
14400 	static const int ctx_reg = BPF_REG_6;
14401 	u8 mode = BPF_MODE(insn->code);
14402 	int i, err;
14403 
14404 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14405 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14406 		return -EINVAL;
14407 	}
14408 
14409 	if (!env->ops->gen_ld_abs) {
14410 		verbose(env, "bpf verifier is misconfigured\n");
14411 		return -EINVAL;
14412 	}
14413 
14414 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14415 	    BPF_SIZE(insn->code) == BPF_DW ||
14416 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14417 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14418 		return -EINVAL;
14419 	}
14420 
14421 	/* check whether implicit source operand (register R6) is readable */
14422 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14423 	if (err)
14424 		return err;
14425 
14426 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14427 	 * gen_ld_abs() may terminate the program at runtime, leading to
14428 	 * reference leak.
14429 	 */
14430 	err = check_reference_leak(env);
14431 	if (err) {
14432 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14433 		return err;
14434 	}
14435 
14436 	if (env->cur_state->active_lock.ptr) {
14437 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14438 		return -EINVAL;
14439 	}
14440 
14441 	if (env->cur_state->active_rcu_lock) {
14442 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14443 		return -EINVAL;
14444 	}
14445 
14446 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14447 		verbose(env,
14448 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14449 		return -EINVAL;
14450 	}
14451 
14452 	if (mode == BPF_IND) {
14453 		/* check explicit source operand */
14454 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14455 		if (err)
14456 			return err;
14457 	}
14458 
14459 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14460 	if (err < 0)
14461 		return err;
14462 
14463 	/* reset caller saved regs to unreadable */
14464 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14465 		mark_reg_not_init(env, regs, caller_saved[i]);
14466 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14467 	}
14468 
14469 	/* mark destination R0 register as readable, since it contains
14470 	 * the value fetched from the packet.
14471 	 * Already marked as written above.
14472 	 */
14473 	mark_reg_unknown(env, regs, BPF_REG_0);
14474 	/* ld_abs load up to 32-bit skb data. */
14475 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14476 	return 0;
14477 }
14478 
14479 static int check_return_code(struct bpf_verifier_env *env)
14480 {
14481 	struct tnum enforce_attach_type_range = tnum_unknown;
14482 	const struct bpf_prog *prog = env->prog;
14483 	struct bpf_reg_state *reg;
14484 	struct tnum range = tnum_range(0, 1);
14485 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14486 	int err;
14487 	struct bpf_func_state *frame = env->cur_state->frame[0];
14488 	const bool is_subprog = frame->subprogno;
14489 
14490 	/* LSM and struct_ops func-ptr's return type could be "void" */
14491 	if (!is_subprog) {
14492 		switch (prog_type) {
14493 		case BPF_PROG_TYPE_LSM:
14494 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14495 				/* See below, can be 0 or 0-1 depending on hook. */
14496 				break;
14497 			fallthrough;
14498 		case BPF_PROG_TYPE_STRUCT_OPS:
14499 			if (!prog->aux->attach_func_proto->type)
14500 				return 0;
14501 			break;
14502 		default:
14503 			break;
14504 		}
14505 	}
14506 
14507 	/* eBPF calling convention is such that R0 is used
14508 	 * to return the value from eBPF program.
14509 	 * Make sure that it's readable at this time
14510 	 * of bpf_exit, which means that program wrote
14511 	 * something into it earlier
14512 	 */
14513 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14514 	if (err)
14515 		return err;
14516 
14517 	if (is_pointer_value(env, BPF_REG_0)) {
14518 		verbose(env, "R0 leaks addr as return value\n");
14519 		return -EACCES;
14520 	}
14521 
14522 	reg = cur_regs(env) + BPF_REG_0;
14523 
14524 	if (frame->in_async_callback_fn) {
14525 		/* enforce return zero from async callbacks like timer */
14526 		if (reg->type != SCALAR_VALUE) {
14527 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14528 				reg_type_str(env, reg->type));
14529 			return -EINVAL;
14530 		}
14531 
14532 		if (!tnum_in(tnum_const(0), reg->var_off)) {
14533 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14534 			return -EINVAL;
14535 		}
14536 		return 0;
14537 	}
14538 
14539 	if (is_subprog) {
14540 		if (reg->type != SCALAR_VALUE) {
14541 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14542 				reg_type_str(env, reg->type));
14543 			return -EINVAL;
14544 		}
14545 		return 0;
14546 	}
14547 
14548 	switch (prog_type) {
14549 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14550 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14551 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14552 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14553 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14554 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14555 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14556 			range = tnum_range(1, 1);
14557 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14558 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14559 			range = tnum_range(0, 3);
14560 		break;
14561 	case BPF_PROG_TYPE_CGROUP_SKB:
14562 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14563 			range = tnum_range(0, 3);
14564 			enforce_attach_type_range = tnum_range(2, 3);
14565 		}
14566 		break;
14567 	case BPF_PROG_TYPE_CGROUP_SOCK:
14568 	case BPF_PROG_TYPE_SOCK_OPS:
14569 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14570 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14571 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14572 		break;
14573 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14574 		if (!env->prog->aux->attach_btf_id)
14575 			return 0;
14576 		range = tnum_const(0);
14577 		break;
14578 	case BPF_PROG_TYPE_TRACING:
14579 		switch (env->prog->expected_attach_type) {
14580 		case BPF_TRACE_FENTRY:
14581 		case BPF_TRACE_FEXIT:
14582 			range = tnum_const(0);
14583 			break;
14584 		case BPF_TRACE_RAW_TP:
14585 		case BPF_MODIFY_RETURN:
14586 			return 0;
14587 		case BPF_TRACE_ITER:
14588 			break;
14589 		default:
14590 			return -ENOTSUPP;
14591 		}
14592 		break;
14593 	case BPF_PROG_TYPE_SK_LOOKUP:
14594 		range = tnum_range(SK_DROP, SK_PASS);
14595 		break;
14596 
14597 	case BPF_PROG_TYPE_LSM:
14598 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14599 			/* Regular BPF_PROG_TYPE_LSM programs can return
14600 			 * any value.
14601 			 */
14602 			return 0;
14603 		}
14604 		if (!env->prog->aux->attach_func_proto->type) {
14605 			/* Make sure programs that attach to void
14606 			 * hooks don't try to modify return value.
14607 			 */
14608 			range = tnum_range(1, 1);
14609 		}
14610 		break;
14611 
14612 	case BPF_PROG_TYPE_NETFILTER:
14613 		range = tnum_range(NF_DROP, NF_ACCEPT);
14614 		break;
14615 	case BPF_PROG_TYPE_EXT:
14616 		/* freplace program can return anything as its return value
14617 		 * depends on the to-be-replaced kernel func or bpf program.
14618 		 */
14619 	default:
14620 		return 0;
14621 	}
14622 
14623 	if (reg->type != SCALAR_VALUE) {
14624 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14625 			reg_type_str(env, reg->type));
14626 		return -EINVAL;
14627 	}
14628 
14629 	if (!tnum_in(range, reg->var_off)) {
14630 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14631 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14632 		    prog_type == BPF_PROG_TYPE_LSM &&
14633 		    !prog->aux->attach_func_proto->type)
14634 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14635 		return -EINVAL;
14636 	}
14637 
14638 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14639 	    tnum_in(enforce_attach_type_range, reg->var_off))
14640 		env->prog->enforce_expected_attach_type = 1;
14641 	return 0;
14642 }
14643 
14644 /* non-recursive DFS pseudo code
14645  * 1  procedure DFS-iterative(G,v):
14646  * 2      label v as discovered
14647  * 3      let S be a stack
14648  * 4      S.push(v)
14649  * 5      while S is not empty
14650  * 6            t <- S.peek()
14651  * 7            if t is what we're looking for:
14652  * 8                return t
14653  * 9            for all edges e in G.adjacentEdges(t) do
14654  * 10               if edge e is already labelled
14655  * 11                   continue with the next edge
14656  * 12               w <- G.adjacentVertex(t,e)
14657  * 13               if vertex w is not discovered and not explored
14658  * 14                   label e as tree-edge
14659  * 15                   label w as discovered
14660  * 16                   S.push(w)
14661  * 17                   continue at 5
14662  * 18               else if vertex w is discovered
14663  * 19                   label e as back-edge
14664  * 20               else
14665  * 21                   // vertex w is explored
14666  * 22                   label e as forward- or cross-edge
14667  * 23           label t as explored
14668  * 24           S.pop()
14669  *
14670  * convention:
14671  * 0x10 - discovered
14672  * 0x11 - discovered and fall-through edge labelled
14673  * 0x12 - discovered and fall-through and branch edges labelled
14674  * 0x20 - explored
14675  */
14676 
14677 enum {
14678 	DISCOVERED = 0x10,
14679 	EXPLORED = 0x20,
14680 	FALLTHROUGH = 1,
14681 	BRANCH = 2,
14682 };
14683 
14684 static u32 state_htab_size(struct bpf_verifier_env *env)
14685 {
14686 	return env->prog->len;
14687 }
14688 
14689 static struct bpf_verifier_state_list **explored_state(
14690 					struct bpf_verifier_env *env,
14691 					int idx)
14692 {
14693 	struct bpf_verifier_state *cur = env->cur_state;
14694 	struct bpf_func_state *state = cur->frame[cur->curframe];
14695 
14696 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14697 }
14698 
14699 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14700 {
14701 	env->insn_aux_data[idx].prune_point = true;
14702 }
14703 
14704 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14705 {
14706 	return env->insn_aux_data[insn_idx].prune_point;
14707 }
14708 
14709 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14710 {
14711 	env->insn_aux_data[idx].force_checkpoint = true;
14712 }
14713 
14714 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14715 {
14716 	return env->insn_aux_data[insn_idx].force_checkpoint;
14717 }
14718 
14719 
14720 enum {
14721 	DONE_EXPLORING = 0,
14722 	KEEP_EXPLORING = 1,
14723 };
14724 
14725 /* t, w, e - match pseudo-code above:
14726  * t - index of current instruction
14727  * w - next instruction
14728  * e - edge
14729  */
14730 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14731 		     bool loop_ok)
14732 {
14733 	int *insn_stack = env->cfg.insn_stack;
14734 	int *insn_state = env->cfg.insn_state;
14735 
14736 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14737 		return DONE_EXPLORING;
14738 
14739 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14740 		return DONE_EXPLORING;
14741 
14742 	if (w < 0 || w >= env->prog->len) {
14743 		verbose_linfo(env, t, "%d: ", t);
14744 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14745 		return -EINVAL;
14746 	}
14747 
14748 	if (e == BRANCH) {
14749 		/* mark branch target for state pruning */
14750 		mark_prune_point(env, w);
14751 		mark_jmp_point(env, w);
14752 	}
14753 
14754 	if (insn_state[w] == 0) {
14755 		/* tree-edge */
14756 		insn_state[t] = DISCOVERED | e;
14757 		insn_state[w] = DISCOVERED;
14758 		if (env->cfg.cur_stack >= env->prog->len)
14759 			return -E2BIG;
14760 		insn_stack[env->cfg.cur_stack++] = w;
14761 		return KEEP_EXPLORING;
14762 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14763 		if (loop_ok && env->bpf_capable)
14764 			return DONE_EXPLORING;
14765 		verbose_linfo(env, t, "%d: ", t);
14766 		verbose_linfo(env, w, "%d: ", w);
14767 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14768 		return -EINVAL;
14769 	} else if (insn_state[w] == EXPLORED) {
14770 		/* forward- or cross-edge */
14771 		insn_state[t] = DISCOVERED | e;
14772 	} else {
14773 		verbose(env, "insn state internal bug\n");
14774 		return -EFAULT;
14775 	}
14776 	return DONE_EXPLORING;
14777 }
14778 
14779 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14780 				struct bpf_verifier_env *env,
14781 				bool visit_callee)
14782 {
14783 	int ret;
14784 
14785 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14786 	if (ret)
14787 		return ret;
14788 
14789 	mark_prune_point(env, t + 1);
14790 	/* when we exit from subprog, we need to record non-linear history */
14791 	mark_jmp_point(env, t + 1);
14792 
14793 	if (visit_callee) {
14794 		mark_prune_point(env, t);
14795 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14796 				/* It's ok to allow recursion from CFG point of
14797 				 * view. __check_func_call() will do the actual
14798 				 * check.
14799 				 */
14800 				bpf_pseudo_func(insns + t));
14801 	}
14802 	return ret;
14803 }
14804 
14805 /* Visits the instruction at index t and returns one of the following:
14806  *  < 0 - an error occurred
14807  *  DONE_EXPLORING - the instruction was fully explored
14808  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14809  */
14810 static int visit_insn(int t, struct bpf_verifier_env *env)
14811 {
14812 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14813 	int ret, off;
14814 
14815 	if (bpf_pseudo_func(insn))
14816 		return visit_func_call_insn(t, insns, env, true);
14817 
14818 	/* All non-branch instructions have a single fall-through edge. */
14819 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14820 	    BPF_CLASS(insn->code) != BPF_JMP32)
14821 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14822 
14823 	switch (BPF_OP(insn->code)) {
14824 	case BPF_EXIT:
14825 		return DONE_EXPLORING;
14826 
14827 	case BPF_CALL:
14828 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14829 			/* Mark this call insn as a prune point to trigger
14830 			 * is_state_visited() check before call itself is
14831 			 * processed by __check_func_call(). Otherwise new
14832 			 * async state will be pushed for further exploration.
14833 			 */
14834 			mark_prune_point(env, t);
14835 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14836 			struct bpf_kfunc_call_arg_meta meta;
14837 
14838 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14839 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14840 				mark_prune_point(env, t);
14841 				/* Checking and saving state checkpoints at iter_next() call
14842 				 * is crucial for fast convergence of open-coded iterator loop
14843 				 * logic, so we need to force it. If we don't do that,
14844 				 * is_state_visited() might skip saving a checkpoint, causing
14845 				 * unnecessarily long sequence of not checkpointed
14846 				 * instructions and jumps, leading to exhaustion of jump
14847 				 * history buffer, and potentially other undesired outcomes.
14848 				 * It is expected that with correct open-coded iterators
14849 				 * convergence will happen quickly, so we don't run a risk of
14850 				 * exhausting memory.
14851 				 */
14852 				mark_force_checkpoint(env, t);
14853 			}
14854 		}
14855 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14856 
14857 	case BPF_JA:
14858 		if (BPF_SRC(insn->code) != BPF_K)
14859 			return -EINVAL;
14860 
14861 		if (BPF_CLASS(insn->code) == BPF_JMP)
14862 			off = insn->off;
14863 		else
14864 			off = insn->imm;
14865 
14866 		/* unconditional jump with single edge */
14867 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env,
14868 				true);
14869 		if (ret)
14870 			return ret;
14871 
14872 		mark_prune_point(env, t + off + 1);
14873 		mark_jmp_point(env, t + off + 1);
14874 
14875 		return ret;
14876 
14877 	default:
14878 		/* conditional jump with two edges */
14879 		mark_prune_point(env, t);
14880 
14881 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14882 		if (ret)
14883 			return ret;
14884 
14885 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14886 	}
14887 }
14888 
14889 /* non-recursive depth-first-search to detect loops in BPF program
14890  * loop == back-edge in directed graph
14891  */
14892 static int check_cfg(struct bpf_verifier_env *env)
14893 {
14894 	int insn_cnt = env->prog->len;
14895 	int *insn_stack, *insn_state;
14896 	int ret = 0;
14897 	int i;
14898 
14899 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14900 	if (!insn_state)
14901 		return -ENOMEM;
14902 
14903 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14904 	if (!insn_stack) {
14905 		kvfree(insn_state);
14906 		return -ENOMEM;
14907 	}
14908 
14909 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14910 	insn_stack[0] = 0; /* 0 is the first instruction */
14911 	env->cfg.cur_stack = 1;
14912 
14913 	while (env->cfg.cur_stack > 0) {
14914 		int t = insn_stack[env->cfg.cur_stack - 1];
14915 
14916 		ret = visit_insn(t, env);
14917 		switch (ret) {
14918 		case DONE_EXPLORING:
14919 			insn_state[t] = EXPLORED;
14920 			env->cfg.cur_stack--;
14921 			break;
14922 		case KEEP_EXPLORING:
14923 			break;
14924 		default:
14925 			if (ret > 0) {
14926 				verbose(env, "visit_insn internal bug\n");
14927 				ret = -EFAULT;
14928 			}
14929 			goto err_free;
14930 		}
14931 	}
14932 
14933 	if (env->cfg.cur_stack < 0) {
14934 		verbose(env, "pop stack internal bug\n");
14935 		ret = -EFAULT;
14936 		goto err_free;
14937 	}
14938 
14939 	for (i = 0; i < insn_cnt; i++) {
14940 		if (insn_state[i] != EXPLORED) {
14941 			verbose(env, "unreachable insn %d\n", i);
14942 			ret = -EINVAL;
14943 			goto err_free;
14944 		}
14945 	}
14946 	ret = 0; /* cfg looks good */
14947 
14948 err_free:
14949 	kvfree(insn_state);
14950 	kvfree(insn_stack);
14951 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14952 	return ret;
14953 }
14954 
14955 static int check_abnormal_return(struct bpf_verifier_env *env)
14956 {
14957 	int i;
14958 
14959 	for (i = 1; i < env->subprog_cnt; i++) {
14960 		if (env->subprog_info[i].has_ld_abs) {
14961 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14962 			return -EINVAL;
14963 		}
14964 		if (env->subprog_info[i].has_tail_call) {
14965 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14966 			return -EINVAL;
14967 		}
14968 	}
14969 	return 0;
14970 }
14971 
14972 /* The minimum supported BTF func info size */
14973 #define MIN_BPF_FUNCINFO_SIZE	8
14974 #define MAX_FUNCINFO_REC_SIZE	252
14975 
14976 static int check_btf_func(struct bpf_verifier_env *env,
14977 			  const union bpf_attr *attr,
14978 			  bpfptr_t uattr)
14979 {
14980 	const struct btf_type *type, *func_proto, *ret_type;
14981 	u32 i, nfuncs, urec_size, min_size;
14982 	u32 krec_size = sizeof(struct bpf_func_info);
14983 	struct bpf_func_info *krecord;
14984 	struct bpf_func_info_aux *info_aux = NULL;
14985 	struct bpf_prog *prog;
14986 	const struct btf *btf;
14987 	bpfptr_t urecord;
14988 	u32 prev_offset = 0;
14989 	bool scalar_return;
14990 	int ret = -ENOMEM;
14991 
14992 	nfuncs = attr->func_info_cnt;
14993 	if (!nfuncs) {
14994 		if (check_abnormal_return(env))
14995 			return -EINVAL;
14996 		return 0;
14997 	}
14998 
14999 	if (nfuncs != env->subprog_cnt) {
15000 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15001 		return -EINVAL;
15002 	}
15003 
15004 	urec_size = attr->func_info_rec_size;
15005 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15006 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15007 	    urec_size % sizeof(u32)) {
15008 		verbose(env, "invalid func info rec size %u\n", urec_size);
15009 		return -EINVAL;
15010 	}
15011 
15012 	prog = env->prog;
15013 	btf = prog->aux->btf;
15014 
15015 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15016 	min_size = min_t(u32, krec_size, urec_size);
15017 
15018 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15019 	if (!krecord)
15020 		return -ENOMEM;
15021 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15022 	if (!info_aux)
15023 		goto err_free;
15024 
15025 	for (i = 0; i < nfuncs; i++) {
15026 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15027 		if (ret) {
15028 			if (ret == -E2BIG) {
15029 				verbose(env, "nonzero tailing record in func info");
15030 				/* set the size kernel expects so loader can zero
15031 				 * out the rest of the record.
15032 				 */
15033 				if (copy_to_bpfptr_offset(uattr,
15034 							  offsetof(union bpf_attr, func_info_rec_size),
15035 							  &min_size, sizeof(min_size)))
15036 					ret = -EFAULT;
15037 			}
15038 			goto err_free;
15039 		}
15040 
15041 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15042 			ret = -EFAULT;
15043 			goto err_free;
15044 		}
15045 
15046 		/* check insn_off */
15047 		ret = -EINVAL;
15048 		if (i == 0) {
15049 			if (krecord[i].insn_off) {
15050 				verbose(env,
15051 					"nonzero insn_off %u for the first func info record",
15052 					krecord[i].insn_off);
15053 				goto err_free;
15054 			}
15055 		} else if (krecord[i].insn_off <= prev_offset) {
15056 			verbose(env,
15057 				"same or smaller insn offset (%u) than previous func info record (%u)",
15058 				krecord[i].insn_off, prev_offset);
15059 			goto err_free;
15060 		}
15061 
15062 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15063 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15064 			goto err_free;
15065 		}
15066 
15067 		/* check type_id */
15068 		type = btf_type_by_id(btf, krecord[i].type_id);
15069 		if (!type || !btf_type_is_func(type)) {
15070 			verbose(env, "invalid type id %d in func info",
15071 				krecord[i].type_id);
15072 			goto err_free;
15073 		}
15074 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15075 
15076 		func_proto = btf_type_by_id(btf, type->type);
15077 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15078 			/* btf_func_check() already verified it during BTF load */
15079 			goto err_free;
15080 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15081 		scalar_return =
15082 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15083 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15084 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15085 			goto err_free;
15086 		}
15087 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15088 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15089 			goto err_free;
15090 		}
15091 
15092 		prev_offset = krecord[i].insn_off;
15093 		bpfptr_add(&urecord, urec_size);
15094 	}
15095 
15096 	prog->aux->func_info = krecord;
15097 	prog->aux->func_info_cnt = nfuncs;
15098 	prog->aux->func_info_aux = info_aux;
15099 	return 0;
15100 
15101 err_free:
15102 	kvfree(krecord);
15103 	kfree(info_aux);
15104 	return ret;
15105 }
15106 
15107 static void adjust_btf_func(struct bpf_verifier_env *env)
15108 {
15109 	struct bpf_prog_aux *aux = env->prog->aux;
15110 	int i;
15111 
15112 	if (!aux->func_info)
15113 		return;
15114 
15115 	for (i = 0; i < env->subprog_cnt; i++)
15116 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15117 }
15118 
15119 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15120 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15121 
15122 static int check_btf_line(struct bpf_verifier_env *env,
15123 			  const union bpf_attr *attr,
15124 			  bpfptr_t uattr)
15125 {
15126 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15127 	struct bpf_subprog_info *sub;
15128 	struct bpf_line_info *linfo;
15129 	struct bpf_prog *prog;
15130 	const struct btf *btf;
15131 	bpfptr_t ulinfo;
15132 	int err;
15133 
15134 	nr_linfo = attr->line_info_cnt;
15135 	if (!nr_linfo)
15136 		return 0;
15137 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15138 		return -EINVAL;
15139 
15140 	rec_size = attr->line_info_rec_size;
15141 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15142 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15143 	    rec_size & (sizeof(u32) - 1))
15144 		return -EINVAL;
15145 
15146 	/* Need to zero it in case the userspace may
15147 	 * pass in a smaller bpf_line_info object.
15148 	 */
15149 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15150 			 GFP_KERNEL | __GFP_NOWARN);
15151 	if (!linfo)
15152 		return -ENOMEM;
15153 
15154 	prog = env->prog;
15155 	btf = prog->aux->btf;
15156 
15157 	s = 0;
15158 	sub = env->subprog_info;
15159 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15160 	expected_size = sizeof(struct bpf_line_info);
15161 	ncopy = min_t(u32, expected_size, rec_size);
15162 	for (i = 0; i < nr_linfo; i++) {
15163 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15164 		if (err) {
15165 			if (err == -E2BIG) {
15166 				verbose(env, "nonzero tailing record in line_info");
15167 				if (copy_to_bpfptr_offset(uattr,
15168 							  offsetof(union bpf_attr, line_info_rec_size),
15169 							  &expected_size, sizeof(expected_size)))
15170 					err = -EFAULT;
15171 			}
15172 			goto err_free;
15173 		}
15174 
15175 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15176 			err = -EFAULT;
15177 			goto err_free;
15178 		}
15179 
15180 		/*
15181 		 * Check insn_off to ensure
15182 		 * 1) strictly increasing AND
15183 		 * 2) bounded by prog->len
15184 		 *
15185 		 * The linfo[0].insn_off == 0 check logically falls into
15186 		 * the later "missing bpf_line_info for func..." case
15187 		 * because the first linfo[0].insn_off must be the
15188 		 * first sub also and the first sub must have
15189 		 * subprog_info[0].start == 0.
15190 		 */
15191 		if ((i && linfo[i].insn_off <= prev_offset) ||
15192 		    linfo[i].insn_off >= prog->len) {
15193 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15194 				i, linfo[i].insn_off, prev_offset,
15195 				prog->len);
15196 			err = -EINVAL;
15197 			goto err_free;
15198 		}
15199 
15200 		if (!prog->insnsi[linfo[i].insn_off].code) {
15201 			verbose(env,
15202 				"Invalid insn code at line_info[%u].insn_off\n",
15203 				i);
15204 			err = -EINVAL;
15205 			goto err_free;
15206 		}
15207 
15208 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15209 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15210 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15211 			err = -EINVAL;
15212 			goto err_free;
15213 		}
15214 
15215 		if (s != env->subprog_cnt) {
15216 			if (linfo[i].insn_off == sub[s].start) {
15217 				sub[s].linfo_idx = i;
15218 				s++;
15219 			} else if (sub[s].start < linfo[i].insn_off) {
15220 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15221 				err = -EINVAL;
15222 				goto err_free;
15223 			}
15224 		}
15225 
15226 		prev_offset = linfo[i].insn_off;
15227 		bpfptr_add(&ulinfo, rec_size);
15228 	}
15229 
15230 	if (s != env->subprog_cnt) {
15231 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15232 			env->subprog_cnt - s, s);
15233 		err = -EINVAL;
15234 		goto err_free;
15235 	}
15236 
15237 	prog->aux->linfo = linfo;
15238 	prog->aux->nr_linfo = nr_linfo;
15239 
15240 	return 0;
15241 
15242 err_free:
15243 	kvfree(linfo);
15244 	return err;
15245 }
15246 
15247 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15248 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15249 
15250 static int check_core_relo(struct bpf_verifier_env *env,
15251 			   const union bpf_attr *attr,
15252 			   bpfptr_t uattr)
15253 {
15254 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15255 	struct bpf_core_relo core_relo = {};
15256 	struct bpf_prog *prog = env->prog;
15257 	const struct btf *btf = prog->aux->btf;
15258 	struct bpf_core_ctx ctx = {
15259 		.log = &env->log,
15260 		.btf = btf,
15261 	};
15262 	bpfptr_t u_core_relo;
15263 	int err;
15264 
15265 	nr_core_relo = attr->core_relo_cnt;
15266 	if (!nr_core_relo)
15267 		return 0;
15268 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15269 		return -EINVAL;
15270 
15271 	rec_size = attr->core_relo_rec_size;
15272 	if (rec_size < MIN_CORE_RELO_SIZE ||
15273 	    rec_size > MAX_CORE_RELO_SIZE ||
15274 	    rec_size % sizeof(u32))
15275 		return -EINVAL;
15276 
15277 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15278 	expected_size = sizeof(struct bpf_core_relo);
15279 	ncopy = min_t(u32, expected_size, rec_size);
15280 
15281 	/* Unlike func_info and line_info, copy and apply each CO-RE
15282 	 * relocation record one at a time.
15283 	 */
15284 	for (i = 0; i < nr_core_relo; i++) {
15285 		/* future proofing when sizeof(bpf_core_relo) changes */
15286 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15287 		if (err) {
15288 			if (err == -E2BIG) {
15289 				verbose(env, "nonzero tailing record in core_relo");
15290 				if (copy_to_bpfptr_offset(uattr,
15291 							  offsetof(union bpf_attr, core_relo_rec_size),
15292 							  &expected_size, sizeof(expected_size)))
15293 					err = -EFAULT;
15294 			}
15295 			break;
15296 		}
15297 
15298 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15299 			err = -EFAULT;
15300 			break;
15301 		}
15302 
15303 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15304 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15305 				i, core_relo.insn_off, prog->len);
15306 			err = -EINVAL;
15307 			break;
15308 		}
15309 
15310 		err = bpf_core_apply(&ctx, &core_relo, i,
15311 				     &prog->insnsi[core_relo.insn_off / 8]);
15312 		if (err)
15313 			break;
15314 		bpfptr_add(&u_core_relo, rec_size);
15315 	}
15316 	return err;
15317 }
15318 
15319 static int check_btf_info(struct bpf_verifier_env *env,
15320 			  const union bpf_attr *attr,
15321 			  bpfptr_t uattr)
15322 {
15323 	struct btf *btf;
15324 	int err;
15325 
15326 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15327 		if (check_abnormal_return(env))
15328 			return -EINVAL;
15329 		return 0;
15330 	}
15331 
15332 	btf = btf_get_by_fd(attr->prog_btf_fd);
15333 	if (IS_ERR(btf))
15334 		return PTR_ERR(btf);
15335 	if (btf_is_kernel(btf)) {
15336 		btf_put(btf);
15337 		return -EACCES;
15338 	}
15339 	env->prog->aux->btf = btf;
15340 
15341 	err = check_btf_func(env, attr, uattr);
15342 	if (err)
15343 		return err;
15344 
15345 	err = check_btf_line(env, attr, uattr);
15346 	if (err)
15347 		return err;
15348 
15349 	err = check_core_relo(env, attr, uattr);
15350 	if (err)
15351 		return err;
15352 
15353 	return 0;
15354 }
15355 
15356 /* check %cur's range satisfies %old's */
15357 static bool range_within(struct bpf_reg_state *old,
15358 			 struct bpf_reg_state *cur)
15359 {
15360 	return old->umin_value <= cur->umin_value &&
15361 	       old->umax_value >= cur->umax_value &&
15362 	       old->smin_value <= cur->smin_value &&
15363 	       old->smax_value >= cur->smax_value &&
15364 	       old->u32_min_value <= cur->u32_min_value &&
15365 	       old->u32_max_value >= cur->u32_max_value &&
15366 	       old->s32_min_value <= cur->s32_min_value &&
15367 	       old->s32_max_value >= cur->s32_max_value;
15368 }
15369 
15370 /* If in the old state two registers had the same id, then they need to have
15371  * the same id in the new state as well.  But that id could be different from
15372  * the old state, so we need to track the mapping from old to new ids.
15373  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15374  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15375  * regs with a different old id could still have new id 9, we don't care about
15376  * that.
15377  * So we look through our idmap to see if this old id has been seen before.  If
15378  * so, we require the new id to match; otherwise, we add the id pair to the map.
15379  */
15380 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15381 {
15382 	struct bpf_id_pair *map = idmap->map;
15383 	unsigned int i;
15384 
15385 	/* either both IDs should be set or both should be zero */
15386 	if (!!old_id != !!cur_id)
15387 		return false;
15388 
15389 	if (old_id == 0) /* cur_id == 0 as well */
15390 		return true;
15391 
15392 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15393 		if (!map[i].old) {
15394 			/* Reached an empty slot; haven't seen this id before */
15395 			map[i].old = old_id;
15396 			map[i].cur = cur_id;
15397 			return true;
15398 		}
15399 		if (map[i].old == old_id)
15400 			return map[i].cur == cur_id;
15401 		if (map[i].cur == cur_id)
15402 			return false;
15403 	}
15404 	/* We ran out of idmap slots, which should be impossible */
15405 	WARN_ON_ONCE(1);
15406 	return false;
15407 }
15408 
15409 /* Similar to check_ids(), but allocate a unique temporary ID
15410  * for 'old_id' or 'cur_id' of zero.
15411  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15412  */
15413 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15414 {
15415 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15416 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15417 
15418 	return check_ids(old_id, cur_id, idmap);
15419 }
15420 
15421 static void clean_func_state(struct bpf_verifier_env *env,
15422 			     struct bpf_func_state *st)
15423 {
15424 	enum bpf_reg_liveness live;
15425 	int i, j;
15426 
15427 	for (i = 0; i < BPF_REG_FP; i++) {
15428 		live = st->regs[i].live;
15429 		/* liveness must not touch this register anymore */
15430 		st->regs[i].live |= REG_LIVE_DONE;
15431 		if (!(live & REG_LIVE_READ))
15432 			/* since the register is unused, clear its state
15433 			 * to make further comparison simpler
15434 			 */
15435 			__mark_reg_not_init(env, &st->regs[i]);
15436 	}
15437 
15438 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15439 		live = st->stack[i].spilled_ptr.live;
15440 		/* liveness must not touch this stack slot anymore */
15441 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15442 		if (!(live & REG_LIVE_READ)) {
15443 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15444 			for (j = 0; j < BPF_REG_SIZE; j++)
15445 				st->stack[i].slot_type[j] = STACK_INVALID;
15446 		}
15447 	}
15448 }
15449 
15450 static void clean_verifier_state(struct bpf_verifier_env *env,
15451 				 struct bpf_verifier_state *st)
15452 {
15453 	int i;
15454 
15455 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15456 		/* all regs in this state in all frames were already marked */
15457 		return;
15458 
15459 	for (i = 0; i <= st->curframe; i++)
15460 		clean_func_state(env, st->frame[i]);
15461 }
15462 
15463 /* the parentage chains form a tree.
15464  * the verifier states are added to state lists at given insn and
15465  * pushed into state stack for future exploration.
15466  * when the verifier reaches bpf_exit insn some of the verifer states
15467  * stored in the state lists have their final liveness state already,
15468  * but a lot of states will get revised from liveness point of view when
15469  * the verifier explores other branches.
15470  * Example:
15471  * 1: r0 = 1
15472  * 2: if r1 == 100 goto pc+1
15473  * 3: r0 = 2
15474  * 4: exit
15475  * when the verifier reaches exit insn the register r0 in the state list of
15476  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15477  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15478  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15479  *
15480  * Since the verifier pushes the branch states as it sees them while exploring
15481  * the program the condition of walking the branch instruction for the second
15482  * time means that all states below this branch were already explored and
15483  * their final liveness marks are already propagated.
15484  * Hence when the verifier completes the search of state list in is_state_visited()
15485  * we can call this clean_live_states() function to mark all liveness states
15486  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15487  * will not be used.
15488  * This function also clears the registers and stack for states that !READ
15489  * to simplify state merging.
15490  *
15491  * Important note here that walking the same branch instruction in the callee
15492  * doesn't meant that the states are DONE. The verifier has to compare
15493  * the callsites
15494  */
15495 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15496 			      struct bpf_verifier_state *cur)
15497 {
15498 	struct bpf_verifier_state_list *sl;
15499 	int i;
15500 
15501 	sl = *explored_state(env, insn);
15502 	while (sl) {
15503 		if (sl->state.branches)
15504 			goto next;
15505 		if (sl->state.insn_idx != insn ||
15506 		    sl->state.curframe != cur->curframe)
15507 			goto next;
15508 		for (i = 0; i <= cur->curframe; i++)
15509 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15510 				goto next;
15511 		clean_verifier_state(env, &sl->state);
15512 next:
15513 		sl = sl->next;
15514 	}
15515 }
15516 
15517 static bool regs_exact(const struct bpf_reg_state *rold,
15518 		       const struct bpf_reg_state *rcur,
15519 		       struct bpf_idmap *idmap)
15520 {
15521 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15522 	       check_ids(rold->id, rcur->id, idmap) &&
15523 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15524 }
15525 
15526 /* Returns true if (rold safe implies rcur safe) */
15527 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15528 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15529 {
15530 	if (!(rold->live & REG_LIVE_READ))
15531 		/* explored state didn't use this */
15532 		return true;
15533 	if (rold->type == NOT_INIT)
15534 		/* explored state can't have used this */
15535 		return true;
15536 	if (rcur->type == NOT_INIT)
15537 		return false;
15538 
15539 	/* Enforce that register types have to match exactly, including their
15540 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15541 	 * rule.
15542 	 *
15543 	 * One can make a point that using a pointer register as unbounded
15544 	 * SCALAR would be technically acceptable, but this could lead to
15545 	 * pointer leaks because scalars are allowed to leak while pointers
15546 	 * are not. We could make this safe in special cases if root is
15547 	 * calling us, but it's probably not worth the hassle.
15548 	 *
15549 	 * Also, register types that are *not* MAYBE_NULL could technically be
15550 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15551 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15552 	 * to the same map).
15553 	 * However, if the old MAYBE_NULL register then got NULL checked,
15554 	 * doing so could have affected others with the same id, and we can't
15555 	 * check for that because we lost the id when we converted to
15556 	 * a non-MAYBE_NULL variant.
15557 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15558 	 * non-MAYBE_NULL registers as well.
15559 	 */
15560 	if (rold->type != rcur->type)
15561 		return false;
15562 
15563 	switch (base_type(rold->type)) {
15564 	case SCALAR_VALUE:
15565 		if (env->explore_alu_limits) {
15566 			/* explore_alu_limits disables tnum_in() and range_within()
15567 			 * logic and requires everything to be strict
15568 			 */
15569 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15570 			       check_scalar_ids(rold->id, rcur->id, idmap);
15571 		}
15572 		if (!rold->precise)
15573 			return true;
15574 		/* Why check_ids() for scalar registers?
15575 		 *
15576 		 * Consider the following BPF code:
15577 		 *   1: r6 = ... unbound scalar, ID=a ...
15578 		 *   2: r7 = ... unbound scalar, ID=b ...
15579 		 *   3: if (r6 > r7) goto +1
15580 		 *   4: r6 = r7
15581 		 *   5: if (r6 > X) goto ...
15582 		 *   6: ... memory operation using r7 ...
15583 		 *
15584 		 * First verification path is [1-6]:
15585 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15586 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15587 		 *   r7 <= X, because r6 and r7 share same id.
15588 		 * Next verification path is [1-4, 6].
15589 		 *
15590 		 * Instruction (6) would be reached in two states:
15591 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15592 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15593 		 *
15594 		 * Use check_ids() to distinguish these states.
15595 		 * ---
15596 		 * Also verify that new value satisfies old value range knowledge.
15597 		 */
15598 		return range_within(rold, rcur) &&
15599 		       tnum_in(rold->var_off, rcur->var_off) &&
15600 		       check_scalar_ids(rold->id, rcur->id, idmap);
15601 	case PTR_TO_MAP_KEY:
15602 	case PTR_TO_MAP_VALUE:
15603 	case PTR_TO_MEM:
15604 	case PTR_TO_BUF:
15605 	case PTR_TO_TP_BUFFER:
15606 		/* If the new min/max/var_off satisfy the old ones and
15607 		 * everything else matches, we are OK.
15608 		 */
15609 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15610 		       range_within(rold, rcur) &&
15611 		       tnum_in(rold->var_off, rcur->var_off) &&
15612 		       check_ids(rold->id, rcur->id, idmap) &&
15613 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15614 	case PTR_TO_PACKET_META:
15615 	case PTR_TO_PACKET:
15616 		/* We must have at least as much range as the old ptr
15617 		 * did, so that any accesses which were safe before are
15618 		 * still safe.  This is true even if old range < old off,
15619 		 * since someone could have accessed through (ptr - k), or
15620 		 * even done ptr -= k in a register, to get a safe access.
15621 		 */
15622 		if (rold->range > rcur->range)
15623 			return false;
15624 		/* If the offsets don't match, we can't trust our alignment;
15625 		 * nor can we be sure that we won't fall out of range.
15626 		 */
15627 		if (rold->off != rcur->off)
15628 			return false;
15629 		/* id relations must be preserved */
15630 		if (!check_ids(rold->id, rcur->id, idmap))
15631 			return false;
15632 		/* new val must satisfy old val knowledge */
15633 		return range_within(rold, rcur) &&
15634 		       tnum_in(rold->var_off, rcur->var_off);
15635 	case PTR_TO_STACK:
15636 		/* two stack pointers are equal only if they're pointing to
15637 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15638 		 */
15639 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15640 	default:
15641 		return regs_exact(rold, rcur, idmap);
15642 	}
15643 }
15644 
15645 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15646 		      struct bpf_func_state *cur, struct bpf_idmap *idmap)
15647 {
15648 	int i, spi;
15649 
15650 	/* walk slots of the explored stack and ignore any additional
15651 	 * slots in the current stack, since explored(safe) state
15652 	 * didn't use them
15653 	 */
15654 	for (i = 0; i < old->allocated_stack; i++) {
15655 		struct bpf_reg_state *old_reg, *cur_reg;
15656 
15657 		spi = i / BPF_REG_SIZE;
15658 
15659 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15660 			i += BPF_REG_SIZE - 1;
15661 			/* explored state didn't use this */
15662 			continue;
15663 		}
15664 
15665 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15666 			continue;
15667 
15668 		if (env->allow_uninit_stack &&
15669 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15670 			continue;
15671 
15672 		/* explored stack has more populated slots than current stack
15673 		 * and these slots were used
15674 		 */
15675 		if (i >= cur->allocated_stack)
15676 			return false;
15677 
15678 		/* if old state was safe with misc data in the stack
15679 		 * it will be safe with zero-initialized stack.
15680 		 * The opposite is not true
15681 		 */
15682 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15683 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15684 			continue;
15685 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15686 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15687 			/* Ex: old explored (safe) state has STACK_SPILL in
15688 			 * this stack slot, but current has STACK_MISC ->
15689 			 * this verifier states are not equivalent,
15690 			 * return false to continue verification of this path
15691 			 */
15692 			return false;
15693 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15694 			continue;
15695 		/* Both old and cur are having same slot_type */
15696 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15697 		case STACK_SPILL:
15698 			/* when explored and current stack slot are both storing
15699 			 * spilled registers, check that stored pointers types
15700 			 * are the same as well.
15701 			 * Ex: explored safe path could have stored
15702 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15703 			 * but current path has stored:
15704 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15705 			 * such verifier states are not equivalent.
15706 			 * return false to continue verification of this path
15707 			 */
15708 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15709 				     &cur->stack[spi].spilled_ptr, idmap))
15710 				return false;
15711 			break;
15712 		case STACK_DYNPTR:
15713 			old_reg = &old->stack[spi].spilled_ptr;
15714 			cur_reg = &cur->stack[spi].spilled_ptr;
15715 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15716 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15717 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15718 				return false;
15719 			break;
15720 		case STACK_ITER:
15721 			old_reg = &old->stack[spi].spilled_ptr;
15722 			cur_reg = &cur->stack[spi].spilled_ptr;
15723 			/* iter.depth is not compared between states as it
15724 			 * doesn't matter for correctness and would otherwise
15725 			 * prevent convergence; we maintain it only to prevent
15726 			 * infinite loop check triggering, see
15727 			 * iter_active_depths_differ()
15728 			 */
15729 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15730 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15731 			    old_reg->iter.state != cur_reg->iter.state ||
15732 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15733 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15734 				return false;
15735 			break;
15736 		case STACK_MISC:
15737 		case STACK_ZERO:
15738 		case STACK_INVALID:
15739 			continue;
15740 		/* Ensure that new unhandled slot types return false by default */
15741 		default:
15742 			return false;
15743 		}
15744 	}
15745 	return true;
15746 }
15747 
15748 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15749 		    struct bpf_idmap *idmap)
15750 {
15751 	int i;
15752 
15753 	if (old->acquired_refs != cur->acquired_refs)
15754 		return false;
15755 
15756 	for (i = 0; i < old->acquired_refs; i++) {
15757 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15758 			return false;
15759 	}
15760 
15761 	return true;
15762 }
15763 
15764 /* compare two verifier states
15765  *
15766  * all states stored in state_list are known to be valid, since
15767  * verifier reached 'bpf_exit' instruction through them
15768  *
15769  * this function is called when verifier exploring different branches of
15770  * execution popped from the state stack. If it sees an old state that has
15771  * more strict register state and more strict stack state then this execution
15772  * branch doesn't need to be explored further, since verifier already
15773  * concluded that more strict state leads to valid finish.
15774  *
15775  * Therefore two states are equivalent if register state is more conservative
15776  * and explored stack state is more conservative than the current one.
15777  * Example:
15778  *       explored                   current
15779  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15780  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15781  *
15782  * In other words if current stack state (one being explored) has more
15783  * valid slots than old one that already passed validation, it means
15784  * the verifier can stop exploring and conclude that current state is valid too
15785  *
15786  * Similarly with registers. If explored state has register type as invalid
15787  * whereas register type in current state is meaningful, it means that
15788  * the current state will reach 'bpf_exit' instruction safely
15789  */
15790 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15791 			      struct bpf_func_state *cur)
15792 {
15793 	int i;
15794 
15795 	for (i = 0; i < MAX_BPF_REG; i++)
15796 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15797 			     &env->idmap_scratch))
15798 			return false;
15799 
15800 	if (!stacksafe(env, old, cur, &env->idmap_scratch))
15801 		return false;
15802 
15803 	if (!refsafe(old, cur, &env->idmap_scratch))
15804 		return false;
15805 
15806 	return true;
15807 }
15808 
15809 static bool states_equal(struct bpf_verifier_env *env,
15810 			 struct bpf_verifier_state *old,
15811 			 struct bpf_verifier_state *cur)
15812 {
15813 	int i;
15814 
15815 	if (old->curframe != cur->curframe)
15816 		return false;
15817 
15818 	env->idmap_scratch.tmp_id_gen = env->id_gen;
15819 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15820 
15821 	/* Verification state from speculative execution simulation
15822 	 * must never prune a non-speculative execution one.
15823 	 */
15824 	if (old->speculative && !cur->speculative)
15825 		return false;
15826 
15827 	if (old->active_lock.ptr != cur->active_lock.ptr)
15828 		return false;
15829 
15830 	/* Old and cur active_lock's have to be either both present
15831 	 * or both absent.
15832 	 */
15833 	if (!!old->active_lock.id != !!cur->active_lock.id)
15834 		return false;
15835 
15836 	if (old->active_lock.id &&
15837 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15838 		return false;
15839 
15840 	if (old->active_rcu_lock != cur->active_rcu_lock)
15841 		return false;
15842 
15843 	/* for states to be equal callsites have to be the same
15844 	 * and all frame states need to be equivalent
15845 	 */
15846 	for (i = 0; i <= old->curframe; i++) {
15847 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15848 			return false;
15849 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15850 			return false;
15851 	}
15852 	return true;
15853 }
15854 
15855 /* Return 0 if no propagation happened. Return negative error code if error
15856  * happened. Otherwise, return the propagated bit.
15857  */
15858 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15859 				  struct bpf_reg_state *reg,
15860 				  struct bpf_reg_state *parent_reg)
15861 {
15862 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15863 	u8 flag = reg->live & REG_LIVE_READ;
15864 	int err;
15865 
15866 	/* When comes here, read flags of PARENT_REG or REG could be any of
15867 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15868 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15869 	 */
15870 	if (parent_flag == REG_LIVE_READ64 ||
15871 	    /* Or if there is no read flag from REG. */
15872 	    !flag ||
15873 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15874 	    parent_flag == flag)
15875 		return 0;
15876 
15877 	err = mark_reg_read(env, reg, parent_reg, flag);
15878 	if (err)
15879 		return err;
15880 
15881 	return flag;
15882 }
15883 
15884 /* A write screens off any subsequent reads; but write marks come from the
15885  * straight-line code between a state and its parent.  When we arrive at an
15886  * equivalent state (jump target or such) we didn't arrive by the straight-line
15887  * code, so read marks in the state must propagate to the parent regardless
15888  * of the state's write marks. That's what 'parent == state->parent' comparison
15889  * in mark_reg_read() is for.
15890  */
15891 static int propagate_liveness(struct bpf_verifier_env *env,
15892 			      const struct bpf_verifier_state *vstate,
15893 			      struct bpf_verifier_state *vparent)
15894 {
15895 	struct bpf_reg_state *state_reg, *parent_reg;
15896 	struct bpf_func_state *state, *parent;
15897 	int i, frame, err = 0;
15898 
15899 	if (vparent->curframe != vstate->curframe) {
15900 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15901 		     vparent->curframe, vstate->curframe);
15902 		return -EFAULT;
15903 	}
15904 	/* Propagate read liveness of registers... */
15905 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15906 	for (frame = 0; frame <= vstate->curframe; frame++) {
15907 		parent = vparent->frame[frame];
15908 		state = vstate->frame[frame];
15909 		parent_reg = parent->regs;
15910 		state_reg = state->regs;
15911 		/* We don't need to worry about FP liveness, it's read-only */
15912 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15913 			err = propagate_liveness_reg(env, &state_reg[i],
15914 						     &parent_reg[i]);
15915 			if (err < 0)
15916 				return err;
15917 			if (err == REG_LIVE_READ64)
15918 				mark_insn_zext(env, &parent_reg[i]);
15919 		}
15920 
15921 		/* Propagate stack slots. */
15922 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15923 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15924 			parent_reg = &parent->stack[i].spilled_ptr;
15925 			state_reg = &state->stack[i].spilled_ptr;
15926 			err = propagate_liveness_reg(env, state_reg,
15927 						     parent_reg);
15928 			if (err < 0)
15929 				return err;
15930 		}
15931 	}
15932 	return 0;
15933 }
15934 
15935 /* find precise scalars in the previous equivalent state and
15936  * propagate them into the current state
15937  */
15938 static int propagate_precision(struct bpf_verifier_env *env,
15939 			       const struct bpf_verifier_state *old)
15940 {
15941 	struct bpf_reg_state *state_reg;
15942 	struct bpf_func_state *state;
15943 	int i, err = 0, fr;
15944 	bool first;
15945 
15946 	for (fr = old->curframe; fr >= 0; fr--) {
15947 		state = old->frame[fr];
15948 		state_reg = state->regs;
15949 		first = true;
15950 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15951 			if (state_reg->type != SCALAR_VALUE ||
15952 			    !state_reg->precise ||
15953 			    !(state_reg->live & REG_LIVE_READ))
15954 				continue;
15955 			if (env->log.level & BPF_LOG_LEVEL2) {
15956 				if (first)
15957 					verbose(env, "frame %d: propagating r%d", fr, i);
15958 				else
15959 					verbose(env, ",r%d", i);
15960 			}
15961 			bt_set_frame_reg(&env->bt, fr, i);
15962 			first = false;
15963 		}
15964 
15965 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15966 			if (!is_spilled_reg(&state->stack[i]))
15967 				continue;
15968 			state_reg = &state->stack[i].spilled_ptr;
15969 			if (state_reg->type != SCALAR_VALUE ||
15970 			    !state_reg->precise ||
15971 			    !(state_reg->live & REG_LIVE_READ))
15972 				continue;
15973 			if (env->log.level & BPF_LOG_LEVEL2) {
15974 				if (first)
15975 					verbose(env, "frame %d: propagating fp%d",
15976 						fr, (-i - 1) * BPF_REG_SIZE);
15977 				else
15978 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15979 			}
15980 			bt_set_frame_slot(&env->bt, fr, i);
15981 			first = false;
15982 		}
15983 		if (!first)
15984 			verbose(env, "\n");
15985 	}
15986 
15987 	err = mark_chain_precision_batch(env);
15988 	if (err < 0)
15989 		return err;
15990 
15991 	return 0;
15992 }
15993 
15994 static bool states_maybe_looping(struct bpf_verifier_state *old,
15995 				 struct bpf_verifier_state *cur)
15996 {
15997 	struct bpf_func_state *fold, *fcur;
15998 	int i, fr = cur->curframe;
15999 
16000 	if (old->curframe != fr)
16001 		return false;
16002 
16003 	fold = old->frame[fr];
16004 	fcur = cur->frame[fr];
16005 	for (i = 0; i < MAX_BPF_REG; i++)
16006 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16007 			   offsetof(struct bpf_reg_state, parent)))
16008 			return false;
16009 	return true;
16010 }
16011 
16012 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16013 {
16014 	return env->insn_aux_data[insn_idx].is_iter_next;
16015 }
16016 
16017 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16018  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16019  * states to match, which otherwise would look like an infinite loop. So while
16020  * iter_next() calls are taken care of, we still need to be careful and
16021  * prevent erroneous and too eager declaration of "ininite loop", when
16022  * iterators are involved.
16023  *
16024  * Here's a situation in pseudo-BPF assembly form:
16025  *
16026  *   0: again:                          ; set up iter_next() call args
16027  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16028  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16029  *   3:   if r0 == 0 goto done
16030  *   4:   ... something useful here ...
16031  *   5:   goto again                    ; another iteration
16032  *   6: done:
16033  *   7:   r1 = &it
16034  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16035  *   9:   exit
16036  *
16037  * This is a typical loop. Let's assume that we have a prune point at 1:,
16038  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16039  * again`, assuming other heuristics don't get in a way).
16040  *
16041  * When we first time come to 1:, let's say we have some state X. We proceed
16042  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16043  * Now we come back to validate that forked ACTIVE state. We proceed through
16044  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16045  * are converging. But the problem is that we don't know that yet, as this
16046  * convergence has to happen at iter_next() call site only. So if nothing is
16047  * done, at 1: verifier will use bounded loop logic and declare infinite
16048  * looping (and would be *technically* correct, if not for iterator's
16049  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16050  * don't want that. So what we do in process_iter_next_call() when we go on
16051  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16052  * a different iteration. So when we suspect an infinite loop, we additionally
16053  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16054  * pretend we are not looping and wait for next iter_next() call.
16055  *
16056  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16057  * loop, because that would actually mean infinite loop, as DRAINED state is
16058  * "sticky", and so we'll keep returning into the same instruction with the
16059  * same state (at least in one of possible code paths).
16060  *
16061  * This approach allows to keep infinite loop heuristic even in the face of
16062  * active iterator. E.g., C snippet below is and will be detected as
16063  * inifintely looping:
16064  *
16065  *   struct bpf_iter_num it;
16066  *   int *p, x;
16067  *
16068  *   bpf_iter_num_new(&it, 0, 10);
16069  *   while ((p = bpf_iter_num_next(&t))) {
16070  *       x = p;
16071  *       while (x--) {} // <<-- infinite loop here
16072  *   }
16073  *
16074  */
16075 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16076 {
16077 	struct bpf_reg_state *slot, *cur_slot;
16078 	struct bpf_func_state *state;
16079 	int i, fr;
16080 
16081 	for (fr = old->curframe; fr >= 0; fr--) {
16082 		state = old->frame[fr];
16083 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16084 			if (state->stack[i].slot_type[0] != STACK_ITER)
16085 				continue;
16086 
16087 			slot = &state->stack[i].spilled_ptr;
16088 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16089 				continue;
16090 
16091 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16092 			if (cur_slot->iter.depth != slot->iter.depth)
16093 				return true;
16094 		}
16095 	}
16096 	return false;
16097 }
16098 
16099 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16100 {
16101 	struct bpf_verifier_state_list *new_sl;
16102 	struct bpf_verifier_state_list *sl, **pprev;
16103 	struct bpf_verifier_state *cur = env->cur_state, *new;
16104 	int i, j, err, states_cnt = 0;
16105 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16106 	bool add_new_state = force_new_state;
16107 
16108 	/* bpf progs typically have pruning point every 4 instructions
16109 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16110 	 * Do not add new state for future pruning if the verifier hasn't seen
16111 	 * at least 2 jumps and at least 8 instructions.
16112 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16113 	 * In tests that amounts to up to 50% reduction into total verifier
16114 	 * memory consumption and 20% verifier time speedup.
16115 	 */
16116 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16117 	    env->insn_processed - env->prev_insn_processed >= 8)
16118 		add_new_state = true;
16119 
16120 	pprev = explored_state(env, insn_idx);
16121 	sl = *pprev;
16122 
16123 	clean_live_states(env, insn_idx, cur);
16124 
16125 	while (sl) {
16126 		states_cnt++;
16127 		if (sl->state.insn_idx != insn_idx)
16128 			goto next;
16129 
16130 		if (sl->state.branches) {
16131 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16132 
16133 			if (frame->in_async_callback_fn &&
16134 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16135 				/* Different async_entry_cnt means that the verifier is
16136 				 * processing another entry into async callback.
16137 				 * Seeing the same state is not an indication of infinite
16138 				 * loop or infinite recursion.
16139 				 * But finding the same state doesn't mean that it's safe
16140 				 * to stop processing the current state. The previous state
16141 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16142 				 * Checking in_async_callback_fn alone is not enough either.
16143 				 * Since the verifier still needs to catch infinite loops
16144 				 * inside async callbacks.
16145 				 */
16146 				goto skip_inf_loop_check;
16147 			}
16148 			/* BPF open-coded iterators loop detection is special.
16149 			 * states_maybe_looping() logic is too simplistic in detecting
16150 			 * states that *might* be equivalent, because it doesn't know
16151 			 * about ID remapping, so don't even perform it.
16152 			 * See process_iter_next_call() and iter_active_depths_differ()
16153 			 * for overview of the logic. When current and one of parent
16154 			 * states are detected as equivalent, it's a good thing: we prove
16155 			 * convergence and can stop simulating further iterations.
16156 			 * It's safe to assume that iterator loop will finish, taking into
16157 			 * account iter_next() contract of eventually returning
16158 			 * sticky NULL result.
16159 			 */
16160 			if (is_iter_next_insn(env, insn_idx)) {
16161 				if (states_equal(env, &sl->state, cur)) {
16162 					struct bpf_func_state *cur_frame;
16163 					struct bpf_reg_state *iter_state, *iter_reg;
16164 					int spi;
16165 
16166 					cur_frame = cur->frame[cur->curframe];
16167 					/* btf_check_iter_kfuncs() enforces that
16168 					 * iter state pointer is always the first arg
16169 					 */
16170 					iter_reg = &cur_frame->regs[BPF_REG_1];
16171 					/* current state is valid due to states_equal(),
16172 					 * so we can assume valid iter and reg state,
16173 					 * no need for extra (re-)validations
16174 					 */
16175 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16176 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16177 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16178 						goto hit;
16179 				}
16180 				goto skip_inf_loop_check;
16181 			}
16182 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16183 			if (states_maybe_looping(&sl->state, cur) &&
16184 			    states_equal(env, &sl->state, cur) &&
16185 			    !iter_active_depths_differ(&sl->state, cur)) {
16186 				verbose_linfo(env, insn_idx, "; ");
16187 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16188 				return -EINVAL;
16189 			}
16190 			/* if the verifier is processing a loop, avoid adding new state
16191 			 * too often, since different loop iterations have distinct
16192 			 * states and may not help future pruning.
16193 			 * This threshold shouldn't be too low to make sure that
16194 			 * a loop with large bound will be rejected quickly.
16195 			 * The most abusive loop will be:
16196 			 * r1 += 1
16197 			 * if r1 < 1000000 goto pc-2
16198 			 * 1M insn_procssed limit / 100 == 10k peak states.
16199 			 * This threshold shouldn't be too high either, since states
16200 			 * at the end of the loop are likely to be useful in pruning.
16201 			 */
16202 skip_inf_loop_check:
16203 			if (!force_new_state &&
16204 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16205 			    env->insn_processed - env->prev_insn_processed < 100)
16206 				add_new_state = false;
16207 			goto miss;
16208 		}
16209 		if (states_equal(env, &sl->state, cur)) {
16210 hit:
16211 			sl->hit_cnt++;
16212 			/* reached equivalent register/stack state,
16213 			 * prune the search.
16214 			 * Registers read by the continuation are read by us.
16215 			 * If we have any write marks in env->cur_state, they
16216 			 * will prevent corresponding reads in the continuation
16217 			 * from reaching our parent (an explored_state).  Our
16218 			 * own state will get the read marks recorded, but
16219 			 * they'll be immediately forgotten as we're pruning
16220 			 * this state and will pop a new one.
16221 			 */
16222 			err = propagate_liveness(env, &sl->state, cur);
16223 
16224 			/* if previous state reached the exit with precision and
16225 			 * current state is equivalent to it (except precsion marks)
16226 			 * the precision needs to be propagated back in
16227 			 * the current state.
16228 			 */
16229 			err = err ? : push_jmp_history(env, cur);
16230 			err = err ? : propagate_precision(env, &sl->state);
16231 			if (err)
16232 				return err;
16233 			return 1;
16234 		}
16235 miss:
16236 		/* when new state is not going to be added do not increase miss count.
16237 		 * Otherwise several loop iterations will remove the state
16238 		 * recorded earlier. The goal of these heuristics is to have
16239 		 * states from some iterations of the loop (some in the beginning
16240 		 * and some at the end) to help pruning.
16241 		 */
16242 		if (add_new_state)
16243 			sl->miss_cnt++;
16244 		/* heuristic to determine whether this state is beneficial
16245 		 * to keep checking from state equivalence point of view.
16246 		 * Higher numbers increase max_states_per_insn and verification time,
16247 		 * but do not meaningfully decrease insn_processed.
16248 		 */
16249 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16250 			/* the state is unlikely to be useful. Remove it to
16251 			 * speed up verification
16252 			 */
16253 			*pprev = sl->next;
16254 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16255 				u32 br = sl->state.branches;
16256 
16257 				WARN_ONCE(br,
16258 					  "BUG live_done but branches_to_explore %d\n",
16259 					  br);
16260 				free_verifier_state(&sl->state, false);
16261 				kfree(sl);
16262 				env->peak_states--;
16263 			} else {
16264 				/* cannot free this state, since parentage chain may
16265 				 * walk it later. Add it for free_list instead to
16266 				 * be freed at the end of verification
16267 				 */
16268 				sl->next = env->free_list;
16269 				env->free_list = sl;
16270 			}
16271 			sl = *pprev;
16272 			continue;
16273 		}
16274 next:
16275 		pprev = &sl->next;
16276 		sl = *pprev;
16277 	}
16278 
16279 	if (env->max_states_per_insn < states_cnt)
16280 		env->max_states_per_insn = states_cnt;
16281 
16282 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16283 		return 0;
16284 
16285 	if (!add_new_state)
16286 		return 0;
16287 
16288 	/* There were no equivalent states, remember the current one.
16289 	 * Technically the current state is not proven to be safe yet,
16290 	 * but it will either reach outer most bpf_exit (which means it's safe)
16291 	 * or it will be rejected. When there are no loops the verifier won't be
16292 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16293 	 * again on the way to bpf_exit.
16294 	 * When looping the sl->state.branches will be > 0 and this state
16295 	 * will not be considered for equivalence until branches == 0.
16296 	 */
16297 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16298 	if (!new_sl)
16299 		return -ENOMEM;
16300 	env->total_states++;
16301 	env->peak_states++;
16302 	env->prev_jmps_processed = env->jmps_processed;
16303 	env->prev_insn_processed = env->insn_processed;
16304 
16305 	/* forget precise markings we inherited, see __mark_chain_precision */
16306 	if (env->bpf_capable)
16307 		mark_all_scalars_imprecise(env, cur);
16308 
16309 	/* add new state to the head of linked list */
16310 	new = &new_sl->state;
16311 	err = copy_verifier_state(new, cur);
16312 	if (err) {
16313 		free_verifier_state(new, false);
16314 		kfree(new_sl);
16315 		return err;
16316 	}
16317 	new->insn_idx = insn_idx;
16318 	WARN_ONCE(new->branches != 1,
16319 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16320 
16321 	cur->parent = new;
16322 	cur->first_insn_idx = insn_idx;
16323 	clear_jmp_history(cur);
16324 	new_sl->next = *explored_state(env, insn_idx);
16325 	*explored_state(env, insn_idx) = new_sl;
16326 	/* connect new state to parentage chain. Current frame needs all
16327 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16328 	 * to the stack implicitly by JITs) so in callers' frames connect just
16329 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16330 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16331 	 * from callee with its full parentage chain, anyway.
16332 	 */
16333 	/* clear write marks in current state: the writes we did are not writes
16334 	 * our child did, so they don't screen off its reads from us.
16335 	 * (There are no read marks in current state, because reads always mark
16336 	 * their parent and current state never has children yet.  Only
16337 	 * explored_states can get read marks.)
16338 	 */
16339 	for (j = 0; j <= cur->curframe; j++) {
16340 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16341 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16342 		for (i = 0; i < BPF_REG_FP; i++)
16343 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16344 	}
16345 
16346 	/* all stack frames are accessible from callee, clear them all */
16347 	for (j = 0; j <= cur->curframe; j++) {
16348 		struct bpf_func_state *frame = cur->frame[j];
16349 		struct bpf_func_state *newframe = new->frame[j];
16350 
16351 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16352 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16353 			frame->stack[i].spilled_ptr.parent =
16354 						&newframe->stack[i].spilled_ptr;
16355 		}
16356 	}
16357 	return 0;
16358 }
16359 
16360 /* Return true if it's OK to have the same insn return a different type. */
16361 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16362 {
16363 	switch (base_type(type)) {
16364 	case PTR_TO_CTX:
16365 	case PTR_TO_SOCKET:
16366 	case PTR_TO_SOCK_COMMON:
16367 	case PTR_TO_TCP_SOCK:
16368 	case PTR_TO_XDP_SOCK:
16369 	case PTR_TO_BTF_ID:
16370 		return false;
16371 	default:
16372 		return true;
16373 	}
16374 }
16375 
16376 /* If an instruction was previously used with particular pointer types, then we
16377  * need to be careful to avoid cases such as the below, where it may be ok
16378  * for one branch accessing the pointer, but not ok for the other branch:
16379  *
16380  * R1 = sock_ptr
16381  * goto X;
16382  * ...
16383  * R1 = some_other_valid_ptr;
16384  * goto X;
16385  * ...
16386  * R2 = *(u32 *)(R1 + 0);
16387  */
16388 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16389 {
16390 	return src != prev && (!reg_type_mismatch_ok(src) ||
16391 			       !reg_type_mismatch_ok(prev));
16392 }
16393 
16394 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16395 			     bool allow_trust_missmatch)
16396 {
16397 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16398 
16399 	if (*prev_type == NOT_INIT) {
16400 		/* Saw a valid insn
16401 		 * dst_reg = *(u32 *)(src_reg + off)
16402 		 * save type to validate intersecting paths
16403 		 */
16404 		*prev_type = type;
16405 	} else if (reg_type_mismatch(type, *prev_type)) {
16406 		/* Abuser program is trying to use the same insn
16407 		 * dst_reg = *(u32*) (src_reg + off)
16408 		 * with different pointer types:
16409 		 * src_reg == ctx in one branch and
16410 		 * src_reg == stack|map in some other branch.
16411 		 * Reject it.
16412 		 */
16413 		if (allow_trust_missmatch &&
16414 		    base_type(type) == PTR_TO_BTF_ID &&
16415 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16416 			/*
16417 			 * Have to support a use case when one path through
16418 			 * the program yields TRUSTED pointer while another
16419 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16420 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16421 			 */
16422 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16423 		} else {
16424 			verbose(env, "same insn cannot be used with different pointers\n");
16425 			return -EINVAL;
16426 		}
16427 	}
16428 
16429 	return 0;
16430 }
16431 
16432 static int do_check(struct bpf_verifier_env *env)
16433 {
16434 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16435 	struct bpf_verifier_state *state = env->cur_state;
16436 	struct bpf_insn *insns = env->prog->insnsi;
16437 	struct bpf_reg_state *regs;
16438 	int insn_cnt = env->prog->len;
16439 	bool do_print_state = false;
16440 	int prev_insn_idx = -1;
16441 
16442 	for (;;) {
16443 		struct bpf_insn *insn;
16444 		u8 class;
16445 		int err;
16446 
16447 		env->prev_insn_idx = prev_insn_idx;
16448 		if (env->insn_idx >= insn_cnt) {
16449 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16450 				env->insn_idx, insn_cnt);
16451 			return -EFAULT;
16452 		}
16453 
16454 		insn = &insns[env->insn_idx];
16455 		class = BPF_CLASS(insn->code);
16456 
16457 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16458 			verbose(env,
16459 				"BPF program is too large. Processed %d insn\n",
16460 				env->insn_processed);
16461 			return -E2BIG;
16462 		}
16463 
16464 		state->last_insn_idx = env->prev_insn_idx;
16465 
16466 		if (is_prune_point(env, env->insn_idx)) {
16467 			err = is_state_visited(env, env->insn_idx);
16468 			if (err < 0)
16469 				return err;
16470 			if (err == 1) {
16471 				/* found equivalent state, can prune the search */
16472 				if (env->log.level & BPF_LOG_LEVEL) {
16473 					if (do_print_state)
16474 						verbose(env, "\nfrom %d to %d%s: safe\n",
16475 							env->prev_insn_idx, env->insn_idx,
16476 							env->cur_state->speculative ?
16477 							" (speculative execution)" : "");
16478 					else
16479 						verbose(env, "%d: safe\n", env->insn_idx);
16480 				}
16481 				goto process_bpf_exit;
16482 			}
16483 		}
16484 
16485 		if (is_jmp_point(env, env->insn_idx)) {
16486 			err = push_jmp_history(env, state);
16487 			if (err)
16488 				return err;
16489 		}
16490 
16491 		if (signal_pending(current))
16492 			return -EAGAIN;
16493 
16494 		if (need_resched())
16495 			cond_resched();
16496 
16497 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16498 			verbose(env, "\nfrom %d to %d%s:",
16499 				env->prev_insn_idx, env->insn_idx,
16500 				env->cur_state->speculative ?
16501 				" (speculative execution)" : "");
16502 			print_verifier_state(env, state->frame[state->curframe], true);
16503 			do_print_state = false;
16504 		}
16505 
16506 		if (env->log.level & BPF_LOG_LEVEL) {
16507 			const struct bpf_insn_cbs cbs = {
16508 				.cb_call	= disasm_kfunc_name,
16509 				.cb_print	= verbose,
16510 				.private_data	= env,
16511 			};
16512 
16513 			if (verifier_state_scratched(env))
16514 				print_insn_state(env, state->frame[state->curframe]);
16515 
16516 			verbose_linfo(env, env->insn_idx, "; ");
16517 			env->prev_log_pos = env->log.end_pos;
16518 			verbose(env, "%d: ", env->insn_idx);
16519 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16520 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16521 			env->prev_log_pos = env->log.end_pos;
16522 		}
16523 
16524 		if (bpf_prog_is_offloaded(env->prog->aux)) {
16525 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16526 							   env->prev_insn_idx);
16527 			if (err)
16528 				return err;
16529 		}
16530 
16531 		regs = cur_regs(env);
16532 		sanitize_mark_insn_seen(env);
16533 		prev_insn_idx = env->insn_idx;
16534 
16535 		if (class == BPF_ALU || class == BPF_ALU64) {
16536 			err = check_alu_op(env, insn);
16537 			if (err)
16538 				return err;
16539 
16540 		} else if (class == BPF_LDX) {
16541 			enum bpf_reg_type src_reg_type;
16542 
16543 			/* check for reserved fields is already done */
16544 
16545 			/* check src operand */
16546 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16547 			if (err)
16548 				return err;
16549 
16550 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16551 			if (err)
16552 				return err;
16553 
16554 			src_reg_type = regs[insn->src_reg].type;
16555 
16556 			/* check that memory (src_reg + off) is readable,
16557 			 * the state of dst_reg will be updated by this func
16558 			 */
16559 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
16560 					       insn->off, BPF_SIZE(insn->code),
16561 					       BPF_READ, insn->dst_reg, false,
16562 					       BPF_MODE(insn->code) == BPF_MEMSX);
16563 			if (err)
16564 				return err;
16565 
16566 			err = save_aux_ptr_type(env, src_reg_type, true);
16567 			if (err)
16568 				return err;
16569 		} else if (class == BPF_STX) {
16570 			enum bpf_reg_type dst_reg_type;
16571 
16572 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16573 				err = check_atomic(env, env->insn_idx, insn);
16574 				if (err)
16575 					return err;
16576 				env->insn_idx++;
16577 				continue;
16578 			}
16579 
16580 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16581 				verbose(env, "BPF_STX uses reserved fields\n");
16582 				return -EINVAL;
16583 			}
16584 
16585 			/* check src1 operand */
16586 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16587 			if (err)
16588 				return err;
16589 			/* check src2 operand */
16590 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16591 			if (err)
16592 				return err;
16593 
16594 			dst_reg_type = regs[insn->dst_reg].type;
16595 
16596 			/* check that memory (dst_reg + off) is writeable */
16597 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16598 					       insn->off, BPF_SIZE(insn->code),
16599 					       BPF_WRITE, insn->src_reg, false, false);
16600 			if (err)
16601 				return err;
16602 
16603 			err = save_aux_ptr_type(env, dst_reg_type, false);
16604 			if (err)
16605 				return err;
16606 		} else if (class == BPF_ST) {
16607 			enum bpf_reg_type dst_reg_type;
16608 
16609 			if (BPF_MODE(insn->code) != BPF_MEM ||
16610 			    insn->src_reg != BPF_REG_0) {
16611 				verbose(env, "BPF_ST uses reserved fields\n");
16612 				return -EINVAL;
16613 			}
16614 			/* check src operand */
16615 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16616 			if (err)
16617 				return err;
16618 
16619 			dst_reg_type = regs[insn->dst_reg].type;
16620 
16621 			/* check that memory (dst_reg + off) is writeable */
16622 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16623 					       insn->off, BPF_SIZE(insn->code),
16624 					       BPF_WRITE, -1, false, false);
16625 			if (err)
16626 				return err;
16627 
16628 			err = save_aux_ptr_type(env, dst_reg_type, false);
16629 			if (err)
16630 				return err;
16631 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16632 			u8 opcode = BPF_OP(insn->code);
16633 
16634 			env->jmps_processed++;
16635 			if (opcode == BPF_CALL) {
16636 				if (BPF_SRC(insn->code) != BPF_K ||
16637 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16638 				     && insn->off != 0) ||
16639 				    (insn->src_reg != BPF_REG_0 &&
16640 				     insn->src_reg != BPF_PSEUDO_CALL &&
16641 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16642 				    insn->dst_reg != BPF_REG_0 ||
16643 				    class == BPF_JMP32) {
16644 					verbose(env, "BPF_CALL uses reserved fields\n");
16645 					return -EINVAL;
16646 				}
16647 
16648 				if (env->cur_state->active_lock.ptr) {
16649 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16650 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16651 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16652 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16653 						verbose(env, "function calls are not allowed while holding a lock\n");
16654 						return -EINVAL;
16655 					}
16656 				}
16657 				if (insn->src_reg == BPF_PSEUDO_CALL)
16658 					err = check_func_call(env, insn, &env->insn_idx);
16659 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16660 					err = check_kfunc_call(env, insn, &env->insn_idx);
16661 				else
16662 					err = check_helper_call(env, insn, &env->insn_idx);
16663 				if (err)
16664 					return err;
16665 
16666 				mark_reg_scratched(env, BPF_REG_0);
16667 			} else if (opcode == BPF_JA) {
16668 				if (BPF_SRC(insn->code) != BPF_K ||
16669 				    insn->src_reg != BPF_REG_0 ||
16670 				    insn->dst_reg != BPF_REG_0 ||
16671 				    (class == BPF_JMP && insn->imm != 0) ||
16672 				    (class == BPF_JMP32 && insn->off != 0)) {
16673 					verbose(env, "BPF_JA uses reserved fields\n");
16674 					return -EINVAL;
16675 				}
16676 
16677 				if (class == BPF_JMP)
16678 					env->insn_idx += insn->off + 1;
16679 				else
16680 					env->insn_idx += insn->imm + 1;
16681 				continue;
16682 
16683 			} else if (opcode == BPF_EXIT) {
16684 				if (BPF_SRC(insn->code) != BPF_K ||
16685 				    insn->imm != 0 ||
16686 				    insn->src_reg != BPF_REG_0 ||
16687 				    insn->dst_reg != BPF_REG_0 ||
16688 				    class == BPF_JMP32) {
16689 					verbose(env, "BPF_EXIT uses reserved fields\n");
16690 					return -EINVAL;
16691 				}
16692 
16693 				if (env->cur_state->active_lock.ptr &&
16694 				    !in_rbtree_lock_required_cb(env)) {
16695 					verbose(env, "bpf_spin_unlock is missing\n");
16696 					return -EINVAL;
16697 				}
16698 
16699 				if (env->cur_state->active_rcu_lock &&
16700 				    !in_rbtree_lock_required_cb(env)) {
16701 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16702 					return -EINVAL;
16703 				}
16704 
16705 				/* We must do check_reference_leak here before
16706 				 * prepare_func_exit to handle the case when
16707 				 * state->curframe > 0, it may be a callback
16708 				 * function, for which reference_state must
16709 				 * match caller reference state when it exits.
16710 				 */
16711 				err = check_reference_leak(env);
16712 				if (err)
16713 					return err;
16714 
16715 				if (state->curframe) {
16716 					/* exit from nested function */
16717 					err = prepare_func_exit(env, &env->insn_idx);
16718 					if (err)
16719 						return err;
16720 					do_print_state = true;
16721 					continue;
16722 				}
16723 
16724 				err = check_return_code(env);
16725 				if (err)
16726 					return err;
16727 process_bpf_exit:
16728 				mark_verifier_state_scratched(env);
16729 				update_branch_counts(env, env->cur_state);
16730 				err = pop_stack(env, &prev_insn_idx,
16731 						&env->insn_idx, pop_log);
16732 				if (err < 0) {
16733 					if (err != -ENOENT)
16734 						return err;
16735 					break;
16736 				} else {
16737 					do_print_state = true;
16738 					continue;
16739 				}
16740 			} else {
16741 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16742 				if (err)
16743 					return err;
16744 			}
16745 		} else if (class == BPF_LD) {
16746 			u8 mode = BPF_MODE(insn->code);
16747 
16748 			if (mode == BPF_ABS || mode == BPF_IND) {
16749 				err = check_ld_abs(env, insn);
16750 				if (err)
16751 					return err;
16752 
16753 			} else if (mode == BPF_IMM) {
16754 				err = check_ld_imm(env, insn);
16755 				if (err)
16756 					return err;
16757 
16758 				env->insn_idx++;
16759 				sanitize_mark_insn_seen(env);
16760 			} else {
16761 				verbose(env, "invalid BPF_LD mode\n");
16762 				return -EINVAL;
16763 			}
16764 		} else {
16765 			verbose(env, "unknown insn class %d\n", class);
16766 			return -EINVAL;
16767 		}
16768 
16769 		env->insn_idx++;
16770 	}
16771 
16772 	return 0;
16773 }
16774 
16775 static int find_btf_percpu_datasec(struct btf *btf)
16776 {
16777 	const struct btf_type *t;
16778 	const char *tname;
16779 	int i, n;
16780 
16781 	/*
16782 	 * Both vmlinux and module each have their own ".data..percpu"
16783 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16784 	 * types to look at only module's own BTF types.
16785 	 */
16786 	n = btf_nr_types(btf);
16787 	if (btf_is_module(btf))
16788 		i = btf_nr_types(btf_vmlinux);
16789 	else
16790 		i = 1;
16791 
16792 	for(; i < n; i++) {
16793 		t = btf_type_by_id(btf, i);
16794 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16795 			continue;
16796 
16797 		tname = btf_name_by_offset(btf, t->name_off);
16798 		if (!strcmp(tname, ".data..percpu"))
16799 			return i;
16800 	}
16801 
16802 	return -ENOENT;
16803 }
16804 
16805 /* replace pseudo btf_id with kernel symbol address */
16806 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16807 			       struct bpf_insn *insn,
16808 			       struct bpf_insn_aux_data *aux)
16809 {
16810 	const struct btf_var_secinfo *vsi;
16811 	const struct btf_type *datasec;
16812 	struct btf_mod_pair *btf_mod;
16813 	const struct btf_type *t;
16814 	const char *sym_name;
16815 	bool percpu = false;
16816 	u32 type, id = insn->imm;
16817 	struct btf *btf;
16818 	s32 datasec_id;
16819 	u64 addr;
16820 	int i, btf_fd, err;
16821 
16822 	btf_fd = insn[1].imm;
16823 	if (btf_fd) {
16824 		btf = btf_get_by_fd(btf_fd);
16825 		if (IS_ERR(btf)) {
16826 			verbose(env, "invalid module BTF object FD specified.\n");
16827 			return -EINVAL;
16828 		}
16829 	} else {
16830 		if (!btf_vmlinux) {
16831 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16832 			return -EINVAL;
16833 		}
16834 		btf = btf_vmlinux;
16835 		btf_get(btf);
16836 	}
16837 
16838 	t = btf_type_by_id(btf, id);
16839 	if (!t) {
16840 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16841 		err = -ENOENT;
16842 		goto err_put;
16843 	}
16844 
16845 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16846 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16847 		err = -EINVAL;
16848 		goto err_put;
16849 	}
16850 
16851 	sym_name = btf_name_by_offset(btf, t->name_off);
16852 	addr = kallsyms_lookup_name(sym_name);
16853 	if (!addr) {
16854 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16855 			sym_name);
16856 		err = -ENOENT;
16857 		goto err_put;
16858 	}
16859 	insn[0].imm = (u32)addr;
16860 	insn[1].imm = addr >> 32;
16861 
16862 	if (btf_type_is_func(t)) {
16863 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16864 		aux->btf_var.mem_size = 0;
16865 		goto check_btf;
16866 	}
16867 
16868 	datasec_id = find_btf_percpu_datasec(btf);
16869 	if (datasec_id > 0) {
16870 		datasec = btf_type_by_id(btf, datasec_id);
16871 		for_each_vsi(i, datasec, vsi) {
16872 			if (vsi->type == id) {
16873 				percpu = true;
16874 				break;
16875 			}
16876 		}
16877 	}
16878 
16879 	type = t->type;
16880 	t = btf_type_skip_modifiers(btf, type, NULL);
16881 	if (percpu) {
16882 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16883 		aux->btf_var.btf = btf;
16884 		aux->btf_var.btf_id = type;
16885 	} else if (!btf_type_is_struct(t)) {
16886 		const struct btf_type *ret;
16887 		const char *tname;
16888 		u32 tsize;
16889 
16890 		/* resolve the type size of ksym. */
16891 		ret = btf_resolve_size(btf, t, &tsize);
16892 		if (IS_ERR(ret)) {
16893 			tname = btf_name_by_offset(btf, t->name_off);
16894 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16895 				tname, PTR_ERR(ret));
16896 			err = -EINVAL;
16897 			goto err_put;
16898 		}
16899 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16900 		aux->btf_var.mem_size = tsize;
16901 	} else {
16902 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16903 		aux->btf_var.btf = btf;
16904 		aux->btf_var.btf_id = type;
16905 	}
16906 check_btf:
16907 	/* check whether we recorded this BTF (and maybe module) already */
16908 	for (i = 0; i < env->used_btf_cnt; i++) {
16909 		if (env->used_btfs[i].btf == btf) {
16910 			btf_put(btf);
16911 			return 0;
16912 		}
16913 	}
16914 
16915 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16916 		err = -E2BIG;
16917 		goto err_put;
16918 	}
16919 
16920 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16921 	btf_mod->btf = btf;
16922 	btf_mod->module = NULL;
16923 
16924 	/* if we reference variables from kernel module, bump its refcount */
16925 	if (btf_is_module(btf)) {
16926 		btf_mod->module = btf_try_get_module(btf);
16927 		if (!btf_mod->module) {
16928 			err = -ENXIO;
16929 			goto err_put;
16930 		}
16931 	}
16932 
16933 	env->used_btf_cnt++;
16934 
16935 	return 0;
16936 err_put:
16937 	btf_put(btf);
16938 	return err;
16939 }
16940 
16941 static bool is_tracing_prog_type(enum bpf_prog_type type)
16942 {
16943 	switch (type) {
16944 	case BPF_PROG_TYPE_KPROBE:
16945 	case BPF_PROG_TYPE_TRACEPOINT:
16946 	case BPF_PROG_TYPE_PERF_EVENT:
16947 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16948 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16949 		return true;
16950 	default:
16951 		return false;
16952 	}
16953 }
16954 
16955 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16956 					struct bpf_map *map,
16957 					struct bpf_prog *prog)
16958 
16959 {
16960 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16961 
16962 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16963 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16964 		if (is_tracing_prog_type(prog_type)) {
16965 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16966 			return -EINVAL;
16967 		}
16968 	}
16969 
16970 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16971 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16972 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16973 			return -EINVAL;
16974 		}
16975 
16976 		if (is_tracing_prog_type(prog_type)) {
16977 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16978 			return -EINVAL;
16979 		}
16980 	}
16981 
16982 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16983 		if (is_tracing_prog_type(prog_type)) {
16984 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16985 			return -EINVAL;
16986 		}
16987 	}
16988 
16989 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16990 	    !bpf_offload_prog_map_match(prog, map)) {
16991 		verbose(env, "offload device mismatch between prog and map\n");
16992 		return -EINVAL;
16993 	}
16994 
16995 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16996 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16997 		return -EINVAL;
16998 	}
16999 
17000 	if (prog->aux->sleepable)
17001 		switch (map->map_type) {
17002 		case BPF_MAP_TYPE_HASH:
17003 		case BPF_MAP_TYPE_LRU_HASH:
17004 		case BPF_MAP_TYPE_ARRAY:
17005 		case BPF_MAP_TYPE_PERCPU_HASH:
17006 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17007 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17008 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17009 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17010 		case BPF_MAP_TYPE_RINGBUF:
17011 		case BPF_MAP_TYPE_USER_RINGBUF:
17012 		case BPF_MAP_TYPE_INODE_STORAGE:
17013 		case BPF_MAP_TYPE_SK_STORAGE:
17014 		case BPF_MAP_TYPE_TASK_STORAGE:
17015 		case BPF_MAP_TYPE_CGRP_STORAGE:
17016 			break;
17017 		default:
17018 			verbose(env,
17019 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17020 			return -EINVAL;
17021 		}
17022 
17023 	return 0;
17024 }
17025 
17026 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17027 {
17028 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17029 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17030 }
17031 
17032 /* find and rewrite pseudo imm in ld_imm64 instructions:
17033  *
17034  * 1. if it accesses map FD, replace it with actual map pointer.
17035  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17036  *
17037  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17038  */
17039 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17040 {
17041 	struct bpf_insn *insn = env->prog->insnsi;
17042 	int insn_cnt = env->prog->len;
17043 	int i, j, err;
17044 
17045 	err = bpf_prog_calc_tag(env->prog);
17046 	if (err)
17047 		return err;
17048 
17049 	for (i = 0; i < insn_cnt; i++, insn++) {
17050 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17051 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17052 		    insn->imm != 0)) {
17053 			verbose(env, "BPF_LDX uses reserved fields\n");
17054 			return -EINVAL;
17055 		}
17056 
17057 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17058 			struct bpf_insn_aux_data *aux;
17059 			struct bpf_map *map;
17060 			struct fd f;
17061 			u64 addr;
17062 			u32 fd;
17063 
17064 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17065 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17066 			    insn[1].off != 0) {
17067 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17068 				return -EINVAL;
17069 			}
17070 
17071 			if (insn[0].src_reg == 0)
17072 				/* valid generic load 64-bit imm */
17073 				goto next_insn;
17074 
17075 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17076 				aux = &env->insn_aux_data[i];
17077 				err = check_pseudo_btf_id(env, insn, aux);
17078 				if (err)
17079 					return err;
17080 				goto next_insn;
17081 			}
17082 
17083 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17084 				aux = &env->insn_aux_data[i];
17085 				aux->ptr_type = PTR_TO_FUNC;
17086 				goto next_insn;
17087 			}
17088 
17089 			/* In final convert_pseudo_ld_imm64() step, this is
17090 			 * converted into regular 64-bit imm load insn.
17091 			 */
17092 			switch (insn[0].src_reg) {
17093 			case BPF_PSEUDO_MAP_VALUE:
17094 			case BPF_PSEUDO_MAP_IDX_VALUE:
17095 				break;
17096 			case BPF_PSEUDO_MAP_FD:
17097 			case BPF_PSEUDO_MAP_IDX:
17098 				if (insn[1].imm == 0)
17099 					break;
17100 				fallthrough;
17101 			default:
17102 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17103 				return -EINVAL;
17104 			}
17105 
17106 			switch (insn[0].src_reg) {
17107 			case BPF_PSEUDO_MAP_IDX_VALUE:
17108 			case BPF_PSEUDO_MAP_IDX:
17109 				if (bpfptr_is_null(env->fd_array)) {
17110 					verbose(env, "fd_idx without fd_array is invalid\n");
17111 					return -EPROTO;
17112 				}
17113 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17114 							    insn[0].imm * sizeof(fd),
17115 							    sizeof(fd)))
17116 					return -EFAULT;
17117 				break;
17118 			default:
17119 				fd = insn[0].imm;
17120 				break;
17121 			}
17122 
17123 			f = fdget(fd);
17124 			map = __bpf_map_get(f);
17125 			if (IS_ERR(map)) {
17126 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
17127 					insn[0].imm);
17128 				return PTR_ERR(map);
17129 			}
17130 
17131 			err = check_map_prog_compatibility(env, map, env->prog);
17132 			if (err) {
17133 				fdput(f);
17134 				return err;
17135 			}
17136 
17137 			aux = &env->insn_aux_data[i];
17138 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17139 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17140 				addr = (unsigned long)map;
17141 			} else {
17142 				u32 off = insn[1].imm;
17143 
17144 				if (off >= BPF_MAX_VAR_OFF) {
17145 					verbose(env, "direct value offset of %u is not allowed\n", off);
17146 					fdput(f);
17147 					return -EINVAL;
17148 				}
17149 
17150 				if (!map->ops->map_direct_value_addr) {
17151 					verbose(env, "no direct value access support for this map type\n");
17152 					fdput(f);
17153 					return -EINVAL;
17154 				}
17155 
17156 				err = map->ops->map_direct_value_addr(map, &addr, off);
17157 				if (err) {
17158 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17159 						map->value_size, off);
17160 					fdput(f);
17161 					return err;
17162 				}
17163 
17164 				aux->map_off = off;
17165 				addr += off;
17166 			}
17167 
17168 			insn[0].imm = (u32)addr;
17169 			insn[1].imm = addr >> 32;
17170 
17171 			/* check whether we recorded this map already */
17172 			for (j = 0; j < env->used_map_cnt; j++) {
17173 				if (env->used_maps[j] == map) {
17174 					aux->map_index = j;
17175 					fdput(f);
17176 					goto next_insn;
17177 				}
17178 			}
17179 
17180 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17181 				fdput(f);
17182 				return -E2BIG;
17183 			}
17184 
17185 			/* hold the map. If the program is rejected by verifier,
17186 			 * the map will be released by release_maps() or it
17187 			 * will be used by the valid program until it's unloaded
17188 			 * and all maps are released in free_used_maps()
17189 			 */
17190 			bpf_map_inc(map);
17191 
17192 			aux->map_index = env->used_map_cnt;
17193 			env->used_maps[env->used_map_cnt++] = map;
17194 
17195 			if (bpf_map_is_cgroup_storage(map) &&
17196 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17197 				verbose(env, "only one cgroup storage of each type is allowed\n");
17198 				fdput(f);
17199 				return -EBUSY;
17200 			}
17201 
17202 			fdput(f);
17203 next_insn:
17204 			insn++;
17205 			i++;
17206 			continue;
17207 		}
17208 
17209 		/* Basic sanity check before we invest more work here. */
17210 		if (!bpf_opcode_in_insntable(insn->code)) {
17211 			verbose(env, "unknown opcode %02x\n", insn->code);
17212 			return -EINVAL;
17213 		}
17214 	}
17215 
17216 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17217 	 * 'struct bpf_map *' into a register instead of user map_fd.
17218 	 * These pointers will be used later by verifier to validate map access.
17219 	 */
17220 	return 0;
17221 }
17222 
17223 /* drop refcnt of maps used by the rejected program */
17224 static void release_maps(struct bpf_verifier_env *env)
17225 {
17226 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17227 			     env->used_map_cnt);
17228 }
17229 
17230 /* drop refcnt of maps used by the rejected program */
17231 static void release_btfs(struct bpf_verifier_env *env)
17232 {
17233 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17234 			     env->used_btf_cnt);
17235 }
17236 
17237 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17238 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17239 {
17240 	struct bpf_insn *insn = env->prog->insnsi;
17241 	int insn_cnt = env->prog->len;
17242 	int i;
17243 
17244 	for (i = 0; i < insn_cnt; i++, insn++) {
17245 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17246 			continue;
17247 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17248 			continue;
17249 		insn->src_reg = 0;
17250 	}
17251 }
17252 
17253 /* single env->prog->insni[off] instruction was replaced with the range
17254  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17255  * [0, off) and [off, end) to new locations, so the patched range stays zero
17256  */
17257 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17258 				 struct bpf_insn_aux_data *new_data,
17259 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17260 {
17261 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17262 	struct bpf_insn *insn = new_prog->insnsi;
17263 	u32 old_seen = old_data[off].seen;
17264 	u32 prog_len;
17265 	int i;
17266 
17267 	/* aux info at OFF always needs adjustment, no matter fast path
17268 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17269 	 * original insn at old prog.
17270 	 */
17271 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17272 
17273 	if (cnt == 1)
17274 		return;
17275 	prog_len = new_prog->len;
17276 
17277 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17278 	memcpy(new_data + off + cnt - 1, old_data + off,
17279 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17280 	for (i = off; i < off + cnt - 1; i++) {
17281 		/* Expand insni[off]'s seen count to the patched range. */
17282 		new_data[i].seen = old_seen;
17283 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17284 	}
17285 	env->insn_aux_data = new_data;
17286 	vfree(old_data);
17287 }
17288 
17289 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17290 {
17291 	int i;
17292 
17293 	if (len == 1)
17294 		return;
17295 	/* NOTE: fake 'exit' subprog should be updated as well. */
17296 	for (i = 0; i <= env->subprog_cnt; i++) {
17297 		if (env->subprog_info[i].start <= off)
17298 			continue;
17299 		env->subprog_info[i].start += len - 1;
17300 	}
17301 }
17302 
17303 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17304 {
17305 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17306 	int i, sz = prog->aux->size_poke_tab;
17307 	struct bpf_jit_poke_descriptor *desc;
17308 
17309 	for (i = 0; i < sz; i++) {
17310 		desc = &tab[i];
17311 		if (desc->insn_idx <= off)
17312 			continue;
17313 		desc->insn_idx += len - 1;
17314 	}
17315 }
17316 
17317 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17318 					    const struct bpf_insn *patch, u32 len)
17319 {
17320 	struct bpf_prog *new_prog;
17321 	struct bpf_insn_aux_data *new_data = NULL;
17322 
17323 	if (len > 1) {
17324 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17325 					      sizeof(struct bpf_insn_aux_data)));
17326 		if (!new_data)
17327 			return NULL;
17328 	}
17329 
17330 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17331 	if (IS_ERR(new_prog)) {
17332 		if (PTR_ERR(new_prog) == -ERANGE)
17333 			verbose(env,
17334 				"insn %d cannot be patched due to 16-bit range\n",
17335 				env->insn_aux_data[off].orig_idx);
17336 		vfree(new_data);
17337 		return NULL;
17338 	}
17339 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17340 	adjust_subprog_starts(env, off, len);
17341 	adjust_poke_descs(new_prog, off, len);
17342 	return new_prog;
17343 }
17344 
17345 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17346 					      u32 off, u32 cnt)
17347 {
17348 	int i, j;
17349 
17350 	/* find first prog starting at or after off (first to remove) */
17351 	for (i = 0; i < env->subprog_cnt; i++)
17352 		if (env->subprog_info[i].start >= off)
17353 			break;
17354 	/* find first prog starting at or after off + cnt (first to stay) */
17355 	for (j = i; j < env->subprog_cnt; j++)
17356 		if (env->subprog_info[j].start >= off + cnt)
17357 			break;
17358 	/* if j doesn't start exactly at off + cnt, we are just removing
17359 	 * the front of previous prog
17360 	 */
17361 	if (env->subprog_info[j].start != off + cnt)
17362 		j--;
17363 
17364 	if (j > i) {
17365 		struct bpf_prog_aux *aux = env->prog->aux;
17366 		int move;
17367 
17368 		/* move fake 'exit' subprog as well */
17369 		move = env->subprog_cnt + 1 - j;
17370 
17371 		memmove(env->subprog_info + i,
17372 			env->subprog_info + j,
17373 			sizeof(*env->subprog_info) * move);
17374 		env->subprog_cnt -= j - i;
17375 
17376 		/* remove func_info */
17377 		if (aux->func_info) {
17378 			move = aux->func_info_cnt - j;
17379 
17380 			memmove(aux->func_info + i,
17381 				aux->func_info + j,
17382 				sizeof(*aux->func_info) * move);
17383 			aux->func_info_cnt -= j - i;
17384 			/* func_info->insn_off is set after all code rewrites,
17385 			 * in adjust_btf_func() - no need to adjust
17386 			 */
17387 		}
17388 	} else {
17389 		/* convert i from "first prog to remove" to "first to adjust" */
17390 		if (env->subprog_info[i].start == off)
17391 			i++;
17392 	}
17393 
17394 	/* update fake 'exit' subprog as well */
17395 	for (; i <= env->subprog_cnt; i++)
17396 		env->subprog_info[i].start -= cnt;
17397 
17398 	return 0;
17399 }
17400 
17401 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17402 				      u32 cnt)
17403 {
17404 	struct bpf_prog *prog = env->prog;
17405 	u32 i, l_off, l_cnt, nr_linfo;
17406 	struct bpf_line_info *linfo;
17407 
17408 	nr_linfo = prog->aux->nr_linfo;
17409 	if (!nr_linfo)
17410 		return 0;
17411 
17412 	linfo = prog->aux->linfo;
17413 
17414 	/* find first line info to remove, count lines to be removed */
17415 	for (i = 0; i < nr_linfo; i++)
17416 		if (linfo[i].insn_off >= off)
17417 			break;
17418 
17419 	l_off = i;
17420 	l_cnt = 0;
17421 	for (; i < nr_linfo; i++)
17422 		if (linfo[i].insn_off < off + cnt)
17423 			l_cnt++;
17424 		else
17425 			break;
17426 
17427 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17428 	 * last removed linfo.  prog is already modified, so prog->len == off
17429 	 * means no live instructions after (tail of the program was removed).
17430 	 */
17431 	if (prog->len != off && l_cnt &&
17432 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17433 		l_cnt--;
17434 		linfo[--i].insn_off = off + cnt;
17435 	}
17436 
17437 	/* remove the line info which refer to the removed instructions */
17438 	if (l_cnt) {
17439 		memmove(linfo + l_off, linfo + i,
17440 			sizeof(*linfo) * (nr_linfo - i));
17441 
17442 		prog->aux->nr_linfo -= l_cnt;
17443 		nr_linfo = prog->aux->nr_linfo;
17444 	}
17445 
17446 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17447 	for (i = l_off; i < nr_linfo; i++)
17448 		linfo[i].insn_off -= cnt;
17449 
17450 	/* fix up all subprogs (incl. 'exit') which start >= off */
17451 	for (i = 0; i <= env->subprog_cnt; i++)
17452 		if (env->subprog_info[i].linfo_idx > l_off) {
17453 			/* program may have started in the removed region but
17454 			 * may not be fully removed
17455 			 */
17456 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17457 				env->subprog_info[i].linfo_idx -= l_cnt;
17458 			else
17459 				env->subprog_info[i].linfo_idx = l_off;
17460 		}
17461 
17462 	return 0;
17463 }
17464 
17465 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17466 {
17467 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17468 	unsigned int orig_prog_len = env->prog->len;
17469 	int err;
17470 
17471 	if (bpf_prog_is_offloaded(env->prog->aux))
17472 		bpf_prog_offload_remove_insns(env, off, cnt);
17473 
17474 	err = bpf_remove_insns(env->prog, off, cnt);
17475 	if (err)
17476 		return err;
17477 
17478 	err = adjust_subprog_starts_after_remove(env, off, cnt);
17479 	if (err)
17480 		return err;
17481 
17482 	err = bpf_adj_linfo_after_remove(env, off, cnt);
17483 	if (err)
17484 		return err;
17485 
17486 	memmove(aux_data + off,	aux_data + off + cnt,
17487 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
17488 
17489 	return 0;
17490 }
17491 
17492 /* The verifier does more data flow analysis than llvm and will not
17493  * explore branches that are dead at run time. Malicious programs can
17494  * have dead code too. Therefore replace all dead at-run-time code
17495  * with 'ja -1'.
17496  *
17497  * Just nops are not optimal, e.g. if they would sit at the end of the
17498  * program and through another bug we would manage to jump there, then
17499  * we'd execute beyond program memory otherwise. Returning exception
17500  * code also wouldn't work since we can have subprogs where the dead
17501  * code could be located.
17502  */
17503 static void sanitize_dead_code(struct bpf_verifier_env *env)
17504 {
17505 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17506 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17507 	struct bpf_insn *insn = env->prog->insnsi;
17508 	const int insn_cnt = env->prog->len;
17509 	int i;
17510 
17511 	for (i = 0; i < insn_cnt; i++) {
17512 		if (aux_data[i].seen)
17513 			continue;
17514 		memcpy(insn + i, &trap, sizeof(trap));
17515 		aux_data[i].zext_dst = false;
17516 	}
17517 }
17518 
17519 static bool insn_is_cond_jump(u8 code)
17520 {
17521 	u8 op;
17522 
17523 	op = BPF_OP(code);
17524 	if (BPF_CLASS(code) == BPF_JMP32)
17525 		return op != BPF_JA;
17526 
17527 	if (BPF_CLASS(code) != BPF_JMP)
17528 		return false;
17529 
17530 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17531 }
17532 
17533 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17534 {
17535 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17536 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17537 	struct bpf_insn *insn = env->prog->insnsi;
17538 	const int insn_cnt = env->prog->len;
17539 	int i;
17540 
17541 	for (i = 0; i < insn_cnt; i++, insn++) {
17542 		if (!insn_is_cond_jump(insn->code))
17543 			continue;
17544 
17545 		if (!aux_data[i + 1].seen)
17546 			ja.off = insn->off;
17547 		else if (!aux_data[i + 1 + insn->off].seen)
17548 			ja.off = 0;
17549 		else
17550 			continue;
17551 
17552 		if (bpf_prog_is_offloaded(env->prog->aux))
17553 			bpf_prog_offload_replace_insn(env, i, &ja);
17554 
17555 		memcpy(insn, &ja, sizeof(ja));
17556 	}
17557 }
17558 
17559 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17560 {
17561 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17562 	int insn_cnt = env->prog->len;
17563 	int i, err;
17564 
17565 	for (i = 0; i < insn_cnt; i++) {
17566 		int j;
17567 
17568 		j = 0;
17569 		while (i + j < insn_cnt && !aux_data[i + j].seen)
17570 			j++;
17571 		if (!j)
17572 			continue;
17573 
17574 		err = verifier_remove_insns(env, i, j);
17575 		if (err)
17576 			return err;
17577 		insn_cnt = env->prog->len;
17578 	}
17579 
17580 	return 0;
17581 }
17582 
17583 static int opt_remove_nops(struct bpf_verifier_env *env)
17584 {
17585 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17586 	struct bpf_insn *insn = env->prog->insnsi;
17587 	int insn_cnt = env->prog->len;
17588 	int i, err;
17589 
17590 	for (i = 0; i < insn_cnt; i++) {
17591 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17592 			continue;
17593 
17594 		err = verifier_remove_insns(env, i, 1);
17595 		if (err)
17596 			return err;
17597 		insn_cnt--;
17598 		i--;
17599 	}
17600 
17601 	return 0;
17602 }
17603 
17604 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17605 					 const union bpf_attr *attr)
17606 {
17607 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17608 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17609 	int i, patch_len, delta = 0, len = env->prog->len;
17610 	struct bpf_insn *insns = env->prog->insnsi;
17611 	struct bpf_prog *new_prog;
17612 	bool rnd_hi32;
17613 
17614 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17615 	zext_patch[1] = BPF_ZEXT_REG(0);
17616 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17617 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17618 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17619 	for (i = 0; i < len; i++) {
17620 		int adj_idx = i + delta;
17621 		struct bpf_insn insn;
17622 		int load_reg;
17623 
17624 		insn = insns[adj_idx];
17625 		load_reg = insn_def_regno(&insn);
17626 		if (!aux[adj_idx].zext_dst) {
17627 			u8 code, class;
17628 			u32 imm_rnd;
17629 
17630 			if (!rnd_hi32)
17631 				continue;
17632 
17633 			code = insn.code;
17634 			class = BPF_CLASS(code);
17635 			if (load_reg == -1)
17636 				continue;
17637 
17638 			/* NOTE: arg "reg" (the fourth one) is only used for
17639 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17640 			 *       here.
17641 			 */
17642 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17643 				if (class == BPF_LD &&
17644 				    BPF_MODE(code) == BPF_IMM)
17645 					i++;
17646 				continue;
17647 			}
17648 
17649 			/* ctx load could be transformed into wider load. */
17650 			if (class == BPF_LDX &&
17651 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17652 				continue;
17653 
17654 			imm_rnd = get_random_u32();
17655 			rnd_hi32_patch[0] = insn;
17656 			rnd_hi32_patch[1].imm = imm_rnd;
17657 			rnd_hi32_patch[3].dst_reg = load_reg;
17658 			patch = rnd_hi32_patch;
17659 			patch_len = 4;
17660 			goto apply_patch_buffer;
17661 		}
17662 
17663 		/* Add in an zero-extend instruction if a) the JIT has requested
17664 		 * it or b) it's a CMPXCHG.
17665 		 *
17666 		 * The latter is because: BPF_CMPXCHG always loads a value into
17667 		 * R0, therefore always zero-extends. However some archs'
17668 		 * equivalent instruction only does this load when the
17669 		 * comparison is successful. This detail of CMPXCHG is
17670 		 * orthogonal to the general zero-extension behaviour of the
17671 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17672 		 */
17673 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17674 			continue;
17675 
17676 		/* Zero-extension is done by the caller. */
17677 		if (bpf_pseudo_kfunc_call(&insn))
17678 			continue;
17679 
17680 		if (WARN_ON(load_reg == -1)) {
17681 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17682 			return -EFAULT;
17683 		}
17684 
17685 		zext_patch[0] = insn;
17686 		zext_patch[1].dst_reg = load_reg;
17687 		zext_patch[1].src_reg = load_reg;
17688 		patch = zext_patch;
17689 		patch_len = 2;
17690 apply_patch_buffer:
17691 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17692 		if (!new_prog)
17693 			return -ENOMEM;
17694 		env->prog = new_prog;
17695 		insns = new_prog->insnsi;
17696 		aux = env->insn_aux_data;
17697 		delta += patch_len - 1;
17698 	}
17699 
17700 	return 0;
17701 }
17702 
17703 /* convert load instructions that access fields of a context type into a
17704  * sequence of instructions that access fields of the underlying structure:
17705  *     struct __sk_buff    -> struct sk_buff
17706  *     struct bpf_sock_ops -> struct sock
17707  */
17708 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17709 {
17710 	const struct bpf_verifier_ops *ops = env->ops;
17711 	int i, cnt, size, ctx_field_size, delta = 0;
17712 	const int insn_cnt = env->prog->len;
17713 	struct bpf_insn insn_buf[16], *insn;
17714 	u32 target_size, size_default, off;
17715 	struct bpf_prog *new_prog;
17716 	enum bpf_access_type type;
17717 	bool is_narrower_load;
17718 
17719 	if (ops->gen_prologue || env->seen_direct_write) {
17720 		if (!ops->gen_prologue) {
17721 			verbose(env, "bpf verifier is misconfigured\n");
17722 			return -EINVAL;
17723 		}
17724 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17725 					env->prog);
17726 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17727 			verbose(env, "bpf verifier is misconfigured\n");
17728 			return -EINVAL;
17729 		} else if (cnt) {
17730 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17731 			if (!new_prog)
17732 				return -ENOMEM;
17733 
17734 			env->prog = new_prog;
17735 			delta += cnt - 1;
17736 		}
17737 	}
17738 
17739 	if (bpf_prog_is_offloaded(env->prog->aux))
17740 		return 0;
17741 
17742 	insn = env->prog->insnsi + delta;
17743 
17744 	for (i = 0; i < insn_cnt; i++, insn++) {
17745 		bpf_convert_ctx_access_t convert_ctx_access;
17746 		u8 mode;
17747 
17748 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17749 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17750 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17751 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17752 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17753 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17754 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17755 			type = BPF_READ;
17756 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17757 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17758 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17759 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17760 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17761 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17762 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17763 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17764 			type = BPF_WRITE;
17765 		} else {
17766 			continue;
17767 		}
17768 
17769 		if (type == BPF_WRITE &&
17770 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17771 			struct bpf_insn patch[] = {
17772 				*insn,
17773 				BPF_ST_NOSPEC(),
17774 			};
17775 
17776 			cnt = ARRAY_SIZE(patch);
17777 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17778 			if (!new_prog)
17779 				return -ENOMEM;
17780 
17781 			delta    += cnt - 1;
17782 			env->prog = new_prog;
17783 			insn      = new_prog->insnsi + i + delta;
17784 			continue;
17785 		}
17786 
17787 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17788 		case PTR_TO_CTX:
17789 			if (!ops->convert_ctx_access)
17790 				continue;
17791 			convert_ctx_access = ops->convert_ctx_access;
17792 			break;
17793 		case PTR_TO_SOCKET:
17794 		case PTR_TO_SOCK_COMMON:
17795 			convert_ctx_access = bpf_sock_convert_ctx_access;
17796 			break;
17797 		case PTR_TO_TCP_SOCK:
17798 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17799 			break;
17800 		case PTR_TO_XDP_SOCK:
17801 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17802 			break;
17803 		case PTR_TO_BTF_ID:
17804 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17805 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17806 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17807 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17808 		 * any faults for loads into such types. BPF_WRITE is disallowed
17809 		 * for this case.
17810 		 */
17811 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17812 			if (type == BPF_READ) {
17813 				if (BPF_MODE(insn->code) == BPF_MEM)
17814 					insn->code = BPF_LDX | BPF_PROBE_MEM |
17815 						     BPF_SIZE((insn)->code);
17816 				else
17817 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17818 						     BPF_SIZE((insn)->code);
17819 				env->prog->aux->num_exentries++;
17820 			}
17821 			continue;
17822 		default:
17823 			continue;
17824 		}
17825 
17826 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17827 		size = BPF_LDST_BYTES(insn);
17828 		mode = BPF_MODE(insn->code);
17829 
17830 		/* If the read access is a narrower load of the field,
17831 		 * convert to a 4/8-byte load, to minimum program type specific
17832 		 * convert_ctx_access changes. If conversion is successful,
17833 		 * we will apply proper mask to the result.
17834 		 */
17835 		is_narrower_load = size < ctx_field_size;
17836 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17837 		off = insn->off;
17838 		if (is_narrower_load) {
17839 			u8 size_code;
17840 
17841 			if (type == BPF_WRITE) {
17842 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17843 				return -EINVAL;
17844 			}
17845 
17846 			size_code = BPF_H;
17847 			if (ctx_field_size == 4)
17848 				size_code = BPF_W;
17849 			else if (ctx_field_size == 8)
17850 				size_code = BPF_DW;
17851 
17852 			insn->off = off & ~(size_default - 1);
17853 			insn->code = BPF_LDX | BPF_MEM | size_code;
17854 		}
17855 
17856 		target_size = 0;
17857 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17858 					 &target_size);
17859 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17860 		    (ctx_field_size && !target_size)) {
17861 			verbose(env, "bpf verifier is misconfigured\n");
17862 			return -EINVAL;
17863 		}
17864 
17865 		if (is_narrower_load && size < target_size) {
17866 			u8 shift = bpf_ctx_narrow_access_offset(
17867 				off, size, size_default) * 8;
17868 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17869 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17870 				return -EINVAL;
17871 			}
17872 			if (ctx_field_size <= 4) {
17873 				if (shift)
17874 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17875 									insn->dst_reg,
17876 									shift);
17877 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17878 								(1 << size * 8) - 1);
17879 			} else {
17880 				if (shift)
17881 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17882 									insn->dst_reg,
17883 									shift);
17884 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17885 								(1ULL << size * 8) - 1);
17886 			}
17887 		}
17888 		if (mode == BPF_MEMSX)
17889 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17890 						       insn->dst_reg, insn->dst_reg,
17891 						       size * 8, 0);
17892 
17893 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17894 		if (!new_prog)
17895 			return -ENOMEM;
17896 
17897 		delta += cnt - 1;
17898 
17899 		/* keep walking new program and skip insns we just inserted */
17900 		env->prog = new_prog;
17901 		insn      = new_prog->insnsi + i + delta;
17902 	}
17903 
17904 	return 0;
17905 }
17906 
17907 static int jit_subprogs(struct bpf_verifier_env *env)
17908 {
17909 	struct bpf_prog *prog = env->prog, **func, *tmp;
17910 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17911 	struct bpf_map *map_ptr;
17912 	struct bpf_insn *insn;
17913 	void *old_bpf_func;
17914 	int err, num_exentries;
17915 
17916 	if (env->subprog_cnt <= 1)
17917 		return 0;
17918 
17919 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17920 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17921 			continue;
17922 
17923 		/* Upon error here we cannot fall back to interpreter but
17924 		 * need a hard reject of the program. Thus -EFAULT is
17925 		 * propagated in any case.
17926 		 */
17927 		subprog = find_subprog(env, i + insn->imm + 1);
17928 		if (subprog < 0) {
17929 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17930 				  i + insn->imm + 1);
17931 			return -EFAULT;
17932 		}
17933 		/* temporarily remember subprog id inside insn instead of
17934 		 * aux_data, since next loop will split up all insns into funcs
17935 		 */
17936 		insn->off = subprog;
17937 		/* remember original imm in case JIT fails and fallback
17938 		 * to interpreter will be needed
17939 		 */
17940 		env->insn_aux_data[i].call_imm = insn->imm;
17941 		/* point imm to __bpf_call_base+1 from JITs point of view */
17942 		insn->imm = 1;
17943 		if (bpf_pseudo_func(insn))
17944 			/* jit (e.g. x86_64) may emit fewer instructions
17945 			 * if it learns a u32 imm is the same as a u64 imm.
17946 			 * Force a non zero here.
17947 			 */
17948 			insn[1].imm = 1;
17949 	}
17950 
17951 	err = bpf_prog_alloc_jited_linfo(prog);
17952 	if (err)
17953 		goto out_undo_insn;
17954 
17955 	err = -ENOMEM;
17956 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17957 	if (!func)
17958 		goto out_undo_insn;
17959 
17960 	for (i = 0; i < env->subprog_cnt; i++) {
17961 		subprog_start = subprog_end;
17962 		subprog_end = env->subprog_info[i + 1].start;
17963 
17964 		len = subprog_end - subprog_start;
17965 		/* bpf_prog_run() doesn't call subprogs directly,
17966 		 * hence main prog stats include the runtime of subprogs.
17967 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17968 		 * func[i]->stats will never be accessed and stays NULL
17969 		 */
17970 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17971 		if (!func[i])
17972 			goto out_free;
17973 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17974 		       len * sizeof(struct bpf_insn));
17975 		func[i]->type = prog->type;
17976 		func[i]->len = len;
17977 		if (bpf_prog_calc_tag(func[i]))
17978 			goto out_free;
17979 		func[i]->is_func = 1;
17980 		func[i]->aux->func_idx = i;
17981 		/* Below members will be freed only at prog->aux */
17982 		func[i]->aux->btf = prog->aux->btf;
17983 		func[i]->aux->func_info = prog->aux->func_info;
17984 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17985 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17986 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17987 
17988 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17989 			struct bpf_jit_poke_descriptor *poke;
17990 
17991 			poke = &prog->aux->poke_tab[j];
17992 			if (poke->insn_idx < subprog_end &&
17993 			    poke->insn_idx >= subprog_start)
17994 				poke->aux = func[i]->aux;
17995 		}
17996 
17997 		func[i]->aux->name[0] = 'F';
17998 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17999 		func[i]->jit_requested = 1;
18000 		func[i]->blinding_requested = prog->blinding_requested;
18001 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18002 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18003 		func[i]->aux->linfo = prog->aux->linfo;
18004 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18005 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18006 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18007 		num_exentries = 0;
18008 		insn = func[i]->insnsi;
18009 		for (j = 0; j < func[i]->len; j++, insn++) {
18010 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18011 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18012 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18013 				num_exentries++;
18014 		}
18015 		func[i]->aux->num_exentries = num_exentries;
18016 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18017 		func[i] = bpf_int_jit_compile(func[i]);
18018 		if (!func[i]->jited) {
18019 			err = -ENOTSUPP;
18020 			goto out_free;
18021 		}
18022 		cond_resched();
18023 	}
18024 
18025 	/* at this point all bpf functions were successfully JITed
18026 	 * now populate all bpf_calls with correct addresses and
18027 	 * run last pass of JIT
18028 	 */
18029 	for (i = 0; i < env->subprog_cnt; i++) {
18030 		insn = func[i]->insnsi;
18031 		for (j = 0; j < func[i]->len; j++, insn++) {
18032 			if (bpf_pseudo_func(insn)) {
18033 				subprog = insn->off;
18034 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18035 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18036 				continue;
18037 			}
18038 			if (!bpf_pseudo_call(insn))
18039 				continue;
18040 			subprog = insn->off;
18041 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18042 		}
18043 
18044 		/* we use the aux data to keep a list of the start addresses
18045 		 * of the JITed images for each function in the program
18046 		 *
18047 		 * for some architectures, such as powerpc64, the imm field
18048 		 * might not be large enough to hold the offset of the start
18049 		 * address of the callee's JITed image from __bpf_call_base
18050 		 *
18051 		 * in such cases, we can lookup the start address of a callee
18052 		 * by using its subprog id, available from the off field of
18053 		 * the call instruction, as an index for this list
18054 		 */
18055 		func[i]->aux->func = func;
18056 		func[i]->aux->func_cnt = env->subprog_cnt;
18057 	}
18058 	for (i = 0; i < env->subprog_cnt; i++) {
18059 		old_bpf_func = func[i]->bpf_func;
18060 		tmp = bpf_int_jit_compile(func[i]);
18061 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18062 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18063 			err = -ENOTSUPP;
18064 			goto out_free;
18065 		}
18066 		cond_resched();
18067 	}
18068 
18069 	/* finally lock prog and jit images for all functions and
18070 	 * populate kallsysm. Begin at the first subprogram, since
18071 	 * bpf_prog_load will add the kallsyms for the main program.
18072 	 */
18073 	for (i = 1; i < env->subprog_cnt; i++) {
18074 		bpf_prog_lock_ro(func[i]);
18075 		bpf_prog_kallsyms_add(func[i]);
18076 	}
18077 
18078 	/* Last step: make now unused interpreter insns from main
18079 	 * prog consistent for later dump requests, so they can
18080 	 * later look the same as if they were interpreted only.
18081 	 */
18082 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18083 		if (bpf_pseudo_func(insn)) {
18084 			insn[0].imm = env->insn_aux_data[i].call_imm;
18085 			insn[1].imm = insn->off;
18086 			insn->off = 0;
18087 			continue;
18088 		}
18089 		if (!bpf_pseudo_call(insn))
18090 			continue;
18091 		insn->off = env->insn_aux_data[i].call_imm;
18092 		subprog = find_subprog(env, i + insn->off + 1);
18093 		insn->imm = subprog;
18094 	}
18095 
18096 	prog->jited = 1;
18097 	prog->bpf_func = func[0]->bpf_func;
18098 	prog->jited_len = func[0]->jited_len;
18099 	prog->aux->extable = func[0]->aux->extable;
18100 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18101 	prog->aux->func = func;
18102 	prog->aux->func_cnt = env->subprog_cnt;
18103 	bpf_prog_jit_attempt_done(prog);
18104 	return 0;
18105 out_free:
18106 	/* We failed JIT'ing, so at this point we need to unregister poke
18107 	 * descriptors from subprogs, so that kernel is not attempting to
18108 	 * patch it anymore as we're freeing the subprog JIT memory.
18109 	 */
18110 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18111 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18112 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18113 	}
18114 	/* At this point we're guaranteed that poke descriptors are not
18115 	 * live anymore. We can just unlink its descriptor table as it's
18116 	 * released with the main prog.
18117 	 */
18118 	for (i = 0; i < env->subprog_cnt; i++) {
18119 		if (!func[i])
18120 			continue;
18121 		func[i]->aux->poke_tab = NULL;
18122 		bpf_jit_free(func[i]);
18123 	}
18124 	kfree(func);
18125 out_undo_insn:
18126 	/* cleanup main prog to be interpreted */
18127 	prog->jit_requested = 0;
18128 	prog->blinding_requested = 0;
18129 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18130 		if (!bpf_pseudo_call(insn))
18131 			continue;
18132 		insn->off = 0;
18133 		insn->imm = env->insn_aux_data[i].call_imm;
18134 	}
18135 	bpf_prog_jit_attempt_done(prog);
18136 	return err;
18137 }
18138 
18139 static int fixup_call_args(struct bpf_verifier_env *env)
18140 {
18141 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18142 	struct bpf_prog *prog = env->prog;
18143 	struct bpf_insn *insn = prog->insnsi;
18144 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18145 	int i, depth;
18146 #endif
18147 	int err = 0;
18148 
18149 	if (env->prog->jit_requested &&
18150 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18151 		err = jit_subprogs(env);
18152 		if (err == 0)
18153 			return 0;
18154 		if (err == -EFAULT)
18155 			return err;
18156 	}
18157 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18158 	if (has_kfunc_call) {
18159 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18160 		return -EINVAL;
18161 	}
18162 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18163 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18164 		 * have to be rejected, since interpreter doesn't support them yet.
18165 		 */
18166 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18167 		return -EINVAL;
18168 	}
18169 	for (i = 0; i < prog->len; i++, insn++) {
18170 		if (bpf_pseudo_func(insn)) {
18171 			/* When JIT fails the progs with callback calls
18172 			 * have to be rejected, since interpreter doesn't support them yet.
18173 			 */
18174 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18175 			return -EINVAL;
18176 		}
18177 
18178 		if (!bpf_pseudo_call(insn))
18179 			continue;
18180 		depth = get_callee_stack_depth(env, insn, i);
18181 		if (depth < 0)
18182 			return depth;
18183 		bpf_patch_call_args(insn, depth);
18184 	}
18185 	err = 0;
18186 #endif
18187 	return err;
18188 }
18189 
18190 /* replace a generic kfunc with a specialized version if necessary */
18191 static void specialize_kfunc(struct bpf_verifier_env *env,
18192 			     u32 func_id, u16 offset, unsigned long *addr)
18193 {
18194 	struct bpf_prog *prog = env->prog;
18195 	bool seen_direct_write;
18196 	void *xdp_kfunc;
18197 	bool is_rdonly;
18198 
18199 	if (bpf_dev_bound_kfunc_id(func_id)) {
18200 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18201 		if (xdp_kfunc) {
18202 			*addr = (unsigned long)xdp_kfunc;
18203 			return;
18204 		}
18205 		/* fallback to default kfunc when not supported by netdev */
18206 	}
18207 
18208 	if (offset)
18209 		return;
18210 
18211 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18212 		seen_direct_write = env->seen_direct_write;
18213 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18214 
18215 		if (is_rdonly)
18216 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18217 
18218 		/* restore env->seen_direct_write to its original value, since
18219 		 * may_access_direct_pkt_data mutates it
18220 		 */
18221 		env->seen_direct_write = seen_direct_write;
18222 	}
18223 }
18224 
18225 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18226 					    u16 struct_meta_reg,
18227 					    u16 node_offset_reg,
18228 					    struct bpf_insn *insn,
18229 					    struct bpf_insn *insn_buf,
18230 					    int *cnt)
18231 {
18232 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18233 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18234 
18235 	insn_buf[0] = addr[0];
18236 	insn_buf[1] = addr[1];
18237 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18238 	insn_buf[3] = *insn;
18239 	*cnt = 4;
18240 }
18241 
18242 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18243 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18244 {
18245 	const struct bpf_kfunc_desc *desc;
18246 
18247 	if (!insn->imm) {
18248 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18249 		return -EINVAL;
18250 	}
18251 
18252 	*cnt = 0;
18253 
18254 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18255 	 * __bpf_call_base, unless the JIT needs to call functions that are
18256 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18257 	 */
18258 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18259 	if (!desc) {
18260 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18261 			insn->imm);
18262 		return -EFAULT;
18263 	}
18264 
18265 	if (!bpf_jit_supports_far_kfunc_call())
18266 		insn->imm = BPF_CALL_IMM(desc->addr);
18267 	if (insn->off)
18268 		return 0;
18269 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18270 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18271 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18272 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18273 
18274 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18275 		insn_buf[1] = addr[0];
18276 		insn_buf[2] = addr[1];
18277 		insn_buf[3] = *insn;
18278 		*cnt = 4;
18279 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18280 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18281 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18282 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18283 
18284 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18285 		    !kptr_struct_meta) {
18286 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18287 				insn_idx);
18288 			return -EFAULT;
18289 		}
18290 
18291 		insn_buf[0] = addr[0];
18292 		insn_buf[1] = addr[1];
18293 		insn_buf[2] = *insn;
18294 		*cnt = 3;
18295 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18296 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18297 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18298 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18299 		int struct_meta_reg = BPF_REG_3;
18300 		int node_offset_reg = BPF_REG_4;
18301 
18302 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18303 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18304 			struct_meta_reg = BPF_REG_4;
18305 			node_offset_reg = BPF_REG_5;
18306 		}
18307 
18308 		if (!kptr_struct_meta) {
18309 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18310 				insn_idx);
18311 			return -EFAULT;
18312 		}
18313 
18314 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18315 						node_offset_reg, insn, insn_buf, cnt);
18316 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18317 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18318 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18319 		*cnt = 1;
18320 	}
18321 	return 0;
18322 }
18323 
18324 /* Do various post-verification rewrites in a single program pass.
18325  * These rewrites simplify JIT and interpreter implementations.
18326  */
18327 static int do_misc_fixups(struct bpf_verifier_env *env)
18328 {
18329 	struct bpf_prog *prog = env->prog;
18330 	enum bpf_attach_type eatype = prog->expected_attach_type;
18331 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18332 	struct bpf_insn *insn = prog->insnsi;
18333 	const struct bpf_func_proto *fn;
18334 	const int insn_cnt = prog->len;
18335 	const struct bpf_map_ops *ops;
18336 	struct bpf_insn_aux_data *aux;
18337 	struct bpf_insn insn_buf[16];
18338 	struct bpf_prog *new_prog;
18339 	struct bpf_map *map_ptr;
18340 	int i, ret, cnt, delta = 0;
18341 
18342 	for (i = 0; i < insn_cnt; i++, insn++) {
18343 		/* Make divide-by-zero exceptions impossible. */
18344 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18345 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18346 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18347 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18348 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18349 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18350 			struct bpf_insn *patchlet;
18351 			struct bpf_insn chk_and_div[] = {
18352 				/* [R,W]x div 0 -> 0 */
18353 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18354 					     BPF_JNE | BPF_K, insn->src_reg,
18355 					     0, 2, 0),
18356 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18357 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18358 				*insn,
18359 			};
18360 			struct bpf_insn chk_and_mod[] = {
18361 				/* [R,W]x mod 0 -> [R,W]x */
18362 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18363 					     BPF_JEQ | BPF_K, insn->src_reg,
18364 					     0, 1 + (is64 ? 0 : 1), 0),
18365 				*insn,
18366 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18367 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18368 			};
18369 
18370 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18371 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18372 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18373 
18374 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18375 			if (!new_prog)
18376 				return -ENOMEM;
18377 
18378 			delta    += cnt - 1;
18379 			env->prog = prog = new_prog;
18380 			insn      = new_prog->insnsi + i + delta;
18381 			continue;
18382 		}
18383 
18384 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18385 		if (BPF_CLASS(insn->code) == BPF_LD &&
18386 		    (BPF_MODE(insn->code) == BPF_ABS ||
18387 		     BPF_MODE(insn->code) == BPF_IND)) {
18388 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18389 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18390 				verbose(env, "bpf verifier is misconfigured\n");
18391 				return -EINVAL;
18392 			}
18393 
18394 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18395 			if (!new_prog)
18396 				return -ENOMEM;
18397 
18398 			delta    += cnt - 1;
18399 			env->prog = prog = new_prog;
18400 			insn      = new_prog->insnsi + i + delta;
18401 			continue;
18402 		}
18403 
18404 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18405 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18406 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18407 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18408 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18409 			struct bpf_insn *patch = &insn_buf[0];
18410 			bool issrc, isneg, isimm;
18411 			u32 off_reg;
18412 
18413 			aux = &env->insn_aux_data[i + delta];
18414 			if (!aux->alu_state ||
18415 			    aux->alu_state == BPF_ALU_NON_POINTER)
18416 				continue;
18417 
18418 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18419 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18420 				BPF_ALU_SANITIZE_SRC;
18421 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18422 
18423 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18424 			if (isimm) {
18425 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18426 			} else {
18427 				if (isneg)
18428 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18429 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18430 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18431 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18432 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18433 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18434 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18435 			}
18436 			if (!issrc)
18437 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18438 			insn->src_reg = BPF_REG_AX;
18439 			if (isneg)
18440 				insn->code = insn->code == code_add ?
18441 					     code_sub : code_add;
18442 			*patch++ = *insn;
18443 			if (issrc && isneg && !isimm)
18444 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18445 			cnt = patch - insn_buf;
18446 
18447 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18448 			if (!new_prog)
18449 				return -ENOMEM;
18450 
18451 			delta    += cnt - 1;
18452 			env->prog = prog = new_prog;
18453 			insn      = new_prog->insnsi + i + delta;
18454 			continue;
18455 		}
18456 
18457 		if (insn->code != (BPF_JMP | BPF_CALL))
18458 			continue;
18459 		if (insn->src_reg == BPF_PSEUDO_CALL)
18460 			continue;
18461 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18462 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18463 			if (ret)
18464 				return ret;
18465 			if (cnt == 0)
18466 				continue;
18467 
18468 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18469 			if (!new_prog)
18470 				return -ENOMEM;
18471 
18472 			delta	 += cnt - 1;
18473 			env->prog = prog = new_prog;
18474 			insn	  = new_prog->insnsi + i + delta;
18475 			continue;
18476 		}
18477 
18478 		if (insn->imm == BPF_FUNC_get_route_realm)
18479 			prog->dst_needed = 1;
18480 		if (insn->imm == BPF_FUNC_get_prandom_u32)
18481 			bpf_user_rnd_init_once();
18482 		if (insn->imm == BPF_FUNC_override_return)
18483 			prog->kprobe_override = 1;
18484 		if (insn->imm == BPF_FUNC_tail_call) {
18485 			/* If we tail call into other programs, we
18486 			 * cannot make any assumptions since they can
18487 			 * be replaced dynamically during runtime in
18488 			 * the program array.
18489 			 */
18490 			prog->cb_access = 1;
18491 			if (!allow_tail_call_in_subprogs(env))
18492 				prog->aux->stack_depth = MAX_BPF_STACK;
18493 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18494 
18495 			/* mark bpf_tail_call as different opcode to avoid
18496 			 * conditional branch in the interpreter for every normal
18497 			 * call and to prevent accidental JITing by JIT compiler
18498 			 * that doesn't support bpf_tail_call yet
18499 			 */
18500 			insn->imm = 0;
18501 			insn->code = BPF_JMP | BPF_TAIL_CALL;
18502 
18503 			aux = &env->insn_aux_data[i + delta];
18504 			if (env->bpf_capable && !prog->blinding_requested &&
18505 			    prog->jit_requested &&
18506 			    !bpf_map_key_poisoned(aux) &&
18507 			    !bpf_map_ptr_poisoned(aux) &&
18508 			    !bpf_map_ptr_unpriv(aux)) {
18509 				struct bpf_jit_poke_descriptor desc = {
18510 					.reason = BPF_POKE_REASON_TAIL_CALL,
18511 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18512 					.tail_call.key = bpf_map_key_immediate(aux),
18513 					.insn_idx = i + delta,
18514 				};
18515 
18516 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
18517 				if (ret < 0) {
18518 					verbose(env, "adding tail call poke descriptor failed\n");
18519 					return ret;
18520 				}
18521 
18522 				insn->imm = ret + 1;
18523 				continue;
18524 			}
18525 
18526 			if (!bpf_map_ptr_unpriv(aux))
18527 				continue;
18528 
18529 			/* instead of changing every JIT dealing with tail_call
18530 			 * emit two extra insns:
18531 			 * if (index >= max_entries) goto out;
18532 			 * index &= array->index_mask;
18533 			 * to avoid out-of-bounds cpu speculation
18534 			 */
18535 			if (bpf_map_ptr_poisoned(aux)) {
18536 				verbose(env, "tail_call abusing map_ptr\n");
18537 				return -EINVAL;
18538 			}
18539 
18540 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18541 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18542 						  map_ptr->max_entries, 2);
18543 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18544 						    container_of(map_ptr,
18545 								 struct bpf_array,
18546 								 map)->index_mask);
18547 			insn_buf[2] = *insn;
18548 			cnt = 3;
18549 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18550 			if (!new_prog)
18551 				return -ENOMEM;
18552 
18553 			delta    += cnt - 1;
18554 			env->prog = prog = new_prog;
18555 			insn      = new_prog->insnsi + i + delta;
18556 			continue;
18557 		}
18558 
18559 		if (insn->imm == BPF_FUNC_timer_set_callback) {
18560 			/* The verifier will process callback_fn as many times as necessary
18561 			 * with different maps and the register states prepared by
18562 			 * set_timer_callback_state will be accurate.
18563 			 *
18564 			 * The following use case is valid:
18565 			 *   map1 is shared by prog1, prog2, prog3.
18566 			 *   prog1 calls bpf_timer_init for some map1 elements
18567 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
18568 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
18569 			 *   prog3 calls bpf_timer_start for some map1 elements.
18570 			 *     Those that were not both bpf_timer_init-ed and
18571 			 *     bpf_timer_set_callback-ed will return -EINVAL.
18572 			 */
18573 			struct bpf_insn ld_addrs[2] = {
18574 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18575 			};
18576 
18577 			insn_buf[0] = ld_addrs[0];
18578 			insn_buf[1] = ld_addrs[1];
18579 			insn_buf[2] = *insn;
18580 			cnt = 3;
18581 
18582 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18583 			if (!new_prog)
18584 				return -ENOMEM;
18585 
18586 			delta    += cnt - 1;
18587 			env->prog = prog = new_prog;
18588 			insn      = new_prog->insnsi + i + delta;
18589 			goto patch_call_imm;
18590 		}
18591 
18592 		if (is_storage_get_function(insn->imm)) {
18593 			if (!env->prog->aux->sleepable ||
18594 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
18595 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18596 			else
18597 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18598 			insn_buf[1] = *insn;
18599 			cnt = 2;
18600 
18601 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18602 			if (!new_prog)
18603 				return -ENOMEM;
18604 
18605 			delta += cnt - 1;
18606 			env->prog = prog = new_prog;
18607 			insn = new_prog->insnsi + i + delta;
18608 			goto patch_call_imm;
18609 		}
18610 
18611 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18612 		 * and other inlining handlers are currently limited to 64 bit
18613 		 * only.
18614 		 */
18615 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18616 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
18617 		     insn->imm == BPF_FUNC_map_update_elem ||
18618 		     insn->imm == BPF_FUNC_map_delete_elem ||
18619 		     insn->imm == BPF_FUNC_map_push_elem   ||
18620 		     insn->imm == BPF_FUNC_map_pop_elem    ||
18621 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18622 		     insn->imm == BPF_FUNC_redirect_map    ||
18623 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18624 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18625 			aux = &env->insn_aux_data[i + delta];
18626 			if (bpf_map_ptr_poisoned(aux))
18627 				goto patch_call_imm;
18628 
18629 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18630 			ops = map_ptr->ops;
18631 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18632 			    ops->map_gen_lookup) {
18633 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18634 				if (cnt == -EOPNOTSUPP)
18635 					goto patch_map_ops_generic;
18636 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18637 					verbose(env, "bpf verifier is misconfigured\n");
18638 					return -EINVAL;
18639 				}
18640 
18641 				new_prog = bpf_patch_insn_data(env, i + delta,
18642 							       insn_buf, cnt);
18643 				if (!new_prog)
18644 					return -ENOMEM;
18645 
18646 				delta    += cnt - 1;
18647 				env->prog = prog = new_prog;
18648 				insn      = new_prog->insnsi + i + delta;
18649 				continue;
18650 			}
18651 
18652 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18653 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18654 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18655 				     (long (*)(struct bpf_map *map, void *key))NULL));
18656 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18657 				     (long (*)(struct bpf_map *map, void *key, void *value,
18658 					      u64 flags))NULL));
18659 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18660 				     (long (*)(struct bpf_map *map, void *value,
18661 					      u64 flags))NULL));
18662 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18663 				     (long (*)(struct bpf_map *map, void *value))NULL));
18664 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18665 				     (long (*)(struct bpf_map *map, void *value))NULL));
18666 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18667 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18668 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18669 				     (long (*)(struct bpf_map *map,
18670 					      bpf_callback_t callback_fn,
18671 					      void *callback_ctx,
18672 					      u64 flags))NULL));
18673 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18674 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18675 
18676 patch_map_ops_generic:
18677 			switch (insn->imm) {
18678 			case BPF_FUNC_map_lookup_elem:
18679 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18680 				continue;
18681 			case BPF_FUNC_map_update_elem:
18682 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18683 				continue;
18684 			case BPF_FUNC_map_delete_elem:
18685 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18686 				continue;
18687 			case BPF_FUNC_map_push_elem:
18688 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18689 				continue;
18690 			case BPF_FUNC_map_pop_elem:
18691 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18692 				continue;
18693 			case BPF_FUNC_map_peek_elem:
18694 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18695 				continue;
18696 			case BPF_FUNC_redirect_map:
18697 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18698 				continue;
18699 			case BPF_FUNC_for_each_map_elem:
18700 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18701 				continue;
18702 			case BPF_FUNC_map_lookup_percpu_elem:
18703 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18704 				continue;
18705 			}
18706 
18707 			goto patch_call_imm;
18708 		}
18709 
18710 		/* Implement bpf_jiffies64 inline. */
18711 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18712 		    insn->imm == BPF_FUNC_jiffies64) {
18713 			struct bpf_insn ld_jiffies_addr[2] = {
18714 				BPF_LD_IMM64(BPF_REG_0,
18715 					     (unsigned long)&jiffies),
18716 			};
18717 
18718 			insn_buf[0] = ld_jiffies_addr[0];
18719 			insn_buf[1] = ld_jiffies_addr[1];
18720 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18721 						  BPF_REG_0, 0);
18722 			cnt = 3;
18723 
18724 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18725 						       cnt);
18726 			if (!new_prog)
18727 				return -ENOMEM;
18728 
18729 			delta    += cnt - 1;
18730 			env->prog = prog = new_prog;
18731 			insn      = new_prog->insnsi + i + delta;
18732 			continue;
18733 		}
18734 
18735 		/* Implement bpf_get_func_arg inline. */
18736 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18737 		    insn->imm == BPF_FUNC_get_func_arg) {
18738 			/* Load nr_args from ctx - 8 */
18739 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18740 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18741 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18742 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18743 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18744 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18745 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18746 			insn_buf[7] = BPF_JMP_A(1);
18747 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18748 			cnt = 9;
18749 
18750 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18751 			if (!new_prog)
18752 				return -ENOMEM;
18753 
18754 			delta    += cnt - 1;
18755 			env->prog = prog = new_prog;
18756 			insn      = new_prog->insnsi + i + delta;
18757 			continue;
18758 		}
18759 
18760 		/* Implement bpf_get_func_ret inline. */
18761 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18762 		    insn->imm == BPF_FUNC_get_func_ret) {
18763 			if (eatype == BPF_TRACE_FEXIT ||
18764 			    eatype == BPF_MODIFY_RETURN) {
18765 				/* Load nr_args from ctx - 8 */
18766 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18767 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18768 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18769 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18770 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18771 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18772 				cnt = 6;
18773 			} else {
18774 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18775 				cnt = 1;
18776 			}
18777 
18778 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18779 			if (!new_prog)
18780 				return -ENOMEM;
18781 
18782 			delta    += cnt - 1;
18783 			env->prog = prog = new_prog;
18784 			insn      = new_prog->insnsi + i + delta;
18785 			continue;
18786 		}
18787 
18788 		/* Implement get_func_arg_cnt inline. */
18789 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18790 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18791 			/* Load nr_args from ctx - 8 */
18792 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18793 
18794 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18795 			if (!new_prog)
18796 				return -ENOMEM;
18797 
18798 			env->prog = prog = new_prog;
18799 			insn      = new_prog->insnsi + i + delta;
18800 			continue;
18801 		}
18802 
18803 		/* Implement bpf_get_func_ip inline. */
18804 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18805 		    insn->imm == BPF_FUNC_get_func_ip) {
18806 			/* Load IP address from ctx - 16 */
18807 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18808 
18809 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18810 			if (!new_prog)
18811 				return -ENOMEM;
18812 
18813 			env->prog = prog = new_prog;
18814 			insn      = new_prog->insnsi + i + delta;
18815 			continue;
18816 		}
18817 
18818 patch_call_imm:
18819 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18820 		/* all functions that have prototype and verifier allowed
18821 		 * programs to call them, must be real in-kernel functions
18822 		 */
18823 		if (!fn->func) {
18824 			verbose(env,
18825 				"kernel subsystem misconfigured func %s#%d\n",
18826 				func_id_name(insn->imm), insn->imm);
18827 			return -EFAULT;
18828 		}
18829 		insn->imm = fn->func - __bpf_call_base;
18830 	}
18831 
18832 	/* Since poke tab is now finalized, publish aux to tracker. */
18833 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18834 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18835 		if (!map_ptr->ops->map_poke_track ||
18836 		    !map_ptr->ops->map_poke_untrack ||
18837 		    !map_ptr->ops->map_poke_run) {
18838 			verbose(env, "bpf verifier is misconfigured\n");
18839 			return -EINVAL;
18840 		}
18841 
18842 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18843 		if (ret < 0) {
18844 			verbose(env, "tracking tail call prog failed\n");
18845 			return ret;
18846 		}
18847 	}
18848 
18849 	sort_kfunc_descs_by_imm_off(env->prog);
18850 
18851 	return 0;
18852 }
18853 
18854 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18855 					int position,
18856 					s32 stack_base,
18857 					u32 callback_subprogno,
18858 					u32 *cnt)
18859 {
18860 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18861 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18862 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18863 	int reg_loop_max = BPF_REG_6;
18864 	int reg_loop_cnt = BPF_REG_7;
18865 	int reg_loop_ctx = BPF_REG_8;
18866 
18867 	struct bpf_prog *new_prog;
18868 	u32 callback_start;
18869 	u32 call_insn_offset;
18870 	s32 callback_offset;
18871 
18872 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18873 	 * be careful to modify this code in sync.
18874 	 */
18875 	struct bpf_insn insn_buf[] = {
18876 		/* Return error and jump to the end of the patch if
18877 		 * expected number of iterations is too big.
18878 		 */
18879 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18880 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18881 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18882 		/* spill R6, R7, R8 to use these as loop vars */
18883 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18884 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18885 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18886 		/* initialize loop vars */
18887 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18888 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18889 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18890 		/* loop header,
18891 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18892 		 */
18893 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18894 		/* callback call,
18895 		 * correct callback offset would be set after patching
18896 		 */
18897 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18898 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18899 		BPF_CALL_REL(0),
18900 		/* increment loop counter */
18901 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18902 		/* jump to loop header if callback returned 0 */
18903 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18904 		/* return value of bpf_loop,
18905 		 * set R0 to the number of iterations
18906 		 */
18907 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18908 		/* restore original values of R6, R7, R8 */
18909 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18910 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18911 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18912 	};
18913 
18914 	*cnt = ARRAY_SIZE(insn_buf);
18915 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18916 	if (!new_prog)
18917 		return new_prog;
18918 
18919 	/* callback start is known only after patching */
18920 	callback_start = env->subprog_info[callback_subprogno].start;
18921 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18922 	call_insn_offset = position + 12;
18923 	callback_offset = callback_start - call_insn_offset - 1;
18924 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18925 
18926 	return new_prog;
18927 }
18928 
18929 static bool is_bpf_loop_call(struct bpf_insn *insn)
18930 {
18931 	return insn->code == (BPF_JMP | BPF_CALL) &&
18932 		insn->src_reg == 0 &&
18933 		insn->imm == BPF_FUNC_loop;
18934 }
18935 
18936 /* For all sub-programs in the program (including main) check
18937  * insn_aux_data to see if there are bpf_loop calls that require
18938  * inlining. If such calls are found the calls are replaced with a
18939  * sequence of instructions produced by `inline_bpf_loop` function and
18940  * subprog stack_depth is increased by the size of 3 registers.
18941  * This stack space is used to spill values of the R6, R7, R8.  These
18942  * registers are used to store the loop bound, counter and context
18943  * variables.
18944  */
18945 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18946 {
18947 	struct bpf_subprog_info *subprogs = env->subprog_info;
18948 	int i, cur_subprog = 0, cnt, delta = 0;
18949 	struct bpf_insn *insn = env->prog->insnsi;
18950 	int insn_cnt = env->prog->len;
18951 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18952 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18953 	u16 stack_depth_extra = 0;
18954 
18955 	for (i = 0; i < insn_cnt; i++, insn++) {
18956 		struct bpf_loop_inline_state *inline_state =
18957 			&env->insn_aux_data[i + delta].loop_inline_state;
18958 
18959 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18960 			struct bpf_prog *new_prog;
18961 
18962 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18963 			new_prog = inline_bpf_loop(env,
18964 						   i + delta,
18965 						   -(stack_depth + stack_depth_extra),
18966 						   inline_state->callback_subprogno,
18967 						   &cnt);
18968 			if (!new_prog)
18969 				return -ENOMEM;
18970 
18971 			delta     += cnt - 1;
18972 			env->prog  = new_prog;
18973 			insn       = new_prog->insnsi + i + delta;
18974 		}
18975 
18976 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18977 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18978 			cur_subprog++;
18979 			stack_depth = subprogs[cur_subprog].stack_depth;
18980 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18981 			stack_depth_extra = 0;
18982 		}
18983 	}
18984 
18985 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18986 
18987 	return 0;
18988 }
18989 
18990 static void free_states(struct bpf_verifier_env *env)
18991 {
18992 	struct bpf_verifier_state_list *sl, *sln;
18993 	int i;
18994 
18995 	sl = env->free_list;
18996 	while (sl) {
18997 		sln = sl->next;
18998 		free_verifier_state(&sl->state, false);
18999 		kfree(sl);
19000 		sl = sln;
19001 	}
19002 	env->free_list = NULL;
19003 
19004 	if (!env->explored_states)
19005 		return;
19006 
19007 	for (i = 0; i < state_htab_size(env); i++) {
19008 		sl = env->explored_states[i];
19009 
19010 		while (sl) {
19011 			sln = sl->next;
19012 			free_verifier_state(&sl->state, false);
19013 			kfree(sl);
19014 			sl = sln;
19015 		}
19016 		env->explored_states[i] = NULL;
19017 	}
19018 }
19019 
19020 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19021 {
19022 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19023 	struct bpf_verifier_state *state;
19024 	struct bpf_reg_state *regs;
19025 	int ret, i;
19026 
19027 	env->prev_linfo = NULL;
19028 	env->pass_cnt++;
19029 
19030 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19031 	if (!state)
19032 		return -ENOMEM;
19033 	state->curframe = 0;
19034 	state->speculative = false;
19035 	state->branches = 1;
19036 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19037 	if (!state->frame[0]) {
19038 		kfree(state);
19039 		return -ENOMEM;
19040 	}
19041 	env->cur_state = state;
19042 	init_func_state(env, state->frame[0],
19043 			BPF_MAIN_FUNC /* callsite */,
19044 			0 /* frameno */,
19045 			subprog);
19046 	state->first_insn_idx = env->subprog_info[subprog].start;
19047 	state->last_insn_idx = -1;
19048 
19049 	regs = state->frame[state->curframe]->regs;
19050 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19051 		ret = btf_prepare_func_args(env, subprog, regs);
19052 		if (ret)
19053 			goto out;
19054 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19055 			if (regs[i].type == PTR_TO_CTX)
19056 				mark_reg_known_zero(env, regs, i);
19057 			else if (regs[i].type == SCALAR_VALUE)
19058 				mark_reg_unknown(env, regs, i);
19059 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19060 				const u32 mem_size = regs[i].mem_size;
19061 
19062 				mark_reg_known_zero(env, regs, i);
19063 				regs[i].mem_size = mem_size;
19064 				regs[i].id = ++env->id_gen;
19065 			}
19066 		}
19067 	} else {
19068 		/* 1st arg to a function */
19069 		regs[BPF_REG_1].type = PTR_TO_CTX;
19070 		mark_reg_known_zero(env, regs, BPF_REG_1);
19071 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19072 		if (ret == -EFAULT)
19073 			/* unlikely verifier bug. abort.
19074 			 * ret == 0 and ret < 0 are sadly acceptable for
19075 			 * main() function due to backward compatibility.
19076 			 * Like socket filter program may be written as:
19077 			 * int bpf_prog(struct pt_regs *ctx)
19078 			 * and never dereference that ctx in the program.
19079 			 * 'struct pt_regs' is a type mismatch for socket
19080 			 * filter that should be using 'struct __sk_buff'.
19081 			 */
19082 			goto out;
19083 	}
19084 
19085 	ret = do_check(env);
19086 out:
19087 	/* check for NULL is necessary, since cur_state can be freed inside
19088 	 * do_check() under memory pressure.
19089 	 */
19090 	if (env->cur_state) {
19091 		free_verifier_state(env->cur_state, true);
19092 		env->cur_state = NULL;
19093 	}
19094 	while (!pop_stack(env, NULL, NULL, false));
19095 	if (!ret && pop_log)
19096 		bpf_vlog_reset(&env->log, 0);
19097 	free_states(env);
19098 	return ret;
19099 }
19100 
19101 /* Verify all global functions in a BPF program one by one based on their BTF.
19102  * All global functions must pass verification. Otherwise the whole program is rejected.
19103  * Consider:
19104  * int bar(int);
19105  * int foo(int f)
19106  * {
19107  *    return bar(f);
19108  * }
19109  * int bar(int b)
19110  * {
19111  *    ...
19112  * }
19113  * foo() will be verified first for R1=any_scalar_value. During verification it
19114  * will be assumed that bar() already verified successfully and call to bar()
19115  * from foo() will be checked for type match only. Later bar() will be verified
19116  * independently to check that it's safe for R1=any_scalar_value.
19117  */
19118 static int do_check_subprogs(struct bpf_verifier_env *env)
19119 {
19120 	struct bpf_prog_aux *aux = env->prog->aux;
19121 	int i, ret;
19122 
19123 	if (!aux->func_info)
19124 		return 0;
19125 
19126 	for (i = 1; i < env->subprog_cnt; i++) {
19127 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19128 			continue;
19129 		env->insn_idx = env->subprog_info[i].start;
19130 		WARN_ON_ONCE(env->insn_idx == 0);
19131 		ret = do_check_common(env, i);
19132 		if (ret) {
19133 			return ret;
19134 		} else if (env->log.level & BPF_LOG_LEVEL) {
19135 			verbose(env,
19136 				"Func#%d is safe for any args that match its prototype\n",
19137 				i);
19138 		}
19139 	}
19140 	return 0;
19141 }
19142 
19143 static int do_check_main(struct bpf_verifier_env *env)
19144 {
19145 	int ret;
19146 
19147 	env->insn_idx = 0;
19148 	ret = do_check_common(env, 0);
19149 	if (!ret)
19150 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19151 	return ret;
19152 }
19153 
19154 
19155 static void print_verification_stats(struct bpf_verifier_env *env)
19156 {
19157 	int i;
19158 
19159 	if (env->log.level & BPF_LOG_STATS) {
19160 		verbose(env, "verification time %lld usec\n",
19161 			div_u64(env->verification_time, 1000));
19162 		verbose(env, "stack depth ");
19163 		for (i = 0; i < env->subprog_cnt; i++) {
19164 			u32 depth = env->subprog_info[i].stack_depth;
19165 
19166 			verbose(env, "%d", depth);
19167 			if (i + 1 < env->subprog_cnt)
19168 				verbose(env, "+");
19169 		}
19170 		verbose(env, "\n");
19171 	}
19172 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19173 		"total_states %d peak_states %d mark_read %d\n",
19174 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19175 		env->max_states_per_insn, env->total_states,
19176 		env->peak_states, env->longest_mark_read_walk);
19177 }
19178 
19179 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19180 {
19181 	const struct btf_type *t, *func_proto;
19182 	const struct bpf_struct_ops *st_ops;
19183 	const struct btf_member *member;
19184 	struct bpf_prog *prog = env->prog;
19185 	u32 btf_id, member_idx;
19186 	const char *mname;
19187 
19188 	if (!prog->gpl_compatible) {
19189 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19190 		return -EINVAL;
19191 	}
19192 
19193 	btf_id = prog->aux->attach_btf_id;
19194 	st_ops = bpf_struct_ops_find(btf_id);
19195 	if (!st_ops) {
19196 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19197 			btf_id);
19198 		return -ENOTSUPP;
19199 	}
19200 
19201 	t = st_ops->type;
19202 	member_idx = prog->expected_attach_type;
19203 	if (member_idx >= btf_type_vlen(t)) {
19204 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19205 			member_idx, st_ops->name);
19206 		return -EINVAL;
19207 	}
19208 
19209 	member = &btf_type_member(t)[member_idx];
19210 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19211 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19212 					       NULL);
19213 	if (!func_proto) {
19214 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19215 			mname, member_idx, st_ops->name);
19216 		return -EINVAL;
19217 	}
19218 
19219 	if (st_ops->check_member) {
19220 		int err = st_ops->check_member(t, member, prog);
19221 
19222 		if (err) {
19223 			verbose(env, "attach to unsupported member %s of struct %s\n",
19224 				mname, st_ops->name);
19225 			return err;
19226 		}
19227 	}
19228 
19229 	prog->aux->attach_func_proto = func_proto;
19230 	prog->aux->attach_func_name = mname;
19231 	env->ops = st_ops->verifier_ops;
19232 
19233 	return 0;
19234 }
19235 #define SECURITY_PREFIX "security_"
19236 
19237 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19238 {
19239 	if (within_error_injection_list(addr) ||
19240 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19241 		return 0;
19242 
19243 	return -EINVAL;
19244 }
19245 
19246 /* list of non-sleepable functions that are otherwise on
19247  * ALLOW_ERROR_INJECTION list
19248  */
19249 BTF_SET_START(btf_non_sleepable_error_inject)
19250 /* Three functions below can be called from sleepable and non-sleepable context.
19251  * Assume non-sleepable from bpf safety point of view.
19252  */
19253 BTF_ID(func, __filemap_add_folio)
19254 BTF_ID(func, should_fail_alloc_page)
19255 BTF_ID(func, should_failslab)
19256 BTF_SET_END(btf_non_sleepable_error_inject)
19257 
19258 static int check_non_sleepable_error_inject(u32 btf_id)
19259 {
19260 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19261 }
19262 
19263 int bpf_check_attach_target(struct bpf_verifier_log *log,
19264 			    const struct bpf_prog *prog,
19265 			    const struct bpf_prog *tgt_prog,
19266 			    u32 btf_id,
19267 			    struct bpf_attach_target_info *tgt_info)
19268 {
19269 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19270 	const char prefix[] = "btf_trace_";
19271 	int ret = 0, subprog = -1, i;
19272 	const struct btf_type *t;
19273 	bool conservative = true;
19274 	const char *tname;
19275 	struct btf *btf;
19276 	long addr = 0;
19277 	struct module *mod = NULL;
19278 
19279 	if (!btf_id) {
19280 		bpf_log(log, "Tracing programs must provide btf_id\n");
19281 		return -EINVAL;
19282 	}
19283 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19284 	if (!btf) {
19285 		bpf_log(log,
19286 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19287 		return -EINVAL;
19288 	}
19289 	t = btf_type_by_id(btf, btf_id);
19290 	if (!t) {
19291 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19292 		return -EINVAL;
19293 	}
19294 	tname = btf_name_by_offset(btf, t->name_off);
19295 	if (!tname) {
19296 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19297 		return -EINVAL;
19298 	}
19299 	if (tgt_prog) {
19300 		struct bpf_prog_aux *aux = tgt_prog->aux;
19301 
19302 		if (bpf_prog_is_dev_bound(prog->aux) &&
19303 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19304 			bpf_log(log, "Target program bound device mismatch");
19305 			return -EINVAL;
19306 		}
19307 
19308 		for (i = 0; i < aux->func_info_cnt; i++)
19309 			if (aux->func_info[i].type_id == btf_id) {
19310 				subprog = i;
19311 				break;
19312 			}
19313 		if (subprog == -1) {
19314 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19315 			return -EINVAL;
19316 		}
19317 		conservative = aux->func_info_aux[subprog].unreliable;
19318 		if (prog_extension) {
19319 			if (conservative) {
19320 				bpf_log(log,
19321 					"Cannot replace static functions\n");
19322 				return -EINVAL;
19323 			}
19324 			if (!prog->jit_requested) {
19325 				bpf_log(log,
19326 					"Extension programs should be JITed\n");
19327 				return -EINVAL;
19328 			}
19329 		}
19330 		if (!tgt_prog->jited) {
19331 			bpf_log(log, "Can attach to only JITed progs\n");
19332 			return -EINVAL;
19333 		}
19334 		if (tgt_prog->type == prog->type) {
19335 			/* Cannot fentry/fexit another fentry/fexit program.
19336 			 * Cannot attach program extension to another extension.
19337 			 * It's ok to attach fentry/fexit to extension program.
19338 			 */
19339 			bpf_log(log, "Cannot recursively attach\n");
19340 			return -EINVAL;
19341 		}
19342 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19343 		    prog_extension &&
19344 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19345 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19346 			/* Program extensions can extend all program types
19347 			 * except fentry/fexit. The reason is the following.
19348 			 * The fentry/fexit programs are used for performance
19349 			 * analysis, stats and can be attached to any program
19350 			 * type except themselves. When extension program is
19351 			 * replacing XDP function it is necessary to allow
19352 			 * performance analysis of all functions. Both original
19353 			 * XDP program and its program extension. Hence
19354 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19355 			 * allowed. If extending of fentry/fexit was allowed it
19356 			 * would be possible to create long call chain
19357 			 * fentry->extension->fentry->extension beyond
19358 			 * reasonable stack size. Hence extending fentry is not
19359 			 * allowed.
19360 			 */
19361 			bpf_log(log, "Cannot extend fentry/fexit\n");
19362 			return -EINVAL;
19363 		}
19364 	} else {
19365 		if (prog_extension) {
19366 			bpf_log(log, "Cannot replace kernel functions\n");
19367 			return -EINVAL;
19368 		}
19369 	}
19370 
19371 	switch (prog->expected_attach_type) {
19372 	case BPF_TRACE_RAW_TP:
19373 		if (tgt_prog) {
19374 			bpf_log(log,
19375 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19376 			return -EINVAL;
19377 		}
19378 		if (!btf_type_is_typedef(t)) {
19379 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19380 				btf_id);
19381 			return -EINVAL;
19382 		}
19383 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19384 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19385 				btf_id, tname);
19386 			return -EINVAL;
19387 		}
19388 		tname += sizeof(prefix) - 1;
19389 		t = btf_type_by_id(btf, t->type);
19390 		if (!btf_type_is_ptr(t))
19391 			/* should never happen in valid vmlinux build */
19392 			return -EINVAL;
19393 		t = btf_type_by_id(btf, t->type);
19394 		if (!btf_type_is_func_proto(t))
19395 			/* should never happen in valid vmlinux build */
19396 			return -EINVAL;
19397 
19398 		break;
19399 	case BPF_TRACE_ITER:
19400 		if (!btf_type_is_func(t)) {
19401 			bpf_log(log, "attach_btf_id %u is not a function\n",
19402 				btf_id);
19403 			return -EINVAL;
19404 		}
19405 		t = btf_type_by_id(btf, t->type);
19406 		if (!btf_type_is_func_proto(t))
19407 			return -EINVAL;
19408 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19409 		if (ret)
19410 			return ret;
19411 		break;
19412 	default:
19413 		if (!prog_extension)
19414 			return -EINVAL;
19415 		fallthrough;
19416 	case BPF_MODIFY_RETURN:
19417 	case BPF_LSM_MAC:
19418 	case BPF_LSM_CGROUP:
19419 	case BPF_TRACE_FENTRY:
19420 	case BPF_TRACE_FEXIT:
19421 		if (!btf_type_is_func(t)) {
19422 			bpf_log(log, "attach_btf_id %u is not a function\n",
19423 				btf_id);
19424 			return -EINVAL;
19425 		}
19426 		if (prog_extension &&
19427 		    btf_check_type_match(log, prog, btf, t))
19428 			return -EINVAL;
19429 		t = btf_type_by_id(btf, t->type);
19430 		if (!btf_type_is_func_proto(t))
19431 			return -EINVAL;
19432 
19433 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19434 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19435 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19436 			return -EINVAL;
19437 
19438 		if (tgt_prog && conservative)
19439 			t = NULL;
19440 
19441 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19442 		if (ret < 0)
19443 			return ret;
19444 
19445 		if (tgt_prog) {
19446 			if (subprog == 0)
19447 				addr = (long) tgt_prog->bpf_func;
19448 			else
19449 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19450 		} else {
19451 			if (btf_is_module(btf)) {
19452 				mod = btf_try_get_module(btf);
19453 				if (mod)
19454 					addr = find_kallsyms_symbol_value(mod, tname);
19455 				else
19456 					addr = 0;
19457 			} else {
19458 				addr = kallsyms_lookup_name(tname);
19459 			}
19460 			if (!addr) {
19461 				module_put(mod);
19462 				bpf_log(log,
19463 					"The address of function %s cannot be found\n",
19464 					tname);
19465 				return -ENOENT;
19466 			}
19467 		}
19468 
19469 		if (prog->aux->sleepable) {
19470 			ret = -EINVAL;
19471 			switch (prog->type) {
19472 			case BPF_PROG_TYPE_TRACING:
19473 
19474 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
19475 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19476 				 */
19477 				if (!check_non_sleepable_error_inject(btf_id) &&
19478 				    within_error_injection_list(addr))
19479 					ret = 0;
19480 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
19481 				 * in the fmodret id set with the KF_SLEEPABLE flag.
19482 				 */
19483 				else {
19484 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19485 										prog);
19486 
19487 					if (flags && (*flags & KF_SLEEPABLE))
19488 						ret = 0;
19489 				}
19490 				break;
19491 			case BPF_PROG_TYPE_LSM:
19492 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
19493 				 * Only some of them are sleepable.
19494 				 */
19495 				if (bpf_lsm_is_sleepable_hook(btf_id))
19496 					ret = 0;
19497 				break;
19498 			default:
19499 				break;
19500 			}
19501 			if (ret) {
19502 				module_put(mod);
19503 				bpf_log(log, "%s is not sleepable\n", tname);
19504 				return ret;
19505 			}
19506 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19507 			if (tgt_prog) {
19508 				module_put(mod);
19509 				bpf_log(log, "can't modify return codes of BPF programs\n");
19510 				return -EINVAL;
19511 			}
19512 			ret = -EINVAL;
19513 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19514 			    !check_attach_modify_return(addr, tname))
19515 				ret = 0;
19516 			if (ret) {
19517 				module_put(mod);
19518 				bpf_log(log, "%s() is not modifiable\n", tname);
19519 				return ret;
19520 			}
19521 		}
19522 
19523 		break;
19524 	}
19525 	tgt_info->tgt_addr = addr;
19526 	tgt_info->tgt_name = tname;
19527 	tgt_info->tgt_type = t;
19528 	tgt_info->tgt_mod = mod;
19529 	return 0;
19530 }
19531 
19532 BTF_SET_START(btf_id_deny)
19533 BTF_ID_UNUSED
19534 #ifdef CONFIG_SMP
19535 BTF_ID(func, migrate_disable)
19536 BTF_ID(func, migrate_enable)
19537 #endif
19538 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19539 BTF_ID(func, rcu_read_unlock_strict)
19540 #endif
19541 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19542 BTF_ID(func, preempt_count_add)
19543 BTF_ID(func, preempt_count_sub)
19544 #endif
19545 #ifdef CONFIG_PREEMPT_RCU
19546 BTF_ID(func, __rcu_read_lock)
19547 BTF_ID(func, __rcu_read_unlock)
19548 #endif
19549 BTF_SET_END(btf_id_deny)
19550 
19551 static bool can_be_sleepable(struct bpf_prog *prog)
19552 {
19553 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19554 		switch (prog->expected_attach_type) {
19555 		case BPF_TRACE_FENTRY:
19556 		case BPF_TRACE_FEXIT:
19557 		case BPF_MODIFY_RETURN:
19558 		case BPF_TRACE_ITER:
19559 			return true;
19560 		default:
19561 			return false;
19562 		}
19563 	}
19564 	return prog->type == BPF_PROG_TYPE_LSM ||
19565 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19566 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19567 }
19568 
19569 static int check_attach_btf_id(struct bpf_verifier_env *env)
19570 {
19571 	struct bpf_prog *prog = env->prog;
19572 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19573 	struct bpf_attach_target_info tgt_info = {};
19574 	u32 btf_id = prog->aux->attach_btf_id;
19575 	struct bpf_trampoline *tr;
19576 	int ret;
19577 	u64 key;
19578 
19579 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19580 		if (prog->aux->sleepable)
19581 			/* attach_btf_id checked to be zero already */
19582 			return 0;
19583 		verbose(env, "Syscall programs can only be sleepable\n");
19584 		return -EINVAL;
19585 	}
19586 
19587 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19588 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19589 		return -EINVAL;
19590 	}
19591 
19592 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19593 		return check_struct_ops_btf_id(env);
19594 
19595 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19596 	    prog->type != BPF_PROG_TYPE_LSM &&
19597 	    prog->type != BPF_PROG_TYPE_EXT)
19598 		return 0;
19599 
19600 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19601 	if (ret)
19602 		return ret;
19603 
19604 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19605 		/* to make freplace equivalent to their targets, they need to
19606 		 * inherit env->ops and expected_attach_type for the rest of the
19607 		 * verification
19608 		 */
19609 		env->ops = bpf_verifier_ops[tgt_prog->type];
19610 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19611 	}
19612 
19613 	/* store info about the attachment target that will be used later */
19614 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19615 	prog->aux->attach_func_name = tgt_info.tgt_name;
19616 	prog->aux->mod = tgt_info.tgt_mod;
19617 
19618 	if (tgt_prog) {
19619 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19620 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19621 	}
19622 
19623 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19624 		prog->aux->attach_btf_trace = true;
19625 		return 0;
19626 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19627 		if (!bpf_iter_prog_supported(prog))
19628 			return -EINVAL;
19629 		return 0;
19630 	}
19631 
19632 	if (prog->type == BPF_PROG_TYPE_LSM) {
19633 		ret = bpf_lsm_verify_prog(&env->log, prog);
19634 		if (ret < 0)
19635 			return ret;
19636 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19637 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19638 		return -EINVAL;
19639 	}
19640 
19641 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19642 	tr = bpf_trampoline_get(key, &tgt_info);
19643 	if (!tr)
19644 		return -ENOMEM;
19645 
19646 	prog->aux->dst_trampoline = tr;
19647 	return 0;
19648 }
19649 
19650 struct btf *bpf_get_btf_vmlinux(void)
19651 {
19652 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19653 		mutex_lock(&bpf_verifier_lock);
19654 		if (!btf_vmlinux)
19655 			btf_vmlinux = btf_parse_vmlinux();
19656 		mutex_unlock(&bpf_verifier_lock);
19657 	}
19658 	return btf_vmlinux;
19659 }
19660 
19661 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19662 {
19663 	u64 start_time = ktime_get_ns();
19664 	struct bpf_verifier_env *env;
19665 	int i, len, ret = -EINVAL, err;
19666 	u32 log_true_size;
19667 	bool is_priv;
19668 
19669 	/* no program is valid */
19670 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19671 		return -EINVAL;
19672 
19673 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19674 	 * allocate/free it every time bpf_check() is called
19675 	 */
19676 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19677 	if (!env)
19678 		return -ENOMEM;
19679 
19680 	env->bt.env = env;
19681 
19682 	len = (*prog)->len;
19683 	env->insn_aux_data =
19684 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19685 	ret = -ENOMEM;
19686 	if (!env->insn_aux_data)
19687 		goto err_free_env;
19688 	for (i = 0; i < len; i++)
19689 		env->insn_aux_data[i].orig_idx = i;
19690 	env->prog = *prog;
19691 	env->ops = bpf_verifier_ops[env->prog->type];
19692 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19693 	is_priv = bpf_capable();
19694 
19695 	bpf_get_btf_vmlinux();
19696 
19697 	/* grab the mutex to protect few globals used by verifier */
19698 	if (!is_priv)
19699 		mutex_lock(&bpf_verifier_lock);
19700 
19701 	/* user could have requested verbose verifier output
19702 	 * and supplied buffer to store the verification trace
19703 	 */
19704 	ret = bpf_vlog_init(&env->log, attr->log_level,
19705 			    (char __user *) (unsigned long) attr->log_buf,
19706 			    attr->log_size);
19707 	if (ret)
19708 		goto err_unlock;
19709 
19710 	mark_verifier_state_clean(env);
19711 
19712 	if (IS_ERR(btf_vmlinux)) {
19713 		/* Either gcc or pahole or kernel are broken. */
19714 		verbose(env, "in-kernel BTF is malformed\n");
19715 		ret = PTR_ERR(btf_vmlinux);
19716 		goto skip_full_check;
19717 	}
19718 
19719 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19720 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19721 		env->strict_alignment = true;
19722 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19723 		env->strict_alignment = false;
19724 
19725 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19726 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19727 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19728 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19729 	env->bpf_capable = bpf_capable();
19730 
19731 	if (is_priv)
19732 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19733 
19734 	env->explored_states = kvcalloc(state_htab_size(env),
19735 				       sizeof(struct bpf_verifier_state_list *),
19736 				       GFP_USER);
19737 	ret = -ENOMEM;
19738 	if (!env->explored_states)
19739 		goto skip_full_check;
19740 
19741 	ret = add_subprog_and_kfunc(env);
19742 	if (ret < 0)
19743 		goto skip_full_check;
19744 
19745 	ret = check_subprogs(env);
19746 	if (ret < 0)
19747 		goto skip_full_check;
19748 
19749 	ret = check_btf_info(env, attr, uattr);
19750 	if (ret < 0)
19751 		goto skip_full_check;
19752 
19753 	ret = check_attach_btf_id(env);
19754 	if (ret)
19755 		goto skip_full_check;
19756 
19757 	ret = resolve_pseudo_ldimm64(env);
19758 	if (ret < 0)
19759 		goto skip_full_check;
19760 
19761 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19762 		ret = bpf_prog_offload_verifier_prep(env->prog);
19763 		if (ret)
19764 			goto skip_full_check;
19765 	}
19766 
19767 	ret = check_cfg(env);
19768 	if (ret < 0)
19769 		goto skip_full_check;
19770 
19771 	ret = do_check_subprogs(env);
19772 	ret = ret ?: do_check_main(env);
19773 
19774 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19775 		ret = bpf_prog_offload_finalize(env);
19776 
19777 skip_full_check:
19778 	kvfree(env->explored_states);
19779 
19780 	if (ret == 0)
19781 		ret = check_max_stack_depth(env);
19782 
19783 	/* instruction rewrites happen after this point */
19784 	if (ret == 0)
19785 		ret = optimize_bpf_loop(env);
19786 
19787 	if (is_priv) {
19788 		if (ret == 0)
19789 			opt_hard_wire_dead_code_branches(env);
19790 		if (ret == 0)
19791 			ret = opt_remove_dead_code(env);
19792 		if (ret == 0)
19793 			ret = opt_remove_nops(env);
19794 	} else {
19795 		if (ret == 0)
19796 			sanitize_dead_code(env);
19797 	}
19798 
19799 	if (ret == 0)
19800 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19801 		ret = convert_ctx_accesses(env);
19802 
19803 	if (ret == 0)
19804 		ret = do_misc_fixups(env);
19805 
19806 	/* do 32-bit optimization after insn patching has done so those patched
19807 	 * insns could be handled correctly.
19808 	 */
19809 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19810 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19811 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19812 								     : false;
19813 	}
19814 
19815 	if (ret == 0)
19816 		ret = fixup_call_args(env);
19817 
19818 	env->verification_time = ktime_get_ns() - start_time;
19819 	print_verification_stats(env);
19820 	env->prog->aux->verified_insns = env->insn_processed;
19821 
19822 	/* preserve original error even if log finalization is successful */
19823 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19824 	if (err)
19825 		ret = err;
19826 
19827 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19828 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19829 				  &log_true_size, sizeof(log_true_size))) {
19830 		ret = -EFAULT;
19831 		goto err_release_maps;
19832 	}
19833 
19834 	if (ret)
19835 		goto err_release_maps;
19836 
19837 	if (env->used_map_cnt) {
19838 		/* if program passed verifier, update used_maps in bpf_prog_info */
19839 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19840 							  sizeof(env->used_maps[0]),
19841 							  GFP_KERNEL);
19842 
19843 		if (!env->prog->aux->used_maps) {
19844 			ret = -ENOMEM;
19845 			goto err_release_maps;
19846 		}
19847 
19848 		memcpy(env->prog->aux->used_maps, env->used_maps,
19849 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19850 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19851 	}
19852 	if (env->used_btf_cnt) {
19853 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19854 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19855 							  sizeof(env->used_btfs[0]),
19856 							  GFP_KERNEL);
19857 		if (!env->prog->aux->used_btfs) {
19858 			ret = -ENOMEM;
19859 			goto err_release_maps;
19860 		}
19861 
19862 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19863 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19864 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19865 	}
19866 	if (env->used_map_cnt || env->used_btf_cnt) {
19867 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19868 		 * bpf_ld_imm64 instructions
19869 		 */
19870 		convert_pseudo_ld_imm64(env);
19871 	}
19872 
19873 	adjust_btf_func(env);
19874 
19875 err_release_maps:
19876 	if (!env->prog->aux->used_maps)
19877 		/* if we didn't copy map pointers into bpf_prog_info, release
19878 		 * them now. Otherwise free_used_maps() will release them.
19879 		 */
19880 		release_maps(env);
19881 	if (!env->prog->aux->used_btfs)
19882 		release_btfs(env);
19883 
19884 	/* extension progs temporarily inherit the attach_type of their targets
19885 	   for verification purposes, so set it back to zero before returning
19886 	 */
19887 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19888 		env->prog->expected_attach_type = 0;
19889 
19890 	*prog = env->prog;
19891 err_unlock:
19892 	if (!is_priv)
19893 		mutex_unlock(&bpf_verifier_lock);
19894 	vfree(env->insn_aux_data);
19895 err_free_env:
19896 	kfree(env);
19897 	return ret;
19898 }
19899