xref: /openbmc/linux/kernel/bpf/verifier.c (revision f4356947)
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 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4226 		   insn->imm != 0 && env->bpf_capable) {
4227 		struct bpf_reg_state fake_reg = {};
4228 
4229 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4230 		fake_reg.type = SCALAR_VALUE;
4231 		save_register_state(state, spi, &fake_reg, size);
4232 	} else if (reg && is_spillable_regtype(reg->type)) {
4233 		/* register containing pointer is being spilled into stack */
4234 		if (size != BPF_REG_SIZE) {
4235 			verbose_linfo(env, insn_idx, "; ");
4236 			verbose(env, "invalid size of register spill\n");
4237 			return -EACCES;
4238 		}
4239 		if (state != cur && reg->type == PTR_TO_STACK) {
4240 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4241 			return -EINVAL;
4242 		}
4243 		save_register_state(state, spi, reg, size);
4244 	} else {
4245 		u8 type = STACK_MISC;
4246 
4247 		/* regular write of data into stack destroys any spilled ptr */
4248 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4249 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4250 		if (is_stack_slot_special(&state->stack[spi]))
4251 			for (i = 0; i < BPF_REG_SIZE; i++)
4252 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4253 
4254 		/* only mark the slot as written if all 8 bytes were written
4255 		 * otherwise read propagation may incorrectly stop too soon
4256 		 * when stack slots are partially written.
4257 		 * This heuristic means that read propagation will be
4258 		 * conservative, since it will add reg_live_read marks
4259 		 * to stack slots all the way to first state when programs
4260 		 * writes+reads less than 8 bytes
4261 		 */
4262 		if (size == BPF_REG_SIZE)
4263 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4264 
4265 		/* when we zero initialize stack slots mark them as such */
4266 		if ((reg && register_is_null(reg)) ||
4267 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4268 			/* backtracking doesn't work for STACK_ZERO yet. */
4269 			err = mark_chain_precision(env, value_regno);
4270 			if (err)
4271 				return err;
4272 			type = STACK_ZERO;
4273 		}
4274 
4275 		/* Mark slots affected by this stack write. */
4276 		for (i = 0; i < size; i++)
4277 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4278 				type;
4279 	}
4280 	return 0;
4281 }
4282 
4283 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4284  * known to contain a variable offset.
4285  * This function checks whether the write is permitted and conservatively
4286  * tracks the effects of the write, considering that each stack slot in the
4287  * dynamic range is potentially written to.
4288  *
4289  * 'off' includes 'regno->off'.
4290  * 'value_regno' can be -1, meaning that an unknown value is being written to
4291  * the stack.
4292  *
4293  * Spilled pointers in range are not marked as written because we don't know
4294  * what's going to be actually written. This means that read propagation for
4295  * future reads cannot be terminated by this write.
4296  *
4297  * For privileged programs, uninitialized stack slots are considered
4298  * initialized by this write (even though we don't know exactly what offsets
4299  * are going to be written to). The idea is that we don't want the verifier to
4300  * reject future reads that access slots written to through variable offsets.
4301  */
4302 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4303 				     /* func where register points to */
4304 				     struct bpf_func_state *state,
4305 				     int ptr_regno, int off, int size,
4306 				     int value_regno, int insn_idx)
4307 {
4308 	struct bpf_func_state *cur; /* state of the current function */
4309 	int min_off, max_off;
4310 	int i, err;
4311 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4312 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4313 	bool writing_zero = false;
4314 	/* set if the fact that we're writing a zero is used to let any
4315 	 * stack slots remain STACK_ZERO
4316 	 */
4317 	bool zero_used = false;
4318 
4319 	cur = env->cur_state->frame[env->cur_state->curframe];
4320 	ptr_reg = &cur->regs[ptr_regno];
4321 	min_off = ptr_reg->smin_value + off;
4322 	max_off = ptr_reg->smax_value + off + size;
4323 	if (value_regno >= 0)
4324 		value_reg = &cur->regs[value_regno];
4325 	if ((value_reg && register_is_null(value_reg)) ||
4326 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4327 		writing_zero = true;
4328 
4329 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4330 	if (err)
4331 		return err;
4332 
4333 	for (i = min_off; i < max_off; i++) {
4334 		int spi;
4335 
4336 		spi = __get_spi(i);
4337 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4338 		if (err)
4339 			return err;
4340 	}
4341 
4342 	/* Variable offset writes destroy any spilled pointers in range. */
4343 	for (i = min_off; i < max_off; i++) {
4344 		u8 new_type, *stype;
4345 		int slot, spi;
4346 
4347 		slot = -i - 1;
4348 		spi = slot / BPF_REG_SIZE;
4349 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4350 		mark_stack_slot_scratched(env, spi);
4351 
4352 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4353 			/* Reject the write if range we may write to has not
4354 			 * been initialized beforehand. If we didn't reject
4355 			 * here, the ptr status would be erased below (even
4356 			 * though not all slots are actually overwritten),
4357 			 * possibly opening the door to leaks.
4358 			 *
4359 			 * We do however catch STACK_INVALID case below, and
4360 			 * only allow reading possibly uninitialized memory
4361 			 * later for CAP_PERFMON, as the write may not happen to
4362 			 * that slot.
4363 			 */
4364 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4365 				insn_idx, i);
4366 			return -EINVAL;
4367 		}
4368 
4369 		/* Erase all spilled pointers. */
4370 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4371 
4372 		/* Update the slot type. */
4373 		new_type = STACK_MISC;
4374 		if (writing_zero && *stype == STACK_ZERO) {
4375 			new_type = STACK_ZERO;
4376 			zero_used = true;
4377 		}
4378 		/* If the slot is STACK_INVALID, we check whether it's OK to
4379 		 * pretend that it will be initialized by this write. The slot
4380 		 * might not actually be written to, and so if we mark it as
4381 		 * initialized future reads might leak uninitialized memory.
4382 		 * For privileged programs, we will accept such reads to slots
4383 		 * that may or may not be written because, if we're reject
4384 		 * them, the error would be too confusing.
4385 		 */
4386 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4387 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4388 					insn_idx, i);
4389 			return -EINVAL;
4390 		}
4391 		*stype = new_type;
4392 	}
4393 	if (zero_used) {
4394 		/* backtracking doesn't work for STACK_ZERO yet. */
4395 		err = mark_chain_precision(env, value_regno);
4396 		if (err)
4397 			return err;
4398 	}
4399 	return 0;
4400 }
4401 
4402 /* When register 'dst_regno' is assigned some values from stack[min_off,
4403  * max_off), we set the register's type according to the types of the
4404  * respective stack slots. If all the stack values are known to be zeros, then
4405  * so is the destination reg. Otherwise, the register is considered to be
4406  * SCALAR. This function does not deal with register filling; the caller must
4407  * ensure that all spilled registers in the stack range have been marked as
4408  * read.
4409  */
4410 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4411 				/* func where src register points to */
4412 				struct bpf_func_state *ptr_state,
4413 				int min_off, int max_off, int dst_regno)
4414 {
4415 	struct bpf_verifier_state *vstate = env->cur_state;
4416 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4417 	int i, slot, spi;
4418 	u8 *stype;
4419 	int zeros = 0;
4420 
4421 	for (i = min_off; i < max_off; i++) {
4422 		slot = -i - 1;
4423 		spi = slot / BPF_REG_SIZE;
4424 		mark_stack_slot_scratched(env, spi);
4425 		stype = ptr_state->stack[spi].slot_type;
4426 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4427 			break;
4428 		zeros++;
4429 	}
4430 	if (zeros == max_off - min_off) {
4431 		/* any access_size read into register is zero extended,
4432 		 * so the whole register == const_zero
4433 		 */
4434 		__mark_reg_const_zero(&state->regs[dst_regno]);
4435 		/* backtracking doesn't support STACK_ZERO yet,
4436 		 * so mark it precise here, so that later
4437 		 * backtracking can stop here.
4438 		 * Backtracking may not need this if this register
4439 		 * doesn't participate in pointer adjustment.
4440 		 * Forward propagation of precise flag is not
4441 		 * necessary either. This mark is only to stop
4442 		 * backtracking. Any register that contributed
4443 		 * to const 0 was marked precise before spill.
4444 		 */
4445 		state->regs[dst_regno].precise = true;
4446 	} else {
4447 		/* have read misc data from the stack */
4448 		mark_reg_unknown(env, state->regs, dst_regno);
4449 	}
4450 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4451 }
4452 
4453 /* Read the stack at 'off' and put the results into the register indicated by
4454  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4455  * spilled reg.
4456  *
4457  * 'dst_regno' can be -1, meaning that the read value is not going to a
4458  * register.
4459  *
4460  * The access is assumed to be within the current stack bounds.
4461  */
4462 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4463 				      /* func where src register points to */
4464 				      struct bpf_func_state *reg_state,
4465 				      int off, int size, int dst_regno)
4466 {
4467 	struct bpf_verifier_state *vstate = env->cur_state;
4468 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4469 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4470 	struct bpf_reg_state *reg;
4471 	u8 *stype, type;
4472 
4473 	stype = reg_state->stack[spi].slot_type;
4474 	reg = &reg_state->stack[spi].spilled_ptr;
4475 
4476 	mark_stack_slot_scratched(env, spi);
4477 
4478 	if (is_spilled_reg(&reg_state->stack[spi])) {
4479 		u8 spill_size = 1;
4480 
4481 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4482 			spill_size++;
4483 
4484 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4485 			if (reg->type != SCALAR_VALUE) {
4486 				verbose_linfo(env, env->insn_idx, "; ");
4487 				verbose(env, "invalid size of register fill\n");
4488 				return -EACCES;
4489 			}
4490 
4491 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4492 			if (dst_regno < 0)
4493 				return 0;
4494 
4495 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4496 				/* The earlier check_reg_arg() has decided the
4497 				 * subreg_def for this insn.  Save it first.
4498 				 */
4499 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4500 
4501 				copy_register_state(&state->regs[dst_regno], reg);
4502 				state->regs[dst_regno].subreg_def = subreg_def;
4503 			} else {
4504 				for (i = 0; i < size; i++) {
4505 					type = stype[(slot - i) % BPF_REG_SIZE];
4506 					if (type == STACK_SPILL)
4507 						continue;
4508 					if (type == STACK_MISC)
4509 						continue;
4510 					if (type == STACK_INVALID && env->allow_uninit_stack)
4511 						continue;
4512 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4513 						off, i, size);
4514 					return -EACCES;
4515 				}
4516 				mark_reg_unknown(env, state->regs, dst_regno);
4517 			}
4518 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4519 			return 0;
4520 		}
4521 
4522 		if (dst_regno >= 0) {
4523 			/* restore register state from stack */
4524 			copy_register_state(&state->regs[dst_regno], reg);
4525 			/* mark reg as written since spilled pointer state likely
4526 			 * has its liveness marks cleared by is_state_visited()
4527 			 * which resets stack/reg liveness for state transitions
4528 			 */
4529 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4530 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4531 			/* If dst_regno==-1, the caller is asking us whether
4532 			 * it is acceptable to use this value as a SCALAR_VALUE
4533 			 * (e.g. for XADD).
4534 			 * We must not allow unprivileged callers to do that
4535 			 * with spilled pointers.
4536 			 */
4537 			verbose(env, "leaking pointer from stack off %d\n",
4538 				off);
4539 			return -EACCES;
4540 		}
4541 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4542 	} else {
4543 		for (i = 0; i < size; i++) {
4544 			type = stype[(slot - i) % BPF_REG_SIZE];
4545 			if (type == STACK_MISC)
4546 				continue;
4547 			if (type == STACK_ZERO)
4548 				continue;
4549 			if (type == STACK_INVALID && env->allow_uninit_stack)
4550 				continue;
4551 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4552 				off, i, size);
4553 			return -EACCES;
4554 		}
4555 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4556 		if (dst_regno >= 0)
4557 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4558 	}
4559 	return 0;
4560 }
4561 
4562 enum bpf_access_src {
4563 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4564 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4565 };
4566 
4567 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4568 					 int regno, int off, int access_size,
4569 					 bool zero_size_allowed,
4570 					 enum bpf_access_src type,
4571 					 struct bpf_call_arg_meta *meta);
4572 
4573 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4574 {
4575 	return cur_regs(env) + regno;
4576 }
4577 
4578 /* Read the stack at 'ptr_regno + off' and put the result into the register
4579  * 'dst_regno'.
4580  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4581  * but not its variable offset.
4582  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4583  *
4584  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4585  * filling registers (i.e. reads of spilled register cannot be detected when
4586  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4587  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4588  * offset; for a fixed offset check_stack_read_fixed_off should be used
4589  * instead.
4590  */
4591 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4592 				    int ptr_regno, int off, int size, int dst_regno)
4593 {
4594 	/* The state of the source register. */
4595 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4596 	struct bpf_func_state *ptr_state = func(env, reg);
4597 	int err;
4598 	int min_off, max_off;
4599 
4600 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4601 	 */
4602 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4603 					    false, ACCESS_DIRECT, NULL);
4604 	if (err)
4605 		return err;
4606 
4607 	min_off = reg->smin_value + off;
4608 	max_off = reg->smax_value + off;
4609 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4610 	return 0;
4611 }
4612 
4613 /* check_stack_read dispatches to check_stack_read_fixed_off or
4614  * check_stack_read_var_off.
4615  *
4616  * The caller must ensure that the offset falls within the allocated stack
4617  * bounds.
4618  *
4619  * 'dst_regno' is a register which will receive the value from the stack. It
4620  * can be -1, meaning that the read value is not going to a register.
4621  */
4622 static int check_stack_read(struct bpf_verifier_env *env,
4623 			    int ptr_regno, int off, int size,
4624 			    int dst_regno)
4625 {
4626 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4627 	struct bpf_func_state *state = func(env, reg);
4628 	int err;
4629 	/* Some accesses are only permitted with a static offset. */
4630 	bool var_off = !tnum_is_const(reg->var_off);
4631 
4632 	/* The offset is required to be static when reads don't go to a
4633 	 * register, in order to not leak pointers (see
4634 	 * check_stack_read_fixed_off).
4635 	 */
4636 	if (dst_regno < 0 && var_off) {
4637 		char tn_buf[48];
4638 
4639 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4640 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4641 			tn_buf, off, size);
4642 		return -EACCES;
4643 	}
4644 	/* Variable offset is prohibited for unprivileged mode for simplicity
4645 	 * since it requires corresponding support in Spectre masking for stack
4646 	 * ALU. See also retrieve_ptr_limit(). The check in
4647 	 * check_stack_access_for_ptr_arithmetic() called by
4648 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4649 	 * with variable offsets, therefore no check is required here. Further,
4650 	 * just checking it here would be insufficient as speculative stack
4651 	 * writes could still lead to unsafe speculative behaviour.
4652 	 */
4653 	if (!var_off) {
4654 		off += reg->var_off.value;
4655 		err = check_stack_read_fixed_off(env, state, off, size,
4656 						 dst_regno);
4657 	} else {
4658 		/* Variable offset stack reads need more conservative handling
4659 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4660 		 * branch.
4661 		 */
4662 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4663 					       dst_regno);
4664 	}
4665 	return err;
4666 }
4667 
4668 
4669 /* check_stack_write dispatches to check_stack_write_fixed_off or
4670  * check_stack_write_var_off.
4671  *
4672  * 'ptr_regno' is the register used as a pointer into the stack.
4673  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4674  * 'value_regno' is the register whose value we're writing to the stack. It can
4675  * be -1, meaning that we're not writing from a register.
4676  *
4677  * The caller must ensure that the offset falls within the maximum stack size.
4678  */
4679 static int check_stack_write(struct bpf_verifier_env *env,
4680 			     int ptr_regno, int off, int size,
4681 			     int value_regno, int insn_idx)
4682 {
4683 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4684 	struct bpf_func_state *state = func(env, reg);
4685 	int err;
4686 
4687 	if (tnum_is_const(reg->var_off)) {
4688 		off += reg->var_off.value;
4689 		err = check_stack_write_fixed_off(env, state, off, size,
4690 						  value_regno, insn_idx);
4691 	} else {
4692 		/* Variable offset stack reads need more conservative handling
4693 		 * than fixed offset ones.
4694 		 */
4695 		err = check_stack_write_var_off(env, state,
4696 						ptr_regno, off, size,
4697 						value_regno, insn_idx);
4698 	}
4699 	return err;
4700 }
4701 
4702 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4703 				 int off, int size, enum bpf_access_type type)
4704 {
4705 	struct bpf_reg_state *regs = cur_regs(env);
4706 	struct bpf_map *map = regs[regno].map_ptr;
4707 	u32 cap = bpf_map_flags_to_cap(map);
4708 
4709 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4710 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4711 			map->value_size, off, size);
4712 		return -EACCES;
4713 	}
4714 
4715 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4716 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4717 			map->value_size, off, size);
4718 		return -EACCES;
4719 	}
4720 
4721 	return 0;
4722 }
4723 
4724 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4725 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4726 			      int off, int size, u32 mem_size,
4727 			      bool zero_size_allowed)
4728 {
4729 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4730 	struct bpf_reg_state *reg;
4731 
4732 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4733 		return 0;
4734 
4735 	reg = &cur_regs(env)[regno];
4736 	switch (reg->type) {
4737 	case PTR_TO_MAP_KEY:
4738 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4739 			mem_size, off, size);
4740 		break;
4741 	case PTR_TO_MAP_VALUE:
4742 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4743 			mem_size, off, size);
4744 		break;
4745 	case PTR_TO_PACKET:
4746 	case PTR_TO_PACKET_META:
4747 	case PTR_TO_PACKET_END:
4748 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4749 			off, size, regno, reg->id, off, mem_size);
4750 		break;
4751 	case PTR_TO_MEM:
4752 	default:
4753 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4754 			mem_size, off, size);
4755 	}
4756 
4757 	return -EACCES;
4758 }
4759 
4760 /* check read/write into a memory region with possible variable offset */
4761 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4762 				   int off, int size, u32 mem_size,
4763 				   bool zero_size_allowed)
4764 {
4765 	struct bpf_verifier_state *vstate = env->cur_state;
4766 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4767 	struct bpf_reg_state *reg = &state->regs[regno];
4768 	int err;
4769 
4770 	/* We may have adjusted the register pointing to memory region, so we
4771 	 * need to try adding each of min_value and max_value to off
4772 	 * to make sure our theoretical access will be safe.
4773 	 *
4774 	 * The minimum value is only important with signed
4775 	 * comparisons where we can't assume the floor of a
4776 	 * value is 0.  If we are using signed variables for our
4777 	 * index'es we need to make sure that whatever we use
4778 	 * will have a set floor within our range.
4779 	 */
4780 	if (reg->smin_value < 0 &&
4781 	    (reg->smin_value == S64_MIN ||
4782 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4783 	      reg->smin_value + off < 0)) {
4784 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4785 			regno);
4786 		return -EACCES;
4787 	}
4788 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4789 				 mem_size, zero_size_allowed);
4790 	if (err) {
4791 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4792 			regno);
4793 		return err;
4794 	}
4795 
4796 	/* If we haven't set a max value then we need to bail since we can't be
4797 	 * sure we won't do bad things.
4798 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4799 	 */
4800 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4801 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4802 			regno);
4803 		return -EACCES;
4804 	}
4805 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4806 				 mem_size, zero_size_allowed);
4807 	if (err) {
4808 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4809 			regno);
4810 		return err;
4811 	}
4812 
4813 	return 0;
4814 }
4815 
4816 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4817 			       const struct bpf_reg_state *reg, int regno,
4818 			       bool fixed_off_ok)
4819 {
4820 	/* Access to this pointer-typed register or passing it to a helper
4821 	 * is only allowed in its original, unmodified form.
4822 	 */
4823 
4824 	if (reg->off < 0) {
4825 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4826 			reg_type_str(env, reg->type), regno, reg->off);
4827 		return -EACCES;
4828 	}
4829 
4830 	if (!fixed_off_ok && reg->off) {
4831 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4832 			reg_type_str(env, reg->type), regno, reg->off);
4833 		return -EACCES;
4834 	}
4835 
4836 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4837 		char tn_buf[48];
4838 
4839 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4840 		verbose(env, "variable %s access var_off=%s disallowed\n",
4841 			reg_type_str(env, reg->type), tn_buf);
4842 		return -EACCES;
4843 	}
4844 
4845 	return 0;
4846 }
4847 
4848 int check_ptr_off_reg(struct bpf_verifier_env *env,
4849 		      const struct bpf_reg_state *reg, int regno)
4850 {
4851 	return __check_ptr_off_reg(env, reg, regno, false);
4852 }
4853 
4854 static int map_kptr_match_type(struct bpf_verifier_env *env,
4855 			       struct btf_field *kptr_field,
4856 			       struct bpf_reg_state *reg, u32 regno)
4857 {
4858 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4859 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4860 	const char *reg_name = "";
4861 
4862 	/* Only unreferenced case accepts untrusted pointers */
4863 	if (kptr_field->type == BPF_KPTR_UNREF)
4864 		perm_flags |= PTR_UNTRUSTED;
4865 
4866 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4867 		goto bad_type;
4868 
4869 	if (!btf_is_kernel(reg->btf)) {
4870 		verbose(env, "R%d must point to kernel BTF\n", regno);
4871 		return -EINVAL;
4872 	}
4873 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4874 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4875 
4876 	/* For ref_ptr case, release function check should ensure we get one
4877 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4878 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4879 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4880 	 * reg->off and reg->ref_obj_id are not needed here.
4881 	 */
4882 	if (__check_ptr_off_reg(env, reg, regno, true))
4883 		return -EACCES;
4884 
4885 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4886 	 * we also need to take into account the reg->off.
4887 	 *
4888 	 * We want to support cases like:
4889 	 *
4890 	 * struct foo {
4891 	 *         struct bar br;
4892 	 *         struct baz bz;
4893 	 * };
4894 	 *
4895 	 * struct foo *v;
4896 	 * v = func();	      // PTR_TO_BTF_ID
4897 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4898 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4899 	 *                    // first member type of struct after comparison fails
4900 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4901 	 *                    // to match type
4902 	 *
4903 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4904 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4905 	 * the struct to match type against first member of struct, i.e. reject
4906 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4907 	 * strict mode to true for type match.
4908 	 */
4909 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4910 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4911 				  kptr_field->type == BPF_KPTR_REF))
4912 		goto bad_type;
4913 	return 0;
4914 bad_type:
4915 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4916 		reg_type_str(env, reg->type), reg_name);
4917 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4918 	if (kptr_field->type == BPF_KPTR_UNREF)
4919 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4920 			targ_name);
4921 	else
4922 		verbose(env, "\n");
4923 	return -EINVAL;
4924 }
4925 
4926 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4927  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4928  */
4929 static bool in_rcu_cs(struct bpf_verifier_env *env)
4930 {
4931 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4932 }
4933 
4934 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4935 BTF_SET_START(rcu_protected_types)
4936 BTF_ID(struct, prog_test_ref_kfunc)
4937 BTF_ID(struct, cgroup)
4938 BTF_ID(struct, bpf_cpumask)
4939 BTF_ID(struct, task_struct)
4940 BTF_SET_END(rcu_protected_types)
4941 
4942 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4943 {
4944 	if (!btf_is_kernel(btf))
4945 		return false;
4946 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4947 }
4948 
4949 static bool rcu_safe_kptr(const struct btf_field *field)
4950 {
4951 	const struct btf_field_kptr *kptr = &field->kptr;
4952 
4953 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4954 }
4955 
4956 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4957 				 int value_regno, int insn_idx,
4958 				 struct btf_field *kptr_field)
4959 {
4960 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4961 	int class = BPF_CLASS(insn->code);
4962 	struct bpf_reg_state *val_reg;
4963 
4964 	/* Things we already checked for in check_map_access and caller:
4965 	 *  - Reject cases where variable offset may touch kptr
4966 	 *  - size of access (must be BPF_DW)
4967 	 *  - tnum_is_const(reg->var_off)
4968 	 *  - kptr_field->offset == off + reg->var_off.value
4969 	 */
4970 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4971 	if (BPF_MODE(insn->code) != BPF_MEM) {
4972 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4973 		return -EACCES;
4974 	}
4975 
4976 	/* We only allow loading referenced kptr, since it will be marked as
4977 	 * untrusted, similar to unreferenced kptr.
4978 	 */
4979 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4980 		verbose(env, "store to referenced kptr disallowed\n");
4981 		return -EACCES;
4982 	}
4983 
4984 	if (class == BPF_LDX) {
4985 		val_reg = reg_state(env, value_regno);
4986 		/* We can simply mark the value_regno receiving the pointer
4987 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4988 		 */
4989 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4990 				kptr_field->kptr.btf_id,
4991 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4992 				PTR_MAYBE_NULL | MEM_RCU :
4993 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
4994 		/* For mark_ptr_or_null_reg */
4995 		val_reg->id = ++env->id_gen;
4996 	} else if (class == BPF_STX) {
4997 		val_reg = reg_state(env, value_regno);
4998 		if (!register_is_null(val_reg) &&
4999 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5000 			return -EACCES;
5001 	} else if (class == BPF_ST) {
5002 		if (insn->imm) {
5003 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5004 				kptr_field->offset);
5005 			return -EACCES;
5006 		}
5007 	} else {
5008 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5009 		return -EACCES;
5010 	}
5011 	return 0;
5012 }
5013 
5014 /* check read/write into a map element with possible variable offset */
5015 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5016 			    int off, int size, bool zero_size_allowed,
5017 			    enum bpf_access_src src)
5018 {
5019 	struct bpf_verifier_state *vstate = env->cur_state;
5020 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5021 	struct bpf_reg_state *reg = &state->regs[regno];
5022 	struct bpf_map *map = reg->map_ptr;
5023 	struct btf_record *rec;
5024 	int err, i;
5025 
5026 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5027 				      zero_size_allowed);
5028 	if (err)
5029 		return err;
5030 
5031 	if (IS_ERR_OR_NULL(map->record))
5032 		return 0;
5033 	rec = map->record;
5034 	for (i = 0; i < rec->cnt; i++) {
5035 		struct btf_field *field = &rec->fields[i];
5036 		u32 p = field->offset;
5037 
5038 		/* If any part of a field  can be touched by load/store, reject
5039 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5040 		 * it is sufficient to check x1 < y2 && y1 < x2.
5041 		 */
5042 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5043 		    p < reg->umax_value + off + size) {
5044 			switch (field->type) {
5045 			case BPF_KPTR_UNREF:
5046 			case BPF_KPTR_REF:
5047 				if (src != ACCESS_DIRECT) {
5048 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5049 					return -EACCES;
5050 				}
5051 				if (!tnum_is_const(reg->var_off)) {
5052 					verbose(env, "kptr access cannot have variable offset\n");
5053 					return -EACCES;
5054 				}
5055 				if (p != off + reg->var_off.value) {
5056 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5057 						p, off + reg->var_off.value);
5058 					return -EACCES;
5059 				}
5060 				if (size != bpf_size_to_bytes(BPF_DW)) {
5061 					verbose(env, "kptr access size must be BPF_DW\n");
5062 					return -EACCES;
5063 				}
5064 				break;
5065 			default:
5066 				verbose(env, "%s cannot be accessed directly by load/store\n",
5067 					btf_field_type_name(field->type));
5068 				return -EACCES;
5069 			}
5070 		}
5071 	}
5072 	return 0;
5073 }
5074 
5075 #define MAX_PACKET_OFF 0xffff
5076 
5077 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5078 				       const struct bpf_call_arg_meta *meta,
5079 				       enum bpf_access_type t)
5080 {
5081 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5082 
5083 	switch (prog_type) {
5084 	/* Program types only with direct read access go here! */
5085 	case BPF_PROG_TYPE_LWT_IN:
5086 	case BPF_PROG_TYPE_LWT_OUT:
5087 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5088 	case BPF_PROG_TYPE_SK_REUSEPORT:
5089 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5090 	case BPF_PROG_TYPE_CGROUP_SKB:
5091 		if (t == BPF_WRITE)
5092 			return false;
5093 		fallthrough;
5094 
5095 	/* Program types with direct read + write access go here! */
5096 	case BPF_PROG_TYPE_SCHED_CLS:
5097 	case BPF_PROG_TYPE_SCHED_ACT:
5098 	case BPF_PROG_TYPE_XDP:
5099 	case BPF_PROG_TYPE_LWT_XMIT:
5100 	case BPF_PROG_TYPE_SK_SKB:
5101 	case BPF_PROG_TYPE_SK_MSG:
5102 		if (meta)
5103 			return meta->pkt_access;
5104 
5105 		env->seen_direct_write = true;
5106 		return true;
5107 
5108 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5109 		if (t == BPF_WRITE)
5110 			env->seen_direct_write = true;
5111 
5112 		return true;
5113 
5114 	default:
5115 		return false;
5116 	}
5117 }
5118 
5119 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5120 			       int size, bool zero_size_allowed)
5121 {
5122 	struct bpf_reg_state *regs = cur_regs(env);
5123 	struct bpf_reg_state *reg = &regs[regno];
5124 	int err;
5125 
5126 	/* We may have added a variable offset to the packet pointer; but any
5127 	 * reg->range we have comes after that.  We are only checking the fixed
5128 	 * offset.
5129 	 */
5130 
5131 	/* We don't allow negative numbers, because we aren't tracking enough
5132 	 * detail to prove they're safe.
5133 	 */
5134 	if (reg->smin_value < 0) {
5135 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5136 			regno);
5137 		return -EACCES;
5138 	}
5139 
5140 	err = reg->range < 0 ? -EINVAL :
5141 	      __check_mem_access(env, regno, off, size, reg->range,
5142 				 zero_size_allowed);
5143 	if (err) {
5144 		verbose(env, "R%d offset is outside of the packet\n", regno);
5145 		return err;
5146 	}
5147 
5148 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5149 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5150 	 * otherwise find_good_pkt_pointers would have refused to set range info
5151 	 * that __check_mem_access would have rejected this pkt access.
5152 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5153 	 */
5154 	env->prog->aux->max_pkt_offset =
5155 		max_t(u32, env->prog->aux->max_pkt_offset,
5156 		      off + reg->umax_value + size - 1);
5157 
5158 	return err;
5159 }
5160 
5161 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5162 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5163 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5164 			    struct btf **btf, u32 *btf_id)
5165 {
5166 	struct bpf_insn_access_aux info = {
5167 		.reg_type = *reg_type,
5168 		.log = &env->log,
5169 	};
5170 
5171 	if (env->ops->is_valid_access &&
5172 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5173 		/* A non zero info.ctx_field_size indicates that this field is a
5174 		 * candidate for later verifier transformation to load the whole
5175 		 * field and then apply a mask when accessed with a narrower
5176 		 * access than actual ctx access size. A zero info.ctx_field_size
5177 		 * will only allow for whole field access and rejects any other
5178 		 * type of narrower access.
5179 		 */
5180 		*reg_type = info.reg_type;
5181 
5182 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5183 			*btf = info.btf;
5184 			*btf_id = info.btf_id;
5185 		} else {
5186 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5187 		}
5188 		/* remember the offset of last byte accessed in ctx */
5189 		if (env->prog->aux->max_ctx_offset < off + size)
5190 			env->prog->aux->max_ctx_offset = off + size;
5191 		return 0;
5192 	}
5193 
5194 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5195 	return -EACCES;
5196 }
5197 
5198 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5199 				  int size)
5200 {
5201 	if (size < 0 || off < 0 ||
5202 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5203 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5204 			off, size);
5205 		return -EACCES;
5206 	}
5207 	return 0;
5208 }
5209 
5210 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5211 			     u32 regno, int off, int size,
5212 			     enum bpf_access_type t)
5213 {
5214 	struct bpf_reg_state *regs = cur_regs(env);
5215 	struct bpf_reg_state *reg = &regs[regno];
5216 	struct bpf_insn_access_aux info = {};
5217 	bool valid;
5218 
5219 	if (reg->smin_value < 0) {
5220 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5221 			regno);
5222 		return -EACCES;
5223 	}
5224 
5225 	switch (reg->type) {
5226 	case PTR_TO_SOCK_COMMON:
5227 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5228 		break;
5229 	case PTR_TO_SOCKET:
5230 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5231 		break;
5232 	case PTR_TO_TCP_SOCK:
5233 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5234 		break;
5235 	case PTR_TO_XDP_SOCK:
5236 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5237 		break;
5238 	default:
5239 		valid = false;
5240 	}
5241 
5242 
5243 	if (valid) {
5244 		env->insn_aux_data[insn_idx].ctx_field_size =
5245 			info.ctx_field_size;
5246 		return 0;
5247 	}
5248 
5249 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5250 		regno, reg_type_str(env, reg->type), off, size);
5251 
5252 	return -EACCES;
5253 }
5254 
5255 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5256 {
5257 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5258 }
5259 
5260 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5261 {
5262 	const struct bpf_reg_state *reg = reg_state(env, regno);
5263 
5264 	return reg->type == PTR_TO_CTX;
5265 }
5266 
5267 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5268 {
5269 	const struct bpf_reg_state *reg = reg_state(env, regno);
5270 
5271 	return type_is_sk_pointer(reg->type);
5272 }
5273 
5274 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5275 {
5276 	const struct bpf_reg_state *reg = reg_state(env, regno);
5277 
5278 	return type_is_pkt_pointer(reg->type);
5279 }
5280 
5281 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5282 {
5283 	const struct bpf_reg_state *reg = reg_state(env, regno);
5284 
5285 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5286 	return reg->type == PTR_TO_FLOW_KEYS;
5287 }
5288 
5289 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5290 {
5291 	/* A referenced register is always trusted. */
5292 	if (reg->ref_obj_id)
5293 		return true;
5294 
5295 	/* If a register is not referenced, it is trusted if it has the
5296 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5297 	 * other type modifiers may be safe, but we elect to take an opt-in
5298 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5299 	 * not.
5300 	 *
5301 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5302 	 * for whether a register is trusted.
5303 	 */
5304 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5305 	       !bpf_type_has_unsafe_modifiers(reg->type);
5306 }
5307 
5308 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5309 {
5310 	return reg->type & MEM_RCU;
5311 }
5312 
5313 static void clear_trusted_flags(enum bpf_type_flag *flag)
5314 {
5315 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5316 }
5317 
5318 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5319 				   const struct bpf_reg_state *reg,
5320 				   int off, int size, bool strict)
5321 {
5322 	struct tnum reg_off;
5323 	int ip_align;
5324 
5325 	/* Byte size accesses are always allowed. */
5326 	if (!strict || size == 1)
5327 		return 0;
5328 
5329 	/* For platforms that do not have a Kconfig enabling
5330 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5331 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5332 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5333 	 * to this code only in strict mode where we want to emulate
5334 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5335 	 * unconditional IP align value of '2'.
5336 	 */
5337 	ip_align = 2;
5338 
5339 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5340 	if (!tnum_is_aligned(reg_off, size)) {
5341 		char tn_buf[48];
5342 
5343 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5344 		verbose(env,
5345 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5346 			ip_align, tn_buf, reg->off, off, size);
5347 		return -EACCES;
5348 	}
5349 
5350 	return 0;
5351 }
5352 
5353 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5354 				       const struct bpf_reg_state *reg,
5355 				       const char *pointer_desc,
5356 				       int off, int size, bool strict)
5357 {
5358 	struct tnum reg_off;
5359 
5360 	/* Byte size accesses are always allowed. */
5361 	if (!strict || size == 1)
5362 		return 0;
5363 
5364 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5365 	if (!tnum_is_aligned(reg_off, size)) {
5366 		char tn_buf[48];
5367 
5368 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5369 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5370 			pointer_desc, tn_buf, reg->off, off, size);
5371 		return -EACCES;
5372 	}
5373 
5374 	return 0;
5375 }
5376 
5377 static int check_ptr_alignment(struct bpf_verifier_env *env,
5378 			       const struct bpf_reg_state *reg, int off,
5379 			       int size, bool strict_alignment_once)
5380 {
5381 	bool strict = env->strict_alignment || strict_alignment_once;
5382 	const char *pointer_desc = "";
5383 
5384 	switch (reg->type) {
5385 	case PTR_TO_PACKET:
5386 	case PTR_TO_PACKET_META:
5387 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5388 		 * right in front, treat it the very same way.
5389 		 */
5390 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5391 	case PTR_TO_FLOW_KEYS:
5392 		pointer_desc = "flow keys ";
5393 		break;
5394 	case PTR_TO_MAP_KEY:
5395 		pointer_desc = "key ";
5396 		break;
5397 	case PTR_TO_MAP_VALUE:
5398 		pointer_desc = "value ";
5399 		break;
5400 	case PTR_TO_CTX:
5401 		pointer_desc = "context ";
5402 		break;
5403 	case PTR_TO_STACK:
5404 		pointer_desc = "stack ";
5405 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5406 		 * and check_stack_read_fixed_off() relies on stack accesses being
5407 		 * aligned.
5408 		 */
5409 		strict = true;
5410 		break;
5411 	case PTR_TO_SOCKET:
5412 		pointer_desc = "sock ";
5413 		break;
5414 	case PTR_TO_SOCK_COMMON:
5415 		pointer_desc = "sock_common ";
5416 		break;
5417 	case PTR_TO_TCP_SOCK:
5418 		pointer_desc = "tcp_sock ";
5419 		break;
5420 	case PTR_TO_XDP_SOCK:
5421 		pointer_desc = "xdp_sock ";
5422 		break;
5423 	default:
5424 		break;
5425 	}
5426 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5427 					   strict);
5428 }
5429 
5430 static int update_stack_depth(struct bpf_verifier_env *env,
5431 			      const struct bpf_func_state *func,
5432 			      int off)
5433 {
5434 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5435 
5436 	if (stack >= -off)
5437 		return 0;
5438 
5439 	/* update known max for given subprogram */
5440 	env->subprog_info[func->subprogno].stack_depth = -off;
5441 	return 0;
5442 }
5443 
5444 /* starting from main bpf function walk all instructions of the function
5445  * and recursively walk all callees that given function can call.
5446  * Ignore jump and exit insns.
5447  * Since recursion is prevented by check_cfg() this algorithm
5448  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5449  */
5450 static int check_max_stack_depth(struct bpf_verifier_env *env)
5451 {
5452 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5453 	struct bpf_subprog_info *subprog = env->subprog_info;
5454 	struct bpf_insn *insn = env->prog->insnsi;
5455 	bool tail_call_reachable = false;
5456 	int ret_insn[MAX_CALL_FRAMES];
5457 	int ret_prog[MAX_CALL_FRAMES];
5458 	int j;
5459 
5460 process_func:
5461 	/* protect against potential stack overflow that might happen when
5462 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5463 	 * depth for such case down to 256 so that the worst case scenario
5464 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5465 	 * 8k).
5466 	 *
5467 	 * To get the idea what might happen, see an example:
5468 	 * func1 -> sub rsp, 128
5469 	 *  subfunc1 -> sub rsp, 256
5470 	 *  tailcall1 -> add rsp, 256
5471 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5472 	 *   subfunc2 -> sub rsp, 64
5473 	 *   subfunc22 -> sub rsp, 128
5474 	 *   tailcall2 -> add rsp, 128
5475 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5476 	 *
5477 	 * tailcall will unwind the current stack frame but it will not get rid
5478 	 * of caller's stack as shown on the example above.
5479 	 */
5480 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5481 		verbose(env,
5482 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5483 			depth);
5484 		return -EACCES;
5485 	}
5486 	/* round up to 32-bytes, since this is granularity
5487 	 * of interpreter stack size
5488 	 */
5489 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5490 	if (depth > MAX_BPF_STACK) {
5491 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5492 			frame + 1, depth);
5493 		return -EACCES;
5494 	}
5495 continue_func:
5496 	subprog_end = subprog[idx + 1].start;
5497 	for (; i < subprog_end; i++) {
5498 		int next_insn;
5499 
5500 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5501 			continue;
5502 		/* remember insn and function to return to */
5503 		ret_insn[frame] = i + 1;
5504 		ret_prog[frame] = idx;
5505 
5506 		/* find the callee */
5507 		next_insn = i + insn[i].imm + 1;
5508 		idx = find_subprog(env, next_insn);
5509 		if (idx < 0) {
5510 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5511 				  next_insn);
5512 			return -EFAULT;
5513 		}
5514 		if (subprog[idx].is_async_cb) {
5515 			if (subprog[idx].has_tail_call) {
5516 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5517 				return -EFAULT;
5518 			}
5519 			 /* async callbacks don't increase bpf prog stack size */
5520 			continue;
5521 		}
5522 		i = next_insn;
5523 
5524 		if (subprog[idx].has_tail_call)
5525 			tail_call_reachable = true;
5526 
5527 		frame++;
5528 		if (frame >= MAX_CALL_FRAMES) {
5529 			verbose(env, "the call stack of %d frames is too deep !\n",
5530 				frame);
5531 			return -E2BIG;
5532 		}
5533 		goto process_func;
5534 	}
5535 	/* if tail call got detected across bpf2bpf calls then mark each of the
5536 	 * currently present subprog frames as tail call reachable subprogs;
5537 	 * this info will be utilized by JIT so that we will be preserving the
5538 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5539 	 */
5540 	if (tail_call_reachable)
5541 		for (j = 0; j < frame; j++)
5542 			subprog[ret_prog[j]].tail_call_reachable = true;
5543 	if (subprog[0].tail_call_reachable)
5544 		env->prog->aux->tail_call_reachable = true;
5545 
5546 	/* end of for() loop means the last insn of the 'subprog'
5547 	 * was reached. Doesn't matter whether it was JA or EXIT
5548 	 */
5549 	if (frame == 0)
5550 		return 0;
5551 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5552 	frame--;
5553 	i = ret_insn[frame];
5554 	idx = ret_prog[frame];
5555 	goto continue_func;
5556 }
5557 
5558 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5559 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5560 				  const struct bpf_insn *insn, int idx)
5561 {
5562 	int start = idx + insn->imm + 1, subprog;
5563 
5564 	subprog = find_subprog(env, start);
5565 	if (subprog < 0) {
5566 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5567 			  start);
5568 		return -EFAULT;
5569 	}
5570 	return env->subprog_info[subprog].stack_depth;
5571 }
5572 #endif
5573 
5574 static int __check_buffer_access(struct bpf_verifier_env *env,
5575 				 const char *buf_info,
5576 				 const struct bpf_reg_state *reg,
5577 				 int regno, int off, int size)
5578 {
5579 	if (off < 0) {
5580 		verbose(env,
5581 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5582 			regno, buf_info, off, size);
5583 		return -EACCES;
5584 	}
5585 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5586 		char tn_buf[48];
5587 
5588 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5589 		verbose(env,
5590 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5591 			regno, off, tn_buf);
5592 		return -EACCES;
5593 	}
5594 
5595 	return 0;
5596 }
5597 
5598 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5599 				  const struct bpf_reg_state *reg,
5600 				  int regno, int off, int size)
5601 {
5602 	int err;
5603 
5604 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5605 	if (err)
5606 		return err;
5607 
5608 	if (off + size > env->prog->aux->max_tp_access)
5609 		env->prog->aux->max_tp_access = off + size;
5610 
5611 	return 0;
5612 }
5613 
5614 static int check_buffer_access(struct bpf_verifier_env *env,
5615 			       const struct bpf_reg_state *reg,
5616 			       int regno, int off, int size,
5617 			       bool zero_size_allowed,
5618 			       u32 *max_access)
5619 {
5620 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5621 	int err;
5622 
5623 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5624 	if (err)
5625 		return err;
5626 
5627 	if (off + size > *max_access)
5628 		*max_access = off + size;
5629 
5630 	return 0;
5631 }
5632 
5633 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5634 static void zext_32_to_64(struct bpf_reg_state *reg)
5635 {
5636 	reg->var_off = tnum_subreg(reg->var_off);
5637 	__reg_assign_32_into_64(reg);
5638 }
5639 
5640 /* truncate register to smaller size (in bytes)
5641  * must be called with size < BPF_REG_SIZE
5642  */
5643 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5644 {
5645 	u64 mask;
5646 
5647 	/* clear high bits in bit representation */
5648 	reg->var_off = tnum_cast(reg->var_off, size);
5649 
5650 	/* fix arithmetic bounds */
5651 	mask = ((u64)1 << (size * 8)) - 1;
5652 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5653 		reg->umin_value &= mask;
5654 		reg->umax_value &= mask;
5655 	} else {
5656 		reg->umin_value = 0;
5657 		reg->umax_value = mask;
5658 	}
5659 	reg->smin_value = reg->umin_value;
5660 	reg->smax_value = reg->umax_value;
5661 
5662 	/* If size is smaller than 32bit register the 32bit register
5663 	 * values are also truncated so we push 64-bit bounds into
5664 	 * 32-bit bounds. Above were truncated < 32-bits already.
5665 	 */
5666 	if (size >= 4)
5667 		return;
5668 	__reg_combine_64_into_32(reg);
5669 }
5670 
5671 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5672 {
5673 	/* A map is considered read-only if the following condition are true:
5674 	 *
5675 	 * 1) BPF program side cannot change any of the map content. The
5676 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5677 	 *    and was set at map creation time.
5678 	 * 2) The map value(s) have been initialized from user space by a
5679 	 *    loader and then "frozen", such that no new map update/delete
5680 	 *    operations from syscall side are possible for the rest of
5681 	 *    the map's lifetime from that point onwards.
5682 	 * 3) Any parallel/pending map update/delete operations from syscall
5683 	 *    side have been completed. Only after that point, it's safe to
5684 	 *    assume that map value(s) are immutable.
5685 	 */
5686 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5687 	       READ_ONCE(map->frozen) &&
5688 	       !bpf_map_write_active(map);
5689 }
5690 
5691 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5692 {
5693 	void *ptr;
5694 	u64 addr;
5695 	int err;
5696 
5697 	err = map->ops->map_direct_value_addr(map, &addr, off);
5698 	if (err)
5699 		return err;
5700 	ptr = (void *)(long)addr + off;
5701 
5702 	switch (size) {
5703 	case sizeof(u8):
5704 		*val = (u64)*(u8 *)ptr;
5705 		break;
5706 	case sizeof(u16):
5707 		*val = (u64)*(u16 *)ptr;
5708 		break;
5709 	case sizeof(u32):
5710 		*val = (u64)*(u32 *)ptr;
5711 		break;
5712 	case sizeof(u64):
5713 		*val = *(u64 *)ptr;
5714 		break;
5715 	default:
5716 		return -EINVAL;
5717 	}
5718 	return 0;
5719 }
5720 
5721 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5722 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5723 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5724 
5725 /*
5726  * Allow list few fields as RCU trusted or full trusted.
5727  * This logic doesn't allow mix tagging and will be removed once GCC supports
5728  * btf_type_tag.
5729  */
5730 
5731 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5732 BTF_TYPE_SAFE_RCU(struct task_struct) {
5733 	const cpumask_t *cpus_ptr;
5734 	struct css_set __rcu *cgroups;
5735 	struct task_struct __rcu *real_parent;
5736 	struct task_struct *group_leader;
5737 };
5738 
5739 BTF_TYPE_SAFE_RCU(struct cgroup) {
5740 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5741 	struct kernfs_node *kn;
5742 };
5743 
5744 BTF_TYPE_SAFE_RCU(struct css_set) {
5745 	struct cgroup *dfl_cgrp;
5746 };
5747 
5748 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5749 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5750 	struct file __rcu *exe_file;
5751 };
5752 
5753 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5754  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5755  */
5756 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5757 	struct sock *sk;
5758 };
5759 
5760 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5761 	struct sock *sk;
5762 };
5763 
5764 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5765 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5766 	struct seq_file *seq;
5767 };
5768 
5769 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5770 	struct bpf_iter_meta *meta;
5771 	struct task_struct *task;
5772 };
5773 
5774 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5775 	struct file *file;
5776 };
5777 
5778 BTF_TYPE_SAFE_TRUSTED(struct file) {
5779 	struct inode *f_inode;
5780 };
5781 
5782 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5783 	/* no negative dentry-s in places where bpf can see it */
5784 	struct inode *d_inode;
5785 };
5786 
5787 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5788 	struct sock *sk;
5789 };
5790 
5791 static bool type_is_rcu(struct bpf_verifier_env *env,
5792 			struct bpf_reg_state *reg,
5793 			const char *field_name, u32 btf_id)
5794 {
5795 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5796 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5797 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5798 
5799 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5800 }
5801 
5802 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5803 				struct bpf_reg_state *reg,
5804 				const char *field_name, u32 btf_id)
5805 {
5806 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5807 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5808 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5809 
5810 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5811 }
5812 
5813 static bool type_is_trusted(struct bpf_verifier_env *env,
5814 			    struct bpf_reg_state *reg,
5815 			    const char *field_name, u32 btf_id)
5816 {
5817 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5818 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5819 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5820 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5821 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5822 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5823 
5824 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5825 }
5826 
5827 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5828 				   struct bpf_reg_state *regs,
5829 				   int regno, int off, int size,
5830 				   enum bpf_access_type atype,
5831 				   int value_regno)
5832 {
5833 	struct bpf_reg_state *reg = regs + regno;
5834 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5835 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5836 	const char *field_name = NULL;
5837 	enum bpf_type_flag flag = 0;
5838 	u32 btf_id = 0;
5839 	int ret;
5840 
5841 	if (!env->allow_ptr_leaks) {
5842 		verbose(env,
5843 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5844 			tname);
5845 		return -EPERM;
5846 	}
5847 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5848 		verbose(env,
5849 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5850 			tname);
5851 		return -EINVAL;
5852 	}
5853 	if (off < 0) {
5854 		verbose(env,
5855 			"R%d is ptr_%s invalid negative access: off=%d\n",
5856 			regno, tname, off);
5857 		return -EACCES;
5858 	}
5859 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5860 		char tn_buf[48];
5861 
5862 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5863 		verbose(env,
5864 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5865 			regno, tname, off, tn_buf);
5866 		return -EACCES;
5867 	}
5868 
5869 	if (reg->type & MEM_USER) {
5870 		verbose(env,
5871 			"R%d is ptr_%s access user memory: off=%d\n",
5872 			regno, tname, off);
5873 		return -EACCES;
5874 	}
5875 
5876 	if (reg->type & MEM_PERCPU) {
5877 		verbose(env,
5878 			"R%d is ptr_%s access percpu memory: off=%d\n",
5879 			regno, tname, off);
5880 		return -EACCES;
5881 	}
5882 
5883 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5884 		if (!btf_is_kernel(reg->btf)) {
5885 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5886 			return -EFAULT;
5887 		}
5888 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5889 	} else {
5890 		/* Writes are permitted with default btf_struct_access for
5891 		 * program allocated objects (which always have ref_obj_id > 0),
5892 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5893 		 */
5894 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5895 			verbose(env, "only read is supported\n");
5896 			return -EACCES;
5897 		}
5898 
5899 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5900 		    !reg->ref_obj_id) {
5901 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5902 			return -EFAULT;
5903 		}
5904 
5905 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5906 	}
5907 
5908 	if (ret < 0)
5909 		return ret;
5910 
5911 	if (ret != PTR_TO_BTF_ID) {
5912 		/* just mark; */
5913 
5914 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5915 		/* If this is an untrusted pointer, all pointers formed by walking it
5916 		 * also inherit the untrusted flag.
5917 		 */
5918 		flag = PTR_UNTRUSTED;
5919 
5920 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5921 		/* By default any pointer obtained from walking a trusted pointer is no
5922 		 * longer trusted, unless the field being accessed has explicitly been
5923 		 * marked as inheriting its parent's state of trust (either full or RCU).
5924 		 * For example:
5925 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
5926 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
5927 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5928 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5929 		 *
5930 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
5931 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
5932 		 */
5933 		if (type_is_trusted(env, reg, field_name, btf_id)) {
5934 			flag |= PTR_TRUSTED;
5935 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5936 			if (type_is_rcu(env, reg, field_name, btf_id)) {
5937 				/* ignore __rcu tag and mark it MEM_RCU */
5938 				flag |= MEM_RCU;
5939 			} else if (flag & MEM_RCU ||
5940 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5941 				/* __rcu tagged pointers can be NULL */
5942 				flag |= MEM_RCU | PTR_MAYBE_NULL;
5943 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
5944 				/* keep as-is */
5945 			} else {
5946 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5947 				clear_trusted_flags(&flag);
5948 			}
5949 		} else {
5950 			/*
5951 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
5952 			 * aggressively mark as untrusted otherwise such
5953 			 * pointers will be plain PTR_TO_BTF_ID without flags
5954 			 * and will be allowed to be passed into helpers for
5955 			 * compat reasons.
5956 			 */
5957 			flag = PTR_UNTRUSTED;
5958 		}
5959 	} else {
5960 		/* Old compat. Deprecated */
5961 		clear_trusted_flags(&flag);
5962 	}
5963 
5964 	if (atype == BPF_READ && value_regno >= 0)
5965 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5966 
5967 	return 0;
5968 }
5969 
5970 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5971 				   struct bpf_reg_state *regs,
5972 				   int regno, int off, int size,
5973 				   enum bpf_access_type atype,
5974 				   int value_regno)
5975 {
5976 	struct bpf_reg_state *reg = regs + regno;
5977 	struct bpf_map *map = reg->map_ptr;
5978 	struct bpf_reg_state map_reg;
5979 	enum bpf_type_flag flag = 0;
5980 	const struct btf_type *t;
5981 	const char *tname;
5982 	u32 btf_id;
5983 	int ret;
5984 
5985 	if (!btf_vmlinux) {
5986 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5987 		return -ENOTSUPP;
5988 	}
5989 
5990 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5991 		verbose(env, "map_ptr access not supported for map type %d\n",
5992 			map->map_type);
5993 		return -ENOTSUPP;
5994 	}
5995 
5996 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5997 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5998 
5999 	if (!env->allow_ptr_leaks) {
6000 		verbose(env,
6001 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6002 			tname);
6003 		return -EPERM;
6004 	}
6005 
6006 	if (off < 0) {
6007 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6008 			regno, tname, off);
6009 		return -EACCES;
6010 	}
6011 
6012 	if (atype != BPF_READ) {
6013 		verbose(env, "only read from %s is supported\n", tname);
6014 		return -EACCES;
6015 	}
6016 
6017 	/* Simulate access to a PTR_TO_BTF_ID */
6018 	memset(&map_reg, 0, sizeof(map_reg));
6019 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6020 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6021 	if (ret < 0)
6022 		return ret;
6023 
6024 	if (value_regno >= 0)
6025 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6026 
6027 	return 0;
6028 }
6029 
6030 /* Check that the stack access at the given offset is within bounds. The
6031  * maximum valid offset is -1.
6032  *
6033  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6034  * -state->allocated_stack for reads.
6035  */
6036 static int check_stack_slot_within_bounds(int off,
6037 					  struct bpf_func_state *state,
6038 					  enum bpf_access_type t)
6039 {
6040 	int min_valid_off;
6041 
6042 	if (t == BPF_WRITE)
6043 		min_valid_off = -MAX_BPF_STACK;
6044 	else
6045 		min_valid_off = -state->allocated_stack;
6046 
6047 	if (off < min_valid_off || off > -1)
6048 		return -EACCES;
6049 	return 0;
6050 }
6051 
6052 /* Check that the stack access at 'regno + off' falls within the maximum stack
6053  * bounds.
6054  *
6055  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6056  */
6057 static int check_stack_access_within_bounds(
6058 		struct bpf_verifier_env *env,
6059 		int regno, int off, int access_size,
6060 		enum bpf_access_src src, enum bpf_access_type type)
6061 {
6062 	struct bpf_reg_state *regs = cur_regs(env);
6063 	struct bpf_reg_state *reg = regs + regno;
6064 	struct bpf_func_state *state = func(env, reg);
6065 	int min_off, max_off;
6066 	int err;
6067 	char *err_extra;
6068 
6069 	if (src == ACCESS_HELPER)
6070 		/* We don't know if helpers are reading or writing (or both). */
6071 		err_extra = " indirect access to";
6072 	else if (type == BPF_READ)
6073 		err_extra = " read from";
6074 	else
6075 		err_extra = " write to";
6076 
6077 	if (tnum_is_const(reg->var_off)) {
6078 		min_off = reg->var_off.value + off;
6079 		if (access_size > 0)
6080 			max_off = min_off + access_size - 1;
6081 		else
6082 			max_off = min_off;
6083 	} else {
6084 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6085 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6086 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6087 				err_extra, regno);
6088 			return -EACCES;
6089 		}
6090 		min_off = reg->smin_value + off;
6091 		if (access_size > 0)
6092 			max_off = reg->smax_value + off + access_size - 1;
6093 		else
6094 			max_off = min_off;
6095 	}
6096 
6097 	err = check_stack_slot_within_bounds(min_off, state, type);
6098 	if (!err)
6099 		err = check_stack_slot_within_bounds(max_off, state, type);
6100 
6101 	if (err) {
6102 		if (tnum_is_const(reg->var_off)) {
6103 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6104 				err_extra, regno, off, access_size);
6105 		} else {
6106 			char tn_buf[48];
6107 
6108 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6109 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6110 				err_extra, regno, tn_buf, access_size);
6111 		}
6112 	}
6113 	return err;
6114 }
6115 
6116 /* check whether memory at (regno + off) is accessible for t = (read | write)
6117  * if t==write, value_regno is a register which value is stored into memory
6118  * if t==read, value_regno is a register which will receive the value from memory
6119  * if t==write && value_regno==-1, some unknown value is stored into memory
6120  * if t==read && value_regno==-1, don't care what we read from memory
6121  */
6122 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6123 			    int off, int bpf_size, enum bpf_access_type t,
6124 			    int value_regno, bool strict_alignment_once)
6125 {
6126 	struct bpf_reg_state *regs = cur_regs(env);
6127 	struct bpf_reg_state *reg = regs + regno;
6128 	struct bpf_func_state *state;
6129 	int size, err = 0;
6130 
6131 	size = bpf_size_to_bytes(bpf_size);
6132 	if (size < 0)
6133 		return size;
6134 
6135 	/* alignment checks will add in reg->off themselves */
6136 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6137 	if (err)
6138 		return err;
6139 
6140 	/* for access checks, reg->off is just part of off */
6141 	off += reg->off;
6142 
6143 	if (reg->type == PTR_TO_MAP_KEY) {
6144 		if (t == BPF_WRITE) {
6145 			verbose(env, "write to change key R%d not allowed\n", regno);
6146 			return -EACCES;
6147 		}
6148 
6149 		err = check_mem_region_access(env, regno, off, size,
6150 					      reg->map_ptr->key_size, false);
6151 		if (err)
6152 			return err;
6153 		if (value_regno >= 0)
6154 			mark_reg_unknown(env, regs, value_regno);
6155 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6156 		struct btf_field *kptr_field = NULL;
6157 
6158 		if (t == BPF_WRITE && value_regno >= 0 &&
6159 		    is_pointer_value(env, value_regno)) {
6160 			verbose(env, "R%d leaks addr into map\n", value_regno);
6161 			return -EACCES;
6162 		}
6163 		err = check_map_access_type(env, regno, off, size, t);
6164 		if (err)
6165 			return err;
6166 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6167 		if (err)
6168 			return err;
6169 		if (tnum_is_const(reg->var_off))
6170 			kptr_field = btf_record_find(reg->map_ptr->record,
6171 						     off + reg->var_off.value, BPF_KPTR);
6172 		if (kptr_field) {
6173 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6174 		} else if (t == BPF_READ && value_regno >= 0) {
6175 			struct bpf_map *map = reg->map_ptr;
6176 
6177 			/* if map is read-only, track its contents as scalars */
6178 			if (tnum_is_const(reg->var_off) &&
6179 			    bpf_map_is_rdonly(map) &&
6180 			    map->ops->map_direct_value_addr) {
6181 				int map_off = off + reg->var_off.value;
6182 				u64 val = 0;
6183 
6184 				err = bpf_map_direct_read(map, map_off, size,
6185 							  &val);
6186 				if (err)
6187 					return err;
6188 
6189 				regs[value_regno].type = SCALAR_VALUE;
6190 				__mark_reg_known(&regs[value_regno], val);
6191 			} else {
6192 				mark_reg_unknown(env, regs, value_regno);
6193 			}
6194 		}
6195 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6196 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6197 
6198 		if (type_may_be_null(reg->type)) {
6199 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6200 				reg_type_str(env, reg->type));
6201 			return -EACCES;
6202 		}
6203 
6204 		if (t == BPF_WRITE && rdonly_mem) {
6205 			verbose(env, "R%d cannot write into %s\n",
6206 				regno, reg_type_str(env, reg->type));
6207 			return -EACCES;
6208 		}
6209 
6210 		if (t == BPF_WRITE && value_regno >= 0 &&
6211 		    is_pointer_value(env, value_regno)) {
6212 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6213 			return -EACCES;
6214 		}
6215 
6216 		err = check_mem_region_access(env, regno, off, size,
6217 					      reg->mem_size, false);
6218 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6219 			mark_reg_unknown(env, regs, value_regno);
6220 	} else if (reg->type == PTR_TO_CTX) {
6221 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6222 		struct btf *btf = NULL;
6223 		u32 btf_id = 0;
6224 
6225 		if (t == BPF_WRITE && value_regno >= 0 &&
6226 		    is_pointer_value(env, value_regno)) {
6227 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6228 			return -EACCES;
6229 		}
6230 
6231 		err = check_ptr_off_reg(env, reg, regno);
6232 		if (err < 0)
6233 			return err;
6234 
6235 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6236 				       &btf_id);
6237 		if (err)
6238 			verbose_linfo(env, insn_idx, "; ");
6239 		if (!err && t == BPF_READ && value_regno >= 0) {
6240 			/* ctx access returns either a scalar, or a
6241 			 * PTR_TO_PACKET[_META,_END]. In the latter
6242 			 * case, we know the offset is zero.
6243 			 */
6244 			if (reg_type == SCALAR_VALUE) {
6245 				mark_reg_unknown(env, regs, value_regno);
6246 			} else {
6247 				mark_reg_known_zero(env, regs,
6248 						    value_regno);
6249 				if (type_may_be_null(reg_type))
6250 					regs[value_regno].id = ++env->id_gen;
6251 				/* A load of ctx field could have different
6252 				 * actual load size with the one encoded in the
6253 				 * insn. When the dst is PTR, it is for sure not
6254 				 * a sub-register.
6255 				 */
6256 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6257 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6258 					regs[value_regno].btf = btf;
6259 					regs[value_regno].btf_id = btf_id;
6260 				}
6261 			}
6262 			regs[value_regno].type = reg_type;
6263 		}
6264 
6265 	} else if (reg->type == PTR_TO_STACK) {
6266 		/* Basic bounds checks. */
6267 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6268 		if (err)
6269 			return err;
6270 
6271 		state = func(env, reg);
6272 		err = update_stack_depth(env, state, off);
6273 		if (err)
6274 			return err;
6275 
6276 		if (t == BPF_READ)
6277 			err = check_stack_read(env, regno, off, size,
6278 					       value_regno);
6279 		else
6280 			err = check_stack_write(env, regno, off, size,
6281 						value_regno, insn_idx);
6282 	} else if (reg_is_pkt_pointer(reg)) {
6283 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6284 			verbose(env, "cannot write into packet\n");
6285 			return -EACCES;
6286 		}
6287 		if (t == BPF_WRITE && value_regno >= 0 &&
6288 		    is_pointer_value(env, value_regno)) {
6289 			verbose(env, "R%d leaks addr into packet\n",
6290 				value_regno);
6291 			return -EACCES;
6292 		}
6293 		err = check_packet_access(env, regno, off, size, false);
6294 		if (!err && t == BPF_READ && value_regno >= 0)
6295 			mark_reg_unknown(env, regs, value_regno);
6296 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6297 		if (t == BPF_WRITE && value_regno >= 0 &&
6298 		    is_pointer_value(env, value_regno)) {
6299 			verbose(env, "R%d leaks addr into flow keys\n",
6300 				value_regno);
6301 			return -EACCES;
6302 		}
6303 
6304 		err = check_flow_keys_access(env, off, size);
6305 		if (!err && t == BPF_READ && value_regno >= 0)
6306 			mark_reg_unknown(env, regs, value_regno);
6307 	} else if (type_is_sk_pointer(reg->type)) {
6308 		if (t == BPF_WRITE) {
6309 			verbose(env, "R%d cannot write into %s\n",
6310 				regno, reg_type_str(env, reg->type));
6311 			return -EACCES;
6312 		}
6313 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6314 		if (!err && value_regno >= 0)
6315 			mark_reg_unknown(env, regs, value_regno);
6316 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6317 		err = check_tp_buffer_access(env, reg, regno, off, size);
6318 		if (!err && t == BPF_READ && value_regno >= 0)
6319 			mark_reg_unknown(env, regs, value_regno);
6320 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6321 		   !type_may_be_null(reg->type)) {
6322 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6323 					      value_regno);
6324 	} else if (reg->type == CONST_PTR_TO_MAP) {
6325 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6326 					      value_regno);
6327 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6328 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6329 		u32 *max_access;
6330 
6331 		if (rdonly_mem) {
6332 			if (t == BPF_WRITE) {
6333 				verbose(env, "R%d cannot write into %s\n",
6334 					regno, reg_type_str(env, reg->type));
6335 				return -EACCES;
6336 			}
6337 			max_access = &env->prog->aux->max_rdonly_access;
6338 		} else {
6339 			max_access = &env->prog->aux->max_rdwr_access;
6340 		}
6341 
6342 		err = check_buffer_access(env, reg, regno, off, size, false,
6343 					  max_access);
6344 
6345 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6346 			mark_reg_unknown(env, regs, value_regno);
6347 	} else {
6348 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6349 			reg_type_str(env, reg->type));
6350 		return -EACCES;
6351 	}
6352 
6353 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6354 	    regs[value_regno].type == SCALAR_VALUE) {
6355 		/* b/h/w load zero-extends, mark upper bits as known 0 */
6356 		coerce_reg_to_size(&regs[value_regno], size);
6357 	}
6358 	return err;
6359 }
6360 
6361 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6362 {
6363 	int load_reg;
6364 	int err;
6365 
6366 	switch (insn->imm) {
6367 	case BPF_ADD:
6368 	case BPF_ADD | BPF_FETCH:
6369 	case BPF_AND:
6370 	case BPF_AND | BPF_FETCH:
6371 	case BPF_OR:
6372 	case BPF_OR | BPF_FETCH:
6373 	case BPF_XOR:
6374 	case BPF_XOR | BPF_FETCH:
6375 	case BPF_XCHG:
6376 	case BPF_CMPXCHG:
6377 		break;
6378 	default:
6379 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6380 		return -EINVAL;
6381 	}
6382 
6383 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6384 		verbose(env, "invalid atomic operand size\n");
6385 		return -EINVAL;
6386 	}
6387 
6388 	/* check src1 operand */
6389 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6390 	if (err)
6391 		return err;
6392 
6393 	/* check src2 operand */
6394 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6395 	if (err)
6396 		return err;
6397 
6398 	if (insn->imm == BPF_CMPXCHG) {
6399 		/* Check comparison of R0 with memory location */
6400 		const u32 aux_reg = BPF_REG_0;
6401 
6402 		err = check_reg_arg(env, aux_reg, SRC_OP);
6403 		if (err)
6404 			return err;
6405 
6406 		if (is_pointer_value(env, aux_reg)) {
6407 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6408 			return -EACCES;
6409 		}
6410 	}
6411 
6412 	if (is_pointer_value(env, insn->src_reg)) {
6413 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6414 		return -EACCES;
6415 	}
6416 
6417 	if (is_ctx_reg(env, insn->dst_reg) ||
6418 	    is_pkt_reg(env, insn->dst_reg) ||
6419 	    is_flow_key_reg(env, insn->dst_reg) ||
6420 	    is_sk_reg(env, insn->dst_reg)) {
6421 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6422 			insn->dst_reg,
6423 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6424 		return -EACCES;
6425 	}
6426 
6427 	if (insn->imm & BPF_FETCH) {
6428 		if (insn->imm == BPF_CMPXCHG)
6429 			load_reg = BPF_REG_0;
6430 		else
6431 			load_reg = insn->src_reg;
6432 
6433 		/* check and record load of old value */
6434 		err = check_reg_arg(env, load_reg, DST_OP);
6435 		if (err)
6436 			return err;
6437 	} else {
6438 		/* This instruction accesses a memory location but doesn't
6439 		 * actually load it into a register.
6440 		 */
6441 		load_reg = -1;
6442 	}
6443 
6444 	/* Check whether we can read the memory, with second call for fetch
6445 	 * case to simulate the register fill.
6446 	 */
6447 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6448 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
6449 	if (!err && load_reg >= 0)
6450 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6451 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6452 				       true);
6453 	if (err)
6454 		return err;
6455 
6456 	/* Check whether we can write into the same memory. */
6457 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6458 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6459 	if (err)
6460 		return err;
6461 
6462 	return 0;
6463 }
6464 
6465 /* When register 'regno' is used to read the stack (either directly or through
6466  * a helper function) make sure that it's within stack boundary and, depending
6467  * on the access type, that all elements of the stack are initialized.
6468  *
6469  * 'off' includes 'regno->off', but not its dynamic part (if any).
6470  *
6471  * All registers that have been spilled on the stack in the slots within the
6472  * read offsets are marked as read.
6473  */
6474 static int check_stack_range_initialized(
6475 		struct bpf_verifier_env *env, int regno, int off,
6476 		int access_size, bool zero_size_allowed,
6477 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6478 {
6479 	struct bpf_reg_state *reg = reg_state(env, regno);
6480 	struct bpf_func_state *state = func(env, reg);
6481 	int err, min_off, max_off, i, j, slot, spi;
6482 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6483 	enum bpf_access_type bounds_check_type;
6484 	/* Some accesses can write anything into the stack, others are
6485 	 * read-only.
6486 	 */
6487 	bool clobber = false;
6488 
6489 	if (access_size == 0 && !zero_size_allowed) {
6490 		verbose(env, "invalid zero-sized read\n");
6491 		return -EACCES;
6492 	}
6493 
6494 	if (type == ACCESS_HELPER) {
6495 		/* The bounds checks for writes are more permissive than for
6496 		 * reads. However, if raw_mode is not set, we'll do extra
6497 		 * checks below.
6498 		 */
6499 		bounds_check_type = BPF_WRITE;
6500 		clobber = true;
6501 	} else {
6502 		bounds_check_type = BPF_READ;
6503 	}
6504 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6505 					       type, bounds_check_type);
6506 	if (err)
6507 		return err;
6508 
6509 
6510 	if (tnum_is_const(reg->var_off)) {
6511 		min_off = max_off = reg->var_off.value + off;
6512 	} else {
6513 		/* Variable offset is prohibited for unprivileged mode for
6514 		 * simplicity since it requires corresponding support in
6515 		 * Spectre masking for stack ALU.
6516 		 * See also retrieve_ptr_limit().
6517 		 */
6518 		if (!env->bypass_spec_v1) {
6519 			char tn_buf[48];
6520 
6521 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6522 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6523 				regno, err_extra, tn_buf);
6524 			return -EACCES;
6525 		}
6526 		/* Only initialized buffer on stack is allowed to be accessed
6527 		 * with variable offset. With uninitialized buffer it's hard to
6528 		 * guarantee that whole memory is marked as initialized on
6529 		 * helper return since specific bounds are unknown what may
6530 		 * cause uninitialized stack leaking.
6531 		 */
6532 		if (meta && meta->raw_mode)
6533 			meta = NULL;
6534 
6535 		min_off = reg->smin_value + off;
6536 		max_off = reg->smax_value + off;
6537 	}
6538 
6539 	if (meta && meta->raw_mode) {
6540 		/* Ensure we won't be overwriting dynptrs when simulating byte
6541 		 * by byte access in check_helper_call using meta.access_size.
6542 		 * This would be a problem if we have a helper in the future
6543 		 * which takes:
6544 		 *
6545 		 *	helper(uninit_mem, len, dynptr)
6546 		 *
6547 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6548 		 * may end up writing to dynptr itself when touching memory from
6549 		 * arg 1. This can be relaxed on a case by case basis for known
6550 		 * safe cases, but reject due to the possibilitiy of aliasing by
6551 		 * default.
6552 		 */
6553 		for (i = min_off; i < max_off + access_size; i++) {
6554 			int stack_off = -i - 1;
6555 
6556 			spi = __get_spi(i);
6557 			/* raw_mode may write past allocated_stack */
6558 			if (state->allocated_stack <= stack_off)
6559 				continue;
6560 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6561 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6562 				return -EACCES;
6563 			}
6564 		}
6565 		meta->access_size = access_size;
6566 		meta->regno = regno;
6567 		return 0;
6568 	}
6569 
6570 	for (i = min_off; i < max_off + access_size; i++) {
6571 		u8 *stype;
6572 
6573 		slot = -i - 1;
6574 		spi = slot / BPF_REG_SIZE;
6575 		if (state->allocated_stack <= slot)
6576 			goto err;
6577 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6578 		if (*stype == STACK_MISC)
6579 			goto mark;
6580 		if ((*stype == STACK_ZERO) ||
6581 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6582 			if (clobber) {
6583 				/* helper can write anything into the stack */
6584 				*stype = STACK_MISC;
6585 			}
6586 			goto mark;
6587 		}
6588 
6589 		if (is_spilled_reg(&state->stack[spi]) &&
6590 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6591 		     env->allow_ptr_leaks)) {
6592 			if (clobber) {
6593 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6594 				for (j = 0; j < BPF_REG_SIZE; j++)
6595 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6596 			}
6597 			goto mark;
6598 		}
6599 
6600 err:
6601 		if (tnum_is_const(reg->var_off)) {
6602 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6603 				err_extra, regno, min_off, i - min_off, access_size);
6604 		} else {
6605 			char tn_buf[48];
6606 
6607 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6608 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6609 				err_extra, regno, tn_buf, i - min_off, access_size);
6610 		}
6611 		return -EACCES;
6612 mark:
6613 		/* reading any byte out of 8-byte 'spill_slot' will cause
6614 		 * the whole slot to be marked as 'read'
6615 		 */
6616 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6617 			      state->stack[spi].spilled_ptr.parent,
6618 			      REG_LIVE_READ64);
6619 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6620 		 * be sure that whether stack slot is written to or not. Hence,
6621 		 * we must still conservatively propagate reads upwards even if
6622 		 * helper may write to the entire memory range.
6623 		 */
6624 	}
6625 	return update_stack_depth(env, state, min_off);
6626 }
6627 
6628 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6629 				   int access_size, bool zero_size_allowed,
6630 				   struct bpf_call_arg_meta *meta)
6631 {
6632 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6633 	u32 *max_access;
6634 
6635 	switch (base_type(reg->type)) {
6636 	case PTR_TO_PACKET:
6637 	case PTR_TO_PACKET_META:
6638 		return check_packet_access(env, regno, reg->off, access_size,
6639 					   zero_size_allowed);
6640 	case PTR_TO_MAP_KEY:
6641 		if (meta && meta->raw_mode) {
6642 			verbose(env, "R%d cannot write into %s\n", regno,
6643 				reg_type_str(env, reg->type));
6644 			return -EACCES;
6645 		}
6646 		return check_mem_region_access(env, regno, reg->off, access_size,
6647 					       reg->map_ptr->key_size, false);
6648 	case PTR_TO_MAP_VALUE:
6649 		if (check_map_access_type(env, regno, reg->off, access_size,
6650 					  meta && meta->raw_mode ? BPF_WRITE :
6651 					  BPF_READ))
6652 			return -EACCES;
6653 		return check_map_access(env, regno, reg->off, access_size,
6654 					zero_size_allowed, ACCESS_HELPER);
6655 	case PTR_TO_MEM:
6656 		if (type_is_rdonly_mem(reg->type)) {
6657 			if (meta && meta->raw_mode) {
6658 				verbose(env, "R%d cannot write into %s\n", regno,
6659 					reg_type_str(env, reg->type));
6660 				return -EACCES;
6661 			}
6662 		}
6663 		return check_mem_region_access(env, regno, reg->off,
6664 					       access_size, reg->mem_size,
6665 					       zero_size_allowed);
6666 	case PTR_TO_BUF:
6667 		if (type_is_rdonly_mem(reg->type)) {
6668 			if (meta && meta->raw_mode) {
6669 				verbose(env, "R%d cannot write into %s\n", regno,
6670 					reg_type_str(env, reg->type));
6671 				return -EACCES;
6672 			}
6673 
6674 			max_access = &env->prog->aux->max_rdonly_access;
6675 		} else {
6676 			max_access = &env->prog->aux->max_rdwr_access;
6677 		}
6678 		return check_buffer_access(env, reg, regno, reg->off,
6679 					   access_size, zero_size_allowed,
6680 					   max_access);
6681 	case PTR_TO_STACK:
6682 		return check_stack_range_initialized(
6683 				env,
6684 				regno, reg->off, access_size,
6685 				zero_size_allowed, ACCESS_HELPER, meta);
6686 	case PTR_TO_BTF_ID:
6687 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
6688 					       access_size, BPF_READ, -1);
6689 	case PTR_TO_CTX:
6690 		/* in case the function doesn't know how to access the context,
6691 		 * (because we are in a program of type SYSCALL for example), we
6692 		 * can not statically check its size.
6693 		 * Dynamically check it now.
6694 		 */
6695 		if (!env->ops->convert_ctx_access) {
6696 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6697 			int offset = access_size - 1;
6698 
6699 			/* Allow zero-byte read from PTR_TO_CTX */
6700 			if (access_size == 0)
6701 				return zero_size_allowed ? 0 : -EACCES;
6702 
6703 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6704 						atype, -1, false);
6705 		}
6706 
6707 		fallthrough;
6708 	default: /* scalar_value or invalid ptr */
6709 		/* Allow zero-byte read from NULL, regardless of pointer type */
6710 		if (zero_size_allowed && access_size == 0 &&
6711 		    register_is_null(reg))
6712 			return 0;
6713 
6714 		verbose(env, "R%d type=%s ", regno,
6715 			reg_type_str(env, reg->type));
6716 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6717 		return -EACCES;
6718 	}
6719 }
6720 
6721 static int check_mem_size_reg(struct bpf_verifier_env *env,
6722 			      struct bpf_reg_state *reg, u32 regno,
6723 			      bool zero_size_allowed,
6724 			      struct bpf_call_arg_meta *meta)
6725 {
6726 	int err;
6727 
6728 	/* This is used to refine r0 return value bounds for helpers
6729 	 * that enforce this value as an upper bound on return values.
6730 	 * See do_refine_retval_range() for helpers that can refine
6731 	 * the return value. C type of helper is u32 so we pull register
6732 	 * bound from umax_value however, if negative verifier errors
6733 	 * out. Only upper bounds can be learned because retval is an
6734 	 * int type and negative retvals are allowed.
6735 	 */
6736 	meta->msize_max_value = reg->umax_value;
6737 
6738 	/* The register is SCALAR_VALUE; the access check
6739 	 * happens using its boundaries.
6740 	 */
6741 	if (!tnum_is_const(reg->var_off))
6742 		/* For unprivileged variable accesses, disable raw
6743 		 * mode so that the program is required to
6744 		 * initialize all the memory that the helper could
6745 		 * just partially fill up.
6746 		 */
6747 		meta = NULL;
6748 
6749 	if (reg->smin_value < 0) {
6750 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6751 			regno);
6752 		return -EACCES;
6753 	}
6754 
6755 	if (reg->umin_value == 0) {
6756 		err = check_helper_mem_access(env, regno - 1, 0,
6757 					      zero_size_allowed,
6758 					      meta);
6759 		if (err)
6760 			return err;
6761 	}
6762 
6763 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6764 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6765 			regno);
6766 		return -EACCES;
6767 	}
6768 	err = check_helper_mem_access(env, regno - 1,
6769 				      reg->umax_value,
6770 				      zero_size_allowed, meta);
6771 	if (!err)
6772 		err = mark_chain_precision(env, regno);
6773 	return err;
6774 }
6775 
6776 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6777 		   u32 regno, u32 mem_size)
6778 {
6779 	bool may_be_null = type_may_be_null(reg->type);
6780 	struct bpf_reg_state saved_reg;
6781 	struct bpf_call_arg_meta meta;
6782 	int err;
6783 
6784 	if (register_is_null(reg))
6785 		return 0;
6786 
6787 	memset(&meta, 0, sizeof(meta));
6788 	/* Assuming that the register contains a value check if the memory
6789 	 * access is safe. Temporarily save and restore the register's state as
6790 	 * the conversion shouldn't be visible to a caller.
6791 	 */
6792 	if (may_be_null) {
6793 		saved_reg = *reg;
6794 		mark_ptr_not_null_reg(reg);
6795 	}
6796 
6797 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6798 	/* Check access for BPF_WRITE */
6799 	meta.raw_mode = true;
6800 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6801 
6802 	if (may_be_null)
6803 		*reg = saved_reg;
6804 
6805 	return err;
6806 }
6807 
6808 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6809 				    u32 regno)
6810 {
6811 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6812 	bool may_be_null = type_may_be_null(mem_reg->type);
6813 	struct bpf_reg_state saved_reg;
6814 	struct bpf_call_arg_meta meta;
6815 	int err;
6816 
6817 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6818 
6819 	memset(&meta, 0, sizeof(meta));
6820 
6821 	if (may_be_null) {
6822 		saved_reg = *mem_reg;
6823 		mark_ptr_not_null_reg(mem_reg);
6824 	}
6825 
6826 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6827 	/* Check access for BPF_WRITE */
6828 	meta.raw_mode = true;
6829 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6830 
6831 	if (may_be_null)
6832 		*mem_reg = saved_reg;
6833 	return err;
6834 }
6835 
6836 /* Implementation details:
6837  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6838  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6839  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6840  * Two separate bpf_obj_new will also have different reg->id.
6841  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6842  * clears reg->id after value_or_null->value transition, since the verifier only
6843  * cares about the range of access to valid map value pointer and doesn't care
6844  * about actual address of the map element.
6845  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6846  * reg->id > 0 after value_or_null->value transition. By doing so
6847  * two bpf_map_lookups will be considered two different pointers that
6848  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6849  * returned from bpf_obj_new.
6850  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6851  * dead-locks.
6852  * Since only one bpf_spin_lock is allowed the checks are simpler than
6853  * reg_is_refcounted() logic. The verifier needs to remember only
6854  * one spin_lock instead of array of acquired_refs.
6855  * cur_state->active_lock remembers which map value element or allocated
6856  * object got locked and clears it after bpf_spin_unlock.
6857  */
6858 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6859 			     bool is_lock)
6860 {
6861 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6862 	struct bpf_verifier_state *cur = env->cur_state;
6863 	bool is_const = tnum_is_const(reg->var_off);
6864 	u64 val = reg->var_off.value;
6865 	struct bpf_map *map = NULL;
6866 	struct btf *btf = NULL;
6867 	struct btf_record *rec;
6868 
6869 	if (!is_const) {
6870 		verbose(env,
6871 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6872 			regno);
6873 		return -EINVAL;
6874 	}
6875 	if (reg->type == PTR_TO_MAP_VALUE) {
6876 		map = reg->map_ptr;
6877 		if (!map->btf) {
6878 			verbose(env,
6879 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6880 				map->name);
6881 			return -EINVAL;
6882 		}
6883 	} else {
6884 		btf = reg->btf;
6885 	}
6886 
6887 	rec = reg_btf_record(reg);
6888 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6889 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6890 			map ? map->name : "kptr");
6891 		return -EINVAL;
6892 	}
6893 	if (rec->spin_lock_off != val + reg->off) {
6894 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6895 			val + reg->off, rec->spin_lock_off);
6896 		return -EINVAL;
6897 	}
6898 	if (is_lock) {
6899 		if (cur->active_lock.ptr) {
6900 			verbose(env,
6901 				"Locking two bpf_spin_locks are not allowed\n");
6902 			return -EINVAL;
6903 		}
6904 		if (map)
6905 			cur->active_lock.ptr = map;
6906 		else
6907 			cur->active_lock.ptr = btf;
6908 		cur->active_lock.id = reg->id;
6909 	} else {
6910 		void *ptr;
6911 
6912 		if (map)
6913 			ptr = map;
6914 		else
6915 			ptr = btf;
6916 
6917 		if (!cur->active_lock.ptr) {
6918 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6919 			return -EINVAL;
6920 		}
6921 		if (cur->active_lock.ptr != ptr ||
6922 		    cur->active_lock.id != reg->id) {
6923 			verbose(env, "bpf_spin_unlock of different lock\n");
6924 			return -EINVAL;
6925 		}
6926 
6927 		invalidate_non_owning_refs(env);
6928 
6929 		cur->active_lock.ptr = NULL;
6930 		cur->active_lock.id = 0;
6931 	}
6932 	return 0;
6933 }
6934 
6935 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6936 			      struct bpf_call_arg_meta *meta)
6937 {
6938 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6939 	bool is_const = tnum_is_const(reg->var_off);
6940 	struct bpf_map *map = reg->map_ptr;
6941 	u64 val = reg->var_off.value;
6942 
6943 	if (!is_const) {
6944 		verbose(env,
6945 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6946 			regno);
6947 		return -EINVAL;
6948 	}
6949 	if (!map->btf) {
6950 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6951 			map->name);
6952 		return -EINVAL;
6953 	}
6954 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6955 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6956 		return -EINVAL;
6957 	}
6958 	if (map->record->timer_off != val + reg->off) {
6959 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6960 			val + reg->off, map->record->timer_off);
6961 		return -EINVAL;
6962 	}
6963 	if (meta->map_ptr) {
6964 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6965 		return -EFAULT;
6966 	}
6967 	meta->map_uid = reg->map_uid;
6968 	meta->map_ptr = map;
6969 	return 0;
6970 }
6971 
6972 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6973 			     struct bpf_call_arg_meta *meta)
6974 {
6975 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6976 	struct bpf_map *map_ptr = reg->map_ptr;
6977 	struct btf_field *kptr_field;
6978 	u32 kptr_off;
6979 
6980 	if (!tnum_is_const(reg->var_off)) {
6981 		verbose(env,
6982 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6983 			regno);
6984 		return -EINVAL;
6985 	}
6986 	if (!map_ptr->btf) {
6987 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6988 			map_ptr->name);
6989 		return -EINVAL;
6990 	}
6991 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6992 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6993 		return -EINVAL;
6994 	}
6995 
6996 	meta->map_ptr = map_ptr;
6997 	kptr_off = reg->off + reg->var_off.value;
6998 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6999 	if (!kptr_field) {
7000 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7001 		return -EACCES;
7002 	}
7003 	if (kptr_field->type != BPF_KPTR_REF) {
7004 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7005 		return -EACCES;
7006 	}
7007 	meta->kptr_field = kptr_field;
7008 	return 0;
7009 }
7010 
7011 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7012  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7013  *
7014  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7015  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7016  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7017  *
7018  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7019  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7020  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7021  * mutate the view of the dynptr and also possibly destroy it. In the latter
7022  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7023  * memory that dynptr points to.
7024  *
7025  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7026  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7027  * readonly dynptr view yet, hence only the first case is tracked and checked.
7028  *
7029  * This is consistent with how C applies the const modifier to a struct object,
7030  * where the pointer itself inside bpf_dynptr becomes const but not what it
7031  * points to.
7032  *
7033  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7034  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7035  */
7036 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7037 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7038 {
7039 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7040 	int err;
7041 
7042 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7043 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7044 	 */
7045 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7046 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7047 		return -EFAULT;
7048 	}
7049 
7050 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7051 	 *		 constructing a mutable bpf_dynptr object.
7052 	 *
7053 	 *		 Currently, this is only possible with PTR_TO_STACK
7054 	 *		 pointing to a region of at least 16 bytes which doesn't
7055 	 *		 contain an existing bpf_dynptr.
7056 	 *
7057 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7058 	 *		 mutated or destroyed. However, the memory it points to
7059 	 *		 may be mutated.
7060 	 *
7061 	 *  None       - Points to a initialized dynptr that can be mutated and
7062 	 *		 destroyed, including mutation of the memory it points
7063 	 *		 to.
7064 	 */
7065 	if (arg_type & MEM_UNINIT) {
7066 		int i;
7067 
7068 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7069 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7070 			return -EINVAL;
7071 		}
7072 
7073 		/* we write BPF_DW bits (8 bytes) at a time */
7074 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7075 			err = check_mem_access(env, insn_idx, regno,
7076 					       i, BPF_DW, BPF_WRITE, -1, false);
7077 			if (err)
7078 				return err;
7079 		}
7080 
7081 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7082 	} else /* MEM_RDONLY and None case from above */ {
7083 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7084 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7085 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7086 			return -EINVAL;
7087 		}
7088 
7089 		if (!is_dynptr_reg_valid_init(env, reg)) {
7090 			verbose(env,
7091 				"Expected an initialized dynptr as arg #%d\n",
7092 				regno);
7093 			return -EINVAL;
7094 		}
7095 
7096 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7097 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7098 			verbose(env,
7099 				"Expected a dynptr of type %s as arg #%d\n",
7100 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7101 			return -EINVAL;
7102 		}
7103 
7104 		err = mark_dynptr_read(env, reg);
7105 	}
7106 	return err;
7107 }
7108 
7109 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7110 {
7111 	struct bpf_func_state *state = func(env, reg);
7112 
7113 	return state->stack[spi].spilled_ptr.ref_obj_id;
7114 }
7115 
7116 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7117 {
7118 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7119 }
7120 
7121 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7122 {
7123 	return meta->kfunc_flags & KF_ITER_NEW;
7124 }
7125 
7126 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7127 {
7128 	return meta->kfunc_flags & KF_ITER_NEXT;
7129 }
7130 
7131 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7132 {
7133 	return meta->kfunc_flags & KF_ITER_DESTROY;
7134 }
7135 
7136 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7137 {
7138 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7139 	 * kfunc is iter state pointer
7140 	 */
7141 	return arg == 0 && is_iter_kfunc(meta);
7142 }
7143 
7144 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7145 			    struct bpf_kfunc_call_arg_meta *meta)
7146 {
7147 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7148 	const struct btf_type *t;
7149 	const struct btf_param *arg;
7150 	int spi, err, i, nr_slots;
7151 	u32 btf_id;
7152 
7153 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7154 	arg = &btf_params(meta->func_proto)[0];
7155 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7156 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7157 	nr_slots = t->size / BPF_REG_SIZE;
7158 
7159 	if (is_iter_new_kfunc(meta)) {
7160 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7161 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7162 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7163 				iter_type_str(meta->btf, btf_id), regno);
7164 			return -EINVAL;
7165 		}
7166 
7167 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7168 			err = check_mem_access(env, insn_idx, regno,
7169 					       i, BPF_DW, BPF_WRITE, -1, false);
7170 			if (err)
7171 				return err;
7172 		}
7173 
7174 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7175 		if (err)
7176 			return err;
7177 	} else {
7178 		/* iter_next() or iter_destroy() expect initialized iter state*/
7179 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7180 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7181 				iter_type_str(meta->btf, btf_id), regno);
7182 			return -EINVAL;
7183 		}
7184 
7185 		spi = iter_get_spi(env, reg, nr_slots);
7186 		if (spi < 0)
7187 			return spi;
7188 
7189 		err = mark_iter_read(env, reg, spi, nr_slots);
7190 		if (err)
7191 			return err;
7192 
7193 		/* remember meta->iter info for process_iter_next_call() */
7194 		meta->iter.spi = spi;
7195 		meta->iter.frameno = reg->frameno;
7196 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7197 
7198 		if (is_iter_destroy_kfunc(meta)) {
7199 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7200 			if (err)
7201 				return err;
7202 		}
7203 	}
7204 
7205 	return 0;
7206 }
7207 
7208 /* process_iter_next_call() is called when verifier gets to iterator's next
7209  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7210  * to it as just "iter_next()" in comments below.
7211  *
7212  * BPF verifier relies on a crucial contract for any iter_next()
7213  * implementation: it should *eventually* return NULL, and once that happens
7214  * it should keep returning NULL. That is, once iterator exhausts elements to
7215  * iterate, it should never reset or spuriously return new elements.
7216  *
7217  * With the assumption of such contract, process_iter_next_call() simulates
7218  * a fork in the verifier state to validate loop logic correctness and safety
7219  * without having to simulate infinite amount of iterations.
7220  *
7221  * In current state, we first assume that iter_next() returned NULL and
7222  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7223  * conditions we should not form an infinite loop and should eventually reach
7224  * exit.
7225  *
7226  * Besides that, we also fork current state and enqueue it for later
7227  * verification. In a forked state we keep iterator state as ACTIVE
7228  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7229  * also bump iteration depth to prevent erroneous infinite loop detection
7230  * later on (see iter_active_depths_differ() comment for details). In this
7231  * state we assume that we'll eventually loop back to another iter_next()
7232  * calls (it could be in exactly same location or in some other instruction,
7233  * it doesn't matter, we don't make any unnecessary assumptions about this,
7234  * everything revolves around iterator state in a stack slot, not which
7235  * instruction is calling iter_next()). When that happens, we either will come
7236  * to iter_next() with equivalent state and can conclude that next iteration
7237  * will proceed in exactly the same way as we just verified, so it's safe to
7238  * assume that loop converges. If not, we'll go on another iteration
7239  * simulation with a different input state, until all possible starting states
7240  * are validated or we reach maximum number of instructions limit.
7241  *
7242  * This way, we will either exhaustively discover all possible input states
7243  * that iterator loop can start with and eventually will converge, or we'll
7244  * effectively regress into bounded loop simulation logic and either reach
7245  * maximum number of instructions if loop is not provably convergent, or there
7246  * is some statically known limit on number of iterations (e.g., if there is
7247  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7248  *
7249  * One very subtle but very important aspect is that we *always* simulate NULL
7250  * condition first (as the current state) before we simulate non-NULL case.
7251  * This has to do with intricacies of scalar precision tracking. By simulating
7252  * "exit condition" of iter_next() returning NULL first, we make sure all the
7253  * relevant precision marks *that will be set **after** we exit iterator loop*
7254  * are propagated backwards to common parent state of NULL and non-NULL
7255  * branches. Thanks to that, state equivalence checks done later in forked
7256  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7257  * precision marks are finalized and won't change. Because simulating another
7258  * ACTIVE iterator iteration won't change them (because given same input
7259  * states we'll end up with exactly same output states which we are currently
7260  * comparing; and verification after the loop already propagated back what
7261  * needs to be **additionally** tracked as precise). It's subtle, grok
7262  * precision tracking for more intuitive understanding.
7263  */
7264 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7265 				  struct bpf_kfunc_call_arg_meta *meta)
7266 {
7267 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7268 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7269 	struct bpf_reg_state *cur_iter, *queued_iter;
7270 	int iter_frameno = meta->iter.frameno;
7271 	int iter_spi = meta->iter.spi;
7272 
7273 	BTF_TYPE_EMIT(struct bpf_iter);
7274 
7275 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7276 
7277 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7278 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7279 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7280 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7281 		return -EFAULT;
7282 	}
7283 
7284 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7285 		/* branch out active iter state */
7286 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7287 		if (!queued_st)
7288 			return -ENOMEM;
7289 
7290 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7291 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7292 		queued_iter->iter.depth++;
7293 
7294 		queued_fr = queued_st->frame[queued_st->curframe];
7295 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7296 	}
7297 
7298 	/* switch to DRAINED state, but keep the depth unchanged */
7299 	/* mark current iter state as drained and assume returned NULL */
7300 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7301 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7302 
7303 	return 0;
7304 }
7305 
7306 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7307 {
7308 	return type == ARG_CONST_SIZE ||
7309 	       type == ARG_CONST_SIZE_OR_ZERO;
7310 }
7311 
7312 static bool arg_type_is_release(enum bpf_arg_type type)
7313 {
7314 	return type & OBJ_RELEASE;
7315 }
7316 
7317 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7318 {
7319 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7320 }
7321 
7322 static int int_ptr_type_to_size(enum bpf_arg_type type)
7323 {
7324 	if (type == ARG_PTR_TO_INT)
7325 		return sizeof(u32);
7326 	else if (type == ARG_PTR_TO_LONG)
7327 		return sizeof(u64);
7328 
7329 	return -EINVAL;
7330 }
7331 
7332 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7333 				 const struct bpf_call_arg_meta *meta,
7334 				 enum bpf_arg_type *arg_type)
7335 {
7336 	if (!meta->map_ptr) {
7337 		/* kernel subsystem misconfigured verifier */
7338 		verbose(env, "invalid map_ptr to access map->type\n");
7339 		return -EACCES;
7340 	}
7341 
7342 	switch (meta->map_ptr->map_type) {
7343 	case BPF_MAP_TYPE_SOCKMAP:
7344 	case BPF_MAP_TYPE_SOCKHASH:
7345 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7346 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7347 		} else {
7348 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7349 			return -EINVAL;
7350 		}
7351 		break;
7352 	case BPF_MAP_TYPE_BLOOM_FILTER:
7353 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7354 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7355 		break;
7356 	default:
7357 		break;
7358 	}
7359 	return 0;
7360 }
7361 
7362 struct bpf_reg_types {
7363 	const enum bpf_reg_type types[10];
7364 	u32 *btf_id;
7365 };
7366 
7367 static const struct bpf_reg_types sock_types = {
7368 	.types = {
7369 		PTR_TO_SOCK_COMMON,
7370 		PTR_TO_SOCKET,
7371 		PTR_TO_TCP_SOCK,
7372 		PTR_TO_XDP_SOCK,
7373 	},
7374 };
7375 
7376 #ifdef CONFIG_NET
7377 static const struct bpf_reg_types btf_id_sock_common_types = {
7378 	.types = {
7379 		PTR_TO_SOCK_COMMON,
7380 		PTR_TO_SOCKET,
7381 		PTR_TO_TCP_SOCK,
7382 		PTR_TO_XDP_SOCK,
7383 		PTR_TO_BTF_ID,
7384 		PTR_TO_BTF_ID | PTR_TRUSTED,
7385 	},
7386 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7387 };
7388 #endif
7389 
7390 static const struct bpf_reg_types mem_types = {
7391 	.types = {
7392 		PTR_TO_STACK,
7393 		PTR_TO_PACKET,
7394 		PTR_TO_PACKET_META,
7395 		PTR_TO_MAP_KEY,
7396 		PTR_TO_MAP_VALUE,
7397 		PTR_TO_MEM,
7398 		PTR_TO_MEM | MEM_RINGBUF,
7399 		PTR_TO_BUF,
7400 		PTR_TO_BTF_ID | PTR_TRUSTED,
7401 	},
7402 };
7403 
7404 static const struct bpf_reg_types int_ptr_types = {
7405 	.types = {
7406 		PTR_TO_STACK,
7407 		PTR_TO_PACKET,
7408 		PTR_TO_PACKET_META,
7409 		PTR_TO_MAP_KEY,
7410 		PTR_TO_MAP_VALUE,
7411 	},
7412 };
7413 
7414 static const struct bpf_reg_types spin_lock_types = {
7415 	.types = {
7416 		PTR_TO_MAP_VALUE,
7417 		PTR_TO_BTF_ID | MEM_ALLOC,
7418 	}
7419 };
7420 
7421 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7422 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7423 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7424 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7425 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7426 static const struct bpf_reg_types btf_ptr_types = {
7427 	.types = {
7428 		PTR_TO_BTF_ID,
7429 		PTR_TO_BTF_ID | PTR_TRUSTED,
7430 		PTR_TO_BTF_ID | MEM_RCU,
7431 	},
7432 };
7433 static const struct bpf_reg_types percpu_btf_ptr_types = {
7434 	.types = {
7435 		PTR_TO_BTF_ID | MEM_PERCPU,
7436 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7437 	}
7438 };
7439 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7440 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7441 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7442 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7443 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7444 static const struct bpf_reg_types dynptr_types = {
7445 	.types = {
7446 		PTR_TO_STACK,
7447 		CONST_PTR_TO_DYNPTR,
7448 	}
7449 };
7450 
7451 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7452 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7453 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7454 	[ARG_CONST_SIZE]		= &scalar_types,
7455 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7456 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7457 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7458 	[ARG_PTR_TO_CTX]		= &context_types,
7459 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7460 #ifdef CONFIG_NET
7461 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7462 #endif
7463 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7464 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7465 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7466 	[ARG_PTR_TO_MEM]		= &mem_types,
7467 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7468 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7469 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7470 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7471 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7472 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7473 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7474 	[ARG_PTR_TO_TIMER]		= &timer_types,
7475 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7476 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7477 };
7478 
7479 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7480 			  enum bpf_arg_type arg_type,
7481 			  const u32 *arg_btf_id,
7482 			  struct bpf_call_arg_meta *meta)
7483 {
7484 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7485 	enum bpf_reg_type expected, type = reg->type;
7486 	const struct bpf_reg_types *compatible;
7487 	int i, j;
7488 
7489 	compatible = compatible_reg_types[base_type(arg_type)];
7490 	if (!compatible) {
7491 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7492 		return -EFAULT;
7493 	}
7494 
7495 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7496 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7497 	 *
7498 	 * Same for MAYBE_NULL:
7499 	 *
7500 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7501 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7502 	 *
7503 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7504 	 *
7505 	 * Therefore we fold these flags depending on the arg_type before comparison.
7506 	 */
7507 	if (arg_type & MEM_RDONLY)
7508 		type &= ~MEM_RDONLY;
7509 	if (arg_type & PTR_MAYBE_NULL)
7510 		type &= ~PTR_MAYBE_NULL;
7511 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7512 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7513 
7514 	if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7515 		type &= ~MEM_ALLOC;
7516 
7517 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7518 		expected = compatible->types[i];
7519 		if (expected == NOT_INIT)
7520 			break;
7521 
7522 		if (type == expected)
7523 			goto found;
7524 	}
7525 
7526 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7527 	for (j = 0; j + 1 < i; j++)
7528 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7529 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7530 	return -EACCES;
7531 
7532 found:
7533 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7534 		return 0;
7535 
7536 	if (compatible == &mem_types) {
7537 		if (!(arg_type & MEM_RDONLY)) {
7538 			verbose(env,
7539 				"%s() may write into memory pointed by R%d type=%s\n",
7540 				func_id_name(meta->func_id),
7541 				regno, reg_type_str(env, reg->type));
7542 			return -EACCES;
7543 		}
7544 		return 0;
7545 	}
7546 
7547 	switch ((int)reg->type) {
7548 	case PTR_TO_BTF_ID:
7549 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7550 	case PTR_TO_BTF_ID | MEM_RCU:
7551 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7552 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7553 	{
7554 		/* For bpf_sk_release, it needs to match against first member
7555 		 * 'struct sock_common', hence make an exception for it. This
7556 		 * allows bpf_sk_release to work for multiple socket types.
7557 		 */
7558 		bool strict_type_match = arg_type_is_release(arg_type) &&
7559 					 meta->func_id != BPF_FUNC_sk_release;
7560 
7561 		if (type_may_be_null(reg->type) &&
7562 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7563 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7564 			return -EACCES;
7565 		}
7566 
7567 		if (!arg_btf_id) {
7568 			if (!compatible->btf_id) {
7569 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7570 				return -EFAULT;
7571 			}
7572 			arg_btf_id = compatible->btf_id;
7573 		}
7574 
7575 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7576 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7577 				return -EACCES;
7578 		} else {
7579 			if (arg_btf_id == BPF_PTR_POISON) {
7580 				verbose(env, "verifier internal error:");
7581 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7582 					regno);
7583 				return -EACCES;
7584 			}
7585 
7586 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7587 						  btf_vmlinux, *arg_btf_id,
7588 						  strict_type_match)) {
7589 				verbose(env, "R%d is of type %s but %s is expected\n",
7590 					regno, btf_type_name(reg->btf, reg->btf_id),
7591 					btf_type_name(btf_vmlinux, *arg_btf_id));
7592 				return -EACCES;
7593 			}
7594 		}
7595 		break;
7596 	}
7597 	case PTR_TO_BTF_ID | MEM_ALLOC:
7598 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7599 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7600 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7601 			return -EFAULT;
7602 		}
7603 		/* Handled by helper specific checks */
7604 		break;
7605 	case PTR_TO_BTF_ID | MEM_PERCPU:
7606 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7607 		/* Handled by helper specific checks */
7608 		break;
7609 	default:
7610 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7611 		return -EFAULT;
7612 	}
7613 	return 0;
7614 }
7615 
7616 static struct btf_field *
7617 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7618 {
7619 	struct btf_field *field;
7620 	struct btf_record *rec;
7621 
7622 	rec = reg_btf_record(reg);
7623 	if (!rec)
7624 		return NULL;
7625 
7626 	field = btf_record_find(rec, off, fields);
7627 	if (!field)
7628 		return NULL;
7629 
7630 	return field;
7631 }
7632 
7633 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7634 			   const struct bpf_reg_state *reg, int regno,
7635 			   enum bpf_arg_type arg_type)
7636 {
7637 	u32 type = reg->type;
7638 
7639 	/* When referenced register is passed to release function, its fixed
7640 	 * offset must be 0.
7641 	 *
7642 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7643 	 * meta->release_regno.
7644 	 */
7645 	if (arg_type_is_release(arg_type)) {
7646 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7647 		 * may not directly point to the object being released, but to
7648 		 * dynptr pointing to such object, which might be at some offset
7649 		 * on the stack. In that case, we simply to fallback to the
7650 		 * default handling.
7651 		 */
7652 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7653 			return 0;
7654 
7655 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7656 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7657 				return __check_ptr_off_reg(env, reg, regno, true);
7658 
7659 			verbose(env, "R%d must have zero offset when passed to release func\n",
7660 				regno);
7661 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7662 				btf_type_name(reg->btf, reg->btf_id), reg->off);
7663 			return -EINVAL;
7664 		}
7665 
7666 		/* Doing check_ptr_off_reg check for the offset will catch this
7667 		 * because fixed_off_ok is false, but checking here allows us
7668 		 * to give the user a better error message.
7669 		 */
7670 		if (reg->off) {
7671 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7672 				regno);
7673 			return -EINVAL;
7674 		}
7675 		return __check_ptr_off_reg(env, reg, regno, false);
7676 	}
7677 
7678 	switch (type) {
7679 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7680 	case PTR_TO_STACK:
7681 	case PTR_TO_PACKET:
7682 	case PTR_TO_PACKET_META:
7683 	case PTR_TO_MAP_KEY:
7684 	case PTR_TO_MAP_VALUE:
7685 	case PTR_TO_MEM:
7686 	case PTR_TO_MEM | MEM_RDONLY:
7687 	case PTR_TO_MEM | MEM_RINGBUF:
7688 	case PTR_TO_BUF:
7689 	case PTR_TO_BUF | MEM_RDONLY:
7690 	case SCALAR_VALUE:
7691 		return 0;
7692 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7693 	 * fixed offset.
7694 	 */
7695 	case PTR_TO_BTF_ID:
7696 	case PTR_TO_BTF_ID | MEM_ALLOC:
7697 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7698 	case PTR_TO_BTF_ID | MEM_RCU:
7699 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7700 		/* When referenced PTR_TO_BTF_ID is passed to release function,
7701 		 * its fixed offset must be 0. In the other cases, fixed offset
7702 		 * can be non-zero. This was already checked above. So pass
7703 		 * fixed_off_ok as true to allow fixed offset for all other
7704 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7705 		 * still need to do checks instead of returning.
7706 		 */
7707 		return __check_ptr_off_reg(env, reg, regno, true);
7708 	default:
7709 		return __check_ptr_off_reg(env, reg, regno, false);
7710 	}
7711 }
7712 
7713 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7714 						const struct bpf_func_proto *fn,
7715 						struct bpf_reg_state *regs)
7716 {
7717 	struct bpf_reg_state *state = NULL;
7718 	int i;
7719 
7720 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7721 		if (arg_type_is_dynptr(fn->arg_type[i])) {
7722 			if (state) {
7723 				verbose(env, "verifier internal error: multiple dynptr args\n");
7724 				return NULL;
7725 			}
7726 			state = &regs[BPF_REG_1 + i];
7727 		}
7728 
7729 	if (!state)
7730 		verbose(env, "verifier internal error: no dynptr arg found\n");
7731 
7732 	return state;
7733 }
7734 
7735 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7736 {
7737 	struct bpf_func_state *state = func(env, reg);
7738 	int spi;
7739 
7740 	if (reg->type == CONST_PTR_TO_DYNPTR)
7741 		return reg->id;
7742 	spi = dynptr_get_spi(env, reg);
7743 	if (spi < 0)
7744 		return spi;
7745 	return state->stack[spi].spilled_ptr.id;
7746 }
7747 
7748 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7749 {
7750 	struct bpf_func_state *state = func(env, reg);
7751 	int spi;
7752 
7753 	if (reg->type == CONST_PTR_TO_DYNPTR)
7754 		return reg->ref_obj_id;
7755 	spi = dynptr_get_spi(env, reg);
7756 	if (spi < 0)
7757 		return spi;
7758 	return state->stack[spi].spilled_ptr.ref_obj_id;
7759 }
7760 
7761 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7762 					    struct bpf_reg_state *reg)
7763 {
7764 	struct bpf_func_state *state = func(env, reg);
7765 	int spi;
7766 
7767 	if (reg->type == CONST_PTR_TO_DYNPTR)
7768 		return reg->dynptr.type;
7769 
7770 	spi = __get_spi(reg->off);
7771 	if (spi < 0) {
7772 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7773 		return BPF_DYNPTR_TYPE_INVALID;
7774 	}
7775 
7776 	return state->stack[spi].spilled_ptr.dynptr.type;
7777 }
7778 
7779 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7780 			  struct bpf_call_arg_meta *meta,
7781 			  const struct bpf_func_proto *fn,
7782 			  int insn_idx)
7783 {
7784 	u32 regno = BPF_REG_1 + arg;
7785 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7786 	enum bpf_arg_type arg_type = fn->arg_type[arg];
7787 	enum bpf_reg_type type = reg->type;
7788 	u32 *arg_btf_id = NULL;
7789 	int err = 0;
7790 
7791 	if (arg_type == ARG_DONTCARE)
7792 		return 0;
7793 
7794 	err = check_reg_arg(env, regno, SRC_OP);
7795 	if (err)
7796 		return err;
7797 
7798 	if (arg_type == ARG_ANYTHING) {
7799 		if (is_pointer_value(env, regno)) {
7800 			verbose(env, "R%d leaks addr into helper function\n",
7801 				regno);
7802 			return -EACCES;
7803 		}
7804 		return 0;
7805 	}
7806 
7807 	if (type_is_pkt_pointer(type) &&
7808 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7809 		verbose(env, "helper access to the packet is not allowed\n");
7810 		return -EACCES;
7811 	}
7812 
7813 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7814 		err = resolve_map_arg_type(env, meta, &arg_type);
7815 		if (err)
7816 			return err;
7817 	}
7818 
7819 	if (register_is_null(reg) && type_may_be_null(arg_type))
7820 		/* A NULL register has a SCALAR_VALUE type, so skip
7821 		 * type checking.
7822 		 */
7823 		goto skip_type_check;
7824 
7825 	/* arg_btf_id and arg_size are in a union. */
7826 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7827 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7828 		arg_btf_id = fn->arg_btf_id[arg];
7829 
7830 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7831 	if (err)
7832 		return err;
7833 
7834 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7835 	if (err)
7836 		return err;
7837 
7838 skip_type_check:
7839 	if (arg_type_is_release(arg_type)) {
7840 		if (arg_type_is_dynptr(arg_type)) {
7841 			struct bpf_func_state *state = func(env, reg);
7842 			int spi;
7843 
7844 			/* Only dynptr created on stack can be released, thus
7845 			 * the get_spi and stack state checks for spilled_ptr
7846 			 * should only be done before process_dynptr_func for
7847 			 * PTR_TO_STACK.
7848 			 */
7849 			if (reg->type == PTR_TO_STACK) {
7850 				spi = dynptr_get_spi(env, reg);
7851 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7852 					verbose(env, "arg %d is an unacquired reference\n", regno);
7853 					return -EINVAL;
7854 				}
7855 			} else {
7856 				verbose(env, "cannot release unowned const bpf_dynptr\n");
7857 				return -EINVAL;
7858 			}
7859 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
7860 			verbose(env, "R%d must be referenced when passed to release function\n",
7861 				regno);
7862 			return -EINVAL;
7863 		}
7864 		if (meta->release_regno) {
7865 			verbose(env, "verifier internal error: more than one release argument\n");
7866 			return -EFAULT;
7867 		}
7868 		meta->release_regno = regno;
7869 	}
7870 
7871 	if (reg->ref_obj_id) {
7872 		if (meta->ref_obj_id) {
7873 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7874 				regno, reg->ref_obj_id,
7875 				meta->ref_obj_id);
7876 			return -EFAULT;
7877 		}
7878 		meta->ref_obj_id = reg->ref_obj_id;
7879 	}
7880 
7881 	switch (base_type(arg_type)) {
7882 	case ARG_CONST_MAP_PTR:
7883 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7884 		if (meta->map_ptr) {
7885 			/* Use map_uid (which is unique id of inner map) to reject:
7886 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7887 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7888 			 * if (inner_map1 && inner_map2) {
7889 			 *     timer = bpf_map_lookup_elem(inner_map1);
7890 			 *     if (timer)
7891 			 *         // mismatch would have been allowed
7892 			 *         bpf_timer_init(timer, inner_map2);
7893 			 * }
7894 			 *
7895 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
7896 			 */
7897 			if (meta->map_ptr != reg->map_ptr ||
7898 			    meta->map_uid != reg->map_uid) {
7899 				verbose(env,
7900 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7901 					meta->map_uid, reg->map_uid);
7902 				return -EINVAL;
7903 			}
7904 		}
7905 		meta->map_ptr = reg->map_ptr;
7906 		meta->map_uid = reg->map_uid;
7907 		break;
7908 	case ARG_PTR_TO_MAP_KEY:
7909 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
7910 		 * check that [key, key + map->key_size) are within
7911 		 * stack limits and initialized
7912 		 */
7913 		if (!meta->map_ptr) {
7914 			/* in function declaration map_ptr must come before
7915 			 * map_key, so that it's verified and known before
7916 			 * we have to check map_key here. Otherwise it means
7917 			 * that kernel subsystem misconfigured verifier
7918 			 */
7919 			verbose(env, "invalid map_ptr to access map->key\n");
7920 			return -EACCES;
7921 		}
7922 		err = check_helper_mem_access(env, regno,
7923 					      meta->map_ptr->key_size, false,
7924 					      NULL);
7925 		break;
7926 	case ARG_PTR_TO_MAP_VALUE:
7927 		if (type_may_be_null(arg_type) && register_is_null(reg))
7928 			return 0;
7929 
7930 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
7931 		 * check [value, value + map->value_size) validity
7932 		 */
7933 		if (!meta->map_ptr) {
7934 			/* kernel subsystem misconfigured verifier */
7935 			verbose(env, "invalid map_ptr to access map->value\n");
7936 			return -EACCES;
7937 		}
7938 		meta->raw_mode = arg_type & MEM_UNINIT;
7939 		err = check_helper_mem_access(env, regno,
7940 					      meta->map_ptr->value_size, false,
7941 					      meta);
7942 		break;
7943 	case ARG_PTR_TO_PERCPU_BTF_ID:
7944 		if (!reg->btf_id) {
7945 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7946 			return -EACCES;
7947 		}
7948 		meta->ret_btf = reg->btf;
7949 		meta->ret_btf_id = reg->btf_id;
7950 		break;
7951 	case ARG_PTR_TO_SPIN_LOCK:
7952 		if (in_rbtree_lock_required_cb(env)) {
7953 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7954 			return -EACCES;
7955 		}
7956 		if (meta->func_id == BPF_FUNC_spin_lock) {
7957 			err = process_spin_lock(env, regno, true);
7958 			if (err)
7959 				return err;
7960 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
7961 			err = process_spin_lock(env, regno, false);
7962 			if (err)
7963 				return err;
7964 		} else {
7965 			verbose(env, "verifier internal error\n");
7966 			return -EFAULT;
7967 		}
7968 		break;
7969 	case ARG_PTR_TO_TIMER:
7970 		err = process_timer_func(env, regno, meta);
7971 		if (err)
7972 			return err;
7973 		break;
7974 	case ARG_PTR_TO_FUNC:
7975 		meta->subprogno = reg->subprogno;
7976 		break;
7977 	case ARG_PTR_TO_MEM:
7978 		/* The access to this pointer is only checked when we hit the
7979 		 * next is_mem_size argument below.
7980 		 */
7981 		meta->raw_mode = arg_type & MEM_UNINIT;
7982 		if (arg_type & MEM_FIXED_SIZE) {
7983 			err = check_helper_mem_access(env, regno,
7984 						      fn->arg_size[arg], false,
7985 						      meta);
7986 		}
7987 		break;
7988 	case ARG_CONST_SIZE:
7989 		err = check_mem_size_reg(env, reg, regno, false, meta);
7990 		break;
7991 	case ARG_CONST_SIZE_OR_ZERO:
7992 		err = check_mem_size_reg(env, reg, regno, true, meta);
7993 		break;
7994 	case ARG_PTR_TO_DYNPTR:
7995 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
7996 		if (err)
7997 			return err;
7998 		break;
7999 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8000 		if (!tnum_is_const(reg->var_off)) {
8001 			verbose(env, "R%d is not a known constant'\n",
8002 				regno);
8003 			return -EACCES;
8004 		}
8005 		meta->mem_size = reg->var_off.value;
8006 		err = mark_chain_precision(env, regno);
8007 		if (err)
8008 			return err;
8009 		break;
8010 	case ARG_PTR_TO_INT:
8011 	case ARG_PTR_TO_LONG:
8012 	{
8013 		int size = int_ptr_type_to_size(arg_type);
8014 
8015 		err = check_helper_mem_access(env, regno, size, false, meta);
8016 		if (err)
8017 			return err;
8018 		err = check_ptr_alignment(env, reg, 0, size, true);
8019 		break;
8020 	}
8021 	case ARG_PTR_TO_CONST_STR:
8022 	{
8023 		struct bpf_map *map = reg->map_ptr;
8024 		int map_off;
8025 		u64 map_addr;
8026 		char *str_ptr;
8027 
8028 		if (!bpf_map_is_rdonly(map)) {
8029 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8030 			return -EACCES;
8031 		}
8032 
8033 		if (!tnum_is_const(reg->var_off)) {
8034 			verbose(env, "R%d is not a constant address'\n", regno);
8035 			return -EACCES;
8036 		}
8037 
8038 		if (!map->ops->map_direct_value_addr) {
8039 			verbose(env, "no direct value access support for this map type\n");
8040 			return -EACCES;
8041 		}
8042 
8043 		err = check_map_access(env, regno, reg->off,
8044 				       map->value_size - reg->off, false,
8045 				       ACCESS_HELPER);
8046 		if (err)
8047 			return err;
8048 
8049 		map_off = reg->off + reg->var_off.value;
8050 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8051 		if (err) {
8052 			verbose(env, "direct value access on string failed\n");
8053 			return err;
8054 		}
8055 
8056 		str_ptr = (char *)(long)(map_addr);
8057 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8058 			verbose(env, "string is not zero-terminated\n");
8059 			return -EINVAL;
8060 		}
8061 		break;
8062 	}
8063 	case ARG_PTR_TO_KPTR:
8064 		err = process_kptr_func(env, regno, meta);
8065 		if (err)
8066 			return err;
8067 		break;
8068 	}
8069 
8070 	return err;
8071 }
8072 
8073 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8074 {
8075 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8076 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8077 
8078 	if (func_id != BPF_FUNC_map_update_elem)
8079 		return false;
8080 
8081 	/* It's not possible to get access to a locked struct sock in these
8082 	 * contexts, so updating is safe.
8083 	 */
8084 	switch (type) {
8085 	case BPF_PROG_TYPE_TRACING:
8086 		if (eatype == BPF_TRACE_ITER)
8087 			return true;
8088 		break;
8089 	case BPF_PROG_TYPE_SOCKET_FILTER:
8090 	case BPF_PROG_TYPE_SCHED_CLS:
8091 	case BPF_PROG_TYPE_SCHED_ACT:
8092 	case BPF_PROG_TYPE_XDP:
8093 	case BPF_PROG_TYPE_SK_REUSEPORT:
8094 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8095 	case BPF_PROG_TYPE_SK_LOOKUP:
8096 		return true;
8097 	default:
8098 		break;
8099 	}
8100 
8101 	verbose(env, "cannot update sockmap in this context\n");
8102 	return false;
8103 }
8104 
8105 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8106 {
8107 	return env->prog->jit_requested &&
8108 	       bpf_jit_supports_subprog_tailcalls();
8109 }
8110 
8111 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8112 					struct bpf_map *map, int func_id)
8113 {
8114 	if (!map)
8115 		return 0;
8116 
8117 	/* We need a two way check, first is from map perspective ... */
8118 	switch (map->map_type) {
8119 	case BPF_MAP_TYPE_PROG_ARRAY:
8120 		if (func_id != BPF_FUNC_tail_call)
8121 			goto error;
8122 		break;
8123 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8124 		if (func_id != BPF_FUNC_perf_event_read &&
8125 		    func_id != BPF_FUNC_perf_event_output &&
8126 		    func_id != BPF_FUNC_skb_output &&
8127 		    func_id != BPF_FUNC_perf_event_read_value &&
8128 		    func_id != BPF_FUNC_xdp_output)
8129 			goto error;
8130 		break;
8131 	case BPF_MAP_TYPE_RINGBUF:
8132 		if (func_id != BPF_FUNC_ringbuf_output &&
8133 		    func_id != BPF_FUNC_ringbuf_reserve &&
8134 		    func_id != BPF_FUNC_ringbuf_query &&
8135 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8136 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8137 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8138 			goto error;
8139 		break;
8140 	case BPF_MAP_TYPE_USER_RINGBUF:
8141 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8142 			goto error;
8143 		break;
8144 	case BPF_MAP_TYPE_STACK_TRACE:
8145 		if (func_id != BPF_FUNC_get_stackid)
8146 			goto error;
8147 		break;
8148 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8149 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8150 		    func_id != BPF_FUNC_current_task_under_cgroup)
8151 			goto error;
8152 		break;
8153 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8154 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8155 		if (func_id != BPF_FUNC_get_local_storage)
8156 			goto error;
8157 		break;
8158 	case BPF_MAP_TYPE_DEVMAP:
8159 	case BPF_MAP_TYPE_DEVMAP_HASH:
8160 		if (func_id != BPF_FUNC_redirect_map &&
8161 		    func_id != BPF_FUNC_map_lookup_elem)
8162 			goto error;
8163 		break;
8164 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8165 	 * appear.
8166 	 */
8167 	case BPF_MAP_TYPE_CPUMAP:
8168 		if (func_id != BPF_FUNC_redirect_map)
8169 			goto error;
8170 		break;
8171 	case BPF_MAP_TYPE_XSKMAP:
8172 		if (func_id != BPF_FUNC_redirect_map &&
8173 		    func_id != BPF_FUNC_map_lookup_elem)
8174 			goto error;
8175 		break;
8176 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8177 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8178 		if (func_id != BPF_FUNC_map_lookup_elem)
8179 			goto error;
8180 		break;
8181 	case BPF_MAP_TYPE_SOCKMAP:
8182 		if (func_id != BPF_FUNC_sk_redirect_map &&
8183 		    func_id != BPF_FUNC_sock_map_update &&
8184 		    func_id != BPF_FUNC_map_delete_elem &&
8185 		    func_id != BPF_FUNC_msg_redirect_map &&
8186 		    func_id != BPF_FUNC_sk_select_reuseport &&
8187 		    func_id != BPF_FUNC_map_lookup_elem &&
8188 		    !may_update_sockmap(env, func_id))
8189 			goto error;
8190 		break;
8191 	case BPF_MAP_TYPE_SOCKHASH:
8192 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8193 		    func_id != BPF_FUNC_sock_hash_update &&
8194 		    func_id != BPF_FUNC_map_delete_elem &&
8195 		    func_id != BPF_FUNC_msg_redirect_hash &&
8196 		    func_id != BPF_FUNC_sk_select_reuseport &&
8197 		    func_id != BPF_FUNC_map_lookup_elem &&
8198 		    !may_update_sockmap(env, func_id))
8199 			goto error;
8200 		break;
8201 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8202 		if (func_id != BPF_FUNC_sk_select_reuseport)
8203 			goto error;
8204 		break;
8205 	case BPF_MAP_TYPE_QUEUE:
8206 	case BPF_MAP_TYPE_STACK:
8207 		if (func_id != BPF_FUNC_map_peek_elem &&
8208 		    func_id != BPF_FUNC_map_pop_elem &&
8209 		    func_id != BPF_FUNC_map_push_elem)
8210 			goto error;
8211 		break;
8212 	case BPF_MAP_TYPE_SK_STORAGE:
8213 		if (func_id != BPF_FUNC_sk_storage_get &&
8214 		    func_id != BPF_FUNC_sk_storage_delete &&
8215 		    func_id != BPF_FUNC_kptr_xchg)
8216 			goto error;
8217 		break;
8218 	case BPF_MAP_TYPE_INODE_STORAGE:
8219 		if (func_id != BPF_FUNC_inode_storage_get &&
8220 		    func_id != BPF_FUNC_inode_storage_delete &&
8221 		    func_id != BPF_FUNC_kptr_xchg)
8222 			goto error;
8223 		break;
8224 	case BPF_MAP_TYPE_TASK_STORAGE:
8225 		if (func_id != BPF_FUNC_task_storage_get &&
8226 		    func_id != BPF_FUNC_task_storage_delete &&
8227 		    func_id != BPF_FUNC_kptr_xchg)
8228 			goto error;
8229 		break;
8230 	case BPF_MAP_TYPE_CGRP_STORAGE:
8231 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8232 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8233 		    func_id != BPF_FUNC_kptr_xchg)
8234 			goto error;
8235 		break;
8236 	case BPF_MAP_TYPE_BLOOM_FILTER:
8237 		if (func_id != BPF_FUNC_map_peek_elem &&
8238 		    func_id != BPF_FUNC_map_push_elem)
8239 			goto error;
8240 		break;
8241 	default:
8242 		break;
8243 	}
8244 
8245 	/* ... and second from the function itself. */
8246 	switch (func_id) {
8247 	case BPF_FUNC_tail_call:
8248 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8249 			goto error;
8250 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8251 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8252 			return -EINVAL;
8253 		}
8254 		break;
8255 	case BPF_FUNC_perf_event_read:
8256 	case BPF_FUNC_perf_event_output:
8257 	case BPF_FUNC_perf_event_read_value:
8258 	case BPF_FUNC_skb_output:
8259 	case BPF_FUNC_xdp_output:
8260 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8261 			goto error;
8262 		break;
8263 	case BPF_FUNC_ringbuf_output:
8264 	case BPF_FUNC_ringbuf_reserve:
8265 	case BPF_FUNC_ringbuf_query:
8266 	case BPF_FUNC_ringbuf_reserve_dynptr:
8267 	case BPF_FUNC_ringbuf_submit_dynptr:
8268 	case BPF_FUNC_ringbuf_discard_dynptr:
8269 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8270 			goto error;
8271 		break;
8272 	case BPF_FUNC_user_ringbuf_drain:
8273 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8274 			goto error;
8275 		break;
8276 	case BPF_FUNC_get_stackid:
8277 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8278 			goto error;
8279 		break;
8280 	case BPF_FUNC_current_task_under_cgroup:
8281 	case BPF_FUNC_skb_under_cgroup:
8282 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8283 			goto error;
8284 		break;
8285 	case BPF_FUNC_redirect_map:
8286 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8287 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8288 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8289 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8290 			goto error;
8291 		break;
8292 	case BPF_FUNC_sk_redirect_map:
8293 	case BPF_FUNC_msg_redirect_map:
8294 	case BPF_FUNC_sock_map_update:
8295 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8296 			goto error;
8297 		break;
8298 	case BPF_FUNC_sk_redirect_hash:
8299 	case BPF_FUNC_msg_redirect_hash:
8300 	case BPF_FUNC_sock_hash_update:
8301 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8302 			goto error;
8303 		break;
8304 	case BPF_FUNC_get_local_storage:
8305 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8306 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8307 			goto error;
8308 		break;
8309 	case BPF_FUNC_sk_select_reuseport:
8310 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8311 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8312 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8313 			goto error;
8314 		break;
8315 	case BPF_FUNC_map_pop_elem:
8316 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8317 		    map->map_type != BPF_MAP_TYPE_STACK)
8318 			goto error;
8319 		break;
8320 	case BPF_FUNC_map_peek_elem:
8321 	case BPF_FUNC_map_push_elem:
8322 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8323 		    map->map_type != BPF_MAP_TYPE_STACK &&
8324 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8325 			goto error;
8326 		break;
8327 	case BPF_FUNC_map_lookup_percpu_elem:
8328 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8329 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8330 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8331 			goto error;
8332 		break;
8333 	case BPF_FUNC_sk_storage_get:
8334 	case BPF_FUNC_sk_storage_delete:
8335 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8336 			goto error;
8337 		break;
8338 	case BPF_FUNC_inode_storage_get:
8339 	case BPF_FUNC_inode_storage_delete:
8340 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8341 			goto error;
8342 		break;
8343 	case BPF_FUNC_task_storage_get:
8344 	case BPF_FUNC_task_storage_delete:
8345 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8346 			goto error;
8347 		break;
8348 	case BPF_FUNC_cgrp_storage_get:
8349 	case BPF_FUNC_cgrp_storage_delete:
8350 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8351 			goto error;
8352 		break;
8353 	default:
8354 		break;
8355 	}
8356 
8357 	return 0;
8358 error:
8359 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8360 		map->map_type, func_id_name(func_id), func_id);
8361 	return -EINVAL;
8362 }
8363 
8364 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8365 {
8366 	int count = 0;
8367 
8368 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8369 		count++;
8370 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8371 		count++;
8372 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8373 		count++;
8374 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8375 		count++;
8376 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8377 		count++;
8378 
8379 	/* We only support one arg being in raw mode at the moment,
8380 	 * which is sufficient for the helper functions we have
8381 	 * right now.
8382 	 */
8383 	return count <= 1;
8384 }
8385 
8386 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8387 {
8388 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8389 	bool has_size = fn->arg_size[arg] != 0;
8390 	bool is_next_size = false;
8391 
8392 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8393 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8394 
8395 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8396 		return is_next_size;
8397 
8398 	return has_size == is_next_size || is_next_size == is_fixed;
8399 }
8400 
8401 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8402 {
8403 	/* bpf_xxx(..., buf, len) call will access 'len'
8404 	 * bytes from memory 'buf'. Both arg types need
8405 	 * to be paired, so make sure there's no buggy
8406 	 * helper function specification.
8407 	 */
8408 	if (arg_type_is_mem_size(fn->arg1_type) ||
8409 	    check_args_pair_invalid(fn, 0) ||
8410 	    check_args_pair_invalid(fn, 1) ||
8411 	    check_args_pair_invalid(fn, 2) ||
8412 	    check_args_pair_invalid(fn, 3) ||
8413 	    check_args_pair_invalid(fn, 4))
8414 		return false;
8415 
8416 	return true;
8417 }
8418 
8419 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8420 {
8421 	int i;
8422 
8423 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8424 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8425 			return !!fn->arg_btf_id[i];
8426 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8427 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8428 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8429 		    /* arg_btf_id and arg_size are in a union. */
8430 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8431 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8432 			return false;
8433 	}
8434 
8435 	return true;
8436 }
8437 
8438 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8439 {
8440 	return check_raw_mode_ok(fn) &&
8441 	       check_arg_pair_ok(fn) &&
8442 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8443 }
8444 
8445 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8446  * are now invalid, so turn them into unknown SCALAR_VALUE.
8447  *
8448  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8449  * since these slices point to packet data.
8450  */
8451 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8452 {
8453 	struct bpf_func_state *state;
8454 	struct bpf_reg_state *reg;
8455 
8456 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8457 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8458 			mark_reg_invalid(env, reg);
8459 	}));
8460 }
8461 
8462 enum {
8463 	AT_PKT_END = -1,
8464 	BEYOND_PKT_END = -2,
8465 };
8466 
8467 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8468 {
8469 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8470 	struct bpf_reg_state *reg = &state->regs[regn];
8471 
8472 	if (reg->type != PTR_TO_PACKET)
8473 		/* PTR_TO_PACKET_META is not supported yet */
8474 		return;
8475 
8476 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8477 	 * How far beyond pkt_end it goes is unknown.
8478 	 * if (!range_open) it's the case of pkt >= pkt_end
8479 	 * if (range_open) it's the case of pkt > pkt_end
8480 	 * hence this pointer is at least 1 byte bigger than pkt_end
8481 	 */
8482 	if (range_open)
8483 		reg->range = BEYOND_PKT_END;
8484 	else
8485 		reg->range = AT_PKT_END;
8486 }
8487 
8488 /* The pointer with the specified id has released its reference to kernel
8489  * resources. Identify all copies of the same pointer and clear the reference.
8490  */
8491 static int release_reference(struct bpf_verifier_env *env,
8492 			     int ref_obj_id)
8493 {
8494 	struct bpf_func_state *state;
8495 	struct bpf_reg_state *reg;
8496 	int err;
8497 
8498 	err = release_reference_state(cur_func(env), ref_obj_id);
8499 	if (err)
8500 		return err;
8501 
8502 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8503 		if (reg->ref_obj_id == ref_obj_id)
8504 			mark_reg_invalid(env, reg);
8505 	}));
8506 
8507 	return 0;
8508 }
8509 
8510 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8511 {
8512 	struct bpf_func_state *unused;
8513 	struct bpf_reg_state *reg;
8514 
8515 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8516 		if (type_is_non_owning_ref(reg->type))
8517 			mark_reg_invalid(env, reg);
8518 	}));
8519 }
8520 
8521 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8522 				    struct bpf_reg_state *regs)
8523 {
8524 	int i;
8525 
8526 	/* after the call registers r0 - r5 were scratched */
8527 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8528 		mark_reg_not_init(env, regs, caller_saved[i]);
8529 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8530 	}
8531 }
8532 
8533 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8534 				   struct bpf_func_state *caller,
8535 				   struct bpf_func_state *callee,
8536 				   int insn_idx);
8537 
8538 static int set_callee_state(struct bpf_verifier_env *env,
8539 			    struct bpf_func_state *caller,
8540 			    struct bpf_func_state *callee, int insn_idx);
8541 
8542 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8543 			     int *insn_idx, int subprog,
8544 			     set_callee_state_fn set_callee_state_cb)
8545 {
8546 	struct bpf_verifier_state *state = env->cur_state;
8547 	struct bpf_func_state *caller, *callee;
8548 	int err;
8549 
8550 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8551 		verbose(env, "the call stack of %d frames is too deep\n",
8552 			state->curframe + 2);
8553 		return -E2BIG;
8554 	}
8555 
8556 	caller = state->frame[state->curframe];
8557 	if (state->frame[state->curframe + 1]) {
8558 		verbose(env, "verifier bug. Frame %d already allocated\n",
8559 			state->curframe + 1);
8560 		return -EFAULT;
8561 	}
8562 
8563 	err = btf_check_subprog_call(env, subprog, caller->regs);
8564 	if (err == -EFAULT)
8565 		return err;
8566 	if (subprog_is_global(env, subprog)) {
8567 		if (err) {
8568 			verbose(env, "Caller passes invalid args into func#%d\n",
8569 				subprog);
8570 			return err;
8571 		} else {
8572 			if (env->log.level & BPF_LOG_LEVEL)
8573 				verbose(env,
8574 					"Func#%d is global and valid. Skipping.\n",
8575 					subprog);
8576 			clear_caller_saved_regs(env, caller->regs);
8577 
8578 			/* All global functions return a 64-bit SCALAR_VALUE */
8579 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8580 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8581 
8582 			/* continue with next insn after call */
8583 			return 0;
8584 		}
8585 	}
8586 
8587 	/* set_callee_state is used for direct subprog calls, but we are
8588 	 * interested in validating only BPF helpers that can call subprogs as
8589 	 * callbacks
8590 	 */
8591 	if (set_callee_state_cb != set_callee_state) {
8592 		if (bpf_pseudo_kfunc_call(insn) &&
8593 		    !is_callback_calling_kfunc(insn->imm)) {
8594 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8595 				func_id_name(insn->imm), insn->imm);
8596 			return -EFAULT;
8597 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8598 			   !is_callback_calling_function(insn->imm)) { /* helper */
8599 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8600 				func_id_name(insn->imm), insn->imm);
8601 			return -EFAULT;
8602 		}
8603 	}
8604 
8605 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8606 	    insn->src_reg == 0 &&
8607 	    insn->imm == BPF_FUNC_timer_set_callback) {
8608 		struct bpf_verifier_state *async_cb;
8609 
8610 		/* there is no real recursion here. timer callbacks are async */
8611 		env->subprog_info[subprog].is_async_cb = true;
8612 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8613 					 *insn_idx, subprog);
8614 		if (!async_cb)
8615 			return -EFAULT;
8616 		callee = async_cb->frame[0];
8617 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8618 
8619 		/* Convert bpf_timer_set_callback() args into timer callback args */
8620 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8621 		if (err)
8622 			return err;
8623 
8624 		clear_caller_saved_regs(env, caller->regs);
8625 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8626 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8627 		/* continue with next insn after call */
8628 		return 0;
8629 	}
8630 
8631 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8632 	if (!callee)
8633 		return -ENOMEM;
8634 	state->frame[state->curframe + 1] = callee;
8635 
8636 	/* callee cannot access r0, r6 - r9 for reading and has to write
8637 	 * into its own stack before reading from it.
8638 	 * callee can read/write into caller's stack
8639 	 */
8640 	init_func_state(env, callee,
8641 			/* remember the callsite, it will be used by bpf_exit */
8642 			*insn_idx /* callsite */,
8643 			state->curframe + 1 /* frameno within this callchain */,
8644 			subprog /* subprog number within this prog */);
8645 
8646 	/* Transfer references to the callee */
8647 	err = copy_reference_state(callee, caller);
8648 	if (err)
8649 		goto err_out;
8650 
8651 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8652 	if (err)
8653 		goto err_out;
8654 
8655 	clear_caller_saved_regs(env, caller->regs);
8656 
8657 	/* only increment it after check_reg_arg() finished */
8658 	state->curframe++;
8659 
8660 	/* and go analyze first insn of the callee */
8661 	*insn_idx = env->subprog_info[subprog].start - 1;
8662 
8663 	if (env->log.level & BPF_LOG_LEVEL) {
8664 		verbose(env, "caller:\n");
8665 		print_verifier_state(env, caller, true);
8666 		verbose(env, "callee:\n");
8667 		print_verifier_state(env, callee, true);
8668 	}
8669 	return 0;
8670 
8671 err_out:
8672 	free_func_state(callee);
8673 	state->frame[state->curframe + 1] = NULL;
8674 	return err;
8675 }
8676 
8677 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8678 				   struct bpf_func_state *caller,
8679 				   struct bpf_func_state *callee)
8680 {
8681 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8682 	 *      void *callback_ctx, u64 flags);
8683 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8684 	 *      void *callback_ctx);
8685 	 */
8686 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8687 
8688 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8689 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8690 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8691 
8692 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8693 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8694 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8695 
8696 	/* pointer to stack or null */
8697 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8698 
8699 	/* unused */
8700 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8701 	return 0;
8702 }
8703 
8704 static int set_callee_state(struct bpf_verifier_env *env,
8705 			    struct bpf_func_state *caller,
8706 			    struct bpf_func_state *callee, int insn_idx)
8707 {
8708 	int i;
8709 
8710 	/* copy r1 - r5 args that callee can access.  The copy includes parent
8711 	 * pointers, which connects us up to the liveness chain
8712 	 */
8713 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8714 		callee->regs[i] = caller->regs[i];
8715 	return 0;
8716 }
8717 
8718 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8719 			   int *insn_idx)
8720 {
8721 	int subprog, target_insn;
8722 
8723 	target_insn = *insn_idx + insn->imm + 1;
8724 	subprog = find_subprog(env, target_insn);
8725 	if (subprog < 0) {
8726 		verbose(env, "verifier bug. No program starts at insn %d\n",
8727 			target_insn);
8728 		return -EFAULT;
8729 	}
8730 
8731 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8732 }
8733 
8734 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8735 				       struct bpf_func_state *caller,
8736 				       struct bpf_func_state *callee,
8737 				       int insn_idx)
8738 {
8739 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8740 	struct bpf_map *map;
8741 	int err;
8742 
8743 	if (bpf_map_ptr_poisoned(insn_aux)) {
8744 		verbose(env, "tail_call abusing map_ptr\n");
8745 		return -EINVAL;
8746 	}
8747 
8748 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8749 	if (!map->ops->map_set_for_each_callback_args ||
8750 	    !map->ops->map_for_each_callback) {
8751 		verbose(env, "callback function not allowed for map\n");
8752 		return -ENOTSUPP;
8753 	}
8754 
8755 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8756 	if (err)
8757 		return err;
8758 
8759 	callee->in_callback_fn = true;
8760 	callee->callback_ret_range = tnum_range(0, 1);
8761 	return 0;
8762 }
8763 
8764 static int set_loop_callback_state(struct bpf_verifier_env *env,
8765 				   struct bpf_func_state *caller,
8766 				   struct bpf_func_state *callee,
8767 				   int insn_idx)
8768 {
8769 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8770 	 *	    u64 flags);
8771 	 * callback_fn(u32 index, void *callback_ctx);
8772 	 */
8773 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8774 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8775 
8776 	/* unused */
8777 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8778 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8779 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8780 
8781 	callee->in_callback_fn = true;
8782 	callee->callback_ret_range = tnum_range(0, 1);
8783 	return 0;
8784 }
8785 
8786 static int set_timer_callback_state(struct bpf_verifier_env *env,
8787 				    struct bpf_func_state *caller,
8788 				    struct bpf_func_state *callee,
8789 				    int insn_idx)
8790 {
8791 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8792 
8793 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8794 	 * callback_fn(struct bpf_map *map, void *key, void *value);
8795 	 */
8796 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8797 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8798 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
8799 
8800 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8801 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8802 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
8803 
8804 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8805 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8806 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
8807 
8808 	/* unused */
8809 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8810 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8811 	callee->in_async_callback_fn = true;
8812 	callee->callback_ret_range = tnum_range(0, 1);
8813 	return 0;
8814 }
8815 
8816 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8817 				       struct bpf_func_state *caller,
8818 				       struct bpf_func_state *callee,
8819 				       int insn_idx)
8820 {
8821 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8822 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8823 	 * (callback_fn)(struct task_struct *task,
8824 	 *               struct vm_area_struct *vma, void *callback_ctx);
8825 	 */
8826 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8827 
8828 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8829 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8830 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8831 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8832 
8833 	/* pointer to stack or null */
8834 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8835 
8836 	/* unused */
8837 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8838 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8839 	callee->in_callback_fn = true;
8840 	callee->callback_ret_range = tnum_range(0, 1);
8841 	return 0;
8842 }
8843 
8844 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8845 					   struct bpf_func_state *caller,
8846 					   struct bpf_func_state *callee,
8847 					   int insn_idx)
8848 {
8849 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8850 	 *			  callback_ctx, u64 flags);
8851 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8852 	 */
8853 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8854 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8855 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8856 
8857 	/* unused */
8858 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8859 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8860 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8861 
8862 	callee->in_callback_fn = true;
8863 	callee->callback_ret_range = tnum_range(0, 1);
8864 	return 0;
8865 }
8866 
8867 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8868 					 struct bpf_func_state *caller,
8869 					 struct bpf_func_state *callee,
8870 					 int insn_idx)
8871 {
8872 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
8873 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8874 	 *
8875 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
8876 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8877 	 * by this point, so look at 'root'
8878 	 */
8879 	struct btf_field *field;
8880 
8881 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8882 				      BPF_RB_ROOT);
8883 	if (!field || !field->graph_root.value_btf_id)
8884 		return -EFAULT;
8885 
8886 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8887 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8888 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8889 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8890 
8891 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8892 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8893 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8894 	callee->in_callback_fn = true;
8895 	callee->callback_ret_range = tnum_range(0, 1);
8896 	return 0;
8897 }
8898 
8899 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8900 
8901 /* Are we currently verifying the callback for a rbtree helper that must
8902  * be called with lock held? If so, no need to complain about unreleased
8903  * lock
8904  */
8905 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8906 {
8907 	struct bpf_verifier_state *state = env->cur_state;
8908 	struct bpf_insn *insn = env->prog->insnsi;
8909 	struct bpf_func_state *callee;
8910 	int kfunc_btf_id;
8911 
8912 	if (!state->curframe)
8913 		return false;
8914 
8915 	callee = state->frame[state->curframe];
8916 
8917 	if (!callee->in_callback_fn)
8918 		return false;
8919 
8920 	kfunc_btf_id = insn[callee->callsite].imm;
8921 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8922 }
8923 
8924 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8925 {
8926 	struct bpf_verifier_state *state = env->cur_state;
8927 	struct bpf_func_state *caller, *callee;
8928 	struct bpf_reg_state *r0;
8929 	int err;
8930 
8931 	callee = state->frame[state->curframe];
8932 	r0 = &callee->regs[BPF_REG_0];
8933 	if (r0->type == PTR_TO_STACK) {
8934 		/* technically it's ok to return caller's stack pointer
8935 		 * (or caller's caller's pointer) back to the caller,
8936 		 * since these pointers are valid. Only current stack
8937 		 * pointer will be invalid as soon as function exits,
8938 		 * but let's be conservative
8939 		 */
8940 		verbose(env, "cannot return stack pointer to the caller\n");
8941 		return -EINVAL;
8942 	}
8943 
8944 	caller = state->frame[state->curframe - 1];
8945 	if (callee->in_callback_fn) {
8946 		/* enforce R0 return value range [0, 1]. */
8947 		struct tnum range = callee->callback_ret_range;
8948 
8949 		if (r0->type != SCALAR_VALUE) {
8950 			verbose(env, "R0 not a scalar value\n");
8951 			return -EACCES;
8952 		}
8953 		if (!tnum_in(range, r0->var_off)) {
8954 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8955 			return -EINVAL;
8956 		}
8957 	} else {
8958 		/* return to the caller whatever r0 had in the callee */
8959 		caller->regs[BPF_REG_0] = *r0;
8960 	}
8961 
8962 	/* callback_fn frame should have released its own additions to parent's
8963 	 * reference state at this point, or check_reference_leak would
8964 	 * complain, hence it must be the same as the caller. There is no need
8965 	 * to copy it back.
8966 	 */
8967 	if (!callee->in_callback_fn) {
8968 		/* Transfer references to the caller */
8969 		err = copy_reference_state(caller, callee);
8970 		if (err)
8971 			return err;
8972 	}
8973 
8974 	*insn_idx = callee->callsite + 1;
8975 	if (env->log.level & BPF_LOG_LEVEL) {
8976 		verbose(env, "returning from callee:\n");
8977 		print_verifier_state(env, callee, true);
8978 		verbose(env, "to caller at %d:\n", *insn_idx);
8979 		print_verifier_state(env, caller, true);
8980 	}
8981 	/* clear everything in the callee */
8982 	free_func_state(callee);
8983 	state->frame[state->curframe--] = NULL;
8984 	return 0;
8985 }
8986 
8987 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8988 				   int func_id,
8989 				   struct bpf_call_arg_meta *meta)
8990 {
8991 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8992 
8993 	if (ret_type != RET_INTEGER ||
8994 	    (func_id != BPF_FUNC_get_stack &&
8995 	     func_id != BPF_FUNC_get_task_stack &&
8996 	     func_id != BPF_FUNC_probe_read_str &&
8997 	     func_id != BPF_FUNC_probe_read_kernel_str &&
8998 	     func_id != BPF_FUNC_probe_read_user_str))
8999 		return;
9000 
9001 	ret_reg->smax_value = meta->msize_max_value;
9002 	ret_reg->s32_max_value = meta->msize_max_value;
9003 	ret_reg->smin_value = -MAX_ERRNO;
9004 	ret_reg->s32_min_value = -MAX_ERRNO;
9005 	reg_bounds_sync(ret_reg);
9006 }
9007 
9008 static int
9009 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9010 		int func_id, int insn_idx)
9011 {
9012 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9013 	struct bpf_map *map = meta->map_ptr;
9014 
9015 	if (func_id != BPF_FUNC_tail_call &&
9016 	    func_id != BPF_FUNC_map_lookup_elem &&
9017 	    func_id != BPF_FUNC_map_update_elem &&
9018 	    func_id != BPF_FUNC_map_delete_elem &&
9019 	    func_id != BPF_FUNC_map_push_elem &&
9020 	    func_id != BPF_FUNC_map_pop_elem &&
9021 	    func_id != BPF_FUNC_map_peek_elem &&
9022 	    func_id != BPF_FUNC_for_each_map_elem &&
9023 	    func_id != BPF_FUNC_redirect_map &&
9024 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9025 		return 0;
9026 
9027 	if (map == NULL) {
9028 		verbose(env, "kernel subsystem misconfigured verifier\n");
9029 		return -EINVAL;
9030 	}
9031 
9032 	/* In case of read-only, some additional restrictions
9033 	 * need to be applied in order to prevent altering the
9034 	 * state of the map from program side.
9035 	 */
9036 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9037 	    (func_id == BPF_FUNC_map_delete_elem ||
9038 	     func_id == BPF_FUNC_map_update_elem ||
9039 	     func_id == BPF_FUNC_map_push_elem ||
9040 	     func_id == BPF_FUNC_map_pop_elem)) {
9041 		verbose(env, "write into map forbidden\n");
9042 		return -EACCES;
9043 	}
9044 
9045 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9046 		bpf_map_ptr_store(aux, meta->map_ptr,
9047 				  !meta->map_ptr->bypass_spec_v1);
9048 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9049 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9050 				  !meta->map_ptr->bypass_spec_v1);
9051 	return 0;
9052 }
9053 
9054 static int
9055 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9056 		int func_id, int insn_idx)
9057 {
9058 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9059 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9060 	struct bpf_map *map = meta->map_ptr;
9061 	u64 val, max;
9062 	int err;
9063 
9064 	if (func_id != BPF_FUNC_tail_call)
9065 		return 0;
9066 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9067 		verbose(env, "kernel subsystem misconfigured verifier\n");
9068 		return -EINVAL;
9069 	}
9070 
9071 	reg = &regs[BPF_REG_3];
9072 	val = reg->var_off.value;
9073 	max = map->max_entries;
9074 
9075 	if (!(register_is_const(reg) && val < max)) {
9076 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9077 		return 0;
9078 	}
9079 
9080 	err = mark_chain_precision(env, BPF_REG_3);
9081 	if (err)
9082 		return err;
9083 	if (bpf_map_key_unseen(aux))
9084 		bpf_map_key_store(aux, val);
9085 	else if (!bpf_map_key_poisoned(aux) &&
9086 		  bpf_map_key_immediate(aux) != val)
9087 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9088 	return 0;
9089 }
9090 
9091 static int check_reference_leak(struct bpf_verifier_env *env)
9092 {
9093 	struct bpf_func_state *state = cur_func(env);
9094 	bool refs_lingering = false;
9095 	int i;
9096 
9097 	if (state->frameno && !state->in_callback_fn)
9098 		return 0;
9099 
9100 	for (i = 0; i < state->acquired_refs; i++) {
9101 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9102 			continue;
9103 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9104 			state->refs[i].id, state->refs[i].insn_idx);
9105 		refs_lingering = true;
9106 	}
9107 	return refs_lingering ? -EINVAL : 0;
9108 }
9109 
9110 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9111 				   struct bpf_reg_state *regs)
9112 {
9113 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9114 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9115 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9116 	struct bpf_bprintf_data data = {};
9117 	int err, fmt_map_off, num_args;
9118 	u64 fmt_addr;
9119 	char *fmt;
9120 
9121 	/* data must be an array of u64 */
9122 	if (data_len_reg->var_off.value % 8)
9123 		return -EINVAL;
9124 	num_args = data_len_reg->var_off.value / 8;
9125 
9126 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9127 	 * and map_direct_value_addr is set.
9128 	 */
9129 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9130 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9131 						  fmt_map_off);
9132 	if (err) {
9133 		verbose(env, "verifier bug\n");
9134 		return -EFAULT;
9135 	}
9136 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9137 
9138 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9139 	 * can focus on validating the format specifiers.
9140 	 */
9141 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9142 	if (err < 0)
9143 		verbose(env, "Invalid format string\n");
9144 
9145 	return err;
9146 }
9147 
9148 static int check_get_func_ip(struct bpf_verifier_env *env)
9149 {
9150 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9151 	int func_id = BPF_FUNC_get_func_ip;
9152 
9153 	if (type == BPF_PROG_TYPE_TRACING) {
9154 		if (!bpf_prog_has_trampoline(env->prog)) {
9155 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9156 				func_id_name(func_id), func_id);
9157 			return -ENOTSUPP;
9158 		}
9159 		return 0;
9160 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9161 		return 0;
9162 	}
9163 
9164 	verbose(env, "func %s#%d not supported for program type %d\n",
9165 		func_id_name(func_id), func_id, type);
9166 	return -ENOTSUPP;
9167 }
9168 
9169 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9170 {
9171 	return &env->insn_aux_data[env->insn_idx];
9172 }
9173 
9174 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9175 {
9176 	struct bpf_reg_state *regs = cur_regs(env);
9177 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9178 	bool reg_is_null = register_is_null(reg);
9179 
9180 	if (reg_is_null)
9181 		mark_chain_precision(env, BPF_REG_4);
9182 
9183 	return reg_is_null;
9184 }
9185 
9186 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9187 {
9188 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9189 
9190 	if (!state->initialized) {
9191 		state->initialized = 1;
9192 		state->fit_for_inline = loop_flag_is_zero(env);
9193 		state->callback_subprogno = subprogno;
9194 		return;
9195 	}
9196 
9197 	if (!state->fit_for_inline)
9198 		return;
9199 
9200 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9201 				 state->callback_subprogno == subprogno);
9202 }
9203 
9204 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9205 			     int *insn_idx_p)
9206 {
9207 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9208 	const struct bpf_func_proto *fn = NULL;
9209 	enum bpf_return_type ret_type;
9210 	enum bpf_type_flag ret_flag;
9211 	struct bpf_reg_state *regs;
9212 	struct bpf_call_arg_meta meta;
9213 	int insn_idx = *insn_idx_p;
9214 	bool changes_data;
9215 	int i, err, func_id;
9216 
9217 	/* find function prototype */
9218 	func_id = insn->imm;
9219 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9220 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9221 			func_id);
9222 		return -EINVAL;
9223 	}
9224 
9225 	if (env->ops->get_func_proto)
9226 		fn = env->ops->get_func_proto(func_id, env->prog);
9227 	if (!fn) {
9228 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9229 			func_id);
9230 		return -EINVAL;
9231 	}
9232 
9233 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9234 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9235 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9236 		return -EINVAL;
9237 	}
9238 
9239 	if (fn->allowed && !fn->allowed(env->prog)) {
9240 		verbose(env, "helper call is not allowed in probe\n");
9241 		return -EINVAL;
9242 	}
9243 
9244 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9245 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9246 		return -EINVAL;
9247 	}
9248 
9249 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9250 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9251 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9252 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9253 			func_id_name(func_id), func_id);
9254 		return -EINVAL;
9255 	}
9256 
9257 	memset(&meta, 0, sizeof(meta));
9258 	meta.pkt_access = fn->pkt_access;
9259 
9260 	err = check_func_proto(fn, func_id);
9261 	if (err) {
9262 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9263 			func_id_name(func_id), func_id);
9264 		return err;
9265 	}
9266 
9267 	if (env->cur_state->active_rcu_lock) {
9268 		if (fn->might_sleep) {
9269 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9270 				func_id_name(func_id), func_id);
9271 			return -EINVAL;
9272 		}
9273 
9274 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9275 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9276 	}
9277 
9278 	meta.func_id = func_id;
9279 	/* check args */
9280 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9281 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9282 		if (err)
9283 			return err;
9284 	}
9285 
9286 	err = record_func_map(env, &meta, func_id, insn_idx);
9287 	if (err)
9288 		return err;
9289 
9290 	err = record_func_key(env, &meta, func_id, insn_idx);
9291 	if (err)
9292 		return err;
9293 
9294 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9295 	 * is inferred from register state.
9296 	 */
9297 	for (i = 0; i < meta.access_size; i++) {
9298 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9299 				       BPF_WRITE, -1, false);
9300 		if (err)
9301 			return err;
9302 	}
9303 
9304 	regs = cur_regs(env);
9305 
9306 	if (meta.release_regno) {
9307 		err = -EINVAL;
9308 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9309 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9310 		 * is safe to do directly.
9311 		 */
9312 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9313 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9314 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9315 				return -EFAULT;
9316 			}
9317 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9318 		} else if (meta.ref_obj_id) {
9319 			err = release_reference(env, meta.ref_obj_id);
9320 		} else if (register_is_null(&regs[meta.release_regno])) {
9321 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9322 			 * released is NULL, which must be > R0.
9323 			 */
9324 			err = 0;
9325 		}
9326 		if (err) {
9327 			verbose(env, "func %s#%d reference has not been acquired before\n",
9328 				func_id_name(func_id), func_id);
9329 			return err;
9330 		}
9331 	}
9332 
9333 	switch (func_id) {
9334 	case BPF_FUNC_tail_call:
9335 		err = check_reference_leak(env);
9336 		if (err) {
9337 			verbose(env, "tail_call would lead to reference leak\n");
9338 			return err;
9339 		}
9340 		break;
9341 	case BPF_FUNC_get_local_storage:
9342 		/* check that flags argument in get_local_storage(map, flags) is 0,
9343 		 * this is required because get_local_storage() can't return an error.
9344 		 */
9345 		if (!register_is_null(&regs[BPF_REG_2])) {
9346 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9347 			return -EINVAL;
9348 		}
9349 		break;
9350 	case BPF_FUNC_for_each_map_elem:
9351 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9352 					set_map_elem_callback_state);
9353 		break;
9354 	case BPF_FUNC_timer_set_callback:
9355 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9356 					set_timer_callback_state);
9357 		break;
9358 	case BPF_FUNC_find_vma:
9359 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9360 					set_find_vma_callback_state);
9361 		break;
9362 	case BPF_FUNC_snprintf:
9363 		err = check_bpf_snprintf_call(env, regs);
9364 		break;
9365 	case BPF_FUNC_loop:
9366 		update_loop_inline_state(env, meta.subprogno);
9367 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9368 					set_loop_callback_state);
9369 		break;
9370 	case BPF_FUNC_dynptr_from_mem:
9371 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9372 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9373 				reg_type_str(env, regs[BPF_REG_1].type));
9374 			return -EACCES;
9375 		}
9376 		break;
9377 	case BPF_FUNC_set_retval:
9378 		if (prog_type == BPF_PROG_TYPE_LSM &&
9379 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9380 			if (!env->prog->aux->attach_func_proto->type) {
9381 				/* Make sure programs that attach to void
9382 				 * hooks don't try to modify return value.
9383 				 */
9384 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9385 				return -EINVAL;
9386 			}
9387 		}
9388 		break;
9389 	case BPF_FUNC_dynptr_data:
9390 	{
9391 		struct bpf_reg_state *reg;
9392 		int id, ref_obj_id;
9393 
9394 		reg = get_dynptr_arg_reg(env, fn, regs);
9395 		if (!reg)
9396 			return -EFAULT;
9397 
9398 
9399 		if (meta.dynptr_id) {
9400 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9401 			return -EFAULT;
9402 		}
9403 		if (meta.ref_obj_id) {
9404 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9405 			return -EFAULT;
9406 		}
9407 
9408 		id = dynptr_id(env, reg);
9409 		if (id < 0) {
9410 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9411 			return id;
9412 		}
9413 
9414 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9415 		if (ref_obj_id < 0) {
9416 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9417 			return ref_obj_id;
9418 		}
9419 
9420 		meta.dynptr_id = id;
9421 		meta.ref_obj_id = ref_obj_id;
9422 
9423 		break;
9424 	}
9425 	case BPF_FUNC_dynptr_write:
9426 	{
9427 		enum bpf_dynptr_type dynptr_type;
9428 		struct bpf_reg_state *reg;
9429 
9430 		reg = get_dynptr_arg_reg(env, fn, regs);
9431 		if (!reg)
9432 			return -EFAULT;
9433 
9434 		dynptr_type = dynptr_get_type(env, reg);
9435 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9436 			return -EFAULT;
9437 
9438 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9439 			/* this will trigger clear_all_pkt_pointers(), which will
9440 			 * invalidate all dynptr slices associated with the skb
9441 			 */
9442 			changes_data = true;
9443 
9444 		break;
9445 	}
9446 	case BPF_FUNC_user_ringbuf_drain:
9447 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9448 					set_user_ringbuf_callback_state);
9449 		break;
9450 	}
9451 
9452 	if (err)
9453 		return err;
9454 
9455 	/* reset caller saved regs */
9456 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9457 		mark_reg_not_init(env, regs, caller_saved[i]);
9458 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9459 	}
9460 
9461 	/* helper call returns 64-bit value. */
9462 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9463 
9464 	/* update return register (already marked as written above) */
9465 	ret_type = fn->ret_type;
9466 	ret_flag = type_flag(ret_type);
9467 
9468 	switch (base_type(ret_type)) {
9469 	case RET_INTEGER:
9470 		/* sets type to SCALAR_VALUE */
9471 		mark_reg_unknown(env, regs, BPF_REG_0);
9472 		break;
9473 	case RET_VOID:
9474 		regs[BPF_REG_0].type = NOT_INIT;
9475 		break;
9476 	case RET_PTR_TO_MAP_VALUE:
9477 		/* There is no offset yet applied, variable or fixed */
9478 		mark_reg_known_zero(env, regs, BPF_REG_0);
9479 		/* remember map_ptr, so that check_map_access()
9480 		 * can check 'value_size' boundary of memory access
9481 		 * to map element returned from bpf_map_lookup_elem()
9482 		 */
9483 		if (meta.map_ptr == NULL) {
9484 			verbose(env,
9485 				"kernel subsystem misconfigured verifier\n");
9486 			return -EINVAL;
9487 		}
9488 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9489 		regs[BPF_REG_0].map_uid = meta.map_uid;
9490 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9491 		if (!type_may_be_null(ret_type) &&
9492 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9493 			regs[BPF_REG_0].id = ++env->id_gen;
9494 		}
9495 		break;
9496 	case RET_PTR_TO_SOCKET:
9497 		mark_reg_known_zero(env, regs, BPF_REG_0);
9498 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9499 		break;
9500 	case RET_PTR_TO_SOCK_COMMON:
9501 		mark_reg_known_zero(env, regs, BPF_REG_0);
9502 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9503 		break;
9504 	case RET_PTR_TO_TCP_SOCK:
9505 		mark_reg_known_zero(env, regs, BPF_REG_0);
9506 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9507 		break;
9508 	case RET_PTR_TO_MEM:
9509 		mark_reg_known_zero(env, regs, BPF_REG_0);
9510 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9511 		regs[BPF_REG_0].mem_size = meta.mem_size;
9512 		break;
9513 	case RET_PTR_TO_MEM_OR_BTF_ID:
9514 	{
9515 		const struct btf_type *t;
9516 
9517 		mark_reg_known_zero(env, regs, BPF_REG_0);
9518 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9519 		if (!btf_type_is_struct(t)) {
9520 			u32 tsize;
9521 			const struct btf_type *ret;
9522 			const char *tname;
9523 
9524 			/* resolve the type size of ksym. */
9525 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9526 			if (IS_ERR(ret)) {
9527 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9528 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9529 					tname, PTR_ERR(ret));
9530 				return -EINVAL;
9531 			}
9532 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9533 			regs[BPF_REG_0].mem_size = tsize;
9534 		} else {
9535 			/* MEM_RDONLY may be carried from ret_flag, but it
9536 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9537 			 * it will confuse the check of PTR_TO_BTF_ID in
9538 			 * check_mem_access().
9539 			 */
9540 			ret_flag &= ~MEM_RDONLY;
9541 
9542 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9543 			regs[BPF_REG_0].btf = meta.ret_btf;
9544 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9545 		}
9546 		break;
9547 	}
9548 	case RET_PTR_TO_BTF_ID:
9549 	{
9550 		struct btf *ret_btf;
9551 		int ret_btf_id;
9552 
9553 		mark_reg_known_zero(env, regs, BPF_REG_0);
9554 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9555 		if (func_id == BPF_FUNC_kptr_xchg) {
9556 			ret_btf = meta.kptr_field->kptr.btf;
9557 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9558 			if (!btf_is_kernel(ret_btf))
9559 				regs[BPF_REG_0].type |= MEM_ALLOC;
9560 		} else {
9561 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9562 				verbose(env, "verifier internal error:");
9563 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9564 					func_id_name(func_id));
9565 				return -EINVAL;
9566 			}
9567 			ret_btf = btf_vmlinux;
9568 			ret_btf_id = *fn->ret_btf_id;
9569 		}
9570 		if (ret_btf_id == 0) {
9571 			verbose(env, "invalid return type %u of func %s#%d\n",
9572 				base_type(ret_type), func_id_name(func_id),
9573 				func_id);
9574 			return -EINVAL;
9575 		}
9576 		regs[BPF_REG_0].btf = ret_btf;
9577 		regs[BPF_REG_0].btf_id = ret_btf_id;
9578 		break;
9579 	}
9580 	default:
9581 		verbose(env, "unknown return type %u of func %s#%d\n",
9582 			base_type(ret_type), func_id_name(func_id), func_id);
9583 		return -EINVAL;
9584 	}
9585 
9586 	if (type_may_be_null(regs[BPF_REG_0].type))
9587 		regs[BPF_REG_0].id = ++env->id_gen;
9588 
9589 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9590 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9591 			func_id_name(func_id), func_id);
9592 		return -EFAULT;
9593 	}
9594 
9595 	if (is_dynptr_ref_function(func_id))
9596 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9597 
9598 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9599 		/* For release_reference() */
9600 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9601 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9602 		int id = acquire_reference_state(env, insn_idx);
9603 
9604 		if (id < 0)
9605 			return id;
9606 		/* For mark_ptr_or_null_reg() */
9607 		regs[BPF_REG_0].id = id;
9608 		/* For release_reference() */
9609 		regs[BPF_REG_0].ref_obj_id = id;
9610 	}
9611 
9612 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9613 
9614 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9615 	if (err)
9616 		return err;
9617 
9618 	if ((func_id == BPF_FUNC_get_stack ||
9619 	     func_id == BPF_FUNC_get_task_stack) &&
9620 	    !env->prog->has_callchain_buf) {
9621 		const char *err_str;
9622 
9623 #ifdef CONFIG_PERF_EVENTS
9624 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9625 		err_str = "cannot get callchain buffer for func %s#%d\n";
9626 #else
9627 		err = -ENOTSUPP;
9628 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9629 #endif
9630 		if (err) {
9631 			verbose(env, err_str, func_id_name(func_id), func_id);
9632 			return err;
9633 		}
9634 
9635 		env->prog->has_callchain_buf = true;
9636 	}
9637 
9638 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9639 		env->prog->call_get_stack = true;
9640 
9641 	if (func_id == BPF_FUNC_get_func_ip) {
9642 		if (check_get_func_ip(env))
9643 			return -ENOTSUPP;
9644 		env->prog->call_get_func_ip = true;
9645 	}
9646 
9647 	if (changes_data)
9648 		clear_all_pkt_pointers(env);
9649 	return 0;
9650 }
9651 
9652 /* mark_btf_func_reg_size() is used when the reg size is determined by
9653  * the BTF func_proto's return value size and argument.
9654  */
9655 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9656 				   size_t reg_size)
9657 {
9658 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9659 
9660 	if (regno == BPF_REG_0) {
9661 		/* Function return value */
9662 		reg->live |= REG_LIVE_WRITTEN;
9663 		reg->subreg_def = reg_size == sizeof(u64) ?
9664 			DEF_NOT_SUBREG : env->insn_idx + 1;
9665 	} else {
9666 		/* Function argument */
9667 		if (reg_size == sizeof(u64)) {
9668 			mark_insn_zext(env, reg);
9669 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9670 		} else {
9671 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9672 		}
9673 	}
9674 }
9675 
9676 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9677 {
9678 	return meta->kfunc_flags & KF_ACQUIRE;
9679 }
9680 
9681 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9682 {
9683 	return meta->kfunc_flags & KF_RET_NULL;
9684 }
9685 
9686 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9687 {
9688 	return meta->kfunc_flags & KF_RELEASE;
9689 }
9690 
9691 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9692 {
9693 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9694 }
9695 
9696 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9697 {
9698 	return meta->kfunc_flags & KF_SLEEPABLE;
9699 }
9700 
9701 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9702 {
9703 	return meta->kfunc_flags & KF_DESTRUCTIVE;
9704 }
9705 
9706 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9707 {
9708 	return meta->kfunc_flags & KF_RCU;
9709 }
9710 
9711 static bool __kfunc_param_match_suffix(const struct btf *btf,
9712 				       const struct btf_param *arg,
9713 				       const char *suffix)
9714 {
9715 	int suffix_len = strlen(suffix), len;
9716 	const char *param_name;
9717 
9718 	/* In the future, this can be ported to use BTF tagging */
9719 	param_name = btf_name_by_offset(btf, arg->name_off);
9720 	if (str_is_empty(param_name))
9721 		return false;
9722 	len = strlen(param_name);
9723 	if (len < suffix_len)
9724 		return false;
9725 	param_name += len - suffix_len;
9726 	return !strncmp(param_name, suffix, suffix_len);
9727 }
9728 
9729 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9730 				  const struct btf_param *arg,
9731 				  const struct bpf_reg_state *reg)
9732 {
9733 	const struct btf_type *t;
9734 
9735 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9736 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9737 		return false;
9738 
9739 	return __kfunc_param_match_suffix(btf, arg, "__sz");
9740 }
9741 
9742 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9743 					const struct btf_param *arg,
9744 					const struct bpf_reg_state *reg)
9745 {
9746 	const struct btf_type *t;
9747 
9748 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9749 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9750 		return false;
9751 
9752 	return __kfunc_param_match_suffix(btf, arg, "__szk");
9753 }
9754 
9755 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9756 {
9757 	return __kfunc_param_match_suffix(btf, arg, "__opt");
9758 }
9759 
9760 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9761 {
9762 	return __kfunc_param_match_suffix(btf, arg, "__k");
9763 }
9764 
9765 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9766 {
9767 	return __kfunc_param_match_suffix(btf, arg, "__ign");
9768 }
9769 
9770 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9771 {
9772 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
9773 }
9774 
9775 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9776 {
9777 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
9778 }
9779 
9780 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9781 {
9782 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9783 }
9784 
9785 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9786 					  const struct btf_param *arg,
9787 					  const char *name)
9788 {
9789 	int len, target_len = strlen(name);
9790 	const char *param_name;
9791 
9792 	param_name = btf_name_by_offset(btf, arg->name_off);
9793 	if (str_is_empty(param_name))
9794 		return false;
9795 	len = strlen(param_name);
9796 	if (len != target_len)
9797 		return false;
9798 	if (strcmp(param_name, name))
9799 		return false;
9800 
9801 	return true;
9802 }
9803 
9804 enum {
9805 	KF_ARG_DYNPTR_ID,
9806 	KF_ARG_LIST_HEAD_ID,
9807 	KF_ARG_LIST_NODE_ID,
9808 	KF_ARG_RB_ROOT_ID,
9809 	KF_ARG_RB_NODE_ID,
9810 };
9811 
9812 BTF_ID_LIST(kf_arg_btf_ids)
9813 BTF_ID(struct, bpf_dynptr_kern)
9814 BTF_ID(struct, bpf_list_head)
9815 BTF_ID(struct, bpf_list_node)
9816 BTF_ID(struct, bpf_rb_root)
9817 BTF_ID(struct, bpf_rb_node)
9818 
9819 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9820 				    const struct btf_param *arg, int type)
9821 {
9822 	const struct btf_type *t;
9823 	u32 res_id;
9824 
9825 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9826 	if (!t)
9827 		return false;
9828 	if (!btf_type_is_ptr(t))
9829 		return false;
9830 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
9831 	if (!t)
9832 		return false;
9833 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9834 }
9835 
9836 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9837 {
9838 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9839 }
9840 
9841 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9842 {
9843 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9844 }
9845 
9846 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9847 {
9848 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9849 }
9850 
9851 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9852 {
9853 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9854 }
9855 
9856 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9857 {
9858 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9859 }
9860 
9861 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9862 				  const struct btf_param *arg)
9863 {
9864 	const struct btf_type *t;
9865 
9866 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9867 	if (!t)
9868 		return false;
9869 
9870 	return true;
9871 }
9872 
9873 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9874 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9875 					const struct btf *btf,
9876 					const struct btf_type *t, int rec)
9877 {
9878 	const struct btf_type *member_type;
9879 	const struct btf_member *member;
9880 	u32 i;
9881 
9882 	if (!btf_type_is_struct(t))
9883 		return false;
9884 
9885 	for_each_member(i, t, member) {
9886 		const struct btf_array *array;
9887 
9888 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9889 		if (btf_type_is_struct(member_type)) {
9890 			if (rec >= 3) {
9891 				verbose(env, "max struct nesting depth exceeded\n");
9892 				return false;
9893 			}
9894 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9895 				return false;
9896 			continue;
9897 		}
9898 		if (btf_type_is_array(member_type)) {
9899 			array = btf_array(member_type);
9900 			if (!array->nelems)
9901 				return false;
9902 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9903 			if (!btf_type_is_scalar(member_type))
9904 				return false;
9905 			continue;
9906 		}
9907 		if (!btf_type_is_scalar(member_type))
9908 			return false;
9909 	}
9910 	return true;
9911 }
9912 
9913 
9914 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9915 #ifdef CONFIG_NET
9916 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9917 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9918 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9919 #endif
9920 };
9921 
9922 enum kfunc_ptr_arg_type {
9923 	KF_ARG_PTR_TO_CTX,
9924 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
9925 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
9926 	KF_ARG_PTR_TO_DYNPTR,
9927 	KF_ARG_PTR_TO_ITER,
9928 	KF_ARG_PTR_TO_LIST_HEAD,
9929 	KF_ARG_PTR_TO_LIST_NODE,
9930 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
9931 	KF_ARG_PTR_TO_MEM,
9932 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
9933 	KF_ARG_PTR_TO_CALLBACK,
9934 	KF_ARG_PTR_TO_RB_ROOT,
9935 	KF_ARG_PTR_TO_RB_NODE,
9936 };
9937 
9938 enum special_kfunc_type {
9939 	KF_bpf_obj_new_impl,
9940 	KF_bpf_obj_drop_impl,
9941 	KF_bpf_refcount_acquire_impl,
9942 	KF_bpf_list_push_front_impl,
9943 	KF_bpf_list_push_back_impl,
9944 	KF_bpf_list_pop_front,
9945 	KF_bpf_list_pop_back,
9946 	KF_bpf_cast_to_kern_ctx,
9947 	KF_bpf_rdonly_cast,
9948 	KF_bpf_rcu_read_lock,
9949 	KF_bpf_rcu_read_unlock,
9950 	KF_bpf_rbtree_remove,
9951 	KF_bpf_rbtree_add_impl,
9952 	KF_bpf_rbtree_first,
9953 	KF_bpf_dynptr_from_skb,
9954 	KF_bpf_dynptr_from_xdp,
9955 	KF_bpf_dynptr_slice,
9956 	KF_bpf_dynptr_slice_rdwr,
9957 	KF_bpf_dynptr_clone,
9958 };
9959 
9960 BTF_SET_START(special_kfunc_set)
9961 BTF_ID(func, bpf_obj_new_impl)
9962 BTF_ID(func, bpf_obj_drop_impl)
9963 BTF_ID(func, bpf_refcount_acquire_impl)
9964 BTF_ID(func, bpf_list_push_front_impl)
9965 BTF_ID(func, bpf_list_push_back_impl)
9966 BTF_ID(func, bpf_list_pop_front)
9967 BTF_ID(func, bpf_list_pop_back)
9968 BTF_ID(func, bpf_cast_to_kern_ctx)
9969 BTF_ID(func, bpf_rdonly_cast)
9970 BTF_ID(func, bpf_rbtree_remove)
9971 BTF_ID(func, bpf_rbtree_add_impl)
9972 BTF_ID(func, bpf_rbtree_first)
9973 BTF_ID(func, bpf_dynptr_from_skb)
9974 BTF_ID(func, bpf_dynptr_from_xdp)
9975 BTF_ID(func, bpf_dynptr_slice)
9976 BTF_ID(func, bpf_dynptr_slice_rdwr)
9977 BTF_ID(func, bpf_dynptr_clone)
9978 BTF_SET_END(special_kfunc_set)
9979 
9980 BTF_ID_LIST(special_kfunc_list)
9981 BTF_ID(func, bpf_obj_new_impl)
9982 BTF_ID(func, bpf_obj_drop_impl)
9983 BTF_ID(func, bpf_refcount_acquire_impl)
9984 BTF_ID(func, bpf_list_push_front_impl)
9985 BTF_ID(func, bpf_list_push_back_impl)
9986 BTF_ID(func, bpf_list_pop_front)
9987 BTF_ID(func, bpf_list_pop_back)
9988 BTF_ID(func, bpf_cast_to_kern_ctx)
9989 BTF_ID(func, bpf_rdonly_cast)
9990 BTF_ID(func, bpf_rcu_read_lock)
9991 BTF_ID(func, bpf_rcu_read_unlock)
9992 BTF_ID(func, bpf_rbtree_remove)
9993 BTF_ID(func, bpf_rbtree_add_impl)
9994 BTF_ID(func, bpf_rbtree_first)
9995 BTF_ID(func, bpf_dynptr_from_skb)
9996 BTF_ID(func, bpf_dynptr_from_xdp)
9997 BTF_ID(func, bpf_dynptr_slice)
9998 BTF_ID(func, bpf_dynptr_slice_rdwr)
9999 BTF_ID(func, bpf_dynptr_clone)
10000 
10001 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10002 {
10003 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10004 }
10005 
10006 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10007 {
10008 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10009 }
10010 
10011 static enum kfunc_ptr_arg_type
10012 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10013 		       struct bpf_kfunc_call_arg_meta *meta,
10014 		       const struct btf_type *t, const struct btf_type *ref_t,
10015 		       const char *ref_tname, const struct btf_param *args,
10016 		       int argno, int nargs)
10017 {
10018 	u32 regno = argno + 1;
10019 	struct bpf_reg_state *regs = cur_regs(env);
10020 	struct bpf_reg_state *reg = &regs[regno];
10021 	bool arg_mem_size = false;
10022 
10023 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10024 		return KF_ARG_PTR_TO_CTX;
10025 
10026 	/* In this function, we verify the kfunc's BTF as per the argument type,
10027 	 * leaving the rest of the verification with respect to the register
10028 	 * type to our caller. When a set of conditions hold in the BTF type of
10029 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10030 	 */
10031 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10032 		return KF_ARG_PTR_TO_CTX;
10033 
10034 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10035 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10036 
10037 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10038 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10039 
10040 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10041 		return KF_ARG_PTR_TO_DYNPTR;
10042 
10043 	if (is_kfunc_arg_iter(meta, argno))
10044 		return KF_ARG_PTR_TO_ITER;
10045 
10046 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10047 		return KF_ARG_PTR_TO_LIST_HEAD;
10048 
10049 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10050 		return KF_ARG_PTR_TO_LIST_NODE;
10051 
10052 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10053 		return KF_ARG_PTR_TO_RB_ROOT;
10054 
10055 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10056 		return KF_ARG_PTR_TO_RB_NODE;
10057 
10058 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10059 		if (!btf_type_is_struct(ref_t)) {
10060 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10061 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10062 			return -EINVAL;
10063 		}
10064 		return KF_ARG_PTR_TO_BTF_ID;
10065 	}
10066 
10067 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10068 		return KF_ARG_PTR_TO_CALLBACK;
10069 
10070 
10071 	if (argno + 1 < nargs &&
10072 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10073 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10074 		arg_mem_size = true;
10075 
10076 	/* This is the catch all argument type of register types supported by
10077 	 * check_helper_mem_access. However, we only allow when argument type is
10078 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10079 	 * arg_mem_size is true, the pointer can be void *.
10080 	 */
10081 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10082 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10083 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10084 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10085 		return -EINVAL;
10086 	}
10087 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10088 }
10089 
10090 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10091 					struct bpf_reg_state *reg,
10092 					const struct btf_type *ref_t,
10093 					const char *ref_tname, u32 ref_id,
10094 					struct bpf_kfunc_call_arg_meta *meta,
10095 					int argno)
10096 {
10097 	const struct btf_type *reg_ref_t;
10098 	bool strict_type_match = false;
10099 	const struct btf *reg_btf;
10100 	const char *reg_ref_tname;
10101 	u32 reg_ref_id;
10102 
10103 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10104 		reg_btf = reg->btf;
10105 		reg_ref_id = reg->btf_id;
10106 	} else {
10107 		reg_btf = btf_vmlinux;
10108 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10109 	}
10110 
10111 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10112 	 * or releasing a reference, or are no-cast aliases. We do _not_
10113 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10114 	 * as we want to enable BPF programs to pass types that are bitwise
10115 	 * equivalent without forcing them to explicitly cast with something
10116 	 * like bpf_cast_to_kern_ctx().
10117 	 *
10118 	 * For example, say we had a type like the following:
10119 	 *
10120 	 * struct bpf_cpumask {
10121 	 *	cpumask_t cpumask;
10122 	 *	refcount_t usage;
10123 	 * };
10124 	 *
10125 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10126 	 * to a struct cpumask, so it would be safe to pass a struct
10127 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10128 	 *
10129 	 * The philosophy here is similar to how we allow scalars of different
10130 	 * types to be passed to kfuncs as long as the size is the same. The
10131 	 * only difference here is that we're simply allowing
10132 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10133 	 * resolve types.
10134 	 */
10135 	if (is_kfunc_acquire(meta) ||
10136 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10137 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10138 		strict_type_match = true;
10139 
10140 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10141 
10142 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10143 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10144 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10145 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10146 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10147 			btf_type_str(reg_ref_t), reg_ref_tname);
10148 		return -EINVAL;
10149 	}
10150 	return 0;
10151 }
10152 
10153 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10154 {
10155 	struct bpf_verifier_state *state = env->cur_state;
10156 
10157 	if (!state->active_lock.ptr) {
10158 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10159 		return -EFAULT;
10160 	}
10161 
10162 	if (type_flag(reg->type) & NON_OWN_REF) {
10163 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10164 		return -EFAULT;
10165 	}
10166 
10167 	reg->type |= NON_OWN_REF;
10168 	return 0;
10169 }
10170 
10171 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10172 {
10173 	struct bpf_func_state *state, *unused;
10174 	struct bpf_reg_state *reg;
10175 	int i;
10176 
10177 	state = cur_func(env);
10178 
10179 	if (!ref_obj_id) {
10180 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10181 			     "owning -> non-owning conversion\n");
10182 		return -EFAULT;
10183 	}
10184 
10185 	for (i = 0; i < state->acquired_refs; i++) {
10186 		if (state->refs[i].id != ref_obj_id)
10187 			continue;
10188 
10189 		/* Clear ref_obj_id here so release_reference doesn't clobber
10190 		 * the whole reg
10191 		 */
10192 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10193 			if (reg->ref_obj_id == ref_obj_id) {
10194 				reg->ref_obj_id = 0;
10195 				ref_set_non_owning(env, reg);
10196 			}
10197 		}));
10198 		return 0;
10199 	}
10200 
10201 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10202 	return -EFAULT;
10203 }
10204 
10205 /* Implementation details:
10206  *
10207  * Each register points to some region of memory, which we define as an
10208  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10209  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10210  * allocation. The lock and the data it protects are colocated in the same
10211  * memory region.
10212  *
10213  * Hence, everytime a register holds a pointer value pointing to such
10214  * allocation, the verifier preserves a unique reg->id for it.
10215  *
10216  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10217  * bpf_spin_lock is called.
10218  *
10219  * To enable this, lock state in the verifier captures two values:
10220  *	active_lock.ptr = Register's type specific pointer
10221  *	active_lock.id  = A unique ID for each register pointer value
10222  *
10223  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10224  * supported register types.
10225  *
10226  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10227  * allocated objects is the reg->btf pointer.
10228  *
10229  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10230  * can establish the provenance of the map value statically for each distinct
10231  * lookup into such maps. They always contain a single map value hence unique
10232  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10233  *
10234  * So, in case of global variables, they use array maps with max_entries = 1,
10235  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10236  * into the same map value as max_entries is 1, as described above).
10237  *
10238  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10239  * outer map pointer (in verifier context), but each lookup into an inner map
10240  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10241  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10242  * will get different reg->id assigned to each lookup, hence different
10243  * active_lock.id.
10244  *
10245  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10246  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10247  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10248  */
10249 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10250 {
10251 	void *ptr;
10252 	u32 id;
10253 
10254 	switch ((int)reg->type) {
10255 	case PTR_TO_MAP_VALUE:
10256 		ptr = reg->map_ptr;
10257 		break;
10258 	case PTR_TO_BTF_ID | MEM_ALLOC:
10259 		ptr = reg->btf;
10260 		break;
10261 	default:
10262 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10263 		return -EFAULT;
10264 	}
10265 	id = reg->id;
10266 
10267 	if (!env->cur_state->active_lock.ptr)
10268 		return -EINVAL;
10269 	if (env->cur_state->active_lock.ptr != ptr ||
10270 	    env->cur_state->active_lock.id != id) {
10271 		verbose(env, "held lock and object are not in the same allocation\n");
10272 		return -EINVAL;
10273 	}
10274 	return 0;
10275 }
10276 
10277 static bool is_bpf_list_api_kfunc(u32 btf_id)
10278 {
10279 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10280 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10281 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10282 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10283 }
10284 
10285 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10286 {
10287 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10288 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10289 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10290 }
10291 
10292 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10293 {
10294 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10295 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10296 }
10297 
10298 static bool is_callback_calling_kfunc(u32 btf_id)
10299 {
10300 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10301 }
10302 
10303 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10304 {
10305 	return is_bpf_rbtree_api_kfunc(btf_id);
10306 }
10307 
10308 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10309 					  enum btf_field_type head_field_type,
10310 					  u32 kfunc_btf_id)
10311 {
10312 	bool ret;
10313 
10314 	switch (head_field_type) {
10315 	case BPF_LIST_HEAD:
10316 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10317 		break;
10318 	case BPF_RB_ROOT:
10319 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10320 		break;
10321 	default:
10322 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10323 			btf_field_type_name(head_field_type));
10324 		return false;
10325 	}
10326 
10327 	if (!ret)
10328 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10329 			btf_field_type_name(head_field_type));
10330 	return ret;
10331 }
10332 
10333 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10334 					  enum btf_field_type node_field_type,
10335 					  u32 kfunc_btf_id)
10336 {
10337 	bool ret;
10338 
10339 	switch (node_field_type) {
10340 	case BPF_LIST_NODE:
10341 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10342 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10343 		break;
10344 	case BPF_RB_NODE:
10345 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10346 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10347 		break;
10348 	default:
10349 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10350 			btf_field_type_name(node_field_type));
10351 		return false;
10352 	}
10353 
10354 	if (!ret)
10355 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10356 			btf_field_type_name(node_field_type));
10357 	return ret;
10358 }
10359 
10360 static int
10361 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10362 				   struct bpf_reg_state *reg, u32 regno,
10363 				   struct bpf_kfunc_call_arg_meta *meta,
10364 				   enum btf_field_type head_field_type,
10365 				   struct btf_field **head_field)
10366 {
10367 	const char *head_type_name;
10368 	struct btf_field *field;
10369 	struct btf_record *rec;
10370 	u32 head_off;
10371 
10372 	if (meta->btf != btf_vmlinux) {
10373 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10374 		return -EFAULT;
10375 	}
10376 
10377 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10378 		return -EFAULT;
10379 
10380 	head_type_name = btf_field_type_name(head_field_type);
10381 	if (!tnum_is_const(reg->var_off)) {
10382 		verbose(env,
10383 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10384 			regno, head_type_name);
10385 		return -EINVAL;
10386 	}
10387 
10388 	rec = reg_btf_record(reg);
10389 	head_off = reg->off + reg->var_off.value;
10390 	field = btf_record_find(rec, head_off, head_field_type);
10391 	if (!field) {
10392 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10393 		return -EINVAL;
10394 	}
10395 
10396 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10397 	if (check_reg_allocation_locked(env, reg)) {
10398 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10399 			rec->spin_lock_off, head_type_name);
10400 		return -EINVAL;
10401 	}
10402 
10403 	if (*head_field) {
10404 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10405 		return -EFAULT;
10406 	}
10407 	*head_field = field;
10408 	return 0;
10409 }
10410 
10411 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10412 					   struct bpf_reg_state *reg, u32 regno,
10413 					   struct bpf_kfunc_call_arg_meta *meta)
10414 {
10415 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10416 							  &meta->arg_list_head.field);
10417 }
10418 
10419 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10420 					     struct bpf_reg_state *reg, u32 regno,
10421 					     struct bpf_kfunc_call_arg_meta *meta)
10422 {
10423 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10424 							  &meta->arg_rbtree_root.field);
10425 }
10426 
10427 static int
10428 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10429 				   struct bpf_reg_state *reg, u32 regno,
10430 				   struct bpf_kfunc_call_arg_meta *meta,
10431 				   enum btf_field_type head_field_type,
10432 				   enum btf_field_type node_field_type,
10433 				   struct btf_field **node_field)
10434 {
10435 	const char *node_type_name;
10436 	const struct btf_type *et, *t;
10437 	struct btf_field *field;
10438 	u32 node_off;
10439 
10440 	if (meta->btf != btf_vmlinux) {
10441 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10442 		return -EFAULT;
10443 	}
10444 
10445 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10446 		return -EFAULT;
10447 
10448 	node_type_name = btf_field_type_name(node_field_type);
10449 	if (!tnum_is_const(reg->var_off)) {
10450 		verbose(env,
10451 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10452 			regno, node_type_name);
10453 		return -EINVAL;
10454 	}
10455 
10456 	node_off = reg->off + reg->var_off.value;
10457 	field = reg_find_field_offset(reg, node_off, node_field_type);
10458 	if (!field || field->offset != node_off) {
10459 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10460 		return -EINVAL;
10461 	}
10462 
10463 	field = *node_field;
10464 
10465 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10466 	t = btf_type_by_id(reg->btf, reg->btf_id);
10467 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10468 				  field->graph_root.value_btf_id, true)) {
10469 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10470 			"in struct %s, but arg is at offset=%d in struct %s\n",
10471 			btf_field_type_name(head_field_type),
10472 			btf_field_type_name(node_field_type),
10473 			field->graph_root.node_offset,
10474 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10475 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10476 		return -EINVAL;
10477 	}
10478 
10479 	if (node_off != field->graph_root.node_offset) {
10480 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10481 			node_off, btf_field_type_name(node_field_type),
10482 			field->graph_root.node_offset,
10483 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10484 		return -EINVAL;
10485 	}
10486 
10487 	return 0;
10488 }
10489 
10490 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10491 					   struct bpf_reg_state *reg, u32 regno,
10492 					   struct bpf_kfunc_call_arg_meta *meta)
10493 {
10494 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10495 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10496 						  &meta->arg_list_head.field);
10497 }
10498 
10499 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10500 					     struct bpf_reg_state *reg, u32 regno,
10501 					     struct bpf_kfunc_call_arg_meta *meta)
10502 {
10503 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10504 						  BPF_RB_ROOT, BPF_RB_NODE,
10505 						  &meta->arg_rbtree_root.field);
10506 }
10507 
10508 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10509 			    int insn_idx)
10510 {
10511 	const char *func_name = meta->func_name, *ref_tname;
10512 	const struct btf *btf = meta->btf;
10513 	const struct btf_param *args;
10514 	struct btf_record *rec;
10515 	u32 i, nargs;
10516 	int ret;
10517 
10518 	args = (const struct btf_param *)(meta->func_proto + 1);
10519 	nargs = btf_type_vlen(meta->func_proto);
10520 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10521 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10522 			MAX_BPF_FUNC_REG_ARGS);
10523 		return -EINVAL;
10524 	}
10525 
10526 	/* Check that BTF function arguments match actual types that the
10527 	 * verifier sees.
10528 	 */
10529 	for (i = 0; i < nargs; i++) {
10530 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10531 		const struct btf_type *t, *ref_t, *resolve_ret;
10532 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10533 		u32 regno = i + 1, ref_id, type_size;
10534 		bool is_ret_buf_sz = false;
10535 		int kf_arg_type;
10536 
10537 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10538 
10539 		if (is_kfunc_arg_ignore(btf, &args[i]))
10540 			continue;
10541 
10542 		if (btf_type_is_scalar(t)) {
10543 			if (reg->type != SCALAR_VALUE) {
10544 				verbose(env, "R%d is not a scalar\n", regno);
10545 				return -EINVAL;
10546 			}
10547 
10548 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10549 				if (meta->arg_constant.found) {
10550 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10551 					return -EFAULT;
10552 				}
10553 				if (!tnum_is_const(reg->var_off)) {
10554 					verbose(env, "R%d must be a known constant\n", regno);
10555 					return -EINVAL;
10556 				}
10557 				ret = mark_chain_precision(env, regno);
10558 				if (ret < 0)
10559 					return ret;
10560 				meta->arg_constant.found = true;
10561 				meta->arg_constant.value = reg->var_off.value;
10562 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10563 				meta->r0_rdonly = true;
10564 				is_ret_buf_sz = true;
10565 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10566 				is_ret_buf_sz = true;
10567 			}
10568 
10569 			if (is_ret_buf_sz) {
10570 				if (meta->r0_size) {
10571 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10572 					return -EINVAL;
10573 				}
10574 
10575 				if (!tnum_is_const(reg->var_off)) {
10576 					verbose(env, "R%d is not a const\n", regno);
10577 					return -EINVAL;
10578 				}
10579 
10580 				meta->r0_size = reg->var_off.value;
10581 				ret = mark_chain_precision(env, regno);
10582 				if (ret)
10583 					return ret;
10584 			}
10585 			continue;
10586 		}
10587 
10588 		if (!btf_type_is_ptr(t)) {
10589 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10590 			return -EINVAL;
10591 		}
10592 
10593 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10594 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10595 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10596 			return -EACCES;
10597 		}
10598 
10599 		if (reg->ref_obj_id) {
10600 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10601 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10602 					regno, reg->ref_obj_id,
10603 					meta->ref_obj_id);
10604 				return -EFAULT;
10605 			}
10606 			meta->ref_obj_id = reg->ref_obj_id;
10607 			if (is_kfunc_release(meta))
10608 				meta->release_regno = regno;
10609 		}
10610 
10611 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10612 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10613 
10614 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10615 		if (kf_arg_type < 0)
10616 			return kf_arg_type;
10617 
10618 		switch (kf_arg_type) {
10619 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10620 		case KF_ARG_PTR_TO_BTF_ID:
10621 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10622 				break;
10623 
10624 			if (!is_trusted_reg(reg)) {
10625 				if (!is_kfunc_rcu(meta)) {
10626 					verbose(env, "R%d must be referenced or trusted\n", regno);
10627 					return -EINVAL;
10628 				}
10629 				if (!is_rcu_reg(reg)) {
10630 					verbose(env, "R%d must be a rcu pointer\n", regno);
10631 					return -EINVAL;
10632 				}
10633 			}
10634 
10635 			fallthrough;
10636 		case KF_ARG_PTR_TO_CTX:
10637 			/* Trusted arguments have the same offset checks as release arguments */
10638 			arg_type |= OBJ_RELEASE;
10639 			break;
10640 		case KF_ARG_PTR_TO_DYNPTR:
10641 		case KF_ARG_PTR_TO_ITER:
10642 		case KF_ARG_PTR_TO_LIST_HEAD:
10643 		case KF_ARG_PTR_TO_LIST_NODE:
10644 		case KF_ARG_PTR_TO_RB_ROOT:
10645 		case KF_ARG_PTR_TO_RB_NODE:
10646 		case KF_ARG_PTR_TO_MEM:
10647 		case KF_ARG_PTR_TO_MEM_SIZE:
10648 		case KF_ARG_PTR_TO_CALLBACK:
10649 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10650 			/* Trusted by default */
10651 			break;
10652 		default:
10653 			WARN_ON_ONCE(1);
10654 			return -EFAULT;
10655 		}
10656 
10657 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10658 			arg_type |= OBJ_RELEASE;
10659 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10660 		if (ret < 0)
10661 			return ret;
10662 
10663 		switch (kf_arg_type) {
10664 		case KF_ARG_PTR_TO_CTX:
10665 			if (reg->type != PTR_TO_CTX) {
10666 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10667 				return -EINVAL;
10668 			}
10669 
10670 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10671 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10672 				if (ret < 0)
10673 					return -EINVAL;
10674 				meta->ret_btf_id  = ret;
10675 			}
10676 			break;
10677 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10678 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10679 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10680 				return -EINVAL;
10681 			}
10682 			if (!reg->ref_obj_id) {
10683 				verbose(env, "allocated object must be referenced\n");
10684 				return -EINVAL;
10685 			}
10686 			if (meta->btf == btf_vmlinux &&
10687 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10688 				meta->arg_btf = reg->btf;
10689 				meta->arg_btf_id = reg->btf_id;
10690 			}
10691 			break;
10692 		case KF_ARG_PTR_TO_DYNPTR:
10693 		{
10694 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10695 			int clone_ref_obj_id = 0;
10696 
10697 			if (reg->type != PTR_TO_STACK &&
10698 			    reg->type != CONST_PTR_TO_DYNPTR) {
10699 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10700 				return -EINVAL;
10701 			}
10702 
10703 			if (reg->type == CONST_PTR_TO_DYNPTR)
10704 				dynptr_arg_type |= MEM_RDONLY;
10705 
10706 			if (is_kfunc_arg_uninit(btf, &args[i]))
10707 				dynptr_arg_type |= MEM_UNINIT;
10708 
10709 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10710 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
10711 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10712 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
10713 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10714 				   (dynptr_arg_type & MEM_UNINIT)) {
10715 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10716 
10717 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10718 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10719 					return -EFAULT;
10720 				}
10721 
10722 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10723 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10724 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10725 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10726 					return -EFAULT;
10727 				}
10728 			}
10729 
10730 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10731 			if (ret < 0)
10732 				return ret;
10733 
10734 			if (!(dynptr_arg_type & MEM_UNINIT)) {
10735 				int id = dynptr_id(env, reg);
10736 
10737 				if (id < 0) {
10738 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10739 					return id;
10740 				}
10741 				meta->initialized_dynptr.id = id;
10742 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10743 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10744 			}
10745 
10746 			break;
10747 		}
10748 		case KF_ARG_PTR_TO_ITER:
10749 			ret = process_iter_arg(env, regno, insn_idx, meta);
10750 			if (ret < 0)
10751 				return ret;
10752 			break;
10753 		case KF_ARG_PTR_TO_LIST_HEAD:
10754 			if (reg->type != PTR_TO_MAP_VALUE &&
10755 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10756 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10757 				return -EINVAL;
10758 			}
10759 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10760 				verbose(env, "allocated object must be referenced\n");
10761 				return -EINVAL;
10762 			}
10763 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10764 			if (ret < 0)
10765 				return ret;
10766 			break;
10767 		case KF_ARG_PTR_TO_RB_ROOT:
10768 			if (reg->type != PTR_TO_MAP_VALUE &&
10769 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10770 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10771 				return -EINVAL;
10772 			}
10773 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10774 				verbose(env, "allocated object must be referenced\n");
10775 				return -EINVAL;
10776 			}
10777 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10778 			if (ret < 0)
10779 				return ret;
10780 			break;
10781 		case KF_ARG_PTR_TO_LIST_NODE:
10782 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10783 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10784 				return -EINVAL;
10785 			}
10786 			if (!reg->ref_obj_id) {
10787 				verbose(env, "allocated object must be referenced\n");
10788 				return -EINVAL;
10789 			}
10790 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10791 			if (ret < 0)
10792 				return ret;
10793 			break;
10794 		case KF_ARG_PTR_TO_RB_NODE:
10795 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10796 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10797 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
10798 					return -EINVAL;
10799 				}
10800 				if (in_rbtree_lock_required_cb(env)) {
10801 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10802 					return -EINVAL;
10803 				}
10804 			} else {
10805 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10806 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10807 					return -EINVAL;
10808 				}
10809 				if (!reg->ref_obj_id) {
10810 					verbose(env, "allocated object must be referenced\n");
10811 					return -EINVAL;
10812 				}
10813 			}
10814 
10815 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10816 			if (ret < 0)
10817 				return ret;
10818 			break;
10819 		case KF_ARG_PTR_TO_BTF_ID:
10820 			/* Only base_type is checked, further checks are done here */
10821 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10822 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10823 			    !reg2btf_ids[base_type(reg->type)]) {
10824 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10825 				verbose(env, "expected %s or socket\n",
10826 					reg_type_str(env, base_type(reg->type) |
10827 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10828 				return -EINVAL;
10829 			}
10830 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10831 			if (ret < 0)
10832 				return ret;
10833 			break;
10834 		case KF_ARG_PTR_TO_MEM:
10835 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10836 			if (IS_ERR(resolve_ret)) {
10837 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10838 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10839 				return -EINVAL;
10840 			}
10841 			ret = check_mem_reg(env, reg, regno, type_size);
10842 			if (ret < 0)
10843 				return ret;
10844 			break;
10845 		case KF_ARG_PTR_TO_MEM_SIZE:
10846 		{
10847 			struct bpf_reg_state *buff_reg = &regs[regno];
10848 			const struct btf_param *buff_arg = &args[i];
10849 			struct bpf_reg_state *size_reg = &regs[regno + 1];
10850 			const struct btf_param *size_arg = &args[i + 1];
10851 
10852 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
10853 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10854 				if (ret < 0) {
10855 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10856 					return ret;
10857 				}
10858 			}
10859 
10860 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10861 				if (meta->arg_constant.found) {
10862 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10863 					return -EFAULT;
10864 				}
10865 				if (!tnum_is_const(size_reg->var_off)) {
10866 					verbose(env, "R%d must be a known constant\n", regno + 1);
10867 					return -EINVAL;
10868 				}
10869 				meta->arg_constant.found = true;
10870 				meta->arg_constant.value = size_reg->var_off.value;
10871 			}
10872 
10873 			/* Skip next '__sz' or '__szk' argument */
10874 			i++;
10875 			break;
10876 		}
10877 		case KF_ARG_PTR_TO_CALLBACK:
10878 			meta->subprogno = reg->subprogno;
10879 			break;
10880 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10881 			if (!type_is_ptr_alloc_obj(reg->type) && !type_is_non_owning_ref(reg->type)) {
10882 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
10883 				return -EINVAL;
10884 			}
10885 
10886 			rec = reg_btf_record(reg);
10887 			if (!rec) {
10888 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
10889 				return -EFAULT;
10890 			}
10891 
10892 			if (rec->refcount_off < 0) {
10893 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
10894 				return -EINVAL;
10895 			}
10896 			if (rec->refcount_off >= 0) {
10897 				verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
10898 				return -EINVAL;
10899 			}
10900 			meta->arg_btf = reg->btf;
10901 			meta->arg_btf_id = reg->btf_id;
10902 			break;
10903 		}
10904 	}
10905 
10906 	if (is_kfunc_release(meta) && !meta->release_regno) {
10907 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10908 			func_name);
10909 		return -EINVAL;
10910 	}
10911 
10912 	return 0;
10913 }
10914 
10915 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10916 			    struct bpf_insn *insn,
10917 			    struct bpf_kfunc_call_arg_meta *meta,
10918 			    const char **kfunc_name)
10919 {
10920 	const struct btf_type *func, *func_proto;
10921 	u32 func_id, *kfunc_flags;
10922 	const char *func_name;
10923 	struct btf *desc_btf;
10924 
10925 	if (kfunc_name)
10926 		*kfunc_name = NULL;
10927 
10928 	if (!insn->imm)
10929 		return -EINVAL;
10930 
10931 	desc_btf = find_kfunc_desc_btf(env, insn->off);
10932 	if (IS_ERR(desc_btf))
10933 		return PTR_ERR(desc_btf);
10934 
10935 	func_id = insn->imm;
10936 	func = btf_type_by_id(desc_btf, func_id);
10937 	func_name = btf_name_by_offset(desc_btf, func->name_off);
10938 	if (kfunc_name)
10939 		*kfunc_name = func_name;
10940 	func_proto = btf_type_by_id(desc_btf, func->type);
10941 
10942 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
10943 	if (!kfunc_flags) {
10944 		return -EACCES;
10945 	}
10946 
10947 	memset(meta, 0, sizeof(*meta));
10948 	meta->btf = desc_btf;
10949 	meta->func_id = func_id;
10950 	meta->kfunc_flags = *kfunc_flags;
10951 	meta->func_proto = func_proto;
10952 	meta->func_name = func_name;
10953 
10954 	return 0;
10955 }
10956 
10957 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10958 			    int *insn_idx_p)
10959 {
10960 	const struct btf_type *t, *ptr_type;
10961 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
10962 	struct bpf_reg_state *regs = cur_regs(env);
10963 	const char *func_name, *ptr_type_name;
10964 	bool sleepable, rcu_lock, rcu_unlock;
10965 	struct bpf_kfunc_call_arg_meta meta;
10966 	struct bpf_insn_aux_data *insn_aux;
10967 	int err, insn_idx = *insn_idx_p;
10968 	const struct btf_param *args;
10969 	const struct btf_type *ret_t;
10970 	struct btf *desc_btf;
10971 
10972 	/* skip for now, but return error when we find this in fixup_kfunc_call */
10973 	if (!insn->imm)
10974 		return 0;
10975 
10976 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10977 	if (err == -EACCES && func_name)
10978 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
10979 	if (err)
10980 		return err;
10981 	desc_btf = meta.btf;
10982 	insn_aux = &env->insn_aux_data[insn_idx];
10983 
10984 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10985 
10986 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10987 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10988 		return -EACCES;
10989 	}
10990 
10991 	sleepable = is_kfunc_sleepable(&meta);
10992 	if (sleepable && !env->prog->aux->sleepable) {
10993 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10994 		return -EACCES;
10995 	}
10996 
10997 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10998 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10999 
11000 	if (env->cur_state->active_rcu_lock) {
11001 		struct bpf_func_state *state;
11002 		struct bpf_reg_state *reg;
11003 
11004 		if (rcu_lock) {
11005 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11006 			return -EINVAL;
11007 		} else if (rcu_unlock) {
11008 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11009 				if (reg->type & MEM_RCU) {
11010 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11011 					reg->type |= PTR_UNTRUSTED;
11012 				}
11013 			}));
11014 			env->cur_state->active_rcu_lock = false;
11015 		} else if (sleepable) {
11016 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11017 			return -EACCES;
11018 		}
11019 	} else if (rcu_lock) {
11020 		env->cur_state->active_rcu_lock = true;
11021 	} else if (rcu_unlock) {
11022 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11023 		return -EINVAL;
11024 	}
11025 
11026 	/* Check the arguments */
11027 	err = check_kfunc_args(env, &meta, insn_idx);
11028 	if (err < 0)
11029 		return err;
11030 	/* In case of release function, we get register number of refcounted
11031 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11032 	 */
11033 	if (meta.release_regno) {
11034 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11035 		if (err) {
11036 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11037 				func_name, meta.func_id);
11038 			return err;
11039 		}
11040 	}
11041 
11042 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11043 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11044 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11045 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11046 		insn_aux->insert_off = regs[BPF_REG_2].off;
11047 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11048 		if (err) {
11049 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11050 				func_name, meta.func_id);
11051 			return err;
11052 		}
11053 
11054 		err = release_reference(env, release_ref_obj_id);
11055 		if (err) {
11056 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11057 				func_name, meta.func_id);
11058 			return err;
11059 		}
11060 	}
11061 
11062 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11063 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11064 					set_rbtree_add_callback_state);
11065 		if (err) {
11066 			verbose(env, "kfunc %s#%d failed callback verification\n",
11067 				func_name, meta.func_id);
11068 			return err;
11069 		}
11070 	}
11071 
11072 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11073 		mark_reg_not_init(env, regs, caller_saved[i]);
11074 
11075 	/* Check return type */
11076 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11077 
11078 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11079 		/* Only exception is bpf_obj_new_impl */
11080 		if (meta.btf != btf_vmlinux ||
11081 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11082 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11083 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11084 			return -EINVAL;
11085 		}
11086 	}
11087 
11088 	if (btf_type_is_scalar(t)) {
11089 		mark_reg_unknown(env, regs, BPF_REG_0);
11090 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11091 	} else if (btf_type_is_ptr(t)) {
11092 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11093 
11094 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11095 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11096 				struct btf *ret_btf;
11097 				u32 ret_btf_id;
11098 
11099 				if (unlikely(!bpf_global_ma_set))
11100 					return -ENOMEM;
11101 
11102 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11103 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11104 					return -EINVAL;
11105 				}
11106 
11107 				ret_btf = env->prog->aux->btf;
11108 				ret_btf_id = meta.arg_constant.value;
11109 
11110 				/* This may be NULL due to user not supplying a BTF */
11111 				if (!ret_btf) {
11112 					verbose(env, "bpf_obj_new requires prog BTF\n");
11113 					return -EINVAL;
11114 				}
11115 
11116 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11117 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11118 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11119 					return -EINVAL;
11120 				}
11121 
11122 				mark_reg_known_zero(env, regs, BPF_REG_0);
11123 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11124 				regs[BPF_REG_0].btf = ret_btf;
11125 				regs[BPF_REG_0].btf_id = ret_btf_id;
11126 
11127 				insn_aux->obj_new_size = ret_t->size;
11128 				insn_aux->kptr_struct_meta =
11129 					btf_find_struct_meta(ret_btf, ret_btf_id);
11130 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11131 				mark_reg_known_zero(env, regs, BPF_REG_0);
11132 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11133 				regs[BPF_REG_0].btf = meta.arg_btf;
11134 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11135 
11136 				insn_aux->kptr_struct_meta =
11137 					btf_find_struct_meta(meta.arg_btf,
11138 							     meta.arg_btf_id);
11139 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11140 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11141 				struct btf_field *field = meta.arg_list_head.field;
11142 
11143 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11144 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11145 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11146 				struct btf_field *field = meta.arg_rbtree_root.field;
11147 
11148 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11149 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11150 				mark_reg_known_zero(env, regs, BPF_REG_0);
11151 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11152 				regs[BPF_REG_0].btf = desc_btf;
11153 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11154 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11155 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11156 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11157 					verbose(env,
11158 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11159 					return -EINVAL;
11160 				}
11161 
11162 				mark_reg_known_zero(env, regs, BPF_REG_0);
11163 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11164 				regs[BPF_REG_0].btf = desc_btf;
11165 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11166 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11167 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11168 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11169 
11170 				mark_reg_known_zero(env, regs, BPF_REG_0);
11171 
11172 				if (!meta.arg_constant.found) {
11173 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11174 					return -EFAULT;
11175 				}
11176 
11177 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11178 
11179 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11180 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11181 
11182 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11183 					regs[BPF_REG_0].type |= MEM_RDONLY;
11184 				} else {
11185 					/* this will set env->seen_direct_write to true */
11186 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11187 						verbose(env, "the prog does not allow writes to packet data\n");
11188 						return -EINVAL;
11189 					}
11190 				}
11191 
11192 				if (!meta.initialized_dynptr.id) {
11193 					verbose(env, "verifier internal error: no dynptr id\n");
11194 					return -EFAULT;
11195 				}
11196 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11197 
11198 				/* we don't need to set BPF_REG_0's ref obj id
11199 				 * because packet slices are not refcounted (see
11200 				 * dynptr_type_refcounted)
11201 				 */
11202 			} else {
11203 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11204 					meta.func_name);
11205 				return -EFAULT;
11206 			}
11207 		} else if (!__btf_type_is_struct(ptr_type)) {
11208 			if (!meta.r0_size) {
11209 				__u32 sz;
11210 
11211 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11212 					meta.r0_size = sz;
11213 					meta.r0_rdonly = true;
11214 				}
11215 			}
11216 			if (!meta.r0_size) {
11217 				ptr_type_name = btf_name_by_offset(desc_btf,
11218 								   ptr_type->name_off);
11219 				verbose(env,
11220 					"kernel function %s returns pointer type %s %s is not supported\n",
11221 					func_name,
11222 					btf_type_str(ptr_type),
11223 					ptr_type_name);
11224 				return -EINVAL;
11225 			}
11226 
11227 			mark_reg_known_zero(env, regs, BPF_REG_0);
11228 			regs[BPF_REG_0].type = PTR_TO_MEM;
11229 			regs[BPF_REG_0].mem_size = meta.r0_size;
11230 
11231 			if (meta.r0_rdonly)
11232 				regs[BPF_REG_0].type |= MEM_RDONLY;
11233 
11234 			/* Ensures we don't access the memory after a release_reference() */
11235 			if (meta.ref_obj_id)
11236 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11237 		} else {
11238 			mark_reg_known_zero(env, regs, BPF_REG_0);
11239 			regs[BPF_REG_0].btf = desc_btf;
11240 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11241 			regs[BPF_REG_0].btf_id = ptr_type_id;
11242 		}
11243 
11244 		if (is_kfunc_ret_null(&meta)) {
11245 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11246 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11247 			regs[BPF_REG_0].id = ++env->id_gen;
11248 		}
11249 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11250 		if (is_kfunc_acquire(&meta)) {
11251 			int id = acquire_reference_state(env, insn_idx);
11252 
11253 			if (id < 0)
11254 				return id;
11255 			if (is_kfunc_ret_null(&meta))
11256 				regs[BPF_REG_0].id = id;
11257 			regs[BPF_REG_0].ref_obj_id = id;
11258 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11259 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11260 		}
11261 
11262 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11263 			regs[BPF_REG_0].id = ++env->id_gen;
11264 	} else if (btf_type_is_void(t)) {
11265 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11266 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11267 				insn_aux->kptr_struct_meta =
11268 					btf_find_struct_meta(meta.arg_btf,
11269 							     meta.arg_btf_id);
11270 			}
11271 		}
11272 	}
11273 
11274 	nargs = btf_type_vlen(meta.func_proto);
11275 	args = (const struct btf_param *)(meta.func_proto + 1);
11276 	for (i = 0; i < nargs; i++) {
11277 		u32 regno = i + 1;
11278 
11279 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11280 		if (btf_type_is_ptr(t))
11281 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11282 		else
11283 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11284 			mark_btf_func_reg_size(env, regno, t->size);
11285 	}
11286 
11287 	if (is_iter_next_kfunc(&meta)) {
11288 		err = process_iter_next_call(env, insn_idx, &meta);
11289 		if (err)
11290 			return err;
11291 	}
11292 
11293 	return 0;
11294 }
11295 
11296 static bool signed_add_overflows(s64 a, s64 b)
11297 {
11298 	/* Do the add in u64, where overflow is well-defined */
11299 	s64 res = (s64)((u64)a + (u64)b);
11300 
11301 	if (b < 0)
11302 		return res > a;
11303 	return res < a;
11304 }
11305 
11306 static bool signed_add32_overflows(s32 a, s32 b)
11307 {
11308 	/* Do the add in u32, where overflow is well-defined */
11309 	s32 res = (s32)((u32)a + (u32)b);
11310 
11311 	if (b < 0)
11312 		return res > a;
11313 	return res < a;
11314 }
11315 
11316 static bool signed_sub_overflows(s64 a, s64 b)
11317 {
11318 	/* Do the sub in u64, where overflow is well-defined */
11319 	s64 res = (s64)((u64)a - (u64)b);
11320 
11321 	if (b < 0)
11322 		return res < a;
11323 	return res > a;
11324 }
11325 
11326 static bool signed_sub32_overflows(s32 a, s32 b)
11327 {
11328 	/* Do the sub in u32, where overflow is well-defined */
11329 	s32 res = (s32)((u32)a - (u32)b);
11330 
11331 	if (b < 0)
11332 		return res < a;
11333 	return res > a;
11334 }
11335 
11336 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11337 				  const struct bpf_reg_state *reg,
11338 				  enum bpf_reg_type type)
11339 {
11340 	bool known = tnum_is_const(reg->var_off);
11341 	s64 val = reg->var_off.value;
11342 	s64 smin = reg->smin_value;
11343 
11344 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11345 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11346 			reg_type_str(env, type), val);
11347 		return false;
11348 	}
11349 
11350 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11351 		verbose(env, "%s pointer offset %d is not allowed\n",
11352 			reg_type_str(env, type), reg->off);
11353 		return false;
11354 	}
11355 
11356 	if (smin == S64_MIN) {
11357 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11358 			reg_type_str(env, type));
11359 		return false;
11360 	}
11361 
11362 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11363 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11364 			smin, reg_type_str(env, type));
11365 		return false;
11366 	}
11367 
11368 	return true;
11369 }
11370 
11371 enum {
11372 	REASON_BOUNDS	= -1,
11373 	REASON_TYPE	= -2,
11374 	REASON_PATHS	= -3,
11375 	REASON_LIMIT	= -4,
11376 	REASON_STACK	= -5,
11377 };
11378 
11379 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11380 			      u32 *alu_limit, bool mask_to_left)
11381 {
11382 	u32 max = 0, ptr_limit = 0;
11383 
11384 	switch (ptr_reg->type) {
11385 	case PTR_TO_STACK:
11386 		/* Offset 0 is out-of-bounds, but acceptable start for the
11387 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11388 		 * offset where we would need to deal with min/max bounds is
11389 		 * currently prohibited for unprivileged.
11390 		 */
11391 		max = MAX_BPF_STACK + mask_to_left;
11392 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11393 		break;
11394 	case PTR_TO_MAP_VALUE:
11395 		max = ptr_reg->map_ptr->value_size;
11396 		ptr_limit = (mask_to_left ?
11397 			     ptr_reg->smin_value :
11398 			     ptr_reg->umax_value) + ptr_reg->off;
11399 		break;
11400 	default:
11401 		return REASON_TYPE;
11402 	}
11403 
11404 	if (ptr_limit >= max)
11405 		return REASON_LIMIT;
11406 	*alu_limit = ptr_limit;
11407 	return 0;
11408 }
11409 
11410 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11411 				    const struct bpf_insn *insn)
11412 {
11413 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11414 }
11415 
11416 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11417 				       u32 alu_state, u32 alu_limit)
11418 {
11419 	/* If we arrived here from different branches with different
11420 	 * state or limits to sanitize, then this won't work.
11421 	 */
11422 	if (aux->alu_state &&
11423 	    (aux->alu_state != alu_state ||
11424 	     aux->alu_limit != alu_limit))
11425 		return REASON_PATHS;
11426 
11427 	/* Corresponding fixup done in do_misc_fixups(). */
11428 	aux->alu_state = alu_state;
11429 	aux->alu_limit = alu_limit;
11430 	return 0;
11431 }
11432 
11433 static int sanitize_val_alu(struct bpf_verifier_env *env,
11434 			    struct bpf_insn *insn)
11435 {
11436 	struct bpf_insn_aux_data *aux = cur_aux(env);
11437 
11438 	if (can_skip_alu_sanitation(env, insn))
11439 		return 0;
11440 
11441 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11442 }
11443 
11444 static bool sanitize_needed(u8 opcode)
11445 {
11446 	return opcode == BPF_ADD || opcode == BPF_SUB;
11447 }
11448 
11449 struct bpf_sanitize_info {
11450 	struct bpf_insn_aux_data aux;
11451 	bool mask_to_left;
11452 };
11453 
11454 static struct bpf_verifier_state *
11455 sanitize_speculative_path(struct bpf_verifier_env *env,
11456 			  const struct bpf_insn *insn,
11457 			  u32 next_idx, u32 curr_idx)
11458 {
11459 	struct bpf_verifier_state *branch;
11460 	struct bpf_reg_state *regs;
11461 
11462 	branch = push_stack(env, next_idx, curr_idx, true);
11463 	if (branch && insn) {
11464 		regs = branch->frame[branch->curframe]->regs;
11465 		if (BPF_SRC(insn->code) == BPF_K) {
11466 			mark_reg_unknown(env, regs, insn->dst_reg);
11467 		} else if (BPF_SRC(insn->code) == BPF_X) {
11468 			mark_reg_unknown(env, regs, insn->dst_reg);
11469 			mark_reg_unknown(env, regs, insn->src_reg);
11470 		}
11471 	}
11472 	return branch;
11473 }
11474 
11475 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11476 			    struct bpf_insn *insn,
11477 			    const struct bpf_reg_state *ptr_reg,
11478 			    const struct bpf_reg_state *off_reg,
11479 			    struct bpf_reg_state *dst_reg,
11480 			    struct bpf_sanitize_info *info,
11481 			    const bool commit_window)
11482 {
11483 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11484 	struct bpf_verifier_state *vstate = env->cur_state;
11485 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11486 	bool off_is_neg = off_reg->smin_value < 0;
11487 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11488 	u8 opcode = BPF_OP(insn->code);
11489 	u32 alu_state, alu_limit;
11490 	struct bpf_reg_state tmp;
11491 	bool ret;
11492 	int err;
11493 
11494 	if (can_skip_alu_sanitation(env, insn))
11495 		return 0;
11496 
11497 	/* We already marked aux for masking from non-speculative
11498 	 * paths, thus we got here in the first place. We only care
11499 	 * to explore bad access from here.
11500 	 */
11501 	if (vstate->speculative)
11502 		goto do_sim;
11503 
11504 	if (!commit_window) {
11505 		if (!tnum_is_const(off_reg->var_off) &&
11506 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11507 			return REASON_BOUNDS;
11508 
11509 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11510 				     (opcode == BPF_SUB && !off_is_neg);
11511 	}
11512 
11513 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11514 	if (err < 0)
11515 		return err;
11516 
11517 	if (commit_window) {
11518 		/* In commit phase we narrow the masking window based on
11519 		 * the observed pointer move after the simulated operation.
11520 		 */
11521 		alu_state = info->aux.alu_state;
11522 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11523 	} else {
11524 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11525 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11526 		alu_state |= ptr_is_dst_reg ?
11527 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11528 
11529 		/* Limit pruning on unknown scalars to enable deep search for
11530 		 * potential masking differences from other program paths.
11531 		 */
11532 		if (!off_is_imm)
11533 			env->explore_alu_limits = true;
11534 	}
11535 
11536 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11537 	if (err < 0)
11538 		return err;
11539 do_sim:
11540 	/* If we're in commit phase, we're done here given we already
11541 	 * pushed the truncated dst_reg into the speculative verification
11542 	 * stack.
11543 	 *
11544 	 * Also, when register is a known constant, we rewrite register-based
11545 	 * operation to immediate-based, and thus do not need masking (and as
11546 	 * a consequence, do not need to simulate the zero-truncation either).
11547 	 */
11548 	if (commit_window || off_is_imm)
11549 		return 0;
11550 
11551 	/* Simulate and find potential out-of-bounds access under
11552 	 * speculative execution from truncation as a result of
11553 	 * masking when off was not within expected range. If off
11554 	 * sits in dst, then we temporarily need to move ptr there
11555 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11556 	 * for cases where we use K-based arithmetic in one direction
11557 	 * and truncated reg-based in the other in order to explore
11558 	 * bad access.
11559 	 */
11560 	if (!ptr_is_dst_reg) {
11561 		tmp = *dst_reg;
11562 		copy_register_state(dst_reg, ptr_reg);
11563 	}
11564 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11565 					env->insn_idx);
11566 	if (!ptr_is_dst_reg && ret)
11567 		*dst_reg = tmp;
11568 	return !ret ? REASON_STACK : 0;
11569 }
11570 
11571 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11572 {
11573 	struct bpf_verifier_state *vstate = env->cur_state;
11574 
11575 	/* If we simulate paths under speculation, we don't update the
11576 	 * insn as 'seen' such that when we verify unreachable paths in
11577 	 * the non-speculative domain, sanitize_dead_code() can still
11578 	 * rewrite/sanitize them.
11579 	 */
11580 	if (!vstate->speculative)
11581 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11582 }
11583 
11584 static int sanitize_err(struct bpf_verifier_env *env,
11585 			const struct bpf_insn *insn, int reason,
11586 			const struct bpf_reg_state *off_reg,
11587 			const struct bpf_reg_state *dst_reg)
11588 {
11589 	static const char *err = "pointer arithmetic with it prohibited for !root";
11590 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11591 	u32 dst = insn->dst_reg, src = insn->src_reg;
11592 
11593 	switch (reason) {
11594 	case REASON_BOUNDS:
11595 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11596 			off_reg == dst_reg ? dst : src, err);
11597 		break;
11598 	case REASON_TYPE:
11599 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11600 			off_reg == dst_reg ? src : dst, err);
11601 		break;
11602 	case REASON_PATHS:
11603 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11604 			dst, op, err);
11605 		break;
11606 	case REASON_LIMIT:
11607 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11608 			dst, op, err);
11609 		break;
11610 	case REASON_STACK:
11611 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11612 			dst, err);
11613 		break;
11614 	default:
11615 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11616 			reason);
11617 		break;
11618 	}
11619 
11620 	return -EACCES;
11621 }
11622 
11623 /* check that stack access falls within stack limits and that 'reg' doesn't
11624  * have a variable offset.
11625  *
11626  * Variable offset is prohibited for unprivileged mode for simplicity since it
11627  * requires corresponding support in Spectre masking for stack ALU.  See also
11628  * retrieve_ptr_limit().
11629  *
11630  *
11631  * 'off' includes 'reg->off'.
11632  */
11633 static int check_stack_access_for_ptr_arithmetic(
11634 				struct bpf_verifier_env *env,
11635 				int regno,
11636 				const struct bpf_reg_state *reg,
11637 				int off)
11638 {
11639 	if (!tnum_is_const(reg->var_off)) {
11640 		char tn_buf[48];
11641 
11642 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11643 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11644 			regno, tn_buf, off);
11645 		return -EACCES;
11646 	}
11647 
11648 	if (off >= 0 || off < -MAX_BPF_STACK) {
11649 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11650 			"prohibited for !root; off=%d\n", regno, off);
11651 		return -EACCES;
11652 	}
11653 
11654 	return 0;
11655 }
11656 
11657 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11658 				 const struct bpf_insn *insn,
11659 				 const struct bpf_reg_state *dst_reg)
11660 {
11661 	u32 dst = insn->dst_reg;
11662 
11663 	/* For unprivileged we require that resulting offset must be in bounds
11664 	 * in order to be able to sanitize access later on.
11665 	 */
11666 	if (env->bypass_spec_v1)
11667 		return 0;
11668 
11669 	switch (dst_reg->type) {
11670 	case PTR_TO_STACK:
11671 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11672 					dst_reg->off + dst_reg->var_off.value))
11673 			return -EACCES;
11674 		break;
11675 	case PTR_TO_MAP_VALUE:
11676 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11677 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11678 				"prohibited for !root\n", dst);
11679 			return -EACCES;
11680 		}
11681 		break;
11682 	default:
11683 		break;
11684 	}
11685 
11686 	return 0;
11687 }
11688 
11689 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11690  * Caller should also handle BPF_MOV case separately.
11691  * If we return -EACCES, caller may want to try again treating pointer as a
11692  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11693  */
11694 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11695 				   struct bpf_insn *insn,
11696 				   const struct bpf_reg_state *ptr_reg,
11697 				   const struct bpf_reg_state *off_reg)
11698 {
11699 	struct bpf_verifier_state *vstate = env->cur_state;
11700 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11701 	struct bpf_reg_state *regs = state->regs, *dst_reg;
11702 	bool known = tnum_is_const(off_reg->var_off);
11703 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11704 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11705 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11706 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11707 	struct bpf_sanitize_info info = {};
11708 	u8 opcode = BPF_OP(insn->code);
11709 	u32 dst = insn->dst_reg;
11710 	int ret;
11711 
11712 	dst_reg = &regs[dst];
11713 
11714 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11715 	    smin_val > smax_val || umin_val > umax_val) {
11716 		/* Taint dst register if offset had invalid bounds derived from
11717 		 * e.g. dead branches.
11718 		 */
11719 		__mark_reg_unknown(env, dst_reg);
11720 		return 0;
11721 	}
11722 
11723 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
11724 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
11725 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11726 			__mark_reg_unknown(env, dst_reg);
11727 			return 0;
11728 		}
11729 
11730 		verbose(env,
11731 			"R%d 32-bit pointer arithmetic prohibited\n",
11732 			dst);
11733 		return -EACCES;
11734 	}
11735 
11736 	if (ptr_reg->type & PTR_MAYBE_NULL) {
11737 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11738 			dst, reg_type_str(env, ptr_reg->type));
11739 		return -EACCES;
11740 	}
11741 
11742 	switch (base_type(ptr_reg->type)) {
11743 	case CONST_PTR_TO_MAP:
11744 		/* smin_val represents the known value */
11745 		if (known && smin_val == 0 && opcode == BPF_ADD)
11746 			break;
11747 		fallthrough;
11748 	case PTR_TO_PACKET_END:
11749 	case PTR_TO_SOCKET:
11750 	case PTR_TO_SOCK_COMMON:
11751 	case PTR_TO_TCP_SOCK:
11752 	case PTR_TO_XDP_SOCK:
11753 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11754 			dst, reg_type_str(env, ptr_reg->type));
11755 		return -EACCES;
11756 	default:
11757 		break;
11758 	}
11759 
11760 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11761 	 * The id may be overwritten later if we create a new variable offset.
11762 	 */
11763 	dst_reg->type = ptr_reg->type;
11764 	dst_reg->id = ptr_reg->id;
11765 
11766 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11767 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11768 		return -EINVAL;
11769 
11770 	/* pointer types do not carry 32-bit bounds at the moment. */
11771 	__mark_reg32_unbounded(dst_reg);
11772 
11773 	if (sanitize_needed(opcode)) {
11774 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11775 				       &info, false);
11776 		if (ret < 0)
11777 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11778 	}
11779 
11780 	switch (opcode) {
11781 	case BPF_ADD:
11782 		/* We can take a fixed offset as long as it doesn't overflow
11783 		 * the s32 'off' field
11784 		 */
11785 		if (known && (ptr_reg->off + smin_val ==
11786 			      (s64)(s32)(ptr_reg->off + smin_val))) {
11787 			/* pointer += K.  Accumulate it into fixed offset */
11788 			dst_reg->smin_value = smin_ptr;
11789 			dst_reg->smax_value = smax_ptr;
11790 			dst_reg->umin_value = umin_ptr;
11791 			dst_reg->umax_value = umax_ptr;
11792 			dst_reg->var_off = ptr_reg->var_off;
11793 			dst_reg->off = ptr_reg->off + smin_val;
11794 			dst_reg->raw = ptr_reg->raw;
11795 			break;
11796 		}
11797 		/* A new variable offset is created.  Note that off_reg->off
11798 		 * == 0, since it's a scalar.
11799 		 * dst_reg gets the pointer type and since some positive
11800 		 * integer value was added to the pointer, give it a new 'id'
11801 		 * if it's a PTR_TO_PACKET.
11802 		 * this creates a new 'base' pointer, off_reg (variable) gets
11803 		 * added into the variable offset, and we copy the fixed offset
11804 		 * from ptr_reg.
11805 		 */
11806 		if (signed_add_overflows(smin_ptr, smin_val) ||
11807 		    signed_add_overflows(smax_ptr, smax_val)) {
11808 			dst_reg->smin_value = S64_MIN;
11809 			dst_reg->smax_value = S64_MAX;
11810 		} else {
11811 			dst_reg->smin_value = smin_ptr + smin_val;
11812 			dst_reg->smax_value = smax_ptr + smax_val;
11813 		}
11814 		if (umin_ptr + umin_val < umin_ptr ||
11815 		    umax_ptr + umax_val < umax_ptr) {
11816 			dst_reg->umin_value = 0;
11817 			dst_reg->umax_value = U64_MAX;
11818 		} else {
11819 			dst_reg->umin_value = umin_ptr + umin_val;
11820 			dst_reg->umax_value = umax_ptr + umax_val;
11821 		}
11822 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11823 		dst_reg->off = ptr_reg->off;
11824 		dst_reg->raw = ptr_reg->raw;
11825 		if (reg_is_pkt_pointer(ptr_reg)) {
11826 			dst_reg->id = ++env->id_gen;
11827 			/* something was added to pkt_ptr, set range to zero */
11828 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11829 		}
11830 		break;
11831 	case BPF_SUB:
11832 		if (dst_reg == off_reg) {
11833 			/* scalar -= pointer.  Creates an unknown scalar */
11834 			verbose(env, "R%d tried to subtract pointer from scalar\n",
11835 				dst);
11836 			return -EACCES;
11837 		}
11838 		/* We don't allow subtraction from FP, because (according to
11839 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
11840 		 * be able to deal with it.
11841 		 */
11842 		if (ptr_reg->type == PTR_TO_STACK) {
11843 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
11844 				dst);
11845 			return -EACCES;
11846 		}
11847 		if (known && (ptr_reg->off - smin_val ==
11848 			      (s64)(s32)(ptr_reg->off - smin_val))) {
11849 			/* pointer -= K.  Subtract it from fixed offset */
11850 			dst_reg->smin_value = smin_ptr;
11851 			dst_reg->smax_value = smax_ptr;
11852 			dst_reg->umin_value = umin_ptr;
11853 			dst_reg->umax_value = umax_ptr;
11854 			dst_reg->var_off = ptr_reg->var_off;
11855 			dst_reg->id = ptr_reg->id;
11856 			dst_reg->off = ptr_reg->off - smin_val;
11857 			dst_reg->raw = ptr_reg->raw;
11858 			break;
11859 		}
11860 		/* A new variable offset is created.  If the subtrahend is known
11861 		 * nonnegative, then any reg->range we had before is still good.
11862 		 */
11863 		if (signed_sub_overflows(smin_ptr, smax_val) ||
11864 		    signed_sub_overflows(smax_ptr, smin_val)) {
11865 			/* Overflow possible, we know nothing */
11866 			dst_reg->smin_value = S64_MIN;
11867 			dst_reg->smax_value = S64_MAX;
11868 		} else {
11869 			dst_reg->smin_value = smin_ptr - smax_val;
11870 			dst_reg->smax_value = smax_ptr - smin_val;
11871 		}
11872 		if (umin_ptr < umax_val) {
11873 			/* Overflow possible, we know nothing */
11874 			dst_reg->umin_value = 0;
11875 			dst_reg->umax_value = U64_MAX;
11876 		} else {
11877 			/* Cannot overflow (as long as bounds are consistent) */
11878 			dst_reg->umin_value = umin_ptr - umax_val;
11879 			dst_reg->umax_value = umax_ptr - umin_val;
11880 		}
11881 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11882 		dst_reg->off = ptr_reg->off;
11883 		dst_reg->raw = ptr_reg->raw;
11884 		if (reg_is_pkt_pointer(ptr_reg)) {
11885 			dst_reg->id = ++env->id_gen;
11886 			/* something was added to pkt_ptr, set range to zero */
11887 			if (smin_val < 0)
11888 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11889 		}
11890 		break;
11891 	case BPF_AND:
11892 	case BPF_OR:
11893 	case BPF_XOR:
11894 		/* bitwise ops on pointers are troublesome, prohibit. */
11895 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11896 			dst, bpf_alu_string[opcode >> 4]);
11897 		return -EACCES;
11898 	default:
11899 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
11900 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11901 			dst, bpf_alu_string[opcode >> 4]);
11902 		return -EACCES;
11903 	}
11904 
11905 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11906 		return -EINVAL;
11907 	reg_bounds_sync(dst_reg);
11908 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11909 		return -EACCES;
11910 	if (sanitize_needed(opcode)) {
11911 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11912 				       &info, true);
11913 		if (ret < 0)
11914 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11915 	}
11916 
11917 	return 0;
11918 }
11919 
11920 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11921 				 struct bpf_reg_state *src_reg)
11922 {
11923 	s32 smin_val = src_reg->s32_min_value;
11924 	s32 smax_val = src_reg->s32_max_value;
11925 	u32 umin_val = src_reg->u32_min_value;
11926 	u32 umax_val = src_reg->u32_max_value;
11927 
11928 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11929 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11930 		dst_reg->s32_min_value = S32_MIN;
11931 		dst_reg->s32_max_value = S32_MAX;
11932 	} else {
11933 		dst_reg->s32_min_value += smin_val;
11934 		dst_reg->s32_max_value += smax_val;
11935 	}
11936 	if (dst_reg->u32_min_value + umin_val < umin_val ||
11937 	    dst_reg->u32_max_value + umax_val < umax_val) {
11938 		dst_reg->u32_min_value = 0;
11939 		dst_reg->u32_max_value = U32_MAX;
11940 	} else {
11941 		dst_reg->u32_min_value += umin_val;
11942 		dst_reg->u32_max_value += umax_val;
11943 	}
11944 }
11945 
11946 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11947 			       struct bpf_reg_state *src_reg)
11948 {
11949 	s64 smin_val = src_reg->smin_value;
11950 	s64 smax_val = src_reg->smax_value;
11951 	u64 umin_val = src_reg->umin_value;
11952 	u64 umax_val = src_reg->umax_value;
11953 
11954 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11955 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
11956 		dst_reg->smin_value = S64_MIN;
11957 		dst_reg->smax_value = S64_MAX;
11958 	} else {
11959 		dst_reg->smin_value += smin_val;
11960 		dst_reg->smax_value += smax_val;
11961 	}
11962 	if (dst_reg->umin_value + umin_val < umin_val ||
11963 	    dst_reg->umax_value + umax_val < umax_val) {
11964 		dst_reg->umin_value = 0;
11965 		dst_reg->umax_value = U64_MAX;
11966 	} else {
11967 		dst_reg->umin_value += umin_val;
11968 		dst_reg->umax_value += umax_val;
11969 	}
11970 }
11971 
11972 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11973 				 struct bpf_reg_state *src_reg)
11974 {
11975 	s32 smin_val = src_reg->s32_min_value;
11976 	s32 smax_val = src_reg->s32_max_value;
11977 	u32 umin_val = src_reg->u32_min_value;
11978 	u32 umax_val = src_reg->u32_max_value;
11979 
11980 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11981 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11982 		/* Overflow possible, we know nothing */
11983 		dst_reg->s32_min_value = S32_MIN;
11984 		dst_reg->s32_max_value = S32_MAX;
11985 	} else {
11986 		dst_reg->s32_min_value -= smax_val;
11987 		dst_reg->s32_max_value -= smin_val;
11988 	}
11989 	if (dst_reg->u32_min_value < umax_val) {
11990 		/* Overflow possible, we know nothing */
11991 		dst_reg->u32_min_value = 0;
11992 		dst_reg->u32_max_value = U32_MAX;
11993 	} else {
11994 		/* Cannot overflow (as long as bounds are consistent) */
11995 		dst_reg->u32_min_value -= umax_val;
11996 		dst_reg->u32_max_value -= umin_val;
11997 	}
11998 }
11999 
12000 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12001 			       struct bpf_reg_state *src_reg)
12002 {
12003 	s64 smin_val = src_reg->smin_value;
12004 	s64 smax_val = src_reg->smax_value;
12005 	u64 umin_val = src_reg->umin_value;
12006 	u64 umax_val = src_reg->umax_value;
12007 
12008 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12009 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12010 		/* Overflow possible, we know nothing */
12011 		dst_reg->smin_value = S64_MIN;
12012 		dst_reg->smax_value = S64_MAX;
12013 	} else {
12014 		dst_reg->smin_value -= smax_val;
12015 		dst_reg->smax_value -= smin_val;
12016 	}
12017 	if (dst_reg->umin_value < umax_val) {
12018 		/* Overflow possible, we know nothing */
12019 		dst_reg->umin_value = 0;
12020 		dst_reg->umax_value = U64_MAX;
12021 	} else {
12022 		/* Cannot overflow (as long as bounds are consistent) */
12023 		dst_reg->umin_value -= umax_val;
12024 		dst_reg->umax_value -= umin_val;
12025 	}
12026 }
12027 
12028 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12029 				 struct bpf_reg_state *src_reg)
12030 {
12031 	s32 smin_val = src_reg->s32_min_value;
12032 	u32 umin_val = src_reg->u32_min_value;
12033 	u32 umax_val = src_reg->u32_max_value;
12034 
12035 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12036 		/* Ain't nobody got time to multiply that sign */
12037 		__mark_reg32_unbounded(dst_reg);
12038 		return;
12039 	}
12040 	/* Both values are positive, so we can work with unsigned and
12041 	 * copy the result to signed (unless it exceeds S32_MAX).
12042 	 */
12043 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12044 		/* Potential overflow, we know nothing */
12045 		__mark_reg32_unbounded(dst_reg);
12046 		return;
12047 	}
12048 	dst_reg->u32_min_value *= umin_val;
12049 	dst_reg->u32_max_value *= umax_val;
12050 	if (dst_reg->u32_max_value > S32_MAX) {
12051 		/* Overflow possible, we know nothing */
12052 		dst_reg->s32_min_value = S32_MIN;
12053 		dst_reg->s32_max_value = S32_MAX;
12054 	} else {
12055 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12056 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12057 	}
12058 }
12059 
12060 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12061 			       struct bpf_reg_state *src_reg)
12062 {
12063 	s64 smin_val = src_reg->smin_value;
12064 	u64 umin_val = src_reg->umin_value;
12065 	u64 umax_val = src_reg->umax_value;
12066 
12067 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12068 		/* Ain't nobody got time to multiply that sign */
12069 		__mark_reg64_unbounded(dst_reg);
12070 		return;
12071 	}
12072 	/* Both values are positive, so we can work with unsigned and
12073 	 * copy the result to signed (unless it exceeds S64_MAX).
12074 	 */
12075 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12076 		/* Potential overflow, we know nothing */
12077 		__mark_reg64_unbounded(dst_reg);
12078 		return;
12079 	}
12080 	dst_reg->umin_value *= umin_val;
12081 	dst_reg->umax_value *= umax_val;
12082 	if (dst_reg->umax_value > S64_MAX) {
12083 		/* Overflow possible, we know nothing */
12084 		dst_reg->smin_value = S64_MIN;
12085 		dst_reg->smax_value = S64_MAX;
12086 	} else {
12087 		dst_reg->smin_value = dst_reg->umin_value;
12088 		dst_reg->smax_value = dst_reg->umax_value;
12089 	}
12090 }
12091 
12092 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12093 				 struct bpf_reg_state *src_reg)
12094 {
12095 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12096 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12097 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12098 	s32 smin_val = src_reg->s32_min_value;
12099 	u32 umax_val = src_reg->u32_max_value;
12100 
12101 	if (src_known && dst_known) {
12102 		__mark_reg32_known(dst_reg, var32_off.value);
12103 		return;
12104 	}
12105 
12106 	/* We get our minimum from the var_off, since that's inherently
12107 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12108 	 */
12109 	dst_reg->u32_min_value = var32_off.value;
12110 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12111 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12112 		/* Lose signed bounds when ANDing negative numbers,
12113 		 * ain't nobody got time for that.
12114 		 */
12115 		dst_reg->s32_min_value = S32_MIN;
12116 		dst_reg->s32_max_value = S32_MAX;
12117 	} else {
12118 		/* ANDing two positives gives a positive, so safe to
12119 		 * cast result into s64.
12120 		 */
12121 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12122 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12123 	}
12124 }
12125 
12126 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12127 			       struct bpf_reg_state *src_reg)
12128 {
12129 	bool src_known = tnum_is_const(src_reg->var_off);
12130 	bool dst_known = tnum_is_const(dst_reg->var_off);
12131 	s64 smin_val = src_reg->smin_value;
12132 	u64 umax_val = src_reg->umax_value;
12133 
12134 	if (src_known && dst_known) {
12135 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12136 		return;
12137 	}
12138 
12139 	/* We get our minimum from the var_off, since that's inherently
12140 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12141 	 */
12142 	dst_reg->umin_value = dst_reg->var_off.value;
12143 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12144 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12145 		/* Lose signed bounds when ANDing negative numbers,
12146 		 * ain't nobody got time for that.
12147 		 */
12148 		dst_reg->smin_value = S64_MIN;
12149 		dst_reg->smax_value = S64_MAX;
12150 	} else {
12151 		/* ANDing two positives gives a positive, so safe to
12152 		 * cast result into s64.
12153 		 */
12154 		dst_reg->smin_value = dst_reg->umin_value;
12155 		dst_reg->smax_value = dst_reg->umax_value;
12156 	}
12157 	/* We may learn something more from the var_off */
12158 	__update_reg_bounds(dst_reg);
12159 }
12160 
12161 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12162 				struct bpf_reg_state *src_reg)
12163 {
12164 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12165 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12166 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12167 	s32 smin_val = src_reg->s32_min_value;
12168 	u32 umin_val = src_reg->u32_min_value;
12169 
12170 	if (src_known && dst_known) {
12171 		__mark_reg32_known(dst_reg, var32_off.value);
12172 		return;
12173 	}
12174 
12175 	/* We get our maximum from the var_off, and our minimum is the
12176 	 * maximum of the operands' minima
12177 	 */
12178 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12179 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12180 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12181 		/* Lose signed bounds when ORing negative numbers,
12182 		 * ain't nobody got time for that.
12183 		 */
12184 		dst_reg->s32_min_value = S32_MIN;
12185 		dst_reg->s32_max_value = S32_MAX;
12186 	} else {
12187 		/* ORing two positives gives a positive, so safe to
12188 		 * cast result into s64.
12189 		 */
12190 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12191 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12192 	}
12193 }
12194 
12195 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12196 			      struct bpf_reg_state *src_reg)
12197 {
12198 	bool src_known = tnum_is_const(src_reg->var_off);
12199 	bool dst_known = tnum_is_const(dst_reg->var_off);
12200 	s64 smin_val = src_reg->smin_value;
12201 	u64 umin_val = src_reg->umin_value;
12202 
12203 	if (src_known && dst_known) {
12204 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12205 		return;
12206 	}
12207 
12208 	/* We get our maximum from the var_off, and our minimum is the
12209 	 * maximum of the operands' minima
12210 	 */
12211 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12212 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12213 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12214 		/* Lose signed bounds when ORing negative numbers,
12215 		 * ain't nobody got time for that.
12216 		 */
12217 		dst_reg->smin_value = S64_MIN;
12218 		dst_reg->smax_value = S64_MAX;
12219 	} else {
12220 		/* ORing two positives gives a positive, so safe to
12221 		 * cast result into s64.
12222 		 */
12223 		dst_reg->smin_value = dst_reg->umin_value;
12224 		dst_reg->smax_value = dst_reg->umax_value;
12225 	}
12226 	/* We may learn something more from the var_off */
12227 	__update_reg_bounds(dst_reg);
12228 }
12229 
12230 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12231 				 struct bpf_reg_state *src_reg)
12232 {
12233 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12234 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12235 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12236 	s32 smin_val = src_reg->s32_min_value;
12237 
12238 	if (src_known && dst_known) {
12239 		__mark_reg32_known(dst_reg, var32_off.value);
12240 		return;
12241 	}
12242 
12243 	/* We get both minimum and maximum from the var32_off. */
12244 	dst_reg->u32_min_value = var32_off.value;
12245 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12246 
12247 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12248 		/* XORing two positive sign numbers gives a positive,
12249 		 * so safe to cast u32 result into s32.
12250 		 */
12251 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12252 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12253 	} else {
12254 		dst_reg->s32_min_value = S32_MIN;
12255 		dst_reg->s32_max_value = S32_MAX;
12256 	}
12257 }
12258 
12259 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12260 			       struct bpf_reg_state *src_reg)
12261 {
12262 	bool src_known = tnum_is_const(src_reg->var_off);
12263 	bool dst_known = tnum_is_const(dst_reg->var_off);
12264 	s64 smin_val = src_reg->smin_value;
12265 
12266 	if (src_known && dst_known) {
12267 		/* dst_reg->var_off.value has been updated earlier */
12268 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12269 		return;
12270 	}
12271 
12272 	/* We get both minimum and maximum from the var_off. */
12273 	dst_reg->umin_value = dst_reg->var_off.value;
12274 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12275 
12276 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12277 		/* XORing two positive sign numbers gives a positive,
12278 		 * so safe to cast u64 result into s64.
12279 		 */
12280 		dst_reg->smin_value = dst_reg->umin_value;
12281 		dst_reg->smax_value = dst_reg->umax_value;
12282 	} else {
12283 		dst_reg->smin_value = S64_MIN;
12284 		dst_reg->smax_value = S64_MAX;
12285 	}
12286 
12287 	__update_reg_bounds(dst_reg);
12288 }
12289 
12290 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12291 				   u64 umin_val, u64 umax_val)
12292 {
12293 	/* We lose all sign bit information (except what we can pick
12294 	 * up from var_off)
12295 	 */
12296 	dst_reg->s32_min_value = S32_MIN;
12297 	dst_reg->s32_max_value = S32_MAX;
12298 	/* If we might shift our top bit out, then we know nothing */
12299 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12300 		dst_reg->u32_min_value = 0;
12301 		dst_reg->u32_max_value = U32_MAX;
12302 	} else {
12303 		dst_reg->u32_min_value <<= umin_val;
12304 		dst_reg->u32_max_value <<= umax_val;
12305 	}
12306 }
12307 
12308 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12309 				 struct bpf_reg_state *src_reg)
12310 {
12311 	u32 umax_val = src_reg->u32_max_value;
12312 	u32 umin_val = src_reg->u32_min_value;
12313 	/* u32 alu operation will zext upper bits */
12314 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12315 
12316 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12317 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12318 	/* Not required but being careful mark reg64 bounds as unknown so
12319 	 * that we are forced to pick them up from tnum and zext later and
12320 	 * if some path skips this step we are still safe.
12321 	 */
12322 	__mark_reg64_unbounded(dst_reg);
12323 	__update_reg32_bounds(dst_reg);
12324 }
12325 
12326 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12327 				   u64 umin_val, u64 umax_val)
12328 {
12329 	/* Special case <<32 because it is a common compiler pattern to sign
12330 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12331 	 * positive we know this shift will also be positive so we can track
12332 	 * bounds correctly. Otherwise we lose all sign bit information except
12333 	 * what we can pick up from var_off. Perhaps we can generalize this
12334 	 * later to shifts of any length.
12335 	 */
12336 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12337 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12338 	else
12339 		dst_reg->smax_value = S64_MAX;
12340 
12341 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12342 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12343 	else
12344 		dst_reg->smin_value = S64_MIN;
12345 
12346 	/* If we might shift our top bit out, then we know nothing */
12347 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12348 		dst_reg->umin_value = 0;
12349 		dst_reg->umax_value = U64_MAX;
12350 	} else {
12351 		dst_reg->umin_value <<= umin_val;
12352 		dst_reg->umax_value <<= umax_val;
12353 	}
12354 }
12355 
12356 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12357 			       struct bpf_reg_state *src_reg)
12358 {
12359 	u64 umax_val = src_reg->umax_value;
12360 	u64 umin_val = src_reg->umin_value;
12361 
12362 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12363 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12364 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12365 
12366 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12367 	/* We may learn something more from the var_off */
12368 	__update_reg_bounds(dst_reg);
12369 }
12370 
12371 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12372 				 struct bpf_reg_state *src_reg)
12373 {
12374 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12375 	u32 umax_val = src_reg->u32_max_value;
12376 	u32 umin_val = src_reg->u32_min_value;
12377 
12378 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12379 	 * be negative, then either:
12380 	 * 1) src_reg might be zero, so the sign bit of the result is
12381 	 *    unknown, so we lose our signed bounds
12382 	 * 2) it's known negative, thus the unsigned bounds capture the
12383 	 *    signed bounds
12384 	 * 3) the signed bounds cross zero, so they tell us nothing
12385 	 *    about the result
12386 	 * If the value in dst_reg is known nonnegative, then again the
12387 	 * unsigned bounds capture the signed bounds.
12388 	 * Thus, in all cases it suffices to blow away our signed bounds
12389 	 * and rely on inferring new ones from the unsigned bounds and
12390 	 * var_off of the result.
12391 	 */
12392 	dst_reg->s32_min_value = S32_MIN;
12393 	dst_reg->s32_max_value = S32_MAX;
12394 
12395 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12396 	dst_reg->u32_min_value >>= umax_val;
12397 	dst_reg->u32_max_value >>= umin_val;
12398 
12399 	__mark_reg64_unbounded(dst_reg);
12400 	__update_reg32_bounds(dst_reg);
12401 }
12402 
12403 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12404 			       struct bpf_reg_state *src_reg)
12405 {
12406 	u64 umax_val = src_reg->umax_value;
12407 	u64 umin_val = src_reg->umin_value;
12408 
12409 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12410 	 * be negative, then either:
12411 	 * 1) src_reg might be zero, so the sign bit of the result is
12412 	 *    unknown, so we lose our signed bounds
12413 	 * 2) it's known negative, thus the unsigned bounds capture the
12414 	 *    signed bounds
12415 	 * 3) the signed bounds cross zero, so they tell us nothing
12416 	 *    about the result
12417 	 * If the value in dst_reg is known nonnegative, then again the
12418 	 * unsigned bounds capture the signed bounds.
12419 	 * Thus, in all cases it suffices to blow away our signed bounds
12420 	 * and rely on inferring new ones from the unsigned bounds and
12421 	 * var_off of the result.
12422 	 */
12423 	dst_reg->smin_value = S64_MIN;
12424 	dst_reg->smax_value = S64_MAX;
12425 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12426 	dst_reg->umin_value >>= umax_val;
12427 	dst_reg->umax_value >>= umin_val;
12428 
12429 	/* Its not easy to operate on alu32 bounds here because it depends
12430 	 * on bits being shifted in. Take easy way out and mark unbounded
12431 	 * so we can recalculate later from tnum.
12432 	 */
12433 	__mark_reg32_unbounded(dst_reg);
12434 	__update_reg_bounds(dst_reg);
12435 }
12436 
12437 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12438 				  struct bpf_reg_state *src_reg)
12439 {
12440 	u64 umin_val = src_reg->u32_min_value;
12441 
12442 	/* Upon reaching here, src_known is true and
12443 	 * umax_val is equal to umin_val.
12444 	 */
12445 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12446 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12447 
12448 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12449 
12450 	/* blow away the dst_reg umin_value/umax_value and rely on
12451 	 * dst_reg var_off to refine the result.
12452 	 */
12453 	dst_reg->u32_min_value = 0;
12454 	dst_reg->u32_max_value = U32_MAX;
12455 
12456 	__mark_reg64_unbounded(dst_reg);
12457 	__update_reg32_bounds(dst_reg);
12458 }
12459 
12460 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12461 				struct bpf_reg_state *src_reg)
12462 {
12463 	u64 umin_val = src_reg->umin_value;
12464 
12465 	/* Upon reaching here, src_known is true and umax_val is equal
12466 	 * to umin_val.
12467 	 */
12468 	dst_reg->smin_value >>= umin_val;
12469 	dst_reg->smax_value >>= umin_val;
12470 
12471 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12472 
12473 	/* blow away the dst_reg umin_value/umax_value and rely on
12474 	 * dst_reg var_off to refine the result.
12475 	 */
12476 	dst_reg->umin_value = 0;
12477 	dst_reg->umax_value = U64_MAX;
12478 
12479 	/* Its not easy to operate on alu32 bounds here because it depends
12480 	 * on bits being shifted in from upper 32-bits. Take easy way out
12481 	 * and mark unbounded so we can recalculate later from tnum.
12482 	 */
12483 	__mark_reg32_unbounded(dst_reg);
12484 	__update_reg_bounds(dst_reg);
12485 }
12486 
12487 /* WARNING: This function does calculations on 64-bit values, but the actual
12488  * execution may occur on 32-bit values. Therefore, things like bitshifts
12489  * need extra checks in the 32-bit case.
12490  */
12491 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12492 				      struct bpf_insn *insn,
12493 				      struct bpf_reg_state *dst_reg,
12494 				      struct bpf_reg_state src_reg)
12495 {
12496 	struct bpf_reg_state *regs = cur_regs(env);
12497 	u8 opcode = BPF_OP(insn->code);
12498 	bool src_known;
12499 	s64 smin_val, smax_val;
12500 	u64 umin_val, umax_val;
12501 	s32 s32_min_val, s32_max_val;
12502 	u32 u32_min_val, u32_max_val;
12503 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12504 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12505 	int ret;
12506 
12507 	smin_val = src_reg.smin_value;
12508 	smax_val = src_reg.smax_value;
12509 	umin_val = src_reg.umin_value;
12510 	umax_val = src_reg.umax_value;
12511 
12512 	s32_min_val = src_reg.s32_min_value;
12513 	s32_max_val = src_reg.s32_max_value;
12514 	u32_min_val = src_reg.u32_min_value;
12515 	u32_max_val = src_reg.u32_max_value;
12516 
12517 	if (alu32) {
12518 		src_known = tnum_subreg_is_const(src_reg.var_off);
12519 		if ((src_known &&
12520 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12521 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12522 			/* Taint dst register if offset had invalid bounds
12523 			 * derived from e.g. dead branches.
12524 			 */
12525 			__mark_reg_unknown(env, dst_reg);
12526 			return 0;
12527 		}
12528 	} else {
12529 		src_known = tnum_is_const(src_reg.var_off);
12530 		if ((src_known &&
12531 		     (smin_val != smax_val || umin_val != umax_val)) ||
12532 		    smin_val > smax_val || umin_val > umax_val) {
12533 			/* Taint dst register if offset had invalid bounds
12534 			 * derived from e.g. dead branches.
12535 			 */
12536 			__mark_reg_unknown(env, dst_reg);
12537 			return 0;
12538 		}
12539 	}
12540 
12541 	if (!src_known &&
12542 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12543 		__mark_reg_unknown(env, dst_reg);
12544 		return 0;
12545 	}
12546 
12547 	if (sanitize_needed(opcode)) {
12548 		ret = sanitize_val_alu(env, insn);
12549 		if (ret < 0)
12550 			return sanitize_err(env, insn, ret, NULL, NULL);
12551 	}
12552 
12553 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12554 	 * There are two classes of instructions: The first class we track both
12555 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12556 	 * greatest amount of precision when alu operations are mixed with jmp32
12557 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12558 	 * and BPF_OR. This is possible because these ops have fairly easy to
12559 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12560 	 * See alu32 verifier tests for examples. The second class of
12561 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12562 	 * with regards to tracking sign/unsigned bounds because the bits may
12563 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12564 	 * the reg unbounded in the subreg bound space and use the resulting
12565 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12566 	 */
12567 	switch (opcode) {
12568 	case BPF_ADD:
12569 		scalar32_min_max_add(dst_reg, &src_reg);
12570 		scalar_min_max_add(dst_reg, &src_reg);
12571 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12572 		break;
12573 	case BPF_SUB:
12574 		scalar32_min_max_sub(dst_reg, &src_reg);
12575 		scalar_min_max_sub(dst_reg, &src_reg);
12576 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12577 		break;
12578 	case BPF_MUL:
12579 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12580 		scalar32_min_max_mul(dst_reg, &src_reg);
12581 		scalar_min_max_mul(dst_reg, &src_reg);
12582 		break;
12583 	case BPF_AND:
12584 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12585 		scalar32_min_max_and(dst_reg, &src_reg);
12586 		scalar_min_max_and(dst_reg, &src_reg);
12587 		break;
12588 	case BPF_OR:
12589 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12590 		scalar32_min_max_or(dst_reg, &src_reg);
12591 		scalar_min_max_or(dst_reg, &src_reg);
12592 		break;
12593 	case BPF_XOR:
12594 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12595 		scalar32_min_max_xor(dst_reg, &src_reg);
12596 		scalar_min_max_xor(dst_reg, &src_reg);
12597 		break;
12598 	case BPF_LSH:
12599 		if (umax_val >= insn_bitness) {
12600 			/* Shifts greater than 31 or 63 are undefined.
12601 			 * This includes shifts by a negative number.
12602 			 */
12603 			mark_reg_unknown(env, regs, insn->dst_reg);
12604 			break;
12605 		}
12606 		if (alu32)
12607 			scalar32_min_max_lsh(dst_reg, &src_reg);
12608 		else
12609 			scalar_min_max_lsh(dst_reg, &src_reg);
12610 		break;
12611 	case BPF_RSH:
12612 		if (umax_val >= insn_bitness) {
12613 			/* Shifts greater than 31 or 63 are undefined.
12614 			 * This includes shifts by a negative number.
12615 			 */
12616 			mark_reg_unknown(env, regs, insn->dst_reg);
12617 			break;
12618 		}
12619 		if (alu32)
12620 			scalar32_min_max_rsh(dst_reg, &src_reg);
12621 		else
12622 			scalar_min_max_rsh(dst_reg, &src_reg);
12623 		break;
12624 	case BPF_ARSH:
12625 		if (umax_val >= insn_bitness) {
12626 			/* Shifts greater than 31 or 63 are undefined.
12627 			 * This includes shifts by a negative number.
12628 			 */
12629 			mark_reg_unknown(env, regs, insn->dst_reg);
12630 			break;
12631 		}
12632 		if (alu32)
12633 			scalar32_min_max_arsh(dst_reg, &src_reg);
12634 		else
12635 			scalar_min_max_arsh(dst_reg, &src_reg);
12636 		break;
12637 	default:
12638 		mark_reg_unknown(env, regs, insn->dst_reg);
12639 		break;
12640 	}
12641 
12642 	/* ALU32 ops are zero extended into 64bit register */
12643 	if (alu32)
12644 		zext_32_to_64(dst_reg);
12645 	reg_bounds_sync(dst_reg);
12646 	return 0;
12647 }
12648 
12649 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12650  * and var_off.
12651  */
12652 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12653 				   struct bpf_insn *insn)
12654 {
12655 	struct bpf_verifier_state *vstate = env->cur_state;
12656 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12657 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12658 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12659 	u8 opcode = BPF_OP(insn->code);
12660 	int err;
12661 
12662 	dst_reg = &regs[insn->dst_reg];
12663 	src_reg = NULL;
12664 	if (dst_reg->type != SCALAR_VALUE)
12665 		ptr_reg = dst_reg;
12666 	else
12667 		/* Make sure ID is cleared otherwise dst_reg min/max could be
12668 		 * incorrectly propagated into other registers by find_equal_scalars()
12669 		 */
12670 		dst_reg->id = 0;
12671 	if (BPF_SRC(insn->code) == BPF_X) {
12672 		src_reg = &regs[insn->src_reg];
12673 		if (src_reg->type != SCALAR_VALUE) {
12674 			if (dst_reg->type != SCALAR_VALUE) {
12675 				/* Combining two pointers by any ALU op yields
12676 				 * an arbitrary scalar. Disallow all math except
12677 				 * pointer subtraction
12678 				 */
12679 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12680 					mark_reg_unknown(env, regs, insn->dst_reg);
12681 					return 0;
12682 				}
12683 				verbose(env, "R%d pointer %s pointer prohibited\n",
12684 					insn->dst_reg,
12685 					bpf_alu_string[opcode >> 4]);
12686 				return -EACCES;
12687 			} else {
12688 				/* scalar += pointer
12689 				 * This is legal, but we have to reverse our
12690 				 * src/dest handling in computing the range
12691 				 */
12692 				err = mark_chain_precision(env, insn->dst_reg);
12693 				if (err)
12694 					return err;
12695 				return adjust_ptr_min_max_vals(env, insn,
12696 							       src_reg, dst_reg);
12697 			}
12698 		} else if (ptr_reg) {
12699 			/* pointer += scalar */
12700 			err = mark_chain_precision(env, insn->src_reg);
12701 			if (err)
12702 				return err;
12703 			return adjust_ptr_min_max_vals(env, insn,
12704 						       dst_reg, src_reg);
12705 		} else if (dst_reg->precise) {
12706 			/* if dst_reg is precise, src_reg should be precise as well */
12707 			err = mark_chain_precision(env, insn->src_reg);
12708 			if (err)
12709 				return err;
12710 		}
12711 	} else {
12712 		/* Pretend the src is a reg with a known value, since we only
12713 		 * need to be able to read from this state.
12714 		 */
12715 		off_reg.type = SCALAR_VALUE;
12716 		__mark_reg_known(&off_reg, insn->imm);
12717 		src_reg = &off_reg;
12718 		if (ptr_reg) /* pointer += K */
12719 			return adjust_ptr_min_max_vals(env, insn,
12720 						       ptr_reg, src_reg);
12721 	}
12722 
12723 	/* Got here implies adding two SCALAR_VALUEs */
12724 	if (WARN_ON_ONCE(ptr_reg)) {
12725 		print_verifier_state(env, state, true);
12726 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
12727 		return -EINVAL;
12728 	}
12729 	if (WARN_ON(!src_reg)) {
12730 		print_verifier_state(env, state, true);
12731 		verbose(env, "verifier internal error: no src_reg\n");
12732 		return -EINVAL;
12733 	}
12734 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12735 }
12736 
12737 /* check validity of 32-bit and 64-bit arithmetic operations */
12738 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12739 {
12740 	struct bpf_reg_state *regs = cur_regs(env);
12741 	u8 opcode = BPF_OP(insn->code);
12742 	int err;
12743 
12744 	if (opcode == BPF_END || opcode == BPF_NEG) {
12745 		if (opcode == BPF_NEG) {
12746 			if (BPF_SRC(insn->code) != BPF_K ||
12747 			    insn->src_reg != BPF_REG_0 ||
12748 			    insn->off != 0 || insn->imm != 0) {
12749 				verbose(env, "BPF_NEG uses reserved fields\n");
12750 				return -EINVAL;
12751 			}
12752 		} else {
12753 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12754 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12755 			    BPF_CLASS(insn->code) == BPF_ALU64) {
12756 				verbose(env, "BPF_END uses reserved fields\n");
12757 				return -EINVAL;
12758 			}
12759 		}
12760 
12761 		/* check src operand */
12762 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12763 		if (err)
12764 			return err;
12765 
12766 		if (is_pointer_value(env, insn->dst_reg)) {
12767 			verbose(env, "R%d pointer arithmetic prohibited\n",
12768 				insn->dst_reg);
12769 			return -EACCES;
12770 		}
12771 
12772 		/* check dest operand */
12773 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
12774 		if (err)
12775 			return err;
12776 
12777 	} else if (opcode == BPF_MOV) {
12778 
12779 		if (BPF_SRC(insn->code) == BPF_X) {
12780 			if (insn->imm != 0 || insn->off != 0) {
12781 				verbose(env, "BPF_MOV uses reserved fields\n");
12782 				return -EINVAL;
12783 			}
12784 
12785 			/* check src operand */
12786 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12787 			if (err)
12788 				return err;
12789 		} else {
12790 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12791 				verbose(env, "BPF_MOV uses reserved fields\n");
12792 				return -EINVAL;
12793 			}
12794 		}
12795 
12796 		/* check dest operand, mark as required later */
12797 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12798 		if (err)
12799 			return err;
12800 
12801 		if (BPF_SRC(insn->code) == BPF_X) {
12802 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
12803 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12804 
12805 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12806 				/* case: R1 = R2
12807 				 * copy register state to dest reg
12808 				 */
12809 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12810 					/* Assign src and dst registers the same ID
12811 					 * that will be used by find_equal_scalars()
12812 					 * to propagate min/max range.
12813 					 */
12814 					src_reg->id = ++env->id_gen;
12815 				copy_register_state(dst_reg, src_reg);
12816 				dst_reg->live |= REG_LIVE_WRITTEN;
12817 				dst_reg->subreg_def = DEF_NOT_SUBREG;
12818 			} else {
12819 				/* R1 = (u32) R2 */
12820 				if (is_pointer_value(env, insn->src_reg)) {
12821 					verbose(env,
12822 						"R%d partial copy of pointer\n",
12823 						insn->src_reg);
12824 					return -EACCES;
12825 				} else if (src_reg->type == SCALAR_VALUE) {
12826 					bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12827 
12828 					if (is_src_reg_u32 && !src_reg->id)
12829 						src_reg->id = ++env->id_gen;
12830 					copy_register_state(dst_reg, src_reg);
12831 					/* Make sure ID is cleared if src_reg is not in u32 range otherwise
12832 					 * dst_reg min/max could be incorrectly
12833 					 * propagated into src_reg by find_equal_scalars()
12834 					 */
12835 					if (!is_src_reg_u32)
12836 						dst_reg->id = 0;
12837 					dst_reg->live |= REG_LIVE_WRITTEN;
12838 					dst_reg->subreg_def = env->insn_idx + 1;
12839 				} else {
12840 					mark_reg_unknown(env, regs,
12841 							 insn->dst_reg);
12842 				}
12843 				zext_32_to_64(dst_reg);
12844 				reg_bounds_sync(dst_reg);
12845 			}
12846 		} else {
12847 			/* case: R = imm
12848 			 * remember the value we stored into this reg
12849 			 */
12850 			/* clear any state __mark_reg_known doesn't set */
12851 			mark_reg_unknown(env, regs, insn->dst_reg);
12852 			regs[insn->dst_reg].type = SCALAR_VALUE;
12853 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12854 				__mark_reg_known(regs + insn->dst_reg,
12855 						 insn->imm);
12856 			} else {
12857 				__mark_reg_known(regs + insn->dst_reg,
12858 						 (u32)insn->imm);
12859 			}
12860 		}
12861 
12862 	} else if (opcode > BPF_END) {
12863 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12864 		return -EINVAL;
12865 
12866 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
12867 
12868 		if (BPF_SRC(insn->code) == BPF_X) {
12869 			if (insn->imm != 0 || insn->off != 0) {
12870 				verbose(env, "BPF_ALU uses reserved fields\n");
12871 				return -EINVAL;
12872 			}
12873 			/* check src1 operand */
12874 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12875 			if (err)
12876 				return err;
12877 		} else {
12878 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12879 				verbose(env, "BPF_ALU uses reserved fields\n");
12880 				return -EINVAL;
12881 			}
12882 		}
12883 
12884 		/* check src2 operand */
12885 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12886 		if (err)
12887 			return err;
12888 
12889 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12890 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12891 			verbose(env, "div by zero\n");
12892 			return -EINVAL;
12893 		}
12894 
12895 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12896 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12897 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12898 
12899 			if (insn->imm < 0 || insn->imm >= size) {
12900 				verbose(env, "invalid shift %d\n", insn->imm);
12901 				return -EINVAL;
12902 			}
12903 		}
12904 
12905 		/* check dest operand */
12906 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12907 		if (err)
12908 			return err;
12909 
12910 		return adjust_reg_min_max_vals(env, insn);
12911 	}
12912 
12913 	return 0;
12914 }
12915 
12916 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12917 				   struct bpf_reg_state *dst_reg,
12918 				   enum bpf_reg_type type,
12919 				   bool range_right_open)
12920 {
12921 	struct bpf_func_state *state;
12922 	struct bpf_reg_state *reg;
12923 	int new_range;
12924 
12925 	if (dst_reg->off < 0 ||
12926 	    (dst_reg->off == 0 && range_right_open))
12927 		/* This doesn't give us any range */
12928 		return;
12929 
12930 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
12931 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12932 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
12933 		 * than pkt_end, but that's because it's also less than pkt.
12934 		 */
12935 		return;
12936 
12937 	new_range = dst_reg->off;
12938 	if (range_right_open)
12939 		new_range++;
12940 
12941 	/* Examples for register markings:
12942 	 *
12943 	 * pkt_data in dst register:
12944 	 *
12945 	 *   r2 = r3;
12946 	 *   r2 += 8;
12947 	 *   if (r2 > pkt_end) goto <handle exception>
12948 	 *   <access okay>
12949 	 *
12950 	 *   r2 = r3;
12951 	 *   r2 += 8;
12952 	 *   if (r2 < pkt_end) goto <access okay>
12953 	 *   <handle exception>
12954 	 *
12955 	 *   Where:
12956 	 *     r2 == dst_reg, pkt_end == src_reg
12957 	 *     r2=pkt(id=n,off=8,r=0)
12958 	 *     r3=pkt(id=n,off=0,r=0)
12959 	 *
12960 	 * pkt_data in src register:
12961 	 *
12962 	 *   r2 = r3;
12963 	 *   r2 += 8;
12964 	 *   if (pkt_end >= r2) goto <access okay>
12965 	 *   <handle exception>
12966 	 *
12967 	 *   r2 = r3;
12968 	 *   r2 += 8;
12969 	 *   if (pkt_end <= r2) goto <handle exception>
12970 	 *   <access okay>
12971 	 *
12972 	 *   Where:
12973 	 *     pkt_end == dst_reg, r2 == src_reg
12974 	 *     r2=pkt(id=n,off=8,r=0)
12975 	 *     r3=pkt(id=n,off=0,r=0)
12976 	 *
12977 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12978 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12979 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
12980 	 * the check.
12981 	 */
12982 
12983 	/* If our ids match, then we must have the same max_value.  And we
12984 	 * don't care about the other reg's fixed offset, since if it's too big
12985 	 * the range won't allow anything.
12986 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12987 	 */
12988 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12989 		if (reg->type == type && reg->id == dst_reg->id)
12990 			/* keep the maximum range already checked */
12991 			reg->range = max(reg->range, new_range);
12992 	}));
12993 }
12994 
12995 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12996 {
12997 	struct tnum subreg = tnum_subreg(reg->var_off);
12998 	s32 sval = (s32)val;
12999 
13000 	switch (opcode) {
13001 	case BPF_JEQ:
13002 		if (tnum_is_const(subreg))
13003 			return !!tnum_equals_const(subreg, val);
13004 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13005 			return 0;
13006 		break;
13007 	case BPF_JNE:
13008 		if (tnum_is_const(subreg))
13009 			return !tnum_equals_const(subreg, val);
13010 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13011 			return 1;
13012 		break;
13013 	case BPF_JSET:
13014 		if ((~subreg.mask & subreg.value) & val)
13015 			return 1;
13016 		if (!((subreg.mask | subreg.value) & val))
13017 			return 0;
13018 		break;
13019 	case BPF_JGT:
13020 		if (reg->u32_min_value > val)
13021 			return 1;
13022 		else if (reg->u32_max_value <= val)
13023 			return 0;
13024 		break;
13025 	case BPF_JSGT:
13026 		if (reg->s32_min_value > sval)
13027 			return 1;
13028 		else if (reg->s32_max_value <= sval)
13029 			return 0;
13030 		break;
13031 	case BPF_JLT:
13032 		if (reg->u32_max_value < val)
13033 			return 1;
13034 		else if (reg->u32_min_value >= val)
13035 			return 0;
13036 		break;
13037 	case BPF_JSLT:
13038 		if (reg->s32_max_value < sval)
13039 			return 1;
13040 		else if (reg->s32_min_value >= sval)
13041 			return 0;
13042 		break;
13043 	case BPF_JGE:
13044 		if (reg->u32_min_value >= val)
13045 			return 1;
13046 		else if (reg->u32_max_value < val)
13047 			return 0;
13048 		break;
13049 	case BPF_JSGE:
13050 		if (reg->s32_min_value >= sval)
13051 			return 1;
13052 		else if (reg->s32_max_value < sval)
13053 			return 0;
13054 		break;
13055 	case BPF_JLE:
13056 		if (reg->u32_max_value <= val)
13057 			return 1;
13058 		else if (reg->u32_min_value > val)
13059 			return 0;
13060 		break;
13061 	case BPF_JSLE:
13062 		if (reg->s32_max_value <= sval)
13063 			return 1;
13064 		else if (reg->s32_min_value > sval)
13065 			return 0;
13066 		break;
13067 	}
13068 
13069 	return -1;
13070 }
13071 
13072 
13073 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13074 {
13075 	s64 sval = (s64)val;
13076 
13077 	switch (opcode) {
13078 	case BPF_JEQ:
13079 		if (tnum_is_const(reg->var_off))
13080 			return !!tnum_equals_const(reg->var_off, val);
13081 		else if (val < reg->umin_value || val > reg->umax_value)
13082 			return 0;
13083 		break;
13084 	case BPF_JNE:
13085 		if (tnum_is_const(reg->var_off))
13086 			return !tnum_equals_const(reg->var_off, val);
13087 		else if (val < reg->umin_value || val > reg->umax_value)
13088 			return 1;
13089 		break;
13090 	case BPF_JSET:
13091 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13092 			return 1;
13093 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13094 			return 0;
13095 		break;
13096 	case BPF_JGT:
13097 		if (reg->umin_value > val)
13098 			return 1;
13099 		else if (reg->umax_value <= val)
13100 			return 0;
13101 		break;
13102 	case BPF_JSGT:
13103 		if (reg->smin_value > sval)
13104 			return 1;
13105 		else if (reg->smax_value <= sval)
13106 			return 0;
13107 		break;
13108 	case BPF_JLT:
13109 		if (reg->umax_value < val)
13110 			return 1;
13111 		else if (reg->umin_value >= val)
13112 			return 0;
13113 		break;
13114 	case BPF_JSLT:
13115 		if (reg->smax_value < sval)
13116 			return 1;
13117 		else if (reg->smin_value >= sval)
13118 			return 0;
13119 		break;
13120 	case BPF_JGE:
13121 		if (reg->umin_value >= val)
13122 			return 1;
13123 		else if (reg->umax_value < val)
13124 			return 0;
13125 		break;
13126 	case BPF_JSGE:
13127 		if (reg->smin_value >= sval)
13128 			return 1;
13129 		else if (reg->smax_value < sval)
13130 			return 0;
13131 		break;
13132 	case BPF_JLE:
13133 		if (reg->umax_value <= val)
13134 			return 1;
13135 		else if (reg->umin_value > val)
13136 			return 0;
13137 		break;
13138 	case BPF_JSLE:
13139 		if (reg->smax_value <= sval)
13140 			return 1;
13141 		else if (reg->smin_value > sval)
13142 			return 0;
13143 		break;
13144 	}
13145 
13146 	return -1;
13147 }
13148 
13149 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13150  * and return:
13151  *  1 - branch will be taken and "goto target" will be executed
13152  *  0 - branch will not be taken and fall-through to next insn
13153  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13154  *      range [0,10]
13155  */
13156 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13157 			   bool is_jmp32)
13158 {
13159 	if (__is_pointer_value(false, reg)) {
13160 		if (!reg_type_not_null(reg->type))
13161 			return -1;
13162 
13163 		/* If pointer is valid tests against zero will fail so we can
13164 		 * use this to direct branch taken.
13165 		 */
13166 		if (val != 0)
13167 			return -1;
13168 
13169 		switch (opcode) {
13170 		case BPF_JEQ:
13171 			return 0;
13172 		case BPF_JNE:
13173 			return 1;
13174 		default:
13175 			return -1;
13176 		}
13177 	}
13178 
13179 	if (is_jmp32)
13180 		return is_branch32_taken(reg, val, opcode);
13181 	return is_branch64_taken(reg, val, opcode);
13182 }
13183 
13184 static int flip_opcode(u32 opcode)
13185 {
13186 	/* How can we transform "a <op> b" into "b <op> a"? */
13187 	static const u8 opcode_flip[16] = {
13188 		/* these stay the same */
13189 		[BPF_JEQ  >> 4] = BPF_JEQ,
13190 		[BPF_JNE  >> 4] = BPF_JNE,
13191 		[BPF_JSET >> 4] = BPF_JSET,
13192 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13193 		[BPF_JGE  >> 4] = BPF_JLE,
13194 		[BPF_JGT  >> 4] = BPF_JLT,
13195 		[BPF_JLE  >> 4] = BPF_JGE,
13196 		[BPF_JLT  >> 4] = BPF_JGT,
13197 		[BPF_JSGE >> 4] = BPF_JSLE,
13198 		[BPF_JSGT >> 4] = BPF_JSLT,
13199 		[BPF_JSLE >> 4] = BPF_JSGE,
13200 		[BPF_JSLT >> 4] = BPF_JSGT
13201 	};
13202 	return opcode_flip[opcode >> 4];
13203 }
13204 
13205 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13206 				   struct bpf_reg_state *src_reg,
13207 				   u8 opcode)
13208 {
13209 	struct bpf_reg_state *pkt;
13210 
13211 	if (src_reg->type == PTR_TO_PACKET_END) {
13212 		pkt = dst_reg;
13213 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13214 		pkt = src_reg;
13215 		opcode = flip_opcode(opcode);
13216 	} else {
13217 		return -1;
13218 	}
13219 
13220 	if (pkt->range >= 0)
13221 		return -1;
13222 
13223 	switch (opcode) {
13224 	case BPF_JLE:
13225 		/* pkt <= pkt_end */
13226 		fallthrough;
13227 	case BPF_JGT:
13228 		/* pkt > pkt_end */
13229 		if (pkt->range == BEYOND_PKT_END)
13230 			/* pkt has at last one extra byte beyond pkt_end */
13231 			return opcode == BPF_JGT;
13232 		break;
13233 	case BPF_JLT:
13234 		/* pkt < pkt_end */
13235 		fallthrough;
13236 	case BPF_JGE:
13237 		/* pkt >= pkt_end */
13238 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13239 			return opcode == BPF_JGE;
13240 		break;
13241 	}
13242 	return -1;
13243 }
13244 
13245 /* Adjusts the register min/max values in the case that the dst_reg is the
13246  * variable register that we are working on, and src_reg is a constant or we're
13247  * simply doing a BPF_K check.
13248  * In JEQ/JNE cases we also adjust the var_off values.
13249  */
13250 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13251 			    struct bpf_reg_state *false_reg,
13252 			    u64 val, u32 val32,
13253 			    u8 opcode, bool is_jmp32)
13254 {
13255 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13256 	struct tnum false_64off = false_reg->var_off;
13257 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13258 	struct tnum true_64off = true_reg->var_off;
13259 	s64 sval = (s64)val;
13260 	s32 sval32 = (s32)val32;
13261 
13262 	/* If the dst_reg is a pointer, we can't learn anything about its
13263 	 * variable offset from the compare (unless src_reg were a pointer into
13264 	 * the same object, but we don't bother with that.
13265 	 * Since false_reg and true_reg have the same type by construction, we
13266 	 * only need to check one of them for pointerness.
13267 	 */
13268 	if (__is_pointer_value(false, false_reg))
13269 		return;
13270 
13271 	switch (opcode) {
13272 	/* JEQ/JNE comparison doesn't change the register equivalence.
13273 	 *
13274 	 * r1 = r2;
13275 	 * if (r1 == 42) goto label;
13276 	 * ...
13277 	 * label: // here both r1 and r2 are known to be 42.
13278 	 *
13279 	 * Hence when marking register as known preserve it's ID.
13280 	 */
13281 	case BPF_JEQ:
13282 		if (is_jmp32) {
13283 			__mark_reg32_known(true_reg, val32);
13284 			true_32off = tnum_subreg(true_reg->var_off);
13285 		} else {
13286 			___mark_reg_known(true_reg, val);
13287 			true_64off = true_reg->var_off;
13288 		}
13289 		break;
13290 	case BPF_JNE:
13291 		if (is_jmp32) {
13292 			__mark_reg32_known(false_reg, val32);
13293 			false_32off = tnum_subreg(false_reg->var_off);
13294 		} else {
13295 			___mark_reg_known(false_reg, val);
13296 			false_64off = false_reg->var_off;
13297 		}
13298 		break;
13299 	case BPF_JSET:
13300 		if (is_jmp32) {
13301 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13302 			if (is_power_of_2(val32))
13303 				true_32off = tnum_or(true_32off,
13304 						     tnum_const(val32));
13305 		} else {
13306 			false_64off = tnum_and(false_64off, tnum_const(~val));
13307 			if (is_power_of_2(val))
13308 				true_64off = tnum_or(true_64off,
13309 						     tnum_const(val));
13310 		}
13311 		break;
13312 	case BPF_JGE:
13313 	case BPF_JGT:
13314 	{
13315 		if (is_jmp32) {
13316 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13317 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13318 
13319 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13320 						       false_umax);
13321 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13322 						      true_umin);
13323 		} else {
13324 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13325 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13326 
13327 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13328 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13329 		}
13330 		break;
13331 	}
13332 	case BPF_JSGE:
13333 	case BPF_JSGT:
13334 	{
13335 		if (is_jmp32) {
13336 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13337 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13338 
13339 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13340 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13341 		} else {
13342 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13343 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13344 
13345 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13346 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13347 		}
13348 		break;
13349 	}
13350 	case BPF_JLE:
13351 	case BPF_JLT:
13352 	{
13353 		if (is_jmp32) {
13354 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13355 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13356 
13357 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13358 						       false_umin);
13359 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13360 						      true_umax);
13361 		} else {
13362 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13363 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13364 
13365 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13366 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13367 		}
13368 		break;
13369 	}
13370 	case BPF_JSLE:
13371 	case BPF_JSLT:
13372 	{
13373 		if (is_jmp32) {
13374 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13375 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13376 
13377 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13378 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13379 		} else {
13380 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13381 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13382 
13383 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13384 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13385 		}
13386 		break;
13387 	}
13388 	default:
13389 		return;
13390 	}
13391 
13392 	if (is_jmp32) {
13393 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13394 					     tnum_subreg(false_32off));
13395 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13396 					    tnum_subreg(true_32off));
13397 		__reg_combine_32_into_64(false_reg);
13398 		__reg_combine_32_into_64(true_reg);
13399 	} else {
13400 		false_reg->var_off = false_64off;
13401 		true_reg->var_off = true_64off;
13402 		__reg_combine_64_into_32(false_reg);
13403 		__reg_combine_64_into_32(true_reg);
13404 	}
13405 }
13406 
13407 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13408  * the variable reg.
13409  */
13410 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13411 				struct bpf_reg_state *false_reg,
13412 				u64 val, u32 val32,
13413 				u8 opcode, bool is_jmp32)
13414 {
13415 	opcode = flip_opcode(opcode);
13416 	/* This uses zero as "not present in table"; luckily the zero opcode,
13417 	 * BPF_JA, can't get here.
13418 	 */
13419 	if (opcode)
13420 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13421 }
13422 
13423 /* Regs are known to be equal, so intersect their min/max/var_off */
13424 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13425 				  struct bpf_reg_state *dst_reg)
13426 {
13427 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13428 							dst_reg->umin_value);
13429 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13430 							dst_reg->umax_value);
13431 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13432 							dst_reg->smin_value);
13433 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13434 							dst_reg->smax_value);
13435 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13436 							     dst_reg->var_off);
13437 	reg_bounds_sync(src_reg);
13438 	reg_bounds_sync(dst_reg);
13439 }
13440 
13441 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13442 				struct bpf_reg_state *true_dst,
13443 				struct bpf_reg_state *false_src,
13444 				struct bpf_reg_state *false_dst,
13445 				u8 opcode)
13446 {
13447 	switch (opcode) {
13448 	case BPF_JEQ:
13449 		__reg_combine_min_max(true_src, true_dst);
13450 		break;
13451 	case BPF_JNE:
13452 		__reg_combine_min_max(false_src, false_dst);
13453 		break;
13454 	}
13455 }
13456 
13457 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13458 				 struct bpf_reg_state *reg, u32 id,
13459 				 bool is_null)
13460 {
13461 	if (type_may_be_null(reg->type) && reg->id == id &&
13462 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13463 		/* Old offset (both fixed and variable parts) should have been
13464 		 * known-zero, because we don't allow pointer arithmetic on
13465 		 * pointers that might be NULL. If we see this happening, don't
13466 		 * convert the register.
13467 		 *
13468 		 * But in some cases, some helpers that return local kptrs
13469 		 * advance offset for the returned pointer. In those cases, it
13470 		 * is fine to expect to see reg->off.
13471 		 */
13472 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13473 			return;
13474 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13475 		    WARN_ON_ONCE(reg->off))
13476 			return;
13477 
13478 		if (is_null) {
13479 			reg->type = SCALAR_VALUE;
13480 			/* We don't need id and ref_obj_id from this point
13481 			 * onwards anymore, thus we should better reset it,
13482 			 * so that state pruning has chances to take effect.
13483 			 */
13484 			reg->id = 0;
13485 			reg->ref_obj_id = 0;
13486 
13487 			return;
13488 		}
13489 
13490 		mark_ptr_not_null_reg(reg);
13491 
13492 		if (!reg_may_point_to_spin_lock(reg)) {
13493 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13494 			 * in release_reference().
13495 			 *
13496 			 * reg->id is still used by spin_lock ptr. Other
13497 			 * than spin_lock ptr type, reg->id can be reset.
13498 			 */
13499 			reg->id = 0;
13500 		}
13501 	}
13502 }
13503 
13504 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13505  * be folded together at some point.
13506  */
13507 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13508 				  bool is_null)
13509 {
13510 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13511 	struct bpf_reg_state *regs = state->regs, *reg;
13512 	u32 ref_obj_id = regs[regno].ref_obj_id;
13513 	u32 id = regs[regno].id;
13514 
13515 	if (ref_obj_id && ref_obj_id == id && is_null)
13516 		/* regs[regno] is in the " == NULL" branch.
13517 		 * No one could have freed the reference state before
13518 		 * doing the NULL check.
13519 		 */
13520 		WARN_ON_ONCE(release_reference_state(state, id));
13521 
13522 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13523 		mark_ptr_or_null_reg(state, reg, id, is_null);
13524 	}));
13525 }
13526 
13527 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13528 				   struct bpf_reg_state *dst_reg,
13529 				   struct bpf_reg_state *src_reg,
13530 				   struct bpf_verifier_state *this_branch,
13531 				   struct bpf_verifier_state *other_branch)
13532 {
13533 	if (BPF_SRC(insn->code) != BPF_X)
13534 		return false;
13535 
13536 	/* Pointers are always 64-bit. */
13537 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13538 		return false;
13539 
13540 	switch (BPF_OP(insn->code)) {
13541 	case BPF_JGT:
13542 		if ((dst_reg->type == PTR_TO_PACKET &&
13543 		     src_reg->type == PTR_TO_PACKET_END) ||
13544 		    (dst_reg->type == PTR_TO_PACKET_META &&
13545 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13546 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13547 			find_good_pkt_pointers(this_branch, dst_reg,
13548 					       dst_reg->type, false);
13549 			mark_pkt_end(other_branch, insn->dst_reg, true);
13550 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13551 			    src_reg->type == PTR_TO_PACKET) ||
13552 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13553 			    src_reg->type == PTR_TO_PACKET_META)) {
13554 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13555 			find_good_pkt_pointers(other_branch, src_reg,
13556 					       src_reg->type, true);
13557 			mark_pkt_end(this_branch, insn->src_reg, false);
13558 		} else {
13559 			return false;
13560 		}
13561 		break;
13562 	case BPF_JLT:
13563 		if ((dst_reg->type == PTR_TO_PACKET &&
13564 		     src_reg->type == PTR_TO_PACKET_END) ||
13565 		    (dst_reg->type == PTR_TO_PACKET_META &&
13566 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13567 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13568 			find_good_pkt_pointers(other_branch, dst_reg,
13569 					       dst_reg->type, true);
13570 			mark_pkt_end(this_branch, insn->dst_reg, false);
13571 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13572 			    src_reg->type == PTR_TO_PACKET) ||
13573 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13574 			    src_reg->type == PTR_TO_PACKET_META)) {
13575 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13576 			find_good_pkt_pointers(this_branch, src_reg,
13577 					       src_reg->type, false);
13578 			mark_pkt_end(other_branch, insn->src_reg, true);
13579 		} else {
13580 			return false;
13581 		}
13582 		break;
13583 	case BPF_JGE:
13584 		if ((dst_reg->type == PTR_TO_PACKET &&
13585 		     src_reg->type == PTR_TO_PACKET_END) ||
13586 		    (dst_reg->type == PTR_TO_PACKET_META &&
13587 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13588 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13589 			find_good_pkt_pointers(this_branch, dst_reg,
13590 					       dst_reg->type, true);
13591 			mark_pkt_end(other_branch, insn->dst_reg, false);
13592 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13593 			    src_reg->type == PTR_TO_PACKET) ||
13594 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13595 			    src_reg->type == PTR_TO_PACKET_META)) {
13596 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13597 			find_good_pkt_pointers(other_branch, src_reg,
13598 					       src_reg->type, false);
13599 			mark_pkt_end(this_branch, insn->src_reg, true);
13600 		} else {
13601 			return false;
13602 		}
13603 		break;
13604 	case BPF_JLE:
13605 		if ((dst_reg->type == PTR_TO_PACKET &&
13606 		     src_reg->type == PTR_TO_PACKET_END) ||
13607 		    (dst_reg->type == PTR_TO_PACKET_META &&
13608 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13609 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13610 			find_good_pkt_pointers(other_branch, dst_reg,
13611 					       dst_reg->type, false);
13612 			mark_pkt_end(this_branch, insn->dst_reg, true);
13613 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13614 			    src_reg->type == PTR_TO_PACKET) ||
13615 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13616 			    src_reg->type == PTR_TO_PACKET_META)) {
13617 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13618 			find_good_pkt_pointers(this_branch, src_reg,
13619 					       src_reg->type, true);
13620 			mark_pkt_end(other_branch, insn->src_reg, false);
13621 		} else {
13622 			return false;
13623 		}
13624 		break;
13625 	default:
13626 		return false;
13627 	}
13628 
13629 	return true;
13630 }
13631 
13632 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13633 			       struct bpf_reg_state *known_reg)
13634 {
13635 	struct bpf_func_state *state;
13636 	struct bpf_reg_state *reg;
13637 
13638 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13639 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13640 			copy_register_state(reg, known_reg);
13641 	}));
13642 }
13643 
13644 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13645 			     struct bpf_insn *insn, int *insn_idx)
13646 {
13647 	struct bpf_verifier_state *this_branch = env->cur_state;
13648 	struct bpf_verifier_state *other_branch;
13649 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13650 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13651 	struct bpf_reg_state *eq_branch_regs;
13652 	u8 opcode = BPF_OP(insn->code);
13653 	bool is_jmp32;
13654 	int pred = -1;
13655 	int err;
13656 
13657 	/* Only conditional jumps are expected to reach here. */
13658 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
13659 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13660 		return -EINVAL;
13661 	}
13662 
13663 	if (BPF_SRC(insn->code) == BPF_X) {
13664 		if (insn->imm != 0) {
13665 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13666 			return -EINVAL;
13667 		}
13668 
13669 		/* check src1 operand */
13670 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13671 		if (err)
13672 			return err;
13673 
13674 		if (is_pointer_value(env, insn->src_reg)) {
13675 			verbose(env, "R%d pointer comparison prohibited\n",
13676 				insn->src_reg);
13677 			return -EACCES;
13678 		}
13679 		src_reg = &regs[insn->src_reg];
13680 	} else {
13681 		if (insn->src_reg != BPF_REG_0) {
13682 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13683 			return -EINVAL;
13684 		}
13685 	}
13686 
13687 	/* check src2 operand */
13688 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13689 	if (err)
13690 		return err;
13691 
13692 	dst_reg = &regs[insn->dst_reg];
13693 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13694 
13695 	if (BPF_SRC(insn->code) == BPF_K) {
13696 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13697 	} else if (src_reg->type == SCALAR_VALUE &&
13698 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13699 		pred = is_branch_taken(dst_reg,
13700 				       tnum_subreg(src_reg->var_off).value,
13701 				       opcode,
13702 				       is_jmp32);
13703 	} else if (src_reg->type == SCALAR_VALUE &&
13704 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13705 		pred = is_branch_taken(dst_reg,
13706 				       src_reg->var_off.value,
13707 				       opcode,
13708 				       is_jmp32);
13709 	} else if (dst_reg->type == SCALAR_VALUE &&
13710 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13711 		pred = is_branch_taken(src_reg,
13712 				       tnum_subreg(dst_reg->var_off).value,
13713 				       flip_opcode(opcode),
13714 				       is_jmp32);
13715 	} else if (dst_reg->type == SCALAR_VALUE &&
13716 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13717 		pred = is_branch_taken(src_reg,
13718 				       dst_reg->var_off.value,
13719 				       flip_opcode(opcode),
13720 				       is_jmp32);
13721 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
13722 		   reg_is_pkt_pointer_any(src_reg) &&
13723 		   !is_jmp32) {
13724 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13725 	}
13726 
13727 	if (pred >= 0) {
13728 		/* If we get here with a dst_reg pointer type it is because
13729 		 * above is_branch_taken() special cased the 0 comparison.
13730 		 */
13731 		if (!__is_pointer_value(false, dst_reg))
13732 			err = mark_chain_precision(env, insn->dst_reg);
13733 		if (BPF_SRC(insn->code) == BPF_X && !err &&
13734 		    !__is_pointer_value(false, src_reg))
13735 			err = mark_chain_precision(env, insn->src_reg);
13736 		if (err)
13737 			return err;
13738 	}
13739 
13740 	if (pred == 1) {
13741 		/* Only follow the goto, ignore fall-through. If needed, push
13742 		 * the fall-through branch for simulation under speculative
13743 		 * execution.
13744 		 */
13745 		if (!env->bypass_spec_v1 &&
13746 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
13747 					       *insn_idx))
13748 			return -EFAULT;
13749 		*insn_idx += insn->off;
13750 		return 0;
13751 	} else if (pred == 0) {
13752 		/* Only follow the fall-through branch, since that's where the
13753 		 * program will go. If needed, push the goto branch for
13754 		 * simulation under speculative execution.
13755 		 */
13756 		if (!env->bypass_spec_v1 &&
13757 		    !sanitize_speculative_path(env, insn,
13758 					       *insn_idx + insn->off + 1,
13759 					       *insn_idx))
13760 			return -EFAULT;
13761 		return 0;
13762 	}
13763 
13764 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13765 				  false);
13766 	if (!other_branch)
13767 		return -EFAULT;
13768 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13769 
13770 	/* detect if we are comparing against a constant value so we can adjust
13771 	 * our min/max values for our dst register.
13772 	 * this is only legit if both are scalars (or pointers to the same
13773 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13774 	 * because otherwise the different base pointers mean the offsets aren't
13775 	 * comparable.
13776 	 */
13777 	if (BPF_SRC(insn->code) == BPF_X) {
13778 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13779 
13780 		if (dst_reg->type == SCALAR_VALUE &&
13781 		    src_reg->type == SCALAR_VALUE) {
13782 			if (tnum_is_const(src_reg->var_off) ||
13783 			    (is_jmp32 &&
13784 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
13785 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
13786 						dst_reg,
13787 						src_reg->var_off.value,
13788 						tnum_subreg(src_reg->var_off).value,
13789 						opcode, is_jmp32);
13790 			else if (tnum_is_const(dst_reg->var_off) ||
13791 				 (is_jmp32 &&
13792 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
13793 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13794 						    src_reg,
13795 						    dst_reg->var_off.value,
13796 						    tnum_subreg(dst_reg->var_off).value,
13797 						    opcode, is_jmp32);
13798 			else if (!is_jmp32 &&
13799 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
13800 				/* Comparing for equality, we can combine knowledge */
13801 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
13802 						    &other_branch_regs[insn->dst_reg],
13803 						    src_reg, dst_reg, opcode);
13804 			if (src_reg->id &&
13805 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13806 				find_equal_scalars(this_branch, src_reg);
13807 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13808 			}
13809 
13810 		}
13811 	} else if (dst_reg->type == SCALAR_VALUE) {
13812 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
13813 					dst_reg, insn->imm, (u32)insn->imm,
13814 					opcode, is_jmp32);
13815 	}
13816 
13817 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13818 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13819 		find_equal_scalars(this_branch, dst_reg);
13820 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13821 	}
13822 
13823 	/* if one pointer register is compared to another pointer
13824 	 * register check if PTR_MAYBE_NULL could be lifted.
13825 	 * E.g. register A - maybe null
13826 	 *      register B - not null
13827 	 * for JNE A, B, ... - A is not null in the false branch;
13828 	 * for JEQ A, B, ... - A is not null in the true branch.
13829 	 *
13830 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
13831 	 * not need to be null checked by the BPF program, i.e.,
13832 	 * could be null even without PTR_MAYBE_NULL marking, so
13833 	 * only propagate nullness when neither reg is that type.
13834 	 */
13835 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13836 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13837 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13838 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
13839 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13840 		eq_branch_regs = NULL;
13841 		switch (opcode) {
13842 		case BPF_JEQ:
13843 			eq_branch_regs = other_branch_regs;
13844 			break;
13845 		case BPF_JNE:
13846 			eq_branch_regs = regs;
13847 			break;
13848 		default:
13849 			/* do nothing */
13850 			break;
13851 		}
13852 		if (eq_branch_regs) {
13853 			if (type_may_be_null(src_reg->type))
13854 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13855 			else
13856 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13857 		}
13858 	}
13859 
13860 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13861 	 * NOTE: these optimizations below are related with pointer comparison
13862 	 *       which will never be JMP32.
13863 	 */
13864 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13865 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13866 	    type_may_be_null(dst_reg->type)) {
13867 		/* Mark all identical registers in each branch as either
13868 		 * safe or unknown depending R == 0 or R != 0 conditional.
13869 		 */
13870 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13871 				      opcode == BPF_JNE);
13872 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13873 				      opcode == BPF_JEQ);
13874 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
13875 					   this_branch, other_branch) &&
13876 		   is_pointer_value(env, insn->dst_reg)) {
13877 		verbose(env, "R%d pointer comparison prohibited\n",
13878 			insn->dst_reg);
13879 		return -EACCES;
13880 	}
13881 	if (env->log.level & BPF_LOG_LEVEL)
13882 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
13883 	return 0;
13884 }
13885 
13886 /* verify BPF_LD_IMM64 instruction */
13887 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
13888 {
13889 	struct bpf_insn_aux_data *aux = cur_aux(env);
13890 	struct bpf_reg_state *regs = cur_regs(env);
13891 	struct bpf_reg_state *dst_reg;
13892 	struct bpf_map *map;
13893 	int err;
13894 
13895 	if (BPF_SIZE(insn->code) != BPF_DW) {
13896 		verbose(env, "invalid BPF_LD_IMM insn\n");
13897 		return -EINVAL;
13898 	}
13899 	if (insn->off != 0) {
13900 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
13901 		return -EINVAL;
13902 	}
13903 
13904 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
13905 	if (err)
13906 		return err;
13907 
13908 	dst_reg = &regs[insn->dst_reg];
13909 	if (insn->src_reg == 0) {
13910 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13911 
13912 		dst_reg->type = SCALAR_VALUE;
13913 		__mark_reg_known(&regs[insn->dst_reg], imm);
13914 		return 0;
13915 	}
13916 
13917 	/* All special src_reg cases are listed below. From this point onwards
13918 	 * we either succeed and assign a corresponding dst_reg->type after
13919 	 * zeroing the offset, or fail and reject the program.
13920 	 */
13921 	mark_reg_known_zero(env, regs, insn->dst_reg);
13922 
13923 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13924 		dst_reg->type = aux->btf_var.reg_type;
13925 		switch (base_type(dst_reg->type)) {
13926 		case PTR_TO_MEM:
13927 			dst_reg->mem_size = aux->btf_var.mem_size;
13928 			break;
13929 		case PTR_TO_BTF_ID:
13930 			dst_reg->btf = aux->btf_var.btf;
13931 			dst_reg->btf_id = aux->btf_var.btf_id;
13932 			break;
13933 		default:
13934 			verbose(env, "bpf verifier is misconfigured\n");
13935 			return -EFAULT;
13936 		}
13937 		return 0;
13938 	}
13939 
13940 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
13941 		struct bpf_prog_aux *aux = env->prog->aux;
13942 		u32 subprogno = find_subprog(env,
13943 					     env->insn_idx + insn->imm + 1);
13944 
13945 		if (!aux->func_info) {
13946 			verbose(env, "missing btf func_info\n");
13947 			return -EINVAL;
13948 		}
13949 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13950 			verbose(env, "callback function not static\n");
13951 			return -EINVAL;
13952 		}
13953 
13954 		dst_reg->type = PTR_TO_FUNC;
13955 		dst_reg->subprogno = subprogno;
13956 		return 0;
13957 	}
13958 
13959 	map = env->used_maps[aux->map_index];
13960 	dst_reg->map_ptr = map;
13961 
13962 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13963 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13964 		dst_reg->type = PTR_TO_MAP_VALUE;
13965 		dst_reg->off = aux->map_off;
13966 		WARN_ON_ONCE(map->max_entries != 1);
13967 		/* We want reg->id to be same (0) as map_value is not distinct */
13968 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13969 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13970 		dst_reg->type = CONST_PTR_TO_MAP;
13971 	} else {
13972 		verbose(env, "bpf verifier is misconfigured\n");
13973 		return -EINVAL;
13974 	}
13975 
13976 	return 0;
13977 }
13978 
13979 static bool may_access_skb(enum bpf_prog_type type)
13980 {
13981 	switch (type) {
13982 	case BPF_PROG_TYPE_SOCKET_FILTER:
13983 	case BPF_PROG_TYPE_SCHED_CLS:
13984 	case BPF_PROG_TYPE_SCHED_ACT:
13985 		return true;
13986 	default:
13987 		return false;
13988 	}
13989 }
13990 
13991 /* verify safety of LD_ABS|LD_IND instructions:
13992  * - they can only appear in the programs where ctx == skb
13993  * - since they are wrappers of function calls, they scratch R1-R5 registers,
13994  *   preserve R6-R9, and store return value into R0
13995  *
13996  * Implicit input:
13997  *   ctx == skb == R6 == CTX
13998  *
13999  * Explicit input:
14000  *   SRC == any register
14001  *   IMM == 32-bit immediate
14002  *
14003  * Output:
14004  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14005  */
14006 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14007 {
14008 	struct bpf_reg_state *regs = cur_regs(env);
14009 	static const int ctx_reg = BPF_REG_6;
14010 	u8 mode = BPF_MODE(insn->code);
14011 	int i, err;
14012 
14013 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14014 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14015 		return -EINVAL;
14016 	}
14017 
14018 	if (!env->ops->gen_ld_abs) {
14019 		verbose(env, "bpf verifier is misconfigured\n");
14020 		return -EINVAL;
14021 	}
14022 
14023 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14024 	    BPF_SIZE(insn->code) == BPF_DW ||
14025 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14026 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14027 		return -EINVAL;
14028 	}
14029 
14030 	/* check whether implicit source operand (register R6) is readable */
14031 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14032 	if (err)
14033 		return err;
14034 
14035 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14036 	 * gen_ld_abs() may terminate the program at runtime, leading to
14037 	 * reference leak.
14038 	 */
14039 	err = check_reference_leak(env);
14040 	if (err) {
14041 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14042 		return err;
14043 	}
14044 
14045 	if (env->cur_state->active_lock.ptr) {
14046 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14047 		return -EINVAL;
14048 	}
14049 
14050 	if (env->cur_state->active_rcu_lock) {
14051 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14052 		return -EINVAL;
14053 	}
14054 
14055 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14056 		verbose(env,
14057 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14058 		return -EINVAL;
14059 	}
14060 
14061 	if (mode == BPF_IND) {
14062 		/* check explicit source operand */
14063 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14064 		if (err)
14065 			return err;
14066 	}
14067 
14068 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14069 	if (err < 0)
14070 		return err;
14071 
14072 	/* reset caller saved regs to unreadable */
14073 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14074 		mark_reg_not_init(env, regs, caller_saved[i]);
14075 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14076 	}
14077 
14078 	/* mark destination R0 register as readable, since it contains
14079 	 * the value fetched from the packet.
14080 	 * Already marked as written above.
14081 	 */
14082 	mark_reg_unknown(env, regs, BPF_REG_0);
14083 	/* ld_abs load up to 32-bit skb data. */
14084 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14085 	return 0;
14086 }
14087 
14088 static int check_return_code(struct bpf_verifier_env *env)
14089 {
14090 	struct tnum enforce_attach_type_range = tnum_unknown;
14091 	const struct bpf_prog *prog = env->prog;
14092 	struct bpf_reg_state *reg;
14093 	struct tnum range = tnum_range(0, 1);
14094 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14095 	int err;
14096 	struct bpf_func_state *frame = env->cur_state->frame[0];
14097 	const bool is_subprog = frame->subprogno;
14098 
14099 	/* LSM and struct_ops func-ptr's return type could be "void" */
14100 	if (!is_subprog) {
14101 		switch (prog_type) {
14102 		case BPF_PROG_TYPE_LSM:
14103 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14104 				/* See below, can be 0 or 0-1 depending on hook. */
14105 				break;
14106 			fallthrough;
14107 		case BPF_PROG_TYPE_STRUCT_OPS:
14108 			if (!prog->aux->attach_func_proto->type)
14109 				return 0;
14110 			break;
14111 		default:
14112 			break;
14113 		}
14114 	}
14115 
14116 	/* eBPF calling convention is such that R0 is used
14117 	 * to return the value from eBPF program.
14118 	 * Make sure that it's readable at this time
14119 	 * of bpf_exit, which means that program wrote
14120 	 * something into it earlier
14121 	 */
14122 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14123 	if (err)
14124 		return err;
14125 
14126 	if (is_pointer_value(env, BPF_REG_0)) {
14127 		verbose(env, "R0 leaks addr as return value\n");
14128 		return -EACCES;
14129 	}
14130 
14131 	reg = cur_regs(env) + BPF_REG_0;
14132 
14133 	if (frame->in_async_callback_fn) {
14134 		/* enforce return zero from async callbacks like timer */
14135 		if (reg->type != SCALAR_VALUE) {
14136 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14137 				reg_type_str(env, reg->type));
14138 			return -EINVAL;
14139 		}
14140 
14141 		if (!tnum_in(tnum_const(0), reg->var_off)) {
14142 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14143 			return -EINVAL;
14144 		}
14145 		return 0;
14146 	}
14147 
14148 	if (is_subprog) {
14149 		if (reg->type != SCALAR_VALUE) {
14150 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14151 				reg_type_str(env, reg->type));
14152 			return -EINVAL;
14153 		}
14154 		return 0;
14155 	}
14156 
14157 	switch (prog_type) {
14158 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14159 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14160 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14161 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14162 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14163 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14164 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14165 			range = tnum_range(1, 1);
14166 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14167 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14168 			range = tnum_range(0, 3);
14169 		break;
14170 	case BPF_PROG_TYPE_CGROUP_SKB:
14171 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14172 			range = tnum_range(0, 3);
14173 			enforce_attach_type_range = tnum_range(2, 3);
14174 		}
14175 		break;
14176 	case BPF_PROG_TYPE_CGROUP_SOCK:
14177 	case BPF_PROG_TYPE_SOCK_OPS:
14178 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14179 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14180 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14181 		break;
14182 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14183 		if (!env->prog->aux->attach_btf_id)
14184 			return 0;
14185 		range = tnum_const(0);
14186 		break;
14187 	case BPF_PROG_TYPE_TRACING:
14188 		switch (env->prog->expected_attach_type) {
14189 		case BPF_TRACE_FENTRY:
14190 		case BPF_TRACE_FEXIT:
14191 			range = tnum_const(0);
14192 			break;
14193 		case BPF_TRACE_RAW_TP:
14194 		case BPF_MODIFY_RETURN:
14195 			return 0;
14196 		case BPF_TRACE_ITER:
14197 			break;
14198 		default:
14199 			return -ENOTSUPP;
14200 		}
14201 		break;
14202 	case BPF_PROG_TYPE_SK_LOOKUP:
14203 		range = tnum_range(SK_DROP, SK_PASS);
14204 		break;
14205 
14206 	case BPF_PROG_TYPE_LSM:
14207 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14208 			/* Regular BPF_PROG_TYPE_LSM programs can return
14209 			 * any value.
14210 			 */
14211 			return 0;
14212 		}
14213 		if (!env->prog->aux->attach_func_proto->type) {
14214 			/* Make sure programs that attach to void
14215 			 * hooks don't try to modify return value.
14216 			 */
14217 			range = tnum_range(1, 1);
14218 		}
14219 		break;
14220 
14221 	case BPF_PROG_TYPE_NETFILTER:
14222 		range = tnum_range(NF_DROP, NF_ACCEPT);
14223 		break;
14224 	case BPF_PROG_TYPE_EXT:
14225 		/* freplace program can return anything as its return value
14226 		 * depends on the to-be-replaced kernel func or bpf program.
14227 		 */
14228 	default:
14229 		return 0;
14230 	}
14231 
14232 	if (reg->type != SCALAR_VALUE) {
14233 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14234 			reg_type_str(env, reg->type));
14235 		return -EINVAL;
14236 	}
14237 
14238 	if (!tnum_in(range, reg->var_off)) {
14239 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14240 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14241 		    prog_type == BPF_PROG_TYPE_LSM &&
14242 		    !prog->aux->attach_func_proto->type)
14243 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14244 		return -EINVAL;
14245 	}
14246 
14247 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14248 	    tnum_in(enforce_attach_type_range, reg->var_off))
14249 		env->prog->enforce_expected_attach_type = 1;
14250 	return 0;
14251 }
14252 
14253 /* non-recursive DFS pseudo code
14254  * 1  procedure DFS-iterative(G,v):
14255  * 2      label v as discovered
14256  * 3      let S be a stack
14257  * 4      S.push(v)
14258  * 5      while S is not empty
14259  * 6            t <- S.peek()
14260  * 7            if t is what we're looking for:
14261  * 8                return t
14262  * 9            for all edges e in G.adjacentEdges(t) do
14263  * 10               if edge e is already labelled
14264  * 11                   continue with the next edge
14265  * 12               w <- G.adjacentVertex(t,e)
14266  * 13               if vertex w is not discovered and not explored
14267  * 14                   label e as tree-edge
14268  * 15                   label w as discovered
14269  * 16                   S.push(w)
14270  * 17                   continue at 5
14271  * 18               else if vertex w is discovered
14272  * 19                   label e as back-edge
14273  * 20               else
14274  * 21                   // vertex w is explored
14275  * 22                   label e as forward- or cross-edge
14276  * 23           label t as explored
14277  * 24           S.pop()
14278  *
14279  * convention:
14280  * 0x10 - discovered
14281  * 0x11 - discovered and fall-through edge labelled
14282  * 0x12 - discovered and fall-through and branch edges labelled
14283  * 0x20 - explored
14284  */
14285 
14286 enum {
14287 	DISCOVERED = 0x10,
14288 	EXPLORED = 0x20,
14289 	FALLTHROUGH = 1,
14290 	BRANCH = 2,
14291 };
14292 
14293 static u32 state_htab_size(struct bpf_verifier_env *env)
14294 {
14295 	return env->prog->len;
14296 }
14297 
14298 static struct bpf_verifier_state_list **explored_state(
14299 					struct bpf_verifier_env *env,
14300 					int idx)
14301 {
14302 	struct bpf_verifier_state *cur = env->cur_state;
14303 	struct bpf_func_state *state = cur->frame[cur->curframe];
14304 
14305 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14306 }
14307 
14308 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14309 {
14310 	env->insn_aux_data[idx].prune_point = true;
14311 }
14312 
14313 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14314 {
14315 	return env->insn_aux_data[insn_idx].prune_point;
14316 }
14317 
14318 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14319 {
14320 	env->insn_aux_data[idx].force_checkpoint = true;
14321 }
14322 
14323 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14324 {
14325 	return env->insn_aux_data[insn_idx].force_checkpoint;
14326 }
14327 
14328 
14329 enum {
14330 	DONE_EXPLORING = 0,
14331 	KEEP_EXPLORING = 1,
14332 };
14333 
14334 /* t, w, e - match pseudo-code above:
14335  * t - index of current instruction
14336  * w - next instruction
14337  * e - edge
14338  */
14339 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14340 		     bool loop_ok)
14341 {
14342 	int *insn_stack = env->cfg.insn_stack;
14343 	int *insn_state = env->cfg.insn_state;
14344 
14345 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14346 		return DONE_EXPLORING;
14347 
14348 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14349 		return DONE_EXPLORING;
14350 
14351 	if (w < 0 || w >= env->prog->len) {
14352 		verbose_linfo(env, t, "%d: ", t);
14353 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14354 		return -EINVAL;
14355 	}
14356 
14357 	if (e == BRANCH) {
14358 		/* mark branch target for state pruning */
14359 		mark_prune_point(env, w);
14360 		mark_jmp_point(env, w);
14361 	}
14362 
14363 	if (insn_state[w] == 0) {
14364 		/* tree-edge */
14365 		insn_state[t] = DISCOVERED | e;
14366 		insn_state[w] = DISCOVERED;
14367 		if (env->cfg.cur_stack >= env->prog->len)
14368 			return -E2BIG;
14369 		insn_stack[env->cfg.cur_stack++] = w;
14370 		return KEEP_EXPLORING;
14371 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14372 		if (loop_ok && env->bpf_capable)
14373 			return DONE_EXPLORING;
14374 		verbose_linfo(env, t, "%d: ", t);
14375 		verbose_linfo(env, w, "%d: ", w);
14376 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14377 		return -EINVAL;
14378 	} else if (insn_state[w] == EXPLORED) {
14379 		/* forward- or cross-edge */
14380 		insn_state[t] = DISCOVERED | e;
14381 	} else {
14382 		verbose(env, "insn state internal bug\n");
14383 		return -EFAULT;
14384 	}
14385 	return DONE_EXPLORING;
14386 }
14387 
14388 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14389 				struct bpf_verifier_env *env,
14390 				bool visit_callee)
14391 {
14392 	int ret;
14393 
14394 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14395 	if (ret)
14396 		return ret;
14397 
14398 	mark_prune_point(env, t + 1);
14399 	/* when we exit from subprog, we need to record non-linear history */
14400 	mark_jmp_point(env, t + 1);
14401 
14402 	if (visit_callee) {
14403 		mark_prune_point(env, t);
14404 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14405 				/* It's ok to allow recursion from CFG point of
14406 				 * view. __check_func_call() will do the actual
14407 				 * check.
14408 				 */
14409 				bpf_pseudo_func(insns + t));
14410 	}
14411 	return ret;
14412 }
14413 
14414 /* Visits the instruction at index t and returns one of the following:
14415  *  < 0 - an error occurred
14416  *  DONE_EXPLORING - the instruction was fully explored
14417  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14418  */
14419 static int visit_insn(int t, struct bpf_verifier_env *env)
14420 {
14421 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14422 	int ret;
14423 
14424 	if (bpf_pseudo_func(insn))
14425 		return visit_func_call_insn(t, insns, env, true);
14426 
14427 	/* All non-branch instructions have a single fall-through edge. */
14428 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14429 	    BPF_CLASS(insn->code) != BPF_JMP32)
14430 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14431 
14432 	switch (BPF_OP(insn->code)) {
14433 	case BPF_EXIT:
14434 		return DONE_EXPLORING;
14435 
14436 	case BPF_CALL:
14437 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14438 			/* Mark this call insn as a prune point to trigger
14439 			 * is_state_visited() check before call itself is
14440 			 * processed by __check_func_call(). Otherwise new
14441 			 * async state will be pushed for further exploration.
14442 			 */
14443 			mark_prune_point(env, t);
14444 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14445 			struct bpf_kfunc_call_arg_meta meta;
14446 
14447 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14448 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14449 				mark_prune_point(env, t);
14450 				/* Checking and saving state checkpoints at iter_next() call
14451 				 * is crucial for fast convergence of open-coded iterator loop
14452 				 * logic, so we need to force it. If we don't do that,
14453 				 * is_state_visited() might skip saving a checkpoint, causing
14454 				 * unnecessarily long sequence of not checkpointed
14455 				 * instructions and jumps, leading to exhaustion of jump
14456 				 * history buffer, and potentially other undesired outcomes.
14457 				 * It is expected that with correct open-coded iterators
14458 				 * convergence will happen quickly, so we don't run a risk of
14459 				 * exhausting memory.
14460 				 */
14461 				mark_force_checkpoint(env, t);
14462 			}
14463 		}
14464 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14465 
14466 	case BPF_JA:
14467 		if (BPF_SRC(insn->code) != BPF_K)
14468 			return -EINVAL;
14469 
14470 		/* unconditional jump with single edge */
14471 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14472 				true);
14473 		if (ret)
14474 			return ret;
14475 
14476 		mark_prune_point(env, t + insn->off + 1);
14477 		mark_jmp_point(env, t + insn->off + 1);
14478 
14479 		return ret;
14480 
14481 	default:
14482 		/* conditional jump with two edges */
14483 		mark_prune_point(env, t);
14484 
14485 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14486 		if (ret)
14487 			return ret;
14488 
14489 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14490 	}
14491 }
14492 
14493 /* non-recursive depth-first-search to detect loops in BPF program
14494  * loop == back-edge in directed graph
14495  */
14496 static int check_cfg(struct bpf_verifier_env *env)
14497 {
14498 	int insn_cnt = env->prog->len;
14499 	int *insn_stack, *insn_state;
14500 	int ret = 0;
14501 	int i;
14502 
14503 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14504 	if (!insn_state)
14505 		return -ENOMEM;
14506 
14507 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14508 	if (!insn_stack) {
14509 		kvfree(insn_state);
14510 		return -ENOMEM;
14511 	}
14512 
14513 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14514 	insn_stack[0] = 0; /* 0 is the first instruction */
14515 	env->cfg.cur_stack = 1;
14516 
14517 	while (env->cfg.cur_stack > 0) {
14518 		int t = insn_stack[env->cfg.cur_stack - 1];
14519 
14520 		ret = visit_insn(t, env);
14521 		switch (ret) {
14522 		case DONE_EXPLORING:
14523 			insn_state[t] = EXPLORED;
14524 			env->cfg.cur_stack--;
14525 			break;
14526 		case KEEP_EXPLORING:
14527 			break;
14528 		default:
14529 			if (ret > 0) {
14530 				verbose(env, "visit_insn internal bug\n");
14531 				ret = -EFAULT;
14532 			}
14533 			goto err_free;
14534 		}
14535 	}
14536 
14537 	if (env->cfg.cur_stack < 0) {
14538 		verbose(env, "pop stack internal bug\n");
14539 		ret = -EFAULT;
14540 		goto err_free;
14541 	}
14542 
14543 	for (i = 0; i < insn_cnt; i++) {
14544 		if (insn_state[i] != EXPLORED) {
14545 			verbose(env, "unreachable insn %d\n", i);
14546 			ret = -EINVAL;
14547 			goto err_free;
14548 		}
14549 	}
14550 	ret = 0; /* cfg looks good */
14551 
14552 err_free:
14553 	kvfree(insn_state);
14554 	kvfree(insn_stack);
14555 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14556 	return ret;
14557 }
14558 
14559 static int check_abnormal_return(struct bpf_verifier_env *env)
14560 {
14561 	int i;
14562 
14563 	for (i = 1; i < env->subprog_cnt; i++) {
14564 		if (env->subprog_info[i].has_ld_abs) {
14565 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14566 			return -EINVAL;
14567 		}
14568 		if (env->subprog_info[i].has_tail_call) {
14569 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14570 			return -EINVAL;
14571 		}
14572 	}
14573 	return 0;
14574 }
14575 
14576 /* The minimum supported BTF func info size */
14577 #define MIN_BPF_FUNCINFO_SIZE	8
14578 #define MAX_FUNCINFO_REC_SIZE	252
14579 
14580 static int check_btf_func(struct bpf_verifier_env *env,
14581 			  const union bpf_attr *attr,
14582 			  bpfptr_t uattr)
14583 {
14584 	const struct btf_type *type, *func_proto, *ret_type;
14585 	u32 i, nfuncs, urec_size, min_size;
14586 	u32 krec_size = sizeof(struct bpf_func_info);
14587 	struct bpf_func_info *krecord;
14588 	struct bpf_func_info_aux *info_aux = NULL;
14589 	struct bpf_prog *prog;
14590 	const struct btf *btf;
14591 	bpfptr_t urecord;
14592 	u32 prev_offset = 0;
14593 	bool scalar_return;
14594 	int ret = -ENOMEM;
14595 
14596 	nfuncs = attr->func_info_cnt;
14597 	if (!nfuncs) {
14598 		if (check_abnormal_return(env))
14599 			return -EINVAL;
14600 		return 0;
14601 	}
14602 
14603 	if (nfuncs != env->subprog_cnt) {
14604 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14605 		return -EINVAL;
14606 	}
14607 
14608 	urec_size = attr->func_info_rec_size;
14609 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14610 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
14611 	    urec_size % sizeof(u32)) {
14612 		verbose(env, "invalid func info rec size %u\n", urec_size);
14613 		return -EINVAL;
14614 	}
14615 
14616 	prog = env->prog;
14617 	btf = prog->aux->btf;
14618 
14619 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14620 	min_size = min_t(u32, krec_size, urec_size);
14621 
14622 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14623 	if (!krecord)
14624 		return -ENOMEM;
14625 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14626 	if (!info_aux)
14627 		goto err_free;
14628 
14629 	for (i = 0; i < nfuncs; i++) {
14630 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14631 		if (ret) {
14632 			if (ret == -E2BIG) {
14633 				verbose(env, "nonzero tailing record in func info");
14634 				/* set the size kernel expects so loader can zero
14635 				 * out the rest of the record.
14636 				 */
14637 				if (copy_to_bpfptr_offset(uattr,
14638 							  offsetof(union bpf_attr, func_info_rec_size),
14639 							  &min_size, sizeof(min_size)))
14640 					ret = -EFAULT;
14641 			}
14642 			goto err_free;
14643 		}
14644 
14645 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14646 			ret = -EFAULT;
14647 			goto err_free;
14648 		}
14649 
14650 		/* check insn_off */
14651 		ret = -EINVAL;
14652 		if (i == 0) {
14653 			if (krecord[i].insn_off) {
14654 				verbose(env,
14655 					"nonzero insn_off %u for the first func info record",
14656 					krecord[i].insn_off);
14657 				goto err_free;
14658 			}
14659 		} else if (krecord[i].insn_off <= prev_offset) {
14660 			verbose(env,
14661 				"same or smaller insn offset (%u) than previous func info record (%u)",
14662 				krecord[i].insn_off, prev_offset);
14663 			goto err_free;
14664 		}
14665 
14666 		if (env->subprog_info[i].start != krecord[i].insn_off) {
14667 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14668 			goto err_free;
14669 		}
14670 
14671 		/* check type_id */
14672 		type = btf_type_by_id(btf, krecord[i].type_id);
14673 		if (!type || !btf_type_is_func(type)) {
14674 			verbose(env, "invalid type id %d in func info",
14675 				krecord[i].type_id);
14676 			goto err_free;
14677 		}
14678 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14679 
14680 		func_proto = btf_type_by_id(btf, type->type);
14681 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14682 			/* btf_func_check() already verified it during BTF load */
14683 			goto err_free;
14684 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14685 		scalar_return =
14686 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14687 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14688 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14689 			goto err_free;
14690 		}
14691 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14692 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14693 			goto err_free;
14694 		}
14695 
14696 		prev_offset = krecord[i].insn_off;
14697 		bpfptr_add(&urecord, urec_size);
14698 	}
14699 
14700 	prog->aux->func_info = krecord;
14701 	prog->aux->func_info_cnt = nfuncs;
14702 	prog->aux->func_info_aux = info_aux;
14703 	return 0;
14704 
14705 err_free:
14706 	kvfree(krecord);
14707 	kfree(info_aux);
14708 	return ret;
14709 }
14710 
14711 static void adjust_btf_func(struct bpf_verifier_env *env)
14712 {
14713 	struct bpf_prog_aux *aux = env->prog->aux;
14714 	int i;
14715 
14716 	if (!aux->func_info)
14717 		return;
14718 
14719 	for (i = 0; i < env->subprog_cnt; i++)
14720 		aux->func_info[i].insn_off = env->subprog_info[i].start;
14721 }
14722 
14723 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
14724 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
14725 
14726 static int check_btf_line(struct bpf_verifier_env *env,
14727 			  const union bpf_attr *attr,
14728 			  bpfptr_t uattr)
14729 {
14730 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14731 	struct bpf_subprog_info *sub;
14732 	struct bpf_line_info *linfo;
14733 	struct bpf_prog *prog;
14734 	const struct btf *btf;
14735 	bpfptr_t ulinfo;
14736 	int err;
14737 
14738 	nr_linfo = attr->line_info_cnt;
14739 	if (!nr_linfo)
14740 		return 0;
14741 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14742 		return -EINVAL;
14743 
14744 	rec_size = attr->line_info_rec_size;
14745 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14746 	    rec_size > MAX_LINEINFO_REC_SIZE ||
14747 	    rec_size & (sizeof(u32) - 1))
14748 		return -EINVAL;
14749 
14750 	/* Need to zero it in case the userspace may
14751 	 * pass in a smaller bpf_line_info object.
14752 	 */
14753 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14754 			 GFP_KERNEL | __GFP_NOWARN);
14755 	if (!linfo)
14756 		return -ENOMEM;
14757 
14758 	prog = env->prog;
14759 	btf = prog->aux->btf;
14760 
14761 	s = 0;
14762 	sub = env->subprog_info;
14763 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14764 	expected_size = sizeof(struct bpf_line_info);
14765 	ncopy = min_t(u32, expected_size, rec_size);
14766 	for (i = 0; i < nr_linfo; i++) {
14767 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14768 		if (err) {
14769 			if (err == -E2BIG) {
14770 				verbose(env, "nonzero tailing record in line_info");
14771 				if (copy_to_bpfptr_offset(uattr,
14772 							  offsetof(union bpf_attr, line_info_rec_size),
14773 							  &expected_size, sizeof(expected_size)))
14774 					err = -EFAULT;
14775 			}
14776 			goto err_free;
14777 		}
14778 
14779 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14780 			err = -EFAULT;
14781 			goto err_free;
14782 		}
14783 
14784 		/*
14785 		 * Check insn_off to ensure
14786 		 * 1) strictly increasing AND
14787 		 * 2) bounded by prog->len
14788 		 *
14789 		 * The linfo[0].insn_off == 0 check logically falls into
14790 		 * the later "missing bpf_line_info for func..." case
14791 		 * because the first linfo[0].insn_off must be the
14792 		 * first sub also and the first sub must have
14793 		 * subprog_info[0].start == 0.
14794 		 */
14795 		if ((i && linfo[i].insn_off <= prev_offset) ||
14796 		    linfo[i].insn_off >= prog->len) {
14797 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14798 				i, linfo[i].insn_off, prev_offset,
14799 				prog->len);
14800 			err = -EINVAL;
14801 			goto err_free;
14802 		}
14803 
14804 		if (!prog->insnsi[linfo[i].insn_off].code) {
14805 			verbose(env,
14806 				"Invalid insn code at line_info[%u].insn_off\n",
14807 				i);
14808 			err = -EINVAL;
14809 			goto err_free;
14810 		}
14811 
14812 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14813 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14814 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14815 			err = -EINVAL;
14816 			goto err_free;
14817 		}
14818 
14819 		if (s != env->subprog_cnt) {
14820 			if (linfo[i].insn_off == sub[s].start) {
14821 				sub[s].linfo_idx = i;
14822 				s++;
14823 			} else if (sub[s].start < linfo[i].insn_off) {
14824 				verbose(env, "missing bpf_line_info for func#%u\n", s);
14825 				err = -EINVAL;
14826 				goto err_free;
14827 			}
14828 		}
14829 
14830 		prev_offset = linfo[i].insn_off;
14831 		bpfptr_add(&ulinfo, rec_size);
14832 	}
14833 
14834 	if (s != env->subprog_cnt) {
14835 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14836 			env->subprog_cnt - s, s);
14837 		err = -EINVAL;
14838 		goto err_free;
14839 	}
14840 
14841 	prog->aux->linfo = linfo;
14842 	prog->aux->nr_linfo = nr_linfo;
14843 
14844 	return 0;
14845 
14846 err_free:
14847 	kvfree(linfo);
14848 	return err;
14849 }
14850 
14851 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
14852 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
14853 
14854 static int check_core_relo(struct bpf_verifier_env *env,
14855 			   const union bpf_attr *attr,
14856 			   bpfptr_t uattr)
14857 {
14858 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14859 	struct bpf_core_relo core_relo = {};
14860 	struct bpf_prog *prog = env->prog;
14861 	const struct btf *btf = prog->aux->btf;
14862 	struct bpf_core_ctx ctx = {
14863 		.log = &env->log,
14864 		.btf = btf,
14865 	};
14866 	bpfptr_t u_core_relo;
14867 	int err;
14868 
14869 	nr_core_relo = attr->core_relo_cnt;
14870 	if (!nr_core_relo)
14871 		return 0;
14872 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14873 		return -EINVAL;
14874 
14875 	rec_size = attr->core_relo_rec_size;
14876 	if (rec_size < MIN_CORE_RELO_SIZE ||
14877 	    rec_size > MAX_CORE_RELO_SIZE ||
14878 	    rec_size % sizeof(u32))
14879 		return -EINVAL;
14880 
14881 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14882 	expected_size = sizeof(struct bpf_core_relo);
14883 	ncopy = min_t(u32, expected_size, rec_size);
14884 
14885 	/* Unlike func_info and line_info, copy and apply each CO-RE
14886 	 * relocation record one at a time.
14887 	 */
14888 	for (i = 0; i < nr_core_relo; i++) {
14889 		/* future proofing when sizeof(bpf_core_relo) changes */
14890 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14891 		if (err) {
14892 			if (err == -E2BIG) {
14893 				verbose(env, "nonzero tailing record in core_relo");
14894 				if (copy_to_bpfptr_offset(uattr,
14895 							  offsetof(union bpf_attr, core_relo_rec_size),
14896 							  &expected_size, sizeof(expected_size)))
14897 					err = -EFAULT;
14898 			}
14899 			break;
14900 		}
14901 
14902 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14903 			err = -EFAULT;
14904 			break;
14905 		}
14906 
14907 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14908 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14909 				i, core_relo.insn_off, prog->len);
14910 			err = -EINVAL;
14911 			break;
14912 		}
14913 
14914 		err = bpf_core_apply(&ctx, &core_relo, i,
14915 				     &prog->insnsi[core_relo.insn_off / 8]);
14916 		if (err)
14917 			break;
14918 		bpfptr_add(&u_core_relo, rec_size);
14919 	}
14920 	return err;
14921 }
14922 
14923 static int check_btf_info(struct bpf_verifier_env *env,
14924 			  const union bpf_attr *attr,
14925 			  bpfptr_t uattr)
14926 {
14927 	struct btf *btf;
14928 	int err;
14929 
14930 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
14931 		if (check_abnormal_return(env))
14932 			return -EINVAL;
14933 		return 0;
14934 	}
14935 
14936 	btf = btf_get_by_fd(attr->prog_btf_fd);
14937 	if (IS_ERR(btf))
14938 		return PTR_ERR(btf);
14939 	if (btf_is_kernel(btf)) {
14940 		btf_put(btf);
14941 		return -EACCES;
14942 	}
14943 	env->prog->aux->btf = btf;
14944 
14945 	err = check_btf_func(env, attr, uattr);
14946 	if (err)
14947 		return err;
14948 
14949 	err = check_btf_line(env, attr, uattr);
14950 	if (err)
14951 		return err;
14952 
14953 	err = check_core_relo(env, attr, uattr);
14954 	if (err)
14955 		return err;
14956 
14957 	return 0;
14958 }
14959 
14960 /* check %cur's range satisfies %old's */
14961 static bool range_within(struct bpf_reg_state *old,
14962 			 struct bpf_reg_state *cur)
14963 {
14964 	return old->umin_value <= cur->umin_value &&
14965 	       old->umax_value >= cur->umax_value &&
14966 	       old->smin_value <= cur->smin_value &&
14967 	       old->smax_value >= cur->smax_value &&
14968 	       old->u32_min_value <= cur->u32_min_value &&
14969 	       old->u32_max_value >= cur->u32_max_value &&
14970 	       old->s32_min_value <= cur->s32_min_value &&
14971 	       old->s32_max_value >= cur->s32_max_value;
14972 }
14973 
14974 /* If in the old state two registers had the same id, then they need to have
14975  * the same id in the new state as well.  But that id could be different from
14976  * the old state, so we need to track the mapping from old to new ids.
14977  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14978  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
14979  * regs with a different old id could still have new id 9, we don't care about
14980  * that.
14981  * So we look through our idmap to see if this old id has been seen before.  If
14982  * so, we require the new id to match; otherwise, we add the id pair to the map.
14983  */
14984 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14985 {
14986 	unsigned int i;
14987 
14988 	/* either both IDs should be set or both should be zero */
14989 	if (!!old_id != !!cur_id)
14990 		return false;
14991 
14992 	if (old_id == 0) /* cur_id == 0 as well */
14993 		return true;
14994 
14995 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14996 		if (!idmap[i].old) {
14997 			/* Reached an empty slot; haven't seen this id before */
14998 			idmap[i].old = old_id;
14999 			idmap[i].cur = cur_id;
15000 			return true;
15001 		}
15002 		if (idmap[i].old == old_id)
15003 			return idmap[i].cur == cur_id;
15004 	}
15005 	/* We ran out of idmap slots, which should be impossible */
15006 	WARN_ON_ONCE(1);
15007 	return false;
15008 }
15009 
15010 static void clean_func_state(struct bpf_verifier_env *env,
15011 			     struct bpf_func_state *st)
15012 {
15013 	enum bpf_reg_liveness live;
15014 	int i, j;
15015 
15016 	for (i = 0; i < BPF_REG_FP; i++) {
15017 		live = st->regs[i].live;
15018 		/* liveness must not touch this register anymore */
15019 		st->regs[i].live |= REG_LIVE_DONE;
15020 		if (!(live & REG_LIVE_READ))
15021 			/* since the register is unused, clear its state
15022 			 * to make further comparison simpler
15023 			 */
15024 			__mark_reg_not_init(env, &st->regs[i]);
15025 	}
15026 
15027 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15028 		live = st->stack[i].spilled_ptr.live;
15029 		/* liveness must not touch this stack slot anymore */
15030 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15031 		if (!(live & REG_LIVE_READ)) {
15032 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15033 			for (j = 0; j < BPF_REG_SIZE; j++)
15034 				st->stack[i].slot_type[j] = STACK_INVALID;
15035 		}
15036 	}
15037 }
15038 
15039 static void clean_verifier_state(struct bpf_verifier_env *env,
15040 				 struct bpf_verifier_state *st)
15041 {
15042 	int i;
15043 
15044 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15045 		/* all regs in this state in all frames were already marked */
15046 		return;
15047 
15048 	for (i = 0; i <= st->curframe; i++)
15049 		clean_func_state(env, st->frame[i]);
15050 }
15051 
15052 /* the parentage chains form a tree.
15053  * the verifier states are added to state lists at given insn and
15054  * pushed into state stack for future exploration.
15055  * when the verifier reaches bpf_exit insn some of the verifer states
15056  * stored in the state lists have their final liveness state already,
15057  * but a lot of states will get revised from liveness point of view when
15058  * the verifier explores other branches.
15059  * Example:
15060  * 1: r0 = 1
15061  * 2: if r1 == 100 goto pc+1
15062  * 3: r0 = 2
15063  * 4: exit
15064  * when the verifier reaches exit insn the register r0 in the state list of
15065  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15066  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15067  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15068  *
15069  * Since the verifier pushes the branch states as it sees them while exploring
15070  * the program the condition of walking the branch instruction for the second
15071  * time means that all states below this branch were already explored and
15072  * their final liveness marks are already propagated.
15073  * Hence when the verifier completes the search of state list in is_state_visited()
15074  * we can call this clean_live_states() function to mark all liveness states
15075  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15076  * will not be used.
15077  * This function also clears the registers and stack for states that !READ
15078  * to simplify state merging.
15079  *
15080  * Important note here that walking the same branch instruction in the callee
15081  * doesn't meant that the states are DONE. The verifier has to compare
15082  * the callsites
15083  */
15084 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15085 			      struct bpf_verifier_state *cur)
15086 {
15087 	struct bpf_verifier_state_list *sl;
15088 	int i;
15089 
15090 	sl = *explored_state(env, insn);
15091 	while (sl) {
15092 		if (sl->state.branches)
15093 			goto next;
15094 		if (sl->state.insn_idx != insn ||
15095 		    sl->state.curframe != cur->curframe)
15096 			goto next;
15097 		for (i = 0; i <= cur->curframe; i++)
15098 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15099 				goto next;
15100 		clean_verifier_state(env, &sl->state);
15101 next:
15102 		sl = sl->next;
15103 	}
15104 }
15105 
15106 static bool regs_exact(const struct bpf_reg_state *rold,
15107 		       const struct bpf_reg_state *rcur,
15108 		       struct bpf_id_pair *idmap)
15109 {
15110 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15111 	       check_ids(rold->id, rcur->id, idmap) &&
15112 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15113 }
15114 
15115 /* Returns true if (rold safe implies rcur safe) */
15116 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15117 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
15118 {
15119 	if (!(rold->live & REG_LIVE_READ))
15120 		/* explored state didn't use this */
15121 		return true;
15122 	if (rold->type == NOT_INIT)
15123 		/* explored state can't have used this */
15124 		return true;
15125 	if (rcur->type == NOT_INIT)
15126 		return false;
15127 
15128 	/* Enforce that register types have to match exactly, including their
15129 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15130 	 * rule.
15131 	 *
15132 	 * One can make a point that using a pointer register as unbounded
15133 	 * SCALAR would be technically acceptable, but this could lead to
15134 	 * pointer leaks because scalars are allowed to leak while pointers
15135 	 * are not. We could make this safe in special cases if root is
15136 	 * calling us, but it's probably not worth the hassle.
15137 	 *
15138 	 * Also, register types that are *not* MAYBE_NULL could technically be
15139 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15140 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15141 	 * to the same map).
15142 	 * However, if the old MAYBE_NULL register then got NULL checked,
15143 	 * doing so could have affected others with the same id, and we can't
15144 	 * check for that because we lost the id when we converted to
15145 	 * a non-MAYBE_NULL variant.
15146 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15147 	 * non-MAYBE_NULL registers as well.
15148 	 */
15149 	if (rold->type != rcur->type)
15150 		return false;
15151 
15152 	switch (base_type(rold->type)) {
15153 	case SCALAR_VALUE:
15154 		if (regs_exact(rold, rcur, idmap))
15155 			return true;
15156 		if (env->explore_alu_limits)
15157 			return false;
15158 		if (!rold->precise)
15159 			return true;
15160 		/* new val must satisfy old val knowledge */
15161 		return range_within(rold, rcur) &&
15162 		       tnum_in(rold->var_off, rcur->var_off);
15163 	case PTR_TO_MAP_KEY:
15164 	case PTR_TO_MAP_VALUE:
15165 	case PTR_TO_MEM:
15166 	case PTR_TO_BUF:
15167 	case PTR_TO_TP_BUFFER:
15168 		/* If the new min/max/var_off satisfy the old ones and
15169 		 * everything else matches, we are OK.
15170 		 */
15171 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15172 		       range_within(rold, rcur) &&
15173 		       tnum_in(rold->var_off, rcur->var_off) &&
15174 		       check_ids(rold->id, rcur->id, idmap) &&
15175 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15176 	case PTR_TO_PACKET_META:
15177 	case PTR_TO_PACKET:
15178 		/* We must have at least as much range as the old ptr
15179 		 * did, so that any accesses which were safe before are
15180 		 * still safe.  This is true even if old range < old off,
15181 		 * since someone could have accessed through (ptr - k), or
15182 		 * even done ptr -= k in a register, to get a safe access.
15183 		 */
15184 		if (rold->range > rcur->range)
15185 			return false;
15186 		/* If the offsets don't match, we can't trust our alignment;
15187 		 * nor can we be sure that we won't fall out of range.
15188 		 */
15189 		if (rold->off != rcur->off)
15190 			return false;
15191 		/* id relations must be preserved */
15192 		if (!check_ids(rold->id, rcur->id, idmap))
15193 			return false;
15194 		/* new val must satisfy old val knowledge */
15195 		return range_within(rold, rcur) &&
15196 		       tnum_in(rold->var_off, rcur->var_off);
15197 	case PTR_TO_STACK:
15198 		/* two stack pointers are equal only if they're pointing to
15199 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15200 		 */
15201 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15202 	default:
15203 		return regs_exact(rold, rcur, idmap);
15204 	}
15205 }
15206 
15207 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15208 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
15209 {
15210 	int i, spi;
15211 
15212 	/* walk slots of the explored stack and ignore any additional
15213 	 * slots in the current stack, since explored(safe) state
15214 	 * didn't use them
15215 	 */
15216 	for (i = 0; i < old->allocated_stack; i++) {
15217 		struct bpf_reg_state *old_reg, *cur_reg;
15218 
15219 		spi = i / BPF_REG_SIZE;
15220 
15221 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15222 			i += BPF_REG_SIZE - 1;
15223 			/* explored state didn't use this */
15224 			continue;
15225 		}
15226 
15227 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15228 			continue;
15229 
15230 		if (env->allow_uninit_stack &&
15231 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15232 			continue;
15233 
15234 		/* explored stack has more populated slots than current stack
15235 		 * and these slots were used
15236 		 */
15237 		if (i >= cur->allocated_stack)
15238 			return false;
15239 
15240 		/* if old state was safe with misc data in the stack
15241 		 * it will be safe with zero-initialized stack.
15242 		 * The opposite is not true
15243 		 */
15244 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15245 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15246 			continue;
15247 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15248 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15249 			/* Ex: old explored (safe) state has STACK_SPILL in
15250 			 * this stack slot, but current has STACK_MISC ->
15251 			 * this verifier states are not equivalent,
15252 			 * return false to continue verification of this path
15253 			 */
15254 			return false;
15255 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15256 			continue;
15257 		/* Both old and cur are having same slot_type */
15258 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15259 		case STACK_SPILL:
15260 			/* when explored and current stack slot are both storing
15261 			 * spilled registers, check that stored pointers types
15262 			 * are the same as well.
15263 			 * Ex: explored safe path could have stored
15264 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15265 			 * but current path has stored:
15266 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15267 			 * such verifier states are not equivalent.
15268 			 * return false to continue verification of this path
15269 			 */
15270 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15271 				     &cur->stack[spi].spilled_ptr, idmap))
15272 				return false;
15273 			break;
15274 		case STACK_DYNPTR:
15275 			old_reg = &old->stack[spi].spilled_ptr;
15276 			cur_reg = &cur->stack[spi].spilled_ptr;
15277 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15278 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15279 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15280 				return false;
15281 			break;
15282 		case STACK_ITER:
15283 			old_reg = &old->stack[spi].spilled_ptr;
15284 			cur_reg = &cur->stack[spi].spilled_ptr;
15285 			/* iter.depth is not compared between states as it
15286 			 * doesn't matter for correctness and would otherwise
15287 			 * prevent convergence; we maintain it only to prevent
15288 			 * infinite loop check triggering, see
15289 			 * iter_active_depths_differ()
15290 			 */
15291 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15292 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15293 			    old_reg->iter.state != cur_reg->iter.state ||
15294 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15295 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15296 				return false;
15297 			break;
15298 		case STACK_MISC:
15299 		case STACK_ZERO:
15300 		case STACK_INVALID:
15301 			continue;
15302 		/* Ensure that new unhandled slot types return false by default */
15303 		default:
15304 			return false;
15305 		}
15306 	}
15307 	return true;
15308 }
15309 
15310 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15311 		    struct bpf_id_pair *idmap)
15312 {
15313 	int i;
15314 
15315 	if (old->acquired_refs != cur->acquired_refs)
15316 		return false;
15317 
15318 	for (i = 0; i < old->acquired_refs; i++) {
15319 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15320 			return false;
15321 	}
15322 
15323 	return true;
15324 }
15325 
15326 /* compare two verifier states
15327  *
15328  * all states stored in state_list are known to be valid, since
15329  * verifier reached 'bpf_exit' instruction through them
15330  *
15331  * this function is called when verifier exploring different branches of
15332  * execution popped from the state stack. If it sees an old state that has
15333  * more strict register state and more strict stack state then this execution
15334  * branch doesn't need to be explored further, since verifier already
15335  * concluded that more strict state leads to valid finish.
15336  *
15337  * Therefore two states are equivalent if register state is more conservative
15338  * and explored stack state is more conservative than the current one.
15339  * Example:
15340  *       explored                   current
15341  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15342  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15343  *
15344  * In other words if current stack state (one being explored) has more
15345  * valid slots than old one that already passed validation, it means
15346  * the verifier can stop exploring and conclude that current state is valid too
15347  *
15348  * Similarly with registers. If explored state has register type as invalid
15349  * whereas register type in current state is meaningful, it means that
15350  * the current state will reach 'bpf_exit' instruction safely
15351  */
15352 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15353 			      struct bpf_func_state *cur)
15354 {
15355 	int i;
15356 
15357 	for (i = 0; i < MAX_BPF_REG; i++)
15358 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15359 			     env->idmap_scratch))
15360 			return false;
15361 
15362 	if (!stacksafe(env, old, cur, env->idmap_scratch))
15363 		return false;
15364 
15365 	if (!refsafe(old, cur, env->idmap_scratch))
15366 		return false;
15367 
15368 	return true;
15369 }
15370 
15371 static bool states_equal(struct bpf_verifier_env *env,
15372 			 struct bpf_verifier_state *old,
15373 			 struct bpf_verifier_state *cur)
15374 {
15375 	int i;
15376 
15377 	if (old->curframe != cur->curframe)
15378 		return false;
15379 
15380 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
15381 
15382 	/* Verification state from speculative execution simulation
15383 	 * must never prune a non-speculative execution one.
15384 	 */
15385 	if (old->speculative && !cur->speculative)
15386 		return false;
15387 
15388 	if (old->active_lock.ptr != cur->active_lock.ptr)
15389 		return false;
15390 
15391 	/* Old and cur active_lock's have to be either both present
15392 	 * or both absent.
15393 	 */
15394 	if (!!old->active_lock.id != !!cur->active_lock.id)
15395 		return false;
15396 
15397 	if (old->active_lock.id &&
15398 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
15399 		return false;
15400 
15401 	if (old->active_rcu_lock != cur->active_rcu_lock)
15402 		return false;
15403 
15404 	/* for states to be equal callsites have to be the same
15405 	 * and all frame states need to be equivalent
15406 	 */
15407 	for (i = 0; i <= old->curframe; i++) {
15408 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15409 			return false;
15410 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15411 			return false;
15412 	}
15413 	return true;
15414 }
15415 
15416 /* Return 0 if no propagation happened. Return negative error code if error
15417  * happened. Otherwise, return the propagated bit.
15418  */
15419 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15420 				  struct bpf_reg_state *reg,
15421 				  struct bpf_reg_state *parent_reg)
15422 {
15423 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15424 	u8 flag = reg->live & REG_LIVE_READ;
15425 	int err;
15426 
15427 	/* When comes here, read flags of PARENT_REG or REG could be any of
15428 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15429 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15430 	 */
15431 	if (parent_flag == REG_LIVE_READ64 ||
15432 	    /* Or if there is no read flag from REG. */
15433 	    !flag ||
15434 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15435 	    parent_flag == flag)
15436 		return 0;
15437 
15438 	err = mark_reg_read(env, reg, parent_reg, flag);
15439 	if (err)
15440 		return err;
15441 
15442 	return flag;
15443 }
15444 
15445 /* A write screens off any subsequent reads; but write marks come from the
15446  * straight-line code between a state and its parent.  When we arrive at an
15447  * equivalent state (jump target or such) we didn't arrive by the straight-line
15448  * code, so read marks in the state must propagate to the parent regardless
15449  * of the state's write marks. That's what 'parent == state->parent' comparison
15450  * in mark_reg_read() is for.
15451  */
15452 static int propagate_liveness(struct bpf_verifier_env *env,
15453 			      const struct bpf_verifier_state *vstate,
15454 			      struct bpf_verifier_state *vparent)
15455 {
15456 	struct bpf_reg_state *state_reg, *parent_reg;
15457 	struct bpf_func_state *state, *parent;
15458 	int i, frame, err = 0;
15459 
15460 	if (vparent->curframe != vstate->curframe) {
15461 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15462 		     vparent->curframe, vstate->curframe);
15463 		return -EFAULT;
15464 	}
15465 	/* Propagate read liveness of registers... */
15466 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15467 	for (frame = 0; frame <= vstate->curframe; frame++) {
15468 		parent = vparent->frame[frame];
15469 		state = vstate->frame[frame];
15470 		parent_reg = parent->regs;
15471 		state_reg = state->regs;
15472 		/* We don't need to worry about FP liveness, it's read-only */
15473 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15474 			err = propagate_liveness_reg(env, &state_reg[i],
15475 						     &parent_reg[i]);
15476 			if (err < 0)
15477 				return err;
15478 			if (err == REG_LIVE_READ64)
15479 				mark_insn_zext(env, &parent_reg[i]);
15480 		}
15481 
15482 		/* Propagate stack slots. */
15483 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15484 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15485 			parent_reg = &parent->stack[i].spilled_ptr;
15486 			state_reg = &state->stack[i].spilled_ptr;
15487 			err = propagate_liveness_reg(env, state_reg,
15488 						     parent_reg);
15489 			if (err < 0)
15490 				return err;
15491 		}
15492 	}
15493 	return 0;
15494 }
15495 
15496 /* find precise scalars in the previous equivalent state and
15497  * propagate them into the current state
15498  */
15499 static int propagate_precision(struct bpf_verifier_env *env,
15500 			       const struct bpf_verifier_state *old)
15501 {
15502 	struct bpf_reg_state *state_reg;
15503 	struct bpf_func_state *state;
15504 	int i, err = 0, fr;
15505 	bool first;
15506 
15507 	for (fr = old->curframe; fr >= 0; fr--) {
15508 		state = old->frame[fr];
15509 		state_reg = state->regs;
15510 		first = true;
15511 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15512 			if (state_reg->type != SCALAR_VALUE ||
15513 			    !state_reg->precise ||
15514 			    !(state_reg->live & REG_LIVE_READ))
15515 				continue;
15516 			if (env->log.level & BPF_LOG_LEVEL2) {
15517 				if (first)
15518 					verbose(env, "frame %d: propagating r%d", fr, i);
15519 				else
15520 					verbose(env, ",r%d", i);
15521 			}
15522 			bt_set_frame_reg(&env->bt, fr, i);
15523 			first = false;
15524 		}
15525 
15526 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15527 			if (!is_spilled_reg(&state->stack[i]))
15528 				continue;
15529 			state_reg = &state->stack[i].spilled_ptr;
15530 			if (state_reg->type != SCALAR_VALUE ||
15531 			    !state_reg->precise ||
15532 			    !(state_reg->live & REG_LIVE_READ))
15533 				continue;
15534 			if (env->log.level & BPF_LOG_LEVEL2) {
15535 				if (first)
15536 					verbose(env, "frame %d: propagating fp%d",
15537 						fr, (-i - 1) * BPF_REG_SIZE);
15538 				else
15539 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15540 			}
15541 			bt_set_frame_slot(&env->bt, fr, i);
15542 			first = false;
15543 		}
15544 		if (!first)
15545 			verbose(env, "\n");
15546 	}
15547 
15548 	err = mark_chain_precision_batch(env);
15549 	if (err < 0)
15550 		return err;
15551 
15552 	return 0;
15553 }
15554 
15555 static bool states_maybe_looping(struct bpf_verifier_state *old,
15556 				 struct bpf_verifier_state *cur)
15557 {
15558 	struct bpf_func_state *fold, *fcur;
15559 	int i, fr = cur->curframe;
15560 
15561 	if (old->curframe != fr)
15562 		return false;
15563 
15564 	fold = old->frame[fr];
15565 	fcur = cur->frame[fr];
15566 	for (i = 0; i < MAX_BPF_REG; i++)
15567 		if (memcmp(&fold->regs[i], &fcur->regs[i],
15568 			   offsetof(struct bpf_reg_state, parent)))
15569 			return false;
15570 	return true;
15571 }
15572 
15573 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15574 {
15575 	return env->insn_aux_data[insn_idx].is_iter_next;
15576 }
15577 
15578 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15579  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15580  * states to match, which otherwise would look like an infinite loop. So while
15581  * iter_next() calls are taken care of, we still need to be careful and
15582  * prevent erroneous and too eager declaration of "ininite loop", when
15583  * iterators are involved.
15584  *
15585  * Here's a situation in pseudo-BPF assembly form:
15586  *
15587  *   0: again:                          ; set up iter_next() call args
15588  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15589  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15590  *   3:   if r0 == 0 goto done
15591  *   4:   ... something useful here ...
15592  *   5:   goto again                    ; another iteration
15593  *   6: done:
15594  *   7:   r1 = &it
15595  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15596  *   9:   exit
15597  *
15598  * This is a typical loop. Let's assume that we have a prune point at 1:,
15599  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15600  * again`, assuming other heuristics don't get in a way).
15601  *
15602  * When we first time come to 1:, let's say we have some state X. We proceed
15603  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15604  * Now we come back to validate that forked ACTIVE state. We proceed through
15605  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15606  * are converging. But the problem is that we don't know that yet, as this
15607  * convergence has to happen at iter_next() call site only. So if nothing is
15608  * done, at 1: verifier will use bounded loop logic and declare infinite
15609  * looping (and would be *technically* correct, if not for iterator's
15610  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15611  * don't want that. So what we do in process_iter_next_call() when we go on
15612  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15613  * a different iteration. So when we suspect an infinite loop, we additionally
15614  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15615  * pretend we are not looping and wait for next iter_next() call.
15616  *
15617  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15618  * loop, because that would actually mean infinite loop, as DRAINED state is
15619  * "sticky", and so we'll keep returning into the same instruction with the
15620  * same state (at least in one of possible code paths).
15621  *
15622  * This approach allows to keep infinite loop heuristic even in the face of
15623  * active iterator. E.g., C snippet below is and will be detected as
15624  * inifintely looping:
15625  *
15626  *   struct bpf_iter_num it;
15627  *   int *p, x;
15628  *
15629  *   bpf_iter_num_new(&it, 0, 10);
15630  *   while ((p = bpf_iter_num_next(&t))) {
15631  *       x = p;
15632  *       while (x--) {} // <<-- infinite loop here
15633  *   }
15634  *
15635  */
15636 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15637 {
15638 	struct bpf_reg_state *slot, *cur_slot;
15639 	struct bpf_func_state *state;
15640 	int i, fr;
15641 
15642 	for (fr = old->curframe; fr >= 0; fr--) {
15643 		state = old->frame[fr];
15644 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15645 			if (state->stack[i].slot_type[0] != STACK_ITER)
15646 				continue;
15647 
15648 			slot = &state->stack[i].spilled_ptr;
15649 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15650 				continue;
15651 
15652 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15653 			if (cur_slot->iter.depth != slot->iter.depth)
15654 				return true;
15655 		}
15656 	}
15657 	return false;
15658 }
15659 
15660 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15661 {
15662 	struct bpf_verifier_state_list *new_sl;
15663 	struct bpf_verifier_state_list *sl, **pprev;
15664 	struct bpf_verifier_state *cur = env->cur_state, *new;
15665 	int i, j, err, states_cnt = 0;
15666 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15667 	bool add_new_state = force_new_state;
15668 
15669 	/* bpf progs typically have pruning point every 4 instructions
15670 	 * http://vger.kernel.org/bpfconf2019.html#session-1
15671 	 * Do not add new state for future pruning if the verifier hasn't seen
15672 	 * at least 2 jumps and at least 8 instructions.
15673 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15674 	 * In tests that amounts to up to 50% reduction into total verifier
15675 	 * memory consumption and 20% verifier time speedup.
15676 	 */
15677 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15678 	    env->insn_processed - env->prev_insn_processed >= 8)
15679 		add_new_state = true;
15680 
15681 	pprev = explored_state(env, insn_idx);
15682 	sl = *pprev;
15683 
15684 	clean_live_states(env, insn_idx, cur);
15685 
15686 	while (sl) {
15687 		states_cnt++;
15688 		if (sl->state.insn_idx != insn_idx)
15689 			goto next;
15690 
15691 		if (sl->state.branches) {
15692 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15693 
15694 			if (frame->in_async_callback_fn &&
15695 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15696 				/* Different async_entry_cnt means that the verifier is
15697 				 * processing another entry into async callback.
15698 				 * Seeing the same state is not an indication of infinite
15699 				 * loop or infinite recursion.
15700 				 * But finding the same state doesn't mean that it's safe
15701 				 * to stop processing the current state. The previous state
15702 				 * hasn't yet reached bpf_exit, since state.branches > 0.
15703 				 * Checking in_async_callback_fn alone is not enough either.
15704 				 * Since the verifier still needs to catch infinite loops
15705 				 * inside async callbacks.
15706 				 */
15707 				goto skip_inf_loop_check;
15708 			}
15709 			/* BPF open-coded iterators loop detection is special.
15710 			 * states_maybe_looping() logic is too simplistic in detecting
15711 			 * states that *might* be equivalent, because it doesn't know
15712 			 * about ID remapping, so don't even perform it.
15713 			 * See process_iter_next_call() and iter_active_depths_differ()
15714 			 * for overview of the logic. When current and one of parent
15715 			 * states are detected as equivalent, it's a good thing: we prove
15716 			 * convergence and can stop simulating further iterations.
15717 			 * It's safe to assume that iterator loop will finish, taking into
15718 			 * account iter_next() contract of eventually returning
15719 			 * sticky NULL result.
15720 			 */
15721 			if (is_iter_next_insn(env, insn_idx)) {
15722 				if (states_equal(env, &sl->state, cur)) {
15723 					struct bpf_func_state *cur_frame;
15724 					struct bpf_reg_state *iter_state, *iter_reg;
15725 					int spi;
15726 
15727 					cur_frame = cur->frame[cur->curframe];
15728 					/* btf_check_iter_kfuncs() enforces that
15729 					 * iter state pointer is always the first arg
15730 					 */
15731 					iter_reg = &cur_frame->regs[BPF_REG_1];
15732 					/* current state is valid due to states_equal(),
15733 					 * so we can assume valid iter and reg state,
15734 					 * no need for extra (re-)validations
15735 					 */
15736 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15737 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15738 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15739 						goto hit;
15740 				}
15741 				goto skip_inf_loop_check;
15742 			}
15743 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
15744 			if (states_maybe_looping(&sl->state, cur) &&
15745 			    states_equal(env, &sl->state, cur) &&
15746 			    !iter_active_depths_differ(&sl->state, cur)) {
15747 				verbose_linfo(env, insn_idx, "; ");
15748 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15749 				return -EINVAL;
15750 			}
15751 			/* if the verifier is processing a loop, avoid adding new state
15752 			 * too often, since different loop iterations have distinct
15753 			 * states and may not help future pruning.
15754 			 * This threshold shouldn't be too low to make sure that
15755 			 * a loop with large bound will be rejected quickly.
15756 			 * The most abusive loop will be:
15757 			 * r1 += 1
15758 			 * if r1 < 1000000 goto pc-2
15759 			 * 1M insn_procssed limit / 100 == 10k peak states.
15760 			 * This threshold shouldn't be too high either, since states
15761 			 * at the end of the loop are likely to be useful in pruning.
15762 			 */
15763 skip_inf_loop_check:
15764 			if (!force_new_state &&
15765 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
15766 			    env->insn_processed - env->prev_insn_processed < 100)
15767 				add_new_state = false;
15768 			goto miss;
15769 		}
15770 		if (states_equal(env, &sl->state, cur)) {
15771 hit:
15772 			sl->hit_cnt++;
15773 			/* reached equivalent register/stack state,
15774 			 * prune the search.
15775 			 * Registers read by the continuation are read by us.
15776 			 * If we have any write marks in env->cur_state, they
15777 			 * will prevent corresponding reads in the continuation
15778 			 * from reaching our parent (an explored_state).  Our
15779 			 * own state will get the read marks recorded, but
15780 			 * they'll be immediately forgotten as we're pruning
15781 			 * this state and will pop a new one.
15782 			 */
15783 			err = propagate_liveness(env, &sl->state, cur);
15784 
15785 			/* if previous state reached the exit with precision and
15786 			 * current state is equivalent to it (except precsion marks)
15787 			 * the precision needs to be propagated back in
15788 			 * the current state.
15789 			 */
15790 			err = err ? : push_jmp_history(env, cur);
15791 			err = err ? : propagate_precision(env, &sl->state);
15792 			if (err)
15793 				return err;
15794 			return 1;
15795 		}
15796 miss:
15797 		/* when new state is not going to be added do not increase miss count.
15798 		 * Otherwise several loop iterations will remove the state
15799 		 * recorded earlier. The goal of these heuristics is to have
15800 		 * states from some iterations of the loop (some in the beginning
15801 		 * and some at the end) to help pruning.
15802 		 */
15803 		if (add_new_state)
15804 			sl->miss_cnt++;
15805 		/* heuristic to determine whether this state is beneficial
15806 		 * to keep checking from state equivalence point of view.
15807 		 * Higher numbers increase max_states_per_insn and verification time,
15808 		 * but do not meaningfully decrease insn_processed.
15809 		 */
15810 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15811 			/* the state is unlikely to be useful. Remove it to
15812 			 * speed up verification
15813 			 */
15814 			*pprev = sl->next;
15815 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15816 				u32 br = sl->state.branches;
15817 
15818 				WARN_ONCE(br,
15819 					  "BUG live_done but branches_to_explore %d\n",
15820 					  br);
15821 				free_verifier_state(&sl->state, false);
15822 				kfree(sl);
15823 				env->peak_states--;
15824 			} else {
15825 				/* cannot free this state, since parentage chain may
15826 				 * walk it later. Add it for free_list instead to
15827 				 * be freed at the end of verification
15828 				 */
15829 				sl->next = env->free_list;
15830 				env->free_list = sl;
15831 			}
15832 			sl = *pprev;
15833 			continue;
15834 		}
15835 next:
15836 		pprev = &sl->next;
15837 		sl = *pprev;
15838 	}
15839 
15840 	if (env->max_states_per_insn < states_cnt)
15841 		env->max_states_per_insn = states_cnt;
15842 
15843 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15844 		return 0;
15845 
15846 	if (!add_new_state)
15847 		return 0;
15848 
15849 	/* There were no equivalent states, remember the current one.
15850 	 * Technically the current state is not proven to be safe yet,
15851 	 * but it will either reach outer most bpf_exit (which means it's safe)
15852 	 * or it will be rejected. When there are no loops the verifier won't be
15853 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15854 	 * again on the way to bpf_exit.
15855 	 * When looping the sl->state.branches will be > 0 and this state
15856 	 * will not be considered for equivalence until branches == 0.
15857 	 */
15858 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15859 	if (!new_sl)
15860 		return -ENOMEM;
15861 	env->total_states++;
15862 	env->peak_states++;
15863 	env->prev_jmps_processed = env->jmps_processed;
15864 	env->prev_insn_processed = env->insn_processed;
15865 
15866 	/* forget precise markings we inherited, see __mark_chain_precision */
15867 	if (env->bpf_capable)
15868 		mark_all_scalars_imprecise(env, cur);
15869 
15870 	/* add new state to the head of linked list */
15871 	new = &new_sl->state;
15872 	err = copy_verifier_state(new, cur);
15873 	if (err) {
15874 		free_verifier_state(new, false);
15875 		kfree(new_sl);
15876 		return err;
15877 	}
15878 	new->insn_idx = insn_idx;
15879 	WARN_ONCE(new->branches != 1,
15880 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
15881 
15882 	cur->parent = new;
15883 	cur->first_insn_idx = insn_idx;
15884 	clear_jmp_history(cur);
15885 	new_sl->next = *explored_state(env, insn_idx);
15886 	*explored_state(env, insn_idx) = new_sl;
15887 	/* connect new state to parentage chain. Current frame needs all
15888 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
15889 	 * to the stack implicitly by JITs) so in callers' frames connect just
15890 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15891 	 * the state of the call instruction (with WRITTEN set), and r0 comes
15892 	 * from callee with its full parentage chain, anyway.
15893 	 */
15894 	/* clear write marks in current state: the writes we did are not writes
15895 	 * our child did, so they don't screen off its reads from us.
15896 	 * (There are no read marks in current state, because reads always mark
15897 	 * their parent and current state never has children yet.  Only
15898 	 * explored_states can get read marks.)
15899 	 */
15900 	for (j = 0; j <= cur->curframe; j++) {
15901 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15902 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15903 		for (i = 0; i < BPF_REG_FP; i++)
15904 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15905 	}
15906 
15907 	/* all stack frames are accessible from callee, clear them all */
15908 	for (j = 0; j <= cur->curframe; j++) {
15909 		struct bpf_func_state *frame = cur->frame[j];
15910 		struct bpf_func_state *newframe = new->frame[j];
15911 
15912 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
15913 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
15914 			frame->stack[i].spilled_ptr.parent =
15915 						&newframe->stack[i].spilled_ptr;
15916 		}
15917 	}
15918 	return 0;
15919 }
15920 
15921 /* Return true if it's OK to have the same insn return a different type. */
15922 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15923 {
15924 	switch (base_type(type)) {
15925 	case PTR_TO_CTX:
15926 	case PTR_TO_SOCKET:
15927 	case PTR_TO_SOCK_COMMON:
15928 	case PTR_TO_TCP_SOCK:
15929 	case PTR_TO_XDP_SOCK:
15930 	case PTR_TO_BTF_ID:
15931 		return false;
15932 	default:
15933 		return true;
15934 	}
15935 }
15936 
15937 /* If an instruction was previously used with particular pointer types, then we
15938  * need to be careful to avoid cases such as the below, where it may be ok
15939  * for one branch accessing the pointer, but not ok for the other branch:
15940  *
15941  * R1 = sock_ptr
15942  * goto X;
15943  * ...
15944  * R1 = some_other_valid_ptr;
15945  * goto X;
15946  * ...
15947  * R2 = *(u32 *)(R1 + 0);
15948  */
15949 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15950 {
15951 	return src != prev && (!reg_type_mismatch_ok(src) ||
15952 			       !reg_type_mismatch_ok(prev));
15953 }
15954 
15955 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15956 			     bool allow_trust_missmatch)
15957 {
15958 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15959 
15960 	if (*prev_type == NOT_INIT) {
15961 		/* Saw a valid insn
15962 		 * dst_reg = *(u32 *)(src_reg + off)
15963 		 * save type to validate intersecting paths
15964 		 */
15965 		*prev_type = type;
15966 	} else if (reg_type_mismatch(type, *prev_type)) {
15967 		/* Abuser program is trying to use the same insn
15968 		 * dst_reg = *(u32*) (src_reg + off)
15969 		 * with different pointer types:
15970 		 * src_reg == ctx in one branch and
15971 		 * src_reg == stack|map in some other branch.
15972 		 * Reject it.
15973 		 */
15974 		if (allow_trust_missmatch &&
15975 		    base_type(type) == PTR_TO_BTF_ID &&
15976 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
15977 			/*
15978 			 * Have to support a use case when one path through
15979 			 * the program yields TRUSTED pointer while another
15980 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
15981 			 * BPF_PROBE_MEM.
15982 			 */
15983 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15984 		} else {
15985 			verbose(env, "same insn cannot be used with different pointers\n");
15986 			return -EINVAL;
15987 		}
15988 	}
15989 
15990 	return 0;
15991 }
15992 
15993 static int do_check(struct bpf_verifier_env *env)
15994 {
15995 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15996 	struct bpf_verifier_state *state = env->cur_state;
15997 	struct bpf_insn *insns = env->prog->insnsi;
15998 	struct bpf_reg_state *regs;
15999 	int insn_cnt = env->prog->len;
16000 	bool do_print_state = false;
16001 	int prev_insn_idx = -1;
16002 
16003 	for (;;) {
16004 		struct bpf_insn *insn;
16005 		u8 class;
16006 		int err;
16007 
16008 		env->prev_insn_idx = prev_insn_idx;
16009 		if (env->insn_idx >= insn_cnt) {
16010 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16011 				env->insn_idx, insn_cnt);
16012 			return -EFAULT;
16013 		}
16014 
16015 		insn = &insns[env->insn_idx];
16016 		class = BPF_CLASS(insn->code);
16017 
16018 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16019 			verbose(env,
16020 				"BPF program is too large. Processed %d insn\n",
16021 				env->insn_processed);
16022 			return -E2BIG;
16023 		}
16024 
16025 		state->last_insn_idx = env->prev_insn_idx;
16026 
16027 		if (is_prune_point(env, env->insn_idx)) {
16028 			err = is_state_visited(env, env->insn_idx);
16029 			if (err < 0)
16030 				return err;
16031 			if (err == 1) {
16032 				/* found equivalent state, can prune the search */
16033 				if (env->log.level & BPF_LOG_LEVEL) {
16034 					if (do_print_state)
16035 						verbose(env, "\nfrom %d to %d%s: safe\n",
16036 							env->prev_insn_idx, env->insn_idx,
16037 							env->cur_state->speculative ?
16038 							" (speculative execution)" : "");
16039 					else
16040 						verbose(env, "%d: safe\n", env->insn_idx);
16041 				}
16042 				goto process_bpf_exit;
16043 			}
16044 		}
16045 
16046 		if (is_jmp_point(env, env->insn_idx)) {
16047 			err = push_jmp_history(env, state);
16048 			if (err)
16049 				return err;
16050 		}
16051 
16052 		if (signal_pending(current))
16053 			return -EAGAIN;
16054 
16055 		if (need_resched())
16056 			cond_resched();
16057 
16058 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16059 			verbose(env, "\nfrom %d to %d%s:",
16060 				env->prev_insn_idx, env->insn_idx,
16061 				env->cur_state->speculative ?
16062 				" (speculative execution)" : "");
16063 			print_verifier_state(env, state->frame[state->curframe], true);
16064 			do_print_state = false;
16065 		}
16066 
16067 		if (env->log.level & BPF_LOG_LEVEL) {
16068 			const struct bpf_insn_cbs cbs = {
16069 				.cb_call	= disasm_kfunc_name,
16070 				.cb_print	= verbose,
16071 				.private_data	= env,
16072 			};
16073 
16074 			if (verifier_state_scratched(env))
16075 				print_insn_state(env, state->frame[state->curframe]);
16076 
16077 			verbose_linfo(env, env->insn_idx, "; ");
16078 			env->prev_log_pos = env->log.end_pos;
16079 			verbose(env, "%d: ", env->insn_idx);
16080 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16081 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16082 			env->prev_log_pos = env->log.end_pos;
16083 		}
16084 
16085 		if (bpf_prog_is_offloaded(env->prog->aux)) {
16086 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16087 							   env->prev_insn_idx);
16088 			if (err)
16089 				return err;
16090 		}
16091 
16092 		regs = cur_regs(env);
16093 		sanitize_mark_insn_seen(env);
16094 		prev_insn_idx = env->insn_idx;
16095 
16096 		if (class == BPF_ALU || class == BPF_ALU64) {
16097 			err = check_alu_op(env, insn);
16098 			if (err)
16099 				return err;
16100 
16101 		} else if (class == BPF_LDX) {
16102 			enum bpf_reg_type src_reg_type;
16103 
16104 			/* check for reserved fields is already done */
16105 
16106 			/* check src operand */
16107 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16108 			if (err)
16109 				return err;
16110 
16111 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16112 			if (err)
16113 				return err;
16114 
16115 			src_reg_type = regs[insn->src_reg].type;
16116 
16117 			/* check that memory (src_reg + off) is readable,
16118 			 * the state of dst_reg will be updated by this func
16119 			 */
16120 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
16121 					       insn->off, BPF_SIZE(insn->code),
16122 					       BPF_READ, insn->dst_reg, false);
16123 			if (err)
16124 				return err;
16125 
16126 			err = save_aux_ptr_type(env, src_reg_type, true);
16127 			if (err)
16128 				return err;
16129 		} else if (class == BPF_STX) {
16130 			enum bpf_reg_type dst_reg_type;
16131 
16132 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16133 				err = check_atomic(env, env->insn_idx, insn);
16134 				if (err)
16135 					return err;
16136 				env->insn_idx++;
16137 				continue;
16138 			}
16139 
16140 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16141 				verbose(env, "BPF_STX uses reserved fields\n");
16142 				return -EINVAL;
16143 			}
16144 
16145 			/* check src1 operand */
16146 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16147 			if (err)
16148 				return err;
16149 			/* check src2 operand */
16150 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16151 			if (err)
16152 				return err;
16153 
16154 			dst_reg_type = regs[insn->dst_reg].type;
16155 
16156 			/* check that memory (dst_reg + off) is writeable */
16157 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16158 					       insn->off, BPF_SIZE(insn->code),
16159 					       BPF_WRITE, insn->src_reg, false);
16160 			if (err)
16161 				return err;
16162 
16163 			err = save_aux_ptr_type(env, dst_reg_type, false);
16164 			if (err)
16165 				return err;
16166 		} else if (class == BPF_ST) {
16167 			enum bpf_reg_type dst_reg_type;
16168 
16169 			if (BPF_MODE(insn->code) != BPF_MEM ||
16170 			    insn->src_reg != BPF_REG_0) {
16171 				verbose(env, "BPF_ST uses reserved fields\n");
16172 				return -EINVAL;
16173 			}
16174 			/* check src operand */
16175 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16176 			if (err)
16177 				return err;
16178 
16179 			dst_reg_type = regs[insn->dst_reg].type;
16180 
16181 			/* check that memory (dst_reg + off) is writeable */
16182 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16183 					       insn->off, BPF_SIZE(insn->code),
16184 					       BPF_WRITE, -1, false);
16185 			if (err)
16186 				return err;
16187 
16188 			err = save_aux_ptr_type(env, dst_reg_type, false);
16189 			if (err)
16190 				return err;
16191 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16192 			u8 opcode = BPF_OP(insn->code);
16193 
16194 			env->jmps_processed++;
16195 			if (opcode == BPF_CALL) {
16196 				if (BPF_SRC(insn->code) != BPF_K ||
16197 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16198 				     && insn->off != 0) ||
16199 				    (insn->src_reg != BPF_REG_0 &&
16200 				     insn->src_reg != BPF_PSEUDO_CALL &&
16201 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16202 				    insn->dst_reg != BPF_REG_0 ||
16203 				    class == BPF_JMP32) {
16204 					verbose(env, "BPF_CALL uses reserved fields\n");
16205 					return -EINVAL;
16206 				}
16207 
16208 				if (env->cur_state->active_lock.ptr) {
16209 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16210 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16211 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16212 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16213 						verbose(env, "function calls are not allowed while holding a lock\n");
16214 						return -EINVAL;
16215 					}
16216 				}
16217 				if (insn->src_reg == BPF_PSEUDO_CALL)
16218 					err = check_func_call(env, insn, &env->insn_idx);
16219 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16220 					err = check_kfunc_call(env, insn, &env->insn_idx);
16221 				else
16222 					err = check_helper_call(env, insn, &env->insn_idx);
16223 				if (err)
16224 					return err;
16225 
16226 				mark_reg_scratched(env, BPF_REG_0);
16227 			} else if (opcode == BPF_JA) {
16228 				if (BPF_SRC(insn->code) != BPF_K ||
16229 				    insn->imm != 0 ||
16230 				    insn->src_reg != BPF_REG_0 ||
16231 				    insn->dst_reg != BPF_REG_0 ||
16232 				    class == BPF_JMP32) {
16233 					verbose(env, "BPF_JA uses reserved fields\n");
16234 					return -EINVAL;
16235 				}
16236 
16237 				env->insn_idx += insn->off + 1;
16238 				continue;
16239 
16240 			} else if (opcode == BPF_EXIT) {
16241 				if (BPF_SRC(insn->code) != BPF_K ||
16242 				    insn->imm != 0 ||
16243 				    insn->src_reg != BPF_REG_0 ||
16244 				    insn->dst_reg != BPF_REG_0 ||
16245 				    class == BPF_JMP32) {
16246 					verbose(env, "BPF_EXIT uses reserved fields\n");
16247 					return -EINVAL;
16248 				}
16249 
16250 				if (env->cur_state->active_lock.ptr &&
16251 				    !in_rbtree_lock_required_cb(env)) {
16252 					verbose(env, "bpf_spin_unlock is missing\n");
16253 					return -EINVAL;
16254 				}
16255 
16256 				if (env->cur_state->active_rcu_lock) {
16257 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16258 					return -EINVAL;
16259 				}
16260 
16261 				/* We must do check_reference_leak here before
16262 				 * prepare_func_exit to handle the case when
16263 				 * state->curframe > 0, it may be a callback
16264 				 * function, for which reference_state must
16265 				 * match caller reference state when it exits.
16266 				 */
16267 				err = check_reference_leak(env);
16268 				if (err)
16269 					return err;
16270 
16271 				if (state->curframe) {
16272 					/* exit from nested function */
16273 					err = prepare_func_exit(env, &env->insn_idx);
16274 					if (err)
16275 						return err;
16276 					do_print_state = true;
16277 					continue;
16278 				}
16279 
16280 				err = check_return_code(env);
16281 				if (err)
16282 					return err;
16283 process_bpf_exit:
16284 				mark_verifier_state_scratched(env);
16285 				update_branch_counts(env, env->cur_state);
16286 				err = pop_stack(env, &prev_insn_idx,
16287 						&env->insn_idx, pop_log);
16288 				if (err < 0) {
16289 					if (err != -ENOENT)
16290 						return err;
16291 					break;
16292 				} else {
16293 					do_print_state = true;
16294 					continue;
16295 				}
16296 			} else {
16297 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16298 				if (err)
16299 					return err;
16300 			}
16301 		} else if (class == BPF_LD) {
16302 			u8 mode = BPF_MODE(insn->code);
16303 
16304 			if (mode == BPF_ABS || mode == BPF_IND) {
16305 				err = check_ld_abs(env, insn);
16306 				if (err)
16307 					return err;
16308 
16309 			} else if (mode == BPF_IMM) {
16310 				err = check_ld_imm(env, insn);
16311 				if (err)
16312 					return err;
16313 
16314 				env->insn_idx++;
16315 				sanitize_mark_insn_seen(env);
16316 			} else {
16317 				verbose(env, "invalid BPF_LD mode\n");
16318 				return -EINVAL;
16319 			}
16320 		} else {
16321 			verbose(env, "unknown insn class %d\n", class);
16322 			return -EINVAL;
16323 		}
16324 
16325 		env->insn_idx++;
16326 	}
16327 
16328 	return 0;
16329 }
16330 
16331 static int find_btf_percpu_datasec(struct btf *btf)
16332 {
16333 	const struct btf_type *t;
16334 	const char *tname;
16335 	int i, n;
16336 
16337 	/*
16338 	 * Both vmlinux and module each have their own ".data..percpu"
16339 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16340 	 * types to look at only module's own BTF types.
16341 	 */
16342 	n = btf_nr_types(btf);
16343 	if (btf_is_module(btf))
16344 		i = btf_nr_types(btf_vmlinux);
16345 	else
16346 		i = 1;
16347 
16348 	for(; i < n; i++) {
16349 		t = btf_type_by_id(btf, i);
16350 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16351 			continue;
16352 
16353 		tname = btf_name_by_offset(btf, t->name_off);
16354 		if (!strcmp(tname, ".data..percpu"))
16355 			return i;
16356 	}
16357 
16358 	return -ENOENT;
16359 }
16360 
16361 /* replace pseudo btf_id with kernel symbol address */
16362 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16363 			       struct bpf_insn *insn,
16364 			       struct bpf_insn_aux_data *aux)
16365 {
16366 	const struct btf_var_secinfo *vsi;
16367 	const struct btf_type *datasec;
16368 	struct btf_mod_pair *btf_mod;
16369 	const struct btf_type *t;
16370 	const char *sym_name;
16371 	bool percpu = false;
16372 	u32 type, id = insn->imm;
16373 	struct btf *btf;
16374 	s32 datasec_id;
16375 	u64 addr;
16376 	int i, btf_fd, err;
16377 
16378 	btf_fd = insn[1].imm;
16379 	if (btf_fd) {
16380 		btf = btf_get_by_fd(btf_fd);
16381 		if (IS_ERR(btf)) {
16382 			verbose(env, "invalid module BTF object FD specified.\n");
16383 			return -EINVAL;
16384 		}
16385 	} else {
16386 		if (!btf_vmlinux) {
16387 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16388 			return -EINVAL;
16389 		}
16390 		btf = btf_vmlinux;
16391 		btf_get(btf);
16392 	}
16393 
16394 	t = btf_type_by_id(btf, id);
16395 	if (!t) {
16396 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16397 		err = -ENOENT;
16398 		goto err_put;
16399 	}
16400 
16401 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16402 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16403 		err = -EINVAL;
16404 		goto err_put;
16405 	}
16406 
16407 	sym_name = btf_name_by_offset(btf, t->name_off);
16408 	addr = kallsyms_lookup_name(sym_name);
16409 	if (!addr) {
16410 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16411 			sym_name);
16412 		err = -ENOENT;
16413 		goto err_put;
16414 	}
16415 	insn[0].imm = (u32)addr;
16416 	insn[1].imm = addr >> 32;
16417 
16418 	if (btf_type_is_func(t)) {
16419 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16420 		aux->btf_var.mem_size = 0;
16421 		goto check_btf;
16422 	}
16423 
16424 	datasec_id = find_btf_percpu_datasec(btf);
16425 	if (datasec_id > 0) {
16426 		datasec = btf_type_by_id(btf, datasec_id);
16427 		for_each_vsi(i, datasec, vsi) {
16428 			if (vsi->type == id) {
16429 				percpu = true;
16430 				break;
16431 			}
16432 		}
16433 	}
16434 
16435 	type = t->type;
16436 	t = btf_type_skip_modifiers(btf, type, NULL);
16437 	if (percpu) {
16438 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16439 		aux->btf_var.btf = btf;
16440 		aux->btf_var.btf_id = type;
16441 	} else if (!btf_type_is_struct(t)) {
16442 		const struct btf_type *ret;
16443 		const char *tname;
16444 		u32 tsize;
16445 
16446 		/* resolve the type size of ksym. */
16447 		ret = btf_resolve_size(btf, t, &tsize);
16448 		if (IS_ERR(ret)) {
16449 			tname = btf_name_by_offset(btf, t->name_off);
16450 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16451 				tname, PTR_ERR(ret));
16452 			err = -EINVAL;
16453 			goto err_put;
16454 		}
16455 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16456 		aux->btf_var.mem_size = tsize;
16457 	} else {
16458 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16459 		aux->btf_var.btf = btf;
16460 		aux->btf_var.btf_id = type;
16461 	}
16462 check_btf:
16463 	/* check whether we recorded this BTF (and maybe module) already */
16464 	for (i = 0; i < env->used_btf_cnt; i++) {
16465 		if (env->used_btfs[i].btf == btf) {
16466 			btf_put(btf);
16467 			return 0;
16468 		}
16469 	}
16470 
16471 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16472 		err = -E2BIG;
16473 		goto err_put;
16474 	}
16475 
16476 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16477 	btf_mod->btf = btf;
16478 	btf_mod->module = NULL;
16479 
16480 	/* if we reference variables from kernel module, bump its refcount */
16481 	if (btf_is_module(btf)) {
16482 		btf_mod->module = btf_try_get_module(btf);
16483 		if (!btf_mod->module) {
16484 			err = -ENXIO;
16485 			goto err_put;
16486 		}
16487 	}
16488 
16489 	env->used_btf_cnt++;
16490 
16491 	return 0;
16492 err_put:
16493 	btf_put(btf);
16494 	return err;
16495 }
16496 
16497 static bool is_tracing_prog_type(enum bpf_prog_type type)
16498 {
16499 	switch (type) {
16500 	case BPF_PROG_TYPE_KPROBE:
16501 	case BPF_PROG_TYPE_TRACEPOINT:
16502 	case BPF_PROG_TYPE_PERF_EVENT:
16503 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16504 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16505 		return true;
16506 	default:
16507 		return false;
16508 	}
16509 }
16510 
16511 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16512 					struct bpf_map *map,
16513 					struct bpf_prog *prog)
16514 
16515 {
16516 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16517 
16518 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16519 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16520 		if (is_tracing_prog_type(prog_type)) {
16521 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16522 			return -EINVAL;
16523 		}
16524 	}
16525 
16526 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16527 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16528 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16529 			return -EINVAL;
16530 		}
16531 
16532 		if (is_tracing_prog_type(prog_type)) {
16533 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16534 			return -EINVAL;
16535 		}
16536 
16537 		if (prog->aux->sleepable) {
16538 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16539 			return -EINVAL;
16540 		}
16541 	}
16542 
16543 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16544 		if (is_tracing_prog_type(prog_type)) {
16545 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16546 			return -EINVAL;
16547 		}
16548 	}
16549 
16550 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16551 	    !bpf_offload_prog_map_match(prog, map)) {
16552 		verbose(env, "offload device mismatch between prog and map\n");
16553 		return -EINVAL;
16554 	}
16555 
16556 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16557 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16558 		return -EINVAL;
16559 	}
16560 
16561 	if (prog->aux->sleepable)
16562 		switch (map->map_type) {
16563 		case BPF_MAP_TYPE_HASH:
16564 		case BPF_MAP_TYPE_LRU_HASH:
16565 		case BPF_MAP_TYPE_ARRAY:
16566 		case BPF_MAP_TYPE_PERCPU_HASH:
16567 		case BPF_MAP_TYPE_PERCPU_ARRAY:
16568 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16569 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16570 		case BPF_MAP_TYPE_HASH_OF_MAPS:
16571 		case BPF_MAP_TYPE_RINGBUF:
16572 		case BPF_MAP_TYPE_USER_RINGBUF:
16573 		case BPF_MAP_TYPE_INODE_STORAGE:
16574 		case BPF_MAP_TYPE_SK_STORAGE:
16575 		case BPF_MAP_TYPE_TASK_STORAGE:
16576 		case BPF_MAP_TYPE_CGRP_STORAGE:
16577 			break;
16578 		default:
16579 			verbose(env,
16580 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16581 			return -EINVAL;
16582 		}
16583 
16584 	return 0;
16585 }
16586 
16587 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16588 {
16589 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16590 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16591 }
16592 
16593 /* find and rewrite pseudo imm in ld_imm64 instructions:
16594  *
16595  * 1. if it accesses map FD, replace it with actual map pointer.
16596  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16597  *
16598  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16599  */
16600 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16601 {
16602 	struct bpf_insn *insn = env->prog->insnsi;
16603 	int insn_cnt = env->prog->len;
16604 	int i, j, err;
16605 
16606 	err = bpf_prog_calc_tag(env->prog);
16607 	if (err)
16608 		return err;
16609 
16610 	for (i = 0; i < insn_cnt; i++, insn++) {
16611 		if (BPF_CLASS(insn->code) == BPF_LDX &&
16612 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16613 			verbose(env, "BPF_LDX uses reserved fields\n");
16614 			return -EINVAL;
16615 		}
16616 
16617 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16618 			struct bpf_insn_aux_data *aux;
16619 			struct bpf_map *map;
16620 			struct fd f;
16621 			u64 addr;
16622 			u32 fd;
16623 
16624 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
16625 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16626 			    insn[1].off != 0) {
16627 				verbose(env, "invalid bpf_ld_imm64 insn\n");
16628 				return -EINVAL;
16629 			}
16630 
16631 			if (insn[0].src_reg == 0)
16632 				/* valid generic load 64-bit imm */
16633 				goto next_insn;
16634 
16635 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16636 				aux = &env->insn_aux_data[i];
16637 				err = check_pseudo_btf_id(env, insn, aux);
16638 				if (err)
16639 					return err;
16640 				goto next_insn;
16641 			}
16642 
16643 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16644 				aux = &env->insn_aux_data[i];
16645 				aux->ptr_type = PTR_TO_FUNC;
16646 				goto next_insn;
16647 			}
16648 
16649 			/* In final convert_pseudo_ld_imm64() step, this is
16650 			 * converted into regular 64-bit imm load insn.
16651 			 */
16652 			switch (insn[0].src_reg) {
16653 			case BPF_PSEUDO_MAP_VALUE:
16654 			case BPF_PSEUDO_MAP_IDX_VALUE:
16655 				break;
16656 			case BPF_PSEUDO_MAP_FD:
16657 			case BPF_PSEUDO_MAP_IDX:
16658 				if (insn[1].imm == 0)
16659 					break;
16660 				fallthrough;
16661 			default:
16662 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16663 				return -EINVAL;
16664 			}
16665 
16666 			switch (insn[0].src_reg) {
16667 			case BPF_PSEUDO_MAP_IDX_VALUE:
16668 			case BPF_PSEUDO_MAP_IDX:
16669 				if (bpfptr_is_null(env->fd_array)) {
16670 					verbose(env, "fd_idx without fd_array is invalid\n");
16671 					return -EPROTO;
16672 				}
16673 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
16674 							    insn[0].imm * sizeof(fd),
16675 							    sizeof(fd)))
16676 					return -EFAULT;
16677 				break;
16678 			default:
16679 				fd = insn[0].imm;
16680 				break;
16681 			}
16682 
16683 			f = fdget(fd);
16684 			map = __bpf_map_get(f);
16685 			if (IS_ERR(map)) {
16686 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
16687 					insn[0].imm);
16688 				return PTR_ERR(map);
16689 			}
16690 
16691 			err = check_map_prog_compatibility(env, map, env->prog);
16692 			if (err) {
16693 				fdput(f);
16694 				return err;
16695 			}
16696 
16697 			aux = &env->insn_aux_data[i];
16698 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16699 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16700 				addr = (unsigned long)map;
16701 			} else {
16702 				u32 off = insn[1].imm;
16703 
16704 				if (off >= BPF_MAX_VAR_OFF) {
16705 					verbose(env, "direct value offset of %u is not allowed\n", off);
16706 					fdput(f);
16707 					return -EINVAL;
16708 				}
16709 
16710 				if (!map->ops->map_direct_value_addr) {
16711 					verbose(env, "no direct value access support for this map type\n");
16712 					fdput(f);
16713 					return -EINVAL;
16714 				}
16715 
16716 				err = map->ops->map_direct_value_addr(map, &addr, off);
16717 				if (err) {
16718 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16719 						map->value_size, off);
16720 					fdput(f);
16721 					return err;
16722 				}
16723 
16724 				aux->map_off = off;
16725 				addr += off;
16726 			}
16727 
16728 			insn[0].imm = (u32)addr;
16729 			insn[1].imm = addr >> 32;
16730 
16731 			/* check whether we recorded this map already */
16732 			for (j = 0; j < env->used_map_cnt; j++) {
16733 				if (env->used_maps[j] == map) {
16734 					aux->map_index = j;
16735 					fdput(f);
16736 					goto next_insn;
16737 				}
16738 			}
16739 
16740 			if (env->used_map_cnt >= MAX_USED_MAPS) {
16741 				fdput(f);
16742 				return -E2BIG;
16743 			}
16744 
16745 			/* hold the map. If the program is rejected by verifier,
16746 			 * the map will be released by release_maps() or it
16747 			 * will be used by the valid program until it's unloaded
16748 			 * and all maps are released in free_used_maps()
16749 			 */
16750 			bpf_map_inc(map);
16751 
16752 			aux->map_index = env->used_map_cnt;
16753 			env->used_maps[env->used_map_cnt++] = map;
16754 
16755 			if (bpf_map_is_cgroup_storage(map) &&
16756 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
16757 				verbose(env, "only one cgroup storage of each type is allowed\n");
16758 				fdput(f);
16759 				return -EBUSY;
16760 			}
16761 
16762 			fdput(f);
16763 next_insn:
16764 			insn++;
16765 			i++;
16766 			continue;
16767 		}
16768 
16769 		/* Basic sanity check before we invest more work here. */
16770 		if (!bpf_opcode_in_insntable(insn->code)) {
16771 			verbose(env, "unknown opcode %02x\n", insn->code);
16772 			return -EINVAL;
16773 		}
16774 	}
16775 
16776 	/* now all pseudo BPF_LD_IMM64 instructions load valid
16777 	 * 'struct bpf_map *' into a register instead of user map_fd.
16778 	 * These pointers will be used later by verifier to validate map access.
16779 	 */
16780 	return 0;
16781 }
16782 
16783 /* drop refcnt of maps used by the rejected program */
16784 static void release_maps(struct bpf_verifier_env *env)
16785 {
16786 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
16787 			     env->used_map_cnt);
16788 }
16789 
16790 /* drop refcnt of maps used by the rejected program */
16791 static void release_btfs(struct bpf_verifier_env *env)
16792 {
16793 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16794 			     env->used_btf_cnt);
16795 }
16796 
16797 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16798 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16799 {
16800 	struct bpf_insn *insn = env->prog->insnsi;
16801 	int insn_cnt = env->prog->len;
16802 	int i;
16803 
16804 	for (i = 0; i < insn_cnt; i++, insn++) {
16805 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16806 			continue;
16807 		if (insn->src_reg == BPF_PSEUDO_FUNC)
16808 			continue;
16809 		insn->src_reg = 0;
16810 	}
16811 }
16812 
16813 /* single env->prog->insni[off] instruction was replaced with the range
16814  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
16815  * [0, off) and [off, end) to new locations, so the patched range stays zero
16816  */
16817 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16818 				 struct bpf_insn_aux_data *new_data,
16819 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
16820 {
16821 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16822 	struct bpf_insn *insn = new_prog->insnsi;
16823 	u32 old_seen = old_data[off].seen;
16824 	u32 prog_len;
16825 	int i;
16826 
16827 	/* aux info at OFF always needs adjustment, no matter fast path
16828 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16829 	 * original insn at old prog.
16830 	 */
16831 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16832 
16833 	if (cnt == 1)
16834 		return;
16835 	prog_len = new_prog->len;
16836 
16837 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16838 	memcpy(new_data + off + cnt - 1, old_data + off,
16839 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16840 	for (i = off; i < off + cnt - 1; i++) {
16841 		/* Expand insni[off]'s seen count to the patched range. */
16842 		new_data[i].seen = old_seen;
16843 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
16844 	}
16845 	env->insn_aux_data = new_data;
16846 	vfree(old_data);
16847 }
16848 
16849 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16850 {
16851 	int i;
16852 
16853 	if (len == 1)
16854 		return;
16855 	/* NOTE: fake 'exit' subprog should be updated as well. */
16856 	for (i = 0; i <= env->subprog_cnt; i++) {
16857 		if (env->subprog_info[i].start <= off)
16858 			continue;
16859 		env->subprog_info[i].start += len - 1;
16860 	}
16861 }
16862 
16863 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16864 {
16865 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16866 	int i, sz = prog->aux->size_poke_tab;
16867 	struct bpf_jit_poke_descriptor *desc;
16868 
16869 	for (i = 0; i < sz; i++) {
16870 		desc = &tab[i];
16871 		if (desc->insn_idx <= off)
16872 			continue;
16873 		desc->insn_idx += len - 1;
16874 	}
16875 }
16876 
16877 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16878 					    const struct bpf_insn *patch, u32 len)
16879 {
16880 	struct bpf_prog *new_prog;
16881 	struct bpf_insn_aux_data *new_data = NULL;
16882 
16883 	if (len > 1) {
16884 		new_data = vzalloc(array_size(env->prog->len + len - 1,
16885 					      sizeof(struct bpf_insn_aux_data)));
16886 		if (!new_data)
16887 			return NULL;
16888 	}
16889 
16890 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
16891 	if (IS_ERR(new_prog)) {
16892 		if (PTR_ERR(new_prog) == -ERANGE)
16893 			verbose(env,
16894 				"insn %d cannot be patched due to 16-bit range\n",
16895 				env->insn_aux_data[off].orig_idx);
16896 		vfree(new_data);
16897 		return NULL;
16898 	}
16899 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
16900 	adjust_subprog_starts(env, off, len);
16901 	adjust_poke_descs(new_prog, off, len);
16902 	return new_prog;
16903 }
16904 
16905 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16906 					      u32 off, u32 cnt)
16907 {
16908 	int i, j;
16909 
16910 	/* find first prog starting at or after off (first to remove) */
16911 	for (i = 0; i < env->subprog_cnt; i++)
16912 		if (env->subprog_info[i].start >= off)
16913 			break;
16914 	/* find first prog starting at or after off + cnt (first to stay) */
16915 	for (j = i; j < env->subprog_cnt; j++)
16916 		if (env->subprog_info[j].start >= off + cnt)
16917 			break;
16918 	/* if j doesn't start exactly at off + cnt, we are just removing
16919 	 * the front of previous prog
16920 	 */
16921 	if (env->subprog_info[j].start != off + cnt)
16922 		j--;
16923 
16924 	if (j > i) {
16925 		struct bpf_prog_aux *aux = env->prog->aux;
16926 		int move;
16927 
16928 		/* move fake 'exit' subprog as well */
16929 		move = env->subprog_cnt + 1 - j;
16930 
16931 		memmove(env->subprog_info + i,
16932 			env->subprog_info + j,
16933 			sizeof(*env->subprog_info) * move);
16934 		env->subprog_cnt -= j - i;
16935 
16936 		/* remove func_info */
16937 		if (aux->func_info) {
16938 			move = aux->func_info_cnt - j;
16939 
16940 			memmove(aux->func_info + i,
16941 				aux->func_info + j,
16942 				sizeof(*aux->func_info) * move);
16943 			aux->func_info_cnt -= j - i;
16944 			/* func_info->insn_off is set after all code rewrites,
16945 			 * in adjust_btf_func() - no need to adjust
16946 			 */
16947 		}
16948 	} else {
16949 		/* convert i from "first prog to remove" to "first to adjust" */
16950 		if (env->subprog_info[i].start == off)
16951 			i++;
16952 	}
16953 
16954 	/* update fake 'exit' subprog as well */
16955 	for (; i <= env->subprog_cnt; i++)
16956 		env->subprog_info[i].start -= cnt;
16957 
16958 	return 0;
16959 }
16960 
16961 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16962 				      u32 cnt)
16963 {
16964 	struct bpf_prog *prog = env->prog;
16965 	u32 i, l_off, l_cnt, nr_linfo;
16966 	struct bpf_line_info *linfo;
16967 
16968 	nr_linfo = prog->aux->nr_linfo;
16969 	if (!nr_linfo)
16970 		return 0;
16971 
16972 	linfo = prog->aux->linfo;
16973 
16974 	/* find first line info to remove, count lines to be removed */
16975 	for (i = 0; i < nr_linfo; i++)
16976 		if (linfo[i].insn_off >= off)
16977 			break;
16978 
16979 	l_off = i;
16980 	l_cnt = 0;
16981 	for (; i < nr_linfo; i++)
16982 		if (linfo[i].insn_off < off + cnt)
16983 			l_cnt++;
16984 		else
16985 			break;
16986 
16987 	/* First live insn doesn't match first live linfo, it needs to "inherit"
16988 	 * last removed linfo.  prog is already modified, so prog->len == off
16989 	 * means no live instructions after (tail of the program was removed).
16990 	 */
16991 	if (prog->len != off && l_cnt &&
16992 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16993 		l_cnt--;
16994 		linfo[--i].insn_off = off + cnt;
16995 	}
16996 
16997 	/* remove the line info which refer to the removed instructions */
16998 	if (l_cnt) {
16999 		memmove(linfo + l_off, linfo + i,
17000 			sizeof(*linfo) * (nr_linfo - i));
17001 
17002 		prog->aux->nr_linfo -= l_cnt;
17003 		nr_linfo = prog->aux->nr_linfo;
17004 	}
17005 
17006 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17007 	for (i = l_off; i < nr_linfo; i++)
17008 		linfo[i].insn_off -= cnt;
17009 
17010 	/* fix up all subprogs (incl. 'exit') which start >= off */
17011 	for (i = 0; i <= env->subprog_cnt; i++)
17012 		if (env->subprog_info[i].linfo_idx > l_off) {
17013 			/* program may have started in the removed region but
17014 			 * may not be fully removed
17015 			 */
17016 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17017 				env->subprog_info[i].linfo_idx -= l_cnt;
17018 			else
17019 				env->subprog_info[i].linfo_idx = l_off;
17020 		}
17021 
17022 	return 0;
17023 }
17024 
17025 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17026 {
17027 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17028 	unsigned int orig_prog_len = env->prog->len;
17029 	int err;
17030 
17031 	if (bpf_prog_is_offloaded(env->prog->aux))
17032 		bpf_prog_offload_remove_insns(env, off, cnt);
17033 
17034 	err = bpf_remove_insns(env->prog, off, cnt);
17035 	if (err)
17036 		return err;
17037 
17038 	err = adjust_subprog_starts_after_remove(env, off, cnt);
17039 	if (err)
17040 		return err;
17041 
17042 	err = bpf_adj_linfo_after_remove(env, off, cnt);
17043 	if (err)
17044 		return err;
17045 
17046 	memmove(aux_data + off,	aux_data + off + cnt,
17047 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
17048 
17049 	return 0;
17050 }
17051 
17052 /* The verifier does more data flow analysis than llvm and will not
17053  * explore branches that are dead at run time. Malicious programs can
17054  * have dead code too. Therefore replace all dead at-run-time code
17055  * with 'ja -1'.
17056  *
17057  * Just nops are not optimal, e.g. if they would sit at the end of the
17058  * program and through another bug we would manage to jump there, then
17059  * we'd execute beyond program memory otherwise. Returning exception
17060  * code also wouldn't work since we can have subprogs where the dead
17061  * code could be located.
17062  */
17063 static void sanitize_dead_code(struct bpf_verifier_env *env)
17064 {
17065 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17066 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17067 	struct bpf_insn *insn = env->prog->insnsi;
17068 	const int insn_cnt = env->prog->len;
17069 	int i;
17070 
17071 	for (i = 0; i < insn_cnt; i++) {
17072 		if (aux_data[i].seen)
17073 			continue;
17074 		memcpy(insn + i, &trap, sizeof(trap));
17075 		aux_data[i].zext_dst = false;
17076 	}
17077 }
17078 
17079 static bool insn_is_cond_jump(u8 code)
17080 {
17081 	u8 op;
17082 
17083 	if (BPF_CLASS(code) == BPF_JMP32)
17084 		return true;
17085 
17086 	if (BPF_CLASS(code) != BPF_JMP)
17087 		return false;
17088 
17089 	op = BPF_OP(code);
17090 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17091 }
17092 
17093 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17094 {
17095 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17096 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17097 	struct bpf_insn *insn = env->prog->insnsi;
17098 	const int insn_cnt = env->prog->len;
17099 	int i;
17100 
17101 	for (i = 0; i < insn_cnt; i++, insn++) {
17102 		if (!insn_is_cond_jump(insn->code))
17103 			continue;
17104 
17105 		if (!aux_data[i + 1].seen)
17106 			ja.off = insn->off;
17107 		else if (!aux_data[i + 1 + insn->off].seen)
17108 			ja.off = 0;
17109 		else
17110 			continue;
17111 
17112 		if (bpf_prog_is_offloaded(env->prog->aux))
17113 			bpf_prog_offload_replace_insn(env, i, &ja);
17114 
17115 		memcpy(insn, &ja, sizeof(ja));
17116 	}
17117 }
17118 
17119 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17120 {
17121 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17122 	int insn_cnt = env->prog->len;
17123 	int i, err;
17124 
17125 	for (i = 0; i < insn_cnt; i++) {
17126 		int j;
17127 
17128 		j = 0;
17129 		while (i + j < insn_cnt && !aux_data[i + j].seen)
17130 			j++;
17131 		if (!j)
17132 			continue;
17133 
17134 		err = verifier_remove_insns(env, i, j);
17135 		if (err)
17136 			return err;
17137 		insn_cnt = env->prog->len;
17138 	}
17139 
17140 	return 0;
17141 }
17142 
17143 static int opt_remove_nops(struct bpf_verifier_env *env)
17144 {
17145 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17146 	struct bpf_insn *insn = env->prog->insnsi;
17147 	int insn_cnt = env->prog->len;
17148 	int i, err;
17149 
17150 	for (i = 0; i < insn_cnt; i++) {
17151 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17152 			continue;
17153 
17154 		err = verifier_remove_insns(env, i, 1);
17155 		if (err)
17156 			return err;
17157 		insn_cnt--;
17158 		i--;
17159 	}
17160 
17161 	return 0;
17162 }
17163 
17164 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17165 					 const union bpf_attr *attr)
17166 {
17167 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17168 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17169 	int i, patch_len, delta = 0, len = env->prog->len;
17170 	struct bpf_insn *insns = env->prog->insnsi;
17171 	struct bpf_prog *new_prog;
17172 	bool rnd_hi32;
17173 
17174 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17175 	zext_patch[1] = BPF_ZEXT_REG(0);
17176 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17177 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17178 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17179 	for (i = 0; i < len; i++) {
17180 		int adj_idx = i + delta;
17181 		struct bpf_insn insn;
17182 		int load_reg;
17183 
17184 		insn = insns[adj_idx];
17185 		load_reg = insn_def_regno(&insn);
17186 		if (!aux[adj_idx].zext_dst) {
17187 			u8 code, class;
17188 			u32 imm_rnd;
17189 
17190 			if (!rnd_hi32)
17191 				continue;
17192 
17193 			code = insn.code;
17194 			class = BPF_CLASS(code);
17195 			if (load_reg == -1)
17196 				continue;
17197 
17198 			/* NOTE: arg "reg" (the fourth one) is only used for
17199 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17200 			 *       here.
17201 			 */
17202 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17203 				if (class == BPF_LD &&
17204 				    BPF_MODE(code) == BPF_IMM)
17205 					i++;
17206 				continue;
17207 			}
17208 
17209 			/* ctx load could be transformed into wider load. */
17210 			if (class == BPF_LDX &&
17211 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17212 				continue;
17213 
17214 			imm_rnd = get_random_u32();
17215 			rnd_hi32_patch[0] = insn;
17216 			rnd_hi32_patch[1].imm = imm_rnd;
17217 			rnd_hi32_patch[3].dst_reg = load_reg;
17218 			patch = rnd_hi32_patch;
17219 			patch_len = 4;
17220 			goto apply_patch_buffer;
17221 		}
17222 
17223 		/* Add in an zero-extend instruction if a) the JIT has requested
17224 		 * it or b) it's a CMPXCHG.
17225 		 *
17226 		 * The latter is because: BPF_CMPXCHG always loads a value into
17227 		 * R0, therefore always zero-extends. However some archs'
17228 		 * equivalent instruction only does this load when the
17229 		 * comparison is successful. This detail of CMPXCHG is
17230 		 * orthogonal to the general zero-extension behaviour of the
17231 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17232 		 */
17233 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17234 			continue;
17235 
17236 		/* Zero-extension is done by the caller. */
17237 		if (bpf_pseudo_kfunc_call(&insn))
17238 			continue;
17239 
17240 		if (WARN_ON(load_reg == -1)) {
17241 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17242 			return -EFAULT;
17243 		}
17244 
17245 		zext_patch[0] = insn;
17246 		zext_patch[1].dst_reg = load_reg;
17247 		zext_patch[1].src_reg = load_reg;
17248 		patch = zext_patch;
17249 		patch_len = 2;
17250 apply_patch_buffer:
17251 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17252 		if (!new_prog)
17253 			return -ENOMEM;
17254 		env->prog = new_prog;
17255 		insns = new_prog->insnsi;
17256 		aux = env->insn_aux_data;
17257 		delta += patch_len - 1;
17258 	}
17259 
17260 	return 0;
17261 }
17262 
17263 /* convert load instructions that access fields of a context type into a
17264  * sequence of instructions that access fields of the underlying structure:
17265  *     struct __sk_buff    -> struct sk_buff
17266  *     struct bpf_sock_ops -> struct sock
17267  */
17268 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17269 {
17270 	const struct bpf_verifier_ops *ops = env->ops;
17271 	int i, cnt, size, ctx_field_size, delta = 0;
17272 	const int insn_cnt = env->prog->len;
17273 	struct bpf_insn insn_buf[16], *insn;
17274 	u32 target_size, size_default, off;
17275 	struct bpf_prog *new_prog;
17276 	enum bpf_access_type type;
17277 	bool is_narrower_load;
17278 
17279 	if (ops->gen_prologue || env->seen_direct_write) {
17280 		if (!ops->gen_prologue) {
17281 			verbose(env, "bpf verifier is misconfigured\n");
17282 			return -EINVAL;
17283 		}
17284 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17285 					env->prog);
17286 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17287 			verbose(env, "bpf verifier is misconfigured\n");
17288 			return -EINVAL;
17289 		} else if (cnt) {
17290 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17291 			if (!new_prog)
17292 				return -ENOMEM;
17293 
17294 			env->prog = new_prog;
17295 			delta += cnt - 1;
17296 		}
17297 	}
17298 
17299 	if (bpf_prog_is_offloaded(env->prog->aux))
17300 		return 0;
17301 
17302 	insn = env->prog->insnsi + delta;
17303 
17304 	for (i = 0; i < insn_cnt; i++, insn++) {
17305 		bpf_convert_ctx_access_t convert_ctx_access;
17306 
17307 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17308 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17309 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17310 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17311 			type = BPF_READ;
17312 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17313 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17314 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17315 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17316 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17317 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17318 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17319 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17320 			type = BPF_WRITE;
17321 		} else {
17322 			continue;
17323 		}
17324 
17325 		if (type == BPF_WRITE &&
17326 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17327 			struct bpf_insn patch[] = {
17328 				*insn,
17329 				BPF_ST_NOSPEC(),
17330 			};
17331 
17332 			cnt = ARRAY_SIZE(patch);
17333 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17334 			if (!new_prog)
17335 				return -ENOMEM;
17336 
17337 			delta    += cnt - 1;
17338 			env->prog = new_prog;
17339 			insn      = new_prog->insnsi + i + delta;
17340 			continue;
17341 		}
17342 
17343 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17344 		case PTR_TO_CTX:
17345 			if (!ops->convert_ctx_access)
17346 				continue;
17347 			convert_ctx_access = ops->convert_ctx_access;
17348 			break;
17349 		case PTR_TO_SOCKET:
17350 		case PTR_TO_SOCK_COMMON:
17351 			convert_ctx_access = bpf_sock_convert_ctx_access;
17352 			break;
17353 		case PTR_TO_TCP_SOCK:
17354 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17355 			break;
17356 		case PTR_TO_XDP_SOCK:
17357 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17358 			break;
17359 		case PTR_TO_BTF_ID:
17360 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17361 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17362 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17363 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17364 		 * any faults for loads into such types. BPF_WRITE is disallowed
17365 		 * for this case.
17366 		 */
17367 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17368 			if (type == BPF_READ) {
17369 				insn->code = BPF_LDX | BPF_PROBE_MEM |
17370 					BPF_SIZE((insn)->code);
17371 				env->prog->aux->num_exentries++;
17372 			}
17373 			continue;
17374 		default:
17375 			continue;
17376 		}
17377 
17378 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17379 		size = BPF_LDST_BYTES(insn);
17380 
17381 		/* If the read access is a narrower load of the field,
17382 		 * convert to a 4/8-byte load, to minimum program type specific
17383 		 * convert_ctx_access changes. If conversion is successful,
17384 		 * we will apply proper mask to the result.
17385 		 */
17386 		is_narrower_load = size < ctx_field_size;
17387 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17388 		off = insn->off;
17389 		if (is_narrower_load) {
17390 			u8 size_code;
17391 
17392 			if (type == BPF_WRITE) {
17393 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17394 				return -EINVAL;
17395 			}
17396 
17397 			size_code = BPF_H;
17398 			if (ctx_field_size == 4)
17399 				size_code = BPF_W;
17400 			else if (ctx_field_size == 8)
17401 				size_code = BPF_DW;
17402 
17403 			insn->off = off & ~(size_default - 1);
17404 			insn->code = BPF_LDX | BPF_MEM | size_code;
17405 		}
17406 
17407 		target_size = 0;
17408 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17409 					 &target_size);
17410 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17411 		    (ctx_field_size && !target_size)) {
17412 			verbose(env, "bpf verifier is misconfigured\n");
17413 			return -EINVAL;
17414 		}
17415 
17416 		if (is_narrower_load && size < target_size) {
17417 			u8 shift = bpf_ctx_narrow_access_offset(
17418 				off, size, size_default) * 8;
17419 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17420 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17421 				return -EINVAL;
17422 			}
17423 			if (ctx_field_size <= 4) {
17424 				if (shift)
17425 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17426 									insn->dst_reg,
17427 									shift);
17428 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17429 								(1 << size * 8) - 1);
17430 			} else {
17431 				if (shift)
17432 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17433 									insn->dst_reg,
17434 									shift);
17435 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17436 								(1ULL << size * 8) - 1);
17437 			}
17438 		}
17439 
17440 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17441 		if (!new_prog)
17442 			return -ENOMEM;
17443 
17444 		delta += cnt - 1;
17445 
17446 		/* keep walking new program and skip insns we just inserted */
17447 		env->prog = new_prog;
17448 		insn      = new_prog->insnsi + i + delta;
17449 	}
17450 
17451 	return 0;
17452 }
17453 
17454 static int jit_subprogs(struct bpf_verifier_env *env)
17455 {
17456 	struct bpf_prog *prog = env->prog, **func, *tmp;
17457 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17458 	struct bpf_map *map_ptr;
17459 	struct bpf_insn *insn;
17460 	void *old_bpf_func;
17461 	int err, num_exentries;
17462 
17463 	if (env->subprog_cnt <= 1)
17464 		return 0;
17465 
17466 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17467 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17468 			continue;
17469 
17470 		/* Upon error here we cannot fall back to interpreter but
17471 		 * need a hard reject of the program. Thus -EFAULT is
17472 		 * propagated in any case.
17473 		 */
17474 		subprog = find_subprog(env, i + insn->imm + 1);
17475 		if (subprog < 0) {
17476 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17477 				  i + insn->imm + 1);
17478 			return -EFAULT;
17479 		}
17480 		/* temporarily remember subprog id inside insn instead of
17481 		 * aux_data, since next loop will split up all insns into funcs
17482 		 */
17483 		insn->off = subprog;
17484 		/* remember original imm in case JIT fails and fallback
17485 		 * to interpreter will be needed
17486 		 */
17487 		env->insn_aux_data[i].call_imm = insn->imm;
17488 		/* point imm to __bpf_call_base+1 from JITs point of view */
17489 		insn->imm = 1;
17490 		if (bpf_pseudo_func(insn))
17491 			/* jit (e.g. x86_64) may emit fewer instructions
17492 			 * if it learns a u32 imm is the same as a u64 imm.
17493 			 * Force a non zero here.
17494 			 */
17495 			insn[1].imm = 1;
17496 	}
17497 
17498 	err = bpf_prog_alloc_jited_linfo(prog);
17499 	if (err)
17500 		goto out_undo_insn;
17501 
17502 	err = -ENOMEM;
17503 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17504 	if (!func)
17505 		goto out_undo_insn;
17506 
17507 	for (i = 0; i < env->subprog_cnt; i++) {
17508 		subprog_start = subprog_end;
17509 		subprog_end = env->subprog_info[i + 1].start;
17510 
17511 		len = subprog_end - subprog_start;
17512 		/* bpf_prog_run() doesn't call subprogs directly,
17513 		 * hence main prog stats include the runtime of subprogs.
17514 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17515 		 * func[i]->stats will never be accessed and stays NULL
17516 		 */
17517 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17518 		if (!func[i])
17519 			goto out_free;
17520 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17521 		       len * sizeof(struct bpf_insn));
17522 		func[i]->type = prog->type;
17523 		func[i]->len = len;
17524 		if (bpf_prog_calc_tag(func[i]))
17525 			goto out_free;
17526 		func[i]->is_func = 1;
17527 		func[i]->aux->func_idx = i;
17528 		/* Below members will be freed only at prog->aux */
17529 		func[i]->aux->btf = prog->aux->btf;
17530 		func[i]->aux->func_info = prog->aux->func_info;
17531 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17532 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17533 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17534 
17535 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17536 			struct bpf_jit_poke_descriptor *poke;
17537 
17538 			poke = &prog->aux->poke_tab[j];
17539 			if (poke->insn_idx < subprog_end &&
17540 			    poke->insn_idx >= subprog_start)
17541 				poke->aux = func[i]->aux;
17542 		}
17543 
17544 		func[i]->aux->name[0] = 'F';
17545 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17546 		func[i]->jit_requested = 1;
17547 		func[i]->blinding_requested = prog->blinding_requested;
17548 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17549 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17550 		func[i]->aux->linfo = prog->aux->linfo;
17551 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17552 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17553 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17554 		num_exentries = 0;
17555 		insn = func[i]->insnsi;
17556 		for (j = 0; j < func[i]->len; j++, insn++) {
17557 			if (BPF_CLASS(insn->code) == BPF_LDX &&
17558 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
17559 				num_exentries++;
17560 		}
17561 		func[i]->aux->num_exentries = num_exentries;
17562 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17563 		func[i] = bpf_int_jit_compile(func[i]);
17564 		if (!func[i]->jited) {
17565 			err = -ENOTSUPP;
17566 			goto out_free;
17567 		}
17568 		cond_resched();
17569 	}
17570 
17571 	/* at this point all bpf functions were successfully JITed
17572 	 * now populate all bpf_calls with correct addresses and
17573 	 * run last pass of JIT
17574 	 */
17575 	for (i = 0; i < env->subprog_cnt; i++) {
17576 		insn = func[i]->insnsi;
17577 		for (j = 0; j < func[i]->len; j++, insn++) {
17578 			if (bpf_pseudo_func(insn)) {
17579 				subprog = insn->off;
17580 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17581 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17582 				continue;
17583 			}
17584 			if (!bpf_pseudo_call(insn))
17585 				continue;
17586 			subprog = insn->off;
17587 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17588 		}
17589 
17590 		/* we use the aux data to keep a list of the start addresses
17591 		 * of the JITed images for each function in the program
17592 		 *
17593 		 * for some architectures, such as powerpc64, the imm field
17594 		 * might not be large enough to hold the offset of the start
17595 		 * address of the callee's JITed image from __bpf_call_base
17596 		 *
17597 		 * in such cases, we can lookup the start address of a callee
17598 		 * by using its subprog id, available from the off field of
17599 		 * the call instruction, as an index for this list
17600 		 */
17601 		func[i]->aux->func = func;
17602 		func[i]->aux->func_cnt = env->subprog_cnt;
17603 	}
17604 	for (i = 0; i < env->subprog_cnt; i++) {
17605 		old_bpf_func = func[i]->bpf_func;
17606 		tmp = bpf_int_jit_compile(func[i]);
17607 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17608 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17609 			err = -ENOTSUPP;
17610 			goto out_free;
17611 		}
17612 		cond_resched();
17613 	}
17614 
17615 	/* finally lock prog and jit images for all functions and
17616 	 * populate kallsysm
17617 	 */
17618 	for (i = 0; i < env->subprog_cnt; i++) {
17619 		bpf_prog_lock_ro(func[i]);
17620 		bpf_prog_kallsyms_add(func[i]);
17621 	}
17622 
17623 	/* Last step: make now unused interpreter insns from main
17624 	 * prog consistent for later dump requests, so they can
17625 	 * later look the same as if they were interpreted only.
17626 	 */
17627 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17628 		if (bpf_pseudo_func(insn)) {
17629 			insn[0].imm = env->insn_aux_data[i].call_imm;
17630 			insn[1].imm = insn->off;
17631 			insn->off = 0;
17632 			continue;
17633 		}
17634 		if (!bpf_pseudo_call(insn))
17635 			continue;
17636 		insn->off = env->insn_aux_data[i].call_imm;
17637 		subprog = find_subprog(env, i + insn->off + 1);
17638 		insn->imm = subprog;
17639 	}
17640 
17641 	prog->jited = 1;
17642 	prog->bpf_func = func[0]->bpf_func;
17643 	prog->jited_len = func[0]->jited_len;
17644 	prog->aux->func = func;
17645 	prog->aux->func_cnt = env->subprog_cnt;
17646 	bpf_prog_jit_attempt_done(prog);
17647 	return 0;
17648 out_free:
17649 	/* We failed JIT'ing, so at this point we need to unregister poke
17650 	 * descriptors from subprogs, so that kernel is not attempting to
17651 	 * patch it anymore as we're freeing the subprog JIT memory.
17652 	 */
17653 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17654 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17655 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17656 	}
17657 	/* At this point we're guaranteed that poke descriptors are not
17658 	 * live anymore. We can just unlink its descriptor table as it's
17659 	 * released with the main prog.
17660 	 */
17661 	for (i = 0; i < env->subprog_cnt; i++) {
17662 		if (!func[i])
17663 			continue;
17664 		func[i]->aux->poke_tab = NULL;
17665 		bpf_jit_free(func[i]);
17666 	}
17667 	kfree(func);
17668 out_undo_insn:
17669 	/* cleanup main prog to be interpreted */
17670 	prog->jit_requested = 0;
17671 	prog->blinding_requested = 0;
17672 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17673 		if (!bpf_pseudo_call(insn))
17674 			continue;
17675 		insn->off = 0;
17676 		insn->imm = env->insn_aux_data[i].call_imm;
17677 	}
17678 	bpf_prog_jit_attempt_done(prog);
17679 	return err;
17680 }
17681 
17682 static int fixup_call_args(struct bpf_verifier_env *env)
17683 {
17684 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17685 	struct bpf_prog *prog = env->prog;
17686 	struct bpf_insn *insn = prog->insnsi;
17687 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17688 	int i, depth;
17689 #endif
17690 	int err = 0;
17691 
17692 	if (env->prog->jit_requested &&
17693 	    !bpf_prog_is_offloaded(env->prog->aux)) {
17694 		err = jit_subprogs(env);
17695 		if (err == 0)
17696 			return 0;
17697 		if (err == -EFAULT)
17698 			return err;
17699 	}
17700 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17701 	if (has_kfunc_call) {
17702 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17703 		return -EINVAL;
17704 	}
17705 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17706 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
17707 		 * have to be rejected, since interpreter doesn't support them yet.
17708 		 */
17709 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17710 		return -EINVAL;
17711 	}
17712 	for (i = 0; i < prog->len; i++, insn++) {
17713 		if (bpf_pseudo_func(insn)) {
17714 			/* When JIT fails the progs with callback calls
17715 			 * have to be rejected, since interpreter doesn't support them yet.
17716 			 */
17717 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
17718 			return -EINVAL;
17719 		}
17720 
17721 		if (!bpf_pseudo_call(insn))
17722 			continue;
17723 		depth = get_callee_stack_depth(env, insn, i);
17724 		if (depth < 0)
17725 			return depth;
17726 		bpf_patch_call_args(insn, depth);
17727 	}
17728 	err = 0;
17729 #endif
17730 	return err;
17731 }
17732 
17733 /* replace a generic kfunc with a specialized version if necessary */
17734 static void specialize_kfunc(struct bpf_verifier_env *env,
17735 			     u32 func_id, u16 offset, unsigned long *addr)
17736 {
17737 	struct bpf_prog *prog = env->prog;
17738 	bool seen_direct_write;
17739 	void *xdp_kfunc;
17740 	bool is_rdonly;
17741 
17742 	if (bpf_dev_bound_kfunc_id(func_id)) {
17743 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17744 		if (xdp_kfunc) {
17745 			*addr = (unsigned long)xdp_kfunc;
17746 			return;
17747 		}
17748 		/* fallback to default kfunc when not supported by netdev */
17749 	}
17750 
17751 	if (offset)
17752 		return;
17753 
17754 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17755 		seen_direct_write = env->seen_direct_write;
17756 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17757 
17758 		if (is_rdonly)
17759 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17760 
17761 		/* restore env->seen_direct_write to its original value, since
17762 		 * may_access_direct_pkt_data mutates it
17763 		 */
17764 		env->seen_direct_write = seen_direct_write;
17765 	}
17766 }
17767 
17768 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17769 					    u16 struct_meta_reg,
17770 					    u16 node_offset_reg,
17771 					    struct bpf_insn *insn,
17772 					    struct bpf_insn *insn_buf,
17773 					    int *cnt)
17774 {
17775 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17776 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17777 
17778 	insn_buf[0] = addr[0];
17779 	insn_buf[1] = addr[1];
17780 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17781 	insn_buf[3] = *insn;
17782 	*cnt = 4;
17783 }
17784 
17785 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17786 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17787 {
17788 	const struct bpf_kfunc_desc *desc;
17789 
17790 	if (!insn->imm) {
17791 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17792 		return -EINVAL;
17793 	}
17794 
17795 	*cnt = 0;
17796 
17797 	/* insn->imm has the btf func_id. Replace it with an offset relative to
17798 	 * __bpf_call_base, unless the JIT needs to call functions that are
17799 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
17800 	 */
17801 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17802 	if (!desc) {
17803 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17804 			insn->imm);
17805 		return -EFAULT;
17806 	}
17807 
17808 	if (!bpf_jit_supports_far_kfunc_call())
17809 		insn->imm = BPF_CALL_IMM(desc->addr);
17810 	if (insn->off)
17811 		return 0;
17812 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17813 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17814 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17815 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17816 
17817 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17818 		insn_buf[1] = addr[0];
17819 		insn_buf[2] = addr[1];
17820 		insn_buf[3] = *insn;
17821 		*cnt = 4;
17822 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
17823 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
17824 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17825 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17826 
17827 		insn_buf[0] = addr[0];
17828 		insn_buf[1] = addr[1];
17829 		insn_buf[2] = *insn;
17830 		*cnt = 3;
17831 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
17832 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
17833 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17834 		int struct_meta_reg = BPF_REG_3;
17835 		int node_offset_reg = BPF_REG_4;
17836 
17837 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
17838 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17839 			struct_meta_reg = BPF_REG_4;
17840 			node_offset_reg = BPF_REG_5;
17841 		}
17842 
17843 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
17844 						node_offset_reg, insn, insn_buf, cnt);
17845 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17846 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17847 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17848 		*cnt = 1;
17849 	}
17850 	return 0;
17851 }
17852 
17853 /* Do various post-verification rewrites in a single program pass.
17854  * These rewrites simplify JIT and interpreter implementations.
17855  */
17856 static int do_misc_fixups(struct bpf_verifier_env *env)
17857 {
17858 	struct bpf_prog *prog = env->prog;
17859 	enum bpf_attach_type eatype = prog->expected_attach_type;
17860 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17861 	struct bpf_insn *insn = prog->insnsi;
17862 	const struct bpf_func_proto *fn;
17863 	const int insn_cnt = prog->len;
17864 	const struct bpf_map_ops *ops;
17865 	struct bpf_insn_aux_data *aux;
17866 	struct bpf_insn insn_buf[16];
17867 	struct bpf_prog *new_prog;
17868 	struct bpf_map *map_ptr;
17869 	int i, ret, cnt, delta = 0;
17870 
17871 	for (i = 0; i < insn_cnt; i++, insn++) {
17872 		/* Make divide-by-zero exceptions impossible. */
17873 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17874 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17875 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
17876 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
17877 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
17878 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17879 			struct bpf_insn *patchlet;
17880 			struct bpf_insn chk_and_div[] = {
17881 				/* [R,W]x div 0 -> 0 */
17882 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17883 					     BPF_JNE | BPF_K, insn->src_reg,
17884 					     0, 2, 0),
17885 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17886 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17887 				*insn,
17888 			};
17889 			struct bpf_insn chk_and_mod[] = {
17890 				/* [R,W]x mod 0 -> [R,W]x */
17891 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17892 					     BPF_JEQ | BPF_K, insn->src_reg,
17893 					     0, 1 + (is64 ? 0 : 1), 0),
17894 				*insn,
17895 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17896 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
17897 			};
17898 
17899 			patchlet = isdiv ? chk_and_div : chk_and_mod;
17900 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
17901 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
17902 
17903 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
17904 			if (!new_prog)
17905 				return -ENOMEM;
17906 
17907 			delta    += cnt - 1;
17908 			env->prog = prog = new_prog;
17909 			insn      = new_prog->insnsi + i + delta;
17910 			continue;
17911 		}
17912 
17913 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
17914 		if (BPF_CLASS(insn->code) == BPF_LD &&
17915 		    (BPF_MODE(insn->code) == BPF_ABS ||
17916 		     BPF_MODE(insn->code) == BPF_IND)) {
17917 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
17918 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17919 				verbose(env, "bpf verifier is misconfigured\n");
17920 				return -EINVAL;
17921 			}
17922 
17923 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17924 			if (!new_prog)
17925 				return -ENOMEM;
17926 
17927 			delta    += cnt - 1;
17928 			env->prog = prog = new_prog;
17929 			insn      = new_prog->insnsi + i + delta;
17930 			continue;
17931 		}
17932 
17933 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
17934 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17935 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17936 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17937 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
17938 			struct bpf_insn *patch = &insn_buf[0];
17939 			bool issrc, isneg, isimm;
17940 			u32 off_reg;
17941 
17942 			aux = &env->insn_aux_data[i + delta];
17943 			if (!aux->alu_state ||
17944 			    aux->alu_state == BPF_ALU_NON_POINTER)
17945 				continue;
17946 
17947 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17948 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17949 				BPF_ALU_SANITIZE_SRC;
17950 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
17951 
17952 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
17953 			if (isimm) {
17954 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17955 			} else {
17956 				if (isneg)
17957 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17958 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17959 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17960 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17961 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17962 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17963 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17964 			}
17965 			if (!issrc)
17966 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17967 			insn->src_reg = BPF_REG_AX;
17968 			if (isneg)
17969 				insn->code = insn->code == code_add ?
17970 					     code_sub : code_add;
17971 			*patch++ = *insn;
17972 			if (issrc && isneg && !isimm)
17973 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17974 			cnt = patch - insn_buf;
17975 
17976 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17977 			if (!new_prog)
17978 				return -ENOMEM;
17979 
17980 			delta    += cnt - 1;
17981 			env->prog = prog = new_prog;
17982 			insn      = new_prog->insnsi + i + delta;
17983 			continue;
17984 		}
17985 
17986 		if (insn->code != (BPF_JMP | BPF_CALL))
17987 			continue;
17988 		if (insn->src_reg == BPF_PSEUDO_CALL)
17989 			continue;
17990 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17991 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
17992 			if (ret)
17993 				return ret;
17994 			if (cnt == 0)
17995 				continue;
17996 
17997 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17998 			if (!new_prog)
17999 				return -ENOMEM;
18000 
18001 			delta	 += cnt - 1;
18002 			env->prog = prog = new_prog;
18003 			insn	  = new_prog->insnsi + i + delta;
18004 			continue;
18005 		}
18006 
18007 		if (insn->imm == BPF_FUNC_get_route_realm)
18008 			prog->dst_needed = 1;
18009 		if (insn->imm == BPF_FUNC_get_prandom_u32)
18010 			bpf_user_rnd_init_once();
18011 		if (insn->imm == BPF_FUNC_override_return)
18012 			prog->kprobe_override = 1;
18013 		if (insn->imm == BPF_FUNC_tail_call) {
18014 			/* If we tail call into other programs, we
18015 			 * cannot make any assumptions since they can
18016 			 * be replaced dynamically during runtime in
18017 			 * the program array.
18018 			 */
18019 			prog->cb_access = 1;
18020 			if (!allow_tail_call_in_subprogs(env))
18021 				prog->aux->stack_depth = MAX_BPF_STACK;
18022 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18023 
18024 			/* mark bpf_tail_call as different opcode to avoid
18025 			 * conditional branch in the interpreter for every normal
18026 			 * call and to prevent accidental JITing by JIT compiler
18027 			 * that doesn't support bpf_tail_call yet
18028 			 */
18029 			insn->imm = 0;
18030 			insn->code = BPF_JMP | BPF_TAIL_CALL;
18031 
18032 			aux = &env->insn_aux_data[i + delta];
18033 			if (env->bpf_capable && !prog->blinding_requested &&
18034 			    prog->jit_requested &&
18035 			    !bpf_map_key_poisoned(aux) &&
18036 			    !bpf_map_ptr_poisoned(aux) &&
18037 			    !bpf_map_ptr_unpriv(aux)) {
18038 				struct bpf_jit_poke_descriptor desc = {
18039 					.reason = BPF_POKE_REASON_TAIL_CALL,
18040 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18041 					.tail_call.key = bpf_map_key_immediate(aux),
18042 					.insn_idx = i + delta,
18043 				};
18044 
18045 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
18046 				if (ret < 0) {
18047 					verbose(env, "adding tail call poke descriptor failed\n");
18048 					return ret;
18049 				}
18050 
18051 				insn->imm = ret + 1;
18052 				continue;
18053 			}
18054 
18055 			if (!bpf_map_ptr_unpriv(aux))
18056 				continue;
18057 
18058 			/* instead of changing every JIT dealing with tail_call
18059 			 * emit two extra insns:
18060 			 * if (index >= max_entries) goto out;
18061 			 * index &= array->index_mask;
18062 			 * to avoid out-of-bounds cpu speculation
18063 			 */
18064 			if (bpf_map_ptr_poisoned(aux)) {
18065 				verbose(env, "tail_call abusing map_ptr\n");
18066 				return -EINVAL;
18067 			}
18068 
18069 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18070 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18071 						  map_ptr->max_entries, 2);
18072 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18073 						    container_of(map_ptr,
18074 								 struct bpf_array,
18075 								 map)->index_mask);
18076 			insn_buf[2] = *insn;
18077 			cnt = 3;
18078 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18079 			if (!new_prog)
18080 				return -ENOMEM;
18081 
18082 			delta    += cnt - 1;
18083 			env->prog = prog = new_prog;
18084 			insn      = new_prog->insnsi + i + delta;
18085 			continue;
18086 		}
18087 
18088 		if (insn->imm == BPF_FUNC_timer_set_callback) {
18089 			/* The verifier will process callback_fn as many times as necessary
18090 			 * with different maps and the register states prepared by
18091 			 * set_timer_callback_state will be accurate.
18092 			 *
18093 			 * The following use case is valid:
18094 			 *   map1 is shared by prog1, prog2, prog3.
18095 			 *   prog1 calls bpf_timer_init for some map1 elements
18096 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
18097 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
18098 			 *   prog3 calls bpf_timer_start for some map1 elements.
18099 			 *     Those that were not both bpf_timer_init-ed and
18100 			 *     bpf_timer_set_callback-ed will return -EINVAL.
18101 			 */
18102 			struct bpf_insn ld_addrs[2] = {
18103 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18104 			};
18105 
18106 			insn_buf[0] = ld_addrs[0];
18107 			insn_buf[1] = ld_addrs[1];
18108 			insn_buf[2] = *insn;
18109 			cnt = 3;
18110 
18111 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18112 			if (!new_prog)
18113 				return -ENOMEM;
18114 
18115 			delta    += cnt - 1;
18116 			env->prog = prog = new_prog;
18117 			insn      = new_prog->insnsi + i + delta;
18118 			goto patch_call_imm;
18119 		}
18120 
18121 		if (is_storage_get_function(insn->imm)) {
18122 			if (!env->prog->aux->sleepable ||
18123 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
18124 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18125 			else
18126 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18127 			insn_buf[1] = *insn;
18128 			cnt = 2;
18129 
18130 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18131 			if (!new_prog)
18132 				return -ENOMEM;
18133 
18134 			delta += cnt - 1;
18135 			env->prog = prog = new_prog;
18136 			insn = new_prog->insnsi + i + delta;
18137 			goto patch_call_imm;
18138 		}
18139 
18140 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18141 		 * and other inlining handlers are currently limited to 64 bit
18142 		 * only.
18143 		 */
18144 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18145 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
18146 		     insn->imm == BPF_FUNC_map_update_elem ||
18147 		     insn->imm == BPF_FUNC_map_delete_elem ||
18148 		     insn->imm == BPF_FUNC_map_push_elem   ||
18149 		     insn->imm == BPF_FUNC_map_pop_elem    ||
18150 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18151 		     insn->imm == BPF_FUNC_redirect_map    ||
18152 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18153 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18154 			aux = &env->insn_aux_data[i + delta];
18155 			if (bpf_map_ptr_poisoned(aux))
18156 				goto patch_call_imm;
18157 
18158 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18159 			ops = map_ptr->ops;
18160 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18161 			    ops->map_gen_lookup) {
18162 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18163 				if (cnt == -EOPNOTSUPP)
18164 					goto patch_map_ops_generic;
18165 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18166 					verbose(env, "bpf verifier is misconfigured\n");
18167 					return -EINVAL;
18168 				}
18169 
18170 				new_prog = bpf_patch_insn_data(env, i + delta,
18171 							       insn_buf, cnt);
18172 				if (!new_prog)
18173 					return -ENOMEM;
18174 
18175 				delta    += cnt - 1;
18176 				env->prog = prog = new_prog;
18177 				insn      = new_prog->insnsi + i + delta;
18178 				continue;
18179 			}
18180 
18181 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18182 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18183 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18184 				     (long (*)(struct bpf_map *map, void *key))NULL));
18185 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18186 				     (long (*)(struct bpf_map *map, void *key, void *value,
18187 					      u64 flags))NULL));
18188 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18189 				     (long (*)(struct bpf_map *map, void *value,
18190 					      u64 flags))NULL));
18191 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18192 				     (long (*)(struct bpf_map *map, void *value))NULL));
18193 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18194 				     (long (*)(struct bpf_map *map, void *value))NULL));
18195 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18196 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18197 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18198 				     (long (*)(struct bpf_map *map,
18199 					      bpf_callback_t callback_fn,
18200 					      void *callback_ctx,
18201 					      u64 flags))NULL));
18202 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18203 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18204 
18205 patch_map_ops_generic:
18206 			switch (insn->imm) {
18207 			case BPF_FUNC_map_lookup_elem:
18208 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18209 				continue;
18210 			case BPF_FUNC_map_update_elem:
18211 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18212 				continue;
18213 			case BPF_FUNC_map_delete_elem:
18214 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18215 				continue;
18216 			case BPF_FUNC_map_push_elem:
18217 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18218 				continue;
18219 			case BPF_FUNC_map_pop_elem:
18220 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18221 				continue;
18222 			case BPF_FUNC_map_peek_elem:
18223 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18224 				continue;
18225 			case BPF_FUNC_redirect_map:
18226 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18227 				continue;
18228 			case BPF_FUNC_for_each_map_elem:
18229 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18230 				continue;
18231 			case BPF_FUNC_map_lookup_percpu_elem:
18232 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18233 				continue;
18234 			}
18235 
18236 			goto patch_call_imm;
18237 		}
18238 
18239 		/* Implement bpf_jiffies64 inline. */
18240 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18241 		    insn->imm == BPF_FUNC_jiffies64) {
18242 			struct bpf_insn ld_jiffies_addr[2] = {
18243 				BPF_LD_IMM64(BPF_REG_0,
18244 					     (unsigned long)&jiffies),
18245 			};
18246 
18247 			insn_buf[0] = ld_jiffies_addr[0];
18248 			insn_buf[1] = ld_jiffies_addr[1];
18249 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18250 						  BPF_REG_0, 0);
18251 			cnt = 3;
18252 
18253 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18254 						       cnt);
18255 			if (!new_prog)
18256 				return -ENOMEM;
18257 
18258 			delta    += cnt - 1;
18259 			env->prog = prog = new_prog;
18260 			insn      = new_prog->insnsi + i + delta;
18261 			continue;
18262 		}
18263 
18264 		/* Implement bpf_get_func_arg inline. */
18265 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18266 		    insn->imm == BPF_FUNC_get_func_arg) {
18267 			/* Load nr_args from ctx - 8 */
18268 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18269 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18270 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18271 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18272 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18273 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18274 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18275 			insn_buf[7] = BPF_JMP_A(1);
18276 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18277 			cnt = 9;
18278 
18279 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18280 			if (!new_prog)
18281 				return -ENOMEM;
18282 
18283 			delta    += cnt - 1;
18284 			env->prog = prog = new_prog;
18285 			insn      = new_prog->insnsi + i + delta;
18286 			continue;
18287 		}
18288 
18289 		/* Implement bpf_get_func_ret inline. */
18290 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18291 		    insn->imm == BPF_FUNC_get_func_ret) {
18292 			if (eatype == BPF_TRACE_FEXIT ||
18293 			    eatype == BPF_MODIFY_RETURN) {
18294 				/* Load nr_args from ctx - 8 */
18295 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18296 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18297 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18298 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18299 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18300 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18301 				cnt = 6;
18302 			} else {
18303 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18304 				cnt = 1;
18305 			}
18306 
18307 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18308 			if (!new_prog)
18309 				return -ENOMEM;
18310 
18311 			delta    += cnt - 1;
18312 			env->prog = prog = new_prog;
18313 			insn      = new_prog->insnsi + i + delta;
18314 			continue;
18315 		}
18316 
18317 		/* Implement get_func_arg_cnt inline. */
18318 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18319 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18320 			/* Load nr_args from ctx - 8 */
18321 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18322 
18323 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18324 			if (!new_prog)
18325 				return -ENOMEM;
18326 
18327 			env->prog = prog = new_prog;
18328 			insn      = new_prog->insnsi + i + delta;
18329 			continue;
18330 		}
18331 
18332 		/* Implement bpf_get_func_ip inline. */
18333 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18334 		    insn->imm == BPF_FUNC_get_func_ip) {
18335 			/* Load IP address from ctx - 16 */
18336 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18337 
18338 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18339 			if (!new_prog)
18340 				return -ENOMEM;
18341 
18342 			env->prog = prog = new_prog;
18343 			insn      = new_prog->insnsi + i + delta;
18344 			continue;
18345 		}
18346 
18347 patch_call_imm:
18348 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18349 		/* all functions that have prototype and verifier allowed
18350 		 * programs to call them, must be real in-kernel functions
18351 		 */
18352 		if (!fn->func) {
18353 			verbose(env,
18354 				"kernel subsystem misconfigured func %s#%d\n",
18355 				func_id_name(insn->imm), insn->imm);
18356 			return -EFAULT;
18357 		}
18358 		insn->imm = fn->func - __bpf_call_base;
18359 	}
18360 
18361 	/* Since poke tab is now finalized, publish aux to tracker. */
18362 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18363 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18364 		if (!map_ptr->ops->map_poke_track ||
18365 		    !map_ptr->ops->map_poke_untrack ||
18366 		    !map_ptr->ops->map_poke_run) {
18367 			verbose(env, "bpf verifier is misconfigured\n");
18368 			return -EINVAL;
18369 		}
18370 
18371 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18372 		if (ret < 0) {
18373 			verbose(env, "tracking tail call prog failed\n");
18374 			return ret;
18375 		}
18376 	}
18377 
18378 	sort_kfunc_descs_by_imm_off(env->prog);
18379 
18380 	return 0;
18381 }
18382 
18383 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18384 					int position,
18385 					s32 stack_base,
18386 					u32 callback_subprogno,
18387 					u32 *cnt)
18388 {
18389 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18390 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18391 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18392 	int reg_loop_max = BPF_REG_6;
18393 	int reg_loop_cnt = BPF_REG_7;
18394 	int reg_loop_ctx = BPF_REG_8;
18395 
18396 	struct bpf_prog *new_prog;
18397 	u32 callback_start;
18398 	u32 call_insn_offset;
18399 	s32 callback_offset;
18400 
18401 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18402 	 * be careful to modify this code in sync.
18403 	 */
18404 	struct bpf_insn insn_buf[] = {
18405 		/* Return error and jump to the end of the patch if
18406 		 * expected number of iterations is too big.
18407 		 */
18408 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18409 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18410 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18411 		/* spill R6, R7, R8 to use these as loop vars */
18412 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18413 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18414 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18415 		/* initialize loop vars */
18416 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18417 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18418 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18419 		/* loop header,
18420 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18421 		 */
18422 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18423 		/* callback call,
18424 		 * correct callback offset would be set after patching
18425 		 */
18426 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18427 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18428 		BPF_CALL_REL(0),
18429 		/* increment loop counter */
18430 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18431 		/* jump to loop header if callback returned 0 */
18432 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18433 		/* return value of bpf_loop,
18434 		 * set R0 to the number of iterations
18435 		 */
18436 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18437 		/* restore original values of R6, R7, R8 */
18438 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18439 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18440 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18441 	};
18442 
18443 	*cnt = ARRAY_SIZE(insn_buf);
18444 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18445 	if (!new_prog)
18446 		return new_prog;
18447 
18448 	/* callback start is known only after patching */
18449 	callback_start = env->subprog_info[callback_subprogno].start;
18450 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18451 	call_insn_offset = position + 12;
18452 	callback_offset = callback_start - call_insn_offset - 1;
18453 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18454 
18455 	return new_prog;
18456 }
18457 
18458 static bool is_bpf_loop_call(struct bpf_insn *insn)
18459 {
18460 	return insn->code == (BPF_JMP | BPF_CALL) &&
18461 		insn->src_reg == 0 &&
18462 		insn->imm == BPF_FUNC_loop;
18463 }
18464 
18465 /* For all sub-programs in the program (including main) check
18466  * insn_aux_data to see if there are bpf_loop calls that require
18467  * inlining. If such calls are found the calls are replaced with a
18468  * sequence of instructions produced by `inline_bpf_loop` function and
18469  * subprog stack_depth is increased by the size of 3 registers.
18470  * This stack space is used to spill values of the R6, R7, R8.  These
18471  * registers are used to store the loop bound, counter and context
18472  * variables.
18473  */
18474 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18475 {
18476 	struct bpf_subprog_info *subprogs = env->subprog_info;
18477 	int i, cur_subprog = 0, cnt, delta = 0;
18478 	struct bpf_insn *insn = env->prog->insnsi;
18479 	int insn_cnt = env->prog->len;
18480 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18481 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18482 	u16 stack_depth_extra = 0;
18483 
18484 	for (i = 0; i < insn_cnt; i++, insn++) {
18485 		struct bpf_loop_inline_state *inline_state =
18486 			&env->insn_aux_data[i + delta].loop_inline_state;
18487 
18488 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18489 			struct bpf_prog *new_prog;
18490 
18491 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18492 			new_prog = inline_bpf_loop(env,
18493 						   i + delta,
18494 						   -(stack_depth + stack_depth_extra),
18495 						   inline_state->callback_subprogno,
18496 						   &cnt);
18497 			if (!new_prog)
18498 				return -ENOMEM;
18499 
18500 			delta     += cnt - 1;
18501 			env->prog  = new_prog;
18502 			insn       = new_prog->insnsi + i + delta;
18503 		}
18504 
18505 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18506 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18507 			cur_subprog++;
18508 			stack_depth = subprogs[cur_subprog].stack_depth;
18509 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18510 			stack_depth_extra = 0;
18511 		}
18512 	}
18513 
18514 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18515 
18516 	return 0;
18517 }
18518 
18519 static void free_states(struct bpf_verifier_env *env)
18520 {
18521 	struct bpf_verifier_state_list *sl, *sln;
18522 	int i;
18523 
18524 	sl = env->free_list;
18525 	while (sl) {
18526 		sln = sl->next;
18527 		free_verifier_state(&sl->state, false);
18528 		kfree(sl);
18529 		sl = sln;
18530 	}
18531 	env->free_list = NULL;
18532 
18533 	if (!env->explored_states)
18534 		return;
18535 
18536 	for (i = 0; i < state_htab_size(env); i++) {
18537 		sl = env->explored_states[i];
18538 
18539 		while (sl) {
18540 			sln = sl->next;
18541 			free_verifier_state(&sl->state, false);
18542 			kfree(sl);
18543 			sl = sln;
18544 		}
18545 		env->explored_states[i] = NULL;
18546 	}
18547 }
18548 
18549 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18550 {
18551 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18552 	struct bpf_verifier_state *state;
18553 	struct bpf_reg_state *regs;
18554 	int ret, i;
18555 
18556 	env->prev_linfo = NULL;
18557 	env->pass_cnt++;
18558 
18559 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18560 	if (!state)
18561 		return -ENOMEM;
18562 	state->curframe = 0;
18563 	state->speculative = false;
18564 	state->branches = 1;
18565 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18566 	if (!state->frame[0]) {
18567 		kfree(state);
18568 		return -ENOMEM;
18569 	}
18570 	env->cur_state = state;
18571 	init_func_state(env, state->frame[0],
18572 			BPF_MAIN_FUNC /* callsite */,
18573 			0 /* frameno */,
18574 			subprog);
18575 	state->first_insn_idx = env->subprog_info[subprog].start;
18576 	state->last_insn_idx = -1;
18577 
18578 	regs = state->frame[state->curframe]->regs;
18579 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18580 		ret = btf_prepare_func_args(env, subprog, regs);
18581 		if (ret)
18582 			goto out;
18583 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18584 			if (regs[i].type == PTR_TO_CTX)
18585 				mark_reg_known_zero(env, regs, i);
18586 			else if (regs[i].type == SCALAR_VALUE)
18587 				mark_reg_unknown(env, regs, i);
18588 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
18589 				const u32 mem_size = regs[i].mem_size;
18590 
18591 				mark_reg_known_zero(env, regs, i);
18592 				regs[i].mem_size = mem_size;
18593 				regs[i].id = ++env->id_gen;
18594 			}
18595 		}
18596 	} else {
18597 		/* 1st arg to a function */
18598 		regs[BPF_REG_1].type = PTR_TO_CTX;
18599 		mark_reg_known_zero(env, regs, BPF_REG_1);
18600 		ret = btf_check_subprog_arg_match(env, subprog, regs);
18601 		if (ret == -EFAULT)
18602 			/* unlikely verifier bug. abort.
18603 			 * ret == 0 and ret < 0 are sadly acceptable for
18604 			 * main() function due to backward compatibility.
18605 			 * Like socket filter program may be written as:
18606 			 * int bpf_prog(struct pt_regs *ctx)
18607 			 * and never dereference that ctx in the program.
18608 			 * 'struct pt_regs' is a type mismatch for socket
18609 			 * filter that should be using 'struct __sk_buff'.
18610 			 */
18611 			goto out;
18612 	}
18613 
18614 	ret = do_check(env);
18615 out:
18616 	/* check for NULL is necessary, since cur_state can be freed inside
18617 	 * do_check() under memory pressure.
18618 	 */
18619 	if (env->cur_state) {
18620 		free_verifier_state(env->cur_state, true);
18621 		env->cur_state = NULL;
18622 	}
18623 	while (!pop_stack(env, NULL, NULL, false));
18624 	if (!ret && pop_log)
18625 		bpf_vlog_reset(&env->log, 0);
18626 	free_states(env);
18627 	return ret;
18628 }
18629 
18630 /* Verify all global functions in a BPF program one by one based on their BTF.
18631  * All global functions must pass verification. Otherwise the whole program is rejected.
18632  * Consider:
18633  * int bar(int);
18634  * int foo(int f)
18635  * {
18636  *    return bar(f);
18637  * }
18638  * int bar(int b)
18639  * {
18640  *    ...
18641  * }
18642  * foo() will be verified first for R1=any_scalar_value. During verification it
18643  * will be assumed that bar() already verified successfully and call to bar()
18644  * from foo() will be checked for type match only. Later bar() will be verified
18645  * independently to check that it's safe for R1=any_scalar_value.
18646  */
18647 static int do_check_subprogs(struct bpf_verifier_env *env)
18648 {
18649 	struct bpf_prog_aux *aux = env->prog->aux;
18650 	int i, ret;
18651 
18652 	if (!aux->func_info)
18653 		return 0;
18654 
18655 	for (i = 1; i < env->subprog_cnt; i++) {
18656 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18657 			continue;
18658 		env->insn_idx = env->subprog_info[i].start;
18659 		WARN_ON_ONCE(env->insn_idx == 0);
18660 		ret = do_check_common(env, i);
18661 		if (ret) {
18662 			return ret;
18663 		} else if (env->log.level & BPF_LOG_LEVEL) {
18664 			verbose(env,
18665 				"Func#%d is safe for any args that match its prototype\n",
18666 				i);
18667 		}
18668 	}
18669 	return 0;
18670 }
18671 
18672 static int do_check_main(struct bpf_verifier_env *env)
18673 {
18674 	int ret;
18675 
18676 	env->insn_idx = 0;
18677 	ret = do_check_common(env, 0);
18678 	if (!ret)
18679 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18680 	return ret;
18681 }
18682 
18683 
18684 static void print_verification_stats(struct bpf_verifier_env *env)
18685 {
18686 	int i;
18687 
18688 	if (env->log.level & BPF_LOG_STATS) {
18689 		verbose(env, "verification time %lld usec\n",
18690 			div_u64(env->verification_time, 1000));
18691 		verbose(env, "stack depth ");
18692 		for (i = 0; i < env->subprog_cnt; i++) {
18693 			u32 depth = env->subprog_info[i].stack_depth;
18694 
18695 			verbose(env, "%d", depth);
18696 			if (i + 1 < env->subprog_cnt)
18697 				verbose(env, "+");
18698 		}
18699 		verbose(env, "\n");
18700 	}
18701 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18702 		"total_states %d peak_states %d mark_read %d\n",
18703 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18704 		env->max_states_per_insn, env->total_states,
18705 		env->peak_states, env->longest_mark_read_walk);
18706 }
18707 
18708 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18709 {
18710 	const struct btf_type *t, *func_proto;
18711 	const struct bpf_struct_ops *st_ops;
18712 	const struct btf_member *member;
18713 	struct bpf_prog *prog = env->prog;
18714 	u32 btf_id, member_idx;
18715 	const char *mname;
18716 
18717 	if (!prog->gpl_compatible) {
18718 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18719 		return -EINVAL;
18720 	}
18721 
18722 	btf_id = prog->aux->attach_btf_id;
18723 	st_ops = bpf_struct_ops_find(btf_id);
18724 	if (!st_ops) {
18725 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18726 			btf_id);
18727 		return -ENOTSUPP;
18728 	}
18729 
18730 	t = st_ops->type;
18731 	member_idx = prog->expected_attach_type;
18732 	if (member_idx >= btf_type_vlen(t)) {
18733 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18734 			member_idx, st_ops->name);
18735 		return -EINVAL;
18736 	}
18737 
18738 	member = &btf_type_member(t)[member_idx];
18739 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18740 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18741 					       NULL);
18742 	if (!func_proto) {
18743 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18744 			mname, member_idx, st_ops->name);
18745 		return -EINVAL;
18746 	}
18747 
18748 	if (st_ops->check_member) {
18749 		int err = st_ops->check_member(t, member, prog);
18750 
18751 		if (err) {
18752 			verbose(env, "attach to unsupported member %s of struct %s\n",
18753 				mname, st_ops->name);
18754 			return err;
18755 		}
18756 	}
18757 
18758 	prog->aux->attach_func_proto = func_proto;
18759 	prog->aux->attach_func_name = mname;
18760 	env->ops = st_ops->verifier_ops;
18761 
18762 	return 0;
18763 }
18764 #define SECURITY_PREFIX "security_"
18765 
18766 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18767 {
18768 	if (within_error_injection_list(addr) ||
18769 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18770 		return 0;
18771 
18772 	return -EINVAL;
18773 }
18774 
18775 /* list of non-sleepable functions that are otherwise on
18776  * ALLOW_ERROR_INJECTION list
18777  */
18778 BTF_SET_START(btf_non_sleepable_error_inject)
18779 /* Three functions below can be called from sleepable and non-sleepable context.
18780  * Assume non-sleepable from bpf safety point of view.
18781  */
18782 BTF_ID(func, __filemap_add_folio)
18783 BTF_ID(func, should_fail_alloc_page)
18784 BTF_ID(func, should_failslab)
18785 BTF_SET_END(btf_non_sleepable_error_inject)
18786 
18787 static int check_non_sleepable_error_inject(u32 btf_id)
18788 {
18789 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18790 }
18791 
18792 int bpf_check_attach_target(struct bpf_verifier_log *log,
18793 			    const struct bpf_prog *prog,
18794 			    const struct bpf_prog *tgt_prog,
18795 			    u32 btf_id,
18796 			    struct bpf_attach_target_info *tgt_info)
18797 {
18798 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18799 	const char prefix[] = "btf_trace_";
18800 	int ret = 0, subprog = -1, i;
18801 	const struct btf_type *t;
18802 	bool conservative = true;
18803 	const char *tname;
18804 	struct btf *btf;
18805 	long addr = 0;
18806 	struct module *mod = NULL;
18807 
18808 	if (!btf_id) {
18809 		bpf_log(log, "Tracing programs must provide btf_id\n");
18810 		return -EINVAL;
18811 	}
18812 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18813 	if (!btf) {
18814 		bpf_log(log,
18815 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18816 		return -EINVAL;
18817 	}
18818 	t = btf_type_by_id(btf, btf_id);
18819 	if (!t) {
18820 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18821 		return -EINVAL;
18822 	}
18823 	tname = btf_name_by_offset(btf, t->name_off);
18824 	if (!tname) {
18825 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18826 		return -EINVAL;
18827 	}
18828 	if (tgt_prog) {
18829 		struct bpf_prog_aux *aux = tgt_prog->aux;
18830 
18831 		if (bpf_prog_is_dev_bound(prog->aux) &&
18832 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18833 			bpf_log(log, "Target program bound device mismatch");
18834 			return -EINVAL;
18835 		}
18836 
18837 		for (i = 0; i < aux->func_info_cnt; i++)
18838 			if (aux->func_info[i].type_id == btf_id) {
18839 				subprog = i;
18840 				break;
18841 			}
18842 		if (subprog == -1) {
18843 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
18844 			return -EINVAL;
18845 		}
18846 		conservative = aux->func_info_aux[subprog].unreliable;
18847 		if (prog_extension) {
18848 			if (conservative) {
18849 				bpf_log(log,
18850 					"Cannot replace static functions\n");
18851 				return -EINVAL;
18852 			}
18853 			if (!prog->jit_requested) {
18854 				bpf_log(log,
18855 					"Extension programs should be JITed\n");
18856 				return -EINVAL;
18857 			}
18858 		}
18859 		if (!tgt_prog->jited) {
18860 			bpf_log(log, "Can attach to only JITed progs\n");
18861 			return -EINVAL;
18862 		}
18863 		if (tgt_prog->type == prog->type) {
18864 			/* Cannot fentry/fexit another fentry/fexit program.
18865 			 * Cannot attach program extension to another extension.
18866 			 * It's ok to attach fentry/fexit to extension program.
18867 			 */
18868 			bpf_log(log, "Cannot recursively attach\n");
18869 			return -EINVAL;
18870 		}
18871 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18872 		    prog_extension &&
18873 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18874 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18875 			/* Program extensions can extend all program types
18876 			 * except fentry/fexit. The reason is the following.
18877 			 * The fentry/fexit programs are used for performance
18878 			 * analysis, stats and can be attached to any program
18879 			 * type except themselves. When extension program is
18880 			 * replacing XDP function it is necessary to allow
18881 			 * performance analysis of all functions. Both original
18882 			 * XDP program and its program extension. Hence
18883 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18884 			 * allowed. If extending of fentry/fexit was allowed it
18885 			 * would be possible to create long call chain
18886 			 * fentry->extension->fentry->extension beyond
18887 			 * reasonable stack size. Hence extending fentry is not
18888 			 * allowed.
18889 			 */
18890 			bpf_log(log, "Cannot extend fentry/fexit\n");
18891 			return -EINVAL;
18892 		}
18893 	} else {
18894 		if (prog_extension) {
18895 			bpf_log(log, "Cannot replace kernel functions\n");
18896 			return -EINVAL;
18897 		}
18898 	}
18899 
18900 	switch (prog->expected_attach_type) {
18901 	case BPF_TRACE_RAW_TP:
18902 		if (tgt_prog) {
18903 			bpf_log(log,
18904 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18905 			return -EINVAL;
18906 		}
18907 		if (!btf_type_is_typedef(t)) {
18908 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
18909 				btf_id);
18910 			return -EINVAL;
18911 		}
18912 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
18913 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
18914 				btf_id, tname);
18915 			return -EINVAL;
18916 		}
18917 		tname += sizeof(prefix) - 1;
18918 		t = btf_type_by_id(btf, t->type);
18919 		if (!btf_type_is_ptr(t))
18920 			/* should never happen in valid vmlinux build */
18921 			return -EINVAL;
18922 		t = btf_type_by_id(btf, t->type);
18923 		if (!btf_type_is_func_proto(t))
18924 			/* should never happen in valid vmlinux build */
18925 			return -EINVAL;
18926 
18927 		break;
18928 	case BPF_TRACE_ITER:
18929 		if (!btf_type_is_func(t)) {
18930 			bpf_log(log, "attach_btf_id %u is not a function\n",
18931 				btf_id);
18932 			return -EINVAL;
18933 		}
18934 		t = btf_type_by_id(btf, t->type);
18935 		if (!btf_type_is_func_proto(t))
18936 			return -EINVAL;
18937 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18938 		if (ret)
18939 			return ret;
18940 		break;
18941 	default:
18942 		if (!prog_extension)
18943 			return -EINVAL;
18944 		fallthrough;
18945 	case BPF_MODIFY_RETURN:
18946 	case BPF_LSM_MAC:
18947 	case BPF_LSM_CGROUP:
18948 	case BPF_TRACE_FENTRY:
18949 	case BPF_TRACE_FEXIT:
18950 		if (!btf_type_is_func(t)) {
18951 			bpf_log(log, "attach_btf_id %u is not a function\n",
18952 				btf_id);
18953 			return -EINVAL;
18954 		}
18955 		if (prog_extension &&
18956 		    btf_check_type_match(log, prog, btf, t))
18957 			return -EINVAL;
18958 		t = btf_type_by_id(btf, t->type);
18959 		if (!btf_type_is_func_proto(t))
18960 			return -EINVAL;
18961 
18962 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18963 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18964 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18965 			return -EINVAL;
18966 
18967 		if (tgt_prog && conservative)
18968 			t = NULL;
18969 
18970 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18971 		if (ret < 0)
18972 			return ret;
18973 
18974 		if (tgt_prog) {
18975 			if (subprog == 0)
18976 				addr = (long) tgt_prog->bpf_func;
18977 			else
18978 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
18979 		} else {
18980 			if (btf_is_module(btf)) {
18981 				mod = btf_try_get_module(btf);
18982 				if (mod)
18983 					addr = find_kallsyms_symbol_value(mod, tname);
18984 				else
18985 					addr = 0;
18986 			} else {
18987 				addr = kallsyms_lookup_name(tname);
18988 			}
18989 			if (!addr) {
18990 				module_put(mod);
18991 				bpf_log(log,
18992 					"The address of function %s cannot be found\n",
18993 					tname);
18994 				return -ENOENT;
18995 			}
18996 		}
18997 
18998 		if (prog->aux->sleepable) {
18999 			ret = -EINVAL;
19000 			switch (prog->type) {
19001 			case BPF_PROG_TYPE_TRACING:
19002 
19003 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
19004 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19005 				 */
19006 				if (!check_non_sleepable_error_inject(btf_id) &&
19007 				    within_error_injection_list(addr))
19008 					ret = 0;
19009 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
19010 				 * in the fmodret id set with the KF_SLEEPABLE flag.
19011 				 */
19012 				else {
19013 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19014 										prog);
19015 
19016 					if (flags && (*flags & KF_SLEEPABLE))
19017 						ret = 0;
19018 				}
19019 				break;
19020 			case BPF_PROG_TYPE_LSM:
19021 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
19022 				 * Only some of them are sleepable.
19023 				 */
19024 				if (bpf_lsm_is_sleepable_hook(btf_id))
19025 					ret = 0;
19026 				break;
19027 			default:
19028 				break;
19029 			}
19030 			if (ret) {
19031 				module_put(mod);
19032 				bpf_log(log, "%s is not sleepable\n", tname);
19033 				return ret;
19034 			}
19035 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19036 			if (tgt_prog) {
19037 				module_put(mod);
19038 				bpf_log(log, "can't modify return codes of BPF programs\n");
19039 				return -EINVAL;
19040 			}
19041 			ret = -EINVAL;
19042 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19043 			    !check_attach_modify_return(addr, tname))
19044 				ret = 0;
19045 			if (ret) {
19046 				module_put(mod);
19047 				bpf_log(log, "%s() is not modifiable\n", tname);
19048 				return ret;
19049 			}
19050 		}
19051 
19052 		break;
19053 	}
19054 	tgt_info->tgt_addr = addr;
19055 	tgt_info->tgt_name = tname;
19056 	tgt_info->tgt_type = t;
19057 	tgt_info->tgt_mod = mod;
19058 	return 0;
19059 }
19060 
19061 BTF_SET_START(btf_id_deny)
19062 BTF_ID_UNUSED
19063 #ifdef CONFIG_SMP
19064 BTF_ID(func, migrate_disable)
19065 BTF_ID(func, migrate_enable)
19066 #endif
19067 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19068 BTF_ID(func, rcu_read_unlock_strict)
19069 #endif
19070 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19071 BTF_ID(func, preempt_count_add)
19072 BTF_ID(func, preempt_count_sub)
19073 #endif
19074 #ifdef CONFIG_PREEMPT_RCU
19075 BTF_ID(func, __rcu_read_lock)
19076 BTF_ID(func, __rcu_read_unlock)
19077 #endif
19078 BTF_SET_END(btf_id_deny)
19079 
19080 static bool can_be_sleepable(struct bpf_prog *prog)
19081 {
19082 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19083 		switch (prog->expected_attach_type) {
19084 		case BPF_TRACE_FENTRY:
19085 		case BPF_TRACE_FEXIT:
19086 		case BPF_MODIFY_RETURN:
19087 		case BPF_TRACE_ITER:
19088 			return true;
19089 		default:
19090 			return false;
19091 		}
19092 	}
19093 	return prog->type == BPF_PROG_TYPE_LSM ||
19094 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19095 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19096 }
19097 
19098 static int check_attach_btf_id(struct bpf_verifier_env *env)
19099 {
19100 	struct bpf_prog *prog = env->prog;
19101 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19102 	struct bpf_attach_target_info tgt_info = {};
19103 	u32 btf_id = prog->aux->attach_btf_id;
19104 	struct bpf_trampoline *tr;
19105 	int ret;
19106 	u64 key;
19107 
19108 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19109 		if (prog->aux->sleepable)
19110 			/* attach_btf_id checked to be zero already */
19111 			return 0;
19112 		verbose(env, "Syscall programs can only be sleepable\n");
19113 		return -EINVAL;
19114 	}
19115 
19116 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19117 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19118 		return -EINVAL;
19119 	}
19120 
19121 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19122 		return check_struct_ops_btf_id(env);
19123 
19124 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19125 	    prog->type != BPF_PROG_TYPE_LSM &&
19126 	    prog->type != BPF_PROG_TYPE_EXT)
19127 		return 0;
19128 
19129 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19130 	if (ret)
19131 		return ret;
19132 
19133 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19134 		/* to make freplace equivalent to their targets, they need to
19135 		 * inherit env->ops and expected_attach_type for the rest of the
19136 		 * verification
19137 		 */
19138 		env->ops = bpf_verifier_ops[tgt_prog->type];
19139 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19140 	}
19141 
19142 	/* store info about the attachment target that will be used later */
19143 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19144 	prog->aux->attach_func_name = tgt_info.tgt_name;
19145 	prog->aux->mod = tgt_info.tgt_mod;
19146 
19147 	if (tgt_prog) {
19148 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19149 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19150 	}
19151 
19152 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19153 		prog->aux->attach_btf_trace = true;
19154 		return 0;
19155 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19156 		if (!bpf_iter_prog_supported(prog))
19157 			return -EINVAL;
19158 		return 0;
19159 	}
19160 
19161 	if (prog->type == BPF_PROG_TYPE_LSM) {
19162 		ret = bpf_lsm_verify_prog(&env->log, prog);
19163 		if (ret < 0)
19164 			return ret;
19165 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19166 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19167 		return -EINVAL;
19168 	}
19169 
19170 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19171 	tr = bpf_trampoline_get(key, &tgt_info);
19172 	if (!tr)
19173 		return -ENOMEM;
19174 
19175 	prog->aux->dst_trampoline = tr;
19176 	return 0;
19177 }
19178 
19179 struct btf *bpf_get_btf_vmlinux(void)
19180 {
19181 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19182 		mutex_lock(&bpf_verifier_lock);
19183 		if (!btf_vmlinux)
19184 			btf_vmlinux = btf_parse_vmlinux();
19185 		mutex_unlock(&bpf_verifier_lock);
19186 	}
19187 	return btf_vmlinux;
19188 }
19189 
19190 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19191 {
19192 	u64 start_time = ktime_get_ns();
19193 	struct bpf_verifier_env *env;
19194 	int i, len, ret = -EINVAL, err;
19195 	u32 log_true_size;
19196 	bool is_priv;
19197 
19198 	/* no program is valid */
19199 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19200 		return -EINVAL;
19201 
19202 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19203 	 * allocate/free it every time bpf_check() is called
19204 	 */
19205 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19206 	if (!env)
19207 		return -ENOMEM;
19208 
19209 	env->bt.env = env;
19210 
19211 	len = (*prog)->len;
19212 	env->insn_aux_data =
19213 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19214 	ret = -ENOMEM;
19215 	if (!env->insn_aux_data)
19216 		goto err_free_env;
19217 	for (i = 0; i < len; i++)
19218 		env->insn_aux_data[i].orig_idx = i;
19219 	env->prog = *prog;
19220 	env->ops = bpf_verifier_ops[env->prog->type];
19221 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19222 	is_priv = bpf_capable();
19223 
19224 	bpf_get_btf_vmlinux();
19225 
19226 	/* grab the mutex to protect few globals used by verifier */
19227 	if (!is_priv)
19228 		mutex_lock(&bpf_verifier_lock);
19229 
19230 	/* user could have requested verbose verifier output
19231 	 * and supplied buffer to store the verification trace
19232 	 */
19233 	ret = bpf_vlog_init(&env->log, attr->log_level,
19234 			    (char __user *) (unsigned long) attr->log_buf,
19235 			    attr->log_size);
19236 	if (ret)
19237 		goto err_unlock;
19238 
19239 	mark_verifier_state_clean(env);
19240 
19241 	if (IS_ERR(btf_vmlinux)) {
19242 		/* Either gcc or pahole or kernel are broken. */
19243 		verbose(env, "in-kernel BTF is malformed\n");
19244 		ret = PTR_ERR(btf_vmlinux);
19245 		goto skip_full_check;
19246 	}
19247 
19248 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19249 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19250 		env->strict_alignment = true;
19251 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19252 		env->strict_alignment = false;
19253 
19254 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19255 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19256 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19257 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19258 	env->bpf_capable = bpf_capable();
19259 
19260 	if (is_priv)
19261 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19262 
19263 	env->explored_states = kvcalloc(state_htab_size(env),
19264 				       sizeof(struct bpf_verifier_state_list *),
19265 				       GFP_USER);
19266 	ret = -ENOMEM;
19267 	if (!env->explored_states)
19268 		goto skip_full_check;
19269 
19270 	ret = add_subprog_and_kfunc(env);
19271 	if (ret < 0)
19272 		goto skip_full_check;
19273 
19274 	ret = check_subprogs(env);
19275 	if (ret < 0)
19276 		goto skip_full_check;
19277 
19278 	ret = check_btf_info(env, attr, uattr);
19279 	if (ret < 0)
19280 		goto skip_full_check;
19281 
19282 	ret = check_attach_btf_id(env);
19283 	if (ret)
19284 		goto skip_full_check;
19285 
19286 	ret = resolve_pseudo_ldimm64(env);
19287 	if (ret < 0)
19288 		goto skip_full_check;
19289 
19290 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19291 		ret = bpf_prog_offload_verifier_prep(env->prog);
19292 		if (ret)
19293 			goto skip_full_check;
19294 	}
19295 
19296 	ret = check_cfg(env);
19297 	if (ret < 0)
19298 		goto skip_full_check;
19299 
19300 	ret = do_check_subprogs(env);
19301 	ret = ret ?: do_check_main(env);
19302 
19303 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19304 		ret = bpf_prog_offload_finalize(env);
19305 
19306 skip_full_check:
19307 	kvfree(env->explored_states);
19308 
19309 	if (ret == 0)
19310 		ret = check_max_stack_depth(env);
19311 
19312 	/* instruction rewrites happen after this point */
19313 	if (ret == 0)
19314 		ret = optimize_bpf_loop(env);
19315 
19316 	if (is_priv) {
19317 		if (ret == 0)
19318 			opt_hard_wire_dead_code_branches(env);
19319 		if (ret == 0)
19320 			ret = opt_remove_dead_code(env);
19321 		if (ret == 0)
19322 			ret = opt_remove_nops(env);
19323 	} else {
19324 		if (ret == 0)
19325 			sanitize_dead_code(env);
19326 	}
19327 
19328 	if (ret == 0)
19329 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19330 		ret = convert_ctx_accesses(env);
19331 
19332 	if (ret == 0)
19333 		ret = do_misc_fixups(env);
19334 
19335 	/* do 32-bit optimization after insn patching has done so those patched
19336 	 * insns could be handled correctly.
19337 	 */
19338 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19339 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19340 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19341 								     : false;
19342 	}
19343 
19344 	if (ret == 0)
19345 		ret = fixup_call_args(env);
19346 
19347 	env->verification_time = ktime_get_ns() - start_time;
19348 	print_verification_stats(env);
19349 	env->prog->aux->verified_insns = env->insn_processed;
19350 
19351 	/* preserve original error even if log finalization is successful */
19352 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19353 	if (err)
19354 		ret = err;
19355 
19356 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19357 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19358 				  &log_true_size, sizeof(log_true_size))) {
19359 		ret = -EFAULT;
19360 		goto err_release_maps;
19361 	}
19362 
19363 	if (ret)
19364 		goto err_release_maps;
19365 
19366 	if (env->used_map_cnt) {
19367 		/* if program passed verifier, update used_maps in bpf_prog_info */
19368 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19369 							  sizeof(env->used_maps[0]),
19370 							  GFP_KERNEL);
19371 
19372 		if (!env->prog->aux->used_maps) {
19373 			ret = -ENOMEM;
19374 			goto err_release_maps;
19375 		}
19376 
19377 		memcpy(env->prog->aux->used_maps, env->used_maps,
19378 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19379 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19380 	}
19381 	if (env->used_btf_cnt) {
19382 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19383 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19384 							  sizeof(env->used_btfs[0]),
19385 							  GFP_KERNEL);
19386 		if (!env->prog->aux->used_btfs) {
19387 			ret = -ENOMEM;
19388 			goto err_release_maps;
19389 		}
19390 
19391 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19392 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19393 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19394 	}
19395 	if (env->used_map_cnt || env->used_btf_cnt) {
19396 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19397 		 * bpf_ld_imm64 instructions
19398 		 */
19399 		convert_pseudo_ld_imm64(env);
19400 	}
19401 
19402 	adjust_btf_func(env);
19403 
19404 err_release_maps:
19405 	if (!env->prog->aux->used_maps)
19406 		/* if we didn't copy map pointers into bpf_prog_info, release
19407 		 * them now. Otherwise free_used_maps() will release them.
19408 		 */
19409 		release_maps(env);
19410 	if (!env->prog->aux->used_btfs)
19411 		release_btfs(env);
19412 
19413 	/* extension progs temporarily inherit the attach_type of their targets
19414 	   for verification purposes, so set it back to zero before returning
19415 	 */
19416 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19417 		env->prog->expected_attach_type = 0;
19418 
19419 	*prog = env->prog;
19420 err_unlock:
19421 	if (!is_priv)
19422 		mutex_unlock(&bpf_verifier_lock);
19423 	vfree(env->insn_aux_data);
19424 err_free_env:
19425 	kfree(env);
19426 	return ret;
19427 }
19428