xref: /openbmc/linux/kernel/bpf/verifier.c (revision d5a05299306227d73b0febba9cecedf88931c507)
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 
29 #include "disasm.h"
30 
31 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
32 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
33 	[_id] = & _name ## _verifier_ops,
34 #define BPF_MAP_TYPE(_id, _ops)
35 #define BPF_LINK_TYPE(_id, _name)
36 #include <linux/bpf_types.h>
37 #undef BPF_PROG_TYPE
38 #undef BPF_MAP_TYPE
39 #undef BPF_LINK_TYPE
40 };
41 
42 /* bpf_check() is a static code analyzer that walks eBPF program
43  * instruction by instruction and updates register/stack state.
44  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
45  *
46  * The first pass is depth-first-search to check that the program is a DAG.
47  * It rejects the following programs:
48  * - larger than BPF_MAXINSNS insns
49  * - if loop is present (detected via back-edge)
50  * - unreachable insns exist (shouldn't be a forest. program = one function)
51  * - out of bounds or malformed jumps
52  * The second pass is all possible path descent from the 1st insn.
53  * Since it's analyzing all paths through the program, the length of the
54  * analysis is limited to 64k insn, which may be hit even if total number of
55  * insn is less then 4K, but there are too many branches that change stack/regs.
56  * Number of 'branches to be analyzed' is limited to 1k
57  *
58  * On entry to each instruction, each register has a type, and the instruction
59  * changes the types of the registers depending on instruction semantics.
60  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
61  * copied to R1.
62  *
63  * All registers are 64-bit.
64  * R0 - return register
65  * R1-R5 argument passing registers
66  * R6-R9 callee saved registers
67  * R10 - frame pointer read-only
68  *
69  * At the start of BPF program the register R1 contains a pointer to bpf_context
70  * and has type PTR_TO_CTX.
71  *
72  * Verifier tracks arithmetic operations on pointers in case:
73  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75  * 1st insn copies R10 (which has FRAME_PTR) type into R1
76  * and 2nd arithmetic instruction is pattern matched to recognize
77  * that it wants to construct a pointer to some element within stack.
78  * So after 2nd insn, the register R1 has type PTR_TO_STACK
79  * (and -20 constant is saved for further stack bounds checking).
80  * Meaning that this reg is a pointer to stack plus known immediate constant.
81  *
82  * Most of the time the registers have SCALAR_VALUE type, which
83  * means the register has some value, but it's not a valid pointer.
84  * (like pointer plus pointer becomes SCALAR_VALUE type)
85  *
86  * When verifier sees load or store instructions the type of base register
87  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88  * four pointer types recognized by check_mem_access() function.
89  *
90  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91  * and the range of [ptr, ptr + map's value_size) is accessible.
92  *
93  * registers used to pass values to function calls are checked against
94  * function argument constraints.
95  *
96  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97  * It means that the register type passed to this function must be
98  * PTR_TO_STACK and it will be used inside the function as
99  * 'pointer to map element key'
100  *
101  * For example the argument constraints for bpf_map_lookup_elem():
102  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103  *   .arg1_type = ARG_CONST_MAP_PTR,
104  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
105  *
106  * ret_type says that this function returns 'pointer to map elem value or null'
107  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108  * 2nd argument should be a pointer to stack, which will be used inside
109  * the helper function as a pointer to map element key.
110  *
111  * On the kernel side the helper function looks like:
112  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
113  * {
114  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115  *    void *key = (void *) (unsigned long) r2;
116  *    void *value;
117  *
118  *    here kernel can access 'key' and 'map' pointers safely, knowing that
119  *    [key, key + map->key_size) bytes are valid and were initialized on
120  *    the stack of eBPF program.
121  * }
122  *
123  * Corresponding eBPF program may look like:
124  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
125  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
127  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128  * here verifier looks at prototype of map_lookup_elem() and sees:
129  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
131  *
132  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134  * and were initialized prior to this call.
135  * If it's ok, then verifier allows this BPF_CALL insn and looks at
136  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138  * returns either pointer to map value or NULL.
139  *
140  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141  * insn, the register holding that pointer in the true branch changes state to
142  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143  * branch. See check_cond_jmp_op().
144  *
145  * After the call R0 is set to return type of the function and registers R1-R5
146  * are set to NOT_INIT to indicate that they are no longer readable.
147  *
148  * The following reference types represent a potential reference to a kernel
149  * resource which, after first being allocated, must be checked and freed by
150  * the BPF program:
151  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
152  *
153  * When the verifier sees a helper call return a reference type, it allocates a
154  * pointer id for the reference and stores it in the current function state.
155  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157  * passes through a NULL-check conditional. For the branch wherein the state is
158  * changed to CONST_IMM, the verifier releases the reference.
159  *
160  * For each helper function that allocates a reference, such as
161  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162  * bpf_sk_release(). When a reference type passes into the release function,
163  * the verifier also releases the reference. If any unchecked or unreleased
164  * reference remains at the end of the program, the verifier rejects it.
165  */
166 
167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
168 struct bpf_verifier_stack_elem {
169 	/* verifer state is 'st'
170 	 * before processing instruction 'insn_idx'
171 	 * and after processing instruction 'prev_insn_idx'
172 	 */
173 	struct bpf_verifier_state st;
174 	int insn_idx;
175 	int prev_insn_idx;
176 	struct bpf_verifier_stack_elem *next;
177 	/* length of verifier log at the time this state was pushed on stack */
178 	u32 log_pos;
179 };
180 
181 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
182 #define BPF_COMPLEXITY_LIMIT_STATES	64
183 
184 #define BPF_MAP_KEY_POISON	(1ULL << 63)
185 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
186 
187 #define BPF_MAP_PTR_UNPRIV	1UL
188 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
189 					  POISON_POINTER_DELTA))
190 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
191 
192 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
193 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
195 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
196 static int ref_set_non_owning(struct bpf_verifier_env *env,
197 			      struct bpf_reg_state *reg);
198 static void specialize_kfunc(struct bpf_verifier_env *env,
199 			     u32 func_id, u16 offset, unsigned long *addr);
200 
201 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
202 {
203 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
204 }
205 
206 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
207 {
208 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
209 }
210 
211 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
212 			      const struct bpf_map *map, bool unpriv)
213 {
214 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
215 	unpriv |= bpf_map_ptr_unpriv(aux);
216 	aux->map_ptr_state = (unsigned long)map |
217 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
218 }
219 
220 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
221 {
222 	return aux->map_key_state & BPF_MAP_KEY_POISON;
223 }
224 
225 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
226 {
227 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
228 }
229 
230 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
231 {
232 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
233 }
234 
235 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
236 {
237 	bool poisoned = bpf_map_key_poisoned(aux);
238 
239 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
240 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
241 }
242 
243 static bool bpf_helper_call(const struct bpf_insn *insn)
244 {
245 	return insn->code == (BPF_JMP | BPF_CALL) &&
246 	       insn->src_reg == 0;
247 }
248 
249 static bool bpf_pseudo_call(const struct bpf_insn *insn)
250 {
251 	return insn->code == (BPF_JMP | BPF_CALL) &&
252 	       insn->src_reg == BPF_PSEUDO_CALL;
253 }
254 
255 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
256 {
257 	return insn->code == (BPF_JMP | BPF_CALL) &&
258 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
259 }
260 
261 struct bpf_call_arg_meta {
262 	struct bpf_map *map_ptr;
263 	bool raw_mode;
264 	bool pkt_access;
265 	u8 release_regno;
266 	int regno;
267 	int access_size;
268 	int mem_size;
269 	u64 msize_max_value;
270 	int ref_obj_id;
271 	int dynptr_id;
272 	int map_uid;
273 	int func_id;
274 	struct btf *btf;
275 	u32 btf_id;
276 	struct btf *ret_btf;
277 	u32 ret_btf_id;
278 	u32 subprogno;
279 	struct btf_field *kptr_field;
280 };
281 
282 struct bpf_kfunc_call_arg_meta {
283 	/* In parameters */
284 	struct btf *btf;
285 	u32 func_id;
286 	u32 kfunc_flags;
287 	const struct btf_type *func_proto;
288 	const char *func_name;
289 	/* Out parameters */
290 	u32 ref_obj_id;
291 	u8 release_regno;
292 	bool r0_rdonly;
293 	u32 ret_btf_id;
294 	u64 r0_size;
295 	u32 subprogno;
296 	struct {
297 		u64 value;
298 		bool found;
299 	} arg_constant;
300 
301 	/* arg_btf and arg_btf_id are used by kfunc-specific handling,
302 	 * generally to pass info about user-defined local kptr types to later
303 	 * verification logic
304 	 *   bpf_obj_drop
305 	 *     Record the local kptr type to be drop'd
306 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
307 	 *     Record the local kptr type to be refcount_incr'd
308 	 */
309 	struct btf *arg_btf;
310 	u32 arg_btf_id;
311 
312 	struct {
313 		struct btf_field *field;
314 	} arg_list_head;
315 	struct {
316 		struct btf_field *field;
317 	} arg_rbtree_root;
318 	struct {
319 		enum bpf_dynptr_type type;
320 		u32 id;
321 		u32 ref_obj_id;
322 	} initialized_dynptr;
323 	struct {
324 		u8 spi;
325 		u8 frameno;
326 	} iter;
327 	u64 mem_size;
328 };
329 
330 struct btf *btf_vmlinux;
331 
332 static DEFINE_MUTEX(bpf_verifier_lock);
333 
334 static const struct bpf_line_info *
335 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
336 {
337 	const struct bpf_line_info *linfo;
338 	const struct bpf_prog *prog;
339 	u32 i, nr_linfo;
340 
341 	prog = env->prog;
342 	nr_linfo = prog->aux->nr_linfo;
343 
344 	if (!nr_linfo || insn_off >= prog->len)
345 		return NULL;
346 
347 	linfo = prog->aux->linfo;
348 	for (i = 1; i < nr_linfo; i++)
349 		if (insn_off < linfo[i].insn_off)
350 			break;
351 
352 	return &linfo[i - 1];
353 }
354 
355 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
356 {
357 	struct bpf_verifier_env *env = private_data;
358 	va_list args;
359 
360 	if (!bpf_verifier_log_needed(&env->log))
361 		return;
362 
363 	va_start(args, fmt);
364 	bpf_verifier_vlog(&env->log, fmt, args);
365 	va_end(args);
366 }
367 
368 static const char *ltrim(const char *s)
369 {
370 	while (isspace(*s))
371 		s++;
372 
373 	return s;
374 }
375 
376 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
377 					 u32 insn_off,
378 					 const char *prefix_fmt, ...)
379 {
380 	const struct bpf_line_info *linfo;
381 
382 	if (!bpf_verifier_log_needed(&env->log))
383 		return;
384 
385 	linfo = find_linfo(env, insn_off);
386 	if (!linfo || linfo == env->prev_linfo)
387 		return;
388 
389 	if (prefix_fmt) {
390 		va_list args;
391 
392 		va_start(args, prefix_fmt);
393 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
394 		va_end(args);
395 	}
396 
397 	verbose(env, "%s\n",
398 		ltrim(btf_name_by_offset(env->prog->aux->btf,
399 					 linfo->line_off)));
400 
401 	env->prev_linfo = linfo;
402 }
403 
404 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
405 				   struct bpf_reg_state *reg,
406 				   struct tnum *range, const char *ctx,
407 				   const char *reg_name)
408 {
409 	char tn_buf[48];
410 
411 	verbose(env, "At %s the register %s ", ctx, reg_name);
412 	if (!tnum_is_unknown(reg->var_off)) {
413 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
414 		verbose(env, "has value %s", tn_buf);
415 	} else {
416 		verbose(env, "has unknown scalar value");
417 	}
418 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
419 	verbose(env, " should have been in %s\n", tn_buf);
420 }
421 
422 static bool type_is_pkt_pointer(enum bpf_reg_type type)
423 {
424 	type = base_type(type);
425 	return type == PTR_TO_PACKET ||
426 	       type == PTR_TO_PACKET_META;
427 }
428 
429 static bool type_is_sk_pointer(enum bpf_reg_type type)
430 {
431 	return type == PTR_TO_SOCKET ||
432 		type == PTR_TO_SOCK_COMMON ||
433 		type == PTR_TO_TCP_SOCK ||
434 		type == PTR_TO_XDP_SOCK;
435 }
436 
437 static bool type_may_be_null(u32 type)
438 {
439 	return type & PTR_MAYBE_NULL;
440 }
441 
442 static bool reg_type_not_null(enum bpf_reg_type type)
443 {
444 	if (type_may_be_null(type))
445 		return false;
446 
447 	type = base_type(type);
448 	return type == PTR_TO_SOCKET ||
449 		type == PTR_TO_TCP_SOCK ||
450 		type == PTR_TO_MAP_VALUE ||
451 		type == PTR_TO_MAP_KEY ||
452 		type == PTR_TO_SOCK_COMMON ||
453 		type == PTR_TO_MEM;
454 }
455 
456 static bool type_is_ptr_alloc_obj(u32 type)
457 {
458 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
459 }
460 
461 static bool type_is_non_owning_ref(u32 type)
462 {
463 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
464 }
465 
466 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
467 {
468 	struct btf_record *rec = NULL;
469 	struct btf_struct_meta *meta;
470 
471 	if (reg->type == PTR_TO_MAP_VALUE) {
472 		rec = reg->map_ptr->record;
473 	} else if (type_is_ptr_alloc_obj(reg->type)) {
474 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
475 		if (meta)
476 			rec = meta->record;
477 	}
478 	return rec;
479 }
480 
481 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
482 {
483 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
484 
485 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
486 }
487 
488 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
489 {
490 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
491 }
492 
493 static bool type_is_rdonly_mem(u32 type)
494 {
495 	return type & MEM_RDONLY;
496 }
497 
498 static bool is_acquire_function(enum bpf_func_id func_id,
499 				const struct bpf_map *map)
500 {
501 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
502 
503 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
504 	    func_id == BPF_FUNC_sk_lookup_udp ||
505 	    func_id == BPF_FUNC_skc_lookup_tcp ||
506 	    func_id == BPF_FUNC_ringbuf_reserve ||
507 	    func_id == BPF_FUNC_kptr_xchg)
508 		return true;
509 
510 	if (func_id == BPF_FUNC_map_lookup_elem &&
511 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
512 	     map_type == BPF_MAP_TYPE_SOCKHASH))
513 		return true;
514 
515 	return false;
516 }
517 
518 static bool is_ptr_cast_function(enum bpf_func_id func_id)
519 {
520 	return func_id == BPF_FUNC_tcp_sock ||
521 		func_id == BPF_FUNC_sk_fullsock ||
522 		func_id == BPF_FUNC_skc_to_tcp_sock ||
523 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
524 		func_id == BPF_FUNC_skc_to_udp6_sock ||
525 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
526 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
527 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
528 }
529 
530 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
531 {
532 	return func_id == BPF_FUNC_dynptr_data;
533 }
534 
535 static bool is_callback_calling_kfunc(u32 btf_id);
536 
537 static bool is_callback_calling_function(enum bpf_func_id func_id)
538 {
539 	return func_id == BPF_FUNC_for_each_map_elem ||
540 	       func_id == BPF_FUNC_timer_set_callback ||
541 	       func_id == BPF_FUNC_find_vma ||
542 	       func_id == BPF_FUNC_loop ||
543 	       func_id == BPF_FUNC_user_ringbuf_drain;
544 }
545 
546 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
547 {
548 	return func_id == BPF_FUNC_timer_set_callback;
549 }
550 
551 static bool is_storage_get_function(enum bpf_func_id func_id)
552 {
553 	return func_id == BPF_FUNC_sk_storage_get ||
554 	       func_id == BPF_FUNC_inode_storage_get ||
555 	       func_id == BPF_FUNC_task_storage_get ||
556 	       func_id == BPF_FUNC_cgrp_storage_get;
557 }
558 
559 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
560 					const struct bpf_map *map)
561 {
562 	int ref_obj_uses = 0;
563 
564 	if (is_ptr_cast_function(func_id))
565 		ref_obj_uses++;
566 	if (is_acquire_function(func_id, map))
567 		ref_obj_uses++;
568 	if (is_dynptr_ref_function(func_id))
569 		ref_obj_uses++;
570 
571 	return ref_obj_uses > 1;
572 }
573 
574 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
575 {
576 	return BPF_CLASS(insn->code) == BPF_STX &&
577 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
578 	       insn->imm == BPF_CMPXCHG;
579 }
580 
581 /* string representation of 'enum bpf_reg_type'
582  *
583  * Note that reg_type_str() can not appear more than once in a single verbose()
584  * statement.
585  */
586 static const char *reg_type_str(struct bpf_verifier_env *env,
587 				enum bpf_reg_type type)
588 {
589 	char postfix[16] = {0}, prefix[64] = {0};
590 	static const char * const str[] = {
591 		[NOT_INIT]		= "?",
592 		[SCALAR_VALUE]		= "scalar",
593 		[PTR_TO_CTX]		= "ctx",
594 		[CONST_PTR_TO_MAP]	= "map_ptr",
595 		[PTR_TO_MAP_VALUE]	= "map_value",
596 		[PTR_TO_STACK]		= "fp",
597 		[PTR_TO_PACKET]		= "pkt",
598 		[PTR_TO_PACKET_META]	= "pkt_meta",
599 		[PTR_TO_PACKET_END]	= "pkt_end",
600 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
601 		[PTR_TO_SOCKET]		= "sock",
602 		[PTR_TO_SOCK_COMMON]	= "sock_common",
603 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
604 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
605 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
606 		[PTR_TO_BTF_ID]		= "ptr_",
607 		[PTR_TO_MEM]		= "mem",
608 		[PTR_TO_BUF]		= "buf",
609 		[PTR_TO_FUNC]		= "func",
610 		[PTR_TO_MAP_KEY]	= "map_key",
611 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
612 	};
613 
614 	if (type & PTR_MAYBE_NULL) {
615 		if (base_type(type) == PTR_TO_BTF_ID)
616 			strncpy(postfix, "or_null_", 16);
617 		else
618 			strncpy(postfix, "_or_null", 16);
619 	}
620 
621 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
622 		 type & MEM_RDONLY ? "rdonly_" : "",
623 		 type & MEM_RINGBUF ? "ringbuf_" : "",
624 		 type & MEM_USER ? "user_" : "",
625 		 type & MEM_PERCPU ? "percpu_" : "",
626 		 type & MEM_RCU ? "rcu_" : "",
627 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
628 		 type & PTR_TRUSTED ? "trusted_" : ""
629 	);
630 
631 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
632 		 prefix, str[base_type(type)], postfix);
633 	return env->tmp_str_buf;
634 }
635 
636 static char slot_type_char[] = {
637 	[STACK_INVALID]	= '?',
638 	[STACK_SPILL]	= 'r',
639 	[STACK_MISC]	= 'm',
640 	[STACK_ZERO]	= '0',
641 	[STACK_DYNPTR]	= 'd',
642 	[STACK_ITER]	= 'i',
643 };
644 
645 static void print_liveness(struct bpf_verifier_env *env,
646 			   enum bpf_reg_liveness live)
647 {
648 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
649 	    verbose(env, "_");
650 	if (live & REG_LIVE_READ)
651 		verbose(env, "r");
652 	if (live & REG_LIVE_WRITTEN)
653 		verbose(env, "w");
654 	if (live & REG_LIVE_DONE)
655 		verbose(env, "D");
656 }
657 
658 static int __get_spi(s32 off)
659 {
660 	return (-off - 1) / BPF_REG_SIZE;
661 }
662 
663 static struct bpf_func_state *func(struct bpf_verifier_env *env,
664 				   const struct bpf_reg_state *reg)
665 {
666 	struct bpf_verifier_state *cur = env->cur_state;
667 
668 	return cur->frame[reg->frameno];
669 }
670 
671 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
672 {
673        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
674 
675        /* We need to check that slots between [spi - nr_slots + 1, spi] are
676 	* within [0, allocated_stack).
677 	*
678 	* Please note that the spi grows downwards. For example, a dynptr
679 	* takes the size of two stack slots; the first slot will be at
680 	* spi and the second slot will be at spi - 1.
681 	*/
682        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
683 }
684 
685 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
686 			          const char *obj_kind, int nr_slots)
687 {
688 	int off, spi;
689 
690 	if (!tnum_is_const(reg->var_off)) {
691 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
692 		return -EINVAL;
693 	}
694 
695 	off = reg->off + reg->var_off.value;
696 	if (off % BPF_REG_SIZE) {
697 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
698 		return -EINVAL;
699 	}
700 
701 	spi = __get_spi(off);
702 	if (spi + 1 < nr_slots) {
703 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
704 		return -EINVAL;
705 	}
706 
707 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
708 		return -ERANGE;
709 	return spi;
710 }
711 
712 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
713 {
714 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
715 }
716 
717 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
718 {
719 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
720 }
721 
722 static const char *btf_type_name(const struct btf *btf, u32 id)
723 {
724 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
725 }
726 
727 static const char *dynptr_type_str(enum bpf_dynptr_type type)
728 {
729 	switch (type) {
730 	case BPF_DYNPTR_TYPE_LOCAL:
731 		return "local";
732 	case BPF_DYNPTR_TYPE_RINGBUF:
733 		return "ringbuf";
734 	case BPF_DYNPTR_TYPE_SKB:
735 		return "skb";
736 	case BPF_DYNPTR_TYPE_XDP:
737 		return "xdp";
738 	case BPF_DYNPTR_TYPE_INVALID:
739 		return "<invalid>";
740 	default:
741 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
742 		return "<unknown>";
743 	}
744 }
745 
746 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
747 {
748 	if (!btf || btf_id == 0)
749 		return "<invalid>";
750 
751 	/* we already validated that type is valid and has conforming name */
752 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
753 }
754 
755 static const char *iter_state_str(enum bpf_iter_state state)
756 {
757 	switch (state) {
758 	case BPF_ITER_STATE_ACTIVE:
759 		return "active";
760 	case BPF_ITER_STATE_DRAINED:
761 		return "drained";
762 	case BPF_ITER_STATE_INVALID:
763 		return "<invalid>";
764 	default:
765 		WARN_ONCE(1, "unknown iter state %d\n", state);
766 		return "<unknown>";
767 	}
768 }
769 
770 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
771 {
772 	env->scratched_regs |= 1U << regno;
773 }
774 
775 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
776 {
777 	env->scratched_stack_slots |= 1ULL << spi;
778 }
779 
780 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
781 {
782 	return (env->scratched_regs >> regno) & 1;
783 }
784 
785 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
786 {
787 	return (env->scratched_stack_slots >> regno) & 1;
788 }
789 
790 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
791 {
792 	return env->scratched_regs || env->scratched_stack_slots;
793 }
794 
795 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
796 {
797 	env->scratched_regs = 0U;
798 	env->scratched_stack_slots = 0ULL;
799 }
800 
801 /* Used for printing the entire verifier state. */
802 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
803 {
804 	env->scratched_regs = ~0U;
805 	env->scratched_stack_slots = ~0ULL;
806 }
807 
808 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
809 {
810 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
811 	case DYNPTR_TYPE_LOCAL:
812 		return BPF_DYNPTR_TYPE_LOCAL;
813 	case DYNPTR_TYPE_RINGBUF:
814 		return BPF_DYNPTR_TYPE_RINGBUF;
815 	case DYNPTR_TYPE_SKB:
816 		return BPF_DYNPTR_TYPE_SKB;
817 	case DYNPTR_TYPE_XDP:
818 		return BPF_DYNPTR_TYPE_XDP;
819 	default:
820 		return BPF_DYNPTR_TYPE_INVALID;
821 	}
822 }
823 
824 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
825 {
826 	switch (type) {
827 	case BPF_DYNPTR_TYPE_LOCAL:
828 		return DYNPTR_TYPE_LOCAL;
829 	case BPF_DYNPTR_TYPE_RINGBUF:
830 		return DYNPTR_TYPE_RINGBUF;
831 	case BPF_DYNPTR_TYPE_SKB:
832 		return DYNPTR_TYPE_SKB;
833 	case BPF_DYNPTR_TYPE_XDP:
834 		return DYNPTR_TYPE_XDP;
835 	default:
836 		return 0;
837 	}
838 }
839 
840 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
841 {
842 	return type == BPF_DYNPTR_TYPE_RINGBUF;
843 }
844 
845 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
846 			      enum bpf_dynptr_type type,
847 			      bool first_slot, int dynptr_id);
848 
849 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
850 				struct bpf_reg_state *reg);
851 
852 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
853 				   struct bpf_reg_state *sreg1,
854 				   struct bpf_reg_state *sreg2,
855 				   enum bpf_dynptr_type type)
856 {
857 	int id = ++env->id_gen;
858 
859 	__mark_dynptr_reg(sreg1, type, true, id);
860 	__mark_dynptr_reg(sreg2, type, false, id);
861 }
862 
863 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
864 			       struct bpf_reg_state *reg,
865 			       enum bpf_dynptr_type type)
866 {
867 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
868 }
869 
870 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
871 				        struct bpf_func_state *state, int spi);
872 
873 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
874 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
875 {
876 	struct bpf_func_state *state = func(env, reg);
877 	enum bpf_dynptr_type type;
878 	int spi, i, err;
879 
880 	spi = dynptr_get_spi(env, reg);
881 	if (spi < 0)
882 		return spi;
883 
884 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
885 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
886 	 * to ensure that for the following example:
887 	 *	[d1][d1][d2][d2]
888 	 * spi    3   2   1   0
889 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
890 	 * case they do belong to same dynptr, second call won't see slot_type
891 	 * as STACK_DYNPTR and will simply skip destruction.
892 	 */
893 	err = destroy_if_dynptr_stack_slot(env, state, spi);
894 	if (err)
895 		return err;
896 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
897 	if (err)
898 		return err;
899 
900 	for (i = 0; i < BPF_REG_SIZE; i++) {
901 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
902 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
903 	}
904 
905 	type = arg_to_dynptr_type(arg_type);
906 	if (type == BPF_DYNPTR_TYPE_INVALID)
907 		return -EINVAL;
908 
909 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
910 			       &state->stack[spi - 1].spilled_ptr, type);
911 
912 	if (dynptr_type_refcounted(type)) {
913 		/* The id is used to track proper releasing */
914 		int id;
915 
916 		if (clone_ref_obj_id)
917 			id = clone_ref_obj_id;
918 		else
919 			id = acquire_reference_state(env, insn_idx);
920 
921 		if (id < 0)
922 			return id;
923 
924 		state->stack[spi].spilled_ptr.ref_obj_id = id;
925 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
926 	}
927 
928 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
929 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
930 
931 	return 0;
932 }
933 
934 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
935 {
936 	int i;
937 
938 	for (i = 0; i < BPF_REG_SIZE; i++) {
939 		state->stack[spi].slot_type[i] = STACK_INVALID;
940 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
941 	}
942 
943 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
944 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
945 
946 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
947 	 *
948 	 * While we don't allow reading STACK_INVALID, it is still possible to
949 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
950 	 * helpers or insns can do partial read of that part without failing,
951 	 * but check_stack_range_initialized, check_stack_read_var_off, and
952 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
953 	 * the slot conservatively. Hence we need to prevent those liveness
954 	 * marking walks.
955 	 *
956 	 * This was not a problem before because STACK_INVALID is only set by
957 	 * default (where the default reg state has its reg->parent as NULL), or
958 	 * in clean_live_states after REG_LIVE_DONE (at which point
959 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
960 	 * verifier state exploration (like we did above). Hence, for our case
961 	 * parentage chain will still be live (i.e. reg->parent may be
962 	 * non-NULL), while earlier reg->parent was NULL, so we need
963 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
964 	 * done later on reads or by mark_dynptr_read as well to unnecessary
965 	 * mark registers in verifier state.
966 	 */
967 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
968 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
969 }
970 
971 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
972 {
973 	struct bpf_func_state *state = func(env, reg);
974 	int spi, ref_obj_id, i;
975 
976 	spi = dynptr_get_spi(env, reg);
977 	if (spi < 0)
978 		return spi;
979 
980 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
981 		invalidate_dynptr(env, state, spi);
982 		return 0;
983 	}
984 
985 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
986 
987 	/* If the dynptr has a ref_obj_id, then we need to invalidate
988 	 * two things:
989 	 *
990 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
991 	 * 2) Any slices derived from this dynptr.
992 	 */
993 
994 	/* Invalidate any slices associated with this dynptr */
995 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
996 
997 	/* Invalidate any dynptr clones */
998 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
999 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1000 			continue;
1001 
1002 		/* it should always be the case that if the ref obj id
1003 		 * matches then the stack slot also belongs to a
1004 		 * dynptr
1005 		 */
1006 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1007 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1008 			return -EFAULT;
1009 		}
1010 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1011 			invalidate_dynptr(env, state, i);
1012 	}
1013 
1014 	return 0;
1015 }
1016 
1017 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1018 			       struct bpf_reg_state *reg);
1019 
1020 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1021 {
1022 	if (!env->allow_ptr_leaks)
1023 		__mark_reg_not_init(env, reg);
1024 	else
1025 		__mark_reg_unknown(env, reg);
1026 }
1027 
1028 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1029 				        struct bpf_func_state *state, int spi)
1030 {
1031 	struct bpf_func_state *fstate;
1032 	struct bpf_reg_state *dreg;
1033 	int i, dynptr_id;
1034 
1035 	/* We always ensure that STACK_DYNPTR is never set partially,
1036 	 * hence just checking for slot_type[0] is enough. This is
1037 	 * different for STACK_SPILL, where it may be only set for
1038 	 * 1 byte, so code has to use is_spilled_reg.
1039 	 */
1040 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1041 		return 0;
1042 
1043 	/* Reposition spi to first slot */
1044 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1045 		spi = spi + 1;
1046 
1047 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1048 		verbose(env, "cannot overwrite referenced dynptr\n");
1049 		return -EINVAL;
1050 	}
1051 
1052 	mark_stack_slot_scratched(env, spi);
1053 	mark_stack_slot_scratched(env, spi - 1);
1054 
1055 	/* Writing partially to one dynptr stack slot destroys both. */
1056 	for (i = 0; i < BPF_REG_SIZE; i++) {
1057 		state->stack[spi].slot_type[i] = STACK_INVALID;
1058 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1059 	}
1060 
1061 	dynptr_id = state->stack[spi].spilled_ptr.id;
1062 	/* Invalidate any slices associated with this dynptr */
1063 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1064 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1065 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1066 			continue;
1067 		if (dreg->dynptr_id == dynptr_id)
1068 			mark_reg_invalid(env, dreg);
1069 	}));
1070 
1071 	/* Do not release reference state, we are destroying dynptr on stack,
1072 	 * not using some helper to release it. Just reset register.
1073 	 */
1074 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1075 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1076 
1077 	/* Same reason as unmark_stack_slots_dynptr above */
1078 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1079 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1080 
1081 	return 0;
1082 }
1083 
1084 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1085 {
1086 	int spi;
1087 
1088 	if (reg->type == CONST_PTR_TO_DYNPTR)
1089 		return false;
1090 
1091 	spi = dynptr_get_spi(env, reg);
1092 
1093 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1094 	 * error because this just means the stack state hasn't been updated yet.
1095 	 * We will do check_mem_access to check and update stack bounds later.
1096 	 */
1097 	if (spi < 0 && spi != -ERANGE)
1098 		return false;
1099 
1100 	/* We don't need to check if the stack slots are marked by previous
1101 	 * dynptr initializations because we allow overwriting existing unreferenced
1102 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1103 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1104 	 * touching are completely destructed before we reinitialize them for a new
1105 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1106 	 * instead of delaying it until the end where the user will get "Unreleased
1107 	 * reference" error.
1108 	 */
1109 	return true;
1110 }
1111 
1112 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1113 {
1114 	struct bpf_func_state *state = func(env, reg);
1115 	int i, spi;
1116 
1117 	/* This already represents first slot of initialized bpf_dynptr.
1118 	 *
1119 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1120 	 * check_func_arg_reg_off's logic, so we don't need to check its
1121 	 * offset and alignment.
1122 	 */
1123 	if (reg->type == CONST_PTR_TO_DYNPTR)
1124 		return true;
1125 
1126 	spi = dynptr_get_spi(env, reg);
1127 	if (spi < 0)
1128 		return false;
1129 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1130 		return false;
1131 
1132 	for (i = 0; i < BPF_REG_SIZE; i++) {
1133 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1134 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1135 			return false;
1136 	}
1137 
1138 	return true;
1139 }
1140 
1141 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1142 				    enum bpf_arg_type arg_type)
1143 {
1144 	struct bpf_func_state *state = func(env, reg);
1145 	enum bpf_dynptr_type dynptr_type;
1146 	int spi;
1147 
1148 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1149 	if (arg_type == ARG_PTR_TO_DYNPTR)
1150 		return true;
1151 
1152 	dynptr_type = arg_to_dynptr_type(arg_type);
1153 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1154 		return reg->dynptr.type == dynptr_type;
1155 	} else {
1156 		spi = dynptr_get_spi(env, reg);
1157 		if (spi < 0)
1158 			return false;
1159 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1160 	}
1161 }
1162 
1163 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1164 
1165 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1166 				 struct bpf_reg_state *reg, int insn_idx,
1167 				 struct btf *btf, u32 btf_id, int nr_slots)
1168 {
1169 	struct bpf_func_state *state = func(env, reg);
1170 	int spi, i, j, id;
1171 
1172 	spi = iter_get_spi(env, reg, nr_slots);
1173 	if (spi < 0)
1174 		return spi;
1175 
1176 	id = acquire_reference_state(env, insn_idx);
1177 	if (id < 0)
1178 		return id;
1179 
1180 	for (i = 0; i < nr_slots; i++) {
1181 		struct bpf_stack_state *slot = &state->stack[spi - i];
1182 		struct bpf_reg_state *st = &slot->spilled_ptr;
1183 
1184 		__mark_reg_known_zero(st);
1185 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1186 		st->live |= REG_LIVE_WRITTEN;
1187 		st->ref_obj_id = i == 0 ? id : 0;
1188 		st->iter.btf = btf;
1189 		st->iter.btf_id = btf_id;
1190 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1191 		st->iter.depth = 0;
1192 
1193 		for (j = 0; j < BPF_REG_SIZE; j++)
1194 			slot->slot_type[j] = STACK_ITER;
1195 
1196 		mark_stack_slot_scratched(env, spi - i);
1197 	}
1198 
1199 	return 0;
1200 }
1201 
1202 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1203 				   struct bpf_reg_state *reg, int nr_slots)
1204 {
1205 	struct bpf_func_state *state = func(env, reg);
1206 	int spi, i, j;
1207 
1208 	spi = iter_get_spi(env, reg, nr_slots);
1209 	if (spi < 0)
1210 		return spi;
1211 
1212 	for (i = 0; i < nr_slots; i++) {
1213 		struct bpf_stack_state *slot = &state->stack[spi - i];
1214 		struct bpf_reg_state *st = &slot->spilled_ptr;
1215 
1216 		if (i == 0)
1217 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1218 
1219 		__mark_reg_not_init(env, st);
1220 
1221 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1222 		st->live |= REG_LIVE_WRITTEN;
1223 
1224 		for (j = 0; j < BPF_REG_SIZE; j++)
1225 			slot->slot_type[j] = STACK_INVALID;
1226 
1227 		mark_stack_slot_scratched(env, spi - i);
1228 	}
1229 
1230 	return 0;
1231 }
1232 
1233 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1234 				     struct bpf_reg_state *reg, int nr_slots)
1235 {
1236 	struct bpf_func_state *state = func(env, reg);
1237 	int spi, i, j;
1238 
1239 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1240 	 * will do check_mem_access to check and update stack bounds later, so
1241 	 * return true for that case.
1242 	 */
1243 	spi = iter_get_spi(env, reg, nr_slots);
1244 	if (spi == -ERANGE)
1245 		return true;
1246 	if (spi < 0)
1247 		return false;
1248 
1249 	for (i = 0; i < nr_slots; i++) {
1250 		struct bpf_stack_state *slot = &state->stack[spi - i];
1251 
1252 		for (j = 0; j < BPF_REG_SIZE; j++)
1253 			if (slot->slot_type[j] == STACK_ITER)
1254 				return false;
1255 	}
1256 
1257 	return true;
1258 }
1259 
1260 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1261 				   struct btf *btf, u32 btf_id, int nr_slots)
1262 {
1263 	struct bpf_func_state *state = func(env, reg);
1264 	int spi, i, j;
1265 
1266 	spi = iter_get_spi(env, reg, nr_slots);
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 		struct bpf_reg_state *st = &slot->spilled_ptr;
1273 
1274 		/* only main (first) slot has ref_obj_id set */
1275 		if (i == 0 && !st->ref_obj_id)
1276 			return false;
1277 		if (i != 0 && st->ref_obj_id)
1278 			return false;
1279 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1280 			return false;
1281 
1282 		for (j = 0; j < BPF_REG_SIZE; j++)
1283 			if (slot->slot_type[j] != STACK_ITER)
1284 				return false;
1285 	}
1286 
1287 	return true;
1288 }
1289 
1290 /* Check if given stack slot is "special":
1291  *   - spilled register state (STACK_SPILL);
1292  *   - dynptr state (STACK_DYNPTR);
1293  *   - iter state (STACK_ITER).
1294  */
1295 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1296 {
1297 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1298 
1299 	switch (type) {
1300 	case STACK_SPILL:
1301 	case STACK_DYNPTR:
1302 	case STACK_ITER:
1303 		return true;
1304 	case STACK_INVALID:
1305 	case STACK_MISC:
1306 	case STACK_ZERO:
1307 		return false;
1308 	default:
1309 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1310 		return true;
1311 	}
1312 }
1313 
1314 /* The reg state of a pointer or a bounded scalar was saved when
1315  * it was spilled to the stack.
1316  */
1317 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1318 {
1319 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1320 }
1321 
1322 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1323 {
1324 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1325 	       stack->spilled_ptr.type == SCALAR_VALUE;
1326 }
1327 
1328 static void scrub_spilled_slot(u8 *stype)
1329 {
1330 	if (*stype != STACK_INVALID)
1331 		*stype = STACK_MISC;
1332 }
1333 
1334 static void print_verifier_state(struct bpf_verifier_env *env,
1335 				 const struct bpf_func_state *state,
1336 				 bool print_all)
1337 {
1338 	const struct bpf_reg_state *reg;
1339 	enum bpf_reg_type t;
1340 	int i;
1341 
1342 	if (state->frameno)
1343 		verbose(env, " frame%d:", state->frameno);
1344 	for (i = 0; i < MAX_BPF_REG; i++) {
1345 		reg = &state->regs[i];
1346 		t = reg->type;
1347 		if (t == NOT_INIT)
1348 			continue;
1349 		if (!print_all && !reg_scratched(env, i))
1350 			continue;
1351 		verbose(env, " R%d", i);
1352 		print_liveness(env, reg->live);
1353 		verbose(env, "=");
1354 		if (t == SCALAR_VALUE && reg->precise)
1355 			verbose(env, "P");
1356 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1357 		    tnum_is_const(reg->var_off)) {
1358 			/* reg->off should be 0 for SCALAR_VALUE */
1359 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1360 			verbose(env, "%lld", reg->var_off.value + reg->off);
1361 		} else {
1362 			const char *sep = "";
1363 
1364 			verbose(env, "%s", reg_type_str(env, t));
1365 			if (base_type(t) == PTR_TO_BTF_ID)
1366 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1367 			verbose(env, "(");
1368 /*
1369  * _a stands for append, was shortened to avoid multiline statements below.
1370  * This macro is used to output a comma separated list of attributes.
1371  */
1372 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1373 
1374 			if (reg->id)
1375 				verbose_a("id=%d", reg->id);
1376 			if (reg->ref_obj_id)
1377 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1378 			if (type_is_non_owning_ref(reg->type))
1379 				verbose_a("%s", "non_own_ref");
1380 			if (t != SCALAR_VALUE)
1381 				verbose_a("off=%d", reg->off);
1382 			if (type_is_pkt_pointer(t))
1383 				verbose_a("r=%d", reg->range);
1384 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1385 				 base_type(t) == PTR_TO_MAP_KEY ||
1386 				 base_type(t) == PTR_TO_MAP_VALUE)
1387 				verbose_a("ks=%d,vs=%d",
1388 					  reg->map_ptr->key_size,
1389 					  reg->map_ptr->value_size);
1390 			if (tnum_is_const(reg->var_off)) {
1391 				/* Typically an immediate SCALAR_VALUE, but
1392 				 * could be a pointer whose offset is too big
1393 				 * for reg->off
1394 				 */
1395 				verbose_a("imm=%llx", reg->var_off.value);
1396 			} else {
1397 				if (reg->smin_value != reg->umin_value &&
1398 				    reg->smin_value != S64_MIN)
1399 					verbose_a("smin=%lld", (long long)reg->smin_value);
1400 				if (reg->smax_value != reg->umax_value &&
1401 				    reg->smax_value != S64_MAX)
1402 					verbose_a("smax=%lld", (long long)reg->smax_value);
1403 				if (reg->umin_value != 0)
1404 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1405 				if (reg->umax_value != U64_MAX)
1406 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1407 				if (!tnum_is_unknown(reg->var_off)) {
1408 					char tn_buf[48];
1409 
1410 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1411 					verbose_a("var_off=%s", tn_buf);
1412 				}
1413 				if (reg->s32_min_value != reg->smin_value &&
1414 				    reg->s32_min_value != S32_MIN)
1415 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1416 				if (reg->s32_max_value != reg->smax_value &&
1417 				    reg->s32_max_value != S32_MAX)
1418 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1419 				if (reg->u32_min_value != reg->umin_value &&
1420 				    reg->u32_min_value != U32_MIN)
1421 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1422 				if (reg->u32_max_value != reg->umax_value &&
1423 				    reg->u32_max_value != U32_MAX)
1424 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1425 			}
1426 #undef verbose_a
1427 
1428 			verbose(env, ")");
1429 		}
1430 	}
1431 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1432 		char types_buf[BPF_REG_SIZE + 1];
1433 		bool valid = false;
1434 		int j;
1435 
1436 		for (j = 0; j < BPF_REG_SIZE; j++) {
1437 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1438 				valid = true;
1439 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1440 		}
1441 		types_buf[BPF_REG_SIZE] = 0;
1442 		if (!valid)
1443 			continue;
1444 		if (!print_all && !stack_slot_scratched(env, i))
1445 			continue;
1446 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1447 		case STACK_SPILL:
1448 			reg = &state->stack[i].spilled_ptr;
1449 			t = reg->type;
1450 
1451 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1452 			print_liveness(env, reg->live);
1453 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1454 			if (t == SCALAR_VALUE && reg->precise)
1455 				verbose(env, "P");
1456 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1457 				verbose(env, "%lld", reg->var_off.value + reg->off);
1458 			break;
1459 		case STACK_DYNPTR:
1460 			i += BPF_DYNPTR_NR_SLOTS - 1;
1461 			reg = &state->stack[i].spilled_ptr;
1462 
1463 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1464 			print_liveness(env, reg->live);
1465 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1466 			if (reg->ref_obj_id)
1467 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1468 			break;
1469 		case STACK_ITER:
1470 			/* only main slot has ref_obj_id set; skip others */
1471 			reg = &state->stack[i].spilled_ptr;
1472 			if (!reg->ref_obj_id)
1473 				continue;
1474 
1475 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1476 			print_liveness(env, reg->live);
1477 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1478 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1479 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1480 				reg->iter.depth);
1481 			break;
1482 		case STACK_MISC:
1483 		case STACK_ZERO:
1484 		default:
1485 			reg = &state->stack[i].spilled_ptr;
1486 
1487 			for (j = 0; j < BPF_REG_SIZE; j++)
1488 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1489 			types_buf[BPF_REG_SIZE] = 0;
1490 
1491 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1492 			print_liveness(env, reg->live);
1493 			verbose(env, "=%s", types_buf);
1494 			break;
1495 		}
1496 	}
1497 	if (state->acquired_refs && state->refs[0].id) {
1498 		verbose(env, " refs=%d", state->refs[0].id);
1499 		for (i = 1; i < state->acquired_refs; i++)
1500 			if (state->refs[i].id)
1501 				verbose(env, ",%d", state->refs[i].id);
1502 	}
1503 	if (state->in_callback_fn)
1504 		verbose(env, " cb");
1505 	if (state->in_async_callback_fn)
1506 		verbose(env, " async_cb");
1507 	verbose(env, "\n");
1508 	mark_verifier_state_clean(env);
1509 }
1510 
1511 static inline u32 vlog_alignment(u32 pos)
1512 {
1513 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1514 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1515 }
1516 
1517 static void print_insn_state(struct bpf_verifier_env *env,
1518 			     const struct bpf_func_state *state)
1519 {
1520 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1521 		/* remove new line character */
1522 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1523 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1524 	} else {
1525 		verbose(env, "%d:", env->insn_idx);
1526 	}
1527 	print_verifier_state(env, state, false);
1528 }
1529 
1530 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1531  * small to hold src. This is different from krealloc since we don't want to preserve
1532  * the contents of dst.
1533  *
1534  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1535  * not be allocated.
1536  */
1537 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1538 {
1539 	size_t alloc_bytes;
1540 	void *orig = dst;
1541 	size_t bytes;
1542 
1543 	if (ZERO_OR_NULL_PTR(src))
1544 		goto out;
1545 
1546 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1547 		return NULL;
1548 
1549 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1550 	dst = krealloc(orig, alloc_bytes, flags);
1551 	if (!dst) {
1552 		kfree(orig);
1553 		return NULL;
1554 	}
1555 
1556 	memcpy(dst, src, bytes);
1557 out:
1558 	return dst ? dst : ZERO_SIZE_PTR;
1559 }
1560 
1561 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1562  * small to hold new_n items. new items are zeroed out if the array grows.
1563  *
1564  * Contrary to krealloc_array, does not free arr if new_n is zero.
1565  */
1566 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1567 {
1568 	size_t alloc_size;
1569 	void *new_arr;
1570 
1571 	if (!new_n || old_n == new_n)
1572 		goto out;
1573 
1574 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1575 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1576 	if (!new_arr) {
1577 		kfree(arr);
1578 		return NULL;
1579 	}
1580 	arr = new_arr;
1581 
1582 	if (new_n > old_n)
1583 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1584 
1585 out:
1586 	return arr ? arr : ZERO_SIZE_PTR;
1587 }
1588 
1589 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1590 {
1591 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1592 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1593 	if (!dst->refs)
1594 		return -ENOMEM;
1595 
1596 	dst->acquired_refs = src->acquired_refs;
1597 	return 0;
1598 }
1599 
1600 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1601 {
1602 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1603 
1604 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1605 				GFP_KERNEL);
1606 	if (!dst->stack)
1607 		return -ENOMEM;
1608 
1609 	dst->allocated_stack = src->allocated_stack;
1610 	return 0;
1611 }
1612 
1613 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1614 {
1615 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1616 				    sizeof(struct bpf_reference_state));
1617 	if (!state->refs)
1618 		return -ENOMEM;
1619 
1620 	state->acquired_refs = n;
1621 	return 0;
1622 }
1623 
1624 static int grow_stack_state(struct bpf_func_state *state, int size)
1625 {
1626 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1627 
1628 	if (old_n >= n)
1629 		return 0;
1630 
1631 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1632 	if (!state->stack)
1633 		return -ENOMEM;
1634 
1635 	state->allocated_stack = size;
1636 	return 0;
1637 }
1638 
1639 /* Acquire a pointer id from the env and update the state->refs to include
1640  * this new pointer reference.
1641  * On success, returns a valid pointer id to associate with the register
1642  * On failure, returns a negative errno.
1643  */
1644 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1645 {
1646 	struct bpf_func_state *state = cur_func(env);
1647 	int new_ofs = state->acquired_refs;
1648 	int id, err;
1649 
1650 	err = resize_reference_state(state, state->acquired_refs + 1);
1651 	if (err)
1652 		return err;
1653 	id = ++env->id_gen;
1654 	state->refs[new_ofs].id = id;
1655 	state->refs[new_ofs].insn_idx = insn_idx;
1656 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1657 
1658 	return id;
1659 }
1660 
1661 /* release function corresponding to acquire_reference_state(). Idempotent. */
1662 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1663 {
1664 	int i, last_idx;
1665 
1666 	last_idx = state->acquired_refs - 1;
1667 	for (i = 0; i < state->acquired_refs; i++) {
1668 		if (state->refs[i].id == ptr_id) {
1669 			/* Cannot release caller references in callbacks */
1670 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1671 				return -EINVAL;
1672 			if (last_idx && i != last_idx)
1673 				memcpy(&state->refs[i], &state->refs[last_idx],
1674 				       sizeof(*state->refs));
1675 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1676 			state->acquired_refs--;
1677 			return 0;
1678 		}
1679 	}
1680 	return -EINVAL;
1681 }
1682 
1683 static void free_func_state(struct bpf_func_state *state)
1684 {
1685 	if (!state)
1686 		return;
1687 	kfree(state->refs);
1688 	kfree(state->stack);
1689 	kfree(state);
1690 }
1691 
1692 static void clear_jmp_history(struct bpf_verifier_state *state)
1693 {
1694 	kfree(state->jmp_history);
1695 	state->jmp_history = NULL;
1696 	state->jmp_history_cnt = 0;
1697 }
1698 
1699 static void free_verifier_state(struct bpf_verifier_state *state,
1700 				bool free_self)
1701 {
1702 	int i;
1703 
1704 	for (i = 0; i <= state->curframe; i++) {
1705 		free_func_state(state->frame[i]);
1706 		state->frame[i] = NULL;
1707 	}
1708 	clear_jmp_history(state);
1709 	if (free_self)
1710 		kfree(state);
1711 }
1712 
1713 /* copy verifier state from src to dst growing dst stack space
1714  * when necessary to accommodate larger src stack
1715  */
1716 static int copy_func_state(struct bpf_func_state *dst,
1717 			   const struct bpf_func_state *src)
1718 {
1719 	int err;
1720 
1721 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1722 	err = copy_reference_state(dst, src);
1723 	if (err)
1724 		return err;
1725 	return copy_stack_state(dst, src);
1726 }
1727 
1728 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1729 			       const struct bpf_verifier_state *src)
1730 {
1731 	struct bpf_func_state *dst;
1732 	int i, err;
1733 
1734 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1735 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1736 					    GFP_USER);
1737 	if (!dst_state->jmp_history)
1738 		return -ENOMEM;
1739 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1740 
1741 	/* if dst has more stack frames then src frame, free them */
1742 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1743 		free_func_state(dst_state->frame[i]);
1744 		dst_state->frame[i] = NULL;
1745 	}
1746 	dst_state->speculative = src->speculative;
1747 	dst_state->active_rcu_lock = src->active_rcu_lock;
1748 	dst_state->curframe = src->curframe;
1749 	dst_state->active_lock.ptr = src->active_lock.ptr;
1750 	dst_state->active_lock.id = src->active_lock.id;
1751 	dst_state->branches = src->branches;
1752 	dst_state->parent = src->parent;
1753 	dst_state->first_insn_idx = src->first_insn_idx;
1754 	dst_state->last_insn_idx = src->last_insn_idx;
1755 	for (i = 0; i <= src->curframe; i++) {
1756 		dst = dst_state->frame[i];
1757 		if (!dst) {
1758 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1759 			if (!dst)
1760 				return -ENOMEM;
1761 			dst_state->frame[i] = dst;
1762 		}
1763 		err = copy_func_state(dst, src->frame[i]);
1764 		if (err)
1765 			return err;
1766 	}
1767 	return 0;
1768 }
1769 
1770 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1771 {
1772 	while (st) {
1773 		u32 br = --st->branches;
1774 
1775 		/* WARN_ON(br > 1) technically makes sense here,
1776 		 * but see comment in push_stack(), hence:
1777 		 */
1778 		WARN_ONCE((int)br < 0,
1779 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1780 			  br);
1781 		if (br)
1782 			break;
1783 		st = st->parent;
1784 	}
1785 }
1786 
1787 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1788 		     int *insn_idx, bool pop_log)
1789 {
1790 	struct bpf_verifier_state *cur = env->cur_state;
1791 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1792 	int err;
1793 
1794 	if (env->head == NULL)
1795 		return -ENOENT;
1796 
1797 	if (cur) {
1798 		err = copy_verifier_state(cur, &head->st);
1799 		if (err)
1800 			return err;
1801 	}
1802 	if (pop_log)
1803 		bpf_vlog_reset(&env->log, head->log_pos);
1804 	if (insn_idx)
1805 		*insn_idx = head->insn_idx;
1806 	if (prev_insn_idx)
1807 		*prev_insn_idx = head->prev_insn_idx;
1808 	elem = head->next;
1809 	free_verifier_state(&head->st, false);
1810 	kfree(head);
1811 	env->head = elem;
1812 	env->stack_size--;
1813 	return 0;
1814 }
1815 
1816 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1817 					     int insn_idx, int prev_insn_idx,
1818 					     bool speculative)
1819 {
1820 	struct bpf_verifier_state *cur = env->cur_state;
1821 	struct bpf_verifier_stack_elem *elem;
1822 	int err;
1823 
1824 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1825 	if (!elem)
1826 		goto err;
1827 
1828 	elem->insn_idx = insn_idx;
1829 	elem->prev_insn_idx = prev_insn_idx;
1830 	elem->next = env->head;
1831 	elem->log_pos = env->log.end_pos;
1832 	env->head = elem;
1833 	env->stack_size++;
1834 	err = copy_verifier_state(&elem->st, cur);
1835 	if (err)
1836 		goto err;
1837 	elem->st.speculative |= speculative;
1838 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1839 		verbose(env, "The sequence of %d jumps is too complex.\n",
1840 			env->stack_size);
1841 		goto err;
1842 	}
1843 	if (elem->st.parent) {
1844 		++elem->st.parent->branches;
1845 		/* WARN_ON(branches > 2) technically makes sense here,
1846 		 * but
1847 		 * 1. speculative states will bump 'branches' for non-branch
1848 		 * instructions
1849 		 * 2. is_state_visited() heuristics may decide not to create
1850 		 * a new state for a sequence of branches and all such current
1851 		 * and cloned states will be pointing to a single parent state
1852 		 * which might have large 'branches' count.
1853 		 */
1854 	}
1855 	return &elem->st;
1856 err:
1857 	free_verifier_state(env->cur_state, true);
1858 	env->cur_state = NULL;
1859 	/* pop all elements and return */
1860 	while (!pop_stack(env, NULL, NULL, false));
1861 	return NULL;
1862 }
1863 
1864 #define CALLER_SAVED_REGS 6
1865 static const int caller_saved[CALLER_SAVED_REGS] = {
1866 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1867 };
1868 
1869 /* This helper doesn't clear reg->id */
1870 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1871 {
1872 	reg->var_off = tnum_const(imm);
1873 	reg->smin_value = (s64)imm;
1874 	reg->smax_value = (s64)imm;
1875 	reg->umin_value = imm;
1876 	reg->umax_value = imm;
1877 
1878 	reg->s32_min_value = (s32)imm;
1879 	reg->s32_max_value = (s32)imm;
1880 	reg->u32_min_value = (u32)imm;
1881 	reg->u32_max_value = (u32)imm;
1882 }
1883 
1884 /* Mark the unknown part of a register (variable offset or scalar value) as
1885  * known to have the value @imm.
1886  */
1887 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1888 {
1889 	/* Clear off and union(map_ptr, range) */
1890 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1891 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1892 	reg->id = 0;
1893 	reg->ref_obj_id = 0;
1894 	___mark_reg_known(reg, imm);
1895 }
1896 
1897 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1898 {
1899 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1900 	reg->s32_min_value = (s32)imm;
1901 	reg->s32_max_value = (s32)imm;
1902 	reg->u32_min_value = (u32)imm;
1903 	reg->u32_max_value = (u32)imm;
1904 }
1905 
1906 /* Mark the 'variable offset' part of a register as zero.  This should be
1907  * used only on registers holding a pointer type.
1908  */
1909 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1910 {
1911 	__mark_reg_known(reg, 0);
1912 }
1913 
1914 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1915 {
1916 	__mark_reg_known(reg, 0);
1917 	reg->type = SCALAR_VALUE;
1918 }
1919 
1920 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1921 				struct bpf_reg_state *regs, u32 regno)
1922 {
1923 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1924 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1925 		/* Something bad happened, let's kill all regs */
1926 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1927 			__mark_reg_not_init(env, regs + regno);
1928 		return;
1929 	}
1930 	__mark_reg_known_zero(regs + regno);
1931 }
1932 
1933 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1934 			      bool first_slot, int dynptr_id)
1935 {
1936 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1937 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1938 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1939 	 */
1940 	__mark_reg_known_zero(reg);
1941 	reg->type = CONST_PTR_TO_DYNPTR;
1942 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1943 	reg->id = dynptr_id;
1944 	reg->dynptr.type = type;
1945 	reg->dynptr.first_slot = first_slot;
1946 }
1947 
1948 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1949 {
1950 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1951 		const struct bpf_map *map = reg->map_ptr;
1952 
1953 		if (map->inner_map_meta) {
1954 			reg->type = CONST_PTR_TO_MAP;
1955 			reg->map_ptr = map->inner_map_meta;
1956 			/* transfer reg's id which is unique for every map_lookup_elem
1957 			 * as UID of the inner map.
1958 			 */
1959 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1960 				reg->map_uid = reg->id;
1961 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1962 			reg->type = PTR_TO_XDP_SOCK;
1963 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1964 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1965 			reg->type = PTR_TO_SOCKET;
1966 		} else {
1967 			reg->type = PTR_TO_MAP_VALUE;
1968 		}
1969 		return;
1970 	}
1971 
1972 	reg->type &= ~PTR_MAYBE_NULL;
1973 }
1974 
1975 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1976 				struct btf_field_graph_root *ds_head)
1977 {
1978 	__mark_reg_known_zero(&regs[regno]);
1979 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1980 	regs[regno].btf = ds_head->btf;
1981 	regs[regno].btf_id = ds_head->value_btf_id;
1982 	regs[regno].off = ds_head->node_offset;
1983 }
1984 
1985 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1986 {
1987 	return type_is_pkt_pointer(reg->type);
1988 }
1989 
1990 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1991 {
1992 	return reg_is_pkt_pointer(reg) ||
1993 	       reg->type == PTR_TO_PACKET_END;
1994 }
1995 
1996 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1997 {
1998 	return base_type(reg->type) == PTR_TO_MEM &&
1999 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2000 }
2001 
2002 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2003 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2004 				    enum bpf_reg_type which)
2005 {
2006 	/* The register can already have a range from prior markings.
2007 	 * This is fine as long as it hasn't been advanced from its
2008 	 * origin.
2009 	 */
2010 	return reg->type == which &&
2011 	       reg->id == 0 &&
2012 	       reg->off == 0 &&
2013 	       tnum_equals_const(reg->var_off, 0);
2014 }
2015 
2016 /* Reset the min/max bounds of a register */
2017 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2018 {
2019 	reg->smin_value = S64_MIN;
2020 	reg->smax_value = S64_MAX;
2021 	reg->umin_value = 0;
2022 	reg->umax_value = U64_MAX;
2023 
2024 	reg->s32_min_value = S32_MIN;
2025 	reg->s32_max_value = S32_MAX;
2026 	reg->u32_min_value = 0;
2027 	reg->u32_max_value = U32_MAX;
2028 }
2029 
2030 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2031 {
2032 	reg->smin_value = S64_MIN;
2033 	reg->smax_value = S64_MAX;
2034 	reg->umin_value = 0;
2035 	reg->umax_value = U64_MAX;
2036 }
2037 
2038 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2039 {
2040 	reg->s32_min_value = S32_MIN;
2041 	reg->s32_max_value = S32_MAX;
2042 	reg->u32_min_value = 0;
2043 	reg->u32_max_value = U32_MAX;
2044 }
2045 
2046 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2047 {
2048 	struct tnum var32_off = tnum_subreg(reg->var_off);
2049 
2050 	/* min signed is max(sign bit) | min(other bits) */
2051 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2052 			var32_off.value | (var32_off.mask & S32_MIN));
2053 	/* max signed is min(sign bit) | max(other bits) */
2054 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2055 			var32_off.value | (var32_off.mask & S32_MAX));
2056 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2057 	reg->u32_max_value = min(reg->u32_max_value,
2058 				 (u32)(var32_off.value | var32_off.mask));
2059 }
2060 
2061 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2062 {
2063 	/* min signed is max(sign bit) | min(other bits) */
2064 	reg->smin_value = max_t(s64, reg->smin_value,
2065 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2066 	/* max signed is min(sign bit) | max(other bits) */
2067 	reg->smax_value = min_t(s64, reg->smax_value,
2068 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2069 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2070 	reg->umax_value = min(reg->umax_value,
2071 			      reg->var_off.value | reg->var_off.mask);
2072 }
2073 
2074 static void __update_reg_bounds(struct bpf_reg_state *reg)
2075 {
2076 	__update_reg32_bounds(reg);
2077 	__update_reg64_bounds(reg);
2078 }
2079 
2080 /* Uses signed min/max values to inform unsigned, and vice-versa */
2081 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2082 {
2083 	/* Learn sign from signed bounds.
2084 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2085 	 * are the same, so combine.  This works even in the negative case, e.g.
2086 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2087 	 */
2088 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2089 		reg->s32_min_value = reg->u32_min_value =
2090 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2091 		reg->s32_max_value = reg->u32_max_value =
2092 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2093 		return;
2094 	}
2095 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2096 	 * boundary, so we must be careful.
2097 	 */
2098 	if ((s32)reg->u32_max_value >= 0) {
2099 		/* Positive.  We can't learn anything from the smin, but smax
2100 		 * is positive, hence safe.
2101 		 */
2102 		reg->s32_min_value = reg->u32_min_value;
2103 		reg->s32_max_value = reg->u32_max_value =
2104 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2105 	} else if ((s32)reg->u32_min_value < 0) {
2106 		/* Negative.  We can't learn anything from the smax, but smin
2107 		 * is negative, hence safe.
2108 		 */
2109 		reg->s32_min_value = reg->u32_min_value =
2110 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2111 		reg->s32_max_value = reg->u32_max_value;
2112 	}
2113 }
2114 
2115 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2116 {
2117 	/* Learn sign from signed bounds.
2118 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2119 	 * are the same, so combine.  This works even in the negative case, e.g.
2120 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2121 	 */
2122 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2123 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2124 							  reg->umin_value);
2125 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2126 							  reg->umax_value);
2127 		return;
2128 	}
2129 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2130 	 * boundary, so we must be careful.
2131 	 */
2132 	if ((s64)reg->umax_value >= 0) {
2133 		/* Positive.  We can't learn anything from the smin, but smax
2134 		 * is positive, hence safe.
2135 		 */
2136 		reg->smin_value = reg->umin_value;
2137 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2138 							  reg->umax_value);
2139 	} else if ((s64)reg->umin_value < 0) {
2140 		/* Negative.  We can't learn anything from the smax, but smin
2141 		 * is negative, hence safe.
2142 		 */
2143 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2144 							  reg->umin_value);
2145 		reg->smax_value = reg->umax_value;
2146 	}
2147 }
2148 
2149 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2150 {
2151 	__reg32_deduce_bounds(reg);
2152 	__reg64_deduce_bounds(reg);
2153 }
2154 
2155 /* Attempts to improve var_off based on unsigned min/max information */
2156 static void __reg_bound_offset(struct bpf_reg_state *reg)
2157 {
2158 	struct tnum var64_off = tnum_intersect(reg->var_off,
2159 					       tnum_range(reg->umin_value,
2160 							  reg->umax_value));
2161 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2162 					       tnum_range(reg->u32_min_value,
2163 							  reg->u32_max_value));
2164 
2165 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2166 }
2167 
2168 static void reg_bounds_sync(struct bpf_reg_state *reg)
2169 {
2170 	/* We might have learned new bounds from the var_off. */
2171 	__update_reg_bounds(reg);
2172 	/* We might have learned something about the sign bit. */
2173 	__reg_deduce_bounds(reg);
2174 	/* We might have learned some bits from the bounds. */
2175 	__reg_bound_offset(reg);
2176 	/* Intersecting with the old var_off might have improved our bounds
2177 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2178 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2179 	 */
2180 	__update_reg_bounds(reg);
2181 }
2182 
2183 static bool __reg32_bound_s64(s32 a)
2184 {
2185 	return a >= 0 && a <= S32_MAX;
2186 }
2187 
2188 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2189 {
2190 	reg->umin_value = reg->u32_min_value;
2191 	reg->umax_value = reg->u32_max_value;
2192 
2193 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2194 	 * be positive otherwise set to worse case bounds and refine later
2195 	 * from tnum.
2196 	 */
2197 	if (__reg32_bound_s64(reg->s32_min_value) &&
2198 	    __reg32_bound_s64(reg->s32_max_value)) {
2199 		reg->smin_value = reg->s32_min_value;
2200 		reg->smax_value = reg->s32_max_value;
2201 	} else {
2202 		reg->smin_value = 0;
2203 		reg->smax_value = U32_MAX;
2204 	}
2205 }
2206 
2207 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2208 {
2209 	/* special case when 64-bit register has upper 32-bit register
2210 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2211 	 * allowing us to use 32-bit bounds directly,
2212 	 */
2213 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2214 		__reg_assign_32_into_64(reg);
2215 	} else {
2216 		/* Otherwise the best we can do is push lower 32bit known and
2217 		 * unknown bits into register (var_off set from jmp logic)
2218 		 * then learn as much as possible from the 64-bit tnum
2219 		 * known and unknown bits. The previous smin/smax bounds are
2220 		 * invalid here because of jmp32 compare so mark them unknown
2221 		 * so they do not impact tnum bounds calculation.
2222 		 */
2223 		__mark_reg64_unbounded(reg);
2224 	}
2225 	reg_bounds_sync(reg);
2226 }
2227 
2228 static bool __reg64_bound_s32(s64 a)
2229 {
2230 	return a >= S32_MIN && a <= S32_MAX;
2231 }
2232 
2233 static bool __reg64_bound_u32(u64 a)
2234 {
2235 	return a >= U32_MIN && a <= U32_MAX;
2236 }
2237 
2238 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2239 {
2240 	__mark_reg32_unbounded(reg);
2241 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2242 		reg->s32_min_value = (s32)reg->smin_value;
2243 		reg->s32_max_value = (s32)reg->smax_value;
2244 	}
2245 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2246 		reg->u32_min_value = (u32)reg->umin_value;
2247 		reg->u32_max_value = (u32)reg->umax_value;
2248 	}
2249 	reg_bounds_sync(reg);
2250 }
2251 
2252 /* Mark a register as having a completely unknown (scalar) value. */
2253 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2254 			       struct bpf_reg_state *reg)
2255 {
2256 	/*
2257 	 * Clear type, off, and union(map_ptr, range) and
2258 	 * padding between 'type' and union
2259 	 */
2260 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2261 	reg->type = SCALAR_VALUE;
2262 	reg->id = 0;
2263 	reg->ref_obj_id = 0;
2264 	reg->var_off = tnum_unknown;
2265 	reg->frameno = 0;
2266 	reg->precise = !env->bpf_capable;
2267 	__mark_reg_unbounded(reg);
2268 }
2269 
2270 static void mark_reg_unknown(struct bpf_verifier_env *env,
2271 			     struct bpf_reg_state *regs, u32 regno)
2272 {
2273 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2274 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2275 		/* Something bad happened, let's kill all regs except FP */
2276 		for (regno = 0; regno < BPF_REG_FP; regno++)
2277 			__mark_reg_not_init(env, regs + regno);
2278 		return;
2279 	}
2280 	__mark_reg_unknown(env, regs + regno);
2281 }
2282 
2283 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2284 				struct bpf_reg_state *reg)
2285 {
2286 	__mark_reg_unknown(env, reg);
2287 	reg->type = NOT_INIT;
2288 }
2289 
2290 static void mark_reg_not_init(struct bpf_verifier_env *env,
2291 			      struct bpf_reg_state *regs, u32 regno)
2292 {
2293 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2294 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2295 		/* Something bad happened, let's kill all regs except FP */
2296 		for (regno = 0; regno < BPF_REG_FP; regno++)
2297 			__mark_reg_not_init(env, regs + regno);
2298 		return;
2299 	}
2300 	__mark_reg_not_init(env, regs + regno);
2301 }
2302 
2303 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2304 			    struct bpf_reg_state *regs, u32 regno,
2305 			    enum bpf_reg_type reg_type,
2306 			    struct btf *btf, u32 btf_id,
2307 			    enum bpf_type_flag flag)
2308 {
2309 	if (reg_type == SCALAR_VALUE) {
2310 		mark_reg_unknown(env, regs, regno);
2311 		return;
2312 	}
2313 	mark_reg_known_zero(env, regs, regno);
2314 	regs[regno].type = PTR_TO_BTF_ID | flag;
2315 	regs[regno].btf = btf;
2316 	regs[regno].btf_id = btf_id;
2317 }
2318 
2319 #define DEF_NOT_SUBREG	(0)
2320 static void init_reg_state(struct bpf_verifier_env *env,
2321 			   struct bpf_func_state *state)
2322 {
2323 	struct bpf_reg_state *regs = state->regs;
2324 	int i;
2325 
2326 	for (i = 0; i < MAX_BPF_REG; i++) {
2327 		mark_reg_not_init(env, regs, i);
2328 		regs[i].live = REG_LIVE_NONE;
2329 		regs[i].parent = NULL;
2330 		regs[i].subreg_def = DEF_NOT_SUBREG;
2331 	}
2332 
2333 	/* frame pointer */
2334 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2335 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2336 	regs[BPF_REG_FP].frameno = state->frameno;
2337 }
2338 
2339 #define BPF_MAIN_FUNC (-1)
2340 static void init_func_state(struct bpf_verifier_env *env,
2341 			    struct bpf_func_state *state,
2342 			    int callsite, int frameno, int subprogno)
2343 {
2344 	state->callsite = callsite;
2345 	state->frameno = frameno;
2346 	state->subprogno = subprogno;
2347 	state->callback_ret_range = tnum_range(0, 0);
2348 	init_reg_state(env, state);
2349 	mark_verifier_state_scratched(env);
2350 }
2351 
2352 /* Similar to push_stack(), but for async callbacks */
2353 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2354 						int insn_idx, int prev_insn_idx,
2355 						int subprog)
2356 {
2357 	struct bpf_verifier_stack_elem *elem;
2358 	struct bpf_func_state *frame;
2359 
2360 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2361 	if (!elem)
2362 		goto err;
2363 
2364 	elem->insn_idx = insn_idx;
2365 	elem->prev_insn_idx = prev_insn_idx;
2366 	elem->next = env->head;
2367 	elem->log_pos = env->log.end_pos;
2368 	env->head = elem;
2369 	env->stack_size++;
2370 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2371 		verbose(env,
2372 			"The sequence of %d jumps is too complex for async cb.\n",
2373 			env->stack_size);
2374 		goto err;
2375 	}
2376 	/* Unlike push_stack() do not copy_verifier_state().
2377 	 * The caller state doesn't matter.
2378 	 * This is async callback. It starts in a fresh stack.
2379 	 * Initialize it similar to do_check_common().
2380 	 */
2381 	elem->st.branches = 1;
2382 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2383 	if (!frame)
2384 		goto err;
2385 	init_func_state(env, frame,
2386 			BPF_MAIN_FUNC /* callsite */,
2387 			0 /* frameno within this callchain */,
2388 			subprog /* subprog number within this prog */);
2389 	elem->st.frame[0] = frame;
2390 	return &elem->st;
2391 err:
2392 	free_verifier_state(env->cur_state, true);
2393 	env->cur_state = NULL;
2394 	/* pop all elements and return */
2395 	while (!pop_stack(env, NULL, NULL, false));
2396 	return NULL;
2397 }
2398 
2399 
2400 enum reg_arg_type {
2401 	SRC_OP,		/* register is used as source operand */
2402 	DST_OP,		/* register is used as destination operand */
2403 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2404 };
2405 
2406 static int cmp_subprogs(const void *a, const void *b)
2407 {
2408 	return ((struct bpf_subprog_info *)a)->start -
2409 	       ((struct bpf_subprog_info *)b)->start;
2410 }
2411 
2412 static int find_subprog(struct bpf_verifier_env *env, int off)
2413 {
2414 	struct bpf_subprog_info *p;
2415 
2416 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2417 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2418 	if (!p)
2419 		return -ENOENT;
2420 	return p - env->subprog_info;
2421 
2422 }
2423 
2424 static int add_subprog(struct bpf_verifier_env *env, int off)
2425 {
2426 	int insn_cnt = env->prog->len;
2427 	int ret;
2428 
2429 	if (off >= insn_cnt || off < 0) {
2430 		verbose(env, "call to invalid destination\n");
2431 		return -EINVAL;
2432 	}
2433 	ret = find_subprog(env, off);
2434 	if (ret >= 0)
2435 		return ret;
2436 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2437 		verbose(env, "too many subprograms\n");
2438 		return -E2BIG;
2439 	}
2440 	/* determine subprog starts. The end is one before the next starts */
2441 	env->subprog_info[env->subprog_cnt++].start = off;
2442 	sort(env->subprog_info, env->subprog_cnt,
2443 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2444 	return env->subprog_cnt - 1;
2445 }
2446 
2447 #define MAX_KFUNC_DESCS 256
2448 #define MAX_KFUNC_BTFS	256
2449 
2450 struct bpf_kfunc_desc {
2451 	struct btf_func_model func_model;
2452 	u32 func_id;
2453 	s32 imm;
2454 	u16 offset;
2455 	unsigned long addr;
2456 };
2457 
2458 struct bpf_kfunc_btf {
2459 	struct btf *btf;
2460 	struct module *module;
2461 	u16 offset;
2462 };
2463 
2464 struct bpf_kfunc_desc_tab {
2465 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2466 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2467 	 * available, therefore at the end of verification do_misc_fixups()
2468 	 * sorts this by imm and offset.
2469 	 */
2470 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2471 	u32 nr_descs;
2472 };
2473 
2474 struct bpf_kfunc_btf_tab {
2475 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2476 	u32 nr_descs;
2477 };
2478 
2479 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2480 {
2481 	const struct bpf_kfunc_desc *d0 = a;
2482 	const struct bpf_kfunc_desc *d1 = b;
2483 
2484 	/* func_id is not greater than BTF_MAX_TYPE */
2485 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2486 }
2487 
2488 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2489 {
2490 	const struct bpf_kfunc_btf *d0 = a;
2491 	const struct bpf_kfunc_btf *d1 = b;
2492 
2493 	return d0->offset - d1->offset;
2494 }
2495 
2496 static const struct bpf_kfunc_desc *
2497 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2498 {
2499 	struct bpf_kfunc_desc desc = {
2500 		.func_id = func_id,
2501 		.offset = offset,
2502 	};
2503 	struct bpf_kfunc_desc_tab *tab;
2504 
2505 	tab = prog->aux->kfunc_tab;
2506 	return bsearch(&desc, tab->descs, tab->nr_descs,
2507 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2508 }
2509 
2510 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2511 		       u16 btf_fd_idx, u8 **func_addr)
2512 {
2513 	const struct bpf_kfunc_desc *desc;
2514 
2515 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2516 	if (!desc)
2517 		return -EFAULT;
2518 
2519 	*func_addr = (u8 *)desc->addr;
2520 	return 0;
2521 }
2522 
2523 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2524 					 s16 offset)
2525 {
2526 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2527 	struct bpf_kfunc_btf_tab *tab;
2528 	struct bpf_kfunc_btf *b;
2529 	struct module *mod;
2530 	struct btf *btf;
2531 	int btf_fd;
2532 
2533 	tab = env->prog->aux->kfunc_btf_tab;
2534 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2535 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2536 	if (!b) {
2537 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2538 			verbose(env, "too many different module BTFs\n");
2539 			return ERR_PTR(-E2BIG);
2540 		}
2541 
2542 		if (bpfptr_is_null(env->fd_array)) {
2543 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2544 			return ERR_PTR(-EPROTO);
2545 		}
2546 
2547 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2548 					    offset * sizeof(btf_fd),
2549 					    sizeof(btf_fd)))
2550 			return ERR_PTR(-EFAULT);
2551 
2552 		btf = btf_get_by_fd(btf_fd);
2553 		if (IS_ERR(btf)) {
2554 			verbose(env, "invalid module BTF fd specified\n");
2555 			return btf;
2556 		}
2557 
2558 		if (!btf_is_module(btf)) {
2559 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2560 			btf_put(btf);
2561 			return ERR_PTR(-EINVAL);
2562 		}
2563 
2564 		mod = btf_try_get_module(btf);
2565 		if (!mod) {
2566 			btf_put(btf);
2567 			return ERR_PTR(-ENXIO);
2568 		}
2569 
2570 		b = &tab->descs[tab->nr_descs++];
2571 		b->btf = btf;
2572 		b->module = mod;
2573 		b->offset = offset;
2574 
2575 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2576 		     kfunc_btf_cmp_by_off, NULL);
2577 	}
2578 	return b->btf;
2579 }
2580 
2581 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2582 {
2583 	if (!tab)
2584 		return;
2585 
2586 	while (tab->nr_descs--) {
2587 		module_put(tab->descs[tab->nr_descs].module);
2588 		btf_put(tab->descs[tab->nr_descs].btf);
2589 	}
2590 	kfree(tab);
2591 }
2592 
2593 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2594 {
2595 	if (offset) {
2596 		if (offset < 0) {
2597 			/* In the future, this can be allowed to increase limit
2598 			 * of fd index into fd_array, interpreted as u16.
2599 			 */
2600 			verbose(env, "negative offset disallowed for kernel module function call\n");
2601 			return ERR_PTR(-EINVAL);
2602 		}
2603 
2604 		return __find_kfunc_desc_btf(env, offset);
2605 	}
2606 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2607 }
2608 
2609 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2610 {
2611 	const struct btf_type *func, *func_proto;
2612 	struct bpf_kfunc_btf_tab *btf_tab;
2613 	struct bpf_kfunc_desc_tab *tab;
2614 	struct bpf_prog_aux *prog_aux;
2615 	struct bpf_kfunc_desc *desc;
2616 	const char *func_name;
2617 	struct btf *desc_btf;
2618 	unsigned long call_imm;
2619 	unsigned long addr;
2620 	int err;
2621 
2622 	prog_aux = env->prog->aux;
2623 	tab = prog_aux->kfunc_tab;
2624 	btf_tab = prog_aux->kfunc_btf_tab;
2625 	if (!tab) {
2626 		if (!btf_vmlinux) {
2627 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2628 			return -ENOTSUPP;
2629 		}
2630 
2631 		if (!env->prog->jit_requested) {
2632 			verbose(env, "JIT is required for calling kernel function\n");
2633 			return -ENOTSUPP;
2634 		}
2635 
2636 		if (!bpf_jit_supports_kfunc_call()) {
2637 			verbose(env, "JIT does not support calling kernel function\n");
2638 			return -ENOTSUPP;
2639 		}
2640 
2641 		if (!env->prog->gpl_compatible) {
2642 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2643 			return -EINVAL;
2644 		}
2645 
2646 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2647 		if (!tab)
2648 			return -ENOMEM;
2649 		prog_aux->kfunc_tab = tab;
2650 	}
2651 
2652 	/* func_id == 0 is always invalid, but instead of returning an error, be
2653 	 * conservative and wait until the code elimination pass before returning
2654 	 * error, so that invalid calls that get pruned out can be in BPF programs
2655 	 * loaded from userspace.  It is also required that offset be untouched
2656 	 * for such calls.
2657 	 */
2658 	if (!func_id && !offset)
2659 		return 0;
2660 
2661 	if (!btf_tab && offset) {
2662 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2663 		if (!btf_tab)
2664 			return -ENOMEM;
2665 		prog_aux->kfunc_btf_tab = btf_tab;
2666 	}
2667 
2668 	desc_btf = find_kfunc_desc_btf(env, offset);
2669 	if (IS_ERR(desc_btf)) {
2670 		verbose(env, "failed to find BTF for kernel function\n");
2671 		return PTR_ERR(desc_btf);
2672 	}
2673 
2674 	if (find_kfunc_desc(env->prog, func_id, offset))
2675 		return 0;
2676 
2677 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2678 		verbose(env, "too many different kernel function calls\n");
2679 		return -E2BIG;
2680 	}
2681 
2682 	func = btf_type_by_id(desc_btf, func_id);
2683 	if (!func || !btf_type_is_func(func)) {
2684 		verbose(env, "kernel btf_id %u is not a function\n",
2685 			func_id);
2686 		return -EINVAL;
2687 	}
2688 	func_proto = btf_type_by_id(desc_btf, func->type);
2689 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2690 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2691 			func_id);
2692 		return -EINVAL;
2693 	}
2694 
2695 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2696 	addr = kallsyms_lookup_name(func_name);
2697 	if (!addr) {
2698 		verbose(env, "cannot find address for kernel function %s\n",
2699 			func_name);
2700 		return -EINVAL;
2701 	}
2702 	specialize_kfunc(env, func_id, offset, &addr);
2703 
2704 	if (bpf_jit_supports_far_kfunc_call()) {
2705 		call_imm = func_id;
2706 	} else {
2707 		call_imm = BPF_CALL_IMM(addr);
2708 		/* Check whether the relative offset overflows desc->imm */
2709 		if ((unsigned long)(s32)call_imm != call_imm) {
2710 			verbose(env, "address of kernel function %s is out of range\n",
2711 				func_name);
2712 			return -EINVAL;
2713 		}
2714 	}
2715 
2716 	if (bpf_dev_bound_kfunc_id(func_id)) {
2717 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2718 		if (err)
2719 			return err;
2720 	}
2721 
2722 	desc = &tab->descs[tab->nr_descs++];
2723 	desc->func_id = func_id;
2724 	desc->imm = call_imm;
2725 	desc->offset = offset;
2726 	desc->addr = addr;
2727 	err = btf_distill_func_proto(&env->log, desc_btf,
2728 				     func_proto, func_name,
2729 				     &desc->func_model);
2730 	if (!err)
2731 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2732 		     kfunc_desc_cmp_by_id_off, NULL);
2733 	return err;
2734 }
2735 
2736 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2737 {
2738 	const struct bpf_kfunc_desc *d0 = a;
2739 	const struct bpf_kfunc_desc *d1 = b;
2740 
2741 	if (d0->imm != d1->imm)
2742 		return d0->imm < d1->imm ? -1 : 1;
2743 	if (d0->offset != d1->offset)
2744 		return d0->offset < d1->offset ? -1 : 1;
2745 	return 0;
2746 }
2747 
2748 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2749 {
2750 	struct bpf_kfunc_desc_tab *tab;
2751 
2752 	tab = prog->aux->kfunc_tab;
2753 	if (!tab)
2754 		return;
2755 
2756 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2757 	     kfunc_desc_cmp_by_imm_off, NULL);
2758 }
2759 
2760 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2761 {
2762 	return !!prog->aux->kfunc_tab;
2763 }
2764 
2765 const struct btf_func_model *
2766 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2767 			 const struct bpf_insn *insn)
2768 {
2769 	const struct bpf_kfunc_desc desc = {
2770 		.imm = insn->imm,
2771 		.offset = insn->off,
2772 	};
2773 	const struct bpf_kfunc_desc *res;
2774 	struct bpf_kfunc_desc_tab *tab;
2775 
2776 	tab = prog->aux->kfunc_tab;
2777 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2778 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2779 
2780 	return res ? &res->func_model : NULL;
2781 }
2782 
2783 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2784 {
2785 	struct bpf_subprog_info *subprog = env->subprog_info;
2786 	struct bpf_insn *insn = env->prog->insnsi;
2787 	int i, ret, insn_cnt = env->prog->len;
2788 
2789 	/* Add entry function. */
2790 	ret = add_subprog(env, 0);
2791 	if (ret)
2792 		return ret;
2793 
2794 	for (i = 0; i < insn_cnt; i++, insn++) {
2795 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2796 		    !bpf_pseudo_kfunc_call(insn))
2797 			continue;
2798 
2799 		if (!env->bpf_capable) {
2800 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2801 			return -EPERM;
2802 		}
2803 
2804 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2805 			ret = add_subprog(env, i + insn->imm + 1);
2806 		else
2807 			ret = add_kfunc_call(env, insn->imm, insn->off);
2808 
2809 		if (ret < 0)
2810 			return ret;
2811 	}
2812 
2813 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2814 	 * logic. 'subprog_cnt' should not be increased.
2815 	 */
2816 	subprog[env->subprog_cnt].start = insn_cnt;
2817 
2818 	if (env->log.level & BPF_LOG_LEVEL2)
2819 		for (i = 0; i < env->subprog_cnt; i++)
2820 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2821 
2822 	return 0;
2823 }
2824 
2825 static int check_subprogs(struct bpf_verifier_env *env)
2826 {
2827 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2828 	struct bpf_subprog_info *subprog = env->subprog_info;
2829 	struct bpf_insn *insn = env->prog->insnsi;
2830 	int insn_cnt = env->prog->len;
2831 
2832 	/* now check that all jumps are within the same subprog */
2833 	subprog_start = subprog[cur_subprog].start;
2834 	subprog_end = subprog[cur_subprog + 1].start;
2835 	for (i = 0; i < insn_cnt; i++) {
2836 		u8 code = insn[i].code;
2837 
2838 		if (code == (BPF_JMP | BPF_CALL) &&
2839 		    insn[i].src_reg == 0 &&
2840 		    insn[i].imm == BPF_FUNC_tail_call)
2841 			subprog[cur_subprog].has_tail_call = true;
2842 		if (BPF_CLASS(code) == BPF_LD &&
2843 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2844 			subprog[cur_subprog].has_ld_abs = true;
2845 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2846 			goto next;
2847 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2848 			goto next;
2849 		off = i + insn[i].off + 1;
2850 		if (off < subprog_start || off >= subprog_end) {
2851 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2852 			return -EINVAL;
2853 		}
2854 next:
2855 		if (i == subprog_end - 1) {
2856 			/* to avoid fall-through from one subprog into another
2857 			 * the last insn of the subprog should be either exit
2858 			 * or unconditional jump back
2859 			 */
2860 			if (code != (BPF_JMP | BPF_EXIT) &&
2861 			    code != (BPF_JMP | BPF_JA)) {
2862 				verbose(env, "last insn is not an exit or jmp\n");
2863 				return -EINVAL;
2864 			}
2865 			subprog_start = subprog_end;
2866 			cur_subprog++;
2867 			if (cur_subprog < env->subprog_cnt)
2868 				subprog_end = subprog[cur_subprog + 1].start;
2869 		}
2870 	}
2871 	return 0;
2872 }
2873 
2874 /* Parentage chain of this register (or stack slot) should take care of all
2875  * issues like callee-saved registers, stack slot allocation time, etc.
2876  */
2877 static int mark_reg_read(struct bpf_verifier_env *env,
2878 			 const struct bpf_reg_state *state,
2879 			 struct bpf_reg_state *parent, u8 flag)
2880 {
2881 	bool writes = parent == state->parent; /* Observe write marks */
2882 	int cnt = 0;
2883 
2884 	while (parent) {
2885 		/* if read wasn't screened by an earlier write ... */
2886 		if (writes && state->live & REG_LIVE_WRITTEN)
2887 			break;
2888 		if (parent->live & REG_LIVE_DONE) {
2889 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2890 				reg_type_str(env, parent->type),
2891 				parent->var_off.value, parent->off);
2892 			return -EFAULT;
2893 		}
2894 		/* The first condition is more likely to be true than the
2895 		 * second, checked it first.
2896 		 */
2897 		if ((parent->live & REG_LIVE_READ) == flag ||
2898 		    parent->live & REG_LIVE_READ64)
2899 			/* The parentage chain never changes and
2900 			 * this parent was already marked as LIVE_READ.
2901 			 * There is no need to keep walking the chain again and
2902 			 * keep re-marking all parents as LIVE_READ.
2903 			 * This case happens when the same register is read
2904 			 * multiple times without writes into it in-between.
2905 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2906 			 * then no need to set the weak REG_LIVE_READ32.
2907 			 */
2908 			break;
2909 		/* ... then we depend on parent's value */
2910 		parent->live |= flag;
2911 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2912 		if (flag == REG_LIVE_READ64)
2913 			parent->live &= ~REG_LIVE_READ32;
2914 		state = parent;
2915 		parent = state->parent;
2916 		writes = true;
2917 		cnt++;
2918 	}
2919 
2920 	if (env->longest_mark_read_walk < cnt)
2921 		env->longest_mark_read_walk = cnt;
2922 	return 0;
2923 }
2924 
2925 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2926 {
2927 	struct bpf_func_state *state = func(env, reg);
2928 	int spi, ret;
2929 
2930 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2931 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2932 	 * check_kfunc_call.
2933 	 */
2934 	if (reg->type == CONST_PTR_TO_DYNPTR)
2935 		return 0;
2936 	spi = dynptr_get_spi(env, reg);
2937 	if (spi < 0)
2938 		return spi;
2939 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2940 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2941 	 * read.
2942 	 */
2943 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2944 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2945 	if (ret)
2946 		return ret;
2947 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2948 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2949 }
2950 
2951 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2952 			  int spi, int nr_slots)
2953 {
2954 	struct bpf_func_state *state = func(env, reg);
2955 	int err, i;
2956 
2957 	for (i = 0; i < nr_slots; i++) {
2958 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2959 
2960 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2961 		if (err)
2962 			return err;
2963 
2964 		mark_stack_slot_scratched(env, spi - i);
2965 	}
2966 
2967 	return 0;
2968 }
2969 
2970 /* This function is supposed to be used by the following 32-bit optimization
2971  * code only. It returns TRUE if the source or destination register operates
2972  * on 64-bit, otherwise return FALSE.
2973  */
2974 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2975 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2976 {
2977 	u8 code, class, op;
2978 
2979 	code = insn->code;
2980 	class = BPF_CLASS(code);
2981 	op = BPF_OP(code);
2982 	if (class == BPF_JMP) {
2983 		/* BPF_EXIT for "main" will reach here. Return TRUE
2984 		 * conservatively.
2985 		 */
2986 		if (op == BPF_EXIT)
2987 			return true;
2988 		if (op == BPF_CALL) {
2989 			/* BPF to BPF call will reach here because of marking
2990 			 * caller saved clobber with DST_OP_NO_MARK for which we
2991 			 * don't care the register def because they are anyway
2992 			 * marked as NOT_INIT already.
2993 			 */
2994 			if (insn->src_reg == BPF_PSEUDO_CALL)
2995 				return false;
2996 			/* Helper call will reach here because of arg type
2997 			 * check, conservatively return TRUE.
2998 			 */
2999 			if (t == SRC_OP)
3000 				return true;
3001 
3002 			return false;
3003 		}
3004 	}
3005 
3006 	if (class == BPF_ALU64 || class == BPF_JMP ||
3007 	    /* BPF_END always use BPF_ALU class. */
3008 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3009 		return true;
3010 
3011 	if (class == BPF_ALU || class == BPF_JMP32)
3012 		return false;
3013 
3014 	if (class == BPF_LDX) {
3015 		if (t != SRC_OP)
3016 			return BPF_SIZE(code) == BPF_DW;
3017 		/* LDX source must be ptr. */
3018 		return true;
3019 	}
3020 
3021 	if (class == BPF_STX) {
3022 		/* BPF_STX (including atomic variants) has multiple source
3023 		 * operands, one of which is a ptr. Check whether the caller is
3024 		 * asking about it.
3025 		 */
3026 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3027 			return true;
3028 		return BPF_SIZE(code) == BPF_DW;
3029 	}
3030 
3031 	if (class == BPF_LD) {
3032 		u8 mode = BPF_MODE(code);
3033 
3034 		/* LD_IMM64 */
3035 		if (mode == BPF_IMM)
3036 			return true;
3037 
3038 		/* Both LD_IND and LD_ABS return 32-bit data. */
3039 		if (t != SRC_OP)
3040 			return  false;
3041 
3042 		/* Implicit ctx ptr. */
3043 		if (regno == BPF_REG_6)
3044 			return true;
3045 
3046 		/* Explicit source could be any width. */
3047 		return true;
3048 	}
3049 
3050 	if (class == BPF_ST)
3051 		/* The only source register for BPF_ST is a ptr. */
3052 		return true;
3053 
3054 	/* Conservatively return true at default. */
3055 	return true;
3056 }
3057 
3058 /* Return the regno defined by the insn, or -1. */
3059 static int insn_def_regno(const struct bpf_insn *insn)
3060 {
3061 	switch (BPF_CLASS(insn->code)) {
3062 	case BPF_JMP:
3063 	case BPF_JMP32:
3064 	case BPF_ST:
3065 		return -1;
3066 	case BPF_STX:
3067 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3068 		    (insn->imm & BPF_FETCH)) {
3069 			if (insn->imm == BPF_CMPXCHG)
3070 				return BPF_REG_0;
3071 			else
3072 				return insn->src_reg;
3073 		} else {
3074 			return -1;
3075 		}
3076 	default:
3077 		return insn->dst_reg;
3078 	}
3079 }
3080 
3081 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3082 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3083 {
3084 	int dst_reg = insn_def_regno(insn);
3085 
3086 	if (dst_reg == -1)
3087 		return false;
3088 
3089 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3090 }
3091 
3092 static void mark_insn_zext(struct bpf_verifier_env *env,
3093 			   struct bpf_reg_state *reg)
3094 {
3095 	s32 def_idx = reg->subreg_def;
3096 
3097 	if (def_idx == DEF_NOT_SUBREG)
3098 		return;
3099 
3100 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3101 	/* The dst will be zero extended, so won't be sub-register anymore. */
3102 	reg->subreg_def = DEF_NOT_SUBREG;
3103 }
3104 
3105 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3106 			 enum reg_arg_type t)
3107 {
3108 	struct bpf_verifier_state *vstate = env->cur_state;
3109 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3110 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3111 	struct bpf_reg_state *reg, *regs = state->regs;
3112 	bool rw64;
3113 
3114 	if (regno >= MAX_BPF_REG) {
3115 		verbose(env, "R%d is invalid\n", regno);
3116 		return -EINVAL;
3117 	}
3118 
3119 	mark_reg_scratched(env, regno);
3120 
3121 	reg = &regs[regno];
3122 	rw64 = is_reg64(env, insn, regno, reg, t);
3123 	if (t == SRC_OP) {
3124 		/* check whether register used as source operand can be read */
3125 		if (reg->type == NOT_INIT) {
3126 			verbose(env, "R%d !read_ok\n", regno);
3127 			return -EACCES;
3128 		}
3129 		/* We don't need to worry about FP liveness because it's read-only */
3130 		if (regno == BPF_REG_FP)
3131 			return 0;
3132 
3133 		if (rw64)
3134 			mark_insn_zext(env, reg);
3135 
3136 		return mark_reg_read(env, reg, reg->parent,
3137 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3138 	} else {
3139 		/* check whether register used as dest operand can be written to */
3140 		if (regno == BPF_REG_FP) {
3141 			verbose(env, "frame pointer is read only\n");
3142 			return -EACCES;
3143 		}
3144 		reg->live |= REG_LIVE_WRITTEN;
3145 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3146 		if (t == DST_OP)
3147 			mark_reg_unknown(env, regs, regno);
3148 	}
3149 	return 0;
3150 }
3151 
3152 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3153 {
3154 	env->insn_aux_data[idx].jmp_point = true;
3155 }
3156 
3157 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3158 {
3159 	return env->insn_aux_data[insn_idx].jmp_point;
3160 }
3161 
3162 /* for any branch, call, exit record the history of jmps in the given state */
3163 static int push_jmp_history(struct bpf_verifier_env *env,
3164 			    struct bpf_verifier_state *cur)
3165 {
3166 	u32 cnt = cur->jmp_history_cnt;
3167 	struct bpf_idx_pair *p;
3168 	size_t alloc_size;
3169 
3170 	if (!is_jmp_point(env, env->insn_idx))
3171 		return 0;
3172 
3173 	cnt++;
3174 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3175 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3176 	if (!p)
3177 		return -ENOMEM;
3178 	p[cnt - 1].idx = env->insn_idx;
3179 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3180 	cur->jmp_history = p;
3181 	cur->jmp_history_cnt = cnt;
3182 	return 0;
3183 }
3184 
3185 /* Backtrack one insn at a time. If idx is not at the top of recorded
3186  * history then previous instruction came from straight line execution.
3187  */
3188 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3189 			     u32 *history)
3190 {
3191 	u32 cnt = *history;
3192 
3193 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3194 		i = st->jmp_history[cnt - 1].prev_idx;
3195 		(*history)--;
3196 	} else {
3197 		i--;
3198 	}
3199 	return i;
3200 }
3201 
3202 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3203 {
3204 	const struct btf_type *func;
3205 	struct btf *desc_btf;
3206 
3207 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3208 		return NULL;
3209 
3210 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3211 	if (IS_ERR(desc_btf))
3212 		return "<error>";
3213 
3214 	func = btf_type_by_id(desc_btf, insn->imm);
3215 	return btf_name_by_offset(desc_btf, func->name_off);
3216 }
3217 
3218 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3219 {
3220 	bt->frame = frame;
3221 }
3222 
3223 static inline void bt_reset(struct backtrack_state *bt)
3224 {
3225 	struct bpf_verifier_env *env = bt->env;
3226 
3227 	memset(bt, 0, sizeof(*bt));
3228 	bt->env = env;
3229 }
3230 
3231 static inline u32 bt_empty(struct backtrack_state *bt)
3232 {
3233 	u64 mask = 0;
3234 	int i;
3235 
3236 	for (i = 0; i <= bt->frame; i++)
3237 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3238 
3239 	return mask == 0;
3240 }
3241 
3242 static inline int bt_subprog_enter(struct backtrack_state *bt)
3243 {
3244 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3245 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3246 		WARN_ONCE(1, "verifier backtracking bug");
3247 		return -EFAULT;
3248 	}
3249 	bt->frame++;
3250 	return 0;
3251 }
3252 
3253 static inline int bt_subprog_exit(struct backtrack_state *bt)
3254 {
3255 	if (bt->frame == 0) {
3256 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3257 		WARN_ONCE(1, "verifier backtracking bug");
3258 		return -EFAULT;
3259 	}
3260 	bt->frame--;
3261 	return 0;
3262 }
3263 
3264 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3265 {
3266 	bt->reg_masks[frame] |= 1 << reg;
3267 }
3268 
3269 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3270 {
3271 	bt->reg_masks[frame] &= ~(1 << reg);
3272 }
3273 
3274 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3275 {
3276 	bt_set_frame_reg(bt, bt->frame, reg);
3277 }
3278 
3279 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3280 {
3281 	bt_clear_frame_reg(bt, bt->frame, reg);
3282 }
3283 
3284 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3285 {
3286 	bt->stack_masks[frame] |= 1ull << slot;
3287 }
3288 
3289 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3290 {
3291 	bt->stack_masks[frame] &= ~(1ull << slot);
3292 }
3293 
3294 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3295 {
3296 	bt_set_frame_slot(bt, bt->frame, slot);
3297 }
3298 
3299 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3300 {
3301 	bt_clear_frame_slot(bt, bt->frame, slot);
3302 }
3303 
3304 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3305 {
3306 	return bt->reg_masks[frame];
3307 }
3308 
3309 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3310 {
3311 	return bt->reg_masks[bt->frame];
3312 }
3313 
3314 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3315 {
3316 	return bt->stack_masks[frame];
3317 }
3318 
3319 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3320 {
3321 	return bt->stack_masks[bt->frame];
3322 }
3323 
3324 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3325 {
3326 	return bt->reg_masks[bt->frame] & (1 << reg);
3327 }
3328 
3329 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3330 {
3331 	return bt->stack_masks[bt->frame] & (1ull << slot);
3332 }
3333 
3334 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3335 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3336 {
3337 	DECLARE_BITMAP(mask, 64);
3338 	bool first = true;
3339 	int i, n;
3340 
3341 	buf[0] = '\0';
3342 
3343 	bitmap_from_u64(mask, reg_mask);
3344 	for_each_set_bit(i, mask, 32) {
3345 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3346 		first = false;
3347 		buf += n;
3348 		buf_sz -= n;
3349 		if (buf_sz < 0)
3350 			break;
3351 	}
3352 }
3353 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3354 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3355 {
3356 	DECLARE_BITMAP(mask, 64);
3357 	bool first = true;
3358 	int i, n;
3359 
3360 	buf[0] = '\0';
3361 
3362 	bitmap_from_u64(mask, stack_mask);
3363 	for_each_set_bit(i, mask, 64) {
3364 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3365 		first = false;
3366 		buf += n;
3367 		buf_sz -= n;
3368 		if (buf_sz < 0)
3369 			break;
3370 	}
3371 }
3372 
3373 /* For given verifier state backtrack_insn() is called from the last insn to
3374  * the first insn. Its purpose is to compute a bitmask of registers and
3375  * stack slots that needs precision in the parent verifier state.
3376  *
3377  * @idx is an index of the instruction we are currently processing;
3378  * @subseq_idx is an index of the subsequent instruction that:
3379  *   - *would be* executed next, if jump history is viewed in forward order;
3380  *   - *was* processed previously during backtracking.
3381  */
3382 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3383 			  struct backtrack_state *bt)
3384 {
3385 	const struct bpf_insn_cbs cbs = {
3386 		.cb_call	= disasm_kfunc_name,
3387 		.cb_print	= verbose,
3388 		.private_data	= env,
3389 	};
3390 	struct bpf_insn *insn = env->prog->insnsi + idx;
3391 	u8 class = BPF_CLASS(insn->code);
3392 	u8 opcode = BPF_OP(insn->code);
3393 	u8 mode = BPF_MODE(insn->code);
3394 	u32 dreg = insn->dst_reg;
3395 	u32 sreg = insn->src_reg;
3396 	u32 spi, i;
3397 
3398 	if (insn->code == 0)
3399 		return 0;
3400 	if (env->log.level & BPF_LOG_LEVEL2) {
3401 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3402 		verbose(env, "mark_precise: frame%d: regs=%s ",
3403 			bt->frame, env->tmp_str_buf);
3404 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3405 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3406 		verbose(env, "%d: ", idx);
3407 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3408 	}
3409 
3410 	if (class == BPF_ALU || class == BPF_ALU64) {
3411 		if (!bt_is_reg_set(bt, dreg))
3412 			return 0;
3413 		if (opcode == BPF_MOV) {
3414 			if (BPF_SRC(insn->code) == BPF_X) {
3415 				/* dreg = sreg
3416 				 * dreg needs precision after this insn
3417 				 * sreg needs precision before this insn
3418 				 */
3419 				bt_clear_reg(bt, dreg);
3420 				bt_set_reg(bt, sreg);
3421 			} else {
3422 				/* dreg = K
3423 				 * dreg needs precision after this insn.
3424 				 * Corresponding register is already marked
3425 				 * as precise=true in this verifier state.
3426 				 * No further markings in parent are necessary
3427 				 */
3428 				bt_clear_reg(bt, dreg);
3429 			}
3430 		} else {
3431 			if (BPF_SRC(insn->code) == BPF_X) {
3432 				/* dreg += sreg
3433 				 * both dreg and sreg need precision
3434 				 * before this insn
3435 				 */
3436 				bt_set_reg(bt, sreg);
3437 			} /* else dreg += K
3438 			   * dreg still needs precision before this insn
3439 			   */
3440 		}
3441 	} else if (class == BPF_LDX) {
3442 		if (!bt_is_reg_set(bt, dreg))
3443 			return 0;
3444 		bt_clear_reg(bt, dreg);
3445 
3446 		/* scalars can only be spilled into stack w/o losing precision.
3447 		 * Load from any other memory can be zero extended.
3448 		 * The desire to keep that precision is already indicated
3449 		 * by 'precise' mark in corresponding register of this state.
3450 		 * No further tracking necessary.
3451 		 */
3452 		if (insn->src_reg != BPF_REG_FP)
3453 			return 0;
3454 
3455 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3456 		 * that [fp - off] slot contains scalar that needs to be
3457 		 * tracked with precision
3458 		 */
3459 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3460 		if (spi >= 64) {
3461 			verbose(env, "BUG spi %d\n", spi);
3462 			WARN_ONCE(1, "verifier backtracking bug");
3463 			return -EFAULT;
3464 		}
3465 		bt_set_slot(bt, spi);
3466 	} else if (class == BPF_STX || class == BPF_ST) {
3467 		if (bt_is_reg_set(bt, dreg))
3468 			/* stx & st shouldn't be using _scalar_ dst_reg
3469 			 * to access memory. It means backtracking
3470 			 * encountered a case of pointer subtraction.
3471 			 */
3472 			return -ENOTSUPP;
3473 		/* scalars can only be spilled into stack */
3474 		if (insn->dst_reg != BPF_REG_FP)
3475 			return 0;
3476 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3477 		if (spi >= 64) {
3478 			verbose(env, "BUG spi %d\n", spi);
3479 			WARN_ONCE(1, "verifier backtracking bug");
3480 			return -EFAULT;
3481 		}
3482 		if (!bt_is_slot_set(bt, spi))
3483 			return 0;
3484 		bt_clear_slot(bt, spi);
3485 		if (class == BPF_STX)
3486 			bt_set_reg(bt, sreg);
3487 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3488 		if (bpf_pseudo_call(insn)) {
3489 			int subprog_insn_idx, subprog;
3490 
3491 			subprog_insn_idx = idx + insn->imm + 1;
3492 			subprog = find_subprog(env, subprog_insn_idx);
3493 			if (subprog < 0)
3494 				return -EFAULT;
3495 
3496 			if (subprog_is_global(env, subprog)) {
3497 				/* check that jump history doesn't have any
3498 				 * extra instructions from subprog; the next
3499 				 * instruction after call to global subprog
3500 				 * should be literally next instruction in
3501 				 * caller program
3502 				 */
3503 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3504 				/* r1-r5 are invalidated after subprog call,
3505 				 * so for global func call it shouldn't be set
3506 				 * anymore
3507 				 */
3508 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3509 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3510 					WARN_ONCE(1, "verifier backtracking bug");
3511 					return -EFAULT;
3512 				}
3513 				/* global subprog always sets R0 */
3514 				bt_clear_reg(bt, BPF_REG_0);
3515 				return 0;
3516 			} else {
3517 				/* static subprog call instruction, which
3518 				 * means that we are exiting current subprog,
3519 				 * so only r1-r5 could be still requested as
3520 				 * precise, r0 and r6-r10 or any stack slot in
3521 				 * the current frame should be zero by now
3522 				 */
3523 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3524 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3525 					WARN_ONCE(1, "verifier backtracking bug");
3526 					return -EFAULT;
3527 				}
3528 				/* we don't track register spills perfectly,
3529 				 * so fallback to force-precise instead of failing */
3530 				if (bt_stack_mask(bt) != 0)
3531 					return -ENOTSUPP;
3532 				/* propagate r1-r5 to the caller */
3533 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3534 					if (bt_is_reg_set(bt, i)) {
3535 						bt_clear_reg(bt, i);
3536 						bt_set_frame_reg(bt, bt->frame - 1, i);
3537 					}
3538 				}
3539 				if (bt_subprog_exit(bt))
3540 					return -EFAULT;
3541 				return 0;
3542 			}
3543 		} else if ((bpf_helper_call(insn) &&
3544 			    is_callback_calling_function(insn->imm) &&
3545 			    !is_async_callback_calling_function(insn->imm)) ||
3546 			   (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3547 			/* callback-calling helper or kfunc call, which means
3548 			 * we are exiting from subprog, but unlike the subprog
3549 			 * call handling above, we shouldn't propagate
3550 			 * precision of r1-r5 (if any requested), as they are
3551 			 * not actually arguments passed directly to callback
3552 			 * subprogs
3553 			 */
3554 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3555 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3556 				WARN_ONCE(1, "verifier backtracking bug");
3557 				return -EFAULT;
3558 			}
3559 			if (bt_stack_mask(bt) != 0)
3560 				return -ENOTSUPP;
3561 			/* clear r1-r5 in callback subprog's mask */
3562 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3563 				bt_clear_reg(bt, i);
3564 			if (bt_subprog_exit(bt))
3565 				return -EFAULT;
3566 			return 0;
3567 		} else if (opcode == BPF_CALL) {
3568 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3569 			 * catch this error later. Make backtracking conservative
3570 			 * with ENOTSUPP.
3571 			 */
3572 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3573 				return -ENOTSUPP;
3574 			/* regular helper call sets R0 */
3575 			bt_clear_reg(bt, BPF_REG_0);
3576 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3577 				/* if backtracing was looking for registers R1-R5
3578 				 * they should have been found already.
3579 				 */
3580 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3581 				WARN_ONCE(1, "verifier backtracking bug");
3582 				return -EFAULT;
3583 			}
3584 		} else if (opcode == BPF_EXIT) {
3585 			bool r0_precise;
3586 
3587 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3588 				/* if backtracing was looking for registers R1-R5
3589 				 * they should have been found already.
3590 				 */
3591 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3592 				WARN_ONCE(1, "verifier backtracking bug");
3593 				return -EFAULT;
3594 			}
3595 
3596 			/* BPF_EXIT in subprog or callback always returns
3597 			 * right after the call instruction, so by checking
3598 			 * whether the instruction at subseq_idx-1 is subprog
3599 			 * call or not we can distinguish actual exit from
3600 			 * *subprog* from exit from *callback*. In the former
3601 			 * case, we need to propagate r0 precision, if
3602 			 * necessary. In the former we never do that.
3603 			 */
3604 			r0_precise = subseq_idx - 1 >= 0 &&
3605 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3606 				     bt_is_reg_set(bt, BPF_REG_0);
3607 
3608 			bt_clear_reg(bt, BPF_REG_0);
3609 			if (bt_subprog_enter(bt))
3610 				return -EFAULT;
3611 
3612 			if (r0_precise)
3613 				bt_set_reg(bt, BPF_REG_0);
3614 			/* r6-r9 and stack slots will stay set in caller frame
3615 			 * bitmasks until we return back from callee(s)
3616 			 */
3617 			return 0;
3618 		} else if (BPF_SRC(insn->code) == BPF_X) {
3619 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3620 				return 0;
3621 			/* dreg <cond> sreg
3622 			 * Both dreg and sreg need precision before
3623 			 * this insn. If only sreg was marked precise
3624 			 * before it would be equally necessary to
3625 			 * propagate it to dreg.
3626 			 */
3627 			bt_set_reg(bt, dreg);
3628 			bt_set_reg(bt, sreg);
3629 			 /* else dreg <cond> K
3630 			  * Only dreg still needs precision before
3631 			  * this insn, so for the K-based conditional
3632 			  * there is nothing new to be marked.
3633 			  */
3634 		}
3635 	} else if (class == BPF_LD) {
3636 		if (!bt_is_reg_set(bt, dreg))
3637 			return 0;
3638 		bt_clear_reg(bt, dreg);
3639 		/* It's ld_imm64 or ld_abs or ld_ind.
3640 		 * For ld_imm64 no further tracking of precision
3641 		 * into parent is necessary
3642 		 */
3643 		if (mode == BPF_IND || mode == BPF_ABS)
3644 			/* to be analyzed */
3645 			return -ENOTSUPP;
3646 	}
3647 	return 0;
3648 }
3649 
3650 /* the scalar precision tracking algorithm:
3651  * . at the start all registers have precise=false.
3652  * . scalar ranges are tracked as normal through alu and jmp insns.
3653  * . once precise value of the scalar register is used in:
3654  *   .  ptr + scalar alu
3655  *   . if (scalar cond K|scalar)
3656  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3657  *   backtrack through the verifier states and mark all registers and
3658  *   stack slots with spilled constants that these scalar regisers
3659  *   should be precise.
3660  * . during state pruning two registers (or spilled stack slots)
3661  *   are equivalent if both are not precise.
3662  *
3663  * Note the verifier cannot simply walk register parentage chain,
3664  * since many different registers and stack slots could have been
3665  * used to compute single precise scalar.
3666  *
3667  * The approach of starting with precise=true for all registers and then
3668  * backtrack to mark a register as not precise when the verifier detects
3669  * that program doesn't care about specific value (e.g., when helper
3670  * takes register as ARG_ANYTHING parameter) is not safe.
3671  *
3672  * It's ok to walk single parentage chain of the verifier states.
3673  * It's possible that this backtracking will go all the way till 1st insn.
3674  * All other branches will be explored for needing precision later.
3675  *
3676  * The backtracking needs to deal with cases like:
3677  *   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)
3678  * r9 -= r8
3679  * r5 = r9
3680  * if r5 > 0x79f goto pc+7
3681  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3682  * r5 += 1
3683  * ...
3684  * call bpf_perf_event_output#25
3685  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3686  *
3687  * and this case:
3688  * r6 = 1
3689  * call foo // uses callee's r6 inside to compute r0
3690  * r0 += r6
3691  * if r0 == 0 goto
3692  *
3693  * to track above reg_mask/stack_mask needs to be independent for each frame.
3694  *
3695  * Also if parent's curframe > frame where backtracking started,
3696  * the verifier need to mark registers in both frames, otherwise callees
3697  * may incorrectly prune callers. This is similar to
3698  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3699  *
3700  * For now backtracking falls back into conservative marking.
3701  */
3702 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3703 				     struct bpf_verifier_state *st)
3704 {
3705 	struct bpf_func_state *func;
3706 	struct bpf_reg_state *reg;
3707 	int i, j;
3708 
3709 	if (env->log.level & BPF_LOG_LEVEL2) {
3710 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3711 			st->curframe);
3712 	}
3713 
3714 	/* big hammer: mark all scalars precise in this path.
3715 	 * pop_stack may still get !precise scalars.
3716 	 * We also skip current state and go straight to first parent state,
3717 	 * because precision markings in current non-checkpointed state are
3718 	 * not needed. See why in the comment in __mark_chain_precision below.
3719 	 */
3720 	for (st = st->parent; st; st = st->parent) {
3721 		for (i = 0; i <= st->curframe; i++) {
3722 			func = st->frame[i];
3723 			for (j = 0; j < BPF_REG_FP; j++) {
3724 				reg = &func->regs[j];
3725 				if (reg->type != SCALAR_VALUE || reg->precise)
3726 					continue;
3727 				reg->precise = true;
3728 				if (env->log.level & BPF_LOG_LEVEL2) {
3729 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3730 						i, j);
3731 				}
3732 			}
3733 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3734 				if (!is_spilled_reg(&func->stack[j]))
3735 					continue;
3736 				reg = &func->stack[j].spilled_ptr;
3737 				if (reg->type != SCALAR_VALUE || reg->precise)
3738 					continue;
3739 				reg->precise = true;
3740 				if (env->log.level & BPF_LOG_LEVEL2) {
3741 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3742 						i, -(j + 1) * 8);
3743 				}
3744 			}
3745 		}
3746 	}
3747 }
3748 
3749 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3750 {
3751 	struct bpf_func_state *func;
3752 	struct bpf_reg_state *reg;
3753 	int i, j;
3754 
3755 	for (i = 0; i <= st->curframe; i++) {
3756 		func = st->frame[i];
3757 		for (j = 0; j < BPF_REG_FP; j++) {
3758 			reg = &func->regs[j];
3759 			if (reg->type != SCALAR_VALUE)
3760 				continue;
3761 			reg->precise = false;
3762 		}
3763 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3764 			if (!is_spilled_reg(&func->stack[j]))
3765 				continue;
3766 			reg = &func->stack[j].spilled_ptr;
3767 			if (reg->type != SCALAR_VALUE)
3768 				continue;
3769 			reg->precise = false;
3770 		}
3771 	}
3772 }
3773 
3774 /*
3775  * __mark_chain_precision() backtracks BPF program instruction sequence and
3776  * chain of verifier states making sure that register *regno* (if regno >= 0)
3777  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3778  * SCALARS, as well as any other registers and slots that contribute to
3779  * a tracked state of given registers/stack slots, depending on specific BPF
3780  * assembly instructions (see backtrack_insns() for exact instruction handling
3781  * logic). This backtracking relies on recorded jmp_history and is able to
3782  * traverse entire chain of parent states. This process ends only when all the
3783  * necessary registers/slots and their transitive dependencies are marked as
3784  * precise.
3785  *
3786  * One important and subtle aspect is that precise marks *do not matter* in
3787  * the currently verified state (current state). It is important to understand
3788  * why this is the case.
3789  *
3790  * First, note that current state is the state that is not yet "checkpointed",
3791  * i.e., it is not yet put into env->explored_states, and it has no children
3792  * states as well. It's ephemeral, and can end up either a) being discarded if
3793  * compatible explored state is found at some point or BPF_EXIT instruction is
3794  * reached or b) checkpointed and put into env->explored_states, branching out
3795  * into one or more children states.
3796  *
3797  * In the former case, precise markings in current state are completely
3798  * ignored by state comparison code (see regsafe() for details). Only
3799  * checkpointed ("old") state precise markings are important, and if old
3800  * state's register/slot is precise, regsafe() assumes current state's
3801  * register/slot as precise and checks value ranges exactly and precisely. If
3802  * states turn out to be compatible, current state's necessary precise
3803  * markings and any required parent states' precise markings are enforced
3804  * after the fact with propagate_precision() logic, after the fact. But it's
3805  * important to realize that in this case, even after marking current state
3806  * registers/slots as precise, we immediately discard current state. So what
3807  * actually matters is any of the precise markings propagated into current
3808  * state's parent states, which are always checkpointed (due to b) case above).
3809  * As such, for scenario a) it doesn't matter if current state has precise
3810  * markings set or not.
3811  *
3812  * Now, for the scenario b), checkpointing and forking into child(ren)
3813  * state(s). Note that before current state gets to checkpointing step, any
3814  * processed instruction always assumes precise SCALAR register/slot
3815  * knowledge: if precise value or range is useful to prune jump branch, BPF
3816  * verifier takes this opportunity enthusiastically. Similarly, when
3817  * register's value is used to calculate offset or memory address, exact
3818  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3819  * what we mentioned above about state comparison ignoring precise markings
3820  * during state comparison, BPF verifier ignores and also assumes precise
3821  * markings *at will* during instruction verification process. But as verifier
3822  * assumes precision, it also propagates any precision dependencies across
3823  * parent states, which are not yet finalized, so can be further restricted
3824  * based on new knowledge gained from restrictions enforced by their children
3825  * states. This is so that once those parent states are finalized, i.e., when
3826  * they have no more active children state, state comparison logic in
3827  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3828  * required for correctness.
3829  *
3830  * To build a bit more intuition, note also that once a state is checkpointed,
3831  * the path we took to get to that state is not important. This is crucial
3832  * property for state pruning. When state is checkpointed and finalized at
3833  * some instruction index, it can be correctly and safely used to "short
3834  * circuit" any *compatible* state that reaches exactly the same instruction
3835  * index. I.e., if we jumped to that instruction from a completely different
3836  * code path than original finalized state was derived from, it doesn't
3837  * matter, current state can be discarded because from that instruction
3838  * forward having a compatible state will ensure we will safely reach the
3839  * exit. States describe preconditions for further exploration, but completely
3840  * forget the history of how we got here.
3841  *
3842  * This also means that even if we needed precise SCALAR range to get to
3843  * finalized state, but from that point forward *that same* SCALAR register is
3844  * never used in a precise context (i.e., it's precise value is not needed for
3845  * correctness), it's correct and safe to mark such register as "imprecise"
3846  * (i.e., precise marking set to false). This is what we rely on when we do
3847  * not set precise marking in current state. If no child state requires
3848  * precision for any given SCALAR register, it's safe to dictate that it can
3849  * be imprecise. If any child state does require this register to be precise,
3850  * we'll mark it precise later retroactively during precise markings
3851  * propagation from child state to parent states.
3852  *
3853  * Skipping precise marking setting in current state is a mild version of
3854  * relying on the above observation. But we can utilize this property even
3855  * more aggressively by proactively forgetting any precise marking in the
3856  * current state (which we inherited from the parent state), right before we
3857  * checkpoint it and branch off into new child state. This is done by
3858  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3859  * finalized states which help in short circuiting more future states.
3860  */
3861 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3862 {
3863 	struct backtrack_state *bt = &env->bt;
3864 	struct bpf_verifier_state *st = env->cur_state;
3865 	int first_idx = st->first_insn_idx;
3866 	int last_idx = env->insn_idx;
3867 	int subseq_idx = -1;
3868 	struct bpf_func_state *func;
3869 	struct bpf_reg_state *reg;
3870 	bool skip_first = true;
3871 	int i, fr, err;
3872 
3873 	if (!env->bpf_capable)
3874 		return 0;
3875 
3876 	/* set frame number from which we are starting to backtrack */
3877 	bt_init(bt, env->cur_state->curframe);
3878 
3879 	/* Do sanity checks against current state of register and/or stack
3880 	 * slot, but don't set precise flag in current state, as precision
3881 	 * tracking in the current state is unnecessary.
3882 	 */
3883 	func = st->frame[bt->frame];
3884 	if (regno >= 0) {
3885 		reg = &func->regs[regno];
3886 		if (reg->type != SCALAR_VALUE) {
3887 			WARN_ONCE(1, "backtracing misuse");
3888 			return -EFAULT;
3889 		}
3890 		bt_set_reg(bt, regno);
3891 	}
3892 
3893 	if (bt_empty(bt))
3894 		return 0;
3895 
3896 	for (;;) {
3897 		DECLARE_BITMAP(mask, 64);
3898 		u32 history = st->jmp_history_cnt;
3899 
3900 		if (env->log.level & BPF_LOG_LEVEL2) {
3901 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
3902 				bt->frame, last_idx, first_idx, subseq_idx);
3903 		}
3904 
3905 		if (last_idx < 0) {
3906 			/* we are at the entry into subprog, which
3907 			 * is expected for global funcs, but only if
3908 			 * requested precise registers are R1-R5
3909 			 * (which are global func's input arguments)
3910 			 */
3911 			if (st->curframe == 0 &&
3912 			    st->frame[0]->subprogno > 0 &&
3913 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3914 			    bt_stack_mask(bt) == 0 &&
3915 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
3916 				bitmap_from_u64(mask, bt_reg_mask(bt));
3917 				for_each_set_bit(i, mask, 32) {
3918 					reg = &st->frame[0]->regs[i];
3919 					if (reg->type != SCALAR_VALUE) {
3920 						bt_clear_reg(bt, i);
3921 						continue;
3922 					}
3923 					reg->precise = true;
3924 				}
3925 				return 0;
3926 			}
3927 
3928 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
3929 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
3930 			WARN_ONCE(1, "verifier backtracking bug");
3931 			return -EFAULT;
3932 		}
3933 
3934 		for (i = last_idx;;) {
3935 			if (skip_first) {
3936 				err = 0;
3937 				skip_first = false;
3938 			} else {
3939 				err = backtrack_insn(env, i, subseq_idx, bt);
3940 			}
3941 			if (err == -ENOTSUPP) {
3942 				mark_all_scalars_precise(env, env->cur_state);
3943 				bt_reset(bt);
3944 				return 0;
3945 			} else if (err) {
3946 				return err;
3947 			}
3948 			if (bt_empty(bt))
3949 				/* Found assignment(s) into tracked register in this state.
3950 				 * Since this state is already marked, just return.
3951 				 * Nothing to be tracked further in the parent state.
3952 				 */
3953 				return 0;
3954 			if (i == first_idx)
3955 				break;
3956 			subseq_idx = i;
3957 			i = get_prev_insn_idx(st, i, &history);
3958 			if (i >= env->prog->len) {
3959 				/* This can happen if backtracking reached insn 0
3960 				 * and there are still reg_mask or stack_mask
3961 				 * to backtrack.
3962 				 * It means the backtracking missed the spot where
3963 				 * particular register was initialized with a constant.
3964 				 */
3965 				verbose(env, "BUG backtracking idx %d\n", i);
3966 				WARN_ONCE(1, "verifier backtracking bug");
3967 				return -EFAULT;
3968 			}
3969 		}
3970 		st = st->parent;
3971 		if (!st)
3972 			break;
3973 
3974 		for (fr = bt->frame; fr >= 0; fr--) {
3975 			func = st->frame[fr];
3976 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3977 			for_each_set_bit(i, mask, 32) {
3978 				reg = &func->regs[i];
3979 				if (reg->type != SCALAR_VALUE) {
3980 					bt_clear_frame_reg(bt, fr, i);
3981 					continue;
3982 				}
3983 				if (reg->precise)
3984 					bt_clear_frame_reg(bt, fr, i);
3985 				else
3986 					reg->precise = true;
3987 			}
3988 
3989 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3990 			for_each_set_bit(i, mask, 64) {
3991 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
3992 					/* the sequence of instructions:
3993 					 * 2: (bf) r3 = r10
3994 					 * 3: (7b) *(u64 *)(r3 -8) = r0
3995 					 * 4: (79) r4 = *(u64 *)(r10 -8)
3996 					 * doesn't contain jmps. It's backtracked
3997 					 * as a single block.
3998 					 * During backtracking insn 3 is not recognized as
3999 					 * stack access, so at the end of backtracking
4000 					 * stack slot fp-8 is still marked in stack_mask.
4001 					 * However the parent state may not have accessed
4002 					 * fp-8 and it's "unallocated" stack space.
4003 					 * In such case fallback to conservative.
4004 					 */
4005 					mark_all_scalars_precise(env, env->cur_state);
4006 					bt_reset(bt);
4007 					return 0;
4008 				}
4009 
4010 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4011 					bt_clear_frame_slot(bt, fr, i);
4012 					continue;
4013 				}
4014 				reg = &func->stack[i].spilled_ptr;
4015 				if (reg->precise)
4016 					bt_clear_frame_slot(bt, fr, i);
4017 				else
4018 					reg->precise = true;
4019 			}
4020 			if (env->log.level & BPF_LOG_LEVEL2) {
4021 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4022 					     bt_frame_reg_mask(bt, fr));
4023 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4024 					fr, env->tmp_str_buf);
4025 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4026 					       bt_frame_stack_mask(bt, fr));
4027 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4028 				print_verifier_state(env, func, true);
4029 			}
4030 		}
4031 
4032 		if (bt_empty(bt))
4033 			return 0;
4034 
4035 		subseq_idx = first_idx;
4036 		last_idx = st->last_insn_idx;
4037 		first_idx = st->first_insn_idx;
4038 	}
4039 
4040 	/* if we still have requested precise regs or slots, we missed
4041 	 * something (e.g., stack access through non-r10 register), so
4042 	 * fallback to marking all precise
4043 	 */
4044 	if (!bt_empty(bt)) {
4045 		mark_all_scalars_precise(env, env->cur_state);
4046 		bt_reset(bt);
4047 	}
4048 
4049 	return 0;
4050 }
4051 
4052 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4053 {
4054 	return __mark_chain_precision(env, regno);
4055 }
4056 
4057 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4058  * desired reg and stack masks across all relevant frames
4059  */
4060 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4061 {
4062 	return __mark_chain_precision(env, -1);
4063 }
4064 
4065 static bool is_spillable_regtype(enum bpf_reg_type type)
4066 {
4067 	switch (base_type(type)) {
4068 	case PTR_TO_MAP_VALUE:
4069 	case PTR_TO_STACK:
4070 	case PTR_TO_CTX:
4071 	case PTR_TO_PACKET:
4072 	case PTR_TO_PACKET_META:
4073 	case PTR_TO_PACKET_END:
4074 	case PTR_TO_FLOW_KEYS:
4075 	case CONST_PTR_TO_MAP:
4076 	case PTR_TO_SOCKET:
4077 	case PTR_TO_SOCK_COMMON:
4078 	case PTR_TO_TCP_SOCK:
4079 	case PTR_TO_XDP_SOCK:
4080 	case PTR_TO_BTF_ID:
4081 	case PTR_TO_BUF:
4082 	case PTR_TO_MEM:
4083 	case PTR_TO_FUNC:
4084 	case PTR_TO_MAP_KEY:
4085 		return true;
4086 	default:
4087 		return false;
4088 	}
4089 }
4090 
4091 /* Does this register contain a constant zero? */
4092 static bool register_is_null(struct bpf_reg_state *reg)
4093 {
4094 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4095 }
4096 
4097 static bool register_is_const(struct bpf_reg_state *reg)
4098 {
4099 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4100 }
4101 
4102 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4103 {
4104 	return tnum_is_unknown(reg->var_off) &&
4105 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4106 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4107 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4108 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4109 }
4110 
4111 static bool register_is_bounded(struct bpf_reg_state *reg)
4112 {
4113 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4114 }
4115 
4116 static bool __is_pointer_value(bool allow_ptr_leaks,
4117 			       const struct bpf_reg_state *reg)
4118 {
4119 	if (allow_ptr_leaks)
4120 		return false;
4121 
4122 	return reg->type != SCALAR_VALUE;
4123 }
4124 
4125 /* Copy src state preserving dst->parent and dst->live fields */
4126 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4127 {
4128 	struct bpf_reg_state *parent = dst->parent;
4129 	enum bpf_reg_liveness live = dst->live;
4130 
4131 	*dst = *src;
4132 	dst->parent = parent;
4133 	dst->live = live;
4134 }
4135 
4136 static void save_register_state(struct bpf_func_state *state,
4137 				int spi, struct bpf_reg_state *reg,
4138 				int size)
4139 {
4140 	int i;
4141 
4142 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4143 	if (size == BPF_REG_SIZE)
4144 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4145 
4146 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4147 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4148 
4149 	/* size < 8 bytes spill */
4150 	for (; i; i--)
4151 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4152 }
4153 
4154 static bool is_bpf_st_mem(struct bpf_insn *insn)
4155 {
4156 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4157 }
4158 
4159 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4160  * stack boundary and alignment are checked in check_mem_access()
4161  */
4162 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4163 				       /* stack frame we're writing to */
4164 				       struct bpf_func_state *state,
4165 				       int off, int size, int value_regno,
4166 				       int insn_idx)
4167 {
4168 	struct bpf_func_state *cur; /* state of the current function */
4169 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4170 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4171 	struct bpf_reg_state *reg = NULL;
4172 	u32 dst_reg = insn->dst_reg;
4173 
4174 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4175 	if (err)
4176 		return err;
4177 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4178 	 * so it's aligned access and [off, off + size) are within stack limits
4179 	 */
4180 	if (!env->allow_ptr_leaks &&
4181 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
4182 	    size != BPF_REG_SIZE) {
4183 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4184 		return -EACCES;
4185 	}
4186 
4187 	cur = env->cur_state->frame[env->cur_state->curframe];
4188 	if (value_regno >= 0)
4189 		reg = &cur->regs[value_regno];
4190 	if (!env->bypass_spec_v4) {
4191 		bool sanitize = reg && is_spillable_regtype(reg->type);
4192 
4193 		for (i = 0; i < size; i++) {
4194 			u8 type = state->stack[spi].slot_type[i];
4195 
4196 			if (type != STACK_MISC && type != STACK_ZERO) {
4197 				sanitize = true;
4198 				break;
4199 			}
4200 		}
4201 
4202 		if (sanitize)
4203 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4204 	}
4205 
4206 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4207 	if (err)
4208 		return err;
4209 
4210 	mark_stack_slot_scratched(env, spi);
4211 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4212 	    !register_is_null(reg) && env->bpf_capable) {
4213 		if (dst_reg != BPF_REG_FP) {
4214 			/* The backtracking logic can only recognize explicit
4215 			 * stack slot address like [fp - 8]. Other spill of
4216 			 * scalar via different register has to be conservative.
4217 			 * Backtrack from here and mark all registers as precise
4218 			 * that contributed into 'reg' being a constant.
4219 			 */
4220 			err = mark_chain_precision(env, value_regno);
4221 			if (err)
4222 				return err;
4223 		}
4224 		save_register_state(state, spi, reg, size);
4225 		/* Break the relation on a narrowing spill. */
4226 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4227 			state->stack[spi].spilled_ptr.id = 0;
4228 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4229 		   insn->imm != 0 && env->bpf_capable) {
4230 		struct bpf_reg_state fake_reg = {};
4231 
4232 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4233 		fake_reg.type = SCALAR_VALUE;
4234 		save_register_state(state, spi, &fake_reg, size);
4235 	} else if (reg && is_spillable_regtype(reg->type)) {
4236 		/* register containing pointer is being spilled into stack */
4237 		if (size != BPF_REG_SIZE) {
4238 			verbose_linfo(env, insn_idx, "; ");
4239 			verbose(env, "invalid size of register spill\n");
4240 			return -EACCES;
4241 		}
4242 		if (state != cur && reg->type == PTR_TO_STACK) {
4243 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4244 			return -EINVAL;
4245 		}
4246 		save_register_state(state, spi, reg, size);
4247 	} else {
4248 		u8 type = STACK_MISC;
4249 
4250 		/* regular write of data into stack destroys any spilled ptr */
4251 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4252 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4253 		if (is_stack_slot_special(&state->stack[spi]))
4254 			for (i = 0; i < BPF_REG_SIZE; i++)
4255 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4256 
4257 		/* only mark the slot as written if all 8 bytes were written
4258 		 * otherwise read propagation may incorrectly stop too soon
4259 		 * when stack slots are partially written.
4260 		 * This heuristic means that read propagation will be
4261 		 * conservative, since it will add reg_live_read marks
4262 		 * to stack slots all the way to first state when programs
4263 		 * writes+reads less than 8 bytes
4264 		 */
4265 		if (size == BPF_REG_SIZE)
4266 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4267 
4268 		/* when we zero initialize stack slots mark them as such */
4269 		if ((reg && register_is_null(reg)) ||
4270 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4271 			/* backtracking doesn't work for STACK_ZERO yet. */
4272 			err = mark_chain_precision(env, value_regno);
4273 			if (err)
4274 				return err;
4275 			type = STACK_ZERO;
4276 		}
4277 
4278 		/* Mark slots affected by this stack write. */
4279 		for (i = 0; i < size; i++)
4280 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4281 				type;
4282 	}
4283 	return 0;
4284 }
4285 
4286 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4287  * known to contain a variable offset.
4288  * This function checks whether the write is permitted and conservatively
4289  * tracks the effects of the write, considering that each stack slot in the
4290  * dynamic range is potentially written to.
4291  *
4292  * 'off' includes 'regno->off'.
4293  * 'value_regno' can be -1, meaning that an unknown value is being written to
4294  * the stack.
4295  *
4296  * Spilled pointers in range are not marked as written because we don't know
4297  * what's going to be actually written. This means that read propagation for
4298  * future reads cannot be terminated by this write.
4299  *
4300  * For privileged programs, uninitialized stack slots are considered
4301  * initialized by this write (even though we don't know exactly what offsets
4302  * are going to be written to). The idea is that we don't want the verifier to
4303  * reject future reads that access slots written to through variable offsets.
4304  */
4305 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4306 				     /* func where register points to */
4307 				     struct bpf_func_state *state,
4308 				     int ptr_regno, int off, int size,
4309 				     int value_regno, int insn_idx)
4310 {
4311 	struct bpf_func_state *cur; /* state of the current function */
4312 	int min_off, max_off;
4313 	int i, err;
4314 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4315 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4316 	bool writing_zero = false;
4317 	/* set if the fact that we're writing a zero is used to let any
4318 	 * stack slots remain STACK_ZERO
4319 	 */
4320 	bool zero_used = false;
4321 
4322 	cur = env->cur_state->frame[env->cur_state->curframe];
4323 	ptr_reg = &cur->regs[ptr_regno];
4324 	min_off = ptr_reg->smin_value + off;
4325 	max_off = ptr_reg->smax_value + off + size;
4326 	if (value_regno >= 0)
4327 		value_reg = &cur->regs[value_regno];
4328 	if ((value_reg && register_is_null(value_reg)) ||
4329 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4330 		writing_zero = true;
4331 
4332 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4333 	if (err)
4334 		return err;
4335 
4336 	for (i = min_off; i < max_off; i++) {
4337 		int spi;
4338 
4339 		spi = __get_spi(i);
4340 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4341 		if (err)
4342 			return err;
4343 	}
4344 
4345 	/* Variable offset writes destroy any spilled pointers in range. */
4346 	for (i = min_off; i < max_off; i++) {
4347 		u8 new_type, *stype;
4348 		int slot, spi;
4349 
4350 		slot = -i - 1;
4351 		spi = slot / BPF_REG_SIZE;
4352 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4353 		mark_stack_slot_scratched(env, spi);
4354 
4355 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4356 			/* Reject the write if range we may write to has not
4357 			 * been initialized beforehand. If we didn't reject
4358 			 * here, the ptr status would be erased below (even
4359 			 * though not all slots are actually overwritten),
4360 			 * possibly opening the door to leaks.
4361 			 *
4362 			 * We do however catch STACK_INVALID case below, and
4363 			 * only allow reading possibly uninitialized memory
4364 			 * later for CAP_PERFMON, as the write may not happen to
4365 			 * that slot.
4366 			 */
4367 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4368 				insn_idx, i);
4369 			return -EINVAL;
4370 		}
4371 
4372 		/* Erase all spilled pointers. */
4373 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4374 
4375 		/* Update the slot type. */
4376 		new_type = STACK_MISC;
4377 		if (writing_zero && *stype == STACK_ZERO) {
4378 			new_type = STACK_ZERO;
4379 			zero_used = true;
4380 		}
4381 		/* If the slot is STACK_INVALID, we check whether it's OK to
4382 		 * pretend that it will be initialized by this write. The slot
4383 		 * might not actually be written to, and so if we mark it as
4384 		 * initialized future reads might leak uninitialized memory.
4385 		 * For privileged programs, we will accept such reads to slots
4386 		 * that may or may not be written because, if we're reject
4387 		 * them, the error would be too confusing.
4388 		 */
4389 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4390 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4391 					insn_idx, i);
4392 			return -EINVAL;
4393 		}
4394 		*stype = new_type;
4395 	}
4396 	if (zero_used) {
4397 		/* backtracking doesn't work for STACK_ZERO yet. */
4398 		err = mark_chain_precision(env, value_regno);
4399 		if (err)
4400 			return err;
4401 	}
4402 	return 0;
4403 }
4404 
4405 /* When register 'dst_regno' is assigned some values from stack[min_off,
4406  * max_off), we set the register's type according to the types of the
4407  * respective stack slots. If all the stack values are known to be zeros, then
4408  * so is the destination reg. Otherwise, the register is considered to be
4409  * SCALAR. This function does not deal with register filling; the caller must
4410  * ensure that all spilled registers in the stack range have been marked as
4411  * read.
4412  */
4413 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4414 				/* func where src register points to */
4415 				struct bpf_func_state *ptr_state,
4416 				int min_off, int max_off, int dst_regno)
4417 {
4418 	struct bpf_verifier_state *vstate = env->cur_state;
4419 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4420 	int i, slot, spi;
4421 	u8 *stype;
4422 	int zeros = 0;
4423 
4424 	for (i = min_off; i < max_off; i++) {
4425 		slot = -i - 1;
4426 		spi = slot / BPF_REG_SIZE;
4427 		mark_stack_slot_scratched(env, spi);
4428 		stype = ptr_state->stack[spi].slot_type;
4429 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4430 			break;
4431 		zeros++;
4432 	}
4433 	if (zeros == max_off - min_off) {
4434 		/* any access_size read into register is zero extended,
4435 		 * so the whole register == const_zero
4436 		 */
4437 		__mark_reg_const_zero(&state->regs[dst_regno]);
4438 		/* backtracking doesn't support STACK_ZERO yet,
4439 		 * so mark it precise here, so that later
4440 		 * backtracking can stop here.
4441 		 * Backtracking may not need this if this register
4442 		 * doesn't participate in pointer adjustment.
4443 		 * Forward propagation of precise flag is not
4444 		 * necessary either. This mark is only to stop
4445 		 * backtracking. Any register that contributed
4446 		 * to const 0 was marked precise before spill.
4447 		 */
4448 		state->regs[dst_regno].precise = true;
4449 	} else {
4450 		/* have read misc data from the stack */
4451 		mark_reg_unknown(env, state->regs, dst_regno);
4452 	}
4453 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4454 }
4455 
4456 /* Read the stack at 'off' and put the results into the register indicated by
4457  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4458  * spilled reg.
4459  *
4460  * 'dst_regno' can be -1, meaning that the read value is not going to a
4461  * register.
4462  *
4463  * The access is assumed to be within the current stack bounds.
4464  */
4465 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4466 				      /* func where src register points to */
4467 				      struct bpf_func_state *reg_state,
4468 				      int off, int size, int dst_regno)
4469 {
4470 	struct bpf_verifier_state *vstate = env->cur_state;
4471 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4472 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4473 	struct bpf_reg_state *reg;
4474 	u8 *stype, type;
4475 
4476 	stype = reg_state->stack[spi].slot_type;
4477 	reg = &reg_state->stack[spi].spilled_ptr;
4478 
4479 	mark_stack_slot_scratched(env, spi);
4480 
4481 	if (is_spilled_reg(&reg_state->stack[spi])) {
4482 		u8 spill_size = 1;
4483 
4484 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4485 			spill_size++;
4486 
4487 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4488 			if (reg->type != SCALAR_VALUE) {
4489 				verbose_linfo(env, env->insn_idx, "; ");
4490 				verbose(env, "invalid size of register fill\n");
4491 				return -EACCES;
4492 			}
4493 
4494 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4495 			if (dst_regno < 0)
4496 				return 0;
4497 
4498 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4499 				/* The earlier check_reg_arg() has decided the
4500 				 * subreg_def for this insn.  Save it first.
4501 				 */
4502 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4503 
4504 				copy_register_state(&state->regs[dst_regno], reg);
4505 				state->regs[dst_regno].subreg_def = subreg_def;
4506 			} else {
4507 				for (i = 0; i < size; i++) {
4508 					type = stype[(slot - i) % BPF_REG_SIZE];
4509 					if (type == STACK_SPILL)
4510 						continue;
4511 					if (type == STACK_MISC)
4512 						continue;
4513 					if (type == STACK_INVALID && env->allow_uninit_stack)
4514 						continue;
4515 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4516 						off, i, size);
4517 					return -EACCES;
4518 				}
4519 				mark_reg_unknown(env, state->regs, dst_regno);
4520 			}
4521 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4522 			return 0;
4523 		}
4524 
4525 		if (dst_regno >= 0) {
4526 			/* restore register state from stack */
4527 			copy_register_state(&state->regs[dst_regno], reg);
4528 			/* mark reg as written since spilled pointer state likely
4529 			 * has its liveness marks cleared by is_state_visited()
4530 			 * which resets stack/reg liveness for state transitions
4531 			 */
4532 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4533 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4534 			/* If dst_regno==-1, the caller is asking us whether
4535 			 * it is acceptable to use this value as a SCALAR_VALUE
4536 			 * (e.g. for XADD).
4537 			 * We must not allow unprivileged callers to do that
4538 			 * with spilled pointers.
4539 			 */
4540 			verbose(env, "leaking pointer from stack off %d\n",
4541 				off);
4542 			return -EACCES;
4543 		}
4544 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4545 	} else {
4546 		for (i = 0; i < size; i++) {
4547 			type = stype[(slot - i) % BPF_REG_SIZE];
4548 			if (type == STACK_MISC)
4549 				continue;
4550 			if (type == STACK_ZERO)
4551 				continue;
4552 			if (type == STACK_INVALID && env->allow_uninit_stack)
4553 				continue;
4554 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4555 				off, i, size);
4556 			return -EACCES;
4557 		}
4558 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4559 		if (dst_regno >= 0)
4560 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4561 	}
4562 	return 0;
4563 }
4564 
4565 enum bpf_access_src {
4566 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4567 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4568 };
4569 
4570 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4571 					 int regno, int off, int access_size,
4572 					 bool zero_size_allowed,
4573 					 enum bpf_access_src type,
4574 					 struct bpf_call_arg_meta *meta);
4575 
4576 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4577 {
4578 	return cur_regs(env) + regno;
4579 }
4580 
4581 /* Read the stack at 'ptr_regno + off' and put the result into the register
4582  * 'dst_regno'.
4583  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4584  * but not its variable offset.
4585  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4586  *
4587  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4588  * filling registers (i.e. reads of spilled register cannot be detected when
4589  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4590  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4591  * offset; for a fixed offset check_stack_read_fixed_off should be used
4592  * instead.
4593  */
4594 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4595 				    int ptr_regno, int off, int size, int dst_regno)
4596 {
4597 	/* The state of the source register. */
4598 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4599 	struct bpf_func_state *ptr_state = func(env, reg);
4600 	int err;
4601 	int min_off, max_off;
4602 
4603 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4604 	 */
4605 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4606 					    false, ACCESS_DIRECT, NULL);
4607 	if (err)
4608 		return err;
4609 
4610 	min_off = reg->smin_value + off;
4611 	max_off = reg->smax_value + off;
4612 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4613 	return 0;
4614 }
4615 
4616 /* check_stack_read dispatches to check_stack_read_fixed_off or
4617  * check_stack_read_var_off.
4618  *
4619  * The caller must ensure that the offset falls within the allocated stack
4620  * bounds.
4621  *
4622  * 'dst_regno' is a register which will receive the value from the stack. It
4623  * can be -1, meaning that the read value is not going to a register.
4624  */
4625 static int check_stack_read(struct bpf_verifier_env *env,
4626 			    int ptr_regno, int off, int size,
4627 			    int dst_regno)
4628 {
4629 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4630 	struct bpf_func_state *state = func(env, reg);
4631 	int err;
4632 	/* Some accesses are only permitted with a static offset. */
4633 	bool var_off = !tnum_is_const(reg->var_off);
4634 
4635 	/* The offset is required to be static when reads don't go to a
4636 	 * register, in order to not leak pointers (see
4637 	 * check_stack_read_fixed_off).
4638 	 */
4639 	if (dst_regno < 0 && var_off) {
4640 		char tn_buf[48];
4641 
4642 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4643 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4644 			tn_buf, off, size);
4645 		return -EACCES;
4646 	}
4647 	/* Variable offset is prohibited for unprivileged mode for simplicity
4648 	 * since it requires corresponding support in Spectre masking for stack
4649 	 * ALU. See also retrieve_ptr_limit(). The check in
4650 	 * check_stack_access_for_ptr_arithmetic() called by
4651 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4652 	 * with variable offsets, therefore no check is required here. Further,
4653 	 * just checking it here would be insufficient as speculative stack
4654 	 * writes could still lead to unsafe speculative behaviour.
4655 	 */
4656 	if (!var_off) {
4657 		off += reg->var_off.value;
4658 		err = check_stack_read_fixed_off(env, state, off, size,
4659 						 dst_regno);
4660 	} else {
4661 		/* Variable offset stack reads need more conservative handling
4662 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4663 		 * branch.
4664 		 */
4665 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4666 					       dst_regno);
4667 	}
4668 	return err;
4669 }
4670 
4671 
4672 /* check_stack_write dispatches to check_stack_write_fixed_off or
4673  * check_stack_write_var_off.
4674  *
4675  * 'ptr_regno' is the register used as a pointer into the stack.
4676  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4677  * 'value_regno' is the register whose value we're writing to the stack. It can
4678  * be -1, meaning that we're not writing from a register.
4679  *
4680  * The caller must ensure that the offset falls within the maximum stack size.
4681  */
4682 static int check_stack_write(struct bpf_verifier_env *env,
4683 			     int ptr_regno, int off, int size,
4684 			     int value_regno, int insn_idx)
4685 {
4686 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4687 	struct bpf_func_state *state = func(env, reg);
4688 	int err;
4689 
4690 	if (tnum_is_const(reg->var_off)) {
4691 		off += reg->var_off.value;
4692 		err = check_stack_write_fixed_off(env, state, off, size,
4693 						  value_regno, insn_idx);
4694 	} else {
4695 		/* Variable offset stack reads need more conservative handling
4696 		 * than fixed offset ones.
4697 		 */
4698 		err = check_stack_write_var_off(env, state,
4699 						ptr_regno, off, size,
4700 						value_regno, insn_idx);
4701 	}
4702 	return err;
4703 }
4704 
4705 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4706 				 int off, int size, enum bpf_access_type type)
4707 {
4708 	struct bpf_reg_state *regs = cur_regs(env);
4709 	struct bpf_map *map = regs[regno].map_ptr;
4710 	u32 cap = bpf_map_flags_to_cap(map);
4711 
4712 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4713 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4714 			map->value_size, off, size);
4715 		return -EACCES;
4716 	}
4717 
4718 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4719 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4720 			map->value_size, off, size);
4721 		return -EACCES;
4722 	}
4723 
4724 	return 0;
4725 }
4726 
4727 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4728 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4729 			      int off, int size, u32 mem_size,
4730 			      bool zero_size_allowed)
4731 {
4732 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4733 	struct bpf_reg_state *reg;
4734 
4735 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4736 		return 0;
4737 
4738 	reg = &cur_regs(env)[regno];
4739 	switch (reg->type) {
4740 	case PTR_TO_MAP_KEY:
4741 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4742 			mem_size, off, size);
4743 		break;
4744 	case PTR_TO_MAP_VALUE:
4745 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4746 			mem_size, off, size);
4747 		break;
4748 	case PTR_TO_PACKET:
4749 	case PTR_TO_PACKET_META:
4750 	case PTR_TO_PACKET_END:
4751 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4752 			off, size, regno, reg->id, off, mem_size);
4753 		break;
4754 	case PTR_TO_MEM:
4755 	default:
4756 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4757 			mem_size, off, size);
4758 	}
4759 
4760 	return -EACCES;
4761 }
4762 
4763 /* check read/write into a memory region with possible variable offset */
4764 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4765 				   int off, int size, u32 mem_size,
4766 				   bool zero_size_allowed)
4767 {
4768 	struct bpf_verifier_state *vstate = env->cur_state;
4769 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4770 	struct bpf_reg_state *reg = &state->regs[regno];
4771 	int err;
4772 
4773 	/* We may have adjusted the register pointing to memory region, so we
4774 	 * need to try adding each of min_value and max_value to off
4775 	 * to make sure our theoretical access will be safe.
4776 	 *
4777 	 * The minimum value is only important with signed
4778 	 * comparisons where we can't assume the floor of a
4779 	 * value is 0.  If we are using signed variables for our
4780 	 * index'es we need to make sure that whatever we use
4781 	 * will have a set floor within our range.
4782 	 */
4783 	if (reg->smin_value < 0 &&
4784 	    (reg->smin_value == S64_MIN ||
4785 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4786 	      reg->smin_value + off < 0)) {
4787 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4788 			regno);
4789 		return -EACCES;
4790 	}
4791 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4792 				 mem_size, zero_size_allowed);
4793 	if (err) {
4794 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4795 			regno);
4796 		return err;
4797 	}
4798 
4799 	/* If we haven't set a max value then we need to bail since we can't be
4800 	 * sure we won't do bad things.
4801 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4802 	 */
4803 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4804 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4805 			regno);
4806 		return -EACCES;
4807 	}
4808 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4809 				 mem_size, zero_size_allowed);
4810 	if (err) {
4811 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4812 			regno);
4813 		return err;
4814 	}
4815 
4816 	return 0;
4817 }
4818 
4819 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4820 			       const struct bpf_reg_state *reg, int regno,
4821 			       bool fixed_off_ok)
4822 {
4823 	/* Access to this pointer-typed register or passing it to a helper
4824 	 * is only allowed in its original, unmodified form.
4825 	 */
4826 
4827 	if (reg->off < 0) {
4828 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4829 			reg_type_str(env, reg->type), regno, reg->off);
4830 		return -EACCES;
4831 	}
4832 
4833 	if (!fixed_off_ok && reg->off) {
4834 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4835 			reg_type_str(env, reg->type), regno, reg->off);
4836 		return -EACCES;
4837 	}
4838 
4839 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4840 		char tn_buf[48];
4841 
4842 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4843 		verbose(env, "variable %s access var_off=%s disallowed\n",
4844 			reg_type_str(env, reg->type), tn_buf);
4845 		return -EACCES;
4846 	}
4847 
4848 	return 0;
4849 }
4850 
4851 int check_ptr_off_reg(struct bpf_verifier_env *env,
4852 		      const struct bpf_reg_state *reg, int regno)
4853 {
4854 	return __check_ptr_off_reg(env, reg, regno, false);
4855 }
4856 
4857 static int map_kptr_match_type(struct bpf_verifier_env *env,
4858 			       struct btf_field *kptr_field,
4859 			       struct bpf_reg_state *reg, u32 regno)
4860 {
4861 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4862 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4863 	const char *reg_name = "";
4864 
4865 	/* Only unreferenced case accepts untrusted pointers */
4866 	if (kptr_field->type == BPF_KPTR_UNREF)
4867 		perm_flags |= PTR_UNTRUSTED;
4868 
4869 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4870 		goto bad_type;
4871 
4872 	if (!btf_is_kernel(reg->btf)) {
4873 		verbose(env, "R%d must point to kernel BTF\n", regno);
4874 		return -EINVAL;
4875 	}
4876 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4877 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4878 
4879 	/* For ref_ptr case, release function check should ensure we get one
4880 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4881 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4882 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4883 	 * reg->off and reg->ref_obj_id are not needed here.
4884 	 */
4885 	if (__check_ptr_off_reg(env, reg, regno, true))
4886 		return -EACCES;
4887 
4888 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4889 	 * we also need to take into account the reg->off.
4890 	 *
4891 	 * We want to support cases like:
4892 	 *
4893 	 * struct foo {
4894 	 *         struct bar br;
4895 	 *         struct baz bz;
4896 	 * };
4897 	 *
4898 	 * struct foo *v;
4899 	 * v = func();	      // PTR_TO_BTF_ID
4900 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4901 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4902 	 *                    // first member type of struct after comparison fails
4903 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4904 	 *                    // to match type
4905 	 *
4906 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4907 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4908 	 * the struct to match type against first member of struct, i.e. reject
4909 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4910 	 * strict mode to true for type match.
4911 	 */
4912 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4913 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4914 				  kptr_field->type == BPF_KPTR_REF))
4915 		goto bad_type;
4916 	return 0;
4917 bad_type:
4918 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4919 		reg_type_str(env, reg->type), reg_name);
4920 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4921 	if (kptr_field->type == BPF_KPTR_UNREF)
4922 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4923 			targ_name);
4924 	else
4925 		verbose(env, "\n");
4926 	return -EINVAL;
4927 }
4928 
4929 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4930  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4931  */
4932 static bool in_rcu_cs(struct bpf_verifier_env *env)
4933 {
4934 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4935 }
4936 
4937 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4938 BTF_SET_START(rcu_protected_types)
4939 BTF_ID(struct, prog_test_ref_kfunc)
4940 BTF_ID(struct, cgroup)
4941 BTF_ID(struct, bpf_cpumask)
4942 BTF_ID(struct, task_struct)
4943 BTF_SET_END(rcu_protected_types)
4944 
4945 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4946 {
4947 	if (!btf_is_kernel(btf))
4948 		return false;
4949 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4950 }
4951 
4952 static bool rcu_safe_kptr(const struct btf_field *field)
4953 {
4954 	const struct btf_field_kptr *kptr = &field->kptr;
4955 
4956 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4957 }
4958 
4959 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4960 				 int value_regno, int insn_idx,
4961 				 struct btf_field *kptr_field)
4962 {
4963 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4964 	int class = BPF_CLASS(insn->code);
4965 	struct bpf_reg_state *val_reg;
4966 
4967 	/* Things we already checked for in check_map_access and caller:
4968 	 *  - Reject cases where variable offset may touch kptr
4969 	 *  - size of access (must be BPF_DW)
4970 	 *  - tnum_is_const(reg->var_off)
4971 	 *  - kptr_field->offset == off + reg->var_off.value
4972 	 */
4973 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4974 	if (BPF_MODE(insn->code) != BPF_MEM) {
4975 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4976 		return -EACCES;
4977 	}
4978 
4979 	/* We only allow loading referenced kptr, since it will be marked as
4980 	 * untrusted, similar to unreferenced kptr.
4981 	 */
4982 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4983 		verbose(env, "store to referenced kptr disallowed\n");
4984 		return -EACCES;
4985 	}
4986 
4987 	if (class == BPF_LDX) {
4988 		val_reg = reg_state(env, value_regno);
4989 		/* We can simply mark the value_regno receiving the pointer
4990 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4991 		 */
4992 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4993 				kptr_field->kptr.btf_id,
4994 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4995 				PTR_MAYBE_NULL | MEM_RCU :
4996 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
4997 		/* For mark_ptr_or_null_reg */
4998 		val_reg->id = ++env->id_gen;
4999 	} else if (class == BPF_STX) {
5000 		val_reg = reg_state(env, value_regno);
5001 		if (!register_is_null(val_reg) &&
5002 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5003 			return -EACCES;
5004 	} else if (class == BPF_ST) {
5005 		if (insn->imm) {
5006 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5007 				kptr_field->offset);
5008 			return -EACCES;
5009 		}
5010 	} else {
5011 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5012 		return -EACCES;
5013 	}
5014 	return 0;
5015 }
5016 
5017 /* check read/write into a map element with possible variable offset */
5018 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5019 			    int off, int size, bool zero_size_allowed,
5020 			    enum bpf_access_src src)
5021 {
5022 	struct bpf_verifier_state *vstate = env->cur_state;
5023 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5024 	struct bpf_reg_state *reg = &state->regs[regno];
5025 	struct bpf_map *map = reg->map_ptr;
5026 	struct btf_record *rec;
5027 	int err, i;
5028 
5029 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5030 				      zero_size_allowed);
5031 	if (err)
5032 		return err;
5033 
5034 	if (IS_ERR_OR_NULL(map->record))
5035 		return 0;
5036 	rec = map->record;
5037 	for (i = 0; i < rec->cnt; i++) {
5038 		struct btf_field *field = &rec->fields[i];
5039 		u32 p = field->offset;
5040 
5041 		/* If any part of a field  can be touched by load/store, reject
5042 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5043 		 * it is sufficient to check x1 < y2 && y1 < x2.
5044 		 */
5045 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5046 		    p < reg->umax_value + off + size) {
5047 			switch (field->type) {
5048 			case BPF_KPTR_UNREF:
5049 			case BPF_KPTR_REF:
5050 				if (src != ACCESS_DIRECT) {
5051 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5052 					return -EACCES;
5053 				}
5054 				if (!tnum_is_const(reg->var_off)) {
5055 					verbose(env, "kptr access cannot have variable offset\n");
5056 					return -EACCES;
5057 				}
5058 				if (p != off + reg->var_off.value) {
5059 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5060 						p, off + reg->var_off.value);
5061 					return -EACCES;
5062 				}
5063 				if (size != bpf_size_to_bytes(BPF_DW)) {
5064 					verbose(env, "kptr access size must be BPF_DW\n");
5065 					return -EACCES;
5066 				}
5067 				break;
5068 			default:
5069 				verbose(env, "%s cannot be accessed directly by load/store\n",
5070 					btf_field_type_name(field->type));
5071 				return -EACCES;
5072 			}
5073 		}
5074 	}
5075 	return 0;
5076 }
5077 
5078 #define MAX_PACKET_OFF 0xffff
5079 
5080 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5081 				       const struct bpf_call_arg_meta *meta,
5082 				       enum bpf_access_type t)
5083 {
5084 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5085 
5086 	switch (prog_type) {
5087 	/* Program types only with direct read access go here! */
5088 	case BPF_PROG_TYPE_LWT_IN:
5089 	case BPF_PROG_TYPE_LWT_OUT:
5090 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5091 	case BPF_PROG_TYPE_SK_REUSEPORT:
5092 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5093 	case BPF_PROG_TYPE_CGROUP_SKB:
5094 		if (t == BPF_WRITE)
5095 			return false;
5096 		fallthrough;
5097 
5098 	/* Program types with direct read + write access go here! */
5099 	case BPF_PROG_TYPE_SCHED_CLS:
5100 	case BPF_PROG_TYPE_SCHED_ACT:
5101 	case BPF_PROG_TYPE_XDP:
5102 	case BPF_PROG_TYPE_LWT_XMIT:
5103 	case BPF_PROG_TYPE_SK_SKB:
5104 	case BPF_PROG_TYPE_SK_MSG:
5105 		if (meta)
5106 			return meta->pkt_access;
5107 
5108 		env->seen_direct_write = true;
5109 		return true;
5110 
5111 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5112 		if (t == BPF_WRITE)
5113 			env->seen_direct_write = true;
5114 
5115 		return true;
5116 
5117 	default:
5118 		return false;
5119 	}
5120 }
5121 
5122 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5123 			       int size, bool zero_size_allowed)
5124 {
5125 	struct bpf_reg_state *regs = cur_regs(env);
5126 	struct bpf_reg_state *reg = &regs[regno];
5127 	int err;
5128 
5129 	/* We may have added a variable offset to the packet pointer; but any
5130 	 * reg->range we have comes after that.  We are only checking the fixed
5131 	 * offset.
5132 	 */
5133 
5134 	/* We don't allow negative numbers, because we aren't tracking enough
5135 	 * detail to prove they're safe.
5136 	 */
5137 	if (reg->smin_value < 0) {
5138 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5139 			regno);
5140 		return -EACCES;
5141 	}
5142 
5143 	err = reg->range < 0 ? -EINVAL :
5144 	      __check_mem_access(env, regno, off, size, reg->range,
5145 				 zero_size_allowed);
5146 	if (err) {
5147 		verbose(env, "R%d offset is outside of the packet\n", regno);
5148 		return err;
5149 	}
5150 
5151 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5152 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5153 	 * otherwise find_good_pkt_pointers would have refused to set range info
5154 	 * that __check_mem_access would have rejected this pkt access.
5155 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5156 	 */
5157 	env->prog->aux->max_pkt_offset =
5158 		max_t(u32, env->prog->aux->max_pkt_offset,
5159 		      off + reg->umax_value + size - 1);
5160 
5161 	return err;
5162 }
5163 
5164 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5165 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5166 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5167 			    struct btf **btf, u32 *btf_id)
5168 {
5169 	struct bpf_insn_access_aux info = {
5170 		.reg_type = *reg_type,
5171 		.log = &env->log,
5172 	};
5173 
5174 	if (env->ops->is_valid_access &&
5175 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5176 		/* A non zero info.ctx_field_size indicates that this field is a
5177 		 * candidate for later verifier transformation to load the whole
5178 		 * field and then apply a mask when accessed with a narrower
5179 		 * access than actual ctx access size. A zero info.ctx_field_size
5180 		 * will only allow for whole field access and rejects any other
5181 		 * type of narrower access.
5182 		 */
5183 		*reg_type = info.reg_type;
5184 
5185 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5186 			*btf = info.btf;
5187 			*btf_id = info.btf_id;
5188 		} else {
5189 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5190 		}
5191 		/* remember the offset of last byte accessed in ctx */
5192 		if (env->prog->aux->max_ctx_offset < off + size)
5193 			env->prog->aux->max_ctx_offset = off + size;
5194 		return 0;
5195 	}
5196 
5197 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5198 	return -EACCES;
5199 }
5200 
5201 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5202 				  int size)
5203 {
5204 	if (size < 0 || off < 0 ||
5205 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5206 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5207 			off, size);
5208 		return -EACCES;
5209 	}
5210 	return 0;
5211 }
5212 
5213 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5214 			     u32 regno, int off, int size,
5215 			     enum bpf_access_type t)
5216 {
5217 	struct bpf_reg_state *regs = cur_regs(env);
5218 	struct bpf_reg_state *reg = &regs[regno];
5219 	struct bpf_insn_access_aux info = {};
5220 	bool valid;
5221 
5222 	if (reg->smin_value < 0) {
5223 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5224 			regno);
5225 		return -EACCES;
5226 	}
5227 
5228 	switch (reg->type) {
5229 	case PTR_TO_SOCK_COMMON:
5230 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5231 		break;
5232 	case PTR_TO_SOCKET:
5233 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5234 		break;
5235 	case PTR_TO_TCP_SOCK:
5236 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5237 		break;
5238 	case PTR_TO_XDP_SOCK:
5239 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5240 		break;
5241 	default:
5242 		valid = false;
5243 	}
5244 
5245 
5246 	if (valid) {
5247 		env->insn_aux_data[insn_idx].ctx_field_size =
5248 			info.ctx_field_size;
5249 		return 0;
5250 	}
5251 
5252 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5253 		regno, reg_type_str(env, reg->type), off, size);
5254 
5255 	return -EACCES;
5256 }
5257 
5258 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5259 {
5260 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5261 }
5262 
5263 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5264 {
5265 	const struct bpf_reg_state *reg = reg_state(env, regno);
5266 
5267 	return reg->type == PTR_TO_CTX;
5268 }
5269 
5270 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5271 {
5272 	const struct bpf_reg_state *reg = reg_state(env, regno);
5273 
5274 	return type_is_sk_pointer(reg->type);
5275 }
5276 
5277 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5278 {
5279 	const struct bpf_reg_state *reg = reg_state(env, regno);
5280 
5281 	return type_is_pkt_pointer(reg->type);
5282 }
5283 
5284 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5285 {
5286 	const struct bpf_reg_state *reg = reg_state(env, regno);
5287 
5288 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5289 	return reg->type == PTR_TO_FLOW_KEYS;
5290 }
5291 
5292 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5293 {
5294 	/* A referenced register is always trusted. */
5295 	if (reg->ref_obj_id)
5296 		return true;
5297 
5298 	/* If a register is not referenced, it is trusted if it has the
5299 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5300 	 * other type modifiers may be safe, but we elect to take an opt-in
5301 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5302 	 * not.
5303 	 *
5304 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5305 	 * for whether a register is trusted.
5306 	 */
5307 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5308 	       !bpf_type_has_unsafe_modifiers(reg->type);
5309 }
5310 
5311 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5312 {
5313 	return reg->type & MEM_RCU;
5314 }
5315 
5316 static void clear_trusted_flags(enum bpf_type_flag *flag)
5317 {
5318 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5319 }
5320 
5321 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5322 				   const struct bpf_reg_state *reg,
5323 				   int off, int size, bool strict)
5324 {
5325 	struct tnum reg_off;
5326 	int ip_align;
5327 
5328 	/* Byte size accesses are always allowed. */
5329 	if (!strict || size == 1)
5330 		return 0;
5331 
5332 	/* For platforms that do not have a Kconfig enabling
5333 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5334 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5335 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5336 	 * to this code only in strict mode where we want to emulate
5337 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5338 	 * unconditional IP align value of '2'.
5339 	 */
5340 	ip_align = 2;
5341 
5342 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5343 	if (!tnum_is_aligned(reg_off, size)) {
5344 		char tn_buf[48];
5345 
5346 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5347 		verbose(env,
5348 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5349 			ip_align, tn_buf, reg->off, off, size);
5350 		return -EACCES;
5351 	}
5352 
5353 	return 0;
5354 }
5355 
5356 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5357 				       const struct bpf_reg_state *reg,
5358 				       const char *pointer_desc,
5359 				       int off, int size, bool strict)
5360 {
5361 	struct tnum reg_off;
5362 
5363 	/* Byte size accesses are always allowed. */
5364 	if (!strict || size == 1)
5365 		return 0;
5366 
5367 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5368 	if (!tnum_is_aligned(reg_off, size)) {
5369 		char tn_buf[48];
5370 
5371 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5372 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5373 			pointer_desc, tn_buf, reg->off, off, size);
5374 		return -EACCES;
5375 	}
5376 
5377 	return 0;
5378 }
5379 
5380 static int check_ptr_alignment(struct bpf_verifier_env *env,
5381 			       const struct bpf_reg_state *reg, int off,
5382 			       int size, bool strict_alignment_once)
5383 {
5384 	bool strict = env->strict_alignment || strict_alignment_once;
5385 	const char *pointer_desc = "";
5386 
5387 	switch (reg->type) {
5388 	case PTR_TO_PACKET:
5389 	case PTR_TO_PACKET_META:
5390 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5391 		 * right in front, treat it the very same way.
5392 		 */
5393 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5394 	case PTR_TO_FLOW_KEYS:
5395 		pointer_desc = "flow keys ";
5396 		break;
5397 	case PTR_TO_MAP_KEY:
5398 		pointer_desc = "key ";
5399 		break;
5400 	case PTR_TO_MAP_VALUE:
5401 		pointer_desc = "value ";
5402 		break;
5403 	case PTR_TO_CTX:
5404 		pointer_desc = "context ";
5405 		break;
5406 	case PTR_TO_STACK:
5407 		pointer_desc = "stack ";
5408 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5409 		 * and check_stack_read_fixed_off() relies on stack accesses being
5410 		 * aligned.
5411 		 */
5412 		strict = true;
5413 		break;
5414 	case PTR_TO_SOCKET:
5415 		pointer_desc = "sock ";
5416 		break;
5417 	case PTR_TO_SOCK_COMMON:
5418 		pointer_desc = "sock_common ";
5419 		break;
5420 	case PTR_TO_TCP_SOCK:
5421 		pointer_desc = "tcp_sock ";
5422 		break;
5423 	case PTR_TO_XDP_SOCK:
5424 		pointer_desc = "xdp_sock ";
5425 		break;
5426 	default:
5427 		break;
5428 	}
5429 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5430 					   strict);
5431 }
5432 
5433 static int update_stack_depth(struct bpf_verifier_env *env,
5434 			      const struct bpf_func_state *func,
5435 			      int off)
5436 {
5437 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5438 
5439 	if (stack >= -off)
5440 		return 0;
5441 
5442 	/* update known max for given subprogram */
5443 	env->subprog_info[func->subprogno].stack_depth = -off;
5444 	return 0;
5445 }
5446 
5447 /* starting from main bpf function walk all instructions of the function
5448  * and recursively walk all callees that given function can call.
5449  * Ignore jump and exit insns.
5450  * Since recursion is prevented by check_cfg() this algorithm
5451  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5452  */
5453 static int check_max_stack_depth(struct bpf_verifier_env *env)
5454 {
5455 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5456 	struct bpf_subprog_info *subprog = env->subprog_info;
5457 	struct bpf_insn *insn = env->prog->insnsi;
5458 	bool tail_call_reachable = false;
5459 	int ret_insn[MAX_CALL_FRAMES];
5460 	int ret_prog[MAX_CALL_FRAMES];
5461 	int j;
5462 
5463 process_func:
5464 	/* protect against potential stack overflow that might happen when
5465 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5466 	 * depth for such case down to 256 so that the worst case scenario
5467 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5468 	 * 8k).
5469 	 *
5470 	 * To get the idea what might happen, see an example:
5471 	 * func1 -> sub rsp, 128
5472 	 *  subfunc1 -> sub rsp, 256
5473 	 *  tailcall1 -> add rsp, 256
5474 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5475 	 *   subfunc2 -> sub rsp, 64
5476 	 *   subfunc22 -> sub rsp, 128
5477 	 *   tailcall2 -> add rsp, 128
5478 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5479 	 *
5480 	 * tailcall will unwind the current stack frame but it will not get rid
5481 	 * of caller's stack as shown on the example above.
5482 	 */
5483 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5484 		verbose(env,
5485 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5486 			depth);
5487 		return -EACCES;
5488 	}
5489 	/* round up to 32-bytes, since this is granularity
5490 	 * of interpreter stack size
5491 	 */
5492 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5493 	if (depth > MAX_BPF_STACK) {
5494 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5495 			frame + 1, depth);
5496 		return -EACCES;
5497 	}
5498 continue_func:
5499 	subprog_end = subprog[idx + 1].start;
5500 	for (; i < subprog_end; i++) {
5501 		int next_insn;
5502 
5503 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5504 			continue;
5505 		/* remember insn and function to return to */
5506 		ret_insn[frame] = i + 1;
5507 		ret_prog[frame] = idx;
5508 
5509 		/* find the callee */
5510 		next_insn = i + insn[i].imm + 1;
5511 		idx = find_subprog(env, next_insn);
5512 		if (idx < 0) {
5513 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5514 				  next_insn);
5515 			return -EFAULT;
5516 		}
5517 		if (subprog[idx].is_async_cb) {
5518 			if (subprog[idx].has_tail_call) {
5519 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5520 				return -EFAULT;
5521 			}
5522 			 /* async callbacks don't increase bpf prog stack size */
5523 			continue;
5524 		}
5525 		i = next_insn;
5526 
5527 		if (subprog[idx].has_tail_call)
5528 			tail_call_reachable = true;
5529 
5530 		frame++;
5531 		if (frame >= MAX_CALL_FRAMES) {
5532 			verbose(env, "the call stack of %d frames is too deep !\n",
5533 				frame);
5534 			return -E2BIG;
5535 		}
5536 		goto process_func;
5537 	}
5538 	/* if tail call got detected across bpf2bpf calls then mark each of the
5539 	 * currently present subprog frames as tail call reachable subprogs;
5540 	 * this info will be utilized by JIT so that we will be preserving the
5541 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5542 	 */
5543 	if (tail_call_reachable)
5544 		for (j = 0; j < frame; j++)
5545 			subprog[ret_prog[j]].tail_call_reachable = true;
5546 	if (subprog[0].tail_call_reachable)
5547 		env->prog->aux->tail_call_reachable = true;
5548 
5549 	/* end of for() loop means the last insn of the 'subprog'
5550 	 * was reached. Doesn't matter whether it was JA or EXIT
5551 	 */
5552 	if (frame == 0)
5553 		return 0;
5554 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5555 	frame--;
5556 	i = ret_insn[frame];
5557 	idx = ret_prog[frame];
5558 	goto continue_func;
5559 }
5560 
5561 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5562 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5563 				  const struct bpf_insn *insn, int idx)
5564 {
5565 	int start = idx + insn->imm + 1, subprog;
5566 
5567 	subprog = find_subprog(env, start);
5568 	if (subprog < 0) {
5569 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5570 			  start);
5571 		return -EFAULT;
5572 	}
5573 	return env->subprog_info[subprog].stack_depth;
5574 }
5575 #endif
5576 
5577 static int __check_buffer_access(struct bpf_verifier_env *env,
5578 				 const char *buf_info,
5579 				 const struct bpf_reg_state *reg,
5580 				 int regno, int off, int size)
5581 {
5582 	if (off < 0) {
5583 		verbose(env,
5584 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5585 			regno, buf_info, off, size);
5586 		return -EACCES;
5587 	}
5588 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5589 		char tn_buf[48];
5590 
5591 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5592 		verbose(env,
5593 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5594 			regno, off, tn_buf);
5595 		return -EACCES;
5596 	}
5597 
5598 	return 0;
5599 }
5600 
5601 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5602 				  const struct bpf_reg_state *reg,
5603 				  int regno, int off, int size)
5604 {
5605 	int err;
5606 
5607 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5608 	if (err)
5609 		return err;
5610 
5611 	if (off + size > env->prog->aux->max_tp_access)
5612 		env->prog->aux->max_tp_access = off + size;
5613 
5614 	return 0;
5615 }
5616 
5617 static int check_buffer_access(struct bpf_verifier_env *env,
5618 			       const struct bpf_reg_state *reg,
5619 			       int regno, int off, int size,
5620 			       bool zero_size_allowed,
5621 			       u32 *max_access)
5622 {
5623 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5624 	int err;
5625 
5626 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5627 	if (err)
5628 		return err;
5629 
5630 	if (off + size > *max_access)
5631 		*max_access = off + size;
5632 
5633 	return 0;
5634 }
5635 
5636 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5637 static void zext_32_to_64(struct bpf_reg_state *reg)
5638 {
5639 	reg->var_off = tnum_subreg(reg->var_off);
5640 	__reg_assign_32_into_64(reg);
5641 }
5642 
5643 /* truncate register to smaller size (in bytes)
5644  * must be called with size < BPF_REG_SIZE
5645  */
5646 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5647 {
5648 	u64 mask;
5649 
5650 	/* clear high bits in bit representation */
5651 	reg->var_off = tnum_cast(reg->var_off, size);
5652 
5653 	/* fix arithmetic bounds */
5654 	mask = ((u64)1 << (size * 8)) - 1;
5655 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5656 		reg->umin_value &= mask;
5657 		reg->umax_value &= mask;
5658 	} else {
5659 		reg->umin_value = 0;
5660 		reg->umax_value = mask;
5661 	}
5662 	reg->smin_value = reg->umin_value;
5663 	reg->smax_value = reg->umax_value;
5664 
5665 	/* If size is smaller than 32bit register the 32bit register
5666 	 * values are also truncated so we push 64-bit bounds into
5667 	 * 32-bit bounds. Above were truncated < 32-bits already.
5668 	 */
5669 	if (size >= 4)
5670 		return;
5671 	__reg_combine_64_into_32(reg);
5672 }
5673 
5674 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5675 {
5676 	/* A map is considered read-only if the following condition are true:
5677 	 *
5678 	 * 1) BPF program side cannot change any of the map content. The
5679 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5680 	 *    and was set at map creation time.
5681 	 * 2) The map value(s) have been initialized from user space by a
5682 	 *    loader and then "frozen", such that no new map update/delete
5683 	 *    operations from syscall side are possible for the rest of
5684 	 *    the map's lifetime from that point onwards.
5685 	 * 3) Any parallel/pending map update/delete operations from syscall
5686 	 *    side have been completed. Only after that point, it's safe to
5687 	 *    assume that map value(s) are immutable.
5688 	 */
5689 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5690 	       READ_ONCE(map->frozen) &&
5691 	       !bpf_map_write_active(map);
5692 }
5693 
5694 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5695 {
5696 	void *ptr;
5697 	u64 addr;
5698 	int err;
5699 
5700 	err = map->ops->map_direct_value_addr(map, &addr, off);
5701 	if (err)
5702 		return err;
5703 	ptr = (void *)(long)addr + off;
5704 
5705 	switch (size) {
5706 	case sizeof(u8):
5707 		*val = (u64)*(u8 *)ptr;
5708 		break;
5709 	case sizeof(u16):
5710 		*val = (u64)*(u16 *)ptr;
5711 		break;
5712 	case sizeof(u32):
5713 		*val = (u64)*(u32 *)ptr;
5714 		break;
5715 	case sizeof(u64):
5716 		*val = *(u64 *)ptr;
5717 		break;
5718 	default:
5719 		return -EINVAL;
5720 	}
5721 	return 0;
5722 }
5723 
5724 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5725 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5726 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5727 
5728 /*
5729  * Allow list few fields as RCU trusted or full trusted.
5730  * This logic doesn't allow mix tagging and will be removed once GCC supports
5731  * btf_type_tag.
5732  */
5733 
5734 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5735 BTF_TYPE_SAFE_RCU(struct task_struct) {
5736 	const cpumask_t *cpus_ptr;
5737 	struct css_set __rcu *cgroups;
5738 	struct task_struct __rcu *real_parent;
5739 	struct task_struct *group_leader;
5740 };
5741 
5742 BTF_TYPE_SAFE_RCU(struct cgroup) {
5743 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5744 	struct kernfs_node *kn;
5745 };
5746 
5747 BTF_TYPE_SAFE_RCU(struct css_set) {
5748 	struct cgroup *dfl_cgrp;
5749 };
5750 
5751 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5752 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5753 	struct file __rcu *exe_file;
5754 };
5755 
5756 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5757  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5758  */
5759 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5760 	struct sock *sk;
5761 };
5762 
5763 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5764 	struct sock *sk;
5765 };
5766 
5767 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5768 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5769 	struct seq_file *seq;
5770 };
5771 
5772 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5773 	struct bpf_iter_meta *meta;
5774 	struct task_struct *task;
5775 };
5776 
5777 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5778 	struct file *file;
5779 };
5780 
5781 BTF_TYPE_SAFE_TRUSTED(struct file) {
5782 	struct inode *f_inode;
5783 };
5784 
5785 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5786 	/* no negative dentry-s in places where bpf can see it */
5787 	struct inode *d_inode;
5788 };
5789 
5790 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5791 	struct sock *sk;
5792 };
5793 
5794 static bool type_is_rcu(struct bpf_verifier_env *env,
5795 			struct bpf_reg_state *reg,
5796 			const char *field_name, u32 btf_id)
5797 {
5798 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5799 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5800 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5801 
5802 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5803 }
5804 
5805 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5806 				struct bpf_reg_state *reg,
5807 				const char *field_name, u32 btf_id)
5808 {
5809 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5810 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5811 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5812 
5813 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5814 }
5815 
5816 static bool type_is_trusted(struct bpf_verifier_env *env,
5817 			    struct bpf_reg_state *reg,
5818 			    const char *field_name, u32 btf_id)
5819 {
5820 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5821 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5822 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5823 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5824 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5825 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5826 
5827 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5828 }
5829 
5830 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5831 				   struct bpf_reg_state *regs,
5832 				   int regno, int off, int size,
5833 				   enum bpf_access_type atype,
5834 				   int value_regno)
5835 {
5836 	struct bpf_reg_state *reg = regs + regno;
5837 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5838 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5839 	const char *field_name = NULL;
5840 	enum bpf_type_flag flag = 0;
5841 	u32 btf_id = 0;
5842 	int ret;
5843 
5844 	if (!env->allow_ptr_leaks) {
5845 		verbose(env,
5846 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5847 			tname);
5848 		return -EPERM;
5849 	}
5850 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5851 		verbose(env,
5852 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5853 			tname);
5854 		return -EINVAL;
5855 	}
5856 	if (off < 0) {
5857 		verbose(env,
5858 			"R%d is ptr_%s invalid negative access: off=%d\n",
5859 			regno, tname, off);
5860 		return -EACCES;
5861 	}
5862 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5863 		char tn_buf[48];
5864 
5865 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5866 		verbose(env,
5867 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5868 			regno, tname, off, tn_buf);
5869 		return -EACCES;
5870 	}
5871 
5872 	if (reg->type & MEM_USER) {
5873 		verbose(env,
5874 			"R%d is ptr_%s access user memory: off=%d\n",
5875 			regno, tname, off);
5876 		return -EACCES;
5877 	}
5878 
5879 	if (reg->type & MEM_PERCPU) {
5880 		verbose(env,
5881 			"R%d is ptr_%s access percpu memory: off=%d\n",
5882 			regno, tname, off);
5883 		return -EACCES;
5884 	}
5885 
5886 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5887 		if (!btf_is_kernel(reg->btf)) {
5888 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5889 			return -EFAULT;
5890 		}
5891 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5892 	} else {
5893 		/* Writes are permitted with default btf_struct_access for
5894 		 * program allocated objects (which always have ref_obj_id > 0),
5895 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5896 		 */
5897 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5898 			verbose(env, "only read is supported\n");
5899 			return -EACCES;
5900 		}
5901 
5902 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5903 		    !reg->ref_obj_id) {
5904 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5905 			return -EFAULT;
5906 		}
5907 
5908 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5909 	}
5910 
5911 	if (ret < 0)
5912 		return ret;
5913 
5914 	if (ret != PTR_TO_BTF_ID) {
5915 		/* just mark; */
5916 
5917 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5918 		/* If this is an untrusted pointer, all pointers formed by walking it
5919 		 * also inherit the untrusted flag.
5920 		 */
5921 		flag = PTR_UNTRUSTED;
5922 
5923 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5924 		/* By default any pointer obtained from walking a trusted pointer is no
5925 		 * longer trusted, unless the field being accessed has explicitly been
5926 		 * marked as inheriting its parent's state of trust (either full or RCU).
5927 		 * For example:
5928 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
5929 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
5930 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5931 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5932 		 *
5933 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
5934 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
5935 		 */
5936 		if (type_is_trusted(env, reg, field_name, btf_id)) {
5937 			flag |= PTR_TRUSTED;
5938 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5939 			if (type_is_rcu(env, reg, field_name, btf_id)) {
5940 				/* ignore __rcu tag and mark it MEM_RCU */
5941 				flag |= MEM_RCU;
5942 			} else if (flag & MEM_RCU ||
5943 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5944 				/* __rcu tagged pointers can be NULL */
5945 				flag |= MEM_RCU | PTR_MAYBE_NULL;
5946 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
5947 				/* keep as-is */
5948 			} else {
5949 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5950 				clear_trusted_flags(&flag);
5951 			}
5952 		} else {
5953 			/*
5954 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
5955 			 * aggressively mark as untrusted otherwise such
5956 			 * pointers will be plain PTR_TO_BTF_ID without flags
5957 			 * and will be allowed to be passed into helpers for
5958 			 * compat reasons.
5959 			 */
5960 			flag = PTR_UNTRUSTED;
5961 		}
5962 	} else {
5963 		/* Old compat. Deprecated */
5964 		clear_trusted_flags(&flag);
5965 	}
5966 
5967 	if (atype == BPF_READ && value_regno >= 0)
5968 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5969 
5970 	return 0;
5971 }
5972 
5973 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5974 				   struct bpf_reg_state *regs,
5975 				   int regno, int off, int size,
5976 				   enum bpf_access_type atype,
5977 				   int value_regno)
5978 {
5979 	struct bpf_reg_state *reg = regs + regno;
5980 	struct bpf_map *map = reg->map_ptr;
5981 	struct bpf_reg_state map_reg;
5982 	enum bpf_type_flag flag = 0;
5983 	const struct btf_type *t;
5984 	const char *tname;
5985 	u32 btf_id;
5986 	int ret;
5987 
5988 	if (!btf_vmlinux) {
5989 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5990 		return -ENOTSUPP;
5991 	}
5992 
5993 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5994 		verbose(env, "map_ptr access not supported for map type %d\n",
5995 			map->map_type);
5996 		return -ENOTSUPP;
5997 	}
5998 
5999 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6000 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6001 
6002 	if (!env->allow_ptr_leaks) {
6003 		verbose(env,
6004 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6005 			tname);
6006 		return -EPERM;
6007 	}
6008 
6009 	if (off < 0) {
6010 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6011 			regno, tname, off);
6012 		return -EACCES;
6013 	}
6014 
6015 	if (atype != BPF_READ) {
6016 		verbose(env, "only read from %s is supported\n", tname);
6017 		return -EACCES;
6018 	}
6019 
6020 	/* Simulate access to a PTR_TO_BTF_ID */
6021 	memset(&map_reg, 0, sizeof(map_reg));
6022 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6023 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6024 	if (ret < 0)
6025 		return ret;
6026 
6027 	if (value_regno >= 0)
6028 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6029 
6030 	return 0;
6031 }
6032 
6033 /* Check that the stack access at the given offset is within bounds. The
6034  * maximum valid offset is -1.
6035  *
6036  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6037  * -state->allocated_stack for reads.
6038  */
6039 static int check_stack_slot_within_bounds(int off,
6040 					  struct bpf_func_state *state,
6041 					  enum bpf_access_type t)
6042 {
6043 	int min_valid_off;
6044 
6045 	if (t == BPF_WRITE)
6046 		min_valid_off = -MAX_BPF_STACK;
6047 	else
6048 		min_valid_off = -state->allocated_stack;
6049 
6050 	if (off < min_valid_off || off > -1)
6051 		return -EACCES;
6052 	return 0;
6053 }
6054 
6055 /* Check that the stack access at 'regno + off' falls within the maximum stack
6056  * bounds.
6057  *
6058  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6059  */
6060 static int check_stack_access_within_bounds(
6061 		struct bpf_verifier_env *env,
6062 		int regno, int off, int access_size,
6063 		enum bpf_access_src src, enum bpf_access_type type)
6064 {
6065 	struct bpf_reg_state *regs = cur_regs(env);
6066 	struct bpf_reg_state *reg = regs + regno;
6067 	struct bpf_func_state *state = func(env, reg);
6068 	int min_off, max_off;
6069 	int err;
6070 	char *err_extra;
6071 
6072 	if (src == ACCESS_HELPER)
6073 		/* We don't know if helpers are reading or writing (or both). */
6074 		err_extra = " indirect access to";
6075 	else if (type == BPF_READ)
6076 		err_extra = " read from";
6077 	else
6078 		err_extra = " write to";
6079 
6080 	if (tnum_is_const(reg->var_off)) {
6081 		min_off = reg->var_off.value + off;
6082 		if (access_size > 0)
6083 			max_off = min_off + access_size - 1;
6084 		else
6085 			max_off = min_off;
6086 	} else {
6087 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6088 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6089 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6090 				err_extra, regno);
6091 			return -EACCES;
6092 		}
6093 		min_off = reg->smin_value + off;
6094 		if (access_size > 0)
6095 			max_off = reg->smax_value + off + access_size - 1;
6096 		else
6097 			max_off = min_off;
6098 	}
6099 
6100 	err = check_stack_slot_within_bounds(min_off, state, type);
6101 	if (!err)
6102 		err = check_stack_slot_within_bounds(max_off, state, type);
6103 
6104 	if (err) {
6105 		if (tnum_is_const(reg->var_off)) {
6106 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6107 				err_extra, regno, off, access_size);
6108 		} else {
6109 			char tn_buf[48];
6110 
6111 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6112 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6113 				err_extra, regno, tn_buf, access_size);
6114 		}
6115 	}
6116 	return err;
6117 }
6118 
6119 /* check whether memory at (regno + off) is accessible for t = (read | write)
6120  * if t==write, value_regno is a register which value is stored into memory
6121  * if t==read, value_regno is a register which will receive the value from memory
6122  * if t==write && value_regno==-1, some unknown value is stored into memory
6123  * if t==read && value_regno==-1, don't care what we read from memory
6124  */
6125 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6126 			    int off, int bpf_size, enum bpf_access_type t,
6127 			    int value_regno, bool strict_alignment_once)
6128 {
6129 	struct bpf_reg_state *regs = cur_regs(env);
6130 	struct bpf_reg_state *reg = regs + regno;
6131 	struct bpf_func_state *state;
6132 	int size, err = 0;
6133 
6134 	size = bpf_size_to_bytes(bpf_size);
6135 	if (size < 0)
6136 		return size;
6137 
6138 	/* alignment checks will add in reg->off themselves */
6139 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6140 	if (err)
6141 		return err;
6142 
6143 	/* for access checks, reg->off is just part of off */
6144 	off += reg->off;
6145 
6146 	if (reg->type == PTR_TO_MAP_KEY) {
6147 		if (t == BPF_WRITE) {
6148 			verbose(env, "write to change key R%d not allowed\n", regno);
6149 			return -EACCES;
6150 		}
6151 
6152 		err = check_mem_region_access(env, regno, off, size,
6153 					      reg->map_ptr->key_size, false);
6154 		if (err)
6155 			return err;
6156 		if (value_regno >= 0)
6157 			mark_reg_unknown(env, regs, value_regno);
6158 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6159 		struct btf_field *kptr_field = NULL;
6160 
6161 		if (t == BPF_WRITE && value_regno >= 0 &&
6162 		    is_pointer_value(env, value_regno)) {
6163 			verbose(env, "R%d leaks addr into map\n", value_regno);
6164 			return -EACCES;
6165 		}
6166 		err = check_map_access_type(env, regno, off, size, t);
6167 		if (err)
6168 			return err;
6169 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6170 		if (err)
6171 			return err;
6172 		if (tnum_is_const(reg->var_off))
6173 			kptr_field = btf_record_find(reg->map_ptr->record,
6174 						     off + reg->var_off.value, BPF_KPTR);
6175 		if (kptr_field) {
6176 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6177 		} else if (t == BPF_READ && value_regno >= 0) {
6178 			struct bpf_map *map = reg->map_ptr;
6179 
6180 			/* if map is read-only, track its contents as scalars */
6181 			if (tnum_is_const(reg->var_off) &&
6182 			    bpf_map_is_rdonly(map) &&
6183 			    map->ops->map_direct_value_addr) {
6184 				int map_off = off + reg->var_off.value;
6185 				u64 val = 0;
6186 
6187 				err = bpf_map_direct_read(map, map_off, size,
6188 							  &val);
6189 				if (err)
6190 					return err;
6191 
6192 				regs[value_regno].type = SCALAR_VALUE;
6193 				__mark_reg_known(&regs[value_regno], val);
6194 			} else {
6195 				mark_reg_unknown(env, regs, value_regno);
6196 			}
6197 		}
6198 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6199 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6200 
6201 		if (type_may_be_null(reg->type)) {
6202 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6203 				reg_type_str(env, reg->type));
6204 			return -EACCES;
6205 		}
6206 
6207 		if (t == BPF_WRITE && rdonly_mem) {
6208 			verbose(env, "R%d cannot write into %s\n",
6209 				regno, reg_type_str(env, reg->type));
6210 			return -EACCES;
6211 		}
6212 
6213 		if (t == BPF_WRITE && value_regno >= 0 &&
6214 		    is_pointer_value(env, value_regno)) {
6215 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6216 			return -EACCES;
6217 		}
6218 
6219 		err = check_mem_region_access(env, regno, off, size,
6220 					      reg->mem_size, false);
6221 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6222 			mark_reg_unknown(env, regs, value_regno);
6223 	} else if (reg->type == PTR_TO_CTX) {
6224 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6225 		struct btf *btf = NULL;
6226 		u32 btf_id = 0;
6227 
6228 		if (t == BPF_WRITE && value_regno >= 0 &&
6229 		    is_pointer_value(env, value_regno)) {
6230 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6231 			return -EACCES;
6232 		}
6233 
6234 		err = check_ptr_off_reg(env, reg, regno);
6235 		if (err < 0)
6236 			return err;
6237 
6238 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6239 				       &btf_id);
6240 		if (err)
6241 			verbose_linfo(env, insn_idx, "; ");
6242 		if (!err && t == BPF_READ && value_regno >= 0) {
6243 			/* ctx access returns either a scalar, or a
6244 			 * PTR_TO_PACKET[_META,_END]. In the latter
6245 			 * case, we know the offset is zero.
6246 			 */
6247 			if (reg_type == SCALAR_VALUE) {
6248 				mark_reg_unknown(env, regs, value_regno);
6249 			} else {
6250 				mark_reg_known_zero(env, regs,
6251 						    value_regno);
6252 				if (type_may_be_null(reg_type))
6253 					regs[value_regno].id = ++env->id_gen;
6254 				/* A load of ctx field could have different
6255 				 * actual load size with the one encoded in the
6256 				 * insn. When the dst is PTR, it is for sure not
6257 				 * a sub-register.
6258 				 */
6259 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6260 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6261 					regs[value_regno].btf = btf;
6262 					regs[value_regno].btf_id = btf_id;
6263 				}
6264 			}
6265 			regs[value_regno].type = reg_type;
6266 		}
6267 
6268 	} else if (reg->type == PTR_TO_STACK) {
6269 		/* Basic bounds checks. */
6270 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6271 		if (err)
6272 			return err;
6273 
6274 		state = func(env, reg);
6275 		err = update_stack_depth(env, state, off);
6276 		if (err)
6277 			return err;
6278 
6279 		if (t == BPF_READ)
6280 			err = check_stack_read(env, regno, off, size,
6281 					       value_regno);
6282 		else
6283 			err = check_stack_write(env, regno, off, size,
6284 						value_regno, insn_idx);
6285 	} else if (reg_is_pkt_pointer(reg)) {
6286 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6287 			verbose(env, "cannot write into packet\n");
6288 			return -EACCES;
6289 		}
6290 		if (t == BPF_WRITE && value_regno >= 0 &&
6291 		    is_pointer_value(env, value_regno)) {
6292 			verbose(env, "R%d leaks addr into packet\n",
6293 				value_regno);
6294 			return -EACCES;
6295 		}
6296 		err = check_packet_access(env, regno, off, size, false);
6297 		if (!err && t == BPF_READ && value_regno >= 0)
6298 			mark_reg_unknown(env, regs, value_regno);
6299 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6300 		if (t == BPF_WRITE && value_regno >= 0 &&
6301 		    is_pointer_value(env, value_regno)) {
6302 			verbose(env, "R%d leaks addr into flow keys\n",
6303 				value_regno);
6304 			return -EACCES;
6305 		}
6306 
6307 		err = check_flow_keys_access(env, off, size);
6308 		if (!err && t == BPF_READ && value_regno >= 0)
6309 			mark_reg_unknown(env, regs, value_regno);
6310 	} else if (type_is_sk_pointer(reg->type)) {
6311 		if (t == BPF_WRITE) {
6312 			verbose(env, "R%d cannot write into %s\n",
6313 				regno, reg_type_str(env, reg->type));
6314 			return -EACCES;
6315 		}
6316 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6317 		if (!err && value_regno >= 0)
6318 			mark_reg_unknown(env, regs, value_regno);
6319 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6320 		err = check_tp_buffer_access(env, reg, regno, off, size);
6321 		if (!err && t == BPF_READ && value_regno >= 0)
6322 			mark_reg_unknown(env, regs, value_regno);
6323 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6324 		   !type_may_be_null(reg->type)) {
6325 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6326 					      value_regno);
6327 	} else if (reg->type == CONST_PTR_TO_MAP) {
6328 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6329 					      value_regno);
6330 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6331 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6332 		u32 *max_access;
6333 
6334 		if (rdonly_mem) {
6335 			if (t == BPF_WRITE) {
6336 				verbose(env, "R%d cannot write into %s\n",
6337 					regno, reg_type_str(env, reg->type));
6338 				return -EACCES;
6339 			}
6340 			max_access = &env->prog->aux->max_rdonly_access;
6341 		} else {
6342 			max_access = &env->prog->aux->max_rdwr_access;
6343 		}
6344 
6345 		err = check_buffer_access(env, reg, regno, off, size, false,
6346 					  max_access);
6347 
6348 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6349 			mark_reg_unknown(env, regs, value_regno);
6350 	} else {
6351 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6352 			reg_type_str(env, reg->type));
6353 		return -EACCES;
6354 	}
6355 
6356 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6357 	    regs[value_regno].type == SCALAR_VALUE) {
6358 		/* b/h/w load zero-extends, mark upper bits as known 0 */
6359 		coerce_reg_to_size(&regs[value_regno], size);
6360 	}
6361 	return err;
6362 }
6363 
6364 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6365 {
6366 	int load_reg;
6367 	int err;
6368 
6369 	switch (insn->imm) {
6370 	case BPF_ADD:
6371 	case BPF_ADD | BPF_FETCH:
6372 	case BPF_AND:
6373 	case BPF_AND | BPF_FETCH:
6374 	case BPF_OR:
6375 	case BPF_OR | BPF_FETCH:
6376 	case BPF_XOR:
6377 	case BPF_XOR | BPF_FETCH:
6378 	case BPF_XCHG:
6379 	case BPF_CMPXCHG:
6380 		break;
6381 	default:
6382 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6383 		return -EINVAL;
6384 	}
6385 
6386 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6387 		verbose(env, "invalid atomic operand size\n");
6388 		return -EINVAL;
6389 	}
6390 
6391 	/* check src1 operand */
6392 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6393 	if (err)
6394 		return err;
6395 
6396 	/* check src2 operand */
6397 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6398 	if (err)
6399 		return err;
6400 
6401 	if (insn->imm == BPF_CMPXCHG) {
6402 		/* Check comparison of R0 with memory location */
6403 		const u32 aux_reg = BPF_REG_0;
6404 
6405 		err = check_reg_arg(env, aux_reg, SRC_OP);
6406 		if (err)
6407 			return err;
6408 
6409 		if (is_pointer_value(env, aux_reg)) {
6410 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6411 			return -EACCES;
6412 		}
6413 	}
6414 
6415 	if (is_pointer_value(env, insn->src_reg)) {
6416 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6417 		return -EACCES;
6418 	}
6419 
6420 	if (is_ctx_reg(env, insn->dst_reg) ||
6421 	    is_pkt_reg(env, insn->dst_reg) ||
6422 	    is_flow_key_reg(env, insn->dst_reg) ||
6423 	    is_sk_reg(env, insn->dst_reg)) {
6424 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6425 			insn->dst_reg,
6426 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6427 		return -EACCES;
6428 	}
6429 
6430 	if (insn->imm & BPF_FETCH) {
6431 		if (insn->imm == BPF_CMPXCHG)
6432 			load_reg = BPF_REG_0;
6433 		else
6434 			load_reg = insn->src_reg;
6435 
6436 		/* check and record load of old value */
6437 		err = check_reg_arg(env, load_reg, DST_OP);
6438 		if (err)
6439 			return err;
6440 	} else {
6441 		/* This instruction accesses a memory location but doesn't
6442 		 * actually load it into a register.
6443 		 */
6444 		load_reg = -1;
6445 	}
6446 
6447 	/* Check whether we can read the memory, with second call for fetch
6448 	 * case to simulate the register fill.
6449 	 */
6450 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6451 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
6452 	if (!err && load_reg >= 0)
6453 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6454 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6455 				       true);
6456 	if (err)
6457 		return err;
6458 
6459 	/* Check whether we can write into the same memory. */
6460 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6461 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6462 	if (err)
6463 		return err;
6464 
6465 	return 0;
6466 }
6467 
6468 /* When register 'regno' is used to read the stack (either directly or through
6469  * a helper function) make sure that it's within stack boundary and, depending
6470  * on the access type, that all elements of the stack are initialized.
6471  *
6472  * 'off' includes 'regno->off', but not its dynamic part (if any).
6473  *
6474  * All registers that have been spilled on the stack in the slots within the
6475  * read offsets are marked as read.
6476  */
6477 static int check_stack_range_initialized(
6478 		struct bpf_verifier_env *env, int regno, int off,
6479 		int access_size, bool zero_size_allowed,
6480 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6481 {
6482 	struct bpf_reg_state *reg = reg_state(env, regno);
6483 	struct bpf_func_state *state = func(env, reg);
6484 	int err, min_off, max_off, i, j, slot, spi;
6485 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6486 	enum bpf_access_type bounds_check_type;
6487 	/* Some accesses can write anything into the stack, others are
6488 	 * read-only.
6489 	 */
6490 	bool clobber = false;
6491 
6492 	if (access_size == 0 && !zero_size_allowed) {
6493 		verbose(env, "invalid zero-sized read\n");
6494 		return -EACCES;
6495 	}
6496 
6497 	if (type == ACCESS_HELPER) {
6498 		/* The bounds checks for writes are more permissive than for
6499 		 * reads. However, if raw_mode is not set, we'll do extra
6500 		 * checks below.
6501 		 */
6502 		bounds_check_type = BPF_WRITE;
6503 		clobber = true;
6504 	} else {
6505 		bounds_check_type = BPF_READ;
6506 	}
6507 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6508 					       type, bounds_check_type);
6509 	if (err)
6510 		return err;
6511 
6512 
6513 	if (tnum_is_const(reg->var_off)) {
6514 		min_off = max_off = reg->var_off.value + off;
6515 	} else {
6516 		/* Variable offset is prohibited for unprivileged mode for
6517 		 * simplicity since it requires corresponding support in
6518 		 * Spectre masking for stack ALU.
6519 		 * See also retrieve_ptr_limit().
6520 		 */
6521 		if (!env->bypass_spec_v1) {
6522 			char tn_buf[48];
6523 
6524 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6525 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6526 				regno, err_extra, tn_buf);
6527 			return -EACCES;
6528 		}
6529 		/* Only initialized buffer on stack is allowed to be accessed
6530 		 * with variable offset. With uninitialized buffer it's hard to
6531 		 * guarantee that whole memory is marked as initialized on
6532 		 * helper return since specific bounds are unknown what may
6533 		 * cause uninitialized stack leaking.
6534 		 */
6535 		if (meta && meta->raw_mode)
6536 			meta = NULL;
6537 
6538 		min_off = reg->smin_value + off;
6539 		max_off = reg->smax_value + off;
6540 	}
6541 
6542 	if (meta && meta->raw_mode) {
6543 		/* Ensure we won't be overwriting dynptrs when simulating byte
6544 		 * by byte access in check_helper_call using meta.access_size.
6545 		 * This would be a problem if we have a helper in the future
6546 		 * which takes:
6547 		 *
6548 		 *	helper(uninit_mem, len, dynptr)
6549 		 *
6550 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6551 		 * may end up writing to dynptr itself when touching memory from
6552 		 * arg 1. This can be relaxed on a case by case basis for known
6553 		 * safe cases, but reject due to the possibilitiy of aliasing by
6554 		 * default.
6555 		 */
6556 		for (i = min_off; i < max_off + access_size; i++) {
6557 			int stack_off = -i - 1;
6558 
6559 			spi = __get_spi(i);
6560 			/* raw_mode may write past allocated_stack */
6561 			if (state->allocated_stack <= stack_off)
6562 				continue;
6563 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6564 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6565 				return -EACCES;
6566 			}
6567 		}
6568 		meta->access_size = access_size;
6569 		meta->regno = regno;
6570 		return 0;
6571 	}
6572 
6573 	for (i = min_off; i < max_off + access_size; i++) {
6574 		u8 *stype;
6575 
6576 		slot = -i - 1;
6577 		spi = slot / BPF_REG_SIZE;
6578 		if (state->allocated_stack <= slot)
6579 			goto err;
6580 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6581 		if (*stype == STACK_MISC)
6582 			goto mark;
6583 		if ((*stype == STACK_ZERO) ||
6584 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6585 			if (clobber) {
6586 				/* helper can write anything into the stack */
6587 				*stype = STACK_MISC;
6588 			}
6589 			goto mark;
6590 		}
6591 
6592 		if (is_spilled_reg(&state->stack[spi]) &&
6593 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6594 		     env->allow_ptr_leaks)) {
6595 			if (clobber) {
6596 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6597 				for (j = 0; j < BPF_REG_SIZE; j++)
6598 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6599 			}
6600 			goto mark;
6601 		}
6602 
6603 err:
6604 		if (tnum_is_const(reg->var_off)) {
6605 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6606 				err_extra, regno, min_off, i - min_off, access_size);
6607 		} else {
6608 			char tn_buf[48];
6609 
6610 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6611 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6612 				err_extra, regno, tn_buf, i - min_off, access_size);
6613 		}
6614 		return -EACCES;
6615 mark:
6616 		/* reading any byte out of 8-byte 'spill_slot' will cause
6617 		 * the whole slot to be marked as 'read'
6618 		 */
6619 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6620 			      state->stack[spi].spilled_ptr.parent,
6621 			      REG_LIVE_READ64);
6622 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6623 		 * be sure that whether stack slot is written to or not. Hence,
6624 		 * we must still conservatively propagate reads upwards even if
6625 		 * helper may write to the entire memory range.
6626 		 */
6627 	}
6628 	return update_stack_depth(env, state, min_off);
6629 }
6630 
6631 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6632 				   int access_size, bool zero_size_allowed,
6633 				   struct bpf_call_arg_meta *meta)
6634 {
6635 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6636 	u32 *max_access;
6637 
6638 	switch (base_type(reg->type)) {
6639 	case PTR_TO_PACKET:
6640 	case PTR_TO_PACKET_META:
6641 		return check_packet_access(env, regno, reg->off, access_size,
6642 					   zero_size_allowed);
6643 	case PTR_TO_MAP_KEY:
6644 		if (meta && meta->raw_mode) {
6645 			verbose(env, "R%d cannot write into %s\n", regno,
6646 				reg_type_str(env, reg->type));
6647 			return -EACCES;
6648 		}
6649 		return check_mem_region_access(env, regno, reg->off, access_size,
6650 					       reg->map_ptr->key_size, false);
6651 	case PTR_TO_MAP_VALUE:
6652 		if (check_map_access_type(env, regno, reg->off, access_size,
6653 					  meta && meta->raw_mode ? BPF_WRITE :
6654 					  BPF_READ))
6655 			return -EACCES;
6656 		return check_map_access(env, regno, reg->off, access_size,
6657 					zero_size_allowed, ACCESS_HELPER);
6658 	case PTR_TO_MEM:
6659 		if (type_is_rdonly_mem(reg->type)) {
6660 			if (meta && meta->raw_mode) {
6661 				verbose(env, "R%d cannot write into %s\n", regno,
6662 					reg_type_str(env, reg->type));
6663 				return -EACCES;
6664 			}
6665 		}
6666 		return check_mem_region_access(env, regno, reg->off,
6667 					       access_size, reg->mem_size,
6668 					       zero_size_allowed);
6669 	case PTR_TO_BUF:
6670 		if (type_is_rdonly_mem(reg->type)) {
6671 			if (meta && meta->raw_mode) {
6672 				verbose(env, "R%d cannot write into %s\n", regno,
6673 					reg_type_str(env, reg->type));
6674 				return -EACCES;
6675 			}
6676 
6677 			max_access = &env->prog->aux->max_rdonly_access;
6678 		} else {
6679 			max_access = &env->prog->aux->max_rdwr_access;
6680 		}
6681 		return check_buffer_access(env, reg, regno, reg->off,
6682 					   access_size, zero_size_allowed,
6683 					   max_access);
6684 	case PTR_TO_STACK:
6685 		return check_stack_range_initialized(
6686 				env,
6687 				regno, reg->off, access_size,
6688 				zero_size_allowed, ACCESS_HELPER, meta);
6689 	case PTR_TO_BTF_ID:
6690 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
6691 					       access_size, BPF_READ, -1);
6692 	case PTR_TO_CTX:
6693 		/* in case the function doesn't know how to access the context,
6694 		 * (because we are in a program of type SYSCALL for example), we
6695 		 * can not statically check its size.
6696 		 * Dynamically check it now.
6697 		 */
6698 		if (!env->ops->convert_ctx_access) {
6699 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6700 			int offset = access_size - 1;
6701 
6702 			/* Allow zero-byte read from PTR_TO_CTX */
6703 			if (access_size == 0)
6704 				return zero_size_allowed ? 0 : -EACCES;
6705 
6706 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6707 						atype, -1, false);
6708 		}
6709 
6710 		fallthrough;
6711 	default: /* scalar_value or invalid ptr */
6712 		/* Allow zero-byte read from NULL, regardless of pointer type */
6713 		if (zero_size_allowed && access_size == 0 &&
6714 		    register_is_null(reg))
6715 			return 0;
6716 
6717 		verbose(env, "R%d type=%s ", regno,
6718 			reg_type_str(env, reg->type));
6719 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6720 		return -EACCES;
6721 	}
6722 }
6723 
6724 static int check_mem_size_reg(struct bpf_verifier_env *env,
6725 			      struct bpf_reg_state *reg, u32 regno,
6726 			      bool zero_size_allowed,
6727 			      struct bpf_call_arg_meta *meta)
6728 {
6729 	int err;
6730 
6731 	/* This is used to refine r0 return value bounds for helpers
6732 	 * that enforce this value as an upper bound on return values.
6733 	 * See do_refine_retval_range() for helpers that can refine
6734 	 * the return value. C type of helper is u32 so we pull register
6735 	 * bound from umax_value however, if negative verifier errors
6736 	 * out. Only upper bounds can be learned because retval is an
6737 	 * int type and negative retvals are allowed.
6738 	 */
6739 	meta->msize_max_value = reg->umax_value;
6740 
6741 	/* The register is SCALAR_VALUE; the access check
6742 	 * happens using its boundaries.
6743 	 */
6744 	if (!tnum_is_const(reg->var_off))
6745 		/* For unprivileged variable accesses, disable raw
6746 		 * mode so that the program is required to
6747 		 * initialize all the memory that the helper could
6748 		 * just partially fill up.
6749 		 */
6750 		meta = NULL;
6751 
6752 	if (reg->smin_value < 0) {
6753 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6754 			regno);
6755 		return -EACCES;
6756 	}
6757 
6758 	if (reg->umin_value == 0) {
6759 		err = check_helper_mem_access(env, regno - 1, 0,
6760 					      zero_size_allowed,
6761 					      meta);
6762 		if (err)
6763 			return err;
6764 	}
6765 
6766 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6767 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6768 			regno);
6769 		return -EACCES;
6770 	}
6771 	err = check_helper_mem_access(env, regno - 1,
6772 				      reg->umax_value,
6773 				      zero_size_allowed, meta);
6774 	if (!err)
6775 		err = mark_chain_precision(env, regno);
6776 	return err;
6777 }
6778 
6779 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6780 		   u32 regno, u32 mem_size)
6781 {
6782 	bool may_be_null = type_may_be_null(reg->type);
6783 	struct bpf_reg_state saved_reg;
6784 	struct bpf_call_arg_meta meta;
6785 	int err;
6786 
6787 	if (register_is_null(reg))
6788 		return 0;
6789 
6790 	memset(&meta, 0, sizeof(meta));
6791 	/* Assuming that the register contains a value check if the memory
6792 	 * access is safe. Temporarily save and restore the register's state as
6793 	 * the conversion shouldn't be visible to a caller.
6794 	 */
6795 	if (may_be_null) {
6796 		saved_reg = *reg;
6797 		mark_ptr_not_null_reg(reg);
6798 	}
6799 
6800 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6801 	/* Check access for BPF_WRITE */
6802 	meta.raw_mode = true;
6803 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6804 
6805 	if (may_be_null)
6806 		*reg = saved_reg;
6807 
6808 	return err;
6809 }
6810 
6811 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6812 				    u32 regno)
6813 {
6814 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6815 	bool may_be_null = type_may_be_null(mem_reg->type);
6816 	struct bpf_reg_state saved_reg;
6817 	struct bpf_call_arg_meta meta;
6818 	int err;
6819 
6820 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6821 
6822 	memset(&meta, 0, sizeof(meta));
6823 
6824 	if (may_be_null) {
6825 		saved_reg = *mem_reg;
6826 		mark_ptr_not_null_reg(mem_reg);
6827 	}
6828 
6829 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6830 	/* Check access for BPF_WRITE */
6831 	meta.raw_mode = true;
6832 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6833 
6834 	if (may_be_null)
6835 		*mem_reg = saved_reg;
6836 	return err;
6837 }
6838 
6839 /* Implementation details:
6840  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6841  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6842  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6843  * Two separate bpf_obj_new will also have different reg->id.
6844  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6845  * clears reg->id after value_or_null->value transition, since the verifier only
6846  * cares about the range of access to valid map value pointer and doesn't care
6847  * about actual address of the map element.
6848  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6849  * reg->id > 0 after value_or_null->value transition. By doing so
6850  * two bpf_map_lookups will be considered two different pointers that
6851  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6852  * returned from bpf_obj_new.
6853  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6854  * dead-locks.
6855  * Since only one bpf_spin_lock is allowed the checks are simpler than
6856  * reg_is_refcounted() logic. The verifier needs to remember only
6857  * one spin_lock instead of array of acquired_refs.
6858  * cur_state->active_lock remembers which map value element or allocated
6859  * object got locked and clears it after bpf_spin_unlock.
6860  */
6861 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6862 			     bool is_lock)
6863 {
6864 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6865 	struct bpf_verifier_state *cur = env->cur_state;
6866 	bool is_const = tnum_is_const(reg->var_off);
6867 	u64 val = reg->var_off.value;
6868 	struct bpf_map *map = NULL;
6869 	struct btf *btf = NULL;
6870 	struct btf_record *rec;
6871 
6872 	if (!is_const) {
6873 		verbose(env,
6874 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6875 			regno);
6876 		return -EINVAL;
6877 	}
6878 	if (reg->type == PTR_TO_MAP_VALUE) {
6879 		map = reg->map_ptr;
6880 		if (!map->btf) {
6881 			verbose(env,
6882 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6883 				map->name);
6884 			return -EINVAL;
6885 		}
6886 	} else {
6887 		btf = reg->btf;
6888 	}
6889 
6890 	rec = reg_btf_record(reg);
6891 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6892 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6893 			map ? map->name : "kptr");
6894 		return -EINVAL;
6895 	}
6896 	if (rec->spin_lock_off != val + reg->off) {
6897 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6898 			val + reg->off, rec->spin_lock_off);
6899 		return -EINVAL;
6900 	}
6901 	if (is_lock) {
6902 		if (cur->active_lock.ptr) {
6903 			verbose(env,
6904 				"Locking two bpf_spin_locks are not allowed\n");
6905 			return -EINVAL;
6906 		}
6907 		if (map)
6908 			cur->active_lock.ptr = map;
6909 		else
6910 			cur->active_lock.ptr = btf;
6911 		cur->active_lock.id = reg->id;
6912 	} else {
6913 		void *ptr;
6914 
6915 		if (map)
6916 			ptr = map;
6917 		else
6918 			ptr = btf;
6919 
6920 		if (!cur->active_lock.ptr) {
6921 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6922 			return -EINVAL;
6923 		}
6924 		if (cur->active_lock.ptr != ptr ||
6925 		    cur->active_lock.id != reg->id) {
6926 			verbose(env, "bpf_spin_unlock of different lock\n");
6927 			return -EINVAL;
6928 		}
6929 
6930 		invalidate_non_owning_refs(env);
6931 
6932 		cur->active_lock.ptr = NULL;
6933 		cur->active_lock.id = 0;
6934 	}
6935 	return 0;
6936 }
6937 
6938 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6939 			      struct bpf_call_arg_meta *meta)
6940 {
6941 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6942 	bool is_const = tnum_is_const(reg->var_off);
6943 	struct bpf_map *map = reg->map_ptr;
6944 	u64 val = reg->var_off.value;
6945 
6946 	if (!is_const) {
6947 		verbose(env,
6948 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6949 			regno);
6950 		return -EINVAL;
6951 	}
6952 	if (!map->btf) {
6953 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6954 			map->name);
6955 		return -EINVAL;
6956 	}
6957 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6958 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6959 		return -EINVAL;
6960 	}
6961 	if (map->record->timer_off != val + reg->off) {
6962 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6963 			val + reg->off, map->record->timer_off);
6964 		return -EINVAL;
6965 	}
6966 	if (meta->map_ptr) {
6967 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6968 		return -EFAULT;
6969 	}
6970 	meta->map_uid = reg->map_uid;
6971 	meta->map_ptr = map;
6972 	return 0;
6973 }
6974 
6975 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6976 			     struct bpf_call_arg_meta *meta)
6977 {
6978 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6979 	struct bpf_map *map_ptr = reg->map_ptr;
6980 	struct btf_field *kptr_field;
6981 	u32 kptr_off;
6982 
6983 	if (!tnum_is_const(reg->var_off)) {
6984 		verbose(env,
6985 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6986 			regno);
6987 		return -EINVAL;
6988 	}
6989 	if (!map_ptr->btf) {
6990 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6991 			map_ptr->name);
6992 		return -EINVAL;
6993 	}
6994 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6995 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6996 		return -EINVAL;
6997 	}
6998 
6999 	meta->map_ptr = map_ptr;
7000 	kptr_off = reg->off + reg->var_off.value;
7001 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7002 	if (!kptr_field) {
7003 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7004 		return -EACCES;
7005 	}
7006 	if (kptr_field->type != BPF_KPTR_REF) {
7007 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7008 		return -EACCES;
7009 	}
7010 	meta->kptr_field = kptr_field;
7011 	return 0;
7012 }
7013 
7014 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7015  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7016  *
7017  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7018  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7019  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7020  *
7021  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7022  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7023  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7024  * mutate the view of the dynptr and also possibly destroy it. In the latter
7025  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7026  * memory that dynptr points to.
7027  *
7028  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7029  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7030  * readonly dynptr view yet, hence only the first case is tracked and checked.
7031  *
7032  * This is consistent with how C applies the const modifier to a struct object,
7033  * where the pointer itself inside bpf_dynptr becomes const but not what it
7034  * points to.
7035  *
7036  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7037  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7038  */
7039 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7040 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7041 {
7042 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7043 	int err;
7044 
7045 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7046 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7047 	 */
7048 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7049 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7050 		return -EFAULT;
7051 	}
7052 
7053 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7054 	 *		 constructing a mutable bpf_dynptr object.
7055 	 *
7056 	 *		 Currently, this is only possible with PTR_TO_STACK
7057 	 *		 pointing to a region of at least 16 bytes which doesn't
7058 	 *		 contain an existing bpf_dynptr.
7059 	 *
7060 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7061 	 *		 mutated or destroyed. However, the memory it points to
7062 	 *		 may be mutated.
7063 	 *
7064 	 *  None       - Points to a initialized dynptr that can be mutated and
7065 	 *		 destroyed, including mutation of the memory it points
7066 	 *		 to.
7067 	 */
7068 	if (arg_type & MEM_UNINIT) {
7069 		int i;
7070 
7071 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7072 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7073 			return -EINVAL;
7074 		}
7075 
7076 		/* we write BPF_DW bits (8 bytes) at a time */
7077 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7078 			err = check_mem_access(env, insn_idx, regno,
7079 					       i, BPF_DW, BPF_WRITE, -1, false);
7080 			if (err)
7081 				return err;
7082 		}
7083 
7084 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7085 	} else /* MEM_RDONLY and None case from above */ {
7086 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7087 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7088 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7089 			return -EINVAL;
7090 		}
7091 
7092 		if (!is_dynptr_reg_valid_init(env, reg)) {
7093 			verbose(env,
7094 				"Expected an initialized dynptr as arg #%d\n",
7095 				regno);
7096 			return -EINVAL;
7097 		}
7098 
7099 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7100 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7101 			verbose(env,
7102 				"Expected a dynptr of type %s as arg #%d\n",
7103 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7104 			return -EINVAL;
7105 		}
7106 
7107 		err = mark_dynptr_read(env, reg);
7108 	}
7109 	return err;
7110 }
7111 
7112 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7113 {
7114 	struct bpf_func_state *state = func(env, reg);
7115 
7116 	return state->stack[spi].spilled_ptr.ref_obj_id;
7117 }
7118 
7119 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7120 {
7121 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7122 }
7123 
7124 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7125 {
7126 	return meta->kfunc_flags & KF_ITER_NEW;
7127 }
7128 
7129 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7130 {
7131 	return meta->kfunc_flags & KF_ITER_NEXT;
7132 }
7133 
7134 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7135 {
7136 	return meta->kfunc_flags & KF_ITER_DESTROY;
7137 }
7138 
7139 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7140 {
7141 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7142 	 * kfunc is iter state pointer
7143 	 */
7144 	return arg == 0 && is_iter_kfunc(meta);
7145 }
7146 
7147 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7148 			    struct bpf_kfunc_call_arg_meta *meta)
7149 {
7150 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7151 	const struct btf_type *t;
7152 	const struct btf_param *arg;
7153 	int spi, err, i, nr_slots;
7154 	u32 btf_id;
7155 
7156 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7157 	arg = &btf_params(meta->func_proto)[0];
7158 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7159 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7160 	nr_slots = t->size / BPF_REG_SIZE;
7161 
7162 	if (is_iter_new_kfunc(meta)) {
7163 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7164 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7165 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7166 				iter_type_str(meta->btf, btf_id), regno);
7167 			return -EINVAL;
7168 		}
7169 
7170 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7171 			err = check_mem_access(env, insn_idx, regno,
7172 					       i, BPF_DW, BPF_WRITE, -1, false);
7173 			if (err)
7174 				return err;
7175 		}
7176 
7177 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7178 		if (err)
7179 			return err;
7180 	} else {
7181 		/* iter_next() or iter_destroy() expect initialized iter state*/
7182 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7183 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7184 				iter_type_str(meta->btf, btf_id), regno);
7185 			return -EINVAL;
7186 		}
7187 
7188 		spi = iter_get_spi(env, reg, nr_slots);
7189 		if (spi < 0)
7190 			return spi;
7191 
7192 		err = mark_iter_read(env, reg, spi, nr_slots);
7193 		if (err)
7194 			return err;
7195 
7196 		/* remember meta->iter info for process_iter_next_call() */
7197 		meta->iter.spi = spi;
7198 		meta->iter.frameno = reg->frameno;
7199 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7200 
7201 		if (is_iter_destroy_kfunc(meta)) {
7202 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7203 			if (err)
7204 				return err;
7205 		}
7206 	}
7207 
7208 	return 0;
7209 }
7210 
7211 /* process_iter_next_call() is called when verifier gets to iterator's next
7212  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7213  * to it as just "iter_next()" in comments below.
7214  *
7215  * BPF verifier relies on a crucial contract for any iter_next()
7216  * implementation: it should *eventually* return NULL, and once that happens
7217  * it should keep returning NULL. That is, once iterator exhausts elements to
7218  * iterate, it should never reset or spuriously return new elements.
7219  *
7220  * With the assumption of such contract, process_iter_next_call() simulates
7221  * a fork in the verifier state to validate loop logic correctness and safety
7222  * without having to simulate infinite amount of iterations.
7223  *
7224  * In current state, we first assume that iter_next() returned NULL and
7225  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7226  * conditions we should not form an infinite loop and should eventually reach
7227  * exit.
7228  *
7229  * Besides that, we also fork current state and enqueue it for later
7230  * verification. In a forked state we keep iterator state as ACTIVE
7231  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7232  * also bump iteration depth to prevent erroneous infinite loop detection
7233  * later on (see iter_active_depths_differ() comment for details). In this
7234  * state we assume that we'll eventually loop back to another iter_next()
7235  * calls (it could be in exactly same location or in some other instruction,
7236  * it doesn't matter, we don't make any unnecessary assumptions about this,
7237  * everything revolves around iterator state in a stack slot, not which
7238  * instruction is calling iter_next()). When that happens, we either will come
7239  * to iter_next() with equivalent state and can conclude that next iteration
7240  * will proceed in exactly the same way as we just verified, so it's safe to
7241  * assume that loop converges. If not, we'll go on another iteration
7242  * simulation with a different input state, until all possible starting states
7243  * are validated or we reach maximum number of instructions limit.
7244  *
7245  * This way, we will either exhaustively discover all possible input states
7246  * that iterator loop can start with and eventually will converge, or we'll
7247  * effectively regress into bounded loop simulation logic and either reach
7248  * maximum number of instructions if loop is not provably convergent, or there
7249  * is some statically known limit on number of iterations (e.g., if there is
7250  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7251  *
7252  * One very subtle but very important aspect is that we *always* simulate NULL
7253  * condition first (as the current state) before we simulate non-NULL case.
7254  * This has to do with intricacies of scalar precision tracking. By simulating
7255  * "exit condition" of iter_next() returning NULL first, we make sure all the
7256  * relevant precision marks *that will be set **after** we exit iterator loop*
7257  * are propagated backwards to common parent state of NULL and non-NULL
7258  * branches. Thanks to that, state equivalence checks done later in forked
7259  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7260  * precision marks are finalized and won't change. Because simulating another
7261  * ACTIVE iterator iteration won't change them (because given same input
7262  * states we'll end up with exactly same output states which we are currently
7263  * comparing; and verification after the loop already propagated back what
7264  * needs to be **additionally** tracked as precise). It's subtle, grok
7265  * precision tracking for more intuitive understanding.
7266  */
7267 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7268 				  struct bpf_kfunc_call_arg_meta *meta)
7269 {
7270 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7271 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7272 	struct bpf_reg_state *cur_iter, *queued_iter;
7273 	int iter_frameno = meta->iter.frameno;
7274 	int iter_spi = meta->iter.spi;
7275 
7276 	BTF_TYPE_EMIT(struct bpf_iter);
7277 
7278 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7279 
7280 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7281 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7282 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7283 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7284 		return -EFAULT;
7285 	}
7286 
7287 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7288 		/* branch out active iter state */
7289 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7290 		if (!queued_st)
7291 			return -ENOMEM;
7292 
7293 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7294 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7295 		queued_iter->iter.depth++;
7296 
7297 		queued_fr = queued_st->frame[queued_st->curframe];
7298 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7299 	}
7300 
7301 	/* switch to DRAINED state, but keep the depth unchanged */
7302 	/* mark current iter state as drained and assume returned NULL */
7303 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7304 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7305 
7306 	return 0;
7307 }
7308 
7309 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7310 {
7311 	return type == ARG_CONST_SIZE ||
7312 	       type == ARG_CONST_SIZE_OR_ZERO;
7313 }
7314 
7315 static bool arg_type_is_release(enum bpf_arg_type type)
7316 {
7317 	return type & OBJ_RELEASE;
7318 }
7319 
7320 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7321 {
7322 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7323 }
7324 
7325 static int int_ptr_type_to_size(enum bpf_arg_type type)
7326 {
7327 	if (type == ARG_PTR_TO_INT)
7328 		return sizeof(u32);
7329 	else if (type == ARG_PTR_TO_LONG)
7330 		return sizeof(u64);
7331 
7332 	return -EINVAL;
7333 }
7334 
7335 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7336 				 const struct bpf_call_arg_meta *meta,
7337 				 enum bpf_arg_type *arg_type)
7338 {
7339 	if (!meta->map_ptr) {
7340 		/* kernel subsystem misconfigured verifier */
7341 		verbose(env, "invalid map_ptr to access map->type\n");
7342 		return -EACCES;
7343 	}
7344 
7345 	switch (meta->map_ptr->map_type) {
7346 	case BPF_MAP_TYPE_SOCKMAP:
7347 	case BPF_MAP_TYPE_SOCKHASH:
7348 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7349 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7350 		} else {
7351 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7352 			return -EINVAL;
7353 		}
7354 		break;
7355 	case BPF_MAP_TYPE_BLOOM_FILTER:
7356 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7357 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7358 		break;
7359 	default:
7360 		break;
7361 	}
7362 	return 0;
7363 }
7364 
7365 struct bpf_reg_types {
7366 	const enum bpf_reg_type types[10];
7367 	u32 *btf_id;
7368 };
7369 
7370 static const struct bpf_reg_types sock_types = {
7371 	.types = {
7372 		PTR_TO_SOCK_COMMON,
7373 		PTR_TO_SOCKET,
7374 		PTR_TO_TCP_SOCK,
7375 		PTR_TO_XDP_SOCK,
7376 	},
7377 };
7378 
7379 #ifdef CONFIG_NET
7380 static const struct bpf_reg_types btf_id_sock_common_types = {
7381 	.types = {
7382 		PTR_TO_SOCK_COMMON,
7383 		PTR_TO_SOCKET,
7384 		PTR_TO_TCP_SOCK,
7385 		PTR_TO_XDP_SOCK,
7386 		PTR_TO_BTF_ID,
7387 		PTR_TO_BTF_ID | PTR_TRUSTED,
7388 	},
7389 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7390 };
7391 #endif
7392 
7393 static const struct bpf_reg_types mem_types = {
7394 	.types = {
7395 		PTR_TO_STACK,
7396 		PTR_TO_PACKET,
7397 		PTR_TO_PACKET_META,
7398 		PTR_TO_MAP_KEY,
7399 		PTR_TO_MAP_VALUE,
7400 		PTR_TO_MEM,
7401 		PTR_TO_MEM | MEM_RINGBUF,
7402 		PTR_TO_BUF,
7403 		PTR_TO_BTF_ID | PTR_TRUSTED,
7404 	},
7405 };
7406 
7407 static const struct bpf_reg_types int_ptr_types = {
7408 	.types = {
7409 		PTR_TO_STACK,
7410 		PTR_TO_PACKET,
7411 		PTR_TO_PACKET_META,
7412 		PTR_TO_MAP_KEY,
7413 		PTR_TO_MAP_VALUE,
7414 	},
7415 };
7416 
7417 static const struct bpf_reg_types spin_lock_types = {
7418 	.types = {
7419 		PTR_TO_MAP_VALUE,
7420 		PTR_TO_BTF_ID | MEM_ALLOC,
7421 	}
7422 };
7423 
7424 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7425 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7426 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7427 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7428 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7429 static const struct bpf_reg_types btf_ptr_types = {
7430 	.types = {
7431 		PTR_TO_BTF_ID,
7432 		PTR_TO_BTF_ID | PTR_TRUSTED,
7433 		PTR_TO_BTF_ID | MEM_RCU,
7434 	},
7435 };
7436 static const struct bpf_reg_types percpu_btf_ptr_types = {
7437 	.types = {
7438 		PTR_TO_BTF_ID | MEM_PERCPU,
7439 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7440 	}
7441 };
7442 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7443 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7444 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7445 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7446 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7447 static const struct bpf_reg_types dynptr_types = {
7448 	.types = {
7449 		PTR_TO_STACK,
7450 		CONST_PTR_TO_DYNPTR,
7451 	}
7452 };
7453 
7454 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7455 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7456 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7457 	[ARG_CONST_SIZE]		= &scalar_types,
7458 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7459 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7460 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7461 	[ARG_PTR_TO_CTX]		= &context_types,
7462 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7463 #ifdef CONFIG_NET
7464 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7465 #endif
7466 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7467 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7468 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7469 	[ARG_PTR_TO_MEM]		= &mem_types,
7470 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7471 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7472 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7473 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7474 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7475 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7476 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7477 	[ARG_PTR_TO_TIMER]		= &timer_types,
7478 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7479 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7480 };
7481 
7482 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7483 			  enum bpf_arg_type arg_type,
7484 			  const u32 *arg_btf_id,
7485 			  struct bpf_call_arg_meta *meta)
7486 {
7487 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7488 	enum bpf_reg_type expected, type = reg->type;
7489 	const struct bpf_reg_types *compatible;
7490 	int i, j;
7491 
7492 	compatible = compatible_reg_types[base_type(arg_type)];
7493 	if (!compatible) {
7494 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7495 		return -EFAULT;
7496 	}
7497 
7498 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7499 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7500 	 *
7501 	 * Same for MAYBE_NULL:
7502 	 *
7503 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7504 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7505 	 *
7506 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7507 	 *
7508 	 * Therefore we fold these flags depending on the arg_type before comparison.
7509 	 */
7510 	if (arg_type & MEM_RDONLY)
7511 		type &= ~MEM_RDONLY;
7512 	if (arg_type & PTR_MAYBE_NULL)
7513 		type &= ~PTR_MAYBE_NULL;
7514 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7515 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7516 
7517 	if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7518 		type &= ~MEM_ALLOC;
7519 
7520 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7521 		expected = compatible->types[i];
7522 		if (expected == NOT_INIT)
7523 			break;
7524 
7525 		if (type == expected)
7526 			goto found;
7527 	}
7528 
7529 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7530 	for (j = 0; j + 1 < i; j++)
7531 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7532 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7533 	return -EACCES;
7534 
7535 found:
7536 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7537 		return 0;
7538 
7539 	if (compatible == &mem_types) {
7540 		if (!(arg_type & MEM_RDONLY)) {
7541 			verbose(env,
7542 				"%s() may write into memory pointed by R%d type=%s\n",
7543 				func_id_name(meta->func_id),
7544 				regno, reg_type_str(env, reg->type));
7545 			return -EACCES;
7546 		}
7547 		return 0;
7548 	}
7549 
7550 	switch ((int)reg->type) {
7551 	case PTR_TO_BTF_ID:
7552 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7553 	case PTR_TO_BTF_ID | MEM_RCU:
7554 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7555 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7556 	{
7557 		/* For bpf_sk_release, it needs to match against first member
7558 		 * 'struct sock_common', hence make an exception for it. This
7559 		 * allows bpf_sk_release to work for multiple socket types.
7560 		 */
7561 		bool strict_type_match = arg_type_is_release(arg_type) &&
7562 					 meta->func_id != BPF_FUNC_sk_release;
7563 
7564 		if (type_may_be_null(reg->type) &&
7565 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7566 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7567 			return -EACCES;
7568 		}
7569 
7570 		if (!arg_btf_id) {
7571 			if (!compatible->btf_id) {
7572 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7573 				return -EFAULT;
7574 			}
7575 			arg_btf_id = compatible->btf_id;
7576 		}
7577 
7578 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7579 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7580 				return -EACCES;
7581 		} else {
7582 			if (arg_btf_id == BPF_PTR_POISON) {
7583 				verbose(env, "verifier internal error:");
7584 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7585 					regno);
7586 				return -EACCES;
7587 			}
7588 
7589 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7590 						  btf_vmlinux, *arg_btf_id,
7591 						  strict_type_match)) {
7592 				verbose(env, "R%d is of type %s but %s is expected\n",
7593 					regno, btf_type_name(reg->btf, reg->btf_id),
7594 					btf_type_name(btf_vmlinux, *arg_btf_id));
7595 				return -EACCES;
7596 			}
7597 		}
7598 		break;
7599 	}
7600 	case PTR_TO_BTF_ID | MEM_ALLOC:
7601 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7602 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7603 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7604 			return -EFAULT;
7605 		}
7606 		/* Handled by helper specific checks */
7607 		break;
7608 	case PTR_TO_BTF_ID | MEM_PERCPU:
7609 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7610 		/* Handled by helper specific checks */
7611 		break;
7612 	default:
7613 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7614 		return -EFAULT;
7615 	}
7616 	return 0;
7617 }
7618 
7619 static struct btf_field *
7620 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7621 {
7622 	struct btf_field *field;
7623 	struct btf_record *rec;
7624 
7625 	rec = reg_btf_record(reg);
7626 	if (!rec)
7627 		return NULL;
7628 
7629 	field = btf_record_find(rec, off, fields);
7630 	if (!field)
7631 		return NULL;
7632 
7633 	return field;
7634 }
7635 
7636 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7637 			   const struct bpf_reg_state *reg, int regno,
7638 			   enum bpf_arg_type arg_type)
7639 {
7640 	u32 type = reg->type;
7641 
7642 	/* When referenced register is passed to release function, its fixed
7643 	 * offset must be 0.
7644 	 *
7645 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7646 	 * meta->release_regno.
7647 	 */
7648 	if (arg_type_is_release(arg_type)) {
7649 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7650 		 * may not directly point to the object being released, but to
7651 		 * dynptr pointing to such object, which might be at some offset
7652 		 * on the stack. In that case, we simply to fallback to the
7653 		 * default handling.
7654 		 */
7655 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7656 			return 0;
7657 
7658 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7659 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7660 				return __check_ptr_off_reg(env, reg, regno, true);
7661 
7662 			verbose(env, "R%d must have zero offset when passed to release func\n",
7663 				regno);
7664 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7665 				btf_type_name(reg->btf, reg->btf_id), reg->off);
7666 			return -EINVAL;
7667 		}
7668 
7669 		/* Doing check_ptr_off_reg check for the offset will catch this
7670 		 * because fixed_off_ok is false, but checking here allows us
7671 		 * to give the user a better error message.
7672 		 */
7673 		if (reg->off) {
7674 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7675 				regno);
7676 			return -EINVAL;
7677 		}
7678 		return __check_ptr_off_reg(env, reg, regno, false);
7679 	}
7680 
7681 	switch (type) {
7682 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7683 	case PTR_TO_STACK:
7684 	case PTR_TO_PACKET:
7685 	case PTR_TO_PACKET_META:
7686 	case PTR_TO_MAP_KEY:
7687 	case PTR_TO_MAP_VALUE:
7688 	case PTR_TO_MEM:
7689 	case PTR_TO_MEM | MEM_RDONLY:
7690 	case PTR_TO_MEM | MEM_RINGBUF:
7691 	case PTR_TO_BUF:
7692 	case PTR_TO_BUF | MEM_RDONLY:
7693 	case SCALAR_VALUE:
7694 		return 0;
7695 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7696 	 * fixed offset.
7697 	 */
7698 	case PTR_TO_BTF_ID:
7699 	case PTR_TO_BTF_ID | MEM_ALLOC:
7700 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7701 	case PTR_TO_BTF_ID | MEM_RCU:
7702 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7703 		/* When referenced PTR_TO_BTF_ID is passed to release function,
7704 		 * its fixed offset must be 0. In the other cases, fixed offset
7705 		 * can be non-zero. This was already checked above. So pass
7706 		 * fixed_off_ok as true to allow fixed offset for all other
7707 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7708 		 * still need to do checks instead of returning.
7709 		 */
7710 		return __check_ptr_off_reg(env, reg, regno, true);
7711 	default:
7712 		return __check_ptr_off_reg(env, reg, regno, false);
7713 	}
7714 }
7715 
7716 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7717 						const struct bpf_func_proto *fn,
7718 						struct bpf_reg_state *regs)
7719 {
7720 	struct bpf_reg_state *state = NULL;
7721 	int i;
7722 
7723 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7724 		if (arg_type_is_dynptr(fn->arg_type[i])) {
7725 			if (state) {
7726 				verbose(env, "verifier internal error: multiple dynptr args\n");
7727 				return NULL;
7728 			}
7729 			state = &regs[BPF_REG_1 + i];
7730 		}
7731 
7732 	if (!state)
7733 		verbose(env, "verifier internal error: no dynptr arg found\n");
7734 
7735 	return state;
7736 }
7737 
7738 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7739 {
7740 	struct bpf_func_state *state = func(env, reg);
7741 	int spi;
7742 
7743 	if (reg->type == CONST_PTR_TO_DYNPTR)
7744 		return reg->id;
7745 	spi = dynptr_get_spi(env, reg);
7746 	if (spi < 0)
7747 		return spi;
7748 	return state->stack[spi].spilled_ptr.id;
7749 }
7750 
7751 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7752 {
7753 	struct bpf_func_state *state = func(env, reg);
7754 	int spi;
7755 
7756 	if (reg->type == CONST_PTR_TO_DYNPTR)
7757 		return reg->ref_obj_id;
7758 	spi = dynptr_get_spi(env, reg);
7759 	if (spi < 0)
7760 		return spi;
7761 	return state->stack[spi].spilled_ptr.ref_obj_id;
7762 }
7763 
7764 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7765 					    struct bpf_reg_state *reg)
7766 {
7767 	struct bpf_func_state *state = func(env, reg);
7768 	int spi;
7769 
7770 	if (reg->type == CONST_PTR_TO_DYNPTR)
7771 		return reg->dynptr.type;
7772 
7773 	spi = __get_spi(reg->off);
7774 	if (spi < 0) {
7775 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7776 		return BPF_DYNPTR_TYPE_INVALID;
7777 	}
7778 
7779 	return state->stack[spi].spilled_ptr.dynptr.type;
7780 }
7781 
7782 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7783 			  struct bpf_call_arg_meta *meta,
7784 			  const struct bpf_func_proto *fn,
7785 			  int insn_idx)
7786 {
7787 	u32 regno = BPF_REG_1 + arg;
7788 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7789 	enum bpf_arg_type arg_type = fn->arg_type[arg];
7790 	enum bpf_reg_type type = reg->type;
7791 	u32 *arg_btf_id = NULL;
7792 	int err = 0;
7793 
7794 	if (arg_type == ARG_DONTCARE)
7795 		return 0;
7796 
7797 	err = check_reg_arg(env, regno, SRC_OP);
7798 	if (err)
7799 		return err;
7800 
7801 	if (arg_type == ARG_ANYTHING) {
7802 		if (is_pointer_value(env, regno)) {
7803 			verbose(env, "R%d leaks addr into helper function\n",
7804 				regno);
7805 			return -EACCES;
7806 		}
7807 		return 0;
7808 	}
7809 
7810 	if (type_is_pkt_pointer(type) &&
7811 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7812 		verbose(env, "helper access to the packet is not allowed\n");
7813 		return -EACCES;
7814 	}
7815 
7816 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7817 		err = resolve_map_arg_type(env, meta, &arg_type);
7818 		if (err)
7819 			return err;
7820 	}
7821 
7822 	if (register_is_null(reg) && type_may_be_null(arg_type))
7823 		/* A NULL register has a SCALAR_VALUE type, so skip
7824 		 * type checking.
7825 		 */
7826 		goto skip_type_check;
7827 
7828 	/* arg_btf_id and arg_size are in a union. */
7829 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7830 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7831 		arg_btf_id = fn->arg_btf_id[arg];
7832 
7833 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7834 	if (err)
7835 		return err;
7836 
7837 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7838 	if (err)
7839 		return err;
7840 
7841 skip_type_check:
7842 	if (arg_type_is_release(arg_type)) {
7843 		if (arg_type_is_dynptr(arg_type)) {
7844 			struct bpf_func_state *state = func(env, reg);
7845 			int spi;
7846 
7847 			/* Only dynptr created on stack can be released, thus
7848 			 * the get_spi and stack state checks for spilled_ptr
7849 			 * should only be done before process_dynptr_func for
7850 			 * PTR_TO_STACK.
7851 			 */
7852 			if (reg->type == PTR_TO_STACK) {
7853 				spi = dynptr_get_spi(env, reg);
7854 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7855 					verbose(env, "arg %d is an unacquired reference\n", regno);
7856 					return -EINVAL;
7857 				}
7858 			} else {
7859 				verbose(env, "cannot release unowned const bpf_dynptr\n");
7860 				return -EINVAL;
7861 			}
7862 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
7863 			verbose(env, "R%d must be referenced when passed to release function\n",
7864 				regno);
7865 			return -EINVAL;
7866 		}
7867 		if (meta->release_regno) {
7868 			verbose(env, "verifier internal error: more than one release argument\n");
7869 			return -EFAULT;
7870 		}
7871 		meta->release_regno = regno;
7872 	}
7873 
7874 	if (reg->ref_obj_id) {
7875 		if (meta->ref_obj_id) {
7876 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7877 				regno, reg->ref_obj_id,
7878 				meta->ref_obj_id);
7879 			return -EFAULT;
7880 		}
7881 		meta->ref_obj_id = reg->ref_obj_id;
7882 	}
7883 
7884 	switch (base_type(arg_type)) {
7885 	case ARG_CONST_MAP_PTR:
7886 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7887 		if (meta->map_ptr) {
7888 			/* Use map_uid (which is unique id of inner map) to reject:
7889 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7890 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7891 			 * if (inner_map1 && inner_map2) {
7892 			 *     timer = bpf_map_lookup_elem(inner_map1);
7893 			 *     if (timer)
7894 			 *         // mismatch would have been allowed
7895 			 *         bpf_timer_init(timer, inner_map2);
7896 			 * }
7897 			 *
7898 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
7899 			 */
7900 			if (meta->map_ptr != reg->map_ptr ||
7901 			    meta->map_uid != reg->map_uid) {
7902 				verbose(env,
7903 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7904 					meta->map_uid, reg->map_uid);
7905 				return -EINVAL;
7906 			}
7907 		}
7908 		meta->map_ptr = reg->map_ptr;
7909 		meta->map_uid = reg->map_uid;
7910 		break;
7911 	case ARG_PTR_TO_MAP_KEY:
7912 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
7913 		 * check that [key, key + map->key_size) are within
7914 		 * stack limits and initialized
7915 		 */
7916 		if (!meta->map_ptr) {
7917 			/* in function declaration map_ptr must come before
7918 			 * map_key, so that it's verified and known before
7919 			 * we have to check map_key here. Otherwise it means
7920 			 * that kernel subsystem misconfigured verifier
7921 			 */
7922 			verbose(env, "invalid map_ptr to access map->key\n");
7923 			return -EACCES;
7924 		}
7925 		err = check_helper_mem_access(env, regno,
7926 					      meta->map_ptr->key_size, false,
7927 					      NULL);
7928 		break;
7929 	case ARG_PTR_TO_MAP_VALUE:
7930 		if (type_may_be_null(arg_type) && register_is_null(reg))
7931 			return 0;
7932 
7933 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
7934 		 * check [value, value + map->value_size) validity
7935 		 */
7936 		if (!meta->map_ptr) {
7937 			/* kernel subsystem misconfigured verifier */
7938 			verbose(env, "invalid map_ptr to access map->value\n");
7939 			return -EACCES;
7940 		}
7941 		meta->raw_mode = arg_type & MEM_UNINIT;
7942 		err = check_helper_mem_access(env, regno,
7943 					      meta->map_ptr->value_size, false,
7944 					      meta);
7945 		break;
7946 	case ARG_PTR_TO_PERCPU_BTF_ID:
7947 		if (!reg->btf_id) {
7948 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7949 			return -EACCES;
7950 		}
7951 		meta->ret_btf = reg->btf;
7952 		meta->ret_btf_id = reg->btf_id;
7953 		break;
7954 	case ARG_PTR_TO_SPIN_LOCK:
7955 		if (in_rbtree_lock_required_cb(env)) {
7956 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7957 			return -EACCES;
7958 		}
7959 		if (meta->func_id == BPF_FUNC_spin_lock) {
7960 			err = process_spin_lock(env, regno, true);
7961 			if (err)
7962 				return err;
7963 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
7964 			err = process_spin_lock(env, regno, false);
7965 			if (err)
7966 				return err;
7967 		} else {
7968 			verbose(env, "verifier internal error\n");
7969 			return -EFAULT;
7970 		}
7971 		break;
7972 	case ARG_PTR_TO_TIMER:
7973 		err = process_timer_func(env, regno, meta);
7974 		if (err)
7975 			return err;
7976 		break;
7977 	case ARG_PTR_TO_FUNC:
7978 		meta->subprogno = reg->subprogno;
7979 		break;
7980 	case ARG_PTR_TO_MEM:
7981 		/* The access to this pointer is only checked when we hit the
7982 		 * next is_mem_size argument below.
7983 		 */
7984 		meta->raw_mode = arg_type & MEM_UNINIT;
7985 		if (arg_type & MEM_FIXED_SIZE) {
7986 			err = check_helper_mem_access(env, regno,
7987 						      fn->arg_size[arg], false,
7988 						      meta);
7989 		}
7990 		break;
7991 	case ARG_CONST_SIZE:
7992 		err = check_mem_size_reg(env, reg, regno, false, meta);
7993 		break;
7994 	case ARG_CONST_SIZE_OR_ZERO:
7995 		err = check_mem_size_reg(env, reg, regno, true, meta);
7996 		break;
7997 	case ARG_PTR_TO_DYNPTR:
7998 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
7999 		if (err)
8000 			return err;
8001 		break;
8002 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8003 		if (!tnum_is_const(reg->var_off)) {
8004 			verbose(env, "R%d is not a known constant'\n",
8005 				regno);
8006 			return -EACCES;
8007 		}
8008 		meta->mem_size = reg->var_off.value;
8009 		err = mark_chain_precision(env, regno);
8010 		if (err)
8011 			return err;
8012 		break;
8013 	case ARG_PTR_TO_INT:
8014 	case ARG_PTR_TO_LONG:
8015 	{
8016 		int size = int_ptr_type_to_size(arg_type);
8017 
8018 		err = check_helper_mem_access(env, regno, size, false, meta);
8019 		if (err)
8020 			return err;
8021 		err = check_ptr_alignment(env, reg, 0, size, true);
8022 		break;
8023 	}
8024 	case ARG_PTR_TO_CONST_STR:
8025 	{
8026 		struct bpf_map *map = reg->map_ptr;
8027 		int map_off;
8028 		u64 map_addr;
8029 		char *str_ptr;
8030 
8031 		if (!bpf_map_is_rdonly(map)) {
8032 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8033 			return -EACCES;
8034 		}
8035 
8036 		if (!tnum_is_const(reg->var_off)) {
8037 			verbose(env, "R%d is not a constant address'\n", regno);
8038 			return -EACCES;
8039 		}
8040 
8041 		if (!map->ops->map_direct_value_addr) {
8042 			verbose(env, "no direct value access support for this map type\n");
8043 			return -EACCES;
8044 		}
8045 
8046 		err = check_map_access(env, regno, reg->off,
8047 				       map->value_size - reg->off, false,
8048 				       ACCESS_HELPER);
8049 		if (err)
8050 			return err;
8051 
8052 		map_off = reg->off + reg->var_off.value;
8053 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8054 		if (err) {
8055 			verbose(env, "direct value access on string failed\n");
8056 			return err;
8057 		}
8058 
8059 		str_ptr = (char *)(long)(map_addr);
8060 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8061 			verbose(env, "string is not zero-terminated\n");
8062 			return -EINVAL;
8063 		}
8064 		break;
8065 	}
8066 	case ARG_PTR_TO_KPTR:
8067 		err = process_kptr_func(env, regno, meta);
8068 		if (err)
8069 			return err;
8070 		break;
8071 	}
8072 
8073 	return err;
8074 }
8075 
8076 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8077 {
8078 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8079 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8080 
8081 	if (func_id != BPF_FUNC_map_update_elem)
8082 		return false;
8083 
8084 	/* It's not possible to get access to a locked struct sock in these
8085 	 * contexts, so updating is safe.
8086 	 */
8087 	switch (type) {
8088 	case BPF_PROG_TYPE_TRACING:
8089 		if (eatype == BPF_TRACE_ITER)
8090 			return true;
8091 		break;
8092 	case BPF_PROG_TYPE_SOCKET_FILTER:
8093 	case BPF_PROG_TYPE_SCHED_CLS:
8094 	case BPF_PROG_TYPE_SCHED_ACT:
8095 	case BPF_PROG_TYPE_XDP:
8096 	case BPF_PROG_TYPE_SK_REUSEPORT:
8097 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8098 	case BPF_PROG_TYPE_SK_LOOKUP:
8099 		return true;
8100 	default:
8101 		break;
8102 	}
8103 
8104 	verbose(env, "cannot update sockmap in this context\n");
8105 	return false;
8106 }
8107 
8108 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8109 {
8110 	return env->prog->jit_requested &&
8111 	       bpf_jit_supports_subprog_tailcalls();
8112 }
8113 
8114 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8115 					struct bpf_map *map, int func_id)
8116 {
8117 	if (!map)
8118 		return 0;
8119 
8120 	/* We need a two way check, first is from map perspective ... */
8121 	switch (map->map_type) {
8122 	case BPF_MAP_TYPE_PROG_ARRAY:
8123 		if (func_id != BPF_FUNC_tail_call)
8124 			goto error;
8125 		break;
8126 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8127 		if (func_id != BPF_FUNC_perf_event_read &&
8128 		    func_id != BPF_FUNC_perf_event_output &&
8129 		    func_id != BPF_FUNC_skb_output &&
8130 		    func_id != BPF_FUNC_perf_event_read_value &&
8131 		    func_id != BPF_FUNC_xdp_output)
8132 			goto error;
8133 		break;
8134 	case BPF_MAP_TYPE_RINGBUF:
8135 		if (func_id != BPF_FUNC_ringbuf_output &&
8136 		    func_id != BPF_FUNC_ringbuf_reserve &&
8137 		    func_id != BPF_FUNC_ringbuf_query &&
8138 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8139 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8140 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8141 			goto error;
8142 		break;
8143 	case BPF_MAP_TYPE_USER_RINGBUF:
8144 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8145 			goto error;
8146 		break;
8147 	case BPF_MAP_TYPE_STACK_TRACE:
8148 		if (func_id != BPF_FUNC_get_stackid)
8149 			goto error;
8150 		break;
8151 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8152 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8153 		    func_id != BPF_FUNC_current_task_under_cgroup)
8154 			goto error;
8155 		break;
8156 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8157 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8158 		if (func_id != BPF_FUNC_get_local_storage)
8159 			goto error;
8160 		break;
8161 	case BPF_MAP_TYPE_DEVMAP:
8162 	case BPF_MAP_TYPE_DEVMAP_HASH:
8163 		if (func_id != BPF_FUNC_redirect_map &&
8164 		    func_id != BPF_FUNC_map_lookup_elem)
8165 			goto error;
8166 		break;
8167 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8168 	 * appear.
8169 	 */
8170 	case BPF_MAP_TYPE_CPUMAP:
8171 		if (func_id != BPF_FUNC_redirect_map)
8172 			goto error;
8173 		break;
8174 	case BPF_MAP_TYPE_XSKMAP:
8175 		if (func_id != BPF_FUNC_redirect_map &&
8176 		    func_id != BPF_FUNC_map_lookup_elem)
8177 			goto error;
8178 		break;
8179 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8180 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8181 		if (func_id != BPF_FUNC_map_lookup_elem)
8182 			goto error;
8183 		break;
8184 	case BPF_MAP_TYPE_SOCKMAP:
8185 		if (func_id != BPF_FUNC_sk_redirect_map &&
8186 		    func_id != BPF_FUNC_sock_map_update &&
8187 		    func_id != BPF_FUNC_map_delete_elem &&
8188 		    func_id != BPF_FUNC_msg_redirect_map &&
8189 		    func_id != BPF_FUNC_sk_select_reuseport &&
8190 		    func_id != BPF_FUNC_map_lookup_elem &&
8191 		    !may_update_sockmap(env, func_id))
8192 			goto error;
8193 		break;
8194 	case BPF_MAP_TYPE_SOCKHASH:
8195 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8196 		    func_id != BPF_FUNC_sock_hash_update &&
8197 		    func_id != BPF_FUNC_map_delete_elem &&
8198 		    func_id != BPF_FUNC_msg_redirect_hash &&
8199 		    func_id != BPF_FUNC_sk_select_reuseport &&
8200 		    func_id != BPF_FUNC_map_lookup_elem &&
8201 		    !may_update_sockmap(env, func_id))
8202 			goto error;
8203 		break;
8204 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8205 		if (func_id != BPF_FUNC_sk_select_reuseport)
8206 			goto error;
8207 		break;
8208 	case BPF_MAP_TYPE_QUEUE:
8209 	case BPF_MAP_TYPE_STACK:
8210 		if (func_id != BPF_FUNC_map_peek_elem &&
8211 		    func_id != BPF_FUNC_map_pop_elem &&
8212 		    func_id != BPF_FUNC_map_push_elem)
8213 			goto error;
8214 		break;
8215 	case BPF_MAP_TYPE_SK_STORAGE:
8216 		if (func_id != BPF_FUNC_sk_storage_get &&
8217 		    func_id != BPF_FUNC_sk_storage_delete &&
8218 		    func_id != BPF_FUNC_kptr_xchg)
8219 			goto error;
8220 		break;
8221 	case BPF_MAP_TYPE_INODE_STORAGE:
8222 		if (func_id != BPF_FUNC_inode_storage_get &&
8223 		    func_id != BPF_FUNC_inode_storage_delete &&
8224 		    func_id != BPF_FUNC_kptr_xchg)
8225 			goto error;
8226 		break;
8227 	case BPF_MAP_TYPE_TASK_STORAGE:
8228 		if (func_id != BPF_FUNC_task_storage_get &&
8229 		    func_id != BPF_FUNC_task_storage_delete &&
8230 		    func_id != BPF_FUNC_kptr_xchg)
8231 			goto error;
8232 		break;
8233 	case BPF_MAP_TYPE_CGRP_STORAGE:
8234 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8235 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8236 		    func_id != BPF_FUNC_kptr_xchg)
8237 			goto error;
8238 		break;
8239 	case BPF_MAP_TYPE_BLOOM_FILTER:
8240 		if (func_id != BPF_FUNC_map_peek_elem &&
8241 		    func_id != BPF_FUNC_map_push_elem)
8242 			goto error;
8243 		break;
8244 	default:
8245 		break;
8246 	}
8247 
8248 	/* ... and second from the function itself. */
8249 	switch (func_id) {
8250 	case BPF_FUNC_tail_call:
8251 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8252 			goto error;
8253 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8254 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8255 			return -EINVAL;
8256 		}
8257 		break;
8258 	case BPF_FUNC_perf_event_read:
8259 	case BPF_FUNC_perf_event_output:
8260 	case BPF_FUNC_perf_event_read_value:
8261 	case BPF_FUNC_skb_output:
8262 	case BPF_FUNC_xdp_output:
8263 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8264 			goto error;
8265 		break;
8266 	case BPF_FUNC_ringbuf_output:
8267 	case BPF_FUNC_ringbuf_reserve:
8268 	case BPF_FUNC_ringbuf_query:
8269 	case BPF_FUNC_ringbuf_reserve_dynptr:
8270 	case BPF_FUNC_ringbuf_submit_dynptr:
8271 	case BPF_FUNC_ringbuf_discard_dynptr:
8272 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8273 			goto error;
8274 		break;
8275 	case BPF_FUNC_user_ringbuf_drain:
8276 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8277 			goto error;
8278 		break;
8279 	case BPF_FUNC_get_stackid:
8280 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8281 			goto error;
8282 		break;
8283 	case BPF_FUNC_current_task_under_cgroup:
8284 	case BPF_FUNC_skb_under_cgroup:
8285 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8286 			goto error;
8287 		break;
8288 	case BPF_FUNC_redirect_map:
8289 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8290 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8291 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8292 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8293 			goto error;
8294 		break;
8295 	case BPF_FUNC_sk_redirect_map:
8296 	case BPF_FUNC_msg_redirect_map:
8297 	case BPF_FUNC_sock_map_update:
8298 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8299 			goto error;
8300 		break;
8301 	case BPF_FUNC_sk_redirect_hash:
8302 	case BPF_FUNC_msg_redirect_hash:
8303 	case BPF_FUNC_sock_hash_update:
8304 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8305 			goto error;
8306 		break;
8307 	case BPF_FUNC_get_local_storage:
8308 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8309 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8310 			goto error;
8311 		break;
8312 	case BPF_FUNC_sk_select_reuseport:
8313 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8314 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8315 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8316 			goto error;
8317 		break;
8318 	case BPF_FUNC_map_pop_elem:
8319 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8320 		    map->map_type != BPF_MAP_TYPE_STACK)
8321 			goto error;
8322 		break;
8323 	case BPF_FUNC_map_peek_elem:
8324 	case BPF_FUNC_map_push_elem:
8325 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8326 		    map->map_type != BPF_MAP_TYPE_STACK &&
8327 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8328 			goto error;
8329 		break;
8330 	case BPF_FUNC_map_lookup_percpu_elem:
8331 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8332 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8333 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8334 			goto error;
8335 		break;
8336 	case BPF_FUNC_sk_storage_get:
8337 	case BPF_FUNC_sk_storage_delete:
8338 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8339 			goto error;
8340 		break;
8341 	case BPF_FUNC_inode_storage_get:
8342 	case BPF_FUNC_inode_storage_delete:
8343 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8344 			goto error;
8345 		break;
8346 	case BPF_FUNC_task_storage_get:
8347 	case BPF_FUNC_task_storage_delete:
8348 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8349 			goto error;
8350 		break;
8351 	case BPF_FUNC_cgrp_storage_get:
8352 	case BPF_FUNC_cgrp_storage_delete:
8353 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8354 			goto error;
8355 		break;
8356 	default:
8357 		break;
8358 	}
8359 
8360 	return 0;
8361 error:
8362 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8363 		map->map_type, func_id_name(func_id), func_id);
8364 	return -EINVAL;
8365 }
8366 
8367 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8368 {
8369 	int count = 0;
8370 
8371 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8372 		count++;
8373 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8374 		count++;
8375 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8376 		count++;
8377 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8378 		count++;
8379 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8380 		count++;
8381 
8382 	/* We only support one arg being in raw mode at the moment,
8383 	 * which is sufficient for the helper functions we have
8384 	 * right now.
8385 	 */
8386 	return count <= 1;
8387 }
8388 
8389 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8390 {
8391 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8392 	bool has_size = fn->arg_size[arg] != 0;
8393 	bool is_next_size = false;
8394 
8395 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8396 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8397 
8398 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8399 		return is_next_size;
8400 
8401 	return has_size == is_next_size || is_next_size == is_fixed;
8402 }
8403 
8404 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8405 {
8406 	/* bpf_xxx(..., buf, len) call will access 'len'
8407 	 * bytes from memory 'buf'. Both arg types need
8408 	 * to be paired, so make sure there's no buggy
8409 	 * helper function specification.
8410 	 */
8411 	if (arg_type_is_mem_size(fn->arg1_type) ||
8412 	    check_args_pair_invalid(fn, 0) ||
8413 	    check_args_pair_invalid(fn, 1) ||
8414 	    check_args_pair_invalid(fn, 2) ||
8415 	    check_args_pair_invalid(fn, 3) ||
8416 	    check_args_pair_invalid(fn, 4))
8417 		return false;
8418 
8419 	return true;
8420 }
8421 
8422 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8423 {
8424 	int i;
8425 
8426 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8427 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8428 			return !!fn->arg_btf_id[i];
8429 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8430 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8431 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8432 		    /* arg_btf_id and arg_size are in a union. */
8433 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8434 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8435 			return false;
8436 	}
8437 
8438 	return true;
8439 }
8440 
8441 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8442 {
8443 	return check_raw_mode_ok(fn) &&
8444 	       check_arg_pair_ok(fn) &&
8445 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8446 }
8447 
8448 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8449  * are now invalid, so turn them into unknown SCALAR_VALUE.
8450  *
8451  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8452  * since these slices point to packet data.
8453  */
8454 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8455 {
8456 	struct bpf_func_state *state;
8457 	struct bpf_reg_state *reg;
8458 
8459 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8460 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8461 			mark_reg_invalid(env, reg);
8462 	}));
8463 }
8464 
8465 enum {
8466 	AT_PKT_END = -1,
8467 	BEYOND_PKT_END = -2,
8468 };
8469 
8470 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8471 {
8472 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8473 	struct bpf_reg_state *reg = &state->regs[regn];
8474 
8475 	if (reg->type != PTR_TO_PACKET)
8476 		/* PTR_TO_PACKET_META is not supported yet */
8477 		return;
8478 
8479 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8480 	 * How far beyond pkt_end it goes is unknown.
8481 	 * if (!range_open) it's the case of pkt >= pkt_end
8482 	 * if (range_open) it's the case of pkt > pkt_end
8483 	 * hence this pointer is at least 1 byte bigger than pkt_end
8484 	 */
8485 	if (range_open)
8486 		reg->range = BEYOND_PKT_END;
8487 	else
8488 		reg->range = AT_PKT_END;
8489 }
8490 
8491 /* The pointer with the specified id has released its reference to kernel
8492  * resources. Identify all copies of the same pointer and clear the reference.
8493  */
8494 static int release_reference(struct bpf_verifier_env *env,
8495 			     int ref_obj_id)
8496 {
8497 	struct bpf_func_state *state;
8498 	struct bpf_reg_state *reg;
8499 	int err;
8500 
8501 	err = release_reference_state(cur_func(env), ref_obj_id);
8502 	if (err)
8503 		return err;
8504 
8505 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8506 		if (reg->ref_obj_id == ref_obj_id)
8507 			mark_reg_invalid(env, reg);
8508 	}));
8509 
8510 	return 0;
8511 }
8512 
8513 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8514 {
8515 	struct bpf_func_state *unused;
8516 	struct bpf_reg_state *reg;
8517 
8518 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8519 		if (type_is_non_owning_ref(reg->type))
8520 			mark_reg_invalid(env, reg);
8521 	}));
8522 }
8523 
8524 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8525 				    struct bpf_reg_state *regs)
8526 {
8527 	int i;
8528 
8529 	/* after the call registers r0 - r5 were scratched */
8530 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8531 		mark_reg_not_init(env, regs, caller_saved[i]);
8532 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8533 	}
8534 }
8535 
8536 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8537 				   struct bpf_func_state *caller,
8538 				   struct bpf_func_state *callee,
8539 				   int insn_idx);
8540 
8541 static int set_callee_state(struct bpf_verifier_env *env,
8542 			    struct bpf_func_state *caller,
8543 			    struct bpf_func_state *callee, int insn_idx);
8544 
8545 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8546 			     int *insn_idx, int subprog,
8547 			     set_callee_state_fn set_callee_state_cb)
8548 {
8549 	struct bpf_verifier_state *state = env->cur_state;
8550 	struct bpf_func_state *caller, *callee;
8551 	int err;
8552 
8553 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8554 		verbose(env, "the call stack of %d frames is too deep\n",
8555 			state->curframe + 2);
8556 		return -E2BIG;
8557 	}
8558 
8559 	caller = state->frame[state->curframe];
8560 	if (state->frame[state->curframe + 1]) {
8561 		verbose(env, "verifier bug. Frame %d already allocated\n",
8562 			state->curframe + 1);
8563 		return -EFAULT;
8564 	}
8565 
8566 	err = btf_check_subprog_call(env, subprog, caller->regs);
8567 	if (err == -EFAULT)
8568 		return err;
8569 	if (subprog_is_global(env, subprog)) {
8570 		if (err) {
8571 			verbose(env, "Caller passes invalid args into func#%d\n",
8572 				subprog);
8573 			return err;
8574 		} else {
8575 			if (env->log.level & BPF_LOG_LEVEL)
8576 				verbose(env,
8577 					"Func#%d is global and valid. Skipping.\n",
8578 					subprog);
8579 			clear_caller_saved_regs(env, caller->regs);
8580 
8581 			/* All global functions return a 64-bit SCALAR_VALUE */
8582 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8583 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8584 
8585 			/* continue with next insn after call */
8586 			return 0;
8587 		}
8588 	}
8589 
8590 	/* set_callee_state is used for direct subprog calls, but we are
8591 	 * interested in validating only BPF helpers that can call subprogs as
8592 	 * callbacks
8593 	 */
8594 	if (set_callee_state_cb != set_callee_state) {
8595 		if (bpf_pseudo_kfunc_call(insn) &&
8596 		    !is_callback_calling_kfunc(insn->imm)) {
8597 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8598 				func_id_name(insn->imm), insn->imm);
8599 			return -EFAULT;
8600 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8601 			   !is_callback_calling_function(insn->imm)) { /* helper */
8602 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8603 				func_id_name(insn->imm), insn->imm);
8604 			return -EFAULT;
8605 		}
8606 	}
8607 
8608 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8609 	    insn->src_reg == 0 &&
8610 	    insn->imm == BPF_FUNC_timer_set_callback) {
8611 		struct bpf_verifier_state *async_cb;
8612 
8613 		/* there is no real recursion here. timer callbacks are async */
8614 		env->subprog_info[subprog].is_async_cb = true;
8615 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8616 					 *insn_idx, subprog);
8617 		if (!async_cb)
8618 			return -EFAULT;
8619 		callee = async_cb->frame[0];
8620 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8621 
8622 		/* Convert bpf_timer_set_callback() args into timer callback args */
8623 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8624 		if (err)
8625 			return err;
8626 
8627 		clear_caller_saved_regs(env, caller->regs);
8628 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8629 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8630 		/* continue with next insn after call */
8631 		return 0;
8632 	}
8633 
8634 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8635 	if (!callee)
8636 		return -ENOMEM;
8637 	state->frame[state->curframe + 1] = callee;
8638 
8639 	/* callee cannot access r0, r6 - r9 for reading and has to write
8640 	 * into its own stack before reading from it.
8641 	 * callee can read/write into caller's stack
8642 	 */
8643 	init_func_state(env, callee,
8644 			/* remember the callsite, it will be used by bpf_exit */
8645 			*insn_idx /* callsite */,
8646 			state->curframe + 1 /* frameno within this callchain */,
8647 			subprog /* subprog number within this prog */);
8648 
8649 	/* Transfer references to the callee */
8650 	err = copy_reference_state(callee, caller);
8651 	if (err)
8652 		goto err_out;
8653 
8654 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8655 	if (err)
8656 		goto err_out;
8657 
8658 	clear_caller_saved_regs(env, caller->regs);
8659 
8660 	/* only increment it after check_reg_arg() finished */
8661 	state->curframe++;
8662 
8663 	/* and go analyze first insn of the callee */
8664 	*insn_idx = env->subprog_info[subprog].start - 1;
8665 
8666 	if (env->log.level & BPF_LOG_LEVEL) {
8667 		verbose(env, "caller:\n");
8668 		print_verifier_state(env, caller, true);
8669 		verbose(env, "callee:\n");
8670 		print_verifier_state(env, callee, true);
8671 	}
8672 	return 0;
8673 
8674 err_out:
8675 	free_func_state(callee);
8676 	state->frame[state->curframe + 1] = NULL;
8677 	return err;
8678 }
8679 
8680 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8681 				   struct bpf_func_state *caller,
8682 				   struct bpf_func_state *callee)
8683 {
8684 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8685 	 *      void *callback_ctx, u64 flags);
8686 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8687 	 *      void *callback_ctx);
8688 	 */
8689 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8690 
8691 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8692 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8693 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8694 
8695 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8696 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8697 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8698 
8699 	/* pointer to stack or null */
8700 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8701 
8702 	/* unused */
8703 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8704 	return 0;
8705 }
8706 
8707 static int set_callee_state(struct bpf_verifier_env *env,
8708 			    struct bpf_func_state *caller,
8709 			    struct bpf_func_state *callee, int insn_idx)
8710 {
8711 	int i;
8712 
8713 	/* copy r1 - r5 args that callee can access.  The copy includes parent
8714 	 * pointers, which connects us up to the liveness chain
8715 	 */
8716 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8717 		callee->regs[i] = caller->regs[i];
8718 	return 0;
8719 }
8720 
8721 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8722 			   int *insn_idx)
8723 {
8724 	int subprog, target_insn;
8725 
8726 	target_insn = *insn_idx + insn->imm + 1;
8727 	subprog = find_subprog(env, target_insn);
8728 	if (subprog < 0) {
8729 		verbose(env, "verifier bug. No program starts at insn %d\n",
8730 			target_insn);
8731 		return -EFAULT;
8732 	}
8733 
8734 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8735 }
8736 
8737 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8738 				       struct bpf_func_state *caller,
8739 				       struct bpf_func_state *callee,
8740 				       int insn_idx)
8741 {
8742 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8743 	struct bpf_map *map;
8744 	int err;
8745 
8746 	if (bpf_map_ptr_poisoned(insn_aux)) {
8747 		verbose(env, "tail_call abusing map_ptr\n");
8748 		return -EINVAL;
8749 	}
8750 
8751 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8752 	if (!map->ops->map_set_for_each_callback_args ||
8753 	    !map->ops->map_for_each_callback) {
8754 		verbose(env, "callback function not allowed for map\n");
8755 		return -ENOTSUPP;
8756 	}
8757 
8758 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8759 	if (err)
8760 		return err;
8761 
8762 	callee->in_callback_fn = true;
8763 	callee->callback_ret_range = tnum_range(0, 1);
8764 	return 0;
8765 }
8766 
8767 static int set_loop_callback_state(struct bpf_verifier_env *env,
8768 				   struct bpf_func_state *caller,
8769 				   struct bpf_func_state *callee,
8770 				   int insn_idx)
8771 {
8772 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8773 	 *	    u64 flags);
8774 	 * callback_fn(u32 index, void *callback_ctx);
8775 	 */
8776 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8777 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8778 
8779 	/* unused */
8780 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8781 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8782 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8783 
8784 	callee->in_callback_fn = true;
8785 	callee->callback_ret_range = tnum_range(0, 1);
8786 	return 0;
8787 }
8788 
8789 static int set_timer_callback_state(struct bpf_verifier_env *env,
8790 				    struct bpf_func_state *caller,
8791 				    struct bpf_func_state *callee,
8792 				    int insn_idx)
8793 {
8794 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8795 
8796 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8797 	 * callback_fn(struct bpf_map *map, void *key, void *value);
8798 	 */
8799 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8800 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8801 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
8802 
8803 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8804 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8805 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
8806 
8807 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8808 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8809 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
8810 
8811 	/* unused */
8812 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8813 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8814 	callee->in_async_callback_fn = true;
8815 	callee->callback_ret_range = tnum_range(0, 1);
8816 	return 0;
8817 }
8818 
8819 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8820 				       struct bpf_func_state *caller,
8821 				       struct bpf_func_state *callee,
8822 				       int insn_idx)
8823 {
8824 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8825 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8826 	 * (callback_fn)(struct task_struct *task,
8827 	 *               struct vm_area_struct *vma, void *callback_ctx);
8828 	 */
8829 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8830 
8831 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8832 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8833 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8834 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8835 
8836 	/* pointer to stack or null */
8837 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8838 
8839 	/* unused */
8840 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8841 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8842 	callee->in_callback_fn = true;
8843 	callee->callback_ret_range = tnum_range(0, 1);
8844 	return 0;
8845 }
8846 
8847 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8848 					   struct bpf_func_state *caller,
8849 					   struct bpf_func_state *callee,
8850 					   int insn_idx)
8851 {
8852 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8853 	 *			  callback_ctx, u64 flags);
8854 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8855 	 */
8856 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8857 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8858 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8859 
8860 	/* unused */
8861 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8862 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8863 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8864 
8865 	callee->in_callback_fn = true;
8866 	callee->callback_ret_range = tnum_range(0, 1);
8867 	return 0;
8868 }
8869 
8870 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8871 					 struct bpf_func_state *caller,
8872 					 struct bpf_func_state *callee,
8873 					 int insn_idx)
8874 {
8875 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
8876 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8877 	 *
8878 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
8879 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8880 	 * by this point, so look at 'root'
8881 	 */
8882 	struct btf_field *field;
8883 
8884 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8885 				      BPF_RB_ROOT);
8886 	if (!field || !field->graph_root.value_btf_id)
8887 		return -EFAULT;
8888 
8889 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8890 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8891 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8892 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8893 
8894 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8895 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8896 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8897 	callee->in_callback_fn = true;
8898 	callee->callback_ret_range = tnum_range(0, 1);
8899 	return 0;
8900 }
8901 
8902 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8903 
8904 /* Are we currently verifying the callback for a rbtree helper that must
8905  * be called with lock held? If so, no need to complain about unreleased
8906  * lock
8907  */
8908 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8909 {
8910 	struct bpf_verifier_state *state = env->cur_state;
8911 	struct bpf_insn *insn = env->prog->insnsi;
8912 	struct bpf_func_state *callee;
8913 	int kfunc_btf_id;
8914 
8915 	if (!state->curframe)
8916 		return false;
8917 
8918 	callee = state->frame[state->curframe];
8919 
8920 	if (!callee->in_callback_fn)
8921 		return false;
8922 
8923 	kfunc_btf_id = insn[callee->callsite].imm;
8924 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8925 }
8926 
8927 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8928 {
8929 	struct bpf_verifier_state *state = env->cur_state;
8930 	struct bpf_func_state *caller, *callee;
8931 	struct bpf_reg_state *r0;
8932 	int err;
8933 
8934 	callee = state->frame[state->curframe];
8935 	r0 = &callee->regs[BPF_REG_0];
8936 	if (r0->type == PTR_TO_STACK) {
8937 		/* technically it's ok to return caller's stack pointer
8938 		 * (or caller's caller's pointer) back to the caller,
8939 		 * since these pointers are valid. Only current stack
8940 		 * pointer will be invalid as soon as function exits,
8941 		 * but let's be conservative
8942 		 */
8943 		verbose(env, "cannot return stack pointer to the caller\n");
8944 		return -EINVAL;
8945 	}
8946 
8947 	caller = state->frame[state->curframe - 1];
8948 	if (callee->in_callback_fn) {
8949 		/* enforce R0 return value range [0, 1]. */
8950 		struct tnum range = callee->callback_ret_range;
8951 
8952 		if (r0->type != SCALAR_VALUE) {
8953 			verbose(env, "R0 not a scalar value\n");
8954 			return -EACCES;
8955 		}
8956 		if (!tnum_in(range, r0->var_off)) {
8957 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8958 			return -EINVAL;
8959 		}
8960 	} else {
8961 		/* return to the caller whatever r0 had in the callee */
8962 		caller->regs[BPF_REG_0] = *r0;
8963 	}
8964 
8965 	/* callback_fn frame should have released its own additions to parent's
8966 	 * reference state at this point, or check_reference_leak would
8967 	 * complain, hence it must be the same as the caller. There is no need
8968 	 * to copy it back.
8969 	 */
8970 	if (!callee->in_callback_fn) {
8971 		/* Transfer references to the caller */
8972 		err = copy_reference_state(caller, callee);
8973 		if (err)
8974 			return err;
8975 	}
8976 
8977 	*insn_idx = callee->callsite + 1;
8978 	if (env->log.level & BPF_LOG_LEVEL) {
8979 		verbose(env, "returning from callee:\n");
8980 		print_verifier_state(env, callee, true);
8981 		verbose(env, "to caller at %d:\n", *insn_idx);
8982 		print_verifier_state(env, caller, true);
8983 	}
8984 	/* clear everything in the callee */
8985 	free_func_state(callee);
8986 	state->frame[state->curframe--] = NULL;
8987 	return 0;
8988 }
8989 
8990 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8991 				   int func_id,
8992 				   struct bpf_call_arg_meta *meta)
8993 {
8994 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8995 
8996 	if (ret_type != RET_INTEGER ||
8997 	    (func_id != BPF_FUNC_get_stack &&
8998 	     func_id != BPF_FUNC_get_task_stack &&
8999 	     func_id != BPF_FUNC_probe_read_str &&
9000 	     func_id != BPF_FUNC_probe_read_kernel_str &&
9001 	     func_id != BPF_FUNC_probe_read_user_str))
9002 		return;
9003 
9004 	ret_reg->smax_value = meta->msize_max_value;
9005 	ret_reg->s32_max_value = meta->msize_max_value;
9006 	ret_reg->smin_value = -MAX_ERRNO;
9007 	ret_reg->s32_min_value = -MAX_ERRNO;
9008 	reg_bounds_sync(ret_reg);
9009 }
9010 
9011 static int
9012 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9013 		int func_id, int insn_idx)
9014 {
9015 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9016 	struct bpf_map *map = meta->map_ptr;
9017 
9018 	if (func_id != BPF_FUNC_tail_call &&
9019 	    func_id != BPF_FUNC_map_lookup_elem &&
9020 	    func_id != BPF_FUNC_map_update_elem &&
9021 	    func_id != BPF_FUNC_map_delete_elem &&
9022 	    func_id != BPF_FUNC_map_push_elem &&
9023 	    func_id != BPF_FUNC_map_pop_elem &&
9024 	    func_id != BPF_FUNC_map_peek_elem &&
9025 	    func_id != BPF_FUNC_for_each_map_elem &&
9026 	    func_id != BPF_FUNC_redirect_map &&
9027 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9028 		return 0;
9029 
9030 	if (map == NULL) {
9031 		verbose(env, "kernel subsystem misconfigured verifier\n");
9032 		return -EINVAL;
9033 	}
9034 
9035 	/* In case of read-only, some additional restrictions
9036 	 * need to be applied in order to prevent altering the
9037 	 * state of the map from program side.
9038 	 */
9039 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9040 	    (func_id == BPF_FUNC_map_delete_elem ||
9041 	     func_id == BPF_FUNC_map_update_elem ||
9042 	     func_id == BPF_FUNC_map_push_elem ||
9043 	     func_id == BPF_FUNC_map_pop_elem)) {
9044 		verbose(env, "write into map forbidden\n");
9045 		return -EACCES;
9046 	}
9047 
9048 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9049 		bpf_map_ptr_store(aux, meta->map_ptr,
9050 				  !meta->map_ptr->bypass_spec_v1);
9051 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9052 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9053 				  !meta->map_ptr->bypass_spec_v1);
9054 	return 0;
9055 }
9056 
9057 static int
9058 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9059 		int func_id, int insn_idx)
9060 {
9061 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9062 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9063 	struct bpf_map *map = meta->map_ptr;
9064 	u64 val, max;
9065 	int err;
9066 
9067 	if (func_id != BPF_FUNC_tail_call)
9068 		return 0;
9069 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9070 		verbose(env, "kernel subsystem misconfigured verifier\n");
9071 		return -EINVAL;
9072 	}
9073 
9074 	reg = &regs[BPF_REG_3];
9075 	val = reg->var_off.value;
9076 	max = map->max_entries;
9077 
9078 	if (!(register_is_const(reg) && val < max)) {
9079 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9080 		return 0;
9081 	}
9082 
9083 	err = mark_chain_precision(env, BPF_REG_3);
9084 	if (err)
9085 		return err;
9086 	if (bpf_map_key_unseen(aux))
9087 		bpf_map_key_store(aux, val);
9088 	else if (!bpf_map_key_poisoned(aux) &&
9089 		  bpf_map_key_immediate(aux) != val)
9090 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9091 	return 0;
9092 }
9093 
9094 static int check_reference_leak(struct bpf_verifier_env *env)
9095 {
9096 	struct bpf_func_state *state = cur_func(env);
9097 	bool refs_lingering = false;
9098 	int i;
9099 
9100 	if (state->frameno && !state->in_callback_fn)
9101 		return 0;
9102 
9103 	for (i = 0; i < state->acquired_refs; i++) {
9104 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9105 			continue;
9106 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9107 			state->refs[i].id, state->refs[i].insn_idx);
9108 		refs_lingering = true;
9109 	}
9110 	return refs_lingering ? -EINVAL : 0;
9111 }
9112 
9113 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9114 				   struct bpf_reg_state *regs)
9115 {
9116 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9117 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9118 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9119 	struct bpf_bprintf_data data = {};
9120 	int err, fmt_map_off, num_args;
9121 	u64 fmt_addr;
9122 	char *fmt;
9123 
9124 	/* data must be an array of u64 */
9125 	if (data_len_reg->var_off.value % 8)
9126 		return -EINVAL;
9127 	num_args = data_len_reg->var_off.value / 8;
9128 
9129 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9130 	 * and map_direct_value_addr is set.
9131 	 */
9132 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9133 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9134 						  fmt_map_off);
9135 	if (err) {
9136 		verbose(env, "verifier bug\n");
9137 		return -EFAULT;
9138 	}
9139 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9140 
9141 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9142 	 * can focus on validating the format specifiers.
9143 	 */
9144 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9145 	if (err < 0)
9146 		verbose(env, "Invalid format string\n");
9147 
9148 	return err;
9149 }
9150 
9151 static int check_get_func_ip(struct bpf_verifier_env *env)
9152 {
9153 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9154 	int func_id = BPF_FUNC_get_func_ip;
9155 
9156 	if (type == BPF_PROG_TYPE_TRACING) {
9157 		if (!bpf_prog_has_trampoline(env->prog)) {
9158 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9159 				func_id_name(func_id), func_id);
9160 			return -ENOTSUPP;
9161 		}
9162 		return 0;
9163 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9164 		return 0;
9165 	}
9166 
9167 	verbose(env, "func %s#%d not supported for program type %d\n",
9168 		func_id_name(func_id), func_id, type);
9169 	return -ENOTSUPP;
9170 }
9171 
9172 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9173 {
9174 	return &env->insn_aux_data[env->insn_idx];
9175 }
9176 
9177 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9178 {
9179 	struct bpf_reg_state *regs = cur_regs(env);
9180 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9181 	bool reg_is_null = register_is_null(reg);
9182 
9183 	if (reg_is_null)
9184 		mark_chain_precision(env, BPF_REG_4);
9185 
9186 	return reg_is_null;
9187 }
9188 
9189 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9190 {
9191 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9192 
9193 	if (!state->initialized) {
9194 		state->initialized = 1;
9195 		state->fit_for_inline = loop_flag_is_zero(env);
9196 		state->callback_subprogno = subprogno;
9197 		return;
9198 	}
9199 
9200 	if (!state->fit_for_inline)
9201 		return;
9202 
9203 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9204 				 state->callback_subprogno == subprogno);
9205 }
9206 
9207 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9208 			     int *insn_idx_p)
9209 {
9210 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9211 	const struct bpf_func_proto *fn = NULL;
9212 	enum bpf_return_type ret_type;
9213 	enum bpf_type_flag ret_flag;
9214 	struct bpf_reg_state *regs;
9215 	struct bpf_call_arg_meta meta;
9216 	int insn_idx = *insn_idx_p;
9217 	bool changes_data;
9218 	int i, err, func_id;
9219 
9220 	/* find function prototype */
9221 	func_id = insn->imm;
9222 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9223 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9224 			func_id);
9225 		return -EINVAL;
9226 	}
9227 
9228 	if (env->ops->get_func_proto)
9229 		fn = env->ops->get_func_proto(func_id, env->prog);
9230 	if (!fn) {
9231 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9232 			func_id);
9233 		return -EINVAL;
9234 	}
9235 
9236 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9237 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9238 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9239 		return -EINVAL;
9240 	}
9241 
9242 	if (fn->allowed && !fn->allowed(env->prog)) {
9243 		verbose(env, "helper call is not allowed in probe\n");
9244 		return -EINVAL;
9245 	}
9246 
9247 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9248 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9249 		return -EINVAL;
9250 	}
9251 
9252 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9253 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9254 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9255 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9256 			func_id_name(func_id), func_id);
9257 		return -EINVAL;
9258 	}
9259 
9260 	memset(&meta, 0, sizeof(meta));
9261 	meta.pkt_access = fn->pkt_access;
9262 
9263 	err = check_func_proto(fn, func_id);
9264 	if (err) {
9265 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9266 			func_id_name(func_id), func_id);
9267 		return err;
9268 	}
9269 
9270 	if (env->cur_state->active_rcu_lock) {
9271 		if (fn->might_sleep) {
9272 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9273 				func_id_name(func_id), func_id);
9274 			return -EINVAL;
9275 		}
9276 
9277 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9278 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9279 	}
9280 
9281 	meta.func_id = func_id;
9282 	/* check args */
9283 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9284 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9285 		if (err)
9286 			return err;
9287 	}
9288 
9289 	err = record_func_map(env, &meta, func_id, insn_idx);
9290 	if (err)
9291 		return err;
9292 
9293 	err = record_func_key(env, &meta, func_id, insn_idx);
9294 	if (err)
9295 		return err;
9296 
9297 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9298 	 * is inferred from register state.
9299 	 */
9300 	for (i = 0; i < meta.access_size; i++) {
9301 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9302 				       BPF_WRITE, -1, false);
9303 		if (err)
9304 			return err;
9305 	}
9306 
9307 	regs = cur_regs(env);
9308 
9309 	if (meta.release_regno) {
9310 		err = -EINVAL;
9311 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9312 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9313 		 * is safe to do directly.
9314 		 */
9315 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9316 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9317 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9318 				return -EFAULT;
9319 			}
9320 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9321 		} else if (meta.ref_obj_id) {
9322 			err = release_reference(env, meta.ref_obj_id);
9323 		} else if (register_is_null(&regs[meta.release_regno])) {
9324 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9325 			 * released is NULL, which must be > R0.
9326 			 */
9327 			err = 0;
9328 		}
9329 		if (err) {
9330 			verbose(env, "func %s#%d reference has not been acquired before\n",
9331 				func_id_name(func_id), func_id);
9332 			return err;
9333 		}
9334 	}
9335 
9336 	switch (func_id) {
9337 	case BPF_FUNC_tail_call:
9338 		err = check_reference_leak(env);
9339 		if (err) {
9340 			verbose(env, "tail_call would lead to reference leak\n");
9341 			return err;
9342 		}
9343 		break;
9344 	case BPF_FUNC_get_local_storage:
9345 		/* check that flags argument in get_local_storage(map, flags) is 0,
9346 		 * this is required because get_local_storage() can't return an error.
9347 		 */
9348 		if (!register_is_null(&regs[BPF_REG_2])) {
9349 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9350 			return -EINVAL;
9351 		}
9352 		break;
9353 	case BPF_FUNC_for_each_map_elem:
9354 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9355 					set_map_elem_callback_state);
9356 		break;
9357 	case BPF_FUNC_timer_set_callback:
9358 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9359 					set_timer_callback_state);
9360 		break;
9361 	case BPF_FUNC_find_vma:
9362 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9363 					set_find_vma_callback_state);
9364 		break;
9365 	case BPF_FUNC_snprintf:
9366 		err = check_bpf_snprintf_call(env, regs);
9367 		break;
9368 	case BPF_FUNC_loop:
9369 		update_loop_inline_state(env, meta.subprogno);
9370 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9371 					set_loop_callback_state);
9372 		break;
9373 	case BPF_FUNC_dynptr_from_mem:
9374 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9375 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9376 				reg_type_str(env, regs[BPF_REG_1].type));
9377 			return -EACCES;
9378 		}
9379 		break;
9380 	case BPF_FUNC_set_retval:
9381 		if (prog_type == BPF_PROG_TYPE_LSM &&
9382 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9383 			if (!env->prog->aux->attach_func_proto->type) {
9384 				/* Make sure programs that attach to void
9385 				 * hooks don't try to modify return value.
9386 				 */
9387 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9388 				return -EINVAL;
9389 			}
9390 		}
9391 		break;
9392 	case BPF_FUNC_dynptr_data:
9393 	{
9394 		struct bpf_reg_state *reg;
9395 		int id, ref_obj_id;
9396 
9397 		reg = get_dynptr_arg_reg(env, fn, regs);
9398 		if (!reg)
9399 			return -EFAULT;
9400 
9401 
9402 		if (meta.dynptr_id) {
9403 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9404 			return -EFAULT;
9405 		}
9406 		if (meta.ref_obj_id) {
9407 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9408 			return -EFAULT;
9409 		}
9410 
9411 		id = dynptr_id(env, reg);
9412 		if (id < 0) {
9413 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9414 			return id;
9415 		}
9416 
9417 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9418 		if (ref_obj_id < 0) {
9419 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9420 			return ref_obj_id;
9421 		}
9422 
9423 		meta.dynptr_id = id;
9424 		meta.ref_obj_id = ref_obj_id;
9425 
9426 		break;
9427 	}
9428 	case BPF_FUNC_dynptr_write:
9429 	{
9430 		enum bpf_dynptr_type dynptr_type;
9431 		struct bpf_reg_state *reg;
9432 
9433 		reg = get_dynptr_arg_reg(env, fn, regs);
9434 		if (!reg)
9435 			return -EFAULT;
9436 
9437 		dynptr_type = dynptr_get_type(env, reg);
9438 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9439 			return -EFAULT;
9440 
9441 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9442 			/* this will trigger clear_all_pkt_pointers(), which will
9443 			 * invalidate all dynptr slices associated with the skb
9444 			 */
9445 			changes_data = true;
9446 
9447 		break;
9448 	}
9449 	case BPF_FUNC_user_ringbuf_drain:
9450 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9451 					set_user_ringbuf_callback_state);
9452 		break;
9453 	}
9454 
9455 	if (err)
9456 		return err;
9457 
9458 	/* reset caller saved regs */
9459 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9460 		mark_reg_not_init(env, regs, caller_saved[i]);
9461 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9462 	}
9463 
9464 	/* helper call returns 64-bit value. */
9465 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9466 
9467 	/* update return register (already marked as written above) */
9468 	ret_type = fn->ret_type;
9469 	ret_flag = type_flag(ret_type);
9470 
9471 	switch (base_type(ret_type)) {
9472 	case RET_INTEGER:
9473 		/* sets type to SCALAR_VALUE */
9474 		mark_reg_unknown(env, regs, BPF_REG_0);
9475 		break;
9476 	case RET_VOID:
9477 		regs[BPF_REG_0].type = NOT_INIT;
9478 		break;
9479 	case RET_PTR_TO_MAP_VALUE:
9480 		/* There is no offset yet applied, variable or fixed */
9481 		mark_reg_known_zero(env, regs, BPF_REG_0);
9482 		/* remember map_ptr, so that check_map_access()
9483 		 * can check 'value_size' boundary of memory access
9484 		 * to map element returned from bpf_map_lookup_elem()
9485 		 */
9486 		if (meta.map_ptr == NULL) {
9487 			verbose(env,
9488 				"kernel subsystem misconfigured verifier\n");
9489 			return -EINVAL;
9490 		}
9491 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9492 		regs[BPF_REG_0].map_uid = meta.map_uid;
9493 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9494 		if (!type_may_be_null(ret_type) &&
9495 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9496 			regs[BPF_REG_0].id = ++env->id_gen;
9497 		}
9498 		break;
9499 	case RET_PTR_TO_SOCKET:
9500 		mark_reg_known_zero(env, regs, BPF_REG_0);
9501 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9502 		break;
9503 	case RET_PTR_TO_SOCK_COMMON:
9504 		mark_reg_known_zero(env, regs, BPF_REG_0);
9505 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9506 		break;
9507 	case RET_PTR_TO_TCP_SOCK:
9508 		mark_reg_known_zero(env, regs, BPF_REG_0);
9509 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9510 		break;
9511 	case RET_PTR_TO_MEM:
9512 		mark_reg_known_zero(env, regs, BPF_REG_0);
9513 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9514 		regs[BPF_REG_0].mem_size = meta.mem_size;
9515 		break;
9516 	case RET_PTR_TO_MEM_OR_BTF_ID:
9517 	{
9518 		const struct btf_type *t;
9519 
9520 		mark_reg_known_zero(env, regs, BPF_REG_0);
9521 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9522 		if (!btf_type_is_struct(t)) {
9523 			u32 tsize;
9524 			const struct btf_type *ret;
9525 			const char *tname;
9526 
9527 			/* resolve the type size of ksym. */
9528 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9529 			if (IS_ERR(ret)) {
9530 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9531 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9532 					tname, PTR_ERR(ret));
9533 				return -EINVAL;
9534 			}
9535 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9536 			regs[BPF_REG_0].mem_size = tsize;
9537 		} else {
9538 			/* MEM_RDONLY may be carried from ret_flag, but it
9539 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9540 			 * it will confuse the check of PTR_TO_BTF_ID in
9541 			 * check_mem_access().
9542 			 */
9543 			ret_flag &= ~MEM_RDONLY;
9544 
9545 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9546 			regs[BPF_REG_0].btf = meta.ret_btf;
9547 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9548 		}
9549 		break;
9550 	}
9551 	case RET_PTR_TO_BTF_ID:
9552 	{
9553 		struct btf *ret_btf;
9554 		int ret_btf_id;
9555 
9556 		mark_reg_known_zero(env, regs, BPF_REG_0);
9557 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9558 		if (func_id == BPF_FUNC_kptr_xchg) {
9559 			ret_btf = meta.kptr_field->kptr.btf;
9560 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9561 			if (!btf_is_kernel(ret_btf))
9562 				regs[BPF_REG_0].type |= MEM_ALLOC;
9563 		} else {
9564 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9565 				verbose(env, "verifier internal error:");
9566 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9567 					func_id_name(func_id));
9568 				return -EINVAL;
9569 			}
9570 			ret_btf = btf_vmlinux;
9571 			ret_btf_id = *fn->ret_btf_id;
9572 		}
9573 		if (ret_btf_id == 0) {
9574 			verbose(env, "invalid return type %u of func %s#%d\n",
9575 				base_type(ret_type), func_id_name(func_id),
9576 				func_id);
9577 			return -EINVAL;
9578 		}
9579 		regs[BPF_REG_0].btf = ret_btf;
9580 		regs[BPF_REG_0].btf_id = ret_btf_id;
9581 		break;
9582 	}
9583 	default:
9584 		verbose(env, "unknown return type %u of func %s#%d\n",
9585 			base_type(ret_type), func_id_name(func_id), func_id);
9586 		return -EINVAL;
9587 	}
9588 
9589 	if (type_may_be_null(regs[BPF_REG_0].type))
9590 		regs[BPF_REG_0].id = ++env->id_gen;
9591 
9592 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9593 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9594 			func_id_name(func_id), func_id);
9595 		return -EFAULT;
9596 	}
9597 
9598 	if (is_dynptr_ref_function(func_id))
9599 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9600 
9601 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9602 		/* For release_reference() */
9603 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9604 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9605 		int id = acquire_reference_state(env, insn_idx);
9606 
9607 		if (id < 0)
9608 			return id;
9609 		/* For mark_ptr_or_null_reg() */
9610 		regs[BPF_REG_0].id = id;
9611 		/* For release_reference() */
9612 		regs[BPF_REG_0].ref_obj_id = id;
9613 	}
9614 
9615 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9616 
9617 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9618 	if (err)
9619 		return err;
9620 
9621 	if ((func_id == BPF_FUNC_get_stack ||
9622 	     func_id == BPF_FUNC_get_task_stack) &&
9623 	    !env->prog->has_callchain_buf) {
9624 		const char *err_str;
9625 
9626 #ifdef CONFIG_PERF_EVENTS
9627 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9628 		err_str = "cannot get callchain buffer for func %s#%d\n";
9629 #else
9630 		err = -ENOTSUPP;
9631 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9632 #endif
9633 		if (err) {
9634 			verbose(env, err_str, func_id_name(func_id), func_id);
9635 			return err;
9636 		}
9637 
9638 		env->prog->has_callchain_buf = true;
9639 	}
9640 
9641 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9642 		env->prog->call_get_stack = true;
9643 
9644 	if (func_id == BPF_FUNC_get_func_ip) {
9645 		if (check_get_func_ip(env))
9646 			return -ENOTSUPP;
9647 		env->prog->call_get_func_ip = true;
9648 	}
9649 
9650 	if (changes_data)
9651 		clear_all_pkt_pointers(env);
9652 	return 0;
9653 }
9654 
9655 /* mark_btf_func_reg_size() is used when the reg size is determined by
9656  * the BTF func_proto's return value size and argument.
9657  */
9658 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9659 				   size_t reg_size)
9660 {
9661 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9662 
9663 	if (regno == BPF_REG_0) {
9664 		/* Function return value */
9665 		reg->live |= REG_LIVE_WRITTEN;
9666 		reg->subreg_def = reg_size == sizeof(u64) ?
9667 			DEF_NOT_SUBREG : env->insn_idx + 1;
9668 	} else {
9669 		/* Function argument */
9670 		if (reg_size == sizeof(u64)) {
9671 			mark_insn_zext(env, reg);
9672 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9673 		} else {
9674 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9675 		}
9676 	}
9677 }
9678 
9679 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9680 {
9681 	return meta->kfunc_flags & KF_ACQUIRE;
9682 }
9683 
9684 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9685 {
9686 	return meta->kfunc_flags & KF_RET_NULL;
9687 }
9688 
9689 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9690 {
9691 	return meta->kfunc_flags & KF_RELEASE;
9692 }
9693 
9694 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9695 {
9696 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9697 }
9698 
9699 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9700 {
9701 	return meta->kfunc_flags & KF_SLEEPABLE;
9702 }
9703 
9704 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9705 {
9706 	return meta->kfunc_flags & KF_DESTRUCTIVE;
9707 }
9708 
9709 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9710 {
9711 	return meta->kfunc_flags & KF_RCU;
9712 }
9713 
9714 static bool __kfunc_param_match_suffix(const struct btf *btf,
9715 				       const struct btf_param *arg,
9716 				       const char *suffix)
9717 {
9718 	int suffix_len = strlen(suffix), len;
9719 	const char *param_name;
9720 
9721 	/* In the future, this can be ported to use BTF tagging */
9722 	param_name = btf_name_by_offset(btf, arg->name_off);
9723 	if (str_is_empty(param_name))
9724 		return false;
9725 	len = strlen(param_name);
9726 	if (len < suffix_len)
9727 		return false;
9728 	param_name += len - suffix_len;
9729 	return !strncmp(param_name, suffix, suffix_len);
9730 }
9731 
9732 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9733 				  const struct btf_param *arg,
9734 				  const struct bpf_reg_state *reg)
9735 {
9736 	const struct btf_type *t;
9737 
9738 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9739 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9740 		return false;
9741 
9742 	return __kfunc_param_match_suffix(btf, arg, "__sz");
9743 }
9744 
9745 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9746 					const struct btf_param *arg,
9747 					const struct bpf_reg_state *reg)
9748 {
9749 	const struct btf_type *t;
9750 
9751 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9752 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9753 		return false;
9754 
9755 	return __kfunc_param_match_suffix(btf, arg, "__szk");
9756 }
9757 
9758 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9759 {
9760 	return __kfunc_param_match_suffix(btf, arg, "__opt");
9761 }
9762 
9763 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9764 {
9765 	return __kfunc_param_match_suffix(btf, arg, "__k");
9766 }
9767 
9768 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9769 {
9770 	return __kfunc_param_match_suffix(btf, arg, "__ign");
9771 }
9772 
9773 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9774 {
9775 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
9776 }
9777 
9778 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9779 {
9780 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
9781 }
9782 
9783 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9784 {
9785 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9786 }
9787 
9788 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9789 					  const struct btf_param *arg,
9790 					  const char *name)
9791 {
9792 	int len, target_len = strlen(name);
9793 	const char *param_name;
9794 
9795 	param_name = btf_name_by_offset(btf, arg->name_off);
9796 	if (str_is_empty(param_name))
9797 		return false;
9798 	len = strlen(param_name);
9799 	if (len != target_len)
9800 		return false;
9801 	if (strcmp(param_name, name))
9802 		return false;
9803 
9804 	return true;
9805 }
9806 
9807 enum {
9808 	KF_ARG_DYNPTR_ID,
9809 	KF_ARG_LIST_HEAD_ID,
9810 	KF_ARG_LIST_NODE_ID,
9811 	KF_ARG_RB_ROOT_ID,
9812 	KF_ARG_RB_NODE_ID,
9813 };
9814 
9815 BTF_ID_LIST(kf_arg_btf_ids)
9816 BTF_ID(struct, bpf_dynptr_kern)
9817 BTF_ID(struct, bpf_list_head)
9818 BTF_ID(struct, bpf_list_node)
9819 BTF_ID(struct, bpf_rb_root)
9820 BTF_ID(struct, bpf_rb_node)
9821 
9822 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9823 				    const struct btf_param *arg, int type)
9824 {
9825 	const struct btf_type *t;
9826 	u32 res_id;
9827 
9828 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9829 	if (!t)
9830 		return false;
9831 	if (!btf_type_is_ptr(t))
9832 		return false;
9833 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
9834 	if (!t)
9835 		return false;
9836 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9837 }
9838 
9839 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9840 {
9841 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9842 }
9843 
9844 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9845 {
9846 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9847 }
9848 
9849 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9850 {
9851 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9852 }
9853 
9854 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9855 {
9856 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9857 }
9858 
9859 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9860 {
9861 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9862 }
9863 
9864 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9865 				  const struct btf_param *arg)
9866 {
9867 	const struct btf_type *t;
9868 
9869 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9870 	if (!t)
9871 		return false;
9872 
9873 	return true;
9874 }
9875 
9876 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9877 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9878 					const struct btf *btf,
9879 					const struct btf_type *t, int rec)
9880 {
9881 	const struct btf_type *member_type;
9882 	const struct btf_member *member;
9883 	u32 i;
9884 
9885 	if (!btf_type_is_struct(t))
9886 		return false;
9887 
9888 	for_each_member(i, t, member) {
9889 		const struct btf_array *array;
9890 
9891 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9892 		if (btf_type_is_struct(member_type)) {
9893 			if (rec >= 3) {
9894 				verbose(env, "max struct nesting depth exceeded\n");
9895 				return false;
9896 			}
9897 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9898 				return false;
9899 			continue;
9900 		}
9901 		if (btf_type_is_array(member_type)) {
9902 			array = btf_array(member_type);
9903 			if (!array->nelems)
9904 				return false;
9905 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9906 			if (!btf_type_is_scalar(member_type))
9907 				return false;
9908 			continue;
9909 		}
9910 		if (!btf_type_is_scalar(member_type))
9911 			return false;
9912 	}
9913 	return true;
9914 }
9915 
9916 
9917 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9918 #ifdef CONFIG_NET
9919 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9920 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9921 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9922 #endif
9923 };
9924 
9925 enum kfunc_ptr_arg_type {
9926 	KF_ARG_PTR_TO_CTX,
9927 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
9928 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
9929 	KF_ARG_PTR_TO_DYNPTR,
9930 	KF_ARG_PTR_TO_ITER,
9931 	KF_ARG_PTR_TO_LIST_HEAD,
9932 	KF_ARG_PTR_TO_LIST_NODE,
9933 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
9934 	KF_ARG_PTR_TO_MEM,
9935 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
9936 	KF_ARG_PTR_TO_CALLBACK,
9937 	KF_ARG_PTR_TO_RB_ROOT,
9938 	KF_ARG_PTR_TO_RB_NODE,
9939 };
9940 
9941 enum special_kfunc_type {
9942 	KF_bpf_obj_new_impl,
9943 	KF_bpf_obj_drop_impl,
9944 	KF_bpf_refcount_acquire_impl,
9945 	KF_bpf_list_push_front_impl,
9946 	KF_bpf_list_push_back_impl,
9947 	KF_bpf_list_pop_front,
9948 	KF_bpf_list_pop_back,
9949 	KF_bpf_cast_to_kern_ctx,
9950 	KF_bpf_rdonly_cast,
9951 	KF_bpf_rcu_read_lock,
9952 	KF_bpf_rcu_read_unlock,
9953 	KF_bpf_rbtree_remove,
9954 	KF_bpf_rbtree_add_impl,
9955 	KF_bpf_rbtree_first,
9956 	KF_bpf_dynptr_from_skb,
9957 	KF_bpf_dynptr_from_xdp,
9958 	KF_bpf_dynptr_slice,
9959 	KF_bpf_dynptr_slice_rdwr,
9960 	KF_bpf_dynptr_clone,
9961 };
9962 
9963 BTF_SET_START(special_kfunc_set)
9964 BTF_ID(func, bpf_obj_new_impl)
9965 BTF_ID(func, bpf_obj_drop_impl)
9966 BTF_ID(func, bpf_refcount_acquire_impl)
9967 BTF_ID(func, bpf_list_push_front_impl)
9968 BTF_ID(func, bpf_list_push_back_impl)
9969 BTF_ID(func, bpf_list_pop_front)
9970 BTF_ID(func, bpf_list_pop_back)
9971 BTF_ID(func, bpf_cast_to_kern_ctx)
9972 BTF_ID(func, bpf_rdonly_cast)
9973 BTF_ID(func, bpf_rbtree_remove)
9974 BTF_ID(func, bpf_rbtree_add_impl)
9975 BTF_ID(func, bpf_rbtree_first)
9976 BTF_ID(func, bpf_dynptr_from_skb)
9977 BTF_ID(func, bpf_dynptr_from_xdp)
9978 BTF_ID(func, bpf_dynptr_slice)
9979 BTF_ID(func, bpf_dynptr_slice_rdwr)
9980 BTF_ID(func, bpf_dynptr_clone)
9981 BTF_SET_END(special_kfunc_set)
9982 
9983 BTF_ID_LIST(special_kfunc_list)
9984 BTF_ID(func, bpf_obj_new_impl)
9985 BTF_ID(func, bpf_obj_drop_impl)
9986 BTF_ID(func, bpf_refcount_acquire_impl)
9987 BTF_ID(func, bpf_list_push_front_impl)
9988 BTF_ID(func, bpf_list_push_back_impl)
9989 BTF_ID(func, bpf_list_pop_front)
9990 BTF_ID(func, bpf_list_pop_back)
9991 BTF_ID(func, bpf_cast_to_kern_ctx)
9992 BTF_ID(func, bpf_rdonly_cast)
9993 BTF_ID(func, bpf_rcu_read_lock)
9994 BTF_ID(func, bpf_rcu_read_unlock)
9995 BTF_ID(func, bpf_rbtree_remove)
9996 BTF_ID(func, bpf_rbtree_add_impl)
9997 BTF_ID(func, bpf_rbtree_first)
9998 BTF_ID(func, bpf_dynptr_from_skb)
9999 BTF_ID(func, bpf_dynptr_from_xdp)
10000 BTF_ID(func, bpf_dynptr_slice)
10001 BTF_ID(func, bpf_dynptr_slice_rdwr)
10002 BTF_ID(func, bpf_dynptr_clone)
10003 
10004 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10005 {
10006 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10007 }
10008 
10009 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10010 {
10011 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10012 }
10013 
10014 static enum kfunc_ptr_arg_type
10015 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10016 		       struct bpf_kfunc_call_arg_meta *meta,
10017 		       const struct btf_type *t, const struct btf_type *ref_t,
10018 		       const char *ref_tname, const struct btf_param *args,
10019 		       int argno, int nargs)
10020 {
10021 	u32 regno = argno + 1;
10022 	struct bpf_reg_state *regs = cur_regs(env);
10023 	struct bpf_reg_state *reg = &regs[regno];
10024 	bool arg_mem_size = false;
10025 
10026 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10027 		return KF_ARG_PTR_TO_CTX;
10028 
10029 	/* In this function, we verify the kfunc's BTF as per the argument type,
10030 	 * leaving the rest of the verification with respect to the register
10031 	 * type to our caller. When a set of conditions hold in the BTF type of
10032 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10033 	 */
10034 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10035 		return KF_ARG_PTR_TO_CTX;
10036 
10037 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10038 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10039 
10040 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10041 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10042 
10043 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10044 		return KF_ARG_PTR_TO_DYNPTR;
10045 
10046 	if (is_kfunc_arg_iter(meta, argno))
10047 		return KF_ARG_PTR_TO_ITER;
10048 
10049 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10050 		return KF_ARG_PTR_TO_LIST_HEAD;
10051 
10052 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10053 		return KF_ARG_PTR_TO_LIST_NODE;
10054 
10055 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10056 		return KF_ARG_PTR_TO_RB_ROOT;
10057 
10058 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10059 		return KF_ARG_PTR_TO_RB_NODE;
10060 
10061 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10062 		if (!btf_type_is_struct(ref_t)) {
10063 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10064 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10065 			return -EINVAL;
10066 		}
10067 		return KF_ARG_PTR_TO_BTF_ID;
10068 	}
10069 
10070 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10071 		return KF_ARG_PTR_TO_CALLBACK;
10072 
10073 
10074 	if (argno + 1 < nargs &&
10075 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10076 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10077 		arg_mem_size = true;
10078 
10079 	/* This is the catch all argument type of register types supported by
10080 	 * check_helper_mem_access. However, we only allow when argument type is
10081 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10082 	 * arg_mem_size is true, the pointer can be void *.
10083 	 */
10084 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10085 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10086 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10087 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10088 		return -EINVAL;
10089 	}
10090 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10091 }
10092 
10093 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10094 					struct bpf_reg_state *reg,
10095 					const struct btf_type *ref_t,
10096 					const char *ref_tname, u32 ref_id,
10097 					struct bpf_kfunc_call_arg_meta *meta,
10098 					int argno)
10099 {
10100 	const struct btf_type *reg_ref_t;
10101 	bool strict_type_match = false;
10102 	const struct btf *reg_btf;
10103 	const char *reg_ref_tname;
10104 	u32 reg_ref_id;
10105 
10106 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10107 		reg_btf = reg->btf;
10108 		reg_ref_id = reg->btf_id;
10109 	} else {
10110 		reg_btf = btf_vmlinux;
10111 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10112 	}
10113 
10114 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10115 	 * or releasing a reference, or are no-cast aliases. We do _not_
10116 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10117 	 * as we want to enable BPF programs to pass types that are bitwise
10118 	 * equivalent without forcing them to explicitly cast with something
10119 	 * like bpf_cast_to_kern_ctx().
10120 	 *
10121 	 * For example, say we had a type like the following:
10122 	 *
10123 	 * struct bpf_cpumask {
10124 	 *	cpumask_t cpumask;
10125 	 *	refcount_t usage;
10126 	 * };
10127 	 *
10128 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10129 	 * to a struct cpumask, so it would be safe to pass a struct
10130 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10131 	 *
10132 	 * The philosophy here is similar to how we allow scalars of different
10133 	 * types to be passed to kfuncs as long as the size is the same. The
10134 	 * only difference here is that we're simply allowing
10135 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10136 	 * resolve types.
10137 	 */
10138 	if (is_kfunc_acquire(meta) ||
10139 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10140 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10141 		strict_type_match = true;
10142 
10143 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10144 
10145 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10146 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10147 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10148 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10149 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10150 			btf_type_str(reg_ref_t), reg_ref_tname);
10151 		return -EINVAL;
10152 	}
10153 	return 0;
10154 }
10155 
10156 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10157 {
10158 	struct bpf_verifier_state *state = env->cur_state;
10159 
10160 	if (!state->active_lock.ptr) {
10161 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10162 		return -EFAULT;
10163 	}
10164 
10165 	if (type_flag(reg->type) & NON_OWN_REF) {
10166 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10167 		return -EFAULT;
10168 	}
10169 
10170 	reg->type |= NON_OWN_REF;
10171 	return 0;
10172 }
10173 
10174 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10175 {
10176 	struct bpf_func_state *state, *unused;
10177 	struct bpf_reg_state *reg;
10178 	int i;
10179 
10180 	state = cur_func(env);
10181 
10182 	if (!ref_obj_id) {
10183 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10184 			     "owning -> non-owning conversion\n");
10185 		return -EFAULT;
10186 	}
10187 
10188 	for (i = 0; i < state->acquired_refs; i++) {
10189 		if (state->refs[i].id != ref_obj_id)
10190 			continue;
10191 
10192 		/* Clear ref_obj_id here so release_reference doesn't clobber
10193 		 * the whole reg
10194 		 */
10195 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10196 			if (reg->ref_obj_id == ref_obj_id) {
10197 				reg->ref_obj_id = 0;
10198 				ref_set_non_owning(env, reg);
10199 			}
10200 		}));
10201 		return 0;
10202 	}
10203 
10204 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10205 	return -EFAULT;
10206 }
10207 
10208 /* Implementation details:
10209  *
10210  * Each register points to some region of memory, which we define as an
10211  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10212  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10213  * allocation. The lock and the data it protects are colocated in the same
10214  * memory region.
10215  *
10216  * Hence, everytime a register holds a pointer value pointing to such
10217  * allocation, the verifier preserves a unique reg->id for it.
10218  *
10219  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10220  * bpf_spin_lock is called.
10221  *
10222  * To enable this, lock state in the verifier captures two values:
10223  *	active_lock.ptr = Register's type specific pointer
10224  *	active_lock.id  = A unique ID for each register pointer value
10225  *
10226  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10227  * supported register types.
10228  *
10229  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10230  * allocated objects is the reg->btf pointer.
10231  *
10232  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10233  * can establish the provenance of the map value statically for each distinct
10234  * lookup into such maps. They always contain a single map value hence unique
10235  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10236  *
10237  * So, in case of global variables, they use array maps with max_entries = 1,
10238  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10239  * into the same map value as max_entries is 1, as described above).
10240  *
10241  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10242  * outer map pointer (in verifier context), but each lookup into an inner map
10243  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10244  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10245  * will get different reg->id assigned to each lookup, hence different
10246  * active_lock.id.
10247  *
10248  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10249  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10250  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10251  */
10252 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10253 {
10254 	void *ptr;
10255 	u32 id;
10256 
10257 	switch ((int)reg->type) {
10258 	case PTR_TO_MAP_VALUE:
10259 		ptr = reg->map_ptr;
10260 		break;
10261 	case PTR_TO_BTF_ID | MEM_ALLOC:
10262 		ptr = reg->btf;
10263 		break;
10264 	default:
10265 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10266 		return -EFAULT;
10267 	}
10268 	id = reg->id;
10269 
10270 	if (!env->cur_state->active_lock.ptr)
10271 		return -EINVAL;
10272 	if (env->cur_state->active_lock.ptr != ptr ||
10273 	    env->cur_state->active_lock.id != id) {
10274 		verbose(env, "held lock and object are not in the same allocation\n");
10275 		return -EINVAL;
10276 	}
10277 	return 0;
10278 }
10279 
10280 static bool is_bpf_list_api_kfunc(u32 btf_id)
10281 {
10282 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10283 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10284 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10285 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10286 }
10287 
10288 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10289 {
10290 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10291 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10292 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10293 }
10294 
10295 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10296 {
10297 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10298 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10299 }
10300 
10301 static bool is_callback_calling_kfunc(u32 btf_id)
10302 {
10303 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10304 }
10305 
10306 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10307 {
10308 	return is_bpf_rbtree_api_kfunc(btf_id);
10309 }
10310 
10311 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10312 					  enum btf_field_type head_field_type,
10313 					  u32 kfunc_btf_id)
10314 {
10315 	bool ret;
10316 
10317 	switch (head_field_type) {
10318 	case BPF_LIST_HEAD:
10319 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10320 		break;
10321 	case BPF_RB_ROOT:
10322 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10323 		break;
10324 	default:
10325 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10326 			btf_field_type_name(head_field_type));
10327 		return false;
10328 	}
10329 
10330 	if (!ret)
10331 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10332 			btf_field_type_name(head_field_type));
10333 	return ret;
10334 }
10335 
10336 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10337 					  enum btf_field_type node_field_type,
10338 					  u32 kfunc_btf_id)
10339 {
10340 	bool ret;
10341 
10342 	switch (node_field_type) {
10343 	case BPF_LIST_NODE:
10344 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10345 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10346 		break;
10347 	case BPF_RB_NODE:
10348 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10349 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10350 		break;
10351 	default:
10352 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10353 			btf_field_type_name(node_field_type));
10354 		return false;
10355 	}
10356 
10357 	if (!ret)
10358 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10359 			btf_field_type_name(node_field_type));
10360 	return ret;
10361 }
10362 
10363 static int
10364 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10365 				   struct bpf_reg_state *reg, u32 regno,
10366 				   struct bpf_kfunc_call_arg_meta *meta,
10367 				   enum btf_field_type head_field_type,
10368 				   struct btf_field **head_field)
10369 {
10370 	const char *head_type_name;
10371 	struct btf_field *field;
10372 	struct btf_record *rec;
10373 	u32 head_off;
10374 
10375 	if (meta->btf != btf_vmlinux) {
10376 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10377 		return -EFAULT;
10378 	}
10379 
10380 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10381 		return -EFAULT;
10382 
10383 	head_type_name = btf_field_type_name(head_field_type);
10384 	if (!tnum_is_const(reg->var_off)) {
10385 		verbose(env,
10386 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10387 			regno, head_type_name);
10388 		return -EINVAL;
10389 	}
10390 
10391 	rec = reg_btf_record(reg);
10392 	head_off = reg->off + reg->var_off.value;
10393 	field = btf_record_find(rec, head_off, head_field_type);
10394 	if (!field) {
10395 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10396 		return -EINVAL;
10397 	}
10398 
10399 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10400 	if (check_reg_allocation_locked(env, reg)) {
10401 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10402 			rec->spin_lock_off, head_type_name);
10403 		return -EINVAL;
10404 	}
10405 
10406 	if (*head_field) {
10407 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10408 		return -EFAULT;
10409 	}
10410 	*head_field = field;
10411 	return 0;
10412 }
10413 
10414 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10415 					   struct bpf_reg_state *reg, u32 regno,
10416 					   struct bpf_kfunc_call_arg_meta *meta)
10417 {
10418 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10419 							  &meta->arg_list_head.field);
10420 }
10421 
10422 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10423 					     struct bpf_reg_state *reg, u32 regno,
10424 					     struct bpf_kfunc_call_arg_meta *meta)
10425 {
10426 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10427 							  &meta->arg_rbtree_root.field);
10428 }
10429 
10430 static int
10431 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10432 				   struct bpf_reg_state *reg, u32 regno,
10433 				   struct bpf_kfunc_call_arg_meta *meta,
10434 				   enum btf_field_type head_field_type,
10435 				   enum btf_field_type node_field_type,
10436 				   struct btf_field **node_field)
10437 {
10438 	const char *node_type_name;
10439 	const struct btf_type *et, *t;
10440 	struct btf_field *field;
10441 	u32 node_off;
10442 
10443 	if (meta->btf != btf_vmlinux) {
10444 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10445 		return -EFAULT;
10446 	}
10447 
10448 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10449 		return -EFAULT;
10450 
10451 	node_type_name = btf_field_type_name(node_field_type);
10452 	if (!tnum_is_const(reg->var_off)) {
10453 		verbose(env,
10454 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10455 			regno, node_type_name);
10456 		return -EINVAL;
10457 	}
10458 
10459 	node_off = reg->off + reg->var_off.value;
10460 	field = reg_find_field_offset(reg, node_off, node_field_type);
10461 	if (!field || field->offset != node_off) {
10462 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10463 		return -EINVAL;
10464 	}
10465 
10466 	field = *node_field;
10467 
10468 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10469 	t = btf_type_by_id(reg->btf, reg->btf_id);
10470 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10471 				  field->graph_root.value_btf_id, true)) {
10472 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10473 			"in struct %s, but arg is at offset=%d in struct %s\n",
10474 			btf_field_type_name(head_field_type),
10475 			btf_field_type_name(node_field_type),
10476 			field->graph_root.node_offset,
10477 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10478 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10479 		return -EINVAL;
10480 	}
10481 
10482 	if (node_off != field->graph_root.node_offset) {
10483 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10484 			node_off, btf_field_type_name(node_field_type),
10485 			field->graph_root.node_offset,
10486 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10487 		return -EINVAL;
10488 	}
10489 
10490 	return 0;
10491 }
10492 
10493 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10494 					   struct bpf_reg_state *reg, u32 regno,
10495 					   struct bpf_kfunc_call_arg_meta *meta)
10496 {
10497 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10498 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10499 						  &meta->arg_list_head.field);
10500 }
10501 
10502 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10503 					     struct bpf_reg_state *reg, u32 regno,
10504 					     struct bpf_kfunc_call_arg_meta *meta)
10505 {
10506 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10507 						  BPF_RB_ROOT, BPF_RB_NODE,
10508 						  &meta->arg_rbtree_root.field);
10509 }
10510 
10511 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10512 			    int insn_idx)
10513 {
10514 	const char *func_name = meta->func_name, *ref_tname;
10515 	const struct btf *btf = meta->btf;
10516 	const struct btf_param *args;
10517 	struct btf_record *rec;
10518 	u32 i, nargs;
10519 	int ret;
10520 
10521 	args = (const struct btf_param *)(meta->func_proto + 1);
10522 	nargs = btf_type_vlen(meta->func_proto);
10523 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10524 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10525 			MAX_BPF_FUNC_REG_ARGS);
10526 		return -EINVAL;
10527 	}
10528 
10529 	/* Check that BTF function arguments match actual types that the
10530 	 * verifier sees.
10531 	 */
10532 	for (i = 0; i < nargs; i++) {
10533 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10534 		const struct btf_type *t, *ref_t, *resolve_ret;
10535 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10536 		u32 regno = i + 1, ref_id, type_size;
10537 		bool is_ret_buf_sz = false;
10538 		int kf_arg_type;
10539 
10540 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10541 
10542 		if (is_kfunc_arg_ignore(btf, &args[i]))
10543 			continue;
10544 
10545 		if (btf_type_is_scalar(t)) {
10546 			if (reg->type != SCALAR_VALUE) {
10547 				verbose(env, "R%d is not a scalar\n", regno);
10548 				return -EINVAL;
10549 			}
10550 
10551 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10552 				if (meta->arg_constant.found) {
10553 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10554 					return -EFAULT;
10555 				}
10556 				if (!tnum_is_const(reg->var_off)) {
10557 					verbose(env, "R%d must be a known constant\n", regno);
10558 					return -EINVAL;
10559 				}
10560 				ret = mark_chain_precision(env, regno);
10561 				if (ret < 0)
10562 					return ret;
10563 				meta->arg_constant.found = true;
10564 				meta->arg_constant.value = reg->var_off.value;
10565 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10566 				meta->r0_rdonly = true;
10567 				is_ret_buf_sz = true;
10568 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10569 				is_ret_buf_sz = true;
10570 			}
10571 
10572 			if (is_ret_buf_sz) {
10573 				if (meta->r0_size) {
10574 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10575 					return -EINVAL;
10576 				}
10577 
10578 				if (!tnum_is_const(reg->var_off)) {
10579 					verbose(env, "R%d is not a const\n", regno);
10580 					return -EINVAL;
10581 				}
10582 
10583 				meta->r0_size = reg->var_off.value;
10584 				ret = mark_chain_precision(env, regno);
10585 				if (ret)
10586 					return ret;
10587 			}
10588 			continue;
10589 		}
10590 
10591 		if (!btf_type_is_ptr(t)) {
10592 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10593 			return -EINVAL;
10594 		}
10595 
10596 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10597 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10598 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10599 			return -EACCES;
10600 		}
10601 
10602 		if (reg->ref_obj_id) {
10603 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10604 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10605 					regno, reg->ref_obj_id,
10606 					meta->ref_obj_id);
10607 				return -EFAULT;
10608 			}
10609 			meta->ref_obj_id = reg->ref_obj_id;
10610 			if (is_kfunc_release(meta))
10611 				meta->release_regno = regno;
10612 		}
10613 
10614 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10615 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10616 
10617 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10618 		if (kf_arg_type < 0)
10619 			return kf_arg_type;
10620 
10621 		switch (kf_arg_type) {
10622 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10623 		case KF_ARG_PTR_TO_BTF_ID:
10624 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10625 				break;
10626 
10627 			if (!is_trusted_reg(reg)) {
10628 				if (!is_kfunc_rcu(meta)) {
10629 					verbose(env, "R%d must be referenced or trusted\n", regno);
10630 					return -EINVAL;
10631 				}
10632 				if (!is_rcu_reg(reg)) {
10633 					verbose(env, "R%d must be a rcu pointer\n", regno);
10634 					return -EINVAL;
10635 				}
10636 			}
10637 
10638 			fallthrough;
10639 		case KF_ARG_PTR_TO_CTX:
10640 			/* Trusted arguments have the same offset checks as release arguments */
10641 			arg_type |= OBJ_RELEASE;
10642 			break;
10643 		case KF_ARG_PTR_TO_DYNPTR:
10644 		case KF_ARG_PTR_TO_ITER:
10645 		case KF_ARG_PTR_TO_LIST_HEAD:
10646 		case KF_ARG_PTR_TO_LIST_NODE:
10647 		case KF_ARG_PTR_TO_RB_ROOT:
10648 		case KF_ARG_PTR_TO_RB_NODE:
10649 		case KF_ARG_PTR_TO_MEM:
10650 		case KF_ARG_PTR_TO_MEM_SIZE:
10651 		case KF_ARG_PTR_TO_CALLBACK:
10652 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10653 			/* Trusted by default */
10654 			break;
10655 		default:
10656 			WARN_ON_ONCE(1);
10657 			return -EFAULT;
10658 		}
10659 
10660 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10661 			arg_type |= OBJ_RELEASE;
10662 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10663 		if (ret < 0)
10664 			return ret;
10665 
10666 		switch (kf_arg_type) {
10667 		case KF_ARG_PTR_TO_CTX:
10668 			if (reg->type != PTR_TO_CTX) {
10669 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10670 				return -EINVAL;
10671 			}
10672 
10673 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10674 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10675 				if (ret < 0)
10676 					return -EINVAL;
10677 				meta->ret_btf_id  = ret;
10678 			}
10679 			break;
10680 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10681 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10682 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10683 				return -EINVAL;
10684 			}
10685 			if (!reg->ref_obj_id) {
10686 				verbose(env, "allocated object must be referenced\n");
10687 				return -EINVAL;
10688 			}
10689 			if (meta->btf == btf_vmlinux &&
10690 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10691 				meta->arg_btf = reg->btf;
10692 				meta->arg_btf_id = reg->btf_id;
10693 			}
10694 			break;
10695 		case KF_ARG_PTR_TO_DYNPTR:
10696 		{
10697 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10698 			int clone_ref_obj_id = 0;
10699 
10700 			if (reg->type != PTR_TO_STACK &&
10701 			    reg->type != CONST_PTR_TO_DYNPTR) {
10702 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10703 				return -EINVAL;
10704 			}
10705 
10706 			if (reg->type == CONST_PTR_TO_DYNPTR)
10707 				dynptr_arg_type |= MEM_RDONLY;
10708 
10709 			if (is_kfunc_arg_uninit(btf, &args[i]))
10710 				dynptr_arg_type |= MEM_UNINIT;
10711 
10712 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10713 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
10714 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10715 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
10716 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10717 				   (dynptr_arg_type & MEM_UNINIT)) {
10718 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10719 
10720 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10721 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10722 					return -EFAULT;
10723 				}
10724 
10725 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10726 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10727 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10728 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10729 					return -EFAULT;
10730 				}
10731 			}
10732 
10733 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10734 			if (ret < 0)
10735 				return ret;
10736 
10737 			if (!(dynptr_arg_type & MEM_UNINIT)) {
10738 				int id = dynptr_id(env, reg);
10739 
10740 				if (id < 0) {
10741 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10742 					return id;
10743 				}
10744 				meta->initialized_dynptr.id = id;
10745 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10746 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10747 			}
10748 
10749 			break;
10750 		}
10751 		case KF_ARG_PTR_TO_ITER:
10752 			ret = process_iter_arg(env, regno, insn_idx, meta);
10753 			if (ret < 0)
10754 				return ret;
10755 			break;
10756 		case KF_ARG_PTR_TO_LIST_HEAD:
10757 			if (reg->type != PTR_TO_MAP_VALUE &&
10758 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10759 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10760 				return -EINVAL;
10761 			}
10762 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10763 				verbose(env, "allocated object must be referenced\n");
10764 				return -EINVAL;
10765 			}
10766 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10767 			if (ret < 0)
10768 				return ret;
10769 			break;
10770 		case KF_ARG_PTR_TO_RB_ROOT:
10771 			if (reg->type != PTR_TO_MAP_VALUE &&
10772 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10773 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10774 				return -EINVAL;
10775 			}
10776 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10777 				verbose(env, "allocated object must be referenced\n");
10778 				return -EINVAL;
10779 			}
10780 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10781 			if (ret < 0)
10782 				return ret;
10783 			break;
10784 		case KF_ARG_PTR_TO_LIST_NODE:
10785 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10786 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10787 				return -EINVAL;
10788 			}
10789 			if (!reg->ref_obj_id) {
10790 				verbose(env, "allocated object must be referenced\n");
10791 				return -EINVAL;
10792 			}
10793 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10794 			if (ret < 0)
10795 				return ret;
10796 			break;
10797 		case KF_ARG_PTR_TO_RB_NODE:
10798 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10799 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10800 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
10801 					return -EINVAL;
10802 				}
10803 				if (in_rbtree_lock_required_cb(env)) {
10804 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10805 					return -EINVAL;
10806 				}
10807 			} else {
10808 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10809 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10810 					return -EINVAL;
10811 				}
10812 				if (!reg->ref_obj_id) {
10813 					verbose(env, "allocated object must be referenced\n");
10814 					return -EINVAL;
10815 				}
10816 			}
10817 
10818 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10819 			if (ret < 0)
10820 				return ret;
10821 			break;
10822 		case KF_ARG_PTR_TO_BTF_ID:
10823 			/* Only base_type is checked, further checks are done here */
10824 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10825 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10826 			    !reg2btf_ids[base_type(reg->type)]) {
10827 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10828 				verbose(env, "expected %s or socket\n",
10829 					reg_type_str(env, base_type(reg->type) |
10830 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10831 				return -EINVAL;
10832 			}
10833 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10834 			if (ret < 0)
10835 				return ret;
10836 			break;
10837 		case KF_ARG_PTR_TO_MEM:
10838 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10839 			if (IS_ERR(resolve_ret)) {
10840 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10841 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10842 				return -EINVAL;
10843 			}
10844 			ret = check_mem_reg(env, reg, regno, type_size);
10845 			if (ret < 0)
10846 				return ret;
10847 			break;
10848 		case KF_ARG_PTR_TO_MEM_SIZE:
10849 		{
10850 			struct bpf_reg_state *buff_reg = &regs[regno];
10851 			const struct btf_param *buff_arg = &args[i];
10852 			struct bpf_reg_state *size_reg = &regs[regno + 1];
10853 			const struct btf_param *size_arg = &args[i + 1];
10854 
10855 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
10856 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10857 				if (ret < 0) {
10858 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10859 					return ret;
10860 				}
10861 			}
10862 
10863 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10864 				if (meta->arg_constant.found) {
10865 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10866 					return -EFAULT;
10867 				}
10868 				if (!tnum_is_const(size_reg->var_off)) {
10869 					verbose(env, "R%d must be a known constant\n", regno + 1);
10870 					return -EINVAL;
10871 				}
10872 				meta->arg_constant.found = true;
10873 				meta->arg_constant.value = size_reg->var_off.value;
10874 			}
10875 
10876 			/* Skip next '__sz' or '__szk' argument */
10877 			i++;
10878 			break;
10879 		}
10880 		case KF_ARG_PTR_TO_CALLBACK:
10881 			meta->subprogno = reg->subprogno;
10882 			break;
10883 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10884 			if (!type_is_ptr_alloc_obj(reg->type) && !type_is_non_owning_ref(reg->type)) {
10885 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
10886 				return -EINVAL;
10887 			}
10888 
10889 			rec = reg_btf_record(reg);
10890 			if (!rec) {
10891 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
10892 				return -EFAULT;
10893 			}
10894 
10895 			if (rec->refcount_off < 0) {
10896 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
10897 				return -EINVAL;
10898 			}
10899 			if (rec->refcount_off >= 0) {
10900 				verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
10901 				return -EINVAL;
10902 			}
10903 			meta->arg_btf = reg->btf;
10904 			meta->arg_btf_id = reg->btf_id;
10905 			break;
10906 		}
10907 	}
10908 
10909 	if (is_kfunc_release(meta) && !meta->release_regno) {
10910 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10911 			func_name);
10912 		return -EINVAL;
10913 	}
10914 
10915 	return 0;
10916 }
10917 
10918 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10919 			    struct bpf_insn *insn,
10920 			    struct bpf_kfunc_call_arg_meta *meta,
10921 			    const char **kfunc_name)
10922 {
10923 	const struct btf_type *func, *func_proto;
10924 	u32 func_id, *kfunc_flags;
10925 	const char *func_name;
10926 	struct btf *desc_btf;
10927 
10928 	if (kfunc_name)
10929 		*kfunc_name = NULL;
10930 
10931 	if (!insn->imm)
10932 		return -EINVAL;
10933 
10934 	desc_btf = find_kfunc_desc_btf(env, insn->off);
10935 	if (IS_ERR(desc_btf))
10936 		return PTR_ERR(desc_btf);
10937 
10938 	func_id = insn->imm;
10939 	func = btf_type_by_id(desc_btf, func_id);
10940 	func_name = btf_name_by_offset(desc_btf, func->name_off);
10941 	if (kfunc_name)
10942 		*kfunc_name = func_name;
10943 	func_proto = btf_type_by_id(desc_btf, func->type);
10944 
10945 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
10946 	if (!kfunc_flags) {
10947 		return -EACCES;
10948 	}
10949 
10950 	memset(meta, 0, sizeof(*meta));
10951 	meta->btf = desc_btf;
10952 	meta->func_id = func_id;
10953 	meta->kfunc_flags = *kfunc_flags;
10954 	meta->func_proto = func_proto;
10955 	meta->func_name = func_name;
10956 
10957 	return 0;
10958 }
10959 
10960 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10961 			    int *insn_idx_p)
10962 {
10963 	const struct btf_type *t, *ptr_type;
10964 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
10965 	struct bpf_reg_state *regs = cur_regs(env);
10966 	const char *func_name, *ptr_type_name;
10967 	bool sleepable, rcu_lock, rcu_unlock;
10968 	struct bpf_kfunc_call_arg_meta meta;
10969 	struct bpf_insn_aux_data *insn_aux;
10970 	int err, insn_idx = *insn_idx_p;
10971 	const struct btf_param *args;
10972 	const struct btf_type *ret_t;
10973 	struct btf *desc_btf;
10974 
10975 	/* skip for now, but return error when we find this in fixup_kfunc_call */
10976 	if (!insn->imm)
10977 		return 0;
10978 
10979 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10980 	if (err == -EACCES && func_name)
10981 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
10982 	if (err)
10983 		return err;
10984 	desc_btf = meta.btf;
10985 	insn_aux = &env->insn_aux_data[insn_idx];
10986 
10987 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10988 
10989 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10990 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10991 		return -EACCES;
10992 	}
10993 
10994 	sleepable = is_kfunc_sleepable(&meta);
10995 	if (sleepable && !env->prog->aux->sleepable) {
10996 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10997 		return -EACCES;
10998 	}
10999 
11000 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11001 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11002 
11003 	if (env->cur_state->active_rcu_lock) {
11004 		struct bpf_func_state *state;
11005 		struct bpf_reg_state *reg;
11006 
11007 		if (rcu_lock) {
11008 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11009 			return -EINVAL;
11010 		} else if (rcu_unlock) {
11011 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11012 				if (reg->type & MEM_RCU) {
11013 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11014 					reg->type |= PTR_UNTRUSTED;
11015 				}
11016 			}));
11017 			env->cur_state->active_rcu_lock = false;
11018 		} else if (sleepable) {
11019 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11020 			return -EACCES;
11021 		}
11022 	} else if (rcu_lock) {
11023 		env->cur_state->active_rcu_lock = true;
11024 	} else if (rcu_unlock) {
11025 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11026 		return -EINVAL;
11027 	}
11028 
11029 	/* Check the arguments */
11030 	err = check_kfunc_args(env, &meta, insn_idx);
11031 	if (err < 0)
11032 		return err;
11033 	/* In case of release function, we get register number of refcounted
11034 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11035 	 */
11036 	if (meta.release_regno) {
11037 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11038 		if (err) {
11039 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11040 				func_name, meta.func_id);
11041 			return err;
11042 		}
11043 	}
11044 
11045 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11046 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11047 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11048 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11049 		insn_aux->insert_off = regs[BPF_REG_2].off;
11050 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11051 		if (err) {
11052 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11053 				func_name, meta.func_id);
11054 			return err;
11055 		}
11056 
11057 		err = release_reference(env, release_ref_obj_id);
11058 		if (err) {
11059 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11060 				func_name, meta.func_id);
11061 			return err;
11062 		}
11063 	}
11064 
11065 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11066 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11067 					set_rbtree_add_callback_state);
11068 		if (err) {
11069 			verbose(env, "kfunc %s#%d failed callback verification\n",
11070 				func_name, meta.func_id);
11071 			return err;
11072 		}
11073 	}
11074 
11075 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11076 		mark_reg_not_init(env, regs, caller_saved[i]);
11077 
11078 	/* Check return type */
11079 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11080 
11081 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11082 		/* Only exception is bpf_obj_new_impl */
11083 		if (meta.btf != btf_vmlinux ||
11084 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11085 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11086 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11087 			return -EINVAL;
11088 		}
11089 	}
11090 
11091 	if (btf_type_is_scalar(t)) {
11092 		mark_reg_unknown(env, regs, BPF_REG_0);
11093 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11094 	} else if (btf_type_is_ptr(t)) {
11095 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11096 
11097 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11098 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11099 				struct btf *ret_btf;
11100 				u32 ret_btf_id;
11101 
11102 				if (unlikely(!bpf_global_ma_set))
11103 					return -ENOMEM;
11104 
11105 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11106 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11107 					return -EINVAL;
11108 				}
11109 
11110 				ret_btf = env->prog->aux->btf;
11111 				ret_btf_id = meta.arg_constant.value;
11112 
11113 				/* This may be NULL due to user not supplying a BTF */
11114 				if (!ret_btf) {
11115 					verbose(env, "bpf_obj_new requires prog BTF\n");
11116 					return -EINVAL;
11117 				}
11118 
11119 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11120 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11121 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11122 					return -EINVAL;
11123 				}
11124 
11125 				mark_reg_known_zero(env, regs, BPF_REG_0);
11126 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11127 				regs[BPF_REG_0].btf = ret_btf;
11128 				regs[BPF_REG_0].btf_id = ret_btf_id;
11129 
11130 				insn_aux->obj_new_size = ret_t->size;
11131 				insn_aux->kptr_struct_meta =
11132 					btf_find_struct_meta(ret_btf, ret_btf_id);
11133 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11134 				mark_reg_known_zero(env, regs, BPF_REG_0);
11135 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11136 				regs[BPF_REG_0].btf = meta.arg_btf;
11137 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11138 
11139 				insn_aux->kptr_struct_meta =
11140 					btf_find_struct_meta(meta.arg_btf,
11141 							     meta.arg_btf_id);
11142 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11143 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11144 				struct btf_field *field = meta.arg_list_head.field;
11145 
11146 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11147 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11148 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11149 				struct btf_field *field = meta.arg_rbtree_root.field;
11150 
11151 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11152 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11153 				mark_reg_known_zero(env, regs, BPF_REG_0);
11154 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11155 				regs[BPF_REG_0].btf = desc_btf;
11156 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11157 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11158 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11159 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11160 					verbose(env,
11161 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11162 					return -EINVAL;
11163 				}
11164 
11165 				mark_reg_known_zero(env, regs, BPF_REG_0);
11166 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11167 				regs[BPF_REG_0].btf = desc_btf;
11168 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11169 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11170 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11171 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11172 
11173 				mark_reg_known_zero(env, regs, BPF_REG_0);
11174 
11175 				if (!meta.arg_constant.found) {
11176 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11177 					return -EFAULT;
11178 				}
11179 
11180 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11181 
11182 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11183 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11184 
11185 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11186 					regs[BPF_REG_0].type |= MEM_RDONLY;
11187 				} else {
11188 					/* this will set env->seen_direct_write to true */
11189 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11190 						verbose(env, "the prog does not allow writes to packet data\n");
11191 						return -EINVAL;
11192 					}
11193 				}
11194 
11195 				if (!meta.initialized_dynptr.id) {
11196 					verbose(env, "verifier internal error: no dynptr id\n");
11197 					return -EFAULT;
11198 				}
11199 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11200 
11201 				/* we don't need to set BPF_REG_0's ref obj id
11202 				 * because packet slices are not refcounted (see
11203 				 * dynptr_type_refcounted)
11204 				 */
11205 			} else {
11206 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11207 					meta.func_name);
11208 				return -EFAULT;
11209 			}
11210 		} else if (!__btf_type_is_struct(ptr_type)) {
11211 			if (!meta.r0_size) {
11212 				__u32 sz;
11213 
11214 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11215 					meta.r0_size = sz;
11216 					meta.r0_rdonly = true;
11217 				}
11218 			}
11219 			if (!meta.r0_size) {
11220 				ptr_type_name = btf_name_by_offset(desc_btf,
11221 								   ptr_type->name_off);
11222 				verbose(env,
11223 					"kernel function %s returns pointer type %s %s is not supported\n",
11224 					func_name,
11225 					btf_type_str(ptr_type),
11226 					ptr_type_name);
11227 				return -EINVAL;
11228 			}
11229 
11230 			mark_reg_known_zero(env, regs, BPF_REG_0);
11231 			regs[BPF_REG_0].type = PTR_TO_MEM;
11232 			regs[BPF_REG_0].mem_size = meta.r0_size;
11233 
11234 			if (meta.r0_rdonly)
11235 				regs[BPF_REG_0].type |= MEM_RDONLY;
11236 
11237 			/* Ensures we don't access the memory after a release_reference() */
11238 			if (meta.ref_obj_id)
11239 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11240 		} else {
11241 			mark_reg_known_zero(env, regs, BPF_REG_0);
11242 			regs[BPF_REG_0].btf = desc_btf;
11243 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11244 			regs[BPF_REG_0].btf_id = ptr_type_id;
11245 		}
11246 
11247 		if (is_kfunc_ret_null(&meta)) {
11248 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11249 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11250 			regs[BPF_REG_0].id = ++env->id_gen;
11251 		}
11252 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11253 		if (is_kfunc_acquire(&meta)) {
11254 			int id = acquire_reference_state(env, insn_idx);
11255 
11256 			if (id < 0)
11257 				return id;
11258 			if (is_kfunc_ret_null(&meta))
11259 				regs[BPF_REG_0].id = id;
11260 			regs[BPF_REG_0].ref_obj_id = id;
11261 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11262 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11263 		}
11264 
11265 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11266 			regs[BPF_REG_0].id = ++env->id_gen;
11267 	} else if (btf_type_is_void(t)) {
11268 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11269 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11270 				insn_aux->kptr_struct_meta =
11271 					btf_find_struct_meta(meta.arg_btf,
11272 							     meta.arg_btf_id);
11273 			}
11274 		}
11275 	}
11276 
11277 	nargs = btf_type_vlen(meta.func_proto);
11278 	args = (const struct btf_param *)(meta.func_proto + 1);
11279 	for (i = 0; i < nargs; i++) {
11280 		u32 regno = i + 1;
11281 
11282 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11283 		if (btf_type_is_ptr(t))
11284 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11285 		else
11286 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11287 			mark_btf_func_reg_size(env, regno, t->size);
11288 	}
11289 
11290 	if (is_iter_next_kfunc(&meta)) {
11291 		err = process_iter_next_call(env, insn_idx, &meta);
11292 		if (err)
11293 			return err;
11294 	}
11295 
11296 	return 0;
11297 }
11298 
11299 static bool signed_add_overflows(s64 a, s64 b)
11300 {
11301 	/* Do the add in u64, where overflow is well-defined */
11302 	s64 res = (s64)((u64)a + (u64)b);
11303 
11304 	if (b < 0)
11305 		return res > a;
11306 	return res < a;
11307 }
11308 
11309 static bool signed_add32_overflows(s32 a, s32 b)
11310 {
11311 	/* Do the add in u32, where overflow is well-defined */
11312 	s32 res = (s32)((u32)a + (u32)b);
11313 
11314 	if (b < 0)
11315 		return res > a;
11316 	return res < a;
11317 }
11318 
11319 static bool signed_sub_overflows(s64 a, s64 b)
11320 {
11321 	/* Do the sub in u64, where overflow is well-defined */
11322 	s64 res = (s64)((u64)a - (u64)b);
11323 
11324 	if (b < 0)
11325 		return res < a;
11326 	return res > a;
11327 }
11328 
11329 static bool signed_sub32_overflows(s32 a, s32 b)
11330 {
11331 	/* Do the sub in u32, where overflow is well-defined */
11332 	s32 res = (s32)((u32)a - (u32)b);
11333 
11334 	if (b < 0)
11335 		return res < a;
11336 	return res > a;
11337 }
11338 
11339 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11340 				  const struct bpf_reg_state *reg,
11341 				  enum bpf_reg_type type)
11342 {
11343 	bool known = tnum_is_const(reg->var_off);
11344 	s64 val = reg->var_off.value;
11345 	s64 smin = reg->smin_value;
11346 
11347 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11348 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11349 			reg_type_str(env, type), val);
11350 		return false;
11351 	}
11352 
11353 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11354 		verbose(env, "%s pointer offset %d is not allowed\n",
11355 			reg_type_str(env, type), reg->off);
11356 		return false;
11357 	}
11358 
11359 	if (smin == S64_MIN) {
11360 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11361 			reg_type_str(env, type));
11362 		return false;
11363 	}
11364 
11365 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11366 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11367 			smin, reg_type_str(env, type));
11368 		return false;
11369 	}
11370 
11371 	return true;
11372 }
11373 
11374 enum {
11375 	REASON_BOUNDS	= -1,
11376 	REASON_TYPE	= -2,
11377 	REASON_PATHS	= -3,
11378 	REASON_LIMIT	= -4,
11379 	REASON_STACK	= -5,
11380 };
11381 
11382 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11383 			      u32 *alu_limit, bool mask_to_left)
11384 {
11385 	u32 max = 0, ptr_limit = 0;
11386 
11387 	switch (ptr_reg->type) {
11388 	case PTR_TO_STACK:
11389 		/* Offset 0 is out-of-bounds, but acceptable start for the
11390 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11391 		 * offset where we would need to deal with min/max bounds is
11392 		 * currently prohibited for unprivileged.
11393 		 */
11394 		max = MAX_BPF_STACK + mask_to_left;
11395 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11396 		break;
11397 	case PTR_TO_MAP_VALUE:
11398 		max = ptr_reg->map_ptr->value_size;
11399 		ptr_limit = (mask_to_left ?
11400 			     ptr_reg->smin_value :
11401 			     ptr_reg->umax_value) + ptr_reg->off;
11402 		break;
11403 	default:
11404 		return REASON_TYPE;
11405 	}
11406 
11407 	if (ptr_limit >= max)
11408 		return REASON_LIMIT;
11409 	*alu_limit = ptr_limit;
11410 	return 0;
11411 }
11412 
11413 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11414 				    const struct bpf_insn *insn)
11415 {
11416 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11417 }
11418 
11419 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11420 				       u32 alu_state, u32 alu_limit)
11421 {
11422 	/* If we arrived here from different branches with different
11423 	 * state or limits to sanitize, then this won't work.
11424 	 */
11425 	if (aux->alu_state &&
11426 	    (aux->alu_state != alu_state ||
11427 	     aux->alu_limit != alu_limit))
11428 		return REASON_PATHS;
11429 
11430 	/* Corresponding fixup done in do_misc_fixups(). */
11431 	aux->alu_state = alu_state;
11432 	aux->alu_limit = alu_limit;
11433 	return 0;
11434 }
11435 
11436 static int sanitize_val_alu(struct bpf_verifier_env *env,
11437 			    struct bpf_insn *insn)
11438 {
11439 	struct bpf_insn_aux_data *aux = cur_aux(env);
11440 
11441 	if (can_skip_alu_sanitation(env, insn))
11442 		return 0;
11443 
11444 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11445 }
11446 
11447 static bool sanitize_needed(u8 opcode)
11448 {
11449 	return opcode == BPF_ADD || opcode == BPF_SUB;
11450 }
11451 
11452 struct bpf_sanitize_info {
11453 	struct bpf_insn_aux_data aux;
11454 	bool mask_to_left;
11455 };
11456 
11457 static struct bpf_verifier_state *
11458 sanitize_speculative_path(struct bpf_verifier_env *env,
11459 			  const struct bpf_insn *insn,
11460 			  u32 next_idx, u32 curr_idx)
11461 {
11462 	struct bpf_verifier_state *branch;
11463 	struct bpf_reg_state *regs;
11464 
11465 	branch = push_stack(env, next_idx, curr_idx, true);
11466 	if (branch && insn) {
11467 		regs = branch->frame[branch->curframe]->regs;
11468 		if (BPF_SRC(insn->code) == BPF_K) {
11469 			mark_reg_unknown(env, regs, insn->dst_reg);
11470 		} else if (BPF_SRC(insn->code) == BPF_X) {
11471 			mark_reg_unknown(env, regs, insn->dst_reg);
11472 			mark_reg_unknown(env, regs, insn->src_reg);
11473 		}
11474 	}
11475 	return branch;
11476 }
11477 
11478 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11479 			    struct bpf_insn *insn,
11480 			    const struct bpf_reg_state *ptr_reg,
11481 			    const struct bpf_reg_state *off_reg,
11482 			    struct bpf_reg_state *dst_reg,
11483 			    struct bpf_sanitize_info *info,
11484 			    const bool commit_window)
11485 {
11486 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11487 	struct bpf_verifier_state *vstate = env->cur_state;
11488 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11489 	bool off_is_neg = off_reg->smin_value < 0;
11490 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11491 	u8 opcode = BPF_OP(insn->code);
11492 	u32 alu_state, alu_limit;
11493 	struct bpf_reg_state tmp;
11494 	bool ret;
11495 	int err;
11496 
11497 	if (can_skip_alu_sanitation(env, insn))
11498 		return 0;
11499 
11500 	/* We already marked aux for masking from non-speculative
11501 	 * paths, thus we got here in the first place. We only care
11502 	 * to explore bad access from here.
11503 	 */
11504 	if (vstate->speculative)
11505 		goto do_sim;
11506 
11507 	if (!commit_window) {
11508 		if (!tnum_is_const(off_reg->var_off) &&
11509 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11510 			return REASON_BOUNDS;
11511 
11512 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11513 				     (opcode == BPF_SUB && !off_is_neg);
11514 	}
11515 
11516 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11517 	if (err < 0)
11518 		return err;
11519 
11520 	if (commit_window) {
11521 		/* In commit phase we narrow the masking window based on
11522 		 * the observed pointer move after the simulated operation.
11523 		 */
11524 		alu_state = info->aux.alu_state;
11525 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11526 	} else {
11527 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11528 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11529 		alu_state |= ptr_is_dst_reg ?
11530 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11531 
11532 		/* Limit pruning on unknown scalars to enable deep search for
11533 		 * potential masking differences from other program paths.
11534 		 */
11535 		if (!off_is_imm)
11536 			env->explore_alu_limits = true;
11537 	}
11538 
11539 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11540 	if (err < 0)
11541 		return err;
11542 do_sim:
11543 	/* If we're in commit phase, we're done here given we already
11544 	 * pushed the truncated dst_reg into the speculative verification
11545 	 * stack.
11546 	 *
11547 	 * Also, when register is a known constant, we rewrite register-based
11548 	 * operation to immediate-based, and thus do not need masking (and as
11549 	 * a consequence, do not need to simulate the zero-truncation either).
11550 	 */
11551 	if (commit_window || off_is_imm)
11552 		return 0;
11553 
11554 	/* Simulate and find potential out-of-bounds access under
11555 	 * speculative execution from truncation as a result of
11556 	 * masking when off was not within expected range. If off
11557 	 * sits in dst, then we temporarily need to move ptr there
11558 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11559 	 * for cases where we use K-based arithmetic in one direction
11560 	 * and truncated reg-based in the other in order to explore
11561 	 * bad access.
11562 	 */
11563 	if (!ptr_is_dst_reg) {
11564 		tmp = *dst_reg;
11565 		copy_register_state(dst_reg, ptr_reg);
11566 	}
11567 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11568 					env->insn_idx);
11569 	if (!ptr_is_dst_reg && ret)
11570 		*dst_reg = tmp;
11571 	return !ret ? REASON_STACK : 0;
11572 }
11573 
11574 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11575 {
11576 	struct bpf_verifier_state *vstate = env->cur_state;
11577 
11578 	/* If we simulate paths under speculation, we don't update the
11579 	 * insn as 'seen' such that when we verify unreachable paths in
11580 	 * the non-speculative domain, sanitize_dead_code() can still
11581 	 * rewrite/sanitize them.
11582 	 */
11583 	if (!vstate->speculative)
11584 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11585 }
11586 
11587 static int sanitize_err(struct bpf_verifier_env *env,
11588 			const struct bpf_insn *insn, int reason,
11589 			const struct bpf_reg_state *off_reg,
11590 			const struct bpf_reg_state *dst_reg)
11591 {
11592 	static const char *err = "pointer arithmetic with it prohibited for !root";
11593 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11594 	u32 dst = insn->dst_reg, src = insn->src_reg;
11595 
11596 	switch (reason) {
11597 	case REASON_BOUNDS:
11598 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11599 			off_reg == dst_reg ? dst : src, err);
11600 		break;
11601 	case REASON_TYPE:
11602 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11603 			off_reg == dst_reg ? src : dst, err);
11604 		break;
11605 	case REASON_PATHS:
11606 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11607 			dst, op, err);
11608 		break;
11609 	case REASON_LIMIT:
11610 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11611 			dst, op, err);
11612 		break;
11613 	case REASON_STACK:
11614 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11615 			dst, err);
11616 		break;
11617 	default:
11618 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11619 			reason);
11620 		break;
11621 	}
11622 
11623 	return -EACCES;
11624 }
11625 
11626 /* check that stack access falls within stack limits and that 'reg' doesn't
11627  * have a variable offset.
11628  *
11629  * Variable offset is prohibited for unprivileged mode for simplicity since it
11630  * requires corresponding support in Spectre masking for stack ALU.  See also
11631  * retrieve_ptr_limit().
11632  *
11633  *
11634  * 'off' includes 'reg->off'.
11635  */
11636 static int check_stack_access_for_ptr_arithmetic(
11637 				struct bpf_verifier_env *env,
11638 				int regno,
11639 				const struct bpf_reg_state *reg,
11640 				int off)
11641 {
11642 	if (!tnum_is_const(reg->var_off)) {
11643 		char tn_buf[48];
11644 
11645 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11646 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11647 			regno, tn_buf, off);
11648 		return -EACCES;
11649 	}
11650 
11651 	if (off >= 0 || off < -MAX_BPF_STACK) {
11652 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11653 			"prohibited for !root; off=%d\n", regno, off);
11654 		return -EACCES;
11655 	}
11656 
11657 	return 0;
11658 }
11659 
11660 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11661 				 const struct bpf_insn *insn,
11662 				 const struct bpf_reg_state *dst_reg)
11663 {
11664 	u32 dst = insn->dst_reg;
11665 
11666 	/* For unprivileged we require that resulting offset must be in bounds
11667 	 * in order to be able to sanitize access later on.
11668 	 */
11669 	if (env->bypass_spec_v1)
11670 		return 0;
11671 
11672 	switch (dst_reg->type) {
11673 	case PTR_TO_STACK:
11674 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11675 					dst_reg->off + dst_reg->var_off.value))
11676 			return -EACCES;
11677 		break;
11678 	case PTR_TO_MAP_VALUE:
11679 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11680 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11681 				"prohibited for !root\n", dst);
11682 			return -EACCES;
11683 		}
11684 		break;
11685 	default:
11686 		break;
11687 	}
11688 
11689 	return 0;
11690 }
11691 
11692 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11693  * Caller should also handle BPF_MOV case separately.
11694  * If we return -EACCES, caller may want to try again treating pointer as a
11695  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11696  */
11697 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11698 				   struct bpf_insn *insn,
11699 				   const struct bpf_reg_state *ptr_reg,
11700 				   const struct bpf_reg_state *off_reg)
11701 {
11702 	struct bpf_verifier_state *vstate = env->cur_state;
11703 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11704 	struct bpf_reg_state *regs = state->regs, *dst_reg;
11705 	bool known = tnum_is_const(off_reg->var_off);
11706 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11707 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11708 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11709 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11710 	struct bpf_sanitize_info info = {};
11711 	u8 opcode = BPF_OP(insn->code);
11712 	u32 dst = insn->dst_reg;
11713 	int ret;
11714 
11715 	dst_reg = &regs[dst];
11716 
11717 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11718 	    smin_val > smax_val || umin_val > umax_val) {
11719 		/* Taint dst register if offset had invalid bounds derived from
11720 		 * e.g. dead branches.
11721 		 */
11722 		__mark_reg_unknown(env, dst_reg);
11723 		return 0;
11724 	}
11725 
11726 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
11727 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
11728 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11729 			__mark_reg_unknown(env, dst_reg);
11730 			return 0;
11731 		}
11732 
11733 		verbose(env,
11734 			"R%d 32-bit pointer arithmetic prohibited\n",
11735 			dst);
11736 		return -EACCES;
11737 	}
11738 
11739 	if (ptr_reg->type & PTR_MAYBE_NULL) {
11740 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11741 			dst, reg_type_str(env, ptr_reg->type));
11742 		return -EACCES;
11743 	}
11744 
11745 	switch (base_type(ptr_reg->type)) {
11746 	case CONST_PTR_TO_MAP:
11747 		/* smin_val represents the known value */
11748 		if (known && smin_val == 0 && opcode == BPF_ADD)
11749 			break;
11750 		fallthrough;
11751 	case PTR_TO_PACKET_END:
11752 	case PTR_TO_SOCKET:
11753 	case PTR_TO_SOCK_COMMON:
11754 	case PTR_TO_TCP_SOCK:
11755 	case PTR_TO_XDP_SOCK:
11756 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11757 			dst, reg_type_str(env, ptr_reg->type));
11758 		return -EACCES;
11759 	default:
11760 		break;
11761 	}
11762 
11763 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11764 	 * The id may be overwritten later if we create a new variable offset.
11765 	 */
11766 	dst_reg->type = ptr_reg->type;
11767 	dst_reg->id = ptr_reg->id;
11768 
11769 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11770 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11771 		return -EINVAL;
11772 
11773 	/* pointer types do not carry 32-bit bounds at the moment. */
11774 	__mark_reg32_unbounded(dst_reg);
11775 
11776 	if (sanitize_needed(opcode)) {
11777 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11778 				       &info, false);
11779 		if (ret < 0)
11780 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11781 	}
11782 
11783 	switch (opcode) {
11784 	case BPF_ADD:
11785 		/* We can take a fixed offset as long as it doesn't overflow
11786 		 * the s32 'off' field
11787 		 */
11788 		if (known && (ptr_reg->off + smin_val ==
11789 			      (s64)(s32)(ptr_reg->off + smin_val))) {
11790 			/* pointer += K.  Accumulate it into fixed offset */
11791 			dst_reg->smin_value = smin_ptr;
11792 			dst_reg->smax_value = smax_ptr;
11793 			dst_reg->umin_value = umin_ptr;
11794 			dst_reg->umax_value = umax_ptr;
11795 			dst_reg->var_off = ptr_reg->var_off;
11796 			dst_reg->off = ptr_reg->off + smin_val;
11797 			dst_reg->raw = ptr_reg->raw;
11798 			break;
11799 		}
11800 		/* A new variable offset is created.  Note that off_reg->off
11801 		 * == 0, since it's a scalar.
11802 		 * dst_reg gets the pointer type and since some positive
11803 		 * integer value was added to the pointer, give it a new 'id'
11804 		 * if it's a PTR_TO_PACKET.
11805 		 * this creates a new 'base' pointer, off_reg (variable) gets
11806 		 * added into the variable offset, and we copy the fixed offset
11807 		 * from ptr_reg.
11808 		 */
11809 		if (signed_add_overflows(smin_ptr, smin_val) ||
11810 		    signed_add_overflows(smax_ptr, smax_val)) {
11811 			dst_reg->smin_value = S64_MIN;
11812 			dst_reg->smax_value = S64_MAX;
11813 		} else {
11814 			dst_reg->smin_value = smin_ptr + smin_val;
11815 			dst_reg->smax_value = smax_ptr + smax_val;
11816 		}
11817 		if (umin_ptr + umin_val < umin_ptr ||
11818 		    umax_ptr + umax_val < umax_ptr) {
11819 			dst_reg->umin_value = 0;
11820 			dst_reg->umax_value = U64_MAX;
11821 		} else {
11822 			dst_reg->umin_value = umin_ptr + umin_val;
11823 			dst_reg->umax_value = umax_ptr + umax_val;
11824 		}
11825 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11826 		dst_reg->off = ptr_reg->off;
11827 		dst_reg->raw = ptr_reg->raw;
11828 		if (reg_is_pkt_pointer(ptr_reg)) {
11829 			dst_reg->id = ++env->id_gen;
11830 			/* something was added to pkt_ptr, set range to zero */
11831 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11832 		}
11833 		break;
11834 	case BPF_SUB:
11835 		if (dst_reg == off_reg) {
11836 			/* scalar -= pointer.  Creates an unknown scalar */
11837 			verbose(env, "R%d tried to subtract pointer from scalar\n",
11838 				dst);
11839 			return -EACCES;
11840 		}
11841 		/* We don't allow subtraction from FP, because (according to
11842 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
11843 		 * be able to deal with it.
11844 		 */
11845 		if (ptr_reg->type == PTR_TO_STACK) {
11846 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
11847 				dst);
11848 			return -EACCES;
11849 		}
11850 		if (known && (ptr_reg->off - smin_val ==
11851 			      (s64)(s32)(ptr_reg->off - smin_val))) {
11852 			/* pointer -= K.  Subtract it from fixed offset */
11853 			dst_reg->smin_value = smin_ptr;
11854 			dst_reg->smax_value = smax_ptr;
11855 			dst_reg->umin_value = umin_ptr;
11856 			dst_reg->umax_value = umax_ptr;
11857 			dst_reg->var_off = ptr_reg->var_off;
11858 			dst_reg->id = ptr_reg->id;
11859 			dst_reg->off = ptr_reg->off - smin_val;
11860 			dst_reg->raw = ptr_reg->raw;
11861 			break;
11862 		}
11863 		/* A new variable offset is created.  If the subtrahend is known
11864 		 * nonnegative, then any reg->range we had before is still good.
11865 		 */
11866 		if (signed_sub_overflows(smin_ptr, smax_val) ||
11867 		    signed_sub_overflows(smax_ptr, smin_val)) {
11868 			/* Overflow possible, we know nothing */
11869 			dst_reg->smin_value = S64_MIN;
11870 			dst_reg->smax_value = S64_MAX;
11871 		} else {
11872 			dst_reg->smin_value = smin_ptr - smax_val;
11873 			dst_reg->smax_value = smax_ptr - smin_val;
11874 		}
11875 		if (umin_ptr < umax_val) {
11876 			/* Overflow possible, we know nothing */
11877 			dst_reg->umin_value = 0;
11878 			dst_reg->umax_value = U64_MAX;
11879 		} else {
11880 			/* Cannot overflow (as long as bounds are consistent) */
11881 			dst_reg->umin_value = umin_ptr - umax_val;
11882 			dst_reg->umax_value = umax_ptr - umin_val;
11883 		}
11884 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11885 		dst_reg->off = ptr_reg->off;
11886 		dst_reg->raw = ptr_reg->raw;
11887 		if (reg_is_pkt_pointer(ptr_reg)) {
11888 			dst_reg->id = ++env->id_gen;
11889 			/* something was added to pkt_ptr, set range to zero */
11890 			if (smin_val < 0)
11891 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11892 		}
11893 		break;
11894 	case BPF_AND:
11895 	case BPF_OR:
11896 	case BPF_XOR:
11897 		/* bitwise ops on pointers are troublesome, prohibit. */
11898 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11899 			dst, bpf_alu_string[opcode >> 4]);
11900 		return -EACCES;
11901 	default:
11902 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
11903 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11904 			dst, bpf_alu_string[opcode >> 4]);
11905 		return -EACCES;
11906 	}
11907 
11908 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11909 		return -EINVAL;
11910 	reg_bounds_sync(dst_reg);
11911 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11912 		return -EACCES;
11913 	if (sanitize_needed(opcode)) {
11914 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11915 				       &info, true);
11916 		if (ret < 0)
11917 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11918 	}
11919 
11920 	return 0;
11921 }
11922 
11923 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11924 				 struct bpf_reg_state *src_reg)
11925 {
11926 	s32 smin_val = src_reg->s32_min_value;
11927 	s32 smax_val = src_reg->s32_max_value;
11928 	u32 umin_val = src_reg->u32_min_value;
11929 	u32 umax_val = src_reg->u32_max_value;
11930 
11931 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11932 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11933 		dst_reg->s32_min_value = S32_MIN;
11934 		dst_reg->s32_max_value = S32_MAX;
11935 	} else {
11936 		dst_reg->s32_min_value += smin_val;
11937 		dst_reg->s32_max_value += smax_val;
11938 	}
11939 	if (dst_reg->u32_min_value + umin_val < umin_val ||
11940 	    dst_reg->u32_max_value + umax_val < umax_val) {
11941 		dst_reg->u32_min_value = 0;
11942 		dst_reg->u32_max_value = U32_MAX;
11943 	} else {
11944 		dst_reg->u32_min_value += umin_val;
11945 		dst_reg->u32_max_value += umax_val;
11946 	}
11947 }
11948 
11949 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11950 			       struct bpf_reg_state *src_reg)
11951 {
11952 	s64 smin_val = src_reg->smin_value;
11953 	s64 smax_val = src_reg->smax_value;
11954 	u64 umin_val = src_reg->umin_value;
11955 	u64 umax_val = src_reg->umax_value;
11956 
11957 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11958 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
11959 		dst_reg->smin_value = S64_MIN;
11960 		dst_reg->smax_value = S64_MAX;
11961 	} else {
11962 		dst_reg->smin_value += smin_val;
11963 		dst_reg->smax_value += smax_val;
11964 	}
11965 	if (dst_reg->umin_value + umin_val < umin_val ||
11966 	    dst_reg->umax_value + umax_val < umax_val) {
11967 		dst_reg->umin_value = 0;
11968 		dst_reg->umax_value = U64_MAX;
11969 	} else {
11970 		dst_reg->umin_value += umin_val;
11971 		dst_reg->umax_value += umax_val;
11972 	}
11973 }
11974 
11975 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11976 				 struct bpf_reg_state *src_reg)
11977 {
11978 	s32 smin_val = src_reg->s32_min_value;
11979 	s32 smax_val = src_reg->s32_max_value;
11980 	u32 umin_val = src_reg->u32_min_value;
11981 	u32 umax_val = src_reg->u32_max_value;
11982 
11983 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11984 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11985 		/* Overflow possible, we know nothing */
11986 		dst_reg->s32_min_value = S32_MIN;
11987 		dst_reg->s32_max_value = S32_MAX;
11988 	} else {
11989 		dst_reg->s32_min_value -= smax_val;
11990 		dst_reg->s32_max_value -= smin_val;
11991 	}
11992 	if (dst_reg->u32_min_value < umax_val) {
11993 		/* Overflow possible, we know nothing */
11994 		dst_reg->u32_min_value = 0;
11995 		dst_reg->u32_max_value = U32_MAX;
11996 	} else {
11997 		/* Cannot overflow (as long as bounds are consistent) */
11998 		dst_reg->u32_min_value -= umax_val;
11999 		dst_reg->u32_max_value -= umin_val;
12000 	}
12001 }
12002 
12003 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12004 			       struct bpf_reg_state *src_reg)
12005 {
12006 	s64 smin_val = src_reg->smin_value;
12007 	s64 smax_val = src_reg->smax_value;
12008 	u64 umin_val = src_reg->umin_value;
12009 	u64 umax_val = src_reg->umax_value;
12010 
12011 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12012 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12013 		/* Overflow possible, we know nothing */
12014 		dst_reg->smin_value = S64_MIN;
12015 		dst_reg->smax_value = S64_MAX;
12016 	} else {
12017 		dst_reg->smin_value -= smax_val;
12018 		dst_reg->smax_value -= smin_val;
12019 	}
12020 	if (dst_reg->umin_value < umax_val) {
12021 		/* Overflow possible, we know nothing */
12022 		dst_reg->umin_value = 0;
12023 		dst_reg->umax_value = U64_MAX;
12024 	} else {
12025 		/* Cannot overflow (as long as bounds are consistent) */
12026 		dst_reg->umin_value -= umax_val;
12027 		dst_reg->umax_value -= umin_val;
12028 	}
12029 }
12030 
12031 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12032 				 struct bpf_reg_state *src_reg)
12033 {
12034 	s32 smin_val = src_reg->s32_min_value;
12035 	u32 umin_val = src_reg->u32_min_value;
12036 	u32 umax_val = src_reg->u32_max_value;
12037 
12038 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12039 		/* Ain't nobody got time to multiply that sign */
12040 		__mark_reg32_unbounded(dst_reg);
12041 		return;
12042 	}
12043 	/* Both values are positive, so we can work with unsigned and
12044 	 * copy the result to signed (unless it exceeds S32_MAX).
12045 	 */
12046 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12047 		/* Potential overflow, we know nothing */
12048 		__mark_reg32_unbounded(dst_reg);
12049 		return;
12050 	}
12051 	dst_reg->u32_min_value *= umin_val;
12052 	dst_reg->u32_max_value *= umax_val;
12053 	if (dst_reg->u32_max_value > S32_MAX) {
12054 		/* Overflow possible, we know nothing */
12055 		dst_reg->s32_min_value = S32_MIN;
12056 		dst_reg->s32_max_value = S32_MAX;
12057 	} else {
12058 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12059 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12060 	}
12061 }
12062 
12063 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12064 			       struct bpf_reg_state *src_reg)
12065 {
12066 	s64 smin_val = src_reg->smin_value;
12067 	u64 umin_val = src_reg->umin_value;
12068 	u64 umax_val = src_reg->umax_value;
12069 
12070 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12071 		/* Ain't nobody got time to multiply that sign */
12072 		__mark_reg64_unbounded(dst_reg);
12073 		return;
12074 	}
12075 	/* Both values are positive, so we can work with unsigned and
12076 	 * copy the result to signed (unless it exceeds S64_MAX).
12077 	 */
12078 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12079 		/* Potential overflow, we know nothing */
12080 		__mark_reg64_unbounded(dst_reg);
12081 		return;
12082 	}
12083 	dst_reg->umin_value *= umin_val;
12084 	dst_reg->umax_value *= umax_val;
12085 	if (dst_reg->umax_value > S64_MAX) {
12086 		/* Overflow possible, we know nothing */
12087 		dst_reg->smin_value = S64_MIN;
12088 		dst_reg->smax_value = S64_MAX;
12089 	} else {
12090 		dst_reg->smin_value = dst_reg->umin_value;
12091 		dst_reg->smax_value = dst_reg->umax_value;
12092 	}
12093 }
12094 
12095 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12096 				 struct bpf_reg_state *src_reg)
12097 {
12098 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12099 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12100 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12101 	s32 smin_val = src_reg->s32_min_value;
12102 	u32 umax_val = src_reg->u32_max_value;
12103 
12104 	if (src_known && dst_known) {
12105 		__mark_reg32_known(dst_reg, var32_off.value);
12106 		return;
12107 	}
12108 
12109 	/* We get our minimum from the var_off, since that's inherently
12110 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12111 	 */
12112 	dst_reg->u32_min_value = var32_off.value;
12113 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12114 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12115 		/* Lose signed bounds when ANDing negative numbers,
12116 		 * ain't nobody got time for that.
12117 		 */
12118 		dst_reg->s32_min_value = S32_MIN;
12119 		dst_reg->s32_max_value = S32_MAX;
12120 	} else {
12121 		/* ANDing two positives gives a positive, so safe to
12122 		 * cast result into s64.
12123 		 */
12124 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12125 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12126 	}
12127 }
12128 
12129 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12130 			       struct bpf_reg_state *src_reg)
12131 {
12132 	bool src_known = tnum_is_const(src_reg->var_off);
12133 	bool dst_known = tnum_is_const(dst_reg->var_off);
12134 	s64 smin_val = src_reg->smin_value;
12135 	u64 umax_val = src_reg->umax_value;
12136 
12137 	if (src_known && dst_known) {
12138 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12139 		return;
12140 	}
12141 
12142 	/* We get our minimum from the var_off, since that's inherently
12143 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12144 	 */
12145 	dst_reg->umin_value = dst_reg->var_off.value;
12146 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12147 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12148 		/* Lose signed bounds when ANDing negative numbers,
12149 		 * ain't nobody got time for that.
12150 		 */
12151 		dst_reg->smin_value = S64_MIN;
12152 		dst_reg->smax_value = S64_MAX;
12153 	} else {
12154 		/* ANDing two positives gives a positive, so safe to
12155 		 * cast result into s64.
12156 		 */
12157 		dst_reg->smin_value = dst_reg->umin_value;
12158 		dst_reg->smax_value = dst_reg->umax_value;
12159 	}
12160 	/* We may learn something more from the var_off */
12161 	__update_reg_bounds(dst_reg);
12162 }
12163 
12164 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12165 				struct bpf_reg_state *src_reg)
12166 {
12167 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12168 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12169 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12170 	s32 smin_val = src_reg->s32_min_value;
12171 	u32 umin_val = src_reg->u32_min_value;
12172 
12173 	if (src_known && dst_known) {
12174 		__mark_reg32_known(dst_reg, var32_off.value);
12175 		return;
12176 	}
12177 
12178 	/* We get our maximum from the var_off, and our minimum is the
12179 	 * maximum of the operands' minima
12180 	 */
12181 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12182 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12183 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12184 		/* Lose signed bounds when ORing negative numbers,
12185 		 * ain't nobody got time for that.
12186 		 */
12187 		dst_reg->s32_min_value = S32_MIN;
12188 		dst_reg->s32_max_value = S32_MAX;
12189 	} else {
12190 		/* ORing two positives gives a positive, so safe to
12191 		 * cast result into s64.
12192 		 */
12193 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12194 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12195 	}
12196 }
12197 
12198 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12199 			      struct bpf_reg_state *src_reg)
12200 {
12201 	bool src_known = tnum_is_const(src_reg->var_off);
12202 	bool dst_known = tnum_is_const(dst_reg->var_off);
12203 	s64 smin_val = src_reg->smin_value;
12204 	u64 umin_val = src_reg->umin_value;
12205 
12206 	if (src_known && dst_known) {
12207 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12208 		return;
12209 	}
12210 
12211 	/* We get our maximum from the var_off, and our minimum is the
12212 	 * maximum of the operands' minima
12213 	 */
12214 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12215 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12216 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12217 		/* Lose signed bounds when ORing negative numbers,
12218 		 * ain't nobody got time for that.
12219 		 */
12220 		dst_reg->smin_value = S64_MIN;
12221 		dst_reg->smax_value = S64_MAX;
12222 	} else {
12223 		/* ORing two positives gives a positive, so safe to
12224 		 * cast result into s64.
12225 		 */
12226 		dst_reg->smin_value = dst_reg->umin_value;
12227 		dst_reg->smax_value = dst_reg->umax_value;
12228 	}
12229 	/* We may learn something more from the var_off */
12230 	__update_reg_bounds(dst_reg);
12231 }
12232 
12233 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12234 				 struct bpf_reg_state *src_reg)
12235 {
12236 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12237 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12238 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12239 	s32 smin_val = src_reg->s32_min_value;
12240 
12241 	if (src_known && dst_known) {
12242 		__mark_reg32_known(dst_reg, var32_off.value);
12243 		return;
12244 	}
12245 
12246 	/* We get both minimum and maximum from the var32_off. */
12247 	dst_reg->u32_min_value = var32_off.value;
12248 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12249 
12250 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12251 		/* XORing two positive sign numbers gives a positive,
12252 		 * so safe to cast u32 result into s32.
12253 		 */
12254 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12255 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12256 	} else {
12257 		dst_reg->s32_min_value = S32_MIN;
12258 		dst_reg->s32_max_value = S32_MAX;
12259 	}
12260 }
12261 
12262 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12263 			       struct bpf_reg_state *src_reg)
12264 {
12265 	bool src_known = tnum_is_const(src_reg->var_off);
12266 	bool dst_known = tnum_is_const(dst_reg->var_off);
12267 	s64 smin_val = src_reg->smin_value;
12268 
12269 	if (src_known && dst_known) {
12270 		/* dst_reg->var_off.value has been updated earlier */
12271 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12272 		return;
12273 	}
12274 
12275 	/* We get both minimum and maximum from the var_off. */
12276 	dst_reg->umin_value = dst_reg->var_off.value;
12277 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12278 
12279 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12280 		/* XORing two positive sign numbers gives a positive,
12281 		 * so safe to cast u64 result into s64.
12282 		 */
12283 		dst_reg->smin_value = dst_reg->umin_value;
12284 		dst_reg->smax_value = dst_reg->umax_value;
12285 	} else {
12286 		dst_reg->smin_value = S64_MIN;
12287 		dst_reg->smax_value = S64_MAX;
12288 	}
12289 
12290 	__update_reg_bounds(dst_reg);
12291 }
12292 
12293 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12294 				   u64 umin_val, u64 umax_val)
12295 {
12296 	/* We lose all sign bit information (except what we can pick
12297 	 * up from var_off)
12298 	 */
12299 	dst_reg->s32_min_value = S32_MIN;
12300 	dst_reg->s32_max_value = S32_MAX;
12301 	/* If we might shift our top bit out, then we know nothing */
12302 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12303 		dst_reg->u32_min_value = 0;
12304 		dst_reg->u32_max_value = U32_MAX;
12305 	} else {
12306 		dst_reg->u32_min_value <<= umin_val;
12307 		dst_reg->u32_max_value <<= umax_val;
12308 	}
12309 }
12310 
12311 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12312 				 struct bpf_reg_state *src_reg)
12313 {
12314 	u32 umax_val = src_reg->u32_max_value;
12315 	u32 umin_val = src_reg->u32_min_value;
12316 	/* u32 alu operation will zext upper bits */
12317 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12318 
12319 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12320 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12321 	/* Not required but being careful mark reg64 bounds as unknown so
12322 	 * that we are forced to pick them up from tnum and zext later and
12323 	 * if some path skips this step we are still safe.
12324 	 */
12325 	__mark_reg64_unbounded(dst_reg);
12326 	__update_reg32_bounds(dst_reg);
12327 }
12328 
12329 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12330 				   u64 umin_val, u64 umax_val)
12331 {
12332 	/* Special case <<32 because it is a common compiler pattern to sign
12333 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12334 	 * positive we know this shift will also be positive so we can track
12335 	 * bounds correctly. Otherwise we lose all sign bit information except
12336 	 * what we can pick up from var_off. Perhaps we can generalize this
12337 	 * later to shifts of any length.
12338 	 */
12339 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12340 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12341 	else
12342 		dst_reg->smax_value = S64_MAX;
12343 
12344 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12345 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12346 	else
12347 		dst_reg->smin_value = S64_MIN;
12348 
12349 	/* If we might shift our top bit out, then we know nothing */
12350 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12351 		dst_reg->umin_value = 0;
12352 		dst_reg->umax_value = U64_MAX;
12353 	} else {
12354 		dst_reg->umin_value <<= umin_val;
12355 		dst_reg->umax_value <<= umax_val;
12356 	}
12357 }
12358 
12359 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12360 			       struct bpf_reg_state *src_reg)
12361 {
12362 	u64 umax_val = src_reg->umax_value;
12363 	u64 umin_val = src_reg->umin_value;
12364 
12365 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12366 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12367 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12368 
12369 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12370 	/* We may learn something more from the var_off */
12371 	__update_reg_bounds(dst_reg);
12372 }
12373 
12374 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12375 				 struct bpf_reg_state *src_reg)
12376 {
12377 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12378 	u32 umax_val = src_reg->u32_max_value;
12379 	u32 umin_val = src_reg->u32_min_value;
12380 
12381 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12382 	 * be negative, then either:
12383 	 * 1) src_reg might be zero, so the sign bit of the result is
12384 	 *    unknown, so we lose our signed bounds
12385 	 * 2) it's known negative, thus the unsigned bounds capture the
12386 	 *    signed bounds
12387 	 * 3) the signed bounds cross zero, so they tell us nothing
12388 	 *    about the result
12389 	 * If the value in dst_reg is known nonnegative, then again the
12390 	 * unsigned bounds capture the signed bounds.
12391 	 * Thus, in all cases it suffices to blow away our signed bounds
12392 	 * and rely on inferring new ones from the unsigned bounds and
12393 	 * var_off of the result.
12394 	 */
12395 	dst_reg->s32_min_value = S32_MIN;
12396 	dst_reg->s32_max_value = S32_MAX;
12397 
12398 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12399 	dst_reg->u32_min_value >>= umax_val;
12400 	dst_reg->u32_max_value >>= umin_val;
12401 
12402 	__mark_reg64_unbounded(dst_reg);
12403 	__update_reg32_bounds(dst_reg);
12404 }
12405 
12406 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12407 			       struct bpf_reg_state *src_reg)
12408 {
12409 	u64 umax_val = src_reg->umax_value;
12410 	u64 umin_val = src_reg->umin_value;
12411 
12412 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12413 	 * be negative, then either:
12414 	 * 1) src_reg might be zero, so the sign bit of the result is
12415 	 *    unknown, so we lose our signed bounds
12416 	 * 2) it's known negative, thus the unsigned bounds capture the
12417 	 *    signed bounds
12418 	 * 3) the signed bounds cross zero, so they tell us nothing
12419 	 *    about the result
12420 	 * If the value in dst_reg is known nonnegative, then again the
12421 	 * unsigned bounds capture the signed bounds.
12422 	 * Thus, in all cases it suffices to blow away our signed bounds
12423 	 * and rely on inferring new ones from the unsigned bounds and
12424 	 * var_off of the result.
12425 	 */
12426 	dst_reg->smin_value = S64_MIN;
12427 	dst_reg->smax_value = S64_MAX;
12428 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12429 	dst_reg->umin_value >>= umax_val;
12430 	dst_reg->umax_value >>= umin_val;
12431 
12432 	/* Its not easy to operate on alu32 bounds here because it depends
12433 	 * on bits being shifted in. Take easy way out and mark unbounded
12434 	 * so we can recalculate later from tnum.
12435 	 */
12436 	__mark_reg32_unbounded(dst_reg);
12437 	__update_reg_bounds(dst_reg);
12438 }
12439 
12440 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12441 				  struct bpf_reg_state *src_reg)
12442 {
12443 	u64 umin_val = src_reg->u32_min_value;
12444 
12445 	/* Upon reaching here, src_known is true and
12446 	 * umax_val is equal to umin_val.
12447 	 */
12448 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12449 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12450 
12451 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12452 
12453 	/* blow away the dst_reg umin_value/umax_value and rely on
12454 	 * dst_reg var_off to refine the result.
12455 	 */
12456 	dst_reg->u32_min_value = 0;
12457 	dst_reg->u32_max_value = U32_MAX;
12458 
12459 	__mark_reg64_unbounded(dst_reg);
12460 	__update_reg32_bounds(dst_reg);
12461 }
12462 
12463 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12464 				struct bpf_reg_state *src_reg)
12465 {
12466 	u64 umin_val = src_reg->umin_value;
12467 
12468 	/* Upon reaching here, src_known is true and umax_val is equal
12469 	 * to umin_val.
12470 	 */
12471 	dst_reg->smin_value >>= umin_val;
12472 	dst_reg->smax_value >>= umin_val;
12473 
12474 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12475 
12476 	/* blow away the dst_reg umin_value/umax_value and rely on
12477 	 * dst_reg var_off to refine the result.
12478 	 */
12479 	dst_reg->umin_value = 0;
12480 	dst_reg->umax_value = U64_MAX;
12481 
12482 	/* Its not easy to operate on alu32 bounds here because it depends
12483 	 * on bits being shifted in from upper 32-bits. Take easy way out
12484 	 * and mark unbounded so we can recalculate later from tnum.
12485 	 */
12486 	__mark_reg32_unbounded(dst_reg);
12487 	__update_reg_bounds(dst_reg);
12488 }
12489 
12490 /* WARNING: This function does calculations on 64-bit values, but the actual
12491  * execution may occur on 32-bit values. Therefore, things like bitshifts
12492  * need extra checks in the 32-bit case.
12493  */
12494 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12495 				      struct bpf_insn *insn,
12496 				      struct bpf_reg_state *dst_reg,
12497 				      struct bpf_reg_state src_reg)
12498 {
12499 	struct bpf_reg_state *regs = cur_regs(env);
12500 	u8 opcode = BPF_OP(insn->code);
12501 	bool src_known;
12502 	s64 smin_val, smax_val;
12503 	u64 umin_val, umax_val;
12504 	s32 s32_min_val, s32_max_val;
12505 	u32 u32_min_val, u32_max_val;
12506 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12507 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12508 	int ret;
12509 
12510 	smin_val = src_reg.smin_value;
12511 	smax_val = src_reg.smax_value;
12512 	umin_val = src_reg.umin_value;
12513 	umax_val = src_reg.umax_value;
12514 
12515 	s32_min_val = src_reg.s32_min_value;
12516 	s32_max_val = src_reg.s32_max_value;
12517 	u32_min_val = src_reg.u32_min_value;
12518 	u32_max_val = src_reg.u32_max_value;
12519 
12520 	if (alu32) {
12521 		src_known = tnum_subreg_is_const(src_reg.var_off);
12522 		if ((src_known &&
12523 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12524 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12525 			/* Taint dst register if offset had invalid bounds
12526 			 * derived from e.g. dead branches.
12527 			 */
12528 			__mark_reg_unknown(env, dst_reg);
12529 			return 0;
12530 		}
12531 	} else {
12532 		src_known = tnum_is_const(src_reg.var_off);
12533 		if ((src_known &&
12534 		     (smin_val != smax_val || umin_val != umax_val)) ||
12535 		    smin_val > smax_val || umin_val > umax_val) {
12536 			/* Taint dst register if offset had invalid bounds
12537 			 * derived from e.g. dead branches.
12538 			 */
12539 			__mark_reg_unknown(env, dst_reg);
12540 			return 0;
12541 		}
12542 	}
12543 
12544 	if (!src_known &&
12545 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12546 		__mark_reg_unknown(env, dst_reg);
12547 		return 0;
12548 	}
12549 
12550 	if (sanitize_needed(opcode)) {
12551 		ret = sanitize_val_alu(env, insn);
12552 		if (ret < 0)
12553 			return sanitize_err(env, insn, ret, NULL, NULL);
12554 	}
12555 
12556 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12557 	 * There are two classes of instructions: The first class we track both
12558 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12559 	 * greatest amount of precision when alu operations are mixed with jmp32
12560 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12561 	 * and BPF_OR. This is possible because these ops have fairly easy to
12562 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12563 	 * See alu32 verifier tests for examples. The second class of
12564 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12565 	 * with regards to tracking sign/unsigned bounds because the bits may
12566 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12567 	 * the reg unbounded in the subreg bound space and use the resulting
12568 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12569 	 */
12570 	switch (opcode) {
12571 	case BPF_ADD:
12572 		scalar32_min_max_add(dst_reg, &src_reg);
12573 		scalar_min_max_add(dst_reg, &src_reg);
12574 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12575 		break;
12576 	case BPF_SUB:
12577 		scalar32_min_max_sub(dst_reg, &src_reg);
12578 		scalar_min_max_sub(dst_reg, &src_reg);
12579 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12580 		break;
12581 	case BPF_MUL:
12582 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12583 		scalar32_min_max_mul(dst_reg, &src_reg);
12584 		scalar_min_max_mul(dst_reg, &src_reg);
12585 		break;
12586 	case BPF_AND:
12587 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12588 		scalar32_min_max_and(dst_reg, &src_reg);
12589 		scalar_min_max_and(dst_reg, &src_reg);
12590 		break;
12591 	case BPF_OR:
12592 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12593 		scalar32_min_max_or(dst_reg, &src_reg);
12594 		scalar_min_max_or(dst_reg, &src_reg);
12595 		break;
12596 	case BPF_XOR:
12597 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12598 		scalar32_min_max_xor(dst_reg, &src_reg);
12599 		scalar_min_max_xor(dst_reg, &src_reg);
12600 		break;
12601 	case BPF_LSH:
12602 		if (umax_val >= insn_bitness) {
12603 			/* Shifts greater than 31 or 63 are undefined.
12604 			 * This includes shifts by a negative number.
12605 			 */
12606 			mark_reg_unknown(env, regs, insn->dst_reg);
12607 			break;
12608 		}
12609 		if (alu32)
12610 			scalar32_min_max_lsh(dst_reg, &src_reg);
12611 		else
12612 			scalar_min_max_lsh(dst_reg, &src_reg);
12613 		break;
12614 	case BPF_RSH:
12615 		if (umax_val >= insn_bitness) {
12616 			/* Shifts greater than 31 or 63 are undefined.
12617 			 * This includes shifts by a negative number.
12618 			 */
12619 			mark_reg_unknown(env, regs, insn->dst_reg);
12620 			break;
12621 		}
12622 		if (alu32)
12623 			scalar32_min_max_rsh(dst_reg, &src_reg);
12624 		else
12625 			scalar_min_max_rsh(dst_reg, &src_reg);
12626 		break;
12627 	case BPF_ARSH:
12628 		if (umax_val >= insn_bitness) {
12629 			/* Shifts greater than 31 or 63 are undefined.
12630 			 * This includes shifts by a negative number.
12631 			 */
12632 			mark_reg_unknown(env, regs, insn->dst_reg);
12633 			break;
12634 		}
12635 		if (alu32)
12636 			scalar32_min_max_arsh(dst_reg, &src_reg);
12637 		else
12638 			scalar_min_max_arsh(dst_reg, &src_reg);
12639 		break;
12640 	default:
12641 		mark_reg_unknown(env, regs, insn->dst_reg);
12642 		break;
12643 	}
12644 
12645 	/* ALU32 ops are zero extended into 64bit register */
12646 	if (alu32)
12647 		zext_32_to_64(dst_reg);
12648 	reg_bounds_sync(dst_reg);
12649 	return 0;
12650 }
12651 
12652 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12653  * and var_off.
12654  */
12655 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12656 				   struct bpf_insn *insn)
12657 {
12658 	struct bpf_verifier_state *vstate = env->cur_state;
12659 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12660 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12661 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12662 	u8 opcode = BPF_OP(insn->code);
12663 	int err;
12664 
12665 	dst_reg = &regs[insn->dst_reg];
12666 	src_reg = NULL;
12667 	if (dst_reg->type != SCALAR_VALUE)
12668 		ptr_reg = dst_reg;
12669 	else
12670 		/* Make sure ID is cleared otherwise dst_reg min/max could be
12671 		 * incorrectly propagated into other registers by find_equal_scalars()
12672 		 */
12673 		dst_reg->id = 0;
12674 	if (BPF_SRC(insn->code) == BPF_X) {
12675 		src_reg = &regs[insn->src_reg];
12676 		if (src_reg->type != SCALAR_VALUE) {
12677 			if (dst_reg->type != SCALAR_VALUE) {
12678 				/* Combining two pointers by any ALU op yields
12679 				 * an arbitrary scalar. Disallow all math except
12680 				 * pointer subtraction
12681 				 */
12682 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12683 					mark_reg_unknown(env, regs, insn->dst_reg);
12684 					return 0;
12685 				}
12686 				verbose(env, "R%d pointer %s pointer prohibited\n",
12687 					insn->dst_reg,
12688 					bpf_alu_string[opcode >> 4]);
12689 				return -EACCES;
12690 			} else {
12691 				/* scalar += pointer
12692 				 * This is legal, but we have to reverse our
12693 				 * src/dest handling in computing the range
12694 				 */
12695 				err = mark_chain_precision(env, insn->dst_reg);
12696 				if (err)
12697 					return err;
12698 				return adjust_ptr_min_max_vals(env, insn,
12699 							       src_reg, dst_reg);
12700 			}
12701 		} else if (ptr_reg) {
12702 			/* pointer += scalar */
12703 			err = mark_chain_precision(env, insn->src_reg);
12704 			if (err)
12705 				return err;
12706 			return adjust_ptr_min_max_vals(env, insn,
12707 						       dst_reg, src_reg);
12708 		} else if (dst_reg->precise) {
12709 			/* if dst_reg is precise, src_reg should be precise as well */
12710 			err = mark_chain_precision(env, insn->src_reg);
12711 			if (err)
12712 				return err;
12713 		}
12714 	} else {
12715 		/* Pretend the src is a reg with a known value, since we only
12716 		 * need to be able to read from this state.
12717 		 */
12718 		off_reg.type = SCALAR_VALUE;
12719 		__mark_reg_known(&off_reg, insn->imm);
12720 		src_reg = &off_reg;
12721 		if (ptr_reg) /* pointer += K */
12722 			return adjust_ptr_min_max_vals(env, insn,
12723 						       ptr_reg, src_reg);
12724 	}
12725 
12726 	/* Got here implies adding two SCALAR_VALUEs */
12727 	if (WARN_ON_ONCE(ptr_reg)) {
12728 		print_verifier_state(env, state, true);
12729 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
12730 		return -EINVAL;
12731 	}
12732 	if (WARN_ON(!src_reg)) {
12733 		print_verifier_state(env, state, true);
12734 		verbose(env, "verifier internal error: no src_reg\n");
12735 		return -EINVAL;
12736 	}
12737 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12738 }
12739 
12740 /* check validity of 32-bit and 64-bit arithmetic operations */
12741 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12742 {
12743 	struct bpf_reg_state *regs = cur_regs(env);
12744 	u8 opcode = BPF_OP(insn->code);
12745 	int err;
12746 
12747 	if (opcode == BPF_END || opcode == BPF_NEG) {
12748 		if (opcode == BPF_NEG) {
12749 			if (BPF_SRC(insn->code) != BPF_K ||
12750 			    insn->src_reg != BPF_REG_0 ||
12751 			    insn->off != 0 || insn->imm != 0) {
12752 				verbose(env, "BPF_NEG uses reserved fields\n");
12753 				return -EINVAL;
12754 			}
12755 		} else {
12756 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12757 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12758 			    BPF_CLASS(insn->code) == BPF_ALU64) {
12759 				verbose(env, "BPF_END uses reserved fields\n");
12760 				return -EINVAL;
12761 			}
12762 		}
12763 
12764 		/* check src operand */
12765 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12766 		if (err)
12767 			return err;
12768 
12769 		if (is_pointer_value(env, insn->dst_reg)) {
12770 			verbose(env, "R%d pointer arithmetic prohibited\n",
12771 				insn->dst_reg);
12772 			return -EACCES;
12773 		}
12774 
12775 		/* check dest operand */
12776 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
12777 		if (err)
12778 			return err;
12779 
12780 	} else if (opcode == BPF_MOV) {
12781 
12782 		if (BPF_SRC(insn->code) == BPF_X) {
12783 			if (insn->imm != 0 || insn->off != 0) {
12784 				verbose(env, "BPF_MOV uses reserved fields\n");
12785 				return -EINVAL;
12786 			}
12787 
12788 			/* check src operand */
12789 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12790 			if (err)
12791 				return err;
12792 		} else {
12793 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12794 				verbose(env, "BPF_MOV uses reserved fields\n");
12795 				return -EINVAL;
12796 			}
12797 		}
12798 
12799 		/* check dest operand, mark as required later */
12800 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12801 		if (err)
12802 			return err;
12803 
12804 		if (BPF_SRC(insn->code) == BPF_X) {
12805 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
12806 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12807 
12808 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12809 				/* case: R1 = R2
12810 				 * copy register state to dest reg
12811 				 */
12812 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12813 					/* Assign src and dst registers the same ID
12814 					 * that will be used by find_equal_scalars()
12815 					 * to propagate min/max range.
12816 					 */
12817 					src_reg->id = ++env->id_gen;
12818 				copy_register_state(dst_reg, src_reg);
12819 				dst_reg->live |= REG_LIVE_WRITTEN;
12820 				dst_reg->subreg_def = DEF_NOT_SUBREG;
12821 			} else {
12822 				/* R1 = (u32) R2 */
12823 				if (is_pointer_value(env, insn->src_reg)) {
12824 					verbose(env,
12825 						"R%d partial copy of pointer\n",
12826 						insn->src_reg);
12827 					return -EACCES;
12828 				} else if (src_reg->type == SCALAR_VALUE) {
12829 					bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12830 
12831 					if (is_src_reg_u32 && !src_reg->id)
12832 						src_reg->id = ++env->id_gen;
12833 					copy_register_state(dst_reg, src_reg);
12834 					/* Make sure ID is cleared if src_reg is not in u32 range otherwise
12835 					 * dst_reg min/max could be incorrectly
12836 					 * propagated into src_reg by find_equal_scalars()
12837 					 */
12838 					if (!is_src_reg_u32)
12839 						dst_reg->id = 0;
12840 					dst_reg->live |= REG_LIVE_WRITTEN;
12841 					dst_reg->subreg_def = env->insn_idx + 1;
12842 				} else {
12843 					mark_reg_unknown(env, regs,
12844 							 insn->dst_reg);
12845 				}
12846 				zext_32_to_64(dst_reg);
12847 				reg_bounds_sync(dst_reg);
12848 			}
12849 		} else {
12850 			/* case: R = imm
12851 			 * remember the value we stored into this reg
12852 			 */
12853 			/* clear any state __mark_reg_known doesn't set */
12854 			mark_reg_unknown(env, regs, insn->dst_reg);
12855 			regs[insn->dst_reg].type = SCALAR_VALUE;
12856 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12857 				__mark_reg_known(regs + insn->dst_reg,
12858 						 insn->imm);
12859 			} else {
12860 				__mark_reg_known(regs + insn->dst_reg,
12861 						 (u32)insn->imm);
12862 			}
12863 		}
12864 
12865 	} else if (opcode > BPF_END) {
12866 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12867 		return -EINVAL;
12868 
12869 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
12870 
12871 		if (BPF_SRC(insn->code) == BPF_X) {
12872 			if (insn->imm != 0 || insn->off != 0) {
12873 				verbose(env, "BPF_ALU uses reserved fields\n");
12874 				return -EINVAL;
12875 			}
12876 			/* check src1 operand */
12877 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12878 			if (err)
12879 				return err;
12880 		} else {
12881 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12882 				verbose(env, "BPF_ALU uses reserved fields\n");
12883 				return -EINVAL;
12884 			}
12885 		}
12886 
12887 		/* check src2 operand */
12888 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12889 		if (err)
12890 			return err;
12891 
12892 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12893 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12894 			verbose(env, "div by zero\n");
12895 			return -EINVAL;
12896 		}
12897 
12898 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12899 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12900 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12901 
12902 			if (insn->imm < 0 || insn->imm >= size) {
12903 				verbose(env, "invalid shift %d\n", insn->imm);
12904 				return -EINVAL;
12905 			}
12906 		}
12907 
12908 		/* check dest operand */
12909 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12910 		if (err)
12911 			return err;
12912 
12913 		return adjust_reg_min_max_vals(env, insn);
12914 	}
12915 
12916 	return 0;
12917 }
12918 
12919 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12920 				   struct bpf_reg_state *dst_reg,
12921 				   enum bpf_reg_type type,
12922 				   bool range_right_open)
12923 {
12924 	struct bpf_func_state *state;
12925 	struct bpf_reg_state *reg;
12926 	int new_range;
12927 
12928 	if (dst_reg->off < 0 ||
12929 	    (dst_reg->off == 0 && range_right_open))
12930 		/* This doesn't give us any range */
12931 		return;
12932 
12933 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
12934 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12935 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
12936 		 * than pkt_end, but that's because it's also less than pkt.
12937 		 */
12938 		return;
12939 
12940 	new_range = dst_reg->off;
12941 	if (range_right_open)
12942 		new_range++;
12943 
12944 	/* Examples for register markings:
12945 	 *
12946 	 * pkt_data in dst register:
12947 	 *
12948 	 *   r2 = r3;
12949 	 *   r2 += 8;
12950 	 *   if (r2 > pkt_end) goto <handle exception>
12951 	 *   <access okay>
12952 	 *
12953 	 *   r2 = r3;
12954 	 *   r2 += 8;
12955 	 *   if (r2 < pkt_end) goto <access okay>
12956 	 *   <handle exception>
12957 	 *
12958 	 *   Where:
12959 	 *     r2 == dst_reg, pkt_end == src_reg
12960 	 *     r2=pkt(id=n,off=8,r=0)
12961 	 *     r3=pkt(id=n,off=0,r=0)
12962 	 *
12963 	 * pkt_data in src register:
12964 	 *
12965 	 *   r2 = r3;
12966 	 *   r2 += 8;
12967 	 *   if (pkt_end >= r2) goto <access okay>
12968 	 *   <handle exception>
12969 	 *
12970 	 *   r2 = r3;
12971 	 *   r2 += 8;
12972 	 *   if (pkt_end <= r2) goto <handle exception>
12973 	 *   <access okay>
12974 	 *
12975 	 *   Where:
12976 	 *     pkt_end == dst_reg, r2 == src_reg
12977 	 *     r2=pkt(id=n,off=8,r=0)
12978 	 *     r3=pkt(id=n,off=0,r=0)
12979 	 *
12980 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12981 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12982 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
12983 	 * the check.
12984 	 */
12985 
12986 	/* If our ids match, then we must have the same max_value.  And we
12987 	 * don't care about the other reg's fixed offset, since if it's too big
12988 	 * the range won't allow anything.
12989 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12990 	 */
12991 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12992 		if (reg->type == type && reg->id == dst_reg->id)
12993 			/* keep the maximum range already checked */
12994 			reg->range = max(reg->range, new_range);
12995 	}));
12996 }
12997 
12998 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12999 {
13000 	struct tnum subreg = tnum_subreg(reg->var_off);
13001 	s32 sval = (s32)val;
13002 
13003 	switch (opcode) {
13004 	case BPF_JEQ:
13005 		if (tnum_is_const(subreg))
13006 			return !!tnum_equals_const(subreg, val);
13007 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13008 			return 0;
13009 		break;
13010 	case BPF_JNE:
13011 		if (tnum_is_const(subreg))
13012 			return !tnum_equals_const(subreg, val);
13013 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13014 			return 1;
13015 		break;
13016 	case BPF_JSET:
13017 		if ((~subreg.mask & subreg.value) & val)
13018 			return 1;
13019 		if (!((subreg.mask | subreg.value) & val))
13020 			return 0;
13021 		break;
13022 	case BPF_JGT:
13023 		if (reg->u32_min_value > val)
13024 			return 1;
13025 		else if (reg->u32_max_value <= val)
13026 			return 0;
13027 		break;
13028 	case BPF_JSGT:
13029 		if (reg->s32_min_value > sval)
13030 			return 1;
13031 		else if (reg->s32_max_value <= sval)
13032 			return 0;
13033 		break;
13034 	case BPF_JLT:
13035 		if (reg->u32_max_value < val)
13036 			return 1;
13037 		else if (reg->u32_min_value >= val)
13038 			return 0;
13039 		break;
13040 	case BPF_JSLT:
13041 		if (reg->s32_max_value < sval)
13042 			return 1;
13043 		else if (reg->s32_min_value >= sval)
13044 			return 0;
13045 		break;
13046 	case BPF_JGE:
13047 		if (reg->u32_min_value >= val)
13048 			return 1;
13049 		else if (reg->u32_max_value < val)
13050 			return 0;
13051 		break;
13052 	case BPF_JSGE:
13053 		if (reg->s32_min_value >= sval)
13054 			return 1;
13055 		else if (reg->s32_max_value < sval)
13056 			return 0;
13057 		break;
13058 	case BPF_JLE:
13059 		if (reg->u32_max_value <= val)
13060 			return 1;
13061 		else if (reg->u32_min_value > val)
13062 			return 0;
13063 		break;
13064 	case BPF_JSLE:
13065 		if (reg->s32_max_value <= sval)
13066 			return 1;
13067 		else if (reg->s32_min_value > sval)
13068 			return 0;
13069 		break;
13070 	}
13071 
13072 	return -1;
13073 }
13074 
13075 
13076 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13077 {
13078 	s64 sval = (s64)val;
13079 
13080 	switch (opcode) {
13081 	case BPF_JEQ:
13082 		if (tnum_is_const(reg->var_off))
13083 			return !!tnum_equals_const(reg->var_off, val);
13084 		else if (val < reg->umin_value || val > reg->umax_value)
13085 			return 0;
13086 		break;
13087 	case BPF_JNE:
13088 		if (tnum_is_const(reg->var_off))
13089 			return !tnum_equals_const(reg->var_off, val);
13090 		else if (val < reg->umin_value || val > reg->umax_value)
13091 			return 1;
13092 		break;
13093 	case BPF_JSET:
13094 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13095 			return 1;
13096 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13097 			return 0;
13098 		break;
13099 	case BPF_JGT:
13100 		if (reg->umin_value > val)
13101 			return 1;
13102 		else if (reg->umax_value <= val)
13103 			return 0;
13104 		break;
13105 	case BPF_JSGT:
13106 		if (reg->smin_value > sval)
13107 			return 1;
13108 		else if (reg->smax_value <= sval)
13109 			return 0;
13110 		break;
13111 	case BPF_JLT:
13112 		if (reg->umax_value < val)
13113 			return 1;
13114 		else if (reg->umin_value >= val)
13115 			return 0;
13116 		break;
13117 	case BPF_JSLT:
13118 		if (reg->smax_value < sval)
13119 			return 1;
13120 		else if (reg->smin_value >= sval)
13121 			return 0;
13122 		break;
13123 	case BPF_JGE:
13124 		if (reg->umin_value >= val)
13125 			return 1;
13126 		else if (reg->umax_value < val)
13127 			return 0;
13128 		break;
13129 	case BPF_JSGE:
13130 		if (reg->smin_value >= sval)
13131 			return 1;
13132 		else if (reg->smax_value < sval)
13133 			return 0;
13134 		break;
13135 	case BPF_JLE:
13136 		if (reg->umax_value <= val)
13137 			return 1;
13138 		else if (reg->umin_value > val)
13139 			return 0;
13140 		break;
13141 	case BPF_JSLE:
13142 		if (reg->smax_value <= sval)
13143 			return 1;
13144 		else if (reg->smin_value > sval)
13145 			return 0;
13146 		break;
13147 	}
13148 
13149 	return -1;
13150 }
13151 
13152 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13153  * and return:
13154  *  1 - branch will be taken and "goto target" will be executed
13155  *  0 - branch will not be taken and fall-through to next insn
13156  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13157  *      range [0,10]
13158  */
13159 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13160 			   bool is_jmp32)
13161 {
13162 	if (__is_pointer_value(false, reg)) {
13163 		if (!reg_type_not_null(reg->type))
13164 			return -1;
13165 
13166 		/* If pointer is valid tests against zero will fail so we can
13167 		 * use this to direct branch taken.
13168 		 */
13169 		if (val != 0)
13170 			return -1;
13171 
13172 		switch (opcode) {
13173 		case BPF_JEQ:
13174 			return 0;
13175 		case BPF_JNE:
13176 			return 1;
13177 		default:
13178 			return -1;
13179 		}
13180 	}
13181 
13182 	if (is_jmp32)
13183 		return is_branch32_taken(reg, val, opcode);
13184 	return is_branch64_taken(reg, val, opcode);
13185 }
13186 
13187 static int flip_opcode(u32 opcode)
13188 {
13189 	/* How can we transform "a <op> b" into "b <op> a"? */
13190 	static const u8 opcode_flip[16] = {
13191 		/* these stay the same */
13192 		[BPF_JEQ  >> 4] = BPF_JEQ,
13193 		[BPF_JNE  >> 4] = BPF_JNE,
13194 		[BPF_JSET >> 4] = BPF_JSET,
13195 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13196 		[BPF_JGE  >> 4] = BPF_JLE,
13197 		[BPF_JGT  >> 4] = BPF_JLT,
13198 		[BPF_JLE  >> 4] = BPF_JGE,
13199 		[BPF_JLT  >> 4] = BPF_JGT,
13200 		[BPF_JSGE >> 4] = BPF_JSLE,
13201 		[BPF_JSGT >> 4] = BPF_JSLT,
13202 		[BPF_JSLE >> 4] = BPF_JSGE,
13203 		[BPF_JSLT >> 4] = BPF_JSGT
13204 	};
13205 	return opcode_flip[opcode >> 4];
13206 }
13207 
13208 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13209 				   struct bpf_reg_state *src_reg,
13210 				   u8 opcode)
13211 {
13212 	struct bpf_reg_state *pkt;
13213 
13214 	if (src_reg->type == PTR_TO_PACKET_END) {
13215 		pkt = dst_reg;
13216 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13217 		pkt = src_reg;
13218 		opcode = flip_opcode(opcode);
13219 	} else {
13220 		return -1;
13221 	}
13222 
13223 	if (pkt->range >= 0)
13224 		return -1;
13225 
13226 	switch (opcode) {
13227 	case BPF_JLE:
13228 		/* pkt <= pkt_end */
13229 		fallthrough;
13230 	case BPF_JGT:
13231 		/* pkt > pkt_end */
13232 		if (pkt->range == BEYOND_PKT_END)
13233 			/* pkt has at last one extra byte beyond pkt_end */
13234 			return opcode == BPF_JGT;
13235 		break;
13236 	case BPF_JLT:
13237 		/* pkt < pkt_end */
13238 		fallthrough;
13239 	case BPF_JGE:
13240 		/* pkt >= pkt_end */
13241 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13242 			return opcode == BPF_JGE;
13243 		break;
13244 	}
13245 	return -1;
13246 }
13247 
13248 /* Adjusts the register min/max values in the case that the dst_reg is the
13249  * variable register that we are working on, and src_reg is a constant or we're
13250  * simply doing a BPF_K check.
13251  * In JEQ/JNE cases we also adjust the var_off values.
13252  */
13253 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13254 			    struct bpf_reg_state *false_reg,
13255 			    u64 val, u32 val32,
13256 			    u8 opcode, bool is_jmp32)
13257 {
13258 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13259 	struct tnum false_64off = false_reg->var_off;
13260 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13261 	struct tnum true_64off = true_reg->var_off;
13262 	s64 sval = (s64)val;
13263 	s32 sval32 = (s32)val32;
13264 
13265 	/* If the dst_reg is a pointer, we can't learn anything about its
13266 	 * variable offset from the compare (unless src_reg were a pointer into
13267 	 * the same object, but we don't bother with that.
13268 	 * Since false_reg and true_reg have the same type by construction, we
13269 	 * only need to check one of them for pointerness.
13270 	 */
13271 	if (__is_pointer_value(false, false_reg))
13272 		return;
13273 
13274 	switch (opcode) {
13275 	/* JEQ/JNE comparison doesn't change the register equivalence.
13276 	 *
13277 	 * r1 = r2;
13278 	 * if (r1 == 42) goto label;
13279 	 * ...
13280 	 * label: // here both r1 and r2 are known to be 42.
13281 	 *
13282 	 * Hence when marking register as known preserve it's ID.
13283 	 */
13284 	case BPF_JEQ:
13285 		if (is_jmp32) {
13286 			__mark_reg32_known(true_reg, val32);
13287 			true_32off = tnum_subreg(true_reg->var_off);
13288 		} else {
13289 			___mark_reg_known(true_reg, val);
13290 			true_64off = true_reg->var_off;
13291 		}
13292 		break;
13293 	case BPF_JNE:
13294 		if (is_jmp32) {
13295 			__mark_reg32_known(false_reg, val32);
13296 			false_32off = tnum_subreg(false_reg->var_off);
13297 		} else {
13298 			___mark_reg_known(false_reg, val);
13299 			false_64off = false_reg->var_off;
13300 		}
13301 		break;
13302 	case BPF_JSET:
13303 		if (is_jmp32) {
13304 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13305 			if (is_power_of_2(val32))
13306 				true_32off = tnum_or(true_32off,
13307 						     tnum_const(val32));
13308 		} else {
13309 			false_64off = tnum_and(false_64off, tnum_const(~val));
13310 			if (is_power_of_2(val))
13311 				true_64off = tnum_or(true_64off,
13312 						     tnum_const(val));
13313 		}
13314 		break;
13315 	case BPF_JGE:
13316 	case BPF_JGT:
13317 	{
13318 		if (is_jmp32) {
13319 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13320 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13321 
13322 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13323 						       false_umax);
13324 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13325 						      true_umin);
13326 		} else {
13327 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13328 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13329 
13330 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13331 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13332 		}
13333 		break;
13334 	}
13335 	case BPF_JSGE:
13336 	case BPF_JSGT:
13337 	{
13338 		if (is_jmp32) {
13339 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13340 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13341 
13342 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13343 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13344 		} else {
13345 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13346 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13347 
13348 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13349 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13350 		}
13351 		break;
13352 	}
13353 	case BPF_JLE:
13354 	case BPF_JLT:
13355 	{
13356 		if (is_jmp32) {
13357 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13358 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13359 
13360 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13361 						       false_umin);
13362 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13363 						      true_umax);
13364 		} else {
13365 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13366 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13367 
13368 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13369 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13370 		}
13371 		break;
13372 	}
13373 	case BPF_JSLE:
13374 	case BPF_JSLT:
13375 	{
13376 		if (is_jmp32) {
13377 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13378 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13379 
13380 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13381 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13382 		} else {
13383 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13384 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13385 
13386 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13387 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13388 		}
13389 		break;
13390 	}
13391 	default:
13392 		return;
13393 	}
13394 
13395 	if (is_jmp32) {
13396 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13397 					     tnum_subreg(false_32off));
13398 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13399 					    tnum_subreg(true_32off));
13400 		__reg_combine_32_into_64(false_reg);
13401 		__reg_combine_32_into_64(true_reg);
13402 	} else {
13403 		false_reg->var_off = false_64off;
13404 		true_reg->var_off = true_64off;
13405 		__reg_combine_64_into_32(false_reg);
13406 		__reg_combine_64_into_32(true_reg);
13407 	}
13408 }
13409 
13410 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13411  * the variable reg.
13412  */
13413 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13414 				struct bpf_reg_state *false_reg,
13415 				u64 val, u32 val32,
13416 				u8 opcode, bool is_jmp32)
13417 {
13418 	opcode = flip_opcode(opcode);
13419 	/* This uses zero as "not present in table"; luckily the zero opcode,
13420 	 * BPF_JA, can't get here.
13421 	 */
13422 	if (opcode)
13423 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13424 }
13425 
13426 /* Regs are known to be equal, so intersect their min/max/var_off */
13427 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13428 				  struct bpf_reg_state *dst_reg)
13429 {
13430 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13431 							dst_reg->umin_value);
13432 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13433 							dst_reg->umax_value);
13434 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13435 							dst_reg->smin_value);
13436 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13437 							dst_reg->smax_value);
13438 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13439 							     dst_reg->var_off);
13440 	reg_bounds_sync(src_reg);
13441 	reg_bounds_sync(dst_reg);
13442 }
13443 
13444 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13445 				struct bpf_reg_state *true_dst,
13446 				struct bpf_reg_state *false_src,
13447 				struct bpf_reg_state *false_dst,
13448 				u8 opcode)
13449 {
13450 	switch (opcode) {
13451 	case BPF_JEQ:
13452 		__reg_combine_min_max(true_src, true_dst);
13453 		break;
13454 	case BPF_JNE:
13455 		__reg_combine_min_max(false_src, false_dst);
13456 		break;
13457 	}
13458 }
13459 
13460 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13461 				 struct bpf_reg_state *reg, u32 id,
13462 				 bool is_null)
13463 {
13464 	if (type_may_be_null(reg->type) && reg->id == id &&
13465 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13466 		/* Old offset (both fixed and variable parts) should have been
13467 		 * known-zero, because we don't allow pointer arithmetic on
13468 		 * pointers that might be NULL. If we see this happening, don't
13469 		 * convert the register.
13470 		 *
13471 		 * But in some cases, some helpers that return local kptrs
13472 		 * advance offset for the returned pointer. In those cases, it
13473 		 * is fine to expect to see reg->off.
13474 		 */
13475 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13476 			return;
13477 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13478 		    WARN_ON_ONCE(reg->off))
13479 			return;
13480 
13481 		if (is_null) {
13482 			reg->type = SCALAR_VALUE;
13483 			/* We don't need id and ref_obj_id from this point
13484 			 * onwards anymore, thus we should better reset it,
13485 			 * so that state pruning has chances to take effect.
13486 			 */
13487 			reg->id = 0;
13488 			reg->ref_obj_id = 0;
13489 
13490 			return;
13491 		}
13492 
13493 		mark_ptr_not_null_reg(reg);
13494 
13495 		if (!reg_may_point_to_spin_lock(reg)) {
13496 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13497 			 * in release_reference().
13498 			 *
13499 			 * reg->id is still used by spin_lock ptr. Other
13500 			 * than spin_lock ptr type, reg->id can be reset.
13501 			 */
13502 			reg->id = 0;
13503 		}
13504 	}
13505 }
13506 
13507 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13508  * be folded together at some point.
13509  */
13510 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13511 				  bool is_null)
13512 {
13513 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13514 	struct bpf_reg_state *regs = state->regs, *reg;
13515 	u32 ref_obj_id = regs[regno].ref_obj_id;
13516 	u32 id = regs[regno].id;
13517 
13518 	if (ref_obj_id && ref_obj_id == id && is_null)
13519 		/* regs[regno] is in the " == NULL" branch.
13520 		 * No one could have freed the reference state before
13521 		 * doing the NULL check.
13522 		 */
13523 		WARN_ON_ONCE(release_reference_state(state, id));
13524 
13525 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13526 		mark_ptr_or_null_reg(state, reg, id, is_null);
13527 	}));
13528 }
13529 
13530 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13531 				   struct bpf_reg_state *dst_reg,
13532 				   struct bpf_reg_state *src_reg,
13533 				   struct bpf_verifier_state *this_branch,
13534 				   struct bpf_verifier_state *other_branch)
13535 {
13536 	if (BPF_SRC(insn->code) != BPF_X)
13537 		return false;
13538 
13539 	/* Pointers are always 64-bit. */
13540 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13541 		return false;
13542 
13543 	switch (BPF_OP(insn->code)) {
13544 	case BPF_JGT:
13545 		if ((dst_reg->type == PTR_TO_PACKET &&
13546 		     src_reg->type == PTR_TO_PACKET_END) ||
13547 		    (dst_reg->type == PTR_TO_PACKET_META &&
13548 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13549 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13550 			find_good_pkt_pointers(this_branch, dst_reg,
13551 					       dst_reg->type, false);
13552 			mark_pkt_end(other_branch, insn->dst_reg, true);
13553 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13554 			    src_reg->type == PTR_TO_PACKET) ||
13555 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13556 			    src_reg->type == PTR_TO_PACKET_META)) {
13557 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13558 			find_good_pkt_pointers(other_branch, src_reg,
13559 					       src_reg->type, true);
13560 			mark_pkt_end(this_branch, insn->src_reg, false);
13561 		} else {
13562 			return false;
13563 		}
13564 		break;
13565 	case BPF_JLT:
13566 		if ((dst_reg->type == PTR_TO_PACKET &&
13567 		     src_reg->type == PTR_TO_PACKET_END) ||
13568 		    (dst_reg->type == PTR_TO_PACKET_META &&
13569 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13570 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13571 			find_good_pkt_pointers(other_branch, dst_reg,
13572 					       dst_reg->type, true);
13573 			mark_pkt_end(this_branch, insn->dst_reg, false);
13574 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13575 			    src_reg->type == PTR_TO_PACKET) ||
13576 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13577 			    src_reg->type == PTR_TO_PACKET_META)) {
13578 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13579 			find_good_pkt_pointers(this_branch, src_reg,
13580 					       src_reg->type, false);
13581 			mark_pkt_end(other_branch, insn->src_reg, true);
13582 		} else {
13583 			return false;
13584 		}
13585 		break;
13586 	case BPF_JGE:
13587 		if ((dst_reg->type == PTR_TO_PACKET &&
13588 		     src_reg->type == PTR_TO_PACKET_END) ||
13589 		    (dst_reg->type == PTR_TO_PACKET_META &&
13590 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13591 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13592 			find_good_pkt_pointers(this_branch, dst_reg,
13593 					       dst_reg->type, true);
13594 			mark_pkt_end(other_branch, insn->dst_reg, false);
13595 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13596 			    src_reg->type == PTR_TO_PACKET) ||
13597 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13598 			    src_reg->type == PTR_TO_PACKET_META)) {
13599 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13600 			find_good_pkt_pointers(other_branch, src_reg,
13601 					       src_reg->type, false);
13602 			mark_pkt_end(this_branch, insn->src_reg, true);
13603 		} else {
13604 			return false;
13605 		}
13606 		break;
13607 	case BPF_JLE:
13608 		if ((dst_reg->type == PTR_TO_PACKET &&
13609 		     src_reg->type == PTR_TO_PACKET_END) ||
13610 		    (dst_reg->type == PTR_TO_PACKET_META &&
13611 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13612 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13613 			find_good_pkt_pointers(other_branch, dst_reg,
13614 					       dst_reg->type, false);
13615 			mark_pkt_end(this_branch, insn->dst_reg, true);
13616 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13617 			    src_reg->type == PTR_TO_PACKET) ||
13618 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13619 			    src_reg->type == PTR_TO_PACKET_META)) {
13620 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13621 			find_good_pkt_pointers(this_branch, src_reg,
13622 					       src_reg->type, true);
13623 			mark_pkt_end(other_branch, insn->src_reg, false);
13624 		} else {
13625 			return false;
13626 		}
13627 		break;
13628 	default:
13629 		return false;
13630 	}
13631 
13632 	return true;
13633 }
13634 
13635 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13636 			       struct bpf_reg_state *known_reg)
13637 {
13638 	struct bpf_func_state *state;
13639 	struct bpf_reg_state *reg;
13640 
13641 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13642 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13643 			copy_register_state(reg, known_reg);
13644 	}));
13645 }
13646 
13647 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13648 			     struct bpf_insn *insn, int *insn_idx)
13649 {
13650 	struct bpf_verifier_state *this_branch = env->cur_state;
13651 	struct bpf_verifier_state *other_branch;
13652 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13653 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13654 	struct bpf_reg_state *eq_branch_regs;
13655 	u8 opcode = BPF_OP(insn->code);
13656 	bool is_jmp32;
13657 	int pred = -1;
13658 	int err;
13659 
13660 	/* Only conditional jumps are expected to reach here. */
13661 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
13662 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13663 		return -EINVAL;
13664 	}
13665 
13666 	if (BPF_SRC(insn->code) == BPF_X) {
13667 		if (insn->imm != 0) {
13668 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13669 			return -EINVAL;
13670 		}
13671 
13672 		/* check src1 operand */
13673 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13674 		if (err)
13675 			return err;
13676 
13677 		if (is_pointer_value(env, insn->src_reg)) {
13678 			verbose(env, "R%d pointer comparison prohibited\n",
13679 				insn->src_reg);
13680 			return -EACCES;
13681 		}
13682 		src_reg = &regs[insn->src_reg];
13683 	} else {
13684 		if (insn->src_reg != BPF_REG_0) {
13685 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13686 			return -EINVAL;
13687 		}
13688 	}
13689 
13690 	/* check src2 operand */
13691 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13692 	if (err)
13693 		return err;
13694 
13695 	dst_reg = &regs[insn->dst_reg];
13696 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13697 
13698 	if (BPF_SRC(insn->code) == BPF_K) {
13699 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13700 	} else if (src_reg->type == SCALAR_VALUE &&
13701 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13702 		pred = is_branch_taken(dst_reg,
13703 				       tnum_subreg(src_reg->var_off).value,
13704 				       opcode,
13705 				       is_jmp32);
13706 	} else if (src_reg->type == SCALAR_VALUE &&
13707 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13708 		pred = is_branch_taken(dst_reg,
13709 				       src_reg->var_off.value,
13710 				       opcode,
13711 				       is_jmp32);
13712 	} else if (dst_reg->type == SCALAR_VALUE &&
13713 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13714 		pred = is_branch_taken(src_reg,
13715 				       tnum_subreg(dst_reg->var_off).value,
13716 				       flip_opcode(opcode),
13717 				       is_jmp32);
13718 	} else if (dst_reg->type == SCALAR_VALUE &&
13719 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13720 		pred = is_branch_taken(src_reg,
13721 				       dst_reg->var_off.value,
13722 				       flip_opcode(opcode),
13723 				       is_jmp32);
13724 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
13725 		   reg_is_pkt_pointer_any(src_reg) &&
13726 		   !is_jmp32) {
13727 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13728 	}
13729 
13730 	if (pred >= 0) {
13731 		/* If we get here with a dst_reg pointer type it is because
13732 		 * above is_branch_taken() special cased the 0 comparison.
13733 		 */
13734 		if (!__is_pointer_value(false, dst_reg))
13735 			err = mark_chain_precision(env, insn->dst_reg);
13736 		if (BPF_SRC(insn->code) == BPF_X && !err &&
13737 		    !__is_pointer_value(false, src_reg))
13738 			err = mark_chain_precision(env, insn->src_reg);
13739 		if (err)
13740 			return err;
13741 	}
13742 
13743 	if (pred == 1) {
13744 		/* Only follow the goto, ignore fall-through. If needed, push
13745 		 * the fall-through branch for simulation under speculative
13746 		 * execution.
13747 		 */
13748 		if (!env->bypass_spec_v1 &&
13749 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
13750 					       *insn_idx))
13751 			return -EFAULT;
13752 		*insn_idx += insn->off;
13753 		return 0;
13754 	} else if (pred == 0) {
13755 		/* Only follow the fall-through branch, since that's where the
13756 		 * program will go. If needed, push the goto branch for
13757 		 * simulation under speculative execution.
13758 		 */
13759 		if (!env->bypass_spec_v1 &&
13760 		    !sanitize_speculative_path(env, insn,
13761 					       *insn_idx + insn->off + 1,
13762 					       *insn_idx))
13763 			return -EFAULT;
13764 		return 0;
13765 	}
13766 
13767 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13768 				  false);
13769 	if (!other_branch)
13770 		return -EFAULT;
13771 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13772 
13773 	/* detect if we are comparing against a constant value so we can adjust
13774 	 * our min/max values for our dst register.
13775 	 * this is only legit if both are scalars (or pointers to the same
13776 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13777 	 * because otherwise the different base pointers mean the offsets aren't
13778 	 * comparable.
13779 	 */
13780 	if (BPF_SRC(insn->code) == BPF_X) {
13781 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13782 
13783 		if (dst_reg->type == SCALAR_VALUE &&
13784 		    src_reg->type == SCALAR_VALUE) {
13785 			if (tnum_is_const(src_reg->var_off) ||
13786 			    (is_jmp32 &&
13787 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
13788 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
13789 						dst_reg,
13790 						src_reg->var_off.value,
13791 						tnum_subreg(src_reg->var_off).value,
13792 						opcode, is_jmp32);
13793 			else if (tnum_is_const(dst_reg->var_off) ||
13794 				 (is_jmp32 &&
13795 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
13796 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13797 						    src_reg,
13798 						    dst_reg->var_off.value,
13799 						    tnum_subreg(dst_reg->var_off).value,
13800 						    opcode, is_jmp32);
13801 			else if (!is_jmp32 &&
13802 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
13803 				/* Comparing for equality, we can combine knowledge */
13804 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
13805 						    &other_branch_regs[insn->dst_reg],
13806 						    src_reg, dst_reg, opcode);
13807 			if (src_reg->id &&
13808 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13809 				find_equal_scalars(this_branch, src_reg);
13810 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13811 			}
13812 
13813 		}
13814 	} else if (dst_reg->type == SCALAR_VALUE) {
13815 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
13816 					dst_reg, insn->imm, (u32)insn->imm,
13817 					opcode, is_jmp32);
13818 	}
13819 
13820 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13821 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13822 		find_equal_scalars(this_branch, dst_reg);
13823 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13824 	}
13825 
13826 	/* if one pointer register is compared to another pointer
13827 	 * register check if PTR_MAYBE_NULL could be lifted.
13828 	 * E.g. register A - maybe null
13829 	 *      register B - not null
13830 	 * for JNE A, B, ... - A is not null in the false branch;
13831 	 * for JEQ A, B, ... - A is not null in the true branch.
13832 	 *
13833 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
13834 	 * not need to be null checked by the BPF program, i.e.,
13835 	 * could be null even without PTR_MAYBE_NULL marking, so
13836 	 * only propagate nullness when neither reg is that type.
13837 	 */
13838 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13839 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13840 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13841 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
13842 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13843 		eq_branch_regs = NULL;
13844 		switch (opcode) {
13845 		case BPF_JEQ:
13846 			eq_branch_regs = other_branch_regs;
13847 			break;
13848 		case BPF_JNE:
13849 			eq_branch_regs = regs;
13850 			break;
13851 		default:
13852 			/* do nothing */
13853 			break;
13854 		}
13855 		if (eq_branch_regs) {
13856 			if (type_may_be_null(src_reg->type))
13857 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13858 			else
13859 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13860 		}
13861 	}
13862 
13863 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13864 	 * NOTE: these optimizations below are related with pointer comparison
13865 	 *       which will never be JMP32.
13866 	 */
13867 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13868 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13869 	    type_may_be_null(dst_reg->type)) {
13870 		/* Mark all identical registers in each branch as either
13871 		 * safe or unknown depending R == 0 or R != 0 conditional.
13872 		 */
13873 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13874 				      opcode == BPF_JNE);
13875 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13876 				      opcode == BPF_JEQ);
13877 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
13878 					   this_branch, other_branch) &&
13879 		   is_pointer_value(env, insn->dst_reg)) {
13880 		verbose(env, "R%d pointer comparison prohibited\n",
13881 			insn->dst_reg);
13882 		return -EACCES;
13883 	}
13884 	if (env->log.level & BPF_LOG_LEVEL)
13885 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
13886 	return 0;
13887 }
13888 
13889 /* verify BPF_LD_IMM64 instruction */
13890 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
13891 {
13892 	struct bpf_insn_aux_data *aux = cur_aux(env);
13893 	struct bpf_reg_state *regs = cur_regs(env);
13894 	struct bpf_reg_state *dst_reg;
13895 	struct bpf_map *map;
13896 	int err;
13897 
13898 	if (BPF_SIZE(insn->code) != BPF_DW) {
13899 		verbose(env, "invalid BPF_LD_IMM insn\n");
13900 		return -EINVAL;
13901 	}
13902 	if (insn->off != 0) {
13903 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
13904 		return -EINVAL;
13905 	}
13906 
13907 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
13908 	if (err)
13909 		return err;
13910 
13911 	dst_reg = &regs[insn->dst_reg];
13912 	if (insn->src_reg == 0) {
13913 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13914 
13915 		dst_reg->type = SCALAR_VALUE;
13916 		__mark_reg_known(&regs[insn->dst_reg], imm);
13917 		return 0;
13918 	}
13919 
13920 	/* All special src_reg cases are listed below. From this point onwards
13921 	 * we either succeed and assign a corresponding dst_reg->type after
13922 	 * zeroing the offset, or fail and reject the program.
13923 	 */
13924 	mark_reg_known_zero(env, regs, insn->dst_reg);
13925 
13926 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13927 		dst_reg->type = aux->btf_var.reg_type;
13928 		switch (base_type(dst_reg->type)) {
13929 		case PTR_TO_MEM:
13930 			dst_reg->mem_size = aux->btf_var.mem_size;
13931 			break;
13932 		case PTR_TO_BTF_ID:
13933 			dst_reg->btf = aux->btf_var.btf;
13934 			dst_reg->btf_id = aux->btf_var.btf_id;
13935 			break;
13936 		default:
13937 			verbose(env, "bpf verifier is misconfigured\n");
13938 			return -EFAULT;
13939 		}
13940 		return 0;
13941 	}
13942 
13943 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
13944 		struct bpf_prog_aux *aux = env->prog->aux;
13945 		u32 subprogno = find_subprog(env,
13946 					     env->insn_idx + insn->imm + 1);
13947 
13948 		if (!aux->func_info) {
13949 			verbose(env, "missing btf func_info\n");
13950 			return -EINVAL;
13951 		}
13952 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13953 			verbose(env, "callback function not static\n");
13954 			return -EINVAL;
13955 		}
13956 
13957 		dst_reg->type = PTR_TO_FUNC;
13958 		dst_reg->subprogno = subprogno;
13959 		return 0;
13960 	}
13961 
13962 	map = env->used_maps[aux->map_index];
13963 	dst_reg->map_ptr = map;
13964 
13965 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13966 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13967 		dst_reg->type = PTR_TO_MAP_VALUE;
13968 		dst_reg->off = aux->map_off;
13969 		WARN_ON_ONCE(map->max_entries != 1);
13970 		/* We want reg->id to be same (0) as map_value is not distinct */
13971 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13972 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13973 		dst_reg->type = CONST_PTR_TO_MAP;
13974 	} else {
13975 		verbose(env, "bpf verifier is misconfigured\n");
13976 		return -EINVAL;
13977 	}
13978 
13979 	return 0;
13980 }
13981 
13982 static bool may_access_skb(enum bpf_prog_type type)
13983 {
13984 	switch (type) {
13985 	case BPF_PROG_TYPE_SOCKET_FILTER:
13986 	case BPF_PROG_TYPE_SCHED_CLS:
13987 	case BPF_PROG_TYPE_SCHED_ACT:
13988 		return true;
13989 	default:
13990 		return false;
13991 	}
13992 }
13993 
13994 /* verify safety of LD_ABS|LD_IND instructions:
13995  * - they can only appear in the programs where ctx == skb
13996  * - since they are wrappers of function calls, they scratch R1-R5 registers,
13997  *   preserve R6-R9, and store return value into R0
13998  *
13999  * Implicit input:
14000  *   ctx == skb == R6 == CTX
14001  *
14002  * Explicit input:
14003  *   SRC == any register
14004  *   IMM == 32-bit immediate
14005  *
14006  * Output:
14007  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14008  */
14009 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14010 {
14011 	struct bpf_reg_state *regs = cur_regs(env);
14012 	static const int ctx_reg = BPF_REG_6;
14013 	u8 mode = BPF_MODE(insn->code);
14014 	int i, err;
14015 
14016 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14017 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14018 		return -EINVAL;
14019 	}
14020 
14021 	if (!env->ops->gen_ld_abs) {
14022 		verbose(env, "bpf verifier is misconfigured\n");
14023 		return -EINVAL;
14024 	}
14025 
14026 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14027 	    BPF_SIZE(insn->code) == BPF_DW ||
14028 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14029 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14030 		return -EINVAL;
14031 	}
14032 
14033 	/* check whether implicit source operand (register R6) is readable */
14034 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14035 	if (err)
14036 		return err;
14037 
14038 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14039 	 * gen_ld_abs() may terminate the program at runtime, leading to
14040 	 * reference leak.
14041 	 */
14042 	err = check_reference_leak(env);
14043 	if (err) {
14044 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14045 		return err;
14046 	}
14047 
14048 	if (env->cur_state->active_lock.ptr) {
14049 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14050 		return -EINVAL;
14051 	}
14052 
14053 	if (env->cur_state->active_rcu_lock) {
14054 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14055 		return -EINVAL;
14056 	}
14057 
14058 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14059 		verbose(env,
14060 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14061 		return -EINVAL;
14062 	}
14063 
14064 	if (mode == BPF_IND) {
14065 		/* check explicit source operand */
14066 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14067 		if (err)
14068 			return err;
14069 	}
14070 
14071 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14072 	if (err < 0)
14073 		return err;
14074 
14075 	/* reset caller saved regs to unreadable */
14076 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14077 		mark_reg_not_init(env, regs, caller_saved[i]);
14078 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14079 	}
14080 
14081 	/* mark destination R0 register as readable, since it contains
14082 	 * the value fetched from the packet.
14083 	 * Already marked as written above.
14084 	 */
14085 	mark_reg_unknown(env, regs, BPF_REG_0);
14086 	/* ld_abs load up to 32-bit skb data. */
14087 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14088 	return 0;
14089 }
14090 
14091 static int check_return_code(struct bpf_verifier_env *env)
14092 {
14093 	struct tnum enforce_attach_type_range = tnum_unknown;
14094 	const struct bpf_prog *prog = env->prog;
14095 	struct bpf_reg_state *reg;
14096 	struct tnum range = tnum_range(0, 1);
14097 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14098 	int err;
14099 	struct bpf_func_state *frame = env->cur_state->frame[0];
14100 	const bool is_subprog = frame->subprogno;
14101 
14102 	/* LSM and struct_ops func-ptr's return type could be "void" */
14103 	if (!is_subprog) {
14104 		switch (prog_type) {
14105 		case BPF_PROG_TYPE_LSM:
14106 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14107 				/* See below, can be 0 or 0-1 depending on hook. */
14108 				break;
14109 			fallthrough;
14110 		case BPF_PROG_TYPE_STRUCT_OPS:
14111 			if (!prog->aux->attach_func_proto->type)
14112 				return 0;
14113 			break;
14114 		default:
14115 			break;
14116 		}
14117 	}
14118 
14119 	/* eBPF calling convention is such that R0 is used
14120 	 * to return the value from eBPF program.
14121 	 * Make sure that it's readable at this time
14122 	 * of bpf_exit, which means that program wrote
14123 	 * something into it earlier
14124 	 */
14125 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14126 	if (err)
14127 		return err;
14128 
14129 	if (is_pointer_value(env, BPF_REG_0)) {
14130 		verbose(env, "R0 leaks addr as return value\n");
14131 		return -EACCES;
14132 	}
14133 
14134 	reg = cur_regs(env) + BPF_REG_0;
14135 
14136 	if (frame->in_async_callback_fn) {
14137 		/* enforce return zero from async callbacks like timer */
14138 		if (reg->type != SCALAR_VALUE) {
14139 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14140 				reg_type_str(env, reg->type));
14141 			return -EINVAL;
14142 		}
14143 
14144 		if (!tnum_in(tnum_const(0), reg->var_off)) {
14145 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14146 			return -EINVAL;
14147 		}
14148 		return 0;
14149 	}
14150 
14151 	if (is_subprog) {
14152 		if (reg->type != SCALAR_VALUE) {
14153 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14154 				reg_type_str(env, reg->type));
14155 			return -EINVAL;
14156 		}
14157 		return 0;
14158 	}
14159 
14160 	switch (prog_type) {
14161 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14162 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14163 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14164 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14165 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14166 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14167 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14168 			range = tnum_range(1, 1);
14169 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14170 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14171 			range = tnum_range(0, 3);
14172 		break;
14173 	case BPF_PROG_TYPE_CGROUP_SKB:
14174 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14175 			range = tnum_range(0, 3);
14176 			enforce_attach_type_range = tnum_range(2, 3);
14177 		}
14178 		break;
14179 	case BPF_PROG_TYPE_CGROUP_SOCK:
14180 	case BPF_PROG_TYPE_SOCK_OPS:
14181 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14182 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14183 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14184 		break;
14185 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14186 		if (!env->prog->aux->attach_btf_id)
14187 			return 0;
14188 		range = tnum_const(0);
14189 		break;
14190 	case BPF_PROG_TYPE_TRACING:
14191 		switch (env->prog->expected_attach_type) {
14192 		case BPF_TRACE_FENTRY:
14193 		case BPF_TRACE_FEXIT:
14194 			range = tnum_const(0);
14195 			break;
14196 		case BPF_TRACE_RAW_TP:
14197 		case BPF_MODIFY_RETURN:
14198 			return 0;
14199 		case BPF_TRACE_ITER:
14200 			break;
14201 		default:
14202 			return -ENOTSUPP;
14203 		}
14204 		break;
14205 	case BPF_PROG_TYPE_SK_LOOKUP:
14206 		range = tnum_range(SK_DROP, SK_PASS);
14207 		break;
14208 
14209 	case BPF_PROG_TYPE_LSM:
14210 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14211 			/* Regular BPF_PROG_TYPE_LSM programs can return
14212 			 * any value.
14213 			 */
14214 			return 0;
14215 		}
14216 		if (!env->prog->aux->attach_func_proto->type) {
14217 			/* Make sure programs that attach to void
14218 			 * hooks don't try to modify return value.
14219 			 */
14220 			range = tnum_range(1, 1);
14221 		}
14222 		break;
14223 
14224 	case BPF_PROG_TYPE_NETFILTER:
14225 		range = tnum_range(NF_DROP, NF_ACCEPT);
14226 		break;
14227 	case BPF_PROG_TYPE_EXT:
14228 		/* freplace program can return anything as its return value
14229 		 * depends on the to-be-replaced kernel func or bpf program.
14230 		 */
14231 	default:
14232 		return 0;
14233 	}
14234 
14235 	if (reg->type != SCALAR_VALUE) {
14236 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14237 			reg_type_str(env, reg->type));
14238 		return -EINVAL;
14239 	}
14240 
14241 	if (!tnum_in(range, reg->var_off)) {
14242 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14243 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14244 		    prog_type == BPF_PROG_TYPE_LSM &&
14245 		    !prog->aux->attach_func_proto->type)
14246 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14247 		return -EINVAL;
14248 	}
14249 
14250 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14251 	    tnum_in(enforce_attach_type_range, reg->var_off))
14252 		env->prog->enforce_expected_attach_type = 1;
14253 	return 0;
14254 }
14255 
14256 /* non-recursive DFS pseudo code
14257  * 1  procedure DFS-iterative(G,v):
14258  * 2      label v as discovered
14259  * 3      let S be a stack
14260  * 4      S.push(v)
14261  * 5      while S is not empty
14262  * 6            t <- S.peek()
14263  * 7            if t is what we're looking for:
14264  * 8                return t
14265  * 9            for all edges e in G.adjacentEdges(t) do
14266  * 10               if edge e is already labelled
14267  * 11                   continue with the next edge
14268  * 12               w <- G.adjacentVertex(t,e)
14269  * 13               if vertex w is not discovered and not explored
14270  * 14                   label e as tree-edge
14271  * 15                   label w as discovered
14272  * 16                   S.push(w)
14273  * 17                   continue at 5
14274  * 18               else if vertex w is discovered
14275  * 19                   label e as back-edge
14276  * 20               else
14277  * 21                   // vertex w is explored
14278  * 22                   label e as forward- or cross-edge
14279  * 23           label t as explored
14280  * 24           S.pop()
14281  *
14282  * convention:
14283  * 0x10 - discovered
14284  * 0x11 - discovered and fall-through edge labelled
14285  * 0x12 - discovered and fall-through and branch edges labelled
14286  * 0x20 - explored
14287  */
14288 
14289 enum {
14290 	DISCOVERED = 0x10,
14291 	EXPLORED = 0x20,
14292 	FALLTHROUGH = 1,
14293 	BRANCH = 2,
14294 };
14295 
14296 static u32 state_htab_size(struct bpf_verifier_env *env)
14297 {
14298 	return env->prog->len;
14299 }
14300 
14301 static struct bpf_verifier_state_list **explored_state(
14302 					struct bpf_verifier_env *env,
14303 					int idx)
14304 {
14305 	struct bpf_verifier_state *cur = env->cur_state;
14306 	struct bpf_func_state *state = cur->frame[cur->curframe];
14307 
14308 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14309 }
14310 
14311 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14312 {
14313 	env->insn_aux_data[idx].prune_point = true;
14314 }
14315 
14316 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14317 {
14318 	return env->insn_aux_data[insn_idx].prune_point;
14319 }
14320 
14321 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14322 {
14323 	env->insn_aux_data[idx].force_checkpoint = true;
14324 }
14325 
14326 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14327 {
14328 	return env->insn_aux_data[insn_idx].force_checkpoint;
14329 }
14330 
14331 
14332 enum {
14333 	DONE_EXPLORING = 0,
14334 	KEEP_EXPLORING = 1,
14335 };
14336 
14337 /* t, w, e - match pseudo-code above:
14338  * t - index of current instruction
14339  * w - next instruction
14340  * e - edge
14341  */
14342 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14343 		     bool loop_ok)
14344 {
14345 	int *insn_stack = env->cfg.insn_stack;
14346 	int *insn_state = env->cfg.insn_state;
14347 
14348 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14349 		return DONE_EXPLORING;
14350 
14351 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14352 		return DONE_EXPLORING;
14353 
14354 	if (w < 0 || w >= env->prog->len) {
14355 		verbose_linfo(env, t, "%d: ", t);
14356 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14357 		return -EINVAL;
14358 	}
14359 
14360 	if (e == BRANCH) {
14361 		/* mark branch target for state pruning */
14362 		mark_prune_point(env, w);
14363 		mark_jmp_point(env, w);
14364 	}
14365 
14366 	if (insn_state[w] == 0) {
14367 		/* tree-edge */
14368 		insn_state[t] = DISCOVERED | e;
14369 		insn_state[w] = DISCOVERED;
14370 		if (env->cfg.cur_stack >= env->prog->len)
14371 			return -E2BIG;
14372 		insn_stack[env->cfg.cur_stack++] = w;
14373 		return KEEP_EXPLORING;
14374 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14375 		if (loop_ok && env->bpf_capable)
14376 			return DONE_EXPLORING;
14377 		verbose_linfo(env, t, "%d: ", t);
14378 		verbose_linfo(env, w, "%d: ", w);
14379 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14380 		return -EINVAL;
14381 	} else if (insn_state[w] == EXPLORED) {
14382 		/* forward- or cross-edge */
14383 		insn_state[t] = DISCOVERED | e;
14384 	} else {
14385 		verbose(env, "insn state internal bug\n");
14386 		return -EFAULT;
14387 	}
14388 	return DONE_EXPLORING;
14389 }
14390 
14391 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14392 				struct bpf_verifier_env *env,
14393 				bool visit_callee)
14394 {
14395 	int ret;
14396 
14397 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14398 	if (ret)
14399 		return ret;
14400 
14401 	mark_prune_point(env, t + 1);
14402 	/* when we exit from subprog, we need to record non-linear history */
14403 	mark_jmp_point(env, t + 1);
14404 
14405 	if (visit_callee) {
14406 		mark_prune_point(env, t);
14407 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14408 				/* It's ok to allow recursion from CFG point of
14409 				 * view. __check_func_call() will do the actual
14410 				 * check.
14411 				 */
14412 				bpf_pseudo_func(insns + t));
14413 	}
14414 	return ret;
14415 }
14416 
14417 /* Visits the instruction at index t and returns one of the following:
14418  *  < 0 - an error occurred
14419  *  DONE_EXPLORING - the instruction was fully explored
14420  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14421  */
14422 static int visit_insn(int t, struct bpf_verifier_env *env)
14423 {
14424 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14425 	int ret;
14426 
14427 	if (bpf_pseudo_func(insn))
14428 		return visit_func_call_insn(t, insns, env, true);
14429 
14430 	/* All non-branch instructions have a single fall-through edge. */
14431 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14432 	    BPF_CLASS(insn->code) != BPF_JMP32)
14433 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14434 
14435 	switch (BPF_OP(insn->code)) {
14436 	case BPF_EXIT:
14437 		return DONE_EXPLORING;
14438 
14439 	case BPF_CALL:
14440 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14441 			/* Mark this call insn as a prune point to trigger
14442 			 * is_state_visited() check before call itself is
14443 			 * processed by __check_func_call(). Otherwise new
14444 			 * async state will be pushed for further exploration.
14445 			 */
14446 			mark_prune_point(env, t);
14447 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14448 			struct bpf_kfunc_call_arg_meta meta;
14449 
14450 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14451 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14452 				mark_prune_point(env, t);
14453 				/* Checking and saving state checkpoints at iter_next() call
14454 				 * is crucial for fast convergence of open-coded iterator loop
14455 				 * logic, so we need to force it. If we don't do that,
14456 				 * is_state_visited() might skip saving a checkpoint, causing
14457 				 * unnecessarily long sequence of not checkpointed
14458 				 * instructions and jumps, leading to exhaustion of jump
14459 				 * history buffer, and potentially other undesired outcomes.
14460 				 * It is expected that with correct open-coded iterators
14461 				 * convergence will happen quickly, so we don't run a risk of
14462 				 * exhausting memory.
14463 				 */
14464 				mark_force_checkpoint(env, t);
14465 			}
14466 		}
14467 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14468 
14469 	case BPF_JA:
14470 		if (BPF_SRC(insn->code) != BPF_K)
14471 			return -EINVAL;
14472 
14473 		/* unconditional jump with single edge */
14474 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14475 				true);
14476 		if (ret)
14477 			return ret;
14478 
14479 		mark_prune_point(env, t + insn->off + 1);
14480 		mark_jmp_point(env, t + insn->off + 1);
14481 
14482 		return ret;
14483 
14484 	default:
14485 		/* conditional jump with two edges */
14486 		mark_prune_point(env, t);
14487 
14488 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14489 		if (ret)
14490 			return ret;
14491 
14492 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14493 	}
14494 }
14495 
14496 /* non-recursive depth-first-search to detect loops in BPF program
14497  * loop == back-edge in directed graph
14498  */
14499 static int check_cfg(struct bpf_verifier_env *env)
14500 {
14501 	int insn_cnt = env->prog->len;
14502 	int *insn_stack, *insn_state;
14503 	int ret = 0;
14504 	int i;
14505 
14506 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14507 	if (!insn_state)
14508 		return -ENOMEM;
14509 
14510 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14511 	if (!insn_stack) {
14512 		kvfree(insn_state);
14513 		return -ENOMEM;
14514 	}
14515 
14516 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14517 	insn_stack[0] = 0; /* 0 is the first instruction */
14518 	env->cfg.cur_stack = 1;
14519 
14520 	while (env->cfg.cur_stack > 0) {
14521 		int t = insn_stack[env->cfg.cur_stack - 1];
14522 
14523 		ret = visit_insn(t, env);
14524 		switch (ret) {
14525 		case DONE_EXPLORING:
14526 			insn_state[t] = EXPLORED;
14527 			env->cfg.cur_stack--;
14528 			break;
14529 		case KEEP_EXPLORING:
14530 			break;
14531 		default:
14532 			if (ret > 0) {
14533 				verbose(env, "visit_insn internal bug\n");
14534 				ret = -EFAULT;
14535 			}
14536 			goto err_free;
14537 		}
14538 	}
14539 
14540 	if (env->cfg.cur_stack < 0) {
14541 		verbose(env, "pop stack internal bug\n");
14542 		ret = -EFAULT;
14543 		goto err_free;
14544 	}
14545 
14546 	for (i = 0; i < insn_cnt; i++) {
14547 		if (insn_state[i] != EXPLORED) {
14548 			verbose(env, "unreachable insn %d\n", i);
14549 			ret = -EINVAL;
14550 			goto err_free;
14551 		}
14552 	}
14553 	ret = 0; /* cfg looks good */
14554 
14555 err_free:
14556 	kvfree(insn_state);
14557 	kvfree(insn_stack);
14558 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14559 	return ret;
14560 }
14561 
14562 static int check_abnormal_return(struct bpf_verifier_env *env)
14563 {
14564 	int i;
14565 
14566 	for (i = 1; i < env->subprog_cnt; i++) {
14567 		if (env->subprog_info[i].has_ld_abs) {
14568 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14569 			return -EINVAL;
14570 		}
14571 		if (env->subprog_info[i].has_tail_call) {
14572 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14573 			return -EINVAL;
14574 		}
14575 	}
14576 	return 0;
14577 }
14578 
14579 /* The minimum supported BTF func info size */
14580 #define MIN_BPF_FUNCINFO_SIZE	8
14581 #define MAX_FUNCINFO_REC_SIZE	252
14582 
14583 static int check_btf_func(struct bpf_verifier_env *env,
14584 			  const union bpf_attr *attr,
14585 			  bpfptr_t uattr)
14586 {
14587 	const struct btf_type *type, *func_proto, *ret_type;
14588 	u32 i, nfuncs, urec_size, min_size;
14589 	u32 krec_size = sizeof(struct bpf_func_info);
14590 	struct bpf_func_info *krecord;
14591 	struct bpf_func_info_aux *info_aux = NULL;
14592 	struct bpf_prog *prog;
14593 	const struct btf *btf;
14594 	bpfptr_t urecord;
14595 	u32 prev_offset = 0;
14596 	bool scalar_return;
14597 	int ret = -ENOMEM;
14598 
14599 	nfuncs = attr->func_info_cnt;
14600 	if (!nfuncs) {
14601 		if (check_abnormal_return(env))
14602 			return -EINVAL;
14603 		return 0;
14604 	}
14605 
14606 	if (nfuncs != env->subprog_cnt) {
14607 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14608 		return -EINVAL;
14609 	}
14610 
14611 	urec_size = attr->func_info_rec_size;
14612 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14613 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
14614 	    urec_size % sizeof(u32)) {
14615 		verbose(env, "invalid func info rec size %u\n", urec_size);
14616 		return -EINVAL;
14617 	}
14618 
14619 	prog = env->prog;
14620 	btf = prog->aux->btf;
14621 
14622 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14623 	min_size = min_t(u32, krec_size, urec_size);
14624 
14625 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14626 	if (!krecord)
14627 		return -ENOMEM;
14628 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14629 	if (!info_aux)
14630 		goto err_free;
14631 
14632 	for (i = 0; i < nfuncs; i++) {
14633 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14634 		if (ret) {
14635 			if (ret == -E2BIG) {
14636 				verbose(env, "nonzero tailing record in func info");
14637 				/* set the size kernel expects so loader can zero
14638 				 * out the rest of the record.
14639 				 */
14640 				if (copy_to_bpfptr_offset(uattr,
14641 							  offsetof(union bpf_attr, func_info_rec_size),
14642 							  &min_size, sizeof(min_size)))
14643 					ret = -EFAULT;
14644 			}
14645 			goto err_free;
14646 		}
14647 
14648 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14649 			ret = -EFAULT;
14650 			goto err_free;
14651 		}
14652 
14653 		/* check insn_off */
14654 		ret = -EINVAL;
14655 		if (i == 0) {
14656 			if (krecord[i].insn_off) {
14657 				verbose(env,
14658 					"nonzero insn_off %u for the first func info record",
14659 					krecord[i].insn_off);
14660 				goto err_free;
14661 			}
14662 		} else if (krecord[i].insn_off <= prev_offset) {
14663 			verbose(env,
14664 				"same or smaller insn offset (%u) than previous func info record (%u)",
14665 				krecord[i].insn_off, prev_offset);
14666 			goto err_free;
14667 		}
14668 
14669 		if (env->subprog_info[i].start != krecord[i].insn_off) {
14670 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14671 			goto err_free;
14672 		}
14673 
14674 		/* check type_id */
14675 		type = btf_type_by_id(btf, krecord[i].type_id);
14676 		if (!type || !btf_type_is_func(type)) {
14677 			verbose(env, "invalid type id %d in func info",
14678 				krecord[i].type_id);
14679 			goto err_free;
14680 		}
14681 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14682 
14683 		func_proto = btf_type_by_id(btf, type->type);
14684 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14685 			/* btf_func_check() already verified it during BTF load */
14686 			goto err_free;
14687 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14688 		scalar_return =
14689 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14690 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14691 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14692 			goto err_free;
14693 		}
14694 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14695 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14696 			goto err_free;
14697 		}
14698 
14699 		prev_offset = krecord[i].insn_off;
14700 		bpfptr_add(&urecord, urec_size);
14701 	}
14702 
14703 	prog->aux->func_info = krecord;
14704 	prog->aux->func_info_cnt = nfuncs;
14705 	prog->aux->func_info_aux = info_aux;
14706 	return 0;
14707 
14708 err_free:
14709 	kvfree(krecord);
14710 	kfree(info_aux);
14711 	return ret;
14712 }
14713 
14714 static void adjust_btf_func(struct bpf_verifier_env *env)
14715 {
14716 	struct bpf_prog_aux *aux = env->prog->aux;
14717 	int i;
14718 
14719 	if (!aux->func_info)
14720 		return;
14721 
14722 	for (i = 0; i < env->subprog_cnt; i++)
14723 		aux->func_info[i].insn_off = env->subprog_info[i].start;
14724 }
14725 
14726 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
14727 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
14728 
14729 static int check_btf_line(struct bpf_verifier_env *env,
14730 			  const union bpf_attr *attr,
14731 			  bpfptr_t uattr)
14732 {
14733 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14734 	struct bpf_subprog_info *sub;
14735 	struct bpf_line_info *linfo;
14736 	struct bpf_prog *prog;
14737 	const struct btf *btf;
14738 	bpfptr_t ulinfo;
14739 	int err;
14740 
14741 	nr_linfo = attr->line_info_cnt;
14742 	if (!nr_linfo)
14743 		return 0;
14744 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14745 		return -EINVAL;
14746 
14747 	rec_size = attr->line_info_rec_size;
14748 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14749 	    rec_size > MAX_LINEINFO_REC_SIZE ||
14750 	    rec_size & (sizeof(u32) - 1))
14751 		return -EINVAL;
14752 
14753 	/* Need to zero it in case the userspace may
14754 	 * pass in a smaller bpf_line_info object.
14755 	 */
14756 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14757 			 GFP_KERNEL | __GFP_NOWARN);
14758 	if (!linfo)
14759 		return -ENOMEM;
14760 
14761 	prog = env->prog;
14762 	btf = prog->aux->btf;
14763 
14764 	s = 0;
14765 	sub = env->subprog_info;
14766 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14767 	expected_size = sizeof(struct bpf_line_info);
14768 	ncopy = min_t(u32, expected_size, rec_size);
14769 	for (i = 0; i < nr_linfo; i++) {
14770 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14771 		if (err) {
14772 			if (err == -E2BIG) {
14773 				verbose(env, "nonzero tailing record in line_info");
14774 				if (copy_to_bpfptr_offset(uattr,
14775 							  offsetof(union bpf_attr, line_info_rec_size),
14776 							  &expected_size, sizeof(expected_size)))
14777 					err = -EFAULT;
14778 			}
14779 			goto err_free;
14780 		}
14781 
14782 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14783 			err = -EFAULT;
14784 			goto err_free;
14785 		}
14786 
14787 		/*
14788 		 * Check insn_off to ensure
14789 		 * 1) strictly increasing AND
14790 		 * 2) bounded by prog->len
14791 		 *
14792 		 * The linfo[0].insn_off == 0 check logically falls into
14793 		 * the later "missing bpf_line_info for func..." case
14794 		 * because the first linfo[0].insn_off must be the
14795 		 * first sub also and the first sub must have
14796 		 * subprog_info[0].start == 0.
14797 		 */
14798 		if ((i && linfo[i].insn_off <= prev_offset) ||
14799 		    linfo[i].insn_off >= prog->len) {
14800 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14801 				i, linfo[i].insn_off, prev_offset,
14802 				prog->len);
14803 			err = -EINVAL;
14804 			goto err_free;
14805 		}
14806 
14807 		if (!prog->insnsi[linfo[i].insn_off].code) {
14808 			verbose(env,
14809 				"Invalid insn code at line_info[%u].insn_off\n",
14810 				i);
14811 			err = -EINVAL;
14812 			goto err_free;
14813 		}
14814 
14815 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14816 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14817 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14818 			err = -EINVAL;
14819 			goto err_free;
14820 		}
14821 
14822 		if (s != env->subprog_cnt) {
14823 			if (linfo[i].insn_off == sub[s].start) {
14824 				sub[s].linfo_idx = i;
14825 				s++;
14826 			} else if (sub[s].start < linfo[i].insn_off) {
14827 				verbose(env, "missing bpf_line_info for func#%u\n", s);
14828 				err = -EINVAL;
14829 				goto err_free;
14830 			}
14831 		}
14832 
14833 		prev_offset = linfo[i].insn_off;
14834 		bpfptr_add(&ulinfo, rec_size);
14835 	}
14836 
14837 	if (s != env->subprog_cnt) {
14838 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14839 			env->subprog_cnt - s, s);
14840 		err = -EINVAL;
14841 		goto err_free;
14842 	}
14843 
14844 	prog->aux->linfo = linfo;
14845 	prog->aux->nr_linfo = nr_linfo;
14846 
14847 	return 0;
14848 
14849 err_free:
14850 	kvfree(linfo);
14851 	return err;
14852 }
14853 
14854 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
14855 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
14856 
14857 static int check_core_relo(struct bpf_verifier_env *env,
14858 			   const union bpf_attr *attr,
14859 			   bpfptr_t uattr)
14860 {
14861 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14862 	struct bpf_core_relo core_relo = {};
14863 	struct bpf_prog *prog = env->prog;
14864 	const struct btf *btf = prog->aux->btf;
14865 	struct bpf_core_ctx ctx = {
14866 		.log = &env->log,
14867 		.btf = btf,
14868 	};
14869 	bpfptr_t u_core_relo;
14870 	int err;
14871 
14872 	nr_core_relo = attr->core_relo_cnt;
14873 	if (!nr_core_relo)
14874 		return 0;
14875 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14876 		return -EINVAL;
14877 
14878 	rec_size = attr->core_relo_rec_size;
14879 	if (rec_size < MIN_CORE_RELO_SIZE ||
14880 	    rec_size > MAX_CORE_RELO_SIZE ||
14881 	    rec_size % sizeof(u32))
14882 		return -EINVAL;
14883 
14884 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14885 	expected_size = sizeof(struct bpf_core_relo);
14886 	ncopy = min_t(u32, expected_size, rec_size);
14887 
14888 	/* Unlike func_info and line_info, copy and apply each CO-RE
14889 	 * relocation record one at a time.
14890 	 */
14891 	for (i = 0; i < nr_core_relo; i++) {
14892 		/* future proofing when sizeof(bpf_core_relo) changes */
14893 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14894 		if (err) {
14895 			if (err == -E2BIG) {
14896 				verbose(env, "nonzero tailing record in core_relo");
14897 				if (copy_to_bpfptr_offset(uattr,
14898 							  offsetof(union bpf_attr, core_relo_rec_size),
14899 							  &expected_size, sizeof(expected_size)))
14900 					err = -EFAULT;
14901 			}
14902 			break;
14903 		}
14904 
14905 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14906 			err = -EFAULT;
14907 			break;
14908 		}
14909 
14910 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14911 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14912 				i, core_relo.insn_off, prog->len);
14913 			err = -EINVAL;
14914 			break;
14915 		}
14916 
14917 		err = bpf_core_apply(&ctx, &core_relo, i,
14918 				     &prog->insnsi[core_relo.insn_off / 8]);
14919 		if (err)
14920 			break;
14921 		bpfptr_add(&u_core_relo, rec_size);
14922 	}
14923 	return err;
14924 }
14925 
14926 static int check_btf_info(struct bpf_verifier_env *env,
14927 			  const union bpf_attr *attr,
14928 			  bpfptr_t uattr)
14929 {
14930 	struct btf *btf;
14931 	int err;
14932 
14933 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
14934 		if (check_abnormal_return(env))
14935 			return -EINVAL;
14936 		return 0;
14937 	}
14938 
14939 	btf = btf_get_by_fd(attr->prog_btf_fd);
14940 	if (IS_ERR(btf))
14941 		return PTR_ERR(btf);
14942 	if (btf_is_kernel(btf)) {
14943 		btf_put(btf);
14944 		return -EACCES;
14945 	}
14946 	env->prog->aux->btf = btf;
14947 
14948 	err = check_btf_func(env, attr, uattr);
14949 	if (err)
14950 		return err;
14951 
14952 	err = check_btf_line(env, attr, uattr);
14953 	if (err)
14954 		return err;
14955 
14956 	err = check_core_relo(env, attr, uattr);
14957 	if (err)
14958 		return err;
14959 
14960 	return 0;
14961 }
14962 
14963 /* check %cur's range satisfies %old's */
14964 static bool range_within(struct bpf_reg_state *old,
14965 			 struct bpf_reg_state *cur)
14966 {
14967 	return old->umin_value <= cur->umin_value &&
14968 	       old->umax_value >= cur->umax_value &&
14969 	       old->smin_value <= cur->smin_value &&
14970 	       old->smax_value >= cur->smax_value &&
14971 	       old->u32_min_value <= cur->u32_min_value &&
14972 	       old->u32_max_value >= cur->u32_max_value &&
14973 	       old->s32_min_value <= cur->s32_min_value &&
14974 	       old->s32_max_value >= cur->s32_max_value;
14975 }
14976 
14977 /* If in the old state two registers had the same id, then they need to have
14978  * the same id in the new state as well.  But that id could be different from
14979  * the old state, so we need to track the mapping from old to new ids.
14980  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14981  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
14982  * regs with a different old id could still have new id 9, we don't care about
14983  * that.
14984  * So we look through our idmap to see if this old id has been seen before.  If
14985  * so, we require the new id to match; otherwise, we add the id pair to the map.
14986  */
14987 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14988 {
14989 	unsigned int i;
14990 
14991 	/* either both IDs should be set or both should be zero */
14992 	if (!!old_id != !!cur_id)
14993 		return false;
14994 
14995 	if (old_id == 0) /* cur_id == 0 as well */
14996 		return true;
14997 
14998 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14999 		if (!idmap[i].old) {
15000 			/* Reached an empty slot; haven't seen this id before */
15001 			idmap[i].old = old_id;
15002 			idmap[i].cur = cur_id;
15003 			return true;
15004 		}
15005 		if (idmap[i].old == old_id)
15006 			return idmap[i].cur == cur_id;
15007 	}
15008 	/* We ran out of idmap slots, which should be impossible */
15009 	WARN_ON_ONCE(1);
15010 	return false;
15011 }
15012 
15013 static void clean_func_state(struct bpf_verifier_env *env,
15014 			     struct bpf_func_state *st)
15015 {
15016 	enum bpf_reg_liveness live;
15017 	int i, j;
15018 
15019 	for (i = 0; i < BPF_REG_FP; i++) {
15020 		live = st->regs[i].live;
15021 		/* liveness must not touch this register anymore */
15022 		st->regs[i].live |= REG_LIVE_DONE;
15023 		if (!(live & REG_LIVE_READ))
15024 			/* since the register is unused, clear its state
15025 			 * to make further comparison simpler
15026 			 */
15027 			__mark_reg_not_init(env, &st->regs[i]);
15028 	}
15029 
15030 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15031 		live = st->stack[i].spilled_ptr.live;
15032 		/* liveness must not touch this stack slot anymore */
15033 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15034 		if (!(live & REG_LIVE_READ)) {
15035 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15036 			for (j = 0; j < BPF_REG_SIZE; j++)
15037 				st->stack[i].slot_type[j] = STACK_INVALID;
15038 		}
15039 	}
15040 }
15041 
15042 static void clean_verifier_state(struct bpf_verifier_env *env,
15043 				 struct bpf_verifier_state *st)
15044 {
15045 	int i;
15046 
15047 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15048 		/* all regs in this state in all frames were already marked */
15049 		return;
15050 
15051 	for (i = 0; i <= st->curframe; i++)
15052 		clean_func_state(env, st->frame[i]);
15053 }
15054 
15055 /* the parentage chains form a tree.
15056  * the verifier states are added to state lists at given insn and
15057  * pushed into state stack for future exploration.
15058  * when the verifier reaches bpf_exit insn some of the verifer states
15059  * stored in the state lists have their final liveness state already,
15060  * but a lot of states will get revised from liveness point of view when
15061  * the verifier explores other branches.
15062  * Example:
15063  * 1: r0 = 1
15064  * 2: if r1 == 100 goto pc+1
15065  * 3: r0 = 2
15066  * 4: exit
15067  * when the verifier reaches exit insn the register r0 in the state list of
15068  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15069  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15070  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15071  *
15072  * Since the verifier pushes the branch states as it sees them while exploring
15073  * the program the condition of walking the branch instruction for the second
15074  * time means that all states below this branch were already explored and
15075  * their final liveness marks are already propagated.
15076  * Hence when the verifier completes the search of state list in is_state_visited()
15077  * we can call this clean_live_states() function to mark all liveness states
15078  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15079  * will not be used.
15080  * This function also clears the registers and stack for states that !READ
15081  * to simplify state merging.
15082  *
15083  * Important note here that walking the same branch instruction in the callee
15084  * doesn't meant that the states are DONE. The verifier has to compare
15085  * the callsites
15086  */
15087 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15088 			      struct bpf_verifier_state *cur)
15089 {
15090 	struct bpf_verifier_state_list *sl;
15091 	int i;
15092 
15093 	sl = *explored_state(env, insn);
15094 	while (sl) {
15095 		if (sl->state.branches)
15096 			goto next;
15097 		if (sl->state.insn_idx != insn ||
15098 		    sl->state.curframe != cur->curframe)
15099 			goto next;
15100 		for (i = 0; i <= cur->curframe; i++)
15101 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15102 				goto next;
15103 		clean_verifier_state(env, &sl->state);
15104 next:
15105 		sl = sl->next;
15106 	}
15107 }
15108 
15109 static bool regs_exact(const struct bpf_reg_state *rold,
15110 		       const struct bpf_reg_state *rcur,
15111 		       struct bpf_id_pair *idmap)
15112 {
15113 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15114 	       check_ids(rold->id, rcur->id, idmap) &&
15115 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15116 }
15117 
15118 /* Returns true if (rold safe implies rcur safe) */
15119 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15120 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
15121 {
15122 	if (!(rold->live & REG_LIVE_READ))
15123 		/* explored state didn't use this */
15124 		return true;
15125 	if (rold->type == NOT_INIT)
15126 		/* explored state can't have used this */
15127 		return true;
15128 	if (rcur->type == NOT_INIT)
15129 		return false;
15130 
15131 	/* Enforce that register types have to match exactly, including their
15132 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15133 	 * rule.
15134 	 *
15135 	 * One can make a point that using a pointer register as unbounded
15136 	 * SCALAR would be technically acceptable, but this could lead to
15137 	 * pointer leaks because scalars are allowed to leak while pointers
15138 	 * are not. We could make this safe in special cases if root is
15139 	 * calling us, but it's probably not worth the hassle.
15140 	 *
15141 	 * Also, register types that are *not* MAYBE_NULL could technically be
15142 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15143 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15144 	 * to the same map).
15145 	 * However, if the old MAYBE_NULL register then got NULL checked,
15146 	 * doing so could have affected others with the same id, and we can't
15147 	 * check for that because we lost the id when we converted to
15148 	 * a non-MAYBE_NULL variant.
15149 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15150 	 * non-MAYBE_NULL registers as well.
15151 	 */
15152 	if (rold->type != rcur->type)
15153 		return false;
15154 
15155 	switch (base_type(rold->type)) {
15156 	case SCALAR_VALUE:
15157 		if (regs_exact(rold, rcur, idmap))
15158 			return true;
15159 		if (env->explore_alu_limits)
15160 			return false;
15161 		if (!rold->precise)
15162 			return true;
15163 		/* new val must satisfy old val knowledge */
15164 		return range_within(rold, rcur) &&
15165 		       tnum_in(rold->var_off, rcur->var_off);
15166 	case PTR_TO_MAP_KEY:
15167 	case PTR_TO_MAP_VALUE:
15168 	case PTR_TO_MEM:
15169 	case PTR_TO_BUF:
15170 	case PTR_TO_TP_BUFFER:
15171 		/* If the new min/max/var_off satisfy the old ones and
15172 		 * everything else matches, we are OK.
15173 		 */
15174 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15175 		       range_within(rold, rcur) &&
15176 		       tnum_in(rold->var_off, rcur->var_off) &&
15177 		       check_ids(rold->id, rcur->id, idmap) &&
15178 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15179 	case PTR_TO_PACKET_META:
15180 	case PTR_TO_PACKET:
15181 		/* We must have at least as much range as the old ptr
15182 		 * did, so that any accesses which were safe before are
15183 		 * still safe.  This is true even if old range < old off,
15184 		 * since someone could have accessed through (ptr - k), or
15185 		 * even done ptr -= k in a register, to get a safe access.
15186 		 */
15187 		if (rold->range > rcur->range)
15188 			return false;
15189 		/* If the offsets don't match, we can't trust our alignment;
15190 		 * nor can we be sure that we won't fall out of range.
15191 		 */
15192 		if (rold->off != rcur->off)
15193 			return false;
15194 		/* id relations must be preserved */
15195 		if (!check_ids(rold->id, rcur->id, idmap))
15196 			return false;
15197 		/* new val must satisfy old val knowledge */
15198 		return range_within(rold, rcur) &&
15199 		       tnum_in(rold->var_off, rcur->var_off);
15200 	case PTR_TO_STACK:
15201 		/* two stack pointers are equal only if they're pointing to
15202 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15203 		 */
15204 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15205 	default:
15206 		return regs_exact(rold, rcur, idmap);
15207 	}
15208 }
15209 
15210 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15211 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
15212 {
15213 	int i, spi;
15214 
15215 	/* walk slots of the explored stack and ignore any additional
15216 	 * slots in the current stack, since explored(safe) state
15217 	 * didn't use them
15218 	 */
15219 	for (i = 0; i < old->allocated_stack; i++) {
15220 		struct bpf_reg_state *old_reg, *cur_reg;
15221 
15222 		spi = i / BPF_REG_SIZE;
15223 
15224 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15225 			i += BPF_REG_SIZE - 1;
15226 			/* explored state didn't use this */
15227 			continue;
15228 		}
15229 
15230 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15231 			continue;
15232 
15233 		if (env->allow_uninit_stack &&
15234 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15235 			continue;
15236 
15237 		/* explored stack has more populated slots than current stack
15238 		 * and these slots were used
15239 		 */
15240 		if (i >= cur->allocated_stack)
15241 			return false;
15242 
15243 		/* if old state was safe with misc data in the stack
15244 		 * it will be safe with zero-initialized stack.
15245 		 * The opposite is not true
15246 		 */
15247 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15248 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15249 			continue;
15250 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15251 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15252 			/* Ex: old explored (safe) state has STACK_SPILL in
15253 			 * this stack slot, but current has STACK_MISC ->
15254 			 * this verifier states are not equivalent,
15255 			 * return false to continue verification of this path
15256 			 */
15257 			return false;
15258 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15259 			continue;
15260 		/* Both old and cur are having same slot_type */
15261 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15262 		case STACK_SPILL:
15263 			/* when explored and current stack slot are both storing
15264 			 * spilled registers, check that stored pointers types
15265 			 * are the same as well.
15266 			 * Ex: explored safe path could have stored
15267 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15268 			 * but current path has stored:
15269 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15270 			 * such verifier states are not equivalent.
15271 			 * return false to continue verification of this path
15272 			 */
15273 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15274 				     &cur->stack[spi].spilled_ptr, idmap))
15275 				return false;
15276 			break;
15277 		case STACK_DYNPTR:
15278 			old_reg = &old->stack[spi].spilled_ptr;
15279 			cur_reg = &cur->stack[spi].spilled_ptr;
15280 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15281 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15282 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15283 				return false;
15284 			break;
15285 		case STACK_ITER:
15286 			old_reg = &old->stack[spi].spilled_ptr;
15287 			cur_reg = &cur->stack[spi].spilled_ptr;
15288 			/* iter.depth is not compared between states as it
15289 			 * doesn't matter for correctness and would otherwise
15290 			 * prevent convergence; we maintain it only to prevent
15291 			 * infinite loop check triggering, see
15292 			 * iter_active_depths_differ()
15293 			 */
15294 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15295 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15296 			    old_reg->iter.state != cur_reg->iter.state ||
15297 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15298 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15299 				return false;
15300 			break;
15301 		case STACK_MISC:
15302 		case STACK_ZERO:
15303 		case STACK_INVALID:
15304 			continue;
15305 		/* Ensure that new unhandled slot types return false by default */
15306 		default:
15307 			return false;
15308 		}
15309 	}
15310 	return true;
15311 }
15312 
15313 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15314 		    struct bpf_id_pair *idmap)
15315 {
15316 	int i;
15317 
15318 	if (old->acquired_refs != cur->acquired_refs)
15319 		return false;
15320 
15321 	for (i = 0; i < old->acquired_refs; i++) {
15322 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15323 			return false;
15324 	}
15325 
15326 	return true;
15327 }
15328 
15329 /* compare two verifier states
15330  *
15331  * all states stored in state_list are known to be valid, since
15332  * verifier reached 'bpf_exit' instruction through them
15333  *
15334  * this function is called when verifier exploring different branches of
15335  * execution popped from the state stack. If it sees an old state that has
15336  * more strict register state and more strict stack state then this execution
15337  * branch doesn't need to be explored further, since verifier already
15338  * concluded that more strict state leads to valid finish.
15339  *
15340  * Therefore two states are equivalent if register state is more conservative
15341  * and explored stack state is more conservative than the current one.
15342  * Example:
15343  *       explored                   current
15344  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15345  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15346  *
15347  * In other words if current stack state (one being explored) has more
15348  * valid slots than old one that already passed validation, it means
15349  * the verifier can stop exploring and conclude that current state is valid too
15350  *
15351  * Similarly with registers. If explored state has register type as invalid
15352  * whereas register type in current state is meaningful, it means that
15353  * the current state will reach 'bpf_exit' instruction safely
15354  */
15355 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15356 			      struct bpf_func_state *cur)
15357 {
15358 	int i;
15359 
15360 	for (i = 0; i < MAX_BPF_REG; i++)
15361 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15362 			     env->idmap_scratch))
15363 			return false;
15364 
15365 	if (!stacksafe(env, old, cur, env->idmap_scratch))
15366 		return false;
15367 
15368 	if (!refsafe(old, cur, env->idmap_scratch))
15369 		return false;
15370 
15371 	return true;
15372 }
15373 
15374 static bool states_equal(struct bpf_verifier_env *env,
15375 			 struct bpf_verifier_state *old,
15376 			 struct bpf_verifier_state *cur)
15377 {
15378 	int i;
15379 
15380 	if (old->curframe != cur->curframe)
15381 		return false;
15382 
15383 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
15384 
15385 	/* Verification state from speculative execution simulation
15386 	 * must never prune a non-speculative execution one.
15387 	 */
15388 	if (old->speculative && !cur->speculative)
15389 		return false;
15390 
15391 	if (old->active_lock.ptr != cur->active_lock.ptr)
15392 		return false;
15393 
15394 	/* Old and cur active_lock's have to be either both present
15395 	 * or both absent.
15396 	 */
15397 	if (!!old->active_lock.id != !!cur->active_lock.id)
15398 		return false;
15399 
15400 	if (old->active_lock.id &&
15401 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
15402 		return false;
15403 
15404 	if (old->active_rcu_lock != cur->active_rcu_lock)
15405 		return false;
15406 
15407 	/* for states to be equal callsites have to be the same
15408 	 * and all frame states need to be equivalent
15409 	 */
15410 	for (i = 0; i <= old->curframe; i++) {
15411 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15412 			return false;
15413 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15414 			return false;
15415 	}
15416 	return true;
15417 }
15418 
15419 /* Return 0 if no propagation happened. Return negative error code if error
15420  * happened. Otherwise, return the propagated bit.
15421  */
15422 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15423 				  struct bpf_reg_state *reg,
15424 				  struct bpf_reg_state *parent_reg)
15425 {
15426 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15427 	u8 flag = reg->live & REG_LIVE_READ;
15428 	int err;
15429 
15430 	/* When comes here, read flags of PARENT_REG or REG could be any of
15431 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15432 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15433 	 */
15434 	if (parent_flag == REG_LIVE_READ64 ||
15435 	    /* Or if there is no read flag from REG. */
15436 	    !flag ||
15437 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15438 	    parent_flag == flag)
15439 		return 0;
15440 
15441 	err = mark_reg_read(env, reg, parent_reg, flag);
15442 	if (err)
15443 		return err;
15444 
15445 	return flag;
15446 }
15447 
15448 /* A write screens off any subsequent reads; but write marks come from the
15449  * straight-line code between a state and its parent.  When we arrive at an
15450  * equivalent state (jump target or such) we didn't arrive by the straight-line
15451  * code, so read marks in the state must propagate to the parent regardless
15452  * of the state's write marks. That's what 'parent == state->parent' comparison
15453  * in mark_reg_read() is for.
15454  */
15455 static int propagate_liveness(struct bpf_verifier_env *env,
15456 			      const struct bpf_verifier_state *vstate,
15457 			      struct bpf_verifier_state *vparent)
15458 {
15459 	struct bpf_reg_state *state_reg, *parent_reg;
15460 	struct bpf_func_state *state, *parent;
15461 	int i, frame, err = 0;
15462 
15463 	if (vparent->curframe != vstate->curframe) {
15464 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15465 		     vparent->curframe, vstate->curframe);
15466 		return -EFAULT;
15467 	}
15468 	/* Propagate read liveness of registers... */
15469 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15470 	for (frame = 0; frame <= vstate->curframe; frame++) {
15471 		parent = vparent->frame[frame];
15472 		state = vstate->frame[frame];
15473 		parent_reg = parent->regs;
15474 		state_reg = state->regs;
15475 		/* We don't need to worry about FP liveness, it's read-only */
15476 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15477 			err = propagate_liveness_reg(env, &state_reg[i],
15478 						     &parent_reg[i]);
15479 			if (err < 0)
15480 				return err;
15481 			if (err == REG_LIVE_READ64)
15482 				mark_insn_zext(env, &parent_reg[i]);
15483 		}
15484 
15485 		/* Propagate stack slots. */
15486 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15487 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15488 			parent_reg = &parent->stack[i].spilled_ptr;
15489 			state_reg = &state->stack[i].spilled_ptr;
15490 			err = propagate_liveness_reg(env, state_reg,
15491 						     parent_reg);
15492 			if (err < 0)
15493 				return err;
15494 		}
15495 	}
15496 	return 0;
15497 }
15498 
15499 /* find precise scalars in the previous equivalent state and
15500  * propagate them into the current state
15501  */
15502 static int propagate_precision(struct bpf_verifier_env *env,
15503 			       const struct bpf_verifier_state *old)
15504 {
15505 	struct bpf_reg_state *state_reg;
15506 	struct bpf_func_state *state;
15507 	int i, err = 0, fr;
15508 	bool first;
15509 
15510 	for (fr = old->curframe; fr >= 0; fr--) {
15511 		state = old->frame[fr];
15512 		state_reg = state->regs;
15513 		first = true;
15514 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15515 			if (state_reg->type != SCALAR_VALUE ||
15516 			    !state_reg->precise ||
15517 			    !(state_reg->live & REG_LIVE_READ))
15518 				continue;
15519 			if (env->log.level & BPF_LOG_LEVEL2) {
15520 				if (first)
15521 					verbose(env, "frame %d: propagating r%d", fr, i);
15522 				else
15523 					verbose(env, ",r%d", i);
15524 			}
15525 			bt_set_frame_reg(&env->bt, fr, i);
15526 			first = false;
15527 		}
15528 
15529 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15530 			if (!is_spilled_reg(&state->stack[i]))
15531 				continue;
15532 			state_reg = &state->stack[i].spilled_ptr;
15533 			if (state_reg->type != SCALAR_VALUE ||
15534 			    !state_reg->precise ||
15535 			    !(state_reg->live & REG_LIVE_READ))
15536 				continue;
15537 			if (env->log.level & BPF_LOG_LEVEL2) {
15538 				if (first)
15539 					verbose(env, "frame %d: propagating fp%d",
15540 						fr, (-i - 1) * BPF_REG_SIZE);
15541 				else
15542 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15543 			}
15544 			bt_set_frame_slot(&env->bt, fr, i);
15545 			first = false;
15546 		}
15547 		if (!first)
15548 			verbose(env, "\n");
15549 	}
15550 
15551 	err = mark_chain_precision_batch(env);
15552 	if (err < 0)
15553 		return err;
15554 
15555 	return 0;
15556 }
15557 
15558 static bool states_maybe_looping(struct bpf_verifier_state *old,
15559 				 struct bpf_verifier_state *cur)
15560 {
15561 	struct bpf_func_state *fold, *fcur;
15562 	int i, fr = cur->curframe;
15563 
15564 	if (old->curframe != fr)
15565 		return false;
15566 
15567 	fold = old->frame[fr];
15568 	fcur = cur->frame[fr];
15569 	for (i = 0; i < MAX_BPF_REG; i++)
15570 		if (memcmp(&fold->regs[i], &fcur->regs[i],
15571 			   offsetof(struct bpf_reg_state, parent)))
15572 			return false;
15573 	return true;
15574 }
15575 
15576 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15577 {
15578 	return env->insn_aux_data[insn_idx].is_iter_next;
15579 }
15580 
15581 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15582  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15583  * states to match, which otherwise would look like an infinite loop. So while
15584  * iter_next() calls are taken care of, we still need to be careful and
15585  * prevent erroneous and too eager declaration of "ininite loop", when
15586  * iterators are involved.
15587  *
15588  * Here's a situation in pseudo-BPF assembly form:
15589  *
15590  *   0: again:                          ; set up iter_next() call args
15591  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15592  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15593  *   3:   if r0 == 0 goto done
15594  *   4:   ... something useful here ...
15595  *   5:   goto again                    ; another iteration
15596  *   6: done:
15597  *   7:   r1 = &it
15598  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15599  *   9:   exit
15600  *
15601  * This is a typical loop. Let's assume that we have a prune point at 1:,
15602  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15603  * again`, assuming other heuristics don't get in a way).
15604  *
15605  * When we first time come to 1:, let's say we have some state X. We proceed
15606  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15607  * Now we come back to validate that forked ACTIVE state. We proceed through
15608  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15609  * are converging. But the problem is that we don't know that yet, as this
15610  * convergence has to happen at iter_next() call site only. So if nothing is
15611  * done, at 1: verifier will use bounded loop logic and declare infinite
15612  * looping (and would be *technically* correct, if not for iterator's
15613  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15614  * don't want that. So what we do in process_iter_next_call() when we go on
15615  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15616  * a different iteration. So when we suspect an infinite loop, we additionally
15617  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15618  * pretend we are not looping and wait for next iter_next() call.
15619  *
15620  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15621  * loop, because that would actually mean infinite loop, as DRAINED state is
15622  * "sticky", and so we'll keep returning into the same instruction with the
15623  * same state (at least in one of possible code paths).
15624  *
15625  * This approach allows to keep infinite loop heuristic even in the face of
15626  * active iterator. E.g., C snippet below is and will be detected as
15627  * inifintely looping:
15628  *
15629  *   struct bpf_iter_num it;
15630  *   int *p, x;
15631  *
15632  *   bpf_iter_num_new(&it, 0, 10);
15633  *   while ((p = bpf_iter_num_next(&t))) {
15634  *       x = p;
15635  *       while (x--) {} // <<-- infinite loop here
15636  *   }
15637  *
15638  */
15639 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15640 {
15641 	struct bpf_reg_state *slot, *cur_slot;
15642 	struct bpf_func_state *state;
15643 	int i, fr;
15644 
15645 	for (fr = old->curframe; fr >= 0; fr--) {
15646 		state = old->frame[fr];
15647 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15648 			if (state->stack[i].slot_type[0] != STACK_ITER)
15649 				continue;
15650 
15651 			slot = &state->stack[i].spilled_ptr;
15652 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15653 				continue;
15654 
15655 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15656 			if (cur_slot->iter.depth != slot->iter.depth)
15657 				return true;
15658 		}
15659 	}
15660 	return false;
15661 }
15662 
15663 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15664 {
15665 	struct bpf_verifier_state_list *new_sl;
15666 	struct bpf_verifier_state_list *sl, **pprev;
15667 	struct bpf_verifier_state *cur = env->cur_state, *new;
15668 	int i, j, err, states_cnt = 0;
15669 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15670 	bool add_new_state = force_new_state;
15671 
15672 	/* bpf progs typically have pruning point every 4 instructions
15673 	 * http://vger.kernel.org/bpfconf2019.html#session-1
15674 	 * Do not add new state for future pruning if the verifier hasn't seen
15675 	 * at least 2 jumps and at least 8 instructions.
15676 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15677 	 * In tests that amounts to up to 50% reduction into total verifier
15678 	 * memory consumption and 20% verifier time speedup.
15679 	 */
15680 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15681 	    env->insn_processed - env->prev_insn_processed >= 8)
15682 		add_new_state = true;
15683 
15684 	pprev = explored_state(env, insn_idx);
15685 	sl = *pprev;
15686 
15687 	clean_live_states(env, insn_idx, cur);
15688 
15689 	while (sl) {
15690 		states_cnt++;
15691 		if (sl->state.insn_idx != insn_idx)
15692 			goto next;
15693 
15694 		if (sl->state.branches) {
15695 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15696 
15697 			if (frame->in_async_callback_fn &&
15698 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15699 				/* Different async_entry_cnt means that the verifier is
15700 				 * processing another entry into async callback.
15701 				 * Seeing the same state is not an indication of infinite
15702 				 * loop or infinite recursion.
15703 				 * But finding the same state doesn't mean that it's safe
15704 				 * to stop processing the current state. The previous state
15705 				 * hasn't yet reached bpf_exit, since state.branches > 0.
15706 				 * Checking in_async_callback_fn alone is not enough either.
15707 				 * Since the verifier still needs to catch infinite loops
15708 				 * inside async callbacks.
15709 				 */
15710 				goto skip_inf_loop_check;
15711 			}
15712 			/* BPF open-coded iterators loop detection is special.
15713 			 * states_maybe_looping() logic is too simplistic in detecting
15714 			 * states that *might* be equivalent, because it doesn't know
15715 			 * about ID remapping, so don't even perform it.
15716 			 * See process_iter_next_call() and iter_active_depths_differ()
15717 			 * for overview of the logic. When current and one of parent
15718 			 * states are detected as equivalent, it's a good thing: we prove
15719 			 * convergence and can stop simulating further iterations.
15720 			 * It's safe to assume that iterator loop will finish, taking into
15721 			 * account iter_next() contract of eventually returning
15722 			 * sticky NULL result.
15723 			 */
15724 			if (is_iter_next_insn(env, insn_idx)) {
15725 				if (states_equal(env, &sl->state, cur)) {
15726 					struct bpf_func_state *cur_frame;
15727 					struct bpf_reg_state *iter_state, *iter_reg;
15728 					int spi;
15729 
15730 					cur_frame = cur->frame[cur->curframe];
15731 					/* btf_check_iter_kfuncs() enforces that
15732 					 * iter state pointer is always the first arg
15733 					 */
15734 					iter_reg = &cur_frame->regs[BPF_REG_1];
15735 					/* current state is valid due to states_equal(),
15736 					 * so we can assume valid iter and reg state,
15737 					 * no need for extra (re-)validations
15738 					 */
15739 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15740 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15741 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15742 						goto hit;
15743 				}
15744 				goto skip_inf_loop_check;
15745 			}
15746 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
15747 			if (states_maybe_looping(&sl->state, cur) &&
15748 			    states_equal(env, &sl->state, cur) &&
15749 			    !iter_active_depths_differ(&sl->state, cur)) {
15750 				verbose_linfo(env, insn_idx, "; ");
15751 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15752 				return -EINVAL;
15753 			}
15754 			/* if the verifier is processing a loop, avoid adding new state
15755 			 * too often, since different loop iterations have distinct
15756 			 * states and may not help future pruning.
15757 			 * This threshold shouldn't be too low to make sure that
15758 			 * a loop with large bound will be rejected quickly.
15759 			 * The most abusive loop will be:
15760 			 * r1 += 1
15761 			 * if r1 < 1000000 goto pc-2
15762 			 * 1M insn_procssed limit / 100 == 10k peak states.
15763 			 * This threshold shouldn't be too high either, since states
15764 			 * at the end of the loop are likely to be useful in pruning.
15765 			 */
15766 skip_inf_loop_check:
15767 			if (!force_new_state &&
15768 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
15769 			    env->insn_processed - env->prev_insn_processed < 100)
15770 				add_new_state = false;
15771 			goto miss;
15772 		}
15773 		if (states_equal(env, &sl->state, cur)) {
15774 hit:
15775 			sl->hit_cnt++;
15776 			/* reached equivalent register/stack state,
15777 			 * prune the search.
15778 			 * Registers read by the continuation are read by us.
15779 			 * If we have any write marks in env->cur_state, they
15780 			 * will prevent corresponding reads in the continuation
15781 			 * from reaching our parent (an explored_state).  Our
15782 			 * own state will get the read marks recorded, but
15783 			 * they'll be immediately forgotten as we're pruning
15784 			 * this state and will pop a new one.
15785 			 */
15786 			err = propagate_liveness(env, &sl->state, cur);
15787 
15788 			/* if previous state reached the exit with precision and
15789 			 * current state is equivalent to it (except precsion marks)
15790 			 * the precision needs to be propagated back in
15791 			 * the current state.
15792 			 */
15793 			err = err ? : push_jmp_history(env, cur);
15794 			err = err ? : propagate_precision(env, &sl->state);
15795 			if (err)
15796 				return err;
15797 			return 1;
15798 		}
15799 miss:
15800 		/* when new state is not going to be added do not increase miss count.
15801 		 * Otherwise several loop iterations will remove the state
15802 		 * recorded earlier. The goal of these heuristics is to have
15803 		 * states from some iterations of the loop (some in the beginning
15804 		 * and some at the end) to help pruning.
15805 		 */
15806 		if (add_new_state)
15807 			sl->miss_cnt++;
15808 		/* heuristic to determine whether this state is beneficial
15809 		 * to keep checking from state equivalence point of view.
15810 		 * Higher numbers increase max_states_per_insn and verification time,
15811 		 * but do not meaningfully decrease insn_processed.
15812 		 */
15813 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15814 			/* the state is unlikely to be useful. Remove it to
15815 			 * speed up verification
15816 			 */
15817 			*pprev = sl->next;
15818 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15819 				u32 br = sl->state.branches;
15820 
15821 				WARN_ONCE(br,
15822 					  "BUG live_done but branches_to_explore %d\n",
15823 					  br);
15824 				free_verifier_state(&sl->state, false);
15825 				kfree(sl);
15826 				env->peak_states--;
15827 			} else {
15828 				/* cannot free this state, since parentage chain may
15829 				 * walk it later. Add it for free_list instead to
15830 				 * be freed at the end of verification
15831 				 */
15832 				sl->next = env->free_list;
15833 				env->free_list = sl;
15834 			}
15835 			sl = *pprev;
15836 			continue;
15837 		}
15838 next:
15839 		pprev = &sl->next;
15840 		sl = *pprev;
15841 	}
15842 
15843 	if (env->max_states_per_insn < states_cnt)
15844 		env->max_states_per_insn = states_cnt;
15845 
15846 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15847 		return 0;
15848 
15849 	if (!add_new_state)
15850 		return 0;
15851 
15852 	/* There were no equivalent states, remember the current one.
15853 	 * Technically the current state is not proven to be safe yet,
15854 	 * but it will either reach outer most bpf_exit (which means it's safe)
15855 	 * or it will be rejected. When there are no loops the verifier won't be
15856 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15857 	 * again on the way to bpf_exit.
15858 	 * When looping the sl->state.branches will be > 0 and this state
15859 	 * will not be considered for equivalence until branches == 0.
15860 	 */
15861 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15862 	if (!new_sl)
15863 		return -ENOMEM;
15864 	env->total_states++;
15865 	env->peak_states++;
15866 	env->prev_jmps_processed = env->jmps_processed;
15867 	env->prev_insn_processed = env->insn_processed;
15868 
15869 	/* forget precise markings we inherited, see __mark_chain_precision */
15870 	if (env->bpf_capable)
15871 		mark_all_scalars_imprecise(env, cur);
15872 
15873 	/* add new state to the head of linked list */
15874 	new = &new_sl->state;
15875 	err = copy_verifier_state(new, cur);
15876 	if (err) {
15877 		free_verifier_state(new, false);
15878 		kfree(new_sl);
15879 		return err;
15880 	}
15881 	new->insn_idx = insn_idx;
15882 	WARN_ONCE(new->branches != 1,
15883 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
15884 
15885 	cur->parent = new;
15886 	cur->first_insn_idx = insn_idx;
15887 	clear_jmp_history(cur);
15888 	new_sl->next = *explored_state(env, insn_idx);
15889 	*explored_state(env, insn_idx) = new_sl;
15890 	/* connect new state to parentage chain. Current frame needs all
15891 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
15892 	 * to the stack implicitly by JITs) so in callers' frames connect just
15893 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15894 	 * the state of the call instruction (with WRITTEN set), and r0 comes
15895 	 * from callee with its full parentage chain, anyway.
15896 	 */
15897 	/* clear write marks in current state: the writes we did are not writes
15898 	 * our child did, so they don't screen off its reads from us.
15899 	 * (There are no read marks in current state, because reads always mark
15900 	 * their parent and current state never has children yet.  Only
15901 	 * explored_states can get read marks.)
15902 	 */
15903 	for (j = 0; j <= cur->curframe; j++) {
15904 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15905 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15906 		for (i = 0; i < BPF_REG_FP; i++)
15907 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15908 	}
15909 
15910 	/* all stack frames are accessible from callee, clear them all */
15911 	for (j = 0; j <= cur->curframe; j++) {
15912 		struct bpf_func_state *frame = cur->frame[j];
15913 		struct bpf_func_state *newframe = new->frame[j];
15914 
15915 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
15916 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
15917 			frame->stack[i].spilled_ptr.parent =
15918 						&newframe->stack[i].spilled_ptr;
15919 		}
15920 	}
15921 	return 0;
15922 }
15923 
15924 /* Return true if it's OK to have the same insn return a different type. */
15925 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15926 {
15927 	switch (base_type(type)) {
15928 	case PTR_TO_CTX:
15929 	case PTR_TO_SOCKET:
15930 	case PTR_TO_SOCK_COMMON:
15931 	case PTR_TO_TCP_SOCK:
15932 	case PTR_TO_XDP_SOCK:
15933 	case PTR_TO_BTF_ID:
15934 		return false;
15935 	default:
15936 		return true;
15937 	}
15938 }
15939 
15940 /* If an instruction was previously used with particular pointer types, then we
15941  * need to be careful to avoid cases such as the below, where it may be ok
15942  * for one branch accessing the pointer, but not ok for the other branch:
15943  *
15944  * R1 = sock_ptr
15945  * goto X;
15946  * ...
15947  * R1 = some_other_valid_ptr;
15948  * goto X;
15949  * ...
15950  * R2 = *(u32 *)(R1 + 0);
15951  */
15952 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15953 {
15954 	return src != prev && (!reg_type_mismatch_ok(src) ||
15955 			       !reg_type_mismatch_ok(prev));
15956 }
15957 
15958 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15959 			     bool allow_trust_missmatch)
15960 {
15961 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15962 
15963 	if (*prev_type == NOT_INIT) {
15964 		/* Saw a valid insn
15965 		 * dst_reg = *(u32 *)(src_reg + off)
15966 		 * save type to validate intersecting paths
15967 		 */
15968 		*prev_type = type;
15969 	} else if (reg_type_mismatch(type, *prev_type)) {
15970 		/* Abuser program is trying to use the same insn
15971 		 * dst_reg = *(u32*) (src_reg + off)
15972 		 * with different pointer types:
15973 		 * src_reg == ctx in one branch and
15974 		 * src_reg == stack|map in some other branch.
15975 		 * Reject it.
15976 		 */
15977 		if (allow_trust_missmatch &&
15978 		    base_type(type) == PTR_TO_BTF_ID &&
15979 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
15980 			/*
15981 			 * Have to support a use case when one path through
15982 			 * the program yields TRUSTED pointer while another
15983 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
15984 			 * BPF_PROBE_MEM.
15985 			 */
15986 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15987 		} else {
15988 			verbose(env, "same insn cannot be used with different pointers\n");
15989 			return -EINVAL;
15990 		}
15991 	}
15992 
15993 	return 0;
15994 }
15995 
15996 static int do_check(struct bpf_verifier_env *env)
15997 {
15998 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15999 	struct bpf_verifier_state *state = env->cur_state;
16000 	struct bpf_insn *insns = env->prog->insnsi;
16001 	struct bpf_reg_state *regs;
16002 	int insn_cnt = env->prog->len;
16003 	bool do_print_state = false;
16004 	int prev_insn_idx = -1;
16005 
16006 	for (;;) {
16007 		struct bpf_insn *insn;
16008 		u8 class;
16009 		int err;
16010 
16011 		env->prev_insn_idx = prev_insn_idx;
16012 		if (env->insn_idx >= insn_cnt) {
16013 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16014 				env->insn_idx, insn_cnt);
16015 			return -EFAULT;
16016 		}
16017 
16018 		insn = &insns[env->insn_idx];
16019 		class = BPF_CLASS(insn->code);
16020 
16021 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16022 			verbose(env,
16023 				"BPF program is too large. Processed %d insn\n",
16024 				env->insn_processed);
16025 			return -E2BIG;
16026 		}
16027 
16028 		state->last_insn_idx = env->prev_insn_idx;
16029 
16030 		if (is_prune_point(env, env->insn_idx)) {
16031 			err = is_state_visited(env, env->insn_idx);
16032 			if (err < 0)
16033 				return err;
16034 			if (err == 1) {
16035 				/* found equivalent state, can prune the search */
16036 				if (env->log.level & BPF_LOG_LEVEL) {
16037 					if (do_print_state)
16038 						verbose(env, "\nfrom %d to %d%s: safe\n",
16039 							env->prev_insn_idx, env->insn_idx,
16040 							env->cur_state->speculative ?
16041 							" (speculative execution)" : "");
16042 					else
16043 						verbose(env, "%d: safe\n", env->insn_idx);
16044 				}
16045 				goto process_bpf_exit;
16046 			}
16047 		}
16048 
16049 		if (is_jmp_point(env, env->insn_idx)) {
16050 			err = push_jmp_history(env, state);
16051 			if (err)
16052 				return err;
16053 		}
16054 
16055 		if (signal_pending(current))
16056 			return -EAGAIN;
16057 
16058 		if (need_resched())
16059 			cond_resched();
16060 
16061 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16062 			verbose(env, "\nfrom %d to %d%s:",
16063 				env->prev_insn_idx, env->insn_idx,
16064 				env->cur_state->speculative ?
16065 				" (speculative execution)" : "");
16066 			print_verifier_state(env, state->frame[state->curframe], true);
16067 			do_print_state = false;
16068 		}
16069 
16070 		if (env->log.level & BPF_LOG_LEVEL) {
16071 			const struct bpf_insn_cbs cbs = {
16072 				.cb_call	= disasm_kfunc_name,
16073 				.cb_print	= verbose,
16074 				.private_data	= env,
16075 			};
16076 
16077 			if (verifier_state_scratched(env))
16078 				print_insn_state(env, state->frame[state->curframe]);
16079 
16080 			verbose_linfo(env, env->insn_idx, "; ");
16081 			env->prev_log_pos = env->log.end_pos;
16082 			verbose(env, "%d: ", env->insn_idx);
16083 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16084 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16085 			env->prev_log_pos = env->log.end_pos;
16086 		}
16087 
16088 		if (bpf_prog_is_offloaded(env->prog->aux)) {
16089 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16090 							   env->prev_insn_idx);
16091 			if (err)
16092 				return err;
16093 		}
16094 
16095 		regs = cur_regs(env);
16096 		sanitize_mark_insn_seen(env);
16097 		prev_insn_idx = env->insn_idx;
16098 
16099 		if (class == BPF_ALU || class == BPF_ALU64) {
16100 			err = check_alu_op(env, insn);
16101 			if (err)
16102 				return err;
16103 
16104 		} else if (class == BPF_LDX) {
16105 			enum bpf_reg_type src_reg_type;
16106 
16107 			/* check for reserved fields is already done */
16108 
16109 			/* check src operand */
16110 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16111 			if (err)
16112 				return err;
16113 
16114 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16115 			if (err)
16116 				return err;
16117 
16118 			src_reg_type = regs[insn->src_reg].type;
16119 
16120 			/* check that memory (src_reg + off) is readable,
16121 			 * the state of dst_reg will be updated by this func
16122 			 */
16123 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
16124 					       insn->off, BPF_SIZE(insn->code),
16125 					       BPF_READ, insn->dst_reg, false);
16126 			if (err)
16127 				return err;
16128 
16129 			err = save_aux_ptr_type(env, src_reg_type, true);
16130 			if (err)
16131 				return err;
16132 		} else if (class == BPF_STX) {
16133 			enum bpf_reg_type dst_reg_type;
16134 
16135 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16136 				err = check_atomic(env, env->insn_idx, insn);
16137 				if (err)
16138 					return err;
16139 				env->insn_idx++;
16140 				continue;
16141 			}
16142 
16143 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16144 				verbose(env, "BPF_STX uses reserved fields\n");
16145 				return -EINVAL;
16146 			}
16147 
16148 			/* check src1 operand */
16149 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16150 			if (err)
16151 				return err;
16152 			/* check src2 operand */
16153 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16154 			if (err)
16155 				return err;
16156 
16157 			dst_reg_type = regs[insn->dst_reg].type;
16158 
16159 			/* check that memory (dst_reg + off) is writeable */
16160 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16161 					       insn->off, BPF_SIZE(insn->code),
16162 					       BPF_WRITE, insn->src_reg, false);
16163 			if (err)
16164 				return err;
16165 
16166 			err = save_aux_ptr_type(env, dst_reg_type, false);
16167 			if (err)
16168 				return err;
16169 		} else if (class == BPF_ST) {
16170 			enum bpf_reg_type dst_reg_type;
16171 
16172 			if (BPF_MODE(insn->code) != BPF_MEM ||
16173 			    insn->src_reg != BPF_REG_0) {
16174 				verbose(env, "BPF_ST uses reserved fields\n");
16175 				return -EINVAL;
16176 			}
16177 			/* check src operand */
16178 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16179 			if (err)
16180 				return err;
16181 
16182 			dst_reg_type = regs[insn->dst_reg].type;
16183 
16184 			/* check that memory (dst_reg + off) is writeable */
16185 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16186 					       insn->off, BPF_SIZE(insn->code),
16187 					       BPF_WRITE, -1, false);
16188 			if (err)
16189 				return err;
16190 
16191 			err = save_aux_ptr_type(env, dst_reg_type, false);
16192 			if (err)
16193 				return err;
16194 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16195 			u8 opcode = BPF_OP(insn->code);
16196 
16197 			env->jmps_processed++;
16198 			if (opcode == BPF_CALL) {
16199 				if (BPF_SRC(insn->code) != BPF_K ||
16200 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16201 				     && insn->off != 0) ||
16202 				    (insn->src_reg != BPF_REG_0 &&
16203 				     insn->src_reg != BPF_PSEUDO_CALL &&
16204 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16205 				    insn->dst_reg != BPF_REG_0 ||
16206 				    class == BPF_JMP32) {
16207 					verbose(env, "BPF_CALL uses reserved fields\n");
16208 					return -EINVAL;
16209 				}
16210 
16211 				if (env->cur_state->active_lock.ptr) {
16212 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16213 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16214 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16215 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16216 						verbose(env, "function calls are not allowed while holding a lock\n");
16217 						return -EINVAL;
16218 					}
16219 				}
16220 				if (insn->src_reg == BPF_PSEUDO_CALL)
16221 					err = check_func_call(env, insn, &env->insn_idx);
16222 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16223 					err = check_kfunc_call(env, insn, &env->insn_idx);
16224 				else
16225 					err = check_helper_call(env, insn, &env->insn_idx);
16226 				if (err)
16227 					return err;
16228 
16229 				mark_reg_scratched(env, BPF_REG_0);
16230 			} else if (opcode == BPF_JA) {
16231 				if (BPF_SRC(insn->code) != BPF_K ||
16232 				    insn->imm != 0 ||
16233 				    insn->src_reg != BPF_REG_0 ||
16234 				    insn->dst_reg != BPF_REG_0 ||
16235 				    class == BPF_JMP32) {
16236 					verbose(env, "BPF_JA uses reserved fields\n");
16237 					return -EINVAL;
16238 				}
16239 
16240 				env->insn_idx += insn->off + 1;
16241 				continue;
16242 
16243 			} else if (opcode == BPF_EXIT) {
16244 				if (BPF_SRC(insn->code) != BPF_K ||
16245 				    insn->imm != 0 ||
16246 				    insn->src_reg != BPF_REG_0 ||
16247 				    insn->dst_reg != BPF_REG_0 ||
16248 				    class == BPF_JMP32) {
16249 					verbose(env, "BPF_EXIT uses reserved fields\n");
16250 					return -EINVAL;
16251 				}
16252 
16253 				if (env->cur_state->active_lock.ptr &&
16254 				    !in_rbtree_lock_required_cb(env)) {
16255 					verbose(env, "bpf_spin_unlock is missing\n");
16256 					return -EINVAL;
16257 				}
16258 
16259 				if (env->cur_state->active_rcu_lock) {
16260 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16261 					return -EINVAL;
16262 				}
16263 
16264 				/* We must do check_reference_leak here before
16265 				 * prepare_func_exit to handle the case when
16266 				 * state->curframe > 0, it may be a callback
16267 				 * function, for which reference_state must
16268 				 * match caller reference state when it exits.
16269 				 */
16270 				err = check_reference_leak(env);
16271 				if (err)
16272 					return err;
16273 
16274 				if (state->curframe) {
16275 					/* exit from nested function */
16276 					err = prepare_func_exit(env, &env->insn_idx);
16277 					if (err)
16278 						return err;
16279 					do_print_state = true;
16280 					continue;
16281 				}
16282 
16283 				err = check_return_code(env);
16284 				if (err)
16285 					return err;
16286 process_bpf_exit:
16287 				mark_verifier_state_scratched(env);
16288 				update_branch_counts(env, env->cur_state);
16289 				err = pop_stack(env, &prev_insn_idx,
16290 						&env->insn_idx, pop_log);
16291 				if (err < 0) {
16292 					if (err != -ENOENT)
16293 						return err;
16294 					break;
16295 				} else {
16296 					do_print_state = true;
16297 					continue;
16298 				}
16299 			} else {
16300 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16301 				if (err)
16302 					return err;
16303 			}
16304 		} else if (class == BPF_LD) {
16305 			u8 mode = BPF_MODE(insn->code);
16306 
16307 			if (mode == BPF_ABS || mode == BPF_IND) {
16308 				err = check_ld_abs(env, insn);
16309 				if (err)
16310 					return err;
16311 
16312 			} else if (mode == BPF_IMM) {
16313 				err = check_ld_imm(env, insn);
16314 				if (err)
16315 					return err;
16316 
16317 				env->insn_idx++;
16318 				sanitize_mark_insn_seen(env);
16319 			} else {
16320 				verbose(env, "invalid BPF_LD mode\n");
16321 				return -EINVAL;
16322 			}
16323 		} else {
16324 			verbose(env, "unknown insn class %d\n", class);
16325 			return -EINVAL;
16326 		}
16327 
16328 		env->insn_idx++;
16329 	}
16330 
16331 	return 0;
16332 }
16333 
16334 static int find_btf_percpu_datasec(struct btf *btf)
16335 {
16336 	const struct btf_type *t;
16337 	const char *tname;
16338 	int i, n;
16339 
16340 	/*
16341 	 * Both vmlinux and module each have their own ".data..percpu"
16342 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16343 	 * types to look at only module's own BTF types.
16344 	 */
16345 	n = btf_nr_types(btf);
16346 	if (btf_is_module(btf))
16347 		i = btf_nr_types(btf_vmlinux);
16348 	else
16349 		i = 1;
16350 
16351 	for(; i < n; i++) {
16352 		t = btf_type_by_id(btf, i);
16353 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16354 			continue;
16355 
16356 		tname = btf_name_by_offset(btf, t->name_off);
16357 		if (!strcmp(tname, ".data..percpu"))
16358 			return i;
16359 	}
16360 
16361 	return -ENOENT;
16362 }
16363 
16364 /* replace pseudo btf_id with kernel symbol address */
16365 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16366 			       struct bpf_insn *insn,
16367 			       struct bpf_insn_aux_data *aux)
16368 {
16369 	const struct btf_var_secinfo *vsi;
16370 	const struct btf_type *datasec;
16371 	struct btf_mod_pair *btf_mod;
16372 	const struct btf_type *t;
16373 	const char *sym_name;
16374 	bool percpu = false;
16375 	u32 type, id = insn->imm;
16376 	struct btf *btf;
16377 	s32 datasec_id;
16378 	u64 addr;
16379 	int i, btf_fd, err;
16380 
16381 	btf_fd = insn[1].imm;
16382 	if (btf_fd) {
16383 		btf = btf_get_by_fd(btf_fd);
16384 		if (IS_ERR(btf)) {
16385 			verbose(env, "invalid module BTF object FD specified.\n");
16386 			return -EINVAL;
16387 		}
16388 	} else {
16389 		if (!btf_vmlinux) {
16390 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16391 			return -EINVAL;
16392 		}
16393 		btf = btf_vmlinux;
16394 		btf_get(btf);
16395 	}
16396 
16397 	t = btf_type_by_id(btf, id);
16398 	if (!t) {
16399 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16400 		err = -ENOENT;
16401 		goto err_put;
16402 	}
16403 
16404 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16405 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16406 		err = -EINVAL;
16407 		goto err_put;
16408 	}
16409 
16410 	sym_name = btf_name_by_offset(btf, t->name_off);
16411 	addr = kallsyms_lookup_name(sym_name);
16412 	if (!addr) {
16413 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16414 			sym_name);
16415 		err = -ENOENT;
16416 		goto err_put;
16417 	}
16418 	insn[0].imm = (u32)addr;
16419 	insn[1].imm = addr >> 32;
16420 
16421 	if (btf_type_is_func(t)) {
16422 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16423 		aux->btf_var.mem_size = 0;
16424 		goto check_btf;
16425 	}
16426 
16427 	datasec_id = find_btf_percpu_datasec(btf);
16428 	if (datasec_id > 0) {
16429 		datasec = btf_type_by_id(btf, datasec_id);
16430 		for_each_vsi(i, datasec, vsi) {
16431 			if (vsi->type == id) {
16432 				percpu = true;
16433 				break;
16434 			}
16435 		}
16436 	}
16437 
16438 	type = t->type;
16439 	t = btf_type_skip_modifiers(btf, type, NULL);
16440 	if (percpu) {
16441 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16442 		aux->btf_var.btf = btf;
16443 		aux->btf_var.btf_id = type;
16444 	} else if (!btf_type_is_struct(t)) {
16445 		const struct btf_type *ret;
16446 		const char *tname;
16447 		u32 tsize;
16448 
16449 		/* resolve the type size of ksym. */
16450 		ret = btf_resolve_size(btf, t, &tsize);
16451 		if (IS_ERR(ret)) {
16452 			tname = btf_name_by_offset(btf, t->name_off);
16453 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16454 				tname, PTR_ERR(ret));
16455 			err = -EINVAL;
16456 			goto err_put;
16457 		}
16458 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16459 		aux->btf_var.mem_size = tsize;
16460 	} else {
16461 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16462 		aux->btf_var.btf = btf;
16463 		aux->btf_var.btf_id = type;
16464 	}
16465 check_btf:
16466 	/* check whether we recorded this BTF (and maybe module) already */
16467 	for (i = 0; i < env->used_btf_cnt; i++) {
16468 		if (env->used_btfs[i].btf == btf) {
16469 			btf_put(btf);
16470 			return 0;
16471 		}
16472 	}
16473 
16474 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16475 		err = -E2BIG;
16476 		goto err_put;
16477 	}
16478 
16479 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16480 	btf_mod->btf = btf;
16481 	btf_mod->module = NULL;
16482 
16483 	/* if we reference variables from kernel module, bump its refcount */
16484 	if (btf_is_module(btf)) {
16485 		btf_mod->module = btf_try_get_module(btf);
16486 		if (!btf_mod->module) {
16487 			err = -ENXIO;
16488 			goto err_put;
16489 		}
16490 	}
16491 
16492 	env->used_btf_cnt++;
16493 
16494 	return 0;
16495 err_put:
16496 	btf_put(btf);
16497 	return err;
16498 }
16499 
16500 static bool is_tracing_prog_type(enum bpf_prog_type type)
16501 {
16502 	switch (type) {
16503 	case BPF_PROG_TYPE_KPROBE:
16504 	case BPF_PROG_TYPE_TRACEPOINT:
16505 	case BPF_PROG_TYPE_PERF_EVENT:
16506 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16507 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16508 		return true;
16509 	default:
16510 		return false;
16511 	}
16512 }
16513 
16514 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16515 					struct bpf_map *map,
16516 					struct bpf_prog *prog)
16517 
16518 {
16519 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16520 
16521 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16522 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16523 		if (is_tracing_prog_type(prog_type)) {
16524 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16525 			return -EINVAL;
16526 		}
16527 	}
16528 
16529 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16530 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16531 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16532 			return -EINVAL;
16533 		}
16534 
16535 		if (is_tracing_prog_type(prog_type)) {
16536 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16537 			return -EINVAL;
16538 		}
16539 
16540 		if (prog->aux->sleepable) {
16541 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16542 			return -EINVAL;
16543 		}
16544 	}
16545 
16546 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16547 		if (is_tracing_prog_type(prog_type)) {
16548 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16549 			return -EINVAL;
16550 		}
16551 	}
16552 
16553 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16554 	    !bpf_offload_prog_map_match(prog, map)) {
16555 		verbose(env, "offload device mismatch between prog and map\n");
16556 		return -EINVAL;
16557 	}
16558 
16559 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16560 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16561 		return -EINVAL;
16562 	}
16563 
16564 	if (prog->aux->sleepable)
16565 		switch (map->map_type) {
16566 		case BPF_MAP_TYPE_HASH:
16567 		case BPF_MAP_TYPE_LRU_HASH:
16568 		case BPF_MAP_TYPE_ARRAY:
16569 		case BPF_MAP_TYPE_PERCPU_HASH:
16570 		case BPF_MAP_TYPE_PERCPU_ARRAY:
16571 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16572 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16573 		case BPF_MAP_TYPE_HASH_OF_MAPS:
16574 		case BPF_MAP_TYPE_RINGBUF:
16575 		case BPF_MAP_TYPE_USER_RINGBUF:
16576 		case BPF_MAP_TYPE_INODE_STORAGE:
16577 		case BPF_MAP_TYPE_SK_STORAGE:
16578 		case BPF_MAP_TYPE_TASK_STORAGE:
16579 		case BPF_MAP_TYPE_CGRP_STORAGE:
16580 			break;
16581 		default:
16582 			verbose(env,
16583 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16584 			return -EINVAL;
16585 		}
16586 
16587 	return 0;
16588 }
16589 
16590 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16591 {
16592 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16593 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16594 }
16595 
16596 /* find and rewrite pseudo imm in ld_imm64 instructions:
16597  *
16598  * 1. if it accesses map FD, replace it with actual map pointer.
16599  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16600  *
16601  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16602  */
16603 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16604 {
16605 	struct bpf_insn *insn = env->prog->insnsi;
16606 	int insn_cnt = env->prog->len;
16607 	int i, j, err;
16608 
16609 	err = bpf_prog_calc_tag(env->prog);
16610 	if (err)
16611 		return err;
16612 
16613 	for (i = 0; i < insn_cnt; i++, insn++) {
16614 		if (BPF_CLASS(insn->code) == BPF_LDX &&
16615 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16616 			verbose(env, "BPF_LDX uses reserved fields\n");
16617 			return -EINVAL;
16618 		}
16619 
16620 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16621 			struct bpf_insn_aux_data *aux;
16622 			struct bpf_map *map;
16623 			struct fd f;
16624 			u64 addr;
16625 			u32 fd;
16626 
16627 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
16628 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16629 			    insn[1].off != 0) {
16630 				verbose(env, "invalid bpf_ld_imm64 insn\n");
16631 				return -EINVAL;
16632 			}
16633 
16634 			if (insn[0].src_reg == 0)
16635 				/* valid generic load 64-bit imm */
16636 				goto next_insn;
16637 
16638 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16639 				aux = &env->insn_aux_data[i];
16640 				err = check_pseudo_btf_id(env, insn, aux);
16641 				if (err)
16642 					return err;
16643 				goto next_insn;
16644 			}
16645 
16646 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16647 				aux = &env->insn_aux_data[i];
16648 				aux->ptr_type = PTR_TO_FUNC;
16649 				goto next_insn;
16650 			}
16651 
16652 			/* In final convert_pseudo_ld_imm64() step, this is
16653 			 * converted into regular 64-bit imm load insn.
16654 			 */
16655 			switch (insn[0].src_reg) {
16656 			case BPF_PSEUDO_MAP_VALUE:
16657 			case BPF_PSEUDO_MAP_IDX_VALUE:
16658 				break;
16659 			case BPF_PSEUDO_MAP_FD:
16660 			case BPF_PSEUDO_MAP_IDX:
16661 				if (insn[1].imm == 0)
16662 					break;
16663 				fallthrough;
16664 			default:
16665 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16666 				return -EINVAL;
16667 			}
16668 
16669 			switch (insn[0].src_reg) {
16670 			case BPF_PSEUDO_MAP_IDX_VALUE:
16671 			case BPF_PSEUDO_MAP_IDX:
16672 				if (bpfptr_is_null(env->fd_array)) {
16673 					verbose(env, "fd_idx without fd_array is invalid\n");
16674 					return -EPROTO;
16675 				}
16676 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
16677 							    insn[0].imm * sizeof(fd),
16678 							    sizeof(fd)))
16679 					return -EFAULT;
16680 				break;
16681 			default:
16682 				fd = insn[0].imm;
16683 				break;
16684 			}
16685 
16686 			f = fdget(fd);
16687 			map = __bpf_map_get(f);
16688 			if (IS_ERR(map)) {
16689 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
16690 					insn[0].imm);
16691 				return PTR_ERR(map);
16692 			}
16693 
16694 			err = check_map_prog_compatibility(env, map, env->prog);
16695 			if (err) {
16696 				fdput(f);
16697 				return err;
16698 			}
16699 
16700 			aux = &env->insn_aux_data[i];
16701 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16702 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16703 				addr = (unsigned long)map;
16704 			} else {
16705 				u32 off = insn[1].imm;
16706 
16707 				if (off >= BPF_MAX_VAR_OFF) {
16708 					verbose(env, "direct value offset of %u is not allowed\n", off);
16709 					fdput(f);
16710 					return -EINVAL;
16711 				}
16712 
16713 				if (!map->ops->map_direct_value_addr) {
16714 					verbose(env, "no direct value access support for this map type\n");
16715 					fdput(f);
16716 					return -EINVAL;
16717 				}
16718 
16719 				err = map->ops->map_direct_value_addr(map, &addr, off);
16720 				if (err) {
16721 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16722 						map->value_size, off);
16723 					fdput(f);
16724 					return err;
16725 				}
16726 
16727 				aux->map_off = off;
16728 				addr += off;
16729 			}
16730 
16731 			insn[0].imm = (u32)addr;
16732 			insn[1].imm = addr >> 32;
16733 
16734 			/* check whether we recorded this map already */
16735 			for (j = 0; j < env->used_map_cnt; j++) {
16736 				if (env->used_maps[j] == map) {
16737 					aux->map_index = j;
16738 					fdput(f);
16739 					goto next_insn;
16740 				}
16741 			}
16742 
16743 			if (env->used_map_cnt >= MAX_USED_MAPS) {
16744 				fdput(f);
16745 				return -E2BIG;
16746 			}
16747 
16748 			/* hold the map. If the program is rejected by verifier,
16749 			 * the map will be released by release_maps() or it
16750 			 * will be used by the valid program until it's unloaded
16751 			 * and all maps are released in free_used_maps()
16752 			 */
16753 			bpf_map_inc(map);
16754 
16755 			aux->map_index = env->used_map_cnt;
16756 			env->used_maps[env->used_map_cnt++] = map;
16757 
16758 			if (bpf_map_is_cgroup_storage(map) &&
16759 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
16760 				verbose(env, "only one cgroup storage of each type is allowed\n");
16761 				fdput(f);
16762 				return -EBUSY;
16763 			}
16764 
16765 			fdput(f);
16766 next_insn:
16767 			insn++;
16768 			i++;
16769 			continue;
16770 		}
16771 
16772 		/* Basic sanity check before we invest more work here. */
16773 		if (!bpf_opcode_in_insntable(insn->code)) {
16774 			verbose(env, "unknown opcode %02x\n", insn->code);
16775 			return -EINVAL;
16776 		}
16777 	}
16778 
16779 	/* now all pseudo BPF_LD_IMM64 instructions load valid
16780 	 * 'struct bpf_map *' into a register instead of user map_fd.
16781 	 * These pointers will be used later by verifier to validate map access.
16782 	 */
16783 	return 0;
16784 }
16785 
16786 /* drop refcnt of maps used by the rejected program */
16787 static void release_maps(struct bpf_verifier_env *env)
16788 {
16789 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
16790 			     env->used_map_cnt);
16791 }
16792 
16793 /* drop refcnt of maps used by the rejected program */
16794 static void release_btfs(struct bpf_verifier_env *env)
16795 {
16796 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16797 			     env->used_btf_cnt);
16798 }
16799 
16800 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16801 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16802 {
16803 	struct bpf_insn *insn = env->prog->insnsi;
16804 	int insn_cnt = env->prog->len;
16805 	int i;
16806 
16807 	for (i = 0; i < insn_cnt; i++, insn++) {
16808 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16809 			continue;
16810 		if (insn->src_reg == BPF_PSEUDO_FUNC)
16811 			continue;
16812 		insn->src_reg = 0;
16813 	}
16814 }
16815 
16816 /* single env->prog->insni[off] instruction was replaced with the range
16817  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
16818  * [0, off) and [off, end) to new locations, so the patched range stays zero
16819  */
16820 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16821 				 struct bpf_insn_aux_data *new_data,
16822 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
16823 {
16824 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16825 	struct bpf_insn *insn = new_prog->insnsi;
16826 	u32 old_seen = old_data[off].seen;
16827 	u32 prog_len;
16828 	int i;
16829 
16830 	/* aux info at OFF always needs adjustment, no matter fast path
16831 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16832 	 * original insn at old prog.
16833 	 */
16834 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16835 
16836 	if (cnt == 1)
16837 		return;
16838 	prog_len = new_prog->len;
16839 
16840 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16841 	memcpy(new_data + off + cnt - 1, old_data + off,
16842 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16843 	for (i = off; i < off + cnt - 1; i++) {
16844 		/* Expand insni[off]'s seen count to the patched range. */
16845 		new_data[i].seen = old_seen;
16846 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
16847 	}
16848 	env->insn_aux_data = new_data;
16849 	vfree(old_data);
16850 }
16851 
16852 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16853 {
16854 	int i;
16855 
16856 	if (len == 1)
16857 		return;
16858 	/* NOTE: fake 'exit' subprog should be updated as well. */
16859 	for (i = 0; i <= env->subprog_cnt; i++) {
16860 		if (env->subprog_info[i].start <= off)
16861 			continue;
16862 		env->subprog_info[i].start += len - 1;
16863 	}
16864 }
16865 
16866 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16867 {
16868 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16869 	int i, sz = prog->aux->size_poke_tab;
16870 	struct bpf_jit_poke_descriptor *desc;
16871 
16872 	for (i = 0; i < sz; i++) {
16873 		desc = &tab[i];
16874 		if (desc->insn_idx <= off)
16875 			continue;
16876 		desc->insn_idx += len - 1;
16877 	}
16878 }
16879 
16880 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16881 					    const struct bpf_insn *patch, u32 len)
16882 {
16883 	struct bpf_prog *new_prog;
16884 	struct bpf_insn_aux_data *new_data = NULL;
16885 
16886 	if (len > 1) {
16887 		new_data = vzalloc(array_size(env->prog->len + len - 1,
16888 					      sizeof(struct bpf_insn_aux_data)));
16889 		if (!new_data)
16890 			return NULL;
16891 	}
16892 
16893 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
16894 	if (IS_ERR(new_prog)) {
16895 		if (PTR_ERR(new_prog) == -ERANGE)
16896 			verbose(env,
16897 				"insn %d cannot be patched due to 16-bit range\n",
16898 				env->insn_aux_data[off].orig_idx);
16899 		vfree(new_data);
16900 		return NULL;
16901 	}
16902 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
16903 	adjust_subprog_starts(env, off, len);
16904 	adjust_poke_descs(new_prog, off, len);
16905 	return new_prog;
16906 }
16907 
16908 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16909 					      u32 off, u32 cnt)
16910 {
16911 	int i, j;
16912 
16913 	/* find first prog starting at or after off (first to remove) */
16914 	for (i = 0; i < env->subprog_cnt; i++)
16915 		if (env->subprog_info[i].start >= off)
16916 			break;
16917 	/* find first prog starting at or after off + cnt (first to stay) */
16918 	for (j = i; j < env->subprog_cnt; j++)
16919 		if (env->subprog_info[j].start >= off + cnt)
16920 			break;
16921 	/* if j doesn't start exactly at off + cnt, we are just removing
16922 	 * the front of previous prog
16923 	 */
16924 	if (env->subprog_info[j].start != off + cnt)
16925 		j--;
16926 
16927 	if (j > i) {
16928 		struct bpf_prog_aux *aux = env->prog->aux;
16929 		int move;
16930 
16931 		/* move fake 'exit' subprog as well */
16932 		move = env->subprog_cnt + 1 - j;
16933 
16934 		memmove(env->subprog_info + i,
16935 			env->subprog_info + j,
16936 			sizeof(*env->subprog_info) * move);
16937 		env->subprog_cnt -= j - i;
16938 
16939 		/* remove func_info */
16940 		if (aux->func_info) {
16941 			move = aux->func_info_cnt - j;
16942 
16943 			memmove(aux->func_info + i,
16944 				aux->func_info + j,
16945 				sizeof(*aux->func_info) * move);
16946 			aux->func_info_cnt -= j - i;
16947 			/* func_info->insn_off is set after all code rewrites,
16948 			 * in adjust_btf_func() - no need to adjust
16949 			 */
16950 		}
16951 	} else {
16952 		/* convert i from "first prog to remove" to "first to adjust" */
16953 		if (env->subprog_info[i].start == off)
16954 			i++;
16955 	}
16956 
16957 	/* update fake 'exit' subprog as well */
16958 	for (; i <= env->subprog_cnt; i++)
16959 		env->subprog_info[i].start -= cnt;
16960 
16961 	return 0;
16962 }
16963 
16964 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16965 				      u32 cnt)
16966 {
16967 	struct bpf_prog *prog = env->prog;
16968 	u32 i, l_off, l_cnt, nr_linfo;
16969 	struct bpf_line_info *linfo;
16970 
16971 	nr_linfo = prog->aux->nr_linfo;
16972 	if (!nr_linfo)
16973 		return 0;
16974 
16975 	linfo = prog->aux->linfo;
16976 
16977 	/* find first line info to remove, count lines to be removed */
16978 	for (i = 0; i < nr_linfo; i++)
16979 		if (linfo[i].insn_off >= off)
16980 			break;
16981 
16982 	l_off = i;
16983 	l_cnt = 0;
16984 	for (; i < nr_linfo; i++)
16985 		if (linfo[i].insn_off < off + cnt)
16986 			l_cnt++;
16987 		else
16988 			break;
16989 
16990 	/* First live insn doesn't match first live linfo, it needs to "inherit"
16991 	 * last removed linfo.  prog is already modified, so prog->len == off
16992 	 * means no live instructions after (tail of the program was removed).
16993 	 */
16994 	if (prog->len != off && l_cnt &&
16995 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16996 		l_cnt--;
16997 		linfo[--i].insn_off = off + cnt;
16998 	}
16999 
17000 	/* remove the line info which refer to the removed instructions */
17001 	if (l_cnt) {
17002 		memmove(linfo + l_off, linfo + i,
17003 			sizeof(*linfo) * (nr_linfo - i));
17004 
17005 		prog->aux->nr_linfo -= l_cnt;
17006 		nr_linfo = prog->aux->nr_linfo;
17007 	}
17008 
17009 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17010 	for (i = l_off; i < nr_linfo; i++)
17011 		linfo[i].insn_off -= cnt;
17012 
17013 	/* fix up all subprogs (incl. 'exit') which start >= off */
17014 	for (i = 0; i <= env->subprog_cnt; i++)
17015 		if (env->subprog_info[i].linfo_idx > l_off) {
17016 			/* program may have started in the removed region but
17017 			 * may not be fully removed
17018 			 */
17019 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17020 				env->subprog_info[i].linfo_idx -= l_cnt;
17021 			else
17022 				env->subprog_info[i].linfo_idx = l_off;
17023 		}
17024 
17025 	return 0;
17026 }
17027 
17028 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17029 {
17030 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17031 	unsigned int orig_prog_len = env->prog->len;
17032 	int err;
17033 
17034 	if (bpf_prog_is_offloaded(env->prog->aux))
17035 		bpf_prog_offload_remove_insns(env, off, cnt);
17036 
17037 	err = bpf_remove_insns(env->prog, off, cnt);
17038 	if (err)
17039 		return err;
17040 
17041 	err = adjust_subprog_starts_after_remove(env, off, cnt);
17042 	if (err)
17043 		return err;
17044 
17045 	err = bpf_adj_linfo_after_remove(env, off, cnt);
17046 	if (err)
17047 		return err;
17048 
17049 	memmove(aux_data + off,	aux_data + off + cnt,
17050 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
17051 
17052 	return 0;
17053 }
17054 
17055 /* The verifier does more data flow analysis than llvm and will not
17056  * explore branches that are dead at run time. Malicious programs can
17057  * have dead code too. Therefore replace all dead at-run-time code
17058  * with 'ja -1'.
17059  *
17060  * Just nops are not optimal, e.g. if they would sit at the end of the
17061  * program and through another bug we would manage to jump there, then
17062  * we'd execute beyond program memory otherwise. Returning exception
17063  * code also wouldn't work since we can have subprogs where the dead
17064  * code could be located.
17065  */
17066 static void sanitize_dead_code(struct bpf_verifier_env *env)
17067 {
17068 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17069 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17070 	struct bpf_insn *insn = env->prog->insnsi;
17071 	const int insn_cnt = env->prog->len;
17072 	int i;
17073 
17074 	for (i = 0; i < insn_cnt; i++) {
17075 		if (aux_data[i].seen)
17076 			continue;
17077 		memcpy(insn + i, &trap, sizeof(trap));
17078 		aux_data[i].zext_dst = false;
17079 	}
17080 }
17081 
17082 static bool insn_is_cond_jump(u8 code)
17083 {
17084 	u8 op;
17085 
17086 	if (BPF_CLASS(code) == BPF_JMP32)
17087 		return true;
17088 
17089 	if (BPF_CLASS(code) != BPF_JMP)
17090 		return false;
17091 
17092 	op = BPF_OP(code);
17093 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17094 }
17095 
17096 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17097 {
17098 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17099 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17100 	struct bpf_insn *insn = env->prog->insnsi;
17101 	const int insn_cnt = env->prog->len;
17102 	int i;
17103 
17104 	for (i = 0; i < insn_cnt; i++, insn++) {
17105 		if (!insn_is_cond_jump(insn->code))
17106 			continue;
17107 
17108 		if (!aux_data[i + 1].seen)
17109 			ja.off = insn->off;
17110 		else if (!aux_data[i + 1 + insn->off].seen)
17111 			ja.off = 0;
17112 		else
17113 			continue;
17114 
17115 		if (bpf_prog_is_offloaded(env->prog->aux))
17116 			bpf_prog_offload_replace_insn(env, i, &ja);
17117 
17118 		memcpy(insn, &ja, sizeof(ja));
17119 	}
17120 }
17121 
17122 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17123 {
17124 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17125 	int insn_cnt = env->prog->len;
17126 	int i, err;
17127 
17128 	for (i = 0; i < insn_cnt; i++) {
17129 		int j;
17130 
17131 		j = 0;
17132 		while (i + j < insn_cnt && !aux_data[i + j].seen)
17133 			j++;
17134 		if (!j)
17135 			continue;
17136 
17137 		err = verifier_remove_insns(env, i, j);
17138 		if (err)
17139 			return err;
17140 		insn_cnt = env->prog->len;
17141 	}
17142 
17143 	return 0;
17144 }
17145 
17146 static int opt_remove_nops(struct bpf_verifier_env *env)
17147 {
17148 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17149 	struct bpf_insn *insn = env->prog->insnsi;
17150 	int insn_cnt = env->prog->len;
17151 	int i, err;
17152 
17153 	for (i = 0; i < insn_cnt; i++) {
17154 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17155 			continue;
17156 
17157 		err = verifier_remove_insns(env, i, 1);
17158 		if (err)
17159 			return err;
17160 		insn_cnt--;
17161 		i--;
17162 	}
17163 
17164 	return 0;
17165 }
17166 
17167 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17168 					 const union bpf_attr *attr)
17169 {
17170 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17171 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17172 	int i, patch_len, delta = 0, len = env->prog->len;
17173 	struct bpf_insn *insns = env->prog->insnsi;
17174 	struct bpf_prog *new_prog;
17175 	bool rnd_hi32;
17176 
17177 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17178 	zext_patch[1] = BPF_ZEXT_REG(0);
17179 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17180 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17181 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17182 	for (i = 0; i < len; i++) {
17183 		int adj_idx = i + delta;
17184 		struct bpf_insn insn;
17185 		int load_reg;
17186 
17187 		insn = insns[adj_idx];
17188 		load_reg = insn_def_regno(&insn);
17189 		if (!aux[adj_idx].zext_dst) {
17190 			u8 code, class;
17191 			u32 imm_rnd;
17192 
17193 			if (!rnd_hi32)
17194 				continue;
17195 
17196 			code = insn.code;
17197 			class = BPF_CLASS(code);
17198 			if (load_reg == -1)
17199 				continue;
17200 
17201 			/* NOTE: arg "reg" (the fourth one) is only used for
17202 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17203 			 *       here.
17204 			 */
17205 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17206 				if (class == BPF_LD &&
17207 				    BPF_MODE(code) == BPF_IMM)
17208 					i++;
17209 				continue;
17210 			}
17211 
17212 			/* ctx load could be transformed into wider load. */
17213 			if (class == BPF_LDX &&
17214 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17215 				continue;
17216 
17217 			imm_rnd = get_random_u32();
17218 			rnd_hi32_patch[0] = insn;
17219 			rnd_hi32_patch[1].imm = imm_rnd;
17220 			rnd_hi32_patch[3].dst_reg = load_reg;
17221 			patch = rnd_hi32_patch;
17222 			patch_len = 4;
17223 			goto apply_patch_buffer;
17224 		}
17225 
17226 		/* Add in an zero-extend instruction if a) the JIT has requested
17227 		 * it or b) it's a CMPXCHG.
17228 		 *
17229 		 * The latter is because: BPF_CMPXCHG always loads a value into
17230 		 * R0, therefore always zero-extends. However some archs'
17231 		 * equivalent instruction only does this load when the
17232 		 * comparison is successful. This detail of CMPXCHG is
17233 		 * orthogonal to the general zero-extension behaviour of the
17234 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17235 		 */
17236 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17237 			continue;
17238 
17239 		/* Zero-extension is done by the caller. */
17240 		if (bpf_pseudo_kfunc_call(&insn))
17241 			continue;
17242 
17243 		if (WARN_ON(load_reg == -1)) {
17244 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17245 			return -EFAULT;
17246 		}
17247 
17248 		zext_patch[0] = insn;
17249 		zext_patch[1].dst_reg = load_reg;
17250 		zext_patch[1].src_reg = load_reg;
17251 		patch = zext_patch;
17252 		patch_len = 2;
17253 apply_patch_buffer:
17254 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17255 		if (!new_prog)
17256 			return -ENOMEM;
17257 		env->prog = new_prog;
17258 		insns = new_prog->insnsi;
17259 		aux = env->insn_aux_data;
17260 		delta += patch_len - 1;
17261 	}
17262 
17263 	return 0;
17264 }
17265 
17266 /* convert load instructions that access fields of a context type into a
17267  * sequence of instructions that access fields of the underlying structure:
17268  *     struct __sk_buff    -> struct sk_buff
17269  *     struct bpf_sock_ops -> struct sock
17270  */
17271 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17272 {
17273 	const struct bpf_verifier_ops *ops = env->ops;
17274 	int i, cnt, size, ctx_field_size, delta = 0;
17275 	const int insn_cnt = env->prog->len;
17276 	struct bpf_insn insn_buf[16], *insn;
17277 	u32 target_size, size_default, off;
17278 	struct bpf_prog *new_prog;
17279 	enum bpf_access_type type;
17280 	bool is_narrower_load;
17281 
17282 	if (ops->gen_prologue || env->seen_direct_write) {
17283 		if (!ops->gen_prologue) {
17284 			verbose(env, "bpf verifier is misconfigured\n");
17285 			return -EINVAL;
17286 		}
17287 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17288 					env->prog);
17289 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17290 			verbose(env, "bpf verifier is misconfigured\n");
17291 			return -EINVAL;
17292 		} else if (cnt) {
17293 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17294 			if (!new_prog)
17295 				return -ENOMEM;
17296 
17297 			env->prog = new_prog;
17298 			delta += cnt - 1;
17299 		}
17300 	}
17301 
17302 	if (bpf_prog_is_offloaded(env->prog->aux))
17303 		return 0;
17304 
17305 	insn = env->prog->insnsi + delta;
17306 
17307 	for (i = 0; i < insn_cnt; i++, insn++) {
17308 		bpf_convert_ctx_access_t convert_ctx_access;
17309 
17310 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17311 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17312 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17313 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17314 			type = BPF_READ;
17315 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17316 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17317 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17318 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17319 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17320 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17321 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17322 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17323 			type = BPF_WRITE;
17324 		} else {
17325 			continue;
17326 		}
17327 
17328 		if (type == BPF_WRITE &&
17329 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17330 			struct bpf_insn patch[] = {
17331 				*insn,
17332 				BPF_ST_NOSPEC(),
17333 			};
17334 
17335 			cnt = ARRAY_SIZE(patch);
17336 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17337 			if (!new_prog)
17338 				return -ENOMEM;
17339 
17340 			delta    += cnt - 1;
17341 			env->prog = new_prog;
17342 			insn      = new_prog->insnsi + i + delta;
17343 			continue;
17344 		}
17345 
17346 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17347 		case PTR_TO_CTX:
17348 			if (!ops->convert_ctx_access)
17349 				continue;
17350 			convert_ctx_access = ops->convert_ctx_access;
17351 			break;
17352 		case PTR_TO_SOCKET:
17353 		case PTR_TO_SOCK_COMMON:
17354 			convert_ctx_access = bpf_sock_convert_ctx_access;
17355 			break;
17356 		case PTR_TO_TCP_SOCK:
17357 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17358 			break;
17359 		case PTR_TO_XDP_SOCK:
17360 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17361 			break;
17362 		case PTR_TO_BTF_ID:
17363 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17364 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17365 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17366 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17367 		 * any faults for loads into such types. BPF_WRITE is disallowed
17368 		 * for this case.
17369 		 */
17370 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17371 			if (type == BPF_READ) {
17372 				insn->code = BPF_LDX | BPF_PROBE_MEM |
17373 					BPF_SIZE((insn)->code);
17374 				env->prog->aux->num_exentries++;
17375 			}
17376 			continue;
17377 		default:
17378 			continue;
17379 		}
17380 
17381 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17382 		size = BPF_LDST_BYTES(insn);
17383 
17384 		/* If the read access is a narrower load of the field,
17385 		 * convert to a 4/8-byte load, to minimum program type specific
17386 		 * convert_ctx_access changes. If conversion is successful,
17387 		 * we will apply proper mask to the result.
17388 		 */
17389 		is_narrower_load = size < ctx_field_size;
17390 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17391 		off = insn->off;
17392 		if (is_narrower_load) {
17393 			u8 size_code;
17394 
17395 			if (type == BPF_WRITE) {
17396 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17397 				return -EINVAL;
17398 			}
17399 
17400 			size_code = BPF_H;
17401 			if (ctx_field_size == 4)
17402 				size_code = BPF_W;
17403 			else if (ctx_field_size == 8)
17404 				size_code = BPF_DW;
17405 
17406 			insn->off = off & ~(size_default - 1);
17407 			insn->code = BPF_LDX | BPF_MEM | size_code;
17408 		}
17409 
17410 		target_size = 0;
17411 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17412 					 &target_size);
17413 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17414 		    (ctx_field_size && !target_size)) {
17415 			verbose(env, "bpf verifier is misconfigured\n");
17416 			return -EINVAL;
17417 		}
17418 
17419 		if (is_narrower_load && size < target_size) {
17420 			u8 shift = bpf_ctx_narrow_access_offset(
17421 				off, size, size_default) * 8;
17422 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17423 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17424 				return -EINVAL;
17425 			}
17426 			if (ctx_field_size <= 4) {
17427 				if (shift)
17428 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17429 									insn->dst_reg,
17430 									shift);
17431 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17432 								(1 << size * 8) - 1);
17433 			} else {
17434 				if (shift)
17435 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17436 									insn->dst_reg,
17437 									shift);
17438 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17439 								(1ULL << size * 8) - 1);
17440 			}
17441 		}
17442 
17443 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17444 		if (!new_prog)
17445 			return -ENOMEM;
17446 
17447 		delta += cnt - 1;
17448 
17449 		/* keep walking new program and skip insns we just inserted */
17450 		env->prog = new_prog;
17451 		insn      = new_prog->insnsi + i + delta;
17452 	}
17453 
17454 	return 0;
17455 }
17456 
17457 static int jit_subprogs(struct bpf_verifier_env *env)
17458 {
17459 	struct bpf_prog *prog = env->prog, **func, *tmp;
17460 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17461 	struct bpf_map *map_ptr;
17462 	struct bpf_insn *insn;
17463 	void *old_bpf_func;
17464 	int err, num_exentries;
17465 
17466 	if (env->subprog_cnt <= 1)
17467 		return 0;
17468 
17469 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17470 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17471 			continue;
17472 
17473 		/* Upon error here we cannot fall back to interpreter but
17474 		 * need a hard reject of the program. Thus -EFAULT is
17475 		 * propagated in any case.
17476 		 */
17477 		subprog = find_subprog(env, i + insn->imm + 1);
17478 		if (subprog < 0) {
17479 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17480 				  i + insn->imm + 1);
17481 			return -EFAULT;
17482 		}
17483 		/* temporarily remember subprog id inside insn instead of
17484 		 * aux_data, since next loop will split up all insns into funcs
17485 		 */
17486 		insn->off = subprog;
17487 		/* remember original imm in case JIT fails and fallback
17488 		 * to interpreter will be needed
17489 		 */
17490 		env->insn_aux_data[i].call_imm = insn->imm;
17491 		/* point imm to __bpf_call_base+1 from JITs point of view */
17492 		insn->imm = 1;
17493 		if (bpf_pseudo_func(insn))
17494 			/* jit (e.g. x86_64) may emit fewer instructions
17495 			 * if it learns a u32 imm is the same as a u64 imm.
17496 			 * Force a non zero here.
17497 			 */
17498 			insn[1].imm = 1;
17499 	}
17500 
17501 	err = bpf_prog_alloc_jited_linfo(prog);
17502 	if (err)
17503 		goto out_undo_insn;
17504 
17505 	err = -ENOMEM;
17506 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17507 	if (!func)
17508 		goto out_undo_insn;
17509 
17510 	for (i = 0; i < env->subprog_cnt; i++) {
17511 		subprog_start = subprog_end;
17512 		subprog_end = env->subprog_info[i + 1].start;
17513 
17514 		len = subprog_end - subprog_start;
17515 		/* bpf_prog_run() doesn't call subprogs directly,
17516 		 * hence main prog stats include the runtime of subprogs.
17517 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17518 		 * func[i]->stats will never be accessed and stays NULL
17519 		 */
17520 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17521 		if (!func[i])
17522 			goto out_free;
17523 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17524 		       len * sizeof(struct bpf_insn));
17525 		func[i]->type = prog->type;
17526 		func[i]->len = len;
17527 		if (bpf_prog_calc_tag(func[i]))
17528 			goto out_free;
17529 		func[i]->is_func = 1;
17530 		func[i]->aux->func_idx = i;
17531 		/* Below members will be freed only at prog->aux */
17532 		func[i]->aux->btf = prog->aux->btf;
17533 		func[i]->aux->func_info = prog->aux->func_info;
17534 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17535 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17536 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17537 
17538 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17539 			struct bpf_jit_poke_descriptor *poke;
17540 
17541 			poke = &prog->aux->poke_tab[j];
17542 			if (poke->insn_idx < subprog_end &&
17543 			    poke->insn_idx >= subprog_start)
17544 				poke->aux = func[i]->aux;
17545 		}
17546 
17547 		func[i]->aux->name[0] = 'F';
17548 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17549 		func[i]->jit_requested = 1;
17550 		func[i]->blinding_requested = prog->blinding_requested;
17551 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17552 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17553 		func[i]->aux->linfo = prog->aux->linfo;
17554 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17555 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17556 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17557 		num_exentries = 0;
17558 		insn = func[i]->insnsi;
17559 		for (j = 0; j < func[i]->len; j++, insn++) {
17560 			if (BPF_CLASS(insn->code) == BPF_LDX &&
17561 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
17562 				num_exentries++;
17563 		}
17564 		func[i]->aux->num_exentries = num_exentries;
17565 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17566 		func[i] = bpf_int_jit_compile(func[i]);
17567 		if (!func[i]->jited) {
17568 			err = -ENOTSUPP;
17569 			goto out_free;
17570 		}
17571 		cond_resched();
17572 	}
17573 
17574 	/* at this point all bpf functions were successfully JITed
17575 	 * now populate all bpf_calls with correct addresses and
17576 	 * run last pass of JIT
17577 	 */
17578 	for (i = 0; i < env->subprog_cnt; i++) {
17579 		insn = func[i]->insnsi;
17580 		for (j = 0; j < func[i]->len; j++, insn++) {
17581 			if (bpf_pseudo_func(insn)) {
17582 				subprog = insn->off;
17583 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17584 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17585 				continue;
17586 			}
17587 			if (!bpf_pseudo_call(insn))
17588 				continue;
17589 			subprog = insn->off;
17590 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17591 		}
17592 
17593 		/* we use the aux data to keep a list of the start addresses
17594 		 * of the JITed images for each function in the program
17595 		 *
17596 		 * for some architectures, such as powerpc64, the imm field
17597 		 * might not be large enough to hold the offset of the start
17598 		 * address of the callee's JITed image from __bpf_call_base
17599 		 *
17600 		 * in such cases, we can lookup the start address of a callee
17601 		 * by using its subprog id, available from the off field of
17602 		 * the call instruction, as an index for this list
17603 		 */
17604 		func[i]->aux->func = func;
17605 		func[i]->aux->func_cnt = env->subprog_cnt;
17606 	}
17607 	for (i = 0; i < env->subprog_cnt; i++) {
17608 		old_bpf_func = func[i]->bpf_func;
17609 		tmp = bpf_int_jit_compile(func[i]);
17610 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17611 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17612 			err = -ENOTSUPP;
17613 			goto out_free;
17614 		}
17615 		cond_resched();
17616 	}
17617 
17618 	/* finally lock prog and jit images for all functions and
17619 	 * populate kallsysm. Begin at the first subprogram, since
17620 	 * bpf_prog_load will add the kallsyms for the main program.
17621 	 */
17622 	for (i = 1; i < env->subprog_cnt; i++) {
17623 		bpf_prog_lock_ro(func[i]);
17624 		bpf_prog_kallsyms_add(func[i]);
17625 	}
17626 
17627 	/* Last step: make now unused interpreter insns from main
17628 	 * prog consistent for later dump requests, so they can
17629 	 * later look the same as if they were interpreted only.
17630 	 */
17631 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17632 		if (bpf_pseudo_func(insn)) {
17633 			insn[0].imm = env->insn_aux_data[i].call_imm;
17634 			insn[1].imm = insn->off;
17635 			insn->off = 0;
17636 			continue;
17637 		}
17638 		if (!bpf_pseudo_call(insn))
17639 			continue;
17640 		insn->off = env->insn_aux_data[i].call_imm;
17641 		subprog = find_subprog(env, i + insn->off + 1);
17642 		insn->imm = subprog;
17643 	}
17644 
17645 	prog->jited = 1;
17646 	prog->bpf_func = func[0]->bpf_func;
17647 	prog->jited_len = func[0]->jited_len;
17648 	prog->aux->extable = func[0]->aux->extable;
17649 	prog->aux->num_exentries = func[0]->aux->num_exentries;
17650 	prog->aux->func = func;
17651 	prog->aux->func_cnt = env->subprog_cnt;
17652 	bpf_prog_jit_attempt_done(prog);
17653 	return 0;
17654 out_free:
17655 	/* We failed JIT'ing, so at this point we need to unregister poke
17656 	 * descriptors from subprogs, so that kernel is not attempting to
17657 	 * patch it anymore as we're freeing the subprog JIT memory.
17658 	 */
17659 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17660 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17661 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17662 	}
17663 	/* At this point we're guaranteed that poke descriptors are not
17664 	 * live anymore. We can just unlink its descriptor table as it's
17665 	 * released with the main prog.
17666 	 */
17667 	for (i = 0; i < env->subprog_cnt; i++) {
17668 		if (!func[i])
17669 			continue;
17670 		func[i]->aux->poke_tab = NULL;
17671 		bpf_jit_free(func[i]);
17672 	}
17673 	kfree(func);
17674 out_undo_insn:
17675 	/* cleanup main prog to be interpreted */
17676 	prog->jit_requested = 0;
17677 	prog->blinding_requested = 0;
17678 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17679 		if (!bpf_pseudo_call(insn))
17680 			continue;
17681 		insn->off = 0;
17682 		insn->imm = env->insn_aux_data[i].call_imm;
17683 	}
17684 	bpf_prog_jit_attempt_done(prog);
17685 	return err;
17686 }
17687 
17688 static int fixup_call_args(struct bpf_verifier_env *env)
17689 {
17690 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17691 	struct bpf_prog *prog = env->prog;
17692 	struct bpf_insn *insn = prog->insnsi;
17693 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17694 	int i, depth;
17695 #endif
17696 	int err = 0;
17697 
17698 	if (env->prog->jit_requested &&
17699 	    !bpf_prog_is_offloaded(env->prog->aux)) {
17700 		err = jit_subprogs(env);
17701 		if (err == 0)
17702 			return 0;
17703 		if (err == -EFAULT)
17704 			return err;
17705 	}
17706 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17707 	if (has_kfunc_call) {
17708 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17709 		return -EINVAL;
17710 	}
17711 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17712 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
17713 		 * have to be rejected, since interpreter doesn't support them yet.
17714 		 */
17715 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17716 		return -EINVAL;
17717 	}
17718 	for (i = 0; i < prog->len; i++, insn++) {
17719 		if (bpf_pseudo_func(insn)) {
17720 			/* When JIT fails the progs with callback calls
17721 			 * have to be rejected, since interpreter doesn't support them yet.
17722 			 */
17723 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
17724 			return -EINVAL;
17725 		}
17726 
17727 		if (!bpf_pseudo_call(insn))
17728 			continue;
17729 		depth = get_callee_stack_depth(env, insn, i);
17730 		if (depth < 0)
17731 			return depth;
17732 		bpf_patch_call_args(insn, depth);
17733 	}
17734 	err = 0;
17735 #endif
17736 	return err;
17737 }
17738 
17739 /* replace a generic kfunc with a specialized version if necessary */
17740 static void specialize_kfunc(struct bpf_verifier_env *env,
17741 			     u32 func_id, u16 offset, unsigned long *addr)
17742 {
17743 	struct bpf_prog *prog = env->prog;
17744 	bool seen_direct_write;
17745 	void *xdp_kfunc;
17746 	bool is_rdonly;
17747 
17748 	if (bpf_dev_bound_kfunc_id(func_id)) {
17749 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17750 		if (xdp_kfunc) {
17751 			*addr = (unsigned long)xdp_kfunc;
17752 			return;
17753 		}
17754 		/* fallback to default kfunc when not supported by netdev */
17755 	}
17756 
17757 	if (offset)
17758 		return;
17759 
17760 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17761 		seen_direct_write = env->seen_direct_write;
17762 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17763 
17764 		if (is_rdonly)
17765 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17766 
17767 		/* restore env->seen_direct_write to its original value, since
17768 		 * may_access_direct_pkt_data mutates it
17769 		 */
17770 		env->seen_direct_write = seen_direct_write;
17771 	}
17772 }
17773 
17774 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17775 					    u16 struct_meta_reg,
17776 					    u16 node_offset_reg,
17777 					    struct bpf_insn *insn,
17778 					    struct bpf_insn *insn_buf,
17779 					    int *cnt)
17780 {
17781 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17782 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17783 
17784 	insn_buf[0] = addr[0];
17785 	insn_buf[1] = addr[1];
17786 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17787 	insn_buf[3] = *insn;
17788 	*cnt = 4;
17789 }
17790 
17791 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17792 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17793 {
17794 	const struct bpf_kfunc_desc *desc;
17795 
17796 	if (!insn->imm) {
17797 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17798 		return -EINVAL;
17799 	}
17800 
17801 	*cnt = 0;
17802 
17803 	/* insn->imm has the btf func_id. Replace it with an offset relative to
17804 	 * __bpf_call_base, unless the JIT needs to call functions that are
17805 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
17806 	 */
17807 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17808 	if (!desc) {
17809 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17810 			insn->imm);
17811 		return -EFAULT;
17812 	}
17813 
17814 	if (!bpf_jit_supports_far_kfunc_call())
17815 		insn->imm = BPF_CALL_IMM(desc->addr);
17816 	if (insn->off)
17817 		return 0;
17818 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17819 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17820 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17821 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17822 
17823 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17824 		insn_buf[1] = addr[0];
17825 		insn_buf[2] = addr[1];
17826 		insn_buf[3] = *insn;
17827 		*cnt = 4;
17828 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
17829 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
17830 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17831 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17832 
17833 		insn_buf[0] = addr[0];
17834 		insn_buf[1] = addr[1];
17835 		insn_buf[2] = *insn;
17836 		*cnt = 3;
17837 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
17838 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
17839 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17840 		int struct_meta_reg = BPF_REG_3;
17841 		int node_offset_reg = BPF_REG_4;
17842 
17843 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
17844 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17845 			struct_meta_reg = BPF_REG_4;
17846 			node_offset_reg = BPF_REG_5;
17847 		}
17848 
17849 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
17850 						node_offset_reg, insn, insn_buf, cnt);
17851 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17852 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17853 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17854 		*cnt = 1;
17855 	}
17856 	return 0;
17857 }
17858 
17859 /* Do various post-verification rewrites in a single program pass.
17860  * These rewrites simplify JIT and interpreter implementations.
17861  */
17862 static int do_misc_fixups(struct bpf_verifier_env *env)
17863 {
17864 	struct bpf_prog *prog = env->prog;
17865 	enum bpf_attach_type eatype = prog->expected_attach_type;
17866 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17867 	struct bpf_insn *insn = prog->insnsi;
17868 	const struct bpf_func_proto *fn;
17869 	const int insn_cnt = prog->len;
17870 	const struct bpf_map_ops *ops;
17871 	struct bpf_insn_aux_data *aux;
17872 	struct bpf_insn insn_buf[16];
17873 	struct bpf_prog *new_prog;
17874 	struct bpf_map *map_ptr;
17875 	int i, ret, cnt, delta = 0;
17876 
17877 	for (i = 0; i < insn_cnt; i++, insn++) {
17878 		/* Make divide-by-zero exceptions impossible. */
17879 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17880 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17881 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
17882 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
17883 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
17884 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17885 			struct bpf_insn *patchlet;
17886 			struct bpf_insn chk_and_div[] = {
17887 				/* [R,W]x div 0 -> 0 */
17888 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17889 					     BPF_JNE | BPF_K, insn->src_reg,
17890 					     0, 2, 0),
17891 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17892 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17893 				*insn,
17894 			};
17895 			struct bpf_insn chk_and_mod[] = {
17896 				/* [R,W]x mod 0 -> [R,W]x */
17897 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17898 					     BPF_JEQ | BPF_K, insn->src_reg,
17899 					     0, 1 + (is64 ? 0 : 1), 0),
17900 				*insn,
17901 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17902 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
17903 			};
17904 
17905 			patchlet = isdiv ? chk_and_div : chk_and_mod;
17906 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
17907 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
17908 
17909 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
17910 			if (!new_prog)
17911 				return -ENOMEM;
17912 
17913 			delta    += cnt - 1;
17914 			env->prog = prog = new_prog;
17915 			insn      = new_prog->insnsi + i + delta;
17916 			continue;
17917 		}
17918 
17919 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
17920 		if (BPF_CLASS(insn->code) == BPF_LD &&
17921 		    (BPF_MODE(insn->code) == BPF_ABS ||
17922 		     BPF_MODE(insn->code) == BPF_IND)) {
17923 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
17924 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17925 				verbose(env, "bpf verifier is misconfigured\n");
17926 				return -EINVAL;
17927 			}
17928 
17929 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17930 			if (!new_prog)
17931 				return -ENOMEM;
17932 
17933 			delta    += cnt - 1;
17934 			env->prog = prog = new_prog;
17935 			insn      = new_prog->insnsi + i + delta;
17936 			continue;
17937 		}
17938 
17939 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
17940 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17941 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17942 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17943 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
17944 			struct bpf_insn *patch = &insn_buf[0];
17945 			bool issrc, isneg, isimm;
17946 			u32 off_reg;
17947 
17948 			aux = &env->insn_aux_data[i + delta];
17949 			if (!aux->alu_state ||
17950 			    aux->alu_state == BPF_ALU_NON_POINTER)
17951 				continue;
17952 
17953 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17954 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17955 				BPF_ALU_SANITIZE_SRC;
17956 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
17957 
17958 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
17959 			if (isimm) {
17960 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17961 			} else {
17962 				if (isneg)
17963 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17964 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17965 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17966 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17967 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17968 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17969 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17970 			}
17971 			if (!issrc)
17972 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17973 			insn->src_reg = BPF_REG_AX;
17974 			if (isneg)
17975 				insn->code = insn->code == code_add ?
17976 					     code_sub : code_add;
17977 			*patch++ = *insn;
17978 			if (issrc && isneg && !isimm)
17979 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17980 			cnt = patch - insn_buf;
17981 
17982 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17983 			if (!new_prog)
17984 				return -ENOMEM;
17985 
17986 			delta    += cnt - 1;
17987 			env->prog = prog = new_prog;
17988 			insn      = new_prog->insnsi + i + delta;
17989 			continue;
17990 		}
17991 
17992 		if (insn->code != (BPF_JMP | BPF_CALL))
17993 			continue;
17994 		if (insn->src_reg == BPF_PSEUDO_CALL)
17995 			continue;
17996 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17997 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
17998 			if (ret)
17999 				return ret;
18000 			if (cnt == 0)
18001 				continue;
18002 
18003 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18004 			if (!new_prog)
18005 				return -ENOMEM;
18006 
18007 			delta	 += cnt - 1;
18008 			env->prog = prog = new_prog;
18009 			insn	  = new_prog->insnsi + i + delta;
18010 			continue;
18011 		}
18012 
18013 		if (insn->imm == BPF_FUNC_get_route_realm)
18014 			prog->dst_needed = 1;
18015 		if (insn->imm == BPF_FUNC_get_prandom_u32)
18016 			bpf_user_rnd_init_once();
18017 		if (insn->imm == BPF_FUNC_override_return)
18018 			prog->kprobe_override = 1;
18019 		if (insn->imm == BPF_FUNC_tail_call) {
18020 			/* If we tail call into other programs, we
18021 			 * cannot make any assumptions since they can
18022 			 * be replaced dynamically during runtime in
18023 			 * the program array.
18024 			 */
18025 			prog->cb_access = 1;
18026 			if (!allow_tail_call_in_subprogs(env))
18027 				prog->aux->stack_depth = MAX_BPF_STACK;
18028 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18029 
18030 			/* mark bpf_tail_call as different opcode to avoid
18031 			 * conditional branch in the interpreter for every normal
18032 			 * call and to prevent accidental JITing by JIT compiler
18033 			 * that doesn't support bpf_tail_call yet
18034 			 */
18035 			insn->imm = 0;
18036 			insn->code = BPF_JMP | BPF_TAIL_CALL;
18037 
18038 			aux = &env->insn_aux_data[i + delta];
18039 			if (env->bpf_capable && !prog->blinding_requested &&
18040 			    prog->jit_requested &&
18041 			    !bpf_map_key_poisoned(aux) &&
18042 			    !bpf_map_ptr_poisoned(aux) &&
18043 			    !bpf_map_ptr_unpriv(aux)) {
18044 				struct bpf_jit_poke_descriptor desc = {
18045 					.reason = BPF_POKE_REASON_TAIL_CALL,
18046 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18047 					.tail_call.key = bpf_map_key_immediate(aux),
18048 					.insn_idx = i + delta,
18049 				};
18050 
18051 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
18052 				if (ret < 0) {
18053 					verbose(env, "adding tail call poke descriptor failed\n");
18054 					return ret;
18055 				}
18056 
18057 				insn->imm = ret + 1;
18058 				continue;
18059 			}
18060 
18061 			if (!bpf_map_ptr_unpriv(aux))
18062 				continue;
18063 
18064 			/* instead of changing every JIT dealing with tail_call
18065 			 * emit two extra insns:
18066 			 * if (index >= max_entries) goto out;
18067 			 * index &= array->index_mask;
18068 			 * to avoid out-of-bounds cpu speculation
18069 			 */
18070 			if (bpf_map_ptr_poisoned(aux)) {
18071 				verbose(env, "tail_call abusing map_ptr\n");
18072 				return -EINVAL;
18073 			}
18074 
18075 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18076 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18077 						  map_ptr->max_entries, 2);
18078 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18079 						    container_of(map_ptr,
18080 								 struct bpf_array,
18081 								 map)->index_mask);
18082 			insn_buf[2] = *insn;
18083 			cnt = 3;
18084 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18085 			if (!new_prog)
18086 				return -ENOMEM;
18087 
18088 			delta    += cnt - 1;
18089 			env->prog = prog = new_prog;
18090 			insn      = new_prog->insnsi + i + delta;
18091 			continue;
18092 		}
18093 
18094 		if (insn->imm == BPF_FUNC_timer_set_callback) {
18095 			/* The verifier will process callback_fn as many times as necessary
18096 			 * with different maps and the register states prepared by
18097 			 * set_timer_callback_state will be accurate.
18098 			 *
18099 			 * The following use case is valid:
18100 			 *   map1 is shared by prog1, prog2, prog3.
18101 			 *   prog1 calls bpf_timer_init for some map1 elements
18102 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
18103 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
18104 			 *   prog3 calls bpf_timer_start for some map1 elements.
18105 			 *     Those that were not both bpf_timer_init-ed and
18106 			 *     bpf_timer_set_callback-ed will return -EINVAL.
18107 			 */
18108 			struct bpf_insn ld_addrs[2] = {
18109 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18110 			};
18111 
18112 			insn_buf[0] = ld_addrs[0];
18113 			insn_buf[1] = ld_addrs[1];
18114 			insn_buf[2] = *insn;
18115 			cnt = 3;
18116 
18117 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18118 			if (!new_prog)
18119 				return -ENOMEM;
18120 
18121 			delta    += cnt - 1;
18122 			env->prog = prog = new_prog;
18123 			insn      = new_prog->insnsi + i + delta;
18124 			goto patch_call_imm;
18125 		}
18126 
18127 		if (is_storage_get_function(insn->imm)) {
18128 			if (!env->prog->aux->sleepable ||
18129 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
18130 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18131 			else
18132 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18133 			insn_buf[1] = *insn;
18134 			cnt = 2;
18135 
18136 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18137 			if (!new_prog)
18138 				return -ENOMEM;
18139 
18140 			delta += cnt - 1;
18141 			env->prog = prog = new_prog;
18142 			insn = new_prog->insnsi + i + delta;
18143 			goto patch_call_imm;
18144 		}
18145 
18146 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18147 		 * and other inlining handlers are currently limited to 64 bit
18148 		 * only.
18149 		 */
18150 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18151 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
18152 		     insn->imm == BPF_FUNC_map_update_elem ||
18153 		     insn->imm == BPF_FUNC_map_delete_elem ||
18154 		     insn->imm == BPF_FUNC_map_push_elem   ||
18155 		     insn->imm == BPF_FUNC_map_pop_elem    ||
18156 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18157 		     insn->imm == BPF_FUNC_redirect_map    ||
18158 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18159 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18160 			aux = &env->insn_aux_data[i + delta];
18161 			if (bpf_map_ptr_poisoned(aux))
18162 				goto patch_call_imm;
18163 
18164 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18165 			ops = map_ptr->ops;
18166 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18167 			    ops->map_gen_lookup) {
18168 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18169 				if (cnt == -EOPNOTSUPP)
18170 					goto patch_map_ops_generic;
18171 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18172 					verbose(env, "bpf verifier is misconfigured\n");
18173 					return -EINVAL;
18174 				}
18175 
18176 				new_prog = bpf_patch_insn_data(env, i + delta,
18177 							       insn_buf, cnt);
18178 				if (!new_prog)
18179 					return -ENOMEM;
18180 
18181 				delta    += cnt - 1;
18182 				env->prog = prog = new_prog;
18183 				insn      = new_prog->insnsi + i + delta;
18184 				continue;
18185 			}
18186 
18187 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18188 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18189 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18190 				     (long (*)(struct bpf_map *map, void *key))NULL));
18191 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18192 				     (long (*)(struct bpf_map *map, void *key, void *value,
18193 					      u64 flags))NULL));
18194 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18195 				     (long (*)(struct bpf_map *map, void *value,
18196 					      u64 flags))NULL));
18197 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18198 				     (long (*)(struct bpf_map *map, void *value))NULL));
18199 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18200 				     (long (*)(struct bpf_map *map, void *value))NULL));
18201 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18202 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18203 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18204 				     (long (*)(struct bpf_map *map,
18205 					      bpf_callback_t callback_fn,
18206 					      void *callback_ctx,
18207 					      u64 flags))NULL));
18208 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18209 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18210 
18211 patch_map_ops_generic:
18212 			switch (insn->imm) {
18213 			case BPF_FUNC_map_lookup_elem:
18214 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18215 				continue;
18216 			case BPF_FUNC_map_update_elem:
18217 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18218 				continue;
18219 			case BPF_FUNC_map_delete_elem:
18220 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18221 				continue;
18222 			case BPF_FUNC_map_push_elem:
18223 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18224 				continue;
18225 			case BPF_FUNC_map_pop_elem:
18226 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18227 				continue;
18228 			case BPF_FUNC_map_peek_elem:
18229 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18230 				continue;
18231 			case BPF_FUNC_redirect_map:
18232 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18233 				continue;
18234 			case BPF_FUNC_for_each_map_elem:
18235 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18236 				continue;
18237 			case BPF_FUNC_map_lookup_percpu_elem:
18238 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18239 				continue;
18240 			}
18241 
18242 			goto patch_call_imm;
18243 		}
18244 
18245 		/* Implement bpf_jiffies64 inline. */
18246 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18247 		    insn->imm == BPF_FUNC_jiffies64) {
18248 			struct bpf_insn ld_jiffies_addr[2] = {
18249 				BPF_LD_IMM64(BPF_REG_0,
18250 					     (unsigned long)&jiffies),
18251 			};
18252 
18253 			insn_buf[0] = ld_jiffies_addr[0];
18254 			insn_buf[1] = ld_jiffies_addr[1];
18255 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18256 						  BPF_REG_0, 0);
18257 			cnt = 3;
18258 
18259 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18260 						       cnt);
18261 			if (!new_prog)
18262 				return -ENOMEM;
18263 
18264 			delta    += cnt - 1;
18265 			env->prog = prog = new_prog;
18266 			insn      = new_prog->insnsi + i + delta;
18267 			continue;
18268 		}
18269 
18270 		/* Implement bpf_get_func_arg inline. */
18271 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18272 		    insn->imm == BPF_FUNC_get_func_arg) {
18273 			/* Load nr_args from ctx - 8 */
18274 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18275 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18276 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18277 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18278 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18279 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18280 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18281 			insn_buf[7] = BPF_JMP_A(1);
18282 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18283 			cnt = 9;
18284 
18285 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18286 			if (!new_prog)
18287 				return -ENOMEM;
18288 
18289 			delta    += cnt - 1;
18290 			env->prog = prog = new_prog;
18291 			insn      = new_prog->insnsi + i + delta;
18292 			continue;
18293 		}
18294 
18295 		/* Implement bpf_get_func_ret inline. */
18296 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18297 		    insn->imm == BPF_FUNC_get_func_ret) {
18298 			if (eatype == BPF_TRACE_FEXIT ||
18299 			    eatype == BPF_MODIFY_RETURN) {
18300 				/* Load nr_args from ctx - 8 */
18301 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18302 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18303 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18304 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18305 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18306 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18307 				cnt = 6;
18308 			} else {
18309 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18310 				cnt = 1;
18311 			}
18312 
18313 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18314 			if (!new_prog)
18315 				return -ENOMEM;
18316 
18317 			delta    += cnt - 1;
18318 			env->prog = prog = new_prog;
18319 			insn      = new_prog->insnsi + i + delta;
18320 			continue;
18321 		}
18322 
18323 		/* Implement get_func_arg_cnt inline. */
18324 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18325 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18326 			/* Load nr_args from ctx - 8 */
18327 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18328 
18329 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18330 			if (!new_prog)
18331 				return -ENOMEM;
18332 
18333 			env->prog = prog = new_prog;
18334 			insn      = new_prog->insnsi + i + delta;
18335 			continue;
18336 		}
18337 
18338 		/* Implement bpf_get_func_ip inline. */
18339 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18340 		    insn->imm == BPF_FUNC_get_func_ip) {
18341 			/* Load IP address from ctx - 16 */
18342 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18343 
18344 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18345 			if (!new_prog)
18346 				return -ENOMEM;
18347 
18348 			env->prog = prog = new_prog;
18349 			insn      = new_prog->insnsi + i + delta;
18350 			continue;
18351 		}
18352 
18353 patch_call_imm:
18354 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18355 		/* all functions that have prototype and verifier allowed
18356 		 * programs to call them, must be real in-kernel functions
18357 		 */
18358 		if (!fn->func) {
18359 			verbose(env,
18360 				"kernel subsystem misconfigured func %s#%d\n",
18361 				func_id_name(insn->imm), insn->imm);
18362 			return -EFAULT;
18363 		}
18364 		insn->imm = fn->func - __bpf_call_base;
18365 	}
18366 
18367 	/* Since poke tab is now finalized, publish aux to tracker. */
18368 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18369 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18370 		if (!map_ptr->ops->map_poke_track ||
18371 		    !map_ptr->ops->map_poke_untrack ||
18372 		    !map_ptr->ops->map_poke_run) {
18373 			verbose(env, "bpf verifier is misconfigured\n");
18374 			return -EINVAL;
18375 		}
18376 
18377 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18378 		if (ret < 0) {
18379 			verbose(env, "tracking tail call prog failed\n");
18380 			return ret;
18381 		}
18382 	}
18383 
18384 	sort_kfunc_descs_by_imm_off(env->prog);
18385 
18386 	return 0;
18387 }
18388 
18389 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18390 					int position,
18391 					s32 stack_base,
18392 					u32 callback_subprogno,
18393 					u32 *cnt)
18394 {
18395 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18396 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18397 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18398 	int reg_loop_max = BPF_REG_6;
18399 	int reg_loop_cnt = BPF_REG_7;
18400 	int reg_loop_ctx = BPF_REG_8;
18401 
18402 	struct bpf_prog *new_prog;
18403 	u32 callback_start;
18404 	u32 call_insn_offset;
18405 	s32 callback_offset;
18406 
18407 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18408 	 * be careful to modify this code in sync.
18409 	 */
18410 	struct bpf_insn insn_buf[] = {
18411 		/* Return error and jump to the end of the patch if
18412 		 * expected number of iterations is too big.
18413 		 */
18414 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18415 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18416 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18417 		/* spill R6, R7, R8 to use these as loop vars */
18418 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18419 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18420 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18421 		/* initialize loop vars */
18422 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18423 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18424 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18425 		/* loop header,
18426 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18427 		 */
18428 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18429 		/* callback call,
18430 		 * correct callback offset would be set after patching
18431 		 */
18432 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18433 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18434 		BPF_CALL_REL(0),
18435 		/* increment loop counter */
18436 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18437 		/* jump to loop header if callback returned 0 */
18438 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18439 		/* return value of bpf_loop,
18440 		 * set R0 to the number of iterations
18441 		 */
18442 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18443 		/* restore original values of R6, R7, R8 */
18444 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18445 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18446 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18447 	};
18448 
18449 	*cnt = ARRAY_SIZE(insn_buf);
18450 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18451 	if (!new_prog)
18452 		return new_prog;
18453 
18454 	/* callback start is known only after patching */
18455 	callback_start = env->subprog_info[callback_subprogno].start;
18456 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18457 	call_insn_offset = position + 12;
18458 	callback_offset = callback_start - call_insn_offset - 1;
18459 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18460 
18461 	return new_prog;
18462 }
18463 
18464 static bool is_bpf_loop_call(struct bpf_insn *insn)
18465 {
18466 	return insn->code == (BPF_JMP | BPF_CALL) &&
18467 		insn->src_reg == 0 &&
18468 		insn->imm == BPF_FUNC_loop;
18469 }
18470 
18471 /* For all sub-programs in the program (including main) check
18472  * insn_aux_data to see if there are bpf_loop calls that require
18473  * inlining. If such calls are found the calls are replaced with a
18474  * sequence of instructions produced by `inline_bpf_loop` function and
18475  * subprog stack_depth is increased by the size of 3 registers.
18476  * This stack space is used to spill values of the R6, R7, R8.  These
18477  * registers are used to store the loop bound, counter and context
18478  * variables.
18479  */
18480 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18481 {
18482 	struct bpf_subprog_info *subprogs = env->subprog_info;
18483 	int i, cur_subprog = 0, cnt, delta = 0;
18484 	struct bpf_insn *insn = env->prog->insnsi;
18485 	int insn_cnt = env->prog->len;
18486 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18487 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18488 	u16 stack_depth_extra = 0;
18489 
18490 	for (i = 0; i < insn_cnt; i++, insn++) {
18491 		struct bpf_loop_inline_state *inline_state =
18492 			&env->insn_aux_data[i + delta].loop_inline_state;
18493 
18494 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18495 			struct bpf_prog *new_prog;
18496 
18497 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18498 			new_prog = inline_bpf_loop(env,
18499 						   i + delta,
18500 						   -(stack_depth + stack_depth_extra),
18501 						   inline_state->callback_subprogno,
18502 						   &cnt);
18503 			if (!new_prog)
18504 				return -ENOMEM;
18505 
18506 			delta     += cnt - 1;
18507 			env->prog  = new_prog;
18508 			insn       = new_prog->insnsi + i + delta;
18509 		}
18510 
18511 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18512 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18513 			cur_subprog++;
18514 			stack_depth = subprogs[cur_subprog].stack_depth;
18515 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18516 			stack_depth_extra = 0;
18517 		}
18518 	}
18519 
18520 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18521 
18522 	return 0;
18523 }
18524 
18525 static void free_states(struct bpf_verifier_env *env)
18526 {
18527 	struct bpf_verifier_state_list *sl, *sln;
18528 	int i;
18529 
18530 	sl = env->free_list;
18531 	while (sl) {
18532 		sln = sl->next;
18533 		free_verifier_state(&sl->state, false);
18534 		kfree(sl);
18535 		sl = sln;
18536 	}
18537 	env->free_list = NULL;
18538 
18539 	if (!env->explored_states)
18540 		return;
18541 
18542 	for (i = 0; i < state_htab_size(env); i++) {
18543 		sl = env->explored_states[i];
18544 
18545 		while (sl) {
18546 			sln = sl->next;
18547 			free_verifier_state(&sl->state, false);
18548 			kfree(sl);
18549 			sl = sln;
18550 		}
18551 		env->explored_states[i] = NULL;
18552 	}
18553 }
18554 
18555 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18556 {
18557 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18558 	struct bpf_verifier_state *state;
18559 	struct bpf_reg_state *regs;
18560 	int ret, i;
18561 
18562 	env->prev_linfo = NULL;
18563 	env->pass_cnt++;
18564 
18565 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18566 	if (!state)
18567 		return -ENOMEM;
18568 	state->curframe = 0;
18569 	state->speculative = false;
18570 	state->branches = 1;
18571 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18572 	if (!state->frame[0]) {
18573 		kfree(state);
18574 		return -ENOMEM;
18575 	}
18576 	env->cur_state = state;
18577 	init_func_state(env, state->frame[0],
18578 			BPF_MAIN_FUNC /* callsite */,
18579 			0 /* frameno */,
18580 			subprog);
18581 	state->first_insn_idx = env->subprog_info[subprog].start;
18582 	state->last_insn_idx = -1;
18583 
18584 	regs = state->frame[state->curframe]->regs;
18585 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18586 		ret = btf_prepare_func_args(env, subprog, regs);
18587 		if (ret)
18588 			goto out;
18589 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18590 			if (regs[i].type == PTR_TO_CTX)
18591 				mark_reg_known_zero(env, regs, i);
18592 			else if (regs[i].type == SCALAR_VALUE)
18593 				mark_reg_unknown(env, regs, i);
18594 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
18595 				const u32 mem_size = regs[i].mem_size;
18596 
18597 				mark_reg_known_zero(env, regs, i);
18598 				regs[i].mem_size = mem_size;
18599 				regs[i].id = ++env->id_gen;
18600 			}
18601 		}
18602 	} else {
18603 		/* 1st arg to a function */
18604 		regs[BPF_REG_1].type = PTR_TO_CTX;
18605 		mark_reg_known_zero(env, regs, BPF_REG_1);
18606 		ret = btf_check_subprog_arg_match(env, subprog, regs);
18607 		if (ret == -EFAULT)
18608 			/* unlikely verifier bug. abort.
18609 			 * ret == 0 and ret < 0 are sadly acceptable for
18610 			 * main() function due to backward compatibility.
18611 			 * Like socket filter program may be written as:
18612 			 * int bpf_prog(struct pt_regs *ctx)
18613 			 * and never dereference that ctx in the program.
18614 			 * 'struct pt_regs' is a type mismatch for socket
18615 			 * filter that should be using 'struct __sk_buff'.
18616 			 */
18617 			goto out;
18618 	}
18619 
18620 	ret = do_check(env);
18621 out:
18622 	/* check for NULL is necessary, since cur_state can be freed inside
18623 	 * do_check() under memory pressure.
18624 	 */
18625 	if (env->cur_state) {
18626 		free_verifier_state(env->cur_state, true);
18627 		env->cur_state = NULL;
18628 	}
18629 	while (!pop_stack(env, NULL, NULL, false));
18630 	if (!ret && pop_log)
18631 		bpf_vlog_reset(&env->log, 0);
18632 	free_states(env);
18633 	return ret;
18634 }
18635 
18636 /* Verify all global functions in a BPF program one by one based on their BTF.
18637  * All global functions must pass verification. Otherwise the whole program is rejected.
18638  * Consider:
18639  * int bar(int);
18640  * int foo(int f)
18641  * {
18642  *    return bar(f);
18643  * }
18644  * int bar(int b)
18645  * {
18646  *    ...
18647  * }
18648  * foo() will be verified first for R1=any_scalar_value. During verification it
18649  * will be assumed that bar() already verified successfully and call to bar()
18650  * from foo() will be checked for type match only. Later bar() will be verified
18651  * independently to check that it's safe for R1=any_scalar_value.
18652  */
18653 static int do_check_subprogs(struct bpf_verifier_env *env)
18654 {
18655 	struct bpf_prog_aux *aux = env->prog->aux;
18656 	int i, ret;
18657 
18658 	if (!aux->func_info)
18659 		return 0;
18660 
18661 	for (i = 1; i < env->subprog_cnt; i++) {
18662 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18663 			continue;
18664 		env->insn_idx = env->subprog_info[i].start;
18665 		WARN_ON_ONCE(env->insn_idx == 0);
18666 		ret = do_check_common(env, i);
18667 		if (ret) {
18668 			return ret;
18669 		} else if (env->log.level & BPF_LOG_LEVEL) {
18670 			verbose(env,
18671 				"Func#%d is safe for any args that match its prototype\n",
18672 				i);
18673 		}
18674 	}
18675 	return 0;
18676 }
18677 
18678 static int do_check_main(struct bpf_verifier_env *env)
18679 {
18680 	int ret;
18681 
18682 	env->insn_idx = 0;
18683 	ret = do_check_common(env, 0);
18684 	if (!ret)
18685 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18686 	return ret;
18687 }
18688 
18689 
18690 static void print_verification_stats(struct bpf_verifier_env *env)
18691 {
18692 	int i;
18693 
18694 	if (env->log.level & BPF_LOG_STATS) {
18695 		verbose(env, "verification time %lld usec\n",
18696 			div_u64(env->verification_time, 1000));
18697 		verbose(env, "stack depth ");
18698 		for (i = 0; i < env->subprog_cnt; i++) {
18699 			u32 depth = env->subprog_info[i].stack_depth;
18700 
18701 			verbose(env, "%d", depth);
18702 			if (i + 1 < env->subprog_cnt)
18703 				verbose(env, "+");
18704 		}
18705 		verbose(env, "\n");
18706 	}
18707 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18708 		"total_states %d peak_states %d mark_read %d\n",
18709 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18710 		env->max_states_per_insn, env->total_states,
18711 		env->peak_states, env->longest_mark_read_walk);
18712 }
18713 
18714 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18715 {
18716 	const struct btf_type *t, *func_proto;
18717 	const struct bpf_struct_ops *st_ops;
18718 	const struct btf_member *member;
18719 	struct bpf_prog *prog = env->prog;
18720 	u32 btf_id, member_idx;
18721 	const char *mname;
18722 
18723 	if (!prog->gpl_compatible) {
18724 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18725 		return -EINVAL;
18726 	}
18727 
18728 	btf_id = prog->aux->attach_btf_id;
18729 	st_ops = bpf_struct_ops_find(btf_id);
18730 	if (!st_ops) {
18731 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18732 			btf_id);
18733 		return -ENOTSUPP;
18734 	}
18735 
18736 	t = st_ops->type;
18737 	member_idx = prog->expected_attach_type;
18738 	if (member_idx >= btf_type_vlen(t)) {
18739 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18740 			member_idx, st_ops->name);
18741 		return -EINVAL;
18742 	}
18743 
18744 	member = &btf_type_member(t)[member_idx];
18745 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18746 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18747 					       NULL);
18748 	if (!func_proto) {
18749 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18750 			mname, member_idx, st_ops->name);
18751 		return -EINVAL;
18752 	}
18753 
18754 	if (st_ops->check_member) {
18755 		int err = st_ops->check_member(t, member, prog);
18756 
18757 		if (err) {
18758 			verbose(env, "attach to unsupported member %s of struct %s\n",
18759 				mname, st_ops->name);
18760 			return err;
18761 		}
18762 	}
18763 
18764 	prog->aux->attach_func_proto = func_proto;
18765 	prog->aux->attach_func_name = mname;
18766 	env->ops = st_ops->verifier_ops;
18767 
18768 	return 0;
18769 }
18770 #define SECURITY_PREFIX "security_"
18771 
18772 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18773 {
18774 	if (within_error_injection_list(addr) ||
18775 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18776 		return 0;
18777 
18778 	return -EINVAL;
18779 }
18780 
18781 /* list of non-sleepable functions that are otherwise on
18782  * ALLOW_ERROR_INJECTION list
18783  */
18784 BTF_SET_START(btf_non_sleepable_error_inject)
18785 /* Three functions below can be called from sleepable and non-sleepable context.
18786  * Assume non-sleepable from bpf safety point of view.
18787  */
18788 BTF_ID(func, __filemap_add_folio)
18789 BTF_ID(func, should_fail_alloc_page)
18790 BTF_ID(func, should_failslab)
18791 BTF_SET_END(btf_non_sleepable_error_inject)
18792 
18793 static int check_non_sleepable_error_inject(u32 btf_id)
18794 {
18795 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18796 }
18797 
18798 int bpf_check_attach_target(struct bpf_verifier_log *log,
18799 			    const struct bpf_prog *prog,
18800 			    const struct bpf_prog *tgt_prog,
18801 			    u32 btf_id,
18802 			    struct bpf_attach_target_info *tgt_info)
18803 {
18804 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18805 	const char prefix[] = "btf_trace_";
18806 	int ret = 0, subprog = -1, i;
18807 	const struct btf_type *t;
18808 	bool conservative = true;
18809 	const char *tname;
18810 	struct btf *btf;
18811 	long addr = 0;
18812 	struct module *mod = NULL;
18813 
18814 	if (!btf_id) {
18815 		bpf_log(log, "Tracing programs must provide btf_id\n");
18816 		return -EINVAL;
18817 	}
18818 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18819 	if (!btf) {
18820 		bpf_log(log,
18821 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18822 		return -EINVAL;
18823 	}
18824 	t = btf_type_by_id(btf, btf_id);
18825 	if (!t) {
18826 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18827 		return -EINVAL;
18828 	}
18829 	tname = btf_name_by_offset(btf, t->name_off);
18830 	if (!tname) {
18831 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18832 		return -EINVAL;
18833 	}
18834 	if (tgt_prog) {
18835 		struct bpf_prog_aux *aux = tgt_prog->aux;
18836 
18837 		if (bpf_prog_is_dev_bound(prog->aux) &&
18838 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18839 			bpf_log(log, "Target program bound device mismatch");
18840 			return -EINVAL;
18841 		}
18842 
18843 		for (i = 0; i < aux->func_info_cnt; i++)
18844 			if (aux->func_info[i].type_id == btf_id) {
18845 				subprog = i;
18846 				break;
18847 			}
18848 		if (subprog == -1) {
18849 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
18850 			return -EINVAL;
18851 		}
18852 		conservative = aux->func_info_aux[subprog].unreliable;
18853 		if (prog_extension) {
18854 			if (conservative) {
18855 				bpf_log(log,
18856 					"Cannot replace static functions\n");
18857 				return -EINVAL;
18858 			}
18859 			if (!prog->jit_requested) {
18860 				bpf_log(log,
18861 					"Extension programs should be JITed\n");
18862 				return -EINVAL;
18863 			}
18864 		}
18865 		if (!tgt_prog->jited) {
18866 			bpf_log(log, "Can attach to only JITed progs\n");
18867 			return -EINVAL;
18868 		}
18869 		if (tgt_prog->type == prog->type) {
18870 			/* Cannot fentry/fexit another fentry/fexit program.
18871 			 * Cannot attach program extension to another extension.
18872 			 * It's ok to attach fentry/fexit to extension program.
18873 			 */
18874 			bpf_log(log, "Cannot recursively attach\n");
18875 			return -EINVAL;
18876 		}
18877 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18878 		    prog_extension &&
18879 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18880 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18881 			/* Program extensions can extend all program types
18882 			 * except fentry/fexit. The reason is the following.
18883 			 * The fentry/fexit programs are used for performance
18884 			 * analysis, stats and can be attached to any program
18885 			 * type except themselves. When extension program is
18886 			 * replacing XDP function it is necessary to allow
18887 			 * performance analysis of all functions. Both original
18888 			 * XDP program and its program extension. Hence
18889 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18890 			 * allowed. If extending of fentry/fexit was allowed it
18891 			 * would be possible to create long call chain
18892 			 * fentry->extension->fentry->extension beyond
18893 			 * reasonable stack size. Hence extending fentry is not
18894 			 * allowed.
18895 			 */
18896 			bpf_log(log, "Cannot extend fentry/fexit\n");
18897 			return -EINVAL;
18898 		}
18899 	} else {
18900 		if (prog_extension) {
18901 			bpf_log(log, "Cannot replace kernel functions\n");
18902 			return -EINVAL;
18903 		}
18904 	}
18905 
18906 	switch (prog->expected_attach_type) {
18907 	case BPF_TRACE_RAW_TP:
18908 		if (tgt_prog) {
18909 			bpf_log(log,
18910 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18911 			return -EINVAL;
18912 		}
18913 		if (!btf_type_is_typedef(t)) {
18914 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
18915 				btf_id);
18916 			return -EINVAL;
18917 		}
18918 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
18919 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
18920 				btf_id, tname);
18921 			return -EINVAL;
18922 		}
18923 		tname += sizeof(prefix) - 1;
18924 		t = btf_type_by_id(btf, t->type);
18925 		if (!btf_type_is_ptr(t))
18926 			/* should never happen in valid vmlinux build */
18927 			return -EINVAL;
18928 		t = btf_type_by_id(btf, t->type);
18929 		if (!btf_type_is_func_proto(t))
18930 			/* should never happen in valid vmlinux build */
18931 			return -EINVAL;
18932 
18933 		break;
18934 	case BPF_TRACE_ITER:
18935 		if (!btf_type_is_func(t)) {
18936 			bpf_log(log, "attach_btf_id %u is not a function\n",
18937 				btf_id);
18938 			return -EINVAL;
18939 		}
18940 		t = btf_type_by_id(btf, t->type);
18941 		if (!btf_type_is_func_proto(t))
18942 			return -EINVAL;
18943 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18944 		if (ret)
18945 			return ret;
18946 		break;
18947 	default:
18948 		if (!prog_extension)
18949 			return -EINVAL;
18950 		fallthrough;
18951 	case BPF_MODIFY_RETURN:
18952 	case BPF_LSM_MAC:
18953 	case BPF_LSM_CGROUP:
18954 	case BPF_TRACE_FENTRY:
18955 	case BPF_TRACE_FEXIT:
18956 		if (!btf_type_is_func(t)) {
18957 			bpf_log(log, "attach_btf_id %u is not a function\n",
18958 				btf_id);
18959 			return -EINVAL;
18960 		}
18961 		if (prog_extension &&
18962 		    btf_check_type_match(log, prog, btf, t))
18963 			return -EINVAL;
18964 		t = btf_type_by_id(btf, t->type);
18965 		if (!btf_type_is_func_proto(t))
18966 			return -EINVAL;
18967 
18968 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18969 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18970 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18971 			return -EINVAL;
18972 
18973 		if (tgt_prog && conservative)
18974 			t = NULL;
18975 
18976 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18977 		if (ret < 0)
18978 			return ret;
18979 
18980 		if (tgt_prog) {
18981 			if (subprog == 0)
18982 				addr = (long) tgt_prog->bpf_func;
18983 			else
18984 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
18985 		} else {
18986 			if (btf_is_module(btf)) {
18987 				mod = btf_try_get_module(btf);
18988 				if (mod)
18989 					addr = find_kallsyms_symbol_value(mod, tname);
18990 				else
18991 					addr = 0;
18992 			} else {
18993 				addr = kallsyms_lookup_name(tname);
18994 			}
18995 			if (!addr) {
18996 				module_put(mod);
18997 				bpf_log(log,
18998 					"The address of function %s cannot be found\n",
18999 					tname);
19000 				return -ENOENT;
19001 			}
19002 		}
19003 
19004 		if (prog->aux->sleepable) {
19005 			ret = -EINVAL;
19006 			switch (prog->type) {
19007 			case BPF_PROG_TYPE_TRACING:
19008 
19009 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
19010 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19011 				 */
19012 				if (!check_non_sleepable_error_inject(btf_id) &&
19013 				    within_error_injection_list(addr))
19014 					ret = 0;
19015 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
19016 				 * in the fmodret id set with the KF_SLEEPABLE flag.
19017 				 */
19018 				else {
19019 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19020 										prog);
19021 
19022 					if (flags && (*flags & KF_SLEEPABLE))
19023 						ret = 0;
19024 				}
19025 				break;
19026 			case BPF_PROG_TYPE_LSM:
19027 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
19028 				 * Only some of them are sleepable.
19029 				 */
19030 				if (bpf_lsm_is_sleepable_hook(btf_id))
19031 					ret = 0;
19032 				break;
19033 			default:
19034 				break;
19035 			}
19036 			if (ret) {
19037 				module_put(mod);
19038 				bpf_log(log, "%s is not sleepable\n", tname);
19039 				return ret;
19040 			}
19041 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19042 			if (tgt_prog) {
19043 				module_put(mod);
19044 				bpf_log(log, "can't modify return codes of BPF programs\n");
19045 				return -EINVAL;
19046 			}
19047 			ret = -EINVAL;
19048 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19049 			    !check_attach_modify_return(addr, tname))
19050 				ret = 0;
19051 			if (ret) {
19052 				module_put(mod);
19053 				bpf_log(log, "%s() is not modifiable\n", tname);
19054 				return ret;
19055 			}
19056 		}
19057 
19058 		break;
19059 	}
19060 	tgt_info->tgt_addr = addr;
19061 	tgt_info->tgt_name = tname;
19062 	tgt_info->tgt_type = t;
19063 	tgt_info->tgt_mod = mod;
19064 	return 0;
19065 }
19066 
19067 BTF_SET_START(btf_id_deny)
19068 BTF_ID_UNUSED
19069 #ifdef CONFIG_SMP
19070 BTF_ID(func, migrate_disable)
19071 BTF_ID(func, migrate_enable)
19072 #endif
19073 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19074 BTF_ID(func, rcu_read_unlock_strict)
19075 #endif
19076 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19077 BTF_ID(func, preempt_count_add)
19078 BTF_ID(func, preempt_count_sub)
19079 #endif
19080 #ifdef CONFIG_PREEMPT_RCU
19081 BTF_ID(func, __rcu_read_lock)
19082 BTF_ID(func, __rcu_read_unlock)
19083 #endif
19084 BTF_SET_END(btf_id_deny)
19085 
19086 static bool can_be_sleepable(struct bpf_prog *prog)
19087 {
19088 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19089 		switch (prog->expected_attach_type) {
19090 		case BPF_TRACE_FENTRY:
19091 		case BPF_TRACE_FEXIT:
19092 		case BPF_MODIFY_RETURN:
19093 		case BPF_TRACE_ITER:
19094 			return true;
19095 		default:
19096 			return false;
19097 		}
19098 	}
19099 	return prog->type == BPF_PROG_TYPE_LSM ||
19100 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19101 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19102 }
19103 
19104 static int check_attach_btf_id(struct bpf_verifier_env *env)
19105 {
19106 	struct bpf_prog *prog = env->prog;
19107 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19108 	struct bpf_attach_target_info tgt_info = {};
19109 	u32 btf_id = prog->aux->attach_btf_id;
19110 	struct bpf_trampoline *tr;
19111 	int ret;
19112 	u64 key;
19113 
19114 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19115 		if (prog->aux->sleepable)
19116 			/* attach_btf_id checked to be zero already */
19117 			return 0;
19118 		verbose(env, "Syscall programs can only be sleepable\n");
19119 		return -EINVAL;
19120 	}
19121 
19122 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19123 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19124 		return -EINVAL;
19125 	}
19126 
19127 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19128 		return check_struct_ops_btf_id(env);
19129 
19130 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19131 	    prog->type != BPF_PROG_TYPE_LSM &&
19132 	    prog->type != BPF_PROG_TYPE_EXT)
19133 		return 0;
19134 
19135 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19136 	if (ret)
19137 		return ret;
19138 
19139 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19140 		/* to make freplace equivalent to their targets, they need to
19141 		 * inherit env->ops and expected_attach_type for the rest of the
19142 		 * verification
19143 		 */
19144 		env->ops = bpf_verifier_ops[tgt_prog->type];
19145 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19146 	}
19147 
19148 	/* store info about the attachment target that will be used later */
19149 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19150 	prog->aux->attach_func_name = tgt_info.tgt_name;
19151 	prog->aux->mod = tgt_info.tgt_mod;
19152 
19153 	if (tgt_prog) {
19154 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19155 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19156 	}
19157 
19158 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19159 		prog->aux->attach_btf_trace = true;
19160 		return 0;
19161 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19162 		if (!bpf_iter_prog_supported(prog))
19163 			return -EINVAL;
19164 		return 0;
19165 	}
19166 
19167 	if (prog->type == BPF_PROG_TYPE_LSM) {
19168 		ret = bpf_lsm_verify_prog(&env->log, prog);
19169 		if (ret < 0)
19170 			return ret;
19171 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19172 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19173 		return -EINVAL;
19174 	}
19175 
19176 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19177 	tr = bpf_trampoline_get(key, &tgt_info);
19178 	if (!tr)
19179 		return -ENOMEM;
19180 
19181 	prog->aux->dst_trampoline = tr;
19182 	return 0;
19183 }
19184 
19185 struct btf *bpf_get_btf_vmlinux(void)
19186 {
19187 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19188 		mutex_lock(&bpf_verifier_lock);
19189 		if (!btf_vmlinux)
19190 			btf_vmlinux = btf_parse_vmlinux();
19191 		mutex_unlock(&bpf_verifier_lock);
19192 	}
19193 	return btf_vmlinux;
19194 }
19195 
19196 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19197 {
19198 	u64 start_time = ktime_get_ns();
19199 	struct bpf_verifier_env *env;
19200 	int i, len, ret = -EINVAL, err;
19201 	u32 log_true_size;
19202 	bool is_priv;
19203 
19204 	/* no program is valid */
19205 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19206 		return -EINVAL;
19207 
19208 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19209 	 * allocate/free it every time bpf_check() is called
19210 	 */
19211 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19212 	if (!env)
19213 		return -ENOMEM;
19214 
19215 	env->bt.env = env;
19216 
19217 	len = (*prog)->len;
19218 	env->insn_aux_data =
19219 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19220 	ret = -ENOMEM;
19221 	if (!env->insn_aux_data)
19222 		goto err_free_env;
19223 	for (i = 0; i < len; i++)
19224 		env->insn_aux_data[i].orig_idx = i;
19225 	env->prog = *prog;
19226 	env->ops = bpf_verifier_ops[env->prog->type];
19227 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19228 	is_priv = bpf_capable();
19229 
19230 	bpf_get_btf_vmlinux();
19231 
19232 	/* grab the mutex to protect few globals used by verifier */
19233 	if (!is_priv)
19234 		mutex_lock(&bpf_verifier_lock);
19235 
19236 	/* user could have requested verbose verifier output
19237 	 * and supplied buffer to store the verification trace
19238 	 */
19239 	ret = bpf_vlog_init(&env->log, attr->log_level,
19240 			    (char __user *) (unsigned long) attr->log_buf,
19241 			    attr->log_size);
19242 	if (ret)
19243 		goto err_unlock;
19244 
19245 	mark_verifier_state_clean(env);
19246 
19247 	if (IS_ERR(btf_vmlinux)) {
19248 		/* Either gcc or pahole or kernel are broken. */
19249 		verbose(env, "in-kernel BTF is malformed\n");
19250 		ret = PTR_ERR(btf_vmlinux);
19251 		goto skip_full_check;
19252 	}
19253 
19254 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19255 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19256 		env->strict_alignment = true;
19257 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19258 		env->strict_alignment = false;
19259 
19260 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19261 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19262 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19263 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19264 	env->bpf_capable = bpf_capable();
19265 
19266 	if (is_priv)
19267 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19268 
19269 	env->explored_states = kvcalloc(state_htab_size(env),
19270 				       sizeof(struct bpf_verifier_state_list *),
19271 				       GFP_USER);
19272 	ret = -ENOMEM;
19273 	if (!env->explored_states)
19274 		goto skip_full_check;
19275 
19276 	ret = add_subprog_and_kfunc(env);
19277 	if (ret < 0)
19278 		goto skip_full_check;
19279 
19280 	ret = check_subprogs(env);
19281 	if (ret < 0)
19282 		goto skip_full_check;
19283 
19284 	ret = check_btf_info(env, attr, uattr);
19285 	if (ret < 0)
19286 		goto skip_full_check;
19287 
19288 	ret = check_attach_btf_id(env);
19289 	if (ret)
19290 		goto skip_full_check;
19291 
19292 	ret = resolve_pseudo_ldimm64(env);
19293 	if (ret < 0)
19294 		goto skip_full_check;
19295 
19296 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19297 		ret = bpf_prog_offload_verifier_prep(env->prog);
19298 		if (ret)
19299 			goto skip_full_check;
19300 	}
19301 
19302 	ret = check_cfg(env);
19303 	if (ret < 0)
19304 		goto skip_full_check;
19305 
19306 	ret = do_check_subprogs(env);
19307 	ret = ret ?: do_check_main(env);
19308 
19309 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19310 		ret = bpf_prog_offload_finalize(env);
19311 
19312 skip_full_check:
19313 	kvfree(env->explored_states);
19314 
19315 	if (ret == 0)
19316 		ret = check_max_stack_depth(env);
19317 
19318 	/* instruction rewrites happen after this point */
19319 	if (ret == 0)
19320 		ret = optimize_bpf_loop(env);
19321 
19322 	if (is_priv) {
19323 		if (ret == 0)
19324 			opt_hard_wire_dead_code_branches(env);
19325 		if (ret == 0)
19326 			ret = opt_remove_dead_code(env);
19327 		if (ret == 0)
19328 			ret = opt_remove_nops(env);
19329 	} else {
19330 		if (ret == 0)
19331 			sanitize_dead_code(env);
19332 	}
19333 
19334 	if (ret == 0)
19335 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19336 		ret = convert_ctx_accesses(env);
19337 
19338 	if (ret == 0)
19339 		ret = do_misc_fixups(env);
19340 
19341 	/* do 32-bit optimization after insn patching has done so those patched
19342 	 * insns could be handled correctly.
19343 	 */
19344 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19345 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19346 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19347 								     : false;
19348 	}
19349 
19350 	if (ret == 0)
19351 		ret = fixup_call_args(env);
19352 
19353 	env->verification_time = ktime_get_ns() - start_time;
19354 	print_verification_stats(env);
19355 	env->prog->aux->verified_insns = env->insn_processed;
19356 
19357 	/* preserve original error even if log finalization is successful */
19358 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19359 	if (err)
19360 		ret = err;
19361 
19362 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19363 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19364 				  &log_true_size, sizeof(log_true_size))) {
19365 		ret = -EFAULT;
19366 		goto err_release_maps;
19367 	}
19368 
19369 	if (ret)
19370 		goto err_release_maps;
19371 
19372 	if (env->used_map_cnt) {
19373 		/* if program passed verifier, update used_maps in bpf_prog_info */
19374 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19375 							  sizeof(env->used_maps[0]),
19376 							  GFP_KERNEL);
19377 
19378 		if (!env->prog->aux->used_maps) {
19379 			ret = -ENOMEM;
19380 			goto err_release_maps;
19381 		}
19382 
19383 		memcpy(env->prog->aux->used_maps, env->used_maps,
19384 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19385 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19386 	}
19387 	if (env->used_btf_cnt) {
19388 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19389 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19390 							  sizeof(env->used_btfs[0]),
19391 							  GFP_KERNEL);
19392 		if (!env->prog->aux->used_btfs) {
19393 			ret = -ENOMEM;
19394 			goto err_release_maps;
19395 		}
19396 
19397 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19398 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19399 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19400 	}
19401 	if (env->used_map_cnt || env->used_btf_cnt) {
19402 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19403 		 * bpf_ld_imm64 instructions
19404 		 */
19405 		convert_pseudo_ld_imm64(env);
19406 	}
19407 
19408 	adjust_btf_func(env);
19409 
19410 err_release_maps:
19411 	if (!env->prog->aux->used_maps)
19412 		/* if we didn't copy map pointers into bpf_prog_info, release
19413 		 * them now. Otherwise free_used_maps() will release them.
19414 		 */
19415 		release_maps(env);
19416 	if (!env->prog->aux->used_btfs)
19417 		release_btfs(env);
19418 
19419 	/* extension progs temporarily inherit the attach_type of their targets
19420 	   for verification purposes, so set it back to zero before returning
19421 	 */
19422 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19423 		env->prog->expected_attach_type = 0;
19424 
19425 	*prog = env->prog;
19426 err_unlock:
19427 	if (!is_priv)
19428 		mutex_unlock(&bpf_verifier_lock);
19429 	vfree(env->insn_aux_data);
19430 err_free_env:
19431 	kfree(env);
19432 	return ret;
19433 }
19434