xref: /openbmc/linux/kernel/bpf/verifier.c (revision f655badf2a8fc028433d9583bf86a6b473721f09)
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_pseudo_call(const struct bpf_insn *insn)
244 {
245 	return insn->code == (BPF_JMP | BPF_CALL) &&
246 	       insn->src_reg == BPF_PSEUDO_CALL;
247 }
248 
249 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
250 {
251 	return insn->code == (BPF_JMP | BPF_CALL) &&
252 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
253 }
254 
255 struct bpf_call_arg_meta {
256 	struct bpf_map *map_ptr;
257 	bool raw_mode;
258 	bool pkt_access;
259 	u8 release_regno;
260 	int regno;
261 	int access_size;
262 	int mem_size;
263 	u64 msize_max_value;
264 	int ref_obj_id;
265 	int dynptr_id;
266 	int map_uid;
267 	int func_id;
268 	struct btf *btf;
269 	u32 btf_id;
270 	struct btf *ret_btf;
271 	u32 ret_btf_id;
272 	u32 subprogno;
273 	struct btf_field *kptr_field;
274 };
275 
276 struct btf_and_id {
277 	struct btf *btf;
278 	u32 btf_id;
279 };
280 
281 struct bpf_kfunc_call_arg_meta {
282 	/* In parameters */
283 	struct btf *btf;
284 	u32 func_id;
285 	u32 kfunc_flags;
286 	const struct btf_type *func_proto;
287 	const char *func_name;
288 	/* Out parameters */
289 	u32 ref_obj_id;
290 	u8 release_regno;
291 	bool r0_rdonly;
292 	u32 ret_btf_id;
293 	u64 r0_size;
294 	u32 subprogno;
295 	struct {
296 		u64 value;
297 		bool found;
298 	} arg_constant;
299 	union {
300 		struct btf_and_id arg_obj_drop;
301 		struct btf_and_id arg_refcount_acquire;
302 	};
303 	struct {
304 		struct btf_field *field;
305 	} arg_list_head;
306 	struct {
307 		struct btf_field *field;
308 	} arg_rbtree_root;
309 	struct {
310 		enum bpf_dynptr_type type;
311 		u32 id;
312 		u32 ref_obj_id;
313 	} initialized_dynptr;
314 	struct {
315 		u8 spi;
316 		u8 frameno;
317 	} iter;
318 	u64 mem_size;
319 };
320 
321 struct btf *btf_vmlinux;
322 
323 static DEFINE_MUTEX(bpf_verifier_lock);
324 
325 static const struct bpf_line_info *
326 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
327 {
328 	const struct bpf_line_info *linfo;
329 	const struct bpf_prog *prog;
330 	u32 i, nr_linfo;
331 
332 	prog = env->prog;
333 	nr_linfo = prog->aux->nr_linfo;
334 
335 	if (!nr_linfo || insn_off >= prog->len)
336 		return NULL;
337 
338 	linfo = prog->aux->linfo;
339 	for (i = 1; i < nr_linfo; i++)
340 		if (insn_off < linfo[i].insn_off)
341 			break;
342 
343 	return &linfo[i - 1];
344 }
345 
346 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
347 {
348 	struct bpf_verifier_env *env = private_data;
349 	va_list args;
350 
351 	if (!bpf_verifier_log_needed(&env->log))
352 		return;
353 
354 	va_start(args, fmt);
355 	bpf_verifier_vlog(&env->log, fmt, args);
356 	va_end(args);
357 }
358 
359 static const char *ltrim(const char *s)
360 {
361 	while (isspace(*s))
362 		s++;
363 
364 	return s;
365 }
366 
367 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
368 					 u32 insn_off,
369 					 const char *prefix_fmt, ...)
370 {
371 	const struct bpf_line_info *linfo;
372 
373 	if (!bpf_verifier_log_needed(&env->log))
374 		return;
375 
376 	linfo = find_linfo(env, insn_off);
377 	if (!linfo || linfo == env->prev_linfo)
378 		return;
379 
380 	if (prefix_fmt) {
381 		va_list args;
382 
383 		va_start(args, prefix_fmt);
384 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
385 		va_end(args);
386 	}
387 
388 	verbose(env, "%s\n",
389 		ltrim(btf_name_by_offset(env->prog->aux->btf,
390 					 linfo->line_off)));
391 
392 	env->prev_linfo = linfo;
393 }
394 
395 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
396 				   struct bpf_reg_state *reg,
397 				   struct tnum *range, const char *ctx,
398 				   const char *reg_name)
399 {
400 	char tn_buf[48];
401 
402 	verbose(env, "At %s the register %s ", ctx, reg_name);
403 	if (!tnum_is_unknown(reg->var_off)) {
404 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
405 		verbose(env, "has value %s", tn_buf);
406 	} else {
407 		verbose(env, "has unknown scalar value");
408 	}
409 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
410 	verbose(env, " should have been in %s\n", tn_buf);
411 }
412 
413 static bool type_is_pkt_pointer(enum bpf_reg_type type)
414 {
415 	type = base_type(type);
416 	return type == PTR_TO_PACKET ||
417 	       type == PTR_TO_PACKET_META;
418 }
419 
420 static bool type_is_sk_pointer(enum bpf_reg_type type)
421 {
422 	return type == PTR_TO_SOCKET ||
423 		type == PTR_TO_SOCK_COMMON ||
424 		type == PTR_TO_TCP_SOCK ||
425 		type == PTR_TO_XDP_SOCK;
426 }
427 
428 static bool type_may_be_null(u32 type)
429 {
430 	return type & PTR_MAYBE_NULL;
431 }
432 
433 static bool reg_type_not_null(enum bpf_reg_type type)
434 {
435 	if (type_may_be_null(type))
436 		return false;
437 
438 	type = base_type(type);
439 	return type == PTR_TO_SOCKET ||
440 		type == PTR_TO_TCP_SOCK ||
441 		type == PTR_TO_MAP_VALUE ||
442 		type == PTR_TO_MAP_KEY ||
443 		type == PTR_TO_SOCK_COMMON ||
444 		type == PTR_TO_MEM;
445 }
446 
447 static bool type_is_ptr_alloc_obj(u32 type)
448 {
449 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
450 }
451 
452 static bool type_is_non_owning_ref(u32 type)
453 {
454 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
455 }
456 
457 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
458 {
459 	struct btf_record *rec = NULL;
460 	struct btf_struct_meta *meta;
461 
462 	if (reg->type == PTR_TO_MAP_VALUE) {
463 		rec = reg->map_ptr->record;
464 	} else if (type_is_ptr_alloc_obj(reg->type)) {
465 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
466 		if (meta)
467 			rec = meta->record;
468 	}
469 	return rec;
470 }
471 
472 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
473 {
474 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
475 }
476 
477 static bool type_is_rdonly_mem(u32 type)
478 {
479 	return type & MEM_RDONLY;
480 }
481 
482 static bool is_acquire_function(enum bpf_func_id func_id,
483 				const struct bpf_map *map)
484 {
485 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
486 
487 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
488 	    func_id == BPF_FUNC_sk_lookup_udp ||
489 	    func_id == BPF_FUNC_skc_lookup_tcp ||
490 	    func_id == BPF_FUNC_ringbuf_reserve ||
491 	    func_id == BPF_FUNC_kptr_xchg)
492 		return true;
493 
494 	if (func_id == BPF_FUNC_map_lookup_elem &&
495 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
496 	     map_type == BPF_MAP_TYPE_SOCKHASH))
497 		return true;
498 
499 	return false;
500 }
501 
502 static bool is_ptr_cast_function(enum bpf_func_id func_id)
503 {
504 	return func_id == BPF_FUNC_tcp_sock ||
505 		func_id == BPF_FUNC_sk_fullsock ||
506 		func_id == BPF_FUNC_skc_to_tcp_sock ||
507 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
508 		func_id == BPF_FUNC_skc_to_udp6_sock ||
509 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
510 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
511 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
512 }
513 
514 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
515 {
516 	return func_id == BPF_FUNC_dynptr_data;
517 }
518 
519 static bool is_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_for_each_map_elem ||
522 	       func_id == BPF_FUNC_timer_set_callback ||
523 	       func_id == BPF_FUNC_find_vma ||
524 	       func_id == BPF_FUNC_loop ||
525 	       func_id == BPF_FUNC_user_ringbuf_drain;
526 }
527 
528 static bool is_storage_get_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_sk_storage_get ||
531 	       func_id == BPF_FUNC_inode_storage_get ||
532 	       func_id == BPF_FUNC_task_storage_get ||
533 	       func_id == BPF_FUNC_cgrp_storage_get;
534 }
535 
536 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
537 					const struct bpf_map *map)
538 {
539 	int ref_obj_uses = 0;
540 
541 	if (is_ptr_cast_function(func_id))
542 		ref_obj_uses++;
543 	if (is_acquire_function(func_id, map))
544 		ref_obj_uses++;
545 	if (is_dynptr_ref_function(func_id))
546 		ref_obj_uses++;
547 
548 	return ref_obj_uses > 1;
549 }
550 
551 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
552 {
553 	return BPF_CLASS(insn->code) == BPF_STX &&
554 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
555 	       insn->imm == BPF_CMPXCHG;
556 }
557 
558 /* string representation of 'enum bpf_reg_type'
559  *
560  * Note that reg_type_str() can not appear more than once in a single verbose()
561  * statement.
562  */
563 static const char *reg_type_str(struct bpf_verifier_env *env,
564 				enum bpf_reg_type type)
565 {
566 	char postfix[16] = {0}, prefix[64] = {0};
567 	static const char * const str[] = {
568 		[NOT_INIT]		= "?",
569 		[SCALAR_VALUE]		= "scalar",
570 		[PTR_TO_CTX]		= "ctx",
571 		[CONST_PTR_TO_MAP]	= "map_ptr",
572 		[PTR_TO_MAP_VALUE]	= "map_value",
573 		[PTR_TO_STACK]		= "fp",
574 		[PTR_TO_PACKET]		= "pkt",
575 		[PTR_TO_PACKET_META]	= "pkt_meta",
576 		[PTR_TO_PACKET_END]	= "pkt_end",
577 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
578 		[PTR_TO_SOCKET]		= "sock",
579 		[PTR_TO_SOCK_COMMON]	= "sock_common",
580 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
581 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
582 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
583 		[PTR_TO_BTF_ID]		= "ptr_",
584 		[PTR_TO_MEM]		= "mem",
585 		[PTR_TO_BUF]		= "buf",
586 		[PTR_TO_FUNC]		= "func",
587 		[PTR_TO_MAP_KEY]	= "map_key",
588 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
589 	};
590 
591 	if (type & PTR_MAYBE_NULL) {
592 		if (base_type(type) == PTR_TO_BTF_ID)
593 			strncpy(postfix, "or_null_", 16);
594 		else
595 			strncpy(postfix, "_or_null", 16);
596 	}
597 
598 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
599 		 type & MEM_RDONLY ? "rdonly_" : "",
600 		 type & MEM_RINGBUF ? "ringbuf_" : "",
601 		 type & MEM_USER ? "user_" : "",
602 		 type & MEM_PERCPU ? "percpu_" : "",
603 		 type & MEM_RCU ? "rcu_" : "",
604 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
605 		 type & PTR_TRUSTED ? "trusted_" : ""
606 	);
607 
608 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
609 		 prefix, str[base_type(type)], postfix);
610 	return env->tmp_str_buf;
611 }
612 
613 static char slot_type_char[] = {
614 	[STACK_INVALID]	= '?',
615 	[STACK_SPILL]	= 'r',
616 	[STACK_MISC]	= 'm',
617 	[STACK_ZERO]	= '0',
618 	[STACK_DYNPTR]	= 'd',
619 	[STACK_ITER]	= 'i',
620 };
621 
622 static void print_liveness(struct bpf_verifier_env *env,
623 			   enum bpf_reg_liveness live)
624 {
625 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
626 	    verbose(env, "_");
627 	if (live & REG_LIVE_READ)
628 		verbose(env, "r");
629 	if (live & REG_LIVE_WRITTEN)
630 		verbose(env, "w");
631 	if (live & REG_LIVE_DONE)
632 		verbose(env, "D");
633 }
634 
635 static int __get_spi(s32 off)
636 {
637 	return (-off - 1) / BPF_REG_SIZE;
638 }
639 
640 static struct bpf_func_state *func(struct bpf_verifier_env *env,
641 				   const struct bpf_reg_state *reg)
642 {
643 	struct bpf_verifier_state *cur = env->cur_state;
644 
645 	return cur->frame[reg->frameno];
646 }
647 
648 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
649 {
650        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
651 
652        /* We need to check that slots between [spi - nr_slots + 1, spi] are
653 	* within [0, allocated_stack).
654 	*
655 	* Please note that the spi grows downwards. For example, a dynptr
656 	* takes the size of two stack slots; the first slot will be at
657 	* spi and the second slot will be at spi - 1.
658 	*/
659        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
660 }
661 
662 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
663 			          const char *obj_kind, int nr_slots)
664 {
665 	int off, spi;
666 
667 	if (!tnum_is_const(reg->var_off)) {
668 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
669 		return -EINVAL;
670 	}
671 
672 	off = reg->off + reg->var_off.value;
673 	if (off % BPF_REG_SIZE) {
674 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
675 		return -EINVAL;
676 	}
677 
678 	spi = __get_spi(off);
679 	if (spi + 1 < nr_slots) {
680 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
681 		return -EINVAL;
682 	}
683 
684 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
685 		return -ERANGE;
686 	return spi;
687 }
688 
689 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
690 {
691 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
692 }
693 
694 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
695 {
696 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
697 }
698 
699 static const char *btf_type_name(const struct btf *btf, u32 id)
700 {
701 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
702 }
703 
704 static const char *dynptr_type_str(enum bpf_dynptr_type type)
705 {
706 	switch (type) {
707 	case BPF_DYNPTR_TYPE_LOCAL:
708 		return "local";
709 	case BPF_DYNPTR_TYPE_RINGBUF:
710 		return "ringbuf";
711 	case BPF_DYNPTR_TYPE_SKB:
712 		return "skb";
713 	case BPF_DYNPTR_TYPE_XDP:
714 		return "xdp";
715 	case BPF_DYNPTR_TYPE_INVALID:
716 		return "<invalid>";
717 	default:
718 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
719 		return "<unknown>";
720 	}
721 }
722 
723 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
724 {
725 	if (!btf || btf_id == 0)
726 		return "<invalid>";
727 
728 	/* we already validated that type is valid and has conforming name */
729 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
730 }
731 
732 static const char *iter_state_str(enum bpf_iter_state state)
733 {
734 	switch (state) {
735 	case BPF_ITER_STATE_ACTIVE:
736 		return "active";
737 	case BPF_ITER_STATE_DRAINED:
738 		return "drained";
739 	case BPF_ITER_STATE_INVALID:
740 		return "<invalid>";
741 	default:
742 		WARN_ONCE(1, "unknown iter state %d\n", state);
743 		return "<unknown>";
744 	}
745 }
746 
747 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
748 {
749 	env->scratched_regs |= 1U << regno;
750 }
751 
752 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
753 {
754 	env->scratched_stack_slots |= 1ULL << spi;
755 }
756 
757 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
758 {
759 	return (env->scratched_regs >> regno) & 1;
760 }
761 
762 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
763 {
764 	return (env->scratched_stack_slots >> regno) & 1;
765 }
766 
767 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
768 {
769 	return env->scratched_regs || env->scratched_stack_slots;
770 }
771 
772 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
773 {
774 	env->scratched_regs = 0U;
775 	env->scratched_stack_slots = 0ULL;
776 }
777 
778 /* Used for printing the entire verifier state. */
779 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
780 {
781 	env->scratched_regs = ~0U;
782 	env->scratched_stack_slots = ~0ULL;
783 }
784 
785 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
786 {
787 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
788 	case DYNPTR_TYPE_LOCAL:
789 		return BPF_DYNPTR_TYPE_LOCAL;
790 	case DYNPTR_TYPE_RINGBUF:
791 		return BPF_DYNPTR_TYPE_RINGBUF;
792 	case DYNPTR_TYPE_SKB:
793 		return BPF_DYNPTR_TYPE_SKB;
794 	case DYNPTR_TYPE_XDP:
795 		return BPF_DYNPTR_TYPE_XDP;
796 	default:
797 		return BPF_DYNPTR_TYPE_INVALID;
798 	}
799 }
800 
801 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
802 {
803 	switch (type) {
804 	case BPF_DYNPTR_TYPE_LOCAL:
805 		return DYNPTR_TYPE_LOCAL;
806 	case BPF_DYNPTR_TYPE_RINGBUF:
807 		return DYNPTR_TYPE_RINGBUF;
808 	case BPF_DYNPTR_TYPE_SKB:
809 		return DYNPTR_TYPE_SKB;
810 	case BPF_DYNPTR_TYPE_XDP:
811 		return DYNPTR_TYPE_XDP;
812 	default:
813 		return 0;
814 	}
815 }
816 
817 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
818 {
819 	return type == BPF_DYNPTR_TYPE_RINGBUF;
820 }
821 
822 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
823 			      enum bpf_dynptr_type type,
824 			      bool first_slot, int dynptr_id);
825 
826 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
827 				struct bpf_reg_state *reg);
828 
829 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
830 				   struct bpf_reg_state *sreg1,
831 				   struct bpf_reg_state *sreg2,
832 				   enum bpf_dynptr_type type)
833 {
834 	int id = ++env->id_gen;
835 
836 	__mark_dynptr_reg(sreg1, type, true, id);
837 	__mark_dynptr_reg(sreg2, type, false, id);
838 }
839 
840 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
841 			       struct bpf_reg_state *reg,
842 			       enum bpf_dynptr_type type)
843 {
844 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
845 }
846 
847 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
848 				        struct bpf_func_state *state, int spi);
849 
850 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
851 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
852 {
853 	struct bpf_func_state *state = func(env, reg);
854 	enum bpf_dynptr_type type;
855 	int spi, i, err;
856 
857 	spi = dynptr_get_spi(env, reg);
858 	if (spi < 0)
859 		return spi;
860 
861 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
862 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
863 	 * to ensure that for the following example:
864 	 *	[d1][d1][d2][d2]
865 	 * spi    3   2   1   0
866 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
867 	 * case they do belong to same dynptr, second call won't see slot_type
868 	 * as STACK_DYNPTR and will simply skip destruction.
869 	 */
870 	err = destroy_if_dynptr_stack_slot(env, state, spi);
871 	if (err)
872 		return err;
873 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
874 	if (err)
875 		return err;
876 
877 	for (i = 0; i < BPF_REG_SIZE; i++) {
878 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
879 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
880 	}
881 
882 	type = arg_to_dynptr_type(arg_type);
883 	if (type == BPF_DYNPTR_TYPE_INVALID)
884 		return -EINVAL;
885 
886 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
887 			       &state->stack[spi - 1].spilled_ptr, type);
888 
889 	if (dynptr_type_refcounted(type)) {
890 		/* The id is used to track proper releasing */
891 		int id;
892 
893 		if (clone_ref_obj_id)
894 			id = clone_ref_obj_id;
895 		else
896 			id = acquire_reference_state(env, insn_idx);
897 
898 		if (id < 0)
899 			return id;
900 
901 		state->stack[spi].spilled_ptr.ref_obj_id = id;
902 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
903 	}
904 
905 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
906 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
907 
908 	return 0;
909 }
910 
911 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
912 {
913 	int i;
914 
915 	for (i = 0; i < BPF_REG_SIZE; i++) {
916 		state->stack[spi].slot_type[i] = STACK_INVALID;
917 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
918 	}
919 
920 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
921 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
922 
923 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
924 	 *
925 	 * While we don't allow reading STACK_INVALID, it is still possible to
926 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
927 	 * helpers or insns can do partial read of that part without failing,
928 	 * but check_stack_range_initialized, check_stack_read_var_off, and
929 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
930 	 * the slot conservatively. Hence we need to prevent those liveness
931 	 * marking walks.
932 	 *
933 	 * This was not a problem before because STACK_INVALID is only set by
934 	 * default (where the default reg state has its reg->parent as NULL), or
935 	 * in clean_live_states after REG_LIVE_DONE (at which point
936 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
937 	 * verifier state exploration (like we did above). Hence, for our case
938 	 * parentage chain will still be live (i.e. reg->parent may be
939 	 * non-NULL), while earlier reg->parent was NULL, so we need
940 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
941 	 * done later on reads or by mark_dynptr_read as well to unnecessary
942 	 * mark registers in verifier state.
943 	 */
944 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
945 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
946 }
947 
948 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
949 {
950 	struct bpf_func_state *state = func(env, reg);
951 	int spi, ref_obj_id, i;
952 
953 	spi = dynptr_get_spi(env, reg);
954 	if (spi < 0)
955 		return spi;
956 
957 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
958 		invalidate_dynptr(env, state, spi);
959 		return 0;
960 	}
961 
962 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
963 
964 	/* If the dynptr has a ref_obj_id, then we need to invalidate
965 	 * two things:
966 	 *
967 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
968 	 * 2) Any slices derived from this dynptr.
969 	 */
970 
971 	/* Invalidate any slices associated with this dynptr */
972 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
973 
974 	/* Invalidate any dynptr clones */
975 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
976 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
977 			continue;
978 
979 		/* it should always be the case that if the ref obj id
980 		 * matches then the stack slot also belongs to a
981 		 * dynptr
982 		 */
983 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
984 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
985 			return -EFAULT;
986 		}
987 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
988 			invalidate_dynptr(env, state, i);
989 	}
990 
991 	return 0;
992 }
993 
994 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
995 			       struct bpf_reg_state *reg);
996 
997 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
998 {
999 	if (!env->allow_ptr_leaks)
1000 		__mark_reg_not_init(env, reg);
1001 	else
1002 		__mark_reg_unknown(env, reg);
1003 }
1004 
1005 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1006 				        struct bpf_func_state *state, int spi)
1007 {
1008 	struct bpf_func_state *fstate;
1009 	struct bpf_reg_state *dreg;
1010 	int i, dynptr_id;
1011 
1012 	/* We always ensure that STACK_DYNPTR is never set partially,
1013 	 * hence just checking for slot_type[0] is enough. This is
1014 	 * different for STACK_SPILL, where it may be only set for
1015 	 * 1 byte, so code has to use is_spilled_reg.
1016 	 */
1017 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1018 		return 0;
1019 
1020 	/* Reposition spi to first slot */
1021 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1022 		spi = spi + 1;
1023 
1024 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1025 		verbose(env, "cannot overwrite referenced dynptr\n");
1026 		return -EINVAL;
1027 	}
1028 
1029 	mark_stack_slot_scratched(env, spi);
1030 	mark_stack_slot_scratched(env, spi - 1);
1031 
1032 	/* Writing partially to one dynptr stack slot destroys both. */
1033 	for (i = 0; i < BPF_REG_SIZE; i++) {
1034 		state->stack[spi].slot_type[i] = STACK_INVALID;
1035 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1036 	}
1037 
1038 	dynptr_id = state->stack[spi].spilled_ptr.id;
1039 	/* Invalidate any slices associated with this dynptr */
1040 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1041 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1042 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1043 			continue;
1044 		if (dreg->dynptr_id == dynptr_id)
1045 			mark_reg_invalid(env, dreg);
1046 	}));
1047 
1048 	/* Do not release reference state, we are destroying dynptr on stack,
1049 	 * not using some helper to release it. Just reset register.
1050 	 */
1051 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1052 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1053 
1054 	/* Same reason as unmark_stack_slots_dynptr above */
1055 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1056 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1057 
1058 	return 0;
1059 }
1060 
1061 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1062 {
1063 	int spi;
1064 
1065 	if (reg->type == CONST_PTR_TO_DYNPTR)
1066 		return false;
1067 
1068 	spi = dynptr_get_spi(env, reg);
1069 
1070 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1071 	 * error because this just means the stack state hasn't been updated yet.
1072 	 * We will do check_mem_access to check and update stack bounds later.
1073 	 */
1074 	if (spi < 0 && spi != -ERANGE)
1075 		return false;
1076 
1077 	/* We don't need to check if the stack slots are marked by previous
1078 	 * dynptr initializations because we allow overwriting existing unreferenced
1079 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1080 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1081 	 * touching are completely destructed before we reinitialize them for a new
1082 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1083 	 * instead of delaying it until the end where the user will get "Unreleased
1084 	 * reference" error.
1085 	 */
1086 	return true;
1087 }
1088 
1089 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1090 {
1091 	struct bpf_func_state *state = func(env, reg);
1092 	int i, spi;
1093 
1094 	/* This already represents first slot of initialized bpf_dynptr.
1095 	 *
1096 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1097 	 * check_func_arg_reg_off's logic, so we don't need to check its
1098 	 * offset and alignment.
1099 	 */
1100 	if (reg->type == CONST_PTR_TO_DYNPTR)
1101 		return true;
1102 
1103 	spi = dynptr_get_spi(env, reg);
1104 	if (spi < 0)
1105 		return false;
1106 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1107 		return false;
1108 
1109 	for (i = 0; i < BPF_REG_SIZE; i++) {
1110 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1111 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1112 			return false;
1113 	}
1114 
1115 	return true;
1116 }
1117 
1118 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1119 				    enum bpf_arg_type arg_type)
1120 {
1121 	struct bpf_func_state *state = func(env, reg);
1122 	enum bpf_dynptr_type dynptr_type;
1123 	int spi;
1124 
1125 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1126 	if (arg_type == ARG_PTR_TO_DYNPTR)
1127 		return true;
1128 
1129 	dynptr_type = arg_to_dynptr_type(arg_type);
1130 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1131 		return reg->dynptr.type == dynptr_type;
1132 	} else {
1133 		spi = dynptr_get_spi(env, reg);
1134 		if (spi < 0)
1135 			return false;
1136 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1137 	}
1138 }
1139 
1140 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1141 
1142 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1143 				 struct bpf_reg_state *reg, int insn_idx,
1144 				 struct btf *btf, u32 btf_id, int nr_slots)
1145 {
1146 	struct bpf_func_state *state = func(env, reg);
1147 	int spi, i, j, id;
1148 
1149 	spi = iter_get_spi(env, reg, nr_slots);
1150 	if (spi < 0)
1151 		return spi;
1152 
1153 	id = acquire_reference_state(env, insn_idx);
1154 	if (id < 0)
1155 		return id;
1156 
1157 	for (i = 0; i < nr_slots; i++) {
1158 		struct bpf_stack_state *slot = &state->stack[spi - i];
1159 		struct bpf_reg_state *st = &slot->spilled_ptr;
1160 
1161 		__mark_reg_known_zero(st);
1162 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1163 		st->live |= REG_LIVE_WRITTEN;
1164 		st->ref_obj_id = i == 0 ? id : 0;
1165 		st->iter.btf = btf;
1166 		st->iter.btf_id = btf_id;
1167 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1168 		st->iter.depth = 0;
1169 
1170 		for (j = 0; j < BPF_REG_SIZE; j++)
1171 			slot->slot_type[j] = STACK_ITER;
1172 
1173 		mark_stack_slot_scratched(env, spi - i);
1174 	}
1175 
1176 	return 0;
1177 }
1178 
1179 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1180 				   struct bpf_reg_state *reg, int nr_slots)
1181 {
1182 	struct bpf_func_state *state = func(env, reg);
1183 	int spi, i, j;
1184 
1185 	spi = iter_get_spi(env, reg, nr_slots);
1186 	if (spi < 0)
1187 		return spi;
1188 
1189 	for (i = 0; i < nr_slots; i++) {
1190 		struct bpf_stack_state *slot = &state->stack[spi - i];
1191 		struct bpf_reg_state *st = &slot->spilled_ptr;
1192 
1193 		if (i == 0)
1194 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1195 
1196 		__mark_reg_not_init(env, st);
1197 
1198 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1199 		st->live |= REG_LIVE_WRITTEN;
1200 
1201 		for (j = 0; j < BPF_REG_SIZE; j++)
1202 			slot->slot_type[j] = STACK_INVALID;
1203 
1204 		mark_stack_slot_scratched(env, spi - i);
1205 	}
1206 
1207 	return 0;
1208 }
1209 
1210 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1211 				     struct bpf_reg_state *reg, int nr_slots)
1212 {
1213 	struct bpf_func_state *state = func(env, reg);
1214 	int spi, i, j;
1215 
1216 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1217 	 * will do check_mem_access to check and update stack bounds later, so
1218 	 * return true for that case.
1219 	 */
1220 	spi = iter_get_spi(env, reg, nr_slots);
1221 	if (spi == -ERANGE)
1222 		return true;
1223 	if (spi < 0)
1224 		return false;
1225 
1226 	for (i = 0; i < nr_slots; i++) {
1227 		struct bpf_stack_state *slot = &state->stack[spi - i];
1228 
1229 		for (j = 0; j < BPF_REG_SIZE; j++)
1230 			if (slot->slot_type[j] == STACK_ITER)
1231 				return false;
1232 	}
1233 
1234 	return true;
1235 }
1236 
1237 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1238 				   struct btf *btf, u32 btf_id, int nr_slots)
1239 {
1240 	struct bpf_func_state *state = func(env, reg);
1241 	int spi, i, j;
1242 
1243 	spi = iter_get_spi(env, reg, nr_slots);
1244 	if (spi < 0)
1245 		return false;
1246 
1247 	for (i = 0; i < nr_slots; i++) {
1248 		struct bpf_stack_state *slot = &state->stack[spi - i];
1249 		struct bpf_reg_state *st = &slot->spilled_ptr;
1250 
1251 		/* only main (first) slot has ref_obj_id set */
1252 		if (i == 0 && !st->ref_obj_id)
1253 			return false;
1254 		if (i != 0 && st->ref_obj_id)
1255 			return false;
1256 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1257 			return false;
1258 
1259 		for (j = 0; j < BPF_REG_SIZE; j++)
1260 			if (slot->slot_type[j] != STACK_ITER)
1261 				return false;
1262 	}
1263 
1264 	return true;
1265 }
1266 
1267 /* Check if given stack slot is "special":
1268  *   - spilled register state (STACK_SPILL);
1269  *   - dynptr state (STACK_DYNPTR);
1270  *   - iter state (STACK_ITER).
1271  */
1272 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1273 {
1274 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1275 
1276 	switch (type) {
1277 	case STACK_SPILL:
1278 	case STACK_DYNPTR:
1279 	case STACK_ITER:
1280 		return true;
1281 	case STACK_INVALID:
1282 	case STACK_MISC:
1283 	case STACK_ZERO:
1284 		return false;
1285 	default:
1286 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1287 		return true;
1288 	}
1289 }
1290 
1291 /* The reg state of a pointer or a bounded scalar was saved when
1292  * it was spilled to the stack.
1293  */
1294 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1295 {
1296 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1297 }
1298 
1299 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1300 {
1301 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1302 	       stack->spilled_ptr.type == SCALAR_VALUE;
1303 }
1304 
1305 static void scrub_spilled_slot(u8 *stype)
1306 {
1307 	if (*stype != STACK_INVALID)
1308 		*stype = STACK_MISC;
1309 }
1310 
1311 static void print_verifier_state(struct bpf_verifier_env *env,
1312 				 const struct bpf_func_state *state,
1313 				 bool print_all)
1314 {
1315 	const struct bpf_reg_state *reg;
1316 	enum bpf_reg_type t;
1317 	int i;
1318 
1319 	if (state->frameno)
1320 		verbose(env, " frame%d:", state->frameno);
1321 	for (i = 0; i < MAX_BPF_REG; i++) {
1322 		reg = &state->regs[i];
1323 		t = reg->type;
1324 		if (t == NOT_INIT)
1325 			continue;
1326 		if (!print_all && !reg_scratched(env, i))
1327 			continue;
1328 		verbose(env, " R%d", i);
1329 		print_liveness(env, reg->live);
1330 		verbose(env, "=");
1331 		if (t == SCALAR_VALUE && reg->precise)
1332 			verbose(env, "P");
1333 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1334 		    tnum_is_const(reg->var_off)) {
1335 			/* reg->off should be 0 for SCALAR_VALUE */
1336 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1337 			verbose(env, "%lld", reg->var_off.value + reg->off);
1338 		} else {
1339 			const char *sep = "";
1340 
1341 			verbose(env, "%s", reg_type_str(env, t));
1342 			if (base_type(t) == PTR_TO_BTF_ID)
1343 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1344 			verbose(env, "(");
1345 /*
1346  * _a stands for append, was shortened to avoid multiline statements below.
1347  * This macro is used to output a comma separated list of attributes.
1348  */
1349 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1350 
1351 			if (reg->id)
1352 				verbose_a("id=%d", reg->id);
1353 			if (reg->ref_obj_id)
1354 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1355 			if (type_is_non_owning_ref(reg->type))
1356 				verbose_a("%s", "non_own_ref");
1357 			if (t != SCALAR_VALUE)
1358 				verbose_a("off=%d", reg->off);
1359 			if (type_is_pkt_pointer(t))
1360 				verbose_a("r=%d", reg->range);
1361 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1362 				 base_type(t) == PTR_TO_MAP_KEY ||
1363 				 base_type(t) == PTR_TO_MAP_VALUE)
1364 				verbose_a("ks=%d,vs=%d",
1365 					  reg->map_ptr->key_size,
1366 					  reg->map_ptr->value_size);
1367 			if (tnum_is_const(reg->var_off)) {
1368 				/* Typically an immediate SCALAR_VALUE, but
1369 				 * could be a pointer whose offset is too big
1370 				 * for reg->off
1371 				 */
1372 				verbose_a("imm=%llx", reg->var_off.value);
1373 			} else {
1374 				if (reg->smin_value != reg->umin_value &&
1375 				    reg->smin_value != S64_MIN)
1376 					verbose_a("smin=%lld", (long long)reg->smin_value);
1377 				if (reg->smax_value != reg->umax_value &&
1378 				    reg->smax_value != S64_MAX)
1379 					verbose_a("smax=%lld", (long long)reg->smax_value);
1380 				if (reg->umin_value != 0)
1381 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1382 				if (reg->umax_value != U64_MAX)
1383 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1384 				if (!tnum_is_unknown(reg->var_off)) {
1385 					char tn_buf[48];
1386 
1387 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1388 					verbose_a("var_off=%s", tn_buf);
1389 				}
1390 				if (reg->s32_min_value != reg->smin_value &&
1391 				    reg->s32_min_value != S32_MIN)
1392 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1393 				if (reg->s32_max_value != reg->smax_value &&
1394 				    reg->s32_max_value != S32_MAX)
1395 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1396 				if (reg->u32_min_value != reg->umin_value &&
1397 				    reg->u32_min_value != U32_MIN)
1398 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1399 				if (reg->u32_max_value != reg->umax_value &&
1400 				    reg->u32_max_value != U32_MAX)
1401 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1402 			}
1403 #undef verbose_a
1404 
1405 			verbose(env, ")");
1406 		}
1407 	}
1408 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1409 		char types_buf[BPF_REG_SIZE + 1];
1410 		bool valid = false;
1411 		int j;
1412 
1413 		for (j = 0; j < BPF_REG_SIZE; j++) {
1414 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1415 				valid = true;
1416 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1417 		}
1418 		types_buf[BPF_REG_SIZE] = 0;
1419 		if (!valid)
1420 			continue;
1421 		if (!print_all && !stack_slot_scratched(env, i))
1422 			continue;
1423 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1424 		case STACK_SPILL:
1425 			reg = &state->stack[i].spilled_ptr;
1426 			t = reg->type;
1427 
1428 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1429 			print_liveness(env, reg->live);
1430 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1431 			if (t == SCALAR_VALUE && reg->precise)
1432 				verbose(env, "P");
1433 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1434 				verbose(env, "%lld", reg->var_off.value + reg->off);
1435 			break;
1436 		case STACK_DYNPTR:
1437 			i += BPF_DYNPTR_NR_SLOTS - 1;
1438 			reg = &state->stack[i].spilled_ptr;
1439 
1440 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1441 			print_liveness(env, reg->live);
1442 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1443 			if (reg->ref_obj_id)
1444 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1445 			break;
1446 		case STACK_ITER:
1447 			/* only main slot has ref_obj_id set; skip others */
1448 			reg = &state->stack[i].spilled_ptr;
1449 			if (!reg->ref_obj_id)
1450 				continue;
1451 
1452 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1453 			print_liveness(env, reg->live);
1454 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1455 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1456 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1457 				reg->iter.depth);
1458 			break;
1459 		case STACK_MISC:
1460 		case STACK_ZERO:
1461 		default:
1462 			reg = &state->stack[i].spilled_ptr;
1463 
1464 			for (j = 0; j < BPF_REG_SIZE; j++)
1465 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1466 			types_buf[BPF_REG_SIZE] = 0;
1467 
1468 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1469 			print_liveness(env, reg->live);
1470 			verbose(env, "=%s", types_buf);
1471 			break;
1472 		}
1473 	}
1474 	if (state->acquired_refs && state->refs[0].id) {
1475 		verbose(env, " refs=%d", state->refs[0].id);
1476 		for (i = 1; i < state->acquired_refs; i++)
1477 			if (state->refs[i].id)
1478 				verbose(env, ",%d", state->refs[i].id);
1479 	}
1480 	if (state->in_callback_fn)
1481 		verbose(env, " cb");
1482 	if (state->in_async_callback_fn)
1483 		verbose(env, " async_cb");
1484 	verbose(env, "\n");
1485 	mark_verifier_state_clean(env);
1486 }
1487 
1488 static inline u32 vlog_alignment(u32 pos)
1489 {
1490 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1491 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1492 }
1493 
1494 static void print_insn_state(struct bpf_verifier_env *env,
1495 			     const struct bpf_func_state *state)
1496 {
1497 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1498 		/* remove new line character */
1499 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1500 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1501 	} else {
1502 		verbose(env, "%d:", env->insn_idx);
1503 	}
1504 	print_verifier_state(env, state, false);
1505 }
1506 
1507 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1508  * small to hold src. This is different from krealloc since we don't want to preserve
1509  * the contents of dst.
1510  *
1511  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1512  * not be allocated.
1513  */
1514 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1515 {
1516 	size_t alloc_bytes;
1517 	void *orig = dst;
1518 	size_t bytes;
1519 
1520 	if (ZERO_OR_NULL_PTR(src))
1521 		goto out;
1522 
1523 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1524 		return NULL;
1525 
1526 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1527 	dst = krealloc(orig, alloc_bytes, flags);
1528 	if (!dst) {
1529 		kfree(orig);
1530 		return NULL;
1531 	}
1532 
1533 	memcpy(dst, src, bytes);
1534 out:
1535 	return dst ? dst : ZERO_SIZE_PTR;
1536 }
1537 
1538 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1539  * small to hold new_n items. new items are zeroed out if the array grows.
1540  *
1541  * Contrary to krealloc_array, does not free arr if new_n is zero.
1542  */
1543 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1544 {
1545 	size_t alloc_size;
1546 	void *new_arr;
1547 
1548 	if (!new_n || old_n == new_n)
1549 		goto out;
1550 
1551 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1552 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1553 	if (!new_arr) {
1554 		kfree(arr);
1555 		return NULL;
1556 	}
1557 	arr = new_arr;
1558 
1559 	if (new_n > old_n)
1560 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1561 
1562 out:
1563 	return arr ? arr : ZERO_SIZE_PTR;
1564 }
1565 
1566 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1567 {
1568 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1569 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1570 	if (!dst->refs)
1571 		return -ENOMEM;
1572 
1573 	dst->acquired_refs = src->acquired_refs;
1574 	return 0;
1575 }
1576 
1577 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1578 {
1579 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1580 
1581 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1582 				GFP_KERNEL);
1583 	if (!dst->stack)
1584 		return -ENOMEM;
1585 
1586 	dst->allocated_stack = src->allocated_stack;
1587 	return 0;
1588 }
1589 
1590 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1591 {
1592 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1593 				    sizeof(struct bpf_reference_state));
1594 	if (!state->refs)
1595 		return -ENOMEM;
1596 
1597 	state->acquired_refs = n;
1598 	return 0;
1599 }
1600 
1601 static int grow_stack_state(struct bpf_func_state *state, int size)
1602 {
1603 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1604 
1605 	if (old_n >= n)
1606 		return 0;
1607 
1608 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1609 	if (!state->stack)
1610 		return -ENOMEM;
1611 
1612 	state->allocated_stack = size;
1613 	return 0;
1614 }
1615 
1616 /* Acquire a pointer id from the env and update the state->refs to include
1617  * this new pointer reference.
1618  * On success, returns a valid pointer id to associate with the register
1619  * On failure, returns a negative errno.
1620  */
1621 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1622 {
1623 	struct bpf_func_state *state = cur_func(env);
1624 	int new_ofs = state->acquired_refs;
1625 	int id, err;
1626 
1627 	err = resize_reference_state(state, state->acquired_refs + 1);
1628 	if (err)
1629 		return err;
1630 	id = ++env->id_gen;
1631 	state->refs[new_ofs].id = id;
1632 	state->refs[new_ofs].insn_idx = insn_idx;
1633 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1634 
1635 	return id;
1636 }
1637 
1638 /* release function corresponding to acquire_reference_state(). Idempotent. */
1639 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1640 {
1641 	int i, last_idx;
1642 
1643 	last_idx = state->acquired_refs - 1;
1644 	for (i = 0; i < state->acquired_refs; i++) {
1645 		if (state->refs[i].id == ptr_id) {
1646 			/* Cannot release caller references in callbacks */
1647 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1648 				return -EINVAL;
1649 			if (last_idx && i != last_idx)
1650 				memcpy(&state->refs[i], &state->refs[last_idx],
1651 				       sizeof(*state->refs));
1652 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1653 			state->acquired_refs--;
1654 			return 0;
1655 		}
1656 	}
1657 	return -EINVAL;
1658 }
1659 
1660 static void free_func_state(struct bpf_func_state *state)
1661 {
1662 	if (!state)
1663 		return;
1664 	kfree(state->refs);
1665 	kfree(state->stack);
1666 	kfree(state);
1667 }
1668 
1669 static void clear_jmp_history(struct bpf_verifier_state *state)
1670 {
1671 	kfree(state->jmp_history);
1672 	state->jmp_history = NULL;
1673 	state->jmp_history_cnt = 0;
1674 }
1675 
1676 static void free_verifier_state(struct bpf_verifier_state *state,
1677 				bool free_self)
1678 {
1679 	int i;
1680 
1681 	for (i = 0; i <= state->curframe; i++) {
1682 		free_func_state(state->frame[i]);
1683 		state->frame[i] = NULL;
1684 	}
1685 	clear_jmp_history(state);
1686 	if (free_self)
1687 		kfree(state);
1688 }
1689 
1690 /* copy verifier state from src to dst growing dst stack space
1691  * when necessary to accommodate larger src stack
1692  */
1693 static int copy_func_state(struct bpf_func_state *dst,
1694 			   const struct bpf_func_state *src)
1695 {
1696 	int err;
1697 
1698 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1699 	err = copy_reference_state(dst, src);
1700 	if (err)
1701 		return err;
1702 	return copy_stack_state(dst, src);
1703 }
1704 
1705 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1706 			       const struct bpf_verifier_state *src)
1707 {
1708 	struct bpf_func_state *dst;
1709 	int i, err;
1710 
1711 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1712 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1713 					    GFP_USER);
1714 	if (!dst_state->jmp_history)
1715 		return -ENOMEM;
1716 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1717 
1718 	/* if dst has more stack frames then src frame, free them */
1719 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1720 		free_func_state(dst_state->frame[i]);
1721 		dst_state->frame[i] = NULL;
1722 	}
1723 	dst_state->speculative = src->speculative;
1724 	dst_state->active_rcu_lock = src->active_rcu_lock;
1725 	dst_state->curframe = src->curframe;
1726 	dst_state->active_lock.ptr = src->active_lock.ptr;
1727 	dst_state->active_lock.id = src->active_lock.id;
1728 	dst_state->branches = src->branches;
1729 	dst_state->parent = src->parent;
1730 	dst_state->first_insn_idx = src->first_insn_idx;
1731 	dst_state->last_insn_idx = src->last_insn_idx;
1732 	for (i = 0; i <= src->curframe; i++) {
1733 		dst = dst_state->frame[i];
1734 		if (!dst) {
1735 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1736 			if (!dst)
1737 				return -ENOMEM;
1738 			dst_state->frame[i] = dst;
1739 		}
1740 		err = copy_func_state(dst, src->frame[i]);
1741 		if (err)
1742 			return err;
1743 	}
1744 	return 0;
1745 }
1746 
1747 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1748 {
1749 	while (st) {
1750 		u32 br = --st->branches;
1751 
1752 		/* WARN_ON(br > 1) technically makes sense here,
1753 		 * but see comment in push_stack(), hence:
1754 		 */
1755 		WARN_ONCE((int)br < 0,
1756 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1757 			  br);
1758 		if (br)
1759 			break;
1760 		st = st->parent;
1761 	}
1762 }
1763 
1764 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1765 		     int *insn_idx, bool pop_log)
1766 {
1767 	struct bpf_verifier_state *cur = env->cur_state;
1768 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1769 	int err;
1770 
1771 	if (env->head == NULL)
1772 		return -ENOENT;
1773 
1774 	if (cur) {
1775 		err = copy_verifier_state(cur, &head->st);
1776 		if (err)
1777 			return err;
1778 	}
1779 	if (pop_log)
1780 		bpf_vlog_reset(&env->log, head->log_pos);
1781 	if (insn_idx)
1782 		*insn_idx = head->insn_idx;
1783 	if (prev_insn_idx)
1784 		*prev_insn_idx = head->prev_insn_idx;
1785 	elem = head->next;
1786 	free_verifier_state(&head->st, false);
1787 	kfree(head);
1788 	env->head = elem;
1789 	env->stack_size--;
1790 	return 0;
1791 }
1792 
1793 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1794 					     int insn_idx, int prev_insn_idx,
1795 					     bool speculative)
1796 {
1797 	struct bpf_verifier_state *cur = env->cur_state;
1798 	struct bpf_verifier_stack_elem *elem;
1799 	int err;
1800 
1801 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1802 	if (!elem)
1803 		goto err;
1804 
1805 	elem->insn_idx = insn_idx;
1806 	elem->prev_insn_idx = prev_insn_idx;
1807 	elem->next = env->head;
1808 	elem->log_pos = env->log.end_pos;
1809 	env->head = elem;
1810 	env->stack_size++;
1811 	err = copy_verifier_state(&elem->st, cur);
1812 	if (err)
1813 		goto err;
1814 	elem->st.speculative |= speculative;
1815 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1816 		verbose(env, "The sequence of %d jumps is too complex.\n",
1817 			env->stack_size);
1818 		goto err;
1819 	}
1820 	if (elem->st.parent) {
1821 		++elem->st.parent->branches;
1822 		/* WARN_ON(branches > 2) technically makes sense here,
1823 		 * but
1824 		 * 1. speculative states will bump 'branches' for non-branch
1825 		 * instructions
1826 		 * 2. is_state_visited() heuristics may decide not to create
1827 		 * a new state for a sequence of branches and all such current
1828 		 * and cloned states will be pointing to a single parent state
1829 		 * which might have large 'branches' count.
1830 		 */
1831 	}
1832 	return &elem->st;
1833 err:
1834 	free_verifier_state(env->cur_state, true);
1835 	env->cur_state = NULL;
1836 	/* pop all elements and return */
1837 	while (!pop_stack(env, NULL, NULL, false));
1838 	return NULL;
1839 }
1840 
1841 #define CALLER_SAVED_REGS 6
1842 static const int caller_saved[CALLER_SAVED_REGS] = {
1843 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1844 };
1845 
1846 /* This helper doesn't clear reg->id */
1847 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1848 {
1849 	reg->var_off = tnum_const(imm);
1850 	reg->smin_value = (s64)imm;
1851 	reg->smax_value = (s64)imm;
1852 	reg->umin_value = imm;
1853 	reg->umax_value = imm;
1854 
1855 	reg->s32_min_value = (s32)imm;
1856 	reg->s32_max_value = (s32)imm;
1857 	reg->u32_min_value = (u32)imm;
1858 	reg->u32_max_value = (u32)imm;
1859 }
1860 
1861 /* Mark the unknown part of a register (variable offset or scalar value) as
1862  * known to have the value @imm.
1863  */
1864 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1865 {
1866 	/* Clear off and union(map_ptr, range) */
1867 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1868 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1869 	reg->id = 0;
1870 	reg->ref_obj_id = 0;
1871 	___mark_reg_known(reg, imm);
1872 }
1873 
1874 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1875 {
1876 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1877 	reg->s32_min_value = (s32)imm;
1878 	reg->s32_max_value = (s32)imm;
1879 	reg->u32_min_value = (u32)imm;
1880 	reg->u32_max_value = (u32)imm;
1881 }
1882 
1883 /* Mark the 'variable offset' part of a register as zero.  This should be
1884  * used only on registers holding a pointer type.
1885  */
1886 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1887 {
1888 	__mark_reg_known(reg, 0);
1889 }
1890 
1891 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1892 {
1893 	__mark_reg_known(reg, 0);
1894 	reg->type = SCALAR_VALUE;
1895 }
1896 
1897 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1898 				struct bpf_reg_state *regs, u32 regno)
1899 {
1900 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1901 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1902 		/* Something bad happened, let's kill all regs */
1903 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1904 			__mark_reg_not_init(env, regs + regno);
1905 		return;
1906 	}
1907 	__mark_reg_known_zero(regs + regno);
1908 }
1909 
1910 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1911 			      bool first_slot, int dynptr_id)
1912 {
1913 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1914 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1915 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1916 	 */
1917 	__mark_reg_known_zero(reg);
1918 	reg->type = CONST_PTR_TO_DYNPTR;
1919 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1920 	reg->id = dynptr_id;
1921 	reg->dynptr.type = type;
1922 	reg->dynptr.first_slot = first_slot;
1923 }
1924 
1925 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1926 {
1927 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1928 		const struct bpf_map *map = reg->map_ptr;
1929 
1930 		if (map->inner_map_meta) {
1931 			reg->type = CONST_PTR_TO_MAP;
1932 			reg->map_ptr = map->inner_map_meta;
1933 			/* transfer reg's id which is unique for every map_lookup_elem
1934 			 * as UID of the inner map.
1935 			 */
1936 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1937 				reg->map_uid = reg->id;
1938 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1939 			reg->type = PTR_TO_XDP_SOCK;
1940 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1941 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1942 			reg->type = PTR_TO_SOCKET;
1943 		} else {
1944 			reg->type = PTR_TO_MAP_VALUE;
1945 		}
1946 		return;
1947 	}
1948 
1949 	reg->type &= ~PTR_MAYBE_NULL;
1950 }
1951 
1952 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1953 				struct btf_field_graph_root *ds_head)
1954 {
1955 	__mark_reg_known_zero(&regs[regno]);
1956 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1957 	regs[regno].btf = ds_head->btf;
1958 	regs[regno].btf_id = ds_head->value_btf_id;
1959 	regs[regno].off = ds_head->node_offset;
1960 }
1961 
1962 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1963 {
1964 	return type_is_pkt_pointer(reg->type);
1965 }
1966 
1967 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1968 {
1969 	return reg_is_pkt_pointer(reg) ||
1970 	       reg->type == PTR_TO_PACKET_END;
1971 }
1972 
1973 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1974 {
1975 	return base_type(reg->type) == PTR_TO_MEM &&
1976 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1977 }
1978 
1979 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1980 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1981 				    enum bpf_reg_type which)
1982 {
1983 	/* The register can already have a range from prior markings.
1984 	 * This is fine as long as it hasn't been advanced from its
1985 	 * origin.
1986 	 */
1987 	return reg->type == which &&
1988 	       reg->id == 0 &&
1989 	       reg->off == 0 &&
1990 	       tnum_equals_const(reg->var_off, 0);
1991 }
1992 
1993 /* Reset the min/max bounds of a register */
1994 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1995 {
1996 	reg->smin_value = S64_MIN;
1997 	reg->smax_value = S64_MAX;
1998 	reg->umin_value = 0;
1999 	reg->umax_value = U64_MAX;
2000 
2001 	reg->s32_min_value = S32_MIN;
2002 	reg->s32_max_value = S32_MAX;
2003 	reg->u32_min_value = 0;
2004 	reg->u32_max_value = U32_MAX;
2005 }
2006 
2007 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2008 {
2009 	reg->smin_value = S64_MIN;
2010 	reg->smax_value = S64_MAX;
2011 	reg->umin_value = 0;
2012 	reg->umax_value = U64_MAX;
2013 }
2014 
2015 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2016 {
2017 	reg->s32_min_value = S32_MIN;
2018 	reg->s32_max_value = S32_MAX;
2019 	reg->u32_min_value = 0;
2020 	reg->u32_max_value = U32_MAX;
2021 }
2022 
2023 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2024 {
2025 	struct tnum var32_off = tnum_subreg(reg->var_off);
2026 
2027 	/* min signed is max(sign bit) | min(other bits) */
2028 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2029 			var32_off.value | (var32_off.mask & S32_MIN));
2030 	/* max signed is min(sign bit) | max(other bits) */
2031 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2032 			var32_off.value | (var32_off.mask & S32_MAX));
2033 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2034 	reg->u32_max_value = min(reg->u32_max_value,
2035 				 (u32)(var32_off.value | var32_off.mask));
2036 }
2037 
2038 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2039 {
2040 	/* min signed is max(sign bit) | min(other bits) */
2041 	reg->smin_value = max_t(s64, reg->smin_value,
2042 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2043 	/* max signed is min(sign bit) | max(other bits) */
2044 	reg->smax_value = min_t(s64, reg->smax_value,
2045 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2046 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2047 	reg->umax_value = min(reg->umax_value,
2048 			      reg->var_off.value | reg->var_off.mask);
2049 }
2050 
2051 static void __update_reg_bounds(struct bpf_reg_state *reg)
2052 {
2053 	__update_reg32_bounds(reg);
2054 	__update_reg64_bounds(reg);
2055 }
2056 
2057 /* Uses signed min/max values to inform unsigned, and vice-versa */
2058 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2059 {
2060 	/* Learn sign from signed bounds.
2061 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2062 	 * are the same, so combine.  This works even in the negative case, e.g.
2063 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2064 	 */
2065 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2066 		reg->s32_min_value = reg->u32_min_value =
2067 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2068 		reg->s32_max_value = reg->u32_max_value =
2069 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2070 		return;
2071 	}
2072 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2073 	 * boundary, so we must be careful.
2074 	 */
2075 	if ((s32)reg->u32_max_value >= 0) {
2076 		/* Positive.  We can't learn anything from the smin, but smax
2077 		 * is positive, hence safe.
2078 		 */
2079 		reg->s32_min_value = reg->u32_min_value;
2080 		reg->s32_max_value = reg->u32_max_value =
2081 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2082 	} else if ((s32)reg->u32_min_value < 0) {
2083 		/* Negative.  We can't learn anything from the smax, but smin
2084 		 * is negative, hence safe.
2085 		 */
2086 		reg->s32_min_value = reg->u32_min_value =
2087 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2088 		reg->s32_max_value = reg->u32_max_value;
2089 	}
2090 }
2091 
2092 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2093 {
2094 	/* Learn sign from signed bounds.
2095 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2096 	 * are the same, so combine.  This works even in the negative case, e.g.
2097 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2098 	 */
2099 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2100 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2101 							  reg->umin_value);
2102 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2103 							  reg->umax_value);
2104 		return;
2105 	}
2106 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2107 	 * boundary, so we must be careful.
2108 	 */
2109 	if ((s64)reg->umax_value >= 0) {
2110 		/* Positive.  We can't learn anything from the smin, but smax
2111 		 * is positive, hence safe.
2112 		 */
2113 		reg->smin_value = reg->umin_value;
2114 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2115 							  reg->umax_value);
2116 	} else if ((s64)reg->umin_value < 0) {
2117 		/* Negative.  We can't learn anything from the smax, but smin
2118 		 * is negative, hence safe.
2119 		 */
2120 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2121 							  reg->umin_value);
2122 		reg->smax_value = reg->umax_value;
2123 	}
2124 }
2125 
2126 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2127 {
2128 	__reg32_deduce_bounds(reg);
2129 	__reg64_deduce_bounds(reg);
2130 }
2131 
2132 /* Attempts to improve var_off based on unsigned min/max information */
2133 static void __reg_bound_offset(struct bpf_reg_state *reg)
2134 {
2135 	struct tnum var64_off = tnum_intersect(reg->var_off,
2136 					       tnum_range(reg->umin_value,
2137 							  reg->umax_value));
2138 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2139 					       tnum_range(reg->u32_min_value,
2140 							  reg->u32_max_value));
2141 
2142 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2143 }
2144 
2145 static void reg_bounds_sync(struct bpf_reg_state *reg)
2146 {
2147 	/* We might have learned new bounds from the var_off. */
2148 	__update_reg_bounds(reg);
2149 	/* We might have learned something about the sign bit. */
2150 	__reg_deduce_bounds(reg);
2151 	/* We might have learned some bits from the bounds. */
2152 	__reg_bound_offset(reg);
2153 	/* Intersecting with the old var_off might have improved our bounds
2154 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2155 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2156 	 */
2157 	__update_reg_bounds(reg);
2158 }
2159 
2160 static bool __reg32_bound_s64(s32 a)
2161 {
2162 	return a >= 0 && a <= S32_MAX;
2163 }
2164 
2165 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2166 {
2167 	reg->umin_value = reg->u32_min_value;
2168 	reg->umax_value = reg->u32_max_value;
2169 
2170 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2171 	 * be positive otherwise set to worse case bounds and refine later
2172 	 * from tnum.
2173 	 */
2174 	if (__reg32_bound_s64(reg->s32_min_value) &&
2175 	    __reg32_bound_s64(reg->s32_max_value)) {
2176 		reg->smin_value = reg->s32_min_value;
2177 		reg->smax_value = reg->s32_max_value;
2178 	} else {
2179 		reg->smin_value = 0;
2180 		reg->smax_value = U32_MAX;
2181 	}
2182 }
2183 
2184 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2185 {
2186 	/* special case when 64-bit register has upper 32-bit register
2187 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2188 	 * allowing us to use 32-bit bounds directly,
2189 	 */
2190 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2191 		__reg_assign_32_into_64(reg);
2192 	} else {
2193 		/* Otherwise the best we can do is push lower 32bit known and
2194 		 * unknown bits into register (var_off set from jmp logic)
2195 		 * then learn as much as possible from the 64-bit tnum
2196 		 * known and unknown bits. The previous smin/smax bounds are
2197 		 * invalid here because of jmp32 compare so mark them unknown
2198 		 * so they do not impact tnum bounds calculation.
2199 		 */
2200 		__mark_reg64_unbounded(reg);
2201 	}
2202 	reg_bounds_sync(reg);
2203 }
2204 
2205 static bool __reg64_bound_s32(s64 a)
2206 {
2207 	return a >= S32_MIN && a <= S32_MAX;
2208 }
2209 
2210 static bool __reg64_bound_u32(u64 a)
2211 {
2212 	return a >= U32_MIN && a <= U32_MAX;
2213 }
2214 
2215 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2216 {
2217 	__mark_reg32_unbounded(reg);
2218 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2219 		reg->s32_min_value = (s32)reg->smin_value;
2220 		reg->s32_max_value = (s32)reg->smax_value;
2221 	}
2222 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2223 		reg->u32_min_value = (u32)reg->umin_value;
2224 		reg->u32_max_value = (u32)reg->umax_value;
2225 	}
2226 	reg_bounds_sync(reg);
2227 }
2228 
2229 /* Mark a register as having a completely unknown (scalar) value. */
2230 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2231 			       struct bpf_reg_state *reg)
2232 {
2233 	/*
2234 	 * Clear type, off, and union(map_ptr, range) and
2235 	 * padding between 'type' and union
2236 	 */
2237 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2238 	reg->type = SCALAR_VALUE;
2239 	reg->id = 0;
2240 	reg->ref_obj_id = 0;
2241 	reg->var_off = tnum_unknown;
2242 	reg->frameno = 0;
2243 	reg->precise = !env->bpf_capable;
2244 	__mark_reg_unbounded(reg);
2245 }
2246 
2247 static void mark_reg_unknown(struct bpf_verifier_env *env,
2248 			     struct bpf_reg_state *regs, u32 regno)
2249 {
2250 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2251 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2252 		/* Something bad happened, let's kill all regs except FP */
2253 		for (regno = 0; regno < BPF_REG_FP; regno++)
2254 			__mark_reg_not_init(env, regs + regno);
2255 		return;
2256 	}
2257 	__mark_reg_unknown(env, regs + regno);
2258 }
2259 
2260 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2261 				struct bpf_reg_state *reg)
2262 {
2263 	__mark_reg_unknown(env, reg);
2264 	reg->type = NOT_INIT;
2265 }
2266 
2267 static void mark_reg_not_init(struct bpf_verifier_env *env,
2268 			      struct bpf_reg_state *regs, u32 regno)
2269 {
2270 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2271 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2272 		/* Something bad happened, let's kill all regs except FP */
2273 		for (regno = 0; regno < BPF_REG_FP; regno++)
2274 			__mark_reg_not_init(env, regs + regno);
2275 		return;
2276 	}
2277 	__mark_reg_not_init(env, regs + regno);
2278 }
2279 
2280 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2281 			    struct bpf_reg_state *regs, u32 regno,
2282 			    enum bpf_reg_type reg_type,
2283 			    struct btf *btf, u32 btf_id,
2284 			    enum bpf_type_flag flag)
2285 {
2286 	if (reg_type == SCALAR_VALUE) {
2287 		mark_reg_unknown(env, regs, regno);
2288 		return;
2289 	}
2290 	mark_reg_known_zero(env, regs, regno);
2291 	regs[regno].type = PTR_TO_BTF_ID | flag;
2292 	regs[regno].btf = btf;
2293 	regs[regno].btf_id = btf_id;
2294 }
2295 
2296 #define DEF_NOT_SUBREG	(0)
2297 static void init_reg_state(struct bpf_verifier_env *env,
2298 			   struct bpf_func_state *state)
2299 {
2300 	struct bpf_reg_state *regs = state->regs;
2301 	int i;
2302 
2303 	for (i = 0; i < MAX_BPF_REG; i++) {
2304 		mark_reg_not_init(env, regs, i);
2305 		regs[i].live = REG_LIVE_NONE;
2306 		regs[i].parent = NULL;
2307 		regs[i].subreg_def = DEF_NOT_SUBREG;
2308 	}
2309 
2310 	/* frame pointer */
2311 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2312 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2313 	regs[BPF_REG_FP].frameno = state->frameno;
2314 }
2315 
2316 #define BPF_MAIN_FUNC (-1)
2317 static void init_func_state(struct bpf_verifier_env *env,
2318 			    struct bpf_func_state *state,
2319 			    int callsite, int frameno, int subprogno)
2320 {
2321 	state->callsite = callsite;
2322 	state->frameno = frameno;
2323 	state->subprogno = subprogno;
2324 	state->callback_ret_range = tnum_range(0, 0);
2325 	init_reg_state(env, state);
2326 	mark_verifier_state_scratched(env);
2327 }
2328 
2329 /* Similar to push_stack(), but for async callbacks */
2330 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2331 						int insn_idx, int prev_insn_idx,
2332 						int subprog)
2333 {
2334 	struct bpf_verifier_stack_elem *elem;
2335 	struct bpf_func_state *frame;
2336 
2337 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2338 	if (!elem)
2339 		goto err;
2340 
2341 	elem->insn_idx = insn_idx;
2342 	elem->prev_insn_idx = prev_insn_idx;
2343 	elem->next = env->head;
2344 	elem->log_pos = env->log.end_pos;
2345 	env->head = elem;
2346 	env->stack_size++;
2347 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2348 		verbose(env,
2349 			"The sequence of %d jumps is too complex for async cb.\n",
2350 			env->stack_size);
2351 		goto err;
2352 	}
2353 	/* Unlike push_stack() do not copy_verifier_state().
2354 	 * The caller state doesn't matter.
2355 	 * This is async callback. It starts in a fresh stack.
2356 	 * Initialize it similar to do_check_common().
2357 	 */
2358 	elem->st.branches = 1;
2359 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2360 	if (!frame)
2361 		goto err;
2362 	init_func_state(env, frame,
2363 			BPF_MAIN_FUNC /* callsite */,
2364 			0 /* frameno within this callchain */,
2365 			subprog /* subprog number within this prog */);
2366 	elem->st.frame[0] = frame;
2367 	return &elem->st;
2368 err:
2369 	free_verifier_state(env->cur_state, true);
2370 	env->cur_state = NULL;
2371 	/* pop all elements and return */
2372 	while (!pop_stack(env, NULL, NULL, false));
2373 	return NULL;
2374 }
2375 
2376 
2377 enum reg_arg_type {
2378 	SRC_OP,		/* register is used as source operand */
2379 	DST_OP,		/* register is used as destination operand */
2380 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2381 };
2382 
2383 static int cmp_subprogs(const void *a, const void *b)
2384 {
2385 	return ((struct bpf_subprog_info *)a)->start -
2386 	       ((struct bpf_subprog_info *)b)->start;
2387 }
2388 
2389 static int find_subprog(struct bpf_verifier_env *env, int off)
2390 {
2391 	struct bpf_subprog_info *p;
2392 
2393 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2394 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2395 	if (!p)
2396 		return -ENOENT;
2397 	return p - env->subprog_info;
2398 
2399 }
2400 
2401 static int add_subprog(struct bpf_verifier_env *env, int off)
2402 {
2403 	int insn_cnt = env->prog->len;
2404 	int ret;
2405 
2406 	if (off >= insn_cnt || off < 0) {
2407 		verbose(env, "call to invalid destination\n");
2408 		return -EINVAL;
2409 	}
2410 	ret = find_subprog(env, off);
2411 	if (ret >= 0)
2412 		return ret;
2413 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2414 		verbose(env, "too many subprograms\n");
2415 		return -E2BIG;
2416 	}
2417 	/* determine subprog starts. The end is one before the next starts */
2418 	env->subprog_info[env->subprog_cnt++].start = off;
2419 	sort(env->subprog_info, env->subprog_cnt,
2420 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2421 	return env->subprog_cnt - 1;
2422 }
2423 
2424 #define MAX_KFUNC_DESCS 256
2425 #define MAX_KFUNC_BTFS	256
2426 
2427 struct bpf_kfunc_desc {
2428 	struct btf_func_model func_model;
2429 	u32 func_id;
2430 	s32 imm;
2431 	u16 offset;
2432 	unsigned long addr;
2433 };
2434 
2435 struct bpf_kfunc_btf {
2436 	struct btf *btf;
2437 	struct module *module;
2438 	u16 offset;
2439 };
2440 
2441 struct bpf_kfunc_desc_tab {
2442 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2443 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2444 	 * available, therefore at the end of verification do_misc_fixups()
2445 	 * sorts this by imm and offset.
2446 	 */
2447 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2448 	u32 nr_descs;
2449 };
2450 
2451 struct bpf_kfunc_btf_tab {
2452 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2453 	u32 nr_descs;
2454 };
2455 
2456 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2457 {
2458 	const struct bpf_kfunc_desc *d0 = a;
2459 	const struct bpf_kfunc_desc *d1 = b;
2460 
2461 	/* func_id is not greater than BTF_MAX_TYPE */
2462 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2463 }
2464 
2465 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2466 {
2467 	const struct bpf_kfunc_btf *d0 = a;
2468 	const struct bpf_kfunc_btf *d1 = b;
2469 
2470 	return d0->offset - d1->offset;
2471 }
2472 
2473 static const struct bpf_kfunc_desc *
2474 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2475 {
2476 	struct bpf_kfunc_desc desc = {
2477 		.func_id = func_id,
2478 		.offset = offset,
2479 	};
2480 	struct bpf_kfunc_desc_tab *tab;
2481 
2482 	tab = prog->aux->kfunc_tab;
2483 	return bsearch(&desc, tab->descs, tab->nr_descs,
2484 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2485 }
2486 
2487 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2488 		       u16 btf_fd_idx, u8 **func_addr)
2489 {
2490 	const struct bpf_kfunc_desc *desc;
2491 
2492 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2493 	if (!desc)
2494 		return -EFAULT;
2495 
2496 	*func_addr = (u8 *)desc->addr;
2497 	return 0;
2498 }
2499 
2500 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2501 					 s16 offset)
2502 {
2503 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2504 	struct bpf_kfunc_btf_tab *tab;
2505 	struct bpf_kfunc_btf *b;
2506 	struct module *mod;
2507 	struct btf *btf;
2508 	int btf_fd;
2509 
2510 	tab = env->prog->aux->kfunc_btf_tab;
2511 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2512 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2513 	if (!b) {
2514 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2515 			verbose(env, "too many different module BTFs\n");
2516 			return ERR_PTR(-E2BIG);
2517 		}
2518 
2519 		if (bpfptr_is_null(env->fd_array)) {
2520 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2521 			return ERR_PTR(-EPROTO);
2522 		}
2523 
2524 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2525 					    offset * sizeof(btf_fd),
2526 					    sizeof(btf_fd)))
2527 			return ERR_PTR(-EFAULT);
2528 
2529 		btf = btf_get_by_fd(btf_fd);
2530 		if (IS_ERR(btf)) {
2531 			verbose(env, "invalid module BTF fd specified\n");
2532 			return btf;
2533 		}
2534 
2535 		if (!btf_is_module(btf)) {
2536 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2537 			btf_put(btf);
2538 			return ERR_PTR(-EINVAL);
2539 		}
2540 
2541 		mod = btf_try_get_module(btf);
2542 		if (!mod) {
2543 			btf_put(btf);
2544 			return ERR_PTR(-ENXIO);
2545 		}
2546 
2547 		b = &tab->descs[tab->nr_descs++];
2548 		b->btf = btf;
2549 		b->module = mod;
2550 		b->offset = offset;
2551 
2552 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2553 		     kfunc_btf_cmp_by_off, NULL);
2554 	}
2555 	return b->btf;
2556 }
2557 
2558 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2559 {
2560 	if (!tab)
2561 		return;
2562 
2563 	while (tab->nr_descs--) {
2564 		module_put(tab->descs[tab->nr_descs].module);
2565 		btf_put(tab->descs[tab->nr_descs].btf);
2566 	}
2567 	kfree(tab);
2568 }
2569 
2570 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2571 {
2572 	if (offset) {
2573 		if (offset < 0) {
2574 			/* In the future, this can be allowed to increase limit
2575 			 * of fd index into fd_array, interpreted as u16.
2576 			 */
2577 			verbose(env, "negative offset disallowed for kernel module function call\n");
2578 			return ERR_PTR(-EINVAL);
2579 		}
2580 
2581 		return __find_kfunc_desc_btf(env, offset);
2582 	}
2583 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2584 }
2585 
2586 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2587 {
2588 	const struct btf_type *func, *func_proto;
2589 	struct bpf_kfunc_btf_tab *btf_tab;
2590 	struct bpf_kfunc_desc_tab *tab;
2591 	struct bpf_prog_aux *prog_aux;
2592 	struct bpf_kfunc_desc *desc;
2593 	const char *func_name;
2594 	struct btf *desc_btf;
2595 	unsigned long call_imm;
2596 	unsigned long addr;
2597 	int err;
2598 
2599 	prog_aux = env->prog->aux;
2600 	tab = prog_aux->kfunc_tab;
2601 	btf_tab = prog_aux->kfunc_btf_tab;
2602 	if (!tab) {
2603 		if (!btf_vmlinux) {
2604 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2605 			return -ENOTSUPP;
2606 		}
2607 
2608 		if (!env->prog->jit_requested) {
2609 			verbose(env, "JIT is required for calling kernel function\n");
2610 			return -ENOTSUPP;
2611 		}
2612 
2613 		if (!bpf_jit_supports_kfunc_call()) {
2614 			verbose(env, "JIT does not support calling kernel function\n");
2615 			return -ENOTSUPP;
2616 		}
2617 
2618 		if (!env->prog->gpl_compatible) {
2619 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2620 			return -EINVAL;
2621 		}
2622 
2623 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2624 		if (!tab)
2625 			return -ENOMEM;
2626 		prog_aux->kfunc_tab = tab;
2627 	}
2628 
2629 	/* func_id == 0 is always invalid, but instead of returning an error, be
2630 	 * conservative and wait until the code elimination pass before returning
2631 	 * error, so that invalid calls that get pruned out can be in BPF programs
2632 	 * loaded from userspace.  It is also required that offset be untouched
2633 	 * for such calls.
2634 	 */
2635 	if (!func_id && !offset)
2636 		return 0;
2637 
2638 	if (!btf_tab && offset) {
2639 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2640 		if (!btf_tab)
2641 			return -ENOMEM;
2642 		prog_aux->kfunc_btf_tab = btf_tab;
2643 	}
2644 
2645 	desc_btf = find_kfunc_desc_btf(env, offset);
2646 	if (IS_ERR(desc_btf)) {
2647 		verbose(env, "failed to find BTF for kernel function\n");
2648 		return PTR_ERR(desc_btf);
2649 	}
2650 
2651 	if (find_kfunc_desc(env->prog, func_id, offset))
2652 		return 0;
2653 
2654 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2655 		verbose(env, "too many different kernel function calls\n");
2656 		return -E2BIG;
2657 	}
2658 
2659 	func = btf_type_by_id(desc_btf, func_id);
2660 	if (!func || !btf_type_is_func(func)) {
2661 		verbose(env, "kernel btf_id %u is not a function\n",
2662 			func_id);
2663 		return -EINVAL;
2664 	}
2665 	func_proto = btf_type_by_id(desc_btf, func->type);
2666 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2667 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2668 			func_id);
2669 		return -EINVAL;
2670 	}
2671 
2672 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2673 	addr = kallsyms_lookup_name(func_name);
2674 	if (!addr) {
2675 		verbose(env, "cannot find address for kernel function %s\n",
2676 			func_name);
2677 		return -EINVAL;
2678 	}
2679 	specialize_kfunc(env, func_id, offset, &addr);
2680 
2681 	if (bpf_jit_supports_far_kfunc_call()) {
2682 		call_imm = func_id;
2683 	} else {
2684 		call_imm = BPF_CALL_IMM(addr);
2685 		/* Check whether the relative offset overflows desc->imm */
2686 		if ((unsigned long)(s32)call_imm != call_imm) {
2687 			verbose(env, "address of kernel function %s is out of range\n",
2688 				func_name);
2689 			return -EINVAL;
2690 		}
2691 	}
2692 
2693 	if (bpf_dev_bound_kfunc_id(func_id)) {
2694 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2695 		if (err)
2696 			return err;
2697 	}
2698 
2699 	desc = &tab->descs[tab->nr_descs++];
2700 	desc->func_id = func_id;
2701 	desc->imm = call_imm;
2702 	desc->offset = offset;
2703 	desc->addr = addr;
2704 	err = btf_distill_func_proto(&env->log, desc_btf,
2705 				     func_proto, func_name,
2706 				     &desc->func_model);
2707 	if (!err)
2708 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2709 		     kfunc_desc_cmp_by_id_off, NULL);
2710 	return err;
2711 }
2712 
2713 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2714 {
2715 	const struct bpf_kfunc_desc *d0 = a;
2716 	const struct bpf_kfunc_desc *d1 = b;
2717 
2718 	if (d0->imm != d1->imm)
2719 		return d0->imm < d1->imm ? -1 : 1;
2720 	if (d0->offset != d1->offset)
2721 		return d0->offset < d1->offset ? -1 : 1;
2722 	return 0;
2723 }
2724 
2725 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2726 {
2727 	struct bpf_kfunc_desc_tab *tab;
2728 
2729 	tab = prog->aux->kfunc_tab;
2730 	if (!tab)
2731 		return;
2732 
2733 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2734 	     kfunc_desc_cmp_by_imm_off, NULL);
2735 }
2736 
2737 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2738 {
2739 	return !!prog->aux->kfunc_tab;
2740 }
2741 
2742 const struct btf_func_model *
2743 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2744 			 const struct bpf_insn *insn)
2745 {
2746 	const struct bpf_kfunc_desc desc = {
2747 		.imm = insn->imm,
2748 		.offset = insn->off,
2749 	};
2750 	const struct bpf_kfunc_desc *res;
2751 	struct bpf_kfunc_desc_tab *tab;
2752 
2753 	tab = prog->aux->kfunc_tab;
2754 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2755 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2756 
2757 	return res ? &res->func_model : NULL;
2758 }
2759 
2760 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2761 {
2762 	struct bpf_subprog_info *subprog = env->subprog_info;
2763 	struct bpf_insn *insn = env->prog->insnsi;
2764 	int i, ret, insn_cnt = env->prog->len;
2765 
2766 	/* Add entry function. */
2767 	ret = add_subprog(env, 0);
2768 	if (ret)
2769 		return ret;
2770 
2771 	for (i = 0; i < insn_cnt; i++, insn++) {
2772 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2773 		    !bpf_pseudo_kfunc_call(insn))
2774 			continue;
2775 
2776 		if (!env->bpf_capable) {
2777 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2778 			return -EPERM;
2779 		}
2780 
2781 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2782 			ret = add_subprog(env, i + insn->imm + 1);
2783 		else
2784 			ret = add_kfunc_call(env, insn->imm, insn->off);
2785 
2786 		if (ret < 0)
2787 			return ret;
2788 	}
2789 
2790 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2791 	 * logic. 'subprog_cnt' should not be increased.
2792 	 */
2793 	subprog[env->subprog_cnt].start = insn_cnt;
2794 
2795 	if (env->log.level & BPF_LOG_LEVEL2)
2796 		for (i = 0; i < env->subprog_cnt; i++)
2797 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2798 
2799 	return 0;
2800 }
2801 
2802 static int check_subprogs(struct bpf_verifier_env *env)
2803 {
2804 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2805 	struct bpf_subprog_info *subprog = env->subprog_info;
2806 	struct bpf_insn *insn = env->prog->insnsi;
2807 	int insn_cnt = env->prog->len;
2808 
2809 	/* now check that all jumps are within the same subprog */
2810 	subprog_start = subprog[cur_subprog].start;
2811 	subprog_end = subprog[cur_subprog + 1].start;
2812 	for (i = 0; i < insn_cnt; i++) {
2813 		u8 code = insn[i].code;
2814 
2815 		if (code == (BPF_JMP | BPF_CALL) &&
2816 		    insn[i].src_reg == 0 &&
2817 		    insn[i].imm == BPF_FUNC_tail_call)
2818 			subprog[cur_subprog].has_tail_call = true;
2819 		if (BPF_CLASS(code) == BPF_LD &&
2820 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2821 			subprog[cur_subprog].has_ld_abs = true;
2822 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2823 			goto next;
2824 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2825 			goto next;
2826 		off = i + insn[i].off + 1;
2827 		if (off < subprog_start || off >= subprog_end) {
2828 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2829 			return -EINVAL;
2830 		}
2831 next:
2832 		if (i == subprog_end - 1) {
2833 			/* to avoid fall-through from one subprog into another
2834 			 * the last insn of the subprog should be either exit
2835 			 * or unconditional jump back
2836 			 */
2837 			if (code != (BPF_JMP | BPF_EXIT) &&
2838 			    code != (BPF_JMP | BPF_JA)) {
2839 				verbose(env, "last insn is not an exit or jmp\n");
2840 				return -EINVAL;
2841 			}
2842 			subprog_start = subprog_end;
2843 			cur_subprog++;
2844 			if (cur_subprog < env->subprog_cnt)
2845 				subprog_end = subprog[cur_subprog + 1].start;
2846 		}
2847 	}
2848 	return 0;
2849 }
2850 
2851 /* Parentage chain of this register (or stack slot) should take care of all
2852  * issues like callee-saved registers, stack slot allocation time, etc.
2853  */
2854 static int mark_reg_read(struct bpf_verifier_env *env,
2855 			 const struct bpf_reg_state *state,
2856 			 struct bpf_reg_state *parent, u8 flag)
2857 {
2858 	bool writes = parent == state->parent; /* Observe write marks */
2859 	int cnt = 0;
2860 
2861 	while (parent) {
2862 		/* if read wasn't screened by an earlier write ... */
2863 		if (writes && state->live & REG_LIVE_WRITTEN)
2864 			break;
2865 		if (parent->live & REG_LIVE_DONE) {
2866 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2867 				reg_type_str(env, parent->type),
2868 				parent->var_off.value, parent->off);
2869 			return -EFAULT;
2870 		}
2871 		/* The first condition is more likely to be true than the
2872 		 * second, checked it first.
2873 		 */
2874 		if ((parent->live & REG_LIVE_READ) == flag ||
2875 		    parent->live & REG_LIVE_READ64)
2876 			/* The parentage chain never changes and
2877 			 * this parent was already marked as LIVE_READ.
2878 			 * There is no need to keep walking the chain again and
2879 			 * keep re-marking all parents as LIVE_READ.
2880 			 * This case happens when the same register is read
2881 			 * multiple times without writes into it in-between.
2882 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2883 			 * then no need to set the weak REG_LIVE_READ32.
2884 			 */
2885 			break;
2886 		/* ... then we depend on parent's value */
2887 		parent->live |= flag;
2888 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2889 		if (flag == REG_LIVE_READ64)
2890 			parent->live &= ~REG_LIVE_READ32;
2891 		state = parent;
2892 		parent = state->parent;
2893 		writes = true;
2894 		cnt++;
2895 	}
2896 
2897 	if (env->longest_mark_read_walk < cnt)
2898 		env->longest_mark_read_walk = cnt;
2899 	return 0;
2900 }
2901 
2902 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2903 {
2904 	struct bpf_func_state *state = func(env, reg);
2905 	int spi, ret;
2906 
2907 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2908 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2909 	 * check_kfunc_call.
2910 	 */
2911 	if (reg->type == CONST_PTR_TO_DYNPTR)
2912 		return 0;
2913 	spi = dynptr_get_spi(env, reg);
2914 	if (spi < 0)
2915 		return spi;
2916 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2917 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2918 	 * read.
2919 	 */
2920 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2921 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2922 	if (ret)
2923 		return ret;
2924 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2925 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2926 }
2927 
2928 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2929 			  int spi, int nr_slots)
2930 {
2931 	struct bpf_func_state *state = func(env, reg);
2932 	int err, i;
2933 
2934 	for (i = 0; i < nr_slots; i++) {
2935 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2936 
2937 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2938 		if (err)
2939 			return err;
2940 
2941 		mark_stack_slot_scratched(env, spi - i);
2942 	}
2943 
2944 	return 0;
2945 }
2946 
2947 /* This function is supposed to be used by the following 32-bit optimization
2948  * code only. It returns TRUE if the source or destination register operates
2949  * on 64-bit, otherwise return FALSE.
2950  */
2951 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2952 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2953 {
2954 	u8 code, class, op;
2955 
2956 	code = insn->code;
2957 	class = BPF_CLASS(code);
2958 	op = BPF_OP(code);
2959 	if (class == BPF_JMP) {
2960 		/* BPF_EXIT for "main" will reach here. Return TRUE
2961 		 * conservatively.
2962 		 */
2963 		if (op == BPF_EXIT)
2964 			return true;
2965 		if (op == BPF_CALL) {
2966 			/* BPF to BPF call will reach here because of marking
2967 			 * caller saved clobber with DST_OP_NO_MARK for which we
2968 			 * don't care the register def because they are anyway
2969 			 * marked as NOT_INIT already.
2970 			 */
2971 			if (insn->src_reg == BPF_PSEUDO_CALL)
2972 				return false;
2973 			/* Helper call will reach here because of arg type
2974 			 * check, conservatively return TRUE.
2975 			 */
2976 			if (t == SRC_OP)
2977 				return true;
2978 
2979 			return false;
2980 		}
2981 	}
2982 
2983 	if (class == BPF_ALU64 || class == BPF_JMP ||
2984 	    /* BPF_END always use BPF_ALU class. */
2985 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2986 		return true;
2987 
2988 	if (class == BPF_ALU || class == BPF_JMP32)
2989 		return false;
2990 
2991 	if (class == BPF_LDX) {
2992 		if (t != SRC_OP)
2993 			return BPF_SIZE(code) == BPF_DW;
2994 		/* LDX source must be ptr. */
2995 		return true;
2996 	}
2997 
2998 	if (class == BPF_STX) {
2999 		/* BPF_STX (including atomic variants) has multiple source
3000 		 * operands, one of which is a ptr. Check whether the caller is
3001 		 * asking about it.
3002 		 */
3003 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3004 			return true;
3005 		return BPF_SIZE(code) == BPF_DW;
3006 	}
3007 
3008 	if (class == BPF_LD) {
3009 		u8 mode = BPF_MODE(code);
3010 
3011 		/* LD_IMM64 */
3012 		if (mode == BPF_IMM)
3013 			return true;
3014 
3015 		/* Both LD_IND and LD_ABS return 32-bit data. */
3016 		if (t != SRC_OP)
3017 			return  false;
3018 
3019 		/* Implicit ctx ptr. */
3020 		if (regno == BPF_REG_6)
3021 			return true;
3022 
3023 		/* Explicit source could be any width. */
3024 		return true;
3025 	}
3026 
3027 	if (class == BPF_ST)
3028 		/* The only source register for BPF_ST is a ptr. */
3029 		return true;
3030 
3031 	/* Conservatively return true at default. */
3032 	return true;
3033 }
3034 
3035 /* Return the regno defined by the insn, or -1. */
3036 static int insn_def_regno(const struct bpf_insn *insn)
3037 {
3038 	switch (BPF_CLASS(insn->code)) {
3039 	case BPF_JMP:
3040 	case BPF_JMP32:
3041 	case BPF_ST:
3042 		return -1;
3043 	case BPF_STX:
3044 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3045 		    (insn->imm & BPF_FETCH)) {
3046 			if (insn->imm == BPF_CMPXCHG)
3047 				return BPF_REG_0;
3048 			else
3049 				return insn->src_reg;
3050 		} else {
3051 			return -1;
3052 		}
3053 	default:
3054 		return insn->dst_reg;
3055 	}
3056 }
3057 
3058 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3059 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3060 {
3061 	int dst_reg = insn_def_regno(insn);
3062 
3063 	if (dst_reg == -1)
3064 		return false;
3065 
3066 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3067 }
3068 
3069 static void mark_insn_zext(struct bpf_verifier_env *env,
3070 			   struct bpf_reg_state *reg)
3071 {
3072 	s32 def_idx = reg->subreg_def;
3073 
3074 	if (def_idx == DEF_NOT_SUBREG)
3075 		return;
3076 
3077 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3078 	/* The dst will be zero extended, so won't be sub-register anymore. */
3079 	reg->subreg_def = DEF_NOT_SUBREG;
3080 }
3081 
3082 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3083 			 enum reg_arg_type t)
3084 {
3085 	struct bpf_verifier_state *vstate = env->cur_state;
3086 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3087 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3088 	struct bpf_reg_state *reg, *regs = state->regs;
3089 	bool rw64;
3090 
3091 	if (regno >= MAX_BPF_REG) {
3092 		verbose(env, "R%d is invalid\n", regno);
3093 		return -EINVAL;
3094 	}
3095 
3096 	mark_reg_scratched(env, regno);
3097 
3098 	reg = &regs[regno];
3099 	rw64 = is_reg64(env, insn, regno, reg, t);
3100 	if (t == SRC_OP) {
3101 		/* check whether register used as source operand can be read */
3102 		if (reg->type == NOT_INIT) {
3103 			verbose(env, "R%d !read_ok\n", regno);
3104 			return -EACCES;
3105 		}
3106 		/* We don't need to worry about FP liveness because it's read-only */
3107 		if (regno == BPF_REG_FP)
3108 			return 0;
3109 
3110 		if (rw64)
3111 			mark_insn_zext(env, reg);
3112 
3113 		return mark_reg_read(env, reg, reg->parent,
3114 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3115 	} else {
3116 		/* check whether register used as dest operand can be written to */
3117 		if (regno == BPF_REG_FP) {
3118 			verbose(env, "frame pointer is read only\n");
3119 			return -EACCES;
3120 		}
3121 		reg->live |= REG_LIVE_WRITTEN;
3122 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3123 		if (t == DST_OP)
3124 			mark_reg_unknown(env, regs, regno);
3125 	}
3126 	return 0;
3127 }
3128 
3129 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3130 {
3131 	env->insn_aux_data[idx].jmp_point = true;
3132 }
3133 
3134 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3135 {
3136 	return env->insn_aux_data[insn_idx].jmp_point;
3137 }
3138 
3139 /* for any branch, call, exit record the history of jmps in the given state */
3140 static int push_jmp_history(struct bpf_verifier_env *env,
3141 			    struct bpf_verifier_state *cur)
3142 {
3143 	u32 cnt = cur->jmp_history_cnt;
3144 	struct bpf_idx_pair *p;
3145 	size_t alloc_size;
3146 
3147 	if (!is_jmp_point(env, env->insn_idx))
3148 		return 0;
3149 
3150 	cnt++;
3151 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3152 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3153 	if (!p)
3154 		return -ENOMEM;
3155 	p[cnt - 1].idx = env->insn_idx;
3156 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3157 	cur->jmp_history = p;
3158 	cur->jmp_history_cnt = cnt;
3159 	return 0;
3160 }
3161 
3162 /* Backtrack one insn at a time. If idx is not at the top of recorded
3163  * history then previous instruction came from straight line execution.
3164  */
3165 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3166 			     u32 *history)
3167 {
3168 	u32 cnt = *history;
3169 
3170 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3171 		i = st->jmp_history[cnt - 1].prev_idx;
3172 		(*history)--;
3173 	} else {
3174 		i--;
3175 	}
3176 	return i;
3177 }
3178 
3179 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3180 {
3181 	const struct btf_type *func;
3182 	struct btf *desc_btf;
3183 
3184 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3185 		return NULL;
3186 
3187 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3188 	if (IS_ERR(desc_btf))
3189 		return "<error>";
3190 
3191 	func = btf_type_by_id(desc_btf, insn->imm);
3192 	return btf_name_by_offset(desc_btf, func->name_off);
3193 }
3194 
3195 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3196 {
3197 	bt->frame = frame;
3198 }
3199 
3200 static inline void bt_reset(struct backtrack_state *bt)
3201 {
3202 	struct bpf_verifier_env *env = bt->env;
3203 
3204 	memset(bt, 0, sizeof(*bt));
3205 	bt->env = env;
3206 }
3207 
3208 static inline u32 bt_empty(struct backtrack_state *bt)
3209 {
3210 	u64 mask = 0;
3211 	int i;
3212 
3213 	for (i = 0; i <= bt->frame; i++)
3214 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3215 
3216 	return mask == 0;
3217 }
3218 
3219 static inline int bt_subprog_enter(struct backtrack_state *bt)
3220 {
3221 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3222 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3223 		WARN_ONCE(1, "verifier backtracking bug");
3224 		return -EFAULT;
3225 	}
3226 	bt->frame++;
3227 	return 0;
3228 }
3229 
3230 static inline int bt_subprog_exit(struct backtrack_state *bt)
3231 {
3232 	if (bt->frame == 0) {
3233 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3234 		WARN_ONCE(1, "verifier backtracking bug");
3235 		return -EFAULT;
3236 	}
3237 	bt->frame--;
3238 	return 0;
3239 }
3240 
3241 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3242 {
3243 	bt->reg_masks[frame] |= 1 << reg;
3244 }
3245 
3246 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3247 {
3248 	bt->reg_masks[frame] &= ~(1 << reg);
3249 }
3250 
3251 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3252 {
3253 	bt_set_frame_reg(bt, bt->frame, reg);
3254 }
3255 
3256 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3257 {
3258 	bt_clear_frame_reg(bt, bt->frame, reg);
3259 }
3260 
3261 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3262 {
3263 	bt->stack_masks[frame] |= 1ull << slot;
3264 }
3265 
3266 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3267 {
3268 	bt->stack_masks[frame] &= ~(1ull << slot);
3269 }
3270 
3271 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3272 {
3273 	bt_set_frame_slot(bt, bt->frame, slot);
3274 }
3275 
3276 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3277 {
3278 	bt_clear_frame_slot(bt, bt->frame, slot);
3279 }
3280 
3281 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3282 {
3283 	return bt->reg_masks[frame];
3284 }
3285 
3286 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3287 {
3288 	return bt->reg_masks[bt->frame];
3289 }
3290 
3291 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3292 {
3293 	return bt->stack_masks[frame];
3294 }
3295 
3296 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3297 {
3298 	return bt->stack_masks[bt->frame];
3299 }
3300 
3301 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3302 {
3303 	return bt->reg_masks[bt->frame] & (1 << reg);
3304 }
3305 
3306 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3307 {
3308 	return bt->stack_masks[bt->frame] & (1ull << slot);
3309 }
3310 
3311 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3312 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3313 {
3314 	DECLARE_BITMAP(mask, 64);
3315 	bool first = true;
3316 	int i, n;
3317 
3318 	buf[0] = '\0';
3319 
3320 	bitmap_from_u64(mask, reg_mask);
3321 	for_each_set_bit(i, mask, 32) {
3322 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3323 		first = false;
3324 		buf += n;
3325 		buf_sz -= n;
3326 		if (buf_sz < 0)
3327 			break;
3328 	}
3329 }
3330 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3331 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3332 {
3333 	DECLARE_BITMAP(mask, 64);
3334 	bool first = true;
3335 	int i, n;
3336 
3337 	buf[0] = '\0';
3338 
3339 	bitmap_from_u64(mask, stack_mask);
3340 	for_each_set_bit(i, mask, 64) {
3341 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3342 		first = false;
3343 		buf += n;
3344 		buf_sz -= n;
3345 		if (buf_sz < 0)
3346 			break;
3347 	}
3348 }
3349 
3350 /* For given verifier state backtrack_insn() is called from the last insn to
3351  * the first insn. Its purpose is to compute a bitmask of registers and
3352  * stack slots that needs precision in the parent verifier state.
3353  */
3354 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
3355 			  struct backtrack_state *bt)
3356 {
3357 	const struct bpf_insn_cbs cbs = {
3358 		.cb_call	= disasm_kfunc_name,
3359 		.cb_print	= verbose,
3360 		.private_data	= env,
3361 	};
3362 	struct bpf_insn *insn = env->prog->insnsi + idx;
3363 	u8 class = BPF_CLASS(insn->code);
3364 	u8 opcode = BPF_OP(insn->code);
3365 	u8 mode = BPF_MODE(insn->code);
3366 	u32 dreg = insn->dst_reg;
3367 	u32 sreg = insn->src_reg;
3368 	u32 spi;
3369 
3370 	if (insn->code == 0)
3371 		return 0;
3372 	if (env->log.level & BPF_LOG_LEVEL2) {
3373 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3374 		verbose(env, "mark_precise: frame%d: regs=%s ",
3375 			bt->frame, env->tmp_str_buf);
3376 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3377 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3378 		verbose(env, "%d: ", idx);
3379 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3380 	}
3381 
3382 	if (class == BPF_ALU || class == BPF_ALU64) {
3383 		if (!bt_is_reg_set(bt, dreg))
3384 			return 0;
3385 		if (opcode == BPF_MOV) {
3386 			if (BPF_SRC(insn->code) == BPF_X) {
3387 				/* dreg = sreg
3388 				 * dreg needs precision after this insn
3389 				 * sreg needs precision before this insn
3390 				 */
3391 				bt_clear_reg(bt, dreg);
3392 				bt_set_reg(bt, sreg);
3393 			} else {
3394 				/* dreg = K
3395 				 * dreg needs precision after this insn.
3396 				 * Corresponding register is already marked
3397 				 * as precise=true in this verifier state.
3398 				 * No further markings in parent are necessary
3399 				 */
3400 				bt_clear_reg(bt, dreg);
3401 			}
3402 		} else {
3403 			if (BPF_SRC(insn->code) == BPF_X) {
3404 				/* dreg += sreg
3405 				 * both dreg and sreg need precision
3406 				 * before this insn
3407 				 */
3408 				bt_set_reg(bt, sreg);
3409 			} /* else dreg += K
3410 			   * dreg still needs precision before this insn
3411 			   */
3412 		}
3413 	} else if (class == BPF_LDX) {
3414 		if (!bt_is_reg_set(bt, dreg))
3415 			return 0;
3416 		bt_clear_reg(bt, dreg);
3417 
3418 		/* scalars can only be spilled into stack w/o losing precision.
3419 		 * Load from any other memory can be zero extended.
3420 		 * The desire to keep that precision is already indicated
3421 		 * by 'precise' mark in corresponding register of this state.
3422 		 * No further tracking necessary.
3423 		 */
3424 		if (insn->src_reg != BPF_REG_FP)
3425 			return 0;
3426 
3427 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3428 		 * that [fp - off] slot contains scalar that needs to be
3429 		 * tracked with precision
3430 		 */
3431 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3432 		if (spi >= 64) {
3433 			verbose(env, "BUG spi %d\n", spi);
3434 			WARN_ONCE(1, "verifier backtracking bug");
3435 			return -EFAULT;
3436 		}
3437 		bt_set_slot(bt, spi);
3438 	} else if (class == BPF_STX || class == BPF_ST) {
3439 		if (bt_is_reg_set(bt, dreg))
3440 			/* stx & st shouldn't be using _scalar_ dst_reg
3441 			 * to access memory. It means backtracking
3442 			 * encountered a case of pointer subtraction.
3443 			 */
3444 			return -ENOTSUPP;
3445 		/* scalars can only be spilled into stack */
3446 		if (insn->dst_reg != BPF_REG_FP)
3447 			return 0;
3448 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3449 		if (spi >= 64) {
3450 			verbose(env, "BUG spi %d\n", spi);
3451 			WARN_ONCE(1, "verifier backtracking bug");
3452 			return -EFAULT;
3453 		}
3454 		if (!bt_is_slot_set(bt, spi))
3455 			return 0;
3456 		bt_clear_slot(bt, spi);
3457 		if (class == BPF_STX)
3458 			bt_set_reg(bt, sreg);
3459 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3460 		if (opcode == BPF_CALL) {
3461 			if (insn->src_reg == BPF_PSEUDO_CALL)
3462 				return -ENOTSUPP;
3463 			/* BPF helpers that invoke callback subprogs are
3464 			 * equivalent to BPF_PSEUDO_CALL above
3465 			 */
3466 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3467 				return -ENOTSUPP;
3468 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3469 			 * catch this error later. Make backtracking conservative
3470 			 * with ENOTSUPP.
3471 			 */
3472 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3473 				return -ENOTSUPP;
3474 			/* regular helper call sets R0 */
3475 			bt_clear_reg(bt, BPF_REG_0);
3476 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3477 				/* if backtracing was looking for registers R1-R5
3478 				 * they should have been found already.
3479 				 */
3480 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3481 				WARN_ONCE(1, "verifier backtracking bug");
3482 				return -EFAULT;
3483 			}
3484 		} else if (opcode == BPF_EXIT) {
3485 			return -ENOTSUPP;
3486 		} else if (BPF_SRC(insn->code) == BPF_X) {
3487 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3488 				return 0;
3489 			/* dreg <cond> sreg
3490 			 * Both dreg and sreg need precision before
3491 			 * this insn. If only sreg was marked precise
3492 			 * before it would be equally necessary to
3493 			 * propagate it to dreg.
3494 			 */
3495 			bt_set_reg(bt, dreg);
3496 			bt_set_reg(bt, sreg);
3497 			 /* else dreg <cond> K
3498 			  * Only dreg still needs precision before
3499 			  * this insn, so for the K-based conditional
3500 			  * there is nothing new to be marked.
3501 			  */
3502 		}
3503 	} else if (class == BPF_LD) {
3504 		if (!bt_is_reg_set(bt, dreg))
3505 			return 0;
3506 		bt_clear_reg(bt, dreg);
3507 		/* It's ld_imm64 or ld_abs or ld_ind.
3508 		 * For ld_imm64 no further tracking of precision
3509 		 * into parent is necessary
3510 		 */
3511 		if (mode == BPF_IND || mode == BPF_ABS)
3512 			/* to be analyzed */
3513 			return -ENOTSUPP;
3514 	}
3515 	return 0;
3516 }
3517 
3518 /* the scalar precision tracking algorithm:
3519  * . at the start all registers have precise=false.
3520  * . scalar ranges are tracked as normal through alu and jmp insns.
3521  * . once precise value of the scalar register is used in:
3522  *   .  ptr + scalar alu
3523  *   . if (scalar cond K|scalar)
3524  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3525  *   backtrack through the verifier states and mark all registers and
3526  *   stack slots with spilled constants that these scalar regisers
3527  *   should be precise.
3528  * . during state pruning two registers (or spilled stack slots)
3529  *   are equivalent if both are not precise.
3530  *
3531  * Note the verifier cannot simply walk register parentage chain,
3532  * since many different registers and stack slots could have been
3533  * used to compute single precise scalar.
3534  *
3535  * The approach of starting with precise=true for all registers and then
3536  * backtrack to mark a register as not precise when the verifier detects
3537  * that program doesn't care about specific value (e.g., when helper
3538  * takes register as ARG_ANYTHING parameter) is not safe.
3539  *
3540  * It's ok to walk single parentage chain of the verifier states.
3541  * It's possible that this backtracking will go all the way till 1st insn.
3542  * All other branches will be explored for needing precision later.
3543  *
3544  * The backtracking needs to deal with cases like:
3545  *   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)
3546  * r9 -= r8
3547  * r5 = r9
3548  * if r5 > 0x79f goto pc+7
3549  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3550  * r5 += 1
3551  * ...
3552  * call bpf_perf_event_output#25
3553  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3554  *
3555  * and this case:
3556  * r6 = 1
3557  * call foo // uses callee's r6 inside to compute r0
3558  * r0 += r6
3559  * if r0 == 0 goto
3560  *
3561  * to track above reg_mask/stack_mask needs to be independent for each frame.
3562  *
3563  * Also if parent's curframe > frame where backtracking started,
3564  * the verifier need to mark registers in both frames, otherwise callees
3565  * may incorrectly prune callers. This is similar to
3566  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3567  *
3568  * For now backtracking falls back into conservative marking.
3569  */
3570 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3571 				     struct bpf_verifier_state *st)
3572 {
3573 	struct bpf_func_state *func;
3574 	struct bpf_reg_state *reg;
3575 	int i, j;
3576 
3577 	if (env->log.level & BPF_LOG_LEVEL2) {
3578 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3579 			st->curframe);
3580 	}
3581 
3582 	/* big hammer: mark all scalars precise in this path.
3583 	 * pop_stack may still get !precise scalars.
3584 	 * We also skip current state and go straight to first parent state,
3585 	 * because precision markings in current non-checkpointed state are
3586 	 * not needed. See why in the comment in __mark_chain_precision below.
3587 	 */
3588 	for (st = st->parent; st; st = st->parent) {
3589 		for (i = 0; i <= st->curframe; i++) {
3590 			func = st->frame[i];
3591 			for (j = 0; j < BPF_REG_FP; j++) {
3592 				reg = &func->regs[j];
3593 				if (reg->type != SCALAR_VALUE || reg->precise)
3594 					continue;
3595 				reg->precise = true;
3596 				if (env->log.level & BPF_LOG_LEVEL2) {
3597 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3598 						i, j);
3599 				}
3600 			}
3601 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3602 				if (!is_spilled_reg(&func->stack[j]))
3603 					continue;
3604 				reg = &func->stack[j].spilled_ptr;
3605 				if (reg->type != SCALAR_VALUE || reg->precise)
3606 					continue;
3607 				reg->precise = true;
3608 				if (env->log.level & BPF_LOG_LEVEL2) {
3609 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3610 						i, -(j + 1) * 8);
3611 				}
3612 			}
3613 		}
3614 	}
3615 }
3616 
3617 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3618 {
3619 	struct bpf_func_state *func;
3620 	struct bpf_reg_state *reg;
3621 	int i, j;
3622 
3623 	for (i = 0; i <= st->curframe; i++) {
3624 		func = st->frame[i];
3625 		for (j = 0; j < BPF_REG_FP; j++) {
3626 			reg = &func->regs[j];
3627 			if (reg->type != SCALAR_VALUE)
3628 				continue;
3629 			reg->precise = false;
3630 		}
3631 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3632 			if (!is_spilled_reg(&func->stack[j]))
3633 				continue;
3634 			reg = &func->stack[j].spilled_ptr;
3635 			if (reg->type != SCALAR_VALUE)
3636 				continue;
3637 			reg->precise = false;
3638 		}
3639 	}
3640 }
3641 
3642 /*
3643  * __mark_chain_precision() backtracks BPF program instruction sequence and
3644  * chain of verifier states making sure that register *regno* (if regno >= 0)
3645  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3646  * SCALARS, as well as any other registers and slots that contribute to
3647  * a tracked state of given registers/stack slots, depending on specific BPF
3648  * assembly instructions (see backtrack_insns() for exact instruction handling
3649  * logic). This backtracking relies on recorded jmp_history and is able to
3650  * traverse entire chain of parent states. This process ends only when all the
3651  * necessary registers/slots and their transitive dependencies are marked as
3652  * precise.
3653  *
3654  * One important and subtle aspect is that precise marks *do not matter* in
3655  * the currently verified state (current state). It is important to understand
3656  * why this is the case.
3657  *
3658  * First, note that current state is the state that is not yet "checkpointed",
3659  * i.e., it is not yet put into env->explored_states, and it has no children
3660  * states as well. It's ephemeral, and can end up either a) being discarded if
3661  * compatible explored state is found at some point or BPF_EXIT instruction is
3662  * reached or b) checkpointed and put into env->explored_states, branching out
3663  * into one or more children states.
3664  *
3665  * In the former case, precise markings in current state are completely
3666  * ignored by state comparison code (see regsafe() for details). Only
3667  * checkpointed ("old") state precise markings are important, and if old
3668  * state's register/slot is precise, regsafe() assumes current state's
3669  * register/slot as precise and checks value ranges exactly and precisely. If
3670  * states turn out to be compatible, current state's necessary precise
3671  * markings and any required parent states' precise markings are enforced
3672  * after the fact with propagate_precision() logic, after the fact. But it's
3673  * important to realize that in this case, even after marking current state
3674  * registers/slots as precise, we immediately discard current state. So what
3675  * actually matters is any of the precise markings propagated into current
3676  * state's parent states, which are always checkpointed (due to b) case above).
3677  * As such, for scenario a) it doesn't matter if current state has precise
3678  * markings set or not.
3679  *
3680  * Now, for the scenario b), checkpointing and forking into child(ren)
3681  * state(s). Note that before current state gets to checkpointing step, any
3682  * processed instruction always assumes precise SCALAR register/slot
3683  * knowledge: if precise value or range is useful to prune jump branch, BPF
3684  * verifier takes this opportunity enthusiastically. Similarly, when
3685  * register's value is used to calculate offset or memory address, exact
3686  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3687  * what we mentioned above about state comparison ignoring precise markings
3688  * during state comparison, BPF verifier ignores and also assumes precise
3689  * markings *at will* during instruction verification process. But as verifier
3690  * assumes precision, it also propagates any precision dependencies across
3691  * parent states, which are not yet finalized, so can be further restricted
3692  * based on new knowledge gained from restrictions enforced by their children
3693  * states. This is so that once those parent states are finalized, i.e., when
3694  * they have no more active children state, state comparison logic in
3695  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3696  * required for correctness.
3697  *
3698  * To build a bit more intuition, note also that once a state is checkpointed,
3699  * the path we took to get to that state is not important. This is crucial
3700  * property for state pruning. When state is checkpointed and finalized at
3701  * some instruction index, it can be correctly and safely used to "short
3702  * circuit" any *compatible* state that reaches exactly the same instruction
3703  * index. I.e., if we jumped to that instruction from a completely different
3704  * code path than original finalized state was derived from, it doesn't
3705  * matter, current state can be discarded because from that instruction
3706  * forward having a compatible state will ensure we will safely reach the
3707  * exit. States describe preconditions for further exploration, but completely
3708  * forget the history of how we got here.
3709  *
3710  * This also means that even if we needed precise SCALAR range to get to
3711  * finalized state, but from that point forward *that same* SCALAR register is
3712  * never used in a precise context (i.e., it's precise value is not needed for
3713  * correctness), it's correct and safe to mark such register as "imprecise"
3714  * (i.e., precise marking set to false). This is what we rely on when we do
3715  * not set precise marking in current state. If no child state requires
3716  * precision for any given SCALAR register, it's safe to dictate that it can
3717  * be imprecise. If any child state does require this register to be precise,
3718  * we'll mark it precise later retroactively during precise markings
3719  * propagation from child state to parent states.
3720  *
3721  * Skipping precise marking setting in current state is a mild version of
3722  * relying on the above observation. But we can utilize this property even
3723  * more aggressively by proactively forgetting any precise marking in the
3724  * current state (which we inherited from the parent state), right before we
3725  * checkpoint it and branch off into new child state. This is done by
3726  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3727  * finalized states which help in short circuiting more future states.
3728  */
3729 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3730 {
3731 	struct backtrack_state *bt = &env->bt;
3732 	struct bpf_verifier_state *st = env->cur_state;
3733 	int first_idx = st->first_insn_idx;
3734 	int last_idx = env->insn_idx;
3735 	struct bpf_func_state *func;
3736 	struct bpf_reg_state *reg;
3737 	bool skip_first = true;
3738 	int i, fr, err;
3739 
3740 	if (!env->bpf_capable)
3741 		return 0;
3742 
3743 	/* set frame number from which we are starting to backtrack */
3744 	bt_init(bt, env->cur_state->curframe);
3745 
3746 	/* Do sanity checks against current state of register and/or stack
3747 	 * slot, but don't set precise flag in current state, as precision
3748 	 * tracking in the current state is unnecessary.
3749 	 */
3750 	func = st->frame[bt->frame];
3751 	if (regno >= 0) {
3752 		reg = &func->regs[regno];
3753 		if (reg->type != SCALAR_VALUE) {
3754 			WARN_ONCE(1, "backtracing misuse");
3755 			return -EFAULT;
3756 		}
3757 		bt_set_reg(bt, regno);
3758 	}
3759 
3760 	if (bt_empty(bt))
3761 		return 0;
3762 
3763 	for (;;) {
3764 		DECLARE_BITMAP(mask, 64);
3765 		u32 history = st->jmp_history_cnt;
3766 
3767 		if (env->log.level & BPF_LOG_LEVEL2) {
3768 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d\n",
3769 				bt->frame, last_idx, first_idx);
3770 		}
3771 
3772 		if (last_idx < 0) {
3773 			/* we are at the entry into subprog, which
3774 			 * is expected for global funcs, but only if
3775 			 * requested precise registers are R1-R5
3776 			 * (which are global func's input arguments)
3777 			 */
3778 			if (st->curframe == 0 &&
3779 			    st->frame[0]->subprogno > 0 &&
3780 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3781 			    bt_stack_mask(bt) == 0 &&
3782 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
3783 				bitmap_from_u64(mask, bt_reg_mask(bt));
3784 				for_each_set_bit(i, mask, 32) {
3785 					reg = &st->frame[0]->regs[i];
3786 					if (reg->type != SCALAR_VALUE) {
3787 						bt_clear_reg(bt, i);
3788 						continue;
3789 					}
3790 					reg->precise = true;
3791 				}
3792 				return 0;
3793 			}
3794 
3795 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
3796 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
3797 			WARN_ONCE(1, "verifier backtracking bug");
3798 			return -EFAULT;
3799 		}
3800 
3801 		for (i = last_idx;;) {
3802 			if (skip_first) {
3803 				err = 0;
3804 				skip_first = false;
3805 			} else {
3806 				err = backtrack_insn(env, i, bt);
3807 			}
3808 			if (err == -ENOTSUPP) {
3809 				mark_all_scalars_precise(env, st);
3810 				bt_reset(bt);
3811 				return 0;
3812 			} else if (err) {
3813 				return err;
3814 			}
3815 			if (bt_empty(bt))
3816 				/* Found assignment(s) into tracked register in this state.
3817 				 * Since this state is already marked, just return.
3818 				 * Nothing to be tracked further in the parent state.
3819 				 */
3820 				return 0;
3821 			if (i == first_idx)
3822 				break;
3823 			i = get_prev_insn_idx(st, i, &history);
3824 			if (i >= env->prog->len) {
3825 				/* This can happen if backtracking reached insn 0
3826 				 * and there are still reg_mask or stack_mask
3827 				 * to backtrack.
3828 				 * It means the backtracking missed the spot where
3829 				 * particular register was initialized with a constant.
3830 				 */
3831 				verbose(env, "BUG backtracking idx %d\n", i);
3832 				WARN_ONCE(1, "verifier backtracking bug");
3833 				return -EFAULT;
3834 			}
3835 		}
3836 		st = st->parent;
3837 		if (!st)
3838 			break;
3839 
3840 		for (fr = bt->frame; fr >= 0; fr--) {
3841 			func = st->frame[fr];
3842 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3843 			for_each_set_bit(i, mask, 32) {
3844 				reg = &func->regs[i];
3845 				if (reg->type != SCALAR_VALUE) {
3846 					bt_clear_frame_reg(bt, fr, i);
3847 					continue;
3848 				}
3849 				if (reg->precise)
3850 					bt_clear_frame_reg(bt, fr, i);
3851 				else
3852 					reg->precise = true;
3853 			}
3854 
3855 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3856 			for_each_set_bit(i, mask, 64) {
3857 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
3858 					/* the sequence of instructions:
3859 					 * 2: (bf) r3 = r10
3860 					 * 3: (7b) *(u64 *)(r3 -8) = r0
3861 					 * 4: (79) r4 = *(u64 *)(r10 -8)
3862 					 * doesn't contain jmps. It's backtracked
3863 					 * as a single block.
3864 					 * During backtracking insn 3 is not recognized as
3865 					 * stack access, so at the end of backtracking
3866 					 * stack slot fp-8 is still marked in stack_mask.
3867 					 * However the parent state may not have accessed
3868 					 * fp-8 and it's "unallocated" stack space.
3869 					 * In such case fallback to conservative.
3870 					 */
3871 					mark_all_scalars_precise(env, st);
3872 					bt_reset(bt);
3873 					return 0;
3874 				}
3875 
3876 				if (!is_spilled_scalar_reg(&func->stack[i])) {
3877 					bt_clear_frame_slot(bt, fr, i);
3878 					continue;
3879 				}
3880 				reg = &func->stack[i].spilled_ptr;
3881 				if (reg->precise)
3882 					bt_clear_frame_slot(bt, fr, i);
3883 				else
3884 					reg->precise = true;
3885 			}
3886 			if (env->log.level & BPF_LOG_LEVEL2) {
3887 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
3888 					     bt_frame_reg_mask(bt, fr));
3889 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
3890 					fr, env->tmp_str_buf);
3891 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
3892 					       bt_frame_stack_mask(bt, fr));
3893 				verbose(env, "stack=%s: ", env->tmp_str_buf);
3894 				print_verifier_state(env, func, true);
3895 			}
3896 		}
3897 
3898 		if (bt_empty(bt))
3899 			break;
3900 
3901 		last_idx = st->last_insn_idx;
3902 		first_idx = st->first_insn_idx;
3903 	}
3904 	return 0;
3905 }
3906 
3907 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3908 {
3909 	return __mark_chain_precision(env, regno);
3910 }
3911 
3912 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3913  * desired reg and stack masks across all relevant frames
3914  */
3915 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
3916 {
3917 	return __mark_chain_precision(env, -1);
3918 }
3919 
3920 static bool is_spillable_regtype(enum bpf_reg_type type)
3921 {
3922 	switch (base_type(type)) {
3923 	case PTR_TO_MAP_VALUE:
3924 	case PTR_TO_STACK:
3925 	case PTR_TO_CTX:
3926 	case PTR_TO_PACKET:
3927 	case PTR_TO_PACKET_META:
3928 	case PTR_TO_PACKET_END:
3929 	case PTR_TO_FLOW_KEYS:
3930 	case CONST_PTR_TO_MAP:
3931 	case PTR_TO_SOCKET:
3932 	case PTR_TO_SOCK_COMMON:
3933 	case PTR_TO_TCP_SOCK:
3934 	case PTR_TO_XDP_SOCK:
3935 	case PTR_TO_BTF_ID:
3936 	case PTR_TO_BUF:
3937 	case PTR_TO_MEM:
3938 	case PTR_TO_FUNC:
3939 	case PTR_TO_MAP_KEY:
3940 		return true;
3941 	default:
3942 		return false;
3943 	}
3944 }
3945 
3946 /* Does this register contain a constant zero? */
3947 static bool register_is_null(struct bpf_reg_state *reg)
3948 {
3949 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3950 }
3951 
3952 static bool register_is_const(struct bpf_reg_state *reg)
3953 {
3954 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3955 }
3956 
3957 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3958 {
3959 	return tnum_is_unknown(reg->var_off) &&
3960 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3961 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3962 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3963 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3964 }
3965 
3966 static bool register_is_bounded(struct bpf_reg_state *reg)
3967 {
3968 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3969 }
3970 
3971 static bool __is_pointer_value(bool allow_ptr_leaks,
3972 			       const struct bpf_reg_state *reg)
3973 {
3974 	if (allow_ptr_leaks)
3975 		return false;
3976 
3977 	return reg->type != SCALAR_VALUE;
3978 }
3979 
3980 /* Copy src state preserving dst->parent and dst->live fields */
3981 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3982 {
3983 	struct bpf_reg_state *parent = dst->parent;
3984 	enum bpf_reg_liveness live = dst->live;
3985 
3986 	*dst = *src;
3987 	dst->parent = parent;
3988 	dst->live = live;
3989 }
3990 
3991 static void save_register_state(struct bpf_func_state *state,
3992 				int spi, struct bpf_reg_state *reg,
3993 				int size)
3994 {
3995 	int i;
3996 
3997 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
3998 	if (size == BPF_REG_SIZE)
3999 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4000 
4001 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4002 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4003 
4004 	/* size < 8 bytes spill */
4005 	for (; i; i--)
4006 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4007 }
4008 
4009 static bool is_bpf_st_mem(struct bpf_insn *insn)
4010 {
4011 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4012 }
4013 
4014 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4015  * stack boundary and alignment are checked in check_mem_access()
4016  */
4017 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4018 				       /* stack frame we're writing to */
4019 				       struct bpf_func_state *state,
4020 				       int off, int size, int value_regno,
4021 				       int insn_idx)
4022 {
4023 	struct bpf_func_state *cur; /* state of the current function */
4024 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4025 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4026 	struct bpf_reg_state *reg = NULL;
4027 	u32 dst_reg = insn->dst_reg;
4028 
4029 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4030 	if (err)
4031 		return err;
4032 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4033 	 * so it's aligned access and [off, off + size) are within stack limits
4034 	 */
4035 	if (!env->allow_ptr_leaks &&
4036 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
4037 	    size != BPF_REG_SIZE) {
4038 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4039 		return -EACCES;
4040 	}
4041 
4042 	cur = env->cur_state->frame[env->cur_state->curframe];
4043 	if (value_regno >= 0)
4044 		reg = &cur->regs[value_regno];
4045 	if (!env->bypass_spec_v4) {
4046 		bool sanitize = reg && is_spillable_regtype(reg->type);
4047 
4048 		for (i = 0; i < size; i++) {
4049 			u8 type = state->stack[spi].slot_type[i];
4050 
4051 			if (type != STACK_MISC && type != STACK_ZERO) {
4052 				sanitize = true;
4053 				break;
4054 			}
4055 		}
4056 
4057 		if (sanitize)
4058 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4059 	}
4060 
4061 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4062 	if (err)
4063 		return err;
4064 
4065 	mark_stack_slot_scratched(env, spi);
4066 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4067 	    !register_is_null(reg) && env->bpf_capable) {
4068 		if (dst_reg != BPF_REG_FP) {
4069 			/* The backtracking logic can only recognize explicit
4070 			 * stack slot address like [fp - 8]. Other spill of
4071 			 * scalar via different register has to be conservative.
4072 			 * Backtrack from here and mark all registers as precise
4073 			 * that contributed into 'reg' being a constant.
4074 			 */
4075 			err = mark_chain_precision(env, value_regno);
4076 			if (err)
4077 				return err;
4078 		}
4079 		save_register_state(state, spi, reg, size);
4080 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4081 		   insn->imm != 0 && env->bpf_capable) {
4082 		struct bpf_reg_state fake_reg = {};
4083 
4084 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4085 		fake_reg.type = SCALAR_VALUE;
4086 		save_register_state(state, spi, &fake_reg, size);
4087 	} else if (reg && is_spillable_regtype(reg->type)) {
4088 		/* register containing pointer is being spilled into stack */
4089 		if (size != BPF_REG_SIZE) {
4090 			verbose_linfo(env, insn_idx, "; ");
4091 			verbose(env, "invalid size of register spill\n");
4092 			return -EACCES;
4093 		}
4094 		if (state != cur && reg->type == PTR_TO_STACK) {
4095 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4096 			return -EINVAL;
4097 		}
4098 		save_register_state(state, spi, reg, size);
4099 	} else {
4100 		u8 type = STACK_MISC;
4101 
4102 		/* regular write of data into stack destroys any spilled ptr */
4103 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4104 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4105 		if (is_stack_slot_special(&state->stack[spi]))
4106 			for (i = 0; i < BPF_REG_SIZE; i++)
4107 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4108 
4109 		/* only mark the slot as written if all 8 bytes were written
4110 		 * otherwise read propagation may incorrectly stop too soon
4111 		 * when stack slots are partially written.
4112 		 * This heuristic means that read propagation will be
4113 		 * conservative, since it will add reg_live_read marks
4114 		 * to stack slots all the way to first state when programs
4115 		 * writes+reads less than 8 bytes
4116 		 */
4117 		if (size == BPF_REG_SIZE)
4118 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4119 
4120 		/* when we zero initialize stack slots mark them as such */
4121 		if ((reg && register_is_null(reg)) ||
4122 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4123 			/* backtracking doesn't work for STACK_ZERO yet. */
4124 			err = mark_chain_precision(env, value_regno);
4125 			if (err)
4126 				return err;
4127 			type = STACK_ZERO;
4128 		}
4129 
4130 		/* Mark slots affected by this stack write. */
4131 		for (i = 0; i < size; i++)
4132 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4133 				type;
4134 	}
4135 	return 0;
4136 }
4137 
4138 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4139  * known to contain a variable offset.
4140  * This function checks whether the write is permitted and conservatively
4141  * tracks the effects of the write, considering that each stack slot in the
4142  * dynamic range is potentially written to.
4143  *
4144  * 'off' includes 'regno->off'.
4145  * 'value_regno' can be -1, meaning that an unknown value is being written to
4146  * the stack.
4147  *
4148  * Spilled pointers in range are not marked as written because we don't know
4149  * what's going to be actually written. This means that read propagation for
4150  * future reads cannot be terminated by this write.
4151  *
4152  * For privileged programs, uninitialized stack slots are considered
4153  * initialized by this write (even though we don't know exactly what offsets
4154  * are going to be written to). The idea is that we don't want the verifier to
4155  * reject future reads that access slots written to through variable offsets.
4156  */
4157 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4158 				     /* func where register points to */
4159 				     struct bpf_func_state *state,
4160 				     int ptr_regno, int off, int size,
4161 				     int value_regno, int insn_idx)
4162 {
4163 	struct bpf_func_state *cur; /* state of the current function */
4164 	int min_off, max_off;
4165 	int i, err;
4166 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4167 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4168 	bool writing_zero = false;
4169 	/* set if the fact that we're writing a zero is used to let any
4170 	 * stack slots remain STACK_ZERO
4171 	 */
4172 	bool zero_used = false;
4173 
4174 	cur = env->cur_state->frame[env->cur_state->curframe];
4175 	ptr_reg = &cur->regs[ptr_regno];
4176 	min_off = ptr_reg->smin_value + off;
4177 	max_off = ptr_reg->smax_value + off + size;
4178 	if (value_regno >= 0)
4179 		value_reg = &cur->regs[value_regno];
4180 	if ((value_reg && register_is_null(value_reg)) ||
4181 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4182 		writing_zero = true;
4183 
4184 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4185 	if (err)
4186 		return err;
4187 
4188 	for (i = min_off; i < max_off; i++) {
4189 		int spi;
4190 
4191 		spi = __get_spi(i);
4192 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4193 		if (err)
4194 			return err;
4195 	}
4196 
4197 	/* Variable offset writes destroy any spilled pointers in range. */
4198 	for (i = min_off; i < max_off; i++) {
4199 		u8 new_type, *stype;
4200 		int slot, spi;
4201 
4202 		slot = -i - 1;
4203 		spi = slot / BPF_REG_SIZE;
4204 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4205 		mark_stack_slot_scratched(env, spi);
4206 
4207 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4208 			/* Reject the write if range we may write to has not
4209 			 * been initialized beforehand. If we didn't reject
4210 			 * here, the ptr status would be erased below (even
4211 			 * though not all slots are actually overwritten),
4212 			 * possibly opening the door to leaks.
4213 			 *
4214 			 * We do however catch STACK_INVALID case below, and
4215 			 * only allow reading possibly uninitialized memory
4216 			 * later for CAP_PERFMON, as the write may not happen to
4217 			 * that slot.
4218 			 */
4219 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4220 				insn_idx, i);
4221 			return -EINVAL;
4222 		}
4223 
4224 		/* Erase all spilled pointers. */
4225 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4226 
4227 		/* Update the slot type. */
4228 		new_type = STACK_MISC;
4229 		if (writing_zero && *stype == STACK_ZERO) {
4230 			new_type = STACK_ZERO;
4231 			zero_used = true;
4232 		}
4233 		/* If the slot is STACK_INVALID, we check whether it's OK to
4234 		 * pretend that it will be initialized by this write. The slot
4235 		 * might not actually be written to, and so if we mark it as
4236 		 * initialized future reads might leak uninitialized memory.
4237 		 * For privileged programs, we will accept such reads to slots
4238 		 * that may or may not be written because, if we're reject
4239 		 * them, the error would be too confusing.
4240 		 */
4241 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4242 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4243 					insn_idx, i);
4244 			return -EINVAL;
4245 		}
4246 		*stype = new_type;
4247 	}
4248 	if (zero_used) {
4249 		/* backtracking doesn't work for STACK_ZERO yet. */
4250 		err = mark_chain_precision(env, value_regno);
4251 		if (err)
4252 			return err;
4253 	}
4254 	return 0;
4255 }
4256 
4257 /* When register 'dst_regno' is assigned some values from stack[min_off,
4258  * max_off), we set the register's type according to the types of the
4259  * respective stack slots. If all the stack values are known to be zeros, then
4260  * so is the destination reg. Otherwise, the register is considered to be
4261  * SCALAR. This function does not deal with register filling; the caller must
4262  * ensure that all spilled registers in the stack range have been marked as
4263  * read.
4264  */
4265 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4266 				/* func where src register points to */
4267 				struct bpf_func_state *ptr_state,
4268 				int min_off, int max_off, int dst_regno)
4269 {
4270 	struct bpf_verifier_state *vstate = env->cur_state;
4271 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4272 	int i, slot, spi;
4273 	u8 *stype;
4274 	int zeros = 0;
4275 
4276 	for (i = min_off; i < max_off; i++) {
4277 		slot = -i - 1;
4278 		spi = slot / BPF_REG_SIZE;
4279 		mark_stack_slot_scratched(env, spi);
4280 		stype = ptr_state->stack[spi].slot_type;
4281 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4282 			break;
4283 		zeros++;
4284 	}
4285 	if (zeros == max_off - min_off) {
4286 		/* any access_size read into register is zero extended,
4287 		 * so the whole register == const_zero
4288 		 */
4289 		__mark_reg_const_zero(&state->regs[dst_regno]);
4290 		/* backtracking doesn't support STACK_ZERO yet,
4291 		 * so mark it precise here, so that later
4292 		 * backtracking can stop here.
4293 		 * Backtracking may not need this if this register
4294 		 * doesn't participate in pointer adjustment.
4295 		 * Forward propagation of precise flag is not
4296 		 * necessary either. This mark is only to stop
4297 		 * backtracking. Any register that contributed
4298 		 * to const 0 was marked precise before spill.
4299 		 */
4300 		state->regs[dst_regno].precise = true;
4301 	} else {
4302 		/* have read misc data from the stack */
4303 		mark_reg_unknown(env, state->regs, dst_regno);
4304 	}
4305 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4306 }
4307 
4308 /* Read the stack at 'off' and put the results into the register indicated by
4309  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4310  * spilled reg.
4311  *
4312  * 'dst_regno' can be -1, meaning that the read value is not going to a
4313  * register.
4314  *
4315  * The access is assumed to be within the current stack bounds.
4316  */
4317 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4318 				      /* func where src register points to */
4319 				      struct bpf_func_state *reg_state,
4320 				      int off, int size, int dst_regno)
4321 {
4322 	struct bpf_verifier_state *vstate = env->cur_state;
4323 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4324 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4325 	struct bpf_reg_state *reg;
4326 	u8 *stype, type;
4327 
4328 	stype = reg_state->stack[spi].slot_type;
4329 	reg = &reg_state->stack[spi].spilled_ptr;
4330 
4331 	mark_stack_slot_scratched(env, spi);
4332 
4333 	if (is_spilled_reg(&reg_state->stack[spi])) {
4334 		u8 spill_size = 1;
4335 
4336 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4337 			spill_size++;
4338 
4339 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4340 			if (reg->type != SCALAR_VALUE) {
4341 				verbose_linfo(env, env->insn_idx, "; ");
4342 				verbose(env, "invalid size of register fill\n");
4343 				return -EACCES;
4344 			}
4345 
4346 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4347 			if (dst_regno < 0)
4348 				return 0;
4349 
4350 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4351 				/* The earlier check_reg_arg() has decided the
4352 				 * subreg_def for this insn.  Save it first.
4353 				 */
4354 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4355 
4356 				copy_register_state(&state->regs[dst_regno], reg);
4357 				state->regs[dst_regno].subreg_def = subreg_def;
4358 			} else {
4359 				for (i = 0; i < size; i++) {
4360 					type = stype[(slot - i) % BPF_REG_SIZE];
4361 					if (type == STACK_SPILL)
4362 						continue;
4363 					if (type == STACK_MISC)
4364 						continue;
4365 					if (type == STACK_INVALID && env->allow_uninit_stack)
4366 						continue;
4367 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4368 						off, i, size);
4369 					return -EACCES;
4370 				}
4371 				mark_reg_unknown(env, state->regs, dst_regno);
4372 			}
4373 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4374 			return 0;
4375 		}
4376 
4377 		if (dst_regno >= 0) {
4378 			/* restore register state from stack */
4379 			copy_register_state(&state->regs[dst_regno], reg);
4380 			/* mark reg as written since spilled pointer state likely
4381 			 * has its liveness marks cleared by is_state_visited()
4382 			 * which resets stack/reg liveness for state transitions
4383 			 */
4384 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4385 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4386 			/* If dst_regno==-1, the caller is asking us whether
4387 			 * it is acceptable to use this value as a SCALAR_VALUE
4388 			 * (e.g. for XADD).
4389 			 * We must not allow unprivileged callers to do that
4390 			 * with spilled pointers.
4391 			 */
4392 			verbose(env, "leaking pointer from stack off %d\n",
4393 				off);
4394 			return -EACCES;
4395 		}
4396 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4397 	} else {
4398 		for (i = 0; i < size; i++) {
4399 			type = stype[(slot - i) % BPF_REG_SIZE];
4400 			if (type == STACK_MISC)
4401 				continue;
4402 			if (type == STACK_ZERO)
4403 				continue;
4404 			if (type == STACK_INVALID && env->allow_uninit_stack)
4405 				continue;
4406 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4407 				off, i, size);
4408 			return -EACCES;
4409 		}
4410 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4411 		if (dst_regno >= 0)
4412 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4413 	}
4414 	return 0;
4415 }
4416 
4417 enum bpf_access_src {
4418 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4419 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4420 };
4421 
4422 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4423 					 int regno, int off, int access_size,
4424 					 bool zero_size_allowed,
4425 					 enum bpf_access_src type,
4426 					 struct bpf_call_arg_meta *meta);
4427 
4428 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4429 {
4430 	return cur_regs(env) + regno;
4431 }
4432 
4433 /* Read the stack at 'ptr_regno + off' and put the result into the register
4434  * 'dst_regno'.
4435  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4436  * but not its variable offset.
4437  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4438  *
4439  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4440  * filling registers (i.e. reads of spilled register cannot be detected when
4441  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4442  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4443  * offset; for a fixed offset check_stack_read_fixed_off should be used
4444  * instead.
4445  */
4446 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4447 				    int ptr_regno, int off, int size, int dst_regno)
4448 {
4449 	/* The state of the source register. */
4450 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4451 	struct bpf_func_state *ptr_state = func(env, reg);
4452 	int err;
4453 	int min_off, max_off;
4454 
4455 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4456 	 */
4457 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4458 					    false, ACCESS_DIRECT, NULL);
4459 	if (err)
4460 		return err;
4461 
4462 	min_off = reg->smin_value + off;
4463 	max_off = reg->smax_value + off;
4464 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4465 	return 0;
4466 }
4467 
4468 /* check_stack_read dispatches to check_stack_read_fixed_off or
4469  * check_stack_read_var_off.
4470  *
4471  * The caller must ensure that the offset falls within the allocated stack
4472  * bounds.
4473  *
4474  * 'dst_regno' is a register which will receive the value from the stack. It
4475  * can be -1, meaning that the read value is not going to a register.
4476  */
4477 static int check_stack_read(struct bpf_verifier_env *env,
4478 			    int ptr_regno, int off, int size,
4479 			    int dst_regno)
4480 {
4481 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4482 	struct bpf_func_state *state = func(env, reg);
4483 	int err;
4484 	/* Some accesses are only permitted with a static offset. */
4485 	bool var_off = !tnum_is_const(reg->var_off);
4486 
4487 	/* The offset is required to be static when reads don't go to a
4488 	 * register, in order to not leak pointers (see
4489 	 * check_stack_read_fixed_off).
4490 	 */
4491 	if (dst_regno < 0 && var_off) {
4492 		char tn_buf[48];
4493 
4494 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4495 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4496 			tn_buf, off, size);
4497 		return -EACCES;
4498 	}
4499 	/* Variable offset is prohibited for unprivileged mode for simplicity
4500 	 * since it requires corresponding support in Spectre masking for stack
4501 	 * ALU. See also retrieve_ptr_limit(). The check in
4502 	 * check_stack_access_for_ptr_arithmetic() called by
4503 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4504 	 * with variable offsets, therefore no check is required here. Further,
4505 	 * just checking it here would be insufficient as speculative stack
4506 	 * writes could still lead to unsafe speculative behaviour.
4507 	 */
4508 	if (!var_off) {
4509 		off += reg->var_off.value;
4510 		err = check_stack_read_fixed_off(env, state, off, size,
4511 						 dst_regno);
4512 	} else {
4513 		/* Variable offset stack reads need more conservative handling
4514 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4515 		 * branch.
4516 		 */
4517 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4518 					       dst_regno);
4519 	}
4520 	return err;
4521 }
4522 
4523 
4524 /* check_stack_write dispatches to check_stack_write_fixed_off or
4525  * check_stack_write_var_off.
4526  *
4527  * 'ptr_regno' is the register used as a pointer into the stack.
4528  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4529  * 'value_regno' is the register whose value we're writing to the stack. It can
4530  * be -1, meaning that we're not writing from a register.
4531  *
4532  * The caller must ensure that the offset falls within the maximum stack size.
4533  */
4534 static int check_stack_write(struct bpf_verifier_env *env,
4535 			     int ptr_regno, int off, int size,
4536 			     int value_regno, int insn_idx)
4537 {
4538 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4539 	struct bpf_func_state *state = func(env, reg);
4540 	int err;
4541 
4542 	if (tnum_is_const(reg->var_off)) {
4543 		off += reg->var_off.value;
4544 		err = check_stack_write_fixed_off(env, state, off, size,
4545 						  value_regno, insn_idx);
4546 	} else {
4547 		/* Variable offset stack reads need more conservative handling
4548 		 * than fixed offset ones.
4549 		 */
4550 		err = check_stack_write_var_off(env, state,
4551 						ptr_regno, off, size,
4552 						value_regno, insn_idx);
4553 	}
4554 	return err;
4555 }
4556 
4557 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4558 				 int off, int size, enum bpf_access_type type)
4559 {
4560 	struct bpf_reg_state *regs = cur_regs(env);
4561 	struct bpf_map *map = regs[regno].map_ptr;
4562 	u32 cap = bpf_map_flags_to_cap(map);
4563 
4564 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4565 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4566 			map->value_size, off, size);
4567 		return -EACCES;
4568 	}
4569 
4570 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4571 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4572 			map->value_size, off, size);
4573 		return -EACCES;
4574 	}
4575 
4576 	return 0;
4577 }
4578 
4579 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4580 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4581 			      int off, int size, u32 mem_size,
4582 			      bool zero_size_allowed)
4583 {
4584 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4585 	struct bpf_reg_state *reg;
4586 
4587 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4588 		return 0;
4589 
4590 	reg = &cur_regs(env)[regno];
4591 	switch (reg->type) {
4592 	case PTR_TO_MAP_KEY:
4593 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4594 			mem_size, off, size);
4595 		break;
4596 	case PTR_TO_MAP_VALUE:
4597 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4598 			mem_size, off, size);
4599 		break;
4600 	case PTR_TO_PACKET:
4601 	case PTR_TO_PACKET_META:
4602 	case PTR_TO_PACKET_END:
4603 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4604 			off, size, regno, reg->id, off, mem_size);
4605 		break;
4606 	case PTR_TO_MEM:
4607 	default:
4608 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4609 			mem_size, off, size);
4610 	}
4611 
4612 	return -EACCES;
4613 }
4614 
4615 /* check read/write into a memory region with possible variable offset */
4616 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4617 				   int off, int size, u32 mem_size,
4618 				   bool zero_size_allowed)
4619 {
4620 	struct bpf_verifier_state *vstate = env->cur_state;
4621 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4622 	struct bpf_reg_state *reg = &state->regs[regno];
4623 	int err;
4624 
4625 	/* We may have adjusted the register pointing to memory region, so we
4626 	 * need to try adding each of min_value and max_value to off
4627 	 * to make sure our theoretical access will be safe.
4628 	 *
4629 	 * The minimum value is only important with signed
4630 	 * comparisons where we can't assume the floor of a
4631 	 * value is 0.  If we are using signed variables for our
4632 	 * index'es we need to make sure that whatever we use
4633 	 * will have a set floor within our range.
4634 	 */
4635 	if (reg->smin_value < 0 &&
4636 	    (reg->smin_value == S64_MIN ||
4637 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4638 	      reg->smin_value + off < 0)) {
4639 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4640 			regno);
4641 		return -EACCES;
4642 	}
4643 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4644 				 mem_size, zero_size_allowed);
4645 	if (err) {
4646 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4647 			regno);
4648 		return err;
4649 	}
4650 
4651 	/* If we haven't set a max value then we need to bail since we can't be
4652 	 * sure we won't do bad things.
4653 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4654 	 */
4655 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4656 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4657 			regno);
4658 		return -EACCES;
4659 	}
4660 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4661 				 mem_size, zero_size_allowed);
4662 	if (err) {
4663 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4664 			regno);
4665 		return err;
4666 	}
4667 
4668 	return 0;
4669 }
4670 
4671 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4672 			       const struct bpf_reg_state *reg, int regno,
4673 			       bool fixed_off_ok)
4674 {
4675 	/* Access to this pointer-typed register or passing it to a helper
4676 	 * is only allowed in its original, unmodified form.
4677 	 */
4678 
4679 	if (reg->off < 0) {
4680 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4681 			reg_type_str(env, reg->type), regno, reg->off);
4682 		return -EACCES;
4683 	}
4684 
4685 	if (!fixed_off_ok && reg->off) {
4686 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4687 			reg_type_str(env, reg->type), regno, reg->off);
4688 		return -EACCES;
4689 	}
4690 
4691 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4692 		char tn_buf[48];
4693 
4694 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4695 		verbose(env, "variable %s access var_off=%s disallowed\n",
4696 			reg_type_str(env, reg->type), tn_buf);
4697 		return -EACCES;
4698 	}
4699 
4700 	return 0;
4701 }
4702 
4703 int check_ptr_off_reg(struct bpf_verifier_env *env,
4704 		      const struct bpf_reg_state *reg, int regno)
4705 {
4706 	return __check_ptr_off_reg(env, reg, regno, false);
4707 }
4708 
4709 static int map_kptr_match_type(struct bpf_verifier_env *env,
4710 			       struct btf_field *kptr_field,
4711 			       struct bpf_reg_state *reg, u32 regno)
4712 {
4713 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4714 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4715 	const char *reg_name = "";
4716 
4717 	/* Only unreferenced case accepts untrusted pointers */
4718 	if (kptr_field->type == BPF_KPTR_UNREF)
4719 		perm_flags |= PTR_UNTRUSTED;
4720 
4721 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4722 		goto bad_type;
4723 
4724 	if (!btf_is_kernel(reg->btf)) {
4725 		verbose(env, "R%d must point to kernel BTF\n", regno);
4726 		return -EINVAL;
4727 	}
4728 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4729 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4730 
4731 	/* For ref_ptr case, release function check should ensure we get one
4732 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4733 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4734 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4735 	 * reg->off and reg->ref_obj_id are not needed here.
4736 	 */
4737 	if (__check_ptr_off_reg(env, reg, regno, true))
4738 		return -EACCES;
4739 
4740 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4741 	 * we also need to take into account the reg->off.
4742 	 *
4743 	 * We want to support cases like:
4744 	 *
4745 	 * struct foo {
4746 	 *         struct bar br;
4747 	 *         struct baz bz;
4748 	 * };
4749 	 *
4750 	 * struct foo *v;
4751 	 * v = func();	      // PTR_TO_BTF_ID
4752 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4753 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4754 	 *                    // first member type of struct after comparison fails
4755 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4756 	 *                    // to match type
4757 	 *
4758 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4759 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4760 	 * the struct to match type against first member of struct, i.e. reject
4761 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4762 	 * strict mode to true for type match.
4763 	 */
4764 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4765 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4766 				  kptr_field->type == BPF_KPTR_REF))
4767 		goto bad_type;
4768 	return 0;
4769 bad_type:
4770 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4771 		reg_type_str(env, reg->type), reg_name);
4772 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4773 	if (kptr_field->type == BPF_KPTR_UNREF)
4774 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4775 			targ_name);
4776 	else
4777 		verbose(env, "\n");
4778 	return -EINVAL;
4779 }
4780 
4781 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4782  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4783  */
4784 static bool in_rcu_cs(struct bpf_verifier_env *env)
4785 {
4786 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4787 }
4788 
4789 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4790 BTF_SET_START(rcu_protected_types)
4791 BTF_ID(struct, prog_test_ref_kfunc)
4792 BTF_ID(struct, cgroup)
4793 BTF_ID(struct, bpf_cpumask)
4794 BTF_ID(struct, task_struct)
4795 BTF_SET_END(rcu_protected_types)
4796 
4797 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4798 {
4799 	if (!btf_is_kernel(btf))
4800 		return false;
4801 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4802 }
4803 
4804 static bool rcu_safe_kptr(const struct btf_field *field)
4805 {
4806 	const struct btf_field_kptr *kptr = &field->kptr;
4807 
4808 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4809 }
4810 
4811 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4812 				 int value_regno, int insn_idx,
4813 				 struct btf_field *kptr_field)
4814 {
4815 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4816 	int class = BPF_CLASS(insn->code);
4817 	struct bpf_reg_state *val_reg;
4818 
4819 	/* Things we already checked for in check_map_access and caller:
4820 	 *  - Reject cases where variable offset may touch kptr
4821 	 *  - size of access (must be BPF_DW)
4822 	 *  - tnum_is_const(reg->var_off)
4823 	 *  - kptr_field->offset == off + reg->var_off.value
4824 	 */
4825 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4826 	if (BPF_MODE(insn->code) != BPF_MEM) {
4827 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4828 		return -EACCES;
4829 	}
4830 
4831 	/* We only allow loading referenced kptr, since it will be marked as
4832 	 * untrusted, similar to unreferenced kptr.
4833 	 */
4834 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4835 		verbose(env, "store to referenced kptr disallowed\n");
4836 		return -EACCES;
4837 	}
4838 
4839 	if (class == BPF_LDX) {
4840 		val_reg = reg_state(env, value_regno);
4841 		/* We can simply mark the value_regno receiving the pointer
4842 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4843 		 */
4844 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4845 				kptr_field->kptr.btf_id,
4846 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4847 				PTR_MAYBE_NULL | MEM_RCU :
4848 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
4849 		/* For mark_ptr_or_null_reg */
4850 		val_reg->id = ++env->id_gen;
4851 	} else if (class == BPF_STX) {
4852 		val_reg = reg_state(env, value_regno);
4853 		if (!register_is_null(val_reg) &&
4854 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4855 			return -EACCES;
4856 	} else if (class == BPF_ST) {
4857 		if (insn->imm) {
4858 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4859 				kptr_field->offset);
4860 			return -EACCES;
4861 		}
4862 	} else {
4863 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4864 		return -EACCES;
4865 	}
4866 	return 0;
4867 }
4868 
4869 /* check read/write into a map element with possible variable offset */
4870 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4871 			    int off, int size, bool zero_size_allowed,
4872 			    enum bpf_access_src src)
4873 {
4874 	struct bpf_verifier_state *vstate = env->cur_state;
4875 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4876 	struct bpf_reg_state *reg = &state->regs[regno];
4877 	struct bpf_map *map = reg->map_ptr;
4878 	struct btf_record *rec;
4879 	int err, i;
4880 
4881 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4882 				      zero_size_allowed);
4883 	if (err)
4884 		return err;
4885 
4886 	if (IS_ERR_OR_NULL(map->record))
4887 		return 0;
4888 	rec = map->record;
4889 	for (i = 0; i < rec->cnt; i++) {
4890 		struct btf_field *field = &rec->fields[i];
4891 		u32 p = field->offset;
4892 
4893 		/* If any part of a field  can be touched by load/store, reject
4894 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4895 		 * it is sufficient to check x1 < y2 && y1 < x2.
4896 		 */
4897 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4898 		    p < reg->umax_value + off + size) {
4899 			switch (field->type) {
4900 			case BPF_KPTR_UNREF:
4901 			case BPF_KPTR_REF:
4902 				if (src != ACCESS_DIRECT) {
4903 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4904 					return -EACCES;
4905 				}
4906 				if (!tnum_is_const(reg->var_off)) {
4907 					verbose(env, "kptr access cannot have variable offset\n");
4908 					return -EACCES;
4909 				}
4910 				if (p != off + reg->var_off.value) {
4911 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4912 						p, off + reg->var_off.value);
4913 					return -EACCES;
4914 				}
4915 				if (size != bpf_size_to_bytes(BPF_DW)) {
4916 					verbose(env, "kptr access size must be BPF_DW\n");
4917 					return -EACCES;
4918 				}
4919 				break;
4920 			default:
4921 				verbose(env, "%s cannot be accessed directly by load/store\n",
4922 					btf_field_type_name(field->type));
4923 				return -EACCES;
4924 			}
4925 		}
4926 	}
4927 	return 0;
4928 }
4929 
4930 #define MAX_PACKET_OFF 0xffff
4931 
4932 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4933 				       const struct bpf_call_arg_meta *meta,
4934 				       enum bpf_access_type t)
4935 {
4936 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4937 
4938 	switch (prog_type) {
4939 	/* Program types only with direct read access go here! */
4940 	case BPF_PROG_TYPE_LWT_IN:
4941 	case BPF_PROG_TYPE_LWT_OUT:
4942 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4943 	case BPF_PROG_TYPE_SK_REUSEPORT:
4944 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4945 	case BPF_PROG_TYPE_CGROUP_SKB:
4946 		if (t == BPF_WRITE)
4947 			return false;
4948 		fallthrough;
4949 
4950 	/* Program types with direct read + write access go here! */
4951 	case BPF_PROG_TYPE_SCHED_CLS:
4952 	case BPF_PROG_TYPE_SCHED_ACT:
4953 	case BPF_PROG_TYPE_XDP:
4954 	case BPF_PROG_TYPE_LWT_XMIT:
4955 	case BPF_PROG_TYPE_SK_SKB:
4956 	case BPF_PROG_TYPE_SK_MSG:
4957 		if (meta)
4958 			return meta->pkt_access;
4959 
4960 		env->seen_direct_write = true;
4961 		return true;
4962 
4963 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4964 		if (t == BPF_WRITE)
4965 			env->seen_direct_write = true;
4966 
4967 		return true;
4968 
4969 	default:
4970 		return false;
4971 	}
4972 }
4973 
4974 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4975 			       int size, bool zero_size_allowed)
4976 {
4977 	struct bpf_reg_state *regs = cur_regs(env);
4978 	struct bpf_reg_state *reg = &regs[regno];
4979 	int err;
4980 
4981 	/* We may have added a variable offset to the packet pointer; but any
4982 	 * reg->range we have comes after that.  We are only checking the fixed
4983 	 * offset.
4984 	 */
4985 
4986 	/* We don't allow negative numbers, because we aren't tracking enough
4987 	 * detail to prove they're safe.
4988 	 */
4989 	if (reg->smin_value < 0) {
4990 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4991 			regno);
4992 		return -EACCES;
4993 	}
4994 
4995 	err = reg->range < 0 ? -EINVAL :
4996 	      __check_mem_access(env, regno, off, size, reg->range,
4997 				 zero_size_allowed);
4998 	if (err) {
4999 		verbose(env, "R%d offset is outside of the packet\n", regno);
5000 		return err;
5001 	}
5002 
5003 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5004 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5005 	 * otherwise find_good_pkt_pointers would have refused to set range info
5006 	 * that __check_mem_access would have rejected this pkt access.
5007 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5008 	 */
5009 	env->prog->aux->max_pkt_offset =
5010 		max_t(u32, env->prog->aux->max_pkt_offset,
5011 		      off + reg->umax_value + size - 1);
5012 
5013 	return err;
5014 }
5015 
5016 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5017 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5018 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5019 			    struct btf **btf, u32 *btf_id)
5020 {
5021 	struct bpf_insn_access_aux info = {
5022 		.reg_type = *reg_type,
5023 		.log = &env->log,
5024 	};
5025 
5026 	if (env->ops->is_valid_access &&
5027 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5028 		/* A non zero info.ctx_field_size indicates that this field is a
5029 		 * candidate for later verifier transformation to load the whole
5030 		 * field and then apply a mask when accessed with a narrower
5031 		 * access than actual ctx access size. A zero info.ctx_field_size
5032 		 * will only allow for whole field access and rejects any other
5033 		 * type of narrower access.
5034 		 */
5035 		*reg_type = info.reg_type;
5036 
5037 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5038 			*btf = info.btf;
5039 			*btf_id = info.btf_id;
5040 		} else {
5041 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5042 		}
5043 		/* remember the offset of last byte accessed in ctx */
5044 		if (env->prog->aux->max_ctx_offset < off + size)
5045 			env->prog->aux->max_ctx_offset = off + size;
5046 		return 0;
5047 	}
5048 
5049 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5050 	return -EACCES;
5051 }
5052 
5053 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5054 				  int size)
5055 {
5056 	if (size < 0 || off < 0 ||
5057 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5058 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5059 			off, size);
5060 		return -EACCES;
5061 	}
5062 	return 0;
5063 }
5064 
5065 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5066 			     u32 regno, int off, int size,
5067 			     enum bpf_access_type t)
5068 {
5069 	struct bpf_reg_state *regs = cur_regs(env);
5070 	struct bpf_reg_state *reg = &regs[regno];
5071 	struct bpf_insn_access_aux info = {};
5072 	bool valid;
5073 
5074 	if (reg->smin_value < 0) {
5075 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5076 			regno);
5077 		return -EACCES;
5078 	}
5079 
5080 	switch (reg->type) {
5081 	case PTR_TO_SOCK_COMMON:
5082 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5083 		break;
5084 	case PTR_TO_SOCKET:
5085 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5086 		break;
5087 	case PTR_TO_TCP_SOCK:
5088 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5089 		break;
5090 	case PTR_TO_XDP_SOCK:
5091 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5092 		break;
5093 	default:
5094 		valid = false;
5095 	}
5096 
5097 
5098 	if (valid) {
5099 		env->insn_aux_data[insn_idx].ctx_field_size =
5100 			info.ctx_field_size;
5101 		return 0;
5102 	}
5103 
5104 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5105 		regno, reg_type_str(env, reg->type), off, size);
5106 
5107 	return -EACCES;
5108 }
5109 
5110 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5111 {
5112 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5113 }
5114 
5115 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5116 {
5117 	const struct bpf_reg_state *reg = reg_state(env, regno);
5118 
5119 	return reg->type == PTR_TO_CTX;
5120 }
5121 
5122 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5123 {
5124 	const struct bpf_reg_state *reg = reg_state(env, regno);
5125 
5126 	return type_is_sk_pointer(reg->type);
5127 }
5128 
5129 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5130 {
5131 	const struct bpf_reg_state *reg = reg_state(env, regno);
5132 
5133 	return type_is_pkt_pointer(reg->type);
5134 }
5135 
5136 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5137 {
5138 	const struct bpf_reg_state *reg = reg_state(env, regno);
5139 
5140 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5141 	return reg->type == PTR_TO_FLOW_KEYS;
5142 }
5143 
5144 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5145 {
5146 	/* A referenced register is always trusted. */
5147 	if (reg->ref_obj_id)
5148 		return true;
5149 
5150 	/* If a register is not referenced, it is trusted if it has the
5151 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5152 	 * other type modifiers may be safe, but we elect to take an opt-in
5153 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5154 	 * not.
5155 	 *
5156 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5157 	 * for whether a register is trusted.
5158 	 */
5159 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5160 	       !bpf_type_has_unsafe_modifiers(reg->type);
5161 }
5162 
5163 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5164 {
5165 	return reg->type & MEM_RCU;
5166 }
5167 
5168 static void clear_trusted_flags(enum bpf_type_flag *flag)
5169 {
5170 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5171 }
5172 
5173 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5174 				   const struct bpf_reg_state *reg,
5175 				   int off, int size, bool strict)
5176 {
5177 	struct tnum reg_off;
5178 	int ip_align;
5179 
5180 	/* Byte size accesses are always allowed. */
5181 	if (!strict || size == 1)
5182 		return 0;
5183 
5184 	/* For platforms that do not have a Kconfig enabling
5185 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5186 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5187 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5188 	 * to this code only in strict mode where we want to emulate
5189 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5190 	 * unconditional IP align value of '2'.
5191 	 */
5192 	ip_align = 2;
5193 
5194 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5195 	if (!tnum_is_aligned(reg_off, size)) {
5196 		char tn_buf[48];
5197 
5198 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5199 		verbose(env,
5200 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5201 			ip_align, tn_buf, reg->off, off, size);
5202 		return -EACCES;
5203 	}
5204 
5205 	return 0;
5206 }
5207 
5208 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5209 				       const struct bpf_reg_state *reg,
5210 				       const char *pointer_desc,
5211 				       int off, int size, bool strict)
5212 {
5213 	struct tnum reg_off;
5214 
5215 	/* Byte size accesses are always allowed. */
5216 	if (!strict || size == 1)
5217 		return 0;
5218 
5219 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5220 	if (!tnum_is_aligned(reg_off, size)) {
5221 		char tn_buf[48];
5222 
5223 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5224 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5225 			pointer_desc, tn_buf, reg->off, off, size);
5226 		return -EACCES;
5227 	}
5228 
5229 	return 0;
5230 }
5231 
5232 static int check_ptr_alignment(struct bpf_verifier_env *env,
5233 			       const struct bpf_reg_state *reg, int off,
5234 			       int size, bool strict_alignment_once)
5235 {
5236 	bool strict = env->strict_alignment || strict_alignment_once;
5237 	const char *pointer_desc = "";
5238 
5239 	switch (reg->type) {
5240 	case PTR_TO_PACKET:
5241 	case PTR_TO_PACKET_META:
5242 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5243 		 * right in front, treat it the very same way.
5244 		 */
5245 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5246 	case PTR_TO_FLOW_KEYS:
5247 		pointer_desc = "flow keys ";
5248 		break;
5249 	case PTR_TO_MAP_KEY:
5250 		pointer_desc = "key ";
5251 		break;
5252 	case PTR_TO_MAP_VALUE:
5253 		pointer_desc = "value ";
5254 		break;
5255 	case PTR_TO_CTX:
5256 		pointer_desc = "context ";
5257 		break;
5258 	case PTR_TO_STACK:
5259 		pointer_desc = "stack ";
5260 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5261 		 * and check_stack_read_fixed_off() relies on stack accesses being
5262 		 * aligned.
5263 		 */
5264 		strict = true;
5265 		break;
5266 	case PTR_TO_SOCKET:
5267 		pointer_desc = "sock ";
5268 		break;
5269 	case PTR_TO_SOCK_COMMON:
5270 		pointer_desc = "sock_common ";
5271 		break;
5272 	case PTR_TO_TCP_SOCK:
5273 		pointer_desc = "tcp_sock ";
5274 		break;
5275 	case PTR_TO_XDP_SOCK:
5276 		pointer_desc = "xdp_sock ";
5277 		break;
5278 	default:
5279 		break;
5280 	}
5281 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5282 					   strict);
5283 }
5284 
5285 static int update_stack_depth(struct bpf_verifier_env *env,
5286 			      const struct bpf_func_state *func,
5287 			      int off)
5288 {
5289 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5290 
5291 	if (stack >= -off)
5292 		return 0;
5293 
5294 	/* update known max for given subprogram */
5295 	env->subprog_info[func->subprogno].stack_depth = -off;
5296 	return 0;
5297 }
5298 
5299 /* starting from main bpf function walk all instructions of the function
5300  * and recursively walk all callees that given function can call.
5301  * Ignore jump and exit insns.
5302  * Since recursion is prevented by check_cfg() this algorithm
5303  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5304  */
5305 static int check_max_stack_depth(struct bpf_verifier_env *env)
5306 {
5307 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5308 	struct bpf_subprog_info *subprog = env->subprog_info;
5309 	struct bpf_insn *insn = env->prog->insnsi;
5310 	bool tail_call_reachable = false;
5311 	int ret_insn[MAX_CALL_FRAMES];
5312 	int ret_prog[MAX_CALL_FRAMES];
5313 	int j;
5314 
5315 process_func:
5316 	/* protect against potential stack overflow that might happen when
5317 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5318 	 * depth for such case down to 256 so that the worst case scenario
5319 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5320 	 * 8k).
5321 	 *
5322 	 * To get the idea what might happen, see an example:
5323 	 * func1 -> sub rsp, 128
5324 	 *  subfunc1 -> sub rsp, 256
5325 	 *  tailcall1 -> add rsp, 256
5326 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5327 	 *   subfunc2 -> sub rsp, 64
5328 	 *   subfunc22 -> sub rsp, 128
5329 	 *   tailcall2 -> add rsp, 128
5330 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5331 	 *
5332 	 * tailcall will unwind the current stack frame but it will not get rid
5333 	 * of caller's stack as shown on the example above.
5334 	 */
5335 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5336 		verbose(env,
5337 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5338 			depth);
5339 		return -EACCES;
5340 	}
5341 	/* round up to 32-bytes, since this is granularity
5342 	 * of interpreter stack size
5343 	 */
5344 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5345 	if (depth > MAX_BPF_STACK) {
5346 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5347 			frame + 1, depth);
5348 		return -EACCES;
5349 	}
5350 continue_func:
5351 	subprog_end = subprog[idx + 1].start;
5352 	for (; i < subprog_end; i++) {
5353 		int next_insn;
5354 
5355 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5356 			continue;
5357 		/* remember insn and function to return to */
5358 		ret_insn[frame] = i + 1;
5359 		ret_prog[frame] = idx;
5360 
5361 		/* find the callee */
5362 		next_insn = i + insn[i].imm + 1;
5363 		idx = find_subprog(env, next_insn);
5364 		if (idx < 0) {
5365 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5366 				  next_insn);
5367 			return -EFAULT;
5368 		}
5369 		if (subprog[idx].is_async_cb) {
5370 			if (subprog[idx].has_tail_call) {
5371 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5372 				return -EFAULT;
5373 			}
5374 			 /* async callbacks don't increase bpf prog stack size */
5375 			continue;
5376 		}
5377 		i = next_insn;
5378 
5379 		if (subprog[idx].has_tail_call)
5380 			tail_call_reachable = true;
5381 
5382 		frame++;
5383 		if (frame >= MAX_CALL_FRAMES) {
5384 			verbose(env, "the call stack of %d frames is too deep !\n",
5385 				frame);
5386 			return -E2BIG;
5387 		}
5388 		goto process_func;
5389 	}
5390 	/* if tail call got detected across bpf2bpf calls then mark each of the
5391 	 * currently present subprog frames as tail call reachable subprogs;
5392 	 * this info will be utilized by JIT so that we will be preserving the
5393 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5394 	 */
5395 	if (tail_call_reachable)
5396 		for (j = 0; j < frame; j++)
5397 			subprog[ret_prog[j]].tail_call_reachable = true;
5398 	if (subprog[0].tail_call_reachable)
5399 		env->prog->aux->tail_call_reachable = true;
5400 
5401 	/* end of for() loop means the last insn of the 'subprog'
5402 	 * was reached. Doesn't matter whether it was JA or EXIT
5403 	 */
5404 	if (frame == 0)
5405 		return 0;
5406 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5407 	frame--;
5408 	i = ret_insn[frame];
5409 	idx = ret_prog[frame];
5410 	goto continue_func;
5411 }
5412 
5413 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5414 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5415 				  const struct bpf_insn *insn, int idx)
5416 {
5417 	int start = idx + insn->imm + 1, subprog;
5418 
5419 	subprog = find_subprog(env, start);
5420 	if (subprog < 0) {
5421 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5422 			  start);
5423 		return -EFAULT;
5424 	}
5425 	return env->subprog_info[subprog].stack_depth;
5426 }
5427 #endif
5428 
5429 static int __check_buffer_access(struct bpf_verifier_env *env,
5430 				 const char *buf_info,
5431 				 const struct bpf_reg_state *reg,
5432 				 int regno, int off, int size)
5433 {
5434 	if (off < 0) {
5435 		verbose(env,
5436 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5437 			regno, buf_info, off, size);
5438 		return -EACCES;
5439 	}
5440 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5441 		char tn_buf[48];
5442 
5443 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5444 		verbose(env,
5445 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5446 			regno, off, tn_buf);
5447 		return -EACCES;
5448 	}
5449 
5450 	return 0;
5451 }
5452 
5453 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5454 				  const struct bpf_reg_state *reg,
5455 				  int regno, int off, int size)
5456 {
5457 	int err;
5458 
5459 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5460 	if (err)
5461 		return err;
5462 
5463 	if (off + size > env->prog->aux->max_tp_access)
5464 		env->prog->aux->max_tp_access = off + size;
5465 
5466 	return 0;
5467 }
5468 
5469 static int check_buffer_access(struct bpf_verifier_env *env,
5470 			       const struct bpf_reg_state *reg,
5471 			       int regno, int off, int size,
5472 			       bool zero_size_allowed,
5473 			       u32 *max_access)
5474 {
5475 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5476 	int err;
5477 
5478 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5479 	if (err)
5480 		return err;
5481 
5482 	if (off + size > *max_access)
5483 		*max_access = off + size;
5484 
5485 	return 0;
5486 }
5487 
5488 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5489 static void zext_32_to_64(struct bpf_reg_state *reg)
5490 {
5491 	reg->var_off = tnum_subreg(reg->var_off);
5492 	__reg_assign_32_into_64(reg);
5493 }
5494 
5495 /* truncate register to smaller size (in bytes)
5496  * must be called with size < BPF_REG_SIZE
5497  */
5498 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5499 {
5500 	u64 mask;
5501 
5502 	/* clear high bits in bit representation */
5503 	reg->var_off = tnum_cast(reg->var_off, size);
5504 
5505 	/* fix arithmetic bounds */
5506 	mask = ((u64)1 << (size * 8)) - 1;
5507 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5508 		reg->umin_value &= mask;
5509 		reg->umax_value &= mask;
5510 	} else {
5511 		reg->umin_value = 0;
5512 		reg->umax_value = mask;
5513 	}
5514 	reg->smin_value = reg->umin_value;
5515 	reg->smax_value = reg->umax_value;
5516 
5517 	/* If size is smaller than 32bit register the 32bit register
5518 	 * values are also truncated so we push 64-bit bounds into
5519 	 * 32-bit bounds. Above were truncated < 32-bits already.
5520 	 */
5521 	if (size >= 4)
5522 		return;
5523 	__reg_combine_64_into_32(reg);
5524 }
5525 
5526 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5527 {
5528 	/* A map is considered read-only if the following condition are true:
5529 	 *
5530 	 * 1) BPF program side cannot change any of the map content. The
5531 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5532 	 *    and was set at map creation time.
5533 	 * 2) The map value(s) have been initialized from user space by a
5534 	 *    loader and then "frozen", such that no new map update/delete
5535 	 *    operations from syscall side are possible for the rest of
5536 	 *    the map's lifetime from that point onwards.
5537 	 * 3) Any parallel/pending map update/delete operations from syscall
5538 	 *    side have been completed. Only after that point, it's safe to
5539 	 *    assume that map value(s) are immutable.
5540 	 */
5541 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5542 	       READ_ONCE(map->frozen) &&
5543 	       !bpf_map_write_active(map);
5544 }
5545 
5546 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5547 {
5548 	void *ptr;
5549 	u64 addr;
5550 	int err;
5551 
5552 	err = map->ops->map_direct_value_addr(map, &addr, off);
5553 	if (err)
5554 		return err;
5555 	ptr = (void *)(long)addr + off;
5556 
5557 	switch (size) {
5558 	case sizeof(u8):
5559 		*val = (u64)*(u8 *)ptr;
5560 		break;
5561 	case sizeof(u16):
5562 		*val = (u64)*(u16 *)ptr;
5563 		break;
5564 	case sizeof(u32):
5565 		*val = (u64)*(u32 *)ptr;
5566 		break;
5567 	case sizeof(u64):
5568 		*val = *(u64 *)ptr;
5569 		break;
5570 	default:
5571 		return -EINVAL;
5572 	}
5573 	return 0;
5574 }
5575 
5576 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5577 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5578 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5579 
5580 /*
5581  * Allow list few fields as RCU trusted or full trusted.
5582  * This logic doesn't allow mix tagging and will be removed once GCC supports
5583  * btf_type_tag.
5584  */
5585 
5586 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5587 BTF_TYPE_SAFE_RCU(struct task_struct) {
5588 	const cpumask_t *cpus_ptr;
5589 	struct css_set __rcu *cgroups;
5590 	struct task_struct __rcu *real_parent;
5591 	struct task_struct *group_leader;
5592 };
5593 
5594 BTF_TYPE_SAFE_RCU(struct cgroup) {
5595 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5596 	struct kernfs_node *kn;
5597 };
5598 
5599 BTF_TYPE_SAFE_RCU(struct css_set) {
5600 	struct cgroup *dfl_cgrp;
5601 };
5602 
5603 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5604 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5605 	struct file __rcu *exe_file;
5606 };
5607 
5608 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5609  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5610  */
5611 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5612 	struct sock *sk;
5613 };
5614 
5615 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5616 	struct sock *sk;
5617 };
5618 
5619 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5620 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5621 	struct seq_file *seq;
5622 };
5623 
5624 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5625 	struct bpf_iter_meta *meta;
5626 	struct task_struct *task;
5627 };
5628 
5629 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5630 	struct file *file;
5631 };
5632 
5633 BTF_TYPE_SAFE_TRUSTED(struct file) {
5634 	struct inode *f_inode;
5635 };
5636 
5637 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5638 	/* no negative dentry-s in places where bpf can see it */
5639 	struct inode *d_inode;
5640 };
5641 
5642 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5643 	struct sock *sk;
5644 };
5645 
5646 static bool type_is_rcu(struct bpf_verifier_env *env,
5647 			struct bpf_reg_state *reg,
5648 			const char *field_name, u32 btf_id)
5649 {
5650 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5651 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5652 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5653 
5654 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5655 }
5656 
5657 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5658 				struct bpf_reg_state *reg,
5659 				const char *field_name, u32 btf_id)
5660 {
5661 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5662 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5663 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5664 
5665 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5666 }
5667 
5668 static bool type_is_trusted(struct bpf_verifier_env *env,
5669 			    struct bpf_reg_state *reg,
5670 			    const char *field_name, u32 btf_id)
5671 {
5672 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5673 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5674 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5675 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5676 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5677 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5678 
5679 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5680 }
5681 
5682 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5683 				   struct bpf_reg_state *regs,
5684 				   int regno, int off, int size,
5685 				   enum bpf_access_type atype,
5686 				   int value_regno)
5687 {
5688 	struct bpf_reg_state *reg = regs + regno;
5689 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5690 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5691 	const char *field_name = NULL;
5692 	enum bpf_type_flag flag = 0;
5693 	u32 btf_id = 0;
5694 	int ret;
5695 
5696 	if (!env->allow_ptr_leaks) {
5697 		verbose(env,
5698 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5699 			tname);
5700 		return -EPERM;
5701 	}
5702 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5703 		verbose(env,
5704 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5705 			tname);
5706 		return -EINVAL;
5707 	}
5708 	if (off < 0) {
5709 		verbose(env,
5710 			"R%d is ptr_%s invalid negative access: off=%d\n",
5711 			regno, tname, off);
5712 		return -EACCES;
5713 	}
5714 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5715 		char tn_buf[48];
5716 
5717 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5718 		verbose(env,
5719 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5720 			regno, tname, off, tn_buf);
5721 		return -EACCES;
5722 	}
5723 
5724 	if (reg->type & MEM_USER) {
5725 		verbose(env,
5726 			"R%d is ptr_%s access user memory: off=%d\n",
5727 			regno, tname, off);
5728 		return -EACCES;
5729 	}
5730 
5731 	if (reg->type & MEM_PERCPU) {
5732 		verbose(env,
5733 			"R%d is ptr_%s access percpu memory: off=%d\n",
5734 			regno, tname, off);
5735 		return -EACCES;
5736 	}
5737 
5738 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5739 		if (!btf_is_kernel(reg->btf)) {
5740 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5741 			return -EFAULT;
5742 		}
5743 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5744 	} else {
5745 		/* Writes are permitted with default btf_struct_access for
5746 		 * program allocated objects (which always have ref_obj_id > 0),
5747 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5748 		 */
5749 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5750 			verbose(env, "only read is supported\n");
5751 			return -EACCES;
5752 		}
5753 
5754 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5755 		    !reg->ref_obj_id) {
5756 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5757 			return -EFAULT;
5758 		}
5759 
5760 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5761 	}
5762 
5763 	if (ret < 0)
5764 		return ret;
5765 
5766 	if (ret != PTR_TO_BTF_ID) {
5767 		/* just mark; */
5768 
5769 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5770 		/* If this is an untrusted pointer, all pointers formed by walking it
5771 		 * also inherit the untrusted flag.
5772 		 */
5773 		flag = PTR_UNTRUSTED;
5774 
5775 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5776 		/* By default any pointer obtained from walking a trusted pointer is no
5777 		 * longer trusted, unless the field being accessed has explicitly been
5778 		 * marked as inheriting its parent's state of trust (either full or RCU).
5779 		 * For example:
5780 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
5781 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
5782 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5783 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5784 		 *
5785 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
5786 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
5787 		 */
5788 		if (type_is_trusted(env, reg, field_name, btf_id)) {
5789 			flag |= PTR_TRUSTED;
5790 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5791 			if (type_is_rcu(env, reg, field_name, btf_id)) {
5792 				/* ignore __rcu tag and mark it MEM_RCU */
5793 				flag |= MEM_RCU;
5794 			} else if (flag & MEM_RCU ||
5795 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5796 				/* __rcu tagged pointers can be NULL */
5797 				flag |= MEM_RCU | PTR_MAYBE_NULL;
5798 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
5799 				/* keep as-is */
5800 			} else {
5801 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5802 				clear_trusted_flags(&flag);
5803 			}
5804 		} else {
5805 			/*
5806 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
5807 			 * aggressively mark as untrusted otherwise such
5808 			 * pointers will be plain PTR_TO_BTF_ID without flags
5809 			 * and will be allowed to be passed into helpers for
5810 			 * compat reasons.
5811 			 */
5812 			flag = PTR_UNTRUSTED;
5813 		}
5814 	} else {
5815 		/* Old compat. Deprecated */
5816 		clear_trusted_flags(&flag);
5817 	}
5818 
5819 	if (atype == BPF_READ && value_regno >= 0)
5820 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5821 
5822 	return 0;
5823 }
5824 
5825 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5826 				   struct bpf_reg_state *regs,
5827 				   int regno, int off, int size,
5828 				   enum bpf_access_type atype,
5829 				   int value_regno)
5830 {
5831 	struct bpf_reg_state *reg = regs + regno;
5832 	struct bpf_map *map = reg->map_ptr;
5833 	struct bpf_reg_state map_reg;
5834 	enum bpf_type_flag flag = 0;
5835 	const struct btf_type *t;
5836 	const char *tname;
5837 	u32 btf_id;
5838 	int ret;
5839 
5840 	if (!btf_vmlinux) {
5841 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5842 		return -ENOTSUPP;
5843 	}
5844 
5845 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5846 		verbose(env, "map_ptr access not supported for map type %d\n",
5847 			map->map_type);
5848 		return -ENOTSUPP;
5849 	}
5850 
5851 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5852 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5853 
5854 	if (!env->allow_ptr_leaks) {
5855 		verbose(env,
5856 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5857 			tname);
5858 		return -EPERM;
5859 	}
5860 
5861 	if (off < 0) {
5862 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
5863 			regno, tname, off);
5864 		return -EACCES;
5865 	}
5866 
5867 	if (atype != BPF_READ) {
5868 		verbose(env, "only read from %s is supported\n", tname);
5869 		return -EACCES;
5870 	}
5871 
5872 	/* Simulate access to a PTR_TO_BTF_ID */
5873 	memset(&map_reg, 0, sizeof(map_reg));
5874 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5875 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
5876 	if (ret < 0)
5877 		return ret;
5878 
5879 	if (value_regno >= 0)
5880 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5881 
5882 	return 0;
5883 }
5884 
5885 /* Check that the stack access at the given offset is within bounds. The
5886  * maximum valid offset is -1.
5887  *
5888  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5889  * -state->allocated_stack for reads.
5890  */
5891 static int check_stack_slot_within_bounds(int off,
5892 					  struct bpf_func_state *state,
5893 					  enum bpf_access_type t)
5894 {
5895 	int min_valid_off;
5896 
5897 	if (t == BPF_WRITE)
5898 		min_valid_off = -MAX_BPF_STACK;
5899 	else
5900 		min_valid_off = -state->allocated_stack;
5901 
5902 	if (off < min_valid_off || off > -1)
5903 		return -EACCES;
5904 	return 0;
5905 }
5906 
5907 /* Check that the stack access at 'regno + off' falls within the maximum stack
5908  * bounds.
5909  *
5910  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5911  */
5912 static int check_stack_access_within_bounds(
5913 		struct bpf_verifier_env *env,
5914 		int regno, int off, int access_size,
5915 		enum bpf_access_src src, enum bpf_access_type type)
5916 {
5917 	struct bpf_reg_state *regs = cur_regs(env);
5918 	struct bpf_reg_state *reg = regs + regno;
5919 	struct bpf_func_state *state = func(env, reg);
5920 	int min_off, max_off;
5921 	int err;
5922 	char *err_extra;
5923 
5924 	if (src == ACCESS_HELPER)
5925 		/* We don't know if helpers are reading or writing (or both). */
5926 		err_extra = " indirect access to";
5927 	else if (type == BPF_READ)
5928 		err_extra = " read from";
5929 	else
5930 		err_extra = " write to";
5931 
5932 	if (tnum_is_const(reg->var_off)) {
5933 		min_off = reg->var_off.value + off;
5934 		if (access_size > 0)
5935 			max_off = min_off + access_size - 1;
5936 		else
5937 			max_off = min_off;
5938 	} else {
5939 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5940 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5941 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5942 				err_extra, regno);
5943 			return -EACCES;
5944 		}
5945 		min_off = reg->smin_value + off;
5946 		if (access_size > 0)
5947 			max_off = reg->smax_value + off + access_size - 1;
5948 		else
5949 			max_off = min_off;
5950 	}
5951 
5952 	err = check_stack_slot_within_bounds(min_off, state, type);
5953 	if (!err)
5954 		err = check_stack_slot_within_bounds(max_off, state, type);
5955 
5956 	if (err) {
5957 		if (tnum_is_const(reg->var_off)) {
5958 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5959 				err_extra, regno, off, access_size);
5960 		} else {
5961 			char tn_buf[48];
5962 
5963 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5964 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5965 				err_extra, regno, tn_buf, access_size);
5966 		}
5967 	}
5968 	return err;
5969 }
5970 
5971 /* check whether memory at (regno + off) is accessible for t = (read | write)
5972  * if t==write, value_regno is a register which value is stored into memory
5973  * if t==read, value_regno is a register which will receive the value from memory
5974  * if t==write && value_regno==-1, some unknown value is stored into memory
5975  * if t==read && value_regno==-1, don't care what we read from memory
5976  */
5977 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5978 			    int off, int bpf_size, enum bpf_access_type t,
5979 			    int value_regno, bool strict_alignment_once)
5980 {
5981 	struct bpf_reg_state *regs = cur_regs(env);
5982 	struct bpf_reg_state *reg = regs + regno;
5983 	struct bpf_func_state *state;
5984 	int size, err = 0;
5985 
5986 	size = bpf_size_to_bytes(bpf_size);
5987 	if (size < 0)
5988 		return size;
5989 
5990 	/* alignment checks will add in reg->off themselves */
5991 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5992 	if (err)
5993 		return err;
5994 
5995 	/* for access checks, reg->off is just part of off */
5996 	off += reg->off;
5997 
5998 	if (reg->type == PTR_TO_MAP_KEY) {
5999 		if (t == BPF_WRITE) {
6000 			verbose(env, "write to change key R%d not allowed\n", regno);
6001 			return -EACCES;
6002 		}
6003 
6004 		err = check_mem_region_access(env, regno, off, size,
6005 					      reg->map_ptr->key_size, false);
6006 		if (err)
6007 			return err;
6008 		if (value_regno >= 0)
6009 			mark_reg_unknown(env, regs, value_regno);
6010 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6011 		struct btf_field *kptr_field = NULL;
6012 
6013 		if (t == BPF_WRITE && value_regno >= 0 &&
6014 		    is_pointer_value(env, value_regno)) {
6015 			verbose(env, "R%d leaks addr into map\n", value_regno);
6016 			return -EACCES;
6017 		}
6018 		err = check_map_access_type(env, regno, off, size, t);
6019 		if (err)
6020 			return err;
6021 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6022 		if (err)
6023 			return err;
6024 		if (tnum_is_const(reg->var_off))
6025 			kptr_field = btf_record_find(reg->map_ptr->record,
6026 						     off + reg->var_off.value, BPF_KPTR);
6027 		if (kptr_field) {
6028 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6029 		} else if (t == BPF_READ && value_regno >= 0) {
6030 			struct bpf_map *map = reg->map_ptr;
6031 
6032 			/* if map is read-only, track its contents as scalars */
6033 			if (tnum_is_const(reg->var_off) &&
6034 			    bpf_map_is_rdonly(map) &&
6035 			    map->ops->map_direct_value_addr) {
6036 				int map_off = off + reg->var_off.value;
6037 				u64 val = 0;
6038 
6039 				err = bpf_map_direct_read(map, map_off, size,
6040 							  &val);
6041 				if (err)
6042 					return err;
6043 
6044 				regs[value_regno].type = SCALAR_VALUE;
6045 				__mark_reg_known(&regs[value_regno], val);
6046 			} else {
6047 				mark_reg_unknown(env, regs, value_regno);
6048 			}
6049 		}
6050 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6051 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6052 
6053 		if (type_may_be_null(reg->type)) {
6054 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6055 				reg_type_str(env, reg->type));
6056 			return -EACCES;
6057 		}
6058 
6059 		if (t == BPF_WRITE && rdonly_mem) {
6060 			verbose(env, "R%d cannot write into %s\n",
6061 				regno, reg_type_str(env, reg->type));
6062 			return -EACCES;
6063 		}
6064 
6065 		if (t == BPF_WRITE && value_regno >= 0 &&
6066 		    is_pointer_value(env, value_regno)) {
6067 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6068 			return -EACCES;
6069 		}
6070 
6071 		err = check_mem_region_access(env, regno, off, size,
6072 					      reg->mem_size, false);
6073 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6074 			mark_reg_unknown(env, regs, value_regno);
6075 	} else if (reg->type == PTR_TO_CTX) {
6076 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6077 		struct btf *btf = NULL;
6078 		u32 btf_id = 0;
6079 
6080 		if (t == BPF_WRITE && value_regno >= 0 &&
6081 		    is_pointer_value(env, value_regno)) {
6082 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6083 			return -EACCES;
6084 		}
6085 
6086 		err = check_ptr_off_reg(env, reg, regno);
6087 		if (err < 0)
6088 			return err;
6089 
6090 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6091 				       &btf_id);
6092 		if (err)
6093 			verbose_linfo(env, insn_idx, "; ");
6094 		if (!err && t == BPF_READ && value_regno >= 0) {
6095 			/* ctx access returns either a scalar, or a
6096 			 * PTR_TO_PACKET[_META,_END]. In the latter
6097 			 * case, we know the offset is zero.
6098 			 */
6099 			if (reg_type == SCALAR_VALUE) {
6100 				mark_reg_unknown(env, regs, value_regno);
6101 			} else {
6102 				mark_reg_known_zero(env, regs,
6103 						    value_regno);
6104 				if (type_may_be_null(reg_type))
6105 					regs[value_regno].id = ++env->id_gen;
6106 				/* A load of ctx field could have different
6107 				 * actual load size with the one encoded in the
6108 				 * insn. When the dst is PTR, it is for sure not
6109 				 * a sub-register.
6110 				 */
6111 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6112 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6113 					regs[value_regno].btf = btf;
6114 					regs[value_regno].btf_id = btf_id;
6115 				}
6116 			}
6117 			regs[value_regno].type = reg_type;
6118 		}
6119 
6120 	} else if (reg->type == PTR_TO_STACK) {
6121 		/* Basic bounds checks. */
6122 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6123 		if (err)
6124 			return err;
6125 
6126 		state = func(env, reg);
6127 		err = update_stack_depth(env, state, off);
6128 		if (err)
6129 			return err;
6130 
6131 		if (t == BPF_READ)
6132 			err = check_stack_read(env, regno, off, size,
6133 					       value_regno);
6134 		else
6135 			err = check_stack_write(env, regno, off, size,
6136 						value_regno, insn_idx);
6137 	} else if (reg_is_pkt_pointer(reg)) {
6138 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6139 			verbose(env, "cannot write into packet\n");
6140 			return -EACCES;
6141 		}
6142 		if (t == BPF_WRITE && value_regno >= 0 &&
6143 		    is_pointer_value(env, value_regno)) {
6144 			verbose(env, "R%d leaks addr into packet\n",
6145 				value_regno);
6146 			return -EACCES;
6147 		}
6148 		err = check_packet_access(env, regno, off, size, false);
6149 		if (!err && t == BPF_READ && value_regno >= 0)
6150 			mark_reg_unknown(env, regs, value_regno);
6151 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6152 		if (t == BPF_WRITE && value_regno >= 0 &&
6153 		    is_pointer_value(env, value_regno)) {
6154 			verbose(env, "R%d leaks addr into flow keys\n",
6155 				value_regno);
6156 			return -EACCES;
6157 		}
6158 
6159 		err = check_flow_keys_access(env, off, size);
6160 		if (!err && t == BPF_READ && value_regno >= 0)
6161 			mark_reg_unknown(env, regs, value_regno);
6162 	} else if (type_is_sk_pointer(reg->type)) {
6163 		if (t == BPF_WRITE) {
6164 			verbose(env, "R%d cannot write into %s\n",
6165 				regno, reg_type_str(env, reg->type));
6166 			return -EACCES;
6167 		}
6168 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6169 		if (!err && value_regno >= 0)
6170 			mark_reg_unknown(env, regs, value_regno);
6171 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6172 		err = check_tp_buffer_access(env, reg, regno, off, size);
6173 		if (!err && t == BPF_READ && value_regno >= 0)
6174 			mark_reg_unknown(env, regs, value_regno);
6175 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6176 		   !type_may_be_null(reg->type)) {
6177 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6178 					      value_regno);
6179 	} else if (reg->type == CONST_PTR_TO_MAP) {
6180 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6181 					      value_regno);
6182 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6183 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6184 		u32 *max_access;
6185 
6186 		if (rdonly_mem) {
6187 			if (t == BPF_WRITE) {
6188 				verbose(env, "R%d cannot write into %s\n",
6189 					regno, reg_type_str(env, reg->type));
6190 				return -EACCES;
6191 			}
6192 			max_access = &env->prog->aux->max_rdonly_access;
6193 		} else {
6194 			max_access = &env->prog->aux->max_rdwr_access;
6195 		}
6196 
6197 		err = check_buffer_access(env, reg, regno, off, size, false,
6198 					  max_access);
6199 
6200 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6201 			mark_reg_unknown(env, regs, value_regno);
6202 	} else {
6203 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6204 			reg_type_str(env, reg->type));
6205 		return -EACCES;
6206 	}
6207 
6208 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6209 	    regs[value_regno].type == SCALAR_VALUE) {
6210 		/* b/h/w load zero-extends, mark upper bits as known 0 */
6211 		coerce_reg_to_size(&regs[value_regno], size);
6212 	}
6213 	return err;
6214 }
6215 
6216 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6217 {
6218 	int load_reg;
6219 	int err;
6220 
6221 	switch (insn->imm) {
6222 	case BPF_ADD:
6223 	case BPF_ADD | BPF_FETCH:
6224 	case BPF_AND:
6225 	case BPF_AND | BPF_FETCH:
6226 	case BPF_OR:
6227 	case BPF_OR | BPF_FETCH:
6228 	case BPF_XOR:
6229 	case BPF_XOR | BPF_FETCH:
6230 	case BPF_XCHG:
6231 	case BPF_CMPXCHG:
6232 		break;
6233 	default:
6234 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6235 		return -EINVAL;
6236 	}
6237 
6238 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6239 		verbose(env, "invalid atomic operand size\n");
6240 		return -EINVAL;
6241 	}
6242 
6243 	/* check src1 operand */
6244 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6245 	if (err)
6246 		return err;
6247 
6248 	/* check src2 operand */
6249 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6250 	if (err)
6251 		return err;
6252 
6253 	if (insn->imm == BPF_CMPXCHG) {
6254 		/* Check comparison of R0 with memory location */
6255 		const u32 aux_reg = BPF_REG_0;
6256 
6257 		err = check_reg_arg(env, aux_reg, SRC_OP);
6258 		if (err)
6259 			return err;
6260 
6261 		if (is_pointer_value(env, aux_reg)) {
6262 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6263 			return -EACCES;
6264 		}
6265 	}
6266 
6267 	if (is_pointer_value(env, insn->src_reg)) {
6268 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6269 		return -EACCES;
6270 	}
6271 
6272 	if (is_ctx_reg(env, insn->dst_reg) ||
6273 	    is_pkt_reg(env, insn->dst_reg) ||
6274 	    is_flow_key_reg(env, insn->dst_reg) ||
6275 	    is_sk_reg(env, insn->dst_reg)) {
6276 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6277 			insn->dst_reg,
6278 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6279 		return -EACCES;
6280 	}
6281 
6282 	if (insn->imm & BPF_FETCH) {
6283 		if (insn->imm == BPF_CMPXCHG)
6284 			load_reg = BPF_REG_0;
6285 		else
6286 			load_reg = insn->src_reg;
6287 
6288 		/* check and record load of old value */
6289 		err = check_reg_arg(env, load_reg, DST_OP);
6290 		if (err)
6291 			return err;
6292 	} else {
6293 		/* This instruction accesses a memory location but doesn't
6294 		 * actually load it into a register.
6295 		 */
6296 		load_reg = -1;
6297 	}
6298 
6299 	/* Check whether we can read the memory, with second call for fetch
6300 	 * case to simulate the register fill.
6301 	 */
6302 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6303 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
6304 	if (!err && load_reg >= 0)
6305 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6306 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6307 				       true);
6308 	if (err)
6309 		return err;
6310 
6311 	/* Check whether we can write into the same memory. */
6312 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6313 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6314 	if (err)
6315 		return err;
6316 
6317 	return 0;
6318 }
6319 
6320 /* When register 'regno' is used to read the stack (either directly or through
6321  * a helper function) make sure that it's within stack boundary and, depending
6322  * on the access type, that all elements of the stack are initialized.
6323  *
6324  * 'off' includes 'regno->off', but not its dynamic part (if any).
6325  *
6326  * All registers that have been spilled on the stack in the slots within the
6327  * read offsets are marked as read.
6328  */
6329 static int check_stack_range_initialized(
6330 		struct bpf_verifier_env *env, int regno, int off,
6331 		int access_size, bool zero_size_allowed,
6332 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6333 {
6334 	struct bpf_reg_state *reg = reg_state(env, regno);
6335 	struct bpf_func_state *state = func(env, reg);
6336 	int err, min_off, max_off, i, j, slot, spi;
6337 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6338 	enum bpf_access_type bounds_check_type;
6339 	/* Some accesses can write anything into the stack, others are
6340 	 * read-only.
6341 	 */
6342 	bool clobber = false;
6343 
6344 	if (access_size == 0 && !zero_size_allowed) {
6345 		verbose(env, "invalid zero-sized read\n");
6346 		return -EACCES;
6347 	}
6348 
6349 	if (type == ACCESS_HELPER) {
6350 		/* The bounds checks for writes are more permissive than for
6351 		 * reads. However, if raw_mode is not set, we'll do extra
6352 		 * checks below.
6353 		 */
6354 		bounds_check_type = BPF_WRITE;
6355 		clobber = true;
6356 	} else {
6357 		bounds_check_type = BPF_READ;
6358 	}
6359 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6360 					       type, bounds_check_type);
6361 	if (err)
6362 		return err;
6363 
6364 
6365 	if (tnum_is_const(reg->var_off)) {
6366 		min_off = max_off = reg->var_off.value + off;
6367 	} else {
6368 		/* Variable offset is prohibited for unprivileged mode for
6369 		 * simplicity since it requires corresponding support in
6370 		 * Spectre masking for stack ALU.
6371 		 * See also retrieve_ptr_limit().
6372 		 */
6373 		if (!env->bypass_spec_v1) {
6374 			char tn_buf[48];
6375 
6376 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6377 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6378 				regno, err_extra, tn_buf);
6379 			return -EACCES;
6380 		}
6381 		/* Only initialized buffer on stack is allowed to be accessed
6382 		 * with variable offset. With uninitialized buffer it's hard to
6383 		 * guarantee that whole memory is marked as initialized on
6384 		 * helper return since specific bounds are unknown what may
6385 		 * cause uninitialized stack leaking.
6386 		 */
6387 		if (meta && meta->raw_mode)
6388 			meta = NULL;
6389 
6390 		min_off = reg->smin_value + off;
6391 		max_off = reg->smax_value + off;
6392 	}
6393 
6394 	if (meta && meta->raw_mode) {
6395 		/* Ensure we won't be overwriting dynptrs when simulating byte
6396 		 * by byte access in check_helper_call using meta.access_size.
6397 		 * This would be a problem if we have a helper in the future
6398 		 * which takes:
6399 		 *
6400 		 *	helper(uninit_mem, len, dynptr)
6401 		 *
6402 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6403 		 * may end up writing to dynptr itself when touching memory from
6404 		 * arg 1. This can be relaxed on a case by case basis for known
6405 		 * safe cases, but reject due to the possibilitiy of aliasing by
6406 		 * default.
6407 		 */
6408 		for (i = min_off; i < max_off + access_size; i++) {
6409 			int stack_off = -i - 1;
6410 
6411 			spi = __get_spi(i);
6412 			/* raw_mode may write past allocated_stack */
6413 			if (state->allocated_stack <= stack_off)
6414 				continue;
6415 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6416 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6417 				return -EACCES;
6418 			}
6419 		}
6420 		meta->access_size = access_size;
6421 		meta->regno = regno;
6422 		return 0;
6423 	}
6424 
6425 	for (i = min_off; i < max_off + access_size; i++) {
6426 		u8 *stype;
6427 
6428 		slot = -i - 1;
6429 		spi = slot / BPF_REG_SIZE;
6430 		if (state->allocated_stack <= slot)
6431 			goto err;
6432 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6433 		if (*stype == STACK_MISC)
6434 			goto mark;
6435 		if ((*stype == STACK_ZERO) ||
6436 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6437 			if (clobber) {
6438 				/* helper can write anything into the stack */
6439 				*stype = STACK_MISC;
6440 			}
6441 			goto mark;
6442 		}
6443 
6444 		if (is_spilled_reg(&state->stack[spi]) &&
6445 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6446 		     env->allow_ptr_leaks)) {
6447 			if (clobber) {
6448 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6449 				for (j = 0; j < BPF_REG_SIZE; j++)
6450 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6451 			}
6452 			goto mark;
6453 		}
6454 
6455 err:
6456 		if (tnum_is_const(reg->var_off)) {
6457 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6458 				err_extra, regno, min_off, i - min_off, access_size);
6459 		} else {
6460 			char tn_buf[48];
6461 
6462 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6463 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6464 				err_extra, regno, tn_buf, i - min_off, access_size);
6465 		}
6466 		return -EACCES;
6467 mark:
6468 		/* reading any byte out of 8-byte 'spill_slot' will cause
6469 		 * the whole slot to be marked as 'read'
6470 		 */
6471 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6472 			      state->stack[spi].spilled_ptr.parent,
6473 			      REG_LIVE_READ64);
6474 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6475 		 * be sure that whether stack slot is written to or not. Hence,
6476 		 * we must still conservatively propagate reads upwards even if
6477 		 * helper may write to the entire memory range.
6478 		 */
6479 	}
6480 	return update_stack_depth(env, state, min_off);
6481 }
6482 
6483 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6484 				   int access_size, bool zero_size_allowed,
6485 				   struct bpf_call_arg_meta *meta)
6486 {
6487 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6488 	u32 *max_access;
6489 
6490 	switch (base_type(reg->type)) {
6491 	case PTR_TO_PACKET:
6492 	case PTR_TO_PACKET_META:
6493 		return check_packet_access(env, regno, reg->off, access_size,
6494 					   zero_size_allowed);
6495 	case PTR_TO_MAP_KEY:
6496 		if (meta && meta->raw_mode) {
6497 			verbose(env, "R%d cannot write into %s\n", regno,
6498 				reg_type_str(env, reg->type));
6499 			return -EACCES;
6500 		}
6501 		return check_mem_region_access(env, regno, reg->off, access_size,
6502 					       reg->map_ptr->key_size, false);
6503 	case PTR_TO_MAP_VALUE:
6504 		if (check_map_access_type(env, regno, reg->off, access_size,
6505 					  meta && meta->raw_mode ? BPF_WRITE :
6506 					  BPF_READ))
6507 			return -EACCES;
6508 		return check_map_access(env, regno, reg->off, access_size,
6509 					zero_size_allowed, ACCESS_HELPER);
6510 	case PTR_TO_MEM:
6511 		if (type_is_rdonly_mem(reg->type)) {
6512 			if (meta && meta->raw_mode) {
6513 				verbose(env, "R%d cannot write into %s\n", regno,
6514 					reg_type_str(env, reg->type));
6515 				return -EACCES;
6516 			}
6517 		}
6518 		return check_mem_region_access(env, regno, reg->off,
6519 					       access_size, reg->mem_size,
6520 					       zero_size_allowed);
6521 	case PTR_TO_BUF:
6522 		if (type_is_rdonly_mem(reg->type)) {
6523 			if (meta && meta->raw_mode) {
6524 				verbose(env, "R%d cannot write into %s\n", regno,
6525 					reg_type_str(env, reg->type));
6526 				return -EACCES;
6527 			}
6528 
6529 			max_access = &env->prog->aux->max_rdonly_access;
6530 		} else {
6531 			max_access = &env->prog->aux->max_rdwr_access;
6532 		}
6533 		return check_buffer_access(env, reg, regno, reg->off,
6534 					   access_size, zero_size_allowed,
6535 					   max_access);
6536 	case PTR_TO_STACK:
6537 		return check_stack_range_initialized(
6538 				env,
6539 				regno, reg->off, access_size,
6540 				zero_size_allowed, ACCESS_HELPER, meta);
6541 	case PTR_TO_BTF_ID:
6542 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
6543 					       access_size, BPF_READ, -1);
6544 	case PTR_TO_CTX:
6545 		/* in case the function doesn't know how to access the context,
6546 		 * (because we are in a program of type SYSCALL for example), we
6547 		 * can not statically check its size.
6548 		 * Dynamically check it now.
6549 		 */
6550 		if (!env->ops->convert_ctx_access) {
6551 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6552 			int offset = access_size - 1;
6553 
6554 			/* Allow zero-byte read from PTR_TO_CTX */
6555 			if (access_size == 0)
6556 				return zero_size_allowed ? 0 : -EACCES;
6557 
6558 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6559 						atype, -1, false);
6560 		}
6561 
6562 		fallthrough;
6563 	default: /* scalar_value or invalid ptr */
6564 		/* Allow zero-byte read from NULL, regardless of pointer type */
6565 		if (zero_size_allowed && access_size == 0 &&
6566 		    register_is_null(reg))
6567 			return 0;
6568 
6569 		verbose(env, "R%d type=%s ", regno,
6570 			reg_type_str(env, reg->type));
6571 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6572 		return -EACCES;
6573 	}
6574 }
6575 
6576 static int check_mem_size_reg(struct bpf_verifier_env *env,
6577 			      struct bpf_reg_state *reg, u32 regno,
6578 			      bool zero_size_allowed,
6579 			      struct bpf_call_arg_meta *meta)
6580 {
6581 	int err;
6582 
6583 	/* This is used to refine r0 return value bounds for helpers
6584 	 * that enforce this value as an upper bound on return values.
6585 	 * See do_refine_retval_range() for helpers that can refine
6586 	 * the return value. C type of helper is u32 so we pull register
6587 	 * bound from umax_value however, if negative verifier errors
6588 	 * out. Only upper bounds can be learned because retval is an
6589 	 * int type and negative retvals are allowed.
6590 	 */
6591 	meta->msize_max_value = reg->umax_value;
6592 
6593 	/* The register is SCALAR_VALUE; the access check
6594 	 * happens using its boundaries.
6595 	 */
6596 	if (!tnum_is_const(reg->var_off))
6597 		/* For unprivileged variable accesses, disable raw
6598 		 * mode so that the program is required to
6599 		 * initialize all the memory that the helper could
6600 		 * just partially fill up.
6601 		 */
6602 		meta = NULL;
6603 
6604 	if (reg->smin_value < 0) {
6605 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6606 			regno);
6607 		return -EACCES;
6608 	}
6609 
6610 	if (reg->umin_value == 0) {
6611 		err = check_helper_mem_access(env, regno - 1, 0,
6612 					      zero_size_allowed,
6613 					      meta);
6614 		if (err)
6615 			return err;
6616 	}
6617 
6618 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6619 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6620 			regno);
6621 		return -EACCES;
6622 	}
6623 	err = check_helper_mem_access(env, regno - 1,
6624 				      reg->umax_value,
6625 				      zero_size_allowed, meta);
6626 	if (!err)
6627 		err = mark_chain_precision(env, regno);
6628 	return err;
6629 }
6630 
6631 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6632 		   u32 regno, u32 mem_size)
6633 {
6634 	bool may_be_null = type_may_be_null(reg->type);
6635 	struct bpf_reg_state saved_reg;
6636 	struct bpf_call_arg_meta meta;
6637 	int err;
6638 
6639 	if (register_is_null(reg))
6640 		return 0;
6641 
6642 	memset(&meta, 0, sizeof(meta));
6643 	/* Assuming that the register contains a value check if the memory
6644 	 * access is safe. Temporarily save and restore the register's state as
6645 	 * the conversion shouldn't be visible to a caller.
6646 	 */
6647 	if (may_be_null) {
6648 		saved_reg = *reg;
6649 		mark_ptr_not_null_reg(reg);
6650 	}
6651 
6652 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6653 	/* Check access for BPF_WRITE */
6654 	meta.raw_mode = true;
6655 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6656 
6657 	if (may_be_null)
6658 		*reg = saved_reg;
6659 
6660 	return err;
6661 }
6662 
6663 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6664 				    u32 regno)
6665 {
6666 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6667 	bool may_be_null = type_may_be_null(mem_reg->type);
6668 	struct bpf_reg_state saved_reg;
6669 	struct bpf_call_arg_meta meta;
6670 	int err;
6671 
6672 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6673 
6674 	memset(&meta, 0, sizeof(meta));
6675 
6676 	if (may_be_null) {
6677 		saved_reg = *mem_reg;
6678 		mark_ptr_not_null_reg(mem_reg);
6679 	}
6680 
6681 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6682 	/* Check access for BPF_WRITE */
6683 	meta.raw_mode = true;
6684 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6685 
6686 	if (may_be_null)
6687 		*mem_reg = saved_reg;
6688 	return err;
6689 }
6690 
6691 /* Implementation details:
6692  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6693  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6694  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6695  * Two separate bpf_obj_new will also have different reg->id.
6696  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6697  * clears reg->id after value_or_null->value transition, since the verifier only
6698  * cares about the range of access to valid map value pointer and doesn't care
6699  * about actual address of the map element.
6700  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6701  * reg->id > 0 after value_or_null->value transition. By doing so
6702  * two bpf_map_lookups will be considered two different pointers that
6703  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6704  * returned from bpf_obj_new.
6705  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6706  * dead-locks.
6707  * Since only one bpf_spin_lock is allowed the checks are simpler than
6708  * reg_is_refcounted() logic. The verifier needs to remember only
6709  * one spin_lock instead of array of acquired_refs.
6710  * cur_state->active_lock remembers which map value element or allocated
6711  * object got locked and clears it after bpf_spin_unlock.
6712  */
6713 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6714 			     bool is_lock)
6715 {
6716 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6717 	struct bpf_verifier_state *cur = env->cur_state;
6718 	bool is_const = tnum_is_const(reg->var_off);
6719 	u64 val = reg->var_off.value;
6720 	struct bpf_map *map = NULL;
6721 	struct btf *btf = NULL;
6722 	struct btf_record *rec;
6723 
6724 	if (!is_const) {
6725 		verbose(env,
6726 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6727 			regno);
6728 		return -EINVAL;
6729 	}
6730 	if (reg->type == PTR_TO_MAP_VALUE) {
6731 		map = reg->map_ptr;
6732 		if (!map->btf) {
6733 			verbose(env,
6734 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6735 				map->name);
6736 			return -EINVAL;
6737 		}
6738 	} else {
6739 		btf = reg->btf;
6740 	}
6741 
6742 	rec = reg_btf_record(reg);
6743 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6744 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6745 			map ? map->name : "kptr");
6746 		return -EINVAL;
6747 	}
6748 	if (rec->spin_lock_off != val + reg->off) {
6749 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6750 			val + reg->off, rec->spin_lock_off);
6751 		return -EINVAL;
6752 	}
6753 	if (is_lock) {
6754 		if (cur->active_lock.ptr) {
6755 			verbose(env,
6756 				"Locking two bpf_spin_locks are not allowed\n");
6757 			return -EINVAL;
6758 		}
6759 		if (map)
6760 			cur->active_lock.ptr = map;
6761 		else
6762 			cur->active_lock.ptr = btf;
6763 		cur->active_lock.id = reg->id;
6764 	} else {
6765 		void *ptr;
6766 
6767 		if (map)
6768 			ptr = map;
6769 		else
6770 			ptr = btf;
6771 
6772 		if (!cur->active_lock.ptr) {
6773 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6774 			return -EINVAL;
6775 		}
6776 		if (cur->active_lock.ptr != ptr ||
6777 		    cur->active_lock.id != reg->id) {
6778 			verbose(env, "bpf_spin_unlock of different lock\n");
6779 			return -EINVAL;
6780 		}
6781 
6782 		invalidate_non_owning_refs(env);
6783 
6784 		cur->active_lock.ptr = NULL;
6785 		cur->active_lock.id = 0;
6786 	}
6787 	return 0;
6788 }
6789 
6790 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6791 			      struct bpf_call_arg_meta *meta)
6792 {
6793 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6794 	bool is_const = tnum_is_const(reg->var_off);
6795 	struct bpf_map *map = reg->map_ptr;
6796 	u64 val = reg->var_off.value;
6797 
6798 	if (!is_const) {
6799 		verbose(env,
6800 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6801 			regno);
6802 		return -EINVAL;
6803 	}
6804 	if (!map->btf) {
6805 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6806 			map->name);
6807 		return -EINVAL;
6808 	}
6809 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6810 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6811 		return -EINVAL;
6812 	}
6813 	if (map->record->timer_off != val + reg->off) {
6814 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6815 			val + reg->off, map->record->timer_off);
6816 		return -EINVAL;
6817 	}
6818 	if (meta->map_ptr) {
6819 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6820 		return -EFAULT;
6821 	}
6822 	meta->map_uid = reg->map_uid;
6823 	meta->map_ptr = map;
6824 	return 0;
6825 }
6826 
6827 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6828 			     struct bpf_call_arg_meta *meta)
6829 {
6830 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6831 	struct bpf_map *map_ptr = reg->map_ptr;
6832 	struct btf_field *kptr_field;
6833 	u32 kptr_off;
6834 
6835 	if (!tnum_is_const(reg->var_off)) {
6836 		verbose(env,
6837 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6838 			regno);
6839 		return -EINVAL;
6840 	}
6841 	if (!map_ptr->btf) {
6842 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6843 			map_ptr->name);
6844 		return -EINVAL;
6845 	}
6846 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6847 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6848 		return -EINVAL;
6849 	}
6850 
6851 	meta->map_ptr = map_ptr;
6852 	kptr_off = reg->off + reg->var_off.value;
6853 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6854 	if (!kptr_field) {
6855 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6856 		return -EACCES;
6857 	}
6858 	if (kptr_field->type != BPF_KPTR_REF) {
6859 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6860 		return -EACCES;
6861 	}
6862 	meta->kptr_field = kptr_field;
6863 	return 0;
6864 }
6865 
6866 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6867  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6868  *
6869  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6870  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6871  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6872  *
6873  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6874  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6875  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6876  * mutate the view of the dynptr and also possibly destroy it. In the latter
6877  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6878  * memory that dynptr points to.
6879  *
6880  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6881  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6882  * readonly dynptr view yet, hence only the first case is tracked and checked.
6883  *
6884  * This is consistent with how C applies the const modifier to a struct object,
6885  * where the pointer itself inside bpf_dynptr becomes const but not what it
6886  * points to.
6887  *
6888  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6889  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6890  */
6891 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6892 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
6893 {
6894 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6895 	int err;
6896 
6897 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6898 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6899 	 */
6900 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6901 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6902 		return -EFAULT;
6903 	}
6904 
6905 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6906 	 *		 constructing a mutable bpf_dynptr object.
6907 	 *
6908 	 *		 Currently, this is only possible with PTR_TO_STACK
6909 	 *		 pointing to a region of at least 16 bytes which doesn't
6910 	 *		 contain an existing bpf_dynptr.
6911 	 *
6912 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6913 	 *		 mutated or destroyed. However, the memory it points to
6914 	 *		 may be mutated.
6915 	 *
6916 	 *  None       - Points to a initialized dynptr that can be mutated and
6917 	 *		 destroyed, including mutation of the memory it points
6918 	 *		 to.
6919 	 */
6920 	if (arg_type & MEM_UNINIT) {
6921 		int i;
6922 
6923 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
6924 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6925 			return -EINVAL;
6926 		}
6927 
6928 		/* we write BPF_DW bits (8 bytes) at a time */
6929 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6930 			err = check_mem_access(env, insn_idx, regno,
6931 					       i, BPF_DW, BPF_WRITE, -1, false);
6932 			if (err)
6933 				return err;
6934 		}
6935 
6936 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
6937 	} else /* MEM_RDONLY and None case from above */ {
6938 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6939 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6940 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6941 			return -EINVAL;
6942 		}
6943 
6944 		if (!is_dynptr_reg_valid_init(env, reg)) {
6945 			verbose(env,
6946 				"Expected an initialized dynptr as arg #%d\n",
6947 				regno);
6948 			return -EINVAL;
6949 		}
6950 
6951 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6952 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6953 			verbose(env,
6954 				"Expected a dynptr of type %s as arg #%d\n",
6955 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6956 			return -EINVAL;
6957 		}
6958 
6959 		err = mark_dynptr_read(env, reg);
6960 	}
6961 	return err;
6962 }
6963 
6964 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
6965 {
6966 	struct bpf_func_state *state = func(env, reg);
6967 
6968 	return state->stack[spi].spilled_ptr.ref_obj_id;
6969 }
6970 
6971 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6972 {
6973 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
6974 }
6975 
6976 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6977 {
6978 	return meta->kfunc_flags & KF_ITER_NEW;
6979 }
6980 
6981 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6982 {
6983 	return meta->kfunc_flags & KF_ITER_NEXT;
6984 }
6985 
6986 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6987 {
6988 	return meta->kfunc_flags & KF_ITER_DESTROY;
6989 }
6990 
6991 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
6992 {
6993 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
6994 	 * kfunc is iter state pointer
6995 	 */
6996 	return arg == 0 && is_iter_kfunc(meta);
6997 }
6998 
6999 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7000 			    struct bpf_kfunc_call_arg_meta *meta)
7001 {
7002 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7003 	const struct btf_type *t;
7004 	const struct btf_param *arg;
7005 	int spi, err, i, nr_slots;
7006 	u32 btf_id;
7007 
7008 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7009 	arg = &btf_params(meta->func_proto)[0];
7010 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7011 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7012 	nr_slots = t->size / BPF_REG_SIZE;
7013 
7014 	if (is_iter_new_kfunc(meta)) {
7015 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7016 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7017 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7018 				iter_type_str(meta->btf, btf_id), regno);
7019 			return -EINVAL;
7020 		}
7021 
7022 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7023 			err = check_mem_access(env, insn_idx, regno,
7024 					       i, BPF_DW, BPF_WRITE, -1, false);
7025 			if (err)
7026 				return err;
7027 		}
7028 
7029 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7030 		if (err)
7031 			return err;
7032 	} else {
7033 		/* iter_next() or iter_destroy() expect initialized iter state*/
7034 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7035 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7036 				iter_type_str(meta->btf, btf_id), regno);
7037 			return -EINVAL;
7038 		}
7039 
7040 		spi = iter_get_spi(env, reg, nr_slots);
7041 		if (spi < 0)
7042 			return spi;
7043 
7044 		err = mark_iter_read(env, reg, spi, nr_slots);
7045 		if (err)
7046 			return err;
7047 
7048 		/* remember meta->iter info for process_iter_next_call() */
7049 		meta->iter.spi = spi;
7050 		meta->iter.frameno = reg->frameno;
7051 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7052 
7053 		if (is_iter_destroy_kfunc(meta)) {
7054 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7055 			if (err)
7056 				return err;
7057 		}
7058 	}
7059 
7060 	return 0;
7061 }
7062 
7063 /* process_iter_next_call() is called when verifier gets to iterator's next
7064  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7065  * to it as just "iter_next()" in comments below.
7066  *
7067  * BPF verifier relies on a crucial contract for any iter_next()
7068  * implementation: it should *eventually* return NULL, and once that happens
7069  * it should keep returning NULL. That is, once iterator exhausts elements to
7070  * iterate, it should never reset or spuriously return new elements.
7071  *
7072  * With the assumption of such contract, process_iter_next_call() simulates
7073  * a fork in the verifier state to validate loop logic correctness and safety
7074  * without having to simulate infinite amount of iterations.
7075  *
7076  * In current state, we first assume that iter_next() returned NULL and
7077  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7078  * conditions we should not form an infinite loop and should eventually reach
7079  * exit.
7080  *
7081  * Besides that, we also fork current state and enqueue it for later
7082  * verification. In a forked state we keep iterator state as ACTIVE
7083  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7084  * also bump iteration depth to prevent erroneous infinite loop detection
7085  * later on (see iter_active_depths_differ() comment for details). In this
7086  * state we assume that we'll eventually loop back to another iter_next()
7087  * calls (it could be in exactly same location or in some other instruction,
7088  * it doesn't matter, we don't make any unnecessary assumptions about this,
7089  * everything revolves around iterator state in a stack slot, not which
7090  * instruction is calling iter_next()). When that happens, we either will come
7091  * to iter_next() with equivalent state and can conclude that next iteration
7092  * will proceed in exactly the same way as we just verified, so it's safe to
7093  * assume that loop converges. If not, we'll go on another iteration
7094  * simulation with a different input state, until all possible starting states
7095  * are validated or we reach maximum number of instructions limit.
7096  *
7097  * This way, we will either exhaustively discover all possible input states
7098  * that iterator loop can start with and eventually will converge, or we'll
7099  * effectively regress into bounded loop simulation logic and either reach
7100  * maximum number of instructions if loop is not provably convergent, or there
7101  * is some statically known limit on number of iterations (e.g., if there is
7102  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7103  *
7104  * One very subtle but very important aspect is that we *always* simulate NULL
7105  * condition first (as the current state) before we simulate non-NULL case.
7106  * This has to do with intricacies of scalar precision tracking. By simulating
7107  * "exit condition" of iter_next() returning NULL first, we make sure all the
7108  * relevant precision marks *that will be set **after** we exit iterator loop*
7109  * are propagated backwards to common parent state of NULL and non-NULL
7110  * branches. Thanks to that, state equivalence checks done later in forked
7111  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7112  * precision marks are finalized and won't change. Because simulating another
7113  * ACTIVE iterator iteration won't change them (because given same input
7114  * states we'll end up with exactly same output states which we are currently
7115  * comparing; and verification after the loop already propagated back what
7116  * needs to be **additionally** tracked as precise). It's subtle, grok
7117  * precision tracking for more intuitive understanding.
7118  */
7119 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7120 				  struct bpf_kfunc_call_arg_meta *meta)
7121 {
7122 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7123 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7124 	struct bpf_reg_state *cur_iter, *queued_iter;
7125 	int iter_frameno = meta->iter.frameno;
7126 	int iter_spi = meta->iter.spi;
7127 
7128 	BTF_TYPE_EMIT(struct bpf_iter);
7129 
7130 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7131 
7132 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7133 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7134 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7135 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7136 		return -EFAULT;
7137 	}
7138 
7139 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7140 		/* branch out active iter state */
7141 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7142 		if (!queued_st)
7143 			return -ENOMEM;
7144 
7145 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7146 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7147 		queued_iter->iter.depth++;
7148 
7149 		queued_fr = queued_st->frame[queued_st->curframe];
7150 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7151 	}
7152 
7153 	/* switch to DRAINED state, but keep the depth unchanged */
7154 	/* mark current iter state as drained and assume returned NULL */
7155 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7156 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7157 
7158 	return 0;
7159 }
7160 
7161 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7162 {
7163 	return type == ARG_CONST_SIZE ||
7164 	       type == ARG_CONST_SIZE_OR_ZERO;
7165 }
7166 
7167 static bool arg_type_is_release(enum bpf_arg_type type)
7168 {
7169 	return type & OBJ_RELEASE;
7170 }
7171 
7172 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7173 {
7174 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7175 }
7176 
7177 static int int_ptr_type_to_size(enum bpf_arg_type type)
7178 {
7179 	if (type == ARG_PTR_TO_INT)
7180 		return sizeof(u32);
7181 	else if (type == ARG_PTR_TO_LONG)
7182 		return sizeof(u64);
7183 
7184 	return -EINVAL;
7185 }
7186 
7187 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7188 				 const struct bpf_call_arg_meta *meta,
7189 				 enum bpf_arg_type *arg_type)
7190 {
7191 	if (!meta->map_ptr) {
7192 		/* kernel subsystem misconfigured verifier */
7193 		verbose(env, "invalid map_ptr to access map->type\n");
7194 		return -EACCES;
7195 	}
7196 
7197 	switch (meta->map_ptr->map_type) {
7198 	case BPF_MAP_TYPE_SOCKMAP:
7199 	case BPF_MAP_TYPE_SOCKHASH:
7200 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7201 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7202 		} else {
7203 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7204 			return -EINVAL;
7205 		}
7206 		break;
7207 	case BPF_MAP_TYPE_BLOOM_FILTER:
7208 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7209 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7210 		break;
7211 	default:
7212 		break;
7213 	}
7214 	return 0;
7215 }
7216 
7217 struct bpf_reg_types {
7218 	const enum bpf_reg_type types[10];
7219 	u32 *btf_id;
7220 };
7221 
7222 static const struct bpf_reg_types sock_types = {
7223 	.types = {
7224 		PTR_TO_SOCK_COMMON,
7225 		PTR_TO_SOCKET,
7226 		PTR_TO_TCP_SOCK,
7227 		PTR_TO_XDP_SOCK,
7228 	},
7229 };
7230 
7231 #ifdef CONFIG_NET
7232 static const struct bpf_reg_types btf_id_sock_common_types = {
7233 	.types = {
7234 		PTR_TO_SOCK_COMMON,
7235 		PTR_TO_SOCKET,
7236 		PTR_TO_TCP_SOCK,
7237 		PTR_TO_XDP_SOCK,
7238 		PTR_TO_BTF_ID,
7239 		PTR_TO_BTF_ID | PTR_TRUSTED,
7240 	},
7241 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7242 };
7243 #endif
7244 
7245 static const struct bpf_reg_types mem_types = {
7246 	.types = {
7247 		PTR_TO_STACK,
7248 		PTR_TO_PACKET,
7249 		PTR_TO_PACKET_META,
7250 		PTR_TO_MAP_KEY,
7251 		PTR_TO_MAP_VALUE,
7252 		PTR_TO_MEM,
7253 		PTR_TO_MEM | MEM_RINGBUF,
7254 		PTR_TO_BUF,
7255 		PTR_TO_BTF_ID | PTR_TRUSTED,
7256 	},
7257 };
7258 
7259 static const struct bpf_reg_types int_ptr_types = {
7260 	.types = {
7261 		PTR_TO_STACK,
7262 		PTR_TO_PACKET,
7263 		PTR_TO_PACKET_META,
7264 		PTR_TO_MAP_KEY,
7265 		PTR_TO_MAP_VALUE,
7266 	},
7267 };
7268 
7269 static const struct bpf_reg_types spin_lock_types = {
7270 	.types = {
7271 		PTR_TO_MAP_VALUE,
7272 		PTR_TO_BTF_ID | MEM_ALLOC,
7273 	}
7274 };
7275 
7276 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7277 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7278 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7279 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7280 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7281 static const struct bpf_reg_types btf_ptr_types = {
7282 	.types = {
7283 		PTR_TO_BTF_ID,
7284 		PTR_TO_BTF_ID | PTR_TRUSTED,
7285 		PTR_TO_BTF_ID | MEM_RCU,
7286 	},
7287 };
7288 static const struct bpf_reg_types percpu_btf_ptr_types = {
7289 	.types = {
7290 		PTR_TO_BTF_ID | MEM_PERCPU,
7291 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7292 	}
7293 };
7294 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7295 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7296 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7297 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7298 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7299 static const struct bpf_reg_types dynptr_types = {
7300 	.types = {
7301 		PTR_TO_STACK,
7302 		CONST_PTR_TO_DYNPTR,
7303 	}
7304 };
7305 
7306 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7307 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7308 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7309 	[ARG_CONST_SIZE]		= &scalar_types,
7310 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7311 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7312 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7313 	[ARG_PTR_TO_CTX]		= &context_types,
7314 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7315 #ifdef CONFIG_NET
7316 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7317 #endif
7318 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7319 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7320 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7321 	[ARG_PTR_TO_MEM]		= &mem_types,
7322 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7323 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7324 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7325 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7326 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7327 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7328 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7329 	[ARG_PTR_TO_TIMER]		= &timer_types,
7330 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7331 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7332 };
7333 
7334 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7335 			  enum bpf_arg_type arg_type,
7336 			  const u32 *arg_btf_id,
7337 			  struct bpf_call_arg_meta *meta)
7338 {
7339 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7340 	enum bpf_reg_type expected, type = reg->type;
7341 	const struct bpf_reg_types *compatible;
7342 	int i, j;
7343 
7344 	compatible = compatible_reg_types[base_type(arg_type)];
7345 	if (!compatible) {
7346 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7347 		return -EFAULT;
7348 	}
7349 
7350 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7351 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7352 	 *
7353 	 * Same for MAYBE_NULL:
7354 	 *
7355 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7356 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7357 	 *
7358 	 * Therefore we fold these flags depending on the arg_type before comparison.
7359 	 */
7360 	if (arg_type & MEM_RDONLY)
7361 		type &= ~MEM_RDONLY;
7362 	if (arg_type & PTR_MAYBE_NULL)
7363 		type &= ~PTR_MAYBE_NULL;
7364 
7365 	if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7366 		type &= ~MEM_ALLOC;
7367 
7368 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7369 		expected = compatible->types[i];
7370 		if (expected == NOT_INIT)
7371 			break;
7372 
7373 		if (type == expected)
7374 			goto found;
7375 	}
7376 
7377 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7378 	for (j = 0; j + 1 < i; j++)
7379 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7380 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7381 	return -EACCES;
7382 
7383 found:
7384 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7385 		return 0;
7386 
7387 	if (compatible == &mem_types) {
7388 		if (!(arg_type & MEM_RDONLY)) {
7389 			verbose(env,
7390 				"%s() may write into memory pointed by R%d type=%s\n",
7391 				func_id_name(meta->func_id),
7392 				regno, reg_type_str(env, reg->type));
7393 			return -EACCES;
7394 		}
7395 		return 0;
7396 	}
7397 
7398 	switch ((int)reg->type) {
7399 	case PTR_TO_BTF_ID:
7400 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7401 	case PTR_TO_BTF_ID | MEM_RCU:
7402 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7403 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7404 	{
7405 		/* For bpf_sk_release, it needs to match against first member
7406 		 * 'struct sock_common', hence make an exception for it. This
7407 		 * allows bpf_sk_release to work for multiple socket types.
7408 		 */
7409 		bool strict_type_match = arg_type_is_release(arg_type) &&
7410 					 meta->func_id != BPF_FUNC_sk_release;
7411 
7412 		if (type_may_be_null(reg->type) &&
7413 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7414 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7415 			return -EACCES;
7416 		}
7417 
7418 		if (!arg_btf_id) {
7419 			if (!compatible->btf_id) {
7420 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7421 				return -EFAULT;
7422 			}
7423 			arg_btf_id = compatible->btf_id;
7424 		}
7425 
7426 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7427 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7428 				return -EACCES;
7429 		} else {
7430 			if (arg_btf_id == BPF_PTR_POISON) {
7431 				verbose(env, "verifier internal error:");
7432 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7433 					regno);
7434 				return -EACCES;
7435 			}
7436 
7437 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7438 						  btf_vmlinux, *arg_btf_id,
7439 						  strict_type_match)) {
7440 				verbose(env, "R%d is of type %s but %s is expected\n",
7441 					regno, btf_type_name(reg->btf, reg->btf_id),
7442 					btf_type_name(btf_vmlinux, *arg_btf_id));
7443 				return -EACCES;
7444 			}
7445 		}
7446 		break;
7447 	}
7448 	case PTR_TO_BTF_ID | MEM_ALLOC:
7449 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7450 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7451 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7452 			return -EFAULT;
7453 		}
7454 		/* Handled by helper specific checks */
7455 		break;
7456 	case PTR_TO_BTF_ID | MEM_PERCPU:
7457 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7458 		/* Handled by helper specific checks */
7459 		break;
7460 	default:
7461 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7462 		return -EFAULT;
7463 	}
7464 	return 0;
7465 }
7466 
7467 static struct btf_field *
7468 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7469 {
7470 	struct btf_field *field;
7471 	struct btf_record *rec;
7472 
7473 	rec = reg_btf_record(reg);
7474 	if (!rec)
7475 		return NULL;
7476 
7477 	field = btf_record_find(rec, off, fields);
7478 	if (!field)
7479 		return NULL;
7480 
7481 	return field;
7482 }
7483 
7484 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7485 			   const struct bpf_reg_state *reg, int regno,
7486 			   enum bpf_arg_type arg_type)
7487 {
7488 	u32 type = reg->type;
7489 
7490 	/* When referenced register is passed to release function, its fixed
7491 	 * offset must be 0.
7492 	 *
7493 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7494 	 * meta->release_regno.
7495 	 */
7496 	if (arg_type_is_release(arg_type)) {
7497 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7498 		 * may not directly point to the object being released, but to
7499 		 * dynptr pointing to such object, which might be at some offset
7500 		 * on the stack. In that case, we simply to fallback to the
7501 		 * default handling.
7502 		 */
7503 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7504 			return 0;
7505 
7506 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7507 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7508 				return __check_ptr_off_reg(env, reg, regno, true);
7509 
7510 			verbose(env, "R%d must have zero offset when passed to release func\n",
7511 				regno);
7512 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7513 				btf_type_name(reg->btf, reg->btf_id), reg->off);
7514 			return -EINVAL;
7515 		}
7516 
7517 		/* Doing check_ptr_off_reg check for the offset will catch this
7518 		 * because fixed_off_ok is false, but checking here allows us
7519 		 * to give the user a better error message.
7520 		 */
7521 		if (reg->off) {
7522 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7523 				regno);
7524 			return -EINVAL;
7525 		}
7526 		return __check_ptr_off_reg(env, reg, regno, false);
7527 	}
7528 
7529 	switch (type) {
7530 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7531 	case PTR_TO_STACK:
7532 	case PTR_TO_PACKET:
7533 	case PTR_TO_PACKET_META:
7534 	case PTR_TO_MAP_KEY:
7535 	case PTR_TO_MAP_VALUE:
7536 	case PTR_TO_MEM:
7537 	case PTR_TO_MEM | MEM_RDONLY:
7538 	case PTR_TO_MEM | MEM_RINGBUF:
7539 	case PTR_TO_BUF:
7540 	case PTR_TO_BUF | MEM_RDONLY:
7541 	case SCALAR_VALUE:
7542 		return 0;
7543 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7544 	 * fixed offset.
7545 	 */
7546 	case PTR_TO_BTF_ID:
7547 	case PTR_TO_BTF_ID | MEM_ALLOC:
7548 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7549 	case PTR_TO_BTF_ID | MEM_RCU:
7550 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7551 		/* When referenced PTR_TO_BTF_ID is passed to release function,
7552 		 * its fixed offset must be 0. In the other cases, fixed offset
7553 		 * can be non-zero. This was already checked above. So pass
7554 		 * fixed_off_ok as true to allow fixed offset for all other
7555 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7556 		 * still need to do checks instead of returning.
7557 		 */
7558 		return __check_ptr_off_reg(env, reg, regno, true);
7559 	default:
7560 		return __check_ptr_off_reg(env, reg, regno, false);
7561 	}
7562 }
7563 
7564 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7565 						const struct bpf_func_proto *fn,
7566 						struct bpf_reg_state *regs)
7567 {
7568 	struct bpf_reg_state *state = NULL;
7569 	int i;
7570 
7571 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7572 		if (arg_type_is_dynptr(fn->arg_type[i])) {
7573 			if (state) {
7574 				verbose(env, "verifier internal error: multiple dynptr args\n");
7575 				return NULL;
7576 			}
7577 			state = &regs[BPF_REG_1 + i];
7578 		}
7579 
7580 	if (!state)
7581 		verbose(env, "verifier internal error: no dynptr arg found\n");
7582 
7583 	return state;
7584 }
7585 
7586 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7587 {
7588 	struct bpf_func_state *state = func(env, reg);
7589 	int spi;
7590 
7591 	if (reg->type == CONST_PTR_TO_DYNPTR)
7592 		return reg->id;
7593 	spi = dynptr_get_spi(env, reg);
7594 	if (spi < 0)
7595 		return spi;
7596 	return state->stack[spi].spilled_ptr.id;
7597 }
7598 
7599 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7600 {
7601 	struct bpf_func_state *state = func(env, reg);
7602 	int spi;
7603 
7604 	if (reg->type == CONST_PTR_TO_DYNPTR)
7605 		return reg->ref_obj_id;
7606 	spi = dynptr_get_spi(env, reg);
7607 	if (spi < 0)
7608 		return spi;
7609 	return state->stack[spi].spilled_ptr.ref_obj_id;
7610 }
7611 
7612 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7613 					    struct bpf_reg_state *reg)
7614 {
7615 	struct bpf_func_state *state = func(env, reg);
7616 	int spi;
7617 
7618 	if (reg->type == CONST_PTR_TO_DYNPTR)
7619 		return reg->dynptr.type;
7620 
7621 	spi = __get_spi(reg->off);
7622 	if (spi < 0) {
7623 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7624 		return BPF_DYNPTR_TYPE_INVALID;
7625 	}
7626 
7627 	return state->stack[spi].spilled_ptr.dynptr.type;
7628 }
7629 
7630 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7631 			  struct bpf_call_arg_meta *meta,
7632 			  const struct bpf_func_proto *fn,
7633 			  int insn_idx)
7634 {
7635 	u32 regno = BPF_REG_1 + arg;
7636 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7637 	enum bpf_arg_type arg_type = fn->arg_type[arg];
7638 	enum bpf_reg_type type = reg->type;
7639 	u32 *arg_btf_id = NULL;
7640 	int err = 0;
7641 
7642 	if (arg_type == ARG_DONTCARE)
7643 		return 0;
7644 
7645 	err = check_reg_arg(env, regno, SRC_OP);
7646 	if (err)
7647 		return err;
7648 
7649 	if (arg_type == ARG_ANYTHING) {
7650 		if (is_pointer_value(env, regno)) {
7651 			verbose(env, "R%d leaks addr into helper function\n",
7652 				regno);
7653 			return -EACCES;
7654 		}
7655 		return 0;
7656 	}
7657 
7658 	if (type_is_pkt_pointer(type) &&
7659 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7660 		verbose(env, "helper access to the packet is not allowed\n");
7661 		return -EACCES;
7662 	}
7663 
7664 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7665 		err = resolve_map_arg_type(env, meta, &arg_type);
7666 		if (err)
7667 			return err;
7668 	}
7669 
7670 	if (register_is_null(reg) && type_may_be_null(arg_type))
7671 		/* A NULL register has a SCALAR_VALUE type, so skip
7672 		 * type checking.
7673 		 */
7674 		goto skip_type_check;
7675 
7676 	/* arg_btf_id and arg_size are in a union. */
7677 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7678 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7679 		arg_btf_id = fn->arg_btf_id[arg];
7680 
7681 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7682 	if (err)
7683 		return err;
7684 
7685 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7686 	if (err)
7687 		return err;
7688 
7689 skip_type_check:
7690 	if (arg_type_is_release(arg_type)) {
7691 		if (arg_type_is_dynptr(arg_type)) {
7692 			struct bpf_func_state *state = func(env, reg);
7693 			int spi;
7694 
7695 			/* Only dynptr created on stack can be released, thus
7696 			 * the get_spi and stack state checks for spilled_ptr
7697 			 * should only be done before process_dynptr_func for
7698 			 * PTR_TO_STACK.
7699 			 */
7700 			if (reg->type == PTR_TO_STACK) {
7701 				spi = dynptr_get_spi(env, reg);
7702 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7703 					verbose(env, "arg %d is an unacquired reference\n", regno);
7704 					return -EINVAL;
7705 				}
7706 			} else {
7707 				verbose(env, "cannot release unowned const bpf_dynptr\n");
7708 				return -EINVAL;
7709 			}
7710 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
7711 			verbose(env, "R%d must be referenced when passed to release function\n",
7712 				regno);
7713 			return -EINVAL;
7714 		}
7715 		if (meta->release_regno) {
7716 			verbose(env, "verifier internal error: more than one release argument\n");
7717 			return -EFAULT;
7718 		}
7719 		meta->release_regno = regno;
7720 	}
7721 
7722 	if (reg->ref_obj_id) {
7723 		if (meta->ref_obj_id) {
7724 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7725 				regno, reg->ref_obj_id,
7726 				meta->ref_obj_id);
7727 			return -EFAULT;
7728 		}
7729 		meta->ref_obj_id = reg->ref_obj_id;
7730 	}
7731 
7732 	switch (base_type(arg_type)) {
7733 	case ARG_CONST_MAP_PTR:
7734 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7735 		if (meta->map_ptr) {
7736 			/* Use map_uid (which is unique id of inner map) to reject:
7737 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7738 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7739 			 * if (inner_map1 && inner_map2) {
7740 			 *     timer = bpf_map_lookup_elem(inner_map1);
7741 			 *     if (timer)
7742 			 *         // mismatch would have been allowed
7743 			 *         bpf_timer_init(timer, inner_map2);
7744 			 * }
7745 			 *
7746 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
7747 			 */
7748 			if (meta->map_ptr != reg->map_ptr ||
7749 			    meta->map_uid != reg->map_uid) {
7750 				verbose(env,
7751 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7752 					meta->map_uid, reg->map_uid);
7753 				return -EINVAL;
7754 			}
7755 		}
7756 		meta->map_ptr = reg->map_ptr;
7757 		meta->map_uid = reg->map_uid;
7758 		break;
7759 	case ARG_PTR_TO_MAP_KEY:
7760 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
7761 		 * check that [key, key + map->key_size) are within
7762 		 * stack limits and initialized
7763 		 */
7764 		if (!meta->map_ptr) {
7765 			/* in function declaration map_ptr must come before
7766 			 * map_key, so that it's verified and known before
7767 			 * we have to check map_key here. Otherwise it means
7768 			 * that kernel subsystem misconfigured verifier
7769 			 */
7770 			verbose(env, "invalid map_ptr to access map->key\n");
7771 			return -EACCES;
7772 		}
7773 		err = check_helper_mem_access(env, regno,
7774 					      meta->map_ptr->key_size, false,
7775 					      NULL);
7776 		break;
7777 	case ARG_PTR_TO_MAP_VALUE:
7778 		if (type_may_be_null(arg_type) && register_is_null(reg))
7779 			return 0;
7780 
7781 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
7782 		 * check [value, value + map->value_size) validity
7783 		 */
7784 		if (!meta->map_ptr) {
7785 			/* kernel subsystem misconfigured verifier */
7786 			verbose(env, "invalid map_ptr to access map->value\n");
7787 			return -EACCES;
7788 		}
7789 		meta->raw_mode = arg_type & MEM_UNINIT;
7790 		err = check_helper_mem_access(env, regno,
7791 					      meta->map_ptr->value_size, false,
7792 					      meta);
7793 		break;
7794 	case ARG_PTR_TO_PERCPU_BTF_ID:
7795 		if (!reg->btf_id) {
7796 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7797 			return -EACCES;
7798 		}
7799 		meta->ret_btf = reg->btf;
7800 		meta->ret_btf_id = reg->btf_id;
7801 		break;
7802 	case ARG_PTR_TO_SPIN_LOCK:
7803 		if (in_rbtree_lock_required_cb(env)) {
7804 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7805 			return -EACCES;
7806 		}
7807 		if (meta->func_id == BPF_FUNC_spin_lock) {
7808 			err = process_spin_lock(env, regno, true);
7809 			if (err)
7810 				return err;
7811 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
7812 			err = process_spin_lock(env, regno, false);
7813 			if (err)
7814 				return err;
7815 		} else {
7816 			verbose(env, "verifier internal error\n");
7817 			return -EFAULT;
7818 		}
7819 		break;
7820 	case ARG_PTR_TO_TIMER:
7821 		err = process_timer_func(env, regno, meta);
7822 		if (err)
7823 			return err;
7824 		break;
7825 	case ARG_PTR_TO_FUNC:
7826 		meta->subprogno = reg->subprogno;
7827 		break;
7828 	case ARG_PTR_TO_MEM:
7829 		/* The access to this pointer is only checked when we hit the
7830 		 * next is_mem_size argument below.
7831 		 */
7832 		meta->raw_mode = arg_type & MEM_UNINIT;
7833 		if (arg_type & MEM_FIXED_SIZE) {
7834 			err = check_helper_mem_access(env, regno,
7835 						      fn->arg_size[arg], false,
7836 						      meta);
7837 		}
7838 		break;
7839 	case ARG_CONST_SIZE:
7840 		err = check_mem_size_reg(env, reg, regno, false, meta);
7841 		break;
7842 	case ARG_CONST_SIZE_OR_ZERO:
7843 		err = check_mem_size_reg(env, reg, regno, true, meta);
7844 		break;
7845 	case ARG_PTR_TO_DYNPTR:
7846 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
7847 		if (err)
7848 			return err;
7849 		break;
7850 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7851 		if (!tnum_is_const(reg->var_off)) {
7852 			verbose(env, "R%d is not a known constant'\n",
7853 				regno);
7854 			return -EACCES;
7855 		}
7856 		meta->mem_size = reg->var_off.value;
7857 		err = mark_chain_precision(env, regno);
7858 		if (err)
7859 			return err;
7860 		break;
7861 	case ARG_PTR_TO_INT:
7862 	case ARG_PTR_TO_LONG:
7863 	{
7864 		int size = int_ptr_type_to_size(arg_type);
7865 
7866 		err = check_helper_mem_access(env, regno, size, false, meta);
7867 		if (err)
7868 			return err;
7869 		err = check_ptr_alignment(env, reg, 0, size, true);
7870 		break;
7871 	}
7872 	case ARG_PTR_TO_CONST_STR:
7873 	{
7874 		struct bpf_map *map = reg->map_ptr;
7875 		int map_off;
7876 		u64 map_addr;
7877 		char *str_ptr;
7878 
7879 		if (!bpf_map_is_rdonly(map)) {
7880 			verbose(env, "R%d does not point to a readonly map'\n", regno);
7881 			return -EACCES;
7882 		}
7883 
7884 		if (!tnum_is_const(reg->var_off)) {
7885 			verbose(env, "R%d is not a constant address'\n", regno);
7886 			return -EACCES;
7887 		}
7888 
7889 		if (!map->ops->map_direct_value_addr) {
7890 			verbose(env, "no direct value access support for this map type\n");
7891 			return -EACCES;
7892 		}
7893 
7894 		err = check_map_access(env, regno, reg->off,
7895 				       map->value_size - reg->off, false,
7896 				       ACCESS_HELPER);
7897 		if (err)
7898 			return err;
7899 
7900 		map_off = reg->off + reg->var_off.value;
7901 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7902 		if (err) {
7903 			verbose(env, "direct value access on string failed\n");
7904 			return err;
7905 		}
7906 
7907 		str_ptr = (char *)(long)(map_addr);
7908 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7909 			verbose(env, "string is not zero-terminated\n");
7910 			return -EINVAL;
7911 		}
7912 		break;
7913 	}
7914 	case ARG_PTR_TO_KPTR:
7915 		err = process_kptr_func(env, regno, meta);
7916 		if (err)
7917 			return err;
7918 		break;
7919 	}
7920 
7921 	return err;
7922 }
7923 
7924 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7925 {
7926 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
7927 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7928 
7929 	if (func_id != BPF_FUNC_map_update_elem)
7930 		return false;
7931 
7932 	/* It's not possible to get access to a locked struct sock in these
7933 	 * contexts, so updating is safe.
7934 	 */
7935 	switch (type) {
7936 	case BPF_PROG_TYPE_TRACING:
7937 		if (eatype == BPF_TRACE_ITER)
7938 			return true;
7939 		break;
7940 	case BPF_PROG_TYPE_SOCKET_FILTER:
7941 	case BPF_PROG_TYPE_SCHED_CLS:
7942 	case BPF_PROG_TYPE_SCHED_ACT:
7943 	case BPF_PROG_TYPE_XDP:
7944 	case BPF_PROG_TYPE_SK_REUSEPORT:
7945 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
7946 	case BPF_PROG_TYPE_SK_LOOKUP:
7947 		return true;
7948 	default:
7949 		break;
7950 	}
7951 
7952 	verbose(env, "cannot update sockmap in this context\n");
7953 	return false;
7954 }
7955 
7956 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7957 {
7958 	return env->prog->jit_requested &&
7959 	       bpf_jit_supports_subprog_tailcalls();
7960 }
7961 
7962 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7963 					struct bpf_map *map, int func_id)
7964 {
7965 	if (!map)
7966 		return 0;
7967 
7968 	/* We need a two way check, first is from map perspective ... */
7969 	switch (map->map_type) {
7970 	case BPF_MAP_TYPE_PROG_ARRAY:
7971 		if (func_id != BPF_FUNC_tail_call)
7972 			goto error;
7973 		break;
7974 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7975 		if (func_id != BPF_FUNC_perf_event_read &&
7976 		    func_id != BPF_FUNC_perf_event_output &&
7977 		    func_id != BPF_FUNC_skb_output &&
7978 		    func_id != BPF_FUNC_perf_event_read_value &&
7979 		    func_id != BPF_FUNC_xdp_output)
7980 			goto error;
7981 		break;
7982 	case BPF_MAP_TYPE_RINGBUF:
7983 		if (func_id != BPF_FUNC_ringbuf_output &&
7984 		    func_id != BPF_FUNC_ringbuf_reserve &&
7985 		    func_id != BPF_FUNC_ringbuf_query &&
7986 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7987 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7988 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
7989 			goto error;
7990 		break;
7991 	case BPF_MAP_TYPE_USER_RINGBUF:
7992 		if (func_id != BPF_FUNC_user_ringbuf_drain)
7993 			goto error;
7994 		break;
7995 	case BPF_MAP_TYPE_STACK_TRACE:
7996 		if (func_id != BPF_FUNC_get_stackid)
7997 			goto error;
7998 		break;
7999 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8000 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8001 		    func_id != BPF_FUNC_current_task_under_cgroup)
8002 			goto error;
8003 		break;
8004 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8005 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8006 		if (func_id != BPF_FUNC_get_local_storage)
8007 			goto error;
8008 		break;
8009 	case BPF_MAP_TYPE_DEVMAP:
8010 	case BPF_MAP_TYPE_DEVMAP_HASH:
8011 		if (func_id != BPF_FUNC_redirect_map &&
8012 		    func_id != BPF_FUNC_map_lookup_elem)
8013 			goto error;
8014 		break;
8015 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8016 	 * appear.
8017 	 */
8018 	case BPF_MAP_TYPE_CPUMAP:
8019 		if (func_id != BPF_FUNC_redirect_map)
8020 			goto error;
8021 		break;
8022 	case BPF_MAP_TYPE_XSKMAP:
8023 		if (func_id != BPF_FUNC_redirect_map &&
8024 		    func_id != BPF_FUNC_map_lookup_elem)
8025 			goto error;
8026 		break;
8027 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8028 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8029 		if (func_id != BPF_FUNC_map_lookup_elem)
8030 			goto error;
8031 		break;
8032 	case BPF_MAP_TYPE_SOCKMAP:
8033 		if (func_id != BPF_FUNC_sk_redirect_map &&
8034 		    func_id != BPF_FUNC_sock_map_update &&
8035 		    func_id != BPF_FUNC_map_delete_elem &&
8036 		    func_id != BPF_FUNC_msg_redirect_map &&
8037 		    func_id != BPF_FUNC_sk_select_reuseport &&
8038 		    func_id != BPF_FUNC_map_lookup_elem &&
8039 		    !may_update_sockmap(env, func_id))
8040 			goto error;
8041 		break;
8042 	case BPF_MAP_TYPE_SOCKHASH:
8043 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8044 		    func_id != BPF_FUNC_sock_hash_update &&
8045 		    func_id != BPF_FUNC_map_delete_elem &&
8046 		    func_id != BPF_FUNC_msg_redirect_hash &&
8047 		    func_id != BPF_FUNC_sk_select_reuseport &&
8048 		    func_id != BPF_FUNC_map_lookup_elem &&
8049 		    !may_update_sockmap(env, func_id))
8050 			goto error;
8051 		break;
8052 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8053 		if (func_id != BPF_FUNC_sk_select_reuseport)
8054 			goto error;
8055 		break;
8056 	case BPF_MAP_TYPE_QUEUE:
8057 	case BPF_MAP_TYPE_STACK:
8058 		if (func_id != BPF_FUNC_map_peek_elem &&
8059 		    func_id != BPF_FUNC_map_pop_elem &&
8060 		    func_id != BPF_FUNC_map_push_elem)
8061 			goto error;
8062 		break;
8063 	case BPF_MAP_TYPE_SK_STORAGE:
8064 		if (func_id != BPF_FUNC_sk_storage_get &&
8065 		    func_id != BPF_FUNC_sk_storage_delete &&
8066 		    func_id != BPF_FUNC_kptr_xchg)
8067 			goto error;
8068 		break;
8069 	case BPF_MAP_TYPE_INODE_STORAGE:
8070 		if (func_id != BPF_FUNC_inode_storage_get &&
8071 		    func_id != BPF_FUNC_inode_storage_delete &&
8072 		    func_id != BPF_FUNC_kptr_xchg)
8073 			goto error;
8074 		break;
8075 	case BPF_MAP_TYPE_TASK_STORAGE:
8076 		if (func_id != BPF_FUNC_task_storage_get &&
8077 		    func_id != BPF_FUNC_task_storage_delete &&
8078 		    func_id != BPF_FUNC_kptr_xchg)
8079 			goto error;
8080 		break;
8081 	case BPF_MAP_TYPE_CGRP_STORAGE:
8082 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8083 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8084 		    func_id != BPF_FUNC_kptr_xchg)
8085 			goto error;
8086 		break;
8087 	case BPF_MAP_TYPE_BLOOM_FILTER:
8088 		if (func_id != BPF_FUNC_map_peek_elem &&
8089 		    func_id != BPF_FUNC_map_push_elem)
8090 			goto error;
8091 		break;
8092 	default:
8093 		break;
8094 	}
8095 
8096 	/* ... and second from the function itself. */
8097 	switch (func_id) {
8098 	case BPF_FUNC_tail_call:
8099 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8100 			goto error;
8101 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8102 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8103 			return -EINVAL;
8104 		}
8105 		break;
8106 	case BPF_FUNC_perf_event_read:
8107 	case BPF_FUNC_perf_event_output:
8108 	case BPF_FUNC_perf_event_read_value:
8109 	case BPF_FUNC_skb_output:
8110 	case BPF_FUNC_xdp_output:
8111 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8112 			goto error;
8113 		break;
8114 	case BPF_FUNC_ringbuf_output:
8115 	case BPF_FUNC_ringbuf_reserve:
8116 	case BPF_FUNC_ringbuf_query:
8117 	case BPF_FUNC_ringbuf_reserve_dynptr:
8118 	case BPF_FUNC_ringbuf_submit_dynptr:
8119 	case BPF_FUNC_ringbuf_discard_dynptr:
8120 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8121 			goto error;
8122 		break;
8123 	case BPF_FUNC_user_ringbuf_drain:
8124 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8125 			goto error;
8126 		break;
8127 	case BPF_FUNC_get_stackid:
8128 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8129 			goto error;
8130 		break;
8131 	case BPF_FUNC_current_task_under_cgroup:
8132 	case BPF_FUNC_skb_under_cgroup:
8133 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8134 			goto error;
8135 		break;
8136 	case BPF_FUNC_redirect_map:
8137 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8138 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8139 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8140 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8141 			goto error;
8142 		break;
8143 	case BPF_FUNC_sk_redirect_map:
8144 	case BPF_FUNC_msg_redirect_map:
8145 	case BPF_FUNC_sock_map_update:
8146 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8147 			goto error;
8148 		break;
8149 	case BPF_FUNC_sk_redirect_hash:
8150 	case BPF_FUNC_msg_redirect_hash:
8151 	case BPF_FUNC_sock_hash_update:
8152 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8153 			goto error;
8154 		break;
8155 	case BPF_FUNC_get_local_storage:
8156 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8157 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8158 			goto error;
8159 		break;
8160 	case BPF_FUNC_sk_select_reuseport:
8161 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8162 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8163 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8164 			goto error;
8165 		break;
8166 	case BPF_FUNC_map_pop_elem:
8167 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8168 		    map->map_type != BPF_MAP_TYPE_STACK)
8169 			goto error;
8170 		break;
8171 	case BPF_FUNC_map_peek_elem:
8172 	case BPF_FUNC_map_push_elem:
8173 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8174 		    map->map_type != BPF_MAP_TYPE_STACK &&
8175 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8176 			goto error;
8177 		break;
8178 	case BPF_FUNC_map_lookup_percpu_elem:
8179 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8180 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8181 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8182 			goto error;
8183 		break;
8184 	case BPF_FUNC_sk_storage_get:
8185 	case BPF_FUNC_sk_storage_delete:
8186 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8187 			goto error;
8188 		break;
8189 	case BPF_FUNC_inode_storage_get:
8190 	case BPF_FUNC_inode_storage_delete:
8191 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8192 			goto error;
8193 		break;
8194 	case BPF_FUNC_task_storage_get:
8195 	case BPF_FUNC_task_storage_delete:
8196 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8197 			goto error;
8198 		break;
8199 	case BPF_FUNC_cgrp_storage_get:
8200 	case BPF_FUNC_cgrp_storage_delete:
8201 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8202 			goto error;
8203 		break;
8204 	default:
8205 		break;
8206 	}
8207 
8208 	return 0;
8209 error:
8210 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8211 		map->map_type, func_id_name(func_id), func_id);
8212 	return -EINVAL;
8213 }
8214 
8215 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8216 {
8217 	int count = 0;
8218 
8219 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8220 		count++;
8221 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8222 		count++;
8223 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8224 		count++;
8225 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8226 		count++;
8227 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8228 		count++;
8229 
8230 	/* We only support one arg being in raw mode at the moment,
8231 	 * which is sufficient for the helper functions we have
8232 	 * right now.
8233 	 */
8234 	return count <= 1;
8235 }
8236 
8237 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8238 {
8239 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8240 	bool has_size = fn->arg_size[arg] != 0;
8241 	bool is_next_size = false;
8242 
8243 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8244 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8245 
8246 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8247 		return is_next_size;
8248 
8249 	return has_size == is_next_size || is_next_size == is_fixed;
8250 }
8251 
8252 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8253 {
8254 	/* bpf_xxx(..., buf, len) call will access 'len'
8255 	 * bytes from memory 'buf'. Both arg types need
8256 	 * to be paired, so make sure there's no buggy
8257 	 * helper function specification.
8258 	 */
8259 	if (arg_type_is_mem_size(fn->arg1_type) ||
8260 	    check_args_pair_invalid(fn, 0) ||
8261 	    check_args_pair_invalid(fn, 1) ||
8262 	    check_args_pair_invalid(fn, 2) ||
8263 	    check_args_pair_invalid(fn, 3) ||
8264 	    check_args_pair_invalid(fn, 4))
8265 		return false;
8266 
8267 	return true;
8268 }
8269 
8270 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8271 {
8272 	int i;
8273 
8274 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8275 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8276 			return !!fn->arg_btf_id[i];
8277 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8278 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8279 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8280 		    /* arg_btf_id and arg_size are in a union. */
8281 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8282 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8283 			return false;
8284 	}
8285 
8286 	return true;
8287 }
8288 
8289 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8290 {
8291 	return check_raw_mode_ok(fn) &&
8292 	       check_arg_pair_ok(fn) &&
8293 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8294 }
8295 
8296 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8297  * are now invalid, so turn them into unknown SCALAR_VALUE.
8298  *
8299  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8300  * since these slices point to packet data.
8301  */
8302 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8303 {
8304 	struct bpf_func_state *state;
8305 	struct bpf_reg_state *reg;
8306 
8307 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8308 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8309 			mark_reg_invalid(env, reg);
8310 	}));
8311 }
8312 
8313 enum {
8314 	AT_PKT_END = -1,
8315 	BEYOND_PKT_END = -2,
8316 };
8317 
8318 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8319 {
8320 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8321 	struct bpf_reg_state *reg = &state->regs[regn];
8322 
8323 	if (reg->type != PTR_TO_PACKET)
8324 		/* PTR_TO_PACKET_META is not supported yet */
8325 		return;
8326 
8327 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8328 	 * How far beyond pkt_end it goes is unknown.
8329 	 * if (!range_open) it's the case of pkt >= pkt_end
8330 	 * if (range_open) it's the case of pkt > pkt_end
8331 	 * hence this pointer is at least 1 byte bigger than pkt_end
8332 	 */
8333 	if (range_open)
8334 		reg->range = BEYOND_PKT_END;
8335 	else
8336 		reg->range = AT_PKT_END;
8337 }
8338 
8339 /* The pointer with the specified id has released its reference to kernel
8340  * resources. Identify all copies of the same pointer and clear the reference.
8341  */
8342 static int release_reference(struct bpf_verifier_env *env,
8343 			     int ref_obj_id)
8344 {
8345 	struct bpf_func_state *state;
8346 	struct bpf_reg_state *reg;
8347 	int err;
8348 
8349 	err = release_reference_state(cur_func(env), ref_obj_id);
8350 	if (err)
8351 		return err;
8352 
8353 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8354 		if (reg->ref_obj_id == ref_obj_id)
8355 			mark_reg_invalid(env, reg);
8356 	}));
8357 
8358 	return 0;
8359 }
8360 
8361 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8362 {
8363 	struct bpf_func_state *unused;
8364 	struct bpf_reg_state *reg;
8365 
8366 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8367 		if (type_is_non_owning_ref(reg->type))
8368 			mark_reg_invalid(env, reg);
8369 	}));
8370 }
8371 
8372 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8373 				    struct bpf_reg_state *regs)
8374 {
8375 	int i;
8376 
8377 	/* after the call registers r0 - r5 were scratched */
8378 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8379 		mark_reg_not_init(env, regs, caller_saved[i]);
8380 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8381 	}
8382 }
8383 
8384 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8385 				   struct bpf_func_state *caller,
8386 				   struct bpf_func_state *callee,
8387 				   int insn_idx);
8388 
8389 static int set_callee_state(struct bpf_verifier_env *env,
8390 			    struct bpf_func_state *caller,
8391 			    struct bpf_func_state *callee, int insn_idx);
8392 
8393 static bool is_callback_calling_kfunc(u32 btf_id);
8394 
8395 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8396 			     int *insn_idx, int subprog,
8397 			     set_callee_state_fn set_callee_state_cb)
8398 {
8399 	struct bpf_verifier_state *state = env->cur_state;
8400 	struct bpf_func_info_aux *func_info_aux;
8401 	struct bpf_func_state *caller, *callee;
8402 	int err;
8403 	bool is_global = false;
8404 
8405 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8406 		verbose(env, "the call stack of %d frames is too deep\n",
8407 			state->curframe + 2);
8408 		return -E2BIG;
8409 	}
8410 
8411 	caller = state->frame[state->curframe];
8412 	if (state->frame[state->curframe + 1]) {
8413 		verbose(env, "verifier bug. Frame %d already allocated\n",
8414 			state->curframe + 1);
8415 		return -EFAULT;
8416 	}
8417 
8418 	func_info_aux = env->prog->aux->func_info_aux;
8419 	if (func_info_aux)
8420 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
8421 	err = btf_check_subprog_call(env, subprog, caller->regs);
8422 	if (err == -EFAULT)
8423 		return err;
8424 	if (is_global) {
8425 		if (err) {
8426 			verbose(env, "Caller passes invalid args into func#%d\n",
8427 				subprog);
8428 			return err;
8429 		} else {
8430 			if (env->log.level & BPF_LOG_LEVEL)
8431 				verbose(env,
8432 					"Func#%d is global and valid. Skipping.\n",
8433 					subprog);
8434 			clear_caller_saved_regs(env, caller->regs);
8435 
8436 			/* All global functions return a 64-bit SCALAR_VALUE */
8437 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8438 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8439 
8440 			/* continue with next insn after call */
8441 			return 0;
8442 		}
8443 	}
8444 
8445 	/* set_callee_state is used for direct subprog calls, but we are
8446 	 * interested in validating only BPF helpers that can call subprogs as
8447 	 * callbacks
8448 	 */
8449 	if (set_callee_state_cb != set_callee_state) {
8450 		if (bpf_pseudo_kfunc_call(insn) &&
8451 		    !is_callback_calling_kfunc(insn->imm)) {
8452 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8453 				func_id_name(insn->imm), insn->imm);
8454 			return -EFAULT;
8455 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8456 			   !is_callback_calling_function(insn->imm)) { /* helper */
8457 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8458 				func_id_name(insn->imm), insn->imm);
8459 			return -EFAULT;
8460 		}
8461 	}
8462 
8463 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8464 	    insn->src_reg == 0 &&
8465 	    insn->imm == BPF_FUNC_timer_set_callback) {
8466 		struct bpf_verifier_state *async_cb;
8467 
8468 		/* there is no real recursion here. timer callbacks are async */
8469 		env->subprog_info[subprog].is_async_cb = true;
8470 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8471 					 *insn_idx, subprog);
8472 		if (!async_cb)
8473 			return -EFAULT;
8474 		callee = async_cb->frame[0];
8475 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8476 
8477 		/* Convert bpf_timer_set_callback() args into timer callback args */
8478 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8479 		if (err)
8480 			return err;
8481 
8482 		clear_caller_saved_regs(env, caller->regs);
8483 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8484 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8485 		/* continue with next insn after call */
8486 		return 0;
8487 	}
8488 
8489 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8490 	if (!callee)
8491 		return -ENOMEM;
8492 	state->frame[state->curframe + 1] = callee;
8493 
8494 	/* callee cannot access r0, r6 - r9 for reading and has to write
8495 	 * into its own stack before reading from it.
8496 	 * callee can read/write into caller's stack
8497 	 */
8498 	init_func_state(env, callee,
8499 			/* remember the callsite, it will be used by bpf_exit */
8500 			*insn_idx /* callsite */,
8501 			state->curframe + 1 /* frameno within this callchain */,
8502 			subprog /* subprog number within this prog */);
8503 
8504 	/* Transfer references to the callee */
8505 	err = copy_reference_state(callee, caller);
8506 	if (err)
8507 		goto err_out;
8508 
8509 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8510 	if (err)
8511 		goto err_out;
8512 
8513 	clear_caller_saved_regs(env, caller->regs);
8514 
8515 	/* only increment it after check_reg_arg() finished */
8516 	state->curframe++;
8517 
8518 	/* and go analyze first insn of the callee */
8519 	*insn_idx = env->subprog_info[subprog].start - 1;
8520 
8521 	if (env->log.level & BPF_LOG_LEVEL) {
8522 		verbose(env, "caller:\n");
8523 		print_verifier_state(env, caller, true);
8524 		verbose(env, "callee:\n");
8525 		print_verifier_state(env, callee, true);
8526 	}
8527 	return 0;
8528 
8529 err_out:
8530 	free_func_state(callee);
8531 	state->frame[state->curframe + 1] = NULL;
8532 	return err;
8533 }
8534 
8535 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8536 				   struct bpf_func_state *caller,
8537 				   struct bpf_func_state *callee)
8538 {
8539 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8540 	 *      void *callback_ctx, u64 flags);
8541 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8542 	 *      void *callback_ctx);
8543 	 */
8544 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8545 
8546 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8547 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8548 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8549 
8550 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8551 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8552 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8553 
8554 	/* pointer to stack or null */
8555 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8556 
8557 	/* unused */
8558 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8559 	return 0;
8560 }
8561 
8562 static int set_callee_state(struct bpf_verifier_env *env,
8563 			    struct bpf_func_state *caller,
8564 			    struct bpf_func_state *callee, int insn_idx)
8565 {
8566 	int i;
8567 
8568 	/* copy r1 - r5 args that callee can access.  The copy includes parent
8569 	 * pointers, which connects us up to the liveness chain
8570 	 */
8571 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8572 		callee->regs[i] = caller->regs[i];
8573 	return 0;
8574 }
8575 
8576 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8577 			   int *insn_idx)
8578 {
8579 	int subprog, target_insn;
8580 
8581 	target_insn = *insn_idx + insn->imm + 1;
8582 	subprog = find_subprog(env, target_insn);
8583 	if (subprog < 0) {
8584 		verbose(env, "verifier bug. No program starts at insn %d\n",
8585 			target_insn);
8586 		return -EFAULT;
8587 	}
8588 
8589 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8590 }
8591 
8592 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8593 				       struct bpf_func_state *caller,
8594 				       struct bpf_func_state *callee,
8595 				       int insn_idx)
8596 {
8597 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8598 	struct bpf_map *map;
8599 	int err;
8600 
8601 	if (bpf_map_ptr_poisoned(insn_aux)) {
8602 		verbose(env, "tail_call abusing map_ptr\n");
8603 		return -EINVAL;
8604 	}
8605 
8606 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8607 	if (!map->ops->map_set_for_each_callback_args ||
8608 	    !map->ops->map_for_each_callback) {
8609 		verbose(env, "callback function not allowed for map\n");
8610 		return -ENOTSUPP;
8611 	}
8612 
8613 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8614 	if (err)
8615 		return err;
8616 
8617 	callee->in_callback_fn = true;
8618 	callee->callback_ret_range = tnum_range(0, 1);
8619 	return 0;
8620 }
8621 
8622 static int set_loop_callback_state(struct bpf_verifier_env *env,
8623 				   struct bpf_func_state *caller,
8624 				   struct bpf_func_state *callee,
8625 				   int insn_idx)
8626 {
8627 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8628 	 *	    u64 flags);
8629 	 * callback_fn(u32 index, void *callback_ctx);
8630 	 */
8631 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8632 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8633 
8634 	/* unused */
8635 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8636 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8637 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8638 
8639 	callee->in_callback_fn = true;
8640 	callee->callback_ret_range = tnum_range(0, 1);
8641 	return 0;
8642 }
8643 
8644 static int set_timer_callback_state(struct bpf_verifier_env *env,
8645 				    struct bpf_func_state *caller,
8646 				    struct bpf_func_state *callee,
8647 				    int insn_idx)
8648 {
8649 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8650 
8651 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8652 	 * callback_fn(struct bpf_map *map, void *key, void *value);
8653 	 */
8654 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8655 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8656 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
8657 
8658 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8659 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8660 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
8661 
8662 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8663 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8664 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
8665 
8666 	/* unused */
8667 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8668 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8669 	callee->in_async_callback_fn = true;
8670 	callee->callback_ret_range = tnum_range(0, 1);
8671 	return 0;
8672 }
8673 
8674 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8675 				       struct bpf_func_state *caller,
8676 				       struct bpf_func_state *callee,
8677 				       int insn_idx)
8678 {
8679 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8680 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8681 	 * (callback_fn)(struct task_struct *task,
8682 	 *               struct vm_area_struct *vma, void *callback_ctx);
8683 	 */
8684 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8685 
8686 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8687 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8688 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8689 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8690 
8691 	/* pointer to stack or null */
8692 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8693 
8694 	/* unused */
8695 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8696 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8697 	callee->in_callback_fn = true;
8698 	callee->callback_ret_range = tnum_range(0, 1);
8699 	return 0;
8700 }
8701 
8702 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8703 					   struct bpf_func_state *caller,
8704 					   struct bpf_func_state *callee,
8705 					   int insn_idx)
8706 {
8707 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8708 	 *			  callback_ctx, u64 flags);
8709 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8710 	 */
8711 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8712 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8713 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8714 
8715 	/* unused */
8716 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8717 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8718 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8719 
8720 	callee->in_callback_fn = true;
8721 	callee->callback_ret_range = tnum_range(0, 1);
8722 	return 0;
8723 }
8724 
8725 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8726 					 struct bpf_func_state *caller,
8727 					 struct bpf_func_state *callee,
8728 					 int insn_idx)
8729 {
8730 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
8731 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8732 	 *
8733 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
8734 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8735 	 * by this point, so look at 'root'
8736 	 */
8737 	struct btf_field *field;
8738 
8739 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8740 				      BPF_RB_ROOT);
8741 	if (!field || !field->graph_root.value_btf_id)
8742 		return -EFAULT;
8743 
8744 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8745 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8746 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8747 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8748 
8749 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8750 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8751 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8752 	callee->in_callback_fn = true;
8753 	callee->callback_ret_range = tnum_range(0, 1);
8754 	return 0;
8755 }
8756 
8757 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8758 
8759 /* Are we currently verifying the callback for a rbtree helper that must
8760  * be called with lock held? If so, no need to complain about unreleased
8761  * lock
8762  */
8763 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8764 {
8765 	struct bpf_verifier_state *state = env->cur_state;
8766 	struct bpf_insn *insn = env->prog->insnsi;
8767 	struct bpf_func_state *callee;
8768 	int kfunc_btf_id;
8769 
8770 	if (!state->curframe)
8771 		return false;
8772 
8773 	callee = state->frame[state->curframe];
8774 
8775 	if (!callee->in_callback_fn)
8776 		return false;
8777 
8778 	kfunc_btf_id = insn[callee->callsite].imm;
8779 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8780 }
8781 
8782 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8783 {
8784 	struct bpf_verifier_state *state = env->cur_state;
8785 	struct bpf_func_state *caller, *callee;
8786 	struct bpf_reg_state *r0;
8787 	int err;
8788 
8789 	callee = state->frame[state->curframe];
8790 	r0 = &callee->regs[BPF_REG_0];
8791 	if (r0->type == PTR_TO_STACK) {
8792 		/* technically it's ok to return caller's stack pointer
8793 		 * (or caller's caller's pointer) back to the caller,
8794 		 * since these pointers are valid. Only current stack
8795 		 * pointer will be invalid as soon as function exits,
8796 		 * but let's be conservative
8797 		 */
8798 		verbose(env, "cannot return stack pointer to the caller\n");
8799 		return -EINVAL;
8800 	}
8801 
8802 	caller = state->frame[state->curframe - 1];
8803 	if (callee->in_callback_fn) {
8804 		/* enforce R0 return value range [0, 1]. */
8805 		struct tnum range = callee->callback_ret_range;
8806 
8807 		if (r0->type != SCALAR_VALUE) {
8808 			verbose(env, "R0 not a scalar value\n");
8809 			return -EACCES;
8810 		}
8811 		if (!tnum_in(range, r0->var_off)) {
8812 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8813 			return -EINVAL;
8814 		}
8815 	} else {
8816 		/* return to the caller whatever r0 had in the callee */
8817 		caller->regs[BPF_REG_0] = *r0;
8818 	}
8819 
8820 	/* callback_fn frame should have released its own additions to parent's
8821 	 * reference state at this point, or check_reference_leak would
8822 	 * complain, hence it must be the same as the caller. There is no need
8823 	 * to copy it back.
8824 	 */
8825 	if (!callee->in_callback_fn) {
8826 		/* Transfer references to the caller */
8827 		err = copy_reference_state(caller, callee);
8828 		if (err)
8829 			return err;
8830 	}
8831 
8832 	*insn_idx = callee->callsite + 1;
8833 	if (env->log.level & BPF_LOG_LEVEL) {
8834 		verbose(env, "returning from callee:\n");
8835 		print_verifier_state(env, callee, true);
8836 		verbose(env, "to caller at %d:\n", *insn_idx);
8837 		print_verifier_state(env, caller, true);
8838 	}
8839 	/* clear everything in the callee */
8840 	free_func_state(callee);
8841 	state->frame[state->curframe--] = NULL;
8842 	return 0;
8843 }
8844 
8845 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8846 				   int func_id,
8847 				   struct bpf_call_arg_meta *meta)
8848 {
8849 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8850 
8851 	if (ret_type != RET_INTEGER ||
8852 	    (func_id != BPF_FUNC_get_stack &&
8853 	     func_id != BPF_FUNC_get_task_stack &&
8854 	     func_id != BPF_FUNC_probe_read_str &&
8855 	     func_id != BPF_FUNC_probe_read_kernel_str &&
8856 	     func_id != BPF_FUNC_probe_read_user_str))
8857 		return;
8858 
8859 	ret_reg->smax_value = meta->msize_max_value;
8860 	ret_reg->s32_max_value = meta->msize_max_value;
8861 	ret_reg->smin_value = -MAX_ERRNO;
8862 	ret_reg->s32_min_value = -MAX_ERRNO;
8863 	reg_bounds_sync(ret_reg);
8864 }
8865 
8866 static int
8867 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8868 		int func_id, int insn_idx)
8869 {
8870 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8871 	struct bpf_map *map = meta->map_ptr;
8872 
8873 	if (func_id != BPF_FUNC_tail_call &&
8874 	    func_id != BPF_FUNC_map_lookup_elem &&
8875 	    func_id != BPF_FUNC_map_update_elem &&
8876 	    func_id != BPF_FUNC_map_delete_elem &&
8877 	    func_id != BPF_FUNC_map_push_elem &&
8878 	    func_id != BPF_FUNC_map_pop_elem &&
8879 	    func_id != BPF_FUNC_map_peek_elem &&
8880 	    func_id != BPF_FUNC_for_each_map_elem &&
8881 	    func_id != BPF_FUNC_redirect_map &&
8882 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
8883 		return 0;
8884 
8885 	if (map == NULL) {
8886 		verbose(env, "kernel subsystem misconfigured verifier\n");
8887 		return -EINVAL;
8888 	}
8889 
8890 	/* In case of read-only, some additional restrictions
8891 	 * need to be applied in order to prevent altering the
8892 	 * state of the map from program side.
8893 	 */
8894 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8895 	    (func_id == BPF_FUNC_map_delete_elem ||
8896 	     func_id == BPF_FUNC_map_update_elem ||
8897 	     func_id == BPF_FUNC_map_push_elem ||
8898 	     func_id == BPF_FUNC_map_pop_elem)) {
8899 		verbose(env, "write into map forbidden\n");
8900 		return -EACCES;
8901 	}
8902 
8903 	if (!BPF_MAP_PTR(aux->map_ptr_state))
8904 		bpf_map_ptr_store(aux, meta->map_ptr,
8905 				  !meta->map_ptr->bypass_spec_v1);
8906 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8907 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8908 				  !meta->map_ptr->bypass_spec_v1);
8909 	return 0;
8910 }
8911 
8912 static int
8913 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8914 		int func_id, int insn_idx)
8915 {
8916 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8917 	struct bpf_reg_state *regs = cur_regs(env), *reg;
8918 	struct bpf_map *map = meta->map_ptr;
8919 	u64 val, max;
8920 	int err;
8921 
8922 	if (func_id != BPF_FUNC_tail_call)
8923 		return 0;
8924 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8925 		verbose(env, "kernel subsystem misconfigured verifier\n");
8926 		return -EINVAL;
8927 	}
8928 
8929 	reg = &regs[BPF_REG_3];
8930 	val = reg->var_off.value;
8931 	max = map->max_entries;
8932 
8933 	if (!(register_is_const(reg) && val < max)) {
8934 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8935 		return 0;
8936 	}
8937 
8938 	err = mark_chain_precision(env, BPF_REG_3);
8939 	if (err)
8940 		return err;
8941 	if (bpf_map_key_unseen(aux))
8942 		bpf_map_key_store(aux, val);
8943 	else if (!bpf_map_key_poisoned(aux) &&
8944 		  bpf_map_key_immediate(aux) != val)
8945 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8946 	return 0;
8947 }
8948 
8949 static int check_reference_leak(struct bpf_verifier_env *env)
8950 {
8951 	struct bpf_func_state *state = cur_func(env);
8952 	bool refs_lingering = false;
8953 	int i;
8954 
8955 	if (state->frameno && !state->in_callback_fn)
8956 		return 0;
8957 
8958 	for (i = 0; i < state->acquired_refs; i++) {
8959 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8960 			continue;
8961 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8962 			state->refs[i].id, state->refs[i].insn_idx);
8963 		refs_lingering = true;
8964 	}
8965 	return refs_lingering ? -EINVAL : 0;
8966 }
8967 
8968 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8969 				   struct bpf_reg_state *regs)
8970 {
8971 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8972 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8973 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
8974 	struct bpf_bprintf_data data = {};
8975 	int err, fmt_map_off, num_args;
8976 	u64 fmt_addr;
8977 	char *fmt;
8978 
8979 	/* data must be an array of u64 */
8980 	if (data_len_reg->var_off.value % 8)
8981 		return -EINVAL;
8982 	num_args = data_len_reg->var_off.value / 8;
8983 
8984 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8985 	 * and map_direct_value_addr is set.
8986 	 */
8987 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8988 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8989 						  fmt_map_off);
8990 	if (err) {
8991 		verbose(env, "verifier bug\n");
8992 		return -EFAULT;
8993 	}
8994 	fmt = (char *)(long)fmt_addr + fmt_map_off;
8995 
8996 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8997 	 * can focus on validating the format specifiers.
8998 	 */
8999 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9000 	if (err < 0)
9001 		verbose(env, "Invalid format string\n");
9002 
9003 	return err;
9004 }
9005 
9006 static int check_get_func_ip(struct bpf_verifier_env *env)
9007 {
9008 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9009 	int func_id = BPF_FUNC_get_func_ip;
9010 
9011 	if (type == BPF_PROG_TYPE_TRACING) {
9012 		if (!bpf_prog_has_trampoline(env->prog)) {
9013 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9014 				func_id_name(func_id), func_id);
9015 			return -ENOTSUPP;
9016 		}
9017 		return 0;
9018 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9019 		return 0;
9020 	}
9021 
9022 	verbose(env, "func %s#%d not supported for program type %d\n",
9023 		func_id_name(func_id), func_id, type);
9024 	return -ENOTSUPP;
9025 }
9026 
9027 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9028 {
9029 	return &env->insn_aux_data[env->insn_idx];
9030 }
9031 
9032 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9033 {
9034 	struct bpf_reg_state *regs = cur_regs(env);
9035 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9036 	bool reg_is_null = register_is_null(reg);
9037 
9038 	if (reg_is_null)
9039 		mark_chain_precision(env, BPF_REG_4);
9040 
9041 	return reg_is_null;
9042 }
9043 
9044 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9045 {
9046 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9047 
9048 	if (!state->initialized) {
9049 		state->initialized = 1;
9050 		state->fit_for_inline = loop_flag_is_zero(env);
9051 		state->callback_subprogno = subprogno;
9052 		return;
9053 	}
9054 
9055 	if (!state->fit_for_inline)
9056 		return;
9057 
9058 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9059 				 state->callback_subprogno == subprogno);
9060 }
9061 
9062 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9063 			     int *insn_idx_p)
9064 {
9065 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9066 	const struct bpf_func_proto *fn = NULL;
9067 	enum bpf_return_type ret_type;
9068 	enum bpf_type_flag ret_flag;
9069 	struct bpf_reg_state *regs;
9070 	struct bpf_call_arg_meta meta;
9071 	int insn_idx = *insn_idx_p;
9072 	bool changes_data;
9073 	int i, err, func_id;
9074 
9075 	/* find function prototype */
9076 	func_id = insn->imm;
9077 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9078 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9079 			func_id);
9080 		return -EINVAL;
9081 	}
9082 
9083 	if (env->ops->get_func_proto)
9084 		fn = env->ops->get_func_proto(func_id, env->prog);
9085 	if (!fn) {
9086 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9087 			func_id);
9088 		return -EINVAL;
9089 	}
9090 
9091 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9092 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9093 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9094 		return -EINVAL;
9095 	}
9096 
9097 	if (fn->allowed && !fn->allowed(env->prog)) {
9098 		verbose(env, "helper call is not allowed in probe\n");
9099 		return -EINVAL;
9100 	}
9101 
9102 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9103 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9104 		return -EINVAL;
9105 	}
9106 
9107 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9108 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9109 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9110 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9111 			func_id_name(func_id), func_id);
9112 		return -EINVAL;
9113 	}
9114 
9115 	memset(&meta, 0, sizeof(meta));
9116 	meta.pkt_access = fn->pkt_access;
9117 
9118 	err = check_func_proto(fn, func_id);
9119 	if (err) {
9120 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9121 			func_id_name(func_id), func_id);
9122 		return err;
9123 	}
9124 
9125 	if (env->cur_state->active_rcu_lock) {
9126 		if (fn->might_sleep) {
9127 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9128 				func_id_name(func_id), func_id);
9129 			return -EINVAL;
9130 		}
9131 
9132 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9133 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9134 	}
9135 
9136 	meta.func_id = func_id;
9137 	/* check args */
9138 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9139 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9140 		if (err)
9141 			return err;
9142 	}
9143 
9144 	err = record_func_map(env, &meta, func_id, insn_idx);
9145 	if (err)
9146 		return err;
9147 
9148 	err = record_func_key(env, &meta, func_id, insn_idx);
9149 	if (err)
9150 		return err;
9151 
9152 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9153 	 * is inferred from register state.
9154 	 */
9155 	for (i = 0; i < meta.access_size; i++) {
9156 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9157 				       BPF_WRITE, -1, false);
9158 		if (err)
9159 			return err;
9160 	}
9161 
9162 	regs = cur_regs(env);
9163 
9164 	if (meta.release_regno) {
9165 		err = -EINVAL;
9166 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9167 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9168 		 * is safe to do directly.
9169 		 */
9170 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9171 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9172 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9173 				return -EFAULT;
9174 			}
9175 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9176 		} else if (meta.ref_obj_id) {
9177 			err = release_reference(env, meta.ref_obj_id);
9178 		} else if (register_is_null(&regs[meta.release_regno])) {
9179 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9180 			 * released is NULL, which must be > R0.
9181 			 */
9182 			err = 0;
9183 		}
9184 		if (err) {
9185 			verbose(env, "func %s#%d reference has not been acquired before\n",
9186 				func_id_name(func_id), func_id);
9187 			return err;
9188 		}
9189 	}
9190 
9191 	switch (func_id) {
9192 	case BPF_FUNC_tail_call:
9193 		err = check_reference_leak(env);
9194 		if (err) {
9195 			verbose(env, "tail_call would lead to reference leak\n");
9196 			return err;
9197 		}
9198 		break;
9199 	case BPF_FUNC_get_local_storage:
9200 		/* check that flags argument in get_local_storage(map, flags) is 0,
9201 		 * this is required because get_local_storage() can't return an error.
9202 		 */
9203 		if (!register_is_null(&regs[BPF_REG_2])) {
9204 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9205 			return -EINVAL;
9206 		}
9207 		break;
9208 	case BPF_FUNC_for_each_map_elem:
9209 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9210 					set_map_elem_callback_state);
9211 		break;
9212 	case BPF_FUNC_timer_set_callback:
9213 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9214 					set_timer_callback_state);
9215 		break;
9216 	case BPF_FUNC_find_vma:
9217 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9218 					set_find_vma_callback_state);
9219 		break;
9220 	case BPF_FUNC_snprintf:
9221 		err = check_bpf_snprintf_call(env, regs);
9222 		break;
9223 	case BPF_FUNC_loop:
9224 		update_loop_inline_state(env, meta.subprogno);
9225 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9226 					set_loop_callback_state);
9227 		break;
9228 	case BPF_FUNC_dynptr_from_mem:
9229 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9230 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9231 				reg_type_str(env, regs[BPF_REG_1].type));
9232 			return -EACCES;
9233 		}
9234 		break;
9235 	case BPF_FUNC_set_retval:
9236 		if (prog_type == BPF_PROG_TYPE_LSM &&
9237 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9238 			if (!env->prog->aux->attach_func_proto->type) {
9239 				/* Make sure programs that attach to void
9240 				 * hooks don't try to modify return value.
9241 				 */
9242 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9243 				return -EINVAL;
9244 			}
9245 		}
9246 		break;
9247 	case BPF_FUNC_dynptr_data:
9248 	{
9249 		struct bpf_reg_state *reg;
9250 		int id, ref_obj_id;
9251 
9252 		reg = get_dynptr_arg_reg(env, fn, regs);
9253 		if (!reg)
9254 			return -EFAULT;
9255 
9256 
9257 		if (meta.dynptr_id) {
9258 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9259 			return -EFAULT;
9260 		}
9261 		if (meta.ref_obj_id) {
9262 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9263 			return -EFAULT;
9264 		}
9265 
9266 		id = dynptr_id(env, reg);
9267 		if (id < 0) {
9268 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9269 			return id;
9270 		}
9271 
9272 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9273 		if (ref_obj_id < 0) {
9274 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9275 			return ref_obj_id;
9276 		}
9277 
9278 		meta.dynptr_id = id;
9279 		meta.ref_obj_id = ref_obj_id;
9280 
9281 		break;
9282 	}
9283 	case BPF_FUNC_dynptr_write:
9284 	{
9285 		enum bpf_dynptr_type dynptr_type;
9286 		struct bpf_reg_state *reg;
9287 
9288 		reg = get_dynptr_arg_reg(env, fn, regs);
9289 		if (!reg)
9290 			return -EFAULT;
9291 
9292 		dynptr_type = dynptr_get_type(env, reg);
9293 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9294 			return -EFAULT;
9295 
9296 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9297 			/* this will trigger clear_all_pkt_pointers(), which will
9298 			 * invalidate all dynptr slices associated with the skb
9299 			 */
9300 			changes_data = true;
9301 
9302 		break;
9303 	}
9304 	case BPF_FUNC_user_ringbuf_drain:
9305 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9306 					set_user_ringbuf_callback_state);
9307 		break;
9308 	}
9309 
9310 	if (err)
9311 		return err;
9312 
9313 	/* reset caller saved regs */
9314 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9315 		mark_reg_not_init(env, regs, caller_saved[i]);
9316 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9317 	}
9318 
9319 	/* helper call returns 64-bit value. */
9320 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9321 
9322 	/* update return register (already marked as written above) */
9323 	ret_type = fn->ret_type;
9324 	ret_flag = type_flag(ret_type);
9325 
9326 	switch (base_type(ret_type)) {
9327 	case RET_INTEGER:
9328 		/* sets type to SCALAR_VALUE */
9329 		mark_reg_unknown(env, regs, BPF_REG_0);
9330 		break;
9331 	case RET_VOID:
9332 		regs[BPF_REG_0].type = NOT_INIT;
9333 		break;
9334 	case RET_PTR_TO_MAP_VALUE:
9335 		/* There is no offset yet applied, variable or fixed */
9336 		mark_reg_known_zero(env, regs, BPF_REG_0);
9337 		/* remember map_ptr, so that check_map_access()
9338 		 * can check 'value_size' boundary of memory access
9339 		 * to map element returned from bpf_map_lookup_elem()
9340 		 */
9341 		if (meta.map_ptr == NULL) {
9342 			verbose(env,
9343 				"kernel subsystem misconfigured verifier\n");
9344 			return -EINVAL;
9345 		}
9346 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9347 		regs[BPF_REG_0].map_uid = meta.map_uid;
9348 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9349 		if (!type_may_be_null(ret_type) &&
9350 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9351 			regs[BPF_REG_0].id = ++env->id_gen;
9352 		}
9353 		break;
9354 	case RET_PTR_TO_SOCKET:
9355 		mark_reg_known_zero(env, regs, BPF_REG_0);
9356 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9357 		break;
9358 	case RET_PTR_TO_SOCK_COMMON:
9359 		mark_reg_known_zero(env, regs, BPF_REG_0);
9360 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9361 		break;
9362 	case RET_PTR_TO_TCP_SOCK:
9363 		mark_reg_known_zero(env, regs, BPF_REG_0);
9364 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9365 		break;
9366 	case RET_PTR_TO_MEM:
9367 		mark_reg_known_zero(env, regs, BPF_REG_0);
9368 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9369 		regs[BPF_REG_0].mem_size = meta.mem_size;
9370 		break;
9371 	case RET_PTR_TO_MEM_OR_BTF_ID:
9372 	{
9373 		const struct btf_type *t;
9374 
9375 		mark_reg_known_zero(env, regs, BPF_REG_0);
9376 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9377 		if (!btf_type_is_struct(t)) {
9378 			u32 tsize;
9379 			const struct btf_type *ret;
9380 			const char *tname;
9381 
9382 			/* resolve the type size of ksym. */
9383 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9384 			if (IS_ERR(ret)) {
9385 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9386 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9387 					tname, PTR_ERR(ret));
9388 				return -EINVAL;
9389 			}
9390 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9391 			regs[BPF_REG_0].mem_size = tsize;
9392 		} else {
9393 			/* MEM_RDONLY may be carried from ret_flag, but it
9394 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9395 			 * it will confuse the check of PTR_TO_BTF_ID in
9396 			 * check_mem_access().
9397 			 */
9398 			ret_flag &= ~MEM_RDONLY;
9399 
9400 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9401 			regs[BPF_REG_0].btf = meta.ret_btf;
9402 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9403 		}
9404 		break;
9405 	}
9406 	case RET_PTR_TO_BTF_ID:
9407 	{
9408 		struct btf *ret_btf;
9409 		int ret_btf_id;
9410 
9411 		mark_reg_known_zero(env, regs, BPF_REG_0);
9412 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9413 		if (func_id == BPF_FUNC_kptr_xchg) {
9414 			ret_btf = meta.kptr_field->kptr.btf;
9415 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9416 			if (!btf_is_kernel(ret_btf))
9417 				regs[BPF_REG_0].type |= MEM_ALLOC;
9418 		} else {
9419 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9420 				verbose(env, "verifier internal error:");
9421 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9422 					func_id_name(func_id));
9423 				return -EINVAL;
9424 			}
9425 			ret_btf = btf_vmlinux;
9426 			ret_btf_id = *fn->ret_btf_id;
9427 		}
9428 		if (ret_btf_id == 0) {
9429 			verbose(env, "invalid return type %u of func %s#%d\n",
9430 				base_type(ret_type), func_id_name(func_id),
9431 				func_id);
9432 			return -EINVAL;
9433 		}
9434 		regs[BPF_REG_0].btf = ret_btf;
9435 		regs[BPF_REG_0].btf_id = ret_btf_id;
9436 		break;
9437 	}
9438 	default:
9439 		verbose(env, "unknown return type %u of func %s#%d\n",
9440 			base_type(ret_type), func_id_name(func_id), func_id);
9441 		return -EINVAL;
9442 	}
9443 
9444 	if (type_may_be_null(regs[BPF_REG_0].type))
9445 		regs[BPF_REG_0].id = ++env->id_gen;
9446 
9447 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9448 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9449 			func_id_name(func_id), func_id);
9450 		return -EFAULT;
9451 	}
9452 
9453 	if (is_dynptr_ref_function(func_id))
9454 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9455 
9456 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9457 		/* For release_reference() */
9458 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9459 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9460 		int id = acquire_reference_state(env, insn_idx);
9461 
9462 		if (id < 0)
9463 			return id;
9464 		/* For mark_ptr_or_null_reg() */
9465 		regs[BPF_REG_0].id = id;
9466 		/* For release_reference() */
9467 		regs[BPF_REG_0].ref_obj_id = id;
9468 	}
9469 
9470 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9471 
9472 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9473 	if (err)
9474 		return err;
9475 
9476 	if ((func_id == BPF_FUNC_get_stack ||
9477 	     func_id == BPF_FUNC_get_task_stack) &&
9478 	    !env->prog->has_callchain_buf) {
9479 		const char *err_str;
9480 
9481 #ifdef CONFIG_PERF_EVENTS
9482 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9483 		err_str = "cannot get callchain buffer for func %s#%d\n";
9484 #else
9485 		err = -ENOTSUPP;
9486 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9487 #endif
9488 		if (err) {
9489 			verbose(env, err_str, func_id_name(func_id), func_id);
9490 			return err;
9491 		}
9492 
9493 		env->prog->has_callchain_buf = true;
9494 	}
9495 
9496 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9497 		env->prog->call_get_stack = true;
9498 
9499 	if (func_id == BPF_FUNC_get_func_ip) {
9500 		if (check_get_func_ip(env))
9501 			return -ENOTSUPP;
9502 		env->prog->call_get_func_ip = true;
9503 	}
9504 
9505 	if (changes_data)
9506 		clear_all_pkt_pointers(env);
9507 	return 0;
9508 }
9509 
9510 /* mark_btf_func_reg_size() is used when the reg size is determined by
9511  * the BTF func_proto's return value size and argument.
9512  */
9513 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9514 				   size_t reg_size)
9515 {
9516 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9517 
9518 	if (regno == BPF_REG_0) {
9519 		/* Function return value */
9520 		reg->live |= REG_LIVE_WRITTEN;
9521 		reg->subreg_def = reg_size == sizeof(u64) ?
9522 			DEF_NOT_SUBREG : env->insn_idx + 1;
9523 	} else {
9524 		/* Function argument */
9525 		if (reg_size == sizeof(u64)) {
9526 			mark_insn_zext(env, reg);
9527 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9528 		} else {
9529 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9530 		}
9531 	}
9532 }
9533 
9534 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9535 {
9536 	return meta->kfunc_flags & KF_ACQUIRE;
9537 }
9538 
9539 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9540 {
9541 	return meta->kfunc_flags & KF_RET_NULL;
9542 }
9543 
9544 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9545 {
9546 	return meta->kfunc_flags & KF_RELEASE;
9547 }
9548 
9549 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9550 {
9551 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9552 }
9553 
9554 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9555 {
9556 	return meta->kfunc_flags & KF_SLEEPABLE;
9557 }
9558 
9559 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9560 {
9561 	return meta->kfunc_flags & KF_DESTRUCTIVE;
9562 }
9563 
9564 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9565 {
9566 	return meta->kfunc_flags & KF_RCU;
9567 }
9568 
9569 static bool __kfunc_param_match_suffix(const struct btf *btf,
9570 				       const struct btf_param *arg,
9571 				       const char *suffix)
9572 {
9573 	int suffix_len = strlen(suffix), len;
9574 	const char *param_name;
9575 
9576 	/* In the future, this can be ported to use BTF tagging */
9577 	param_name = btf_name_by_offset(btf, arg->name_off);
9578 	if (str_is_empty(param_name))
9579 		return false;
9580 	len = strlen(param_name);
9581 	if (len < suffix_len)
9582 		return false;
9583 	param_name += len - suffix_len;
9584 	return !strncmp(param_name, suffix, suffix_len);
9585 }
9586 
9587 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9588 				  const struct btf_param *arg,
9589 				  const struct bpf_reg_state *reg)
9590 {
9591 	const struct btf_type *t;
9592 
9593 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9594 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9595 		return false;
9596 
9597 	return __kfunc_param_match_suffix(btf, arg, "__sz");
9598 }
9599 
9600 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9601 					const struct btf_param *arg,
9602 					const struct bpf_reg_state *reg)
9603 {
9604 	const struct btf_type *t;
9605 
9606 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9607 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9608 		return false;
9609 
9610 	return __kfunc_param_match_suffix(btf, arg, "__szk");
9611 }
9612 
9613 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9614 {
9615 	return __kfunc_param_match_suffix(btf, arg, "__k");
9616 }
9617 
9618 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9619 {
9620 	return __kfunc_param_match_suffix(btf, arg, "__ign");
9621 }
9622 
9623 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9624 {
9625 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
9626 }
9627 
9628 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9629 {
9630 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
9631 }
9632 
9633 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9634 {
9635 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9636 }
9637 
9638 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9639 					  const struct btf_param *arg,
9640 					  const char *name)
9641 {
9642 	int len, target_len = strlen(name);
9643 	const char *param_name;
9644 
9645 	param_name = btf_name_by_offset(btf, arg->name_off);
9646 	if (str_is_empty(param_name))
9647 		return false;
9648 	len = strlen(param_name);
9649 	if (len != target_len)
9650 		return false;
9651 	if (strcmp(param_name, name))
9652 		return false;
9653 
9654 	return true;
9655 }
9656 
9657 enum {
9658 	KF_ARG_DYNPTR_ID,
9659 	KF_ARG_LIST_HEAD_ID,
9660 	KF_ARG_LIST_NODE_ID,
9661 	KF_ARG_RB_ROOT_ID,
9662 	KF_ARG_RB_NODE_ID,
9663 };
9664 
9665 BTF_ID_LIST(kf_arg_btf_ids)
9666 BTF_ID(struct, bpf_dynptr_kern)
9667 BTF_ID(struct, bpf_list_head)
9668 BTF_ID(struct, bpf_list_node)
9669 BTF_ID(struct, bpf_rb_root)
9670 BTF_ID(struct, bpf_rb_node)
9671 
9672 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9673 				    const struct btf_param *arg, int type)
9674 {
9675 	const struct btf_type *t;
9676 	u32 res_id;
9677 
9678 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9679 	if (!t)
9680 		return false;
9681 	if (!btf_type_is_ptr(t))
9682 		return false;
9683 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
9684 	if (!t)
9685 		return false;
9686 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9687 }
9688 
9689 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9690 {
9691 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9692 }
9693 
9694 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9695 {
9696 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9697 }
9698 
9699 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9700 {
9701 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9702 }
9703 
9704 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9705 {
9706 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9707 }
9708 
9709 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9710 {
9711 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9712 }
9713 
9714 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9715 				  const struct btf_param *arg)
9716 {
9717 	const struct btf_type *t;
9718 
9719 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9720 	if (!t)
9721 		return false;
9722 
9723 	return true;
9724 }
9725 
9726 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9727 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9728 					const struct btf *btf,
9729 					const struct btf_type *t, int rec)
9730 {
9731 	const struct btf_type *member_type;
9732 	const struct btf_member *member;
9733 	u32 i;
9734 
9735 	if (!btf_type_is_struct(t))
9736 		return false;
9737 
9738 	for_each_member(i, t, member) {
9739 		const struct btf_array *array;
9740 
9741 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9742 		if (btf_type_is_struct(member_type)) {
9743 			if (rec >= 3) {
9744 				verbose(env, "max struct nesting depth exceeded\n");
9745 				return false;
9746 			}
9747 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9748 				return false;
9749 			continue;
9750 		}
9751 		if (btf_type_is_array(member_type)) {
9752 			array = btf_array(member_type);
9753 			if (!array->nelems)
9754 				return false;
9755 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9756 			if (!btf_type_is_scalar(member_type))
9757 				return false;
9758 			continue;
9759 		}
9760 		if (!btf_type_is_scalar(member_type))
9761 			return false;
9762 	}
9763 	return true;
9764 }
9765 
9766 
9767 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9768 #ifdef CONFIG_NET
9769 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9770 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9771 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9772 #endif
9773 };
9774 
9775 enum kfunc_ptr_arg_type {
9776 	KF_ARG_PTR_TO_CTX,
9777 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
9778 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
9779 	KF_ARG_PTR_TO_DYNPTR,
9780 	KF_ARG_PTR_TO_ITER,
9781 	KF_ARG_PTR_TO_LIST_HEAD,
9782 	KF_ARG_PTR_TO_LIST_NODE,
9783 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
9784 	KF_ARG_PTR_TO_MEM,
9785 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
9786 	KF_ARG_PTR_TO_CALLBACK,
9787 	KF_ARG_PTR_TO_RB_ROOT,
9788 	KF_ARG_PTR_TO_RB_NODE,
9789 };
9790 
9791 enum special_kfunc_type {
9792 	KF_bpf_obj_new_impl,
9793 	KF_bpf_obj_drop_impl,
9794 	KF_bpf_refcount_acquire_impl,
9795 	KF_bpf_list_push_front_impl,
9796 	KF_bpf_list_push_back_impl,
9797 	KF_bpf_list_pop_front,
9798 	KF_bpf_list_pop_back,
9799 	KF_bpf_cast_to_kern_ctx,
9800 	KF_bpf_rdonly_cast,
9801 	KF_bpf_rcu_read_lock,
9802 	KF_bpf_rcu_read_unlock,
9803 	KF_bpf_rbtree_remove,
9804 	KF_bpf_rbtree_add_impl,
9805 	KF_bpf_rbtree_first,
9806 	KF_bpf_dynptr_from_skb,
9807 	KF_bpf_dynptr_from_xdp,
9808 	KF_bpf_dynptr_slice,
9809 	KF_bpf_dynptr_slice_rdwr,
9810 	KF_bpf_dynptr_clone,
9811 };
9812 
9813 BTF_SET_START(special_kfunc_set)
9814 BTF_ID(func, bpf_obj_new_impl)
9815 BTF_ID(func, bpf_obj_drop_impl)
9816 BTF_ID(func, bpf_refcount_acquire_impl)
9817 BTF_ID(func, bpf_list_push_front_impl)
9818 BTF_ID(func, bpf_list_push_back_impl)
9819 BTF_ID(func, bpf_list_pop_front)
9820 BTF_ID(func, bpf_list_pop_back)
9821 BTF_ID(func, bpf_cast_to_kern_ctx)
9822 BTF_ID(func, bpf_rdonly_cast)
9823 BTF_ID(func, bpf_rbtree_remove)
9824 BTF_ID(func, bpf_rbtree_add_impl)
9825 BTF_ID(func, bpf_rbtree_first)
9826 BTF_ID(func, bpf_dynptr_from_skb)
9827 BTF_ID(func, bpf_dynptr_from_xdp)
9828 BTF_ID(func, bpf_dynptr_slice)
9829 BTF_ID(func, bpf_dynptr_slice_rdwr)
9830 BTF_ID(func, bpf_dynptr_clone)
9831 BTF_SET_END(special_kfunc_set)
9832 
9833 BTF_ID_LIST(special_kfunc_list)
9834 BTF_ID(func, bpf_obj_new_impl)
9835 BTF_ID(func, bpf_obj_drop_impl)
9836 BTF_ID(func, bpf_refcount_acquire_impl)
9837 BTF_ID(func, bpf_list_push_front_impl)
9838 BTF_ID(func, bpf_list_push_back_impl)
9839 BTF_ID(func, bpf_list_pop_front)
9840 BTF_ID(func, bpf_list_pop_back)
9841 BTF_ID(func, bpf_cast_to_kern_ctx)
9842 BTF_ID(func, bpf_rdonly_cast)
9843 BTF_ID(func, bpf_rcu_read_lock)
9844 BTF_ID(func, bpf_rcu_read_unlock)
9845 BTF_ID(func, bpf_rbtree_remove)
9846 BTF_ID(func, bpf_rbtree_add_impl)
9847 BTF_ID(func, bpf_rbtree_first)
9848 BTF_ID(func, bpf_dynptr_from_skb)
9849 BTF_ID(func, bpf_dynptr_from_xdp)
9850 BTF_ID(func, bpf_dynptr_slice)
9851 BTF_ID(func, bpf_dynptr_slice_rdwr)
9852 BTF_ID(func, bpf_dynptr_clone)
9853 
9854 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9855 {
9856 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9857 }
9858 
9859 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9860 {
9861 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9862 }
9863 
9864 static enum kfunc_ptr_arg_type
9865 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9866 		       struct bpf_kfunc_call_arg_meta *meta,
9867 		       const struct btf_type *t, const struct btf_type *ref_t,
9868 		       const char *ref_tname, const struct btf_param *args,
9869 		       int argno, int nargs)
9870 {
9871 	u32 regno = argno + 1;
9872 	struct bpf_reg_state *regs = cur_regs(env);
9873 	struct bpf_reg_state *reg = &regs[regno];
9874 	bool arg_mem_size = false;
9875 
9876 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9877 		return KF_ARG_PTR_TO_CTX;
9878 
9879 	/* In this function, we verify the kfunc's BTF as per the argument type,
9880 	 * leaving the rest of the verification with respect to the register
9881 	 * type to our caller. When a set of conditions hold in the BTF type of
9882 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
9883 	 */
9884 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9885 		return KF_ARG_PTR_TO_CTX;
9886 
9887 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9888 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9889 
9890 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
9891 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
9892 
9893 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9894 		return KF_ARG_PTR_TO_DYNPTR;
9895 
9896 	if (is_kfunc_arg_iter(meta, argno))
9897 		return KF_ARG_PTR_TO_ITER;
9898 
9899 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9900 		return KF_ARG_PTR_TO_LIST_HEAD;
9901 
9902 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9903 		return KF_ARG_PTR_TO_LIST_NODE;
9904 
9905 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9906 		return KF_ARG_PTR_TO_RB_ROOT;
9907 
9908 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9909 		return KF_ARG_PTR_TO_RB_NODE;
9910 
9911 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9912 		if (!btf_type_is_struct(ref_t)) {
9913 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9914 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9915 			return -EINVAL;
9916 		}
9917 		return KF_ARG_PTR_TO_BTF_ID;
9918 	}
9919 
9920 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9921 		return KF_ARG_PTR_TO_CALLBACK;
9922 
9923 
9924 	if (argno + 1 < nargs &&
9925 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
9926 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
9927 		arg_mem_size = true;
9928 
9929 	/* This is the catch all argument type of register types supported by
9930 	 * check_helper_mem_access. However, we only allow when argument type is
9931 	 * pointer to scalar, or struct composed (recursively) of scalars. When
9932 	 * arg_mem_size is true, the pointer can be void *.
9933 	 */
9934 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9935 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9936 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9937 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9938 		return -EINVAL;
9939 	}
9940 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9941 }
9942 
9943 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9944 					struct bpf_reg_state *reg,
9945 					const struct btf_type *ref_t,
9946 					const char *ref_tname, u32 ref_id,
9947 					struct bpf_kfunc_call_arg_meta *meta,
9948 					int argno)
9949 {
9950 	const struct btf_type *reg_ref_t;
9951 	bool strict_type_match = false;
9952 	const struct btf *reg_btf;
9953 	const char *reg_ref_tname;
9954 	u32 reg_ref_id;
9955 
9956 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
9957 		reg_btf = reg->btf;
9958 		reg_ref_id = reg->btf_id;
9959 	} else {
9960 		reg_btf = btf_vmlinux;
9961 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9962 	}
9963 
9964 	/* Enforce strict type matching for calls to kfuncs that are acquiring
9965 	 * or releasing a reference, or are no-cast aliases. We do _not_
9966 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9967 	 * as we want to enable BPF programs to pass types that are bitwise
9968 	 * equivalent without forcing them to explicitly cast with something
9969 	 * like bpf_cast_to_kern_ctx().
9970 	 *
9971 	 * For example, say we had a type like the following:
9972 	 *
9973 	 * struct bpf_cpumask {
9974 	 *	cpumask_t cpumask;
9975 	 *	refcount_t usage;
9976 	 * };
9977 	 *
9978 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9979 	 * to a struct cpumask, so it would be safe to pass a struct
9980 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9981 	 *
9982 	 * The philosophy here is similar to how we allow scalars of different
9983 	 * types to be passed to kfuncs as long as the size is the same. The
9984 	 * only difference here is that we're simply allowing
9985 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9986 	 * resolve types.
9987 	 */
9988 	if (is_kfunc_acquire(meta) ||
9989 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
9990 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9991 		strict_type_match = true;
9992 
9993 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9994 
9995 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9996 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9997 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9998 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9999 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10000 			btf_type_str(reg_ref_t), reg_ref_tname);
10001 		return -EINVAL;
10002 	}
10003 	return 0;
10004 }
10005 
10006 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10007 {
10008 	struct bpf_verifier_state *state = env->cur_state;
10009 
10010 	if (!state->active_lock.ptr) {
10011 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10012 		return -EFAULT;
10013 	}
10014 
10015 	if (type_flag(reg->type) & NON_OWN_REF) {
10016 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10017 		return -EFAULT;
10018 	}
10019 
10020 	reg->type |= NON_OWN_REF;
10021 	return 0;
10022 }
10023 
10024 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10025 {
10026 	struct bpf_func_state *state, *unused;
10027 	struct bpf_reg_state *reg;
10028 	int i;
10029 
10030 	state = cur_func(env);
10031 
10032 	if (!ref_obj_id) {
10033 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10034 			     "owning -> non-owning conversion\n");
10035 		return -EFAULT;
10036 	}
10037 
10038 	for (i = 0; i < state->acquired_refs; i++) {
10039 		if (state->refs[i].id != ref_obj_id)
10040 			continue;
10041 
10042 		/* Clear ref_obj_id here so release_reference doesn't clobber
10043 		 * the whole reg
10044 		 */
10045 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10046 			if (reg->ref_obj_id == ref_obj_id) {
10047 				reg->ref_obj_id = 0;
10048 				ref_set_non_owning(env, reg);
10049 			}
10050 		}));
10051 		return 0;
10052 	}
10053 
10054 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10055 	return -EFAULT;
10056 }
10057 
10058 /* Implementation details:
10059  *
10060  * Each register points to some region of memory, which we define as an
10061  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10062  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10063  * allocation. The lock and the data it protects are colocated in the same
10064  * memory region.
10065  *
10066  * Hence, everytime a register holds a pointer value pointing to such
10067  * allocation, the verifier preserves a unique reg->id for it.
10068  *
10069  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10070  * bpf_spin_lock is called.
10071  *
10072  * To enable this, lock state in the verifier captures two values:
10073  *	active_lock.ptr = Register's type specific pointer
10074  *	active_lock.id  = A unique ID for each register pointer value
10075  *
10076  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10077  * supported register types.
10078  *
10079  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10080  * allocated objects is the reg->btf pointer.
10081  *
10082  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10083  * can establish the provenance of the map value statically for each distinct
10084  * lookup into such maps. They always contain a single map value hence unique
10085  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10086  *
10087  * So, in case of global variables, they use array maps with max_entries = 1,
10088  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10089  * into the same map value as max_entries is 1, as described above).
10090  *
10091  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10092  * outer map pointer (in verifier context), but each lookup into an inner map
10093  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10094  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10095  * will get different reg->id assigned to each lookup, hence different
10096  * active_lock.id.
10097  *
10098  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10099  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10100  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10101  */
10102 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10103 {
10104 	void *ptr;
10105 	u32 id;
10106 
10107 	switch ((int)reg->type) {
10108 	case PTR_TO_MAP_VALUE:
10109 		ptr = reg->map_ptr;
10110 		break;
10111 	case PTR_TO_BTF_ID | MEM_ALLOC:
10112 		ptr = reg->btf;
10113 		break;
10114 	default:
10115 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10116 		return -EFAULT;
10117 	}
10118 	id = reg->id;
10119 
10120 	if (!env->cur_state->active_lock.ptr)
10121 		return -EINVAL;
10122 	if (env->cur_state->active_lock.ptr != ptr ||
10123 	    env->cur_state->active_lock.id != id) {
10124 		verbose(env, "held lock and object are not in the same allocation\n");
10125 		return -EINVAL;
10126 	}
10127 	return 0;
10128 }
10129 
10130 static bool is_bpf_list_api_kfunc(u32 btf_id)
10131 {
10132 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10133 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10134 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10135 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10136 }
10137 
10138 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10139 {
10140 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10141 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10142 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10143 }
10144 
10145 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10146 {
10147 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10148 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10149 }
10150 
10151 static bool is_callback_calling_kfunc(u32 btf_id)
10152 {
10153 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10154 }
10155 
10156 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10157 {
10158 	return is_bpf_rbtree_api_kfunc(btf_id);
10159 }
10160 
10161 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10162 					  enum btf_field_type head_field_type,
10163 					  u32 kfunc_btf_id)
10164 {
10165 	bool ret;
10166 
10167 	switch (head_field_type) {
10168 	case BPF_LIST_HEAD:
10169 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10170 		break;
10171 	case BPF_RB_ROOT:
10172 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10173 		break;
10174 	default:
10175 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10176 			btf_field_type_name(head_field_type));
10177 		return false;
10178 	}
10179 
10180 	if (!ret)
10181 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10182 			btf_field_type_name(head_field_type));
10183 	return ret;
10184 }
10185 
10186 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10187 					  enum btf_field_type node_field_type,
10188 					  u32 kfunc_btf_id)
10189 {
10190 	bool ret;
10191 
10192 	switch (node_field_type) {
10193 	case BPF_LIST_NODE:
10194 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10195 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10196 		break;
10197 	case BPF_RB_NODE:
10198 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10199 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10200 		break;
10201 	default:
10202 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10203 			btf_field_type_name(node_field_type));
10204 		return false;
10205 	}
10206 
10207 	if (!ret)
10208 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10209 			btf_field_type_name(node_field_type));
10210 	return ret;
10211 }
10212 
10213 static int
10214 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10215 				   struct bpf_reg_state *reg, u32 regno,
10216 				   struct bpf_kfunc_call_arg_meta *meta,
10217 				   enum btf_field_type head_field_type,
10218 				   struct btf_field **head_field)
10219 {
10220 	const char *head_type_name;
10221 	struct btf_field *field;
10222 	struct btf_record *rec;
10223 	u32 head_off;
10224 
10225 	if (meta->btf != btf_vmlinux) {
10226 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10227 		return -EFAULT;
10228 	}
10229 
10230 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10231 		return -EFAULT;
10232 
10233 	head_type_name = btf_field_type_name(head_field_type);
10234 	if (!tnum_is_const(reg->var_off)) {
10235 		verbose(env,
10236 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10237 			regno, head_type_name);
10238 		return -EINVAL;
10239 	}
10240 
10241 	rec = reg_btf_record(reg);
10242 	head_off = reg->off + reg->var_off.value;
10243 	field = btf_record_find(rec, head_off, head_field_type);
10244 	if (!field) {
10245 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10246 		return -EINVAL;
10247 	}
10248 
10249 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10250 	if (check_reg_allocation_locked(env, reg)) {
10251 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10252 			rec->spin_lock_off, head_type_name);
10253 		return -EINVAL;
10254 	}
10255 
10256 	if (*head_field) {
10257 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10258 		return -EFAULT;
10259 	}
10260 	*head_field = field;
10261 	return 0;
10262 }
10263 
10264 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10265 					   struct bpf_reg_state *reg, u32 regno,
10266 					   struct bpf_kfunc_call_arg_meta *meta)
10267 {
10268 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10269 							  &meta->arg_list_head.field);
10270 }
10271 
10272 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10273 					     struct bpf_reg_state *reg, u32 regno,
10274 					     struct bpf_kfunc_call_arg_meta *meta)
10275 {
10276 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10277 							  &meta->arg_rbtree_root.field);
10278 }
10279 
10280 static int
10281 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10282 				   struct bpf_reg_state *reg, u32 regno,
10283 				   struct bpf_kfunc_call_arg_meta *meta,
10284 				   enum btf_field_type head_field_type,
10285 				   enum btf_field_type node_field_type,
10286 				   struct btf_field **node_field)
10287 {
10288 	const char *node_type_name;
10289 	const struct btf_type *et, *t;
10290 	struct btf_field *field;
10291 	u32 node_off;
10292 
10293 	if (meta->btf != btf_vmlinux) {
10294 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10295 		return -EFAULT;
10296 	}
10297 
10298 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10299 		return -EFAULT;
10300 
10301 	node_type_name = btf_field_type_name(node_field_type);
10302 	if (!tnum_is_const(reg->var_off)) {
10303 		verbose(env,
10304 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10305 			regno, node_type_name);
10306 		return -EINVAL;
10307 	}
10308 
10309 	node_off = reg->off + reg->var_off.value;
10310 	field = reg_find_field_offset(reg, node_off, node_field_type);
10311 	if (!field || field->offset != node_off) {
10312 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10313 		return -EINVAL;
10314 	}
10315 
10316 	field = *node_field;
10317 
10318 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10319 	t = btf_type_by_id(reg->btf, reg->btf_id);
10320 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10321 				  field->graph_root.value_btf_id, true)) {
10322 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10323 			"in struct %s, but arg is at offset=%d in struct %s\n",
10324 			btf_field_type_name(head_field_type),
10325 			btf_field_type_name(node_field_type),
10326 			field->graph_root.node_offset,
10327 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10328 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10329 		return -EINVAL;
10330 	}
10331 
10332 	if (node_off != field->graph_root.node_offset) {
10333 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10334 			node_off, btf_field_type_name(node_field_type),
10335 			field->graph_root.node_offset,
10336 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10337 		return -EINVAL;
10338 	}
10339 
10340 	return 0;
10341 }
10342 
10343 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10344 					   struct bpf_reg_state *reg, u32 regno,
10345 					   struct bpf_kfunc_call_arg_meta *meta)
10346 {
10347 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10348 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10349 						  &meta->arg_list_head.field);
10350 }
10351 
10352 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10353 					     struct bpf_reg_state *reg, u32 regno,
10354 					     struct bpf_kfunc_call_arg_meta *meta)
10355 {
10356 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10357 						  BPF_RB_ROOT, BPF_RB_NODE,
10358 						  &meta->arg_rbtree_root.field);
10359 }
10360 
10361 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10362 			    int insn_idx)
10363 {
10364 	const char *func_name = meta->func_name, *ref_tname;
10365 	const struct btf *btf = meta->btf;
10366 	const struct btf_param *args;
10367 	struct btf_record *rec;
10368 	u32 i, nargs;
10369 	int ret;
10370 
10371 	args = (const struct btf_param *)(meta->func_proto + 1);
10372 	nargs = btf_type_vlen(meta->func_proto);
10373 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10374 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10375 			MAX_BPF_FUNC_REG_ARGS);
10376 		return -EINVAL;
10377 	}
10378 
10379 	/* Check that BTF function arguments match actual types that the
10380 	 * verifier sees.
10381 	 */
10382 	for (i = 0; i < nargs; i++) {
10383 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10384 		const struct btf_type *t, *ref_t, *resolve_ret;
10385 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10386 		u32 regno = i + 1, ref_id, type_size;
10387 		bool is_ret_buf_sz = false;
10388 		int kf_arg_type;
10389 
10390 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10391 
10392 		if (is_kfunc_arg_ignore(btf, &args[i]))
10393 			continue;
10394 
10395 		if (btf_type_is_scalar(t)) {
10396 			if (reg->type != SCALAR_VALUE) {
10397 				verbose(env, "R%d is not a scalar\n", regno);
10398 				return -EINVAL;
10399 			}
10400 
10401 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10402 				if (meta->arg_constant.found) {
10403 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10404 					return -EFAULT;
10405 				}
10406 				if (!tnum_is_const(reg->var_off)) {
10407 					verbose(env, "R%d must be a known constant\n", regno);
10408 					return -EINVAL;
10409 				}
10410 				ret = mark_chain_precision(env, regno);
10411 				if (ret < 0)
10412 					return ret;
10413 				meta->arg_constant.found = true;
10414 				meta->arg_constant.value = reg->var_off.value;
10415 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10416 				meta->r0_rdonly = true;
10417 				is_ret_buf_sz = true;
10418 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10419 				is_ret_buf_sz = true;
10420 			}
10421 
10422 			if (is_ret_buf_sz) {
10423 				if (meta->r0_size) {
10424 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10425 					return -EINVAL;
10426 				}
10427 
10428 				if (!tnum_is_const(reg->var_off)) {
10429 					verbose(env, "R%d is not a const\n", regno);
10430 					return -EINVAL;
10431 				}
10432 
10433 				meta->r0_size = reg->var_off.value;
10434 				ret = mark_chain_precision(env, regno);
10435 				if (ret)
10436 					return ret;
10437 			}
10438 			continue;
10439 		}
10440 
10441 		if (!btf_type_is_ptr(t)) {
10442 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10443 			return -EINVAL;
10444 		}
10445 
10446 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10447 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10448 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10449 			return -EACCES;
10450 		}
10451 
10452 		if (reg->ref_obj_id) {
10453 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10454 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10455 					regno, reg->ref_obj_id,
10456 					meta->ref_obj_id);
10457 				return -EFAULT;
10458 			}
10459 			meta->ref_obj_id = reg->ref_obj_id;
10460 			if (is_kfunc_release(meta))
10461 				meta->release_regno = regno;
10462 		}
10463 
10464 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10465 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10466 
10467 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10468 		if (kf_arg_type < 0)
10469 			return kf_arg_type;
10470 
10471 		switch (kf_arg_type) {
10472 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10473 		case KF_ARG_PTR_TO_BTF_ID:
10474 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10475 				break;
10476 
10477 			if (!is_trusted_reg(reg)) {
10478 				if (!is_kfunc_rcu(meta)) {
10479 					verbose(env, "R%d must be referenced or trusted\n", regno);
10480 					return -EINVAL;
10481 				}
10482 				if (!is_rcu_reg(reg)) {
10483 					verbose(env, "R%d must be a rcu pointer\n", regno);
10484 					return -EINVAL;
10485 				}
10486 			}
10487 
10488 			fallthrough;
10489 		case KF_ARG_PTR_TO_CTX:
10490 			/* Trusted arguments have the same offset checks as release arguments */
10491 			arg_type |= OBJ_RELEASE;
10492 			break;
10493 		case KF_ARG_PTR_TO_DYNPTR:
10494 		case KF_ARG_PTR_TO_ITER:
10495 		case KF_ARG_PTR_TO_LIST_HEAD:
10496 		case KF_ARG_PTR_TO_LIST_NODE:
10497 		case KF_ARG_PTR_TO_RB_ROOT:
10498 		case KF_ARG_PTR_TO_RB_NODE:
10499 		case KF_ARG_PTR_TO_MEM:
10500 		case KF_ARG_PTR_TO_MEM_SIZE:
10501 		case KF_ARG_PTR_TO_CALLBACK:
10502 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10503 			/* Trusted by default */
10504 			break;
10505 		default:
10506 			WARN_ON_ONCE(1);
10507 			return -EFAULT;
10508 		}
10509 
10510 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10511 			arg_type |= OBJ_RELEASE;
10512 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10513 		if (ret < 0)
10514 			return ret;
10515 
10516 		switch (kf_arg_type) {
10517 		case KF_ARG_PTR_TO_CTX:
10518 			if (reg->type != PTR_TO_CTX) {
10519 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10520 				return -EINVAL;
10521 			}
10522 
10523 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10524 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10525 				if (ret < 0)
10526 					return -EINVAL;
10527 				meta->ret_btf_id  = ret;
10528 			}
10529 			break;
10530 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10531 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10532 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10533 				return -EINVAL;
10534 			}
10535 			if (!reg->ref_obj_id) {
10536 				verbose(env, "allocated object must be referenced\n");
10537 				return -EINVAL;
10538 			}
10539 			if (meta->btf == btf_vmlinux &&
10540 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10541 				meta->arg_obj_drop.btf = reg->btf;
10542 				meta->arg_obj_drop.btf_id = reg->btf_id;
10543 			}
10544 			break;
10545 		case KF_ARG_PTR_TO_DYNPTR:
10546 		{
10547 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10548 			int clone_ref_obj_id = 0;
10549 
10550 			if (reg->type != PTR_TO_STACK &&
10551 			    reg->type != CONST_PTR_TO_DYNPTR) {
10552 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10553 				return -EINVAL;
10554 			}
10555 
10556 			if (reg->type == CONST_PTR_TO_DYNPTR)
10557 				dynptr_arg_type |= MEM_RDONLY;
10558 
10559 			if (is_kfunc_arg_uninit(btf, &args[i]))
10560 				dynptr_arg_type |= MEM_UNINIT;
10561 
10562 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10563 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
10564 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10565 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
10566 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10567 				   (dynptr_arg_type & MEM_UNINIT)) {
10568 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10569 
10570 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10571 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10572 					return -EFAULT;
10573 				}
10574 
10575 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10576 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10577 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10578 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10579 					return -EFAULT;
10580 				}
10581 			}
10582 
10583 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10584 			if (ret < 0)
10585 				return ret;
10586 
10587 			if (!(dynptr_arg_type & MEM_UNINIT)) {
10588 				int id = dynptr_id(env, reg);
10589 
10590 				if (id < 0) {
10591 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10592 					return id;
10593 				}
10594 				meta->initialized_dynptr.id = id;
10595 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10596 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10597 			}
10598 
10599 			break;
10600 		}
10601 		case KF_ARG_PTR_TO_ITER:
10602 			ret = process_iter_arg(env, regno, insn_idx, meta);
10603 			if (ret < 0)
10604 				return ret;
10605 			break;
10606 		case KF_ARG_PTR_TO_LIST_HEAD:
10607 			if (reg->type != PTR_TO_MAP_VALUE &&
10608 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10609 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10610 				return -EINVAL;
10611 			}
10612 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10613 				verbose(env, "allocated object must be referenced\n");
10614 				return -EINVAL;
10615 			}
10616 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10617 			if (ret < 0)
10618 				return ret;
10619 			break;
10620 		case KF_ARG_PTR_TO_RB_ROOT:
10621 			if (reg->type != PTR_TO_MAP_VALUE &&
10622 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10623 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10624 				return -EINVAL;
10625 			}
10626 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10627 				verbose(env, "allocated object must be referenced\n");
10628 				return -EINVAL;
10629 			}
10630 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10631 			if (ret < 0)
10632 				return ret;
10633 			break;
10634 		case KF_ARG_PTR_TO_LIST_NODE:
10635 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10636 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10637 				return -EINVAL;
10638 			}
10639 			if (!reg->ref_obj_id) {
10640 				verbose(env, "allocated object must be referenced\n");
10641 				return -EINVAL;
10642 			}
10643 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10644 			if (ret < 0)
10645 				return ret;
10646 			break;
10647 		case KF_ARG_PTR_TO_RB_NODE:
10648 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10649 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10650 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
10651 					return -EINVAL;
10652 				}
10653 				if (in_rbtree_lock_required_cb(env)) {
10654 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10655 					return -EINVAL;
10656 				}
10657 			} else {
10658 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10659 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10660 					return -EINVAL;
10661 				}
10662 				if (!reg->ref_obj_id) {
10663 					verbose(env, "allocated object must be referenced\n");
10664 					return -EINVAL;
10665 				}
10666 			}
10667 
10668 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10669 			if (ret < 0)
10670 				return ret;
10671 			break;
10672 		case KF_ARG_PTR_TO_BTF_ID:
10673 			/* Only base_type is checked, further checks are done here */
10674 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10675 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10676 			    !reg2btf_ids[base_type(reg->type)]) {
10677 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10678 				verbose(env, "expected %s or socket\n",
10679 					reg_type_str(env, base_type(reg->type) |
10680 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10681 				return -EINVAL;
10682 			}
10683 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10684 			if (ret < 0)
10685 				return ret;
10686 			break;
10687 		case KF_ARG_PTR_TO_MEM:
10688 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10689 			if (IS_ERR(resolve_ret)) {
10690 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10691 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10692 				return -EINVAL;
10693 			}
10694 			ret = check_mem_reg(env, reg, regno, type_size);
10695 			if (ret < 0)
10696 				return ret;
10697 			break;
10698 		case KF_ARG_PTR_TO_MEM_SIZE:
10699 		{
10700 			struct bpf_reg_state *size_reg = &regs[regno + 1];
10701 			const struct btf_param *size_arg = &args[i + 1];
10702 
10703 			ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10704 			if (ret < 0) {
10705 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10706 				return ret;
10707 			}
10708 
10709 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10710 				if (meta->arg_constant.found) {
10711 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10712 					return -EFAULT;
10713 				}
10714 				if (!tnum_is_const(size_reg->var_off)) {
10715 					verbose(env, "R%d must be a known constant\n", regno + 1);
10716 					return -EINVAL;
10717 				}
10718 				meta->arg_constant.found = true;
10719 				meta->arg_constant.value = size_reg->var_off.value;
10720 			}
10721 
10722 			/* Skip next '__sz' or '__szk' argument */
10723 			i++;
10724 			break;
10725 		}
10726 		case KF_ARG_PTR_TO_CALLBACK:
10727 			meta->subprogno = reg->subprogno;
10728 			break;
10729 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10730 			if (!type_is_ptr_alloc_obj(reg->type) && !type_is_non_owning_ref(reg->type)) {
10731 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
10732 				return -EINVAL;
10733 			}
10734 
10735 			rec = reg_btf_record(reg);
10736 			if (!rec) {
10737 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
10738 				return -EFAULT;
10739 			}
10740 
10741 			if (rec->refcount_off < 0) {
10742 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
10743 				return -EINVAL;
10744 			}
10745 			if (rec->refcount_off >= 0) {
10746 				verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
10747 				return -EINVAL;
10748 			}
10749 			meta->arg_refcount_acquire.btf = reg->btf;
10750 			meta->arg_refcount_acquire.btf_id = reg->btf_id;
10751 			break;
10752 		}
10753 	}
10754 
10755 	if (is_kfunc_release(meta) && !meta->release_regno) {
10756 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10757 			func_name);
10758 		return -EINVAL;
10759 	}
10760 
10761 	return 0;
10762 }
10763 
10764 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10765 			    struct bpf_insn *insn,
10766 			    struct bpf_kfunc_call_arg_meta *meta,
10767 			    const char **kfunc_name)
10768 {
10769 	const struct btf_type *func, *func_proto;
10770 	u32 func_id, *kfunc_flags;
10771 	const char *func_name;
10772 	struct btf *desc_btf;
10773 
10774 	if (kfunc_name)
10775 		*kfunc_name = NULL;
10776 
10777 	if (!insn->imm)
10778 		return -EINVAL;
10779 
10780 	desc_btf = find_kfunc_desc_btf(env, insn->off);
10781 	if (IS_ERR(desc_btf))
10782 		return PTR_ERR(desc_btf);
10783 
10784 	func_id = insn->imm;
10785 	func = btf_type_by_id(desc_btf, func_id);
10786 	func_name = btf_name_by_offset(desc_btf, func->name_off);
10787 	if (kfunc_name)
10788 		*kfunc_name = func_name;
10789 	func_proto = btf_type_by_id(desc_btf, func->type);
10790 
10791 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10792 	if (!kfunc_flags) {
10793 		return -EACCES;
10794 	}
10795 
10796 	memset(meta, 0, sizeof(*meta));
10797 	meta->btf = desc_btf;
10798 	meta->func_id = func_id;
10799 	meta->kfunc_flags = *kfunc_flags;
10800 	meta->func_proto = func_proto;
10801 	meta->func_name = func_name;
10802 
10803 	return 0;
10804 }
10805 
10806 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10807 			    int *insn_idx_p)
10808 {
10809 	const struct btf_type *t, *ptr_type;
10810 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
10811 	struct bpf_reg_state *regs = cur_regs(env);
10812 	const char *func_name, *ptr_type_name;
10813 	bool sleepable, rcu_lock, rcu_unlock;
10814 	struct bpf_kfunc_call_arg_meta meta;
10815 	struct bpf_insn_aux_data *insn_aux;
10816 	int err, insn_idx = *insn_idx_p;
10817 	const struct btf_param *args;
10818 	const struct btf_type *ret_t;
10819 	struct btf *desc_btf;
10820 
10821 	/* skip for now, but return error when we find this in fixup_kfunc_call */
10822 	if (!insn->imm)
10823 		return 0;
10824 
10825 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10826 	if (err == -EACCES && func_name)
10827 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
10828 	if (err)
10829 		return err;
10830 	desc_btf = meta.btf;
10831 	insn_aux = &env->insn_aux_data[insn_idx];
10832 
10833 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10834 
10835 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10836 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10837 		return -EACCES;
10838 	}
10839 
10840 	sleepable = is_kfunc_sleepable(&meta);
10841 	if (sleepable && !env->prog->aux->sleepable) {
10842 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10843 		return -EACCES;
10844 	}
10845 
10846 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10847 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10848 
10849 	if (env->cur_state->active_rcu_lock) {
10850 		struct bpf_func_state *state;
10851 		struct bpf_reg_state *reg;
10852 
10853 		if (rcu_lock) {
10854 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10855 			return -EINVAL;
10856 		} else if (rcu_unlock) {
10857 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10858 				if (reg->type & MEM_RCU) {
10859 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10860 					reg->type |= PTR_UNTRUSTED;
10861 				}
10862 			}));
10863 			env->cur_state->active_rcu_lock = false;
10864 		} else if (sleepable) {
10865 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10866 			return -EACCES;
10867 		}
10868 	} else if (rcu_lock) {
10869 		env->cur_state->active_rcu_lock = true;
10870 	} else if (rcu_unlock) {
10871 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10872 		return -EINVAL;
10873 	}
10874 
10875 	/* Check the arguments */
10876 	err = check_kfunc_args(env, &meta, insn_idx);
10877 	if (err < 0)
10878 		return err;
10879 	/* In case of release function, we get register number of refcounted
10880 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10881 	 */
10882 	if (meta.release_regno) {
10883 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10884 		if (err) {
10885 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10886 				func_name, meta.func_id);
10887 			return err;
10888 		}
10889 	}
10890 
10891 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10892 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10893 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
10894 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10895 		insn_aux->insert_off = regs[BPF_REG_2].off;
10896 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10897 		if (err) {
10898 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10899 				func_name, meta.func_id);
10900 			return err;
10901 		}
10902 
10903 		err = release_reference(env, release_ref_obj_id);
10904 		if (err) {
10905 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10906 				func_name, meta.func_id);
10907 			return err;
10908 		}
10909 	}
10910 
10911 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
10912 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10913 					set_rbtree_add_callback_state);
10914 		if (err) {
10915 			verbose(env, "kfunc %s#%d failed callback verification\n",
10916 				func_name, meta.func_id);
10917 			return err;
10918 		}
10919 	}
10920 
10921 	for (i = 0; i < CALLER_SAVED_REGS; i++)
10922 		mark_reg_not_init(env, regs, caller_saved[i]);
10923 
10924 	/* Check return type */
10925 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
10926 
10927 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10928 		/* Only exception is bpf_obj_new_impl */
10929 		if (meta.btf != btf_vmlinux ||
10930 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
10931 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
10932 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10933 			return -EINVAL;
10934 		}
10935 	}
10936 
10937 	if (btf_type_is_scalar(t)) {
10938 		mark_reg_unknown(env, regs, BPF_REG_0);
10939 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10940 	} else if (btf_type_is_ptr(t)) {
10941 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10942 
10943 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10944 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10945 				struct btf *ret_btf;
10946 				u32 ret_btf_id;
10947 
10948 				if (unlikely(!bpf_global_ma_set))
10949 					return -ENOMEM;
10950 
10951 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10952 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10953 					return -EINVAL;
10954 				}
10955 
10956 				ret_btf = env->prog->aux->btf;
10957 				ret_btf_id = meta.arg_constant.value;
10958 
10959 				/* This may be NULL due to user not supplying a BTF */
10960 				if (!ret_btf) {
10961 					verbose(env, "bpf_obj_new requires prog BTF\n");
10962 					return -EINVAL;
10963 				}
10964 
10965 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10966 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
10967 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10968 					return -EINVAL;
10969 				}
10970 
10971 				mark_reg_known_zero(env, regs, BPF_REG_0);
10972 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10973 				regs[BPF_REG_0].btf = ret_btf;
10974 				regs[BPF_REG_0].btf_id = ret_btf_id;
10975 
10976 				insn_aux->obj_new_size = ret_t->size;
10977 				insn_aux->kptr_struct_meta =
10978 					btf_find_struct_meta(ret_btf, ret_btf_id);
10979 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
10980 				mark_reg_known_zero(env, regs, BPF_REG_0);
10981 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10982 				regs[BPF_REG_0].btf = meta.arg_refcount_acquire.btf;
10983 				regs[BPF_REG_0].btf_id = meta.arg_refcount_acquire.btf_id;
10984 
10985 				insn_aux->kptr_struct_meta =
10986 					btf_find_struct_meta(meta.arg_refcount_acquire.btf,
10987 							     meta.arg_refcount_acquire.btf_id);
10988 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10989 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10990 				struct btf_field *field = meta.arg_list_head.field;
10991 
10992 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10993 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10994 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10995 				struct btf_field *field = meta.arg_rbtree_root.field;
10996 
10997 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10998 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10999 				mark_reg_known_zero(env, regs, BPF_REG_0);
11000 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11001 				regs[BPF_REG_0].btf = desc_btf;
11002 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11003 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11004 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11005 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11006 					verbose(env,
11007 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11008 					return -EINVAL;
11009 				}
11010 
11011 				mark_reg_known_zero(env, regs, BPF_REG_0);
11012 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11013 				regs[BPF_REG_0].btf = desc_btf;
11014 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11015 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11016 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11017 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11018 
11019 				mark_reg_known_zero(env, regs, BPF_REG_0);
11020 
11021 				if (!meta.arg_constant.found) {
11022 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11023 					return -EFAULT;
11024 				}
11025 
11026 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11027 
11028 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11029 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11030 
11031 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11032 					regs[BPF_REG_0].type |= MEM_RDONLY;
11033 				} else {
11034 					/* this will set env->seen_direct_write to true */
11035 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11036 						verbose(env, "the prog does not allow writes to packet data\n");
11037 						return -EINVAL;
11038 					}
11039 				}
11040 
11041 				if (!meta.initialized_dynptr.id) {
11042 					verbose(env, "verifier internal error: no dynptr id\n");
11043 					return -EFAULT;
11044 				}
11045 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11046 
11047 				/* we don't need to set BPF_REG_0's ref obj id
11048 				 * because packet slices are not refcounted (see
11049 				 * dynptr_type_refcounted)
11050 				 */
11051 			} else {
11052 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11053 					meta.func_name);
11054 				return -EFAULT;
11055 			}
11056 		} else if (!__btf_type_is_struct(ptr_type)) {
11057 			if (!meta.r0_size) {
11058 				__u32 sz;
11059 
11060 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11061 					meta.r0_size = sz;
11062 					meta.r0_rdonly = true;
11063 				}
11064 			}
11065 			if (!meta.r0_size) {
11066 				ptr_type_name = btf_name_by_offset(desc_btf,
11067 								   ptr_type->name_off);
11068 				verbose(env,
11069 					"kernel function %s returns pointer type %s %s is not supported\n",
11070 					func_name,
11071 					btf_type_str(ptr_type),
11072 					ptr_type_name);
11073 				return -EINVAL;
11074 			}
11075 
11076 			mark_reg_known_zero(env, regs, BPF_REG_0);
11077 			regs[BPF_REG_0].type = PTR_TO_MEM;
11078 			regs[BPF_REG_0].mem_size = meta.r0_size;
11079 
11080 			if (meta.r0_rdonly)
11081 				regs[BPF_REG_0].type |= MEM_RDONLY;
11082 
11083 			/* Ensures we don't access the memory after a release_reference() */
11084 			if (meta.ref_obj_id)
11085 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11086 		} else {
11087 			mark_reg_known_zero(env, regs, BPF_REG_0);
11088 			regs[BPF_REG_0].btf = desc_btf;
11089 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11090 			regs[BPF_REG_0].btf_id = ptr_type_id;
11091 		}
11092 
11093 		if (is_kfunc_ret_null(&meta)) {
11094 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11095 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11096 			regs[BPF_REG_0].id = ++env->id_gen;
11097 		}
11098 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11099 		if (is_kfunc_acquire(&meta)) {
11100 			int id = acquire_reference_state(env, insn_idx);
11101 
11102 			if (id < 0)
11103 				return id;
11104 			if (is_kfunc_ret_null(&meta))
11105 				regs[BPF_REG_0].id = id;
11106 			regs[BPF_REG_0].ref_obj_id = id;
11107 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11108 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11109 		}
11110 
11111 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11112 			regs[BPF_REG_0].id = ++env->id_gen;
11113 	} else if (btf_type_is_void(t)) {
11114 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11115 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11116 				insn_aux->kptr_struct_meta =
11117 					btf_find_struct_meta(meta.arg_obj_drop.btf,
11118 							     meta.arg_obj_drop.btf_id);
11119 			}
11120 		}
11121 	}
11122 
11123 	nargs = btf_type_vlen(meta.func_proto);
11124 	args = (const struct btf_param *)(meta.func_proto + 1);
11125 	for (i = 0; i < nargs; i++) {
11126 		u32 regno = i + 1;
11127 
11128 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11129 		if (btf_type_is_ptr(t))
11130 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11131 		else
11132 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11133 			mark_btf_func_reg_size(env, regno, t->size);
11134 	}
11135 
11136 	if (is_iter_next_kfunc(&meta)) {
11137 		err = process_iter_next_call(env, insn_idx, &meta);
11138 		if (err)
11139 			return err;
11140 	}
11141 
11142 	return 0;
11143 }
11144 
11145 static bool signed_add_overflows(s64 a, s64 b)
11146 {
11147 	/* Do the add in u64, where overflow is well-defined */
11148 	s64 res = (s64)((u64)a + (u64)b);
11149 
11150 	if (b < 0)
11151 		return res > a;
11152 	return res < a;
11153 }
11154 
11155 static bool signed_add32_overflows(s32 a, s32 b)
11156 {
11157 	/* Do the add in u32, where overflow is well-defined */
11158 	s32 res = (s32)((u32)a + (u32)b);
11159 
11160 	if (b < 0)
11161 		return res > a;
11162 	return res < a;
11163 }
11164 
11165 static bool signed_sub_overflows(s64 a, s64 b)
11166 {
11167 	/* Do the sub in u64, where overflow is well-defined */
11168 	s64 res = (s64)((u64)a - (u64)b);
11169 
11170 	if (b < 0)
11171 		return res < a;
11172 	return res > a;
11173 }
11174 
11175 static bool signed_sub32_overflows(s32 a, s32 b)
11176 {
11177 	/* Do the sub in u32, where overflow is well-defined */
11178 	s32 res = (s32)((u32)a - (u32)b);
11179 
11180 	if (b < 0)
11181 		return res < a;
11182 	return res > a;
11183 }
11184 
11185 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11186 				  const struct bpf_reg_state *reg,
11187 				  enum bpf_reg_type type)
11188 {
11189 	bool known = tnum_is_const(reg->var_off);
11190 	s64 val = reg->var_off.value;
11191 	s64 smin = reg->smin_value;
11192 
11193 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11194 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11195 			reg_type_str(env, type), val);
11196 		return false;
11197 	}
11198 
11199 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11200 		verbose(env, "%s pointer offset %d is not allowed\n",
11201 			reg_type_str(env, type), reg->off);
11202 		return false;
11203 	}
11204 
11205 	if (smin == S64_MIN) {
11206 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11207 			reg_type_str(env, type));
11208 		return false;
11209 	}
11210 
11211 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11212 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11213 			smin, reg_type_str(env, type));
11214 		return false;
11215 	}
11216 
11217 	return true;
11218 }
11219 
11220 enum {
11221 	REASON_BOUNDS	= -1,
11222 	REASON_TYPE	= -2,
11223 	REASON_PATHS	= -3,
11224 	REASON_LIMIT	= -4,
11225 	REASON_STACK	= -5,
11226 };
11227 
11228 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11229 			      u32 *alu_limit, bool mask_to_left)
11230 {
11231 	u32 max = 0, ptr_limit = 0;
11232 
11233 	switch (ptr_reg->type) {
11234 	case PTR_TO_STACK:
11235 		/* Offset 0 is out-of-bounds, but acceptable start for the
11236 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11237 		 * offset where we would need to deal with min/max bounds is
11238 		 * currently prohibited for unprivileged.
11239 		 */
11240 		max = MAX_BPF_STACK + mask_to_left;
11241 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11242 		break;
11243 	case PTR_TO_MAP_VALUE:
11244 		max = ptr_reg->map_ptr->value_size;
11245 		ptr_limit = (mask_to_left ?
11246 			     ptr_reg->smin_value :
11247 			     ptr_reg->umax_value) + ptr_reg->off;
11248 		break;
11249 	default:
11250 		return REASON_TYPE;
11251 	}
11252 
11253 	if (ptr_limit >= max)
11254 		return REASON_LIMIT;
11255 	*alu_limit = ptr_limit;
11256 	return 0;
11257 }
11258 
11259 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11260 				    const struct bpf_insn *insn)
11261 {
11262 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11263 }
11264 
11265 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11266 				       u32 alu_state, u32 alu_limit)
11267 {
11268 	/* If we arrived here from different branches with different
11269 	 * state or limits to sanitize, then this won't work.
11270 	 */
11271 	if (aux->alu_state &&
11272 	    (aux->alu_state != alu_state ||
11273 	     aux->alu_limit != alu_limit))
11274 		return REASON_PATHS;
11275 
11276 	/* Corresponding fixup done in do_misc_fixups(). */
11277 	aux->alu_state = alu_state;
11278 	aux->alu_limit = alu_limit;
11279 	return 0;
11280 }
11281 
11282 static int sanitize_val_alu(struct bpf_verifier_env *env,
11283 			    struct bpf_insn *insn)
11284 {
11285 	struct bpf_insn_aux_data *aux = cur_aux(env);
11286 
11287 	if (can_skip_alu_sanitation(env, insn))
11288 		return 0;
11289 
11290 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11291 }
11292 
11293 static bool sanitize_needed(u8 opcode)
11294 {
11295 	return opcode == BPF_ADD || opcode == BPF_SUB;
11296 }
11297 
11298 struct bpf_sanitize_info {
11299 	struct bpf_insn_aux_data aux;
11300 	bool mask_to_left;
11301 };
11302 
11303 static struct bpf_verifier_state *
11304 sanitize_speculative_path(struct bpf_verifier_env *env,
11305 			  const struct bpf_insn *insn,
11306 			  u32 next_idx, u32 curr_idx)
11307 {
11308 	struct bpf_verifier_state *branch;
11309 	struct bpf_reg_state *regs;
11310 
11311 	branch = push_stack(env, next_idx, curr_idx, true);
11312 	if (branch && insn) {
11313 		regs = branch->frame[branch->curframe]->regs;
11314 		if (BPF_SRC(insn->code) == BPF_K) {
11315 			mark_reg_unknown(env, regs, insn->dst_reg);
11316 		} else if (BPF_SRC(insn->code) == BPF_X) {
11317 			mark_reg_unknown(env, regs, insn->dst_reg);
11318 			mark_reg_unknown(env, regs, insn->src_reg);
11319 		}
11320 	}
11321 	return branch;
11322 }
11323 
11324 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11325 			    struct bpf_insn *insn,
11326 			    const struct bpf_reg_state *ptr_reg,
11327 			    const struct bpf_reg_state *off_reg,
11328 			    struct bpf_reg_state *dst_reg,
11329 			    struct bpf_sanitize_info *info,
11330 			    const bool commit_window)
11331 {
11332 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11333 	struct bpf_verifier_state *vstate = env->cur_state;
11334 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11335 	bool off_is_neg = off_reg->smin_value < 0;
11336 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11337 	u8 opcode = BPF_OP(insn->code);
11338 	u32 alu_state, alu_limit;
11339 	struct bpf_reg_state tmp;
11340 	bool ret;
11341 	int err;
11342 
11343 	if (can_skip_alu_sanitation(env, insn))
11344 		return 0;
11345 
11346 	/* We already marked aux for masking from non-speculative
11347 	 * paths, thus we got here in the first place. We only care
11348 	 * to explore bad access from here.
11349 	 */
11350 	if (vstate->speculative)
11351 		goto do_sim;
11352 
11353 	if (!commit_window) {
11354 		if (!tnum_is_const(off_reg->var_off) &&
11355 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11356 			return REASON_BOUNDS;
11357 
11358 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11359 				     (opcode == BPF_SUB && !off_is_neg);
11360 	}
11361 
11362 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11363 	if (err < 0)
11364 		return err;
11365 
11366 	if (commit_window) {
11367 		/* In commit phase we narrow the masking window based on
11368 		 * the observed pointer move after the simulated operation.
11369 		 */
11370 		alu_state = info->aux.alu_state;
11371 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11372 	} else {
11373 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11374 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11375 		alu_state |= ptr_is_dst_reg ?
11376 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11377 
11378 		/* Limit pruning on unknown scalars to enable deep search for
11379 		 * potential masking differences from other program paths.
11380 		 */
11381 		if (!off_is_imm)
11382 			env->explore_alu_limits = true;
11383 	}
11384 
11385 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11386 	if (err < 0)
11387 		return err;
11388 do_sim:
11389 	/* If we're in commit phase, we're done here given we already
11390 	 * pushed the truncated dst_reg into the speculative verification
11391 	 * stack.
11392 	 *
11393 	 * Also, when register is a known constant, we rewrite register-based
11394 	 * operation to immediate-based, and thus do not need masking (and as
11395 	 * a consequence, do not need to simulate the zero-truncation either).
11396 	 */
11397 	if (commit_window || off_is_imm)
11398 		return 0;
11399 
11400 	/* Simulate and find potential out-of-bounds access under
11401 	 * speculative execution from truncation as a result of
11402 	 * masking when off was not within expected range. If off
11403 	 * sits in dst, then we temporarily need to move ptr there
11404 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11405 	 * for cases where we use K-based arithmetic in one direction
11406 	 * and truncated reg-based in the other in order to explore
11407 	 * bad access.
11408 	 */
11409 	if (!ptr_is_dst_reg) {
11410 		tmp = *dst_reg;
11411 		copy_register_state(dst_reg, ptr_reg);
11412 	}
11413 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11414 					env->insn_idx);
11415 	if (!ptr_is_dst_reg && ret)
11416 		*dst_reg = tmp;
11417 	return !ret ? REASON_STACK : 0;
11418 }
11419 
11420 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11421 {
11422 	struct bpf_verifier_state *vstate = env->cur_state;
11423 
11424 	/* If we simulate paths under speculation, we don't update the
11425 	 * insn as 'seen' such that when we verify unreachable paths in
11426 	 * the non-speculative domain, sanitize_dead_code() can still
11427 	 * rewrite/sanitize them.
11428 	 */
11429 	if (!vstate->speculative)
11430 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11431 }
11432 
11433 static int sanitize_err(struct bpf_verifier_env *env,
11434 			const struct bpf_insn *insn, int reason,
11435 			const struct bpf_reg_state *off_reg,
11436 			const struct bpf_reg_state *dst_reg)
11437 {
11438 	static const char *err = "pointer arithmetic with it prohibited for !root";
11439 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11440 	u32 dst = insn->dst_reg, src = insn->src_reg;
11441 
11442 	switch (reason) {
11443 	case REASON_BOUNDS:
11444 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11445 			off_reg == dst_reg ? dst : src, err);
11446 		break;
11447 	case REASON_TYPE:
11448 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11449 			off_reg == dst_reg ? src : dst, err);
11450 		break;
11451 	case REASON_PATHS:
11452 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11453 			dst, op, err);
11454 		break;
11455 	case REASON_LIMIT:
11456 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11457 			dst, op, err);
11458 		break;
11459 	case REASON_STACK:
11460 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11461 			dst, err);
11462 		break;
11463 	default:
11464 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11465 			reason);
11466 		break;
11467 	}
11468 
11469 	return -EACCES;
11470 }
11471 
11472 /* check that stack access falls within stack limits and that 'reg' doesn't
11473  * have a variable offset.
11474  *
11475  * Variable offset is prohibited for unprivileged mode for simplicity since it
11476  * requires corresponding support in Spectre masking for stack ALU.  See also
11477  * retrieve_ptr_limit().
11478  *
11479  *
11480  * 'off' includes 'reg->off'.
11481  */
11482 static int check_stack_access_for_ptr_arithmetic(
11483 				struct bpf_verifier_env *env,
11484 				int regno,
11485 				const struct bpf_reg_state *reg,
11486 				int off)
11487 {
11488 	if (!tnum_is_const(reg->var_off)) {
11489 		char tn_buf[48];
11490 
11491 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11492 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11493 			regno, tn_buf, off);
11494 		return -EACCES;
11495 	}
11496 
11497 	if (off >= 0 || off < -MAX_BPF_STACK) {
11498 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11499 			"prohibited for !root; off=%d\n", regno, off);
11500 		return -EACCES;
11501 	}
11502 
11503 	return 0;
11504 }
11505 
11506 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11507 				 const struct bpf_insn *insn,
11508 				 const struct bpf_reg_state *dst_reg)
11509 {
11510 	u32 dst = insn->dst_reg;
11511 
11512 	/* For unprivileged we require that resulting offset must be in bounds
11513 	 * in order to be able to sanitize access later on.
11514 	 */
11515 	if (env->bypass_spec_v1)
11516 		return 0;
11517 
11518 	switch (dst_reg->type) {
11519 	case PTR_TO_STACK:
11520 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11521 					dst_reg->off + dst_reg->var_off.value))
11522 			return -EACCES;
11523 		break;
11524 	case PTR_TO_MAP_VALUE:
11525 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11526 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11527 				"prohibited for !root\n", dst);
11528 			return -EACCES;
11529 		}
11530 		break;
11531 	default:
11532 		break;
11533 	}
11534 
11535 	return 0;
11536 }
11537 
11538 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11539  * Caller should also handle BPF_MOV case separately.
11540  * If we return -EACCES, caller may want to try again treating pointer as a
11541  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11542  */
11543 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11544 				   struct bpf_insn *insn,
11545 				   const struct bpf_reg_state *ptr_reg,
11546 				   const struct bpf_reg_state *off_reg)
11547 {
11548 	struct bpf_verifier_state *vstate = env->cur_state;
11549 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11550 	struct bpf_reg_state *regs = state->regs, *dst_reg;
11551 	bool known = tnum_is_const(off_reg->var_off);
11552 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11553 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11554 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11555 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11556 	struct bpf_sanitize_info info = {};
11557 	u8 opcode = BPF_OP(insn->code);
11558 	u32 dst = insn->dst_reg;
11559 	int ret;
11560 
11561 	dst_reg = &regs[dst];
11562 
11563 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11564 	    smin_val > smax_val || umin_val > umax_val) {
11565 		/* Taint dst register if offset had invalid bounds derived from
11566 		 * e.g. dead branches.
11567 		 */
11568 		__mark_reg_unknown(env, dst_reg);
11569 		return 0;
11570 	}
11571 
11572 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
11573 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
11574 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11575 			__mark_reg_unknown(env, dst_reg);
11576 			return 0;
11577 		}
11578 
11579 		verbose(env,
11580 			"R%d 32-bit pointer arithmetic prohibited\n",
11581 			dst);
11582 		return -EACCES;
11583 	}
11584 
11585 	if (ptr_reg->type & PTR_MAYBE_NULL) {
11586 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11587 			dst, reg_type_str(env, ptr_reg->type));
11588 		return -EACCES;
11589 	}
11590 
11591 	switch (base_type(ptr_reg->type)) {
11592 	case CONST_PTR_TO_MAP:
11593 		/* smin_val represents the known value */
11594 		if (known && smin_val == 0 && opcode == BPF_ADD)
11595 			break;
11596 		fallthrough;
11597 	case PTR_TO_PACKET_END:
11598 	case PTR_TO_SOCKET:
11599 	case PTR_TO_SOCK_COMMON:
11600 	case PTR_TO_TCP_SOCK:
11601 	case PTR_TO_XDP_SOCK:
11602 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11603 			dst, reg_type_str(env, ptr_reg->type));
11604 		return -EACCES;
11605 	default:
11606 		break;
11607 	}
11608 
11609 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11610 	 * The id may be overwritten later if we create a new variable offset.
11611 	 */
11612 	dst_reg->type = ptr_reg->type;
11613 	dst_reg->id = ptr_reg->id;
11614 
11615 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11616 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11617 		return -EINVAL;
11618 
11619 	/* pointer types do not carry 32-bit bounds at the moment. */
11620 	__mark_reg32_unbounded(dst_reg);
11621 
11622 	if (sanitize_needed(opcode)) {
11623 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11624 				       &info, false);
11625 		if (ret < 0)
11626 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11627 	}
11628 
11629 	switch (opcode) {
11630 	case BPF_ADD:
11631 		/* We can take a fixed offset as long as it doesn't overflow
11632 		 * the s32 'off' field
11633 		 */
11634 		if (known && (ptr_reg->off + smin_val ==
11635 			      (s64)(s32)(ptr_reg->off + smin_val))) {
11636 			/* pointer += K.  Accumulate it into fixed offset */
11637 			dst_reg->smin_value = smin_ptr;
11638 			dst_reg->smax_value = smax_ptr;
11639 			dst_reg->umin_value = umin_ptr;
11640 			dst_reg->umax_value = umax_ptr;
11641 			dst_reg->var_off = ptr_reg->var_off;
11642 			dst_reg->off = ptr_reg->off + smin_val;
11643 			dst_reg->raw = ptr_reg->raw;
11644 			break;
11645 		}
11646 		/* A new variable offset is created.  Note that off_reg->off
11647 		 * == 0, since it's a scalar.
11648 		 * dst_reg gets the pointer type and since some positive
11649 		 * integer value was added to the pointer, give it a new 'id'
11650 		 * if it's a PTR_TO_PACKET.
11651 		 * this creates a new 'base' pointer, off_reg (variable) gets
11652 		 * added into the variable offset, and we copy the fixed offset
11653 		 * from ptr_reg.
11654 		 */
11655 		if (signed_add_overflows(smin_ptr, smin_val) ||
11656 		    signed_add_overflows(smax_ptr, smax_val)) {
11657 			dst_reg->smin_value = S64_MIN;
11658 			dst_reg->smax_value = S64_MAX;
11659 		} else {
11660 			dst_reg->smin_value = smin_ptr + smin_val;
11661 			dst_reg->smax_value = smax_ptr + smax_val;
11662 		}
11663 		if (umin_ptr + umin_val < umin_ptr ||
11664 		    umax_ptr + umax_val < umax_ptr) {
11665 			dst_reg->umin_value = 0;
11666 			dst_reg->umax_value = U64_MAX;
11667 		} else {
11668 			dst_reg->umin_value = umin_ptr + umin_val;
11669 			dst_reg->umax_value = umax_ptr + umax_val;
11670 		}
11671 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11672 		dst_reg->off = ptr_reg->off;
11673 		dst_reg->raw = ptr_reg->raw;
11674 		if (reg_is_pkt_pointer(ptr_reg)) {
11675 			dst_reg->id = ++env->id_gen;
11676 			/* something was added to pkt_ptr, set range to zero */
11677 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11678 		}
11679 		break;
11680 	case BPF_SUB:
11681 		if (dst_reg == off_reg) {
11682 			/* scalar -= pointer.  Creates an unknown scalar */
11683 			verbose(env, "R%d tried to subtract pointer from scalar\n",
11684 				dst);
11685 			return -EACCES;
11686 		}
11687 		/* We don't allow subtraction from FP, because (according to
11688 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
11689 		 * be able to deal with it.
11690 		 */
11691 		if (ptr_reg->type == PTR_TO_STACK) {
11692 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
11693 				dst);
11694 			return -EACCES;
11695 		}
11696 		if (known && (ptr_reg->off - smin_val ==
11697 			      (s64)(s32)(ptr_reg->off - smin_val))) {
11698 			/* pointer -= K.  Subtract it from fixed offset */
11699 			dst_reg->smin_value = smin_ptr;
11700 			dst_reg->smax_value = smax_ptr;
11701 			dst_reg->umin_value = umin_ptr;
11702 			dst_reg->umax_value = umax_ptr;
11703 			dst_reg->var_off = ptr_reg->var_off;
11704 			dst_reg->id = ptr_reg->id;
11705 			dst_reg->off = ptr_reg->off - smin_val;
11706 			dst_reg->raw = ptr_reg->raw;
11707 			break;
11708 		}
11709 		/* A new variable offset is created.  If the subtrahend is known
11710 		 * nonnegative, then any reg->range we had before is still good.
11711 		 */
11712 		if (signed_sub_overflows(smin_ptr, smax_val) ||
11713 		    signed_sub_overflows(smax_ptr, smin_val)) {
11714 			/* Overflow possible, we know nothing */
11715 			dst_reg->smin_value = S64_MIN;
11716 			dst_reg->smax_value = S64_MAX;
11717 		} else {
11718 			dst_reg->smin_value = smin_ptr - smax_val;
11719 			dst_reg->smax_value = smax_ptr - smin_val;
11720 		}
11721 		if (umin_ptr < umax_val) {
11722 			/* Overflow possible, we know nothing */
11723 			dst_reg->umin_value = 0;
11724 			dst_reg->umax_value = U64_MAX;
11725 		} else {
11726 			/* Cannot overflow (as long as bounds are consistent) */
11727 			dst_reg->umin_value = umin_ptr - umax_val;
11728 			dst_reg->umax_value = umax_ptr - umin_val;
11729 		}
11730 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11731 		dst_reg->off = ptr_reg->off;
11732 		dst_reg->raw = ptr_reg->raw;
11733 		if (reg_is_pkt_pointer(ptr_reg)) {
11734 			dst_reg->id = ++env->id_gen;
11735 			/* something was added to pkt_ptr, set range to zero */
11736 			if (smin_val < 0)
11737 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11738 		}
11739 		break;
11740 	case BPF_AND:
11741 	case BPF_OR:
11742 	case BPF_XOR:
11743 		/* bitwise ops on pointers are troublesome, prohibit. */
11744 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11745 			dst, bpf_alu_string[opcode >> 4]);
11746 		return -EACCES;
11747 	default:
11748 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
11749 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11750 			dst, bpf_alu_string[opcode >> 4]);
11751 		return -EACCES;
11752 	}
11753 
11754 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11755 		return -EINVAL;
11756 	reg_bounds_sync(dst_reg);
11757 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11758 		return -EACCES;
11759 	if (sanitize_needed(opcode)) {
11760 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11761 				       &info, true);
11762 		if (ret < 0)
11763 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11764 	}
11765 
11766 	return 0;
11767 }
11768 
11769 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11770 				 struct bpf_reg_state *src_reg)
11771 {
11772 	s32 smin_val = src_reg->s32_min_value;
11773 	s32 smax_val = src_reg->s32_max_value;
11774 	u32 umin_val = src_reg->u32_min_value;
11775 	u32 umax_val = src_reg->u32_max_value;
11776 
11777 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11778 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11779 		dst_reg->s32_min_value = S32_MIN;
11780 		dst_reg->s32_max_value = S32_MAX;
11781 	} else {
11782 		dst_reg->s32_min_value += smin_val;
11783 		dst_reg->s32_max_value += smax_val;
11784 	}
11785 	if (dst_reg->u32_min_value + umin_val < umin_val ||
11786 	    dst_reg->u32_max_value + umax_val < umax_val) {
11787 		dst_reg->u32_min_value = 0;
11788 		dst_reg->u32_max_value = U32_MAX;
11789 	} else {
11790 		dst_reg->u32_min_value += umin_val;
11791 		dst_reg->u32_max_value += umax_val;
11792 	}
11793 }
11794 
11795 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11796 			       struct bpf_reg_state *src_reg)
11797 {
11798 	s64 smin_val = src_reg->smin_value;
11799 	s64 smax_val = src_reg->smax_value;
11800 	u64 umin_val = src_reg->umin_value;
11801 	u64 umax_val = src_reg->umax_value;
11802 
11803 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11804 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
11805 		dst_reg->smin_value = S64_MIN;
11806 		dst_reg->smax_value = S64_MAX;
11807 	} else {
11808 		dst_reg->smin_value += smin_val;
11809 		dst_reg->smax_value += smax_val;
11810 	}
11811 	if (dst_reg->umin_value + umin_val < umin_val ||
11812 	    dst_reg->umax_value + umax_val < umax_val) {
11813 		dst_reg->umin_value = 0;
11814 		dst_reg->umax_value = U64_MAX;
11815 	} else {
11816 		dst_reg->umin_value += umin_val;
11817 		dst_reg->umax_value += umax_val;
11818 	}
11819 }
11820 
11821 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11822 				 struct bpf_reg_state *src_reg)
11823 {
11824 	s32 smin_val = src_reg->s32_min_value;
11825 	s32 smax_val = src_reg->s32_max_value;
11826 	u32 umin_val = src_reg->u32_min_value;
11827 	u32 umax_val = src_reg->u32_max_value;
11828 
11829 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11830 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11831 		/* Overflow possible, we know nothing */
11832 		dst_reg->s32_min_value = S32_MIN;
11833 		dst_reg->s32_max_value = S32_MAX;
11834 	} else {
11835 		dst_reg->s32_min_value -= smax_val;
11836 		dst_reg->s32_max_value -= smin_val;
11837 	}
11838 	if (dst_reg->u32_min_value < umax_val) {
11839 		/* Overflow possible, we know nothing */
11840 		dst_reg->u32_min_value = 0;
11841 		dst_reg->u32_max_value = U32_MAX;
11842 	} else {
11843 		/* Cannot overflow (as long as bounds are consistent) */
11844 		dst_reg->u32_min_value -= umax_val;
11845 		dst_reg->u32_max_value -= umin_val;
11846 	}
11847 }
11848 
11849 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11850 			       struct bpf_reg_state *src_reg)
11851 {
11852 	s64 smin_val = src_reg->smin_value;
11853 	s64 smax_val = src_reg->smax_value;
11854 	u64 umin_val = src_reg->umin_value;
11855 	u64 umax_val = src_reg->umax_value;
11856 
11857 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11858 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11859 		/* Overflow possible, we know nothing */
11860 		dst_reg->smin_value = S64_MIN;
11861 		dst_reg->smax_value = S64_MAX;
11862 	} else {
11863 		dst_reg->smin_value -= smax_val;
11864 		dst_reg->smax_value -= smin_val;
11865 	}
11866 	if (dst_reg->umin_value < umax_val) {
11867 		/* Overflow possible, we know nothing */
11868 		dst_reg->umin_value = 0;
11869 		dst_reg->umax_value = U64_MAX;
11870 	} else {
11871 		/* Cannot overflow (as long as bounds are consistent) */
11872 		dst_reg->umin_value -= umax_val;
11873 		dst_reg->umax_value -= umin_val;
11874 	}
11875 }
11876 
11877 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11878 				 struct bpf_reg_state *src_reg)
11879 {
11880 	s32 smin_val = src_reg->s32_min_value;
11881 	u32 umin_val = src_reg->u32_min_value;
11882 	u32 umax_val = src_reg->u32_max_value;
11883 
11884 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11885 		/* Ain't nobody got time to multiply that sign */
11886 		__mark_reg32_unbounded(dst_reg);
11887 		return;
11888 	}
11889 	/* Both values are positive, so we can work with unsigned and
11890 	 * copy the result to signed (unless it exceeds S32_MAX).
11891 	 */
11892 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11893 		/* Potential overflow, we know nothing */
11894 		__mark_reg32_unbounded(dst_reg);
11895 		return;
11896 	}
11897 	dst_reg->u32_min_value *= umin_val;
11898 	dst_reg->u32_max_value *= umax_val;
11899 	if (dst_reg->u32_max_value > S32_MAX) {
11900 		/* Overflow possible, we know nothing */
11901 		dst_reg->s32_min_value = S32_MIN;
11902 		dst_reg->s32_max_value = S32_MAX;
11903 	} else {
11904 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11905 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11906 	}
11907 }
11908 
11909 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11910 			       struct bpf_reg_state *src_reg)
11911 {
11912 	s64 smin_val = src_reg->smin_value;
11913 	u64 umin_val = src_reg->umin_value;
11914 	u64 umax_val = src_reg->umax_value;
11915 
11916 	if (smin_val < 0 || dst_reg->smin_value < 0) {
11917 		/* Ain't nobody got time to multiply that sign */
11918 		__mark_reg64_unbounded(dst_reg);
11919 		return;
11920 	}
11921 	/* Both values are positive, so we can work with unsigned and
11922 	 * copy the result to signed (unless it exceeds S64_MAX).
11923 	 */
11924 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11925 		/* Potential overflow, we know nothing */
11926 		__mark_reg64_unbounded(dst_reg);
11927 		return;
11928 	}
11929 	dst_reg->umin_value *= umin_val;
11930 	dst_reg->umax_value *= umax_val;
11931 	if (dst_reg->umax_value > S64_MAX) {
11932 		/* Overflow possible, we know nothing */
11933 		dst_reg->smin_value = S64_MIN;
11934 		dst_reg->smax_value = S64_MAX;
11935 	} else {
11936 		dst_reg->smin_value = dst_reg->umin_value;
11937 		dst_reg->smax_value = dst_reg->umax_value;
11938 	}
11939 }
11940 
11941 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11942 				 struct bpf_reg_state *src_reg)
11943 {
11944 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
11945 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11946 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11947 	s32 smin_val = src_reg->s32_min_value;
11948 	u32 umax_val = src_reg->u32_max_value;
11949 
11950 	if (src_known && dst_known) {
11951 		__mark_reg32_known(dst_reg, var32_off.value);
11952 		return;
11953 	}
11954 
11955 	/* We get our minimum from the var_off, since that's inherently
11956 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
11957 	 */
11958 	dst_reg->u32_min_value = var32_off.value;
11959 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11960 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11961 		/* Lose signed bounds when ANDing negative numbers,
11962 		 * ain't nobody got time for that.
11963 		 */
11964 		dst_reg->s32_min_value = S32_MIN;
11965 		dst_reg->s32_max_value = S32_MAX;
11966 	} else {
11967 		/* ANDing two positives gives a positive, so safe to
11968 		 * cast result into s64.
11969 		 */
11970 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11971 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11972 	}
11973 }
11974 
11975 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11976 			       struct bpf_reg_state *src_reg)
11977 {
11978 	bool src_known = tnum_is_const(src_reg->var_off);
11979 	bool dst_known = tnum_is_const(dst_reg->var_off);
11980 	s64 smin_val = src_reg->smin_value;
11981 	u64 umax_val = src_reg->umax_value;
11982 
11983 	if (src_known && dst_known) {
11984 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11985 		return;
11986 	}
11987 
11988 	/* We get our minimum from the var_off, since that's inherently
11989 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
11990 	 */
11991 	dst_reg->umin_value = dst_reg->var_off.value;
11992 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11993 	if (dst_reg->smin_value < 0 || smin_val < 0) {
11994 		/* Lose signed bounds when ANDing negative numbers,
11995 		 * ain't nobody got time for that.
11996 		 */
11997 		dst_reg->smin_value = S64_MIN;
11998 		dst_reg->smax_value = S64_MAX;
11999 	} else {
12000 		/* ANDing two positives gives a positive, so safe to
12001 		 * cast result into s64.
12002 		 */
12003 		dst_reg->smin_value = dst_reg->umin_value;
12004 		dst_reg->smax_value = dst_reg->umax_value;
12005 	}
12006 	/* We may learn something more from the var_off */
12007 	__update_reg_bounds(dst_reg);
12008 }
12009 
12010 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12011 				struct bpf_reg_state *src_reg)
12012 {
12013 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12014 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12015 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12016 	s32 smin_val = src_reg->s32_min_value;
12017 	u32 umin_val = src_reg->u32_min_value;
12018 
12019 	if (src_known && dst_known) {
12020 		__mark_reg32_known(dst_reg, var32_off.value);
12021 		return;
12022 	}
12023 
12024 	/* We get our maximum from the var_off, and our minimum is the
12025 	 * maximum of the operands' minima
12026 	 */
12027 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12028 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12029 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12030 		/* Lose signed bounds when ORing negative numbers,
12031 		 * ain't nobody got time for that.
12032 		 */
12033 		dst_reg->s32_min_value = S32_MIN;
12034 		dst_reg->s32_max_value = S32_MAX;
12035 	} else {
12036 		/* ORing two positives gives a positive, so safe to
12037 		 * cast result into s64.
12038 		 */
12039 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12040 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12041 	}
12042 }
12043 
12044 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12045 			      struct bpf_reg_state *src_reg)
12046 {
12047 	bool src_known = tnum_is_const(src_reg->var_off);
12048 	bool dst_known = tnum_is_const(dst_reg->var_off);
12049 	s64 smin_val = src_reg->smin_value;
12050 	u64 umin_val = src_reg->umin_value;
12051 
12052 	if (src_known && dst_known) {
12053 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12054 		return;
12055 	}
12056 
12057 	/* We get our maximum from the var_off, and our minimum is the
12058 	 * maximum of the operands' minima
12059 	 */
12060 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12061 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12062 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12063 		/* Lose signed bounds when ORing negative numbers,
12064 		 * ain't nobody got time for that.
12065 		 */
12066 		dst_reg->smin_value = S64_MIN;
12067 		dst_reg->smax_value = S64_MAX;
12068 	} else {
12069 		/* ORing two positives gives a positive, so safe to
12070 		 * cast result into s64.
12071 		 */
12072 		dst_reg->smin_value = dst_reg->umin_value;
12073 		dst_reg->smax_value = dst_reg->umax_value;
12074 	}
12075 	/* We may learn something more from the var_off */
12076 	__update_reg_bounds(dst_reg);
12077 }
12078 
12079 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12080 				 struct bpf_reg_state *src_reg)
12081 {
12082 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12083 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12084 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12085 	s32 smin_val = src_reg->s32_min_value;
12086 
12087 	if (src_known && dst_known) {
12088 		__mark_reg32_known(dst_reg, var32_off.value);
12089 		return;
12090 	}
12091 
12092 	/* We get both minimum and maximum from the var32_off. */
12093 	dst_reg->u32_min_value = var32_off.value;
12094 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12095 
12096 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12097 		/* XORing two positive sign numbers gives a positive,
12098 		 * so safe to cast u32 result into s32.
12099 		 */
12100 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12101 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12102 	} else {
12103 		dst_reg->s32_min_value = S32_MIN;
12104 		dst_reg->s32_max_value = S32_MAX;
12105 	}
12106 }
12107 
12108 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12109 			       struct bpf_reg_state *src_reg)
12110 {
12111 	bool src_known = tnum_is_const(src_reg->var_off);
12112 	bool dst_known = tnum_is_const(dst_reg->var_off);
12113 	s64 smin_val = src_reg->smin_value;
12114 
12115 	if (src_known && dst_known) {
12116 		/* dst_reg->var_off.value has been updated earlier */
12117 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12118 		return;
12119 	}
12120 
12121 	/* We get both minimum and maximum from the var_off. */
12122 	dst_reg->umin_value = dst_reg->var_off.value;
12123 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12124 
12125 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12126 		/* XORing two positive sign numbers gives a positive,
12127 		 * so safe to cast u64 result into s64.
12128 		 */
12129 		dst_reg->smin_value = dst_reg->umin_value;
12130 		dst_reg->smax_value = dst_reg->umax_value;
12131 	} else {
12132 		dst_reg->smin_value = S64_MIN;
12133 		dst_reg->smax_value = S64_MAX;
12134 	}
12135 
12136 	__update_reg_bounds(dst_reg);
12137 }
12138 
12139 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12140 				   u64 umin_val, u64 umax_val)
12141 {
12142 	/* We lose all sign bit information (except what we can pick
12143 	 * up from var_off)
12144 	 */
12145 	dst_reg->s32_min_value = S32_MIN;
12146 	dst_reg->s32_max_value = S32_MAX;
12147 	/* If we might shift our top bit out, then we know nothing */
12148 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12149 		dst_reg->u32_min_value = 0;
12150 		dst_reg->u32_max_value = U32_MAX;
12151 	} else {
12152 		dst_reg->u32_min_value <<= umin_val;
12153 		dst_reg->u32_max_value <<= umax_val;
12154 	}
12155 }
12156 
12157 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12158 				 struct bpf_reg_state *src_reg)
12159 {
12160 	u32 umax_val = src_reg->u32_max_value;
12161 	u32 umin_val = src_reg->u32_min_value;
12162 	/* u32 alu operation will zext upper bits */
12163 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12164 
12165 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12166 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12167 	/* Not required but being careful mark reg64 bounds as unknown so
12168 	 * that we are forced to pick them up from tnum and zext later and
12169 	 * if some path skips this step we are still safe.
12170 	 */
12171 	__mark_reg64_unbounded(dst_reg);
12172 	__update_reg32_bounds(dst_reg);
12173 }
12174 
12175 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12176 				   u64 umin_val, u64 umax_val)
12177 {
12178 	/* Special case <<32 because it is a common compiler pattern to sign
12179 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12180 	 * positive we know this shift will also be positive so we can track
12181 	 * bounds correctly. Otherwise we lose all sign bit information except
12182 	 * what we can pick up from var_off. Perhaps we can generalize this
12183 	 * later to shifts of any length.
12184 	 */
12185 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12186 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12187 	else
12188 		dst_reg->smax_value = S64_MAX;
12189 
12190 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12191 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12192 	else
12193 		dst_reg->smin_value = S64_MIN;
12194 
12195 	/* If we might shift our top bit out, then we know nothing */
12196 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12197 		dst_reg->umin_value = 0;
12198 		dst_reg->umax_value = U64_MAX;
12199 	} else {
12200 		dst_reg->umin_value <<= umin_val;
12201 		dst_reg->umax_value <<= umax_val;
12202 	}
12203 }
12204 
12205 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12206 			       struct bpf_reg_state *src_reg)
12207 {
12208 	u64 umax_val = src_reg->umax_value;
12209 	u64 umin_val = src_reg->umin_value;
12210 
12211 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12212 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12213 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12214 
12215 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12216 	/* We may learn something more from the var_off */
12217 	__update_reg_bounds(dst_reg);
12218 }
12219 
12220 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12221 				 struct bpf_reg_state *src_reg)
12222 {
12223 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12224 	u32 umax_val = src_reg->u32_max_value;
12225 	u32 umin_val = src_reg->u32_min_value;
12226 
12227 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12228 	 * be negative, then either:
12229 	 * 1) src_reg might be zero, so the sign bit of the result is
12230 	 *    unknown, so we lose our signed bounds
12231 	 * 2) it's known negative, thus the unsigned bounds capture the
12232 	 *    signed bounds
12233 	 * 3) the signed bounds cross zero, so they tell us nothing
12234 	 *    about the result
12235 	 * If the value in dst_reg is known nonnegative, then again the
12236 	 * unsigned bounds capture the signed bounds.
12237 	 * Thus, in all cases it suffices to blow away our signed bounds
12238 	 * and rely on inferring new ones from the unsigned bounds and
12239 	 * var_off of the result.
12240 	 */
12241 	dst_reg->s32_min_value = S32_MIN;
12242 	dst_reg->s32_max_value = S32_MAX;
12243 
12244 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12245 	dst_reg->u32_min_value >>= umax_val;
12246 	dst_reg->u32_max_value >>= umin_val;
12247 
12248 	__mark_reg64_unbounded(dst_reg);
12249 	__update_reg32_bounds(dst_reg);
12250 }
12251 
12252 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12253 			       struct bpf_reg_state *src_reg)
12254 {
12255 	u64 umax_val = src_reg->umax_value;
12256 	u64 umin_val = src_reg->umin_value;
12257 
12258 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12259 	 * be negative, then either:
12260 	 * 1) src_reg might be zero, so the sign bit of the result is
12261 	 *    unknown, so we lose our signed bounds
12262 	 * 2) it's known negative, thus the unsigned bounds capture the
12263 	 *    signed bounds
12264 	 * 3) the signed bounds cross zero, so they tell us nothing
12265 	 *    about the result
12266 	 * If the value in dst_reg is known nonnegative, then again the
12267 	 * unsigned bounds capture the signed bounds.
12268 	 * Thus, in all cases it suffices to blow away our signed bounds
12269 	 * and rely on inferring new ones from the unsigned bounds and
12270 	 * var_off of the result.
12271 	 */
12272 	dst_reg->smin_value = S64_MIN;
12273 	dst_reg->smax_value = S64_MAX;
12274 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12275 	dst_reg->umin_value >>= umax_val;
12276 	dst_reg->umax_value >>= umin_val;
12277 
12278 	/* Its not easy to operate on alu32 bounds here because it depends
12279 	 * on bits being shifted in. Take easy way out and mark unbounded
12280 	 * so we can recalculate later from tnum.
12281 	 */
12282 	__mark_reg32_unbounded(dst_reg);
12283 	__update_reg_bounds(dst_reg);
12284 }
12285 
12286 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12287 				  struct bpf_reg_state *src_reg)
12288 {
12289 	u64 umin_val = src_reg->u32_min_value;
12290 
12291 	/* Upon reaching here, src_known is true and
12292 	 * umax_val is equal to umin_val.
12293 	 */
12294 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12295 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12296 
12297 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12298 
12299 	/* blow away the dst_reg umin_value/umax_value and rely on
12300 	 * dst_reg var_off to refine the result.
12301 	 */
12302 	dst_reg->u32_min_value = 0;
12303 	dst_reg->u32_max_value = U32_MAX;
12304 
12305 	__mark_reg64_unbounded(dst_reg);
12306 	__update_reg32_bounds(dst_reg);
12307 }
12308 
12309 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12310 				struct bpf_reg_state *src_reg)
12311 {
12312 	u64 umin_val = src_reg->umin_value;
12313 
12314 	/* Upon reaching here, src_known is true and umax_val is equal
12315 	 * to umin_val.
12316 	 */
12317 	dst_reg->smin_value >>= umin_val;
12318 	dst_reg->smax_value >>= umin_val;
12319 
12320 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12321 
12322 	/* blow away the dst_reg umin_value/umax_value and rely on
12323 	 * dst_reg var_off to refine the result.
12324 	 */
12325 	dst_reg->umin_value = 0;
12326 	dst_reg->umax_value = U64_MAX;
12327 
12328 	/* Its not easy to operate on alu32 bounds here because it depends
12329 	 * on bits being shifted in from upper 32-bits. Take easy way out
12330 	 * and mark unbounded so we can recalculate later from tnum.
12331 	 */
12332 	__mark_reg32_unbounded(dst_reg);
12333 	__update_reg_bounds(dst_reg);
12334 }
12335 
12336 /* WARNING: This function does calculations on 64-bit values, but the actual
12337  * execution may occur on 32-bit values. Therefore, things like bitshifts
12338  * need extra checks in the 32-bit case.
12339  */
12340 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12341 				      struct bpf_insn *insn,
12342 				      struct bpf_reg_state *dst_reg,
12343 				      struct bpf_reg_state src_reg)
12344 {
12345 	struct bpf_reg_state *regs = cur_regs(env);
12346 	u8 opcode = BPF_OP(insn->code);
12347 	bool src_known;
12348 	s64 smin_val, smax_val;
12349 	u64 umin_val, umax_val;
12350 	s32 s32_min_val, s32_max_val;
12351 	u32 u32_min_val, u32_max_val;
12352 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12353 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12354 	int ret;
12355 
12356 	smin_val = src_reg.smin_value;
12357 	smax_val = src_reg.smax_value;
12358 	umin_val = src_reg.umin_value;
12359 	umax_val = src_reg.umax_value;
12360 
12361 	s32_min_val = src_reg.s32_min_value;
12362 	s32_max_val = src_reg.s32_max_value;
12363 	u32_min_val = src_reg.u32_min_value;
12364 	u32_max_val = src_reg.u32_max_value;
12365 
12366 	if (alu32) {
12367 		src_known = tnum_subreg_is_const(src_reg.var_off);
12368 		if ((src_known &&
12369 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12370 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12371 			/* Taint dst register if offset had invalid bounds
12372 			 * derived from e.g. dead branches.
12373 			 */
12374 			__mark_reg_unknown(env, dst_reg);
12375 			return 0;
12376 		}
12377 	} else {
12378 		src_known = tnum_is_const(src_reg.var_off);
12379 		if ((src_known &&
12380 		     (smin_val != smax_val || umin_val != umax_val)) ||
12381 		    smin_val > smax_val || umin_val > umax_val) {
12382 			/* Taint dst register if offset had invalid bounds
12383 			 * derived from e.g. dead branches.
12384 			 */
12385 			__mark_reg_unknown(env, dst_reg);
12386 			return 0;
12387 		}
12388 	}
12389 
12390 	if (!src_known &&
12391 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12392 		__mark_reg_unknown(env, dst_reg);
12393 		return 0;
12394 	}
12395 
12396 	if (sanitize_needed(opcode)) {
12397 		ret = sanitize_val_alu(env, insn);
12398 		if (ret < 0)
12399 			return sanitize_err(env, insn, ret, NULL, NULL);
12400 	}
12401 
12402 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12403 	 * There are two classes of instructions: The first class we track both
12404 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12405 	 * greatest amount of precision when alu operations are mixed with jmp32
12406 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12407 	 * and BPF_OR. This is possible because these ops have fairly easy to
12408 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12409 	 * See alu32 verifier tests for examples. The second class of
12410 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12411 	 * with regards to tracking sign/unsigned bounds because the bits may
12412 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12413 	 * the reg unbounded in the subreg bound space and use the resulting
12414 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12415 	 */
12416 	switch (opcode) {
12417 	case BPF_ADD:
12418 		scalar32_min_max_add(dst_reg, &src_reg);
12419 		scalar_min_max_add(dst_reg, &src_reg);
12420 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12421 		break;
12422 	case BPF_SUB:
12423 		scalar32_min_max_sub(dst_reg, &src_reg);
12424 		scalar_min_max_sub(dst_reg, &src_reg);
12425 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12426 		break;
12427 	case BPF_MUL:
12428 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12429 		scalar32_min_max_mul(dst_reg, &src_reg);
12430 		scalar_min_max_mul(dst_reg, &src_reg);
12431 		break;
12432 	case BPF_AND:
12433 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12434 		scalar32_min_max_and(dst_reg, &src_reg);
12435 		scalar_min_max_and(dst_reg, &src_reg);
12436 		break;
12437 	case BPF_OR:
12438 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12439 		scalar32_min_max_or(dst_reg, &src_reg);
12440 		scalar_min_max_or(dst_reg, &src_reg);
12441 		break;
12442 	case BPF_XOR:
12443 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12444 		scalar32_min_max_xor(dst_reg, &src_reg);
12445 		scalar_min_max_xor(dst_reg, &src_reg);
12446 		break;
12447 	case BPF_LSH:
12448 		if (umax_val >= insn_bitness) {
12449 			/* Shifts greater than 31 or 63 are undefined.
12450 			 * This includes shifts by a negative number.
12451 			 */
12452 			mark_reg_unknown(env, regs, insn->dst_reg);
12453 			break;
12454 		}
12455 		if (alu32)
12456 			scalar32_min_max_lsh(dst_reg, &src_reg);
12457 		else
12458 			scalar_min_max_lsh(dst_reg, &src_reg);
12459 		break;
12460 	case BPF_RSH:
12461 		if (umax_val >= insn_bitness) {
12462 			/* Shifts greater than 31 or 63 are undefined.
12463 			 * This includes shifts by a negative number.
12464 			 */
12465 			mark_reg_unknown(env, regs, insn->dst_reg);
12466 			break;
12467 		}
12468 		if (alu32)
12469 			scalar32_min_max_rsh(dst_reg, &src_reg);
12470 		else
12471 			scalar_min_max_rsh(dst_reg, &src_reg);
12472 		break;
12473 	case BPF_ARSH:
12474 		if (umax_val >= insn_bitness) {
12475 			/* Shifts greater than 31 or 63 are undefined.
12476 			 * This includes shifts by a negative number.
12477 			 */
12478 			mark_reg_unknown(env, regs, insn->dst_reg);
12479 			break;
12480 		}
12481 		if (alu32)
12482 			scalar32_min_max_arsh(dst_reg, &src_reg);
12483 		else
12484 			scalar_min_max_arsh(dst_reg, &src_reg);
12485 		break;
12486 	default:
12487 		mark_reg_unknown(env, regs, insn->dst_reg);
12488 		break;
12489 	}
12490 
12491 	/* ALU32 ops are zero extended into 64bit register */
12492 	if (alu32)
12493 		zext_32_to_64(dst_reg);
12494 	reg_bounds_sync(dst_reg);
12495 	return 0;
12496 }
12497 
12498 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12499  * and var_off.
12500  */
12501 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12502 				   struct bpf_insn *insn)
12503 {
12504 	struct bpf_verifier_state *vstate = env->cur_state;
12505 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12506 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12507 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12508 	u8 opcode = BPF_OP(insn->code);
12509 	int err;
12510 
12511 	dst_reg = &regs[insn->dst_reg];
12512 	src_reg = NULL;
12513 	if (dst_reg->type != SCALAR_VALUE)
12514 		ptr_reg = dst_reg;
12515 	else
12516 		/* Make sure ID is cleared otherwise dst_reg min/max could be
12517 		 * incorrectly propagated into other registers by find_equal_scalars()
12518 		 */
12519 		dst_reg->id = 0;
12520 	if (BPF_SRC(insn->code) == BPF_X) {
12521 		src_reg = &regs[insn->src_reg];
12522 		if (src_reg->type != SCALAR_VALUE) {
12523 			if (dst_reg->type != SCALAR_VALUE) {
12524 				/* Combining two pointers by any ALU op yields
12525 				 * an arbitrary scalar. Disallow all math except
12526 				 * pointer subtraction
12527 				 */
12528 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12529 					mark_reg_unknown(env, regs, insn->dst_reg);
12530 					return 0;
12531 				}
12532 				verbose(env, "R%d pointer %s pointer prohibited\n",
12533 					insn->dst_reg,
12534 					bpf_alu_string[opcode >> 4]);
12535 				return -EACCES;
12536 			} else {
12537 				/* scalar += pointer
12538 				 * This is legal, but we have to reverse our
12539 				 * src/dest handling in computing the range
12540 				 */
12541 				err = mark_chain_precision(env, insn->dst_reg);
12542 				if (err)
12543 					return err;
12544 				return adjust_ptr_min_max_vals(env, insn,
12545 							       src_reg, dst_reg);
12546 			}
12547 		} else if (ptr_reg) {
12548 			/* pointer += scalar */
12549 			err = mark_chain_precision(env, insn->src_reg);
12550 			if (err)
12551 				return err;
12552 			return adjust_ptr_min_max_vals(env, insn,
12553 						       dst_reg, src_reg);
12554 		} else if (dst_reg->precise) {
12555 			/* if dst_reg is precise, src_reg should be precise as well */
12556 			err = mark_chain_precision(env, insn->src_reg);
12557 			if (err)
12558 				return err;
12559 		}
12560 	} else {
12561 		/* Pretend the src is a reg with a known value, since we only
12562 		 * need to be able to read from this state.
12563 		 */
12564 		off_reg.type = SCALAR_VALUE;
12565 		__mark_reg_known(&off_reg, insn->imm);
12566 		src_reg = &off_reg;
12567 		if (ptr_reg) /* pointer += K */
12568 			return adjust_ptr_min_max_vals(env, insn,
12569 						       ptr_reg, src_reg);
12570 	}
12571 
12572 	/* Got here implies adding two SCALAR_VALUEs */
12573 	if (WARN_ON_ONCE(ptr_reg)) {
12574 		print_verifier_state(env, state, true);
12575 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
12576 		return -EINVAL;
12577 	}
12578 	if (WARN_ON(!src_reg)) {
12579 		print_verifier_state(env, state, true);
12580 		verbose(env, "verifier internal error: no src_reg\n");
12581 		return -EINVAL;
12582 	}
12583 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12584 }
12585 
12586 /* check validity of 32-bit and 64-bit arithmetic operations */
12587 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12588 {
12589 	struct bpf_reg_state *regs = cur_regs(env);
12590 	u8 opcode = BPF_OP(insn->code);
12591 	int err;
12592 
12593 	if (opcode == BPF_END || opcode == BPF_NEG) {
12594 		if (opcode == BPF_NEG) {
12595 			if (BPF_SRC(insn->code) != BPF_K ||
12596 			    insn->src_reg != BPF_REG_0 ||
12597 			    insn->off != 0 || insn->imm != 0) {
12598 				verbose(env, "BPF_NEG uses reserved fields\n");
12599 				return -EINVAL;
12600 			}
12601 		} else {
12602 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12603 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12604 			    BPF_CLASS(insn->code) == BPF_ALU64) {
12605 				verbose(env, "BPF_END uses reserved fields\n");
12606 				return -EINVAL;
12607 			}
12608 		}
12609 
12610 		/* check src operand */
12611 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12612 		if (err)
12613 			return err;
12614 
12615 		if (is_pointer_value(env, insn->dst_reg)) {
12616 			verbose(env, "R%d pointer arithmetic prohibited\n",
12617 				insn->dst_reg);
12618 			return -EACCES;
12619 		}
12620 
12621 		/* check dest operand */
12622 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
12623 		if (err)
12624 			return err;
12625 
12626 	} else if (opcode == BPF_MOV) {
12627 
12628 		if (BPF_SRC(insn->code) == BPF_X) {
12629 			if (insn->imm != 0 || insn->off != 0) {
12630 				verbose(env, "BPF_MOV uses reserved fields\n");
12631 				return -EINVAL;
12632 			}
12633 
12634 			/* check src operand */
12635 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12636 			if (err)
12637 				return err;
12638 		} else {
12639 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12640 				verbose(env, "BPF_MOV uses reserved fields\n");
12641 				return -EINVAL;
12642 			}
12643 		}
12644 
12645 		/* check dest operand, mark as required later */
12646 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12647 		if (err)
12648 			return err;
12649 
12650 		if (BPF_SRC(insn->code) == BPF_X) {
12651 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
12652 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12653 
12654 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12655 				/* case: R1 = R2
12656 				 * copy register state to dest reg
12657 				 */
12658 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12659 					/* Assign src and dst registers the same ID
12660 					 * that will be used by find_equal_scalars()
12661 					 * to propagate min/max range.
12662 					 */
12663 					src_reg->id = ++env->id_gen;
12664 				copy_register_state(dst_reg, src_reg);
12665 				dst_reg->live |= REG_LIVE_WRITTEN;
12666 				dst_reg->subreg_def = DEF_NOT_SUBREG;
12667 			} else {
12668 				/* R1 = (u32) R2 */
12669 				if (is_pointer_value(env, insn->src_reg)) {
12670 					verbose(env,
12671 						"R%d partial copy of pointer\n",
12672 						insn->src_reg);
12673 					return -EACCES;
12674 				} else if (src_reg->type == SCALAR_VALUE) {
12675 					bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12676 
12677 					if (is_src_reg_u32 && !src_reg->id)
12678 						src_reg->id = ++env->id_gen;
12679 					copy_register_state(dst_reg, src_reg);
12680 					/* Make sure ID is cleared if src_reg is not in u32 range otherwise
12681 					 * dst_reg min/max could be incorrectly
12682 					 * propagated into src_reg by find_equal_scalars()
12683 					 */
12684 					if (!is_src_reg_u32)
12685 						dst_reg->id = 0;
12686 					dst_reg->live |= REG_LIVE_WRITTEN;
12687 					dst_reg->subreg_def = env->insn_idx + 1;
12688 				} else {
12689 					mark_reg_unknown(env, regs,
12690 							 insn->dst_reg);
12691 				}
12692 				zext_32_to_64(dst_reg);
12693 				reg_bounds_sync(dst_reg);
12694 			}
12695 		} else {
12696 			/* case: R = imm
12697 			 * remember the value we stored into this reg
12698 			 */
12699 			/* clear any state __mark_reg_known doesn't set */
12700 			mark_reg_unknown(env, regs, insn->dst_reg);
12701 			regs[insn->dst_reg].type = SCALAR_VALUE;
12702 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12703 				__mark_reg_known(regs + insn->dst_reg,
12704 						 insn->imm);
12705 			} else {
12706 				__mark_reg_known(regs + insn->dst_reg,
12707 						 (u32)insn->imm);
12708 			}
12709 		}
12710 
12711 	} else if (opcode > BPF_END) {
12712 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12713 		return -EINVAL;
12714 
12715 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
12716 
12717 		if (BPF_SRC(insn->code) == BPF_X) {
12718 			if (insn->imm != 0 || insn->off != 0) {
12719 				verbose(env, "BPF_ALU uses reserved fields\n");
12720 				return -EINVAL;
12721 			}
12722 			/* check src1 operand */
12723 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12724 			if (err)
12725 				return err;
12726 		} else {
12727 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12728 				verbose(env, "BPF_ALU uses reserved fields\n");
12729 				return -EINVAL;
12730 			}
12731 		}
12732 
12733 		/* check src2 operand */
12734 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12735 		if (err)
12736 			return err;
12737 
12738 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12739 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12740 			verbose(env, "div by zero\n");
12741 			return -EINVAL;
12742 		}
12743 
12744 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12745 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12746 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12747 
12748 			if (insn->imm < 0 || insn->imm >= size) {
12749 				verbose(env, "invalid shift %d\n", insn->imm);
12750 				return -EINVAL;
12751 			}
12752 		}
12753 
12754 		/* check dest operand */
12755 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12756 		if (err)
12757 			return err;
12758 
12759 		return adjust_reg_min_max_vals(env, insn);
12760 	}
12761 
12762 	return 0;
12763 }
12764 
12765 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12766 				   struct bpf_reg_state *dst_reg,
12767 				   enum bpf_reg_type type,
12768 				   bool range_right_open)
12769 {
12770 	struct bpf_func_state *state;
12771 	struct bpf_reg_state *reg;
12772 	int new_range;
12773 
12774 	if (dst_reg->off < 0 ||
12775 	    (dst_reg->off == 0 && range_right_open))
12776 		/* This doesn't give us any range */
12777 		return;
12778 
12779 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
12780 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12781 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
12782 		 * than pkt_end, but that's because it's also less than pkt.
12783 		 */
12784 		return;
12785 
12786 	new_range = dst_reg->off;
12787 	if (range_right_open)
12788 		new_range++;
12789 
12790 	/* Examples for register markings:
12791 	 *
12792 	 * pkt_data in dst register:
12793 	 *
12794 	 *   r2 = r3;
12795 	 *   r2 += 8;
12796 	 *   if (r2 > pkt_end) goto <handle exception>
12797 	 *   <access okay>
12798 	 *
12799 	 *   r2 = r3;
12800 	 *   r2 += 8;
12801 	 *   if (r2 < pkt_end) goto <access okay>
12802 	 *   <handle exception>
12803 	 *
12804 	 *   Where:
12805 	 *     r2 == dst_reg, pkt_end == src_reg
12806 	 *     r2=pkt(id=n,off=8,r=0)
12807 	 *     r3=pkt(id=n,off=0,r=0)
12808 	 *
12809 	 * pkt_data in src register:
12810 	 *
12811 	 *   r2 = r3;
12812 	 *   r2 += 8;
12813 	 *   if (pkt_end >= r2) goto <access okay>
12814 	 *   <handle exception>
12815 	 *
12816 	 *   r2 = r3;
12817 	 *   r2 += 8;
12818 	 *   if (pkt_end <= r2) goto <handle exception>
12819 	 *   <access okay>
12820 	 *
12821 	 *   Where:
12822 	 *     pkt_end == dst_reg, r2 == src_reg
12823 	 *     r2=pkt(id=n,off=8,r=0)
12824 	 *     r3=pkt(id=n,off=0,r=0)
12825 	 *
12826 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12827 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12828 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
12829 	 * the check.
12830 	 */
12831 
12832 	/* If our ids match, then we must have the same max_value.  And we
12833 	 * don't care about the other reg's fixed offset, since if it's too big
12834 	 * the range won't allow anything.
12835 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12836 	 */
12837 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12838 		if (reg->type == type && reg->id == dst_reg->id)
12839 			/* keep the maximum range already checked */
12840 			reg->range = max(reg->range, new_range);
12841 	}));
12842 }
12843 
12844 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12845 {
12846 	struct tnum subreg = tnum_subreg(reg->var_off);
12847 	s32 sval = (s32)val;
12848 
12849 	switch (opcode) {
12850 	case BPF_JEQ:
12851 		if (tnum_is_const(subreg))
12852 			return !!tnum_equals_const(subreg, val);
12853 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
12854 			return 0;
12855 		break;
12856 	case BPF_JNE:
12857 		if (tnum_is_const(subreg))
12858 			return !tnum_equals_const(subreg, val);
12859 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
12860 			return 1;
12861 		break;
12862 	case BPF_JSET:
12863 		if ((~subreg.mask & subreg.value) & val)
12864 			return 1;
12865 		if (!((subreg.mask | subreg.value) & val))
12866 			return 0;
12867 		break;
12868 	case BPF_JGT:
12869 		if (reg->u32_min_value > val)
12870 			return 1;
12871 		else if (reg->u32_max_value <= val)
12872 			return 0;
12873 		break;
12874 	case BPF_JSGT:
12875 		if (reg->s32_min_value > sval)
12876 			return 1;
12877 		else if (reg->s32_max_value <= sval)
12878 			return 0;
12879 		break;
12880 	case BPF_JLT:
12881 		if (reg->u32_max_value < val)
12882 			return 1;
12883 		else if (reg->u32_min_value >= val)
12884 			return 0;
12885 		break;
12886 	case BPF_JSLT:
12887 		if (reg->s32_max_value < sval)
12888 			return 1;
12889 		else if (reg->s32_min_value >= sval)
12890 			return 0;
12891 		break;
12892 	case BPF_JGE:
12893 		if (reg->u32_min_value >= val)
12894 			return 1;
12895 		else if (reg->u32_max_value < val)
12896 			return 0;
12897 		break;
12898 	case BPF_JSGE:
12899 		if (reg->s32_min_value >= sval)
12900 			return 1;
12901 		else if (reg->s32_max_value < sval)
12902 			return 0;
12903 		break;
12904 	case BPF_JLE:
12905 		if (reg->u32_max_value <= val)
12906 			return 1;
12907 		else if (reg->u32_min_value > val)
12908 			return 0;
12909 		break;
12910 	case BPF_JSLE:
12911 		if (reg->s32_max_value <= sval)
12912 			return 1;
12913 		else if (reg->s32_min_value > sval)
12914 			return 0;
12915 		break;
12916 	}
12917 
12918 	return -1;
12919 }
12920 
12921 
12922 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12923 {
12924 	s64 sval = (s64)val;
12925 
12926 	switch (opcode) {
12927 	case BPF_JEQ:
12928 		if (tnum_is_const(reg->var_off))
12929 			return !!tnum_equals_const(reg->var_off, val);
12930 		else if (val < reg->umin_value || val > reg->umax_value)
12931 			return 0;
12932 		break;
12933 	case BPF_JNE:
12934 		if (tnum_is_const(reg->var_off))
12935 			return !tnum_equals_const(reg->var_off, val);
12936 		else if (val < reg->umin_value || val > reg->umax_value)
12937 			return 1;
12938 		break;
12939 	case BPF_JSET:
12940 		if ((~reg->var_off.mask & reg->var_off.value) & val)
12941 			return 1;
12942 		if (!((reg->var_off.mask | reg->var_off.value) & val))
12943 			return 0;
12944 		break;
12945 	case BPF_JGT:
12946 		if (reg->umin_value > val)
12947 			return 1;
12948 		else if (reg->umax_value <= val)
12949 			return 0;
12950 		break;
12951 	case BPF_JSGT:
12952 		if (reg->smin_value > sval)
12953 			return 1;
12954 		else if (reg->smax_value <= sval)
12955 			return 0;
12956 		break;
12957 	case BPF_JLT:
12958 		if (reg->umax_value < val)
12959 			return 1;
12960 		else if (reg->umin_value >= val)
12961 			return 0;
12962 		break;
12963 	case BPF_JSLT:
12964 		if (reg->smax_value < sval)
12965 			return 1;
12966 		else if (reg->smin_value >= sval)
12967 			return 0;
12968 		break;
12969 	case BPF_JGE:
12970 		if (reg->umin_value >= val)
12971 			return 1;
12972 		else if (reg->umax_value < val)
12973 			return 0;
12974 		break;
12975 	case BPF_JSGE:
12976 		if (reg->smin_value >= sval)
12977 			return 1;
12978 		else if (reg->smax_value < sval)
12979 			return 0;
12980 		break;
12981 	case BPF_JLE:
12982 		if (reg->umax_value <= val)
12983 			return 1;
12984 		else if (reg->umin_value > val)
12985 			return 0;
12986 		break;
12987 	case BPF_JSLE:
12988 		if (reg->smax_value <= sval)
12989 			return 1;
12990 		else if (reg->smin_value > sval)
12991 			return 0;
12992 		break;
12993 	}
12994 
12995 	return -1;
12996 }
12997 
12998 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12999  * and return:
13000  *  1 - branch will be taken and "goto target" will be executed
13001  *  0 - branch will not be taken and fall-through to next insn
13002  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13003  *      range [0,10]
13004  */
13005 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13006 			   bool is_jmp32)
13007 {
13008 	if (__is_pointer_value(false, reg)) {
13009 		if (!reg_type_not_null(reg->type))
13010 			return -1;
13011 
13012 		/* If pointer is valid tests against zero will fail so we can
13013 		 * use this to direct branch taken.
13014 		 */
13015 		if (val != 0)
13016 			return -1;
13017 
13018 		switch (opcode) {
13019 		case BPF_JEQ:
13020 			return 0;
13021 		case BPF_JNE:
13022 			return 1;
13023 		default:
13024 			return -1;
13025 		}
13026 	}
13027 
13028 	if (is_jmp32)
13029 		return is_branch32_taken(reg, val, opcode);
13030 	return is_branch64_taken(reg, val, opcode);
13031 }
13032 
13033 static int flip_opcode(u32 opcode)
13034 {
13035 	/* How can we transform "a <op> b" into "b <op> a"? */
13036 	static const u8 opcode_flip[16] = {
13037 		/* these stay the same */
13038 		[BPF_JEQ  >> 4] = BPF_JEQ,
13039 		[BPF_JNE  >> 4] = BPF_JNE,
13040 		[BPF_JSET >> 4] = BPF_JSET,
13041 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13042 		[BPF_JGE  >> 4] = BPF_JLE,
13043 		[BPF_JGT  >> 4] = BPF_JLT,
13044 		[BPF_JLE  >> 4] = BPF_JGE,
13045 		[BPF_JLT  >> 4] = BPF_JGT,
13046 		[BPF_JSGE >> 4] = BPF_JSLE,
13047 		[BPF_JSGT >> 4] = BPF_JSLT,
13048 		[BPF_JSLE >> 4] = BPF_JSGE,
13049 		[BPF_JSLT >> 4] = BPF_JSGT
13050 	};
13051 	return opcode_flip[opcode >> 4];
13052 }
13053 
13054 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13055 				   struct bpf_reg_state *src_reg,
13056 				   u8 opcode)
13057 {
13058 	struct bpf_reg_state *pkt;
13059 
13060 	if (src_reg->type == PTR_TO_PACKET_END) {
13061 		pkt = dst_reg;
13062 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13063 		pkt = src_reg;
13064 		opcode = flip_opcode(opcode);
13065 	} else {
13066 		return -1;
13067 	}
13068 
13069 	if (pkt->range >= 0)
13070 		return -1;
13071 
13072 	switch (opcode) {
13073 	case BPF_JLE:
13074 		/* pkt <= pkt_end */
13075 		fallthrough;
13076 	case BPF_JGT:
13077 		/* pkt > pkt_end */
13078 		if (pkt->range == BEYOND_PKT_END)
13079 			/* pkt has at last one extra byte beyond pkt_end */
13080 			return opcode == BPF_JGT;
13081 		break;
13082 	case BPF_JLT:
13083 		/* pkt < pkt_end */
13084 		fallthrough;
13085 	case BPF_JGE:
13086 		/* pkt >= pkt_end */
13087 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13088 			return opcode == BPF_JGE;
13089 		break;
13090 	}
13091 	return -1;
13092 }
13093 
13094 /* Adjusts the register min/max values in the case that the dst_reg is the
13095  * variable register that we are working on, and src_reg is a constant or we're
13096  * simply doing a BPF_K check.
13097  * In JEQ/JNE cases we also adjust the var_off values.
13098  */
13099 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13100 			    struct bpf_reg_state *false_reg,
13101 			    u64 val, u32 val32,
13102 			    u8 opcode, bool is_jmp32)
13103 {
13104 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13105 	struct tnum false_64off = false_reg->var_off;
13106 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13107 	struct tnum true_64off = true_reg->var_off;
13108 	s64 sval = (s64)val;
13109 	s32 sval32 = (s32)val32;
13110 
13111 	/* If the dst_reg is a pointer, we can't learn anything about its
13112 	 * variable offset from the compare (unless src_reg were a pointer into
13113 	 * the same object, but we don't bother with that.
13114 	 * Since false_reg and true_reg have the same type by construction, we
13115 	 * only need to check one of them for pointerness.
13116 	 */
13117 	if (__is_pointer_value(false, false_reg))
13118 		return;
13119 
13120 	switch (opcode) {
13121 	/* JEQ/JNE comparison doesn't change the register equivalence.
13122 	 *
13123 	 * r1 = r2;
13124 	 * if (r1 == 42) goto label;
13125 	 * ...
13126 	 * label: // here both r1 and r2 are known to be 42.
13127 	 *
13128 	 * Hence when marking register as known preserve it's ID.
13129 	 */
13130 	case BPF_JEQ:
13131 		if (is_jmp32) {
13132 			__mark_reg32_known(true_reg, val32);
13133 			true_32off = tnum_subreg(true_reg->var_off);
13134 		} else {
13135 			___mark_reg_known(true_reg, val);
13136 			true_64off = true_reg->var_off;
13137 		}
13138 		break;
13139 	case BPF_JNE:
13140 		if (is_jmp32) {
13141 			__mark_reg32_known(false_reg, val32);
13142 			false_32off = tnum_subreg(false_reg->var_off);
13143 		} else {
13144 			___mark_reg_known(false_reg, val);
13145 			false_64off = false_reg->var_off;
13146 		}
13147 		break;
13148 	case BPF_JSET:
13149 		if (is_jmp32) {
13150 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13151 			if (is_power_of_2(val32))
13152 				true_32off = tnum_or(true_32off,
13153 						     tnum_const(val32));
13154 		} else {
13155 			false_64off = tnum_and(false_64off, tnum_const(~val));
13156 			if (is_power_of_2(val))
13157 				true_64off = tnum_or(true_64off,
13158 						     tnum_const(val));
13159 		}
13160 		break;
13161 	case BPF_JGE:
13162 	case BPF_JGT:
13163 	{
13164 		if (is_jmp32) {
13165 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13166 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13167 
13168 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13169 						       false_umax);
13170 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13171 						      true_umin);
13172 		} else {
13173 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13174 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13175 
13176 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13177 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13178 		}
13179 		break;
13180 	}
13181 	case BPF_JSGE:
13182 	case BPF_JSGT:
13183 	{
13184 		if (is_jmp32) {
13185 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13186 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13187 
13188 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13189 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13190 		} else {
13191 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13192 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13193 
13194 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13195 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13196 		}
13197 		break;
13198 	}
13199 	case BPF_JLE:
13200 	case BPF_JLT:
13201 	{
13202 		if (is_jmp32) {
13203 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13204 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13205 
13206 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13207 						       false_umin);
13208 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13209 						      true_umax);
13210 		} else {
13211 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13212 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13213 
13214 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13215 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13216 		}
13217 		break;
13218 	}
13219 	case BPF_JSLE:
13220 	case BPF_JSLT:
13221 	{
13222 		if (is_jmp32) {
13223 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13224 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13225 
13226 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13227 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13228 		} else {
13229 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13230 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13231 
13232 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13233 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13234 		}
13235 		break;
13236 	}
13237 	default:
13238 		return;
13239 	}
13240 
13241 	if (is_jmp32) {
13242 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13243 					     tnum_subreg(false_32off));
13244 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13245 					    tnum_subreg(true_32off));
13246 		__reg_combine_32_into_64(false_reg);
13247 		__reg_combine_32_into_64(true_reg);
13248 	} else {
13249 		false_reg->var_off = false_64off;
13250 		true_reg->var_off = true_64off;
13251 		__reg_combine_64_into_32(false_reg);
13252 		__reg_combine_64_into_32(true_reg);
13253 	}
13254 }
13255 
13256 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13257  * the variable reg.
13258  */
13259 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13260 				struct bpf_reg_state *false_reg,
13261 				u64 val, u32 val32,
13262 				u8 opcode, bool is_jmp32)
13263 {
13264 	opcode = flip_opcode(opcode);
13265 	/* This uses zero as "not present in table"; luckily the zero opcode,
13266 	 * BPF_JA, can't get here.
13267 	 */
13268 	if (opcode)
13269 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13270 }
13271 
13272 /* Regs are known to be equal, so intersect their min/max/var_off */
13273 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13274 				  struct bpf_reg_state *dst_reg)
13275 {
13276 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13277 							dst_reg->umin_value);
13278 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13279 							dst_reg->umax_value);
13280 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13281 							dst_reg->smin_value);
13282 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13283 							dst_reg->smax_value);
13284 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13285 							     dst_reg->var_off);
13286 	reg_bounds_sync(src_reg);
13287 	reg_bounds_sync(dst_reg);
13288 }
13289 
13290 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13291 				struct bpf_reg_state *true_dst,
13292 				struct bpf_reg_state *false_src,
13293 				struct bpf_reg_state *false_dst,
13294 				u8 opcode)
13295 {
13296 	switch (opcode) {
13297 	case BPF_JEQ:
13298 		__reg_combine_min_max(true_src, true_dst);
13299 		break;
13300 	case BPF_JNE:
13301 		__reg_combine_min_max(false_src, false_dst);
13302 		break;
13303 	}
13304 }
13305 
13306 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13307 				 struct bpf_reg_state *reg, u32 id,
13308 				 bool is_null)
13309 {
13310 	if (type_may_be_null(reg->type) && reg->id == id &&
13311 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13312 		/* Old offset (both fixed and variable parts) should have been
13313 		 * known-zero, because we don't allow pointer arithmetic on
13314 		 * pointers that might be NULL. If we see this happening, don't
13315 		 * convert the register.
13316 		 *
13317 		 * But in some cases, some helpers that return local kptrs
13318 		 * advance offset for the returned pointer. In those cases, it
13319 		 * is fine to expect to see reg->off.
13320 		 */
13321 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13322 			return;
13323 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13324 		    WARN_ON_ONCE(reg->off))
13325 			return;
13326 
13327 		if (is_null) {
13328 			reg->type = SCALAR_VALUE;
13329 			/* We don't need id and ref_obj_id from this point
13330 			 * onwards anymore, thus we should better reset it,
13331 			 * so that state pruning has chances to take effect.
13332 			 */
13333 			reg->id = 0;
13334 			reg->ref_obj_id = 0;
13335 
13336 			return;
13337 		}
13338 
13339 		mark_ptr_not_null_reg(reg);
13340 
13341 		if (!reg_may_point_to_spin_lock(reg)) {
13342 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13343 			 * in release_reference().
13344 			 *
13345 			 * reg->id is still used by spin_lock ptr. Other
13346 			 * than spin_lock ptr type, reg->id can be reset.
13347 			 */
13348 			reg->id = 0;
13349 		}
13350 	}
13351 }
13352 
13353 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13354  * be folded together at some point.
13355  */
13356 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13357 				  bool is_null)
13358 {
13359 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13360 	struct bpf_reg_state *regs = state->regs, *reg;
13361 	u32 ref_obj_id = regs[regno].ref_obj_id;
13362 	u32 id = regs[regno].id;
13363 
13364 	if (ref_obj_id && ref_obj_id == id && is_null)
13365 		/* regs[regno] is in the " == NULL" branch.
13366 		 * No one could have freed the reference state before
13367 		 * doing the NULL check.
13368 		 */
13369 		WARN_ON_ONCE(release_reference_state(state, id));
13370 
13371 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13372 		mark_ptr_or_null_reg(state, reg, id, is_null);
13373 	}));
13374 }
13375 
13376 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13377 				   struct bpf_reg_state *dst_reg,
13378 				   struct bpf_reg_state *src_reg,
13379 				   struct bpf_verifier_state *this_branch,
13380 				   struct bpf_verifier_state *other_branch)
13381 {
13382 	if (BPF_SRC(insn->code) != BPF_X)
13383 		return false;
13384 
13385 	/* Pointers are always 64-bit. */
13386 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13387 		return false;
13388 
13389 	switch (BPF_OP(insn->code)) {
13390 	case BPF_JGT:
13391 		if ((dst_reg->type == PTR_TO_PACKET &&
13392 		     src_reg->type == PTR_TO_PACKET_END) ||
13393 		    (dst_reg->type == PTR_TO_PACKET_META &&
13394 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13395 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13396 			find_good_pkt_pointers(this_branch, dst_reg,
13397 					       dst_reg->type, false);
13398 			mark_pkt_end(other_branch, insn->dst_reg, true);
13399 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13400 			    src_reg->type == PTR_TO_PACKET) ||
13401 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13402 			    src_reg->type == PTR_TO_PACKET_META)) {
13403 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13404 			find_good_pkt_pointers(other_branch, src_reg,
13405 					       src_reg->type, true);
13406 			mark_pkt_end(this_branch, insn->src_reg, false);
13407 		} else {
13408 			return false;
13409 		}
13410 		break;
13411 	case BPF_JLT:
13412 		if ((dst_reg->type == PTR_TO_PACKET &&
13413 		     src_reg->type == PTR_TO_PACKET_END) ||
13414 		    (dst_reg->type == PTR_TO_PACKET_META &&
13415 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13416 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13417 			find_good_pkt_pointers(other_branch, dst_reg,
13418 					       dst_reg->type, true);
13419 			mark_pkt_end(this_branch, insn->dst_reg, false);
13420 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13421 			    src_reg->type == PTR_TO_PACKET) ||
13422 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13423 			    src_reg->type == PTR_TO_PACKET_META)) {
13424 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13425 			find_good_pkt_pointers(this_branch, src_reg,
13426 					       src_reg->type, false);
13427 			mark_pkt_end(other_branch, insn->src_reg, true);
13428 		} else {
13429 			return false;
13430 		}
13431 		break;
13432 	case BPF_JGE:
13433 		if ((dst_reg->type == PTR_TO_PACKET &&
13434 		     src_reg->type == PTR_TO_PACKET_END) ||
13435 		    (dst_reg->type == PTR_TO_PACKET_META &&
13436 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13437 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13438 			find_good_pkt_pointers(this_branch, dst_reg,
13439 					       dst_reg->type, true);
13440 			mark_pkt_end(other_branch, insn->dst_reg, false);
13441 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13442 			    src_reg->type == PTR_TO_PACKET) ||
13443 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13444 			    src_reg->type == PTR_TO_PACKET_META)) {
13445 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13446 			find_good_pkt_pointers(other_branch, src_reg,
13447 					       src_reg->type, false);
13448 			mark_pkt_end(this_branch, insn->src_reg, true);
13449 		} else {
13450 			return false;
13451 		}
13452 		break;
13453 	case BPF_JLE:
13454 		if ((dst_reg->type == PTR_TO_PACKET &&
13455 		     src_reg->type == PTR_TO_PACKET_END) ||
13456 		    (dst_reg->type == PTR_TO_PACKET_META &&
13457 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13458 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13459 			find_good_pkt_pointers(other_branch, dst_reg,
13460 					       dst_reg->type, false);
13461 			mark_pkt_end(this_branch, insn->dst_reg, true);
13462 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13463 			    src_reg->type == PTR_TO_PACKET) ||
13464 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13465 			    src_reg->type == PTR_TO_PACKET_META)) {
13466 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13467 			find_good_pkt_pointers(this_branch, src_reg,
13468 					       src_reg->type, true);
13469 			mark_pkt_end(other_branch, insn->src_reg, false);
13470 		} else {
13471 			return false;
13472 		}
13473 		break;
13474 	default:
13475 		return false;
13476 	}
13477 
13478 	return true;
13479 }
13480 
13481 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13482 			       struct bpf_reg_state *known_reg)
13483 {
13484 	struct bpf_func_state *state;
13485 	struct bpf_reg_state *reg;
13486 
13487 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13488 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13489 			copy_register_state(reg, known_reg);
13490 	}));
13491 }
13492 
13493 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13494 			     struct bpf_insn *insn, int *insn_idx)
13495 {
13496 	struct bpf_verifier_state *this_branch = env->cur_state;
13497 	struct bpf_verifier_state *other_branch;
13498 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13499 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13500 	struct bpf_reg_state *eq_branch_regs;
13501 	u8 opcode = BPF_OP(insn->code);
13502 	bool is_jmp32;
13503 	int pred = -1;
13504 	int err;
13505 
13506 	/* Only conditional jumps are expected to reach here. */
13507 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
13508 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13509 		return -EINVAL;
13510 	}
13511 
13512 	if (BPF_SRC(insn->code) == BPF_X) {
13513 		if (insn->imm != 0) {
13514 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13515 			return -EINVAL;
13516 		}
13517 
13518 		/* check src1 operand */
13519 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13520 		if (err)
13521 			return err;
13522 
13523 		if (is_pointer_value(env, insn->src_reg)) {
13524 			verbose(env, "R%d pointer comparison prohibited\n",
13525 				insn->src_reg);
13526 			return -EACCES;
13527 		}
13528 		src_reg = &regs[insn->src_reg];
13529 	} else {
13530 		if (insn->src_reg != BPF_REG_0) {
13531 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13532 			return -EINVAL;
13533 		}
13534 	}
13535 
13536 	/* check src2 operand */
13537 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13538 	if (err)
13539 		return err;
13540 
13541 	dst_reg = &regs[insn->dst_reg];
13542 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13543 
13544 	if (BPF_SRC(insn->code) == BPF_K) {
13545 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13546 	} else if (src_reg->type == SCALAR_VALUE &&
13547 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13548 		pred = is_branch_taken(dst_reg,
13549 				       tnum_subreg(src_reg->var_off).value,
13550 				       opcode,
13551 				       is_jmp32);
13552 	} else if (src_reg->type == SCALAR_VALUE &&
13553 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13554 		pred = is_branch_taken(dst_reg,
13555 				       src_reg->var_off.value,
13556 				       opcode,
13557 				       is_jmp32);
13558 	} else if (dst_reg->type == SCALAR_VALUE &&
13559 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13560 		pred = is_branch_taken(src_reg,
13561 				       tnum_subreg(dst_reg->var_off).value,
13562 				       flip_opcode(opcode),
13563 				       is_jmp32);
13564 	} else if (dst_reg->type == SCALAR_VALUE &&
13565 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13566 		pred = is_branch_taken(src_reg,
13567 				       dst_reg->var_off.value,
13568 				       flip_opcode(opcode),
13569 				       is_jmp32);
13570 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
13571 		   reg_is_pkt_pointer_any(src_reg) &&
13572 		   !is_jmp32) {
13573 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13574 	}
13575 
13576 	if (pred >= 0) {
13577 		/* If we get here with a dst_reg pointer type it is because
13578 		 * above is_branch_taken() special cased the 0 comparison.
13579 		 */
13580 		if (!__is_pointer_value(false, dst_reg))
13581 			err = mark_chain_precision(env, insn->dst_reg);
13582 		if (BPF_SRC(insn->code) == BPF_X && !err &&
13583 		    !__is_pointer_value(false, src_reg))
13584 			err = mark_chain_precision(env, insn->src_reg);
13585 		if (err)
13586 			return err;
13587 	}
13588 
13589 	if (pred == 1) {
13590 		/* Only follow the goto, ignore fall-through. If needed, push
13591 		 * the fall-through branch for simulation under speculative
13592 		 * execution.
13593 		 */
13594 		if (!env->bypass_spec_v1 &&
13595 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
13596 					       *insn_idx))
13597 			return -EFAULT;
13598 		*insn_idx += insn->off;
13599 		return 0;
13600 	} else if (pred == 0) {
13601 		/* Only follow the fall-through branch, since that's where the
13602 		 * program will go. If needed, push the goto branch for
13603 		 * simulation under speculative execution.
13604 		 */
13605 		if (!env->bypass_spec_v1 &&
13606 		    !sanitize_speculative_path(env, insn,
13607 					       *insn_idx + insn->off + 1,
13608 					       *insn_idx))
13609 			return -EFAULT;
13610 		return 0;
13611 	}
13612 
13613 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13614 				  false);
13615 	if (!other_branch)
13616 		return -EFAULT;
13617 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13618 
13619 	/* detect if we are comparing against a constant value so we can adjust
13620 	 * our min/max values for our dst register.
13621 	 * this is only legit if both are scalars (or pointers to the same
13622 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13623 	 * because otherwise the different base pointers mean the offsets aren't
13624 	 * comparable.
13625 	 */
13626 	if (BPF_SRC(insn->code) == BPF_X) {
13627 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13628 
13629 		if (dst_reg->type == SCALAR_VALUE &&
13630 		    src_reg->type == SCALAR_VALUE) {
13631 			if (tnum_is_const(src_reg->var_off) ||
13632 			    (is_jmp32 &&
13633 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
13634 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
13635 						dst_reg,
13636 						src_reg->var_off.value,
13637 						tnum_subreg(src_reg->var_off).value,
13638 						opcode, is_jmp32);
13639 			else if (tnum_is_const(dst_reg->var_off) ||
13640 				 (is_jmp32 &&
13641 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
13642 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13643 						    src_reg,
13644 						    dst_reg->var_off.value,
13645 						    tnum_subreg(dst_reg->var_off).value,
13646 						    opcode, is_jmp32);
13647 			else if (!is_jmp32 &&
13648 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
13649 				/* Comparing for equality, we can combine knowledge */
13650 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
13651 						    &other_branch_regs[insn->dst_reg],
13652 						    src_reg, dst_reg, opcode);
13653 			if (src_reg->id &&
13654 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13655 				find_equal_scalars(this_branch, src_reg);
13656 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13657 			}
13658 
13659 		}
13660 	} else if (dst_reg->type == SCALAR_VALUE) {
13661 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
13662 					dst_reg, insn->imm, (u32)insn->imm,
13663 					opcode, is_jmp32);
13664 	}
13665 
13666 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13667 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13668 		find_equal_scalars(this_branch, dst_reg);
13669 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13670 	}
13671 
13672 	/* if one pointer register is compared to another pointer
13673 	 * register check if PTR_MAYBE_NULL could be lifted.
13674 	 * E.g. register A - maybe null
13675 	 *      register B - not null
13676 	 * for JNE A, B, ... - A is not null in the false branch;
13677 	 * for JEQ A, B, ... - A is not null in the true branch.
13678 	 *
13679 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
13680 	 * not need to be null checked by the BPF program, i.e.,
13681 	 * could be null even without PTR_MAYBE_NULL marking, so
13682 	 * only propagate nullness when neither reg is that type.
13683 	 */
13684 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13685 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13686 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13687 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
13688 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13689 		eq_branch_regs = NULL;
13690 		switch (opcode) {
13691 		case BPF_JEQ:
13692 			eq_branch_regs = other_branch_regs;
13693 			break;
13694 		case BPF_JNE:
13695 			eq_branch_regs = regs;
13696 			break;
13697 		default:
13698 			/* do nothing */
13699 			break;
13700 		}
13701 		if (eq_branch_regs) {
13702 			if (type_may_be_null(src_reg->type))
13703 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13704 			else
13705 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13706 		}
13707 	}
13708 
13709 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13710 	 * NOTE: these optimizations below are related with pointer comparison
13711 	 *       which will never be JMP32.
13712 	 */
13713 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13714 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13715 	    type_may_be_null(dst_reg->type)) {
13716 		/* Mark all identical registers in each branch as either
13717 		 * safe or unknown depending R == 0 or R != 0 conditional.
13718 		 */
13719 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13720 				      opcode == BPF_JNE);
13721 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13722 				      opcode == BPF_JEQ);
13723 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
13724 					   this_branch, other_branch) &&
13725 		   is_pointer_value(env, insn->dst_reg)) {
13726 		verbose(env, "R%d pointer comparison prohibited\n",
13727 			insn->dst_reg);
13728 		return -EACCES;
13729 	}
13730 	if (env->log.level & BPF_LOG_LEVEL)
13731 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
13732 	return 0;
13733 }
13734 
13735 /* verify BPF_LD_IMM64 instruction */
13736 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
13737 {
13738 	struct bpf_insn_aux_data *aux = cur_aux(env);
13739 	struct bpf_reg_state *regs = cur_regs(env);
13740 	struct bpf_reg_state *dst_reg;
13741 	struct bpf_map *map;
13742 	int err;
13743 
13744 	if (BPF_SIZE(insn->code) != BPF_DW) {
13745 		verbose(env, "invalid BPF_LD_IMM insn\n");
13746 		return -EINVAL;
13747 	}
13748 	if (insn->off != 0) {
13749 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
13750 		return -EINVAL;
13751 	}
13752 
13753 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
13754 	if (err)
13755 		return err;
13756 
13757 	dst_reg = &regs[insn->dst_reg];
13758 	if (insn->src_reg == 0) {
13759 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13760 
13761 		dst_reg->type = SCALAR_VALUE;
13762 		__mark_reg_known(&regs[insn->dst_reg], imm);
13763 		return 0;
13764 	}
13765 
13766 	/* All special src_reg cases are listed below. From this point onwards
13767 	 * we either succeed and assign a corresponding dst_reg->type after
13768 	 * zeroing the offset, or fail and reject the program.
13769 	 */
13770 	mark_reg_known_zero(env, regs, insn->dst_reg);
13771 
13772 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13773 		dst_reg->type = aux->btf_var.reg_type;
13774 		switch (base_type(dst_reg->type)) {
13775 		case PTR_TO_MEM:
13776 			dst_reg->mem_size = aux->btf_var.mem_size;
13777 			break;
13778 		case PTR_TO_BTF_ID:
13779 			dst_reg->btf = aux->btf_var.btf;
13780 			dst_reg->btf_id = aux->btf_var.btf_id;
13781 			break;
13782 		default:
13783 			verbose(env, "bpf verifier is misconfigured\n");
13784 			return -EFAULT;
13785 		}
13786 		return 0;
13787 	}
13788 
13789 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
13790 		struct bpf_prog_aux *aux = env->prog->aux;
13791 		u32 subprogno = find_subprog(env,
13792 					     env->insn_idx + insn->imm + 1);
13793 
13794 		if (!aux->func_info) {
13795 			verbose(env, "missing btf func_info\n");
13796 			return -EINVAL;
13797 		}
13798 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13799 			verbose(env, "callback function not static\n");
13800 			return -EINVAL;
13801 		}
13802 
13803 		dst_reg->type = PTR_TO_FUNC;
13804 		dst_reg->subprogno = subprogno;
13805 		return 0;
13806 	}
13807 
13808 	map = env->used_maps[aux->map_index];
13809 	dst_reg->map_ptr = map;
13810 
13811 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13812 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13813 		dst_reg->type = PTR_TO_MAP_VALUE;
13814 		dst_reg->off = aux->map_off;
13815 		WARN_ON_ONCE(map->max_entries != 1);
13816 		/* We want reg->id to be same (0) as map_value is not distinct */
13817 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13818 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13819 		dst_reg->type = CONST_PTR_TO_MAP;
13820 	} else {
13821 		verbose(env, "bpf verifier is misconfigured\n");
13822 		return -EINVAL;
13823 	}
13824 
13825 	return 0;
13826 }
13827 
13828 static bool may_access_skb(enum bpf_prog_type type)
13829 {
13830 	switch (type) {
13831 	case BPF_PROG_TYPE_SOCKET_FILTER:
13832 	case BPF_PROG_TYPE_SCHED_CLS:
13833 	case BPF_PROG_TYPE_SCHED_ACT:
13834 		return true;
13835 	default:
13836 		return false;
13837 	}
13838 }
13839 
13840 /* verify safety of LD_ABS|LD_IND instructions:
13841  * - they can only appear in the programs where ctx == skb
13842  * - since they are wrappers of function calls, they scratch R1-R5 registers,
13843  *   preserve R6-R9, and store return value into R0
13844  *
13845  * Implicit input:
13846  *   ctx == skb == R6 == CTX
13847  *
13848  * Explicit input:
13849  *   SRC == any register
13850  *   IMM == 32-bit immediate
13851  *
13852  * Output:
13853  *   R0 - 8/16/32-bit skb data converted to cpu endianness
13854  */
13855 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13856 {
13857 	struct bpf_reg_state *regs = cur_regs(env);
13858 	static const int ctx_reg = BPF_REG_6;
13859 	u8 mode = BPF_MODE(insn->code);
13860 	int i, err;
13861 
13862 	if (!may_access_skb(resolve_prog_type(env->prog))) {
13863 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13864 		return -EINVAL;
13865 	}
13866 
13867 	if (!env->ops->gen_ld_abs) {
13868 		verbose(env, "bpf verifier is misconfigured\n");
13869 		return -EINVAL;
13870 	}
13871 
13872 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13873 	    BPF_SIZE(insn->code) == BPF_DW ||
13874 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13875 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13876 		return -EINVAL;
13877 	}
13878 
13879 	/* check whether implicit source operand (register R6) is readable */
13880 	err = check_reg_arg(env, ctx_reg, SRC_OP);
13881 	if (err)
13882 		return err;
13883 
13884 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13885 	 * gen_ld_abs() may terminate the program at runtime, leading to
13886 	 * reference leak.
13887 	 */
13888 	err = check_reference_leak(env);
13889 	if (err) {
13890 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13891 		return err;
13892 	}
13893 
13894 	if (env->cur_state->active_lock.ptr) {
13895 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13896 		return -EINVAL;
13897 	}
13898 
13899 	if (env->cur_state->active_rcu_lock) {
13900 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13901 		return -EINVAL;
13902 	}
13903 
13904 	if (regs[ctx_reg].type != PTR_TO_CTX) {
13905 		verbose(env,
13906 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13907 		return -EINVAL;
13908 	}
13909 
13910 	if (mode == BPF_IND) {
13911 		/* check explicit source operand */
13912 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13913 		if (err)
13914 			return err;
13915 	}
13916 
13917 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
13918 	if (err < 0)
13919 		return err;
13920 
13921 	/* reset caller saved regs to unreadable */
13922 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
13923 		mark_reg_not_init(env, regs, caller_saved[i]);
13924 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13925 	}
13926 
13927 	/* mark destination R0 register as readable, since it contains
13928 	 * the value fetched from the packet.
13929 	 * Already marked as written above.
13930 	 */
13931 	mark_reg_unknown(env, regs, BPF_REG_0);
13932 	/* ld_abs load up to 32-bit skb data. */
13933 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13934 	return 0;
13935 }
13936 
13937 static int check_return_code(struct bpf_verifier_env *env)
13938 {
13939 	struct tnum enforce_attach_type_range = tnum_unknown;
13940 	const struct bpf_prog *prog = env->prog;
13941 	struct bpf_reg_state *reg;
13942 	struct tnum range = tnum_range(0, 1);
13943 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13944 	int err;
13945 	struct bpf_func_state *frame = env->cur_state->frame[0];
13946 	const bool is_subprog = frame->subprogno;
13947 
13948 	/* LSM and struct_ops func-ptr's return type could be "void" */
13949 	if (!is_subprog) {
13950 		switch (prog_type) {
13951 		case BPF_PROG_TYPE_LSM:
13952 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
13953 				/* See below, can be 0 or 0-1 depending on hook. */
13954 				break;
13955 			fallthrough;
13956 		case BPF_PROG_TYPE_STRUCT_OPS:
13957 			if (!prog->aux->attach_func_proto->type)
13958 				return 0;
13959 			break;
13960 		default:
13961 			break;
13962 		}
13963 	}
13964 
13965 	/* eBPF calling convention is such that R0 is used
13966 	 * to return the value from eBPF program.
13967 	 * Make sure that it's readable at this time
13968 	 * of bpf_exit, which means that program wrote
13969 	 * something into it earlier
13970 	 */
13971 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13972 	if (err)
13973 		return err;
13974 
13975 	if (is_pointer_value(env, BPF_REG_0)) {
13976 		verbose(env, "R0 leaks addr as return value\n");
13977 		return -EACCES;
13978 	}
13979 
13980 	reg = cur_regs(env) + BPF_REG_0;
13981 
13982 	if (frame->in_async_callback_fn) {
13983 		/* enforce return zero from async callbacks like timer */
13984 		if (reg->type != SCALAR_VALUE) {
13985 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13986 				reg_type_str(env, reg->type));
13987 			return -EINVAL;
13988 		}
13989 
13990 		if (!tnum_in(tnum_const(0), reg->var_off)) {
13991 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13992 			return -EINVAL;
13993 		}
13994 		return 0;
13995 	}
13996 
13997 	if (is_subprog) {
13998 		if (reg->type != SCALAR_VALUE) {
13999 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14000 				reg_type_str(env, reg->type));
14001 			return -EINVAL;
14002 		}
14003 		return 0;
14004 	}
14005 
14006 	switch (prog_type) {
14007 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14008 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14009 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14010 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14011 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14012 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14013 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14014 			range = tnum_range(1, 1);
14015 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14016 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14017 			range = tnum_range(0, 3);
14018 		break;
14019 	case BPF_PROG_TYPE_CGROUP_SKB:
14020 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14021 			range = tnum_range(0, 3);
14022 			enforce_attach_type_range = tnum_range(2, 3);
14023 		}
14024 		break;
14025 	case BPF_PROG_TYPE_CGROUP_SOCK:
14026 	case BPF_PROG_TYPE_SOCK_OPS:
14027 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14028 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14029 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14030 		break;
14031 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14032 		if (!env->prog->aux->attach_btf_id)
14033 			return 0;
14034 		range = tnum_const(0);
14035 		break;
14036 	case BPF_PROG_TYPE_TRACING:
14037 		switch (env->prog->expected_attach_type) {
14038 		case BPF_TRACE_FENTRY:
14039 		case BPF_TRACE_FEXIT:
14040 			range = tnum_const(0);
14041 			break;
14042 		case BPF_TRACE_RAW_TP:
14043 		case BPF_MODIFY_RETURN:
14044 			return 0;
14045 		case BPF_TRACE_ITER:
14046 			break;
14047 		default:
14048 			return -ENOTSUPP;
14049 		}
14050 		break;
14051 	case BPF_PROG_TYPE_SK_LOOKUP:
14052 		range = tnum_range(SK_DROP, SK_PASS);
14053 		break;
14054 
14055 	case BPF_PROG_TYPE_LSM:
14056 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14057 			/* Regular BPF_PROG_TYPE_LSM programs can return
14058 			 * any value.
14059 			 */
14060 			return 0;
14061 		}
14062 		if (!env->prog->aux->attach_func_proto->type) {
14063 			/* Make sure programs that attach to void
14064 			 * hooks don't try to modify return value.
14065 			 */
14066 			range = tnum_range(1, 1);
14067 		}
14068 		break;
14069 
14070 	case BPF_PROG_TYPE_NETFILTER:
14071 		range = tnum_range(NF_DROP, NF_ACCEPT);
14072 		break;
14073 	case BPF_PROG_TYPE_EXT:
14074 		/* freplace program can return anything as its return value
14075 		 * depends on the to-be-replaced kernel func or bpf program.
14076 		 */
14077 	default:
14078 		return 0;
14079 	}
14080 
14081 	if (reg->type != SCALAR_VALUE) {
14082 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14083 			reg_type_str(env, reg->type));
14084 		return -EINVAL;
14085 	}
14086 
14087 	if (!tnum_in(range, reg->var_off)) {
14088 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14089 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14090 		    prog_type == BPF_PROG_TYPE_LSM &&
14091 		    !prog->aux->attach_func_proto->type)
14092 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14093 		return -EINVAL;
14094 	}
14095 
14096 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14097 	    tnum_in(enforce_attach_type_range, reg->var_off))
14098 		env->prog->enforce_expected_attach_type = 1;
14099 	return 0;
14100 }
14101 
14102 /* non-recursive DFS pseudo code
14103  * 1  procedure DFS-iterative(G,v):
14104  * 2      label v as discovered
14105  * 3      let S be a stack
14106  * 4      S.push(v)
14107  * 5      while S is not empty
14108  * 6            t <- S.peek()
14109  * 7            if t is what we're looking for:
14110  * 8                return t
14111  * 9            for all edges e in G.adjacentEdges(t) do
14112  * 10               if edge e is already labelled
14113  * 11                   continue with the next edge
14114  * 12               w <- G.adjacentVertex(t,e)
14115  * 13               if vertex w is not discovered and not explored
14116  * 14                   label e as tree-edge
14117  * 15                   label w as discovered
14118  * 16                   S.push(w)
14119  * 17                   continue at 5
14120  * 18               else if vertex w is discovered
14121  * 19                   label e as back-edge
14122  * 20               else
14123  * 21                   // vertex w is explored
14124  * 22                   label e as forward- or cross-edge
14125  * 23           label t as explored
14126  * 24           S.pop()
14127  *
14128  * convention:
14129  * 0x10 - discovered
14130  * 0x11 - discovered and fall-through edge labelled
14131  * 0x12 - discovered and fall-through and branch edges labelled
14132  * 0x20 - explored
14133  */
14134 
14135 enum {
14136 	DISCOVERED = 0x10,
14137 	EXPLORED = 0x20,
14138 	FALLTHROUGH = 1,
14139 	BRANCH = 2,
14140 };
14141 
14142 static u32 state_htab_size(struct bpf_verifier_env *env)
14143 {
14144 	return env->prog->len;
14145 }
14146 
14147 static struct bpf_verifier_state_list **explored_state(
14148 					struct bpf_verifier_env *env,
14149 					int idx)
14150 {
14151 	struct bpf_verifier_state *cur = env->cur_state;
14152 	struct bpf_func_state *state = cur->frame[cur->curframe];
14153 
14154 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14155 }
14156 
14157 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14158 {
14159 	env->insn_aux_data[idx].prune_point = true;
14160 }
14161 
14162 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14163 {
14164 	return env->insn_aux_data[insn_idx].prune_point;
14165 }
14166 
14167 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14168 {
14169 	env->insn_aux_data[idx].force_checkpoint = true;
14170 }
14171 
14172 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14173 {
14174 	return env->insn_aux_data[insn_idx].force_checkpoint;
14175 }
14176 
14177 
14178 enum {
14179 	DONE_EXPLORING = 0,
14180 	KEEP_EXPLORING = 1,
14181 };
14182 
14183 /* t, w, e - match pseudo-code above:
14184  * t - index of current instruction
14185  * w - next instruction
14186  * e - edge
14187  */
14188 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14189 		     bool loop_ok)
14190 {
14191 	int *insn_stack = env->cfg.insn_stack;
14192 	int *insn_state = env->cfg.insn_state;
14193 
14194 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14195 		return DONE_EXPLORING;
14196 
14197 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14198 		return DONE_EXPLORING;
14199 
14200 	if (w < 0 || w >= env->prog->len) {
14201 		verbose_linfo(env, t, "%d: ", t);
14202 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14203 		return -EINVAL;
14204 	}
14205 
14206 	if (e == BRANCH) {
14207 		/* mark branch target for state pruning */
14208 		mark_prune_point(env, w);
14209 		mark_jmp_point(env, w);
14210 	}
14211 
14212 	if (insn_state[w] == 0) {
14213 		/* tree-edge */
14214 		insn_state[t] = DISCOVERED | e;
14215 		insn_state[w] = DISCOVERED;
14216 		if (env->cfg.cur_stack >= env->prog->len)
14217 			return -E2BIG;
14218 		insn_stack[env->cfg.cur_stack++] = w;
14219 		return KEEP_EXPLORING;
14220 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14221 		if (loop_ok && env->bpf_capable)
14222 			return DONE_EXPLORING;
14223 		verbose_linfo(env, t, "%d: ", t);
14224 		verbose_linfo(env, w, "%d: ", w);
14225 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14226 		return -EINVAL;
14227 	} else if (insn_state[w] == EXPLORED) {
14228 		/* forward- or cross-edge */
14229 		insn_state[t] = DISCOVERED | e;
14230 	} else {
14231 		verbose(env, "insn state internal bug\n");
14232 		return -EFAULT;
14233 	}
14234 	return DONE_EXPLORING;
14235 }
14236 
14237 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14238 				struct bpf_verifier_env *env,
14239 				bool visit_callee)
14240 {
14241 	int ret;
14242 
14243 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14244 	if (ret)
14245 		return ret;
14246 
14247 	mark_prune_point(env, t + 1);
14248 	/* when we exit from subprog, we need to record non-linear history */
14249 	mark_jmp_point(env, t + 1);
14250 
14251 	if (visit_callee) {
14252 		mark_prune_point(env, t);
14253 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14254 				/* It's ok to allow recursion from CFG point of
14255 				 * view. __check_func_call() will do the actual
14256 				 * check.
14257 				 */
14258 				bpf_pseudo_func(insns + t));
14259 	}
14260 	return ret;
14261 }
14262 
14263 /* Visits the instruction at index t and returns one of the following:
14264  *  < 0 - an error occurred
14265  *  DONE_EXPLORING - the instruction was fully explored
14266  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14267  */
14268 static int visit_insn(int t, struct bpf_verifier_env *env)
14269 {
14270 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14271 	int ret;
14272 
14273 	if (bpf_pseudo_func(insn))
14274 		return visit_func_call_insn(t, insns, env, true);
14275 
14276 	/* All non-branch instructions have a single fall-through edge. */
14277 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14278 	    BPF_CLASS(insn->code) != BPF_JMP32)
14279 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14280 
14281 	switch (BPF_OP(insn->code)) {
14282 	case BPF_EXIT:
14283 		return DONE_EXPLORING;
14284 
14285 	case BPF_CALL:
14286 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14287 			/* Mark this call insn as a prune point to trigger
14288 			 * is_state_visited() check before call itself is
14289 			 * processed by __check_func_call(). Otherwise new
14290 			 * async state will be pushed for further exploration.
14291 			 */
14292 			mark_prune_point(env, t);
14293 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14294 			struct bpf_kfunc_call_arg_meta meta;
14295 
14296 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14297 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14298 				mark_prune_point(env, t);
14299 				/* Checking and saving state checkpoints at iter_next() call
14300 				 * is crucial for fast convergence of open-coded iterator loop
14301 				 * logic, so we need to force it. If we don't do that,
14302 				 * is_state_visited() might skip saving a checkpoint, causing
14303 				 * unnecessarily long sequence of not checkpointed
14304 				 * instructions and jumps, leading to exhaustion of jump
14305 				 * history buffer, and potentially other undesired outcomes.
14306 				 * It is expected that with correct open-coded iterators
14307 				 * convergence will happen quickly, so we don't run a risk of
14308 				 * exhausting memory.
14309 				 */
14310 				mark_force_checkpoint(env, t);
14311 			}
14312 		}
14313 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14314 
14315 	case BPF_JA:
14316 		if (BPF_SRC(insn->code) != BPF_K)
14317 			return -EINVAL;
14318 
14319 		/* unconditional jump with single edge */
14320 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14321 				true);
14322 		if (ret)
14323 			return ret;
14324 
14325 		mark_prune_point(env, t + insn->off + 1);
14326 		mark_jmp_point(env, t + insn->off + 1);
14327 
14328 		return ret;
14329 
14330 	default:
14331 		/* conditional jump with two edges */
14332 		mark_prune_point(env, t);
14333 
14334 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14335 		if (ret)
14336 			return ret;
14337 
14338 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14339 	}
14340 }
14341 
14342 /* non-recursive depth-first-search to detect loops in BPF program
14343  * loop == back-edge in directed graph
14344  */
14345 static int check_cfg(struct bpf_verifier_env *env)
14346 {
14347 	int insn_cnt = env->prog->len;
14348 	int *insn_stack, *insn_state;
14349 	int ret = 0;
14350 	int i;
14351 
14352 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14353 	if (!insn_state)
14354 		return -ENOMEM;
14355 
14356 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14357 	if (!insn_stack) {
14358 		kvfree(insn_state);
14359 		return -ENOMEM;
14360 	}
14361 
14362 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14363 	insn_stack[0] = 0; /* 0 is the first instruction */
14364 	env->cfg.cur_stack = 1;
14365 
14366 	while (env->cfg.cur_stack > 0) {
14367 		int t = insn_stack[env->cfg.cur_stack - 1];
14368 
14369 		ret = visit_insn(t, env);
14370 		switch (ret) {
14371 		case DONE_EXPLORING:
14372 			insn_state[t] = EXPLORED;
14373 			env->cfg.cur_stack--;
14374 			break;
14375 		case KEEP_EXPLORING:
14376 			break;
14377 		default:
14378 			if (ret > 0) {
14379 				verbose(env, "visit_insn internal bug\n");
14380 				ret = -EFAULT;
14381 			}
14382 			goto err_free;
14383 		}
14384 	}
14385 
14386 	if (env->cfg.cur_stack < 0) {
14387 		verbose(env, "pop stack internal bug\n");
14388 		ret = -EFAULT;
14389 		goto err_free;
14390 	}
14391 
14392 	for (i = 0; i < insn_cnt; i++) {
14393 		if (insn_state[i] != EXPLORED) {
14394 			verbose(env, "unreachable insn %d\n", i);
14395 			ret = -EINVAL;
14396 			goto err_free;
14397 		}
14398 	}
14399 	ret = 0; /* cfg looks good */
14400 
14401 err_free:
14402 	kvfree(insn_state);
14403 	kvfree(insn_stack);
14404 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14405 	return ret;
14406 }
14407 
14408 static int check_abnormal_return(struct bpf_verifier_env *env)
14409 {
14410 	int i;
14411 
14412 	for (i = 1; i < env->subprog_cnt; i++) {
14413 		if (env->subprog_info[i].has_ld_abs) {
14414 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14415 			return -EINVAL;
14416 		}
14417 		if (env->subprog_info[i].has_tail_call) {
14418 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14419 			return -EINVAL;
14420 		}
14421 	}
14422 	return 0;
14423 }
14424 
14425 /* The minimum supported BTF func info size */
14426 #define MIN_BPF_FUNCINFO_SIZE	8
14427 #define MAX_FUNCINFO_REC_SIZE	252
14428 
14429 static int check_btf_func(struct bpf_verifier_env *env,
14430 			  const union bpf_attr *attr,
14431 			  bpfptr_t uattr)
14432 {
14433 	const struct btf_type *type, *func_proto, *ret_type;
14434 	u32 i, nfuncs, urec_size, min_size;
14435 	u32 krec_size = sizeof(struct bpf_func_info);
14436 	struct bpf_func_info *krecord;
14437 	struct bpf_func_info_aux *info_aux = NULL;
14438 	struct bpf_prog *prog;
14439 	const struct btf *btf;
14440 	bpfptr_t urecord;
14441 	u32 prev_offset = 0;
14442 	bool scalar_return;
14443 	int ret = -ENOMEM;
14444 
14445 	nfuncs = attr->func_info_cnt;
14446 	if (!nfuncs) {
14447 		if (check_abnormal_return(env))
14448 			return -EINVAL;
14449 		return 0;
14450 	}
14451 
14452 	if (nfuncs != env->subprog_cnt) {
14453 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14454 		return -EINVAL;
14455 	}
14456 
14457 	urec_size = attr->func_info_rec_size;
14458 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14459 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
14460 	    urec_size % sizeof(u32)) {
14461 		verbose(env, "invalid func info rec size %u\n", urec_size);
14462 		return -EINVAL;
14463 	}
14464 
14465 	prog = env->prog;
14466 	btf = prog->aux->btf;
14467 
14468 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14469 	min_size = min_t(u32, krec_size, urec_size);
14470 
14471 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14472 	if (!krecord)
14473 		return -ENOMEM;
14474 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14475 	if (!info_aux)
14476 		goto err_free;
14477 
14478 	for (i = 0; i < nfuncs; i++) {
14479 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14480 		if (ret) {
14481 			if (ret == -E2BIG) {
14482 				verbose(env, "nonzero tailing record in func info");
14483 				/* set the size kernel expects so loader can zero
14484 				 * out the rest of the record.
14485 				 */
14486 				if (copy_to_bpfptr_offset(uattr,
14487 							  offsetof(union bpf_attr, func_info_rec_size),
14488 							  &min_size, sizeof(min_size)))
14489 					ret = -EFAULT;
14490 			}
14491 			goto err_free;
14492 		}
14493 
14494 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14495 			ret = -EFAULT;
14496 			goto err_free;
14497 		}
14498 
14499 		/* check insn_off */
14500 		ret = -EINVAL;
14501 		if (i == 0) {
14502 			if (krecord[i].insn_off) {
14503 				verbose(env,
14504 					"nonzero insn_off %u for the first func info record",
14505 					krecord[i].insn_off);
14506 				goto err_free;
14507 			}
14508 		} else if (krecord[i].insn_off <= prev_offset) {
14509 			verbose(env,
14510 				"same or smaller insn offset (%u) than previous func info record (%u)",
14511 				krecord[i].insn_off, prev_offset);
14512 			goto err_free;
14513 		}
14514 
14515 		if (env->subprog_info[i].start != krecord[i].insn_off) {
14516 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14517 			goto err_free;
14518 		}
14519 
14520 		/* check type_id */
14521 		type = btf_type_by_id(btf, krecord[i].type_id);
14522 		if (!type || !btf_type_is_func(type)) {
14523 			verbose(env, "invalid type id %d in func info",
14524 				krecord[i].type_id);
14525 			goto err_free;
14526 		}
14527 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14528 
14529 		func_proto = btf_type_by_id(btf, type->type);
14530 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14531 			/* btf_func_check() already verified it during BTF load */
14532 			goto err_free;
14533 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14534 		scalar_return =
14535 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14536 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14537 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14538 			goto err_free;
14539 		}
14540 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14541 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14542 			goto err_free;
14543 		}
14544 
14545 		prev_offset = krecord[i].insn_off;
14546 		bpfptr_add(&urecord, urec_size);
14547 	}
14548 
14549 	prog->aux->func_info = krecord;
14550 	prog->aux->func_info_cnt = nfuncs;
14551 	prog->aux->func_info_aux = info_aux;
14552 	return 0;
14553 
14554 err_free:
14555 	kvfree(krecord);
14556 	kfree(info_aux);
14557 	return ret;
14558 }
14559 
14560 static void adjust_btf_func(struct bpf_verifier_env *env)
14561 {
14562 	struct bpf_prog_aux *aux = env->prog->aux;
14563 	int i;
14564 
14565 	if (!aux->func_info)
14566 		return;
14567 
14568 	for (i = 0; i < env->subprog_cnt; i++)
14569 		aux->func_info[i].insn_off = env->subprog_info[i].start;
14570 }
14571 
14572 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
14573 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
14574 
14575 static int check_btf_line(struct bpf_verifier_env *env,
14576 			  const union bpf_attr *attr,
14577 			  bpfptr_t uattr)
14578 {
14579 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14580 	struct bpf_subprog_info *sub;
14581 	struct bpf_line_info *linfo;
14582 	struct bpf_prog *prog;
14583 	const struct btf *btf;
14584 	bpfptr_t ulinfo;
14585 	int err;
14586 
14587 	nr_linfo = attr->line_info_cnt;
14588 	if (!nr_linfo)
14589 		return 0;
14590 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14591 		return -EINVAL;
14592 
14593 	rec_size = attr->line_info_rec_size;
14594 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14595 	    rec_size > MAX_LINEINFO_REC_SIZE ||
14596 	    rec_size & (sizeof(u32) - 1))
14597 		return -EINVAL;
14598 
14599 	/* Need to zero it in case the userspace may
14600 	 * pass in a smaller bpf_line_info object.
14601 	 */
14602 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14603 			 GFP_KERNEL | __GFP_NOWARN);
14604 	if (!linfo)
14605 		return -ENOMEM;
14606 
14607 	prog = env->prog;
14608 	btf = prog->aux->btf;
14609 
14610 	s = 0;
14611 	sub = env->subprog_info;
14612 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14613 	expected_size = sizeof(struct bpf_line_info);
14614 	ncopy = min_t(u32, expected_size, rec_size);
14615 	for (i = 0; i < nr_linfo; i++) {
14616 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14617 		if (err) {
14618 			if (err == -E2BIG) {
14619 				verbose(env, "nonzero tailing record in line_info");
14620 				if (copy_to_bpfptr_offset(uattr,
14621 							  offsetof(union bpf_attr, line_info_rec_size),
14622 							  &expected_size, sizeof(expected_size)))
14623 					err = -EFAULT;
14624 			}
14625 			goto err_free;
14626 		}
14627 
14628 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14629 			err = -EFAULT;
14630 			goto err_free;
14631 		}
14632 
14633 		/*
14634 		 * Check insn_off to ensure
14635 		 * 1) strictly increasing AND
14636 		 * 2) bounded by prog->len
14637 		 *
14638 		 * The linfo[0].insn_off == 0 check logically falls into
14639 		 * the later "missing bpf_line_info for func..." case
14640 		 * because the first linfo[0].insn_off must be the
14641 		 * first sub also and the first sub must have
14642 		 * subprog_info[0].start == 0.
14643 		 */
14644 		if ((i && linfo[i].insn_off <= prev_offset) ||
14645 		    linfo[i].insn_off >= prog->len) {
14646 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14647 				i, linfo[i].insn_off, prev_offset,
14648 				prog->len);
14649 			err = -EINVAL;
14650 			goto err_free;
14651 		}
14652 
14653 		if (!prog->insnsi[linfo[i].insn_off].code) {
14654 			verbose(env,
14655 				"Invalid insn code at line_info[%u].insn_off\n",
14656 				i);
14657 			err = -EINVAL;
14658 			goto err_free;
14659 		}
14660 
14661 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14662 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14663 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14664 			err = -EINVAL;
14665 			goto err_free;
14666 		}
14667 
14668 		if (s != env->subprog_cnt) {
14669 			if (linfo[i].insn_off == sub[s].start) {
14670 				sub[s].linfo_idx = i;
14671 				s++;
14672 			} else if (sub[s].start < linfo[i].insn_off) {
14673 				verbose(env, "missing bpf_line_info for func#%u\n", s);
14674 				err = -EINVAL;
14675 				goto err_free;
14676 			}
14677 		}
14678 
14679 		prev_offset = linfo[i].insn_off;
14680 		bpfptr_add(&ulinfo, rec_size);
14681 	}
14682 
14683 	if (s != env->subprog_cnt) {
14684 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14685 			env->subprog_cnt - s, s);
14686 		err = -EINVAL;
14687 		goto err_free;
14688 	}
14689 
14690 	prog->aux->linfo = linfo;
14691 	prog->aux->nr_linfo = nr_linfo;
14692 
14693 	return 0;
14694 
14695 err_free:
14696 	kvfree(linfo);
14697 	return err;
14698 }
14699 
14700 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
14701 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
14702 
14703 static int check_core_relo(struct bpf_verifier_env *env,
14704 			   const union bpf_attr *attr,
14705 			   bpfptr_t uattr)
14706 {
14707 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14708 	struct bpf_core_relo core_relo = {};
14709 	struct bpf_prog *prog = env->prog;
14710 	const struct btf *btf = prog->aux->btf;
14711 	struct bpf_core_ctx ctx = {
14712 		.log = &env->log,
14713 		.btf = btf,
14714 	};
14715 	bpfptr_t u_core_relo;
14716 	int err;
14717 
14718 	nr_core_relo = attr->core_relo_cnt;
14719 	if (!nr_core_relo)
14720 		return 0;
14721 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14722 		return -EINVAL;
14723 
14724 	rec_size = attr->core_relo_rec_size;
14725 	if (rec_size < MIN_CORE_RELO_SIZE ||
14726 	    rec_size > MAX_CORE_RELO_SIZE ||
14727 	    rec_size % sizeof(u32))
14728 		return -EINVAL;
14729 
14730 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14731 	expected_size = sizeof(struct bpf_core_relo);
14732 	ncopy = min_t(u32, expected_size, rec_size);
14733 
14734 	/* Unlike func_info and line_info, copy and apply each CO-RE
14735 	 * relocation record one at a time.
14736 	 */
14737 	for (i = 0; i < nr_core_relo; i++) {
14738 		/* future proofing when sizeof(bpf_core_relo) changes */
14739 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14740 		if (err) {
14741 			if (err == -E2BIG) {
14742 				verbose(env, "nonzero tailing record in core_relo");
14743 				if (copy_to_bpfptr_offset(uattr,
14744 							  offsetof(union bpf_attr, core_relo_rec_size),
14745 							  &expected_size, sizeof(expected_size)))
14746 					err = -EFAULT;
14747 			}
14748 			break;
14749 		}
14750 
14751 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14752 			err = -EFAULT;
14753 			break;
14754 		}
14755 
14756 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14757 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14758 				i, core_relo.insn_off, prog->len);
14759 			err = -EINVAL;
14760 			break;
14761 		}
14762 
14763 		err = bpf_core_apply(&ctx, &core_relo, i,
14764 				     &prog->insnsi[core_relo.insn_off / 8]);
14765 		if (err)
14766 			break;
14767 		bpfptr_add(&u_core_relo, rec_size);
14768 	}
14769 	return err;
14770 }
14771 
14772 static int check_btf_info(struct bpf_verifier_env *env,
14773 			  const union bpf_attr *attr,
14774 			  bpfptr_t uattr)
14775 {
14776 	struct btf *btf;
14777 	int err;
14778 
14779 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
14780 		if (check_abnormal_return(env))
14781 			return -EINVAL;
14782 		return 0;
14783 	}
14784 
14785 	btf = btf_get_by_fd(attr->prog_btf_fd);
14786 	if (IS_ERR(btf))
14787 		return PTR_ERR(btf);
14788 	if (btf_is_kernel(btf)) {
14789 		btf_put(btf);
14790 		return -EACCES;
14791 	}
14792 	env->prog->aux->btf = btf;
14793 
14794 	err = check_btf_func(env, attr, uattr);
14795 	if (err)
14796 		return err;
14797 
14798 	err = check_btf_line(env, attr, uattr);
14799 	if (err)
14800 		return err;
14801 
14802 	err = check_core_relo(env, attr, uattr);
14803 	if (err)
14804 		return err;
14805 
14806 	return 0;
14807 }
14808 
14809 /* check %cur's range satisfies %old's */
14810 static bool range_within(struct bpf_reg_state *old,
14811 			 struct bpf_reg_state *cur)
14812 {
14813 	return old->umin_value <= cur->umin_value &&
14814 	       old->umax_value >= cur->umax_value &&
14815 	       old->smin_value <= cur->smin_value &&
14816 	       old->smax_value >= cur->smax_value &&
14817 	       old->u32_min_value <= cur->u32_min_value &&
14818 	       old->u32_max_value >= cur->u32_max_value &&
14819 	       old->s32_min_value <= cur->s32_min_value &&
14820 	       old->s32_max_value >= cur->s32_max_value;
14821 }
14822 
14823 /* If in the old state two registers had the same id, then they need to have
14824  * the same id in the new state as well.  But that id could be different from
14825  * the old state, so we need to track the mapping from old to new ids.
14826  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14827  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
14828  * regs with a different old id could still have new id 9, we don't care about
14829  * that.
14830  * So we look through our idmap to see if this old id has been seen before.  If
14831  * so, we require the new id to match; otherwise, we add the id pair to the map.
14832  */
14833 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14834 {
14835 	unsigned int i;
14836 
14837 	/* either both IDs should be set or both should be zero */
14838 	if (!!old_id != !!cur_id)
14839 		return false;
14840 
14841 	if (old_id == 0) /* cur_id == 0 as well */
14842 		return true;
14843 
14844 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14845 		if (!idmap[i].old) {
14846 			/* Reached an empty slot; haven't seen this id before */
14847 			idmap[i].old = old_id;
14848 			idmap[i].cur = cur_id;
14849 			return true;
14850 		}
14851 		if (idmap[i].old == old_id)
14852 			return idmap[i].cur == cur_id;
14853 	}
14854 	/* We ran out of idmap slots, which should be impossible */
14855 	WARN_ON_ONCE(1);
14856 	return false;
14857 }
14858 
14859 static void clean_func_state(struct bpf_verifier_env *env,
14860 			     struct bpf_func_state *st)
14861 {
14862 	enum bpf_reg_liveness live;
14863 	int i, j;
14864 
14865 	for (i = 0; i < BPF_REG_FP; i++) {
14866 		live = st->regs[i].live;
14867 		/* liveness must not touch this register anymore */
14868 		st->regs[i].live |= REG_LIVE_DONE;
14869 		if (!(live & REG_LIVE_READ))
14870 			/* since the register is unused, clear its state
14871 			 * to make further comparison simpler
14872 			 */
14873 			__mark_reg_not_init(env, &st->regs[i]);
14874 	}
14875 
14876 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14877 		live = st->stack[i].spilled_ptr.live;
14878 		/* liveness must not touch this stack slot anymore */
14879 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14880 		if (!(live & REG_LIVE_READ)) {
14881 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14882 			for (j = 0; j < BPF_REG_SIZE; j++)
14883 				st->stack[i].slot_type[j] = STACK_INVALID;
14884 		}
14885 	}
14886 }
14887 
14888 static void clean_verifier_state(struct bpf_verifier_env *env,
14889 				 struct bpf_verifier_state *st)
14890 {
14891 	int i;
14892 
14893 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14894 		/* all regs in this state in all frames were already marked */
14895 		return;
14896 
14897 	for (i = 0; i <= st->curframe; i++)
14898 		clean_func_state(env, st->frame[i]);
14899 }
14900 
14901 /* the parentage chains form a tree.
14902  * the verifier states are added to state lists at given insn and
14903  * pushed into state stack for future exploration.
14904  * when the verifier reaches bpf_exit insn some of the verifer states
14905  * stored in the state lists have their final liveness state already,
14906  * but a lot of states will get revised from liveness point of view when
14907  * the verifier explores other branches.
14908  * Example:
14909  * 1: r0 = 1
14910  * 2: if r1 == 100 goto pc+1
14911  * 3: r0 = 2
14912  * 4: exit
14913  * when the verifier reaches exit insn the register r0 in the state list of
14914  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14915  * of insn 2 and goes exploring further. At the insn 4 it will walk the
14916  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14917  *
14918  * Since the verifier pushes the branch states as it sees them while exploring
14919  * the program the condition of walking the branch instruction for the second
14920  * time means that all states below this branch were already explored and
14921  * their final liveness marks are already propagated.
14922  * Hence when the verifier completes the search of state list in is_state_visited()
14923  * we can call this clean_live_states() function to mark all liveness states
14924  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14925  * will not be used.
14926  * This function also clears the registers and stack for states that !READ
14927  * to simplify state merging.
14928  *
14929  * Important note here that walking the same branch instruction in the callee
14930  * doesn't meant that the states are DONE. The verifier has to compare
14931  * the callsites
14932  */
14933 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14934 			      struct bpf_verifier_state *cur)
14935 {
14936 	struct bpf_verifier_state_list *sl;
14937 	int i;
14938 
14939 	sl = *explored_state(env, insn);
14940 	while (sl) {
14941 		if (sl->state.branches)
14942 			goto next;
14943 		if (sl->state.insn_idx != insn ||
14944 		    sl->state.curframe != cur->curframe)
14945 			goto next;
14946 		for (i = 0; i <= cur->curframe; i++)
14947 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14948 				goto next;
14949 		clean_verifier_state(env, &sl->state);
14950 next:
14951 		sl = sl->next;
14952 	}
14953 }
14954 
14955 static bool regs_exact(const struct bpf_reg_state *rold,
14956 		       const struct bpf_reg_state *rcur,
14957 		       struct bpf_id_pair *idmap)
14958 {
14959 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
14960 	       check_ids(rold->id, rcur->id, idmap) &&
14961 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14962 }
14963 
14964 /* Returns true if (rold safe implies rcur safe) */
14965 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14966 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14967 {
14968 	if (!(rold->live & REG_LIVE_READ))
14969 		/* explored state didn't use this */
14970 		return true;
14971 	if (rold->type == NOT_INIT)
14972 		/* explored state can't have used this */
14973 		return true;
14974 	if (rcur->type == NOT_INIT)
14975 		return false;
14976 
14977 	/* Enforce that register types have to match exactly, including their
14978 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14979 	 * rule.
14980 	 *
14981 	 * One can make a point that using a pointer register as unbounded
14982 	 * SCALAR would be technically acceptable, but this could lead to
14983 	 * pointer leaks because scalars are allowed to leak while pointers
14984 	 * are not. We could make this safe in special cases if root is
14985 	 * calling us, but it's probably not worth the hassle.
14986 	 *
14987 	 * Also, register types that are *not* MAYBE_NULL could technically be
14988 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14989 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14990 	 * to the same map).
14991 	 * However, if the old MAYBE_NULL register then got NULL checked,
14992 	 * doing so could have affected others with the same id, and we can't
14993 	 * check for that because we lost the id when we converted to
14994 	 * a non-MAYBE_NULL variant.
14995 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
14996 	 * non-MAYBE_NULL registers as well.
14997 	 */
14998 	if (rold->type != rcur->type)
14999 		return false;
15000 
15001 	switch (base_type(rold->type)) {
15002 	case SCALAR_VALUE:
15003 		if (regs_exact(rold, rcur, idmap))
15004 			return true;
15005 		if (env->explore_alu_limits)
15006 			return false;
15007 		if (!rold->precise)
15008 			return true;
15009 		/* new val must satisfy old val knowledge */
15010 		return range_within(rold, rcur) &&
15011 		       tnum_in(rold->var_off, rcur->var_off);
15012 	case PTR_TO_MAP_KEY:
15013 	case PTR_TO_MAP_VALUE:
15014 	case PTR_TO_MEM:
15015 	case PTR_TO_BUF:
15016 	case PTR_TO_TP_BUFFER:
15017 		/* If the new min/max/var_off satisfy the old ones and
15018 		 * everything else matches, we are OK.
15019 		 */
15020 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15021 		       range_within(rold, rcur) &&
15022 		       tnum_in(rold->var_off, rcur->var_off) &&
15023 		       check_ids(rold->id, rcur->id, idmap) &&
15024 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15025 	case PTR_TO_PACKET_META:
15026 	case PTR_TO_PACKET:
15027 		/* We must have at least as much range as the old ptr
15028 		 * did, so that any accesses which were safe before are
15029 		 * still safe.  This is true even if old range < old off,
15030 		 * since someone could have accessed through (ptr - k), or
15031 		 * even done ptr -= k in a register, to get a safe access.
15032 		 */
15033 		if (rold->range > rcur->range)
15034 			return false;
15035 		/* If the offsets don't match, we can't trust our alignment;
15036 		 * nor can we be sure that we won't fall out of range.
15037 		 */
15038 		if (rold->off != rcur->off)
15039 			return false;
15040 		/* id relations must be preserved */
15041 		if (!check_ids(rold->id, rcur->id, idmap))
15042 			return false;
15043 		/* new val must satisfy old val knowledge */
15044 		return range_within(rold, rcur) &&
15045 		       tnum_in(rold->var_off, rcur->var_off);
15046 	case PTR_TO_STACK:
15047 		/* two stack pointers are equal only if they're pointing to
15048 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15049 		 */
15050 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15051 	default:
15052 		return regs_exact(rold, rcur, idmap);
15053 	}
15054 }
15055 
15056 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15057 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
15058 {
15059 	int i, spi;
15060 
15061 	/* walk slots of the explored stack and ignore any additional
15062 	 * slots in the current stack, since explored(safe) state
15063 	 * didn't use them
15064 	 */
15065 	for (i = 0; i < old->allocated_stack; i++) {
15066 		struct bpf_reg_state *old_reg, *cur_reg;
15067 
15068 		spi = i / BPF_REG_SIZE;
15069 
15070 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15071 			i += BPF_REG_SIZE - 1;
15072 			/* explored state didn't use this */
15073 			continue;
15074 		}
15075 
15076 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15077 			continue;
15078 
15079 		if (env->allow_uninit_stack &&
15080 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15081 			continue;
15082 
15083 		/* explored stack has more populated slots than current stack
15084 		 * and these slots were used
15085 		 */
15086 		if (i >= cur->allocated_stack)
15087 			return false;
15088 
15089 		/* if old state was safe with misc data in the stack
15090 		 * it will be safe with zero-initialized stack.
15091 		 * The opposite is not true
15092 		 */
15093 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15094 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15095 			continue;
15096 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15097 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15098 			/* Ex: old explored (safe) state has STACK_SPILL in
15099 			 * this stack slot, but current has STACK_MISC ->
15100 			 * this verifier states are not equivalent,
15101 			 * return false to continue verification of this path
15102 			 */
15103 			return false;
15104 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15105 			continue;
15106 		/* Both old and cur are having same slot_type */
15107 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15108 		case STACK_SPILL:
15109 			/* when explored and current stack slot are both storing
15110 			 * spilled registers, check that stored pointers types
15111 			 * are the same as well.
15112 			 * Ex: explored safe path could have stored
15113 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15114 			 * but current path has stored:
15115 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15116 			 * such verifier states are not equivalent.
15117 			 * return false to continue verification of this path
15118 			 */
15119 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15120 				     &cur->stack[spi].spilled_ptr, idmap))
15121 				return false;
15122 			break;
15123 		case STACK_DYNPTR:
15124 			old_reg = &old->stack[spi].spilled_ptr;
15125 			cur_reg = &cur->stack[spi].spilled_ptr;
15126 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15127 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15128 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15129 				return false;
15130 			break;
15131 		case STACK_ITER:
15132 			old_reg = &old->stack[spi].spilled_ptr;
15133 			cur_reg = &cur->stack[spi].spilled_ptr;
15134 			/* iter.depth is not compared between states as it
15135 			 * doesn't matter for correctness and would otherwise
15136 			 * prevent convergence; we maintain it only to prevent
15137 			 * infinite loop check triggering, see
15138 			 * iter_active_depths_differ()
15139 			 */
15140 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15141 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15142 			    old_reg->iter.state != cur_reg->iter.state ||
15143 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15144 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15145 				return false;
15146 			break;
15147 		case STACK_MISC:
15148 		case STACK_ZERO:
15149 		case STACK_INVALID:
15150 			continue;
15151 		/* Ensure that new unhandled slot types return false by default */
15152 		default:
15153 			return false;
15154 		}
15155 	}
15156 	return true;
15157 }
15158 
15159 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15160 		    struct bpf_id_pair *idmap)
15161 {
15162 	int i;
15163 
15164 	if (old->acquired_refs != cur->acquired_refs)
15165 		return false;
15166 
15167 	for (i = 0; i < old->acquired_refs; i++) {
15168 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15169 			return false;
15170 	}
15171 
15172 	return true;
15173 }
15174 
15175 /* compare two verifier states
15176  *
15177  * all states stored in state_list are known to be valid, since
15178  * verifier reached 'bpf_exit' instruction through them
15179  *
15180  * this function is called when verifier exploring different branches of
15181  * execution popped from the state stack. If it sees an old state that has
15182  * more strict register state and more strict stack state then this execution
15183  * branch doesn't need to be explored further, since verifier already
15184  * concluded that more strict state leads to valid finish.
15185  *
15186  * Therefore two states are equivalent if register state is more conservative
15187  * and explored stack state is more conservative than the current one.
15188  * Example:
15189  *       explored                   current
15190  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15191  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15192  *
15193  * In other words if current stack state (one being explored) has more
15194  * valid slots than old one that already passed validation, it means
15195  * the verifier can stop exploring and conclude that current state is valid too
15196  *
15197  * Similarly with registers. If explored state has register type as invalid
15198  * whereas register type in current state is meaningful, it means that
15199  * the current state will reach 'bpf_exit' instruction safely
15200  */
15201 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15202 			      struct bpf_func_state *cur)
15203 {
15204 	int i;
15205 
15206 	for (i = 0; i < MAX_BPF_REG; i++)
15207 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15208 			     env->idmap_scratch))
15209 			return false;
15210 
15211 	if (!stacksafe(env, old, cur, env->idmap_scratch))
15212 		return false;
15213 
15214 	if (!refsafe(old, cur, env->idmap_scratch))
15215 		return false;
15216 
15217 	return true;
15218 }
15219 
15220 static bool states_equal(struct bpf_verifier_env *env,
15221 			 struct bpf_verifier_state *old,
15222 			 struct bpf_verifier_state *cur)
15223 {
15224 	int i;
15225 
15226 	if (old->curframe != cur->curframe)
15227 		return false;
15228 
15229 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
15230 
15231 	/* Verification state from speculative execution simulation
15232 	 * must never prune a non-speculative execution one.
15233 	 */
15234 	if (old->speculative && !cur->speculative)
15235 		return false;
15236 
15237 	if (old->active_lock.ptr != cur->active_lock.ptr)
15238 		return false;
15239 
15240 	/* Old and cur active_lock's have to be either both present
15241 	 * or both absent.
15242 	 */
15243 	if (!!old->active_lock.id != !!cur->active_lock.id)
15244 		return false;
15245 
15246 	if (old->active_lock.id &&
15247 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
15248 		return false;
15249 
15250 	if (old->active_rcu_lock != cur->active_rcu_lock)
15251 		return false;
15252 
15253 	/* for states to be equal callsites have to be the same
15254 	 * and all frame states need to be equivalent
15255 	 */
15256 	for (i = 0; i <= old->curframe; i++) {
15257 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15258 			return false;
15259 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15260 			return false;
15261 	}
15262 	return true;
15263 }
15264 
15265 /* Return 0 if no propagation happened. Return negative error code if error
15266  * happened. Otherwise, return the propagated bit.
15267  */
15268 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15269 				  struct bpf_reg_state *reg,
15270 				  struct bpf_reg_state *parent_reg)
15271 {
15272 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15273 	u8 flag = reg->live & REG_LIVE_READ;
15274 	int err;
15275 
15276 	/* When comes here, read flags of PARENT_REG or REG could be any of
15277 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15278 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15279 	 */
15280 	if (parent_flag == REG_LIVE_READ64 ||
15281 	    /* Or if there is no read flag from REG. */
15282 	    !flag ||
15283 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15284 	    parent_flag == flag)
15285 		return 0;
15286 
15287 	err = mark_reg_read(env, reg, parent_reg, flag);
15288 	if (err)
15289 		return err;
15290 
15291 	return flag;
15292 }
15293 
15294 /* A write screens off any subsequent reads; but write marks come from the
15295  * straight-line code between a state and its parent.  When we arrive at an
15296  * equivalent state (jump target or such) we didn't arrive by the straight-line
15297  * code, so read marks in the state must propagate to the parent regardless
15298  * of the state's write marks. That's what 'parent == state->parent' comparison
15299  * in mark_reg_read() is for.
15300  */
15301 static int propagate_liveness(struct bpf_verifier_env *env,
15302 			      const struct bpf_verifier_state *vstate,
15303 			      struct bpf_verifier_state *vparent)
15304 {
15305 	struct bpf_reg_state *state_reg, *parent_reg;
15306 	struct bpf_func_state *state, *parent;
15307 	int i, frame, err = 0;
15308 
15309 	if (vparent->curframe != vstate->curframe) {
15310 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15311 		     vparent->curframe, vstate->curframe);
15312 		return -EFAULT;
15313 	}
15314 	/* Propagate read liveness of registers... */
15315 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15316 	for (frame = 0; frame <= vstate->curframe; frame++) {
15317 		parent = vparent->frame[frame];
15318 		state = vstate->frame[frame];
15319 		parent_reg = parent->regs;
15320 		state_reg = state->regs;
15321 		/* We don't need to worry about FP liveness, it's read-only */
15322 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15323 			err = propagate_liveness_reg(env, &state_reg[i],
15324 						     &parent_reg[i]);
15325 			if (err < 0)
15326 				return err;
15327 			if (err == REG_LIVE_READ64)
15328 				mark_insn_zext(env, &parent_reg[i]);
15329 		}
15330 
15331 		/* Propagate stack slots. */
15332 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15333 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15334 			parent_reg = &parent->stack[i].spilled_ptr;
15335 			state_reg = &state->stack[i].spilled_ptr;
15336 			err = propagate_liveness_reg(env, state_reg,
15337 						     parent_reg);
15338 			if (err < 0)
15339 				return err;
15340 		}
15341 	}
15342 	return 0;
15343 }
15344 
15345 /* find precise scalars in the previous equivalent state and
15346  * propagate them into the current state
15347  */
15348 static int propagate_precision(struct bpf_verifier_env *env,
15349 			       const struct bpf_verifier_state *old)
15350 {
15351 	struct bpf_reg_state *state_reg;
15352 	struct bpf_func_state *state;
15353 	int i, err = 0, fr;
15354 	bool first;
15355 
15356 	for (fr = old->curframe; fr >= 0; fr--) {
15357 		state = old->frame[fr];
15358 		state_reg = state->regs;
15359 		first = true;
15360 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15361 			if (state_reg->type != SCALAR_VALUE ||
15362 			    !state_reg->precise ||
15363 			    !(state_reg->live & REG_LIVE_READ))
15364 				continue;
15365 			if (env->log.level & BPF_LOG_LEVEL2) {
15366 				if (first)
15367 					verbose(env, "frame %d: propagating r%d", fr, i);
15368 				else
15369 					verbose(env, ",r%d", i);
15370 			}
15371 			bt_set_frame_reg(&env->bt, fr, i);
15372 			first = false;
15373 		}
15374 
15375 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15376 			if (!is_spilled_reg(&state->stack[i]))
15377 				continue;
15378 			state_reg = &state->stack[i].spilled_ptr;
15379 			if (state_reg->type != SCALAR_VALUE ||
15380 			    !state_reg->precise ||
15381 			    !(state_reg->live & REG_LIVE_READ))
15382 				continue;
15383 			if (env->log.level & BPF_LOG_LEVEL2) {
15384 				if (first)
15385 					verbose(env, "frame %d: propagating fp%d",
15386 						fr, (-i - 1) * BPF_REG_SIZE);
15387 				else
15388 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15389 			}
15390 			bt_set_frame_slot(&env->bt, fr, i);
15391 			first = false;
15392 		}
15393 		if (!first)
15394 			verbose(env, "\n");
15395 	}
15396 
15397 	err = mark_chain_precision_batch(env);
15398 	if (err < 0)
15399 		return err;
15400 
15401 	return 0;
15402 }
15403 
15404 static bool states_maybe_looping(struct bpf_verifier_state *old,
15405 				 struct bpf_verifier_state *cur)
15406 {
15407 	struct bpf_func_state *fold, *fcur;
15408 	int i, fr = cur->curframe;
15409 
15410 	if (old->curframe != fr)
15411 		return false;
15412 
15413 	fold = old->frame[fr];
15414 	fcur = cur->frame[fr];
15415 	for (i = 0; i < MAX_BPF_REG; i++)
15416 		if (memcmp(&fold->regs[i], &fcur->regs[i],
15417 			   offsetof(struct bpf_reg_state, parent)))
15418 			return false;
15419 	return true;
15420 }
15421 
15422 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15423 {
15424 	return env->insn_aux_data[insn_idx].is_iter_next;
15425 }
15426 
15427 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15428  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15429  * states to match, which otherwise would look like an infinite loop. So while
15430  * iter_next() calls are taken care of, we still need to be careful and
15431  * prevent erroneous and too eager declaration of "ininite loop", when
15432  * iterators are involved.
15433  *
15434  * Here's a situation in pseudo-BPF assembly form:
15435  *
15436  *   0: again:                          ; set up iter_next() call args
15437  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15438  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15439  *   3:   if r0 == 0 goto done
15440  *   4:   ... something useful here ...
15441  *   5:   goto again                    ; another iteration
15442  *   6: done:
15443  *   7:   r1 = &it
15444  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15445  *   9:   exit
15446  *
15447  * This is a typical loop. Let's assume that we have a prune point at 1:,
15448  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15449  * again`, assuming other heuristics don't get in a way).
15450  *
15451  * When we first time come to 1:, let's say we have some state X. We proceed
15452  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15453  * Now we come back to validate that forked ACTIVE state. We proceed through
15454  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15455  * are converging. But the problem is that we don't know that yet, as this
15456  * convergence has to happen at iter_next() call site only. So if nothing is
15457  * done, at 1: verifier will use bounded loop logic and declare infinite
15458  * looping (and would be *technically* correct, if not for iterator's
15459  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15460  * don't want that. So what we do in process_iter_next_call() when we go on
15461  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15462  * a different iteration. So when we suspect an infinite loop, we additionally
15463  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15464  * pretend we are not looping and wait for next iter_next() call.
15465  *
15466  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15467  * loop, because that would actually mean infinite loop, as DRAINED state is
15468  * "sticky", and so we'll keep returning into the same instruction with the
15469  * same state (at least in one of possible code paths).
15470  *
15471  * This approach allows to keep infinite loop heuristic even in the face of
15472  * active iterator. E.g., C snippet below is and will be detected as
15473  * inifintely looping:
15474  *
15475  *   struct bpf_iter_num it;
15476  *   int *p, x;
15477  *
15478  *   bpf_iter_num_new(&it, 0, 10);
15479  *   while ((p = bpf_iter_num_next(&t))) {
15480  *       x = p;
15481  *       while (x--) {} // <<-- infinite loop here
15482  *   }
15483  *
15484  */
15485 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15486 {
15487 	struct bpf_reg_state *slot, *cur_slot;
15488 	struct bpf_func_state *state;
15489 	int i, fr;
15490 
15491 	for (fr = old->curframe; fr >= 0; fr--) {
15492 		state = old->frame[fr];
15493 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15494 			if (state->stack[i].slot_type[0] != STACK_ITER)
15495 				continue;
15496 
15497 			slot = &state->stack[i].spilled_ptr;
15498 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15499 				continue;
15500 
15501 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15502 			if (cur_slot->iter.depth != slot->iter.depth)
15503 				return true;
15504 		}
15505 	}
15506 	return false;
15507 }
15508 
15509 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15510 {
15511 	struct bpf_verifier_state_list *new_sl;
15512 	struct bpf_verifier_state_list *sl, **pprev;
15513 	struct bpf_verifier_state *cur = env->cur_state, *new;
15514 	int i, j, err, states_cnt = 0;
15515 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15516 	bool add_new_state = force_new_state;
15517 
15518 	/* bpf progs typically have pruning point every 4 instructions
15519 	 * http://vger.kernel.org/bpfconf2019.html#session-1
15520 	 * Do not add new state for future pruning if the verifier hasn't seen
15521 	 * at least 2 jumps and at least 8 instructions.
15522 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15523 	 * In tests that amounts to up to 50% reduction into total verifier
15524 	 * memory consumption and 20% verifier time speedup.
15525 	 */
15526 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15527 	    env->insn_processed - env->prev_insn_processed >= 8)
15528 		add_new_state = true;
15529 
15530 	pprev = explored_state(env, insn_idx);
15531 	sl = *pprev;
15532 
15533 	clean_live_states(env, insn_idx, cur);
15534 
15535 	while (sl) {
15536 		states_cnt++;
15537 		if (sl->state.insn_idx != insn_idx)
15538 			goto next;
15539 
15540 		if (sl->state.branches) {
15541 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15542 
15543 			if (frame->in_async_callback_fn &&
15544 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15545 				/* Different async_entry_cnt means that the verifier is
15546 				 * processing another entry into async callback.
15547 				 * Seeing the same state is not an indication of infinite
15548 				 * loop or infinite recursion.
15549 				 * But finding the same state doesn't mean that it's safe
15550 				 * to stop processing the current state. The previous state
15551 				 * hasn't yet reached bpf_exit, since state.branches > 0.
15552 				 * Checking in_async_callback_fn alone is not enough either.
15553 				 * Since the verifier still needs to catch infinite loops
15554 				 * inside async callbacks.
15555 				 */
15556 				goto skip_inf_loop_check;
15557 			}
15558 			/* BPF open-coded iterators loop detection is special.
15559 			 * states_maybe_looping() logic is too simplistic in detecting
15560 			 * states that *might* be equivalent, because it doesn't know
15561 			 * about ID remapping, so don't even perform it.
15562 			 * See process_iter_next_call() and iter_active_depths_differ()
15563 			 * for overview of the logic. When current and one of parent
15564 			 * states are detected as equivalent, it's a good thing: we prove
15565 			 * convergence and can stop simulating further iterations.
15566 			 * It's safe to assume that iterator loop will finish, taking into
15567 			 * account iter_next() contract of eventually returning
15568 			 * sticky NULL result.
15569 			 */
15570 			if (is_iter_next_insn(env, insn_idx)) {
15571 				if (states_equal(env, &sl->state, cur)) {
15572 					struct bpf_func_state *cur_frame;
15573 					struct bpf_reg_state *iter_state, *iter_reg;
15574 					int spi;
15575 
15576 					cur_frame = cur->frame[cur->curframe];
15577 					/* btf_check_iter_kfuncs() enforces that
15578 					 * iter state pointer is always the first arg
15579 					 */
15580 					iter_reg = &cur_frame->regs[BPF_REG_1];
15581 					/* current state is valid due to states_equal(),
15582 					 * so we can assume valid iter and reg state,
15583 					 * no need for extra (re-)validations
15584 					 */
15585 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15586 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15587 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15588 						goto hit;
15589 				}
15590 				goto skip_inf_loop_check;
15591 			}
15592 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
15593 			if (states_maybe_looping(&sl->state, cur) &&
15594 			    states_equal(env, &sl->state, cur) &&
15595 			    !iter_active_depths_differ(&sl->state, cur)) {
15596 				verbose_linfo(env, insn_idx, "; ");
15597 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15598 				return -EINVAL;
15599 			}
15600 			/* if the verifier is processing a loop, avoid adding new state
15601 			 * too often, since different loop iterations have distinct
15602 			 * states and may not help future pruning.
15603 			 * This threshold shouldn't be too low to make sure that
15604 			 * a loop with large bound will be rejected quickly.
15605 			 * The most abusive loop will be:
15606 			 * r1 += 1
15607 			 * if r1 < 1000000 goto pc-2
15608 			 * 1M insn_procssed limit / 100 == 10k peak states.
15609 			 * This threshold shouldn't be too high either, since states
15610 			 * at the end of the loop are likely to be useful in pruning.
15611 			 */
15612 skip_inf_loop_check:
15613 			if (!force_new_state &&
15614 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
15615 			    env->insn_processed - env->prev_insn_processed < 100)
15616 				add_new_state = false;
15617 			goto miss;
15618 		}
15619 		if (states_equal(env, &sl->state, cur)) {
15620 hit:
15621 			sl->hit_cnt++;
15622 			/* reached equivalent register/stack state,
15623 			 * prune the search.
15624 			 * Registers read by the continuation are read by us.
15625 			 * If we have any write marks in env->cur_state, they
15626 			 * will prevent corresponding reads in the continuation
15627 			 * from reaching our parent (an explored_state).  Our
15628 			 * own state will get the read marks recorded, but
15629 			 * they'll be immediately forgotten as we're pruning
15630 			 * this state and will pop a new one.
15631 			 */
15632 			err = propagate_liveness(env, &sl->state, cur);
15633 
15634 			/* if previous state reached the exit with precision and
15635 			 * current state is equivalent to it (except precsion marks)
15636 			 * the precision needs to be propagated back in
15637 			 * the current state.
15638 			 */
15639 			err = err ? : push_jmp_history(env, cur);
15640 			err = err ? : propagate_precision(env, &sl->state);
15641 			if (err)
15642 				return err;
15643 			return 1;
15644 		}
15645 miss:
15646 		/* when new state is not going to be added do not increase miss count.
15647 		 * Otherwise several loop iterations will remove the state
15648 		 * recorded earlier. The goal of these heuristics is to have
15649 		 * states from some iterations of the loop (some in the beginning
15650 		 * and some at the end) to help pruning.
15651 		 */
15652 		if (add_new_state)
15653 			sl->miss_cnt++;
15654 		/* heuristic to determine whether this state is beneficial
15655 		 * to keep checking from state equivalence point of view.
15656 		 * Higher numbers increase max_states_per_insn and verification time,
15657 		 * but do not meaningfully decrease insn_processed.
15658 		 */
15659 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15660 			/* the state is unlikely to be useful. Remove it to
15661 			 * speed up verification
15662 			 */
15663 			*pprev = sl->next;
15664 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15665 				u32 br = sl->state.branches;
15666 
15667 				WARN_ONCE(br,
15668 					  "BUG live_done but branches_to_explore %d\n",
15669 					  br);
15670 				free_verifier_state(&sl->state, false);
15671 				kfree(sl);
15672 				env->peak_states--;
15673 			} else {
15674 				/* cannot free this state, since parentage chain may
15675 				 * walk it later. Add it for free_list instead to
15676 				 * be freed at the end of verification
15677 				 */
15678 				sl->next = env->free_list;
15679 				env->free_list = sl;
15680 			}
15681 			sl = *pprev;
15682 			continue;
15683 		}
15684 next:
15685 		pprev = &sl->next;
15686 		sl = *pprev;
15687 	}
15688 
15689 	if (env->max_states_per_insn < states_cnt)
15690 		env->max_states_per_insn = states_cnt;
15691 
15692 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15693 		return 0;
15694 
15695 	if (!add_new_state)
15696 		return 0;
15697 
15698 	/* There were no equivalent states, remember the current one.
15699 	 * Technically the current state is not proven to be safe yet,
15700 	 * but it will either reach outer most bpf_exit (which means it's safe)
15701 	 * or it will be rejected. When there are no loops the verifier won't be
15702 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15703 	 * again on the way to bpf_exit.
15704 	 * When looping the sl->state.branches will be > 0 and this state
15705 	 * will not be considered for equivalence until branches == 0.
15706 	 */
15707 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15708 	if (!new_sl)
15709 		return -ENOMEM;
15710 	env->total_states++;
15711 	env->peak_states++;
15712 	env->prev_jmps_processed = env->jmps_processed;
15713 	env->prev_insn_processed = env->insn_processed;
15714 
15715 	/* forget precise markings we inherited, see __mark_chain_precision */
15716 	if (env->bpf_capable)
15717 		mark_all_scalars_imprecise(env, cur);
15718 
15719 	/* add new state to the head of linked list */
15720 	new = &new_sl->state;
15721 	err = copy_verifier_state(new, cur);
15722 	if (err) {
15723 		free_verifier_state(new, false);
15724 		kfree(new_sl);
15725 		return err;
15726 	}
15727 	new->insn_idx = insn_idx;
15728 	WARN_ONCE(new->branches != 1,
15729 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
15730 
15731 	cur->parent = new;
15732 	cur->first_insn_idx = insn_idx;
15733 	clear_jmp_history(cur);
15734 	new_sl->next = *explored_state(env, insn_idx);
15735 	*explored_state(env, insn_idx) = new_sl;
15736 	/* connect new state to parentage chain. Current frame needs all
15737 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
15738 	 * to the stack implicitly by JITs) so in callers' frames connect just
15739 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15740 	 * the state of the call instruction (with WRITTEN set), and r0 comes
15741 	 * from callee with its full parentage chain, anyway.
15742 	 */
15743 	/* clear write marks in current state: the writes we did are not writes
15744 	 * our child did, so they don't screen off its reads from us.
15745 	 * (There are no read marks in current state, because reads always mark
15746 	 * their parent and current state never has children yet.  Only
15747 	 * explored_states can get read marks.)
15748 	 */
15749 	for (j = 0; j <= cur->curframe; j++) {
15750 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15751 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15752 		for (i = 0; i < BPF_REG_FP; i++)
15753 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15754 	}
15755 
15756 	/* all stack frames are accessible from callee, clear them all */
15757 	for (j = 0; j <= cur->curframe; j++) {
15758 		struct bpf_func_state *frame = cur->frame[j];
15759 		struct bpf_func_state *newframe = new->frame[j];
15760 
15761 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
15762 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
15763 			frame->stack[i].spilled_ptr.parent =
15764 						&newframe->stack[i].spilled_ptr;
15765 		}
15766 	}
15767 	return 0;
15768 }
15769 
15770 /* Return true if it's OK to have the same insn return a different type. */
15771 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15772 {
15773 	switch (base_type(type)) {
15774 	case PTR_TO_CTX:
15775 	case PTR_TO_SOCKET:
15776 	case PTR_TO_SOCK_COMMON:
15777 	case PTR_TO_TCP_SOCK:
15778 	case PTR_TO_XDP_SOCK:
15779 	case PTR_TO_BTF_ID:
15780 		return false;
15781 	default:
15782 		return true;
15783 	}
15784 }
15785 
15786 /* If an instruction was previously used with particular pointer types, then we
15787  * need to be careful to avoid cases such as the below, where it may be ok
15788  * for one branch accessing the pointer, but not ok for the other branch:
15789  *
15790  * R1 = sock_ptr
15791  * goto X;
15792  * ...
15793  * R1 = some_other_valid_ptr;
15794  * goto X;
15795  * ...
15796  * R2 = *(u32 *)(R1 + 0);
15797  */
15798 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15799 {
15800 	return src != prev && (!reg_type_mismatch_ok(src) ||
15801 			       !reg_type_mismatch_ok(prev));
15802 }
15803 
15804 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15805 			     bool allow_trust_missmatch)
15806 {
15807 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15808 
15809 	if (*prev_type == NOT_INIT) {
15810 		/* Saw a valid insn
15811 		 * dst_reg = *(u32 *)(src_reg + off)
15812 		 * save type to validate intersecting paths
15813 		 */
15814 		*prev_type = type;
15815 	} else if (reg_type_mismatch(type, *prev_type)) {
15816 		/* Abuser program is trying to use the same insn
15817 		 * dst_reg = *(u32*) (src_reg + off)
15818 		 * with different pointer types:
15819 		 * src_reg == ctx in one branch and
15820 		 * src_reg == stack|map in some other branch.
15821 		 * Reject it.
15822 		 */
15823 		if (allow_trust_missmatch &&
15824 		    base_type(type) == PTR_TO_BTF_ID &&
15825 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
15826 			/*
15827 			 * Have to support a use case when one path through
15828 			 * the program yields TRUSTED pointer while another
15829 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
15830 			 * BPF_PROBE_MEM.
15831 			 */
15832 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15833 		} else {
15834 			verbose(env, "same insn cannot be used with different pointers\n");
15835 			return -EINVAL;
15836 		}
15837 	}
15838 
15839 	return 0;
15840 }
15841 
15842 static int do_check(struct bpf_verifier_env *env)
15843 {
15844 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15845 	struct bpf_verifier_state *state = env->cur_state;
15846 	struct bpf_insn *insns = env->prog->insnsi;
15847 	struct bpf_reg_state *regs;
15848 	int insn_cnt = env->prog->len;
15849 	bool do_print_state = false;
15850 	int prev_insn_idx = -1;
15851 
15852 	for (;;) {
15853 		struct bpf_insn *insn;
15854 		u8 class;
15855 		int err;
15856 
15857 		env->prev_insn_idx = prev_insn_idx;
15858 		if (env->insn_idx >= insn_cnt) {
15859 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
15860 				env->insn_idx, insn_cnt);
15861 			return -EFAULT;
15862 		}
15863 
15864 		insn = &insns[env->insn_idx];
15865 		class = BPF_CLASS(insn->code);
15866 
15867 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
15868 			verbose(env,
15869 				"BPF program is too large. Processed %d insn\n",
15870 				env->insn_processed);
15871 			return -E2BIG;
15872 		}
15873 
15874 		state->last_insn_idx = env->prev_insn_idx;
15875 
15876 		if (is_prune_point(env, env->insn_idx)) {
15877 			err = is_state_visited(env, env->insn_idx);
15878 			if (err < 0)
15879 				return err;
15880 			if (err == 1) {
15881 				/* found equivalent state, can prune the search */
15882 				if (env->log.level & BPF_LOG_LEVEL) {
15883 					if (do_print_state)
15884 						verbose(env, "\nfrom %d to %d%s: safe\n",
15885 							env->prev_insn_idx, env->insn_idx,
15886 							env->cur_state->speculative ?
15887 							" (speculative execution)" : "");
15888 					else
15889 						verbose(env, "%d: safe\n", env->insn_idx);
15890 				}
15891 				goto process_bpf_exit;
15892 			}
15893 		}
15894 
15895 		if (is_jmp_point(env, env->insn_idx)) {
15896 			err = push_jmp_history(env, state);
15897 			if (err)
15898 				return err;
15899 		}
15900 
15901 		if (signal_pending(current))
15902 			return -EAGAIN;
15903 
15904 		if (need_resched())
15905 			cond_resched();
15906 
15907 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
15908 			verbose(env, "\nfrom %d to %d%s:",
15909 				env->prev_insn_idx, env->insn_idx,
15910 				env->cur_state->speculative ?
15911 				" (speculative execution)" : "");
15912 			print_verifier_state(env, state->frame[state->curframe], true);
15913 			do_print_state = false;
15914 		}
15915 
15916 		if (env->log.level & BPF_LOG_LEVEL) {
15917 			const struct bpf_insn_cbs cbs = {
15918 				.cb_call	= disasm_kfunc_name,
15919 				.cb_print	= verbose,
15920 				.private_data	= env,
15921 			};
15922 
15923 			if (verifier_state_scratched(env))
15924 				print_insn_state(env, state->frame[state->curframe]);
15925 
15926 			verbose_linfo(env, env->insn_idx, "; ");
15927 			env->prev_log_pos = env->log.end_pos;
15928 			verbose(env, "%d: ", env->insn_idx);
15929 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
15930 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
15931 			env->prev_log_pos = env->log.end_pos;
15932 		}
15933 
15934 		if (bpf_prog_is_offloaded(env->prog->aux)) {
15935 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
15936 							   env->prev_insn_idx);
15937 			if (err)
15938 				return err;
15939 		}
15940 
15941 		regs = cur_regs(env);
15942 		sanitize_mark_insn_seen(env);
15943 		prev_insn_idx = env->insn_idx;
15944 
15945 		if (class == BPF_ALU || class == BPF_ALU64) {
15946 			err = check_alu_op(env, insn);
15947 			if (err)
15948 				return err;
15949 
15950 		} else if (class == BPF_LDX) {
15951 			enum bpf_reg_type src_reg_type;
15952 
15953 			/* check for reserved fields is already done */
15954 
15955 			/* check src operand */
15956 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15957 			if (err)
15958 				return err;
15959 
15960 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15961 			if (err)
15962 				return err;
15963 
15964 			src_reg_type = regs[insn->src_reg].type;
15965 
15966 			/* check that memory (src_reg + off) is readable,
15967 			 * the state of dst_reg will be updated by this func
15968 			 */
15969 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
15970 					       insn->off, BPF_SIZE(insn->code),
15971 					       BPF_READ, insn->dst_reg, false);
15972 			if (err)
15973 				return err;
15974 
15975 			err = save_aux_ptr_type(env, src_reg_type, true);
15976 			if (err)
15977 				return err;
15978 		} else if (class == BPF_STX) {
15979 			enum bpf_reg_type dst_reg_type;
15980 
15981 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15982 				err = check_atomic(env, env->insn_idx, insn);
15983 				if (err)
15984 					return err;
15985 				env->insn_idx++;
15986 				continue;
15987 			}
15988 
15989 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15990 				verbose(env, "BPF_STX uses reserved fields\n");
15991 				return -EINVAL;
15992 			}
15993 
15994 			/* check src1 operand */
15995 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15996 			if (err)
15997 				return err;
15998 			/* check src2 operand */
15999 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16000 			if (err)
16001 				return err;
16002 
16003 			dst_reg_type = regs[insn->dst_reg].type;
16004 
16005 			/* check that memory (dst_reg + off) is writeable */
16006 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16007 					       insn->off, BPF_SIZE(insn->code),
16008 					       BPF_WRITE, insn->src_reg, false);
16009 			if (err)
16010 				return err;
16011 
16012 			err = save_aux_ptr_type(env, dst_reg_type, false);
16013 			if (err)
16014 				return err;
16015 		} else if (class == BPF_ST) {
16016 			enum bpf_reg_type dst_reg_type;
16017 
16018 			if (BPF_MODE(insn->code) != BPF_MEM ||
16019 			    insn->src_reg != BPF_REG_0) {
16020 				verbose(env, "BPF_ST uses reserved fields\n");
16021 				return -EINVAL;
16022 			}
16023 			/* check src operand */
16024 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16025 			if (err)
16026 				return err;
16027 
16028 			dst_reg_type = regs[insn->dst_reg].type;
16029 
16030 			/* check that memory (dst_reg + off) is writeable */
16031 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16032 					       insn->off, BPF_SIZE(insn->code),
16033 					       BPF_WRITE, -1, false);
16034 			if (err)
16035 				return err;
16036 
16037 			err = save_aux_ptr_type(env, dst_reg_type, false);
16038 			if (err)
16039 				return err;
16040 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16041 			u8 opcode = BPF_OP(insn->code);
16042 
16043 			env->jmps_processed++;
16044 			if (opcode == BPF_CALL) {
16045 				if (BPF_SRC(insn->code) != BPF_K ||
16046 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16047 				     && insn->off != 0) ||
16048 				    (insn->src_reg != BPF_REG_0 &&
16049 				     insn->src_reg != BPF_PSEUDO_CALL &&
16050 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16051 				    insn->dst_reg != BPF_REG_0 ||
16052 				    class == BPF_JMP32) {
16053 					verbose(env, "BPF_CALL uses reserved fields\n");
16054 					return -EINVAL;
16055 				}
16056 
16057 				if (env->cur_state->active_lock.ptr) {
16058 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16059 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16060 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16061 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16062 						verbose(env, "function calls are not allowed while holding a lock\n");
16063 						return -EINVAL;
16064 					}
16065 				}
16066 				if (insn->src_reg == BPF_PSEUDO_CALL)
16067 					err = check_func_call(env, insn, &env->insn_idx);
16068 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16069 					err = check_kfunc_call(env, insn, &env->insn_idx);
16070 				else
16071 					err = check_helper_call(env, insn, &env->insn_idx);
16072 				if (err)
16073 					return err;
16074 
16075 				mark_reg_scratched(env, BPF_REG_0);
16076 			} else if (opcode == BPF_JA) {
16077 				if (BPF_SRC(insn->code) != BPF_K ||
16078 				    insn->imm != 0 ||
16079 				    insn->src_reg != BPF_REG_0 ||
16080 				    insn->dst_reg != BPF_REG_0 ||
16081 				    class == BPF_JMP32) {
16082 					verbose(env, "BPF_JA uses reserved fields\n");
16083 					return -EINVAL;
16084 				}
16085 
16086 				env->insn_idx += insn->off + 1;
16087 				continue;
16088 
16089 			} else if (opcode == BPF_EXIT) {
16090 				if (BPF_SRC(insn->code) != BPF_K ||
16091 				    insn->imm != 0 ||
16092 				    insn->src_reg != BPF_REG_0 ||
16093 				    insn->dst_reg != BPF_REG_0 ||
16094 				    class == BPF_JMP32) {
16095 					verbose(env, "BPF_EXIT uses reserved fields\n");
16096 					return -EINVAL;
16097 				}
16098 
16099 				if (env->cur_state->active_lock.ptr &&
16100 				    !in_rbtree_lock_required_cb(env)) {
16101 					verbose(env, "bpf_spin_unlock is missing\n");
16102 					return -EINVAL;
16103 				}
16104 
16105 				if (env->cur_state->active_rcu_lock) {
16106 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16107 					return -EINVAL;
16108 				}
16109 
16110 				/* We must do check_reference_leak here before
16111 				 * prepare_func_exit to handle the case when
16112 				 * state->curframe > 0, it may be a callback
16113 				 * function, for which reference_state must
16114 				 * match caller reference state when it exits.
16115 				 */
16116 				err = check_reference_leak(env);
16117 				if (err)
16118 					return err;
16119 
16120 				if (state->curframe) {
16121 					/* exit from nested function */
16122 					err = prepare_func_exit(env, &env->insn_idx);
16123 					if (err)
16124 						return err;
16125 					do_print_state = true;
16126 					continue;
16127 				}
16128 
16129 				err = check_return_code(env);
16130 				if (err)
16131 					return err;
16132 process_bpf_exit:
16133 				mark_verifier_state_scratched(env);
16134 				update_branch_counts(env, env->cur_state);
16135 				err = pop_stack(env, &prev_insn_idx,
16136 						&env->insn_idx, pop_log);
16137 				if (err < 0) {
16138 					if (err != -ENOENT)
16139 						return err;
16140 					break;
16141 				} else {
16142 					do_print_state = true;
16143 					continue;
16144 				}
16145 			} else {
16146 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16147 				if (err)
16148 					return err;
16149 			}
16150 		} else if (class == BPF_LD) {
16151 			u8 mode = BPF_MODE(insn->code);
16152 
16153 			if (mode == BPF_ABS || mode == BPF_IND) {
16154 				err = check_ld_abs(env, insn);
16155 				if (err)
16156 					return err;
16157 
16158 			} else if (mode == BPF_IMM) {
16159 				err = check_ld_imm(env, insn);
16160 				if (err)
16161 					return err;
16162 
16163 				env->insn_idx++;
16164 				sanitize_mark_insn_seen(env);
16165 			} else {
16166 				verbose(env, "invalid BPF_LD mode\n");
16167 				return -EINVAL;
16168 			}
16169 		} else {
16170 			verbose(env, "unknown insn class %d\n", class);
16171 			return -EINVAL;
16172 		}
16173 
16174 		env->insn_idx++;
16175 	}
16176 
16177 	return 0;
16178 }
16179 
16180 static int find_btf_percpu_datasec(struct btf *btf)
16181 {
16182 	const struct btf_type *t;
16183 	const char *tname;
16184 	int i, n;
16185 
16186 	/*
16187 	 * Both vmlinux and module each have their own ".data..percpu"
16188 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16189 	 * types to look at only module's own BTF types.
16190 	 */
16191 	n = btf_nr_types(btf);
16192 	if (btf_is_module(btf))
16193 		i = btf_nr_types(btf_vmlinux);
16194 	else
16195 		i = 1;
16196 
16197 	for(; i < n; i++) {
16198 		t = btf_type_by_id(btf, i);
16199 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16200 			continue;
16201 
16202 		tname = btf_name_by_offset(btf, t->name_off);
16203 		if (!strcmp(tname, ".data..percpu"))
16204 			return i;
16205 	}
16206 
16207 	return -ENOENT;
16208 }
16209 
16210 /* replace pseudo btf_id with kernel symbol address */
16211 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16212 			       struct bpf_insn *insn,
16213 			       struct bpf_insn_aux_data *aux)
16214 {
16215 	const struct btf_var_secinfo *vsi;
16216 	const struct btf_type *datasec;
16217 	struct btf_mod_pair *btf_mod;
16218 	const struct btf_type *t;
16219 	const char *sym_name;
16220 	bool percpu = false;
16221 	u32 type, id = insn->imm;
16222 	struct btf *btf;
16223 	s32 datasec_id;
16224 	u64 addr;
16225 	int i, btf_fd, err;
16226 
16227 	btf_fd = insn[1].imm;
16228 	if (btf_fd) {
16229 		btf = btf_get_by_fd(btf_fd);
16230 		if (IS_ERR(btf)) {
16231 			verbose(env, "invalid module BTF object FD specified.\n");
16232 			return -EINVAL;
16233 		}
16234 	} else {
16235 		if (!btf_vmlinux) {
16236 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16237 			return -EINVAL;
16238 		}
16239 		btf = btf_vmlinux;
16240 		btf_get(btf);
16241 	}
16242 
16243 	t = btf_type_by_id(btf, id);
16244 	if (!t) {
16245 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16246 		err = -ENOENT;
16247 		goto err_put;
16248 	}
16249 
16250 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16251 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16252 		err = -EINVAL;
16253 		goto err_put;
16254 	}
16255 
16256 	sym_name = btf_name_by_offset(btf, t->name_off);
16257 	addr = kallsyms_lookup_name(sym_name);
16258 	if (!addr) {
16259 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16260 			sym_name);
16261 		err = -ENOENT;
16262 		goto err_put;
16263 	}
16264 	insn[0].imm = (u32)addr;
16265 	insn[1].imm = addr >> 32;
16266 
16267 	if (btf_type_is_func(t)) {
16268 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16269 		aux->btf_var.mem_size = 0;
16270 		goto check_btf;
16271 	}
16272 
16273 	datasec_id = find_btf_percpu_datasec(btf);
16274 	if (datasec_id > 0) {
16275 		datasec = btf_type_by_id(btf, datasec_id);
16276 		for_each_vsi(i, datasec, vsi) {
16277 			if (vsi->type == id) {
16278 				percpu = true;
16279 				break;
16280 			}
16281 		}
16282 	}
16283 
16284 	type = t->type;
16285 	t = btf_type_skip_modifiers(btf, type, NULL);
16286 	if (percpu) {
16287 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16288 		aux->btf_var.btf = btf;
16289 		aux->btf_var.btf_id = type;
16290 	} else if (!btf_type_is_struct(t)) {
16291 		const struct btf_type *ret;
16292 		const char *tname;
16293 		u32 tsize;
16294 
16295 		/* resolve the type size of ksym. */
16296 		ret = btf_resolve_size(btf, t, &tsize);
16297 		if (IS_ERR(ret)) {
16298 			tname = btf_name_by_offset(btf, t->name_off);
16299 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16300 				tname, PTR_ERR(ret));
16301 			err = -EINVAL;
16302 			goto err_put;
16303 		}
16304 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16305 		aux->btf_var.mem_size = tsize;
16306 	} else {
16307 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16308 		aux->btf_var.btf = btf;
16309 		aux->btf_var.btf_id = type;
16310 	}
16311 check_btf:
16312 	/* check whether we recorded this BTF (and maybe module) already */
16313 	for (i = 0; i < env->used_btf_cnt; i++) {
16314 		if (env->used_btfs[i].btf == btf) {
16315 			btf_put(btf);
16316 			return 0;
16317 		}
16318 	}
16319 
16320 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16321 		err = -E2BIG;
16322 		goto err_put;
16323 	}
16324 
16325 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16326 	btf_mod->btf = btf;
16327 	btf_mod->module = NULL;
16328 
16329 	/* if we reference variables from kernel module, bump its refcount */
16330 	if (btf_is_module(btf)) {
16331 		btf_mod->module = btf_try_get_module(btf);
16332 		if (!btf_mod->module) {
16333 			err = -ENXIO;
16334 			goto err_put;
16335 		}
16336 	}
16337 
16338 	env->used_btf_cnt++;
16339 
16340 	return 0;
16341 err_put:
16342 	btf_put(btf);
16343 	return err;
16344 }
16345 
16346 static bool is_tracing_prog_type(enum bpf_prog_type type)
16347 {
16348 	switch (type) {
16349 	case BPF_PROG_TYPE_KPROBE:
16350 	case BPF_PROG_TYPE_TRACEPOINT:
16351 	case BPF_PROG_TYPE_PERF_EVENT:
16352 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16353 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16354 		return true;
16355 	default:
16356 		return false;
16357 	}
16358 }
16359 
16360 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16361 					struct bpf_map *map,
16362 					struct bpf_prog *prog)
16363 
16364 {
16365 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16366 
16367 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16368 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16369 		if (is_tracing_prog_type(prog_type)) {
16370 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16371 			return -EINVAL;
16372 		}
16373 	}
16374 
16375 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16376 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16377 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16378 			return -EINVAL;
16379 		}
16380 
16381 		if (is_tracing_prog_type(prog_type)) {
16382 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16383 			return -EINVAL;
16384 		}
16385 
16386 		if (prog->aux->sleepable) {
16387 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16388 			return -EINVAL;
16389 		}
16390 	}
16391 
16392 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16393 		if (is_tracing_prog_type(prog_type)) {
16394 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16395 			return -EINVAL;
16396 		}
16397 	}
16398 
16399 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16400 	    !bpf_offload_prog_map_match(prog, map)) {
16401 		verbose(env, "offload device mismatch between prog and map\n");
16402 		return -EINVAL;
16403 	}
16404 
16405 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16406 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16407 		return -EINVAL;
16408 	}
16409 
16410 	if (prog->aux->sleepable)
16411 		switch (map->map_type) {
16412 		case BPF_MAP_TYPE_HASH:
16413 		case BPF_MAP_TYPE_LRU_HASH:
16414 		case BPF_MAP_TYPE_ARRAY:
16415 		case BPF_MAP_TYPE_PERCPU_HASH:
16416 		case BPF_MAP_TYPE_PERCPU_ARRAY:
16417 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16418 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16419 		case BPF_MAP_TYPE_HASH_OF_MAPS:
16420 		case BPF_MAP_TYPE_RINGBUF:
16421 		case BPF_MAP_TYPE_USER_RINGBUF:
16422 		case BPF_MAP_TYPE_INODE_STORAGE:
16423 		case BPF_MAP_TYPE_SK_STORAGE:
16424 		case BPF_MAP_TYPE_TASK_STORAGE:
16425 		case BPF_MAP_TYPE_CGRP_STORAGE:
16426 			break;
16427 		default:
16428 			verbose(env,
16429 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16430 			return -EINVAL;
16431 		}
16432 
16433 	return 0;
16434 }
16435 
16436 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16437 {
16438 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16439 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16440 }
16441 
16442 /* find and rewrite pseudo imm in ld_imm64 instructions:
16443  *
16444  * 1. if it accesses map FD, replace it with actual map pointer.
16445  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16446  *
16447  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16448  */
16449 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16450 {
16451 	struct bpf_insn *insn = env->prog->insnsi;
16452 	int insn_cnt = env->prog->len;
16453 	int i, j, err;
16454 
16455 	err = bpf_prog_calc_tag(env->prog);
16456 	if (err)
16457 		return err;
16458 
16459 	for (i = 0; i < insn_cnt; i++, insn++) {
16460 		if (BPF_CLASS(insn->code) == BPF_LDX &&
16461 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16462 			verbose(env, "BPF_LDX uses reserved fields\n");
16463 			return -EINVAL;
16464 		}
16465 
16466 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16467 			struct bpf_insn_aux_data *aux;
16468 			struct bpf_map *map;
16469 			struct fd f;
16470 			u64 addr;
16471 			u32 fd;
16472 
16473 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
16474 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16475 			    insn[1].off != 0) {
16476 				verbose(env, "invalid bpf_ld_imm64 insn\n");
16477 				return -EINVAL;
16478 			}
16479 
16480 			if (insn[0].src_reg == 0)
16481 				/* valid generic load 64-bit imm */
16482 				goto next_insn;
16483 
16484 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16485 				aux = &env->insn_aux_data[i];
16486 				err = check_pseudo_btf_id(env, insn, aux);
16487 				if (err)
16488 					return err;
16489 				goto next_insn;
16490 			}
16491 
16492 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16493 				aux = &env->insn_aux_data[i];
16494 				aux->ptr_type = PTR_TO_FUNC;
16495 				goto next_insn;
16496 			}
16497 
16498 			/* In final convert_pseudo_ld_imm64() step, this is
16499 			 * converted into regular 64-bit imm load insn.
16500 			 */
16501 			switch (insn[0].src_reg) {
16502 			case BPF_PSEUDO_MAP_VALUE:
16503 			case BPF_PSEUDO_MAP_IDX_VALUE:
16504 				break;
16505 			case BPF_PSEUDO_MAP_FD:
16506 			case BPF_PSEUDO_MAP_IDX:
16507 				if (insn[1].imm == 0)
16508 					break;
16509 				fallthrough;
16510 			default:
16511 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16512 				return -EINVAL;
16513 			}
16514 
16515 			switch (insn[0].src_reg) {
16516 			case BPF_PSEUDO_MAP_IDX_VALUE:
16517 			case BPF_PSEUDO_MAP_IDX:
16518 				if (bpfptr_is_null(env->fd_array)) {
16519 					verbose(env, "fd_idx without fd_array is invalid\n");
16520 					return -EPROTO;
16521 				}
16522 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
16523 							    insn[0].imm * sizeof(fd),
16524 							    sizeof(fd)))
16525 					return -EFAULT;
16526 				break;
16527 			default:
16528 				fd = insn[0].imm;
16529 				break;
16530 			}
16531 
16532 			f = fdget(fd);
16533 			map = __bpf_map_get(f);
16534 			if (IS_ERR(map)) {
16535 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
16536 					insn[0].imm);
16537 				return PTR_ERR(map);
16538 			}
16539 
16540 			err = check_map_prog_compatibility(env, map, env->prog);
16541 			if (err) {
16542 				fdput(f);
16543 				return err;
16544 			}
16545 
16546 			aux = &env->insn_aux_data[i];
16547 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16548 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16549 				addr = (unsigned long)map;
16550 			} else {
16551 				u32 off = insn[1].imm;
16552 
16553 				if (off >= BPF_MAX_VAR_OFF) {
16554 					verbose(env, "direct value offset of %u is not allowed\n", off);
16555 					fdput(f);
16556 					return -EINVAL;
16557 				}
16558 
16559 				if (!map->ops->map_direct_value_addr) {
16560 					verbose(env, "no direct value access support for this map type\n");
16561 					fdput(f);
16562 					return -EINVAL;
16563 				}
16564 
16565 				err = map->ops->map_direct_value_addr(map, &addr, off);
16566 				if (err) {
16567 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16568 						map->value_size, off);
16569 					fdput(f);
16570 					return err;
16571 				}
16572 
16573 				aux->map_off = off;
16574 				addr += off;
16575 			}
16576 
16577 			insn[0].imm = (u32)addr;
16578 			insn[1].imm = addr >> 32;
16579 
16580 			/* check whether we recorded this map already */
16581 			for (j = 0; j < env->used_map_cnt; j++) {
16582 				if (env->used_maps[j] == map) {
16583 					aux->map_index = j;
16584 					fdput(f);
16585 					goto next_insn;
16586 				}
16587 			}
16588 
16589 			if (env->used_map_cnt >= MAX_USED_MAPS) {
16590 				fdput(f);
16591 				return -E2BIG;
16592 			}
16593 
16594 			/* hold the map. If the program is rejected by verifier,
16595 			 * the map will be released by release_maps() or it
16596 			 * will be used by the valid program until it's unloaded
16597 			 * and all maps are released in free_used_maps()
16598 			 */
16599 			bpf_map_inc(map);
16600 
16601 			aux->map_index = env->used_map_cnt;
16602 			env->used_maps[env->used_map_cnt++] = map;
16603 
16604 			if (bpf_map_is_cgroup_storage(map) &&
16605 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
16606 				verbose(env, "only one cgroup storage of each type is allowed\n");
16607 				fdput(f);
16608 				return -EBUSY;
16609 			}
16610 
16611 			fdput(f);
16612 next_insn:
16613 			insn++;
16614 			i++;
16615 			continue;
16616 		}
16617 
16618 		/* Basic sanity check before we invest more work here. */
16619 		if (!bpf_opcode_in_insntable(insn->code)) {
16620 			verbose(env, "unknown opcode %02x\n", insn->code);
16621 			return -EINVAL;
16622 		}
16623 	}
16624 
16625 	/* now all pseudo BPF_LD_IMM64 instructions load valid
16626 	 * 'struct bpf_map *' into a register instead of user map_fd.
16627 	 * These pointers will be used later by verifier to validate map access.
16628 	 */
16629 	return 0;
16630 }
16631 
16632 /* drop refcnt of maps used by the rejected program */
16633 static void release_maps(struct bpf_verifier_env *env)
16634 {
16635 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
16636 			     env->used_map_cnt);
16637 }
16638 
16639 /* drop refcnt of maps used by the rejected program */
16640 static void release_btfs(struct bpf_verifier_env *env)
16641 {
16642 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16643 			     env->used_btf_cnt);
16644 }
16645 
16646 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16647 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16648 {
16649 	struct bpf_insn *insn = env->prog->insnsi;
16650 	int insn_cnt = env->prog->len;
16651 	int i;
16652 
16653 	for (i = 0; i < insn_cnt; i++, insn++) {
16654 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16655 			continue;
16656 		if (insn->src_reg == BPF_PSEUDO_FUNC)
16657 			continue;
16658 		insn->src_reg = 0;
16659 	}
16660 }
16661 
16662 /* single env->prog->insni[off] instruction was replaced with the range
16663  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
16664  * [0, off) and [off, end) to new locations, so the patched range stays zero
16665  */
16666 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16667 				 struct bpf_insn_aux_data *new_data,
16668 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
16669 {
16670 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16671 	struct bpf_insn *insn = new_prog->insnsi;
16672 	u32 old_seen = old_data[off].seen;
16673 	u32 prog_len;
16674 	int i;
16675 
16676 	/* aux info at OFF always needs adjustment, no matter fast path
16677 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16678 	 * original insn at old prog.
16679 	 */
16680 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16681 
16682 	if (cnt == 1)
16683 		return;
16684 	prog_len = new_prog->len;
16685 
16686 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16687 	memcpy(new_data + off + cnt - 1, old_data + off,
16688 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16689 	for (i = off; i < off + cnt - 1; i++) {
16690 		/* Expand insni[off]'s seen count to the patched range. */
16691 		new_data[i].seen = old_seen;
16692 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
16693 	}
16694 	env->insn_aux_data = new_data;
16695 	vfree(old_data);
16696 }
16697 
16698 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16699 {
16700 	int i;
16701 
16702 	if (len == 1)
16703 		return;
16704 	/* NOTE: fake 'exit' subprog should be updated as well. */
16705 	for (i = 0; i <= env->subprog_cnt; i++) {
16706 		if (env->subprog_info[i].start <= off)
16707 			continue;
16708 		env->subprog_info[i].start += len - 1;
16709 	}
16710 }
16711 
16712 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16713 {
16714 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16715 	int i, sz = prog->aux->size_poke_tab;
16716 	struct bpf_jit_poke_descriptor *desc;
16717 
16718 	for (i = 0; i < sz; i++) {
16719 		desc = &tab[i];
16720 		if (desc->insn_idx <= off)
16721 			continue;
16722 		desc->insn_idx += len - 1;
16723 	}
16724 }
16725 
16726 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16727 					    const struct bpf_insn *patch, u32 len)
16728 {
16729 	struct bpf_prog *new_prog;
16730 	struct bpf_insn_aux_data *new_data = NULL;
16731 
16732 	if (len > 1) {
16733 		new_data = vzalloc(array_size(env->prog->len + len - 1,
16734 					      sizeof(struct bpf_insn_aux_data)));
16735 		if (!new_data)
16736 			return NULL;
16737 	}
16738 
16739 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
16740 	if (IS_ERR(new_prog)) {
16741 		if (PTR_ERR(new_prog) == -ERANGE)
16742 			verbose(env,
16743 				"insn %d cannot be patched due to 16-bit range\n",
16744 				env->insn_aux_data[off].orig_idx);
16745 		vfree(new_data);
16746 		return NULL;
16747 	}
16748 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
16749 	adjust_subprog_starts(env, off, len);
16750 	adjust_poke_descs(new_prog, off, len);
16751 	return new_prog;
16752 }
16753 
16754 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16755 					      u32 off, u32 cnt)
16756 {
16757 	int i, j;
16758 
16759 	/* find first prog starting at or after off (first to remove) */
16760 	for (i = 0; i < env->subprog_cnt; i++)
16761 		if (env->subprog_info[i].start >= off)
16762 			break;
16763 	/* find first prog starting at or after off + cnt (first to stay) */
16764 	for (j = i; j < env->subprog_cnt; j++)
16765 		if (env->subprog_info[j].start >= off + cnt)
16766 			break;
16767 	/* if j doesn't start exactly at off + cnt, we are just removing
16768 	 * the front of previous prog
16769 	 */
16770 	if (env->subprog_info[j].start != off + cnt)
16771 		j--;
16772 
16773 	if (j > i) {
16774 		struct bpf_prog_aux *aux = env->prog->aux;
16775 		int move;
16776 
16777 		/* move fake 'exit' subprog as well */
16778 		move = env->subprog_cnt + 1 - j;
16779 
16780 		memmove(env->subprog_info + i,
16781 			env->subprog_info + j,
16782 			sizeof(*env->subprog_info) * move);
16783 		env->subprog_cnt -= j - i;
16784 
16785 		/* remove func_info */
16786 		if (aux->func_info) {
16787 			move = aux->func_info_cnt - j;
16788 
16789 			memmove(aux->func_info + i,
16790 				aux->func_info + j,
16791 				sizeof(*aux->func_info) * move);
16792 			aux->func_info_cnt -= j - i;
16793 			/* func_info->insn_off is set after all code rewrites,
16794 			 * in adjust_btf_func() - no need to adjust
16795 			 */
16796 		}
16797 	} else {
16798 		/* convert i from "first prog to remove" to "first to adjust" */
16799 		if (env->subprog_info[i].start == off)
16800 			i++;
16801 	}
16802 
16803 	/* update fake 'exit' subprog as well */
16804 	for (; i <= env->subprog_cnt; i++)
16805 		env->subprog_info[i].start -= cnt;
16806 
16807 	return 0;
16808 }
16809 
16810 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16811 				      u32 cnt)
16812 {
16813 	struct bpf_prog *prog = env->prog;
16814 	u32 i, l_off, l_cnt, nr_linfo;
16815 	struct bpf_line_info *linfo;
16816 
16817 	nr_linfo = prog->aux->nr_linfo;
16818 	if (!nr_linfo)
16819 		return 0;
16820 
16821 	linfo = prog->aux->linfo;
16822 
16823 	/* find first line info to remove, count lines to be removed */
16824 	for (i = 0; i < nr_linfo; i++)
16825 		if (linfo[i].insn_off >= off)
16826 			break;
16827 
16828 	l_off = i;
16829 	l_cnt = 0;
16830 	for (; i < nr_linfo; i++)
16831 		if (linfo[i].insn_off < off + cnt)
16832 			l_cnt++;
16833 		else
16834 			break;
16835 
16836 	/* First live insn doesn't match first live linfo, it needs to "inherit"
16837 	 * last removed linfo.  prog is already modified, so prog->len == off
16838 	 * means no live instructions after (tail of the program was removed).
16839 	 */
16840 	if (prog->len != off && l_cnt &&
16841 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16842 		l_cnt--;
16843 		linfo[--i].insn_off = off + cnt;
16844 	}
16845 
16846 	/* remove the line info which refer to the removed instructions */
16847 	if (l_cnt) {
16848 		memmove(linfo + l_off, linfo + i,
16849 			sizeof(*linfo) * (nr_linfo - i));
16850 
16851 		prog->aux->nr_linfo -= l_cnt;
16852 		nr_linfo = prog->aux->nr_linfo;
16853 	}
16854 
16855 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
16856 	for (i = l_off; i < nr_linfo; i++)
16857 		linfo[i].insn_off -= cnt;
16858 
16859 	/* fix up all subprogs (incl. 'exit') which start >= off */
16860 	for (i = 0; i <= env->subprog_cnt; i++)
16861 		if (env->subprog_info[i].linfo_idx > l_off) {
16862 			/* program may have started in the removed region but
16863 			 * may not be fully removed
16864 			 */
16865 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
16866 				env->subprog_info[i].linfo_idx -= l_cnt;
16867 			else
16868 				env->subprog_info[i].linfo_idx = l_off;
16869 		}
16870 
16871 	return 0;
16872 }
16873 
16874 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
16875 {
16876 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16877 	unsigned int orig_prog_len = env->prog->len;
16878 	int err;
16879 
16880 	if (bpf_prog_is_offloaded(env->prog->aux))
16881 		bpf_prog_offload_remove_insns(env, off, cnt);
16882 
16883 	err = bpf_remove_insns(env->prog, off, cnt);
16884 	if (err)
16885 		return err;
16886 
16887 	err = adjust_subprog_starts_after_remove(env, off, cnt);
16888 	if (err)
16889 		return err;
16890 
16891 	err = bpf_adj_linfo_after_remove(env, off, cnt);
16892 	if (err)
16893 		return err;
16894 
16895 	memmove(aux_data + off,	aux_data + off + cnt,
16896 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
16897 
16898 	return 0;
16899 }
16900 
16901 /* The verifier does more data flow analysis than llvm and will not
16902  * explore branches that are dead at run time. Malicious programs can
16903  * have dead code too. Therefore replace all dead at-run-time code
16904  * with 'ja -1'.
16905  *
16906  * Just nops are not optimal, e.g. if they would sit at the end of the
16907  * program and through another bug we would manage to jump there, then
16908  * we'd execute beyond program memory otherwise. Returning exception
16909  * code also wouldn't work since we can have subprogs where the dead
16910  * code could be located.
16911  */
16912 static void sanitize_dead_code(struct bpf_verifier_env *env)
16913 {
16914 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16915 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
16916 	struct bpf_insn *insn = env->prog->insnsi;
16917 	const int insn_cnt = env->prog->len;
16918 	int i;
16919 
16920 	for (i = 0; i < insn_cnt; i++) {
16921 		if (aux_data[i].seen)
16922 			continue;
16923 		memcpy(insn + i, &trap, sizeof(trap));
16924 		aux_data[i].zext_dst = false;
16925 	}
16926 }
16927 
16928 static bool insn_is_cond_jump(u8 code)
16929 {
16930 	u8 op;
16931 
16932 	if (BPF_CLASS(code) == BPF_JMP32)
16933 		return true;
16934 
16935 	if (BPF_CLASS(code) != BPF_JMP)
16936 		return false;
16937 
16938 	op = BPF_OP(code);
16939 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
16940 }
16941 
16942 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
16943 {
16944 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16945 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16946 	struct bpf_insn *insn = env->prog->insnsi;
16947 	const int insn_cnt = env->prog->len;
16948 	int i;
16949 
16950 	for (i = 0; i < insn_cnt; i++, insn++) {
16951 		if (!insn_is_cond_jump(insn->code))
16952 			continue;
16953 
16954 		if (!aux_data[i + 1].seen)
16955 			ja.off = insn->off;
16956 		else if (!aux_data[i + 1 + insn->off].seen)
16957 			ja.off = 0;
16958 		else
16959 			continue;
16960 
16961 		if (bpf_prog_is_offloaded(env->prog->aux))
16962 			bpf_prog_offload_replace_insn(env, i, &ja);
16963 
16964 		memcpy(insn, &ja, sizeof(ja));
16965 	}
16966 }
16967 
16968 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16969 {
16970 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16971 	int insn_cnt = env->prog->len;
16972 	int i, err;
16973 
16974 	for (i = 0; i < insn_cnt; i++) {
16975 		int j;
16976 
16977 		j = 0;
16978 		while (i + j < insn_cnt && !aux_data[i + j].seen)
16979 			j++;
16980 		if (!j)
16981 			continue;
16982 
16983 		err = verifier_remove_insns(env, i, j);
16984 		if (err)
16985 			return err;
16986 		insn_cnt = env->prog->len;
16987 	}
16988 
16989 	return 0;
16990 }
16991 
16992 static int opt_remove_nops(struct bpf_verifier_env *env)
16993 {
16994 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16995 	struct bpf_insn *insn = env->prog->insnsi;
16996 	int insn_cnt = env->prog->len;
16997 	int i, err;
16998 
16999 	for (i = 0; i < insn_cnt; i++) {
17000 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17001 			continue;
17002 
17003 		err = verifier_remove_insns(env, i, 1);
17004 		if (err)
17005 			return err;
17006 		insn_cnt--;
17007 		i--;
17008 	}
17009 
17010 	return 0;
17011 }
17012 
17013 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17014 					 const union bpf_attr *attr)
17015 {
17016 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17017 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17018 	int i, patch_len, delta = 0, len = env->prog->len;
17019 	struct bpf_insn *insns = env->prog->insnsi;
17020 	struct bpf_prog *new_prog;
17021 	bool rnd_hi32;
17022 
17023 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17024 	zext_patch[1] = BPF_ZEXT_REG(0);
17025 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17026 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17027 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17028 	for (i = 0; i < len; i++) {
17029 		int adj_idx = i + delta;
17030 		struct bpf_insn insn;
17031 		int load_reg;
17032 
17033 		insn = insns[adj_idx];
17034 		load_reg = insn_def_regno(&insn);
17035 		if (!aux[adj_idx].zext_dst) {
17036 			u8 code, class;
17037 			u32 imm_rnd;
17038 
17039 			if (!rnd_hi32)
17040 				continue;
17041 
17042 			code = insn.code;
17043 			class = BPF_CLASS(code);
17044 			if (load_reg == -1)
17045 				continue;
17046 
17047 			/* NOTE: arg "reg" (the fourth one) is only used for
17048 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17049 			 *       here.
17050 			 */
17051 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17052 				if (class == BPF_LD &&
17053 				    BPF_MODE(code) == BPF_IMM)
17054 					i++;
17055 				continue;
17056 			}
17057 
17058 			/* ctx load could be transformed into wider load. */
17059 			if (class == BPF_LDX &&
17060 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17061 				continue;
17062 
17063 			imm_rnd = get_random_u32();
17064 			rnd_hi32_patch[0] = insn;
17065 			rnd_hi32_patch[1].imm = imm_rnd;
17066 			rnd_hi32_patch[3].dst_reg = load_reg;
17067 			patch = rnd_hi32_patch;
17068 			patch_len = 4;
17069 			goto apply_patch_buffer;
17070 		}
17071 
17072 		/* Add in an zero-extend instruction if a) the JIT has requested
17073 		 * it or b) it's a CMPXCHG.
17074 		 *
17075 		 * The latter is because: BPF_CMPXCHG always loads a value into
17076 		 * R0, therefore always zero-extends. However some archs'
17077 		 * equivalent instruction only does this load when the
17078 		 * comparison is successful. This detail of CMPXCHG is
17079 		 * orthogonal to the general zero-extension behaviour of the
17080 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17081 		 */
17082 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17083 			continue;
17084 
17085 		/* Zero-extension is done by the caller. */
17086 		if (bpf_pseudo_kfunc_call(&insn))
17087 			continue;
17088 
17089 		if (WARN_ON(load_reg == -1)) {
17090 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17091 			return -EFAULT;
17092 		}
17093 
17094 		zext_patch[0] = insn;
17095 		zext_patch[1].dst_reg = load_reg;
17096 		zext_patch[1].src_reg = load_reg;
17097 		patch = zext_patch;
17098 		patch_len = 2;
17099 apply_patch_buffer:
17100 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17101 		if (!new_prog)
17102 			return -ENOMEM;
17103 		env->prog = new_prog;
17104 		insns = new_prog->insnsi;
17105 		aux = env->insn_aux_data;
17106 		delta += patch_len - 1;
17107 	}
17108 
17109 	return 0;
17110 }
17111 
17112 /* convert load instructions that access fields of a context type into a
17113  * sequence of instructions that access fields of the underlying structure:
17114  *     struct __sk_buff    -> struct sk_buff
17115  *     struct bpf_sock_ops -> struct sock
17116  */
17117 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17118 {
17119 	const struct bpf_verifier_ops *ops = env->ops;
17120 	int i, cnt, size, ctx_field_size, delta = 0;
17121 	const int insn_cnt = env->prog->len;
17122 	struct bpf_insn insn_buf[16], *insn;
17123 	u32 target_size, size_default, off;
17124 	struct bpf_prog *new_prog;
17125 	enum bpf_access_type type;
17126 	bool is_narrower_load;
17127 
17128 	if (ops->gen_prologue || env->seen_direct_write) {
17129 		if (!ops->gen_prologue) {
17130 			verbose(env, "bpf verifier is misconfigured\n");
17131 			return -EINVAL;
17132 		}
17133 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17134 					env->prog);
17135 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17136 			verbose(env, "bpf verifier is misconfigured\n");
17137 			return -EINVAL;
17138 		} else if (cnt) {
17139 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17140 			if (!new_prog)
17141 				return -ENOMEM;
17142 
17143 			env->prog = new_prog;
17144 			delta += cnt - 1;
17145 		}
17146 	}
17147 
17148 	if (bpf_prog_is_offloaded(env->prog->aux))
17149 		return 0;
17150 
17151 	insn = env->prog->insnsi + delta;
17152 
17153 	for (i = 0; i < insn_cnt; i++, insn++) {
17154 		bpf_convert_ctx_access_t convert_ctx_access;
17155 
17156 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17157 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17158 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17159 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17160 			type = BPF_READ;
17161 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17162 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17163 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17164 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17165 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17166 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17167 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17168 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17169 			type = BPF_WRITE;
17170 		} else {
17171 			continue;
17172 		}
17173 
17174 		if (type == BPF_WRITE &&
17175 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17176 			struct bpf_insn patch[] = {
17177 				*insn,
17178 				BPF_ST_NOSPEC(),
17179 			};
17180 
17181 			cnt = ARRAY_SIZE(patch);
17182 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17183 			if (!new_prog)
17184 				return -ENOMEM;
17185 
17186 			delta    += cnt - 1;
17187 			env->prog = new_prog;
17188 			insn      = new_prog->insnsi + i + delta;
17189 			continue;
17190 		}
17191 
17192 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17193 		case PTR_TO_CTX:
17194 			if (!ops->convert_ctx_access)
17195 				continue;
17196 			convert_ctx_access = ops->convert_ctx_access;
17197 			break;
17198 		case PTR_TO_SOCKET:
17199 		case PTR_TO_SOCK_COMMON:
17200 			convert_ctx_access = bpf_sock_convert_ctx_access;
17201 			break;
17202 		case PTR_TO_TCP_SOCK:
17203 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17204 			break;
17205 		case PTR_TO_XDP_SOCK:
17206 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17207 			break;
17208 		case PTR_TO_BTF_ID:
17209 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17210 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17211 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17212 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17213 		 * any faults for loads into such types. BPF_WRITE is disallowed
17214 		 * for this case.
17215 		 */
17216 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17217 			if (type == BPF_READ) {
17218 				insn->code = BPF_LDX | BPF_PROBE_MEM |
17219 					BPF_SIZE((insn)->code);
17220 				env->prog->aux->num_exentries++;
17221 			}
17222 			continue;
17223 		default:
17224 			continue;
17225 		}
17226 
17227 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17228 		size = BPF_LDST_BYTES(insn);
17229 
17230 		/* If the read access is a narrower load of the field,
17231 		 * convert to a 4/8-byte load, to minimum program type specific
17232 		 * convert_ctx_access changes. If conversion is successful,
17233 		 * we will apply proper mask to the result.
17234 		 */
17235 		is_narrower_load = size < ctx_field_size;
17236 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17237 		off = insn->off;
17238 		if (is_narrower_load) {
17239 			u8 size_code;
17240 
17241 			if (type == BPF_WRITE) {
17242 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17243 				return -EINVAL;
17244 			}
17245 
17246 			size_code = BPF_H;
17247 			if (ctx_field_size == 4)
17248 				size_code = BPF_W;
17249 			else if (ctx_field_size == 8)
17250 				size_code = BPF_DW;
17251 
17252 			insn->off = off & ~(size_default - 1);
17253 			insn->code = BPF_LDX | BPF_MEM | size_code;
17254 		}
17255 
17256 		target_size = 0;
17257 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17258 					 &target_size);
17259 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17260 		    (ctx_field_size && !target_size)) {
17261 			verbose(env, "bpf verifier is misconfigured\n");
17262 			return -EINVAL;
17263 		}
17264 
17265 		if (is_narrower_load && size < target_size) {
17266 			u8 shift = bpf_ctx_narrow_access_offset(
17267 				off, size, size_default) * 8;
17268 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17269 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17270 				return -EINVAL;
17271 			}
17272 			if (ctx_field_size <= 4) {
17273 				if (shift)
17274 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17275 									insn->dst_reg,
17276 									shift);
17277 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17278 								(1 << size * 8) - 1);
17279 			} else {
17280 				if (shift)
17281 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17282 									insn->dst_reg,
17283 									shift);
17284 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
17285 								(1ULL << size * 8) - 1);
17286 			}
17287 		}
17288 
17289 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17290 		if (!new_prog)
17291 			return -ENOMEM;
17292 
17293 		delta += cnt - 1;
17294 
17295 		/* keep walking new program and skip insns we just inserted */
17296 		env->prog = new_prog;
17297 		insn      = new_prog->insnsi + i + delta;
17298 	}
17299 
17300 	return 0;
17301 }
17302 
17303 static int jit_subprogs(struct bpf_verifier_env *env)
17304 {
17305 	struct bpf_prog *prog = env->prog, **func, *tmp;
17306 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17307 	struct bpf_map *map_ptr;
17308 	struct bpf_insn *insn;
17309 	void *old_bpf_func;
17310 	int err, num_exentries;
17311 
17312 	if (env->subprog_cnt <= 1)
17313 		return 0;
17314 
17315 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17316 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17317 			continue;
17318 
17319 		/* Upon error here we cannot fall back to interpreter but
17320 		 * need a hard reject of the program. Thus -EFAULT is
17321 		 * propagated in any case.
17322 		 */
17323 		subprog = find_subprog(env, i + insn->imm + 1);
17324 		if (subprog < 0) {
17325 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17326 				  i + insn->imm + 1);
17327 			return -EFAULT;
17328 		}
17329 		/* temporarily remember subprog id inside insn instead of
17330 		 * aux_data, since next loop will split up all insns into funcs
17331 		 */
17332 		insn->off = subprog;
17333 		/* remember original imm in case JIT fails and fallback
17334 		 * to interpreter will be needed
17335 		 */
17336 		env->insn_aux_data[i].call_imm = insn->imm;
17337 		/* point imm to __bpf_call_base+1 from JITs point of view */
17338 		insn->imm = 1;
17339 		if (bpf_pseudo_func(insn))
17340 			/* jit (e.g. x86_64) may emit fewer instructions
17341 			 * if it learns a u32 imm is the same as a u64 imm.
17342 			 * Force a non zero here.
17343 			 */
17344 			insn[1].imm = 1;
17345 	}
17346 
17347 	err = bpf_prog_alloc_jited_linfo(prog);
17348 	if (err)
17349 		goto out_undo_insn;
17350 
17351 	err = -ENOMEM;
17352 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17353 	if (!func)
17354 		goto out_undo_insn;
17355 
17356 	for (i = 0; i < env->subprog_cnt; i++) {
17357 		subprog_start = subprog_end;
17358 		subprog_end = env->subprog_info[i + 1].start;
17359 
17360 		len = subprog_end - subprog_start;
17361 		/* bpf_prog_run() doesn't call subprogs directly,
17362 		 * hence main prog stats include the runtime of subprogs.
17363 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17364 		 * func[i]->stats will never be accessed and stays NULL
17365 		 */
17366 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17367 		if (!func[i])
17368 			goto out_free;
17369 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17370 		       len * sizeof(struct bpf_insn));
17371 		func[i]->type = prog->type;
17372 		func[i]->len = len;
17373 		if (bpf_prog_calc_tag(func[i]))
17374 			goto out_free;
17375 		func[i]->is_func = 1;
17376 		func[i]->aux->func_idx = i;
17377 		/* Below members will be freed only at prog->aux */
17378 		func[i]->aux->btf = prog->aux->btf;
17379 		func[i]->aux->func_info = prog->aux->func_info;
17380 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17381 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17382 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17383 
17384 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17385 			struct bpf_jit_poke_descriptor *poke;
17386 
17387 			poke = &prog->aux->poke_tab[j];
17388 			if (poke->insn_idx < subprog_end &&
17389 			    poke->insn_idx >= subprog_start)
17390 				poke->aux = func[i]->aux;
17391 		}
17392 
17393 		func[i]->aux->name[0] = 'F';
17394 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17395 		func[i]->jit_requested = 1;
17396 		func[i]->blinding_requested = prog->blinding_requested;
17397 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17398 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17399 		func[i]->aux->linfo = prog->aux->linfo;
17400 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17401 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17402 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17403 		num_exentries = 0;
17404 		insn = func[i]->insnsi;
17405 		for (j = 0; j < func[i]->len; j++, insn++) {
17406 			if (BPF_CLASS(insn->code) == BPF_LDX &&
17407 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
17408 				num_exentries++;
17409 		}
17410 		func[i]->aux->num_exentries = num_exentries;
17411 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17412 		func[i] = bpf_int_jit_compile(func[i]);
17413 		if (!func[i]->jited) {
17414 			err = -ENOTSUPP;
17415 			goto out_free;
17416 		}
17417 		cond_resched();
17418 	}
17419 
17420 	/* at this point all bpf functions were successfully JITed
17421 	 * now populate all bpf_calls with correct addresses and
17422 	 * run last pass of JIT
17423 	 */
17424 	for (i = 0; i < env->subprog_cnt; i++) {
17425 		insn = func[i]->insnsi;
17426 		for (j = 0; j < func[i]->len; j++, insn++) {
17427 			if (bpf_pseudo_func(insn)) {
17428 				subprog = insn->off;
17429 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17430 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17431 				continue;
17432 			}
17433 			if (!bpf_pseudo_call(insn))
17434 				continue;
17435 			subprog = insn->off;
17436 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17437 		}
17438 
17439 		/* we use the aux data to keep a list of the start addresses
17440 		 * of the JITed images for each function in the program
17441 		 *
17442 		 * for some architectures, such as powerpc64, the imm field
17443 		 * might not be large enough to hold the offset of the start
17444 		 * address of the callee's JITed image from __bpf_call_base
17445 		 *
17446 		 * in such cases, we can lookup the start address of a callee
17447 		 * by using its subprog id, available from the off field of
17448 		 * the call instruction, as an index for this list
17449 		 */
17450 		func[i]->aux->func = func;
17451 		func[i]->aux->func_cnt = env->subprog_cnt;
17452 	}
17453 	for (i = 0; i < env->subprog_cnt; i++) {
17454 		old_bpf_func = func[i]->bpf_func;
17455 		tmp = bpf_int_jit_compile(func[i]);
17456 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17457 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17458 			err = -ENOTSUPP;
17459 			goto out_free;
17460 		}
17461 		cond_resched();
17462 	}
17463 
17464 	/* finally lock prog and jit images for all functions and
17465 	 * populate kallsysm
17466 	 */
17467 	for (i = 0; i < env->subprog_cnt; i++) {
17468 		bpf_prog_lock_ro(func[i]);
17469 		bpf_prog_kallsyms_add(func[i]);
17470 	}
17471 
17472 	/* Last step: make now unused interpreter insns from main
17473 	 * prog consistent for later dump requests, so they can
17474 	 * later look the same as if they were interpreted only.
17475 	 */
17476 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17477 		if (bpf_pseudo_func(insn)) {
17478 			insn[0].imm = env->insn_aux_data[i].call_imm;
17479 			insn[1].imm = insn->off;
17480 			insn->off = 0;
17481 			continue;
17482 		}
17483 		if (!bpf_pseudo_call(insn))
17484 			continue;
17485 		insn->off = env->insn_aux_data[i].call_imm;
17486 		subprog = find_subprog(env, i + insn->off + 1);
17487 		insn->imm = subprog;
17488 	}
17489 
17490 	prog->jited = 1;
17491 	prog->bpf_func = func[0]->bpf_func;
17492 	prog->jited_len = func[0]->jited_len;
17493 	prog->aux->func = func;
17494 	prog->aux->func_cnt = env->subprog_cnt;
17495 	bpf_prog_jit_attempt_done(prog);
17496 	return 0;
17497 out_free:
17498 	/* We failed JIT'ing, so at this point we need to unregister poke
17499 	 * descriptors from subprogs, so that kernel is not attempting to
17500 	 * patch it anymore as we're freeing the subprog JIT memory.
17501 	 */
17502 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17503 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17504 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17505 	}
17506 	/* At this point we're guaranteed that poke descriptors are not
17507 	 * live anymore. We can just unlink its descriptor table as it's
17508 	 * released with the main prog.
17509 	 */
17510 	for (i = 0; i < env->subprog_cnt; i++) {
17511 		if (!func[i])
17512 			continue;
17513 		func[i]->aux->poke_tab = NULL;
17514 		bpf_jit_free(func[i]);
17515 	}
17516 	kfree(func);
17517 out_undo_insn:
17518 	/* cleanup main prog to be interpreted */
17519 	prog->jit_requested = 0;
17520 	prog->blinding_requested = 0;
17521 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17522 		if (!bpf_pseudo_call(insn))
17523 			continue;
17524 		insn->off = 0;
17525 		insn->imm = env->insn_aux_data[i].call_imm;
17526 	}
17527 	bpf_prog_jit_attempt_done(prog);
17528 	return err;
17529 }
17530 
17531 static int fixup_call_args(struct bpf_verifier_env *env)
17532 {
17533 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17534 	struct bpf_prog *prog = env->prog;
17535 	struct bpf_insn *insn = prog->insnsi;
17536 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17537 	int i, depth;
17538 #endif
17539 	int err = 0;
17540 
17541 	if (env->prog->jit_requested &&
17542 	    !bpf_prog_is_offloaded(env->prog->aux)) {
17543 		err = jit_subprogs(env);
17544 		if (err == 0)
17545 			return 0;
17546 		if (err == -EFAULT)
17547 			return err;
17548 	}
17549 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17550 	if (has_kfunc_call) {
17551 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17552 		return -EINVAL;
17553 	}
17554 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17555 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
17556 		 * have to be rejected, since interpreter doesn't support them yet.
17557 		 */
17558 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17559 		return -EINVAL;
17560 	}
17561 	for (i = 0; i < prog->len; i++, insn++) {
17562 		if (bpf_pseudo_func(insn)) {
17563 			/* When JIT fails the progs with callback calls
17564 			 * have to be rejected, since interpreter doesn't support them yet.
17565 			 */
17566 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
17567 			return -EINVAL;
17568 		}
17569 
17570 		if (!bpf_pseudo_call(insn))
17571 			continue;
17572 		depth = get_callee_stack_depth(env, insn, i);
17573 		if (depth < 0)
17574 			return depth;
17575 		bpf_patch_call_args(insn, depth);
17576 	}
17577 	err = 0;
17578 #endif
17579 	return err;
17580 }
17581 
17582 /* replace a generic kfunc with a specialized version if necessary */
17583 static void specialize_kfunc(struct bpf_verifier_env *env,
17584 			     u32 func_id, u16 offset, unsigned long *addr)
17585 {
17586 	struct bpf_prog *prog = env->prog;
17587 	bool seen_direct_write;
17588 	void *xdp_kfunc;
17589 	bool is_rdonly;
17590 
17591 	if (bpf_dev_bound_kfunc_id(func_id)) {
17592 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17593 		if (xdp_kfunc) {
17594 			*addr = (unsigned long)xdp_kfunc;
17595 			return;
17596 		}
17597 		/* fallback to default kfunc when not supported by netdev */
17598 	}
17599 
17600 	if (offset)
17601 		return;
17602 
17603 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17604 		seen_direct_write = env->seen_direct_write;
17605 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17606 
17607 		if (is_rdonly)
17608 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17609 
17610 		/* restore env->seen_direct_write to its original value, since
17611 		 * may_access_direct_pkt_data mutates it
17612 		 */
17613 		env->seen_direct_write = seen_direct_write;
17614 	}
17615 }
17616 
17617 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17618 					    u16 struct_meta_reg,
17619 					    u16 node_offset_reg,
17620 					    struct bpf_insn *insn,
17621 					    struct bpf_insn *insn_buf,
17622 					    int *cnt)
17623 {
17624 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17625 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17626 
17627 	insn_buf[0] = addr[0];
17628 	insn_buf[1] = addr[1];
17629 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17630 	insn_buf[3] = *insn;
17631 	*cnt = 4;
17632 }
17633 
17634 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17635 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17636 {
17637 	const struct bpf_kfunc_desc *desc;
17638 
17639 	if (!insn->imm) {
17640 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17641 		return -EINVAL;
17642 	}
17643 
17644 	*cnt = 0;
17645 
17646 	/* insn->imm has the btf func_id. Replace it with an offset relative to
17647 	 * __bpf_call_base, unless the JIT needs to call functions that are
17648 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
17649 	 */
17650 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17651 	if (!desc) {
17652 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17653 			insn->imm);
17654 		return -EFAULT;
17655 	}
17656 
17657 	if (!bpf_jit_supports_far_kfunc_call())
17658 		insn->imm = BPF_CALL_IMM(desc->addr);
17659 	if (insn->off)
17660 		return 0;
17661 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17662 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17663 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17664 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17665 
17666 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17667 		insn_buf[1] = addr[0];
17668 		insn_buf[2] = addr[1];
17669 		insn_buf[3] = *insn;
17670 		*cnt = 4;
17671 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
17672 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
17673 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17674 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17675 
17676 		insn_buf[0] = addr[0];
17677 		insn_buf[1] = addr[1];
17678 		insn_buf[2] = *insn;
17679 		*cnt = 3;
17680 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
17681 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
17682 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17683 		int struct_meta_reg = BPF_REG_3;
17684 		int node_offset_reg = BPF_REG_4;
17685 
17686 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
17687 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17688 			struct_meta_reg = BPF_REG_4;
17689 			node_offset_reg = BPF_REG_5;
17690 		}
17691 
17692 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
17693 						node_offset_reg, insn, insn_buf, cnt);
17694 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17695 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17696 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17697 		*cnt = 1;
17698 	}
17699 	return 0;
17700 }
17701 
17702 /* Do various post-verification rewrites in a single program pass.
17703  * These rewrites simplify JIT and interpreter implementations.
17704  */
17705 static int do_misc_fixups(struct bpf_verifier_env *env)
17706 {
17707 	struct bpf_prog *prog = env->prog;
17708 	enum bpf_attach_type eatype = prog->expected_attach_type;
17709 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17710 	struct bpf_insn *insn = prog->insnsi;
17711 	const struct bpf_func_proto *fn;
17712 	const int insn_cnt = prog->len;
17713 	const struct bpf_map_ops *ops;
17714 	struct bpf_insn_aux_data *aux;
17715 	struct bpf_insn insn_buf[16];
17716 	struct bpf_prog *new_prog;
17717 	struct bpf_map *map_ptr;
17718 	int i, ret, cnt, delta = 0;
17719 
17720 	for (i = 0; i < insn_cnt; i++, insn++) {
17721 		/* Make divide-by-zero exceptions impossible. */
17722 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17723 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17724 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
17725 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
17726 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
17727 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17728 			struct bpf_insn *patchlet;
17729 			struct bpf_insn chk_and_div[] = {
17730 				/* [R,W]x div 0 -> 0 */
17731 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17732 					     BPF_JNE | BPF_K, insn->src_reg,
17733 					     0, 2, 0),
17734 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17735 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17736 				*insn,
17737 			};
17738 			struct bpf_insn chk_and_mod[] = {
17739 				/* [R,W]x mod 0 -> [R,W]x */
17740 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17741 					     BPF_JEQ | BPF_K, insn->src_reg,
17742 					     0, 1 + (is64 ? 0 : 1), 0),
17743 				*insn,
17744 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17745 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
17746 			};
17747 
17748 			patchlet = isdiv ? chk_and_div : chk_and_mod;
17749 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
17750 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
17751 
17752 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
17753 			if (!new_prog)
17754 				return -ENOMEM;
17755 
17756 			delta    += cnt - 1;
17757 			env->prog = prog = new_prog;
17758 			insn      = new_prog->insnsi + i + delta;
17759 			continue;
17760 		}
17761 
17762 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
17763 		if (BPF_CLASS(insn->code) == BPF_LD &&
17764 		    (BPF_MODE(insn->code) == BPF_ABS ||
17765 		     BPF_MODE(insn->code) == BPF_IND)) {
17766 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
17767 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17768 				verbose(env, "bpf verifier is misconfigured\n");
17769 				return -EINVAL;
17770 			}
17771 
17772 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17773 			if (!new_prog)
17774 				return -ENOMEM;
17775 
17776 			delta    += cnt - 1;
17777 			env->prog = prog = new_prog;
17778 			insn      = new_prog->insnsi + i + delta;
17779 			continue;
17780 		}
17781 
17782 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
17783 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17784 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17785 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17786 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
17787 			struct bpf_insn *patch = &insn_buf[0];
17788 			bool issrc, isneg, isimm;
17789 			u32 off_reg;
17790 
17791 			aux = &env->insn_aux_data[i + delta];
17792 			if (!aux->alu_state ||
17793 			    aux->alu_state == BPF_ALU_NON_POINTER)
17794 				continue;
17795 
17796 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17797 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17798 				BPF_ALU_SANITIZE_SRC;
17799 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
17800 
17801 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
17802 			if (isimm) {
17803 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17804 			} else {
17805 				if (isneg)
17806 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17807 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17808 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17809 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17810 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17811 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17812 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17813 			}
17814 			if (!issrc)
17815 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17816 			insn->src_reg = BPF_REG_AX;
17817 			if (isneg)
17818 				insn->code = insn->code == code_add ?
17819 					     code_sub : code_add;
17820 			*patch++ = *insn;
17821 			if (issrc && isneg && !isimm)
17822 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17823 			cnt = patch - insn_buf;
17824 
17825 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17826 			if (!new_prog)
17827 				return -ENOMEM;
17828 
17829 			delta    += cnt - 1;
17830 			env->prog = prog = new_prog;
17831 			insn      = new_prog->insnsi + i + delta;
17832 			continue;
17833 		}
17834 
17835 		if (insn->code != (BPF_JMP | BPF_CALL))
17836 			continue;
17837 		if (insn->src_reg == BPF_PSEUDO_CALL)
17838 			continue;
17839 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17840 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
17841 			if (ret)
17842 				return ret;
17843 			if (cnt == 0)
17844 				continue;
17845 
17846 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17847 			if (!new_prog)
17848 				return -ENOMEM;
17849 
17850 			delta	 += cnt - 1;
17851 			env->prog = prog = new_prog;
17852 			insn	  = new_prog->insnsi + i + delta;
17853 			continue;
17854 		}
17855 
17856 		if (insn->imm == BPF_FUNC_get_route_realm)
17857 			prog->dst_needed = 1;
17858 		if (insn->imm == BPF_FUNC_get_prandom_u32)
17859 			bpf_user_rnd_init_once();
17860 		if (insn->imm == BPF_FUNC_override_return)
17861 			prog->kprobe_override = 1;
17862 		if (insn->imm == BPF_FUNC_tail_call) {
17863 			/* If we tail call into other programs, we
17864 			 * cannot make any assumptions since they can
17865 			 * be replaced dynamically during runtime in
17866 			 * the program array.
17867 			 */
17868 			prog->cb_access = 1;
17869 			if (!allow_tail_call_in_subprogs(env))
17870 				prog->aux->stack_depth = MAX_BPF_STACK;
17871 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
17872 
17873 			/* mark bpf_tail_call as different opcode to avoid
17874 			 * conditional branch in the interpreter for every normal
17875 			 * call and to prevent accidental JITing by JIT compiler
17876 			 * that doesn't support bpf_tail_call yet
17877 			 */
17878 			insn->imm = 0;
17879 			insn->code = BPF_JMP | BPF_TAIL_CALL;
17880 
17881 			aux = &env->insn_aux_data[i + delta];
17882 			if (env->bpf_capable && !prog->blinding_requested &&
17883 			    prog->jit_requested &&
17884 			    !bpf_map_key_poisoned(aux) &&
17885 			    !bpf_map_ptr_poisoned(aux) &&
17886 			    !bpf_map_ptr_unpriv(aux)) {
17887 				struct bpf_jit_poke_descriptor desc = {
17888 					.reason = BPF_POKE_REASON_TAIL_CALL,
17889 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
17890 					.tail_call.key = bpf_map_key_immediate(aux),
17891 					.insn_idx = i + delta,
17892 				};
17893 
17894 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
17895 				if (ret < 0) {
17896 					verbose(env, "adding tail call poke descriptor failed\n");
17897 					return ret;
17898 				}
17899 
17900 				insn->imm = ret + 1;
17901 				continue;
17902 			}
17903 
17904 			if (!bpf_map_ptr_unpriv(aux))
17905 				continue;
17906 
17907 			/* instead of changing every JIT dealing with tail_call
17908 			 * emit two extra insns:
17909 			 * if (index >= max_entries) goto out;
17910 			 * index &= array->index_mask;
17911 			 * to avoid out-of-bounds cpu speculation
17912 			 */
17913 			if (bpf_map_ptr_poisoned(aux)) {
17914 				verbose(env, "tail_call abusing map_ptr\n");
17915 				return -EINVAL;
17916 			}
17917 
17918 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17919 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
17920 						  map_ptr->max_entries, 2);
17921 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
17922 						    container_of(map_ptr,
17923 								 struct bpf_array,
17924 								 map)->index_mask);
17925 			insn_buf[2] = *insn;
17926 			cnt = 3;
17927 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17928 			if (!new_prog)
17929 				return -ENOMEM;
17930 
17931 			delta    += cnt - 1;
17932 			env->prog = prog = new_prog;
17933 			insn      = new_prog->insnsi + i + delta;
17934 			continue;
17935 		}
17936 
17937 		if (insn->imm == BPF_FUNC_timer_set_callback) {
17938 			/* The verifier will process callback_fn as many times as necessary
17939 			 * with different maps and the register states prepared by
17940 			 * set_timer_callback_state will be accurate.
17941 			 *
17942 			 * The following use case is valid:
17943 			 *   map1 is shared by prog1, prog2, prog3.
17944 			 *   prog1 calls bpf_timer_init for some map1 elements
17945 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
17946 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
17947 			 *   prog3 calls bpf_timer_start for some map1 elements.
17948 			 *     Those that were not both bpf_timer_init-ed and
17949 			 *     bpf_timer_set_callback-ed will return -EINVAL.
17950 			 */
17951 			struct bpf_insn ld_addrs[2] = {
17952 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
17953 			};
17954 
17955 			insn_buf[0] = ld_addrs[0];
17956 			insn_buf[1] = ld_addrs[1];
17957 			insn_buf[2] = *insn;
17958 			cnt = 3;
17959 
17960 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17961 			if (!new_prog)
17962 				return -ENOMEM;
17963 
17964 			delta    += cnt - 1;
17965 			env->prog = prog = new_prog;
17966 			insn      = new_prog->insnsi + i + delta;
17967 			goto patch_call_imm;
17968 		}
17969 
17970 		if (is_storage_get_function(insn->imm)) {
17971 			if (!env->prog->aux->sleepable ||
17972 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
17973 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
17974 			else
17975 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
17976 			insn_buf[1] = *insn;
17977 			cnt = 2;
17978 
17979 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17980 			if (!new_prog)
17981 				return -ENOMEM;
17982 
17983 			delta += cnt - 1;
17984 			env->prog = prog = new_prog;
17985 			insn = new_prog->insnsi + i + delta;
17986 			goto patch_call_imm;
17987 		}
17988 
17989 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
17990 		 * and other inlining handlers are currently limited to 64 bit
17991 		 * only.
17992 		 */
17993 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
17994 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
17995 		     insn->imm == BPF_FUNC_map_update_elem ||
17996 		     insn->imm == BPF_FUNC_map_delete_elem ||
17997 		     insn->imm == BPF_FUNC_map_push_elem   ||
17998 		     insn->imm == BPF_FUNC_map_pop_elem    ||
17999 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18000 		     insn->imm == BPF_FUNC_redirect_map    ||
18001 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18002 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18003 			aux = &env->insn_aux_data[i + delta];
18004 			if (bpf_map_ptr_poisoned(aux))
18005 				goto patch_call_imm;
18006 
18007 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18008 			ops = map_ptr->ops;
18009 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18010 			    ops->map_gen_lookup) {
18011 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18012 				if (cnt == -EOPNOTSUPP)
18013 					goto patch_map_ops_generic;
18014 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18015 					verbose(env, "bpf verifier is misconfigured\n");
18016 					return -EINVAL;
18017 				}
18018 
18019 				new_prog = bpf_patch_insn_data(env, i + delta,
18020 							       insn_buf, cnt);
18021 				if (!new_prog)
18022 					return -ENOMEM;
18023 
18024 				delta    += cnt - 1;
18025 				env->prog = prog = new_prog;
18026 				insn      = new_prog->insnsi + i + delta;
18027 				continue;
18028 			}
18029 
18030 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18031 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18032 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18033 				     (long (*)(struct bpf_map *map, void *key))NULL));
18034 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18035 				     (long (*)(struct bpf_map *map, void *key, void *value,
18036 					      u64 flags))NULL));
18037 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18038 				     (long (*)(struct bpf_map *map, void *value,
18039 					      u64 flags))NULL));
18040 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18041 				     (long (*)(struct bpf_map *map, void *value))NULL));
18042 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18043 				     (long (*)(struct bpf_map *map, void *value))NULL));
18044 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18045 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18046 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18047 				     (long (*)(struct bpf_map *map,
18048 					      bpf_callback_t callback_fn,
18049 					      void *callback_ctx,
18050 					      u64 flags))NULL));
18051 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18052 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18053 
18054 patch_map_ops_generic:
18055 			switch (insn->imm) {
18056 			case BPF_FUNC_map_lookup_elem:
18057 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18058 				continue;
18059 			case BPF_FUNC_map_update_elem:
18060 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18061 				continue;
18062 			case BPF_FUNC_map_delete_elem:
18063 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18064 				continue;
18065 			case BPF_FUNC_map_push_elem:
18066 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18067 				continue;
18068 			case BPF_FUNC_map_pop_elem:
18069 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18070 				continue;
18071 			case BPF_FUNC_map_peek_elem:
18072 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18073 				continue;
18074 			case BPF_FUNC_redirect_map:
18075 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18076 				continue;
18077 			case BPF_FUNC_for_each_map_elem:
18078 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18079 				continue;
18080 			case BPF_FUNC_map_lookup_percpu_elem:
18081 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18082 				continue;
18083 			}
18084 
18085 			goto patch_call_imm;
18086 		}
18087 
18088 		/* Implement bpf_jiffies64 inline. */
18089 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18090 		    insn->imm == BPF_FUNC_jiffies64) {
18091 			struct bpf_insn ld_jiffies_addr[2] = {
18092 				BPF_LD_IMM64(BPF_REG_0,
18093 					     (unsigned long)&jiffies),
18094 			};
18095 
18096 			insn_buf[0] = ld_jiffies_addr[0];
18097 			insn_buf[1] = ld_jiffies_addr[1];
18098 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18099 						  BPF_REG_0, 0);
18100 			cnt = 3;
18101 
18102 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18103 						       cnt);
18104 			if (!new_prog)
18105 				return -ENOMEM;
18106 
18107 			delta    += cnt - 1;
18108 			env->prog = prog = new_prog;
18109 			insn      = new_prog->insnsi + i + delta;
18110 			continue;
18111 		}
18112 
18113 		/* Implement bpf_get_func_arg inline. */
18114 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18115 		    insn->imm == BPF_FUNC_get_func_arg) {
18116 			/* Load nr_args from ctx - 8 */
18117 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18118 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18119 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18120 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18121 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18122 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18123 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18124 			insn_buf[7] = BPF_JMP_A(1);
18125 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18126 			cnt = 9;
18127 
18128 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18129 			if (!new_prog)
18130 				return -ENOMEM;
18131 
18132 			delta    += cnt - 1;
18133 			env->prog = prog = new_prog;
18134 			insn      = new_prog->insnsi + i + delta;
18135 			continue;
18136 		}
18137 
18138 		/* Implement bpf_get_func_ret inline. */
18139 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18140 		    insn->imm == BPF_FUNC_get_func_ret) {
18141 			if (eatype == BPF_TRACE_FEXIT ||
18142 			    eatype == BPF_MODIFY_RETURN) {
18143 				/* Load nr_args from ctx - 8 */
18144 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18145 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18146 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18147 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18148 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18149 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18150 				cnt = 6;
18151 			} else {
18152 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18153 				cnt = 1;
18154 			}
18155 
18156 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18157 			if (!new_prog)
18158 				return -ENOMEM;
18159 
18160 			delta    += cnt - 1;
18161 			env->prog = prog = new_prog;
18162 			insn      = new_prog->insnsi + i + delta;
18163 			continue;
18164 		}
18165 
18166 		/* Implement get_func_arg_cnt inline. */
18167 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18168 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18169 			/* Load nr_args from ctx - 8 */
18170 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18171 
18172 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18173 			if (!new_prog)
18174 				return -ENOMEM;
18175 
18176 			env->prog = prog = new_prog;
18177 			insn      = new_prog->insnsi + i + delta;
18178 			continue;
18179 		}
18180 
18181 		/* Implement bpf_get_func_ip inline. */
18182 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18183 		    insn->imm == BPF_FUNC_get_func_ip) {
18184 			/* Load IP address from ctx - 16 */
18185 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18186 
18187 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18188 			if (!new_prog)
18189 				return -ENOMEM;
18190 
18191 			env->prog = prog = new_prog;
18192 			insn      = new_prog->insnsi + i + delta;
18193 			continue;
18194 		}
18195 
18196 patch_call_imm:
18197 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18198 		/* all functions that have prototype and verifier allowed
18199 		 * programs to call them, must be real in-kernel functions
18200 		 */
18201 		if (!fn->func) {
18202 			verbose(env,
18203 				"kernel subsystem misconfigured func %s#%d\n",
18204 				func_id_name(insn->imm), insn->imm);
18205 			return -EFAULT;
18206 		}
18207 		insn->imm = fn->func - __bpf_call_base;
18208 	}
18209 
18210 	/* Since poke tab is now finalized, publish aux to tracker. */
18211 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18212 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18213 		if (!map_ptr->ops->map_poke_track ||
18214 		    !map_ptr->ops->map_poke_untrack ||
18215 		    !map_ptr->ops->map_poke_run) {
18216 			verbose(env, "bpf verifier is misconfigured\n");
18217 			return -EINVAL;
18218 		}
18219 
18220 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18221 		if (ret < 0) {
18222 			verbose(env, "tracking tail call prog failed\n");
18223 			return ret;
18224 		}
18225 	}
18226 
18227 	sort_kfunc_descs_by_imm_off(env->prog);
18228 
18229 	return 0;
18230 }
18231 
18232 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18233 					int position,
18234 					s32 stack_base,
18235 					u32 callback_subprogno,
18236 					u32 *cnt)
18237 {
18238 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18239 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18240 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18241 	int reg_loop_max = BPF_REG_6;
18242 	int reg_loop_cnt = BPF_REG_7;
18243 	int reg_loop_ctx = BPF_REG_8;
18244 
18245 	struct bpf_prog *new_prog;
18246 	u32 callback_start;
18247 	u32 call_insn_offset;
18248 	s32 callback_offset;
18249 
18250 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18251 	 * be careful to modify this code in sync.
18252 	 */
18253 	struct bpf_insn insn_buf[] = {
18254 		/* Return error and jump to the end of the patch if
18255 		 * expected number of iterations is too big.
18256 		 */
18257 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18258 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18259 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18260 		/* spill R6, R7, R8 to use these as loop vars */
18261 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18262 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18263 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18264 		/* initialize loop vars */
18265 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18266 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18267 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18268 		/* loop header,
18269 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18270 		 */
18271 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18272 		/* callback call,
18273 		 * correct callback offset would be set after patching
18274 		 */
18275 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18276 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18277 		BPF_CALL_REL(0),
18278 		/* increment loop counter */
18279 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18280 		/* jump to loop header if callback returned 0 */
18281 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18282 		/* return value of bpf_loop,
18283 		 * set R0 to the number of iterations
18284 		 */
18285 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18286 		/* restore original values of R6, R7, R8 */
18287 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18288 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18289 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18290 	};
18291 
18292 	*cnt = ARRAY_SIZE(insn_buf);
18293 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18294 	if (!new_prog)
18295 		return new_prog;
18296 
18297 	/* callback start is known only after patching */
18298 	callback_start = env->subprog_info[callback_subprogno].start;
18299 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18300 	call_insn_offset = position + 12;
18301 	callback_offset = callback_start - call_insn_offset - 1;
18302 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18303 
18304 	return new_prog;
18305 }
18306 
18307 static bool is_bpf_loop_call(struct bpf_insn *insn)
18308 {
18309 	return insn->code == (BPF_JMP | BPF_CALL) &&
18310 		insn->src_reg == 0 &&
18311 		insn->imm == BPF_FUNC_loop;
18312 }
18313 
18314 /* For all sub-programs in the program (including main) check
18315  * insn_aux_data to see if there are bpf_loop calls that require
18316  * inlining. If such calls are found the calls are replaced with a
18317  * sequence of instructions produced by `inline_bpf_loop` function and
18318  * subprog stack_depth is increased by the size of 3 registers.
18319  * This stack space is used to spill values of the R6, R7, R8.  These
18320  * registers are used to store the loop bound, counter and context
18321  * variables.
18322  */
18323 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18324 {
18325 	struct bpf_subprog_info *subprogs = env->subprog_info;
18326 	int i, cur_subprog = 0, cnt, delta = 0;
18327 	struct bpf_insn *insn = env->prog->insnsi;
18328 	int insn_cnt = env->prog->len;
18329 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18330 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18331 	u16 stack_depth_extra = 0;
18332 
18333 	for (i = 0; i < insn_cnt; i++, insn++) {
18334 		struct bpf_loop_inline_state *inline_state =
18335 			&env->insn_aux_data[i + delta].loop_inline_state;
18336 
18337 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18338 			struct bpf_prog *new_prog;
18339 
18340 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18341 			new_prog = inline_bpf_loop(env,
18342 						   i + delta,
18343 						   -(stack_depth + stack_depth_extra),
18344 						   inline_state->callback_subprogno,
18345 						   &cnt);
18346 			if (!new_prog)
18347 				return -ENOMEM;
18348 
18349 			delta     += cnt - 1;
18350 			env->prog  = new_prog;
18351 			insn       = new_prog->insnsi + i + delta;
18352 		}
18353 
18354 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18355 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18356 			cur_subprog++;
18357 			stack_depth = subprogs[cur_subprog].stack_depth;
18358 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18359 			stack_depth_extra = 0;
18360 		}
18361 	}
18362 
18363 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18364 
18365 	return 0;
18366 }
18367 
18368 static void free_states(struct bpf_verifier_env *env)
18369 {
18370 	struct bpf_verifier_state_list *sl, *sln;
18371 	int i;
18372 
18373 	sl = env->free_list;
18374 	while (sl) {
18375 		sln = sl->next;
18376 		free_verifier_state(&sl->state, false);
18377 		kfree(sl);
18378 		sl = sln;
18379 	}
18380 	env->free_list = NULL;
18381 
18382 	if (!env->explored_states)
18383 		return;
18384 
18385 	for (i = 0; i < state_htab_size(env); i++) {
18386 		sl = env->explored_states[i];
18387 
18388 		while (sl) {
18389 			sln = sl->next;
18390 			free_verifier_state(&sl->state, false);
18391 			kfree(sl);
18392 			sl = sln;
18393 		}
18394 		env->explored_states[i] = NULL;
18395 	}
18396 }
18397 
18398 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18399 {
18400 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18401 	struct bpf_verifier_state *state;
18402 	struct bpf_reg_state *regs;
18403 	int ret, i;
18404 
18405 	env->prev_linfo = NULL;
18406 	env->pass_cnt++;
18407 
18408 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18409 	if (!state)
18410 		return -ENOMEM;
18411 	state->curframe = 0;
18412 	state->speculative = false;
18413 	state->branches = 1;
18414 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18415 	if (!state->frame[0]) {
18416 		kfree(state);
18417 		return -ENOMEM;
18418 	}
18419 	env->cur_state = state;
18420 	init_func_state(env, state->frame[0],
18421 			BPF_MAIN_FUNC /* callsite */,
18422 			0 /* frameno */,
18423 			subprog);
18424 	state->first_insn_idx = env->subprog_info[subprog].start;
18425 	state->last_insn_idx = -1;
18426 
18427 	regs = state->frame[state->curframe]->regs;
18428 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18429 		ret = btf_prepare_func_args(env, subprog, regs);
18430 		if (ret)
18431 			goto out;
18432 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18433 			if (regs[i].type == PTR_TO_CTX)
18434 				mark_reg_known_zero(env, regs, i);
18435 			else if (regs[i].type == SCALAR_VALUE)
18436 				mark_reg_unknown(env, regs, i);
18437 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
18438 				const u32 mem_size = regs[i].mem_size;
18439 
18440 				mark_reg_known_zero(env, regs, i);
18441 				regs[i].mem_size = mem_size;
18442 				regs[i].id = ++env->id_gen;
18443 			}
18444 		}
18445 	} else {
18446 		/* 1st arg to a function */
18447 		regs[BPF_REG_1].type = PTR_TO_CTX;
18448 		mark_reg_known_zero(env, regs, BPF_REG_1);
18449 		ret = btf_check_subprog_arg_match(env, subprog, regs);
18450 		if (ret == -EFAULT)
18451 			/* unlikely verifier bug. abort.
18452 			 * ret == 0 and ret < 0 are sadly acceptable for
18453 			 * main() function due to backward compatibility.
18454 			 * Like socket filter program may be written as:
18455 			 * int bpf_prog(struct pt_regs *ctx)
18456 			 * and never dereference that ctx in the program.
18457 			 * 'struct pt_regs' is a type mismatch for socket
18458 			 * filter that should be using 'struct __sk_buff'.
18459 			 */
18460 			goto out;
18461 	}
18462 
18463 	ret = do_check(env);
18464 out:
18465 	/* check for NULL is necessary, since cur_state can be freed inside
18466 	 * do_check() under memory pressure.
18467 	 */
18468 	if (env->cur_state) {
18469 		free_verifier_state(env->cur_state, true);
18470 		env->cur_state = NULL;
18471 	}
18472 	while (!pop_stack(env, NULL, NULL, false));
18473 	if (!ret && pop_log)
18474 		bpf_vlog_reset(&env->log, 0);
18475 	free_states(env);
18476 	return ret;
18477 }
18478 
18479 /* Verify all global functions in a BPF program one by one based on their BTF.
18480  * All global functions must pass verification. Otherwise the whole program is rejected.
18481  * Consider:
18482  * int bar(int);
18483  * int foo(int f)
18484  * {
18485  *    return bar(f);
18486  * }
18487  * int bar(int b)
18488  * {
18489  *    ...
18490  * }
18491  * foo() will be verified first for R1=any_scalar_value. During verification it
18492  * will be assumed that bar() already verified successfully and call to bar()
18493  * from foo() will be checked for type match only. Later bar() will be verified
18494  * independently to check that it's safe for R1=any_scalar_value.
18495  */
18496 static int do_check_subprogs(struct bpf_verifier_env *env)
18497 {
18498 	struct bpf_prog_aux *aux = env->prog->aux;
18499 	int i, ret;
18500 
18501 	if (!aux->func_info)
18502 		return 0;
18503 
18504 	for (i = 1; i < env->subprog_cnt; i++) {
18505 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18506 			continue;
18507 		env->insn_idx = env->subprog_info[i].start;
18508 		WARN_ON_ONCE(env->insn_idx == 0);
18509 		ret = do_check_common(env, i);
18510 		if (ret) {
18511 			return ret;
18512 		} else if (env->log.level & BPF_LOG_LEVEL) {
18513 			verbose(env,
18514 				"Func#%d is safe for any args that match its prototype\n",
18515 				i);
18516 		}
18517 	}
18518 	return 0;
18519 }
18520 
18521 static int do_check_main(struct bpf_verifier_env *env)
18522 {
18523 	int ret;
18524 
18525 	env->insn_idx = 0;
18526 	ret = do_check_common(env, 0);
18527 	if (!ret)
18528 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18529 	return ret;
18530 }
18531 
18532 
18533 static void print_verification_stats(struct bpf_verifier_env *env)
18534 {
18535 	int i;
18536 
18537 	if (env->log.level & BPF_LOG_STATS) {
18538 		verbose(env, "verification time %lld usec\n",
18539 			div_u64(env->verification_time, 1000));
18540 		verbose(env, "stack depth ");
18541 		for (i = 0; i < env->subprog_cnt; i++) {
18542 			u32 depth = env->subprog_info[i].stack_depth;
18543 
18544 			verbose(env, "%d", depth);
18545 			if (i + 1 < env->subprog_cnt)
18546 				verbose(env, "+");
18547 		}
18548 		verbose(env, "\n");
18549 	}
18550 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18551 		"total_states %d peak_states %d mark_read %d\n",
18552 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18553 		env->max_states_per_insn, env->total_states,
18554 		env->peak_states, env->longest_mark_read_walk);
18555 }
18556 
18557 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18558 {
18559 	const struct btf_type *t, *func_proto;
18560 	const struct bpf_struct_ops *st_ops;
18561 	const struct btf_member *member;
18562 	struct bpf_prog *prog = env->prog;
18563 	u32 btf_id, member_idx;
18564 	const char *mname;
18565 
18566 	if (!prog->gpl_compatible) {
18567 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18568 		return -EINVAL;
18569 	}
18570 
18571 	btf_id = prog->aux->attach_btf_id;
18572 	st_ops = bpf_struct_ops_find(btf_id);
18573 	if (!st_ops) {
18574 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18575 			btf_id);
18576 		return -ENOTSUPP;
18577 	}
18578 
18579 	t = st_ops->type;
18580 	member_idx = prog->expected_attach_type;
18581 	if (member_idx >= btf_type_vlen(t)) {
18582 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18583 			member_idx, st_ops->name);
18584 		return -EINVAL;
18585 	}
18586 
18587 	member = &btf_type_member(t)[member_idx];
18588 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18589 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18590 					       NULL);
18591 	if (!func_proto) {
18592 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18593 			mname, member_idx, st_ops->name);
18594 		return -EINVAL;
18595 	}
18596 
18597 	if (st_ops->check_member) {
18598 		int err = st_ops->check_member(t, member, prog);
18599 
18600 		if (err) {
18601 			verbose(env, "attach to unsupported member %s of struct %s\n",
18602 				mname, st_ops->name);
18603 			return err;
18604 		}
18605 	}
18606 
18607 	prog->aux->attach_func_proto = func_proto;
18608 	prog->aux->attach_func_name = mname;
18609 	env->ops = st_ops->verifier_ops;
18610 
18611 	return 0;
18612 }
18613 #define SECURITY_PREFIX "security_"
18614 
18615 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18616 {
18617 	if (within_error_injection_list(addr) ||
18618 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18619 		return 0;
18620 
18621 	return -EINVAL;
18622 }
18623 
18624 /* list of non-sleepable functions that are otherwise on
18625  * ALLOW_ERROR_INJECTION list
18626  */
18627 BTF_SET_START(btf_non_sleepable_error_inject)
18628 /* Three functions below can be called from sleepable and non-sleepable context.
18629  * Assume non-sleepable from bpf safety point of view.
18630  */
18631 BTF_ID(func, __filemap_add_folio)
18632 BTF_ID(func, should_fail_alloc_page)
18633 BTF_ID(func, should_failslab)
18634 BTF_SET_END(btf_non_sleepable_error_inject)
18635 
18636 static int check_non_sleepable_error_inject(u32 btf_id)
18637 {
18638 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18639 }
18640 
18641 int bpf_check_attach_target(struct bpf_verifier_log *log,
18642 			    const struct bpf_prog *prog,
18643 			    const struct bpf_prog *tgt_prog,
18644 			    u32 btf_id,
18645 			    struct bpf_attach_target_info *tgt_info)
18646 {
18647 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18648 	const char prefix[] = "btf_trace_";
18649 	int ret = 0, subprog = -1, i;
18650 	const struct btf_type *t;
18651 	bool conservative = true;
18652 	const char *tname;
18653 	struct btf *btf;
18654 	long addr = 0;
18655 	struct module *mod = NULL;
18656 
18657 	if (!btf_id) {
18658 		bpf_log(log, "Tracing programs must provide btf_id\n");
18659 		return -EINVAL;
18660 	}
18661 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18662 	if (!btf) {
18663 		bpf_log(log,
18664 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18665 		return -EINVAL;
18666 	}
18667 	t = btf_type_by_id(btf, btf_id);
18668 	if (!t) {
18669 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18670 		return -EINVAL;
18671 	}
18672 	tname = btf_name_by_offset(btf, t->name_off);
18673 	if (!tname) {
18674 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18675 		return -EINVAL;
18676 	}
18677 	if (tgt_prog) {
18678 		struct bpf_prog_aux *aux = tgt_prog->aux;
18679 
18680 		if (bpf_prog_is_dev_bound(prog->aux) &&
18681 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18682 			bpf_log(log, "Target program bound device mismatch");
18683 			return -EINVAL;
18684 		}
18685 
18686 		for (i = 0; i < aux->func_info_cnt; i++)
18687 			if (aux->func_info[i].type_id == btf_id) {
18688 				subprog = i;
18689 				break;
18690 			}
18691 		if (subprog == -1) {
18692 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
18693 			return -EINVAL;
18694 		}
18695 		conservative = aux->func_info_aux[subprog].unreliable;
18696 		if (prog_extension) {
18697 			if (conservative) {
18698 				bpf_log(log,
18699 					"Cannot replace static functions\n");
18700 				return -EINVAL;
18701 			}
18702 			if (!prog->jit_requested) {
18703 				bpf_log(log,
18704 					"Extension programs should be JITed\n");
18705 				return -EINVAL;
18706 			}
18707 		}
18708 		if (!tgt_prog->jited) {
18709 			bpf_log(log, "Can attach to only JITed progs\n");
18710 			return -EINVAL;
18711 		}
18712 		if (tgt_prog->type == prog->type) {
18713 			/* Cannot fentry/fexit another fentry/fexit program.
18714 			 * Cannot attach program extension to another extension.
18715 			 * It's ok to attach fentry/fexit to extension program.
18716 			 */
18717 			bpf_log(log, "Cannot recursively attach\n");
18718 			return -EINVAL;
18719 		}
18720 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18721 		    prog_extension &&
18722 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18723 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18724 			/* Program extensions can extend all program types
18725 			 * except fentry/fexit. The reason is the following.
18726 			 * The fentry/fexit programs are used for performance
18727 			 * analysis, stats and can be attached to any program
18728 			 * type except themselves. When extension program is
18729 			 * replacing XDP function it is necessary to allow
18730 			 * performance analysis of all functions. Both original
18731 			 * XDP program and its program extension. Hence
18732 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18733 			 * allowed. If extending of fentry/fexit was allowed it
18734 			 * would be possible to create long call chain
18735 			 * fentry->extension->fentry->extension beyond
18736 			 * reasonable stack size. Hence extending fentry is not
18737 			 * allowed.
18738 			 */
18739 			bpf_log(log, "Cannot extend fentry/fexit\n");
18740 			return -EINVAL;
18741 		}
18742 	} else {
18743 		if (prog_extension) {
18744 			bpf_log(log, "Cannot replace kernel functions\n");
18745 			return -EINVAL;
18746 		}
18747 	}
18748 
18749 	switch (prog->expected_attach_type) {
18750 	case BPF_TRACE_RAW_TP:
18751 		if (tgt_prog) {
18752 			bpf_log(log,
18753 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18754 			return -EINVAL;
18755 		}
18756 		if (!btf_type_is_typedef(t)) {
18757 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
18758 				btf_id);
18759 			return -EINVAL;
18760 		}
18761 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
18762 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
18763 				btf_id, tname);
18764 			return -EINVAL;
18765 		}
18766 		tname += sizeof(prefix) - 1;
18767 		t = btf_type_by_id(btf, t->type);
18768 		if (!btf_type_is_ptr(t))
18769 			/* should never happen in valid vmlinux build */
18770 			return -EINVAL;
18771 		t = btf_type_by_id(btf, t->type);
18772 		if (!btf_type_is_func_proto(t))
18773 			/* should never happen in valid vmlinux build */
18774 			return -EINVAL;
18775 
18776 		break;
18777 	case BPF_TRACE_ITER:
18778 		if (!btf_type_is_func(t)) {
18779 			bpf_log(log, "attach_btf_id %u is not a function\n",
18780 				btf_id);
18781 			return -EINVAL;
18782 		}
18783 		t = btf_type_by_id(btf, t->type);
18784 		if (!btf_type_is_func_proto(t))
18785 			return -EINVAL;
18786 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18787 		if (ret)
18788 			return ret;
18789 		break;
18790 	default:
18791 		if (!prog_extension)
18792 			return -EINVAL;
18793 		fallthrough;
18794 	case BPF_MODIFY_RETURN:
18795 	case BPF_LSM_MAC:
18796 	case BPF_LSM_CGROUP:
18797 	case BPF_TRACE_FENTRY:
18798 	case BPF_TRACE_FEXIT:
18799 		if (!btf_type_is_func(t)) {
18800 			bpf_log(log, "attach_btf_id %u is not a function\n",
18801 				btf_id);
18802 			return -EINVAL;
18803 		}
18804 		if (prog_extension &&
18805 		    btf_check_type_match(log, prog, btf, t))
18806 			return -EINVAL;
18807 		t = btf_type_by_id(btf, t->type);
18808 		if (!btf_type_is_func_proto(t))
18809 			return -EINVAL;
18810 
18811 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18812 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18813 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18814 			return -EINVAL;
18815 
18816 		if (tgt_prog && conservative)
18817 			t = NULL;
18818 
18819 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18820 		if (ret < 0)
18821 			return ret;
18822 
18823 		if (tgt_prog) {
18824 			if (subprog == 0)
18825 				addr = (long) tgt_prog->bpf_func;
18826 			else
18827 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
18828 		} else {
18829 			if (btf_is_module(btf)) {
18830 				mod = btf_try_get_module(btf);
18831 				if (mod)
18832 					addr = find_kallsyms_symbol_value(mod, tname);
18833 				else
18834 					addr = 0;
18835 			} else {
18836 				addr = kallsyms_lookup_name(tname);
18837 			}
18838 			if (!addr) {
18839 				module_put(mod);
18840 				bpf_log(log,
18841 					"The address of function %s cannot be found\n",
18842 					tname);
18843 				return -ENOENT;
18844 			}
18845 		}
18846 
18847 		if (prog->aux->sleepable) {
18848 			ret = -EINVAL;
18849 			switch (prog->type) {
18850 			case BPF_PROG_TYPE_TRACING:
18851 
18852 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
18853 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18854 				 */
18855 				if (!check_non_sleepable_error_inject(btf_id) &&
18856 				    within_error_injection_list(addr))
18857 					ret = 0;
18858 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
18859 				 * in the fmodret id set with the KF_SLEEPABLE flag.
18860 				 */
18861 				else {
18862 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
18863 
18864 					if (flags && (*flags & KF_SLEEPABLE))
18865 						ret = 0;
18866 				}
18867 				break;
18868 			case BPF_PROG_TYPE_LSM:
18869 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
18870 				 * Only some of them are sleepable.
18871 				 */
18872 				if (bpf_lsm_is_sleepable_hook(btf_id))
18873 					ret = 0;
18874 				break;
18875 			default:
18876 				break;
18877 			}
18878 			if (ret) {
18879 				module_put(mod);
18880 				bpf_log(log, "%s is not sleepable\n", tname);
18881 				return ret;
18882 			}
18883 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
18884 			if (tgt_prog) {
18885 				module_put(mod);
18886 				bpf_log(log, "can't modify return codes of BPF programs\n");
18887 				return -EINVAL;
18888 			}
18889 			ret = -EINVAL;
18890 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
18891 			    !check_attach_modify_return(addr, tname))
18892 				ret = 0;
18893 			if (ret) {
18894 				module_put(mod);
18895 				bpf_log(log, "%s() is not modifiable\n", tname);
18896 				return ret;
18897 			}
18898 		}
18899 
18900 		break;
18901 	}
18902 	tgt_info->tgt_addr = addr;
18903 	tgt_info->tgt_name = tname;
18904 	tgt_info->tgt_type = t;
18905 	tgt_info->tgt_mod = mod;
18906 	return 0;
18907 }
18908 
18909 BTF_SET_START(btf_id_deny)
18910 BTF_ID_UNUSED
18911 #ifdef CONFIG_SMP
18912 BTF_ID(func, migrate_disable)
18913 BTF_ID(func, migrate_enable)
18914 #endif
18915 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
18916 BTF_ID(func, rcu_read_unlock_strict)
18917 #endif
18918 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
18919 BTF_ID(func, preempt_count_add)
18920 BTF_ID(func, preempt_count_sub)
18921 #endif
18922 #ifdef CONFIG_PREEMPT_RCU
18923 BTF_ID(func, __rcu_read_lock)
18924 BTF_ID(func, __rcu_read_unlock)
18925 #endif
18926 BTF_SET_END(btf_id_deny)
18927 
18928 static bool can_be_sleepable(struct bpf_prog *prog)
18929 {
18930 	if (prog->type == BPF_PROG_TYPE_TRACING) {
18931 		switch (prog->expected_attach_type) {
18932 		case BPF_TRACE_FENTRY:
18933 		case BPF_TRACE_FEXIT:
18934 		case BPF_MODIFY_RETURN:
18935 		case BPF_TRACE_ITER:
18936 			return true;
18937 		default:
18938 			return false;
18939 		}
18940 	}
18941 	return prog->type == BPF_PROG_TYPE_LSM ||
18942 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
18943 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
18944 }
18945 
18946 static int check_attach_btf_id(struct bpf_verifier_env *env)
18947 {
18948 	struct bpf_prog *prog = env->prog;
18949 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
18950 	struct bpf_attach_target_info tgt_info = {};
18951 	u32 btf_id = prog->aux->attach_btf_id;
18952 	struct bpf_trampoline *tr;
18953 	int ret;
18954 	u64 key;
18955 
18956 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
18957 		if (prog->aux->sleepable)
18958 			/* attach_btf_id checked to be zero already */
18959 			return 0;
18960 		verbose(env, "Syscall programs can only be sleepable\n");
18961 		return -EINVAL;
18962 	}
18963 
18964 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
18965 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
18966 		return -EINVAL;
18967 	}
18968 
18969 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
18970 		return check_struct_ops_btf_id(env);
18971 
18972 	if (prog->type != BPF_PROG_TYPE_TRACING &&
18973 	    prog->type != BPF_PROG_TYPE_LSM &&
18974 	    prog->type != BPF_PROG_TYPE_EXT)
18975 		return 0;
18976 
18977 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
18978 	if (ret)
18979 		return ret;
18980 
18981 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
18982 		/* to make freplace equivalent to their targets, they need to
18983 		 * inherit env->ops and expected_attach_type for the rest of the
18984 		 * verification
18985 		 */
18986 		env->ops = bpf_verifier_ops[tgt_prog->type];
18987 		prog->expected_attach_type = tgt_prog->expected_attach_type;
18988 	}
18989 
18990 	/* store info about the attachment target that will be used later */
18991 	prog->aux->attach_func_proto = tgt_info.tgt_type;
18992 	prog->aux->attach_func_name = tgt_info.tgt_name;
18993 	prog->aux->mod = tgt_info.tgt_mod;
18994 
18995 	if (tgt_prog) {
18996 		prog->aux->saved_dst_prog_type = tgt_prog->type;
18997 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
18998 	}
18999 
19000 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19001 		prog->aux->attach_btf_trace = true;
19002 		return 0;
19003 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19004 		if (!bpf_iter_prog_supported(prog))
19005 			return -EINVAL;
19006 		return 0;
19007 	}
19008 
19009 	if (prog->type == BPF_PROG_TYPE_LSM) {
19010 		ret = bpf_lsm_verify_prog(&env->log, prog);
19011 		if (ret < 0)
19012 			return ret;
19013 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19014 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19015 		return -EINVAL;
19016 	}
19017 
19018 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19019 	tr = bpf_trampoline_get(key, &tgt_info);
19020 	if (!tr)
19021 		return -ENOMEM;
19022 
19023 	prog->aux->dst_trampoline = tr;
19024 	return 0;
19025 }
19026 
19027 struct btf *bpf_get_btf_vmlinux(void)
19028 {
19029 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19030 		mutex_lock(&bpf_verifier_lock);
19031 		if (!btf_vmlinux)
19032 			btf_vmlinux = btf_parse_vmlinux();
19033 		mutex_unlock(&bpf_verifier_lock);
19034 	}
19035 	return btf_vmlinux;
19036 }
19037 
19038 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19039 {
19040 	u64 start_time = ktime_get_ns();
19041 	struct bpf_verifier_env *env;
19042 	int i, len, ret = -EINVAL, err;
19043 	u32 log_true_size;
19044 	bool is_priv;
19045 
19046 	/* no program is valid */
19047 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19048 		return -EINVAL;
19049 
19050 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19051 	 * allocate/free it every time bpf_check() is called
19052 	 */
19053 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19054 	if (!env)
19055 		return -ENOMEM;
19056 
19057 	env->bt.env = env;
19058 
19059 	len = (*prog)->len;
19060 	env->insn_aux_data =
19061 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19062 	ret = -ENOMEM;
19063 	if (!env->insn_aux_data)
19064 		goto err_free_env;
19065 	for (i = 0; i < len; i++)
19066 		env->insn_aux_data[i].orig_idx = i;
19067 	env->prog = *prog;
19068 	env->ops = bpf_verifier_ops[env->prog->type];
19069 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19070 	is_priv = bpf_capable();
19071 
19072 	bpf_get_btf_vmlinux();
19073 
19074 	/* grab the mutex to protect few globals used by verifier */
19075 	if (!is_priv)
19076 		mutex_lock(&bpf_verifier_lock);
19077 
19078 	/* user could have requested verbose verifier output
19079 	 * and supplied buffer to store the verification trace
19080 	 */
19081 	ret = bpf_vlog_init(&env->log, attr->log_level,
19082 			    (char __user *) (unsigned long) attr->log_buf,
19083 			    attr->log_size);
19084 	if (ret)
19085 		goto err_unlock;
19086 
19087 	mark_verifier_state_clean(env);
19088 
19089 	if (IS_ERR(btf_vmlinux)) {
19090 		/* Either gcc or pahole or kernel are broken. */
19091 		verbose(env, "in-kernel BTF is malformed\n");
19092 		ret = PTR_ERR(btf_vmlinux);
19093 		goto skip_full_check;
19094 	}
19095 
19096 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19097 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19098 		env->strict_alignment = true;
19099 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19100 		env->strict_alignment = false;
19101 
19102 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19103 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19104 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19105 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19106 	env->bpf_capable = bpf_capable();
19107 
19108 	if (is_priv)
19109 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19110 
19111 	env->explored_states = kvcalloc(state_htab_size(env),
19112 				       sizeof(struct bpf_verifier_state_list *),
19113 				       GFP_USER);
19114 	ret = -ENOMEM;
19115 	if (!env->explored_states)
19116 		goto skip_full_check;
19117 
19118 	ret = add_subprog_and_kfunc(env);
19119 	if (ret < 0)
19120 		goto skip_full_check;
19121 
19122 	ret = check_subprogs(env);
19123 	if (ret < 0)
19124 		goto skip_full_check;
19125 
19126 	ret = check_btf_info(env, attr, uattr);
19127 	if (ret < 0)
19128 		goto skip_full_check;
19129 
19130 	ret = check_attach_btf_id(env);
19131 	if (ret)
19132 		goto skip_full_check;
19133 
19134 	ret = resolve_pseudo_ldimm64(env);
19135 	if (ret < 0)
19136 		goto skip_full_check;
19137 
19138 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19139 		ret = bpf_prog_offload_verifier_prep(env->prog);
19140 		if (ret)
19141 			goto skip_full_check;
19142 	}
19143 
19144 	ret = check_cfg(env);
19145 	if (ret < 0)
19146 		goto skip_full_check;
19147 
19148 	ret = do_check_subprogs(env);
19149 	ret = ret ?: do_check_main(env);
19150 
19151 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19152 		ret = bpf_prog_offload_finalize(env);
19153 
19154 skip_full_check:
19155 	kvfree(env->explored_states);
19156 
19157 	if (ret == 0)
19158 		ret = check_max_stack_depth(env);
19159 
19160 	/* instruction rewrites happen after this point */
19161 	if (ret == 0)
19162 		ret = optimize_bpf_loop(env);
19163 
19164 	if (is_priv) {
19165 		if (ret == 0)
19166 			opt_hard_wire_dead_code_branches(env);
19167 		if (ret == 0)
19168 			ret = opt_remove_dead_code(env);
19169 		if (ret == 0)
19170 			ret = opt_remove_nops(env);
19171 	} else {
19172 		if (ret == 0)
19173 			sanitize_dead_code(env);
19174 	}
19175 
19176 	if (ret == 0)
19177 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19178 		ret = convert_ctx_accesses(env);
19179 
19180 	if (ret == 0)
19181 		ret = do_misc_fixups(env);
19182 
19183 	/* do 32-bit optimization after insn patching has done so those patched
19184 	 * insns could be handled correctly.
19185 	 */
19186 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19187 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19188 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19189 								     : false;
19190 	}
19191 
19192 	if (ret == 0)
19193 		ret = fixup_call_args(env);
19194 
19195 	env->verification_time = ktime_get_ns() - start_time;
19196 	print_verification_stats(env);
19197 	env->prog->aux->verified_insns = env->insn_processed;
19198 
19199 	/* preserve original error even if log finalization is successful */
19200 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19201 	if (err)
19202 		ret = err;
19203 
19204 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19205 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19206 				  &log_true_size, sizeof(log_true_size))) {
19207 		ret = -EFAULT;
19208 		goto err_release_maps;
19209 	}
19210 
19211 	if (ret)
19212 		goto err_release_maps;
19213 
19214 	if (env->used_map_cnt) {
19215 		/* if program passed verifier, update used_maps in bpf_prog_info */
19216 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19217 							  sizeof(env->used_maps[0]),
19218 							  GFP_KERNEL);
19219 
19220 		if (!env->prog->aux->used_maps) {
19221 			ret = -ENOMEM;
19222 			goto err_release_maps;
19223 		}
19224 
19225 		memcpy(env->prog->aux->used_maps, env->used_maps,
19226 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19227 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19228 	}
19229 	if (env->used_btf_cnt) {
19230 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19231 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19232 							  sizeof(env->used_btfs[0]),
19233 							  GFP_KERNEL);
19234 		if (!env->prog->aux->used_btfs) {
19235 			ret = -ENOMEM;
19236 			goto err_release_maps;
19237 		}
19238 
19239 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19240 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19241 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19242 	}
19243 	if (env->used_map_cnt || env->used_btf_cnt) {
19244 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19245 		 * bpf_ld_imm64 instructions
19246 		 */
19247 		convert_pseudo_ld_imm64(env);
19248 	}
19249 
19250 	adjust_btf_func(env);
19251 
19252 err_release_maps:
19253 	if (!env->prog->aux->used_maps)
19254 		/* if we didn't copy map pointers into bpf_prog_info, release
19255 		 * them now. Otherwise free_used_maps() will release them.
19256 		 */
19257 		release_maps(env);
19258 	if (!env->prog->aux->used_btfs)
19259 		release_btfs(env);
19260 
19261 	/* extension progs temporarily inherit the attach_type of their targets
19262 	   for verification purposes, so set it back to zero before returning
19263 	 */
19264 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19265 		env->prog->expected_attach_type = 0;
19266 
19267 	*prog = env->prog;
19268 err_unlock:
19269 	if (!is_priv)
19270 		mutex_unlock(&bpf_verifier_lock);
19271 	vfree(env->insn_aux_data);
19272 err_free_env:
19273 	kfree(env);
19274 	return ret;
19275 }
19276