xref: /linux-6.15/kernel/bpf/verifier.c (revision 904e6ddf)
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 static bool is_trusted_reg(const struct bpf_reg_state *reg);
201 
202 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
203 {
204 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
205 }
206 
207 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
208 {
209 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
210 }
211 
212 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
213 			      const struct bpf_map *map, bool unpriv)
214 {
215 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
216 	unpriv |= bpf_map_ptr_unpriv(aux);
217 	aux->map_ptr_state = (unsigned long)map |
218 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
219 }
220 
221 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
222 {
223 	return aux->map_key_state & BPF_MAP_KEY_POISON;
224 }
225 
226 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
227 {
228 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
229 }
230 
231 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
232 {
233 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
234 }
235 
236 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
237 {
238 	bool poisoned = bpf_map_key_poisoned(aux);
239 
240 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
241 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
242 }
243 
244 static bool bpf_helper_call(const struct bpf_insn *insn)
245 {
246 	return insn->code == (BPF_JMP | BPF_CALL) &&
247 	       insn->src_reg == 0;
248 }
249 
250 static bool bpf_pseudo_call(const struct bpf_insn *insn)
251 {
252 	return insn->code == (BPF_JMP | BPF_CALL) &&
253 	       insn->src_reg == BPF_PSEUDO_CALL;
254 }
255 
256 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
257 {
258 	return insn->code == (BPF_JMP | BPF_CALL) &&
259 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
260 }
261 
262 struct bpf_call_arg_meta {
263 	struct bpf_map *map_ptr;
264 	bool raw_mode;
265 	bool pkt_access;
266 	u8 release_regno;
267 	int regno;
268 	int access_size;
269 	int mem_size;
270 	u64 msize_max_value;
271 	int ref_obj_id;
272 	int dynptr_id;
273 	int map_uid;
274 	int func_id;
275 	struct btf *btf;
276 	u32 btf_id;
277 	struct btf *ret_btf;
278 	u32 ret_btf_id;
279 	u32 subprogno;
280 	struct btf_field *kptr_field;
281 };
282 
283 struct bpf_kfunc_call_arg_meta {
284 	/* In parameters */
285 	struct btf *btf;
286 	u32 func_id;
287 	u32 kfunc_flags;
288 	const struct btf_type *func_proto;
289 	const char *func_name;
290 	/* Out parameters */
291 	u32 ref_obj_id;
292 	u8 release_regno;
293 	bool r0_rdonly;
294 	u32 ret_btf_id;
295 	u64 r0_size;
296 	u32 subprogno;
297 	struct {
298 		u64 value;
299 		bool found;
300 	} arg_constant;
301 
302 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
303 	 * generally to pass info about user-defined local kptr types to later
304 	 * verification logic
305 	 *   bpf_obj_drop
306 	 *     Record the local kptr type to be drop'd
307 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
308 	 *     Record the local kptr type to be refcount_incr'd and use
309 	 *     arg_owning_ref to determine whether refcount_acquire should be
310 	 *     fallible
311 	 */
312 	struct btf *arg_btf;
313 	u32 arg_btf_id;
314 	bool arg_owning_ref;
315 
316 	struct {
317 		struct btf_field *field;
318 	} arg_list_head;
319 	struct {
320 		struct btf_field *field;
321 	} arg_rbtree_root;
322 	struct {
323 		enum bpf_dynptr_type type;
324 		u32 id;
325 		u32 ref_obj_id;
326 	} initialized_dynptr;
327 	struct {
328 		u8 spi;
329 		u8 frameno;
330 	} iter;
331 	u64 mem_size;
332 };
333 
334 struct btf *btf_vmlinux;
335 
336 static DEFINE_MUTEX(bpf_verifier_lock);
337 
338 static const struct bpf_line_info *
339 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
340 {
341 	const struct bpf_line_info *linfo;
342 	const struct bpf_prog *prog;
343 	u32 i, nr_linfo;
344 
345 	prog = env->prog;
346 	nr_linfo = prog->aux->nr_linfo;
347 
348 	if (!nr_linfo || insn_off >= prog->len)
349 		return NULL;
350 
351 	linfo = prog->aux->linfo;
352 	for (i = 1; i < nr_linfo; i++)
353 		if (insn_off < linfo[i].insn_off)
354 			break;
355 
356 	return &linfo[i - 1];
357 }
358 
359 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
360 {
361 	struct bpf_verifier_env *env = private_data;
362 	va_list args;
363 
364 	if (!bpf_verifier_log_needed(&env->log))
365 		return;
366 
367 	va_start(args, fmt);
368 	bpf_verifier_vlog(&env->log, fmt, args);
369 	va_end(args);
370 }
371 
372 static const char *ltrim(const char *s)
373 {
374 	while (isspace(*s))
375 		s++;
376 
377 	return s;
378 }
379 
380 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
381 					 u32 insn_off,
382 					 const char *prefix_fmt, ...)
383 {
384 	const struct bpf_line_info *linfo;
385 
386 	if (!bpf_verifier_log_needed(&env->log))
387 		return;
388 
389 	linfo = find_linfo(env, insn_off);
390 	if (!linfo || linfo == env->prev_linfo)
391 		return;
392 
393 	if (prefix_fmt) {
394 		va_list args;
395 
396 		va_start(args, prefix_fmt);
397 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
398 		va_end(args);
399 	}
400 
401 	verbose(env, "%s\n",
402 		ltrim(btf_name_by_offset(env->prog->aux->btf,
403 					 linfo->line_off)));
404 
405 	env->prev_linfo = linfo;
406 }
407 
408 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
409 				   struct bpf_reg_state *reg,
410 				   struct tnum *range, const char *ctx,
411 				   const char *reg_name)
412 {
413 	char tn_buf[48];
414 
415 	verbose(env, "At %s the register %s ", ctx, reg_name);
416 	if (!tnum_is_unknown(reg->var_off)) {
417 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
418 		verbose(env, "has value %s", tn_buf);
419 	} else {
420 		verbose(env, "has unknown scalar value");
421 	}
422 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
423 	verbose(env, " should have been in %s\n", tn_buf);
424 }
425 
426 static bool type_is_pkt_pointer(enum bpf_reg_type type)
427 {
428 	type = base_type(type);
429 	return type == PTR_TO_PACKET ||
430 	       type == PTR_TO_PACKET_META;
431 }
432 
433 static bool type_is_sk_pointer(enum bpf_reg_type type)
434 {
435 	return type == PTR_TO_SOCKET ||
436 		type == PTR_TO_SOCK_COMMON ||
437 		type == PTR_TO_TCP_SOCK ||
438 		type == PTR_TO_XDP_SOCK;
439 }
440 
441 static bool type_may_be_null(u32 type)
442 {
443 	return type & PTR_MAYBE_NULL;
444 }
445 
446 static bool reg_not_null(const struct bpf_reg_state *reg)
447 {
448 	enum bpf_reg_type type;
449 
450 	type = reg->type;
451 	if (type_may_be_null(type))
452 		return false;
453 
454 	type = base_type(type);
455 	return type == PTR_TO_SOCKET ||
456 		type == PTR_TO_TCP_SOCK ||
457 		type == PTR_TO_MAP_VALUE ||
458 		type == PTR_TO_MAP_KEY ||
459 		type == PTR_TO_SOCK_COMMON ||
460 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
461 		type == PTR_TO_MEM;
462 }
463 
464 static bool type_is_ptr_alloc_obj(u32 type)
465 {
466 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
467 }
468 
469 static bool type_is_non_owning_ref(u32 type)
470 {
471 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
472 }
473 
474 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
475 {
476 	struct btf_record *rec = NULL;
477 	struct btf_struct_meta *meta;
478 
479 	if (reg->type == PTR_TO_MAP_VALUE) {
480 		rec = reg->map_ptr->record;
481 	} else if (type_is_ptr_alloc_obj(reg->type)) {
482 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
483 		if (meta)
484 			rec = meta->record;
485 	}
486 	return rec;
487 }
488 
489 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
490 {
491 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
492 
493 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
494 }
495 
496 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
497 {
498 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
499 }
500 
501 static bool type_is_rdonly_mem(u32 type)
502 {
503 	return type & MEM_RDONLY;
504 }
505 
506 static bool is_acquire_function(enum bpf_func_id func_id,
507 				const struct bpf_map *map)
508 {
509 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
510 
511 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
512 	    func_id == BPF_FUNC_sk_lookup_udp ||
513 	    func_id == BPF_FUNC_skc_lookup_tcp ||
514 	    func_id == BPF_FUNC_ringbuf_reserve ||
515 	    func_id == BPF_FUNC_kptr_xchg)
516 		return true;
517 
518 	if (func_id == BPF_FUNC_map_lookup_elem &&
519 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
520 	     map_type == BPF_MAP_TYPE_SOCKHASH))
521 		return true;
522 
523 	return false;
524 }
525 
526 static bool is_ptr_cast_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_tcp_sock ||
529 		func_id == BPF_FUNC_sk_fullsock ||
530 		func_id == BPF_FUNC_skc_to_tcp_sock ||
531 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
532 		func_id == BPF_FUNC_skc_to_udp6_sock ||
533 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
534 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
535 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
536 }
537 
538 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
539 {
540 	return func_id == BPF_FUNC_dynptr_data;
541 }
542 
543 static bool is_callback_calling_kfunc(u32 btf_id);
544 
545 static bool is_callback_calling_function(enum bpf_func_id func_id)
546 {
547 	return func_id == BPF_FUNC_for_each_map_elem ||
548 	       func_id == BPF_FUNC_timer_set_callback ||
549 	       func_id == BPF_FUNC_find_vma ||
550 	       func_id == BPF_FUNC_loop ||
551 	       func_id == BPF_FUNC_user_ringbuf_drain;
552 }
553 
554 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
555 {
556 	return func_id == BPF_FUNC_timer_set_callback;
557 }
558 
559 static bool is_storage_get_function(enum bpf_func_id func_id)
560 {
561 	return func_id == BPF_FUNC_sk_storage_get ||
562 	       func_id == BPF_FUNC_inode_storage_get ||
563 	       func_id == BPF_FUNC_task_storage_get ||
564 	       func_id == BPF_FUNC_cgrp_storage_get;
565 }
566 
567 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
568 					const struct bpf_map *map)
569 {
570 	int ref_obj_uses = 0;
571 
572 	if (is_ptr_cast_function(func_id))
573 		ref_obj_uses++;
574 	if (is_acquire_function(func_id, map))
575 		ref_obj_uses++;
576 	if (is_dynptr_ref_function(func_id))
577 		ref_obj_uses++;
578 
579 	return ref_obj_uses > 1;
580 }
581 
582 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
583 {
584 	return BPF_CLASS(insn->code) == BPF_STX &&
585 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
586 	       insn->imm == BPF_CMPXCHG;
587 }
588 
589 /* string representation of 'enum bpf_reg_type'
590  *
591  * Note that reg_type_str() can not appear more than once in a single verbose()
592  * statement.
593  */
594 static const char *reg_type_str(struct bpf_verifier_env *env,
595 				enum bpf_reg_type type)
596 {
597 	char postfix[16] = {0}, prefix[64] = {0};
598 	static const char * const str[] = {
599 		[NOT_INIT]		= "?",
600 		[SCALAR_VALUE]		= "scalar",
601 		[PTR_TO_CTX]		= "ctx",
602 		[CONST_PTR_TO_MAP]	= "map_ptr",
603 		[PTR_TO_MAP_VALUE]	= "map_value",
604 		[PTR_TO_STACK]		= "fp",
605 		[PTR_TO_PACKET]		= "pkt",
606 		[PTR_TO_PACKET_META]	= "pkt_meta",
607 		[PTR_TO_PACKET_END]	= "pkt_end",
608 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
609 		[PTR_TO_SOCKET]		= "sock",
610 		[PTR_TO_SOCK_COMMON]	= "sock_common",
611 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
612 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
613 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
614 		[PTR_TO_BTF_ID]		= "ptr_",
615 		[PTR_TO_MEM]		= "mem",
616 		[PTR_TO_BUF]		= "buf",
617 		[PTR_TO_FUNC]		= "func",
618 		[PTR_TO_MAP_KEY]	= "map_key",
619 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
620 	};
621 
622 	if (type & PTR_MAYBE_NULL) {
623 		if (base_type(type) == PTR_TO_BTF_ID)
624 			strncpy(postfix, "or_null_", 16);
625 		else
626 			strncpy(postfix, "_or_null", 16);
627 	}
628 
629 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
630 		 type & MEM_RDONLY ? "rdonly_" : "",
631 		 type & MEM_RINGBUF ? "ringbuf_" : "",
632 		 type & MEM_USER ? "user_" : "",
633 		 type & MEM_PERCPU ? "percpu_" : "",
634 		 type & MEM_RCU ? "rcu_" : "",
635 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
636 		 type & PTR_TRUSTED ? "trusted_" : ""
637 	);
638 
639 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
640 		 prefix, str[base_type(type)], postfix);
641 	return env->tmp_str_buf;
642 }
643 
644 static char slot_type_char[] = {
645 	[STACK_INVALID]	= '?',
646 	[STACK_SPILL]	= 'r',
647 	[STACK_MISC]	= 'm',
648 	[STACK_ZERO]	= '0',
649 	[STACK_DYNPTR]	= 'd',
650 	[STACK_ITER]	= 'i',
651 };
652 
653 static void print_liveness(struct bpf_verifier_env *env,
654 			   enum bpf_reg_liveness live)
655 {
656 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
657 	    verbose(env, "_");
658 	if (live & REG_LIVE_READ)
659 		verbose(env, "r");
660 	if (live & REG_LIVE_WRITTEN)
661 		verbose(env, "w");
662 	if (live & REG_LIVE_DONE)
663 		verbose(env, "D");
664 }
665 
666 static int __get_spi(s32 off)
667 {
668 	return (-off - 1) / BPF_REG_SIZE;
669 }
670 
671 static struct bpf_func_state *func(struct bpf_verifier_env *env,
672 				   const struct bpf_reg_state *reg)
673 {
674 	struct bpf_verifier_state *cur = env->cur_state;
675 
676 	return cur->frame[reg->frameno];
677 }
678 
679 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
680 {
681        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
682 
683        /* We need to check that slots between [spi - nr_slots + 1, spi] are
684 	* within [0, allocated_stack).
685 	*
686 	* Please note that the spi grows downwards. For example, a dynptr
687 	* takes the size of two stack slots; the first slot will be at
688 	* spi and the second slot will be at spi - 1.
689 	*/
690        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
691 }
692 
693 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
694 			          const char *obj_kind, int nr_slots)
695 {
696 	int off, spi;
697 
698 	if (!tnum_is_const(reg->var_off)) {
699 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
700 		return -EINVAL;
701 	}
702 
703 	off = reg->off + reg->var_off.value;
704 	if (off % BPF_REG_SIZE) {
705 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
706 		return -EINVAL;
707 	}
708 
709 	spi = __get_spi(off);
710 	if (spi + 1 < nr_slots) {
711 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
712 		return -EINVAL;
713 	}
714 
715 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
716 		return -ERANGE;
717 	return spi;
718 }
719 
720 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
721 {
722 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
723 }
724 
725 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
726 {
727 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
728 }
729 
730 static const char *btf_type_name(const struct btf *btf, u32 id)
731 {
732 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
733 }
734 
735 static const char *dynptr_type_str(enum bpf_dynptr_type type)
736 {
737 	switch (type) {
738 	case BPF_DYNPTR_TYPE_LOCAL:
739 		return "local";
740 	case BPF_DYNPTR_TYPE_RINGBUF:
741 		return "ringbuf";
742 	case BPF_DYNPTR_TYPE_SKB:
743 		return "skb";
744 	case BPF_DYNPTR_TYPE_XDP:
745 		return "xdp";
746 	case BPF_DYNPTR_TYPE_INVALID:
747 		return "<invalid>";
748 	default:
749 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
750 		return "<unknown>";
751 	}
752 }
753 
754 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
755 {
756 	if (!btf || btf_id == 0)
757 		return "<invalid>";
758 
759 	/* we already validated that type is valid and has conforming name */
760 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
761 }
762 
763 static const char *iter_state_str(enum bpf_iter_state state)
764 {
765 	switch (state) {
766 	case BPF_ITER_STATE_ACTIVE:
767 		return "active";
768 	case BPF_ITER_STATE_DRAINED:
769 		return "drained";
770 	case BPF_ITER_STATE_INVALID:
771 		return "<invalid>";
772 	default:
773 		WARN_ONCE(1, "unknown iter state %d\n", state);
774 		return "<unknown>";
775 	}
776 }
777 
778 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
779 {
780 	env->scratched_regs |= 1U << regno;
781 }
782 
783 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
784 {
785 	env->scratched_stack_slots |= 1ULL << spi;
786 }
787 
788 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
789 {
790 	return (env->scratched_regs >> regno) & 1;
791 }
792 
793 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
794 {
795 	return (env->scratched_stack_slots >> regno) & 1;
796 }
797 
798 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
799 {
800 	return env->scratched_regs || env->scratched_stack_slots;
801 }
802 
803 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
804 {
805 	env->scratched_regs = 0U;
806 	env->scratched_stack_slots = 0ULL;
807 }
808 
809 /* Used for printing the entire verifier state. */
810 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
811 {
812 	env->scratched_regs = ~0U;
813 	env->scratched_stack_slots = ~0ULL;
814 }
815 
816 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
817 {
818 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
819 	case DYNPTR_TYPE_LOCAL:
820 		return BPF_DYNPTR_TYPE_LOCAL;
821 	case DYNPTR_TYPE_RINGBUF:
822 		return BPF_DYNPTR_TYPE_RINGBUF;
823 	case DYNPTR_TYPE_SKB:
824 		return BPF_DYNPTR_TYPE_SKB;
825 	case DYNPTR_TYPE_XDP:
826 		return BPF_DYNPTR_TYPE_XDP;
827 	default:
828 		return BPF_DYNPTR_TYPE_INVALID;
829 	}
830 }
831 
832 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
833 {
834 	switch (type) {
835 	case BPF_DYNPTR_TYPE_LOCAL:
836 		return DYNPTR_TYPE_LOCAL;
837 	case BPF_DYNPTR_TYPE_RINGBUF:
838 		return DYNPTR_TYPE_RINGBUF;
839 	case BPF_DYNPTR_TYPE_SKB:
840 		return DYNPTR_TYPE_SKB;
841 	case BPF_DYNPTR_TYPE_XDP:
842 		return DYNPTR_TYPE_XDP;
843 	default:
844 		return 0;
845 	}
846 }
847 
848 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
849 {
850 	return type == BPF_DYNPTR_TYPE_RINGBUF;
851 }
852 
853 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
854 			      enum bpf_dynptr_type type,
855 			      bool first_slot, int dynptr_id);
856 
857 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
858 				struct bpf_reg_state *reg);
859 
860 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
861 				   struct bpf_reg_state *sreg1,
862 				   struct bpf_reg_state *sreg2,
863 				   enum bpf_dynptr_type type)
864 {
865 	int id = ++env->id_gen;
866 
867 	__mark_dynptr_reg(sreg1, type, true, id);
868 	__mark_dynptr_reg(sreg2, type, false, id);
869 }
870 
871 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
872 			       struct bpf_reg_state *reg,
873 			       enum bpf_dynptr_type type)
874 {
875 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
876 }
877 
878 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
879 				        struct bpf_func_state *state, int spi);
880 
881 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
882 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
883 {
884 	struct bpf_func_state *state = func(env, reg);
885 	enum bpf_dynptr_type type;
886 	int spi, i, err;
887 
888 	spi = dynptr_get_spi(env, reg);
889 	if (spi < 0)
890 		return spi;
891 
892 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
893 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
894 	 * to ensure that for the following example:
895 	 *	[d1][d1][d2][d2]
896 	 * spi    3   2   1   0
897 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
898 	 * case they do belong to same dynptr, second call won't see slot_type
899 	 * as STACK_DYNPTR and will simply skip destruction.
900 	 */
901 	err = destroy_if_dynptr_stack_slot(env, state, spi);
902 	if (err)
903 		return err;
904 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
905 	if (err)
906 		return err;
907 
908 	for (i = 0; i < BPF_REG_SIZE; i++) {
909 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
910 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
911 	}
912 
913 	type = arg_to_dynptr_type(arg_type);
914 	if (type == BPF_DYNPTR_TYPE_INVALID)
915 		return -EINVAL;
916 
917 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
918 			       &state->stack[spi - 1].spilled_ptr, type);
919 
920 	if (dynptr_type_refcounted(type)) {
921 		/* The id is used to track proper releasing */
922 		int id;
923 
924 		if (clone_ref_obj_id)
925 			id = clone_ref_obj_id;
926 		else
927 			id = acquire_reference_state(env, insn_idx);
928 
929 		if (id < 0)
930 			return id;
931 
932 		state->stack[spi].spilled_ptr.ref_obj_id = id;
933 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
934 	}
935 
936 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
937 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
938 
939 	return 0;
940 }
941 
942 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
943 {
944 	int i;
945 
946 	for (i = 0; i < BPF_REG_SIZE; i++) {
947 		state->stack[spi].slot_type[i] = STACK_INVALID;
948 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
949 	}
950 
951 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
952 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
953 
954 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
955 	 *
956 	 * While we don't allow reading STACK_INVALID, it is still possible to
957 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
958 	 * helpers or insns can do partial read of that part without failing,
959 	 * but check_stack_range_initialized, check_stack_read_var_off, and
960 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
961 	 * the slot conservatively. Hence we need to prevent those liveness
962 	 * marking walks.
963 	 *
964 	 * This was not a problem before because STACK_INVALID is only set by
965 	 * default (where the default reg state has its reg->parent as NULL), or
966 	 * in clean_live_states after REG_LIVE_DONE (at which point
967 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
968 	 * verifier state exploration (like we did above). Hence, for our case
969 	 * parentage chain will still be live (i.e. reg->parent may be
970 	 * non-NULL), while earlier reg->parent was NULL, so we need
971 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
972 	 * done later on reads or by mark_dynptr_read as well to unnecessary
973 	 * mark registers in verifier state.
974 	 */
975 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
976 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
977 }
978 
979 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
980 {
981 	struct bpf_func_state *state = func(env, reg);
982 	int spi, ref_obj_id, i;
983 
984 	spi = dynptr_get_spi(env, reg);
985 	if (spi < 0)
986 		return spi;
987 
988 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
989 		invalidate_dynptr(env, state, spi);
990 		return 0;
991 	}
992 
993 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
994 
995 	/* If the dynptr has a ref_obj_id, then we need to invalidate
996 	 * two things:
997 	 *
998 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
999 	 * 2) Any slices derived from this dynptr.
1000 	 */
1001 
1002 	/* Invalidate any slices associated with this dynptr */
1003 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1004 
1005 	/* Invalidate any dynptr clones */
1006 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1007 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1008 			continue;
1009 
1010 		/* it should always be the case that if the ref obj id
1011 		 * matches then the stack slot also belongs to a
1012 		 * dynptr
1013 		 */
1014 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1015 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1016 			return -EFAULT;
1017 		}
1018 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1019 			invalidate_dynptr(env, state, i);
1020 	}
1021 
1022 	return 0;
1023 }
1024 
1025 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1026 			       struct bpf_reg_state *reg);
1027 
1028 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1029 {
1030 	if (!env->allow_ptr_leaks)
1031 		__mark_reg_not_init(env, reg);
1032 	else
1033 		__mark_reg_unknown(env, reg);
1034 }
1035 
1036 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1037 				        struct bpf_func_state *state, int spi)
1038 {
1039 	struct bpf_func_state *fstate;
1040 	struct bpf_reg_state *dreg;
1041 	int i, dynptr_id;
1042 
1043 	/* We always ensure that STACK_DYNPTR is never set partially,
1044 	 * hence just checking for slot_type[0] is enough. This is
1045 	 * different for STACK_SPILL, where it may be only set for
1046 	 * 1 byte, so code has to use is_spilled_reg.
1047 	 */
1048 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1049 		return 0;
1050 
1051 	/* Reposition spi to first slot */
1052 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1053 		spi = spi + 1;
1054 
1055 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1056 		verbose(env, "cannot overwrite referenced dynptr\n");
1057 		return -EINVAL;
1058 	}
1059 
1060 	mark_stack_slot_scratched(env, spi);
1061 	mark_stack_slot_scratched(env, spi - 1);
1062 
1063 	/* Writing partially to one dynptr stack slot destroys both. */
1064 	for (i = 0; i < BPF_REG_SIZE; i++) {
1065 		state->stack[spi].slot_type[i] = STACK_INVALID;
1066 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1067 	}
1068 
1069 	dynptr_id = state->stack[spi].spilled_ptr.id;
1070 	/* Invalidate any slices associated with this dynptr */
1071 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1072 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1073 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1074 			continue;
1075 		if (dreg->dynptr_id == dynptr_id)
1076 			mark_reg_invalid(env, dreg);
1077 	}));
1078 
1079 	/* Do not release reference state, we are destroying dynptr on stack,
1080 	 * not using some helper to release it. Just reset register.
1081 	 */
1082 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1083 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1084 
1085 	/* Same reason as unmark_stack_slots_dynptr above */
1086 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1087 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1088 
1089 	return 0;
1090 }
1091 
1092 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1093 {
1094 	int spi;
1095 
1096 	if (reg->type == CONST_PTR_TO_DYNPTR)
1097 		return false;
1098 
1099 	spi = dynptr_get_spi(env, reg);
1100 
1101 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1102 	 * error because this just means the stack state hasn't been updated yet.
1103 	 * We will do check_mem_access to check and update stack bounds later.
1104 	 */
1105 	if (spi < 0 && spi != -ERANGE)
1106 		return false;
1107 
1108 	/* We don't need to check if the stack slots are marked by previous
1109 	 * dynptr initializations because we allow overwriting existing unreferenced
1110 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1111 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1112 	 * touching are completely destructed before we reinitialize them for a new
1113 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1114 	 * instead of delaying it until the end where the user will get "Unreleased
1115 	 * reference" error.
1116 	 */
1117 	return true;
1118 }
1119 
1120 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1121 {
1122 	struct bpf_func_state *state = func(env, reg);
1123 	int i, spi;
1124 
1125 	/* This already represents first slot of initialized bpf_dynptr.
1126 	 *
1127 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1128 	 * check_func_arg_reg_off's logic, so we don't need to check its
1129 	 * offset and alignment.
1130 	 */
1131 	if (reg->type == CONST_PTR_TO_DYNPTR)
1132 		return true;
1133 
1134 	spi = dynptr_get_spi(env, reg);
1135 	if (spi < 0)
1136 		return false;
1137 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1138 		return false;
1139 
1140 	for (i = 0; i < BPF_REG_SIZE; i++) {
1141 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1142 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1143 			return false;
1144 	}
1145 
1146 	return true;
1147 }
1148 
1149 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1150 				    enum bpf_arg_type arg_type)
1151 {
1152 	struct bpf_func_state *state = func(env, reg);
1153 	enum bpf_dynptr_type dynptr_type;
1154 	int spi;
1155 
1156 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1157 	if (arg_type == ARG_PTR_TO_DYNPTR)
1158 		return true;
1159 
1160 	dynptr_type = arg_to_dynptr_type(arg_type);
1161 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1162 		return reg->dynptr.type == dynptr_type;
1163 	} else {
1164 		spi = dynptr_get_spi(env, reg);
1165 		if (spi < 0)
1166 			return false;
1167 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1168 	}
1169 }
1170 
1171 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1172 
1173 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1174 				 struct bpf_reg_state *reg, int insn_idx,
1175 				 struct btf *btf, u32 btf_id, int nr_slots)
1176 {
1177 	struct bpf_func_state *state = func(env, reg);
1178 	int spi, i, j, id;
1179 
1180 	spi = iter_get_spi(env, reg, nr_slots);
1181 	if (spi < 0)
1182 		return spi;
1183 
1184 	id = acquire_reference_state(env, insn_idx);
1185 	if (id < 0)
1186 		return id;
1187 
1188 	for (i = 0; i < nr_slots; i++) {
1189 		struct bpf_stack_state *slot = &state->stack[spi - i];
1190 		struct bpf_reg_state *st = &slot->spilled_ptr;
1191 
1192 		__mark_reg_known_zero(st);
1193 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1194 		st->live |= REG_LIVE_WRITTEN;
1195 		st->ref_obj_id = i == 0 ? id : 0;
1196 		st->iter.btf = btf;
1197 		st->iter.btf_id = btf_id;
1198 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1199 		st->iter.depth = 0;
1200 
1201 		for (j = 0; j < BPF_REG_SIZE; j++)
1202 			slot->slot_type[j] = STACK_ITER;
1203 
1204 		mark_stack_slot_scratched(env, spi - i);
1205 	}
1206 
1207 	return 0;
1208 }
1209 
1210 static int unmark_stack_slots_iter(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 	spi = iter_get_spi(env, reg, nr_slots);
1217 	if (spi < 0)
1218 		return spi;
1219 
1220 	for (i = 0; i < nr_slots; i++) {
1221 		struct bpf_stack_state *slot = &state->stack[spi - i];
1222 		struct bpf_reg_state *st = &slot->spilled_ptr;
1223 
1224 		if (i == 0)
1225 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1226 
1227 		__mark_reg_not_init(env, st);
1228 
1229 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1230 		st->live |= REG_LIVE_WRITTEN;
1231 
1232 		for (j = 0; j < BPF_REG_SIZE; j++)
1233 			slot->slot_type[j] = STACK_INVALID;
1234 
1235 		mark_stack_slot_scratched(env, spi - i);
1236 	}
1237 
1238 	return 0;
1239 }
1240 
1241 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1242 				     struct bpf_reg_state *reg, int nr_slots)
1243 {
1244 	struct bpf_func_state *state = func(env, reg);
1245 	int spi, i, j;
1246 
1247 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1248 	 * will do check_mem_access to check and update stack bounds later, so
1249 	 * return true for that case.
1250 	 */
1251 	spi = iter_get_spi(env, reg, nr_slots);
1252 	if (spi == -ERANGE)
1253 		return true;
1254 	if (spi < 0)
1255 		return false;
1256 
1257 	for (i = 0; i < nr_slots; i++) {
1258 		struct bpf_stack_state *slot = &state->stack[spi - i];
1259 
1260 		for (j = 0; j < BPF_REG_SIZE; j++)
1261 			if (slot->slot_type[j] == STACK_ITER)
1262 				return false;
1263 	}
1264 
1265 	return true;
1266 }
1267 
1268 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1269 				   struct btf *btf, u32 btf_id, int nr_slots)
1270 {
1271 	struct bpf_func_state *state = func(env, reg);
1272 	int spi, i, j;
1273 
1274 	spi = iter_get_spi(env, reg, nr_slots);
1275 	if (spi < 0)
1276 		return false;
1277 
1278 	for (i = 0; i < nr_slots; i++) {
1279 		struct bpf_stack_state *slot = &state->stack[spi - i];
1280 		struct bpf_reg_state *st = &slot->spilled_ptr;
1281 
1282 		/* only main (first) slot has ref_obj_id set */
1283 		if (i == 0 && !st->ref_obj_id)
1284 			return false;
1285 		if (i != 0 && st->ref_obj_id)
1286 			return false;
1287 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1288 			return false;
1289 
1290 		for (j = 0; j < BPF_REG_SIZE; j++)
1291 			if (slot->slot_type[j] != STACK_ITER)
1292 				return false;
1293 	}
1294 
1295 	return true;
1296 }
1297 
1298 /* Check if given stack slot is "special":
1299  *   - spilled register state (STACK_SPILL);
1300  *   - dynptr state (STACK_DYNPTR);
1301  *   - iter state (STACK_ITER).
1302  */
1303 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1304 {
1305 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1306 
1307 	switch (type) {
1308 	case STACK_SPILL:
1309 	case STACK_DYNPTR:
1310 	case STACK_ITER:
1311 		return true;
1312 	case STACK_INVALID:
1313 	case STACK_MISC:
1314 	case STACK_ZERO:
1315 		return false;
1316 	default:
1317 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1318 		return true;
1319 	}
1320 }
1321 
1322 /* The reg state of a pointer or a bounded scalar was saved when
1323  * it was spilled to the stack.
1324  */
1325 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1326 {
1327 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1328 }
1329 
1330 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1331 {
1332 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1333 	       stack->spilled_ptr.type == SCALAR_VALUE;
1334 }
1335 
1336 static void scrub_spilled_slot(u8 *stype)
1337 {
1338 	if (*stype != STACK_INVALID)
1339 		*stype = STACK_MISC;
1340 }
1341 
1342 static void print_verifier_state(struct bpf_verifier_env *env,
1343 				 const struct bpf_func_state *state,
1344 				 bool print_all)
1345 {
1346 	const struct bpf_reg_state *reg;
1347 	enum bpf_reg_type t;
1348 	int i;
1349 
1350 	if (state->frameno)
1351 		verbose(env, " frame%d:", state->frameno);
1352 	for (i = 0; i < MAX_BPF_REG; i++) {
1353 		reg = &state->regs[i];
1354 		t = reg->type;
1355 		if (t == NOT_INIT)
1356 			continue;
1357 		if (!print_all && !reg_scratched(env, i))
1358 			continue;
1359 		verbose(env, " R%d", i);
1360 		print_liveness(env, reg->live);
1361 		verbose(env, "=");
1362 		if (t == SCALAR_VALUE && reg->precise)
1363 			verbose(env, "P");
1364 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1365 		    tnum_is_const(reg->var_off)) {
1366 			/* reg->off should be 0 for SCALAR_VALUE */
1367 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1368 			verbose(env, "%lld", reg->var_off.value + reg->off);
1369 		} else {
1370 			const char *sep = "";
1371 
1372 			verbose(env, "%s", reg_type_str(env, t));
1373 			if (base_type(t) == PTR_TO_BTF_ID)
1374 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1375 			verbose(env, "(");
1376 /*
1377  * _a stands for append, was shortened to avoid multiline statements below.
1378  * This macro is used to output a comma separated list of attributes.
1379  */
1380 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1381 
1382 			if (reg->id)
1383 				verbose_a("id=%d", reg->id);
1384 			if (reg->ref_obj_id)
1385 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1386 			if (type_is_non_owning_ref(reg->type))
1387 				verbose_a("%s", "non_own_ref");
1388 			if (t != SCALAR_VALUE)
1389 				verbose_a("off=%d", reg->off);
1390 			if (type_is_pkt_pointer(t))
1391 				verbose_a("r=%d", reg->range);
1392 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1393 				 base_type(t) == PTR_TO_MAP_KEY ||
1394 				 base_type(t) == PTR_TO_MAP_VALUE)
1395 				verbose_a("ks=%d,vs=%d",
1396 					  reg->map_ptr->key_size,
1397 					  reg->map_ptr->value_size);
1398 			if (tnum_is_const(reg->var_off)) {
1399 				/* Typically an immediate SCALAR_VALUE, but
1400 				 * could be a pointer whose offset is too big
1401 				 * for reg->off
1402 				 */
1403 				verbose_a("imm=%llx", reg->var_off.value);
1404 			} else {
1405 				if (reg->smin_value != reg->umin_value &&
1406 				    reg->smin_value != S64_MIN)
1407 					verbose_a("smin=%lld", (long long)reg->smin_value);
1408 				if (reg->smax_value != reg->umax_value &&
1409 				    reg->smax_value != S64_MAX)
1410 					verbose_a("smax=%lld", (long long)reg->smax_value);
1411 				if (reg->umin_value != 0)
1412 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1413 				if (reg->umax_value != U64_MAX)
1414 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1415 				if (!tnum_is_unknown(reg->var_off)) {
1416 					char tn_buf[48];
1417 
1418 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1419 					verbose_a("var_off=%s", tn_buf);
1420 				}
1421 				if (reg->s32_min_value != reg->smin_value &&
1422 				    reg->s32_min_value != S32_MIN)
1423 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1424 				if (reg->s32_max_value != reg->smax_value &&
1425 				    reg->s32_max_value != S32_MAX)
1426 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1427 				if (reg->u32_min_value != reg->umin_value &&
1428 				    reg->u32_min_value != U32_MIN)
1429 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1430 				if (reg->u32_max_value != reg->umax_value &&
1431 				    reg->u32_max_value != U32_MAX)
1432 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1433 			}
1434 #undef verbose_a
1435 
1436 			verbose(env, ")");
1437 		}
1438 	}
1439 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1440 		char types_buf[BPF_REG_SIZE + 1];
1441 		bool valid = false;
1442 		int j;
1443 
1444 		for (j = 0; j < BPF_REG_SIZE; j++) {
1445 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1446 				valid = true;
1447 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1448 		}
1449 		types_buf[BPF_REG_SIZE] = 0;
1450 		if (!valid)
1451 			continue;
1452 		if (!print_all && !stack_slot_scratched(env, i))
1453 			continue;
1454 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1455 		case STACK_SPILL:
1456 			reg = &state->stack[i].spilled_ptr;
1457 			t = reg->type;
1458 
1459 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1460 			print_liveness(env, reg->live);
1461 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1462 			if (t == SCALAR_VALUE && reg->precise)
1463 				verbose(env, "P");
1464 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1465 				verbose(env, "%lld", reg->var_off.value + reg->off);
1466 			break;
1467 		case STACK_DYNPTR:
1468 			i += BPF_DYNPTR_NR_SLOTS - 1;
1469 			reg = &state->stack[i].spilled_ptr;
1470 
1471 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1472 			print_liveness(env, reg->live);
1473 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1474 			if (reg->ref_obj_id)
1475 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1476 			break;
1477 		case STACK_ITER:
1478 			/* only main slot has ref_obj_id set; skip others */
1479 			reg = &state->stack[i].spilled_ptr;
1480 			if (!reg->ref_obj_id)
1481 				continue;
1482 
1483 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1484 			print_liveness(env, reg->live);
1485 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1486 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1487 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1488 				reg->iter.depth);
1489 			break;
1490 		case STACK_MISC:
1491 		case STACK_ZERO:
1492 		default:
1493 			reg = &state->stack[i].spilled_ptr;
1494 
1495 			for (j = 0; j < BPF_REG_SIZE; j++)
1496 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1497 			types_buf[BPF_REG_SIZE] = 0;
1498 
1499 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1500 			print_liveness(env, reg->live);
1501 			verbose(env, "=%s", types_buf);
1502 			break;
1503 		}
1504 	}
1505 	if (state->acquired_refs && state->refs[0].id) {
1506 		verbose(env, " refs=%d", state->refs[0].id);
1507 		for (i = 1; i < state->acquired_refs; i++)
1508 			if (state->refs[i].id)
1509 				verbose(env, ",%d", state->refs[i].id);
1510 	}
1511 	if (state->in_callback_fn)
1512 		verbose(env, " cb");
1513 	if (state->in_async_callback_fn)
1514 		verbose(env, " async_cb");
1515 	verbose(env, "\n");
1516 	mark_verifier_state_clean(env);
1517 }
1518 
1519 static inline u32 vlog_alignment(u32 pos)
1520 {
1521 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1522 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1523 }
1524 
1525 static void print_insn_state(struct bpf_verifier_env *env,
1526 			     const struct bpf_func_state *state)
1527 {
1528 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1529 		/* remove new line character */
1530 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1531 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1532 	} else {
1533 		verbose(env, "%d:", env->insn_idx);
1534 	}
1535 	print_verifier_state(env, state, false);
1536 }
1537 
1538 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1539  * small to hold src. This is different from krealloc since we don't want to preserve
1540  * the contents of dst.
1541  *
1542  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1543  * not be allocated.
1544  */
1545 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1546 {
1547 	size_t alloc_bytes;
1548 	void *orig = dst;
1549 	size_t bytes;
1550 
1551 	if (ZERO_OR_NULL_PTR(src))
1552 		goto out;
1553 
1554 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1555 		return NULL;
1556 
1557 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1558 	dst = krealloc(orig, alloc_bytes, flags);
1559 	if (!dst) {
1560 		kfree(orig);
1561 		return NULL;
1562 	}
1563 
1564 	memcpy(dst, src, bytes);
1565 out:
1566 	return dst ? dst : ZERO_SIZE_PTR;
1567 }
1568 
1569 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1570  * small to hold new_n items. new items are zeroed out if the array grows.
1571  *
1572  * Contrary to krealloc_array, does not free arr if new_n is zero.
1573  */
1574 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1575 {
1576 	size_t alloc_size;
1577 	void *new_arr;
1578 
1579 	if (!new_n || old_n == new_n)
1580 		goto out;
1581 
1582 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1583 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1584 	if (!new_arr) {
1585 		kfree(arr);
1586 		return NULL;
1587 	}
1588 	arr = new_arr;
1589 
1590 	if (new_n > old_n)
1591 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1592 
1593 out:
1594 	return arr ? arr : ZERO_SIZE_PTR;
1595 }
1596 
1597 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1598 {
1599 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1600 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1601 	if (!dst->refs)
1602 		return -ENOMEM;
1603 
1604 	dst->acquired_refs = src->acquired_refs;
1605 	return 0;
1606 }
1607 
1608 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1609 {
1610 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1611 
1612 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1613 				GFP_KERNEL);
1614 	if (!dst->stack)
1615 		return -ENOMEM;
1616 
1617 	dst->allocated_stack = src->allocated_stack;
1618 	return 0;
1619 }
1620 
1621 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1622 {
1623 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1624 				    sizeof(struct bpf_reference_state));
1625 	if (!state->refs)
1626 		return -ENOMEM;
1627 
1628 	state->acquired_refs = n;
1629 	return 0;
1630 }
1631 
1632 static int grow_stack_state(struct bpf_func_state *state, int size)
1633 {
1634 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1635 
1636 	if (old_n >= n)
1637 		return 0;
1638 
1639 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1640 	if (!state->stack)
1641 		return -ENOMEM;
1642 
1643 	state->allocated_stack = size;
1644 	return 0;
1645 }
1646 
1647 /* Acquire a pointer id from the env and update the state->refs to include
1648  * this new pointer reference.
1649  * On success, returns a valid pointer id to associate with the register
1650  * On failure, returns a negative errno.
1651  */
1652 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1653 {
1654 	struct bpf_func_state *state = cur_func(env);
1655 	int new_ofs = state->acquired_refs;
1656 	int id, err;
1657 
1658 	err = resize_reference_state(state, state->acquired_refs + 1);
1659 	if (err)
1660 		return err;
1661 	id = ++env->id_gen;
1662 	state->refs[new_ofs].id = id;
1663 	state->refs[new_ofs].insn_idx = insn_idx;
1664 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1665 
1666 	return id;
1667 }
1668 
1669 /* release function corresponding to acquire_reference_state(). Idempotent. */
1670 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1671 {
1672 	int i, last_idx;
1673 
1674 	last_idx = state->acquired_refs - 1;
1675 	for (i = 0; i < state->acquired_refs; i++) {
1676 		if (state->refs[i].id == ptr_id) {
1677 			/* Cannot release caller references in callbacks */
1678 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1679 				return -EINVAL;
1680 			if (last_idx && i != last_idx)
1681 				memcpy(&state->refs[i], &state->refs[last_idx],
1682 				       sizeof(*state->refs));
1683 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1684 			state->acquired_refs--;
1685 			return 0;
1686 		}
1687 	}
1688 	return -EINVAL;
1689 }
1690 
1691 static void free_func_state(struct bpf_func_state *state)
1692 {
1693 	if (!state)
1694 		return;
1695 	kfree(state->refs);
1696 	kfree(state->stack);
1697 	kfree(state);
1698 }
1699 
1700 static void clear_jmp_history(struct bpf_verifier_state *state)
1701 {
1702 	kfree(state->jmp_history);
1703 	state->jmp_history = NULL;
1704 	state->jmp_history_cnt = 0;
1705 }
1706 
1707 static void free_verifier_state(struct bpf_verifier_state *state,
1708 				bool free_self)
1709 {
1710 	int i;
1711 
1712 	for (i = 0; i <= state->curframe; i++) {
1713 		free_func_state(state->frame[i]);
1714 		state->frame[i] = NULL;
1715 	}
1716 	clear_jmp_history(state);
1717 	if (free_self)
1718 		kfree(state);
1719 }
1720 
1721 /* copy verifier state from src to dst growing dst stack space
1722  * when necessary to accommodate larger src stack
1723  */
1724 static int copy_func_state(struct bpf_func_state *dst,
1725 			   const struct bpf_func_state *src)
1726 {
1727 	int err;
1728 
1729 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1730 	err = copy_reference_state(dst, src);
1731 	if (err)
1732 		return err;
1733 	return copy_stack_state(dst, src);
1734 }
1735 
1736 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1737 			       const struct bpf_verifier_state *src)
1738 {
1739 	struct bpf_func_state *dst;
1740 	int i, err;
1741 
1742 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1743 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1744 					    GFP_USER);
1745 	if (!dst_state->jmp_history)
1746 		return -ENOMEM;
1747 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1748 
1749 	/* if dst has more stack frames then src frame, free them */
1750 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1751 		free_func_state(dst_state->frame[i]);
1752 		dst_state->frame[i] = NULL;
1753 	}
1754 	dst_state->speculative = src->speculative;
1755 	dst_state->active_rcu_lock = src->active_rcu_lock;
1756 	dst_state->curframe = src->curframe;
1757 	dst_state->active_lock.ptr = src->active_lock.ptr;
1758 	dst_state->active_lock.id = src->active_lock.id;
1759 	dst_state->branches = src->branches;
1760 	dst_state->parent = src->parent;
1761 	dst_state->first_insn_idx = src->first_insn_idx;
1762 	dst_state->last_insn_idx = src->last_insn_idx;
1763 	for (i = 0; i <= src->curframe; i++) {
1764 		dst = dst_state->frame[i];
1765 		if (!dst) {
1766 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1767 			if (!dst)
1768 				return -ENOMEM;
1769 			dst_state->frame[i] = dst;
1770 		}
1771 		err = copy_func_state(dst, src->frame[i]);
1772 		if (err)
1773 			return err;
1774 	}
1775 	return 0;
1776 }
1777 
1778 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1779 {
1780 	while (st) {
1781 		u32 br = --st->branches;
1782 
1783 		/* WARN_ON(br > 1) technically makes sense here,
1784 		 * but see comment in push_stack(), hence:
1785 		 */
1786 		WARN_ONCE((int)br < 0,
1787 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1788 			  br);
1789 		if (br)
1790 			break;
1791 		st = st->parent;
1792 	}
1793 }
1794 
1795 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1796 		     int *insn_idx, bool pop_log)
1797 {
1798 	struct bpf_verifier_state *cur = env->cur_state;
1799 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1800 	int err;
1801 
1802 	if (env->head == NULL)
1803 		return -ENOENT;
1804 
1805 	if (cur) {
1806 		err = copy_verifier_state(cur, &head->st);
1807 		if (err)
1808 			return err;
1809 	}
1810 	if (pop_log)
1811 		bpf_vlog_reset(&env->log, head->log_pos);
1812 	if (insn_idx)
1813 		*insn_idx = head->insn_idx;
1814 	if (prev_insn_idx)
1815 		*prev_insn_idx = head->prev_insn_idx;
1816 	elem = head->next;
1817 	free_verifier_state(&head->st, false);
1818 	kfree(head);
1819 	env->head = elem;
1820 	env->stack_size--;
1821 	return 0;
1822 }
1823 
1824 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1825 					     int insn_idx, int prev_insn_idx,
1826 					     bool speculative)
1827 {
1828 	struct bpf_verifier_state *cur = env->cur_state;
1829 	struct bpf_verifier_stack_elem *elem;
1830 	int err;
1831 
1832 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1833 	if (!elem)
1834 		goto err;
1835 
1836 	elem->insn_idx = insn_idx;
1837 	elem->prev_insn_idx = prev_insn_idx;
1838 	elem->next = env->head;
1839 	elem->log_pos = env->log.end_pos;
1840 	env->head = elem;
1841 	env->stack_size++;
1842 	err = copy_verifier_state(&elem->st, cur);
1843 	if (err)
1844 		goto err;
1845 	elem->st.speculative |= speculative;
1846 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1847 		verbose(env, "The sequence of %d jumps is too complex.\n",
1848 			env->stack_size);
1849 		goto err;
1850 	}
1851 	if (elem->st.parent) {
1852 		++elem->st.parent->branches;
1853 		/* WARN_ON(branches > 2) technically makes sense here,
1854 		 * but
1855 		 * 1. speculative states will bump 'branches' for non-branch
1856 		 * instructions
1857 		 * 2. is_state_visited() heuristics may decide not to create
1858 		 * a new state for a sequence of branches and all such current
1859 		 * and cloned states will be pointing to a single parent state
1860 		 * which might have large 'branches' count.
1861 		 */
1862 	}
1863 	return &elem->st;
1864 err:
1865 	free_verifier_state(env->cur_state, true);
1866 	env->cur_state = NULL;
1867 	/* pop all elements and return */
1868 	while (!pop_stack(env, NULL, NULL, false));
1869 	return NULL;
1870 }
1871 
1872 #define CALLER_SAVED_REGS 6
1873 static const int caller_saved[CALLER_SAVED_REGS] = {
1874 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1875 };
1876 
1877 /* This helper doesn't clear reg->id */
1878 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1879 {
1880 	reg->var_off = tnum_const(imm);
1881 	reg->smin_value = (s64)imm;
1882 	reg->smax_value = (s64)imm;
1883 	reg->umin_value = imm;
1884 	reg->umax_value = imm;
1885 
1886 	reg->s32_min_value = (s32)imm;
1887 	reg->s32_max_value = (s32)imm;
1888 	reg->u32_min_value = (u32)imm;
1889 	reg->u32_max_value = (u32)imm;
1890 }
1891 
1892 /* Mark the unknown part of a register (variable offset or scalar value) as
1893  * known to have the value @imm.
1894  */
1895 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1896 {
1897 	/* Clear off and union(map_ptr, range) */
1898 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1899 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1900 	reg->id = 0;
1901 	reg->ref_obj_id = 0;
1902 	___mark_reg_known(reg, imm);
1903 }
1904 
1905 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1906 {
1907 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1908 	reg->s32_min_value = (s32)imm;
1909 	reg->s32_max_value = (s32)imm;
1910 	reg->u32_min_value = (u32)imm;
1911 	reg->u32_max_value = (u32)imm;
1912 }
1913 
1914 /* Mark the 'variable offset' part of a register as zero.  This should be
1915  * used only on registers holding a pointer type.
1916  */
1917 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1918 {
1919 	__mark_reg_known(reg, 0);
1920 }
1921 
1922 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1923 {
1924 	__mark_reg_known(reg, 0);
1925 	reg->type = SCALAR_VALUE;
1926 }
1927 
1928 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1929 				struct bpf_reg_state *regs, u32 regno)
1930 {
1931 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1932 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1933 		/* Something bad happened, let's kill all regs */
1934 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1935 			__mark_reg_not_init(env, regs + regno);
1936 		return;
1937 	}
1938 	__mark_reg_known_zero(regs + regno);
1939 }
1940 
1941 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1942 			      bool first_slot, int dynptr_id)
1943 {
1944 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1945 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1946 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1947 	 */
1948 	__mark_reg_known_zero(reg);
1949 	reg->type = CONST_PTR_TO_DYNPTR;
1950 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1951 	reg->id = dynptr_id;
1952 	reg->dynptr.type = type;
1953 	reg->dynptr.first_slot = first_slot;
1954 }
1955 
1956 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1957 {
1958 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1959 		const struct bpf_map *map = reg->map_ptr;
1960 
1961 		if (map->inner_map_meta) {
1962 			reg->type = CONST_PTR_TO_MAP;
1963 			reg->map_ptr = map->inner_map_meta;
1964 			/* transfer reg's id which is unique for every map_lookup_elem
1965 			 * as UID of the inner map.
1966 			 */
1967 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1968 				reg->map_uid = reg->id;
1969 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1970 			reg->type = PTR_TO_XDP_SOCK;
1971 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1972 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1973 			reg->type = PTR_TO_SOCKET;
1974 		} else {
1975 			reg->type = PTR_TO_MAP_VALUE;
1976 		}
1977 		return;
1978 	}
1979 
1980 	reg->type &= ~PTR_MAYBE_NULL;
1981 }
1982 
1983 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1984 				struct btf_field_graph_root *ds_head)
1985 {
1986 	__mark_reg_known_zero(&regs[regno]);
1987 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1988 	regs[regno].btf = ds_head->btf;
1989 	regs[regno].btf_id = ds_head->value_btf_id;
1990 	regs[regno].off = ds_head->node_offset;
1991 }
1992 
1993 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1994 {
1995 	return type_is_pkt_pointer(reg->type);
1996 }
1997 
1998 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1999 {
2000 	return reg_is_pkt_pointer(reg) ||
2001 	       reg->type == PTR_TO_PACKET_END;
2002 }
2003 
2004 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2005 {
2006 	return base_type(reg->type) == PTR_TO_MEM &&
2007 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2008 }
2009 
2010 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2011 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2012 				    enum bpf_reg_type which)
2013 {
2014 	/* The register can already have a range from prior markings.
2015 	 * This is fine as long as it hasn't been advanced from its
2016 	 * origin.
2017 	 */
2018 	return reg->type == which &&
2019 	       reg->id == 0 &&
2020 	       reg->off == 0 &&
2021 	       tnum_equals_const(reg->var_off, 0);
2022 }
2023 
2024 /* Reset the min/max bounds of a register */
2025 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2026 {
2027 	reg->smin_value = S64_MIN;
2028 	reg->smax_value = S64_MAX;
2029 	reg->umin_value = 0;
2030 	reg->umax_value = U64_MAX;
2031 
2032 	reg->s32_min_value = S32_MIN;
2033 	reg->s32_max_value = S32_MAX;
2034 	reg->u32_min_value = 0;
2035 	reg->u32_max_value = U32_MAX;
2036 }
2037 
2038 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2039 {
2040 	reg->smin_value = S64_MIN;
2041 	reg->smax_value = S64_MAX;
2042 	reg->umin_value = 0;
2043 	reg->umax_value = U64_MAX;
2044 }
2045 
2046 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2047 {
2048 	reg->s32_min_value = S32_MIN;
2049 	reg->s32_max_value = S32_MAX;
2050 	reg->u32_min_value = 0;
2051 	reg->u32_max_value = U32_MAX;
2052 }
2053 
2054 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2055 {
2056 	struct tnum var32_off = tnum_subreg(reg->var_off);
2057 
2058 	/* min signed is max(sign bit) | min(other bits) */
2059 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2060 			var32_off.value | (var32_off.mask & S32_MIN));
2061 	/* max signed is min(sign bit) | max(other bits) */
2062 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2063 			var32_off.value | (var32_off.mask & S32_MAX));
2064 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2065 	reg->u32_max_value = min(reg->u32_max_value,
2066 				 (u32)(var32_off.value | var32_off.mask));
2067 }
2068 
2069 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2070 {
2071 	/* min signed is max(sign bit) | min(other bits) */
2072 	reg->smin_value = max_t(s64, reg->smin_value,
2073 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2074 	/* max signed is min(sign bit) | max(other bits) */
2075 	reg->smax_value = min_t(s64, reg->smax_value,
2076 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2077 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2078 	reg->umax_value = min(reg->umax_value,
2079 			      reg->var_off.value | reg->var_off.mask);
2080 }
2081 
2082 static void __update_reg_bounds(struct bpf_reg_state *reg)
2083 {
2084 	__update_reg32_bounds(reg);
2085 	__update_reg64_bounds(reg);
2086 }
2087 
2088 /* Uses signed min/max values to inform unsigned, and vice-versa */
2089 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2090 {
2091 	/* Learn sign from signed bounds.
2092 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2093 	 * are the same, so combine.  This works even in the negative case, e.g.
2094 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2095 	 */
2096 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2097 		reg->s32_min_value = reg->u32_min_value =
2098 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2099 		reg->s32_max_value = reg->u32_max_value =
2100 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2101 		return;
2102 	}
2103 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2104 	 * boundary, so we must be careful.
2105 	 */
2106 	if ((s32)reg->u32_max_value >= 0) {
2107 		/* Positive.  We can't learn anything from the smin, but smax
2108 		 * is positive, hence safe.
2109 		 */
2110 		reg->s32_min_value = reg->u32_min_value;
2111 		reg->s32_max_value = reg->u32_max_value =
2112 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2113 	} else if ((s32)reg->u32_min_value < 0) {
2114 		/* Negative.  We can't learn anything from the smax, but smin
2115 		 * is negative, hence safe.
2116 		 */
2117 		reg->s32_min_value = reg->u32_min_value =
2118 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2119 		reg->s32_max_value = reg->u32_max_value;
2120 	}
2121 }
2122 
2123 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2124 {
2125 	/* Learn sign from signed bounds.
2126 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2127 	 * are the same, so combine.  This works even in the negative case, e.g.
2128 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2129 	 */
2130 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2131 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2132 							  reg->umin_value);
2133 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2134 							  reg->umax_value);
2135 		return;
2136 	}
2137 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2138 	 * boundary, so we must be careful.
2139 	 */
2140 	if ((s64)reg->umax_value >= 0) {
2141 		/* Positive.  We can't learn anything from the smin, but smax
2142 		 * is positive, hence safe.
2143 		 */
2144 		reg->smin_value = reg->umin_value;
2145 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2146 							  reg->umax_value);
2147 	} else if ((s64)reg->umin_value < 0) {
2148 		/* Negative.  We can't learn anything from the smax, but smin
2149 		 * is negative, hence safe.
2150 		 */
2151 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2152 							  reg->umin_value);
2153 		reg->smax_value = reg->umax_value;
2154 	}
2155 }
2156 
2157 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2158 {
2159 	__reg32_deduce_bounds(reg);
2160 	__reg64_deduce_bounds(reg);
2161 }
2162 
2163 /* Attempts to improve var_off based on unsigned min/max information */
2164 static void __reg_bound_offset(struct bpf_reg_state *reg)
2165 {
2166 	struct tnum var64_off = tnum_intersect(reg->var_off,
2167 					       tnum_range(reg->umin_value,
2168 							  reg->umax_value));
2169 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2170 					       tnum_range(reg->u32_min_value,
2171 							  reg->u32_max_value));
2172 
2173 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2174 }
2175 
2176 static void reg_bounds_sync(struct bpf_reg_state *reg)
2177 {
2178 	/* We might have learned new bounds from the var_off. */
2179 	__update_reg_bounds(reg);
2180 	/* We might have learned something about the sign bit. */
2181 	__reg_deduce_bounds(reg);
2182 	/* We might have learned some bits from the bounds. */
2183 	__reg_bound_offset(reg);
2184 	/* Intersecting with the old var_off might have improved our bounds
2185 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2186 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2187 	 */
2188 	__update_reg_bounds(reg);
2189 }
2190 
2191 static bool __reg32_bound_s64(s32 a)
2192 {
2193 	return a >= 0 && a <= S32_MAX;
2194 }
2195 
2196 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2197 {
2198 	reg->umin_value = reg->u32_min_value;
2199 	reg->umax_value = reg->u32_max_value;
2200 
2201 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2202 	 * be positive otherwise set to worse case bounds and refine later
2203 	 * from tnum.
2204 	 */
2205 	if (__reg32_bound_s64(reg->s32_min_value) &&
2206 	    __reg32_bound_s64(reg->s32_max_value)) {
2207 		reg->smin_value = reg->s32_min_value;
2208 		reg->smax_value = reg->s32_max_value;
2209 	} else {
2210 		reg->smin_value = 0;
2211 		reg->smax_value = U32_MAX;
2212 	}
2213 }
2214 
2215 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2216 {
2217 	/* special case when 64-bit register has upper 32-bit register
2218 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2219 	 * allowing us to use 32-bit bounds directly,
2220 	 */
2221 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2222 		__reg_assign_32_into_64(reg);
2223 	} else {
2224 		/* Otherwise the best we can do is push lower 32bit known and
2225 		 * unknown bits into register (var_off set from jmp logic)
2226 		 * then learn as much as possible from the 64-bit tnum
2227 		 * known and unknown bits. The previous smin/smax bounds are
2228 		 * invalid here because of jmp32 compare so mark them unknown
2229 		 * so they do not impact tnum bounds calculation.
2230 		 */
2231 		__mark_reg64_unbounded(reg);
2232 	}
2233 	reg_bounds_sync(reg);
2234 }
2235 
2236 static bool __reg64_bound_s32(s64 a)
2237 {
2238 	return a >= S32_MIN && a <= S32_MAX;
2239 }
2240 
2241 static bool __reg64_bound_u32(u64 a)
2242 {
2243 	return a >= U32_MIN && a <= U32_MAX;
2244 }
2245 
2246 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2247 {
2248 	__mark_reg32_unbounded(reg);
2249 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2250 		reg->s32_min_value = (s32)reg->smin_value;
2251 		reg->s32_max_value = (s32)reg->smax_value;
2252 	}
2253 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2254 		reg->u32_min_value = (u32)reg->umin_value;
2255 		reg->u32_max_value = (u32)reg->umax_value;
2256 	}
2257 	reg_bounds_sync(reg);
2258 }
2259 
2260 /* Mark a register as having a completely unknown (scalar) value. */
2261 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2262 			       struct bpf_reg_state *reg)
2263 {
2264 	/*
2265 	 * Clear type, off, and union(map_ptr, range) and
2266 	 * padding between 'type' and union
2267 	 */
2268 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2269 	reg->type = SCALAR_VALUE;
2270 	reg->id = 0;
2271 	reg->ref_obj_id = 0;
2272 	reg->var_off = tnum_unknown;
2273 	reg->frameno = 0;
2274 	reg->precise = !env->bpf_capable;
2275 	__mark_reg_unbounded(reg);
2276 }
2277 
2278 static void mark_reg_unknown(struct bpf_verifier_env *env,
2279 			     struct bpf_reg_state *regs, u32 regno)
2280 {
2281 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2282 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2283 		/* Something bad happened, let's kill all regs except FP */
2284 		for (regno = 0; regno < BPF_REG_FP; regno++)
2285 			__mark_reg_not_init(env, regs + regno);
2286 		return;
2287 	}
2288 	__mark_reg_unknown(env, regs + regno);
2289 }
2290 
2291 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2292 				struct bpf_reg_state *reg)
2293 {
2294 	__mark_reg_unknown(env, reg);
2295 	reg->type = NOT_INIT;
2296 }
2297 
2298 static void mark_reg_not_init(struct bpf_verifier_env *env,
2299 			      struct bpf_reg_state *regs, u32 regno)
2300 {
2301 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2302 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2303 		/* Something bad happened, let's kill all regs except FP */
2304 		for (regno = 0; regno < BPF_REG_FP; regno++)
2305 			__mark_reg_not_init(env, regs + regno);
2306 		return;
2307 	}
2308 	__mark_reg_not_init(env, regs + regno);
2309 }
2310 
2311 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2312 			    struct bpf_reg_state *regs, u32 regno,
2313 			    enum bpf_reg_type reg_type,
2314 			    struct btf *btf, u32 btf_id,
2315 			    enum bpf_type_flag flag)
2316 {
2317 	if (reg_type == SCALAR_VALUE) {
2318 		mark_reg_unknown(env, regs, regno);
2319 		return;
2320 	}
2321 	mark_reg_known_zero(env, regs, regno);
2322 	regs[regno].type = PTR_TO_BTF_ID | flag;
2323 	regs[regno].btf = btf;
2324 	regs[regno].btf_id = btf_id;
2325 }
2326 
2327 #define DEF_NOT_SUBREG	(0)
2328 static void init_reg_state(struct bpf_verifier_env *env,
2329 			   struct bpf_func_state *state)
2330 {
2331 	struct bpf_reg_state *regs = state->regs;
2332 	int i;
2333 
2334 	for (i = 0; i < MAX_BPF_REG; i++) {
2335 		mark_reg_not_init(env, regs, i);
2336 		regs[i].live = REG_LIVE_NONE;
2337 		regs[i].parent = NULL;
2338 		regs[i].subreg_def = DEF_NOT_SUBREG;
2339 	}
2340 
2341 	/* frame pointer */
2342 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2343 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2344 	regs[BPF_REG_FP].frameno = state->frameno;
2345 }
2346 
2347 #define BPF_MAIN_FUNC (-1)
2348 static void init_func_state(struct bpf_verifier_env *env,
2349 			    struct bpf_func_state *state,
2350 			    int callsite, int frameno, int subprogno)
2351 {
2352 	state->callsite = callsite;
2353 	state->frameno = frameno;
2354 	state->subprogno = subprogno;
2355 	state->callback_ret_range = tnum_range(0, 0);
2356 	init_reg_state(env, state);
2357 	mark_verifier_state_scratched(env);
2358 }
2359 
2360 /* Similar to push_stack(), but for async callbacks */
2361 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2362 						int insn_idx, int prev_insn_idx,
2363 						int subprog)
2364 {
2365 	struct bpf_verifier_stack_elem *elem;
2366 	struct bpf_func_state *frame;
2367 
2368 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2369 	if (!elem)
2370 		goto err;
2371 
2372 	elem->insn_idx = insn_idx;
2373 	elem->prev_insn_idx = prev_insn_idx;
2374 	elem->next = env->head;
2375 	elem->log_pos = env->log.end_pos;
2376 	env->head = elem;
2377 	env->stack_size++;
2378 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2379 		verbose(env,
2380 			"The sequence of %d jumps is too complex for async cb.\n",
2381 			env->stack_size);
2382 		goto err;
2383 	}
2384 	/* Unlike push_stack() do not copy_verifier_state().
2385 	 * The caller state doesn't matter.
2386 	 * This is async callback. It starts in a fresh stack.
2387 	 * Initialize it similar to do_check_common().
2388 	 */
2389 	elem->st.branches = 1;
2390 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2391 	if (!frame)
2392 		goto err;
2393 	init_func_state(env, frame,
2394 			BPF_MAIN_FUNC /* callsite */,
2395 			0 /* frameno within this callchain */,
2396 			subprog /* subprog number within this prog */);
2397 	elem->st.frame[0] = frame;
2398 	return &elem->st;
2399 err:
2400 	free_verifier_state(env->cur_state, true);
2401 	env->cur_state = NULL;
2402 	/* pop all elements and return */
2403 	while (!pop_stack(env, NULL, NULL, false));
2404 	return NULL;
2405 }
2406 
2407 
2408 enum reg_arg_type {
2409 	SRC_OP,		/* register is used as source operand */
2410 	DST_OP,		/* register is used as destination operand */
2411 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2412 };
2413 
2414 static int cmp_subprogs(const void *a, const void *b)
2415 {
2416 	return ((struct bpf_subprog_info *)a)->start -
2417 	       ((struct bpf_subprog_info *)b)->start;
2418 }
2419 
2420 static int find_subprog(struct bpf_verifier_env *env, int off)
2421 {
2422 	struct bpf_subprog_info *p;
2423 
2424 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2425 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2426 	if (!p)
2427 		return -ENOENT;
2428 	return p - env->subprog_info;
2429 
2430 }
2431 
2432 static int add_subprog(struct bpf_verifier_env *env, int off)
2433 {
2434 	int insn_cnt = env->prog->len;
2435 	int ret;
2436 
2437 	if (off >= insn_cnt || off < 0) {
2438 		verbose(env, "call to invalid destination\n");
2439 		return -EINVAL;
2440 	}
2441 	ret = find_subprog(env, off);
2442 	if (ret >= 0)
2443 		return ret;
2444 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2445 		verbose(env, "too many subprograms\n");
2446 		return -E2BIG;
2447 	}
2448 	/* determine subprog starts. The end is one before the next starts */
2449 	env->subprog_info[env->subprog_cnt++].start = off;
2450 	sort(env->subprog_info, env->subprog_cnt,
2451 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2452 	return env->subprog_cnt - 1;
2453 }
2454 
2455 #define MAX_KFUNC_DESCS 256
2456 #define MAX_KFUNC_BTFS	256
2457 
2458 struct bpf_kfunc_desc {
2459 	struct btf_func_model func_model;
2460 	u32 func_id;
2461 	s32 imm;
2462 	u16 offset;
2463 	unsigned long addr;
2464 };
2465 
2466 struct bpf_kfunc_btf {
2467 	struct btf *btf;
2468 	struct module *module;
2469 	u16 offset;
2470 };
2471 
2472 struct bpf_kfunc_desc_tab {
2473 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2474 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2475 	 * available, therefore at the end of verification do_misc_fixups()
2476 	 * sorts this by imm and offset.
2477 	 */
2478 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2479 	u32 nr_descs;
2480 };
2481 
2482 struct bpf_kfunc_btf_tab {
2483 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2484 	u32 nr_descs;
2485 };
2486 
2487 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2488 {
2489 	const struct bpf_kfunc_desc *d0 = a;
2490 	const struct bpf_kfunc_desc *d1 = b;
2491 
2492 	/* func_id is not greater than BTF_MAX_TYPE */
2493 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2494 }
2495 
2496 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2497 {
2498 	const struct bpf_kfunc_btf *d0 = a;
2499 	const struct bpf_kfunc_btf *d1 = b;
2500 
2501 	return d0->offset - d1->offset;
2502 }
2503 
2504 static const struct bpf_kfunc_desc *
2505 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2506 {
2507 	struct bpf_kfunc_desc desc = {
2508 		.func_id = func_id,
2509 		.offset = offset,
2510 	};
2511 	struct bpf_kfunc_desc_tab *tab;
2512 
2513 	tab = prog->aux->kfunc_tab;
2514 	return bsearch(&desc, tab->descs, tab->nr_descs,
2515 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2516 }
2517 
2518 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2519 		       u16 btf_fd_idx, u8 **func_addr)
2520 {
2521 	const struct bpf_kfunc_desc *desc;
2522 
2523 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2524 	if (!desc)
2525 		return -EFAULT;
2526 
2527 	*func_addr = (u8 *)desc->addr;
2528 	return 0;
2529 }
2530 
2531 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2532 					 s16 offset)
2533 {
2534 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2535 	struct bpf_kfunc_btf_tab *tab;
2536 	struct bpf_kfunc_btf *b;
2537 	struct module *mod;
2538 	struct btf *btf;
2539 	int btf_fd;
2540 
2541 	tab = env->prog->aux->kfunc_btf_tab;
2542 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2543 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2544 	if (!b) {
2545 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2546 			verbose(env, "too many different module BTFs\n");
2547 			return ERR_PTR(-E2BIG);
2548 		}
2549 
2550 		if (bpfptr_is_null(env->fd_array)) {
2551 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2552 			return ERR_PTR(-EPROTO);
2553 		}
2554 
2555 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2556 					    offset * sizeof(btf_fd),
2557 					    sizeof(btf_fd)))
2558 			return ERR_PTR(-EFAULT);
2559 
2560 		btf = btf_get_by_fd(btf_fd);
2561 		if (IS_ERR(btf)) {
2562 			verbose(env, "invalid module BTF fd specified\n");
2563 			return btf;
2564 		}
2565 
2566 		if (!btf_is_module(btf)) {
2567 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2568 			btf_put(btf);
2569 			return ERR_PTR(-EINVAL);
2570 		}
2571 
2572 		mod = btf_try_get_module(btf);
2573 		if (!mod) {
2574 			btf_put(btf);
2575 			return ERR_PTR(-ENXIO);
2576 		}
2577 
2578 		b = &tab->descs[tab->nr_descs++];
2579 		b->btf = btf;
2580 		b->module = mod;
2581 		b->offset = offset;
2582 
2583 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2584 		     kfunc_btf_cmp_by_off, NULL);
2585 	}
2586 	return b->btf;
2587 }
2588 
2589 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2590 {
2591 	if (!tab)
2592 		return;
2593 
2594 	while (tab->nr_descs--) {
2595 		module_put(tab->descs[tab->nr_descs].module);
2596 		btf_put(tab->descs[tab->nr_descs].btf);
2597 	}
2598 	kfree(tab);
2599 }
2600 
2601 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2602 {
2603 	if (offset) {
2604 		if (offset < 0) {
2605 			/* In the future, this can be allowed to increase limit
2606 			 * of fd index into fd_array, interpreted as u16.
2607 			 */
2608 			verbose(env, "negative offset disallowed for kernel module function call\n");
2609 			return ERR_PTR(-EINVAL);
2610 		}
2611 
2612 		return __find_kfunc_desc_btf(env, offset);
2613 	}
2614 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2615 }
2616 
2617 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2618 {
2619 	const struct btf_type *func, *func_proto;
2620 	struct bpf_kfunc_btf_tab *btf_tab;
2621 	struct bpf_kfunc_desc_tab *tab;
2622 	struct bpf_prog_aux *prog_aux;
2623 	struct bpf_kfunc_desc *desc;
2624 	const char *func_name;
2625 	struct btf *desc_btf;
2626 	unsigned long call_imm;
2627 	unsigned long addr;
2628 	int err;
2629 
2630 	prog_aux = env->prog->aux;
2631 	tab = prog_aux->kfunc_tab;
2632 	btf_tab = prog_aux->kfunc_btf_tab;
2633 	if (!tab) {
2634 		if (!btf_vmlinux) {
2635 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2636 			return -ENOTSUPP;
2637 		}
2638 
2639 		if (!env->prog->jit_requested) {
2640 			verbose(env, "JIT is required for calling kernel function\n");
2641 			return -ENOTSUPP;
2642 		}
2643 
2644 		if (!bpf_jit_supports_kfunc_call()) {
2645 			verbose(env, "JIT does not support calling kernel function\n");
2646 			return -ENOTSUPP;
2647 		}
2648 
2649 		if (!env->prog->gpl_compatible) {
2650 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2651 			return -EINVAL;
2652 		}
2653 
2654 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2655 		if (!tab)
2656 			return -ENOMEM;
2657 		prog_aux->kfunc_tab = tab;
2658 	}
2659 
2660 	/* func_id == 0 is always invalid, but instead of returning an error, be
2661 	 * conservative and wait until the code elimination pass before returning
2662 	 * error, so that invalid calls that get pruned out can be in BPF programs
2663 	 * loaded from userspace.  It is also required that offset be untouched
2664 	 * for such calls.
2665 	 */
2666 	if (!func_id && !offset)
2667 		return 0;
2668 
2669 	if (!btf_tab && offset) {
2670 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2671 		if (!btf_tab)
2672 			return -ENOMEM;
2673 		prog_aux->kfunc_btf_tab = btf_tab;
2674 	}
2675 
2676 	desc_btf = find_kfunc_desc_btf(env, offset);
2677 	if (IS_ERR(desc_btf)) {
2678 		verbose(env, "failed to find BTF for kernel function\n");
2679 		return PTR_ERR(desc_btf);
2680 	}
2681 
2682 	if (find_kfunc_desc(env->prog, func_id, offset))
2683 		return 0;
2684 
2685 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2686 		verbose(env, "too many different kernel function calls\n");
2687 		return -E2BIG;
2688 	}
2689 
2690 	func = btf_type_by_id(desc_btf, func_id);
2691 	if (!func || !btf_type_is_func(func)) {
2692 		verbose(env, "kernel btf_id %u is not a function\n",
2693 			func_id);
2694 		return -EINVAL;
2695 	}
2696 	func_proto = btf_type_by_id(desc_btf, func->type);
2697 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2698 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2699 			func_id);
2700 		return -EINVAL;
2701 	}
2702 
2703 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2704 	addr = kallsyms_lookup_name(func_name);
2705 	if (!addr) {
2706 		verbose(env, "cannot find address for kernel function %s\n",
2707 			func_name);
2708 		return -EINVAL;
2709 	}
2710 	specialize_kfunc(env, func_id, offset, &addr);
2711 
2712 	if (bpf_jit_supports_far_kfunc_call()) {
2713 		call_imm = func_id;
2714 	} else {
2715 		call_imm = BPF_CALL_IMM(addr);
2716 		/* Check whether the relative offset overflows desc->imm */
2717 		if ((unsigned long)(s32)call_imm != call_imm) {
2718 			verbose(env, "address of kernel function %s is out of range\n",
2719 				func_name);
2720 			return -EINVAL;
2721 		}
2722 	}
2723 
2724 	if (bpf_dev_bound_kfunc_id(func_id)) {
2725 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2726 		if (err)
2727 			return err;
2728 	}
2729 
2730 	desc = &tab->descs[tab->nr_descs++];
2731 	desc->func_id = func_id;
2732 	desc->imm = call_imm;
2733 	desc->offset = offset;
2734 	desc->addr = addr;
2735 	err = btf_distill_func_proto(&env->log, desc_btf,
2736 				     func_proto, func_name,
2737 				     &desc->func_model);
2738 	if (!err)
2739 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2740 		     kfunc_desc_cmp_by_id_off, NULL);
2741 	return err;
2742 }
2743 
2744 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2745 {
2746 	const struct bpf_kfunc_desc *d0 = a;
2747 	const struct bpf_kfunc_desc *d1 = b;
2748 
2749 	if (d0->imm != d1->imm)
2750 		return d0->imm < d1->imm ? -1 : 1;
2751 	if (d0->offset != d1->offset)
2752 		return d0->offset < d1->offset ? -1 : 1;
2753 	return 0;
2754 }
2755 
2756 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2757 {
2758 	struct bpf_kfunc_desc_tab *tab;
2759 
2760 	tab = prog->aux->kfunc_tab;
2761 	if (!tab)
2762 		return;
2763 
2764 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2765 	     kfunc_desc_cmp_by_imm_off, NULL);
2766 }
2767 
2768 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2769 {
2770 	return !!prog->aux->kfunc_tab;
2771 }
2772 
2773 const struct btf_func_model *
2774 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2775 			 const struct bpf_insn *insn)
2776 {
2777 	const struct bpf_kfunc_desc desc = {
2778 		.imm = insn->imm,
2779 		.offset = insn->off,
2780 	};
2781 	const struct bpf_kfunc_desc *res;
2782 	struct bpf_kfunc_desc_tab *tab;
2783 
2784 	tab = prog->aux->kfunc_tab;
2785 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2786 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2787 
2788 	return res ? &res->func_model : NULL;
2789 }
2790 
2791 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2792 {
2793 	struct bpf_subprog_info *subprog = env->subprog_info;
2794 	struct bpf_insn *insn = env->prog->insnsi;
2795 	int i, ret, insn_cnt = env->prog->len;
2796 
2797 	/* Add entry function. */
2798 	ret = add_subprog(env, 0);
2799 	if (ret)
2800 		return ret;
2801 
2802 	for (i = 0; i < insn_cnt; i++, insn++) {
2803 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2804 		    !bpf_pseudo_kfunc_call(insn))
2805 			continue;
2806 
2807 		if (!env->bpf_capable) {
2808 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2809 			return -EPERM;
2810 		}
2811 
2812 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2813 			ret = add_subprog(env, i + insn->imm + 1);
2814 		else
2815 			ret = add_kfunc_call(env, insn->imm, insn->off);
2816 
2817 		if (ret < 0)
2818 			return ret;
2819 	}
2820 
2821 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2822 	 * logic. 'subprog_cnt' should not be increased.
2823 	 */
2824 	subprog[env->subprog_cnt].start = insn_cnt;
2825 
2826 	if (env->log.level & BPF_LOG_LEVEL2)
2827 		for (i = 0; i < env->subprog_cnt; i++)
2828 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2829 
2830 	return 0;
2831 }
2832 
2833 static int check_subprogs(struct bpf_verifier_env *env)
2834 {
2835 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2836 	struct bpf_subprog_info *subprog = env->subprog_info;
2837 	struct bpf_insn *insn = env->prog->insnsi;
2838 	int insn_cnt = env->prog->len;
2839 
2840 	/* now check that all jumps are within the same subprog */
2841 	subprog_start = subprog[cur_subprog].start;
2842 	subprog_end = subprog[cur_subprog + 1].start;
2843 	for (i = 0; i < insn_cnt; i++) {
2844 		u8 code = insn[i].code;
2845 
2846 		if (code == (BPF_JMP | BPF_CALL) &&
2847 		    insn[i].src_reg == 0 &&
2848 		    insn[i].imm == BPF_FUNC_tail_call)
2849 			subprog[cur_subprog].has_tail_call = true;
2850 		if (BPF_CLASS(code) == BPF_LD &&
2851 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2852 			subprog[cur_subprog].has_ld_abs = true;
2853 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2854 			goto next;
2855 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2856 			goto next;
2857 		off = i + insn[i].off + 1;
2858 		if (off < subprog_start || off >= subprog_end) {
2859 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2860 			return -EINVAL;
2861 		}
2862 next:
2863 		if (i == subprog_end - 1) {
2864 			/* to avoid fall-through from one subprog into another
2865 			 * the last insn of the subprog should be either exit
2866 			 * or unconditional jump back
2867 			 */
2868 			if (code != (BPF_JMP | BPF_EXIT) &&
2869 			    code != (BPF_JMP | BPF_JA)) {
2870 				verbose(env, "last insn is not an exit or jmp\n");
2871 				return -EINVAL;
2872 			}
2873 			subprog_start = subprog_end;
2874 			cur_subprog++;
2875 			if (cur_subprog < env->subprog_cnt)
2876 				subprog_end = subprog[cur_subprog + 1].start;
2877 		}
2878 	}
2879 	return 0;
2880 }
2881 
2882 /* Parentage chain of this register (or stack slot) should take care of all
2883  * issues like callee-saved registers, stack slot allocation time, etc.
2884  */
2885 static int mark_reg_read(struct bpf_verifier_env *env,
2886 			 const struct bpf_reg_state *state,
2887 			 struct bpf_reg_state *parent, u8 flag)
2888 {
2889 	bool writes = parent == state->parent; /* Observe write marks */
2890 	int cnt = 0;
2891 
2892 	while (parent) {
2893 		/* if read wasn't screened by an earlier write ... */
2894 		if (writes && state->live & REG_LIVE_WRITTEN)
2895 			break;
2896 		if (parent->live & REG_LIVE_DONE) {
2897 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2898 				reg_type_str(env, parent->type),
2899 				parent->var_off.value, parent->off);
2900 			return -EFAULT;
2901 		}
2902 		/* The first condition is more likely to be true than the
2903 		 * second, checked it first.
2904 		 */
2905 		if ((parent->live & REG_LIVE_READ) == flag ||
2906 		    parent->live & REG_LIVE_READ64)
2907 			/* The parentage chain never changes and
2908 			 * this parent was already marked as LIVE_READ.
2909 			 * There is no need to keep walking the chain again and
2910 			 * keep re-marking all parents as LIVE_READ.
2911 			 * This case happens when the same register is read
2912 			 * multiple times without writes into it in-between.
2913 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2914 			 * then no need to set the weak REG_LIVE_READ32.
2915 			 */
2916 			break;
2917 		/* ... then we depend on parent's value */
2918 		parent->live |= flag;
2919 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2920 		if (flag == REG_LIVE_READ64)
2921 			parent->live &= ~REG_LIVE_READ32;
2922 		state = parent;
2923 		parent = state->parent;
2924 		writes = true;
2925 		cnt++;
2926 	}
2927 
2928 	if (env->longest_mark_read_walk < cnt)
2929 		env->longest_mark_read_walk = cnt;
2930 	return 0;
2931 }
2932 
2933 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2934 {
2935 	struct bpf_func_state *state = func(env, reg);
2936 	int spi, ret;
2937 
2938 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2939 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2940 	 * check_kfunc_call.
2941 	 */
2942 	if (reg->type == CONST_PTR_TO_DYNPTR)
2943 		return 0;
2944 	spi = dynptr_get_spi(env, reg);
2945 	if (spi < 0)
2946 		return spi;
2947 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2948 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2949 	 * read.
2950 	 */
2951 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2952 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2953 	if (ret)
2954 		return ret;
2955 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2956 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2957 }
2958 
2959 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2960 			  int spi, int nr_slots)
2961 {
2962 	struct bpf_func_state *state = func(env, reg);
2963 	int err, i;
2964 
2965 	for (i = 0; i < nr_slots; i++) {
2966 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2967 
2968 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2969 		if (err)
2970 			return err;
2971 
2972 		mark_stack_slot_scratched(env, spi - i);
2973 	}
2974 
2975 	return 0;
2976 }
2977 
2978 /* This function is supposed to be used by the following 32-bit optimization
2979  * code only. It returns TRUE if the source or destination register operates
2980  * on 64-bit, otherwise return FALSE.
2981  */
2982 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2983 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2984 {
2985 	u8 code, class, op;
2986 
2987 	code = insn->code;
2988 	class = BPF_CLASS(code);
2989 	op = BPF_OP(code);
2990 	if (class == BPF_JMP) {
2991 		/* BPF_EXIT for "main" will reach here. Return TRUE
2992 		 * conservatively.
2993 		 */
2994 		if (op == BPF_EXIT)
2995 			return true;
2996 		if (op == BPF_CALL) {
2997 			/* BPF to BPF call will reach here because of marking
2998 			 * caller saved clobber with DST_OP_NO_MARK for which we
2999 			 * don't care the register def because they are anyway
3000 			 * marked as NOT_INIT already.
3001 			 */
3002 			if (insn->src_reg == BPF_PSEUDO_CALL)
3003 				return false;
3004 			/* Helper call will reach here because of arg type
3005 			 * check, conservatively return TRUE.
3006 			 */
3007 			if (t == SRC_OP)
3008 				return true;
3009 
3010 			return false;
3011 		}
3012 	}
3013 
3014 	if (class == BPF_ALU64 || class == BPF_JMP ||
3015 	    /* BPF_END always use BPF_ALU class. */
3016 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3017 		return true;
3018 
3019 	if (class == BPF_ALU || class == BPF_JMP32)
3020 		return false;
3021 
3022 	if (class == BPF_LDX) {
3023 		if (t != SRC_OP)
3024 			return BPF_SIZE(code) == BPF_DW;
3025 		/* LDX source must be ptr. */
3026 		return true;
3027 	}
3028 
3029 	if (class == BPF_STX) {
3030 		/* BPF_STX (including atomic variants) has multiple source
3031 		 * operands, one of which is a ptr. Check whether the caller is
3032 		 * asking about it.
3033 		 */
3034 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3035 			return true;
3036 		return BPF_SIZE(code) == BPF_DW;
3037 	}
3038 
3039 	if (class == BPF_LD) {
3040 		u8 mode = BPF_MODE(code);
3041 
3042 		/* LD_IMM64 */
3043 		if (mode == BPF_IMM)
3044 			return true;
3045 
3046 		/* Both LD_IND and LD_ABS return 32-bit data. */
3047 		if (t != SRC_OP)
3048 			return  false;
3049 
3050 		/* Implicit ctx ptr. */
3051 		if (regno == BPF_REG_6)
3052 			return true;
3053 
3054 		/* Explicit source could be any width. */
3055 		return true;
3056 	}
3057 
3058 	if (class == BPF_ST)
3059 		/* The only source register for BPF_ST is a ptr. */
3060 		return true;
3061 
3062 	/* Conservatively return true at default. */
3063 	return true;
3064 }
3065 
3066 /* Return the regno defined by the insn, or -1. */
3067 static int insn_def_regno(const struct bpf_insn *insn)
3068 {
3069 	switch (BPF_CLASS(insn->code)) {
3070 	case BPF_JMP:
3071 	case BPF_JMP32:
3072 	case BPF_ST:
3073 		return -1;
3074 	case BPF_STX:
3075 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3076 		    (insn->imm & BPF_FETCH)) {
3077 			if (insn->imm == BPF_CMPXCHG)
3078 				return BPF_REG_0;
3079 			else
3080 				return insn->src_reg;
3081 		} else {
3082 			return -1;
3083 		}
3084 	default:
3085 		return insn->dst_reg;
3086 	}
3087 }
3088 
3089 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3090 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3091 {
3092 	int dst_reg = insn_def_regno(insn);
3093 
3094 	if (dst_reg == -1)
3095 		return false;
3096 
3097 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3098 }
3099 
3100 static void mark_insn_zext(struct bpf_verifier_env *env,
3101 			   struct bpf_reg_state *reg)
3102 {
3103 	s32 def_idx = reg->subreg_def;
3104 
3105 	if (def_idx == DEF_NOT_SUBREG)
3106 		return;
3107 
3108 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3109 	/* The dst will be zero extended, so won't be sub-register anymore. */
3110 	reg->subreg_def = DEF_NOT_SUBREG;
3111 }
3112 
3113 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3114 			 enum reg_arg_type t)
3115 {
3116 	struct bpf_verifier_state *vstate = env->cur_state;
3117 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3118 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3119 	struct bpf_reg_state *reg, *regs = state->regs;
3120 	bool rw64;
3121 
3122 	if (regno >= MAX_BPF_REG) {
3123 		verbose(env, "R%d is invalid\n", regno);
3124 		return -EINVAL;
3125 	}
3126 
3127 	mark_reg_scratched(env, regno);
3128 
3129 	reg = &regs[regno];
3130 	rw64 = is_reg64(env, insn, regno, reg, t);
3131 	if (t == SRC_OP) {
3132 		/* check whether register used as source operand can be read */
3133 		if (reg->type == NOT_INIT) {
3134 			verbose(env, "R%d !read_ok\n", regno);
3135 			return -EACCES;
3136 		}
3137 		/* We don't need to worry about FP liveness because it's read-only */
3138 		if (regno == BPF_REG_FP)
3139 			return 0;
3140 
3141 		if (rw64)
3142 			mark_insn_zext(env, reg);
3143 
3144 		return mark_reg_read(env, reg, reg->parent,
3145 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3146 	} else {
3147 		/* check whether register used as dest operand can be written to */
3148 		if (regno == BPF_REG_FP) {
3149 			verbose(env, "frame pointer is read only\n");
3150 			return -EACCES;
3151 		}
3152 		reg->live |= REG_LIVE_WRITTEN;
3153 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3154 		if (t == DST_OP)
3155 			mark_reg_unknown(env, regs, regno);
3156 	}
3157 	return 0;
3158 }
3159 
3160 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3161 {
3162 	env->insn_aux_data[idx].jmp_point = true;
3163 }
3164 
3165 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3166 {
3167 	return env->insn_aux_data[insn_idx].jmp_point;
3168 }
3169 
3170 /* for any branch, call, exit record the history of jmps in the given state */
3171 static int push_jmp_history(struct bpf_verifier_env *env,
3172 			    struct bpf_verifier_state *cur)
3173 {
3174 	u32 cnt = cur->jmp_history_cnt;
3175 	struct bpf_idx_pair *p;
3176 	size_t alloc_size;
3177 
3178 	if (!is_jmp_point(env, env->insn_idx))
3179 		return 0;
3180 
3181 	cnt++;
3182 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3183 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3184 	if (!p)
3185 		return -ENOMEM;
3186 	p[cnt - 1].idx = env->insn_idx;
3187 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3188 	cur->jmp_history = p;
3189 	cur->jmp_history_cnt = cnt;
3190 	return 0;
3191 }
3192 
3193 /* Backtrack one insn at a time. If idx is not at the top of recorded
3194  * history then previous instruction came from straight line execution.
3195  */
3196 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3197 			     u32 *history)
3198 {
3199 	u32 cnt = *history;
3200 
3201 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3202 		i = st->jmp_history[cnt - 1].prev_idx;
3203 		(*history)--;
3204 	} else {
3205 		i--;
3206 	}
3207 	return i;
3208 }
3209 
3210 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3211 {
3212 	const struct btf_type *func;
3213 	struct btf *desc_btf;
3214 
3215 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3216 		return NULL;
3217 
3218 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3219 	if (IS_ERR(desc_btf))
3220 		return "<error>";
3221 
3222 	func = btf_type_by_id(desc_btf, insn->imm);
3223 	return btf_name_by_offset(desc_btf, func->name_off);
3224 }
3225 
3226 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3227 {
3228 	bt->frame = frame;
3229 }
3230 
3231 static inline void bt_reset(struct backtrack_state *bt)
3232 {
3233 	struct bpf_verifier_env *env = bt->env;
3234 
3235 	memset(bt, 0, sizeof(*bt));
3236 	bt->env = env;
3237 }
3238 
3239 static inline u32 bt_empty(struct backtrack_state *bt)
3240 {
3241 	u64 mask = 0;
3242 	int i;
3243 
3244 	for (i = 0; i <= bt->frame; i++)
3245 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3246 
3247 	return mask == 0;
3248 }
3249 
3250 static inline int bt_subprog_enter(struct backtrack_state *bt)
3251 {
3252 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3253 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3254 		WARN_ONCE(1, "verifier backtracking bug");
3255 		return -EFAULT;
3256 	}
3257 	bt->frame++;
3258 	return 0;
3259 }
3260 
3261 static inline int bt_subprog_exit(struct backtrack_state *bt)
3262 {
3263 	if (bt->frame == 0) {
3264 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3265 		WARN_ONCE(1, "verifier backtracking bug");
3266 		return -EFAULT;
3267 	}
3268 	bt->frame--;
3269 	return 0;
3270 }
3271 
3272 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3273 {
3274 	bt->reg_masks[frame] |= 1 << reg;
3275 }
3276 
3277 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3278 {
3279 	bt->reg_masks[frame] &= ~(1 << reg);
3280 }
3281 
3282 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3283 {
3284 	bt_set_frame_reg(bt, bt->frame, reg);
3285 }
3286 
3287 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3288 {
3289 	bt_clear_frame_reg(bt, bt->frame, reg);
3290 }
3291 
3292 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3293 {
3294 	bt->stack_masks[frame] |= 1ull << slot;
3295 }
3296 
3297 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3298 {
3299 	bt->stack_masks[frame] &= ~(1ull << slot);
3300 }
3301 
3302 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3303 {
3304 	bt_set_frame_slot(bt, bt->frame, slot);
3305 }
3306 
3307 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3308 {
3309 	bt_clear_frame_slot(bt, bt->frame, slot);
3310 }
3311 
3312 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3313 {
3314 	return bt->reg_masks[frame];
3315 }
3316 
3317 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3318 {
3319 	return bt->reg_masks[bt->frame];
3320 }
3321 
3322 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3323 {
3324 	return bt->stack_masks[frame];
3325 }
3326 
3327 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3328 {
3329 	return bt->stack_masks[bt->frame];
3330 }
3331 
3332 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3333 {
3334 	return bt->reg_masks[bt->frame] & (1 << reg);
3335 }
3336 
3337 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3338 {
3339 	return bt->stack_masks[bt->frame] & (1ull << slot);
3340 }
3341 
3342 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3343 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3344 {
3345 	DECLARE_BITMAP(mask, 64);
3346 	bool first = true;
3347 	int i, n;
3348 
3349 	buf[0] = '\0';
3350 
3351 	bitmap_from_u64(mask, reg_mask);
3352 	for_each_set_bit(i, mask, 32) {
3353 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3354 		first = false;
3355 		buf += n;
3356 		buf_sz -= n;
3357 		if (buf_sz < 0)
3358 			break;
3359 	}
3360 }
3361 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3362 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3363 {
3364 	DECLARE_BITMAP(mask, 64);
3365 	bool first = true;
3366 	int i, n;
3367 
3368 	buf[0] = '\0';
3369 
3370 	bitmap_from_u64(mask, stack_mask);
3371 	for_each_set_bit(i, mask, 64) {
3372 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3373 		first = false;
3374 		buf += n;
3375 		buf_sz -= n;
3376 		if (buf_sz < 0)
3377 			break;
3378 	}
3379 }
3380 
3381 /* For given verifier state backtrack_insn() is called from the last insn to
3382  * the first insn. Its purpose is to compute a bitmask of registers and
3383  * stack slots that needs precision in the parent verifier state.
3384  *
3385  * @idx is an index of the instruction we are currently processing;
3386  * @subseq_idx is an index of the subsequent instruction that:
3387  *   - *would be* executed next, if jump history is viewed in forward order;
3388  *   - *was* processed previously during backtracking.
3389  */
3390 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3391 			  struct backtrack_state *bt)
3392 {
3393 	const struct bpf_insn_cbs cbs = {
3394 		.cb_call	= disasm_kfunc_name,
3395 		.cb_print	= verbose,
3396 		.private_data	= env,
3397 	};
3398 	struct bpf_insn *insn = env->prog->insnsi + idx;
3399 	u8 class = BPF_CLASS(insn->code);
3400 	u8 opcode = BPF_OP(insn->code);
3401 	u8 mode = BPF_MODE(insn->code);
3402 	u32 dreg = insn->dst_reg;
3403 	u32 sreg = insn->src_reg;
3404 	u32 spi, i;
3405 
3406 	if (insn->code == 0)
3407 		return 0;
3408 	if (env->log.level & BPF_LOG_LEVEL2) {
3409 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3410 		verbose(env, "mark_precise: frame%d: regs=%s ",
3411 			bt->frame, env->tmp_str_buf);
3412 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3413 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3414 		verbose(env, "%d: ", idx);
3415 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3416 	}
3417 
3418 	if (class == BPF_ALU || class == BPF_ALU64) {
3419 		if (!bt_is_reg_set(bt, dreg))
3420 			return 0;
3421 		if (opcode == BPF_MOV) {
3422 			if (BPF_SRC(insn->code) == BPF_X) {
3423 				/* dreg = sreg
3424 				 * dreg needs precision after this insn
3425 				 * sreg needs precision before this insn
3426 				 */
3427 				bt_clear_reg(bt, dreg);
3428 				bt_set_reg(bt, sreg);
3429 			} else {
3430 				/* dreg = K
3431 				 * dreg needs precision after this insn.
3432 				 * Corresponding register is already marked
3433 				 * as precise=true in this verifier state.
3434 				 * No further markings in parent are necessary
3435 				 */
3436 				bt_clear_reg(bt, dreg);
3437 			}
3438 		} else {
3439 			if (BPF_SRC(insn->code) == BPF_X) {
3440 				/* dreg += sreg
3441 				 * both dreg and sreg need precision
3442 				 * before this insn
3443 				 */
3444 				bt_set_reg(bt, sreg);
3445 			} /* else dreg += K
3446 			   * dreg still needs precision before this insn
3447 			   */
3448 		}
3449 	} else if (class == BPF_LDX) {
3450 		if (!bt_is_reg_set(bt, dreg))
3451 			return 0;
3452 		bt_clear_reg(bt, dreg);
3453 
3454 		/* scalars can only be spilled into stack w/o losing precision.
3455 		 * Load from any other memory can be zero extended.
3456 		 * The desire to keep that precision is already indicated
3457 		 * by 'precise' mark in corresponding register of this state.
3458 		 * No further tracking necessary.
3459 		 */
3460 		if (insn->src_reg != BPF_REG_FP)
3461 			return 0;
3462 
3463 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3464 		 * that [fp - off] slot contains scalar that needs to be
3465 		 * tracked with precision
3466 		 */
3467 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3468 		if (spi >= 64) {
3469 			verbose(env, "BUG spi %d\n", spi);
3470 			WARN_ONCE(1, "verifier backtracking bug");
3471 			return -EFAULT;
3472 		}
3473 		bt_set_slot(bt, spi);
3474 	} else if (class == BPF_STX || class == BPF_ST) {
3475 		if (bt_is_reg_set(bt, dreg))
3476 			/* stx & st shouldn't be using _scalar_ dst_reg
3477 			 * to access memory. It means backtracking
3478 			 * encountered a case of pointer subtraction.
3479 			 */
3480 			return -ENOTSUPP;
3481 		/* scalars can only be spilled into stack */
3482 		if (insn->dst_reg != BPF_REG_FP)
3483 			return 0;
3484 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3485 		if (spi >= 64) {
3486 			verbose(env, "BUG spi %d\n", spi);
3487 			WARN_ONCE(1, "verifier backtracking bug");
3488 			return -EFAULT;
3489 		}
3490 		if (!bt_is_slot_set(bt, spi))
3491 			return 0;
3492 		bt_clear_slot(bt, spi);
3493 		if (class == BPF_STX)
3494 			bt_set_reg(bt, sreg);
3495 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3496 		if (bpf_pseudo_call(insn)) {
3497 			int subprog_insn_idx, subprog;
3498 
3499 			subprog_insn_idx = idx + insn->imm + 1;
3500 			subprog = find_subprog(env, subprog_insn_idx);
3501 			if (subprog < 0)
3502 				return -EFAULT;
3503 
3504 			if (subprog_is_global(env, subprog)) {
3505 				/* check that jump history doesn't have any
3506 				 * extra instructions from subprog; the next
3507 				 * instruction after call to global subprog
3508 				 * should be literally next instruction in
3509 				 * caller program
3510 				 */
3511 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3512 				/* r1-r5 are invalidated after subprog call,
3513 				 * so for global func call it shouldn't be set
3514 				 * anymore
3515 				 */
3516 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3517 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3518 					WARN_ONCE(1, "verifier backtracking bug");
3519 					return -EFAULT;
3520 				}
3521 				/* global subprog always sets R0 */
3522 				bt_clear_reg(bt, BPF_REG_0);
3523 				return 0;
3524 			} else {
3525 				/* static subprog call instruction, which
3526 				 * means that we are exiting current subprog,
3527 				 * so only r1-r5 could be still requested as
3528 				 * precise, r0 and r6-r10 or any stack slot in
3529 				 * the current frame should be zero by now
3530 				 */
3531 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3532 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3533 					WARN_ONCE(1, "verifier backtracking bug");
3534 					return -EFAULT;
3535 				}
3536 				/* we don't track register spills perfectly,
3537 				 * so fallback to force-precise instead of failing */
3538 				if (bt_stack_mask(bt) != 0)
3539 					return -ENOTSUPP;
3540 				/* propagate r1-r5 to the caller */
3541 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3542 					if (bt_is_reg_set(bt, i)) {
3543 						bt_clear_reg(bt, i);
3544 						bt_set_frame_reg(bt, bt->frame - 1, i);
3545 					}
3546 				}
3547 				if (bt_subprog_exit(bt))
3548 					return -EFAULT;
3549 				return 0;
3550 			}
3551 		} else if ((bpf_helper_call(insn) &&
3552 			    is_callback_calling_function(insn->imm) &&
3553 			    !is_async_callback_calling_function(insn->imm)) ||
3554 			   (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3555 			/* callback-calling helper or kfunc call, which means
3556 			 * we are exiting from subprog, but unlike the subprog
3557 			 * call handling above, we shouldn't propagate
3558 			 * precision of r1-r5 (if any requested), as they are
3559 			 * not actually arguments passed directly to callback
3560 			 * subprogs
3561 			 */
3562 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3563 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3564 				WARN_ONCE(1, "verifier backtracking bug");
3565 				return -EFAULT;
3566 			}
3567 			if (bt_stack_mask(bt) != 0)
3568 				return -ENOTSUPP;
3569 			/* clear r1-r5 in callback subprog's mask */
3570 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3571 				bt_clear_reg(bt, i);
3572 			if (bt_subprog_exit(bt))
3573 				return -EFAULT;
3574 			return 0;
3575 		} else if (opcode == BPF_CALL) {
3576 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3577 			 * catch this error later. Make backtracking conservative
3578 			 * with ENOTSUPP.
3579 			 */
3580 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3581 				return -ENOTSUPP;
3582 			/* regular helper call sets R0 */
3583 			bt_clear_reg(bt, BPF_REG_0);
3584 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3585 				/* if backtracing was looking for registers R1-R5
3586 				 * they should have been found already.
3587 				 */
3588 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3589 				WARN_ONCE(1, "verifier backtracking bug");
3590 				return -EFAULT;
3591 			}
3592 		} else if (opcode == BPF_EXIT) {
3593 			bool r0_precise;
3594 
3595 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3596 				/* if backtracing was looking for registers R1-R5
3597 				 * they should have been found already.
3598 				 */
3599 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3600 				WARN_ONCE(1, "verifier backtracking bug");
3601 				return -EFAULT;
3602 			}
3603 
3604 			/* BPF_EXIT in subprog or callback always returns
3605 			 * right after the call instruction, so by checking
3606 			 * whether the instruction at subseq_idx-1 is subprog
3607 			 * call or not we can distinguish actual exit from
3608 			 * *subprog* from exit from *callback*. In the former
3609 			 * case, we need to propagate r0 precision, if
3610 			 * necessary. In the former we never do that.
3611 			 */
3612 			r0_precise = subseq_idx - 1 >= 0 &&
3613 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3614 				     bt_is_reg_set(bt, BPF_REG_0);
3615 
3616 			bt_clear_reg(bt, BPF_REG_0);
3617 			if (bt_subprog_enter(bt))
3618 				return -EFAULT;
3619 
3620 			if (r0_precise)
3621 				bt_set_reg(bt, BPF_REG_0);
3622 			/* r6-r9 and stack slots will stay set in caller frame
3623 			 * bitmasks until we return back from callee(s)
3624 			 */
3625 			return 0;
3626 		} else if (BPF_SRC(insn->code) == BPF_X) {
3627 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3628 				return 0;
3629 			/* dreg <cond> sreg
3630 			 * Both dreg and sreg need precision before
3631 			 * this insn. If only sreg was marked precise
3632 			 * before it would be equally necessary to
3633 			 * propagate it to dreg.
3634 			 */
3635 			bt_set_reg(bt, dreg);
3636 			bt_set_reg(bt, sreg);
3637 			 /* else dreg <cond> K
3638 			  * Only dreg still needs precision before
3639 			  * this insn, so for the K-based conditional
3640 			  * there is nothing new to be marked.
3641 			  */
3642 		}
3643 	} else if (class == BPF_LD) {
3644 		if (!bt_is_reg_set(bt, dreg))
3645 			return 0;
3646 		bt_clear_reg(bt, dreg);
3647 		/* It's ld_imm64 or ld_abs or ld_ind.
3648 		 * For ld_imm64 no further tracking of precision
3649 		 * into parent is necessary
3650 		 */
3651 		if (mode == BPF_IND || mode == BPF_ABS)
3652 			/* to be analyzed */
3653 			return -ENOTSUPP;
3654 	}
3655 	return 0;
3656 }
3657 
3658 /* the scalar precision tracking algorithm:
3659  * . at the start all registers have precise=false.
3660  * . scalar ranges are tracked as normal through alu and jmp insns.
3661  * . once precise value of the scalar register is used in:
3662  *   .  ptr + scalar alu
3663  *   . if (scalar cond K|scalar)
3664  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3665  *   backtrack through the verifier states and mark all registers and
3666  *   stack slots with spilled constants that these scalar regisers
3667  *   should be precise.
3668  * . during state pruning two registers (or spilled stack slots)
3669  *   are equivalent if both are not precise.
3670  *
3671  * Note the verifier cannot simply walk register parentage chain,
3672  * since many different registers and stack slots could have been
3673  * used to compute single precise scalar.
3674  *
3675  * The approach of starting with precise=true for all registers and then
3676  * backtrack to mark a register as not precise when the verifier detects
3677  * that program doesn't care about specific value (e.g., when helper
3678  * takes register as ARG_ANYTHING parameter) is not safe.
3679  *
3680  * It's ok to walk single parentage chain of the verifier states.
3681  * It's possible that this backtracking will go all the way till 1st insn.
3682  * All other branches will be explored for needing precision later.
3683  *
3684  * The backtracking needs to deal with cases like:
3685  *   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)
3686  * r9 -= r8
3687  * r5 = r9
3688  * if r5 > 0x79f goto pc+7
3689  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3690  * r5 += 1
3691  * ...
3692  * call bpf_perf_event_output#25
3693  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3694  *
3695  * and this case:
3696  * r6 = 1
3697  * call foo // uses callee's r6 inside to compute r0
3698  * r0 += r6
3699  * if r0 == 0 goto
3700  *
3701  * to track above reg_mask/stack_mask needs to be independent for each frame.
3702  *
3703  * Also if parent's curframe > frame where backtracking started,
3704  * the verifier need to mark registers in both frames, otherwise callees
3705  * may incorrectly prune callers. This is similar to
3706  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3707  *
3708  * For now backtracking falls back into conservative marking.
3709  */
3710 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3711 				     struct bpf_verifier_state *st)
3712 {
3713 	struct bpf_func_state *func;
3714 	struct bpf_reg_state *reg;
3715 	int i, j;
3716 
3717 	if (env->log.level & BPF_LOG_LEVEL2) {
3718 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3719 			st->curframe);
3720 	}
3721 
3722 	/* big hammer: mark all scalars precise in this path.
3723 	 * pop_stack may still get !precise scalars.
3724 	 * We also skip current state and go straight to first parent state,
3725 	 * because precision markings in current non-checkpointed state are
3726 	 * not needed. See why in the comment in __mark_chain_precision below.
3727 	 */
3728 	for (st = st->parent; st; st = st->parent) {
3729 		for (i = 0; i <= st->curframe; i++) {
3730 			func = st->frame[i];
3731 			for (j = 0; j < BPF_REG_FP; j++) {
3732 				reg = &func->regs[j];
3733 				if (reg->type != SCALAR_VALUE || reg->precise)
3734 					continue;
3735 				reg->precise = true;
3736 				if (env->log.level & BPF_LOG_LEVEL2) {
3737 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3738 						i, j);
3739 				}
3740 			}
3741 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3742 				if (!is_spilled_reg(&func->stack[j]))
3743 					continue;
3744 				reg = &func->stack[j].spilled_ptr;
3745 				if (reg->type != SCALAR_VALUE || reg->precise)
3746 					continue;
3747 				reg->precise = true;
3748 				if (env->log.level & BPF_LOG_LEVEL2) {
3749 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3750 						i, -(j + 1) * 8);
3751 				}
3752 			}
3753 		}
3754 	}
3755 }
3756 
3757 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3758 {
3759 	struct bpf_func_state *func;
3760 	struct bpf_reg_state *reg;
3761 	int i, j;
3762 
3763 	for (i = 0; i <= st->curframe; i++) {
3764 		func = st->frame[i];
3765 		for (j = 0; j < BPF_REG_FP; j++) {
3766 			reg = &func->regs[j];
3767 			if (reg->type != SCALAR_VALUE)
3768 				continue;
3769 			reg->precise = false;
3770 		}
3771 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3772 			if (!is_spilled_reg(&func->stack[j]))
3773 				continue;
3774 			reg = &func->stack[j].spilled_ptr;
3775 			if (reg->type != SCALAR_VALUE)
3776 				continue;
3777 			reg->precise = false;
3778 		}
3779 	}
3780 }
3781 
3782 static bool idset_contains(struct bpf_idset *s, u32 id)
3783 {
3784 	u32 i;
3785 
3786 	for (i = 0; i < s->count; ++i)
3787 		if (s->ids[i] == id)
3788 			return true;
3789 
3790 	return false;
3791 }
3792 
3793 static int idset_push(struct bpf_idset *s, u32 id)
3794 {
3795 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3796 		return -EFAULT;
3797 	s->ids[s->count++] = id;
3798 	return 0;
3799 }
3800 
3801 static void idset_reset(struct bpf_idset *s)
3802 {
3803 	s->count = 0;
3804 }
3805 
3806 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3807  * Mark all registers with these IDs as precise.
3808  */
3809 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3810 {
3811 	struct bpf_idset *precise_ids = &env->idset_scratch;
3812 	struct backtrack_state *bt = &env->bt;
3813 	struct bpf_func_state *func;
3814 	struct bpf_reg_state *reg;
3815 	DECLARE_BITMAP(mask, 64);
3816 	int i, fr;
3817 
3818 	idset_reset(precise_ids);
3819 
3820 	for (fr = bt->frame; fr >= 0; fr--) {
3821 		func = st->frame[fr];
3822 
3823 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3824 		for_each_set_bit(i, mask, 32) {
3825 			reg = &func->regs[i];
3826 			if (!reg->id || reg->type != SCALAR_VALUE)
3827 				continue;
3828 			if (idset_push(precise_ids, reg->id))
3829 				return -EFAULT;
3830 		}
3831 
3832 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3833 		for_each_set_bit(i, mask, 64) {
3834 			if (i >= func->allocated_stack / BPF_REG_SIZE)
3835 				break;
3836 			if (!is_spilled_scalar_reg(&func->stack[i]))
3837 				continue;
3838 			reg = &func->stack[i].spilled_ptr;
3839 			if (!reg->id)
3840 				continue;
3841 			if (idset_push(precise_ids, reg->id))
3842 				return -EFAULT;
3843 		}
3844 	}
3845 
3846 	for (fr = 0; fr <= st->curframe; ++fr) {
3847 		func = st->frame[fr];
3848 
3849 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3850 			reg = &func->regs[i];
3851 			if (!reg->id)
3852 				continue;
3853 			if (!idset_contains(precise_ids, reg->id))
3854 				continue;
3855 			bt_set_frame_reg(bt, fr, i);
3856 		}
3857 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3858 			if (!is_spilled_scalar_reg(&func->stack[i]))
3859 				continue;
3860 			reg = &func->stack[i].spilled_ptr;
3861 			if (!reg->id)
3862 				continue;
3863 			if (!idset_contains(precise_ids, reg->id))
3864 				continue;
3865 			bt_set_frame_slot(bt, fr, i);
3866 		}
3867 	}
3868 
3869 	return 0;
3870 }
3871 
3872 /*
3873  * __mark_chain_precision() backtracks BPF program instruction sequence and
3874  * chain of verifier states making sure that register *regno* (if regno >= 0)
3875  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3876  * SCALARS, as well as any other registers and slots that contribute to
3877  * a tracked state of given registers/stack slots, depending on specific BPF
3878  * assembly instructions (see backtrack_insns() for exact instruction handling
3879  * logic). This backtracking relies on recorded jmp_history and is able to
3880  * traverse entire chain of parent states. This process ends only when all the
3881  * necessary registers/slots and their transitive dependencies are marked as
3882  * precise.
3883  *
3884  * One important and subtle aspect is that precise marks *do not matter* in
3885  * the currently verified state (current state). It is important to understand
3886  * why this is the case.
3887  *
3888  * First, note that current state is the state that is not yet "checkpointed",
3889  * i.e., it is not yet put into env->explored_states, and it has no children
3890  * states as well. It's ephemeral, and can end up either a) being discarded if
3891  * compatible explored state is found at some point or BPF_EXIT instruction is
3892  * reached or b) checkpointed and put into env->explored_states, branching out
3893  * into one or more children states.
3894  *
3895  * In the former case, precise markings in current state are completely
3896  * ignored by state comparison code (see regsafe() for details). Only
3897  * checkpointed ("old") state precise markings are important, and if old
3898  * state's register/slot is precise, regsafe() assumes current state's
3899  * register/slot as precise and checks value ranges exactly and precisely. If
3900  * states turn out to be compatible, current state's necessary precise
3901  * markings and any required parent states' precise markings are enforced
3902  * after the fact with propagate_precision() logic, after the fact. But it's
3903  * important to realize that in this case, even after marking current state
3904  * registers/slots as precise, we immediately discard current state. So what
3905  * actually matters is any of the precise markings propagated into current
3906  * state's parent states, which are always checkpointed (due to b) case above).
3907  * As such, for scenario a) it doesn't matter if current state has precise
3908  * markings set or not.
3909  *
3910  * Now, for the scenario b), checkpointing and forking into child(ren)
3911  * state(s). Note that before current state gets to checkpointing step, any
3912  * processed instruction always assumes precise SCALAR register/slot
3913  * knowledge: if precise value or range is useful to prune jump branch, BPF
3914  * verifier takes this opportunity enthusiastically. Similarly, when
3915  * register's value is used to calculate offset or memory address, exact
3916  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3917  * what we mentioned above about state comparison ignoring precise markings
3918  * during state comparison, BPF verifier ignores and also assumes precise
3919  * markings *at will* during instruction verification process. But as verifier
3920  * assumes precision, it also propagates any precision dependencies across
3921  * parent states, which are not yet finalized, so can be further restricted
3922  * based on new knowledge gained from restrictions enforced by their children
3923  * states. This is so that once those parent states are finalized, i.e., when
3924  * they have no more active children state, state comparison logic in
3925  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3926  * required for correctness.
3927  *
3928  * To build a bit more intuition, note also that once a state is checkpointed,
3929  * the path we took to get to that state is not important. This is crucial
3930  * property for state pruning. When state is checkpointed and finalized at
3931  * some instruction index, it can be correctly and safely used to "short
3932  * circuit" any *compatible* state that reaches exactly the same instruction
3933  * index. I.e., if we jumped to that instruction from a completely different
3934  * code path than original finalized state was derived from, it doesn't
3935  * matter, current state can be discarded because from that instruction
3936  * forward having a compatible state will ensure we will safely reach the
3937  * exit. States describe preconditions for further exploration, but completely
3938  * forget the history of how we got here.
3939  *
3940  * This also means that even if we needed precise SCALAR range to get to
3941  * finalized state, but from that point forward *that same* SCALAR register is
3942  * never used in a precise context (i.e., it's precise value is not needed for
3943  * correctness), it's correct and safe to mark such register as "imprecise"
3944  * (i.e., precise marking set to false). This is what we rely on when we do
3945  * not set precise marking in current state. If no child state requires
3946  * precision for any given SCALAR register, it's safe to dictate that it can
3947  * be imprecise. If any child state does require this register to be precise,
3948  * we'll mark it precise later retroactively during precise markings
3949  * propagation from child state to parent states.
3950  *
3951  * Skipping precise marking setting in current state is a mild version of
3952  * relying on the above observation. But we can utilize this property even
3953  * more aggressively by proactively forgetting any precise marking in the
3954  * current state (which we inherited from the parent state), right before we
3955  * checkpoint it and branch off into new child state. This is done by
3956  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3957  * finalized states which help in short circuiting more future states.
3958  */
3959 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3960 {
3961 	struct backtrack_state *bt = &env->bt;
3962 	struct bpf_verifier_state *st = env->cur_state;
3963 	int first_idx = st->first_insn_idx;
3964 	int last_idx = env->insn_idx;
3965 	int subseq_idx = -1;
3966 	struct bpf_func_state *func;
3967 	struct bpf_reg_state *reg;
3968 	bool skip_first = true;
3969 	int i, fr, err;
3970 
3971 	if (!env->bpf_capable)
3972 		return 0;
3973 
3974 	/* set frame number from which we are starting to backtrack */
3975 	bt_init(bt, env->cur_state->curframe);
3976 
3977 	/* Do sanity checks against current state of register and/or stack
3978 	 * slot, but don't set precise flag in current state, as precision
3979 	 * tracking in the current state is unnecessary.
3980 	 */
3981 	func = st->frame[bt->frame];
3982 	if (regno >= 0) {
3983 		reg = &func->regs[regno];
3984 		if (reg->type != SCALAR_VALUE) {
3985 			WARN_ONCE(1, "backtracing misuse");
3986 			return -EFAULT;
3987 		}
3988 		bt_set_reg(bt, regno);
3989 	}
3990 
3991 	if (bt_empty(bt))
3992 		return 0;
3993 
3994 	for (;;) {
3995 		DECLARE_BITMAP(mask, 64);
3996 		u32 history = st->jmp_history_cnt;
3997 
3998 		if (env->log.level & BPF_LOG_LEVEL2) {
3999 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4000 				bt->frame, last_idx, first_idx, subseq_idx);
4001 		}
4002 
4003 		/* If some register with scalar ID is marked as precise,
4004 		 * make sure that all registers sharing this ID are also precise.
4005 		 * This is needed to estimate effect of find_equal_scalars().
4006 		 * Do this at the last instruction of each state,
4007 		 * bpf_reg_state::id fields are valid for these instructions.
4008 		 *
4009 		 * Allows to track precision in situation like below:
4010 		 *
4011 		 *     r2 = unknown value
4012 		 *     ...
4013 		 *   --- state #0 ---
4014 		 *     ...
4015 		 *     r1 = r2                 // r1 and r2 now share the same ID
4016 		 *     ...
4017 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4018 		 *     ...
4019 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4020 		 *     ...
4021 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4022 		 *     r3 = r10
4023 		 *     r3 += r1                // need to mark both r1 and r2
4024 		 */
4025 		if (mark_precise_scalar_ids(env, st))
4026 			return -EFAULT;
4027 
4028 		if (last_idx < 0) {
4029 			/* we are at the entry into subprog, which
4030 			 * is expected for global funcs, but only if
4031 			 * requested precise registers are R1-R5
4032 			 * (which are global func's input arguments)
4033 			 */
4034 			if (st->curframe == 0 &&
4035 			    st->frame[0]->subprogno > 0 &&
4036 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4037 			    bt_stack_mask(bt) == 0 &&
4038 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4039 				bitmap_from_u64(mask, bt_reg_mask(bt));
4040 				for_each_set_bit(i, mask, 32) {
4041 					reg = &st->frame[0]->regs[i];
4042 					if (reg->type != SCALAR_VALUE) {
4043 						bt_clear_reg(bt, i);
4044 						continue;
4045 					}
4046 					reg->precise = true;
4047 				}
4048 				return 0;
4049 			}
4050 
4051 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4052 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4053 			WARN_ONCE(1, "verifier backtracking bug");
4054 			return -EFAULT;
4055 		}
4056 
4057 		for (i = last_idx;;) {
4058 			if (skip_first) {
4059 				err = 0;
4060 				skip_first = false;
4061 			} else {
4062 				err = backtrack_insn(env, i, subseq_idx, bt);
4063 			}
4064 			if (err == -ENOTSUPP) {
4065 				mark_all_scalars_precise(env, env->cur_state);
4066 				bt_reset(bt);
4067 				return 0;
4068 			} else if (err) {
4069 				return err;
4070 			}
4071 			if (bt_empty(bt))
4072 				/* Found assignment(s) into tracked register in this state.
4073 				 * Since this state is already marked, just return.
4074 				 * Nothing to be tracked further in the parent state.
4075 				 */
4076 				return 0;
4077 			if (i == first_idx)
4078 				break;
4079 			subseq_idx = i;
4080 			i = get_prev_insn_idx(st, i, &history);
4081 			if (i >= env->prog->len) {
4082 				/* This can happen if backtracking reached insn 0
4083 				 * and there are still reg_mask or stack_mask
4084 				 * to backtrack.
4085 				 * It means the backtracking missed the spot where
4086 				 * particular register was initialized with a constant.
4087 				 */
4088 				verbose(env, "BUG backtracking idx %d\n", i);
4089 				WARN_ONCE(1, "verifier backtracking bug");
4090 				return -EFAULT;
4091 			}
4092 		}
4093 		st = st->parent;
4094 		if (!st)
4095 			break;
4096 
4097 		for (fr = bt->frame; fr >= 0; fr--) {
4098 			func = st->frame[fr];
4099 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4100 			for_each_set_bit(i, mask, 32) {
4101 				reg = &func->regs[i];
4102 				if (reg->type != SCALAR_VALUE) {
4103 					bt_clear_frame_reg(bt, fr, i);
4104 					continue;
4105 				}
4106 				if (reg->precise)
4107 					bt_clear_frame_reg(bt, fr, i);
4108 				else
4109 					reg->precise = true;
4110 			}
4111 
4112 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4113 			for_each_set_bit(i, mask, 64) {
4114 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4115 					/* the sequence of instructions:
4116 					 * 2: (bf) r3 = r10
4117 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4118 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4119 					 * doesn't contain jmps. It's backtracked
4120 					 * as a single block.
4121 					 * During backtracking insn 3 is not recognized as
4122 					 * stack access, so at the end of backtracking
4123 					 * stack slot fp-8 is still marked in stack_mask.
4124 					 * However the parent state may not have accessed
4125 					 * fp-8 and it's "unallocated" stack space.
4126 					 * In such case fallback to conservative.
4127 					 */
4128 					mark_all_scalars_precise(env, env->cur_state);
4129 					bt_reset(bt);
4130 					return 0;
4131 				}
4132 
4133 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4134 					bt_clear_frame_slot(bt, fr, i);
4135 					continue;
4136 				}
4137 				reg = &func->stack[i].spilled_ptr;
4138 				if (reg->precise)
4139 					bt_clear_frame_slot(bt, fr, i);
4140 				else
4141 					reg->precise = true;
4142 			}
4143 			if (env->log.level & BPF_LOG_LEVEL2) {
4144 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4145 					     bt_frame_reg_mask(bt, fr));
4146 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4147 					fr, env->tmp_str_buf);
4148 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4149 					       bt_frame_stack_mask(bt, fr));
4150 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4151 				print_verifier_state(env, func, true);
4152 			}
4153 		}
4154 
4155 		if (bt_empty(bt))
4156 			return 0;
4157 
4158 		subseq_idx = first_idx;
4159 		last_idx = st->last_insn_idx;
4160 		first_idx = st->first_insn_idx;
4161 	}
4162 
4163 	/* if we still have requested precise regs or slots, we missed
4164 	 * something (e.g., stack access through non-r10 register), so
4165 	 * fallback to marking all precise
4166 	 */
4167 	if (!bt_empty(bt)) {
4168 		mark_all_scalars_precise(env, env->cur_state);
4169 		bt_reset(bt);
4170 	}
4171 
4172 	return 0;
4173 }
4174 
4175 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4176 {
4177 	return __mark_chain_precision(env, regno);
4178 }
4179 
4180 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4181  * desired reg and stack masks across all relevant frames
4182  */
4183 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4184 {
4185 	return __mark_chain_precision(env, -1);
4186 }
4187 
4188 static bool is_spillable_regtype(enum bpf_reg_type type)
4189 {
4190 	switch (base_type(type)) {
4191 	case PTR_TO_MAP_VALUE:
4192 	case PTR_TO_STACK:
4193 	case PTR_TO_CTX:
4194 	case PTR_TO_PACKET:
4195 	case PTR_TO_PACKET_META:
4196 	case PTR_TO_PACKET_END:
4197 	case PTR_TO_FLOW_KEYS:
4198 	case CONST_PTR_TO_MAP:
4199 	case PTR_TO_SOCKET:
4200 	case PTR_TO_SOCK_COMMON:
4201 	case PTR_TO_TCP_SOCK:
4202 	case PTR_TO_XDP_SOCK:
4203 	case PTR_TO_BTF_ID:
4204 	case PTR_TO_BUF:
4205 	case PTR_TO_MEM:
4206 	case PTR_TO_FUNC:
4207 	case PTR_TO_MAP_KEY:
4208 		return true;
4209 	default:
4210 		return false;
4211 	}
4212 }
4213 
4214 /* Does this register contain a constant zero? */
4215 static bool register_is_null(struct bpf_reg_state *reg)
4216 {
4217 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4218 }
4219 
4220 static bool register_is_const(struct bpf_reg_state *reg)
4221 {
4222 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4223 }
4224 
4225 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4226 {
4227 	return tnum_is_unknown(reg->var_off) &&
4228 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4229 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4230 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4231 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4232 }
4233 
4234 static bool register_is_bounded(struct bpf_reg_state *reg)
4235 {
4236 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4237 }
4238 
4239 static bool __is_pointer_value(bool allow_ptr_leaks,
4240 			       const struct bpf_reg_state *reg)
4241 {
4242 	if (allow_ptr_leaks)
4243 		return false;
4244 
4245 	return reg->type != SCALAR_VALUE;
4246 }
4247 
4248 /* Copy src state preserving dst->parent and dst->live fields */
4249 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4250 {
4251 	struct bpf_reg_state *parent = dst->parent;
4252 	enum bpf_reg_liveness live = dst->live;
4253 
4254 	*dst = *src;
4255 	dst->parent = parent;
4256 	dst->live = live;
4257 }
4258 
4259 static void save_register_state(struct bpf_func_state *state,
4260 				int spi, struct bpf_reg_state *reg,
4261 				int size)
4262 {
4263 	int i;
4264 
4265 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4266 	if (size == BPF_REG_SIZE)
4267 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4268 
4269 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4270 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4271 
4272 	/* size < 8 bytes spill */
4273 	for (; i; i--)
4274 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4275 }
4276 
4277 static bool is_bpf_st_mem(struct bpf_insn *insn)
4278 {
4279 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4280 }
4281 
4282 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4283  * stack boundary and alignment are checked in check_mem_access()
4284  */
4285 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4286 				       /* stack frame we're writing to */
4287 				       struct bpf_func_state *state,
4288 				       int off, int size, int value_regno,
4289 				       int insn_idx)
4290 {
4291 	struct bpf_func_state *cur; /* state of the current function */
4292 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4293 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4294 	struct bpf_reg_state *reg = NULL;
4295 	u32 dst_reg = insn->dst_reg;
4296 
4297 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4298 	if (err)
4299 		return err;
4300 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4301 	 * so it's aligned access and [off, off + size) are within stack limits
4302 	 */
4303 	if (!env->allow_ptr_leaks &&
4304 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
4305 	    size != BPF_REG_SIZE) {
4306 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4307 		return -EACCES;
4308 	}
4309 
4310 	cur = env->cur_state->frame[env->cur_state->curframe];
4311 	if (value_regno >= 0)
4312 		reg = &cur->regs[value_regno];
4313 	if (!env->bypass_spec_v4) {
4314 		bool sanitize = reg && is_spillable_regtype(reg->type);
4315 
4316 		for (i = 0; i < size; i++) {
4317 			u8 type = state->stack[spi].slot_type[i];
4318 
4319 			if (type != STACK_MISC && type != STACK_ZERO) {
4320 				sanitize = true;
4321 				break;
4322 			}
4323 		}
4324 
4325 		if (sanitize)
4326 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4327 	}
4328 
4329 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4330 	if (err)
4331 		return err;
4332 
4333 	mark_stack_slot_scratched(env, spi);
4334 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4335 	    !register_is_null(reg) && env->bpf_capable) {
4336 		if (dst_reg != BPF_REG_FP) {
4337 			/* The backtracking logic can only recognize explicit
4338 			 * stack slot address like [fp - 8]. Other spill of
4339 			 * scalar via different register has to be conservative.
4340 			 * Backtrack from here and mark all registers as precise
4341 			 * that contributed into 'reg' being a constant.
4342 			 */
4343 			err = mark_chain_precision(env, value_regno);
4344 			if (err)
4345 				return err;
4346 		}
4347 		save_register_state(state, spi, reg, size);
4348 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4349 		   insn->imm != 0 && env->bpf_capable) {
4350 		struct bpf_reg_state fake_reg = {};
4351 
4352 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4353 		fake_reg.type = SCALAR_VALUE;
4354 		save_register_state(state, spi, &fake_reg, size);
4355 	} else if (reg && is_spillable_regtype(reg->type)) {
4356 		/* register containing pointer is being spilled into stack */
4357 		if (size != BPF_REG_SIZE) {
4358 			verbose_linfo(env, insn_idx, "; ");
4359 			verbose(env, "invalid size of register spill\n");
4360 			return -EACCES;
4361 		}
4362 		if (state != cur && reg->type == PTR_TO_STACK) {
4363 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4364 			return -EINVAL;
4365 		}
4366 		save_register_state(state, spi, reg, size);
4367 	} else {
4368 		u8 type = STACK_MISC;
4369 
4370 		/* regular write of data into stack destroys any spilled ptr */
4371 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4372 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4373 		if (is_stack_slot_special(&state->stack[spi]))
4374 			for (i = 0; i < BPF_REG_SIZE; i++)
4375 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4376 
4377 		/* only mark the slot as written if all 8 bytes were written
4378 		 * otherwise read propagation may incorrectly stop too soon
4379 		 * when stack slots are partially written.
4380 		 * This heuristic means that read propagation will be
4381 		 * conservative, since it will add reg_live_read marks
4382 		 * to stack slots all the way to first state when programs
4383 		 * writes+reads less than 8 bytes
4384 		 */
4385 		if (size == BPF_REG_SIZE)
4386 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4387 
4388 		/* when we zero initialize stack slots mark them as such */
4389 		if ((reg && register_is_null(reg)) ||
4390 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4391 			/* backtracking doesn't work for STACK_ZERO yet. */
4392 			err = mark_chain_precision(env, value_regno);
4393 			if (err)
4394 				return err;
4395 			type = STACK_ZERO;
4396 		}
4397 
4398 		/* Mark slots affected by this stack write. */
4399 		for (i = 0; i < size; i++)
4400 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4401 				type;
4402 	}
4403 	return 0;
4404 }
4405 
4406 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4407  * known to contain a variable offset.
4408  * This function checks whether the write is permitted and conservatively
4409  * tracks the effects of the write, considering that each stack slot in the
4410  * dynamic range is potentially written to.
4411  *
4412  * 'off' includes 'regno->off'.
4413  * 'value_regno' can be -1, meaning that an unknown value is being written to
4414  * the stack.
4415  *
4416  * Spilled pointers in range are not marked as written because we don't know
4417  * what's going to be actually written. This means that read propagation for
4418  * future reads cannot be terminated by this write.
4419  *
4420  * For privileged programs, uninitialized stack slots are considered
4421  * initialized by this write (even though we don't know exactly what offsets
4422  * are going to be written to). The idea is that we don't want the verifier to
4423  * reject future reads that access slots written to through variable offsets.
4424  */
4425 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4426 				     /* func where register points to */
4427 				     struct bpf_func_state *state,
4428 				     int ptr_regno, int off, int size,
4429 				     int value_regno, int insn_idx)
4430 {
4431 	struct bpf_func_state *cur; /* state of the current function */
4432 	int min_off, max_off;
4433 	int i, err;
4434 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4435 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4436 	bool writing_zero = false;
4437 	/* set if the fact that we're writing a zero is used to let any
4438 	 * stack slots remain STACK_ZERO
4439 	 */
4440 	bool zero_used = false;
4441 
4442 	cur = env->cur_state->frame[env->cur_state->curframe];
4443 	ptr_reg = &cur->regs[ptr_regno];
4444 	min_off = ptr_reg->smin_value + off;
4445 	max_off = ptr_reg->smax_value + off + size;
4446 	if (value_regno >= 0)
4447 		value_reg = &cur->regs[value_regno];
4448 	if ((value_reg && register_is_null(value_reg)) ||
4449 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4450 		writing_zero = true;
4451 
4452 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4453 	if (err)
4454 		return err;
4455 
4456 	for (i = min_off; i < max_off; i++) {
4457 		int spi;
4458 
4459 		spi = __get_spi(i);
4460 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4461 		if (err)
4462 			return err;
4463 	}
4464 
4465 	/* Variable offset writes destroy any spilled pointers in range. */
4466 	for (i = min_off; i < max_off; i++) {
4467 		u8 new_type, *stype;
4468 		int slot, spi;
4469 
4470 		slot = -i - 1;
4471 		spi = slot / BPF_REG_SIZE;
4472 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4473 		mark_stack_slot_scratched(env, spi);
4474 
4475 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4476 			/* Reject the write if range we may write to has not
4477 			 * been initialized beforehand. If we didn't reject
4478 			 * here, the ptr status would be erased below (even
4479 			 * though not all slots are actually overwritten),
4480 			 * possibly opening the door to leaks.
4481 			 *
4482 			 * We do however catch STACK_INVALID case below, and
4483 			 * only allow reading possibly uninitialized memory
4484 			 * later for CAP_PERFMON, as the write may not happen to
4485 			 * that slot.
4486 			 */
4487 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4488 				insn_idx, i);
4489 			return -EINVAL;
4490 		}
4491 
4492 		/* Erase all spilled pointers. */
4493 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4494 
4495 		/* Update the slot type. */
4496 		new_type = STACK_MISC;
4497 		if (writing_zero && *stype == STACK_ZERO) {
4498 			new_type = STACK_ZERO;
4499 			zero_used = true;
4500 		}
4501 		/* If the slot is STACK_INVALID, we check whether it's OK to
4502 		 * pretend that it will be initialized by this write. The slot
4503 		 * might not actually be written to, and so if we mark it as
4504 		 * initialized future reads might leak uninitialized memory.
4505 		 * For privileged programs, we will accept such reads to slots
4506 		 * that may or may not be written because, if we're reject
4507 		 * them, the error would be too confusing.
4508 		 */
4509 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4510 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4511 					insn_idx, i);
4512 			return -EINVAL;
4513 		}
4514 		*stype = new_type;
4515 	}
4516 	if (zero_used) {
4517 		/* backtracking doesn't work for STACK_ZERO yet. */
4518 		err = mark_chain_precision(env, value_regno);
4519 		if (err)
4520 			return err;
4521 	}
4522 	return 0;
4523 }
4524 
4525 /* When register 'dst_regno' is assigned some values from stack[min_off,
4526  * max_off), we set the register's type according to the types of the
4527  * respective stack slots. If all the stack values are known to be zeros, then
4528  * so is the destination reg. Otherwise, the register is considered to be
4529  * SCALAR. This function does not deal with register filling; the caller must
4530  * ensure that all spilled registers in the stack range have been marked as
4531  * read.
4532  */
4533 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4534 				/* func where src register points to */
4535 				struct bpf_func_state *ptr_state,
4536 				int min_off, int max_off, int dst_regno)
4537 {
4538 	struct bpf_verifier_state *vstate = env->cur_state;
4539 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4540 	int i, slot, spi;
4541 	u8 *stype;
4542 	int zeros = 0;
4543 
4544 	for (i = min_off; i < max_off; i++) {
4545 		slot = -i - 1;
4546 		spi = slot / BPF_REG_SIZE;
4547 		mark_stack_slot_scratched(env, spi);
4548 		stype = ptr_state->stack[spi].slot_type;
4549 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4550 			break;
4551 		zeros++;
4552 	}
4553 	if (zeros == max_off - min_off) {
4554 		/* any access_size read into register is zero extended,
4555 		 * so the whole register == const_zero
4556 		 */
4557 		__mark_reg_const_zero(&state->regs[dst_regno]);
4558 		/* backtracking doesn't support STACK_ZERO yet,
4559 		 * so mark it precise here, so that later
4560 		 * backtracking can stop here.
4561 		 * Backtracking may not need this if this register
4562 		 * doesn't participate in pointer adjustment.
4563 		 * Forward propagation of precise flag is not
4564 		 * necessary either. This mark is only to stop
4565 		 * backtracking. Any register that contributed
4566 		 * to const 0 was marked precise before spill.
4567 		 */
4568 		state->regs[dst_regno].precise = true;
4569 	} else {
4570 		/* have read misc data from the stack */
4571 		mark_reg_unknown(env, state->regs, dst_regno);
4572 	}
4573 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4574 }
4575 
4576 /* Read the stack at 'off' and put the results into the register indicated by
4577  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4578  * spilled reg.
4579  *
4580  * 'dst_regno' can be -1, meaning that the read value is not going to a
4581  * register.
4582  *
4583  * The access is assumed to be within the current stack bounds.
4584  */
4585 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4586 				      /* func where src register points to */
4587 				      struct bpf_func_state *reg_state,
4588 				      int off, int size, int dst_regno)
4589 {
4590 	struct bpf_verifier_state *vstate = env->cur_state;
4591 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4592 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4593 	struct bpf_reg_state *reg;
4594 	u8 *stype, type;
4595 
4596 	stype = reg_state->stack[spi].slot_type;
4597 	reg = &reg_state->stack[spi].spilled_ptr;
4598 
4599 	mark_stack_slot_scratched(env, spi);
4600 
4601 	if (is_spilled_reg(&reg_state->stack[spi])) {
4602 		u8 spill_size = 1;
4603 
4604 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4605 			spill_size++;
4606 
4607 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4608 			if (reg->type != SCALAR_VALUE) {
4609 				verbose_linfo(env, env->insn_idx, "; ");
4610 				verbose(env, "invalid size of register fill\n");
4611 				return -EACCES;
4612 			}
4613 
4614 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4615 			if (dst_regno < 0)
4616 				return 0;
4617 
4618 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4619 				/* The earlier check_reg_arg() has decided the
4620 				 * subreg_def for this insn.  Save it first.
4621 				 */
4622 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4623 
4624 				copy_register_state(&state->regs[dst_regno], reg);
4625 				state->regs[dst_regno].subreg_def = subreg_def;
4626 			} else {
4627 				for (i = 0; i < size; i++) {
4628 					type = stype[(slot - i) % BPF_REG_SIZE];
4629 					if (type == STACK_SPILL)
4630 						continue;
4631 					if (type == STACK_MISC)
4632 						continue;
4633 					if (type == STACK_INVALID && env->allow_uninit_stack)
4634 						continue;
4635 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4636 						off, i, size);
4637 					return -EACCES;
4638 				}
4639 				mark_reg_unknown(env, state->regs, dst_regno);
4640 			}
4641 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4642 			return 0;
4643 		}
4644 
4645 		if (dst_regno >= 0) {
4646 			/* restore register state from stack */
4647 			copy_register_state(&state->regs[dst_regno], reg);
4648 			/* mark reg as written since spilled pointer state likely
4649 			 * has its liveness marks cleared by is_state_visited()
4650 			 * which resets stack/reg liveness for state transitions
4651 			 */
4652 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4653 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4654 			/* If dst_regno==-1, the caller is asking us whether
4655 			 * it is acceptable to use this value as a SCALAR_VALUE
4656 			 * (e.g. for XADD).
4657 			 * We must not allow unprivileged callers to do that
4658 			 * with spilled pointers.
4659 			 */
4660 			verbose(env, "leaking pointer from stack off %d\n",
4661 				off);
4662 			return -EACCES;
4663 		}
4664 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4665 	} else {
4666 		for (i = 0; i < size; i++) {
4667 			type = stype[(slot - i) % BPF_REG_SIZE];
4668 			if (type == STACK_MISC)
4669 				continue;
4670 			if (type == STACK_ZERO)
4671 				continue;
4672 			if (type == STACK_INVALID && env->allow_uninit_stack)
4673 				continue;
4674 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4675 				off, i, size);
4676 			return -EACCES;
4677 		}
4678 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4679 		if (dst_regno >= 0)
4680 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4681 	}
4682 	return 0;
4683 }
4684 
4685 enum bpf_access_src {
4686 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4687 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4688 };
4689 
4690 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4691 					 int regno, int off, int access_size,
4692 					 bool zero_size_allowed,
4693 					 enum bpf_access_src type,
4694 					 struct bpf_call_arg_meta *meta);
4695 
4696 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4697 {
4698 	return cur_regs(env) + regno;
4699 }
4700 
4701 /* Read the stack at 'ptr_regno + off' and put the result into the register
4702  * 'dst_regno'.
4703  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4704  * but not its variable offset.
4705  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4706  *
4707  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4708  * filling registers (i.e. reads of spilled register cannot be detected when
4709  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4710  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4711  * offset; for a fixed offset check_stack_read_fixed_off should be used
4712  * instead.
4713  */
4714 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4715 				    int ptr_regno, int off, int size, int dst_regno)
4716 {
4717 	/* The state of the source register. */
4718 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4719 	struct bpf_func_state *ptr_state = func(env, reg);
4720 	int err;
4721 	int min_off, max_off;
4722 
4723 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4724 	 */
4725 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4726 					    false, ACCESS_DIRECT, NULL);
4727 	if (err)
4728 		return err;
4729 
4730 	min_off = reg->smin_value + off;
4731 	max_off = reg->smax_value + off;
4732 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4733 	return 0;
4734 }
4735 
4736 /* check_stack_read dispatches to check_stack_read_fixed_off or
4737  * check_stack_read_var_off.
4738  *
4739  * The caller must ensure that the offset falls within the allocated stack
4740  * bounds.
4741  *
4742  * 'dst_regno' is a register which will receive the value from the stack. It
4743  * can be -1, meaning that the read value is not going to a register.
4744  */
4745 static int check_stack_read(struct bpf_verifier_env *env,
4746 			    int ptr_regno, int off, int size,
4747 			    int dst_regno)
4748 {
4749 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4750 	struct bpf_func_state *state = func(env, reg);
4751 	int err;
4752 	/* Some accesses are only permitted with a static offset. */
4753 	bool var_off = !tnum_is_const(reg->var_off);
4754 
4755 	/* The offset is required to be static when reads don't go to a
4756 	 * register, in order to not leak pointers (see
4757 	 * check_stack_read_fixed_off).
4758 	 */
4759 	if (dst_regno < 0 && var_off) {
4760 		char tn_buf[48];
4761 
4762 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4763 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4764 			tn_buf, off, size);
4765 		return -EACCES;
4766 	}
4767 	/* Variable offset is prohibited for unprivileged mode for simplicity
4768 	 * since it requires corresponding support in Spectre masking for stack
4769 	 * ALU. See also retrieve_ptr_limit(). The check in
4770 	 * check_stack_access_for_ptr_arithmetic() called by
4771 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4772 	 * with variable offsets, therefore no check is required here. Further,
4773 	 * just checking it here would be insufficient as speculative stack
4774 	 * writes could still lead to unsafe speculative behaviour.
4775 	 */
4776 	if (!var_off) {
4777 		off += reg->var_off.value;
4778 		err = check_stack_read_fixed_off(env, state, off, size,
4779 						 dst_regno);
4780 	} else {
4781 		/* Variable offset stack reads need more conservative handling
4782 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4783 		 * branch.
4784 		 */
4785 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4786 					       dst_regno);
4787 	}
4788 	return err;
4789 }
4790 
4791 
4792 /* check_stack_write dispatches to check_stack_write_fixed_off or
4793  * check_stack_write_var_off.
4794  *
4795  * 'ptr_regno' is the register used as a pointer into the stack.
4796  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4797  * 'value_regno' is the register whose value we're writing to the stack. It can
4798  * be -1, meaning that we're not writing from a register.
4799  *
4800  * The caller must ensure that the offset falls within the maximum stack size.
4801  */
4802 static int check_stack_write(struct bpf_verifier_env *env,
4803 			     int ptr_regno, int off, int size,
4804 			     int value_regno, int insn_idx)
4805 {
4806 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4807 	struct bpf_func_state *state = func(env, reg);
4808 	int err;
4809 
4810 	if (tnum_is_const(reg->var_off)) {
4811 		off += reg->var_off.value;
4812 		err = check_stack_write_fixed_off(env, state, off, size,
4813 						  value_regno, insn_idx);
4814 	} else {
4815 		/* Variable offset stack reads need more conservative handling
4816 		 * than fixed offset ones.
4817 		 */
4818 		err = check_stack_write_var_off(env, state,
4819 						ptr_regno, off, size,
4820 						value_regno, insn_idx);
4821 	}
4822 	return err;
4823 }
4824 
4825 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4826 				 int off, int size, enum bpf_access_type type)
4827 {
4828 	struct bpf_reg_state *regs = cur_regs(env);
4829 	struct bpf_map *map = regs[regno].map_ptr;
4830 	u32 cap = bpf_map_flags_to_cap(map);
4831 
4832 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4833 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4834 			map->value_size, off, size);
4835 		return -EACCES;
4836 	}
4837 
4838 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4839 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4840 			map->value_size, off, size);
4841 		return -EACCES;
4842 	}
4843 
4844 	return 0;
4845 }
4846 
4847 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4848 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4849 			      int off, int size, u32 mem_size,
4850 			      bool zero_size_allowed)
4851 {
4852 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4853 	struct bpf_reg_state *reg;
4854 
4855 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4856 		return 0;
4857 
4858 	reg = &cur_regs(env)[regno];
4859 	switch (reg->type) {
4860 	case PTR_TO_MAP_KEY:
4861 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4862 			mem_size, off, size);
4863 		break;
4864 	case PTR_TO_MAP_VALUE:
4865 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4866 			mem_size, off, size);
4867 		break;
4868 	case PTR_TO_PACKET:
4869 	case PTR_TO_PACKET_META:
4870 	case PTR_TO_PACKET_END:
4871 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4872 			off, size, regno, reg->id, off, mem_size);
4873 		break;
4874 	case PTR_TO_MEM:
4875 	default:
4876 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4877 			mem_size, off, size);
4878 	}
4879 
4880 	return -EACCES;
4881 }
4882 
4883 /* check read/write into a memory region with possible variable offset */
4884 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4885 				   int off, int size, u32 mem_size,
4886 				   bool zero_size_allowed)
4887 {
4888 	struct bpf_verifier_state *vstate = env->cur_state;
4889 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4890 	struct bpf_reg_state *reg = &state->regs[regno];
4891 	int err;
4892 
4893 	/* We may have adjusted the register pointing to memory region, so we
4894 	 * need to try adding each of min_value and max_value to off
4895 	 * to make sure our theoretical access will be safe.
4896 	 *
4897 	 * The minimum value is only important with signed
4898 	 * comparisons where we can't assume the floor of a
4899 	 * value is 0.  If we are using signed variables for our
4900 	 * index'es we need to make sure that whatever we use
4901 	 * will have a set floor within our range.
4902 	 */
4903 	if (reg->smin_value < 0 &&
4904 	    (reg->smin_value == S64_MIN ||
4905 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4906 	      reg->smin_value + off < 0)) {
4907 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4908 			regno);
4909 		return -EACCES;
4910 	}
4911 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4912 				 mem_size, zero_size_allowed);
4913 	if (err) {
4914 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4915 			regno);
4916 		return err;
4917 	}
4918 
4919 	/* If we haven't set a max value then we need to bail since we can't be
4920 	 * sure we won't do bad things.
4921 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4922 	 */
4923 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4924 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4925 			regno);
4926 		return -EACCES;
4927 	}
4928 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4929 				 mem_size, zero_size_allowed);
4930 	if (err) {
4931 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4932 			regno);
4933 		return err;
4934 	}
4935 
4936 	return 0;
4937 }
4938 
4939 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4940 			       const struct bpf_reg_state *reg, int regno,
4941 			       bool fixed_off_ok)
4942 {
4943 	/* Access to this pointer-typed register or passing it to a helper
4944 	 * is only allowed in its original, unmodified form.
4945 	 */
4946 
4947 	if (reg->off < 0) {
4948 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4949 			reg_type_str(env, reg->type), regno, reg->off);
4950 		return -EACCES;
4951 	}
4952 
4953 	if (!fixed_off_ok && reg->off) {
4954 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4955 			reg_type_str(env, reg->type), regno, reg->off);
4956 		return -EACCES;
4957 	}
4958 
4959 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4960 		char tn_buf[48];
4961 
4962 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4963 		verbose(env, "variable %s access var_off=%s disallowed\n",
4964 			reg_type_str(env, reg->type), tn_buf);
4965 		return -EACCES;
4966 	}
4967 
4968 	return 0;
4969 }
4970 
4971 int check_ptr_off_reg(struct bpf_verifier_env *env,
4972 		      const struct bpf_reg_state *reg, int regno)
4973 {
4974 	return __check_ptr_off_reg(env, reg, regno, false);
4975 }
4976 
4977 static int map_kptr_match_type(struct bpf_verifier_env *env,
4978 			       struct btf_field *kptr_field,
4979 			       struct bpf_reg_state *reg, u32 regno)
4980 {
4981 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4982 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4983 	const char *reg_name = "";
4984 
4985 	/* Only unreferenced case accepts untrusted pointers */
4986 	if (kptr_field->type == BPF_KPTR_UNREF)
4987 		perm_flags |= PTR_UNTRUSTED;
4988 
4989 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4990 		goto bad_type;
4991 
4992 	if (!btf_is_kernel(reg->btf)) {
4993 		verbose(env, "R%d must point to kernel BTF\n", regno);
4994 		return -EINVAL;
4995 	}
4996 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4997 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4998 
4999 	/* For ref_ptr case, release function check should ensure we get one
5000 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5001 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5002 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5003 	 * reg->off and reg->ref_obj_id are not needed here.
5004 	 */
5005 	if (__check_ptr_off_reg(env, reg, regno, true))
5006 		return -EACCES;
5007 
5008 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
5009 	 * we also need to take into account the reg->off.
5010 	 *
5011 	 * We want to support cases like:
5012 	 *
5013 	 * struct foo {
5014 	 *         struct bar br;
5015 	 *         struct baz bz;
5016 	 * };
5017 	 *
5018 	 * struct foo *v;
5019 	 * v = func();	      // PTR_TO_BTF_ID
5020 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5021 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5022 	 *                    // first member type of struct after comparison fails
5023 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5024 	 *                    // to match type
5025 	 *
5026 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5027 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5028 	 * the struct to match type against first member of struct, i.e. reject
5029 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5030 	 * strict mode to true for type match.
5031 	 */
5032 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5033 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5034 				  kptr_field->type == BPF_KPTR_REF))
5035 		goto bad_type;
5036 	return 0;
5037 bad_type:
5038 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5039 		reg_type_str(env, reg->type), reg_name);
5040 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5041 	if (kptr_field->type == BPF_KPTR_UNREF)
5042 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5043 			targ_name);
5044 	else
5045 		verbose(env, "\n");
5046 	return -EINVAL;
5047 }
5048 
5049 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5050  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5051  */
5052 static bool in_rcu_cs(struct bpf_verifier_env *env)
5053 {
5054 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5055 }
5056 
5057 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5058 BTF_SET_START(rcu_protected_types)
5059 BTF_ID(struct, prog_test_ref_kfunc)
5060 BTF_ID(struct, cgroup)
5061 BTF_ID(struct, bpf_cpumask)
5062 BTF_ID(struct, task_struct)
5063 BTF_SET_END(rcu_protected_types)
5064 
5065 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5066 {
5067 	if (!btf_is_kernel(btf))
5068 		return false;
5069 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5070 }
5071 
5072 static bool rcu_safe_kptr(const struct btf_field *field)
5073 {
5074 	const struct btf_field_kptr *kptr = &field->kptr;
5075 
5076 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5077 }
5078 
5079 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5080 				 int value_regno, int insn_idx,
5081 				 struct btf_field *kptr_field)
5082 {
5083 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5084 	int class = BPF_CLASS(insn->code);
5085 	struct bpf_reg_state *val_reg;
5086 
5087 	/* Things we already checked for in check_map_access and caller:
5088 	 *  - Reject cases where variable offset may touch kptr
5089 	 *  - size of access (must be BPF_DW)
5090 	 *  - tnum_is_const(reg->var_off)
5091 	 *  - kptr_field->offset == off + reg->var_off.value
5092 	 */
5093 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5094 	if (BPF_MODE(insn->code) != BPF_MEM) {
5095 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5096 		return -EACCES;
5097 	}
5098 
5099 	/* We only allow loading referenced kptr, since it will be marked as
5100 	 * untrusted, similar to unreferenced kptr.
5101 	 */
5102 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5103 		verbose(env, "store to referenced kptr disallowed\n");
5104 		return -EACCES;
5105 	}
5106 
5107 	if (class == BPF_LDX) {
5108 		val_reg = reg_state(env, value_regno);
5109 		/* We can simply mark the value_regno receiving the pointer
5110 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5111 		 */
5112 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5113 				kptr_field->kptr.btf_id,
5114 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5115 				PTR_MAYBE_NULL | MEM_RCU :
5116 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5117 		/* For mark_ptr_or_null_reg */
5118 		val_reg->id = ++env->id_gen;
5119 	} else if (class == BPF_STX) {
5120 		val_reg = reg_state(env, value_regno);
5121 		if (!register_is_null(val_reg) &&
5122 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5123 			return -EACCES;
5124 	} else if (class == BPF_ST) {
5125 		if (insn->imm) {
5126 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5127 				kptr_field->offset);
5128 			return -EACCES;
5129 		}
5130 	} else {
5131 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5132 		return -EACCES;
5133 	}
5134 	return 0;
5135 }
5136 
5137 /* check read/write into a map element with possible variable offset */
5138 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5139 			    int off, int size, bool zero_size_allowed,
5140 			    enum bpf_access_src src)
5141 {
5142 	struct bpf_verifier_state *vstate = env->cur_state;
5143 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5144 	struct bpf_reg_state *reg = &state->regs[regno];
5145 	struct bpf_map *map = reg->map_ptr;
5146 	struct btf_record *rec;
5147 	int err, i;
5148 
5149 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5150 				      zero_size_allowed);
5151 	if (err)
5152 		return err;
5153 
5154 	if (IS_ERR_OR_NULL(map->record))
5155 		return 0;
5156 	rec = map->record;
5157 	for (i = 0; i < rec->cnt; i++) {
5158 		struct btf_field *field = &rec->fields[i];
5159 		u32 p = field->offset;
5160 
5161 		/* If any part of a field  can be touched by load/store, reject
5162 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5163 		 * it is sufficient to check x1 < y2 && y1 < x2.
5164 		 */
5165 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5166 		    p < reg->umax_value + off + size) {
5167 			switch (field->type) {
5168 			case BPF_KPTR_UNREF:
5169 			case BPF_KPTR_REF:
5170 				if (src != ACCESS_DIRECT) {
5171 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5172 					return -EACCES;
5173 				}
5174 				if (!tnum_is_const(reg->var_off)) {
5175 					verbose(env, "kptr access cannot have variable offset\n");
5176 					return -EACCES;
5177 				}
5178 				if (p != off + reg->var_off.value) {
5179 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5180 						p, off + reg->var_off.value);
5181 					return -EACCES;
5182 				}
5183 				if (size != bpf_size_to_bytes(BPF_DW)) {
5184 					verbose(env, "kptr access size must be BPF_DW\n");
5185 					return -EACCES;
5186 				}
5187 				break;
5188 			default:
5189 				verbose(env, "%s cannot be accessed directly by load/store\n",
5190 					btf_field_type_name(field->type));
5191 				return -EACCES;
5192 			}
5193 		}
5194 	}
5195 	return 0;
5196 }
5197 
5198 #define MAX_PACKET_OFF 0xffff
5199 
5200 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5201 				       const struct bpf_call_arg_meta *meta,
5202 				       enum bpf_access_type t)
5203 {
5204 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5205 
5206 	switch (prog_type) {
5207 	/* Program types only with direct read access go here! */
5208 	case BPF_PROG_TYPE_LWT_IN:
5209 	case BPF_PROG_TYPE_LWT_OUT:
5210 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5211 	case BPF_PROG_TYPE_SK_REUSEPORT:
5212 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5213 	case BPF_PROG_TYPE_CGROUP_SKB:
5214 		if (t == BPF_WRITE)
5215 			return false;
5216 		fallthrough;
5217 
5218 	/* Program types with direct read + write access go here! */
5219 	case BPF_PROG_TYPE_SCHED_CLS:
5220 	case BPF_PROG_TYPE_SCHED_ACT:
5221 	case BPF_PROG_TYPE_XDP:
5222 	case BPF_PROG_TYPE_LWT_XMIT:
5223 	case BPF_PROG_TYPE_SK_SKB:
5224 	case BPF_PROG_TYPE_SK_MSG:
5225 		if (meta)
5226 			return meta->pkt_access;
5227 
5228 		env->seen_direct_write = true;
5229 		return true;
5230 
5231 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5232 		if (t == BPF_WRITE)
5233 			env->seen_direct_write = true;
5234 
5235 		return true;
5236 
5237 	default:
5238 		return false;
5239 	}
5240 }
5241 
5242 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5243 			       int size, bool zero_size_allowed)
5244 {
5245 	struct bpf_reg_state *regs = cur_regs(env);
5246 	struct bpf_reg_state *reg = &regs[regno];
5247 	int err;
5248 
5249 	/* We may have added a variable offset to the packet pointer; but any
5250 	 * reg->range we have comes after that.  We are only checking the fixed
5251 	 * offset.
5252 	 */
5253 
5254 	/* We don't allow negative numbers, because we aren't tracking enough
5255 	 * detail to prove they're safe.
5256 	 */
5257 	if (reg->smin_value < 0) {
5258 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5259 			regno);
5260 		return -EACCES;
5261 	}
5262 
5263 	err = reg->range < 0 ? -EINVAL :
5264 	      __check_mem_access(env, regno, off, size, reg->range,
5265 				 zero_size_allowed);
5266 	if (err) {
5267 		verbose(env, "R%d offset is outside of the packet\n", regno);
5268 		return err;
5269 	}
5270 
5271 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5272 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5273 	 * otherwise find_good_pkt_pointers would have refused to set range info
5274 	 * that __check_mem_access would have rejected this pkt access.
5275 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5276 	 */
5277 	env->prog->aux->max_pkt_offset =
5278 		max_t(u32, env->prog->aux->max_pkt_offset,
5279 		      off + reg->umax_value + size - 1);
5280 
5281 	return err;
5282 }
5283 
5284 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5285 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5286 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5287 			    struct btf **btf, u32 *btf_id)
5288 {
5289 	struct bpf_insn_access_aux info = {
5290 		.reg_type = *reg_type,
5291 		.log = &env->log,
5292 	};
5293 
5294 	if (env->ops->is_valid_access &&
5295 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5296 		/* A non zero info.ctx_field_size indicates that this field is a
5297 		 * candidate for later verifier transformation to load the whole
5298 		 * field and then apply a mask when accessed with a narrower
5299 		 * access than actual ctx access size. A zero info.ctx_field_size
5300 		 * will only allow for whole field access and rejects any other
5301 		 * type of narrower access.
5302 		 */
5303 		*reg_type = info.reg_type;
5304 
5305 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5306 			*btf = info.btf;
5307 			*btf_id = info.btf_id;
5308 		} else {
5309 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5310 		}
5311 		/* remember the offset of last byte accessed in ctx */
5312 		if (env->prog->aux->max_ctx_offset < off + size)
5313 			env->prog->aux->max_ctx_offset = off + size;
5314 		return 0;
5315 	}
5316 
5317 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5318 	return -EACCES;
5319 }
5320 
5321 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5322 				  int size)
5323 {
5324 	if (size < 0 || off < 0 ||
5325 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5326 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5327 			off, size);
5328 		return -EACCES;
5329 	}
5330 	return 0;
5331 }
5332 
5333 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5334 			     u32 regno, int off, int size,
5335 			     enum bpf_access_type t)
5336 {
5337 	struct bpf_reg_state *regs = cur_regs(env);
5338 	struct bpf_reg_state *reg = &regs[regno];
5339 	struct bpf_insn_access_aux info = {};
5340 	bool valid;
5341 
5342 	if (reg->smin_value < 0) {
5343 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5344 			regno);
5345 		return -EACCES;
5346 	}
5347 
5348 	switch (reg->type) {
5349 	case PTR_TO_SOCK_COMMON:
5350 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5351 		break;
5352 	case PTR_TO_SOCKET:
5353 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5354 		break;
5355 	case PTR_TO_TCP_SOCK:
5356 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5357 		break;
5358 	case PTR_TO_XDP_SOCK:
5359 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5360 		break;
5361 	default:
5362 		valid = false;
5363 	}
5364 
5365 
5366 	if (valid) {
5367 		env->insn_aux_data[insn_idx].ctx_field_size =
5368 			info.ctx_field_size;
5369 		return 0;
5370 	}
5371 
5372 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5373 		regno, reg_type_str(env, reg->type), off, size);
5374 
5375 	return -EACCES;
5376 }
5377 
5378 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5379 {
5380 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5381 }
5382 
5383 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5384 {
5385 	const struct bpf_reg_state *reg = reg_state(env, regno);
5386 
5387 	return reg->type == PTR_TO_CTX;
5388 }
5389 
5390 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5391 {
5392 	const struct bpf_reg_state *reg = reg_state(env, regno);
5393 
5394 	return type_is_sk_pointer(reg->type);
5395 }
5396 
5397 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5398 {
5399 	const struct bpf_reg_state *reg = reg_state(env, regno);
5400 
5401 	return type_is_pkt_pointer(reg->type);
5402 }
5403 
5404 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5405 {
5406 	const struct bpf_reg_state *reg = reg_state(env, regno);
5407 
5408 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5409 	return reg->type == PTR_TO_FLOW_KEYS;
5410 }
5411 
5412 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5413 {
5414 	/* A referenced register is always trusted. */
5415 	if (reg->ref_obj_id)
5416 		return true;
5417 
5418 	/* If a register is not referenced, it is trusted if it has the
5419 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5420 	 * other type modifiers may be safe, but we elect to take an opt-in
5421 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5422 	 * not.
5423 	 *
5424 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5425 	 * for whether a register is trusted.
5426 	 */
5427 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5428 	       !bpf_type_has_unsafe_modifiers(reg->type);
5429 }
5430 
5431 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5432 {
5433 	return reg->type & MEM_RCU;
5434 }
5435 
5436 static void clear_trusted_flags(enum bpf_type_flag *flag)
5437 {
5438 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5439 }
5440 
5441 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5442 				   const struct bpf_reg_state *reg,
5443 				   int off, int size, bool strict)
5444 {
5445 	struct tnum reg_off;
5446 	int ip_align;
5447 
5448 	/* Byte size accesses are always allowed. */
5449 	if (!strict || size == 1)
5450 		return 0;
5451 
5452 	/* For platforms that do not have a Kconfig enabling
5453 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5454 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5455 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5456 	 * to this code only in strict mode where we want to emulate
5457 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5458 	 * unconditional IP align value of '2'.
5459 	 */
5460 	ip_align = 2;
5461 
5462 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5463 	if (!tnum_is_aligned(reg_off, size)) {
5464 		char tn_buf[48];
5465 
5466 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5467 		verbose(env,
5468 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5469 			ip_align, tn_buf, reg->off, off, size);
5470 		return -EACCES;
5471 	}
5472 
5473 	return 0;
5474 }
5475 
5476 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5477 				       const struct bpf_reg_state *reg,
5478 				       const char *pointer_desc,
5479 				       int off, int size, bool strict)
5480 {
5481 	struct tnum reg_off;
5482 
5483 	/* Byte size accesses are always allowed. */
5484 	if (!strict || size == 1)
5485 		return 0;
5486 
5487 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5488 	if (!tnum_is_aligned(reg_off, size)) {
5489 		char tn_buf[48];
5490 
5491 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5492 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5493 			pointer_desc, tn_buf, reg->off, off, size);
5494 		return -EACCES;
5495 	}
5496 
5497 	return 0;
5498 }
5499 
5500 static int check_ptr_alignment(struct bpf_verifier_env *env,
5501 			       const struct bpf_reg_state *reg, int off,
5502 			       int size, bool strict_alignment_once)
5503 {
5504 	bool strict = env->strict_alignment || strict_alignment_once;
5505 	const char *pointer_desc = "";
5506 
5507 	switch (reg->type) {
5508 	case PTR_TO_PACKET:
5509 	case PTR_TO_PACKET_META:
5510 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5511 		 * right in front, treat it the very same way.
5512 		 */
5513 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5514 	case PTR_TO_FLOW_KEYS:
5515 		pointer_desc = "flow keys ";
5516 		break;
5517 	case PTR_TO_MAP_KEY:
5518 		pointer_desc = "key ";
5519 		break;
5520 	case PTR_TO_MAP_VALUE:
5521 		pointer_desc = "value ";
5522 		break;
5523 	case PTR_TO_CTX:
5524 		pointer_desc = "context ";
5525 		break;
5526 	case PTR_TO_STACK:
5527 		pointer_desc = "stack ";
5528 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5529 		 * and check_stack_read_fixed_off() relies on stack accesses being
5530 		 * aligned.
5531 		 */
5532 		strict = true;
5533 		break;
5534 	case PTR_TO_SOCKET:
5535 		pointer_desc = "sock ";
5536 		break;
5537 	case PTR_TO_SOCK_COMMON:
5538 		pointer_desc = "sock_common ";
5539 		break;
5540 	case PTR_TO_TCP_SOCK:
5541 		pointer_desc = "tcp_sock ";
5542 		break;
5543 	case PTR_TO_XDP_SOCK:
5544 		pointer_desc = "xdp_sock ";
5545 		break;
5546 	default:
5547 		break;
5548 	}
5549 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5550 					   strict);
5551 }
5552 
5553 static int update_stack_depth(struct bpf_verifier_env *env,
5554 			      const struct bpf_func_state *func,
5555 			      int off)
5556 {
5557 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5558 
5559 	if (stack >= -off)
5560 		return 0;
5561 
5562 	/* update known max for given subprogram */
5563 	env->subprog_info[func->subprogno].stack_depth = -off;
5564 	return 0;
5565 }
5566 
5567 /* starting from main bpf function walk all instructions of the function
5568  * and recursively walk all callees that given function can call.
5569  * Ignore jump and exit insns.
5570  * Since recursion is prevented by check_cfg() this algorithm
5571  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5572  */
5573 static int check_max_stack_depth(struct bpf_verifier_env *env)
5574 {
5575 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5576 	struct bpf_subprog_info *subprog = env->subprog_info;
5577 	struct bpf_insn *insn = env->prog->insnsi;
5578 	bool tail_call_reachable = false;
5579 	int ret_insn[MAX_CALL_FRAMES];
5580 	int ret_prog[MAX_CALL_FRAMES];
5581 	int j;
5582 
5583 process_func:
5584 	/* protect against potential stack overflow that might happen when
5585 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5586 	 * depth for such case down to 256 so that the worst case scenario
5587 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5588 	 * 8k).
5589 	 *
5590 	 * To get the idea what might happen, see an example:
5591 	 * func1 -> sub rsp, 128
5592 	 *  subfunc1 -> sub rsp, 256
5593 	 *  tailcall1 -> add rsp, 256
5594 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5595 	 *   subfunc2 -> sub rsp, 64
5596 	 *   subfunc22 -> sub rsp, 128
5597 	 *   tailcall2 -> add rsp, 128
5598 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5599 	 *
5600 	 * tailcall will unwind the current stack frame but it will not get rid
5601 	 * of caller's stack as shown on the example above.
5602 	 */
5603 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5604 		verbose(env,
5605 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5606 			depth);
5607 		return -EACCES;
5608 	}
5609 	/* round up to 32-bytes, since this is granularity
5610 	 * of interpreter stack size
5611 	 */
5612 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5613 	if (depth > MAX_BPF_STACK) {
5614 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5615 			frame + 1, depth);
5616 		return -EACCES;
5617 	}
5618 continue_func:
5619 	subprog_end = subprog[idx + 1].start;
5620 	for (; i < subprog_end; i++) {
5621 		int next_insn;
5622 
5623 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5624 			continue;
5625 		/* remember insn and function to return to */
5626 		ret_insn[frame] = i + 1;
5627 		ret_prog[frame] = idx;
5628 
5629 		/* find the callee */
5630 		next_insn = i + insn[i].imm + 1;
5631 		idx = find_subprog(env, next_insn);
5632 		if (idx < 0) {
5633 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5634 				  next_insn);
5635 			return -EFAULT;
5636 		}
5637 		if (subprog[idx].is_async_cb) {
5638 			if (subprog[idx].has_tail_call) {
5639 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5640 				return -EFAULT;
5641 			}
5642 			 /* async callbacks don't increase bpf prog stack size */
5643 			continue;
5644 		}
5645 		i = next_insn;
5646 
5647 		if (subprog[idx].has_tail_call)
5648 			tail_call_reachable = true;
5649 
5650 		frame++;
5651 		if (frame >= MAX_CALL_FRAMES) {
5652 			verbose(env, "the call stack of %d frames is too deep !\n",
5653 				frame);
5654 			return -E2BIG;
5655 		}
5656 		goto process_func;
5657 	}
5658 	/* if tail call got detected across bpf2bpf calls then mark each of the
5659 	 * currently present subprog frames as tail call reachable subprogs;
5660 	 * this info will be utilized by JIT so that we will be preserving the
5661 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5662 	 */
5663 	if (tail_call_reachable)
5664 		for (j = 0; j < frame; j++)
5665 			subprog[ret_prog[j]].tail_call_reachable = true;
5666 	if (subprog[0].tail_call_reachable)
5667 		env->prog->aux->tail_call_reachable = true;
5668 
5669 	/* end of for() loop means the last insn of the 'subprog'
5670 	 * was reached. Doesn't matter whether it was JA or EXIT
5671 	 */
5672 	if (frame == 0)
5673 		return 0;
5674 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5675 	frame--;
5676 	i = ret_insn[frame];
5677 	idx = ret_prog[frame];
5678 	goto continue_func;
5679 }
5680 
5681 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5682 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5683 				  const struct bpf_insn *insn, int idx)
5684 {
5685 	int start = idx + insn->imm + 1, subprog;
5686 
5687 	subprog = find_subprog(env, start);
5688 	if (subprog < 0) {
5689 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5690 			  start);
5691 		return -EFAULT;
5692 	}
5693 	return env->subprog_info[subprog].stack_depth;
5694 }
5695 #endif
5696 
5697 static int __check_buffer_access(struct bpf_verifier_env *env,
5698 				 const char *buf_info,
5699 				 const struct bpf_reg_state *reg,
5700 				 int regno, int off, int size)
5701 {
5702 	if (off < 0) {
5703 		verbose(env,
5704 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5705 			regno, buf_info, off, size);
5706 		return -EACCES;
5707 	}
5708 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5709 		char tn_buf[48];
5710 
5711 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5712 		verbose(env,
5713 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5714 			regno, off, tn_buf);
5715 		return -EACCES;
5716 	}
5717 
5718 	return 0;
5719 }
5720 
5721 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5722 				  const struct bpf_reg_state *reg,
5723 				  int regno, int off, int size)
5724 {
5725 	int err;
5726 
5727 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5728 	if (err)
5729 		return err;
5730 
5731 	if (off + size > env->prog->aux->max_tp_access)
5732 		env->prog->aux->max_tp_access = off + size;
5733 
5734 	return 0;
5735 }
5736 
5737 static int check_buffer_access(struct bpf_verifier_env *env,
5738 			       const struct bpf_reg_state *reg,
5739 			       int regno, int off, int size,
5740 			       bool zero_size_allowed,
5741 			       u32 *max_access)
5742 {
5743 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5744 	int err;
5745 
5746 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5747 	if (err)
5748 		return err;
5749 
5750 	if (off + size > *max_access)
5751 		*max_access = off + size;
5752 
5753 	return 0;
5754 }
5755 
5756 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5757 static void zext_32_to_64(struct bpf_reg_state *reg)
5758 {
5759 	reg->var_off = tnum_subreg(reg->var_off);
5760 	__reg_assign_32_into_64(reg);
5761 }
5762 
5763 /* truncate register to smaller size (in bytes)
5764  * must be called with size < BPF_REG_SIZE
5765  */
5766 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5767 {
5768 	u64 mask;
5769 
5770 	/* clear high bits in bit representation */
5771 	reg->var_off = tnum_cast(reg->var_off, size);
5772 
5773 	/* fix arithmetic bounds */
5774 	mask = ((u64)1 << (size * 8)) - 1;
5775 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5776 		reg->umin_value &= mask;
5777 		reg->umax_value &= mask;
5778 	} else {
5779 		reg->umin_value = 0;
5780 		reg->umax_value = mask;
5781 	}
5782 	reg->smin_value = reg->umin_value;
5783 	reg->smax_value = reg->umax_value;
5784 
5785 	/* If size is smaller than 32bit register the 32bit register
5786 	 * values are also truncated so we push 64-bit bounds into
5787 	 * 32-bit bounds. Above were truncated < 32-bits already.
5788 	 */
5789 	if (size >= 4)
5790 		return;
5791 	__reg_combine_64_into_32(reg);
5792 }
5793 
5794 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5795 {
5796 	/* A map is considered read-only if the following condition are true:
5797 	 *
5798 	 * 1) BPF program side cannot change any of the map content. The
5799 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5800 	 *    and was set at map creation time.
5801 	 * 2) The map value(s) have been initialized from user space by a
5802 	 *    loader and then "frozen", such that no new map update/delete
5803 	 *    operations from syscall side are possible for the rest of
5804 	 *    the map's lifetime from that point onwards.
5805 	 * 3) Any parallel/pending map update/delete operations from syscall
5806 	 *    side have been completed. Only after that point, it's safe to
5807 	 *    assume that map value(s) are immutable.
5808 	 */
5809 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5810 	       READ_ONCE(map->frozen) &&
5811 	       !bpf_map_write_active(map);
5812 }
5813 
5814 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5815 {
5816 	void *ptr;
5817 	u64 addr;
5818 	int err;
5819 
5820 	err = map->ops->map_direct_value_addr(map, &addr, off);
5821 	if (err)
5822 		return err;
5823 	ptr = (void *)(long)addr + off;
5824 
5825 	switch (size) {
5826 	case sizeof(u8):
5827 		*val = (u64)*(u8 *)ptr;
5828 		break;
5829 	case sizeof(u16):
5830 		*val = (u64)*(u16 *)ptr;
5831 		break;
5832 	case sizeof(u32):
5833 		*val = (u64)*(u32 *)ptr;
5834 		break;
5835 	case sizeof(u64):
5836 		*val = *(u64 *)ptr;
5837 		break;
5838 	default:
5839 		return -EINVAL;
5840 	}
5841 	return 0;
5842 }
5843 
5844 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5845 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5846 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5847 
5848 /*
5849  * Allow list few fields as RCU trusted or full trusted.
5850  * This logic doesn't allow mix tagging and will be removed once GCC supports
5851  * btf_type_tag.
5852  */
5853 
5854 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5855 BTF_TYPE_SAFE_RCU(struct task_struct) {
5856 	const cpumask_t *cpus_ptr;
5857 	struct css_set __rcu *cgroups;
5858 	struct task_struct __rcu *real_parent;
5859 	struct task_struct *group_leader;
5860 };
5861 
5862 BTF_TYPE_SAFE_RCU(struct cgroup) {
5863 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5864 	struct kernfs_node *kn;
5865 };
5866 
5867 BTF_TYPE_SAFE_RCU(struct css_set) {
5868 	struct cgroup *dfl_cgrp;
5869 };
5870 
5871 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5872 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5873 	struct file __rcu *exe_file;
5874 };
5875 
5876 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5877  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5878  */
5879 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5880 	struct sock *sk;
5881 };
5882 
5883 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5884 	struct sock *sk;
5885 };
5886 
5887 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5888 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5889 	struct seq_file *seq;
5890 };
5891 
5892 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5893 	struct bpf_iter_meta *meta;
5894 	struct task_struct *task;
5895 };
5896 
5897 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5898 	struct file *file;
5899 };
5900 
5901 BTF_TYPE_SAFE_TRUSTED(struct file) {
5902 	struct inode *f_inode;
5903 };
5904 
5905 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5906 	/* no negative dentry-s in places where bpf can see it */
5907 	struct inode *d_inode;
5908 };
5909 
5910 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5911 	struct sock *sk;
5912 };
5913 
5914 static bool type_is_rcu(struct bpf_verifier_env *env,
5915 			struct bpf_reg_state *reg,
5916 			const char *field_name, u32 btf_id)
5917 {
5918 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5919 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5920 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5921 
5922 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5923 }
5924 
5925 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5926 				struct bpf_reg_state *reg,
5927 				const char *field_name, u32 btf_id)
5928 {
5929 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5930 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5931 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5932 
5933 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5934 }
5935 
5936 static bool type_is_trusted(struct bpf_verifier_env *env,
5937 			    struct bpf_reg_state *reg,
5938 			    const char *field_name, u32 btf_id)
5939 {
5940 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5941 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5942 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5943 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5944 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5945 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5946 
5947 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5948 }
5949 
5950 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5951 				   struct bpf_reg_state *regs,
5952 				   int regno, int off, int size,
5953 				   enum bpf_access_type atype,
5954 				   int value_regno)
5955 {
5956 	struct bpf_reg_state *reg = regs + regno;
5957 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5958 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5959 	const char *field_name = NULL;
5960 	enum bpf_type_flag flag = 0;
5961 	u32 btf_id = 0;
5962 	int ret;
5963 
5964 	if (!env->allow_ptr_leaks) {
5965 		verbose(env,
5966 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5967 			tname);
5968 		return -EPERM;
5969 	}
5970 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5971 		verbose(env,
5972 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5973 			tname);
5974 		return -EINVAL;
5975 	}
5976 	if (off < 0) {
5977 		verbose(env,
5978 			"R%d is ptr_%s invalid negative access: off=%d\n",
5979 			regno, tname, off);
5980 		return -EACCES;
5981 	}
5982 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5983 		char tn_buf[48];
5984 
5985 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5986 		verbose(env,
5987 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5988 			regno, tname, off, tn_buf);
5989 		return -EACCES;
5990 	}
5991 
5992 	if (reg->type & MEM_USER) {
5993 		verbose(env,
5994 			"R%d is ptr_%s access user memory: off=%d\n",
5995 			regno, tname, off);
5996 		return -EACCES;
5997 	}
5998 
5999 	if (reg->type & MEM_PERCPU) {
6000 		verbose(env,
6001 			"R%d is ptr_%s access percpu memory: off=%d\n",
6002 			regno, tname, off);
6003 		return -EACCES;
6004 	}
6005 
6006 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6007 		if (!btf_is_kernel(reg->btf)) {
6008 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6009 			return -EFAULT;
6010 		}
6011 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6012 	} else {
6013 		/* Writes are permitted with default btf_struct_access for
6014 		 * program allocated objects (which always have ref_obj_id > 0),
6015 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6016 		 */
6017 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6018 			verbose(env, "only read is supported\n");
6019 			return -EACCES;
6020 		}
6021 
6022 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6023 		    !reg->ref_obj_id) {
6024 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6025 			return -EFAULT;
6026 		}
6027 
6028 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6029 	}
6030 
6031 	if (ret < 0)
6032 		return ret;
6033 
6034 	if (ret != PTR_TO_BTF_ID) {
6035 		/* just mark; */
6036 
6037 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6038 		/* If this is an untrusted pointer, all pointers formed by walking it
6039 		 * also inherit the untrusted flag.
6040 		 */
6041 		flag = PTR_UNTRUSTED;
6042 
6043 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6044 		/* By default any pointer obtained from walking a trusted pointer is no
6045 		 * longer trusted, unless the field being accessed has explicitly been
6046 		 * marked as inheriting its parent's state of trust (either full or RCU).
6047 		 * For example:
6048 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6049 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6050 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6051 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6052 		 *
6053 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6054 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6055 		 */
6056 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6057 			flag |= PTR_TRUSTED;
6058 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6059 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6060 				/* ignore __rcu tag and mark it MEM_RCU */
6061 				flag |= MEM_RCU;
6062 			} else if (flag & MEM_RCU ||
6063 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6064 				/* __rcu tagged pointers can be NULL */
6065 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6066 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6067 				/* keep as-is */
6068 			} else {
6069 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6070 				clear_trusted_flags(&flag);
6071 			}
6072 		} else {
6073 			/*
6074 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6075 			 * aggressively mark as untrusted otherwise such
6076 			 * pointers will be plain PTR_TO_BTF_ID without flags
6077 			 * and will be allowed to be passed into helpers for
6078 			 * compat reasons.
6079 			 */
6080 			flag = PTR_UNTRUSTED;
6081 		}
6082 	} else {
6083 		/* Old compat. Deprecated */
6084 		clear_trusted_flags(&flag);
6085 	}
6086 
6087 	if (atype == BPF_READ && value_regno >= 0)
6088 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6089 
6090 	return 0;
6091 }
6092 
6093 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6094 				   struct bpf_reg_state *regs,
6095 				   int regno, int off, int size,
6096 				   enum bpf_access_type atype,
6097 				   int value_regno)
6098 {
6099 	struct bpf_reg_state *reg = regs + regno;
6100 	struct bpf_map *map = reg->map_ptr;
6101 	struct bpf_reg_state map_reg;
6102 	enum bpf_type_flag flag = 0;
6103 	const struct btf_type *t;
6104 	const char *tname;
6105 	u32 btf_id;
6106 	int ret;
6107 
6108 	if (!btf_vmlinux) {
6109 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6110 		return -ENOTSUPP;
6111 	}
6112 
6113 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6114 		verbose(env, "map_ptr access not supported for map type %d\n",
6115 			map->map_type);
6116 		return -ENOTSUPP;
6117 	}
6118 
6119 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6120 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6121 
6122 	if (!env->allow_ptr_leaks) {
6123 		verbose(env,
6124 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6125 			tname);
6126 		return -EPERM;
6127 	}
6128 
6129 	if (off < 0) {
6130 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6131 			regno, tname, off);
6132 		return -EACCES;
6133 	}
6134 
6135 	if (atype != BPF_READ) {
6136 		verbose(env, "only read from %s is supported\n", tname);
6137 		return -EACCES;
6138 	}
6139 
6140 	/* Simulate access to a PTR_TO_BTF_ID */
6141 	memset(&map_reg, 0, sizeof(map_reg));
6142 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6143 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6144 	if (ret < 0)
6145 		return ret;
6146 
6147 	if (value_regno >= 0)
6148 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6149 
6150 	return 0;
6151 }
6152 
6153 /* Check that the stack access at the given offset is within bounds. The
6154  * maximum valid offset is -1.
6155  *
6156  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6157  * -state->allocated_stack for reads.
6158  */
6159 static int check_stack_slot_within_bounds(int off,
6160 					  struct bpf_func_state *state,
6161 					  enum bpf_access_type t)
6162 {
6163 	int min_valid_off;
6164 
6165 	if (t == BPF_WRITE)
6166 		min_valid_off = -MAX_BPF_STACK;
6167 	else
6168 		min_valid_off = -state->allocated_stack;
6169 
6170 	if (off < min_valid_off || off > -1)
6171 		return -EACCES;
6172 	return 0;
6173 }
6174 
6175 /* Check that the stack access at 'regno + off' falls within the maximum stack
6176  * bounds.
6177  *
6178  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6179  */
6180 static int check_stack_access_within_bounds(
6181 		struct bpf_verifier_env *env,
6182 		int regno, int off, int access_size,
6183 		enum bpf_access_src src, enum bpf_access_type type)
6184 {
6185 	struct bpf_reg_state *regs = cur_regs(env);
6186 	struct bpf_reg_state *reg = regs + regno;
6187 	struct bpf_func_state *state = func(env, reg);
6188 	int min_off, max_off;
6189 	int err;
6190 	char *err_extra;
6191 
6192 	if (src == ACCESS_HELPER)
6193 		/* We don't know if helpers are reading or writing (or both). */
6194 		err_extra = " indirect access to";
6195 	else if (type == BPF_READ)
6196 		err_extra = " read from";
6197 	else
6198 		err_extra = " write to";
6199 
6200 	if (tnum_is_const(reg->var_off)) {
6201 		min_off = reg->var_off.value + off;
6202 		if (access_size > 0)
6203 			max_off = min_off + access_size - 1;
6204 		else
6205 			max_off = min_off;
6206 	} else {
6207 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6208 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6209 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6210 				err_extra, regno);
6211 			return -EACCES;
6212 		}
6213 		min_off = reg->smin_value + off;
6214 		if (access_size > 0)
6215 			max_off = reg->smax_value + off + access_size - 1;
6216 		else
6217 			max_off = min_off;
6218 	}
6219 
6220 	err = check_stack_slot_within_bounds(min_off, state, type);
6221 	if (!err)
6222 		err = check_stack_slot_within_bounds(max_off, state, type);
6223 
6224 	if (err) {
6225 		if (tnum_is_const(reg->var_off)) {
6226 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6227 				err_extra, regno, off, access_size);
6228 		} else {
6229 			char tn_buf[48];
6230 
6231 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6232 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6233 				err_extra, regno, tn_buf, access_size);
6234 		}
6235 	}
6236 	return err;
6237 }
6238 
6239 /* check whether memory at (regno + off) is accessible for t = (read | write)
6240  * if t==write, value_regno is a register which value is stored into memory
6241  * if t==read, value_regno is a register which will receive the value from memory
6242  * if t==write && value_regno==-1, some unknown value is stored into memory
6243  * if t==read && value_regno==-1, don't care what we read from memory
6244  */
6245 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6246 			    int off, int bpf_size, enum bpf_access_type t,
6247 			    int value_regno, bool strict_alignment_once)
6248 {
6249 	struct bpf_reg_state *regs = cur_regs(env);
6250 	struct bpf_reg_state *reg = regs + regno;
6251 	struct bpf_func_state *state;
6252 	int size, err = 0;
6253 
6254 	size = bpf_size_to_bytes(bpf_size);
6255 	if (size < 0)
6256 		return size;
6257 
6258 	/* alignment checks will add in reg->off themselves */
6259 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6260 	if (err)
6261 		return err;
6262 
6263 	/* for access checks, reg->off is just part of off */
6264 	off += reg->off;
6265 
6266 	if (reg->type == PTR_TO_MAP_KEY) {
6267 		if (t == BPF_WRITE) {
6268 			verbose(env, "write to change key R%d not allowed\n", regno);
6269 			return -EACCES;
6270 		}
6271 
6272 		err = check_mem_region_access(env, regno, off, size,
6273 					      reg->map_ptr->key_size, false);
6274 		if (err)
6275 			return err;
6276 		if (value_regno >= 0)
6277 			mark_reg_unknown(env, regs, value_regno);
6278 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6279 		struct btf_field *kptr_field = NULL;
6280 
6281 		if (t == BPF_WRITE && value_regno >= 0 &&
6282 		    is_pointer_value(env, value_regno)) {
6283 			verbose(env, "R%d leaks addr into map\n", value_regno);
6284 			return -EACCES;
6285 		}
6286 		err = check_map_access_type(env, regno, off, size, t);
6287 		if (err)
6288 			return err;
6289 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6290 		if (err)
6291 			return err;
6292 		if (tnum_is_const(reg->var_off))
6293 			kptr_field = btf_record_find(reg->map_ptr->record,
6294 						     off + reg->var_off.value, BPF_KPTR);
6295 		if (kptr_field) {
6296 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6297 		} else if (t == BPF_READ && value_regno >= 0) {
6298 			struct bpf_map *map = reg->map_ptr;
6299 
6300 			/* if map is read-only, track its contents as scalars */
6301 			if (tnum_is_const(reg->var_off) &&
6302 			    bpf_map_is_rdonly(map) &&
6303 			    map->ops->map_direct_value_addr) {
6304 				int map_off = off + reg->var_off.value;
6305 				u64 val = 0;
6306 
6307 				err = bpf_map_direct_read(map, map_off, size,
6308 							  &val);
6309 				if (err)
6310 					return err;
6311 
6312 				regs[value_regno].type = SCALAR_VALUE;
6313 				__mark_reg_known(&regs[value_regno], val);
6314 			} else {
6315 				mark_reg_unknown(env, regs, value_regno);
6316 			}
6317 		}
6318 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6319 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6320 
6321 		if (type_may_be_null(reg->type)) {
6322 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6323 				reg_type_str(env, reg->type));
6324 			return -EACCES;
6325 		}
6326 
6327 		if (t == BPF_WRITE && rdonly_mem) {
6328 			verbose(env, "R%d cannot write into %s\n",
6329 				regno, reg_type_str(env, reg->type));
6330 			return -EACCES;
6331 		}
6332 
6333 		if (t == BPF_WRITE && value_regno >= 0 &&
6334 		    is_pointer_value(env, value_regno)) {
6335 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6336 			return -EACCES;
6337 		}
6338 
6339 		err = check_mem_region_access(env, regno, off, size,
6340 					      reg->mem_size, false);
6341 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6342 			mark_reg_unknown(env, regs, value_regno);
6343 	} else if (reg->type == PTR_TO_CTX) {
6344 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6345 		struct btf *btf = NULL;
6346 		u32 btf_id = 0;
6347 
6348 		if (t == BPF_WRITE && value_regno >= 0 &&
6349 		    is_pointer_value(env, value_regno)) {
6350 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6351 			return -EACCES;
6352 		}
6353 
6354 		err = check_ptr_off_reg(env, reg, regno);
6355 		if (err < 0)
6356 			return err;
6357 
6358 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6359 				       &btf_id);
6360 		if (err)
6361 			verbose_linfo(env, insn_idx, "; ");
6362 		if (!err && t == BPF_READ && value_regno >= 0) {
6363 			/* ctx access returns either a scalar, or a
6364 			 * PTR_TO_PACKET[_META,_END]. In the latter
6365 			 * case, we know the offset is zero.
6366 			 */
6367 			if (reg_type == SCALAR_VALUE) {
6368 				mark_reg_unknown(env, regs, value_regno);
6369 			} else {
6370 				mark_reg_known_zero(env, regs,
6371 						    value_regno);
6372 				if (type_may_be_null(reg_type))
6373 					regs[value_regno].id = ++env->id_gen;
6374 				/* A load of ctx field could have different
6375 				 * actual load size with the one encoded in the
6376 				 * insn. When the dst is PTR, it is for sure not
6377 				 * a sub-register.
6378 				 */
6379 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6380 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6381 					regs[value_regno].btf = btf;
6382 					regs[value_regno].btf_id = btf_id;
6383 				}
6384 			}
6385 			regs[value_regno].type = reg_type;
6386 		}
6387 
6388 	} else if (reg->type == PTR_TO_STACK) {
6389 		/* Basic bounds checks. */
6390 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6391 		if (err)
6392 			return err;
6393 
6394 		state = func(env, reg);
6395 		err = update_stack_depth(env, state, off);
6396 		if (err)
6397 			return err;
6398 
6399 		if (t == BPF_READ)
6400 			err = check_stack_read(env, regno, off, size,
6401 					       value_regno);
6402 		else
6403 			err = check_stack_write(env, regno, off, size,
6404 						value_regno, insn_idx);
6405 	} else if (reg_is_pkt_pointer(reg)) {
6406 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6407 			verbose(env, "cannot write into packet\n");
6408 			return -EACCES;
6409 		}
6410 		if (t == BPF_WRITE && value_regno >= 0 &&
6411 		    is_pointer_value(env, value_regno)) {
6412 			verbose(env, "R%d leaks addr into packet\n",
6413 				value_regno);
6414 			return -EACCES;
6415 		}
6416 		err = check_packet_access(env, regno, off, size, false);
6417 		if (!err && t == BPF_READ && value_regno >= 0)
6418 			mark_reg_unknown(env, regs, value_regno);
6419 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6420 		if (t == BPF_WRITE && value_regno >= 0 &&
6421 		    is_pointer_value(env, value_regno)) {
6422 			verbose(env, "R%d leaks addr into flow keys\n",
6423 				value_regno);
6424 			return -EACCES;
6425 		}
6426 
6427 		err = check_flow_keys_access(env, off, size);
6428 		if (!err && t == BPF_READ && value_regno >= 0)
6429 			mark_reg_unknown(env, regs, value_regno);
6430 	} else if (type_is_sk_pointer(reg->type)) {
6431 		if (t == BPF_WRITE) {
6432 			verbose(env, "R%d cannot write into %s\n",
6433 				regno, reg_type_str(env, reg->type));
6434 			return -EACCES;
6435 		}
6436 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6437 		if (!err && value_regno >= 0)
6438 			mark_reg_unknown(env, regs, value_regno);
6439 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6440 		err = check_tp_buffer_access(env, reg, regno, off, size);
6441 		if (!err && t == BPF_READ && value_regno >= 0)
6442 			mark_reg_unknown(env, regs, value_regno);
6443 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6444 		   !type_may_be_null(reg->type)) {
6445 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6446 					      value_regno);
6447 	} else if (reg->type == CONST_PTR_TO_MAP) {
6448 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6449 					      value_regno);
6450 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6451 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6452 		u32 *max_access;
6453 
6454 		if (rdonly_mem) {
6455 			if (t == BPF_WRITE) {
6456 				verbose(env, "R%d cannot write into %s\n",
6457 					regno, reg_type_str(env, reg->type));
6458 				return -EACCES;
6459 			}
6460 			max_access = &env->prog->aux->max_rdonly_access;
6461 		} else {
6462 			max_access = &env->prog->aux->max_rdwr_access;
6463 		}
6464 
6465 		err = check_buffer_access(env, reg, regno, off, size, false,
6466 					  max_access);
6467 
6468 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6469 			mark_reg_unknown(env, regs, value_regno);
6470 	} else {
6471 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6472 			reg_type_str(env, reg->type));
6473 		return -EACCES;
6474 	}
6475 
6476 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6477 	    regs[value_regno].type == SCALAR_VALUE) {
6478 		/* b/h/w load zero-extends, mark upper bits as known 0 */
6479 		coerce_reg_to_size(&regs[value_regno], size);
6480 	}
6481 	return err;
6482 }
6483 
6484 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6485 {
6486 	int load_reg;
6487 	int err;
6488 
6489 	switch (insn->imm) {
6490 	case BPF_ADD:
6491 	case BPF_ADD | BPF_FETCH:
6492 	case BPF_AND:
6493 	case BPF_AND | BPF_FETCH:
6494 	case BPF_OR:
6495 	case BPF_OR | BPF_FETCH:
6496 	case BPF_XOR:
6497 	case BPF_XOR | BPF_FETCH:
6498 	case BPF_XCHG:
6499 	case BPF_CMPXCHG:
6500 		break;
6501 	default:
6502 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6503 		return -EINVAL;
6504 	}
6505 
6506 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6507 		verbose(env, "invalid atomic operand size\n");
6508 		return -EINVAL;
6509 	}
6510 
6511 	/* check src1 operand */
6512 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6513 	if (err)
6514 		return err;
6515 
6516 	/* check src2 operand */
6517 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6518 	if (err)
6519 		return err;
6520 
6521 	if (insn->imm == BPF_CMPXCHG) {
6522 		/* Check comparison of R0 with memory location */
6523 		const u32 aux_reg = BPF_REG_0;
6524 
6525 		err = check_reg_arg(env, aux_reg, SRC_OP);
6526 		if (err)
6527 			return err;
6528 
6529 		if (is_pointer_value(env, aux_reg)) {
6530 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6531 			return -EACCES;
6532 		}
6533 	}
6534 
6535 	if (is_pointer_value(env, insn->src_reg)) {
6536 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6537 		return -EACCES;
6538 	}
6539 
6540 	if (is_ctx_reg(env, insn->dst_reg) ||
6541 	    is_pkt_reg(env, insn->dst_reg) ||
6542 	    is_flow_key_reg(env, insn->dst_reg) ||
6543 	    is_sk_reg(env, insn->dst_reg)) {
6544 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6545 			insn->dst_reg,
6546 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6547 		return -EACCES;
6548 	}
6549 
6550 	if (insn->imm & BPF_FETCH) {
6551 		if (insn->imm == BPF_CMPXCHG)
6552 			load_reg = BPF_REG_0;
6553 		else
6554 			load_reg = insn->src_reg;
6555 
6556 		/* check and record load of old value */
6557 		err = check_reg_arg(env, load_reg, DST_OP);
6558 		if (err)
6559 			return err;
6560 	} else {
6561 		/* This instruction accesses a memory location but doesn't
6562 		 * actually load it into a register.
6563 		 */
6564 		load_reg = -1;
6565 	}
6566 
6567 	/* Check whether we can read the memory, with second call for fetch
6568 	 * case to simulate the register fill.
6569 	 */
6570 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6571 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
6572 	if (!err && load_reg >= 0)
6573 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6574 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6575 				       true);
6576 	if (err)
6577 		return err;
6578 
6579 	/* Check whether we can write into the same memory. */
6580 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6581 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6582 	if (err)
6583 		return err;
6584 
6585 	return 0;
6586 }
6587 
6588 /* When register 'regno' is used to read the stack (either directly or through
6589  * a helper function) make sure that it's within stack boundary and, depending
6590  * on the access type, that all elements of the stack are initialized.
6591  *
6592  * 'off' includes 'regno->off', but not its dynamic part (if any).
6593  *
6594  * All registers that have been spilled on the stack in the slots within the
6595  * read offsets are marked as read.
6596  */
6597 static int check_stack_range_initialized(
6598 		struct bpf_verifier_env *env, int regno, int off,
6599 		int access_size, bool zero_size_allowed,
6600 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6601 {
6602 	struct bpf_reg_state *reg = reg_state(env, regno);
6603 	struct bpf_func_state *state = func(env, reg);
6604 	int err, min_off, max_off, i, j, slot, spi;
6605 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6606 	enum bpf_access_type bounds_check_type;
6607 	/* Some accesses can write anything into the stack, others are
6608 	 * read-only.
6609 	 */
6610 	bool clobber = false;
6611 
6612 	if (access_size == 0 && !zero_size_allowed) {
6613 		verbose(env, "invalid zero-sized read\n");
6614 		return -EACCES;
6615 	}
6616 
6617 	if (type == ACCESS_HELPER) {
6618 		/* The bounds checks for writes are more permissive than for
6619 		 * reads. However, if raw_mode is not set, we'll do extra
6620 		 * checks below.
6621 		 */
6622 		bounds_check_type = BPF_WRITE;
6623 		clobber = true;
6624 	} else {
6625 		bounds_check_type = BPF_READ;
6626 	}
6627 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6628 					       type, bounds_check_type);
6629 	if (err)
6630 		return err;
6631 
6632 
6633 	if (tnum_is_const(reg->var_off)) {
6634 		min_off = max_off = reg->var_off.value + off;
6635 	} else {
6636 		/* Variable offset is prohibited for unprivileged mode for
6637 		 * simplicity since it requires corresponding support in
6638 		 * Spectre masking for stack ALU.
6639 		 * See also retrieve_ptr_limit().
6640 		 */
6641 		if (!env->bypass_spec_v1) {
6642 			char tn_buf[48];
6643 
6644 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6645 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6646 				regno, err_extra, tn_buf);
6647 			return -EACCES;
6648 		}
6649 		/* Only initialized buffer on stack is allowed to be accessed
6650 		 * with variable offset. With uninitialized buffer it's hard to
6651 		 * guarantee that whole memory is marked as initialized on
6652 		 * helper return since specific bounds are unknown what may
6653 		 * cause uninitialized stack leaking.
6654 		 */
6655 		if (meta && meta->raw_mode)
6656 			meta = NULL;
6657 
6658 		min_off = reg->smin_value + off;
6659 		max_off = reg->smax_value + off;
6660 	}
6661 
6662 	if (meta && meta->raw_mode) {
6663 		/* Ensure we won't be overwriting dynptrs when simulating byte
6664 		 * by byte access in check_helper_call using meta.access_size.
6665 		 * This would be a problem if we have a helper in the future
6666 		 * which takes:
6667 		 *
6668 		 *	helper(uninit_mem, len, dynptr)
6669 		 *
6670 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6671 		 * may end up writing to dynptr itself when touching memory from
6672 		 * arg 1. This can be relaxed on a case by case basis for known
6673 		 * safe cases, but reject due to the possibilitiy of aliasing by
6674 		 * default.
6675 		 */
6676 		for (i = min_off; i < max_off + access_size; i++) {
6677 			int stack_off = -i - 1;
6678 
6679 			spi = __get_spi(i);
6680 			/* raw_mode may write past allocated_stack */
6681 			if (state->allocated_stack <= stack_off)
6682 				continue;
6683 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6684 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6685 				return -EACCES;
6686 			}
6687 		}
6688 		meta->access_size = access_size;
6689 		meta->regno = regno;
6690 		return 0;
6691 	}
6692 
6693 	for (i = min_off; i < max_off + access_size; i++) {
6694 		u8 *stype;
6695 
6696 		slot = -i - 1;
6697 		spi = slot / BPF_REG_SIZE;
6698 		if (state->allocated_stack <= slot)
6699 			goto err;
6700 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6701 		if (*stype == STACK_MISC)
6702 			goto mark;
6703 		if ((*stype == STACK_ZERO) ||
6704 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6705 			if (clobber) {
6706 				/* helper can write anything into the stack */
6707 				*stype = STACK_MISC;
6708 			}
6709 			goto mark;
6710 		}
6711 
6712 		if (is_spilled_reg(&state->stack[spi]) &&
6713 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6714 		     env->allow_ptr_leaks)) {
6715 			if (clobber) {
6716 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6717 				for (j = 0; j < BPF_REG_SIZE; j++)
6718 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6719 			}
6720 			goto mark;
6721 		}
6722 
6723 err:
6724 		if (tnum_is_const(reg->var_off)) {
6725 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6726 				err_extra, regno, min_off, i - min_off, access_size);
6727 		} else {
6728 			char tn_buf[48];
6729 
6730 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6731 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6732 				err_extra, regno, tn_buf, i - min_off, access_size);
6733 		}
6734 		return -EACCES;
6735 mark:
6736 		/* reading any byte out of 8-byte 'spill_slot' will cause
6737 		 * the whole slot to be marked as 'read'
6738 		 */
6739 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6740 			      state->stack[spi].spilled_ptr.parent,
6741 			      REG_LIVE_READ64);
6742 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6743 		 * be sure that whether stack slot is written to or not. Hence,
6744 		 * we must still conservatively propagate reads upwards even if
6745 		 * helper may write to the entire memory range.
6746 		 */
6747 	}
6748 	return update_stack_depth(env, state, min_off);
6749 }
6750 
6751 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6752 				   int access_size, bool zero_size_allowed,
6753 				   struct bpf_call_arg_meta *meta)
6754 {
6755 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6756 	u32 *max_access;
6757 
6758 	switch (base_type(reg->type)) {
6759 	case PTR_TO_PACKET:
6760 	case PTR_TO_PACKET_META:
6761 		return check_packet_access(env, regno, reg->off, access_size,
6762 					   zero_size_allowed);
6763 	case PTR_TO_MAP_KEY:
6764 		if (meta && meta->raw_mode) {
6765 			verbose(env, "R%d cannot write into %s\n", regno,
6766 				reg_type_str(env, reg->type));
6767 			return -EACCES;
6768 		}
6769 		return check_mem_region_access(env, regno, reg->off, access_size,
6770 					       reg->map_ptr->key_size, false);
6771 	case PTR_TO_MAP_VALUE:
6772 		if (check_map_access_type(env, regno, reg->off, access_size,
6773 					  meta && meta->raw_mode ? BPF_WRITE :
6774 					  BPF_READ))
6775 			return -EACCES;
6776 		return check_map_access(env, regno, reg->off, access_size,
6777 					zero_size_allowed, ACCESS_HELPER);
6778 	case PTR_TO_MEM:
6779 		if (type_is_rdonly_mem(reg->type)) {
6780 			if (meta && meta->raw_mode) {
6781 				verbose(env, "R%d cannot write into %s\n", regno,
6782 					reg_type_str(env, reg->type));
6783 				return -EACCES;
6784 			}
6785 		}
6786 		return check_mem_region_access(env, regno, reg->off,
6787 					       access_size, reg->mem_size,
6788 					       zero_size_allowed);
6789 	case PTR_TO_BUF:
6790 		if (type_is_rdonly_mem(reg->type)) {
6791 			if (meta && meta->raw_mode) {
6792 				verbose(env, "R%d cannot write into %s\n", regno,
6793 					reg_type_str(env, reg->type));
6794 				return -EACCES;
6795 			}
6796 
6797 			max_access = &env->prog->aux->max_rdonly_access;
6798 		} else {
6799 			max_access = &env->prog->aux->max_rdwr_access;
6800 		}
6801 		return check_buffer_access(env, reg, regno, reg->off,
6802 					   access_size, zero_size_allowed,
6803 					   max_access);
6804 	case PTR_TO_STACK:
6805 		return check_stack_range_initialized(
6806 				env,
6807 				regno, reg->off, access_size,
6808 				zero_size_allowed, ACCESS_HELPER, meta);
6809 	case PTR_TO_BTF_ID:
6810 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
6811 					       access_size, BPF_READ, -1);
6812 	case PTR_TO_CTX:
6813 		/* in case the function doesn't know how to access the context,
6814 		 * (because we are in a program of type SYSCALL for example), we
6815 		 * can not statically check its size.
6816 		 * Dynamically check it now.
6817 		 */
6818 		if (!env->ops->convert_ctx_access) {
6819 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6820 			int offset = access_size - 1;
6821 
6822 			/* Allow zero-byte read from PTR_TO_CTX */
6823 			if (access_size == 0)
6824 				return zero_size_allowed ? 0 : -EACCES;
6825 
6826 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6827 						atype, -1, false);
6828 		}
6829 
6830 		fallthrough;
6831 	default: /* scalar_value or invalid ptr */
6832 		/* Allow zero-byte read from NULL, regardless of pointer type */
6833 		if (zero_size_allowed && access_size == 0 &&
6834 		    register_is_null(reg))
6835 			return 0;
6836 
6837 		verbose(env, "R%d type=%s ", regno,
6838 			reg_type_str(env, reg->type));
6839 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6840 		return -EACCES;
6841 	}
6842 }
6843 
6844 static int check_mem_size_reg(struct bpf_verifier_env *env,
6845 			      struct bpf_reg_state *reg, u32 regno,
6846 			      bool zero_size_allowed,
6847 			      struct bpf_call_arg_meta *meta)
6848 {
6849 	int err;
6850 
6851 	/* This is used to refine r0 return value bounds for helpers
6852 	 * that enforce this value as an upper bound on return values.
6853 	 * See do_refine_retval_range() for helpers that can refine
6854 	 * the return value. C type of helper is u32 so we pull register
6855 	 * bound from umax_value however, if negative verifier errors
6856 	 * out. Only upper bounds can be learned because retval is an
6857 	 * int type and negative retvals are allowed.
6858 	 */
6859 	meta->msize_max_value = reg->umax_value;
6860 
6861 	/* The register is SCALAR_VALUE; the access check
6862 	 * happens using its boundaries.
6863 	 */
6864 	if (!tnum_is_const(reg->var_off))
6865 		/* For unprivileged variable accesses, disable raw
6866 		 * mode so that the program is required to
6867 		 * initialize all the memory that the helper could
6868 		 * just partially fill up.
6869 		 */
6870 		meta = NULL;
6871 
6872 	if (reg->smin_value < 0) {
6873 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6874 			regno);
6875 		return -EACCES;
6876 	}
6877 
6878 	if (reg->umin_value == 0) {
6879 		err = check_helper_mem_access(env, regno - 1, 0,
6880 					      zero_size_allowed,
6881 					      meta);
6882 		if (err)
6883 			return err;
6884 	}
6885 
6886 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6887 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6888 			regno);
6889 		return -EACCES;
6890 	}
6891 	err = check_helper_mem_access(env, regno - 1,
6892 				      reg->umax_value,
6893 				      zero_size_allowed, meta);
6894 	if (!err)
6895 		err = mark_chain_precision(env, regno);
6896 	return err;
6897 }
6898 
6899 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6900 		   u32 regno, u32 mem_size)
6901 {
6902 	bool may_be_null = type_may_be_null(reg->type);
6903 	struct bpf_reg_state saved_reg;
6904 	struct bpf_call_arg_meta meta;
6905 	int err;
6906 
6907 	if (register_is_null(reg))
6908 		return 0;
6909 
6910 	memset(&meta, 0, sizeof(meta));
6911 	/* Assuming that the register contains a value check if the memory
6912 	 * access is safe. Temporarily save and restore the register's state as
6913 	 * the conversion shouldn't be visible to a caller.
6914 	 */
6915 	if (may_be_null) {
6916 		saved_reg = *reg;
6917 		mark_ptr_not_null_reg(reg);
6918 	}
6919 
6920 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6921 	/* Check access for BPF_WRITE */
6922 	meta.raw_mode = true;
6923 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6924 
6925 	if (may_be_null)
6926 		*reg = saved_reg;
6927 
6928 	return err;
6929 }
6930 
6931 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6932 				    u32 regno)
6933 {
6934 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6935 	bool may_be_null = type_may_be_null(mem_reg->type);
6936 	struct bpf_reg_state saved_reg;
6937 	struct bpf_call_arg_meta meta;
6938 	int err;
6939 
6940 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6941 
6942 	memset(&meta, 0, sizeof(meta));
6943 
6944 	if (may_be_null) {
6945 		saved_reg = *mem_reg;
6946 		mark_ptr_not_null_reg(mem_reg);
6947 	}
6948 
6949 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6950 	/* Check access for BPF_WRITE */
6951 	meta.raw_mode = true;
6952 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6953 
6954 	if (may_be_null)
6955 		*mem_reg = saved_reg;
6956 	return err;
6957 }
6958 
6959 /* Implementation details:
6960  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6961  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6962  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6963  * Two separate bpf_obj_new will also have different reg->id.
6964  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6965  * clears reg->id after value_or_null->value transition, since the verifier only
6966  * cares about the range of access to valid map value pointer and doesn't care
6967  * about actual address of the map element.
6968  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6969  * reg->id > 0 after value_or_null->value transition. By doing so
6970  * two bpf_map_lookups will be considered two different pointers that
6971  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6972  * returned from bpf_obj_new.
6973  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6974  * dead-locks.
6975  * Since only one bpf_spin_lock is allowed the checks are simpler than
6976  * reg_is_refcounted() logic. The verifier needs to remember only
6977  * one spin_lock instead of array of acquired_refs.
6978  * cur_state->active_lock remembers which map value element or allocated
6979  * object got locked and clears it after bpf_spin_unlock.
6980  */
6981 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6982 			     bool is_lock)
6983 {
6984 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6985 	struct bpf_verifier_state *cur = env->cur_state;
6986 	bool is_const = tnum_is_const(reg->var_off);
6987 	u64 val = reg->var_off.value;
6988 	struct bpf_map *map = NULL;
6989 	struct btf *btf = NULL;
6990 	struct btf_record *rec;
6991 
6992 	if (!is_const) {
6993 		verbose(env,
6994 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6995 			regno);
6996 		return -EINVAL;
6997 	}
6998 	if (reg->type == PTR_TO_MAP_VALUE) {
6999 		map = reg->map_ptr;
7000 		if (!map->btf) {
7001 			verbose(env,
7002 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7003 				map->name);
7004 			return -EINVAL;
7005 		}
7006 	} else {
7007 		btf = reg->btf;
7008 	}
7009 
7010 	rec = reg_btf_record(reg);
7011 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7012 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7013 			map ? map->name : "kptr");
7014 		return -EINVAL;
7015 	}
7016 	if (rec->spin_lock_off != val + reg->off) {
7017 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7018 			val + reg->off, rec->spin_lock_off);
7019 		return -EINVAL;
7020 	}
7021 	if (is_lock) {
7022 		if (cur->active_lock.ptr) {
7023 			verbose(env,
7024 				"Locking two bpf_spin_locks are not allowed\n");
7025 			return -EINVAL;
7026 		}
7027 		if (map)
7028 			cur->active_lock.ptr = map;
7029 		else
7030 			cur->active_lock.ptr = btf;
7031 		cur->active_lock.id = reg->id;
7032 	} else {
7033 		void *ptr;
7034 
7035 		if (map)
7036 			ptr = map;
7037 		else
7038 			ptr = btf;
7039 
7040 		if (!cur->active_lock.ptr) {
7041 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7042 			return -EINVAL;
7043 		}
7044 		if (cur->active_lock.ptr != ptr ||
7045 		    cur->active_lock.id != reg->id) {
7046 			verbose(env, "bpf_spin_unlock of different lock\n");
7047 			return -EINVAL;
7048 		}
7049 
7050 		invalidate_non_owning_refs(env);
7051 
7052 		cur->active_lock.ptr = NULL;
7053 		cur->active_lock.id = 0;
7054 	}
7055 	return 0;
7056 }
7057 
7058 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7059 			      struct bpf_call_arg_meta *meta)
7060 {
7061 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7062 	bool is_const = tnum_is_const(reg->var_off);
7063 	struct bpf_map *map = reg->map_ptr;
7064 	u64 val = reg->var_off.value;
7065 
7066 	if (!is_const) {
7067 		verbose(env,
7068 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7069 			regno);
7070 		return -EINVAL;
7071 	}
7072 	if (!map->btf) {
7073 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7074 			map->name);
7075 		return -EINVAL;
7076 	}
7077 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7078 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7079 		return -EINVAL;
7080 	}
7081 	if (map->record->timer_off != val + reg->off) {
7082 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7083 			val + reg->off, map->record->timer_off);
7084 		return -EINVAL;
7085 	}
7086 	if (meta->map_ptr) {
7087 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7088 		return -EFAULT;
7089 	}
7090 	meta->map_uid = reg->map_uid;
7091 	meta->map_ptr = map;
7092 	return 0;
7093 }
7094 
7095 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7096 			     struct bpf_call_arg_meta *meta)
7097 {
7098 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7099 	struct bpf_map *map_ptr = reg->map_ptr;
7100 	struct btf_field *kptr_field;
7101 	u32 kptr_off;
7102 
7103 	if (!tnum_is_const(reg->var_off)) {
7104 		verbose(env,
7105 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7106 			regno);
7107 		return -EINVAL;
7108 	}
7109 	if (!map_ptr->btf) {
7110 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7111 			map_ptr->name);
7112 		return -EINVAL;
7113 	}
7114 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7115 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7116 		return -EINVAL;
7117 	}
7118 
7119 	meta->map_ptr = map_ptr;
7120 	kptr_off = reg->off + reg->var_off.value;
7121 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7122 	if (!kptr_field) {
7123 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7124 		return -EACCES;
7125 	}
7126 	if (kptr_field->type != BPF_KPTR_REF) {
7127 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7128 		return -EACCES;
7129 	}
7130 	meta->kptr_field = kptr_field;
7131 	return 0;
7132 }
7133 
7134 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7135  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7136  *
7137  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7138  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7139  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7140  *
7141  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7142  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7143  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7144  * mutate the view of the dynptr and also possibly destroy it. In the latter
7145  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7146  * memory that dynptr points to.
7147  *
7148  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7149  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7150  * readonly dynptr view yet, hence only the first case is tracked and checked.
7151  *
7152  * This is consistent with how C applies the const modifier to a struct object,
7153  * where the pointer itself inside bpf_dynptr becomes const but not what it
7154  * points to.
7155  *
7156  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7157  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7158  */
7159 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7160 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7161 {
7162 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7163 	int err;
7164 
7165 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7166 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7167 	 */
7168 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7169 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7170 		return -EFAULT;
7171 	}
7172 
7173 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7174 	 *		 constructing a mutable bpf_dynptr object.
7175 	 *
7176 	 *		 Currently, this is only possible with PTR_TO_STACK
7177 	 *		 pointing to a region of at least 16 bytes which doesn't
7178 	 *		 contain an existing bpf_dynptr.
7179 	 *
7180 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7181 	 *		 mutated or destroyed. However, the memory it points to
7182 	 *		 may be mutated.
7183 	 *
7184 	 *  None       - Points to a initialized dynptr that can be mutated and
7185 	 *		 destroyed, including mutation of the memory it points
7186 	 *		 to.
7187 	 */
7188 	if (arg_type & MEM_UNINIT) {
7189 		int i;
7190 
7191 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7192 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7193 			return -EINVAL;
7194 		}
7195 
7196 		/* we write BPF_DW bits (8 bytes) at a time */
7197 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7198 			err = check_mem_access(env, insn_idx, regno,
7199 					       i, BPF_DW, BPF_WRITE, -1, false);
7200 			if (err)
7201 				return err;
7202 		}
7203 
7204 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7205 	} else /* MEM_RDONLY and None case from above */ {
7206 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7207 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7208 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7209 			return -EINVAL;
7210 		}
7211 
7212 		if (!is_dynptr_reg_valid_init(env, reg)) {
7213 			verbose(env,
7214 				"Expected an initialized dynptr as arg #%d\n",
7215 				regno);
7216 			return -EINVAL;
7217 		}
7218 
7219 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7220 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7221 			verbose(env,
7222 				"Expected a dynptr of type %s as arg #%d\n",
7223 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7224 			return -EINVAL;
7225 		}
7226 
7227 		err = mark_dynptr_read(env, reg);
7228 	}
7229 	return err;
7230 }
7231 
7232 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7233 {
7234 	struct bpf_func_state *state = func(env, reg);
7235 
7236 	return state->stack[spi].spilled_ptr.ref_obj_id;
7237 }
7238 
7239 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7240 {
7241 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7242 }
7243 
7244 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7245 {
7246 	return meta->kfunc_flags & KF_ITER_NEW;
7247 }
7248 
7249 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7250 {
7251 	return meta->kfunc_flags & KF_ITER_NEXT;
7252 }
7253 
7254 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7255 {
7256 	return meta->kfunc_flags & KF_ITER_DESTROY;
7257 }
7258 
7259 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7260 {
7261 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7262 	 * kfunc is iter state pointer
7263 	 */
7264 	return arg == 0 && is_iter_kfunc(meta);
7265 }
7266 
7267 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7268 			    struct bpf_kfunc_call_arg_meta *meta)
7269 {
7270 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7271 	const struct btf_type *t;
7272 	const struct btf_param *arg;
7273 	int spi, err, i, nr_slots;
7274 	u32 btf_id;
7275 
7276 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7277 	arg = &btf_params(meta->func_proto)[0];
7278 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7279 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7280 	nr_slots = t->size / BPF_REG_SIZE;
7281 
7282 	if (is_iter_new_kfunc(meta)) {
7283 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7284 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7285 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7286 				iter_type_str(meta->btf, btf_id), regno);
7287 			return -EINVAL;
7288 		}
7289 
7290 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7291 			err = check_mem_access(env, insn_idx, regno,
7292 					       i, BPF_DW, BPF_WRITE, -1, false);
7293 			if (err)
7294 				return err;
7295 		}
7296 
7297 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7298 		if (err)
7299 			return err;
7300 	} else {
7301 		/* iter_next() or iter_destroy() expect initialized iter state*/
7302 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7303 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7304 				iter_type_str(meta->btf, btf_id), regno);
7305 			return -EINVAL;
7306 		}
7307 
7308 		spi = iter_get_spi(env, reg, nr_slots);
7309 		if (spi < 0)
7310 			return spi;
7311 
7312 		err = mark_iter_read(env, reg, spi, nr_slots);
7313 		if (err)
7314 			return err;
7315 
7316 		/* remember meta->iter info for process_iter_next_call() */
7317 		meta->iter.spi = spi;
7318 		meta->iter.frameno = reg->frameno;
7319 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7320 
7321 		if (is_iter_destroy_kfunc(meta)) {
7322 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7323 			if (err)
7324 				return err;
7325 		}
7326 	}
7327 
7328 	return 0;
7329 }
7330 
7331 /* process_iter_next_call() is called when verifier gets to iterator's next
7332  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7333  * to it as just "iter_next()" in comments below.
7334  *
7335  * BPF verifier relies on a crucial contract for any iter_next()
7336  * implementation: it should *eventually* return NULL, and once that happens
7337  * it should keep returning NULL. That is, once iterator exhausts elements to
7338  * iterate, it should never reset or spuriously return new elements.
7339  *
7340  * With the assumption of such contract, process_iter_next_call() simulates
7341  * a fork in the verifier state to validate loop logic correctness and safety
7342  * without having to simulate infinite amount of iterations.
7343  *
7344  * In current state, we first assume that iter_next() returned NULL and
7345  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7346  * conditions we should not form an infinite loop and should eventually reach
7347  * exit.
7348  *
7349  * Besides that, we also fork current state and enqueue it for later
7350  * verification. In a forked state we keep iterator state as ACTIVE
7351  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7352  * also bump iteration depth to prevent erroneous infinite loop detection
7353  * later on (see iter_active_depths_differ() comment for details). In this
7354  * state we assume that we'll eventually loop back to another iter_next()
7355  * calls (it could be in exactly same location or in some other instruction,
7356  * it doesn't matter, we don't make any unnecessary assumptions about this,
7357  * everything revolves around iterator state in a stack slot, not which
7358  * instruction is calling iter_next()). When that happens, we either will come
7359  * to iter_next() with equivalent state and can conclude that next iteration
7360  * will proceed in exactly the same way as we just verified, so it's safe to
7361  * assume that loop converges. If not, we'll go on another iteration
7362  * simulation with a different input state, until all possible starting states
7363  * are validated or we reach maximum number of instructions limit.
7364  *
7365  * This way, we will either exhaustively discover all possible input states
7366  * that iterator loop can start with and eventually will converge, or we'll
7367  * effectively regress into bounded loop simulation logic and either reach
7368  * maximum number of instructions if loop is not provably convergent, or there
7369  * is some statically known limit on number of iterations (e.g., if there is
7370  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7371  *
7372  * One very subtle but very important aspect is that we *always* simulate NULL
7373  * condition first (as the current state) before we simulate non-NULL case.
7374  * This has to do with intricacies of scalar precision tracking. By simulating
7375  * "exit condition" of iter_next() returning NULL first, we make sure all the
7376  * relevant precision marks *that will be set **after** we exit iterator loop*
7377  * are propagated backwards to common parent state of NULL and non-NULL
7378  * branches. Thanks to that, state equivalence checks done later in forked
7379  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7380  * precision marks are finalized and won't change. Because simulating another
7381  * ACTIVE iterator iteration won't change them (because given same input
7382  * states we'll end up with exactly same output states which we are currently
7383  * comparing; and verification after the loop already propagated back what
7384  * needs to be **additionally** tracked as precise). It's subtle, grok
7385  * precision tracking for more intuitive understanding.
7386  */
7387 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7388 				  struct bpf_kfunc_call_arg_meta *meta)
7389 {
7390 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7391 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7392 	struct bpf_reg_state *cur_iter, *queued_iter;
7393 	int iter_frameno = meta->iter.frameno;
7394 	int iter_spi = meta->iter.spi;
7395 
7396 	BTF_TYPE_EMIT(struct bpf_iter);
7397 
7398 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7399 
7400 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7401 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7402 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7403 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7404 		return -EFAULT;
7405 	}
7406 
7407 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7408 		/* branch out active iter state */
7409 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7410 		if (!queued_st)
7411 			return -ENOMEM;
7412 
7413 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7414 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7415 		queued_iter->iter.depth++;
7416 
7417 		queued_fr = queued_st->frame[queued_st->curframe];
7418 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7419 	}
7420 
7421 	/* switch to DRAINED state, but keep the depth unchanged */
7422 	/* mark current iter state as drained and assume returned NULL */
7423 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7424 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7425 
7426 	return 0;
7427 }
7428 
7429 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7430 {
7431 	return type == ARG_CONST_SIZE ||
7432 	       type == ARG_CONST_SIZE_OR_ZERO;
7433 }
7434 
7435 static bool arg_type_is_release(enum bpf_arg_type type)
7436 {
7437 	return type & OBJ_RELEASE;
7438 }
7439 
7440 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7441 {
7442 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7443 }
7444 
7445 static int int_ptr_type_to_size(enum bpf_arg_type type)
7446 {
7447 	if (type == ARG_PTR_TO_INT)
7448 		return sizeof(u32);
7449 	else if (type == ARG_PTR_TO_LONG)
7450 		return sizeof(u64);
7451 
7452 	return -EINVAL;
7453 }
7454 
7455 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7456 				 const struct bpf_call_arg_meta *meta,
7457 				 enum bpf_arg_type *arg_type)
7458 {
7459 	if (!meta->map_ptr) {
7460 		/* kernel subsystem misconfigured verifier */
7461 		verbose(env, "invalid map_ptr to access map->type\n");
7462 		return -EACCES;
7463 	}
7464 
7465 	switch (meta->map_ptr->map_type) {
7466 	case BPF_MAP_TYPE_SOCKMAP:
7467 	case BPF_MAP_TYPE_SOCKHASH:
7468 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7469 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7470 		} else {
7471 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7472 			return -EINVAL;
7473 		}
7474 		break;
7475 	case BPF_MAP_TYPE_BLOOM_FILTER:
7476 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7477 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7478 		break;
7479 	default:
7480 		break;
7481 	}
7482 	return 0;
7483 }
7484 
7485 struct bpf_reg_types {
7486 	const enum bpf_reg_type types[10];
7487 	u32 *btf_id;
7488 };
7489 
7490 static const struct bpf_reg_types sock_types = {
7491 	.types = {
7492 		PTR_TO_SOCK_COMMON,
7493 		PTR_TO_SOCKET,
7494 		PTR_TO_TCP_SOCK,
7495 		PTR_TO_XDP_SOCK,
7496 	},
7497 };
7498 
7499 #ifdef CONFIG_NET
7500 static const struct bpf_reg_types btf_id_sock_common_types = {
7501 	.types = {
7502 		PTR_TO_SOCK_COMMON,
7503 		PTR_TO_SOCKET,
7504 		PTR_TO_TCP_SOCK,
7505 		PTR_TO_XDP_SOCK,
7506 		PTR_TO_BTF_ID,
7507 		PTR_TO_BTF_ID | PTR_TRUSTED,
7508 	},
7509 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7510 };
7511 #endif
7512 
7513 static const struct bpf_reg_types mem_types = {
7514 	.types = {
7515 		PTR_TO_STACK,
7516 		PTR_TO_PACKET,
7517 		PTR_TO_PACKET_META,
7518 		PTR_TO_MAP_KEY,
7519 		PTR_TO_MAP_VALUE,
7520 		PTR_TO_MEM,
7521 		PTR_TO_MEM | MEM_RINGBUF,
7522 		PTR_TO_BUF,
7523 		PTR_TO_BTF_ID | PTR_TRUSTED,
7524 	},
7525 };
7526 
7527 static const struct bpf_reg_types int_ptr_types = {
7528 	.types = {
7529 		PTR_TO_STACK,
7530 		PTR_TO_PACKET,
7531 		PTR_TO_PACKET_META,
7532 		PTR_TO_MAP_KEY,
7533 		PTR_TO_MAP_VALUE,
7534 	},
7535 };
7536 
7537 static const struct bpf_reg_types spin_lock_types = {
7538 	.types = {
7539 		PTR_TO_MAP_VALUE,
7540 		PTR_TO_BTF_ID | MEM_ALLOC,
7541 	}
7542 };
7543 
7544 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7545 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7546 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7547 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7548 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7549 static const struct bpf_reg_types btf_ptr_types = {
7550 	.types = {
7551 		PTR_TO_BTF_ID,
7552 		PTR_TO_BTF_ID | PTR_TRUSTED,
7553 		PTR_TO_BTF_ID | MEM_RCU,
7554 	},
7555 };
7556 static const struct bpf_reg_types percpu_btf_ptr_types = {
7557 	.types = {
7558 		PTR_TO_BTF_ID | MEM_PERCPU,
7559 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7560 	}
7561 };
7562 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7563 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7564 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7565 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7566 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7567 static const struct bpf_reg_types dynptr_types = {
7568 	.types = {
7569 		PTR_TO_STACK,
7570 		CONST_PTR_TO_DYNPTR,
7571 	}
7572 };
7573 
7574 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7575 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7576 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7577 	[ARG_CONST_SIZE]		= &scalar_types,
7578 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7579 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7580 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7581 	[ARG_PTR_TO_CTX]		= &context_types,
7582 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7583 #ifdef CONFIG_NET
7584 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7585 #endif
7586 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7587 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7588 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7589 	[ARG_PTR_TO_MEM]		= &mem_types,
7590 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7591 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7592 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7593 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7594 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7595 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7596 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7597 	[ARG_PTR_TO_TIMER]		= &timer_types,
7598 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7599 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7600 };
7601 
7602 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7603 			  enum bpf_arg_type arg_type,
7604 			  const u32 *arg_btf_id,
7605 			  struct bpf_call_arg_meta *meta)
7606 {
7607 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7608 	enum bpf_reg_type expected, type = reg->type;
7609 	const struct bpf_reg_types *compatible;
7610 	int i, j;
7611 
7612 	compatible = compatible_reg_types[base_type(arg_type)];
7613 	if (!compatible) {
7614 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7615 		return -EFAULT;
7616 	}
7617 
7618 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7619 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7620 	 *
7621 	 * Same for MAYBE_NULL:
7622 	 *
7623 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7624 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7625 	 *
7626 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7627 	 *
7628 	 * Therefore we fold these flags depending on the arg_type before comparison.
7629 	 */
7630 	if (arg_type & MEM_RDONLY)
7631 		type &= ~MEM_RDONLY;
7632 	if (arg_type & PTR_MAYBE_NULL)
7633 		type &= ~PTR_MAYBE_NULL;
7634 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7635 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7636 
7637 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7638 		type &= ~MEM_ALLOC;
7639 
7640 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7641 		expected = compatible->types[i];
7642 		if (expected == NOT_INIT)
7643 			break;
7644 
7645 		if (type == expected)
7646 			goto found;
7647 	}
7648 
7649 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7650 	for (j = 0; j + 1 < i; j++)
7651 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7652 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7653 	return -EACCES;
7654 
7655 found:
7656 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7657 		return 0;
7658 
7659 	if (compatible == &mem_types) {
7660 		if (!(arg_type & MEM_RDONLY)) {
7661 			verbose(env,
7662 				"%s() may write into memory pointed by R%d type=%s\n",
7663 				func_id_name(meta->func_id),
7664 				regno, reg_type_str(env, reg->type));
7665 			return -EACCES;
7666 		}
7667 		return 0;
7668 	}
7669 
7670 	switch ((int)reg->type) {
7671 	case PTR_TO_BTF_ID:
7672 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7673 	case PTR_TO_BTF_ID | MEM_RCU:
7674 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7675 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7676 	{
7677 		/* For bpf_sk_release, it needs to match against first member
7678 		 * 'struct sock_common', hence make an exception for it. This
7679 		 * allows bpf_sk_release to work for multiple socket types.
7680 		 */
7681 		bool strict_type_match = arg_type_is_release(arg_type) &&
7682 					 meta->func_id != BPF_FUNC_sk_release;
7683 
7684 		if (type_may_be_null(reg->type) &&
7685 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7686 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7687 			return -EACCES;
7688 		}
7689 
7690 		if (!arg_btf_id) {
7691 			if (!compatible->btf_id) {
7692 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7693 				return -EFAULT;
7694 			}
7695 			arg_btf_id = compatible->btf_id;
7696 		}
7697 
7698 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7699 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7700 				return -EACCES;
7701 		} else {
7702 			if (arg_btf_id == BPF_PTR_POISON) {
7703 				verbose(env, "verifier internal error:");
7704 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7705 					regno);
7706 				return -EACCES;
7707 			}
7708 
7709 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7710 						  btf_vmlinux, *arg_btf_id,
7711 						  strict_type_match)) {
7712 				verbose(env, "R%d is of type %s but %s is expected\n",
7713 					regno, btf_type_name(reg->btf, reg->btf_id),
7714 					btf_type_name(btf_vmlinux, *arg_btf_id));
7715 				return -EACCES;
7716 			}
7717 		}
7718 		break;
7719 	}
7720 	case PTR_TO_BTF_ID | MEM_ALLOC:
7721 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7722 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7723 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7724 			return -EFAULT;
7725 		}
7726 		/* Handled by helper specific checks */
7727 		break;
7728 	case PTR_TO_BTF_ID | MEM_PERCPU:
7729 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7730 		/* Handled by helper specific checks */
7731 		break;
7732 	default:
7733 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7734 		return -EFAULT;
7735 	}
7736 	return 0;
7737 }
7738 
7739 static struct btf_field *
7740 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7741 {
7742 	struct btf_field *field;
7743 	struct btf_record *rec;
7744 
7745 	rec = reg_btf_record(reg);
7746 	if (!rec)
7747 		return NULL;
7748 
7749 	field = btf_record_find(rec, off, fields);
7750 	if (!field)
7751 		return NULL;
7752 
7753 	return field;
7754 }
7755 
7756 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7757 			   const struct bpf_reg_state *reg, int regno,
7758 			   enum bpf_arg_type arg_type)
7759 {
7760 	u32 type = reg->type;
7761 
7762 	/* When referenced register is passed to release function, its fixed
7763 	 * offset must be 0.
7764 	 *
7765 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7766 	 * meta->release_regno.
7767 	 */
7768 	if (arg_type_is_release(arg_type)) {
7769 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7770 		 * may not directly point to the object being released, but to
7771 		 * dynptr pointing to such object, which might be at some offset
7772 		 * on the stack. In that case, we simply to fallback to the
7773 		 * default handling.
7774 		 */
7775 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7776 			return 0;
7777 
7778 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7779 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7780 				return __check_ptr_off_reg(env, reg, regno, true);
7781 
7782 			verbose(env, "R%d must have zero offset when passed to release func\n",
7783 				regno);
7784 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7785 				btf_type_name(reg->btf, reg->btf_id), reg->off);
7786 			return -EINVAL;
7787 		}
7788 
7789 		/* Doing check_ptr_off_reg check for the offset will catch this
7790 		 * because fixed_off_ok is false, but checking here allows us
7791 		 * to give the user a better error message.
7792 		 */
7793 		if (reg->off) {
7794 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7795 				regno);
7796 			return -EINVAL;
7797 		}
7798 		return __check_ptr_off_reg(env, reg, regno, false);
7799 	}
7800 
7801 	switch (type) {
7802 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7803 	case PTR_TO_STACK:
7804 	case PTR_TO_PACKET:
7805 	case PTR_TO_PACKET_META:
7806 	case PTR_TO_MAP_KEY:
7807 	case PTR_TO_MAP_VALUE:
7808 	case PTR_TO_MEM:
7809 	case PTR_TO_MEM | MEM_RDONLY:
7810 	case PTR_TO_MEM | MEM_RINGBUF:
7811 	case PTR_TO_BUF:
7812 	case PTR_TO_BUF | MEM_RDONLY:
7813 	case SCALAR_VALUE:
7814 		return 0;
7815 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7816 	 * fixed offset.
7817 	 */
7818 	case PTR_TO_BTF_ID:
7819 	case PTR_TO_BTF_ID | MEM_ALLOC:
7820 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7821 	case PTR_TO_BTF_ID | MEM_RCU:
7822 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7823 		/* When referenced PTR_TO_BTF_ID is passed to release function,
7824 		 * its fixed offset must be 0. In the other cases, fixed offset
7825 		 * can be non-zero. This was already checked above. So pass
7826 		 * fixed_off_ok as true to allow fixed offset for all other
7827 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7828 		 * still need to do checks instead of returning.
7829 		 */
7830 		return __check_ptr_off_reg(env, reg, regno, true);
7831 	default:
7832 		return __check_ptr_off_reg(env, reg, regno, false);
7833 	}
7834 }
7835 
7836 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7837 						const struct bpf_func_proto *fn,
7838 						struct bpf_reg_state *regs)
7839 {
7840 	struct bpf_reg_state *state = NULL;
7841 	int i;
7842 
7843 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7844 		if (arg_type_is_dynptr(fn->arg_type[i])) {
7845 			if (state) {
7846 				verbose(env, "verifier internal error: multiple dynptr args\n");
7847 				return NULL;
7848 			}
7849 			state = &regs[BPF_REG_1 + i];
7850 		}
7851 
7852 	if (!state)
7853 		verbose(env, "verifier internal error: no dynptr arg found\n");
7854 
7855 	return state;
7856 }
7857 
7858 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7859 {
7860 	struct bpf_func_state *state = func(env, reg);
7861 	int spi;
7862 
7863 	if (reg->type == CONST_PTR_TO_DYNPTR)
7864 		return reg->id;
7865 	spi = dynptr_get_spi(env, reg);
7866 	if (spi < 0)
7867 		return spi;
7868 	return state->stack[spi].spilled_ptr.id;
7869 }
7870 
7871 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7872 {
7873 	struct bpf_func_state *state = func(env, reg);
7874 	int spi;
7875 
7876 	if (reg->type == CONST_PTR_TO_DYNPTR)
7877 		return reg->ref_obj_id;
7878 	spi = dynptr_get_spi(env, reg);
7879 	if (spi < 0)
7880 		return spi;
7881 	return state->stack[spi].spilled_ptr.ref_obj_id;
7882 }
7883 
7884 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7885 					    struct bpf_reg_state *reg)
7886 {
7887 	struct bpf_func_state *state = func(env, reg);
7888 	int spi;
7889 
7890 	if (reg->type == CONST_PTR_TO_DYNPTR)
7891 		return reg->dynptr.type;
7892 
7893 	spi = __get_spi(reg->off);
7894 	if (spi < 0) {
7895 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7896 		return BPF_DYNPTR_TYPE_INVALID;
7897 	}
7898 
7899 	return state->stack[spi].spilled_ptr.dynptr.type;
7900 }
7901 
7902 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7903 			  struct bpf_call_arg_meta *meta,
7904 			  const struct bpf_func_proto *fn,
7905 			  int insn_idx)
7906 {
7907 	u32 regno = BPF_REG_1 + arg;
7908 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7909 	enum bpf_arg_type arg_type = fn->arg_type[arg];
7910 	enum bpf_reg_type type = reg->type;
7911 	u32 *arg_btf_id = NULL;
7912 	int err = 0;
7913 
7914 	if (arg_type == ARG_DONTCARE)
7915 		return 0;
7916 
7917 	err = check_reg_arg(env, regno, SRC_OP);
7918 	if (err)
7919 		return err;
7920 
7921 	if (arg_type == ARG_ANYTHING) {
7922 		if (is_pointer_value(env, regno)) {
7923 			verbose(env, "R%d leaks addr into helper function\n",
7924 				regno);
7925 			return -EACCES;
7926 		}
7927 		return 0;
7928 	}
7929 
7930 	if (type_is_pkt_pointer(type) &&
7931 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7932 		verbose(env, "helper access to the packet is not allowed\n");
7933 		return -EACCES;
7934 	}
7935 
7936 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7937 		err = resolve_map_arg_type(env, meta, &arg_type);
7938 		if (err)
7939 			return err;
7940 	}
7941 
7942 	if (register_is_null(reg) && type_may_be_null(arg_type))
7943 		/* A NULL register has a SCALAR_VALUE type, so skip
7944 		 * type checking.
7945 		 */
7946 		goto skip_type_check;
7947 
7948 	/* arg_btf_id and arg_size are in a union. */
7949 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7950 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7951 		arg_btf_id = fn->arg_btf_id[arg];
7952 
7953 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7954 	if (err)
7955 		return err;
7956 
7957 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7958 	if (err)
7959 		return err;
7960 
7961 skip_type_check:
7962 	if (arg_type_is_release(arg_type)) {
7963 		if (arg_type_is_dynptr(arg_type)) {
7964 			struct bpf_func_state *state = func(env, reg);
7965 			int spi;
7966 
7967 			/* Only dynptr created on stack can be released, thus
7968 			 * the get_spi and stack state checks for spilled_ptr
7969 			 * should only be done before process_dynptr_func for
7970 			 * PTR_TO_STACK.
7971 			 */
7972 			if (reg->type == PTR_TO_STACK) {
7973 				spi = dynptr_get_spi(env, reg);
7974 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7975 					verbose(env, "arg %d is an unacquired reference\n", regno);
7976 					return -EINVAL;
7977 				}
7978 			} else {
7979 				verbose(env, "cannot release unowned const bpf_dynptr\n");
7980 				return -EINVAL;
7981 			}
7982 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
7983 			verbose(env, "R%d must be referenced when passed to release function\n",
7984 				regno);
7985 			return -EINVAL;
7986 		}
7987 		if (meta->release_regno) {
7988 			verbose(env, "verifier internal error: more than one release argument\n");
7989 			return -EFAULT;
7990 		}
7991 		meta->release_regno = regno;
7992 	}
7993 
7994 	if (reg->ref_obj_id) {
7995 		if (meta->ref_obj_id) {
7996 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7997 				regno, reg->ref_obj_id,
7998 				meta->ref_obj_id);
7999 			return -EFAULT;
8000 		}
8001 		meta->ref_obj_id = reg->ref_obj_id;
8002 	}
8003 
8004 	switch (base_type(arg_type)) {
8005 	case ARG_CONST_MAP_PTR:
8006 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8007 		if (meta->map_ptr) {
8008 			/* Use map_uid (which is unique id of inner map) to reject:
8009 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8010 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8011 			 * if (inner_map1 && inner_map2) {
8012 			 *     timer = bpf_map_lookup_elem(inner_map1);
8013 			 *     if (timer)
8014 			 *         // mismatch would have been allowed
8015 			 *         bpf_timer_init(timer, inner_map2);
8016 			 * }
8017 			 *
8018 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8019 			 */
8020 			if (meta->map_ptr != reg->map_ptr ||
8021 			    meta->map_uid != reg->map_uid) {
8022 				verbose(env,
8023 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8024 					meta->map_uid, reg->map_uid);
8025 				return -EINVAL;
8026 			}
8027 		}
8028 		meta->map_ptr = reg->map_ptr;
8029 		meta->map_uid = reg->map_uid;
8030 		break;
8031 	case ARG_PTR_TO_MAP_KEY:
8032 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8033 		 * check that [key, key + map->key_size) are within
8034 		 * stack limits and initialized
8035 		 */
8036 		if (!meta->map_ptr) {
8037 			/* in function declaration map_ptr must come before
8038 			 * map_key, so that it's verified and known before
8039 			 * we have to check map_key here. Otherwise it means
8040 			 * that kernel subsystem misconfigured verifier
8041 			 */
8042 			verbose(env, "invalid map_ptr to access map->key\n");
8043 			return -EACCES;
8044 		}
8045 		err = check_helper_mem_access(env, regno,
8046 					      meta->map_ptr->key_size, false,
8047 					      NULL);
8048 		break;
8049 	case ARG_PTR_TO_MAP_VALUE:
8050 		if (type_may_be_null(arg_type) && register_is_null(reg))
8051 			return 0;
8052 
8053 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8054 		 * check [value, value + map->value_size) validity
8055 		 */
8056 		if (!meta->map_ptr) {
8057 			/* kernel subsystem misconfigured verifier */
8058 			verbose(env, "invalid map_ptr to access map->value\n");
8059 			return -EACCES;
8060 		}
8061 		meta->raw_mode = arg_type & MEM_UNINIT;
8062 		err = check_helper_mem_access(env, regno,
8063 					      meta->map_ptr->value_size, false,
8064 					      meta);
8065 		break;
8066 	case ARG_PTR_TO_PERCPU_BTF_ID:
8067 		if (!reg->btf_id) {
8068 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8069 			return -EACCES;
8070 		}
8071 		meta->ret_btf = reg->btf;
8072 		meta->ret_btf_id = reg->btf_id;
8073 		break;
8074 	case ARG_PTR_TO_SPIN_LOCK:
8075 		if (in_rbtree_lock_required_cb(env)) {
8076 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8077 			return -EACCES;
8078 		}
8079 		if (meta->func_id == BPF_FUNC_spin_lock) {
8080 			err = process_spin_lock(env, regno, true);
8081 			if (err)
8082 				return err;
8083 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8084 			err = process_spin_lock(env, regno, false);
8085 			if (err)
8086 				return err;
8087 		} else {
8088 			verbose(env, "verifier internal error\n");
8089 			return -EFAULT;
8090 		}
8091 		break;
8092 	case ARG_PTR_TO_TIMER:
8093 		err = process_timer_func(env, regno, meta);
8094 		if (err)
8095 			return err;
8096 		break;
8097 	case ARG_PTR_TO_FUNC:
8098 		meta->subprogno = reg->subprogno;
8099 		break;
8100 	case ARG_PTR_TO_MEM:
8101 		/* The access to this pointer is only checked when we hit the
8102 		 * next is_mem_size argument below.
8103 		 */
8104 		meta->raw_mode = arg_type & MEM_UNINIT;
8105 		if (arg_type & MEM_FIXED_SIZE) {
8106 			err = check_helper_mem_access(env, regno,
8107 						      fn->arg_size[arg], false,
8108 						      meta);
8109 		}
8110 		break;
8111 	case ARG_CONST_SIZE:
8112 		err = check_mem_size_reg(env, reg, regno, false, meta);
8113 		break;
8114 	case ARG_CONST_SIZE_OR_ZERO:
8115 		err = check_mem_size_reg(env, reg, regno, true, meta);
8116 		break;
8117 	case ARG_PTR_TO_DYNPTR:
8118 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8119 		if (err)
8120 			return err;
8121 		break;
8122 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8123 		if (!tnum_is_const(reg->var_off)) {
8124 			verbose(env, "R%d is not a known constant'\n",
8125 				regno);
8126 			return -EACCES;
8127 		}
8128 		meta->mem_size = reg->var_off.value;
8129 		err = mark_chain_precision(env, regno);
8130 		if (err)
8131 			return err;
8132 		break;
8133 	case ARG_PTR_TO_INT:
8134 	case ARG_PTR_TO_LONG:
8135 	{
8136 		int size = int_ptr_type_to_size(arg_type);
8137 
8138 		err = check_helper_mem_access(env, regno, size, false, meta);
8139 		if (err)
8140 			return err;
8141 		err = check_ptr_alignment(env, reg, 0, size, true);
8142 		break;
8143 	}
8144 	case ARG_PTR_TO_CONST_STR:
8145 	{
8146 		struct bpf_map *map = reg->map_ptr;
8147 		int map_off;
8148 		u64 map_addr;
8149 		char *str_ptr;
8150 
8151 		if (!bpf_map_is_rdonly(map)) {
8152 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8153 			return -EACCES;
8154 		}
8155 
8156 		if (!tnum_is_const(reg->var_off)) {
8157 			verbose(env, "R%d is not a constant address'\n", regno);
8158 			return -EACCES;
8159 		}
8160 
8161 		if (!map->ops->map_direct_value_addr) {
8162 			verbose(env, "no direct value access support for this map type\n");
8163 			return -EACCES;
8164 		}
8165 
8166 		err = check_map_access(env, regno, reg->off,
8167 				       map->value_size - reg->off, false,
8168 				       ACCESS_HELPER);
8169 		if (err)
8170 			return err;
8171 
8172 		map_off = reg->off + reg->var_off.value;
8173 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8174 		if (err) {
8175 			verbose(env, "direct value access on string failed\n");
8176 			return err;
8177 		}
8178 
8179 		str_ptr = (char *)(long)(map_addr);
8180 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8181 			verbose(env, "string is not zero-terminated\n");
8182 			return -EINVAL;
8183 		}
8184 		break;
8185 	}
8186 	case ARG_PTR_TO_KPTR:
8187 		err = process_kptr_func(env, regno, meta);
8188 		if (err)
8189 			return err;
8190 		break;
8191 	}
8192 
8193 	return err;
8194 }
8195 
8196 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8197 {
8198 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8199 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8200 
8201 	if (func_id != BPF_FUNC_map_update_elem)
8202 		return false;
8203 
8204 	/* It's not possible to get access to a locked struct sock in these
8205 	 * contexts, so updating is safe.
8206 	 */
8207 	switch (type) {
8208 	case BPF_PROG_TYPE_TRACING:
8209 		if (eatype == BPF_TRACE_ITER)
8210 			return true;
8211 		break;
8212 	case BPF_PROG_TYPE_SOCKET_FILTER:
8213 	case BPF_PROG_TYPE_SCHED_CLS:
8214 	case BPF_PROG_TYPE_SCHED_ACT:
8215 	case BPF_PROG_TYPE_XDP:
8216 	case BPF_PROG_TYPE_SK_REUSEPORT:
8217 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8218 	case BPF_PROG_TYPE_SK_LOOKUP:
8219 		return true;
8220 	default:
8221 		break;
8222 	}
8223 
8224 	verbose(env, "cannot update sockmap in this context\n");
8225 	return false;
8226 }
8227 
8228 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8229 {
8230 	return env->prog->jit_requested &&
8231 	       bpf_jit_supports_subprog_tailcalls();
8232 }
8233 
8234 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8235 					struct bpf_map *map, int func_id)
8236 {
8237 	if (!map)
8238 		return 0;
8239 
8240 	/* We need a two way check, first is from map perspective ... */
8241 	switch (map->map_type) {
8242 	case BPF_MAP_TYPE_PROG_ARRAY:
8243 		if (func_id != BPF_FUNC_tail_call)
8244 			goto error;
8245 		break;
8246 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8247 		if (func_id != BPF_FUNC_perf_event_read &&
8248 		    func_id != BPF_FUNC_perf_event_output &&
8249 		    func_id != BPF_FUNC_skb_output &&
8250 		    func_id != BPF_FUNC_perf_event_read_value &&
8251 		    func_id != BPF_FUNC_xdp_output)
8252 			goto error;
8253 		break;
8254 	case BPF_MAP_TYPE_RINGBUF:
8255 		if (func_id != BPF_FUNC_ringbuf_output &&
8256 		    func_id != BPF_FUNC_ringbuf_reserve &&
8257 		    func_id != BPF_FUNC_ringbuf_query &&
8258 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8259 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8260 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8261 			goto error;
8262 		break;
8263 	case BPF_MAP_TYPE_USER_RINGBUF:
8264 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8265 			goto error;
8266 		break;
8267 	case BPF_MAP_TYPE_STACK_TRACE:
8268 		if (func_id != BPF_FUNC_get_stackid)
8269 			goto error;
8270 		break;
8271 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8272 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8273 		    func_id != BPF_FUNC_current_task_under_cgroup)
8274 			goto error;
8275 		break;
8276 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8277 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8278 		if (func_id != BPF_FUNC_get_local_storage)
8279 			goto error;
8280 		break;
8281 	case BPF_MAP_TYPE_DEVMAP:
8282 	case BPF_MAP_TYPE_DEVMAP_HASH:
8283 		if (func_id != BPF_FUNC_redirect_map &&
8284 		    func_id != BPF_FUNC_map_lookup_elem)
8285 			goto error;
8286 		break;
8287 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8288 	 * appear.
8289 	 */
8290 	case BPF_MAP_TYPE_CPUMAP:
8291 		if (func_id != BPF_FUNC_redirect_map)
8292 			goto error;
8293 		break;
8294 	case BPF_MAP_TYPE_XSKMAP:
8295 		if (func_id != BPF_FUNC_redirect_map &&
8296 		    func_id != BPF_FUNC_map_lookup_elem)
8297 			goto error;
8298 		break;
8299 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8300 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8301 		if (func_id != BPF_FUNC_map_lookup_elem)
8302 			goto error;
8303 		break;
8304 	case BPF_MAP_TYPE_SOCKMAP:
8305 		if (func_id != BPF_FUNC_sk_redirect_map &&
8306 		    func_id != BPF_FUNC_sock_map_update &&
8307 		    func_id != BPF_FUNC_map_delete_elem &&
8308 		    func_id != BPF_FUNC_msg_redirect_map &&
8309 		    func_id != BPF_FUNC_sk_select_reuseport &&
8310 		    func_id != BPF_FUNC_map_lookup_elem &&
8311 		    !may_update_sockmap(env, func_id))
8312 			goto error;
8313 		break;
8314 	case BPF_MAP_TYPE_SOCKHASH:
8315 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8316 		    func_id != BPF_FUNC_sock_hash_update &&
8317 		    func_id != BPF_FUNC_map_delete_elem &&
8318 		    func_id != BPF_FUNC_msg_redirect_hash &&
8319 		    func_id != BPF_FUNC_sk_select_reuseport &&
8320 		    func_id != BPF_FUNC_map_lookup_elem &&
8321 		    !may_update_sockmap(env, func_id))
8322 			goto error;
8323 		break;
8324 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8325 		if (func_id != BPF_FUNC_sk_select_reuseport)
8326 			goto error;
8327 		break;
8328 	case BPF_MAP_TYPE_QUEUE:
8329 	case BPF_MAP_TYPE_STACK:
8330 		if (func_id != BPF_FUNC_map_peek_elem &&
8331 		    func_id != BPF_FUNC_map_pop_elem &&
8332 		    func_id != BPF_FUNC_map_push_elem)
8333 			goto error;
8334 		break;
8335 	case BPF_MAP_TYPE_SK_STORAGE:
8336 		if (func_id != BPF_FUNC_sk_storage_get &&
8337 		    func_id != BPF_FUNC_sk_storage_delete &&
8338 		    func_id != BPF_FUNC_kptr_xchg)
8339 			goto error;
8340 		break;
8341 	case BPF_MAP_TYPE_INODE_STORAGE:
8342 		if (func_id != BPF_FUNC_inode_storage_get &&
8343 		    func_id != BPF_FUNC_inode_storage_delete &&
8344 		    func_id != BPF_FUNC_kptr_xchg)
8345 			goto error;
8346 		break;
8347 	case BPF_MAP_TYPE_TASK_STORAGE:
8348 		if (func_id != BPF_FUNC_task_storage_get &&
8349 		    func_id != BPF_FUNC_task_storage_delete &&
8350 		    func_id != BPF_FUNC_kptr_xchg)
8351 			goto error;
8352 		break;
8353 	case BPF_MAP_TYPE_CGRP_STORAGE:
8354 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8355 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8356 		    func_id != BPF_FUNC_kptr_xchg)
8357 			goto error;
8358 		break;
8359 	case BPF_MAP_TYPE_BLOOM_FILTER:
8360 		if (func_id != BPF_FUNC_map_peek_elem &&
8361 		    func_id != BPF_FUNC_map_push_elem)
8362 			goto error;
8363 		break;
8364 	default:
8365 		break;
8366 	}
8367 
8368 	/* ... and second from the function itself. */
8369 	switch (func_id) {
8370 	case BPF_FUNC_tail_call:
8371 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8372 			goto error;
8373 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8374 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8375 			return -EINVAL;
8376 		}
8377 		break;
8378 	case BPF_FUNC_perf_event_read:
8379 	case BPF_FUNC_perf_event_output:
8380 	case BPF_FUNC_perf_event_read_value:
8381 	case BPF_FUNC_skb_output:
8382 	case BPF_FUNC_xdp_output:
8383 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8384 			goto error;
8385 		break;
8386 	case BPF_FUNC_ringbuf_output:
8387 	case BPF_FUNC_ringbuf_reserve:
8388 	case BPF_FUNC_ringbuf_query:
8389 	case BPF_FUNC_ringbuf_reserve_dynptr:
8390 	case BPF_FUNC_ringbuf_submit_dynptr:
8391 	case BPF_FUNC_ringbuf_discard_dynptr:
8392 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8393 			goto error;
8394 		break;
8395 	case BPF_FUNC_user_ringbuf_drain:
8396 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8397 			goto error;
8398 		break;
8399 	case BPF_FUNC_get_stackid:
8400 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8401 			goto error;
8402 		break;
8403 	case BPF_FUNC_current_task_under_cgroup:
8404 	case BPF_FUNC_skb_under_cgroup:
8405 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8406 			goto error;
8407 		break;
8408 	case BPF_FUNC_redirect_map:
8409 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8410 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8411 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8412 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8413 			goto error;
8414 		break;
8415 	case BPF_FUNC_sk_redirect_map:
8416 	case BPF_FUNC_msg_redirect_map:
8417 	case BPF_FUNC_sock_map_update:
8418 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8419 			goto error;
8420 		break;
8421 	case BPF_FUNC_sk_redirect_hash:
8422 	case BPF_FUNC_msg_redirect_hash:
8423 	case BPF_FUNC_sock_hash_update:
8424 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8425 			goto error;
8426 		break;
8427 	case BPF_FUNC_get_local_storage:
8428 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8429 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8430 			goto error;
8431 		break;
8432 	case BPF_FUNC_sk_select_reuseport:
8433 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8434 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8435 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8436 			goto error;
8437 		break;
8438 	case BPF_FUNC_map_pop_elem:
8439 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8440 		    map->map_type != BPF_MAP_TYPE_STACK)
8441 			goto error;
8442 		break;
8443 	case BPF_FUNC_map_peek_elem:
8444 	case BPF_FUNC_map_push_elem:
8445 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8446 		    map->map_type != BPF_MAP_TYPE_STACK &&
8447 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8448 			goto error;
8449 		break;
8450 	case BPF_FUNC_map_lookup_percpu_elem:
8451 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8452 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8453 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8454 			goto error;
8455 		break;
8456 	case BPF_FUNC_sk_storage_get:
8457 	case BPF_FUNC_sk_storage_delete:
8458 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8459 			goto error;
8460 		break;
8461 	case BPF_FUNC_inode_storage_get:
8462 	case BPF_FUNC_inode_storage_delete:
8463 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8464 			goto error;
8465 		break;
8466 	case BPF_FUNC_task_storage_get:
8467 	case BPF_FUNC_task_storage_delete:
8468 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8469 			goto error;
8470 		break;
8471 	case BPF_FUNC_cgrp_storage_get:
8472 	case BPF_FUNC_cgrp_storage_delete:
8473 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8474 			goto error;
8475 		break;
8476 	default:
8477 		break;
8478 	}
8479 
8480 	return 0;
8481 error:
8482 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8483 		map->map_type, func_id_name(func_id), func_id);
8484 	return -EINVAL;
8485 }
8486 
8487 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8488 {
8489 	int count = 0;
8490 
8491 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8492 		count++;
8493 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8494 		count++;
8495 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8496 		count++;
8497 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8498 		count++;
8499 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8500 		count++;
8501 
8502 	/* We only support one arg being in raw mode at the moment,
8503 	 * which is sufficient for the helper functions we have
8504 	 * right now.
8505 	 */
8506 	return count <= 1;
8507 }
8508 
8509 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8510 {
8511 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8512 	bool has_size = fn->arg_size[arg] != 0;
8513 	bool is_next_size = false;
8514 
8515 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8516 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8517 
8518 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8519 		return is_next_size;
8520 
8521 	return has_size == is_next_size || is_next_size == is_fixed;
8522 }
8523 
8524 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8525 {
8526 	/* bpf_xxx(..., buf, len) call will access 'len'
8527 	 * bytes from memory 'buf'. Both arg types need
8528 	 * to be paired, so make sure there's no buggy
8529 	 * helper function specification.
8530 	 */
8531 	if (arg_type_is_mem_size(fn->arg1_type) ||
8532 	    check_args_pair_invalid(fn, 0) ||
8533 	    check_args_pair_invalid(fn, 1) ||
8534 	    check_args_pair_invalid(fn, 2) ||
8535 	    check_args_pair_invalid(fn, 3) ||
8536 	    check_args_pair_invalid(fn, 4))
8537 		return false;
8538 
8539 	return true;
8540 }
8541 
8542 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8543 {
8544 	int i;
8545 
8546 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8547 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8548 			return !!fn->arg_btf_id[i];
8549 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8550 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8551 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8552 		    /* arg_btf_id and arg_size are in a union. */
8553 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8554 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8555 			return false;
8556 	}
8557 
8558 	return true;
8559 }
8560 
8561 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8562 {
8563 	return check_raw_mode_ok(fn) &&
8564 	       check_arg_pair_ok(fn) &&
8565 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8566 }
8567 
8568 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8569  * are now invalid, so turn them into unknown SCALAR_VALUE.
8570  *
8571  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8572  * since these slices point to packet data.
8573  */
8574 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8575 {
8576 	struct bpf_func_state *state;
8577 	struct bpf_reg_state *reg;
8578 
8579 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8580 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8581 			mark_reg_invalid(env, reg);
8582 	}));
8583 }
8584 
8585 enum {
8586 	AT_PKT_END = -1,
8587 	BEYOND_PKT_END = -2,
8588 };
8589 
8590 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8591 {
8592 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8593 	struct bpf_reg_state *reg = &state->regs[regn];
8594 
8595 	if (reg->type != PTR_TO_PACKET)
8596 		/* PTR_TO_PACKET_META is not supported yet */
8597 		return;
8598 
8599 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8600 	 * How far beyond pkt_end it goes is unknown.
8601 	 * if (!range_open) it's the case of pkt >= pkt_end
8602 	 * if (range_open) it's the case of pkt > pkt_end
8603 	 * hence this pointer is at least 1 byte bigger than pkt_end
8604 	 */
8605 	if (range_open)
8606 		reg->range = BEYOND_PKT_END;
8607 	else
8608 		reg->range = AT_PKT_END;
8609 }
8610 
8611 /* The pointer with the specified id has released its reference to kernel
8612  * resources. Identify all copies of the same pointer and clear the reference.
8613  */
8614 static int release_reference(struct bpf_verifier_env *env,
8615 			     int ref_obj_id)
8616 {
8617 	struct bpf_func_state *state;
8618 	struct bpf_reg_state *reg;
8619 	int err;
8620 
8621 	err = release_reference_state(cur_func(env), ref_obj_id);
8622 	if (err)
8623 		return err;
8624 
8625 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8626 		if (reg->ref_obj_id == ref_obj_id)
8627 			mark_reg_invalid(env, reg);
8628 	}));
8629 
8630 	return 0;
8631 }
8632 
8633 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8634 {
8635 	struct bpf_func_state *unused;
8636 	struct bpf_reg_state *reg;
8637 
8638 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8639 		if (type_is_non_owning_ref(reg->type))
8640 			mark_reg_invalid(env, reg);
8641 	}));
8642 }
8643 
8644 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8645 				    struct bpf_reg_state *regs)
8646 {
8647 	int i;
8648 
8649 	/* after the call registers r0 - r5 were scratched */
8650 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8651 		mark_reg_not_init(env, regs, caller_saved[i]);
8652 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8653 	}
8654 }
8655 
8656 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8657 				   struct bpf_func_state *caller,
8658 				   struct bpf_func_state *callee,
8659 				   int insn_idx);
8660 
8661 static int set_callee_state(struct bpf_verifier_env *env,
8662 			    struct bpf_func_state *caller,
8663 			    struct bpf_func_state *callee, int insn_idx);
8664 
8665 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8666 			     int *insn_idx, int subprog,
8667 			     set_callee_state_fn set_callee_state_cb)
8668 {
8669 	struct bpf_verifier_state *state = env->cur_state;
8670 	struct bpf_func_state *caller, *callee;
8671 	int err;
8672 
8673 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8674 		verbose(env, "the call stack of %d frames is too deep\n",
8675 			state->curframe + 2);
8676 		return -E2BIG;
8677 	}
8678 
8679 	caller = state->frame[state->curframe];
8680 	if (state->frame[state->curframe + 1]) {
8681 		verbose(env, "verifier bug. Frame %d already allocated\n",
8682 			state->curframe + 1);
8683 		return -EFAULT;
8684 	}
8685 
8686 	err = btf_check_subprog_call(env, subprog, caller->regs);
8687 	if (err == -EFAULT)
8688 		return err;
8689 	if (subprog_is_global(env, subprog)) {
8690 		if (err) {
8691 			verbose(env, "Caller passes invalid args into func#%d\n",
8692 				subprog);
8693 			return err;
8694 		} else {
8695 			if (env->log.level & BPF_LOG_LEVEL)
8696 				verbose(env,
8697 					"Func#%d is global and valid. Skipping.\n",
8698 					subprog);
8699 			clear_caller_saved_regs(env, caller->regs);
8700 
8701 			/* All global functions return a 64-bit SCALAR_VALUE */
8702 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8703 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8704 
8705 			/* continue with next insn after call */
8706 			return 0;
8707 		}
8708 	}
8709 
8710 	/* set_callee_state is used for direct subprog calls, but we are
8711 	 * interested in validating only BPF helpers that can call subprogs as
8712 	 * callbacks
8713 	 */
8714 	if (set_callee_state_cb != set_callee_state) {
8715 		if (bpf_pseudo_kfunc_call(insn) &&
8716 		    !is_callback_calling_kfunc(insn->imm)) {
8717 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8718 				func_id_name(insn->imm), insn->imm);
8719 			return -EFAULT;
8720 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8721 			   !is_callback_calling_function(insn->imm)) { /* helper */
8722 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8723 				func_id_name(insn->imm), insn->imm);
8724 			return -EFAULT;
8725 		}
8726 	}
8727 
8728 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8729 	    insn->src_reg == 0 &&
8730 	    insn->imm == BPF_FUNC_timer_set_callback) {
8731 		struct bpf_verifier_state *async_cb;
8732 
8733 		/* there is no real recursion here. timer callbacks are async */
8734 		env->subprog_info[subprog].is_async_cb = true;
8735 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8736 					 *insn_idx, subprog);
8737 		if (!async_cb)
8738 			return -EFAULT;
8739 		callee = async_cb->frame[0];
8740 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8741 
8742 		/* Convert bpf_timer_set_callback() args into timer callback args */
8743 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8744 		if (err)
8745 			return err;
8746 
8747 		clear_caller_saved_regs(env, caller->regs);
8748 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8749 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8750 		/* continue with next insn after call */
8751 		return 0;
8752 	}
8753 
8754 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8755 	if (!callee)
8756 		return -ENOMEM;
8757 	state->frame[state->curframe + 1] = callee;
8758 
8759 	/* callee cannot access r0, r6 - r9 for reading and has to write
8760 	 * into its own stack before reading from it.
8761 	 * callee can read/write into caller's stack
8762 	 */
8763 	init_func_state(env, callee,
8764 			/* remember the callsite, it will be used by bpf_exit */
8765 			*insn_idx /* callsite */,
8766 			state->curframe + 1 /* frameno within this callchain */,
8767 			subprog /* subprog number within this prog */);
8768 
8769 	/* Transfer references to the callee */
8770 	err = copy_reference_state(callee, caller);
8771 	if (err)
8772 		goto err_out;
8773 
8774 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8775 	if (err)
8776 		goto err_out;
8777 
8778 	clear_caller_saved_regs(env, caller->regs);
8779 
8780 	/* only increment it after check_reg_arg() finished */
8781 	state->curframe++;
8782 
8783 	/* and go analyze first insn of the callee */
8784 	*insn_idx = env->subprog_info[subprog].start - 1;
8785 
8786 	if (env->log.level & BPF_LOG_LEVEL) {
8787 		verbose(env, "caller:\n");
8788 		print_verifier_state(env, caller, true);
8789 		verbose(env, "callee:\n");
8790 		print_verifier_state(env, callee, true);
8791 	}
8792 	return 0;
8793 
8794 err_out:
8795 	free_func_state(callee);
8796 	state->frame[state->curframe + 1] = NULL;
8797 	return err;
8798 }
8799 
8800 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8801 				   struct bpf_func_state *caller,
8802 				   struct bpf_func_state *callee)
8803 {
8804 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8805 	 *      void *callback_ctx, u64 flags);
8806 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8807 	 *      void *callback_ctx);
8808 	 */
8809 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8810 
8811 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8812 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8813 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8814 
8815 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8816 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8817 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8818 
8819 	/* pointer to stack or null */
8820 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8821 
8822 	/* unused */
8823 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8824 	return 0;
8825 }
8826 
8827 static int set_callee_state(struct bpf_verifier_env *env,
8828 			    struct bpf_func_state *caller,
8829 			    struct bpf_func_state *callee, int insn_idx)
8830 {
8831 	int i;
8832 
8833 	/* copy r1 - r5 args that callee can access.  The copy includes parent
8834 	 * pointers, which connects us up to the liveness chain
8835 	 */
8836 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8837 		callee->regs[i] = caller->regs[i];
8838 	return 0;
8839 }
8840 
8841 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8842 			   int *insn_idx)
8843 {
8844 	int subprog, target_insn;
8845 
8846 	target_insn = *insn_idx + insn->imm + 1;
8847 	subprog = find_subprog(env, target_insn);
8848 	if (subprog < 0) {
8849 		verbose(env, "verifier bug. No program starts at insn %d\n",
8850 			target_insn);
8851 		return -EFAULT;
8852 	}
8853 
8854 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8855 }
8856 
8857 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8858 				       struct bpf_func_state *caller,
8859 				       struct bpf_func_state *callee,
8860 				       int insn_idx)
8861 {
8862 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8863 	struct bpf_map *map;
8864 	int err;
8865 
8866 	if (bpf_map_ptr_poisoned(insn_aux)) {
8867 		verbose(env, "tail_call abusing map_ptr\n");
8868 		return -EINVAL;
8869 	}
8870 
8871 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8872 	if (!map->ops->map_set_for_each_callback_args ||
8873 	    !map->ops->map_for_each_callback) {
8874 		verbose(env, "callback function not allowed for map\n");
8875 		return -ENOTSUPP;
8876 	}
8877 
8878 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8879 	if (err)
8880 		return err;
8881 
8882 	callee->in_callback_fn = true;
8883 	callee->callback_ret_range = tnum_range(0, 1);
8884 	return 0;
8885 }
8886 
8887 static int set_loop_callback_state(struct bpf_verifier_env *env,
8888 				   struct bpf_func_state *caller,
8889 				   struct bpf_func_state *callee,
8890 				   int insn_idx)
8891 {
8892 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8893 	 *	    u64 flags);
8894 	 * callback_fn(u32 index, void *callback_ctx);
8895 	 */
8896 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8897 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8898 
8899 	/* unused */
8900 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8901 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8902 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8903 
8904 	callee->in_callback_fn = true;
8905 	callee->callback_ret_range = tnum_range(0, 1);
8906 	return 0;
8907 }
8908 
8909 static int set_timer_callback_state(struct bpf_verifier_env *env,
8910 				    struct bpf_func_state *caller,
8911 				    struct bpf_func_state *callee,
8912 				    int insn_idx)
8913 {
8914 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8915 
8916 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8917 	 * callback_fn(struct bpf_map *map, void *key, void *value);
8918 	 */
8919 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8920 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8921 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
8922 
8923 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8924 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8925 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
8926 
8927 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8928 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8929 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
8930 
8931 	/* unused */
8932 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8933 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8934 	callee->in_async_callback_fn = true;
8935 	callee->callback_ret_range = tnum_range(0, 1);
8936 	return 0;
8937 }
8938 
8939 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8940 				       struct bpf_func_state *caller,
8941 				       struct bpf_func_state *callee,
8942 				       int insn_idx)
8943 {
8944 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8945 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8946 	 * (callback_fn)(struct task_struct *task,
8947 	 *               struct vm_area_struct *vma, void *callback_ctx);
8948 	 */
8949 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8950 
8951 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8952 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8953 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8954 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8955 
8956 	/* pointer to stack or null */
8957 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8958 
8959 	/* unused */
8960 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8961 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8962 	callee->in_callback_fn = true;
8963 	callee->callback_ret_range = tnum_range(0, 1);
8964 	return 0;
8965 }
8966 
8967 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8968 					   struct bpf_func_state *caller,
8969 					   struct bpf_func_state *callee,
8970 					   int insn_idx)
8971 {
8972 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8973 	 *			  callback_ctx, u64 flags);
8974 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8975 	 */
8976 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8977 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8978 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8979 
8980 	/* unused */
8981 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8982 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8983 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8984 
8985 	callee->in_callback_fn = true;
8986 	callee->callback_ret_range = tnum_range(0, 1);
8987 	return 0;
8988 }
8989 
8990 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8991 					 struct bpf_func_state *caller,
8992 					 struct bpf_func_state *callee,
8993 					 int insn_idx)
8994 {
8995 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
8996 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8997 	 *
8998 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
8999 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9000 	 * by this point, so look at 'root'
9001 	 */
9002 	struct btf_field *field;
9003 
9004 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9005 				      BPF_RB_ROOT);
9006 	if (!field || !field->graph_root.value_btf_id)
9007 		return -EFAULT;
9008 
9009 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9010 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9011 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9012 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9013 
9014 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9015 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9016 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9017 	callee->in_callback_fn = true;
9018 	callee->callback_ret_range = tnum_range(0, 1);
9019 	return 0;
9020 }
9021 
9022 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9023 
9024 /* Are we currently verifying the callback for a rbtree helper that must
9025  * be called with lock held? If so, no need to complain about unreleased
9026  * lock
9027  */
9028 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9029 {
9030 	struct bpf_verifier_state *state = env->cur_state;
9031 	struct bpf_insn *insn = env->prog->insnsi;
9032 	struct bpf_func_state *callee;
9033 	int kfunc_btf_id;
9034 
9035 	if (!state->curframe)
9036 		return false;
9037 
9038 	callee = state->frame[state->curframe];
9039 
9040 	if (!callee->in_callback_fn)
9041 		return false;
9042 
9043 	kfunc_btf_id = insn[callee->callsite].imm;
9044 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9045 }
9046 
9047 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9048 {
9049 	struct bpf_verifier_state *state = env->cur_state;
9050 	struct bpf_func_state *caller, *callee;
9051 	struct bpf_reg_state *r0;
9052 	int err;
9053 
9054 	callee = state->frame[state->curframe];
9055 	r0 = &callee->regs[BPF_REG_0];
9056 	if (r0->type == PTR_TO_STACK) {
9057 		/* technically it's ok to return caller's stack pointer
9058 		 * (or caller's caller's pointer) back to the caller,
9059 		 * since these pointers are valid. Only current stack
9060 		 * pointer will be invalid as soon as function exits,
9061 		 * but let's be conservative
9062 		 */
9063 		verbose(env, "cannot return stack pointer to the caller\n");
9064 		return -EINVAL;
9065 	}
9066 
9067 	caller = state->frame[state->curframe - 1];
9068 	if (callee->in_callback_fn) {
9069 		/* enforce R0 return value range [0, 1]. */
9070 		struct tnum range = callee->callback_ret_range;
9071 
9072 		if (r0->type != SCALAR_VALUE) {
9073 			verbose(env, "R0 not a scalar value\n");
9074 			return -EACCES;
9075 		}
9076 		if (!tnum_in(range, r0->var_off)) {
9077 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9078 			return -EINVAL;
9079 		}
9080 	} else {
9081 		/* return to the caller whatever r0 had in the callee */
9082 		caller->regs[BPF_REG_0] = *r0;
9083 	}
9084 
9085 	/* callback_fn frame should have released its own additions to parent's
9086 	 * reference state at this point, or check_reference_leak would
9087 	 * complain, hence it must be the same as the caller. There is no need
9088 	 * to copy it back.
9089 	 */
9090 	if (!callee->in_callback_fn) {
9091 		/* Transfer references to the caller */
9092 		err = copy_reference_state(caller, callee);
9093 		if (err)
9094 			return err;
9095 	}
9096 
9097 	*insn_idx = callee->callsite + 1;
9098 	if (env->log.level & BPF_LOG_LEVEL) {
9099 		verbose(env, "returning from callee:\n");
9100 		print_verifier_state(env, callee, true);
9101 		verbose(env, "to caller at %d:\n", *insn_idx);
9102 		print_verifier_state(env, caller, true);
9103 	}
9104 	/* clear everything in the callee */
9105 	free_func_state(callee);
9106 	state->frame[state->curframe--] = NULL;
9107 	return 0;
9108 }
9109 
9110 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9111 				   int func_id,
9112 				   struct bpf_call_arg_meta *meta)
9113 {
9114 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9115 
9116 	if (ret_type != RET_INTEGER ||
9117 	    (func_id != BPF_FUNC_get_stack &&
9118 	     func_id != BPF_FUNC_get_task_stack &&
9119 	     func_id != BPF_FUNC_probe_read_str &&
9120 	     func_id != BPF_FUNC_probe_read_kernel_str &&
9121 	     func_id != BPF_FUNC_probe_read_user_str))
9122 		return;
9123 
9124 	ret_reg->smax_value = meta->msize_max_value;
9125 	ret_reg->s32_max_value = meta->msize_max_value;
9126 	ret_reg->smin_value = -MAX_ERRNO;
9127 	ret_reg->s32_min_value = -MAX_ERRNO;
9128 	reg_bounds_sync(ret_reg);
9129 }
9130 
9131 static int
9132 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9133 		int func_id, int insn_idx)
9134 {
9135 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9136 	struct bpf_map *map = meta->map_ptr;
9137 
9138 	if (func_id != BPF_FUNC_tail_call &&
9139 	    func_id != BPF_FUNC_map_lookup_elem &&
9140 	    func_id != BPF_FUNC_map_update_elem &&
9141 	    func_id != BPF_FUNC_map_delete_elem &&
9142 	    func_id != BPF_FUNC_map_push_elem &&
9143 	    func_id != BPF_FUNC_map_pop_elem &&
9144 	    func_id != BPF_FUNC_map_peek_elem &&
9145 	    func_id != BPF_FUNC_for_each_map_elem &&
9146 	    func_id != BPF_FUNC_redirect_map &&
9147 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9148 		return 0;
9149 
9150 	if (map == NULL) {
9151 		verbose(env, "kernel subsystem misconfigured verifier\n");
9152 		return -EINVAL;
9153 	}
9154 
9155 	/* In case of read-only, some additional restrictions
9156 	 * need to be applied in order to prevent altering the
9157 	 * state of the map from program side.
9158 	 */
9159 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9160 	    (func_id == BPF_FUNC_map_delete_elem ||
9161 	     func_id == BPF_FUNC_map_update_elem ||
9162 	     func_id == BPF_FUNC_map_push_elem ||
9163 	     func_id == BPF_FUNC_map_pop_elem)) {
9164 		verbose(env, "write into map forbidden\n");
9165 		return -EACCES;
9166 	}
9167 
9168 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9169 		bpf_map_ptr_store(aux, meta->map_ptr,
9170 				  !meta->map_ptr->bypass_spec_v1);
9171 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9172 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9173 				  !meta->map_ptr->bypass_spec_v1);
9174 	return 0;
9175 }
9176 
9177 static int
9178 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9179 		int func_id, int insn_idx)
9180 {
9181 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9182 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9183 	struct bpf_map *map = meta->map_ptr;
9184 	u64 val, max;
9185 	int err;
9186 
9187 	if (func_id != BPF_FUNC_tail_call)
9188 		return 0;
9189 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9190 		verbose(env, "kernel subsystem misconfigured verifier\n");
9191 		return -EINVAL;
9192 	}
9193 
9194 	reg = &regs[BPF_REG_3];
9195 	val = reg->var_off.value;
9196 	max = map->max_entries;
9197 
9198 	if (!(register_is_const(reg) && val < max)) {
9199 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9200 		return 0;
9201 	}
9202 
9203 	err = mark_chain_precision(env, BPF_REG_3);
9204 	if (err)
9205 		return err;
9206 	if (bpf_map_key_unseen(aux))
9207 		bpf_map_key_store(aux, val);
9208 	else if (!bpf_map_key_poisoned(aux) &&
9209 		  bpf_map_key_immediate(aux) != val)
9210 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9211 	return 0;
9212 }
9213 
9214 static int check_reference_leak(struct bpf_verifier_env *env)
9215 {
9216 	struct bpf_func_state *state = cur_func(env);
9217 	bool refs_lingering = false;
9218 	int i;
9219 
9220 	if (state->frameno && !state->in_callback_fn)
9221 		return 0;
9222 
9223 	for (i = 0; i < state->acquired_refs; i++) {
9224 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9225 			continue;
9226 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9227 			state->refs[i].id, state->refs[i].insn_idx);
9228 		refs_lingering = true;
9229 	}
9230 	return refs_lingering ? -EINVAL : 0;
9231 }
9232 
9233 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9234 				   struct bpf_reg_state *regs)
9235 {
9236 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9237 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9238 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9239 	struct bpf_bprintf_data data = {};
9240 	int err, fmt_map_off, num_args;
9241 	u64 fmt_addr;
9242 	char *fmt;
9243 
9244 	/* data must be an array of u64 */
9245 	if (data_len_reg->var_off.value % 8)
9246 		return -EINVAL;
9247 	num_args = data_len_reg->var_off.value / 8;
9248 
9249 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9250 	 * and map_direct_value_addr is set.
9251 	 */
9252 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9253 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9254 						  fmt_map_off);
9255 	if (err) {
9256 		verbose(env, "verifier bug\n");
9257 		return -EFAULT;
9258 	}
9259 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9260 
9261 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9262 	 * can focus on validating the format specifiers.
9263 	 */
9264 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9265 	if (err < 0)
9266 		verbose(env, "Invalid format string\n");
9267 
9268 	return err;
9269 }
9270 
9271 static int check_get_func_ip(struct bpf_verifier_env *env)
9272 {
9273 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9274 	int func_id = BPF_FUNC_get_func_ip;
9275 
9276 	if (type == BPF_PROG_TYPE_TRACING) {
9277 		if (!bpf_prog_has_trampoline(env->prog)) {
9278 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9279 				func_id_name(func_id), func_id);
9280 			return -ENOTSUPP;
9281 		}
9282 		return 0;
9283 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9284 		return 0;
9285 	}
9286 
9287 	verbose(env, "func %s#%d not supported for program type %d\n",
9288 		func_id_name(func_id), func_id, type);
9289 	return -ENOTSUPP;
9290 }
9291 
9292 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9293 {
9294 	return &env->insn_aux_data[env->insn_idx];
9295 }
9296 
9297 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9298 {
9299 	struct bpf_reg_state *regs = cur_regs(env);
9300 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9301 	bool reg_is_null = register_is_null(reg);
9302 
9303 	if (reg_is_null)
9304 		mark_chain_precision(env, BPF_REG_4);
9305 
9306 	return reg_is_null;
9307 }
9308 
9309 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9310 {
9311 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9312 
9313 	if (!state->initialized) {
9314 		state->initialized = 1;
9315 		state->fit_for_inline = loop_flag_is_zero(env);
9316 		state->callback_subprogno = subprogno;
9317 		return;
9318 	}
9319 
9320 	if (!state->fit_for_inline)
9321 		return;
9322 
9323 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9324 				 state->callback_subprogno == subprogno);
9325 }
9326 
9327 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9328 			     int *insn_idx_p)
9329 {
9330 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9331 	const struct bpf_func_proto *fn = NULL;
9332 	enum bpf_return_type ret_type;
9333 	enum bpf_type_flag ret_flag;
9334 	struct bpf_reg_state *regs;
9335 	struct bpf_call_arg_meta meta;
9336 	int insn_idx = *insn_idx_p;
9337 	bool changes_data;
9338 	int i, err, func_id;
9339 
9340 	/* find function prototype */
9341 	func_id = insn->imm;
9342 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9343 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9344 			func_id);
9345 		return -EINVAL;
9346 	}
9347 
9348 	if (env->ops->get_func_proto)
9349 		fn = env->ops->get_func_proto(func_id, env->prog);
9350 	if (!fn) {
9351 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9352 			func_id);
9353 		return -EINVAL;
9354 	}
9355 
9356 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9357 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9358 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9359 		return -EINVAL;
9360 	}
9361 
9362 	if (fn->allowed && !fn->allowed(env->prog)) {
9363 		verbose(env, "helper call is not allowed in probe\n");
9364 		return -EINVAL;
9365 	}
9366 
9367 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9368 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9369 		return -EINVAL;
9370 	}
9371 
9372 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9373 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9374 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9375 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9376 			func_id_name(func_id), func_id);
9377 		return -EINVAL;
9378 	}
9379 
9380 	memset(&meta, 0, sizeof(meta));
9381 	meta.pkt_access = fn->pkt_access;
9382 
9383 	err = check_func_proto(fn, func_id);
9384 	if (err) {
9385 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9386 			func_id_name(func_id), func_id);
9387 		return err;
9388 	}
9389 
9390 	if (env->cur_state->active_rcu_lock) {
9391 		if (fn->might_sleep) {
9392 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9393 				func_id_name(func_id), func_id);
9394 			return -EINVAL;
9395 		}
9396 
9397 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9398 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9399 	}
9400 
9401 	meta.func_id = func_id;
9402 	/* check args */
9403 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9404 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9405 		if (err)
9406 			return err;
9407 	}
9408 
9409 	err = record_func_map(env, &meta, func_id, insn_idx);
9410 	if (err)
9411 		return err;
9412 
9413 	err = record_func_key(env, &meta, func_id, insn_idx);
9414 	if (err)
9415 		return err;
9416 
9417 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9418 	 * is inferred from register state.
9419 	 */
9420 	for (i = 0; i < meta.access_size; i++) {
9421 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9422 				       BPF_WRITE, -1, false);
9423 		if (err)
9424 			return err;
9425 	}
9426 
9427 	regs = cur_regs(env);
9428 
9429 	if (meta.release_regno) {
9430 		err = -EINVAL;
9431 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9432 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9433 		 * is safe to do directly.
9434 		 */
9435 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9436 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9437 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9438 				return -EFAULT;
9439 			}
9440 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9441 		} else if (meta.ref_obj_id) {
9442 			err = release_reference(env, meta.ref_obj_id);
9443 		} else if (register_is_null(&regs[meta.release_regno])) {
9444 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9445 			 * released is NULL, which must be > R0.
9446 			 */
9447 			err = 0;
9448 		}
9449 		if (err) {
9450 			verbose(env, "func %s#%d reference has not been acquired before\n",
9451 				func_id_name(func_id), func_id);
9452 			return err;
9453 		}
9454 	}
9455 
9456 	switch (func_id) {
9457 	case BPF_FUNC_tail_call:
9458 		err = check_reference_leak(env);
9459 		if (err) {
9460 			verbose(env, "tail_call would lead to reference leak\n");
9461 			return err;
9462 		}
9463 		break;
9464 	case BPF_FUNC_get_local_storage:
9465 		/* check that flags argument in get_local_storage(map, flags) is 0,
9466 		 * this is required because get_local_storage() can't return an error.
9467 		 */
9468 		if (!register_is_null(&regs[BPF_REG_2])) {
9469 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9470 			return -EINVAL;
9471 		}
9472 		break;
9473 	case BPF_FUNC_for_each_map_elem:
9474 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9475 					set_map_elem_callback_state);
9476 		break;
9477 	case BPF_FUNC_timer_set_callback:
9478 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9479 					set_timer_callback_state);
9480 		break;
9481 	case BPF_FUNC_find_vma:
9482 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9483 					set_find_vma_callback_state);
9484 		break;
9485 	case BPF_FUNC_snprintf:
9486 		err = check_bpf_snprintf_call(env, regs);
9487 		break;
9488 	case BPF_FUNC_loop:
9489 		update_loop_inline_state(env, meta.subprogno);
9490 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9491 					set_loop_callback_state);
9492 		break;
9493 	case BPF_FUNC_dynptr_from_mem:
9494 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9495 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9496 				reg_type_str(env, regs[BPF_REG_1].type));
9497 			return -EACCES;
9498 		}
9499 		break;
9500 	case BPF_FUNC_set_retval:
9501 		if (prog_type == BPF_PROG_TYPE_LSM &&
9502 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9503 			if (!env->prog->aux->attach_func_proto->type) {
9504 				/* Make sure programs that attach to void
9505 				 * hooks don't try to modify return value.
9506 				 */
9507 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9508 				return -EINVAL;
9509 			}
9510 		}
9511 		break;
9512 	case BPF_FUNC_dynptr_data:
9513 	{
9514 		struct bpf_reg_state *reg;
9515 		int id, ref_obj_id;
9516 
9517 		reg = get_dynptr_arg_reg(env, fn, regs);
9518 		if (!reg)
9519 			return -EFAULT;
9520 
9521 
9522 		if (meta.dynptr_id) {
9523 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9524 			return -EFAULT;
9525 		}
9526 		if (meta.ref_obj_id) {
9527 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9528 			return -EFAULT;
9529 		}
9530 
9531 		id = dynptr_id(env, reg);
9532 		if (id < 0) {
9533 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9534 			return id;
9535 		}
9536 
9537 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9538 		if (ref_obj_id < 0) {
9539 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9540 			return ref_obj_id;
9541 		}
9542 
9543 		meta.dynptr_id = id;
9544 		meta.ref_obj_id = ref_obj_id;
9545 
9546 		break;
9547 	}
9548 	case BPF_FUNC_dynptr_write:
9549 	{
9550 		enum bpf_dynptr_type dynptr_type;
9551 		struct bpf_reg_state *reg;
9552 
9553 		reg = get_dynptr_arg_reg(env, fn, regs);
9554 		if (!reg)
9555 			return -EFAULT;
9556 
9557 		dynptr_type = dynptr_get_type(env, reg);
9558 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9559 			return -EFAULT;
9560 
9561 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9562 			/* this will trigger clear_all_pkt_pointers(), which will
9563 			 * invalidate all dynptr slices associated with the skb
9564 			 */
9565 			changes_data = true;
9566 
9567 		break;
9568 	}
9569 	case BPF_FUNC_user_ringbuf_drain:
9570 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9571 					set_user_ringbuf_callback_state);
9572 		break;
9573 	}
9574 
9575 	if (err)
9576 		return err;
9577 
9578 	/* reset caller saved regs */
9579 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9580 		mark_reg_not_init(env, regs, caller_saved[i]);
9581 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9582 	}
9583 
9584 	/* helper call returns 64-bit value. */
9585 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9586 
9587 	/* update return register (already marked as written above) */
9588 	ret_type = fn->ret_type;
9589 	ret_flag = type_flag(ret_type);
9590 
9591 	switch (base_type(ret_type)) {
9592 	case RET_INTEGER:
9593 		/* sets type to SCALAR_VALUE */
9594 		mark_reg_unknown(env, regs, BPF_REG_0);
9595 		break;
9596 	case RET_VOID:
9597 		regs[BPF_REG_0].type = NOT_INIT;
9598 		break;
9599 	case RET_PTR_TO_MAP_VALUE:
9600 		/* There is no offset yet applied, variable or fixed */
9601 		mark_reg_known_zero(env, regs, BPF_REG_0);
9602 		/* remember map_ptr, so that check_map_access()
9603 		 * can check 'value_size' boundary of memory access
9604 		 * to map element returned from bpf_map_lookup_elem()
9605 		 */
9606 		if (meta.map_ptr == NULL) {
9607 			verbose(env,
9608 				"kernel subsystem misconfigured verifier\n");
9609 			return -EINVAL;
9610 		}
9611 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9612 		regs[BPF_REG_0].map_uid = meta.map_uid;
9613 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9614 		if (!type_may_be_null(ret_type) &&
9615 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9616 			regs[BPF_REG_0].id = ++env->id_gen;
9617 		}
9618 		break;
9619 	case RET_PTR_TO_SOCKET:
9620 		mark_reg_known_zero(env, regs, BPF_REG_0);
9621 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9622 		break;
9623 	case RET_PTR_TO_SOCK_COMMON:
9624 		mark_reg_known_zero(env, regs, BPF_REG_0);
9625 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9626 		break;
9627 	case RET_PTR_TO_TCP_SOCK:
9628 		mark_reg_known_zero(env, regs, BPF_REG_0);
9629 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9630 		break;
9631 	case RET_PTR_TO_MEM:
9632 		mark_reg_known_zero(env, regs, BPF_REG_0);
9633 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9634 		regs[BPF_REG_0].mem_size = meta.mem_size;
9635 		break;
9636 	case RET_PTR_TO_MEM_OR_BTF_ID:
9637 	{
9638 		const struct btf_type *t;
9639 
9640 		mark_reg_known_zero(env, regs, BPF_REG_0);
9641 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9642 		if (!btf_type_is_struct(t)) {
9643 			u32 tsize;
9644 			const struct btf_type *ret;
9645 			const char *tname;
9646 
9647 			/* resolve the type size of ksym. */
9648 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9649 			if (IS_ERR(ret)) {
9650 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9651 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9652 					tname, PTR_ERR(ret));
9653 				return -EINVAL;
9654 			}
9655 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9656 			regs[BPF_REG_0].mem_size = tsize;
9657 		} else {
9658 			/* MEM_RDONLY may be carried from ret_flag, but it
9659 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9660 			 * it will confuse the check of PTR_TO_BTF_ID in
9661 			 * check_mem_access().
9662 			 */
9663 			ret_flag &= ~MEM_RDONLY;
9664 
9665 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9666 			regs[BPF_REG_0].btf = meta.ret_btf;
9667 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9668 		}
9669 		break;
9670 	}
9671 	case RET_PTR_TO_BTF_ID:
9672 	{
9673 		struct btf *ret_btf;
9674 		int ret_btf_id;
9675 
9676 		mark_reg_known_zero(env, regs, BPF_REG_0);
9677 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9678 		if (func_id == BPF_FUNC_kptr_xchg) {
9679 			ret_btf = meta.kptr_field->kptr.btf;
9680 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9681 			if (!btf_is_kernel(ret_btf))
9682 				regs[BPF_REG_0].type |= MEM_ALLOC;
9683 		} else {
9684 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9685 				verbose(env, "verifier internal error:");
9686 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9687 					func_id_name(func_id));
9688 				return -EINVAL;
9689 			}
9690 			ret_btf = btf_vmlinux;
9691 			ret_btf_id = *fn->ret_btf_id;
9692 		}
9693 		if (ret_btf_id == 0) {
9694 			verbose(env, "invalid return type %u of func %s#%d\n",
9695 				base_type(ret_type), func_id_name(func_id),
9696 				func_id);
9697 			return -EINVAL;
9698 		}
9699 		regs[BPF_REG_0].btf = ret_btf;
9700 		regs[BPF_REG_0].btf_id = ret_btf_id;
9701 		break;
9702 	}
9703 	default:
9704 		verbose(env, "unknown return type %u of func %s#%d\n",
9705 			base_type(ret_type), func_id_name(func_id), func_id);
9706 		return -EINVAL;
9707 	}
9708 
9709 	if (type_may_be_null(regs[BPF_REG_0].type))
9710 		regs[BPF_REG_0].id = ++env->id_gen;
9711 
9712 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9713 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9714 			func_id_name(func_id), func_id);
9715 		return -EFAULT;
9716 	}
9717 
9718 	if (is_dynptr_ref_function(func_id))
9719 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9720 
9721 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9722 		/* For release_reference() */
9723 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9724 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9725 		int id = acquire_reference_state(env, insn_idx);
9726 
9727 		if (id < 0)
9728 			return id;
9729 		/* For mark_ptr_or_null_reg() */
9730 		regs[BPF_REG_0].id = id;
9731 		/* For release_reference() */
9732 		regs[BPF_REG_0].ref_obj_id = id;
9733 	}
9734 
9735 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9736 
9737 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9738 	if (err)
9739 		return err;
9740 
9741 	if ((func_id == BPF_FUNC_get_stack ||
9742 	     func_id == BPF_FUNC_get_task_stack) &&
9743 	    !env->prog->has_callchain_buf) {
9744 		const char *err_str;
9745 
9746 #ifdef CONFIG_PERF_EVENTS
9747 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9748 		err_str = "cannot get callchain buffer for func %s#%d\n";
9749 #else
9750 		err = -ENOTSUPP;
9751 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9752 #endif
9753 		if (err) {
9754 			verbose(env, err_str, func_id_name(func_id), func_id);
9755 			return err;
9756 		}
9757 
9758 		env->prog->has_callchain_buf = true;
9759 	}
9760 
9761 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9762 		env->prog->call_get_stack = true;
9763 
9764 	if (func_id == BPF_FUNC_get_func_ip) {
9765 		if (check_get_func_ip(env))
9766 			return -ENOTSUPP;
9767 		env->prog->call_get_func_ip = true;
9768 	}
9769 
9770 	if (changes_data)
9771 		clear_all_pkt_pointers(env);
9772 	return 0;
9773 }
9774 
9775 /* mark_btf_func_reg_size() is used when the reg size is determined by
9776  * the BTF func_proto's return value size and argument.
9777  */
9778 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9779 				   size_t reg_size)
9780 {
9781 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9782 
9783 	if (regno == BPF_REG_0) {
9784 		/* Function return value */
9785 		reg->live |= REG_LIVE_WRITTEN;
9786 		reg->subreg_def = reg_size == sizeof(u64) ?
9787 			DEF_NOT_SUBREG : env->insn_idx + 1;
9788 	} else {
9789 		/* Function argument */
9790 		if (reg_size == sizeof(u64)) {
9791 			mark_insn_zext(env, reg);
9792 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9793 		} else {
9794 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9795 		}
9796 	}
9797 }
9798 
9799 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9800 {
9801 	return meta->kfunc_flags & KF_ACQUIRE;
9802 }
9803 
9804 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9805 {
9806 	return meta->kfunc_flags & KF_RELEASE;
9807 }
9808 
9809 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9810 {
9811 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9812 }
9813 
9814 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9815 {
9816 	return meta->kfunc_flags & KF_SLEEPABLE;
9817 }
9818 
9819 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9820 {
9821 	return meta->kfunc_flags & KF_DESTRUCTIVE;
9822 }
9823 
9824 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9825 {
9826 	return meta->kfunc_flags & KF_RCU;
9827 }
9828 
9829 static bool __kfunc_param_match_suffix(const struct btf *btf,
9830 				       const struct btf_param *arg,
9831 				       const char *suffix)
9832 {
9833 	int suffix_len = strlen(suffix), len;
9834 	const char *param_name;
9835 
9836 	/* In the future, this can be ported to use BTF tagging */
9837 	param_name = btf_name_by_offset(btf, arg->name_off);
9838 	if (str_is_empty(param_name))
9839 		return false;
9840 	len = strlen(param_name);
9841 	if (len < suffix_len)
9842 		return false;
9843 	param_name += len - suffix_len;
9844 	return !strncmp(param_name, suffix, suffix_len);
9845 }
9846 
9847 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9848 				  const struct btf_param *arg,
9849 				  const struct bpf_reg_state *reg)
9850 {
9851 	const struct btf_type *t;
9852 
9853 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9854 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9855 		return false;
9856 
9857 	return __kfunc_param_match_suffix(btf, arg, "__sz");
9858 }
9859 
9860 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9861 					const struct btf_param *arg,
9862 					const struct bpf_reg_state *reg)
9863 {
9864 	const struct btf_type *t;
9865 
9866 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9867 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9868 		return false;
9869 
9870 	return __kfunc_param_match_suffix(btf, arg, "__szk");
9871 }
9872 
9873 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9874 {
9875 	return __kfunc_param_match_suffix(btf, arg, "__opt");
9876 }
9877 
9878 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9879 {
9880 	return __kfunc_param_match_suffix(btf, arg, "__k");
9881 }
9882 
9883 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9884 {
9885 	return __kfunc_param_match_suffix(btf, arg, "__ign");
9886 }
9887 
9888 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9889 {
9890 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
9891 }
9892 
9893 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9894 {
9895 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
9896 }
9897 
9898 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9899 {
9900 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9901 }
9902 
9903 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9904 					  const struct btf_param *arg,
9905 					  const char *name)
9906 {
9907 	int len, target_len = strlen(name);
9908 	const char *param_name;
9909 
9910 	param_name = btf_name_by_offset(btf, arg->name_off);
9911 	if (str_is_empty(param_name))
9912 		return false;
9913 	len = strlen(param_name);
9914 	if (len != target_len)
9915 		return false;
9916 	if (strcmp(param_name, name))
9917 		return false;
9918 
9919 	return true;
9920 }
9921 
9922 enum {
9923 	KF_ARG_DYNPTR_ID,
9924 	KF_ARG_LIST_HEAD_ID,
9925 	KF_ARG_LIST_NODE_ID,
9926 	KF_ARG_RB_ROOT_ID,
9927 	KF_ARG_RB_NODE_ID,
9928 };
9929 
9930 BTF_ID_LIST(kf_arg_btf_ids)
9931 BTF_ID(struct, bpf_dynptr_kern)
9932 BTF_ID(struct, bpf_list_head)
9933 BTF_ID(struct, bpf_list_node)
9934 BTF_ID(struct, bpf_rb_root)
9935 BTF_ID(struct, bpf_rb_node)
9936 
9937 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9938 				    const struct btf_param *arg, int type)
9939 {
9940 	const struct btf_type *t;
9941 	u32 res_id;
9942 
9943 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9944 	if (!t)
9945 		return false;
9946 	if (!btf_type_is_ptr(t))
9947 		return false;
9948 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
9949 	if (!t)
9950 		return false;
9951 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9952 }
9953 
9954 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9955 {
9956 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9957 }
9958 
9959 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9960 {
9961 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9962 }
9963 
9964 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9965 {
9966 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9967 }
9968 
9969 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9970 {
9971 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9972 }
9973 
9974 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9975 {
9976 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9977 }
9978 
9979 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9980 				  const struct btf_param *arg)
9981 {
9982 	const struct btf_type *t;
9983 
9984 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9985 	if (!t)
9986 		return false;
9987 
9988 	return true;
9989 }
9990 
9991 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9992 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9993 					const struct btf *btf,
9994 					const struct btf_type *t, int rec)
9995 {
9996 	const struct btf_type *member_type;
9997 	const struct btf_member *member;
9998 	u32 i;
9999 
10000 	if (!btf_type_is_struct(t))
10001 		return false;
10002 
10003 	for_each_member(i, t, member) {
10004 		const struct btf_array *array;
10005 
10006 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10007 		if (btf_type_is_struct(member_type)) {
10008 			if (rec >= 3) {
10009 				verbose(env, "max struct nesting depth exceeded\n");
10010 				return false;
10011 			}
10012 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10013 				return false;
10014 			continue;
10015 		}
10016 		if (btf_type_is_array(member_type)) {
10017 			array = btf_array(member_type);
10018 			if (!array->nelems)
10019 				return false;
10020 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10021 			if (!btf_type_is_scalar(member_type))
10022 				return false;
10023 			continue;
10024 		}
10025 		if (!btf_type_is_scalar(member_type))
10026 			return false;
10027 	}
10028 	return true;
10029 }
10030 
10031 
10032 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
10033 #ifdef CONFIG_NET
10034 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
10035 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
10036 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
10037 #endif
10038 };
10039 
10040 enum kfunc_ptr_arg_type {
10041 	KF_ARG_PTR_TO_CTX,
10042 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10043 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10044 	KF_ARG_PTR_TO_DYNPTR,
10045 	KF_ARG_PTR_TO_ITER,
10046 	KF_ARG_PTR_TO_LIST_HEAD,
10047 	KF_ARG_PTR_TO_LIST_NODE,
10048 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10049 	KF_ARG_PTR_TO_MEM,
10050 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10051 	KF_ARG_PTR_TO_CALLBACK,
10052 	KF_ARG_PTR_TO_RB_ROOT,
10053 	KF_ARG_PTR_TO_RB_NODE,
10054 };
10055 
10056 enum special_kfunc_type {
10057 	KF_bpf_obj_new_impl,
10058 	KF_bpf_obj_drop_impl,
10059 	KF_bpf_refcount_acquire_impl,
10060 	KF_bpf_list_push_front_impl,
10061 	KF_bpf_list_push_back_impl,
10062 	KF_bpf_list_pop_front,
10063 	KF_bpf_list_pop_back,
10064 	KF_bpf_cast_to_kern_ctx,
10065 	KF_bpf_rdonly_cast,
10066 	KF_bpf_rcu_read_lock,
10067 	KF_bpf_rcu_read_unlock,
10068 	KF_bpf_rbtree_remove,
10069 	KF_bpf_rbtree_add_impl,
10070 	KF_bpf_rbtree_first,
10071 	KF_bpf_dynptr_from_skb,
10072 	KF_bpf_dynptr_from_xdp,
10073 	KF_bpf_dynptr_slice,
10074 	KF_bpf_dynptr_slice_rdwr,
10075 	KF_bpf_dynptr_clone,
10076 };
10077 
10078 BTF_SET_START(special_kfunc_set)
10079 BTF_ID(func, bpf_obj_new_impl)
10080 BTF_ID(func, bpf_obj_drop_impl)
10081 BTF_ID(func, bpf_refcount_acquire_impl)
10082 BTF_ID(func, bpf_list_push_front_impl)
10083 BTF_ID(func, bpf_list_push_back_impl)
10084 BTF_ID(func, bpf_list_pop_front)
10085 BTF_ID(func, bpf_list_pop_back)
10086 BTF_ID(func, bpf_cast_to_kern_ctx)
10087 BTF_ID(func, bpf_rdonly_cast)
10088 BTF_ID(func, bpf_rbtree_remove)
10089 BTF_ID(func, bpf_rbtree_add_impl)
10090 BTF_ID(func, bpf_rbtree_first)
10091 BTF_ID(func, bpf_dynptr_from_skb)
10092 BTF_ID(func, bpf_dynptr_from_xdp)
10093 BTF_ID(func, bpf_dynptr_slice)
10094 BTF_ID(func, bpf_dynptr_slice_rdwr)
10095 BTF_ID(func, bpf_dynptr_clone)
10096 BTF_SET_END(special_kfunc_set)
10097 
10098 BTF_ID_LIST(special_kfunc_list)
10099 BTF_ID(func, bpf_obj_new_impl)
10100 BTF_ID(func, bpf_obj_drop_impl)
10101 BTF_ID(func, bpf_refcount_acquire_impl)
10102 BTF_ID(func, bpf_list_push_front_impl)
10103 BTF_ID(func, bpf_list_push_back_impl)
10104 BTF_ID(func, bpf_list_pop_front)
10105 BTF_ID(func, bpf_list_pop_back)
10106 BTF_ID(func, bpf_cast_to_kern_ctx)
10107 BTF_ID(func, bpf_rdonly_cast)
10108 BTF_ID(func, bpf_rcu_read_lock)
10109 BTF_ID(func, bpf_rcu_read_unlock)
10110 BTF_ID(func, bpf_rbtree_remove)
10111 BTF_ID(func, bpf_rbtree_add_impl)
10112 BTF_ID(func, bpf_rbtree_first)
10113 BTF_ID(func, bpf_dynptr_from_skb)
10114 BTF_ID(func, bpf_dynptr_from_xdp)
10115 BTF_ID(func, bpf_dynptr_slice)
10116 BTF_ID(func, bpf_dynptr_slice_rdwr)
10117 BTF_ID(func, bpf_dynptr_clone)
10118 
10119 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10120 {
10121 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10122 	    meta->arg_owning_ref) {
10123 		return false;
10124 	}
10125 
10126 	return meta->kfunc_flags & KF_RET_NULL;
10127 }
10128 
10129 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10130 {
10131 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10132 }
10133 
10134 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10135 {
10136 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10137 }
10138 
10139 static enum kfunc_ptr_arg_type
10140 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10141 		       struct bpf_kfunc_call_arg_meta *meta,
10142 		       const struct btf_type *t, const struct btf_type *ref_t,
10143 		       const char *ref_tname, const struct btf_param *args,
10144 		       int argno, int nargs)
10145 {
10146 	u32 regno = argno + 1;
10147 	struct bpf_reg_state *regs = cur_regs(env);
10148 	struct bpf_reg_state *reg = &regs[regno];
10149 	bool arg_mem_size = false;
10150 
10151 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10152 		return KF_ARG_PTR_TO_CTX;
10153 
10154 	/* In this function, we verify the kfunc's BTF as per the argument type,
10155 	 * leaving the rest of the verification with respect to the register
10156 	 * type to our caller. When a set of conditions hold in the BTF type of
10157 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10158 	 */
10159 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10160 		return KF_ARG_PTR_TO_CTX;
10161 
10162 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10163 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10164 
10165 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10166 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10167 
10168 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10169 		return KF_ARG_PTR_TO_DYNPTR;
10170 
10171 	if (is_kfunc_arg_iter(meta, argno))
10172 		return KF_ARG_PTR_TO_ITER;
10173 
10174 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10175 		return KF_ARG_PTR_TO_LIST_HEAD;
10176 
10177 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10178 		return KF_ARG_PTR_TO_LIST_NODE;
10179 
10180 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10181 		return KF_ARG_PTR_TO_RB_ROOT;
10182 
10183 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10184 		return KF_ARG_PTR_TO_RB_NODE;
10185 
10186 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10187 		if (!btf_type_is_struct(ref_t)) {
10188 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10189 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10190 			return -EINVAL;
10191 		}
10192 		return KF_ARG_PTR_TO_BTF_ID;
10193 	}
10194 
10195 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10196 		return KF_ARG_PTR_TO_CALLBACK;
10197 
10198 
10199 	if (argno + 1 < nargs &&
10200 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10201 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10202 		arg_mem_size = true;
10203 
10204 	/* This is the catch all argument type of register types supported by
10205 	 * check_helper_mem_access. However, we only allow when argument type is
10206 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10207 	 * arg_mem_size is true, the pointer can be void *.
10208 	 */
10209 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10210 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10211 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10212 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10213 		return -EINVAL;
10214 	}
10215 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10216 }
10217 
10218 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10219 					struct bpf_reg_state *reg,
10220 					const struct btf_type *ref_t,
10221 					const char *ref_tname, u32 ref_id,
10222 					struct bpf_kfunc_call_arg_meta *meta,
10223 					int argno)
10224 {
10225 	const struct btf_type *reg_ref_t;
10226 	bool strict_type_match = false;
10227 	const struct btf *reg_btf;
10228 	const char *reg_ref_tname;
10229 	u32 reg_ref_id;
10230 
10231 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10232 		reg_btf = reg->btf;
10233 		reg_ref_id = reg->btf_id;
10234 	} else {
10235 		reg_btf = btf_vmlinux;
10236 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10237 	}
10238 
10239 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10240 	 * or releasing a reference, or are no-cast aliases. We do _not_
10241 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10242 	 * as we want to enable BPF programs to pass types that are bitwise
10243 	 * equivalent without forcing them to explicitly cast with something
10244 	 * like bpf_cast_to_kern_ctx().
10245 	 *
10246 	 * For example, say we had a type like the following:
10247 	 *
10248 	 * struct bpf_cpumask {
10249 	 *	cpumask_t cpumask;
10250 	 *	refcount_t usage;
10251 	 * };
10252 	 *
10253 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10254 	 * to a struct cpumask, so it would be safe to pass a struct
10255 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10256 	 *
10257 	 * The philosophy here is similar to how we allow scalars of different
10258 	 * types to be passed to kfuncs as long as the size is the same. The
10259 	 * only difference here is that we're simply allowing
10260 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10261 	 * resolve types.
10262 	 */
10263 	if (is_kfunc_acquire(meta) ||
10264 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10265 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10266 		strict_type_match = true;
10267 
10268 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10269 
10270 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10271 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10272 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10273 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10274 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10275 			btf_type_str(reg_ref_t), reg_ref_tname);
10276 		return -EINVAL;
10277 	}
10278 	return 0;
10279 }
10280 
10281 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10282 {
10283 	struct bpf_verifier_state *state = env->cur_state;
10284 
10285 	if (!state->active_lock.ptr) {
10286 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10287 		return -EFAULT;
10288 	}
10289 
10290 	if (type_flag(reg->type) & NON_OWN_REF) {
10291 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10292 		return -EFAULT;
10293 	}
10294 
10295 	reg->type |= NON_OWN_REF;
10296 	return 0;
10297 }
10298 
10299 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10300 {
10301 	struct bpf_func_state *state, *unused;
10302 	struct bpf_reg_state *reg;
10303 	int i;
10304 
10305 	state = cur_func(env);
10306 
10307 	if (!ref_obj_id) {
10308 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10309 			     "owning -> non-owning conversion\n");
10310 		return -EFAULT;
10311 	}
10312 
10313 	for (i = 0; i < state->acquired_refs; i++) {
10314 		if (state->refs[i].id != ref_obj_id)
10315 			continue;
10316 
10317 		/* Clear ref_obj_id here so release_reference doesn't clobber
10318 		 * the whole reg
10319 		 */
10320 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10321 			if (reg->ref_obj_id == ref_obj_id) {
10322 				reg->ref_obj_id = 0;
10323 				ref_set_non_owning(env, reg);
10324 			}
10325 		}));
10326 		return 0;
10327 	}
10328 
10329 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10330 	return -EFAULT;
10331 }
10332 
10333 /* Implementation details:
10334  *
10335  * Each register points to some region of memory, which we define as an
10336  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10337  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10338  * allocation. The lock and the data it protects are colocated in the same
10339  * memory region.
10340  *
10341  * Hence, everytime a register holds a pointer value pointing to such
10342  * allocation, the verifier preserves a unique reg->id for it.
10343  *
10344  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10345  * bpf_spin_lock is called.
10346  *
10347  * To enable this, lock state in the verifier captures two values:
10348  *	active_lock.ptr = Register's type specific pointer
10349  *	active_lock.id  = A unique ID for each register pointer value
10350  *
10351  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10352  * supported register types.
10353  *
10354  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10355  * allocated objects is the reg->btf pointer.
10356  *
10357  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10358  * can establish the provenance of the map value statically for each distinct
10359  * lookup into such maps. They always contain a single map value hence unique
10360  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10361  *
10362  * So, in case of global variables, they use array maps with max_entries = 1,
10363  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10364  * into the same map value as max_entries is 1, as described above).
10365  *
10366  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10367  * outer map pointer (in verifier context), but each lookup into an inner map
10368  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10369  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10370  * will get different reg->id assigned to each lookup, hence different
10371  * active_lock.id.
10372  *
10373  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10374  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10375  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10376  */
10377 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10378 {
10379 	void *ptr;
10380 	u32 id;
10381 
10382 	switch ((int)reg->type) {
10383 	case PTR_TO_MAP_VALUE:
10384 		ptr = reg->map_ptr;
10385 		break;
10386 	case PTR_TO_BTF_ID | MEM_ALLOC:
10387 		ptr = reg->btf;
10388 		break;
10389 	default:
10390 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10391 		return -EFAULT;
10392 	}
10393 	id = reg->id;
10394 
10395 	if (!env->cur_state->active_lock.ptr)
10396 		return -EINVAL;
10397 	if (env->cur_state->active_lock.ptr != ptr ||
10398 	    env->cur_state->active_lock.id != id) {
10399 		verbose(env, "held lock and object are not in the same allocation\n");
10400 		return -EINVAL;
10401 	}
10402 	return 0;
10403 }
10404 
10405 static bool is_bpf_list_api_kfunc(u32 btf_id)
10406 {
10407 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10408 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10409 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10410 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10411 }
10412 
10413 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10414 {
10415 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10416 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10417 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10418 }
10419 
10420 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10421 {
10422 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10423 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10424 }
10425 
10426 static bool is_callback_calling_kfunc(u32 btf_id)
10427 {
10428 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10429 }
10430 
10431 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10432 {
10433 	return is_bpf_rbtree_api_kfunc(btf_id);
10434 }
10435 
10436 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10437 					  enum btf_field_type head_field_type,
10438 					  u32 kfunc_btf_id)
10439 {
10440 	bool ret;
10441 
10442 	switch (head_field_type) {
10443 	case BPF_LIST_HEAD:
10444 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10445 		break;
10446 	case BPF_RB_ROOT:
10447 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10448 		break;
10449 	default:
10450 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10451 			btf_field_type_name(head_field_type));
10452 		return false;
10453 	}
10454 
10455 	if (!ret)
10456 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10457 			btf_field_type_name(head_field_type));
10458 	return ret;
10459 }
10460 
10461 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10462 					  enum btf_field_type node_field_type,
10463 					  u32 kfunc_btf_id)
10464 {
10465 	bool ret;
10466 
10467 	switch (node_field_type) {
10468 	case BPF_LIST_NODE:
10469 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10470 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10471 		break;
10472 	case BPF_RB_NODE:
10473 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10474 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10475 		break;
10476 	default:
10477 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10478 			btf_field_type_name(node_field_type));
10479 		return false;
10480 	}
10481 
10482 	if (!ret)
10483 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10484 			btf_field_type_name(node_field_type));
10485 	return ret;
10486 }
10487 
10488 static int
10489 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10490 				   struct bpf_reg_state *reg, u32 regno,
10491 				   struct bpf_kfunc_call_arg_meta *meta,
10492 				   enum btf_field_type head_field_type,
10493 				   struct btf_field **head_field)
10494 {
10495 	const char *head_type_name;
10496 	struct btf_field *field;
10497 	struct btf_record *rec;
10498 	u32 head_off;
10499 
10500 	if (meta->btf != btf_vmlinux) {
10501 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10502 		return -EFAULT;
10503 	}
10504 
10505 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10506 		return -EFAULT;
10507 
10508 	head_type_name = btf_field_type_name(head_field_type);
10509 	if (!tnum_is_const(reg->var_off)) {
10510 		verbose(env,
10511 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10512 			regno, head_type_name);
10513 		return -EINVAL;
10514 	}
10515 
10516 	rec = reg_btf_record(reg);
10517 	head_off = reg->off + reg->var_off.value;
10518 	field = btf_record_find(rec, head_off, head_field_type);
10519 	if (!field) {
10520 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10521 		return -EINVAL;
10522 	}
10523 
10524 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10525 	if (check_reg_allocation_locked(env, reg)) {
10526 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10527 			rec->spin_lock_off, head_type_name);
10528 		return -EINVAL;
10529 	}
10530 
10531 	if (*head_field) {
10532 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10533 		return -EFAULT;
10534 	}
10535 	*head_field = field;
10536 	return 0;
10537 }
10538 
10539 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10540 					   struct bpf_reg_state *reg, u32 regno,
10541 					   struct bpf_kfunc_call_arg_meta *meta)
10542 {
10543 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10544 							  &meta->arg_list_head.field);
10545 }
10546 
10547 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10548 					     struct bpf_reg_state *reg, u32 regno,
10549 					     struct bpf_kfunc_call_arg_meta *meta)
10550 {
10551 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10552 							  &meta->arg_rbtree_root.field);
10553 }
10554 
10555 static int
10556 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10557 				   struct bpf_reg_state *reg, u32 regno,
10558 				   struct bpf_kfunc_call_arg_meta *meta,
10559 				   enum btf_field_type head_field_type,
10560 				   enum btf_field_type node_field_type,
10561 				   struct btf_field **node_field)
10562 {
10563 	const char *node_type_name;
10564 	const struct btf_type *et, *t;
10565 	struct btf_field *field;
10566 	u32 node_off;
10567 
10568 	if (meta->btf != btf_vmlinux) {
10569 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10570 		return -EFAULT;
10571 	}
10572 
10573 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10574 		return -EFAULT;
10575 
10576 	node_type_name = btf_field_type_name(node_field_type);
10577 	if (!tnum_is_const(reg->var_off)) {
10578 		verbose(env,
10579 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10580 			regno, node_type_name);
10581 		return -EINVAL;
10582 	}
10583 
10584 	node_off = reg->off + reg->var_off.value;
10585 	field = reg_find_field_offset(reg, node_off, node_field_type);
10586 	if (!field || field->offset != node_off) {
10587 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10588 		return -EINVAL;
10589 	}
10590 
10591 	field = *node_field;
10592 
10593 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10594 	t = btf_type_by_id(reg->btf, reg->btf_id);
10595 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10596 				  field->graph_root.value_btf_id, true)) {
10597 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10598 			"in struct %s, but arg is at offset=%d in struct %s\n",
10599 			btf_field_type_name(head_field_type),
10600 			btf_field_type_name(node_field_type),
10601 			field->graph_root.node_offset,
10602 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10603 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10604 		return -EINVAL;
10605 	}
10606 	meta->arg_btf = reg->btf;
10607 	meta->arg_btf_id = reg->btf_id;
10608 
10609 	if (node_off != field->graph_root.node_offset) {
10610 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10611 			node_off, btf_field_type_name(node_field_type),
10612 			field->graph_root.node_offset,
10613 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10614 		return -EINVAL;
10615 	}
10616 
10617 	return 0;
10618 }
10619 
10620 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10621 					   struct bpf_reg_state *reg, u32 regno,
10622 					   struct bpf_kfunc_call_arg_meta *meta)
10623 {
10624 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10625 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10626 						  &meta->arg_list_head.field);
10627 }
10628 
10629 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10630 					     struct bpf_reg_state *reg, u32 regno,
10631 					     struct bpf_kfunc_call_arg_meta *meta)
10632 {
10633 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10634 						  BPF_RB_ROOT, BPF_RB_NODE,
10635 						  &meta->arg_rbtree_root.field);
10636 }
10637 
10638 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10639 			    int insn_idx)
10640 {
10641 	const char *func_name = meta->func_name, *ref_tname;
10642 	const struct btf *btf = meta->btf;
10643 	const struct btf_param *args;
10644 	struct btf_record *rec;
10645 	u32 i, nargs;
10646 	int ret;
10647 
10648 	args = (const struct btf_param *)(meta->func_proto + 1);
10649 	nargs = btf_type_vlen(meta->func_proto);
10650 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10651 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10652 			MAX_BPF_FUNC_REG_ARGS);
10653 		return -EINVAL;
10654 	}
10655 
10656 	/* Check that BTF function arguments match actual types that the
10657 	 * verifier sees.
10658 	 */
10659 	for (i = 0; i < nargs; i++) {
10660 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10661 		const struct btf_type *t, *ref_t, *resolve_ret;
10662 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10663 		u32 regno = i + 1, ref_id, type_size;
10664 		bool is_ret_buf_sz = false;
10665 		int kf_arg_type;
10666 
10667 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10668 
10669 		if (is_kfunc_arg_ignore(btf, &args[i]))
10670 			continue;
10671 
10672 		if (btf_type_is_scalar(t)) {
10673 			if (reg->type != SCALAR_VALUE) {
10674 				verbose(env, "R%d is not a scalar\n", regno);
10675 				return -EINVAL;
10676 			}
10677 
10678 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10679 				if (meta->arg_constant.found) {
10680 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10681 					return -EFAULT;
10682 				}
10683 				if (!tnum_is_const(reg->var_off)) {
10684 					verbose(env, "R%d must be a known constant\n", regno);
10685 					return -EINVAL;
10686 				}
10687 				ret = mark_chain_precision(env, regno);
10688 				if (ret < 0)
10689 					return ret;
10690 				meta->arg_constant.found = true;
10691 				meta->arg_constant.value = reg->var_off.value;
10692 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10693 				meta->r0_rdonly = true;
10694 				is_ret_buf_sz = true;
10695 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10696 				is_ret_buf_sz = true;
10697 			}
10698 
10699 			if (is_ret_buf_sz) {
10700 				if (meta->r0_size) {
10701 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10702 					return -EINVAL;
10703 				}
10704 
10705 				if (!tnum_is_const(reg->var_off)) {
10706 					verbose(env, "R%d is not a const\n", regno);
10707 					return -EINVAL;
10708 				}
10709 
10710 				meta->r0_size = reg->var_off.value;
10711 				ret = mark_chain_precision(env, regno);
10712 				if (ret)
10713 					return ret;
10714 			}
10715 			continue;
10716 		}
10717 
10718 		if (!btf_type_is_ptr(t)) {
10719 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10720 			return -EINVAL;
10721 		}
10722 
10723 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10724 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10725 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10726 			return -EACCES;
10727 		}
10728 
10729 		if (reg->ref_obj_id) {
10730 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10731 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10732 					regno, reg->ref_obj_id,
10733 					meta->ref_obj_id);
10734 				return -EFAULT;
10735 			}
10736 			meta->ref_obj_id = reg->ref_obj_id;
10737 			if (is_kfunc_release(meta))
10738 				meta->release_regno = regno;
10739 		}
10740 
10741 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10742 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10743 
10744 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10745 		if (kf_arg_type < 0)
10746 			return kf_arg_type;
10747 
10748 		switch (kf_arg_type) {
10749 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10750 		case KF_ARG_PTR_TO_BTF_ID:
10751 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10752 				break;
10753 
10754 			if (!is_trusted_reg(reg)) {
10755 				if (!is_kfunc_rcu(meta)) {
10756 					verbose(env, "R%d must be referenced or trusted\n", regno);
10757 					return -EINVAL;
10758 				}
10759 				if (!is_rcu_reg(reg)) {
10760 					verbose(env, "R%d must be a rcu pointer\n", regno);
10761 					return -EINVAL;
10762 				}
10763 			}
10764 
10765 			fallthrough;
10766 		case KF_ARG_PTR_TO_CTX:
10767 			/* Trusted arguments have the same offset checks as release arguments */
10768 			arg_type |= OBJ_RELEASE;
10769 			break;
10770 		case KF_ARG_PTR_TO_DYNPTR:
10771 		case KF_ARG_PTR_TO_ITER:
10772 		case KF_ARG_PTR_TO_LIST_HEAD:
10773 		case KF_ARG_PTR_TO_LIST_NODE:
10774 		case KF_ARG_PTR_TO_RB_ROOT:
10775 		case KF_ARG_PTR_TO_RB_NODE:
10776 		case KF_ARG_PTR_TO_MEM:
10777 		case KF_ARG_PTR_TO_MEM_SIZE:
10778 		case KF_ARG_PTR_TO_CALLBACK:
10779 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10780 			/* Trusted by default */
10781 			break;
10782 		default:
10783 			WARN_ON_ONCE(1);
10784 			return -EFAULT;
10785 		}
10786 
10787 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10788 			arg_type |= OBJ_RELEASE;
10789 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10790 		if (ret < 0)
10791 			return ret;
10792 
10793 		switch (kf_arg_type) {
10794 		case KF_ARG_PTR_TO_CTX:
10795 			if (reg->type != PTR_TO_CTX) {
10796 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10797 				return -EINVAL;
10798 			}
10799 
10800 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10801 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10802 				if (ret < 0)
10803 					return -EINVAL;
10804 				meta->ret_btf_id  = ret;
10805 			}
10806 			break;
10807 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10808 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10809 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10810 				return -EINVAL;
10811 			}
10812 			if (!reg->ref_obj_id) {
10813 				verbose(env, "allocated object must be referenced\n");
10814 				return -EINVAL;
10815 			}
10816 			if (meta->btf == btf_vmlinux &&
10817 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10818 				meta->arg_btf = reg->btf;
10819 				meta->arg_btf_id = reg->btf_id;
10820 			}
10821 			break;
10822 		case KF_ARG_PTR_TO_DYNPTR:
10823 		{
10824 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10825 			int clone_ref_obj_id = 0;
10826 
10827 			if (reg->type != PTR_TO_STACK &&
10828 			    reg->type != CONST_PTR_TO_DYNPTR) {
10829 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10830 				return -EINVAL;
10831 			}
10832 
10833 			if (reg->type == CONST_PTR_TO_DYNPTR)
10834 				dynptr_arg_type |= MEM_RDONLY;
10835 
10836 			if (is_kfunc_arg_uninit(btf, &args[i]))
10837 				dynptr_arg_type |= MEM_UNINIT;
10838 
10839 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10840 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
10841 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10842 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
10843 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10844 				   (dynptr_arg_type & MEM_UNINIT)) {
10845 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10846 
10847 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10848 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10849 					return -EFAULT;
10850 				}
10851 
10852 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10853 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10854 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10855 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10856 					return -EFAULT;
10857 				}
10858 			}
10859 
10860 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10861 			if (ret < 0)
10862 				return ret;
10863 
10864 			if (!(dynptr_arg_type & MEM_UNINIT)) {
10865 				int id = dynptr_id(env, reg);
10866 
10867 				if (id < 0) {
10868 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10869 					return id;
10870 				}
10871 				meta->initialized_dynptr.id = id;
10872 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10873 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10874 			}
10875 
10876 			break;
10877 		}
10878 		case KF_ARG_PTR_TO_ITER:
10879 			ret = process_iter_arg(env, regno, insn_idx, meta);
10880 			if (ret < 0)
10881 				return ret;
10882 			break;
10883 		case KF_ARG_PTR_TO_LIST_HEAD:
10884 			if (reg->type != PTR_TO_MAP_VALUE &&
10885 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10886 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10887 				return -EINVAL;
10888 			}
10889 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10890 				verbose(env, "allocated object must be referenced\n");
10891 				return -EINVAL;
10892 			}
10893 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10894 			if (ret < 0)
10895 				return ret;
10896 			break;
10897 		case KF_ARG_PTR_TO_RB_ROOT:
10898 			if (reg->type != PTR_TO_MAP_VALUE &&
10899 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10900 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10901 				return -EINVAL;
10902 			}
10903 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10904 				verbose(env, "allocated object must be referenced\n");
10905 				return -EINVAL;
10906 			}
10907 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10908 			if (ret < 0)
10909 				return ret;
10910 			break;
10911 		case KF_ARG_PTR_TO_LIST_NODE:
10912 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10913 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10914 				return -EINVAL;
10915 			}
10916 			if (!reg->ref_obj_id) {
10917 				verbose(env, "allocated object must be referenced\n");
10918 				return -EINVAL;
10919 			}
10920 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10921 			if (ret < 0)
10922 				return ret;
10923 			break;
10924 		case KF_ARG_PTR_TO_RB_NODE:
10925 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10926 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10927 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
10928 					return -EINVAL;
10929 				}
10930 				if (in_rbtree_lock_required_cb(env)) {
10931 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10932 					return -EINVAL;
10933 				}
10934 			} else {
10935 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10936 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10937 					return -EINVAL;
10938 				}
10939 				if (!reg->ref_obj_id) {
10940 					verbose(env, "allocated object must be referenced\n");
10941 					return -EINVAL;
10942 				}
10943 			}
10944 
10945 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10946 			if (ret < 0)
10947 				return ret;
10948 			break;
10949 		case KF_ARG_PTR_TO_BTF_ID:
10950 			/* Only base_type is checked, further checks are done here */
10951 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10952 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10953 			    !reg2btf_ids[base_type(reg->type)]) {
10954 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10955 				verbose(env, "expected %s or socket\n",
10956 					reg_type_str(env, base_type(reg->type) |
10957 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10958 				return -EINVAL;
10959 			}
10960 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10961 			if (ret < 0)
10962 				return ret;
10963 			break;
10964 		case KF_ARG_PTR_TO_MEM:
10965 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10966 			if (IS_ERR(resolve_ret)) {
10967 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10968 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10969 				return -EINVAL;
10970 			}
10971 			ret = check_mem_reg(env, reg, regno, type_size);
10972 			if (ret < 0)
10973 				return ret;
10974 			break;
10975 		case KF_ARG_PTR_TO_MEM_SIZE:
10976 		{
10977 			struct bpf_reg_state *buff_reg = &regs[regno];
10978 			const struct btf_param *buff_arg = &args[i];
10979 			struct bpf_reg_state *size_reg = &regs[regno + 1];
10980 			const struct btf_param *size_arg = &args[i + 1];
10981 
10982 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
10983 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10984 				if (ret < 0) {
10985 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10986 					return ret;
10987 				}
10988 			}
10989 
10990 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10991 				if (meta->arg_constant.found) {
10992 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10993 					return -EFAULT;
10994 				}
10995 				if (!tnum_is_const(size_reg->var_off)) {
10996 					verbose(env, "R%d must be a known constant\n", regno + 1);
10997 					return -EINVAL;
10998 				}
10999 				meta->arg_constant.found = true;
11000 				meta->arg_constant.value = size_reg->var_off.value;
11001 			}
11002 
11003 			/* Skip next '__sz' or '__szk' argument */
11004 			i++;
11005 			break;
11006 		}
11007 		case KF_ARG_PTR_TO_CALLBACK:
11008 			meta->subprogno = reg->subprogno;
11009 			break;
11010 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11011 			if (!type_is_ptr_alloc_obj(reg->type)) {
11012 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11013 				return -EINVAL;
11014 			}
11015 			if (!type_is_non_owning_ref(reg->type))
11016 				meta->arg_owning_ref = true;
11017 
11018 			rec = reg_btf_record(reg);
11019 			if (!rec) {
11020 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11021 				return -EFAULT;
11022 			}
11023 
11024 			if (rec->refcount_off < 0) {
11025 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11026 				return -EINVAL;
11027 			}
11028 			if (rec->refcount_off >= 0) {
11029 				verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11030 				return -EINVAL;
11031 			}
11032 			meta->arg_btf = reg->btf;
11033 			meta->arg_btf_id = reg->btf_id;
11034 			break;
11035 		}
11036 	}
11037 
11038 	if (is_kfunc_release(meta) && !meta->release_regno) {
11039 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11040 			func_name);
11041 		return -EINVAL;
11042 	}
11043 
11044 	return 0;
11045 }
11046 
11047 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11048 			    struct bpf_insn *insn,
11049 			    struct bpf_kfunc_call_arg_meta *meta,
11050 			    const char **kfunc_name)
11051 {
11052 	const struct btf_type *func, *func_proto;
11053 	u32 func_id, *kfunc_flags;
11054 	const char *func_name;
11055 	struct btf *desc_btf;
11056 
11057 	if (kfunc_name)
11058 		*kfunc_name = NULL;
11059 
11060 	if (!insn->imm)
11061 		return -EINVAL;
11062 
11063 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11064 	if (IS_ERR(desc_btf))
11065 		return PTR_ERR(desc_btf);
11066 
11067 	func_id = insn->imm;
11068 	func = btf_type_by_id(desc_btf, func_id);
11069 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11070 	if (kfunc_name)
11071 		*kfunc_name = func_name;
11072 	func_proto = btf_type_by_id(desc_btf, func->type);
11073 
11074 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11075 	if (!kfunc_flags) {
11076 		return -EACCES;
11077 	}
11078 
11079 	memset(meta, 0, sizeof(*meta));
11080 	meta->btf = desc_btf;
11081 	meta->func_id = func_id;
11082 	meta->kfunc_flags = *kfunc_flags;
11083 	meta->func_proto = func_proto;
11084 	meta->func_name = func_name;
11085 
11086 	return 0;
11087 }
11088 
11089 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11090 			    int *insn_idx_p)
11091 {
11092 	const struct btf_type *t, *ptr_type;
11093 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11094 	struct bpf_reg_state *regs = cur_regs(env);
11095 	const char *func_name, *ptr_type_name;
11096 	bool sleepable, rcu_lock, rcu_unlock;
11097 	struct bpf_kfunc_call_arg_meta meta;
11098 	struct bpf_insn_aux_data *insn_aux;
11099 	int err, insn_idx = *insn_idx_p;
11100 	const struct btf_param *args;
11101 	const struct btf_type *ret_t;
11102 	struct btf *desc_btf;
11103 
11104 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11105 	if (!insn->imm)
11106 		return 0;
11107 
11108 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11109 	if (err == -EACCES && func_name)
11110 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11111 	if (err)
11112 		return err;
11113 	desc_btf = meta.btf;
11114 	insn_aux = &env->insn_aux_data[insn_idx];
11115 
11116 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11117 
11118 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11119 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11120 		return -EACCES;
11121 	}
11122 
11123 	sleepable = is_kfunc_sleepable(&meta);
11124 	if (sleepable && !env->prog->aux->sleepable) {
11125 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11126 		return -EACCES;
11127 	}
11128 
11129 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11130 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11131 
11132 	if (env->cur_state->active_rcu_lock) {
11133 		struct bpf_func_state *state;
11134 		struct bpf_reg_state *reg;
11135 
11136 		if (rcu_lock) {
11137 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11138 			return -EINVAL;
11139 		} else if (rcu_unlock) {
11140 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11141 				if (reg->type & MEM_RCU) {
11142 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11143 					reg->type |= PTR_UNTRUSTED;
11144 				}
11145 			}));
11146 			env->cur_state->active_rcu_lock = false;
11147 		} else if (sleepable) {
11148 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11149 			return -EACCES;
11150 		}
11151 	} else if (rcu_lock) {
11152 		env->cur_state->active_rcu_lock = true;
11153 	} else if (rcu_unlock) {
11154 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11155 		return -EINVAL;
11156 	}
11157 
11158 	/* Check the arguments */
11159 	err = check_kfunc_args(env, &meta, insn_idx);
11160 	if (err < 0)
11161 		return err;
11162 	/* In case of release function, we get register number of refcounted
11163 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11164 	 */
11165 	if (meta.release_regno) {
11166 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11167 		if (err) {
11168 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11169 				func_name, meta.func_id);
11170 			return err;
11171 		}
11172 	}
11173 
11174 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11175 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11176 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11177 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11178 		insn_aux->insert_off = regs[BPF_REG_2].off;
11179 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11180 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11181 		if (err) {
11182 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11183 				func_name, meta.func_id);
11184 			return err;
11185 		}
11186 
11187 		err = release_reference(env, release_ref_obj_id);
11188 		if (err) {
11189 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11190 				func_name, meta.func_id);
11191 			return err;
11192 		}
11193 	}
11194 
11195 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11196 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11197 					set_rbtree_add_callback_state);
11198 		if (err) {
11199 			verbose(env, "kfunc %s#%d failed callback verification\n",
11200 				func_name, meta.func_id);
11201 			return err;
11202 		}
11203 	}
11204 
11205 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11206 		mark_reg_not_init(env, regs, caller_saved[i]);
11207 
11208 	/* Check return type */
11209 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11210 
11211 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11212 		/* Only exception is bpf_obj_new_impl */
11213 		if (meta.btf != btf_vmlinux ||
11214 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11215 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11216 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11217 			return -EINVAL;
11218 		}
11219 	}
11220 
11221 	if (btf_type_is_scalar(t)) {
11222 		mark_reg_unknown(env, regs, BPF_REG_0);
11223 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11224 	} else if (btf_type_is_ptr(t)) {
11225 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11226 
11227 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11228 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11229 				struct btf *ret_btf;
11230 				u32 ret_btf_id;
11231 
11232 				if (unlikely(!bpf_global_ma_set))
11233 					return -ENOMEM;
11234 
11235 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11236 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11237 					return -EINVAL;
11238 				}
11239 
11240 				ret_btf = env->prog->aux->btf;
11241 				ret_btf_id = meta.arg_constant.value;
11242 
11243 				/* This may be NULL due to user not supplying a BTF */
11244 				if (!ret_btf) {
11245 					verbose(env, "bpf_obj_new requires prog BTF\n");
11246 					return -EINVAL;
11247 				}
11248 
11249 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11250 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11251 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11252 					return -EINVAL;
11253 				}
11254 
11255 				mark_reg_known_zero(env, regs, BPF_REG_0);
11256 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11257 				regs[BPF_REG_0].btf = ret_btf;
11258 				regs[BPF_REG_0].btf_id = ret_btf_id;
11259 
11260 				insn_aux->obj_new_size = ret_t->size;
11261 				insn_aux->kptr_struct_meta =
11262 					btf_find_struct_meta(ret_btf, ret_btf_id);
11263 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11264 				mark_reg_known_zero(env, regs, BPF_REG_0);
11265 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11266 				regs[BPF_REG_0].btf = meta.arg_btf;
11267 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11268 
11269 				insn_aux->kptr_struct_meta =
11270 					btf_find_struct_meta(meta.arg_btf,
11271 							     meta.arg_btf_id);
11272 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11273 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11274 				struct btf_field *field = meta.arg_list_head.field;
11275 
11276 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11277 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11278 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11279 				struct btf_field *field = meta.arg_rbtree_root.field;
11280 
11281 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11282 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11283 				mark_reg_known_zero(env, regs, BPF_REG_0);
11284 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11285 				regs[BPF_REG_0].btf = desc_btf;
11286 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11287 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11288 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11289 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11290 					verbose(env,
11291 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11292 					return -EINVAL;
11293 				}
11294 
11295 				mark_reg_known_zero(env, regs, BPF_REG_0);
11296 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11297 				regs[BPF_REG_0].btf = desc_btf;
11298 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11299 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11300 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11301 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11302 
11303 				mark_reg_known_zero(env, regs, BPF_REG_0);
11304 
11305 				if (!meta.arg_constant.found) {
11306 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11307 					return -EFAULT;
11308 				}
11309 
11310 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11311 
11312 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11313 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11314 
11315 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11316 					regs[BPF_REG_0].type |= MEM_RDONLY;
11317 				} else {
11318 					/* this will set env->seen_direct_write to true */
11319 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11320 						verbose(env, "the prog does not allow writes to packet data\n");
11321 						return -EINVAL;
11322 					}
11323 				}
11324 
11325 				if (!meta.initialized_dynptr.id) {
11326 					verbose(env, "verifier internal error: no dynptr id\n");
11327 					return -EFAULT;
11328 				}
11329 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11330 
11331 				/* we don't need to set BPF_REG_0's ref obj id
11332 				 * because packet slices are not refcounted (see
11333 				 * dynptr_type_refcounted)
11334 				 */
11335 			} else {
11336 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11337 					meta.func_name);
11338 				return -EFAULT;
11339 			}
11340 		} else if (!__btf_type_is_struct(ptr_type)) {
11341 			if (!meta.r0_size) {
11342 				__u32 sz;
11343 
11344 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11345 					meta.r0_size = sz;
11346 					meta.r0_rdonly = true;
11347 				}
11348 			}
11349 			if (!meta.r0_size) {
11350 				ptr_type_name = btf_name_by_offset(desc_btf,
11351 								   ptr_type->name_off);
11352 				verbose(env,
11353 					"kernel function %s returns pointer type %s %s is not supported\n",
11354 					func_name,
11355 					btf_type_str(ptr_type),
11356 					ptr_type_name);
11357 				return -EINVAL;
11358 			}
11359 
11360 			mark_reg_known_zero(env, regs, BPF_REG_0);
11361 			regs[BPF_REG_0].type = PTR_TO_MEM;
11362 			regs[BPF_REG_0].mem_size = meta.r0_size;
11363 
11364 			if (meta.r0_rdonly)
11365 				regs[BPF_REG_0].type |= MEM_RDONLY;
11366 
11367 			/* Ensures we don't access the memory after a release_reference() */
11368 			if (meta.ref_obj_id)
11369 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11370 		} else {
11371 			mark_reg_known_zero(env, regs, BPF_REG_0);
11372 			regs[BPF_REG_0].btf = desc_btf;
11373 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11374 			regs[BPF_REG_0].btf_id = ptr_type_id;
11375 		}
11376 
11377 		if (is_kfunc_ret_null(&meta)) {
11378 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11379 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11380 			regs[BPF_REG_0].id = ++env->id_gen;
11381 		}
11382 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11383 		if (is_kfunc_acquire(&meta)) {
11384 			int id = acquire_reference_state(env, insn_idx);
11385 
11386 			if (id < 0)
11387 				return id;
11388 			if (is_kfunc_ret_null(&meta))
11389 				regs[BPF_REG_0].id = id;
11390 			regs[BPF_REG_0].ref_obj_id = id;
11391 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11392 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11393 		}
11394 
11395 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11396 			regs[BPF_REG_0].id = ++env->id_gen;
11397 	} else if (btf_type_is_void(t)) {
11398 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11399 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11400 				insn_aux->kptr_struct_meta =
11401 					btf_find_struct_meta(meta.arg_btf,
11402 							     meta.arg_btf_id);
11403 			}
11404 		}
11405 	}
11406 
11407 	nargs = btf_type_vlen(meta.func_proto);
11408 	args = (const struct btf_param *)(meta.func_proto + 1);
11409 	for (i = 0; i < nargs; i++) {
11410 		u32 regno = i + 1;
11411 
11412 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11413 		if (btf_type_is_ptr(t))
11414 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11415 		else
11416 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11417 			mark_btf_func_reg_size(env, regno, t->size);
11418 	}
11419 
11420 	if (is_iter_next_kfunc(&meta)) {
11421 		err = process_iter_next_call(env, insn_idx, &meta);
11422 		if (err)
11423 			return err;
11424 	}
11425 
11426 	return 0;
11427 }
11428 
11429 static bool signed_add_overflows(s64 a, s64 b)
11430 {
11431 	/* Do the add in u64, where overflow is well-defined */
11432 	s64 res = (s64)((u64)a + (u64)b);
11433 
11434 	if (b < 0)
11435 		return res > a;
11436 	return res < a;
11437 }
11438 
11439 static bool signed_add32_overflows(s32 a, s32 b)
11440 {
11441 	/* Do the add in u32, where overflow is well-defined */
11442 	s32 res = (s32)((u32)a + (u32)b);
11443 
11444 	if (b < 0)
11445 		return res > a;
11446 	return res < a;
11447 }
11448 
11449 static bool signed_sub_overflows(s64 a, s64 b)
11450 {
11451 	/* Do the sub in u64, where overflow is well-defined */
11452 	s64 res = (s64)((u64)a - (u64)b);
11453 
11454 	if (b < 0)
11455 		return res < a;
11456 	return res > a;
11457 }
11458 
11459 static bool signed_sub32_overflows(s32 a, s32 b)
11460 {
11461 	/* Do the sub in u32, where overflow is well-defined */
11462 	s32 res = (s32)((u32)a - (u32)b);
11463 
11464 	if (b < 0)
11465 		return res < a;
11466 	return res > a;
11467 }
11468 
11469 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11470 				  const struct bpf_reg_state *reg,
11471 				  enum bpf_reg_type type)
11472 {
11473 	bool known = tnum_is_const(reg->var_off);
11474 	s64 val = reg->var_off.value;
11475 	s64 smin = reg->smin_value;
11476 
11477 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11478 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11479 			reg_type_str(env, type), val);
11480 		return false;
11481 	}
11482 
11483 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11484 		verbose(env, "%s pointer offset %d is not allowed\n",
11485 			reg_type_str(env, type), reg->off);
11486 		return false;
11487 	}
11488 
11489 	if (smin == S64_MIN) {
11490 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11491 			reg_type_str(env, type));
11492 		return false;
11493 	}
11494 
11495 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11496 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11497 			smin, reg_type_str(env, type));
11498 		return false;
11499 	}
11500 
11501 	return true;
11502 }
11503 
11504 enum {
11505 	REASON_BOUNDS	= -1,
11506 	REASON_TYPE	= -2,
11507 	REASON_PATHS	= -3,
11508 	REASON_LIMIT	= -4,
11509 	REASON_STACK	= -5,
11510 };
11511 
11512 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11513 			      u32 *alu_limit, bool mask_to_left)
11514 {
11515 	u32 max = 0, ptr_limit = 0;
11516 
11517 	switch (ptr_reg->type) {
11518 	case PTR_TO_STACK:
11519 		/* Offset 0 is out-of-bounds, but acceptable start for the
11520 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11521 		 * offset where we would need to deal with min/max bounds is
11522 		 * currently prohibited for unprivileged.
11523 		 */
11524 		max = MAX_BPF_STACK + mask_to_left;
11525 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11526 		break;
11527 	case PTR_TO_MAP_VALUE:
11528 		max = ptr_reg->map_ptr->value_size;
11529 		ptr_limit = (mask_to_left ?
11530 			     ptr_reg->smin_value :
11531 			     ptr_reg->umax_value) + ptr_reg->off;
11532 		break;
11533 	default:
11534 		return REASON_TYPE;
11535 	}
11536 
11537 	if (ptr_limit >= max)
11538 		return REASON_LIMIT;
11539 	*alu_limit = ptr_limit;
11540 	return 0;
11541 }
11542 
11543 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11544 				    const struct bpf_insn *insn)
11545 {
11546 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11547 }
11548 
11549 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11550 				       u32 alu_state, u32 alu_limit)
11551 {
11552 	/* If we arrived here from different branches with different
11553 	 * state or limits to sanitize, then this won't work.
11554 	 */
11555 	if (aux->alu_state &&
11556 	    (aux->alu_state != alu_state ||
11557 	     aux->alu_limit != alu_limit))
11558 		return REASON_PATHS;
11559 
11560 	/* Corresponding fixup done in do_misc_fixups(). */
11561 	aux->alu_state = alu_state;
11562 	aux->alu_limit = alu_limit;
11563 	return 0;
11564 }
11565 
11566 static int sanitize_val_alu(struct bpf_verifier_env *env,
11567 			    struct bpf_insn *insn)
11568 {
11569 	struct bpf_insn_aux_data *aux = cur_aux(env);
11570 
11571 	if (can_skip_alu_sanitation(env, insn))
11572 		return 0;
11573 
11574 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11575 }
11576 
11577 static bool sanitize_needed(u8 opcode)
11578 {
11579 	return opcode == BPF_ADD || opcode == BPF_SUB;
11580 }
11581 
11582 struct bpf_sanitize_info {
11583 	struct bpf_insn_aux_data aux;
11584 	bool mask_to_left;
11585 };
11586 
11587 static struct bpf_verifier_state *
11588 sanitize_speculative_path(struct bpf_verifier_env *env,
11589 			  const struct bpf_insn *insn,
11590 			  u32 next_idx, u32 curr_idx)
11591 {
11592 	struct bpf_verifier_state *branch;
11593 	struct bpf_reg_state *regs;
11594 
11595 	branch = push_stack(env, next_idx, curr_idx, true);
11596 	if (branch && insn) {
11597 		regs = branch->frame[branch->curframe]->regs;
11598 		if (BPF_SRC(insn->code) == BPF_K) {
11599 			mark_reg_unknown(env, regs, insn->dst_reg);
11600 		} else if (BPF_SRC(insn->code) == BPF_X) {
11601 			mark_reg_unknown(env, regs, insn->dst_reg);
11602 			mark_reg_unknown(env, regs, insn->src_reg);
11603 		}
11604 	}
11605 	return branch;
11606 }
11607 
11608 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11609 			    struct bpf_insn *insn,
11610 			    const struct bpf_reg_state *ptr_reg,
11611 			    const struct bpf_reg_state *off_reg,
11612 			    struct bpf_reg_state *dst_reg,
11613 			    struct bpf_sanitize_info *info,
11614 			    const bool commit_window)
11615 {
11616 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11617 	struct bpf_verifier_state *vstate = env->cur_state;
11618 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11619 	bool off_is_neg = off_reg->smin_value < 0;
11620 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11621 	u8 opcode = BPF_OP(insn->code);
11622 	u32 alu_state, alu_limit;
11623 	struct bpf_reg_state tmp;
11624 	bool ret;
11625 	int err;
11626 
11627 	if (can_skip_alu_sanitation(env, insn))
11628 		return 0;
11629 
11630 	/* We already marked aux for masking from non-speculative
11631 	 * paths, thus we got here in the first place. We only care
11632 	 * to explore bad access from here.
11633 	 */
11634 	if (vstate->speculative)
11635 		goto do_sim;
11636 
11637 	if (!commit_window) {
11638 		if (!tnum_is_const(off_reg->var_off) &&
11639 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11640 			return REASON_BOUNDS;
11641 
11642 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11643 				     (opcode == BPF_SUB && !off_is_neg);
11644 	}
11645 
11646 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11647 	if (err < 0)
11648 		return err;
11649 
11650 	if (commit_window) {
11651 		/* In commit phase we narrow the masking window based on
11652 		 * the observed pointer move after the simulated operation.
11653 		 */
11654 		alu_state = info->aux.alu_state;
11655 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11656 	} else {
11657 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11658 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11659 		alu_state |= ptr_is_dst_reg ?
11660 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11661 
11662 		/* Limit pruning on unknown scalars to enable deep search for
11663 		 * potential masking differences from other program paths.
11664 		 */
11665 		if (!off_is_imm)
11666 			env->explore_alu_limits = true;
11667 	}
11668 
11669 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11670 	if (err < 0)
11671 		return err;
11672 do_sim:
11673 	/* If we're in commit phase, we're done here given we already
11674 	 * pushed the truncated dst_reg into the speculative verification
11675 	 * stack.
11676 	 *
11677 	 * Also, when register is a known constant, we rewrite register-based
11678 	 * operation to immediate-based, and thus do not need masking (and as
11679 	 * a consequence, do not need to simulate the zero-truncation either).
11680 	 */
11681 	if (commit_window || off_is_imm)
11682 		return 0;
11683 
11684 	/* Simulate and find potential out-of-bounds access under
11685 	 * speculative execution from truncation as a result of
11686 	 * masking when off was not within expected range. If off
11687 	 * sits in dst, then we temporarily need to move ptr there
11688 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11689 	 * for cases where we use K-based arithmetic in one direction
11690 	 * and truncated reg-based in the other in order to explore
11691 	 * bad access.
11692 	 */
11693 	if (!ptr_is_dst_reg) {
11694 		tmp = *dst_reg;
11695 		copy_register_state(dst_reg, ptr_reg);
11696 	}
11697 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11698 					env->insn_idx);
11699 	if (!ptr_is_dst_reg && ret)
11700 		*dst_reg = tmp;
11701 	return !ret ? REASON_STACK : 0;
11702 }
11703 
11704 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11705 {
11706 	struct bpf_verifier_state *vstate = env->cur_state;
11707 
11708 	/* If we simulate paths under speculation, we don't update the
11709 	 * insn as 'seen' such that when we verify unreachable paths in
11710 	 * the non-speculative domain, sanitize_dead_code() can still
11711 	 * rewrite/sanitize them.
11712 	 */
11713 	if (!vstate->speculative)
11714 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11715 }
11716 
11717 static int sanitize_err(struct bpf_verifier_env *env,
11718 			const struct bpf_insn *insn, int reason,
11719 			const struct bpf_reg_state *off_reg,
11720 			const struct bpf_reg_state *dst_reg)
11721 {
11722 	static const char *err = "pointer arithmetic with it prohibited for !root";
11723 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11724 	u32 dst = insn->dst_reg, src = insn->src_reg;
11725 
11726 	switch (reason) {
11727 	case REASON_BOUNDS:
11728 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11729 			off_reg == dst_reg ? dst : src, err);
11730 		break;
11731 	case REASON_TYPE:
11732 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11733 			off_reg == dst_reg ? src : dst, err);
11734 		break;
11735 	case REASON_PATHS:
11736 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11737 			dst, op, err);
11738 		break;
11739 	case REASON_LIMIT:
11740 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11741 			dst, op, err);
11742 		break;
11743 	case REASON_STACK:
11744 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11745 			dst, err);
11746 		break;
11747 	default:
11748 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11749 			reason);
11750 		break;
11751 	}
11752 
11753 	return -EACCES;
11754 }
11755 
11756 /* check that stack access falls within stack limits and that 'reg' doesn't
11757  * have a variable offset.
11758  *
11759  * Variable offset is prohibited for unprivileged mode for simplicity since it
11760  * requires corresponding support in Spectre masking for stack ALU.  See also
11761  * retrieve_ptr_limit().
11762  *
11763  *
11764  * 'off' includes 'reg->off'.
11765  */
11766 static int check_stack_access_for_ptr_arithmetic(
11767 				struct bpf_verifier_env *env,
11768 				int regno,
11769 				const struct bpf_reg_state *reg,
11770 				int off)
11771 {
11772 	if (!tnum_is_const(reg->var_off)) {
11773 		char tn_buf[48];
11774 
11775 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11776 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11777 			regno, tn_buf, off);
11778 		return -EACCES;
11779 	}
11780 
11781 	if (off >= 0 || off < -MAX_BPF_STACK) {
11782 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11783 			"prohibited for !root; off=%d\n", regno, off);
11784 		return -EACCES;
11785 	}
11786 
11787 	return 0;
11788 }
11789 
11790 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11791 				 const struct bpf_insn *insn,
11792 				 const struct bpf_reg_state *dst_reg)
11793 {
11794 	u32 dst = insn->dst_reg;
11795 
11796 	/* For unprivileged we require that resulting offset must be in bounds
11797 	 * in order to be able to sanitize access later on.
11798 	 */
11799 	if (env->bypass_spec_v1)
11800 		return 0;
11801 
11802 	switch (dst_reg->type) {
11803 	case PTR_TO_STACK:
11804 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11805 					dst_reg->off + dst_reg->var_off.value))
11806 			return -EACCES;
11807 		break;
11808 	case PTR_TO_MAP_VALUE:
11809 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11810 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11811 				"prohibited for !root\n", dst);
11812 			return -EACCES;
11813 		}
11814 		break;
11815 	default:
11816 		break;
11817 	}
11818 
11819 	return 0;
11820 }
11821 
11822 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11823  * Caller should also handle BPF_MOV case separately.
11824  * If we return -EACCES, caller may want to try again treating pointer as a
11825  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11826  */
11827 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11828 				   struct bpf_insn *insn,
11829 				   const struct bpf_reg_state *ptr_reg,
11830 				   const struct bpf_reg_state *off_reg)
11831 {
11832 	struct bpf_verifier_state *vstate = env->cur_state;
11833 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11834 	struct bpf_reg_state *regs = state->regs, *dst_reg;
11835 	bool known = tnum_is_const(off_reg->var_off);
11836 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11837 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11838 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11839 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11840 	struct bpf_sanitize_info info = {};
11841 	u8 opcode = BPF_OP(insn->code);
11842 	u32 dst = insn->dst_reg;
11843 	int ret;
11844 
11845 	dst_reg = &regs[dst];
11846 
11847 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11848 	    smin_val > smax_val || umin_val > umax_val) {
11849 		/* Taint dst register if offset had invalid bounds derived from
11850 		 * e.g. dead branches.
11851 		 */
11852 		__mark_reg_unknown(env, dst_reg);
11853 		return 0;
11854 	}
11855 
11856 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
11857 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
11858 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11859 			__mark_reg_unknown(env, dst_reg);
11860 			return 0;
11861 		}
11862 
11863 		verbose(env,
11864 			"R%d 32-bit pointer arithmetic prohibited\n",
11865 			dst);
11866 		return -EACCES;
11867 	}
11868 
11869 	if (ptr_reg->type & PTR_MAYBE_NULL) {
11870 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11871 			dst, reg_type_str(env, ptr_reg->type));
11872 		return -EACCES;
11873 	}
11874 
11875 	switch (base_type(ptr_reg->type)) {
11876 	case CONST_PTR_TO_MAP:
11877 		/* smin_val represents the known value */
11878 		if (known && smin_val == 0 && opcode == BPF_ADD)
11879 			break;
11880 		fallthrough;
11881 	case PTR_TO_PACKET_END:
11882 	case PTR_TO_SOCKET:
11883 	case PTR_TO_SOCK_COMMON:
11884 	case PTR_TO_TCP_SOCK:
11885 	case PTR_TO_XDP_SOCK:
11886 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11887 			dst, reg_type_str(env, ptr_reg->type));
11888 		return -EACCES;
11889 	default:
11890 		break;
11891 	}
11892 
11893 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11894 	 * The id may be overwritten later if we create a new variable offset.
11895 	 */
11896 	dst_reg->type = ptr_reg->type;
11897 	dst_reg->id = ptr_reg->id;
11898 
11899 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11900 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11901 		return -EINVAL;
11902 
11903 	/* pointer types do not carry 32-bit bounds at the moment. */
11904 	__mark_reg32_unbounded(dst_reg);
11905 
11906 	if (sanitize_needed(opcode)) {
11907 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11908 				       &info, false);
11909 		if (ret < 0)
11910 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11911 	}
11912 
11913 	switch (opcode) {
11914 	case BPF_ADD:
11915 		/* We can take a fixed offset as long as it doesn't overflow
11916 		 * the s32 'off' field
11917 		 */
11918 		if (known && (ptr_reg->off + smin_val ==
11919 			      (s64)(s32)(ptr_reg->off + smin_val))) {
11920 			/* pointer += K.  Accumulate it into fixed offset */
11921 			dst_reg->smin_value = smin_ptr;
11922 			dst_reg->smax_value = smax_ptr;
11923 			dst_reg->umin_value = umin_ptr;
11924 			dst_reg->umax_value = umax_ptr;
11925 			dst_reg->var_off = ptr_reg->var_off;
11926 			dst_reg->off = ptr_reg->off + smin_val;
11927 			dst_reg->raw = ptr_reg->raw;
11928 			break;
11929 		}
11930 		/* A new variable offset is created.  Note that off_reg->off
11931 		 * == 0, since it's a scalar.
11932 		 * dst_reg gets the pointer type and since some positive
11933 		 * integer value was added to the pointer, give it a new 'id'
11934 		 * if it's a PTR_TO_PACKET.
11935 		 * this creates a new 'base' pointer, off_reg (variable) gets
11936 		 * added into the variable offset, and we copy the fixed offset
11937 		 * from ptr_reg.
11938 		 */
11939 		if (signed_add_overflows(smin_ptr, smin_val) ||
11940 		    signed_add_overflows(smax_ptr, smax_val)) {
11941 			dst_reg->smin_value = S64_MIN;
11942 			dst_reg->smax_value = S64_MAX;
11943 		} else {
11944 			dst_reg->smin_value = smin_ptr + smin_val;
11945 			dst_reg->smax_value = smax_ptr + smax_val;
11946 		}
11947 		if (umin_ptr + umin_val < umin_ptr ||
11948 		    umax_ptr + umax_val < umax_ptr) {
11949 			dst_reg->umin_value = 0;
11950 			dst_reg->umax_value = U64_MAX;
11951 		} else {
11952 			dst_reg->umin_value = umin_ptr + umin_val;
11953 			dst_reg->umax_value = umax_ptr + umax_val;
11954 		}
11955 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11956 		dst_reg->off = ptr_reg->off;
11957 		dst_reg->raw = ptr_reg->raw;
11958 		if (reg_is_pkt_pointer(ptr_reg)) {
11959 			dst_reg->id = ++env->id_gen;
11960 			/* something was added to pkt_ptr, set range to zero */
11961 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11962 		}
11963 		break;
11964 	case BPF_SUB:
11965 		if (dst_reg == off_reg) {
11966 			/* scalar -= pointer.  Creates an unknown scalar */
11967 			verbose(env, "R%d tried to subtract pointer from scalar\n",
11968 				dst);
11969 			return -EACCES;
11970 		}
11971 		/* We don't allow subtraction from FP, because (according to
11972 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
11973 		 * be able to deal with it.
11974 		 */
11975 		if (ptr_reg->type == PTR_TO_STACK) {
11976 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
11977 				dst);
11978 			return -EACCES;
11979 		}
11980 		if (known && (ptr_reg->off - smin_val ==
11981 			      (s64)(s32)(ptr_reg->off - smin_val))) {
11982 			/* pointer -= K.  Subtract it from fixed offset */
11983 			dst_reg->smin_value = smin_ptr;
11984 			dst_reg->smax_value = smax_ptr;
11985 			dst_reg->umin_value = umin_ptr;
11986 			dst_reg->umax_value = umax_ptr;
11987 			dst_reg->var_off = ptr_reg->var_off;
11988 			dst_reg->id = ptr_reg->id;
11989 			dst_reg->off = ptr_reg->off - smin_val;
11990 			dst_reg->raw = ptr_reg->raw;
11991 			break;
11992 		}
11993 		/* A new variable offset is created.  If the subtrahend is known
11994 		 * nonnegative, then any reg->range we had before is still good.
11995 		 */
11996 		if (signed_sub_overflows(smin_ptr, smax_val) ||
11997 		    signed_sub_overflows(smax_ptr, smin_val)) {
11998 			/* Overflow possible, we know nothing */
11999 			dst_reg->smin_value = S64_MIN;
12000 			dst_reg->smax_value = S64_MAX;
12001 		} else {
12002 			dst_reg->smin_value = smin_ptr - smax_val;
12003 			dst_reg->smax_value = smax_ptr - smin_val;
12004 		}
12005 		if (umin_ptr < umax_val) {
12006 			/* Overflow possible, we know nothing */
12007 			dst_reg->umin_value = 0;
12008 			dst_reg->umax_value = U64_MAX;
12009 		} else {
12010 			/* Cannot overflow (as long as bounds are consistent) */
12011 			dst_reg->umin_value = umin_ptr - umax_val;
12012 			dst_reg->umax_value = umax_ptr - umin_val;
12013 		}
12014 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12015 		dst_reg->off = ptr_reg->off;
12016 		dst_reg->raw = ptr_reg->raw;
12017 		if (reg_is_pkt_pointer(ptr_reg)) {
12018 			dst_reg->id = ++env->id_gen;
12019 			/* something was added to pkt_ptr, set range to zero */
12020 			if (smin_val < 0)
12021 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12022 		}
12023 		break;
12024 	case BPF_AND:
12025 	case BPF_OR:
12026 	case BPF_XOR:
12027 		/* bitwise ops on pointers are troublesome, prohibit. */
12028 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12029 			dst, bpf_alu_string[opcode >> 4]);
12030 		return -EACCES;
12031 	default:
12032 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12033 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12034 			dst, bpf_alu_string[opcode >> 4]);
12035 		return -EACCES;
12036 	}
12037 
12038 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12039 		return -EINVAL;
12040 	reg_bounds_sync(dst_reg);
12041 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12042 		return -EACCES;
12043 	if (sanitize_needed(opcode)) {
12044 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12045 				       &info, true);
12046 		if (ret < 0)
12047 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12048 	}
12049 
12050 	return 0;
12051 }
12052 
12053 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12054 				 struct bpf_reg_state *src_reg)
12055 {
12056 	s32 smin_val = src_reg->s32_min_value;
12057 	s32 smax_val = src_reg->s32_max_value;
12058 	u32 umin_val = src_reg->u32_min_value;
12059 	u32 umax_val = src_reg->u32_max_value;
12060 
12061 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12062 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12063 		dst_reg->s32_min_value = S32_MIN;
12064 		dst_reg->s32_max_value = S32_MAX;
12065 	} else {
12066 		dst_reg->s32_min_value += smin_val;
12067 		dst_reg->s32_max_value += smax_val;
12068 	}
12069 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12070 	    dst_reg->u32_max_value + umax_val < umax_val) {
12071 		dst_reg->u32_min_value = 0;
12072 		dst_reg->u32_max_value = U32_MAX;
12073 	} else {
12074 		dst_reg->u32_min_value += umin_val;
12075 		dst_reg->u32_max_value += umax_val;
12076 	}
12077 }
12078 
12079 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12080 			       struct bpf_reg_state *src_reg)
12081 {
12082 	s64 smin_val = src_reg->smin_value;
12083 	s64 smax_val = src_reg->smax_value;
12084 	u64 umin_val = src_reg->umin_value;
12085 	u64 umax_val = src_reg->umax_value;
12086 
12087 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12088 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12089 		dst_reg->smin_value = S64_MIN;
12090 		dst_reg->smax_value = S64_MAX;
12091 	} else {
12092 		dst_reg->smin_value += smin_val;
12093 		dst_reg->smax_value += smax_val;
12094 	}
12095 	if (dst_reg->umin_value + umin_val < umin_val ||
12096 	    dst_reg->umax_value + umax_val < umax_val) {
12097 		dst_reg->umin_value = 0;
12098 		dst_reg->umax_value = U64_MAX;
12099 	} else {
12100 		dst_reg->umin_value += umin_val;
12101 		dst_reg->umax_value += umax_val;
12102 	}
12103 }
12104 
12105 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12106 				 struct bpf_reg_state *src_reg)
12107 {
12108 	s32 smin_val = src_reg->s32_min_value;
12109 	s32 smax_val = src_reg->s32_max_value;
12110 	u32 umin_val = src_reg->u32_min_value;
12111 	u32 umax_val = src_reg->u32_max_value;
12112 
12113 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12114 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12115 		/* Overflow possible, we know nothing */
12116 		dst_reg->s32_min_value = S32_MIN;
12117 		dst_reg->s32_max_value = S32_MAX;
12118 	} else {
12119 		dst_reg->s32_min_value -= smax_val;
12120 		dst_reg->s32_max_value -= smin_val;
12121 	}
12122 	if (dst_reg->u32_min_value < umax_val) {
12123 		/* Overflow possible, we know nothing */
12124 		dst_reg->u32_min_value = 0;
12125 		dst_reg->u32_max_value = U32_MAX;
12126 	} else {
12127 		/* Cannot overflow (as long as bounds are consistent) */
12128 		dst_reg->u32_min_value -= umax_val;
12129 		dst_reg->u32_max_value -= umin_val;
12130 	}
12131 }
12132 
12133 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12134 			       struct bpf_reg_state *src_reg)
12135 {
12136 	s64 smin_val = src_reg->smin_value;
12137 	s64 smax_val = src_reg->smax_value;
12138 	u64 umin_val = src_reg->umin_value;
12139 	u64 umax_val = src_reg->umax_value;
12140 
12141 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12142 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12143 		/* Overflow possible, we know nothing */
12144 		dst_reg->smin_value = S64_MIN;
12145 		dst_reg->smax_value = S64_MAX;
12146 	} else {
12147 		dst_reg->smin_value -= smax_val;
12148 		dst_reg->smax_value -= smin_val;
12149 	}
12150 	if (dst_reg->umin_value < umax_val) {
12151 		/* Overflow possible, we know nothing */
12152 		dst_reg->umin_value = 0;
12153 		dst_reg->umax_value = U64_MAX;
12154 	} else {
12155 		/* Cannot overflow (as long as bounds are consistent) */
12156 		dst_reg->umin_value -= umax_val;
12157 		dst_reg->umax_value -= umin_val;
12158 	}
12159 }
12160 
12161 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12162 				 struct bpf_reg_state *src_reg)
12163 {
12164 	s32 smin_val = src_reg->s32_min_value;
12165 	u32 umin_val = src_reg->u32_min_value;
12166 	u32 umax_val = src_reg->u32_max_value;
12167 
12168 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12169 		/* Ain't nobody got time to multiply that sign */
12170 		__mark_reg32_unbounded(dst_reg);
12171 		return;
12172 	}
12173 	/* Both values are positive, so we can work with unsigned and
12174 	 * copy the result to signed (unless it exceeds S32_MAX).
12175 	 */
12176 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12177 		/* Potential overflow, we know nothing */
12178 		__mark_reg32_unbounded(dst_reg);
12179 		return;
12180 	}
12181 	dst_reg->u32_min_value *= umin_val;
12182 	dst_reg->u32_max_value *= umax_val;
12183 	if (dst_reg->u32_max_value > S32_MAX) {
12184 		/* Overflow possible, we know nothing */
12185 		dst_reg->s32_min_value = S32_MIN;
12186 		dst_reg->s32_max_value = S32_MAX;
12187 	} else {
12188 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12189 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12190 	}
12191 }
12192 
12193 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12194 			       struct bpf_reg_state *src_reg)
12195 {
12196 	s64 smin_val = src_reg->smin_value;
12197 	u64 umin_val = src_reg->umin_value;
12198 	u64 umax_val = src_reg->umax_value;
12199 
12200 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12201 		/* Ain't nobody got time to multiply that sign */
12202 		__mark_reg64_unbounded(dst_reg);
12203 		return;
12204 	}
12205 	/* Both values are positive, so we can work with unsigned and
12206 	 * copy the result to signed (unless it exceeds S64_MAX).
12207 	 */
12208 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12209 		/* Potential overflow, we know nothing */
12210 		__mark_reg64_unbounded(dst_reg);
12211 		return;
12212 	}
12213 	dst_reg->umin_value *= umin_val;
12214 	dst_reg->umax_value *= umax_val;
12215 	if (dst_reg->umax_value > S64_MAX) {
12216 		/* Overflow possible, we know nothing */
12217 		dst_reg->smin_value = S64_MIN;
12218 		dst_reg->smax_value = S64_MAX;
12219 	} else {
12220 		dst_reg->smin_value = dst_reg->umin_value;
12221 		dst_reg->smax_value = dst_reg->umax_value;
12222 	}
12223 }
12224 
12225 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12226 				 struct bpf_reg_state *src_reg)
12227 {
12228 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12229 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12230 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12231 	s32 smin_val = src_reg->s32_min_value;
12232 	u32 umax_val = src_reg->u32_max_value;
12233 
12234 	if (src_known && dst_known) {
12235 		__mark_reg32_known(dst_reg, var32_off.value);
12236 		return;
12237 	}
12238 
12239 	/* We get our minimum from the var_off, since that's inherently
12240 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12241 	 */
12242 	dst_reg->u32_min_value = var32_off.value;
12243 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12244 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12245 		/* Lose signed bounds when ANDing negative numbers,
12246 		 * ain't nobody got time for that.
12247 		 */
12248 		dst_reg->s32_min_value = S32_MIN;
12249 		dst_reg->s32_max_value = S32_MAX;
12250 	} else {
12251 		/* ANDing two positives gives a positive, so safe to
12252 		 * cast result into s64.
12253 		 */
12254 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12255 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12256 	}
12257 }
12258 
12259 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12260 			       struct bpf_reg_state *src_reg)
12261 {
12262 	bool src_known = tnum_is_const(src_reg->var_off);
12263 	bool dst_known = tnum_is_const(dst_reg->var_off);
12264 	s64 smin_val = src_reg->smin_value;
12265 	u64 umax_val = src_reg->umax_value;
12266 
12267 	if (src_known && dst_known) {
12268 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12269 		return;
12270 	}
12271 
12272 	/* We get our minimum from the var_off, since that's inherently
12273 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12274 	 */
12275 	dst_reg->umin_value = dst_reg->var_off.value;
12276 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12277 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12278 		/* Lose signed bounds when ANDing negative numbers,
12279 		 * ain't nobody got time for that.
12280 		 */
12281 		dst_reg->smin_value = S64_MIN;
12282 		dst_reg->smax_value = S64_MAX;
12283 	} else {
12284 		/* ANDing two positives gives a positive, so safe to
12285 		 * cast result into s64.
12286 		 */
12287 		dst_reg->smin_value = dst_reg->umin_value;
12288 		dst_reg->smax_value = dst_reg->umax_value;
12289 	}
12290 	/* We may learn something more from the var_off */
12291 	__update_reg_bounds(dst_reg);
12292 }
12293 
12294 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12295 				struct bpf_reg_state *src_reg)
12296 {
12297 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12298 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12299 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12300 	s32 smin_val = src_reg->s32_min_value;
12301 	u32 umin_val = src_reg->u32_min_value;
12302 
12303 	if (src_known && dst_known) {
12304 		__mark_reg32_known(dst_reg, var32_off.value);
12305 		return;
12306 	}
12307 
12308 	/* We get our maximum from the var_off, and our minimum is the
12309 	 * maximum of the operands' minima
12310 	 */
12311 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12312 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12313 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12314 		/* Lose signed bounds when ORing negative numbers,
12315 		 * ain't nobody got time for that.
12316 		 */
12317 		dst_reg->s32_min_value = S32_MIN;
12318 		dst_reg->s32_max_value = S32_MAX;
12319 	} else {
12320 		/* ORing two positives gives a positive, so safe to
12321 		 * cast result into s64.
12322 		 */
12323 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12324 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12325 	}
12326 }
12327 
12328 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12329 			      struct bpf_reg_state *src_reg)
12330 {
12331 	bool src_known = tnum_is_const(src_reg->var_off);
12332 	bool dst_known = tnum_is_const(dst_reg->var_off);
12333 	s64 smin_val = src_reg->smin_value;
12334 	u64 umin_val = src_reg->umin_value;
12335 
12336 	if (src_known && dst_known) {
12337 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12338 		return;
12339 	}
12340 
12341 	/* We get our maximum from the var_off, and our minimum is the
12342 	 * maximum of the operands' minima
12343 	 */
12344 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12345 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12346 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12347 		/* Lose signed bounds when ORing negative numbers,
12348 		 * ain't nobody got time for that.
12349 		 */
12350 		dst_reg->smin_value = S64_MIN;
12351 		dst_reg->smax_value = S64_MAX;
12352 	} else {
12353 		/* ORing two positives gives a positive, so safe to
12354 		 * cast result into s64.
12355 		 */
12356 		dst_reg->smin_value = dst_reg->umin_value;
12357 		dst_reg->smax_value = dst_reg->umax_value;
12358 	}
12359 	/* We may learn something more from the var_off */
12360 	__update_reg_bounds(dst_reg);
12361 }
12362 
12363 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12364 				 struct bpf_reg_state *src_reg)
12365 {
12366 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12367 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12368 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12369 	s32 smin_val = src_reg->s32_min_value;
12370 
12371 	if (src_known && dst_known) {
12372 		__mark_reg32_known(dst_reg, var32_off.value);
12373 		return;
12374 	}
12375 
12376 	/* We get both minimum and maximum from the var32_off. */
12377 	dst_reg->u32_min_value = var32_off.value;
12378 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12379 
12380 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12381 		/* XORing two positive sign numbers gives a positive,
12382 		 * so safe to cast u32 result into s32.
12383 		 */
12384 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12385 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12386 	} else {
12387 		dst_reg->s32_min_value = S32_MIN;
12388 		dst_reg->s32_max_value = S32_MAX;
12389 	}
12390 }
12391 
12392 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12393 			       struct bpf_reg_state *src_reg)
12394 {
12395 	bool src_known = tnum_is_const(src_reg->var_off);
12396 	bool dst_known = tnum_is_const(dst_reg->var_off);
12397 	s64 smin_val = src_reg->smin_value;
12398 
12399 	if (src_known && dst_known) {
12400 		/* dst_reg->var_off.value has been updated earlier */
12401 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12402 		return;
12403 	}
12404 
12405 	/* We get both minimum and maximum from the var_off. */
12406 	dst_reg->umin_value = dst_reg->var_off.value;
12407 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12408 
12409 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12410 		/* XORing two positive sign numbers gives a positive,
12411 		 * so safe to cast u64 result into s64.
12412 		 */
12413 		dst_reg->smin_value = dst_reg->umin_value;
12414 		dst_reg->smax_value = dst_reg->umax_value;
12415 	} else {
12416 		dst_reg->smin_value = S64_MIN;
12417 		dst_reg->smax_value = S64_MAX;
12418 	}
12419 
12420 	__update_reg_bounds(dst_reg);
12421 }
12422 
12423 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12424 				   u64 umin_val, u64 umax_val)
12425 {
12426 	/* We lose all sign bit information (except what we can pick
12427 	 * up from var_off)
12428 	 */
12429 	dst_reg->s32_min_value = S32_MIN;
12430 	dst_reg->s32_max_value = S32_MAX;
12431 	/* If we might shift our top bit out, then we know nothing */
12432 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12433 		dst_reg->u32_min_value = 0;
12434 		dst_reg->u32_max_value = U32_MAX;
12435 	} else {
12436 		dst_reg->u32_min_value <<= umin_val;
12437 		dst_reg->u32_max_value <<= umax_val;
12438 	}
12439 }
12440 
12441 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12442 				 struct bpf_reg_state *src_reg)
12443 {
12444 	u32 umax_val = src_reg->u32_max_value;
12445 	u32 umin_val = src_reg->u32_min_value;
12446 	/* u32 alu operation will zext upper bits */
12447 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12448 
12449 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12450 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12451 	/* Not required but being careful mark reg64 bounds as unknown so
12452 	 * that we are forced to pick them up from tnum and zext later and
12453 	 * if some path skips this step we are still safe.
12454 	 */
12455 	__mark_reg64_unbounded(dst_reg);
12456 	__update_reg32_bounds(dst_reg);
12457 }
12458 
12459 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12460 				   u64 umin_val, u64 umax_val)
12461 {
12462 	/* Special case <<32 because it is a common compiler pattern to sign
12463 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12464 	 * positive we know this shift will also be positive so we can track
12465 	 * bounds correctly. Otherwise we lose all sign bit information except
12466 	 * what we can pick up from var_off. Perhaps we can generalize this
12467 	 * later to shifts of any length.
12468 	 */
12469 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12470 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12471 	else
12472 		dst_reg->smax_value = S64_MAX;
12473 
12474 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12475 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12476 	else
12477 		dst_reg->smin_value = S64_MIN;
12478 
12479 	/* If we might shift our top bit out, then we know nothing */
12480 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12481 		dst_reg->umin_value = 0;
12482 		dst_reg->umax_value = U64_MAX;
12483 	} else {
12484 		dst_reg->umin_value <<= umin_val;
12485 		dst_reg->umax_value <<= umax_val;
12486 	}
12487 }
12488 
12489 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12490 			       struct bpf_reg_state *src_reg)
12491 {
12492 	u64 umax_val = src_reg->umax_value;
12493 	u64 umin_val = src_reg->umin_value;
12494 
12495 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12496 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12497 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12498 
12499 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12500 	/* We may learn something more from the var_off */
12501 	__update_reg_bounds(dst_reg);
12502 }
12503 
12504 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12505 				 struct bpf_reg_state *src_reg)
12506 {
12507 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12508 	u32 umax_val = src_reg->u32_max_value;
12509 	u32 umin_val = src_reg->u32_min_value;
12510 
12511 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12512 	 * be negative, then either:
12513 	 * 1) src_reg might be zero, so the sign bit of the result is
12514 	 *    unknown, so we lose our signed bounds
12515 	 * 2) it's known negative, thus the unsigned bounds capture the
12516 	 *    signed bounds
12517 	 * 3) the signed bounds cross zero, so they tell us nothing
12518 	 *    about the result
12519 	 * If the value in dst_reg is known nonnegative, then again the
12520 	 * unsigned bounds capture the signed bounds.
12521 	 * Thus, in all cases it suffices to blow away our signed bounds
12522 	 * and rely on inferring new ones from the unsigned bounds and
12523 	 * var_off of the result.
12524 	 */
12525 	dst_reg->s32_min_value = S32_MIN;
12526 	dst_reg->s32_max_value = S32_MAX;
12527 
12528 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12529 	dst_reg->u32_min_value >>= umax_val;
12530 	dst_reg->u32_max_value >>= umin_val;
12531 
12532 	__mark_reg64_unbounded(dst_reg);
12533 	__update_reg32_bounds(dst_reg);
12534 }
12535 
12536 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12537 			       struct bpf_reg_state *src_reg)
12538 {
12539 	u64 umax_val = src_reg->umax_value;
12540 	u64 umin_val = src_reg->umin_value;
12541 
12542 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12543 	 * be negative, then either:
12544 	 * 1) src_reg might be zero, so the sign bit of the result is
12545 	 *    unknown, so we lose our signed bounds
12546 	 * 2) it's known negative, thus the unsigned bounds capture the
12547 	 *    signed bounds
12548 	 * 3) the signed bounds cross zero, so they tell us nothing
12549 	 *    about the result
12550 	 * If the value in dst_reg is known nonnegative, then again the
12551 	 * unsigned bounds capture the signed bounds.
12552 	 * Thus, in all cases it suffices to blow away our signed bounds
12553 	 * and rely on inferring new ones from the unsigned bounds and
12554 	 * var_off of the result.
12555 	 */
12556 	dst_reg->smin_value = S64_MIN;
12557 	dst_reg->smax_value = S64_MAX;
12558 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12559 	dst_reg->umin_value >>= umax_val;
12560 	dst_reg->umax_value >>= umin_val;
12561 
12562 	/* Its not easy to operate on alu32 bounds here because it depends
12563 	 * on bits being shifted in. Take easy way out and mark unbounded
12564 	 * so we can recalculate later from tnum.
12565 	 */
12566 	__mark_reg32_unbounded(dst_reg);
12567 	__update_reg_bounds(dst_reg);
12568 }
12569 
12570 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12571 				  struct bpf_reg_state *src_reg)
12572 {
12573 	u64 umin_val = src_reg->u32_min_value;
12574 
12575 	/* Upon reaching here, src_known is true and
12576 	 * umax_val is equal to umin_val.
12577 	 */
12578 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12579 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12580 
12581 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12582 
12583 	/* blow away the dst_reg umin_value/umax_value and rely on
12584 	 * dst_reg var_off to refine the result.
12585 	 */
12586 	dst_reg->u32_min_value = 0;
12587 	dst_reg->u32_max_value = U32_MAX;
12588 
12589 	__mark_reg64_unbounded(dst_reg);
12590 	__update_reg32_bounds(dst_reg);
12591 }
12592 
12593 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12594 				struct bpf_reg_state *src_reg)
12595 {
12596 	u64 umin_val = src_reg->umin_value;
12597 
12598 	/* Upon reaching here, src_known is true and umax_val is equal
12599 	 * to umin_val.
12600 	 */
12601 	dst_reg->smin_value >>= umin_val;
12602 	dst_reg->smax_value >>= umin_val;
12603 
12604 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12605 
12606 	/* blow away the dst_reg umin_value/umax_value and rely on
12607 	 * dst_reg var_off to refine the result.
12608 	 */
12609 	dst_reg->umin_value = 0;
12610 	dst_reg->umax_value = U64_MAX;
12611 
12612 	/* Its not easy to operate on alu32 bounds here because it depends
12613 	 * on bits being shifted in from upper 32-bits. Take easy way out
12614 	 * and mark unbounded so we can recalculate later from tnum.
12615 	 */
12616 	__mark_reg32_unbounded(dst_reg);
12617 	__update_reg_bounds(dst_reg);
12618 }
12619 
12620 /* WARNING: This function does calculations on 64-bit values, but the actual
12621  * execution may occur on 32-bit values. Therefore, things like bitshifts
12622  * need extra checks in the 32-bit case.
12623  */
12624 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12625 				      struct bpf_insn *insn,
12626 				      struct bpf_reg_state *dst_reg,
12627 				      struct bpf_reg_state src_reg)
12628 {
12629 	struct bpf_reg_state *regs = cur_regs(env);
12630 	u8 opcode = BPF_OP(insn->code);
12631 	bool src_known;
12632 	s64 smin_val, smax_val;
12633 	u64 umin_val, umax_val;
12634 	s32 s32_min_val, s32_max_val;
12635 	u32 u32_min_val, u32_max_val;
12636 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12637 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12638 	int ret;
12639 
12640 	smin_val = src_reg.smin_value;
12641 	smax_val = src_reg.smax_value;
12642 	umin_val = src_reg.umin_value;
12643 	umax_val = src_reg.umax_value;
12644 
12645 	s32_min_val = src_reg.s32_min_value;
12646 	s32_max_val = src_reg.s32_max_value;
12647 	u32_min_val = src_reg.u32_min_value;
12648 	u32_max_val = src_reg.u32_max_value;
12649 
12650 	if (alu32) {
12651 		src_known = tnum_subreg_is_const(src_reg.var_off);
12652 		if ((src_known &&
12653 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12654 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12655 			/* Taint dst register if offset had invalid bounds
12656 			 * derived from e.g. dead branches.
12657 			 */
12658 			__mark_reg_unknown(env, dst_reg);
12659 			return 0;
12660 		}
12661 	} else {
12662 		src_known = tnum_is_const(src_reg.var_off);
12663 		if ((src_known &&
12664 		     (smin_val != smax_val || umin_val != umax_val)) ||
12665 		    smin_val > smax_val || umin_val > umax_val) {
12666 			/* Taint dst register if offset had invalid bounds
12667 			 * derived from e.g. dead branches.
12668 			 */
12669 			__mark_reg_unknown(env, dst_reg);
12670 			return 0;
12671 		}
12672 	}
12673 
12674 	if (!src_known &&
12675 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12676 		__mark_reg_unknown(env, dst_reg);
12677 		return 0;
12678 	}
12679 
12680 	if (sanitize_needed(opcode)) {
12681 		ret = sanitize_val_alu(env, insn);
12682 		if (ret < 0)
12683 			return sanitize_err(env, insn, ret, NULL, NULL);
12684 	}
12685 
12686 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12687 	 * There are two classes of instructions: The first class we track both
12688 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12689 	 * greatest amount of precision when alu operations are mixed with jmp32
12690 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12691 	 * and BPF_OR. This is possible because these ops have fairly easy to
12692 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12693 	 * See alu32 verifier tests for examples. The second class of
12694 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12695 	 * with regards to tracking sign/unsigned bounds because the bits may
12696 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12697 	 * the reg unbounded in the subreg bound space and use the resulting
12698 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12699 	 */
12700 	switch (opcode) {
12701 	case BPF_ADD:
12702 		scalar32_min_max_add(dst_reg, &src_reg);
12703 		scalar_min_max_add(dst_reg, &src_reg);
12704 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12705 		break;
12706 	case BPF_SUB:
12707 		scalar32_min_max_sub(dst_reg, &src_reg);
12708 		scalar_min_max_sub(dst_reg, &src_reg);
12709 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12710 		break;
12711 	case BPF_MUL:
12712 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12713 		scalar32_min_max_mul(dst_reg, &src_reg);
12714 		scalar_min_max_mul(dst_reg, &src_reg);
12715 		break;
12716 	case BPF_AND:
12717 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12718 		scalar32_min_max_and(dst_reg, &src_reg);
12719 		scalar_min_max_and(dst_reg, &src_reg);
12720 		break;
12721 	case BPF_OR:
12722 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12723 		scalar32_min_max_or(dst_reg, &src_reg);
12724 		scalar_min_max_or(dst_reg, &src_reg);
12725 		break;
12726 	case BPF_XOR:
12727 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12728 		scalar32_min_max_xor(dst_reg, &src_reg);
12729 		scalar_min_max_xor(dst_reg, &src_reg);
12730 		break;
12731 	case BPF_LSH:
12732 		if (umax_val >= insn_bitness) {
12733 			/* Shifts greater than 31 or 63 are undefined.
12734 			 * This includes shifts by a negative number.
12735 			 */
12736 			mark_reg_unknown(env, regs, insn->dst_reg);
12737 			break;
12738 		}
12739 		if (alu32)
12740 			scalar32_min_max_lsh(dst_reg, &src_reg);
12741 		else
12742 			scalar_min_max_lsh(dst_reg, &src_reg);
12743 		break;
12744 	case BPF_RSH:
12745 		if (umax_val >= insn_bitness) {
12746 			/* Shifts greater than 31 or 63 are undefined.
12747 			 * This includes shifts by a negative number.
12748 			 */
12749 			mark_reg_unknown(env, regs, insn->dst_reg);
12750 			break;
12751 		}
12752 		if (alu32)
12753 			scalar32_min_max_rsh(dst_reg, &src_reg);
12754 		else
12755 			scalar_min_max_rsh(dst_reg, &src_reg);
12756 		break;
12757 	case BPF_ARSH:
12758 		if (umax_val >= insn_bitness) {
12759 			/* Shifts greater than 31 or 63 are undefined.
12760 			 * This includes shifts by a negative number.
12761 			 */
12762 			mark_reg_unknown(env, regs, insn->dst_reg);
12763 			break;
12764 		}
12765 		if (alu32)
12766 			scalar32_min_max_arsh(dst_reg, &src_reg);
12767 		else
12768 			scalar_min_max_arsh(dst_reg, &src_reg);
12769 		break;
12770 	default:
12771 		mark_reg_unknown(env, regs, insn->dst_reg);
12772 		break;
12773 	}
12774 
12775 	/* ALU32 ops are zero extended into 64bit register */
12776 	if (alu32)
12777 		zext_32_to_64(dst_reg);
12778 	reg_bounds_sync(dst_reg);
12779 	return 0;
12780 }
12781 
12782 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12783  * and var_off.
12784  */
12785 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12786 				   struct bpf_insn *insn)
12787 {
12788 	struct bpf_verifier_state *vstate = env->cur_state;
12789 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12790 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12791 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12792 	u8 opcode = BPF_OP(insn->code);
12793 	int err;
12794 
12795 	dst_reg = &regs[insn->dst_reg];
12796 	src_reg = NULL;
12797 	if (dst_reg->type != SCALAR_VALUE)
12798 		ptr_reg = dst_reg;
12799 	else
12800 		/* Make sure ID is cleared otherwise dst_reg min/max could be
12801 		 * incorrectly propagated into other registers by find_equal_scalars()
12802 		 */
12803 		dst_reg->id = 0;
12804 	if (BPF_SRC(insn->code) == BPF_X) {
12805 		src_reg = &regs[insn->src_reg];
12806 		if (src_reg->type != SCALAR_VALUE) {
12807 			if (dst_reg->type != SCALAR_VALUE) {
12808 				/* Combining two pointers by any ALU op yields
12809 				 * an arbitrary scalar. Disallow all math except
12810 				 * pointer subtraction
12811 				 */
12812 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12813 					mark_reg_unknown(env, regs, insn->dst_reg);
12814 					return 0;
12815 				}
12816 				verbose(env, "R%d pointer %s pointer prohibited\n",
12817 					insn->dst_reg,
12818 					bpf_alu_string[opcode >> 4]);
12819 				return -EACCES;
12820 			} else {
12821 				/* scalar += pointer
12822 				 * This is legal, but we have to reverse our
12823 				 * src/dest handling in computing the range
12824 				 */
12825 				err = mark_chain_precision(env, insn->dst_reg);
12826 				if (err)
12827 					return err;
12828 				return adjust_ptr_min_max_vals(env, insn,
12829 							       src_reg, dst_reg);
12830 			}
12831 		} else if (ptr_reg) {
12832 			/* pointer += scalar */
12833 			err = mark_chain_precision(env, insn->src_reg);
12834 			if (err)
12835 				return err;
12836 			return adjust_ptr_min_max_vals(env, insn,
12837 						       dst_reg, src_reg);
12838 		} else if (dst_reg->precise) {
12839 			/* if dst_reg is precise, src_reg should be precise as well */
12840 			err = mark_chain_precision(env, insn->src_reg);
12841 			if (err)
12842 				return err;
12843 		}
12844 	} else {
12845 		/* Pretend the src is a reg with a known value, since we only
12846 		 * need to be able to read from this state.
12847 		 */
12848 		off_reg.type = SCALAR_VALUE;
12849 		__mark_reg_known(&off_reg, insn->imm);
12850 		src_reg = &off_reg;
12851 		if (ptr_reg) /* pointer += K */
12852 			return adjust_ptr_min_max_vals(env, insn,
12853 						       ptr_reg, src_reg);
12854 	}
12855 
12856 	/* Got here implies adding two SCALAR_VALUEs */
12857 	if (WARN_ON_ONCE(ptr_reg)) {
12858 		print_verifier_state(env, state, true);
12859 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
12860 		return -EINVAL;
12861 	}
12862 	if (WARN_ON(!src_reg)) {
12863 		print_verifier_state(env, state, true);
12864 		verbose(env, "verifier internal error: no src_reg\n");
12865 		return -EINVAL;
12866 	}
12867 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12868 }
12869 
12870 /* check validity of 32-bit and 64-bit arithmetic operations */
12871 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12872 {
12873 	struct bpf_reg_state *regs = cur_regs(env);
12874 	u8 opcode = BPF_OP(insn->code);
12875 	int err;
12876 
12877 	if (opcode == BPF_END || opcode == BPF_NEG) {
12878 		if (opcode == BPF_NEG) {
12879 			if (BPF_SRC(insn->code) != BPF_K ||
12880 			    insn->src_reg != BPF_REG_0 ||
12881 			    insn->off != 0 || insn->imm != 0) {
12882 				verbose(env, "BPF_NEG uses reserved fields\n");
12883 				return -EINVAL;
12884 			}
12885 		} else {
12886 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12887 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12888 			    BPF_CLASS(insn->code) == BPF_ALU64) {
12889 				verbose(env, "BPF_END uses reserved fields\n");
12890 				return -EINVAL;
12891 			}
12892 		}
12893 
12894 		/* check src operand */
12895 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12896 		if (err)
12897 			return err;
12898 
12899 		if (is_pointer_value(env, insn->dst_reg)) {
12900 			verbose(env, "R%d pointer arithmetic prohibited\n",
12901 				insn->dst_reg);
12902 			return -EACCES;
12903 		}
12904 
12905 		/* check dest operand */
12906 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
12907 		if (err)
12908 			return err;
12909 
12910 	} else if (opcode == BPF_MOV) {
12911 
12912 		if (BPF_SRC(insn->code) == BPF_X) {
12913 			if (insn->imm != 0 || insn->off != 0) {
12914 				verbose(env, "BPF_MOV uses reserved fields\n");
12915 				return -EINVAL;
12916 			}
12917 
12918 			/* check src operand */
12919 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12920 			if (err)
12921 				return err;
12922 		} else {
12923 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12924 				verbose(env, "BPF_MOV uses reserved fields\n");
12925 				return -EINVAL;
12926 			}
12927 		}
12928 
12929 		/* check dest operand, mark as required later */
12930 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12931 		if (err)
12932 			return err;
12933 
12934 		if (BPF_SRC(insn->code) == BPF_X) {
12935 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
12936 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12937 
12938 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12939 				/* case: R1 = R2
12940 				 * copy register state to dest reg
12941 				 */
12942 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12943 					/* Assign src and dst registers the same ID
12944 					 * that will be used by find_equal_scalars()
12945 					 * to propagate min/max range.
12946 					 */
12947 					src_reg->id = ++env->id_gen;
12948 				copy_register_state(dst_reg, src_reg);
12949 				dst_reg->live |= REG_LIVE_WRITTEN;
12950 				dst_reg->subreg_def = DEF_NOT_SUBREG;
12951 			} else {
12952 				/* R1 = (u32) R2 */
12953 				if (is_pointer_value(env, insn->src_reg)) {
12954 					verbose(env,
12955 						"R%d partial copy of pointer\n",
12956 						insn->src_reg);
12957 					return -EACCES;
12958 				} else if (src_reg->type == SCALAR_VALUE) {
12959 					bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12960 
12961 					if (is_src_reg_u32 && !src_reg->id)
12962 						src_reg->id = ++env->id_gen;
12963 					copy_register_state(dst_reg, src_reg);
12964 					/* Make sure ID is cleared if src_reg is not in u32 range otherwise
12965 					 * dst_reg min/max could be incorrectly
12966 					 * propagated into src_reg by find_equal_scalars()
12967 					 */
12968 					if (!is_src_reg_u32)
12969 						dst_reg->id = 0;
12970 					dst_reg->live |= REG_LIVE_WRITTEN;
12971 					dst_reg->subreg_def = env->insn_idx + 1;
12972 				} else {
12973 					mark_reg_unknown(env, regs,
12974 							 insn->dst_reg);
12975 				}
12976 				zext_32_to_64(dst_reg);
12977 				reg_bounds_sync(dst_reg);
12978 			}
12979 		} else {
12980 			/* case: R = imm
12981 			 * remember the value we stored into this reg
12982 			 */
12983 			/* clear any state __mark_reg_known doesn't set */
12984 			mark_reg_unknown(env, regs, insn->dst_reg);
12985 			regs[insn->dst_reg].type = SCALAR_VALUE;
12986 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12987 				__mark_reg_known(regs + insn->dst_reg,
12988 						 insn->imm);
12989 			} else {
12990 				__mark_reg_known(regs + insn->dst_reg,
12991 						 (u32)insn->imm);
12992 			}
12993 		}
12994 
12995 	} else if (opcode > BPF_END) {
12996 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12997 		return -EINVAL;
12998 
12999 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13000 
13001 		if (BPF_SRC(insn->code) == BPF_X) {
13002 			if (insn->imm != 0 || insn->off != 0) {
13003 				verbose(env, "BPF_ALU uses reserved fields\n");
13004 				return -EINVAL;
13005 			}
13006 			/* check src1 operand */
13007 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13008 			if (err)
13009 				return err;
13010 		} else {
13011 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13012 				verbose(env, "BPF_ALU uses reserved fields\n");
13013 				return -EINVAL;
13014 			}
13015 		}
13016 
13017 		/* check src2 operand */
13018 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13019 		if (err)
13020 			return err;
13021 
13022 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13023 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13024 			verbose(env, "div by zero\n");
13025 			return -EINVAL;
13026 		}
13027 
13028 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13029 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13030 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13031 
13032 			if (insn->imm < 0 || insn->imm >= size) {
13033 				verbose(env, "invalid shift %d\n", insn->imm);
13034 				return -EINVAL;
13035 			}
13036 		}
13037 
13038 		/* check dest operand */
13039 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13040 		if (err)
13041 			return err;
13042 
13043 		return adjust_reg_min_max_vals(env, insn);
13044 	}
13045 
13046 	return 0;
13047 }
13048 
13049 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13050 				   struct bpf_reg_state *dst_reg,
13051 				   enum bpf_reg_type type,
13052 				   bool range_right_open)
13053 {
13054 	struct bpf_func_state *state;
13055 	struct bpf_reg_state *reg;
13056 	int new_range;
13057 
13058 	if (dst_reg->off < 0 ||
13059 	    (dst_reg->off == 0 && range_right_open))
13060 		/* This doesn't give us any range */
13061 		return;
13062 
13063 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13064 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13065 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13066 		 * than pkt_end, but that's because it's also less than pkt.
13067 		 */
13068 		return;
13069 
13070 	new_range = dst_reg->off;
13071 	if (range_right_open)
13072 		new_range++;
13073 
13074 	/* Examples for register markings:
13075 	 *
13076 	 * pkt_data in dst register:
13077 	 *
13078 	 *   r2 = r3;
13079 	 *   r2 += 8;
13080 	 *   if (r2 > pkt_end) goto <handle exception>
13081 	 *   <access okay>
13082 	 *
13083 	 *   r2 = r3;
13084 	 *   r2 += 8;
13085 	 *   if (r2 < pkt_end) goto <access okay>
13086 	 *   <handle exception>
13087 	 *
13088 	 *   Where:
13089 	 *     r2 == dst_reg, pkt_end == src_reg
13090 	 *     r2=pkt(id=n,off=8,r=0)
13091 	 *     r3=pkt(id=n,off=0,r=0)
13092 	 *
13093 	 * pkt_data in src register:
13094 	 *
13095 	 *   r2 = r3;
13096 	 *   r2 += 8;
13097 	 *   if (pkt_end >= r2) goto <access okay>
13098 	 *   <handle exception>
13099 	 *
13100 	 *   r2 = r3;
13101 	 *   r2 += 8;
13102 	 *   if (pkt_end <= r2) goto <handle exception>
13103 	 *   <access okay>
13104 	 *
13105 	 *   Where:
13106 	 *     pkt_end == dst_reg, r2 == src_reg
13107 	 *     r2=pkt(id=n,off=8,r=0)
13108 	 *     r3=pkt(id=n,off=0,r=0)
13109 	 *
13110 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13111 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13112 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13113 	 * the check.
13114 	 */
13115 
13116 	/* If our ids match, then we must have the same max_value.  And we
13117 	 * don't care about the other reg's fixed offset, since if it's too big
13118 	 * the range won't allow anything.
13119 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13120 	 */
13121 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13122 		if (reg->type == type && reg->id == dst_reg->id)
13123 			/* keep the maximum range already checked */
13124 			reg->range = max(reg->range, new_range);
13125 	}));
13126 }
13127 
13128 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13129 {
13130 	struct tnum subreg = tnum_subreg(reg->var_off);
13131 	s32 sval = (s32)val;
13132 
13133 	switch (opcode) {
13134 	case BPF_JEQ:
13135 		if (tnum_is_const(subreg))
13136 			return !!tnum_equals_const(subreg, val);
13137 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13138 			return 0;
13139 		break;
13140 	case BPF_JNE:
13141 		if (tnum_is_const(subreg))
13142 			return !tnum_equals_const(subreg, val);
13143 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13144 			return 1;
13145 		break;
13146 	case BPF_JSET:
13147 		if ((~subreg.mask & subreg.value) & val)
13148 			return 1;
13149 		if (!((subreg.mask | subreg.value) & val))
13150 			return 0;
13151 		break;
13152 	case BPF_JGT:
13153 		if (reg->u32_min_value > val)
13154 			return 1;
13155 		else if (reg->u32_max_value <= val)
13156 			return 0;
13157 		break;
13158 	case BPF_JSGT:
13159 		if (reg->s32_min_value > sval)
13160 			return 1;
13161 		else if (reg->s32_max_value <= sval)
13162 			return 0;
13163 		break;
13164 	case BPF_JLT:
13165 		if (reg->u32_max_value < val)
13166 			return 1;
13167 		else if (reg->u32_min_value >= val)
13168 			return 0;
13169 		break;
13170 	case BPF_JSLT:
13171 		if (reg->s32_max_value < sval)
13172 			return 1;
13173 		else if (reg->s32_min_value >= sval)
13174 			return 0;
13175 		break;
13176 	case BPF_JGE:
13177 		if (reg->u32_min_value >= val)
13178 			return 1;
13179 		else if (reg->u32_max_value < val)
13180 			return 0;
13181 		break;
13182 	case BPF_JSGE:
13183 		if (reg->s32_min_value >= sval)
13184 			return 1;
13185 		else if (reg->s32_max_value < sval)
13186 			return 0;
13187 		break;
13188 	case BPF_JLE:
13189 		if (reg->u32_max_value <= val)
13190 			return 1;
13191 		else if (reg->u32_min_value > val)
13192 			return 0;
13193 		break;
13194 	case BPF_JSLE:
13195 		if (reg->s32_max_value <= sval)
13196 			return 1;
13197 		else if (reg->s32_min_value > sval)
13198 			return 0;
13199 		break;
13200 	}
13201 
13202 	return -1;
13203 }
13204 
13205 
13206 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13207 {
13208 	s64 sval = (s64)val;
13209 
13210 	switch (opcode) {
13211 	case BPF_JEQ:
13212 		if (tnum_is_const(reg->var_off))
13213 			return !!tnum_equals_const(reg->var_off, val);
13214 		else if (val < reg->umin_value || val > reg->umax_value)
13215 			return 0;
13216 		break;
13217 	case BPF_JNE:
13218 		if (tnum_is_const(reg->var_off))
13219 			return !tnum_equals_const(reg->var_off, val);
13220 		else if (val < reg->umin_value || val > reg->umax_value)
13221 			return 1;
13222 		break;
13223 	case BPF_JSET:
13224 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13225 			return 1;
13226 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13227 			return 0;
13228 		break;
13229 	case BPF_JGT:
13230 		if (reg->umin_value > val)
13231 			return 1;
13232 		else if (reg->umax_value <= val)
13233 			return 0;
13234 		break;
13235 	case BPF_JSGT:
13236 		if (reg->smin_value > sval)
13237 			return 1;
13238 		else if (reg->smax_value <= sval)
13239 			return 0;
13240 		break;
13241 	case BPF_JLT:
13242 		if (reg->umax_value < val)
13243 			return 1;
13244 		else if (reg->umin_value >= val)
13245 			return 0;
13246 		break;
13247 	case BPF_JSLT:
13248 		if (reg->smax_value < sval)
13249 			return 1;
13250 		else if (reg->smin_value >= sval)
13251 			return 0;
13252 		break;
13253 	case BPF_JGE:
13254 		if (reg->umin_value >= val)
13255 			return 1;
13256 		else if (reg->umax_value < val)
13257 			return 0;
13258 		break;
13259 	case BPF_JSGE:
13260 		if (reg->smin_value >= sval)
13261 			return 1;
13262 		else if (reg->smax_value < sval)
13263 			return 0;
13264 		break;
13265 	case BPF_JLE:
13266 		if (reg->umax_value <= val)
13267 			return 1;
13268 		else if (reg->umin_value > val)
13269 			return 0;
13270 		break;
13271 	case BPF_JSLE:
13272 		if (reg->smax_value <= sval)
13273 			return 1;
13274 		else if (reg->smin_value > sval)
13275 			return 0;
13276 		break;
13277 	}
13278 
13279 	return -1;
13280 }
13281 
13282 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13283  * and return:
13284  *  1 - branch will be taken and "goto target" will be executed
13285  *  0 - branch will not be taken and fall-through to next insn
13286  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13287  *      range [0,10]
13288  */
13289 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13290 			   bool is_jmp32)
13291 {
13292 	if (__is_pointer_value(false, reg)) {
13293 		if (!reg_not_null(reg))
13294 			return -1;
13295 
13296 		/* If pointer is valid tests against zero will fail so we can
13297 		 * use this to direct branch taken.
13298 		 */
13299 		if (val != 0)
13300 			return -1;
13301 
13302 		switch (opcode) {
13303 		case BPF_JEQ:
13304 			return 0;
13305 		case BPF_JNE:
13306 			return 1;
13307 		default:
13308 			return -1;
13309 		}
13310 	}
13311 
13312 	if (is_jmp32)
13313 		return is_branch32_taken(reg, val, opcode);
13314 	return is_branch64_taken(reg, val, opcode);
13315 }
13316 
13317 static int flip_opcode(u32 opcode)
13318 {
13319 	/* How can we transform "a <op> b" into "b <op> a"? */
13320 	static const u8 opcode_flip[16] = {
13321 		/* these stay the same */
13322 		[BPF_JEQ  >> 4] = BPF_JEQ,
13323 		[BPF_JNE  >> 4] = BPF_JNE,
13324 		[BPF_JSET >> 4] = BPF_JSET,
13325 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13326 		[BPF_JGE  >> 4] = BPF_JLE,
13327 		[BPF_JGT  >> 4] = BPF_JLT,
13328 		[BPF_JLE  >> 4] = BPF_JGE,
13329 		[BPF_JLT  >> 4] = BPF_JGT,
13330 		[BPF_JSGE >> 4] = BPF_JSLE,
13331 		[BPF_JSGT >> 4] = BPF_JSLT,
13332 		[BPF_JSLE >> 4] = BPF_JSGE,
13333 		[BPF_JSLT >> 4] = BPF_JSGT
13334 	};
13335 	return opcode_flip[opcode >> 4];
13336 }
13337 
13338 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13339 				   struct bpf_reg_state *src_reg,
13340 				   u8 opcode)
13341 {
13342 	struct bpf_reg_state *pkt;
13343 
13344 	if (src_reg->type == PTR_TO_PACKET_END) {
13345 		pkt = dst_reg;
13346 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13347 		pkt = src_reg;
13348 		opcode = flip_opcode(opcode);
13349 	} else {
13350 		return -1;
13351 	}
13352 
13353 	if (pkt->range >= 0)
13354 		return -1;
13355 
13356 	switch (opcode) {
13357 	case BPF_JLE:
13358 		/* pkt <= pkt_end */
13359 		fallthrough;
13360 	case BPF_JGT:
13361 		/* pkt > pkt_end */
13362 		if (pkt->range == BEYOND_PKT_END)
13363 			/* pkt has at last one extra byte beyond pkt_end */
13364 			return opcode == BPF_JGT;
13365 		break;
13366 	case BPF_JLT:
13367 		/* pkt < pkt_end */
13368 		fallthrough;
13369 	case BPF_JGE:
13370 		/* pkt >= pkt_end */
13371 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13372 			return opcode == BPF_JGE;
13373 		break;
13374 	}
13375 	return -1;
13376 }
13377 
13378 /* Adjusts the register min/max values in the case that the dst_reg is the
13379  * variable register that we are working on, and src_reg is a constant or we're
13380  * simply doing a BPF_K check.
13381  * In JEQ/JNE cases we also adjust the var_off values.
13382  */
13383 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13384 			    struct bpf_reg_state *false_reg,
13385 			    u64 val, u32 val32,
13386 			    u8 opcode, bool is_jmp32)
13387 {
13388 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13389 	struct tnum false_64off = false_reg->var_off;
13390 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13391 	struct tnum true_64off = true_reg->var_off;
13392 	s64 sval = (s64)val;
13393 	s32 sval32 = (s32)val32;
13394 
13395 	/* If the dst_reg is a pointer, we can't learn anything about its
13396 	 * variable offset from the compare (unless src_reg were a pointer into
13397 	 * the same object, but we don't bother with that.
13398 	 * Since false_reg and true_reg have the same type by construction, we
13399 	 * only need to check one of them for pointerness.
13400 	 */
13401 	if (__is_pointer_value(false, false_reg))
13402 		return;
13403 
13404 	switch (opcode) {
13405 	/* JEQ/JNE comparison doesn't change the register equivalence.
13406 	 *
13407 	 * r1 = r2;
13408 	 * if (r1 == 42) goto label;
13409 	 * ...
13410 	 * label: // here both r1 and r2 are known to be 42.
13411 	 *
13412 	 * Hence when marking register as known preserve it's ID.
13413 	 */
13414 	case BPF_JEQ:
13415 		if (is_jmp32) {
13416 			__mark_reg32_known(true_reg, val32);
13417 			true_32off = tnum_subreg(true_reg->var_off);
13418 		} else {
13419 			___mark_reg_known(true_reg, val);
13420 			true_64off = true_reg->var_off;
13421 		}
13422 		break;
13423 	case BPF_JNE:
13424 		if (is_jmp32) {
13425 			__mark_reg32_known(false_reg, val32);
13426 			false_32off = tnum_subreg(false_reg->var_off);
13427 		} else {
13428 			___mark_reg_known(false_reg, val);
13429 			false_64off = false_reg->var_off;
13430 		}
13431 		break;
13432 	case BPF_JSET:
13433 		if (is_jmp32) {
13434 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13435 			if (is_power_of_2(val32))
13436 				true_32off = tnum_or(true_32off,
13437 						     tnum_const(val32));
13438 		} else {
13439 			false_64off = tnum_and(false_64off, tnum_const(~val));
13440 			if (is_power_of_2(val))
13441 				true_64off = tnum_or(true_64off,
13442 						     tnum_const(val));
13443 		}
13444 		break;
13445 	case BPF_JGE:
13446 	case BPF_JGT:
13447 	{
13448 		if (is_jmp32) {
13449 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13450 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13451 
13452 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13453 						       false_umax);
13454 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13455 						      true_umin);
13456 		} else {
13457 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13458 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13459 
13460 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13461 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13462 		}
13463 		break;
13464 	}
13465 	case BPF_JSGE:
13466 	case BPF_JSGT:
13467 	{
13468 		if (is_jmp32) {
13469 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13470 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13471 
13472 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13473 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13474 		} else {
13475 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13476 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13477 
13478 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13479 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13480 		}
13481 		break;
13482 	}
13483 	case BPF_JLE:
13484 	case BPF_JLT:
13485 	{
13486 		if (is_jmp32) {
13487 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13488 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13489 
13490 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13491 						       false_umin);
13492 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13493 						      true_umax);
13494 		} else {
13495 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13496 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13497 
13498 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13499 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13500 		}
13501 		break;
13502 	}
13503 	case BPF_JSLE:
13504 	case BPF_JSLT:
13505 	{
13506 		if (is_jmp32) {
13507 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13508 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13509 
13510 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13511 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13512 		} else {
13513 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13514 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13515 
13516 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13517 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13518 		}
13519 		break;
13520 	}
13521 	default:
13522 		return;
13523 	}
13524 
13525 	if (is_jmp32) {
13526 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13527 					     tnum_subreg(false_32off));
13528 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13529 					    tnum_subreg(true_32off));
13530 		__reg_combine_32_into_64(false_reg);
13531 		__reg_combine_32_into_64(true_reg);
13532 	} else {
13533 		false_reg->var_off = false_64off;
13534 		true_reg->var_off = true_64off;
13535 		__reg_combine_64_into_32(false_reg);
13536 		__reg_combine_64_into_32(true_reg);
13537 	}
13538 }
13539 
13540 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13541  * the variable reg.
13542  */
13543 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13544 				struct bpf_reg_state *false_reg,
13545 				u64 val, u32 val32,
13546 				u8 opcode, bool is_jmp32)
13547 {
13548 	opcode = flip_opcode(opcode);
13549 	/* This uses zero as "not present in table"; luckily the zero opcode,
13550 	 * BPF_JA, can't get here.
13551 	 */
13552 	if (opcode)
13553 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13554 }
13555 
13556 /* Regs are known to be equal, so intersect their min/max/var_off */
13557 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13558 				  struct bpf_reg_state *dst_reg)
13559 {
13560 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13561 							dst_reg->umin_value);
13562 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13563 							dst_reg->umax_value);
13564 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13565 							dst_reg->smin_value);
13566 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13567 							dst_reg->smax_value);
13568 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13569 							     dst_reg->var_off);
13570 	reg_bounds_sync(src_reg);
13571 	reg_bounds_sync(dst_reg);
13572 }
13573 
13574 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13575 				struct bpf_reg_state *true_dst,
13576 				struct bpf_reg_state *false_src,
13577 				struct bpf_reg_state *false_dst,
13578 				u8 opcode)
13579 {
13580 	switch (opcode) {
13581 	case BPF_JEQ:
13582 		__reg_combine_min_max(true_src, true_dst);
13583 		break;
13584 	case BPF_JNE:
13585 		__reg_combine_min_max(false_src, false_dst);
13586 		break;
13587 	}
13588 }
13589 
13590 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13591 				 struct bpf_reg_state *reg, u32 id,
13592 				 bool is_null)
13593 {
13594 	if (type_may_be_null(reg->type) && reg->id == id &&
13595 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13596 		/* Old offset (both fixed and variable parts) should have been
13597 		 * known-zero, because we don't allow pointer arithmetic on
13598 		 * pointers that might be NULL. If we see this happening, don't
13599 		 * convert the register.
13600 		 *
13601 		 * But in some cases, some helpers that return local kptrs
13602 		 * advance offset for the returned pointer. In those cases, it
13603 		 * is fine to expect to see reg->off.
13604 		 */
13605 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13606 			return;
13607 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13608 		    WARN_ON_ONCE(reg->off))
13609 			return;
13610 
13611 		if (is_null) {
13612 			reg->type = SCALAR_VALUE;
13613 			/* We don't need id and ref_obj_id from this point
13614 			 * onwards anymore, thus we should better reset it,
13615 			 * so that state pruning has chances to take effect.
13616 			 */
13617 			reg->id = 0;
13618 			reg->ref_obj_id = 0;
13619 
13620 			return;
13621 		}
13622 
13623 		mark_ptr_not_null_reg(reg);
13624 
13625 		if (!reg_may_point_to_spin_lock(reg)) {
13626 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13627 			 * in release_reference().
13628 			 *
13629 			 * reg->id is still used by spin_lock ptr. Other
13630 			 * than spin_lock ptr type, reg->id can be reset.
13631 			 */
13632 			reg->id = 0;
13633 		}
13634 	}
13635 }
13636 
13637 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13638  * be folded together at some point.
13639  */
13640 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13641 				  bool is_null)
13642 {
13643 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13644 	struct bpf_reg_state *regs = state->regs, *reg;
13645 	u32 ref_obj_id = regs[regno].ref_obj_id;
13646 	u32 id = regs[regno].id;
13647 
13648 	if (ref_obj_id && ref_obj_id == id && is_null)
13649 		/* regs[regno] is in the " == NULL" branch.
13650 		 * No one could have freed the reference state before
13651 		 * doing the NULL check.
13652 		 */
13653 		WARN_ON_ONCE(release_reference_state(state, id));
13654 
13655 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13656 		mark_ptr_or_null_reg(state, reg, id, is_null);
13657 	}));
13658 }
13659 
13660 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13661 				   struct bpf_reg_state *dst_reg,
13662 				   struct bpf_reg_state *src_reg,
13663 				   struct bpf_verifier_state *this_branch,
13664 				   struct bpf_verifier_state *other_branch)
13665 {
13666 	if (BPF_SRC(insn->code) != BPF_X)
13667 		return false;
13668 
13669 	/* Pointers are always 64-bit. */
13670 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13671 		return false;
13672 
13673 	switch (BPF_OP(insn->code)) {
13674 	case BPF_JGT:
13675 		if ((dst_reg->type == PTR_TO_PACKET &&
13676 		     src_reg->type == PTR_TO_PACKET_END) ||
13677 		    (dst_reg->type == PTR_TO_PACKET_META &&
13678 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13679 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13680 			find_good_pkt_pointers(this_branch, dst_reg,
13681 					       dst_reg->type, false);
13682 			mark_pkt_end(other_branch, insn->dst_reg, true);
13683 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13684 			    src_reg->type == PTR_TO_PACKET) ||
13685 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13686 			    src_reg->type == PTR_TO_PACKET_META)) {
13687 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13688 			find_good_pkt_pointers(other_branch, src_reg,
13689 					       src_reg->type, true);
13690 			mark_pkt_end(this_branch, insn->src_reg, false);
13691 		} else {
13692 			return false;
13693 		}
13694 		break;
13695 	case BPF_JLT:
13696 		if ((dst_reg->type == PTR_TO_PACKET &&
13697 		     src_reg->type == PTR_TO_PACKET_END) ||
13698 		    (dst_reg->type == PTR_TO_PACKET_META &&
13699 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13700 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13701 			find_good_pkt_pointers(other_branch, dst_reg,
13702 					       dst_reg->type, true);
13703 			mark_pkt_end(this_branch, insn->dst_reg, false);
13704 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13705 			    src_reg->type == PTR_TO_PACKET) ||
13706 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13707 			    src_reg->type == PTR_TO_PACKET_META)) {
13708 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13709 			find_good_pkt_pointers(this_branch, src_reg,
13710 					       src_reg->type, false);
13711 			mark_pkt_end(other_branch, insn->src_reg, true);
13712 		} else {
13713 			return false;
13714 		}
13715 		break;
13716 	case BPF_JGE:
13717 		if ((dst_reg->type == PTR_TO_PACKET &&
13718 		     src_reg->type == PTR_TO_PACKET_END) ||
13719 		    (dst_reg->type == PTR_TO_PACKET_META &&
13720 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13721 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13722 			find_good_pkt_pointers(this_branch, dst_reg,
13723 					       dst_reg->type, true);
13724 			mark_pkt_end(other_branch, insn->dst_reg, false);
13725 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13726 			    src_reg->type == PTR_TO_PACKET) ||
13727 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13728 			    src_reg->type == PTR_TO_PACKET_META)) {
13729 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13730 			find_good_pkt_pointers(other_branch, src_reg,
13731 					       src_reg->type, false);
13732 			mark_pkt_end(this_branch, insn->src_reg, true);
13733 		} else {
13734 			return false;
13735 		}
13736 		break;
13737 	case BPF_JLE:
13738 		if ((dst_reg->type == PTR_TO_PACKET &&
13739 		     src_reg->type == PTR_TO_PACKET_END) ||
13740 		    (dst_reg->type == PTR_TO_PACKET_META &&
13741 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13742 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13743 			find_good_pkt_pointers(other_branch, dst_reg,
13744 					       dst_reg->type, false);
13745 			mark_pkt_end(this_branch, insn->dst_reg, true);
13746 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13747 			    src_reg->type == PTR_TO_PACKET) ||
13748 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13749 			    src_reg->type == PTR_TO_PACKET_META)) {
13750 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13751 			find_good_pkt_pointers(this_branch, src_reg,
13752 					       src_reg->type, true);
13753 			mark_pkt_end(other_branch, insn->src_reg, false);
13754 		} else {
13755 			return false;
13756 		}
13757 		break;
13758 	default:
13759 		return false;
13760 	}
13761 
13762 	return true;
13763 }
13764 
13765 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13766 			       struct bpf_reg_state *known_reg)
13767 {
13768 	struct bpf_func_state *state;
13769 	struct bpf_reg_state *reg;
13770 
13771 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13772 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13773 			copy_register_state(reg, known_reg);
13774 	}));
13775 }
13776 
13777 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13778 			     struct bpf_insn *insn, int *insn_idx)
13779 {
13780 	struct bpf_verifier_state *this_branch = env->cur_state;
13781 	struct bpf_verifier_state *other_branch;
13782 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13783 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13784 	struct bpf_reg_state *eq_branch_regs;
13785 	u8 opcode = BPF_OP(insn->code);
13786 	bool is_jmp32;
13787 	int pred = -1;
13788 	int err;
13789 
13790 	/* Only conditional jumps are expected to reach here. */
13791 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
13792 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13793 		return -EINVAL;
13794 	}
13795 
13796 	if (BPF_SRC(insn->code) == BPF_X) {
13797 		if (insn->imm != 0) {
13798 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13799 			return -EINVAL;
13800 		}
13801 
13802 		/* check src1 operand */
13803 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13804 		if (err)
13805 			return err;
13806 
13807 		if (is_pointer_value(env, insn->src_reg)) {
13808 			verbose(env, "R%d pointer comparison prohibited\n",
13809 				insn->src_reg);
13810 			return -EACCES;
13811 		}
13812 		src_reg = &regs[insn->src_reg];
13813 	} else {
13814 		if (insn->src_reg != BPF_REG_0) {
13815 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13816 			return -EINVAL;
13817 		}
13818 	}
13819 
13820 	/* check src2 operand */
13821 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13822 	if (err)
13823 		return err;
13824 
13825 	dst_reg = &regs[insn->dst_reg];
13826 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13827 
13828 	if (BPF_SRC(insn->code) == BPF_K) {
13829 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13830 	} else if (src_reg->type == SCALAR_VALUE &&
13831 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13832 		pred = is_branch_taken(dst_reg,
13833 				       tnum_subreg(src_reg->var_off).value,
13834 				       opcode,
13835 				       is_jmp32);
13836 	} else if (src_reg->type == SCALAR_VALUE &&
13837 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13838 		pred = is_branch_taken(dst_reg,
13839 				       src_reg->var_off.value,
13840 				       opcode,
13841 				       is_jmp32);
13842 	} else if (dst_reg->type == SCALAR_VALUE &&
13843 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13844 		pred = is_branch_taken(src_reg,
13845 				       tnum_subreg(dst_reg->var_off).value,
13846 				       flip_opcode(opcode),
13847 				       is_jmp32);
13848 	} else if (dst_reg->type == SCALAR_VALUE &&
13849 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13850 		pred = is_branch_taken(src_reg,
13851 				       dst_reg->var_off.value,
13852 				       flip_opcode(opcode),
13853 				       is_jmp32);
13854 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
13855 		   reg_is_pkt_pointer_any(src_reg) &&
13856 		   !is_jmp32) {
13857 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13858 	}
13859 
13860 	if (pred >= 0) {
13861 		/* If we get here with a dst_reg pointer type it is because
13862 		 * above is_branch_taken() special cased the 0 comparison.
13863 		 */
13864 		if (!__is_pointer_value(false, dst_reg))
13865 			err = mark_chain_precision(env, insn->dst_reg);
13866 		if (BPF_SRC(insn->code) == BPF_X && !err &&
13867 		    !__is_pointer_value(false, src_reg))
13868 			err = mark_chain_precision(env, insn->src_reg);
13869 		if (err)
13870 			return err;
13871 	}
13872 
13873 	if (pred == 1) {
13874 		/* Only follow the goto, ignore fall-through. If needed, push
13875 		 * the fall-through branch for simulation under speculative
13876 		 * execution.
13877 		 */
13878 		if (!env->bypass_spec_v1 &&
13879 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
13880 					       *insn_idx))
13881 			return -EFAULT;
13882 		*insn_idx += insn->off;
13883 		return 0;
13884 	} else if (pred == 0) {
13885 		/* Only follow the fall-through branch, since that's where the
13886 		 * program will go. If needed, push the goto branch for
13887 		 * simulation under speculative execution.
13888 		 */
13889 		if (!env->bypass_spec_v1 &&
13890 		    !sanitize_speculative_path(env, insn,
13891 					       *insn_idx + insn->off + 1,
13892 					       *insn_idx))
13893 			return -EFAULT;
13894 		return 0;
13895 	}
13896 
13897 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13898 				  false);
13899 	if (!other_branch)
13900 		return -EFAULT;
13901 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13902 
13903 	/* detect if we are comparing against a constant value so we can adjust
13904 	 * our min/max values for our dst register.
13905 	 * this is only legit if both are scalars (or pointers to the same
13906 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13907 	 * because otherwise the different base pointers mean the offsets aren't
13908 	 * comparable.
13909 	 */
13910 	if (BPF_SRC(insn->code) == BPF_X) {
13911 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13912 
13913 		if (dst_reg->type == SCALAR_VALUE &&
13914 		    src_reg->type == SCALAR_VALUE) {
13915 			if (tnum_is_const(src_reg->var_off) ||
13916 			    (is_jmp32 &&
13917 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
13918 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
13919 						dst_reg,
13920 						src_reg->var_off.value,
13921 						tnum_subreg(src_reg->var_off).value,
13922 						opcode, is_jmp32);
13923 			else if (tnum_is_const(dst_reg->var_off) ||
13924 				 (is_jmp32 &&
13925 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
13926 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13927 						    src_reg,
13928 						    dst_reg->var_off.value,
13929 						    tnum_subreg(dst_reg->var_off).value,
13930 						    opcode, is_jmp32);
13931 			else if (!is_jmp32 &&
13932 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
13933 				/* Comparing for equality, we can combine knowledge */
13934 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
13935 						    &other_branch_regs[insn->dst_reg],
13936 						    src_reg, dst_reg, opcode);
13937 			if (src_reg->id &&
13938 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13939 				find_equal_scalars(this_branch, src_reg);
13940 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13941 			}
13942 
13943 		}
13944 	} else if (dst_reg->type == SCALAR_VALUE) {
13945 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
13946 					dst_reg, insn->imm, (u32)insn->imm,
13947 					opcode, is_jmp32);
13948 	}
13949 
13950 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13951 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13952 		find_equal_scalars(this_branch, dst_reg);
13953 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13954 	}
13955 
13956 	/* if one pointer register is compared to another pointer
13957 	 * register check if PTR_MAYBE_NULL could be lifted.
13958 	 * E.g. register A - maybe null
13959 	 *      register B - not null
13960 	 * for JNE A, B, ... - A is not null in the false branch;
13961 	 * for JEQ A, B, ... - A is not null in the true branch.
13962 	 *
13963 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
13964 	 * not need to be null checked by the BPF program, i.e.,
13965 	 * could be null even without PTR_MAYBE_NULL marking, so
13966 	 * only propagate nullness when neither reg is that type.
13967 	 */
13968 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13969 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13970 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13971 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
13972 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13973 		eq_branch_regs = NULL;
13974 		switch (opcode) {
13975 		case BPF_JEQ:
13976 			eq_branch_regs = other_branch_regs;
13977 			break;
13978 		case BPF_JNE:
13979 			eq_branch_regs = regs;
13980 			break;
13981 		default:
13982 			/* do nothing */
13983 			break;
13984 		}
13985 		if (eq_branch_regs) {
13986 			if (type_may_be_null(src_reg->type))
13987 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13988 			else
13989 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13990 		}
13991 	}
13992 
13993 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13994 	 * NOTE: these optimizations below are related with pointer comparison
13995 	 *       which will never be JMP32.
13996 	 */
13997 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13998 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13999 	    type_may_be_null(dst_reg->type)) {
14000 		/* Mark all identical registers in each branch as either
14001 		 * safe or unknown depending R == 0 or R != 0 conditional.
14002 		 */
14003 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14004 				      opcode == BPF_JNE);
14005 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14006 				      opcode == BPF_JEQ);
14007 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14008 					   this_branch, other_branch) &&
14009 		   is_pointer_value(env, insn->dst_reg)) {
14010 		verbose(env, "R%d pointer comparison prohibited\n",
14011 			insn->dst_reg);
14012 		return -EACCES;
14013 	}
14014 	if (env->log.level & BPF_LOG_LEVEL)
14015 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14016 	return 0;
14017 }
14018 
14019 /* verify BPF_LD_IMM64 instruction */
14020 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14021 {
14022 	struct bpf_insn_aux_data *aux = cur_aux(env);
14023 	struct bpf_reg_state *regs = cur_regs(env);
14024 	struct bpf_reg_state *dst_reg;
14025 	struct bpf_map *map;
14026 	int err;
14027 
14028 	if (BPF_SIZE(insn->code) != BPF_DW) {
14029 		verbose(env, "invalid BPF_LD_IMM insn\n");
14030 		return -EINVAL;
14031 	}
14032 	if (insn->off != 0) {
14033 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14034 		return -EINVAL;
14035 	}
14036 
14037 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14038 	if (err)
14039 		return err;
14040 
14041 	dst_reg = &regs[insn->dst_reg];
14042 	if (insn->src_reg == 0) {
14043 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14044 
14045 		dst_reg->type = SCALAR_VALUE;
14046 		__mark_reg_known(&regs[insn->dst_reg], imm);
14047 		return 0;
14048 	}
14049 
14050 	/* All special src_reg cases are listed below. From this point onwards
14051 	 * we either succeed and assign a corresponding dst_reg->type after
14052 	 * zeroing the offset, or fail and reject the program.
14053 	 */
14054 	mark_reg_known_zero(env, regs, insn->dst_reg);
14055 
14056 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14057 		dst_reg->type = aux->btf_var.reg_type;
14058 		switch (base_type(dst_reg->type)) {
14059 		case PTR_TO_MEM:
14060 			dst_reg->mem_size = aux->btf_var.mem_size;
14061 			break;
14062 		case PTR_TO_BTF_ID:
14063 			dst_reg->btf = aux->btf_var.btf;
14064 			dst_reg->btf_id = aux->btf_var.btf_id;
14065 			break;
14066 		default:
14067 			verbose(env, "bpf verifier is misconfigured\n");
14068 			return -EFAULT;
14069 		}
14070 		return 0;
14071 	}
14072 
14073 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14074 		struct bpf_prog_aux *aux = env->prog->aux;
14075 		u32 subprogno = find_subprog(env,
14076 					     env->insn_idx + insn->imm + 1);
14077 
14078 		if (!aux->func_info) {
14079 			verbose(env, "missing btf func_info\n");
14080 			return -EINVAL;
14081 		}
14082 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14083 			verbose(env, "callback function not static\n");
14084 			return -EINVAL;
14085 		}
14086 
14087 		dst_reg->type = PTR_TO_FUNC;
14088 		dst_reg->subprogno = subprogno;
14089 		return 0;
14090 	}
14091 
14092 	map = env->used_maps[aux->map_index];
14093 	dst_reg->map_ptr = map;
14094 
14095 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14096 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14097 		dst_reg->type = PTR_TO_MAP_VALUE;
14098 		dst_reg->off = aux->map_off;
14099 		WARN_ON_ONCE(map->max_entries != 1);
14100 		/* We want reg->id to be same (0) as map_value is not distinct */
14101 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14102 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14103 		dst_reg->type = CONST_PTR_TO_MAP;
14104 	} else {
14105 		verbose(env, "bpf verifier is misconfigured\n");
14106 		return -EINVAL;
14107 	}
14108 
14109 	return 0;
14110 }
14111 
14112 static bool may_access_skb(enum bpf_prog_type type)
14113 {
14114 	switch (type) {
14115 	case BPF_PROG_TYPE_SOCKET_FILTER:
14116 	case BPF_PROG_TYPE_SCHED_CLS:
14117 	case BPF_PROG_TYPE_SCHED_ACT:
14118 		return true;
14119 	default:
14120 		return false;
14121 	}
14122 }
14123 
14124 /* verify safety of LD_ABS|LD_IND instructions:
14125  * - they can only appear in the programs where ctx == skb
14126  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14127  *   preserve R6-R9, and store return value into R0
14128  *
14129  * Implicit input:
14130  *   ctx == skb == R6 == CTX
14131  *
14132  * Explicit input:
14133  *   SRC == any register
14134  *   IMM == 32-bit immediate
14135  *
14136  * Output:
14137  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14138  */
14139 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14140 {
14141 	struct bpf_reg_state *regs = cur_regs(env);
14142 	static const int ctx_reg = BPF_REG_6;
14143 	u8 mode = BPF_MODE(insn->code);
14144 	int i, err;
14145 
14146 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14147 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14148 		return -EINVAL;
14149 	}
14150 
14151 	if (!env->ops->gen_ld_abs) {
14152 		verbose(env, "bpf verifier is misconfigured\n");
14153 		return -EINVAL;
14154 	}
14155 
14156 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14157 	    BPF_SIZE(insn->code) == BPF_DW ||
14158 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14159 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14160 		return -EINVAL;
14161 	}
14162 
14163 	/* check whether implicit source operand (register R6) is readable */
14164 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14165 	if (err)
14166 		return err;
14167 
14168 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14169 	 * gen_ld_abs() may terminate the program at runtime, leading to
14170 	 * reference leak.
14171 	 */
14172 	err = check_reference_leak(env);
14173 	if (err) {
14174 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14175 		return err;
14176 	}
14177 
14178 	if (env->cur_state->active_lock.ptr) {
14179 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14180 		return -EINVAL;
14181 	}
14182 
14183 	if (env->cur_state->active_rcu_lock) {
14184 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14185 		return -EINVAL;
14186 	}
14187 
14188 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14189 		verbose(env,
14190 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14191 		return -EINVAL;
14192 	}
14193 
14194 	if (mode == BPF_IND) {
14195 		/* check explicit source operand */
14196 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14197 		if (err)
14198 			return err;
14199 	}
14200 
14201 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14202 	if (err < 0)
14203 		return err;
14204 
14205 	/* reset caller saved regs to unreadable */
14206 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14207 		mark_reg_not_init(env, regs, caller_saved[i]);
14208 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14209 	}
14210 
14211 	/* mark destination R0 register as readable, since it contains
14212 	 * the value fetched from the packet.
14213 	 * Already marked as written above.
14214 	 */
14215 	mark_reg_unknown(env, regs, BPF_REG_0);
14216 	/* ld_abs load up to 32-bit skb data. */
14217 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14218 	return 0;
14219 }
14220 
14221 static int check_return_code(struct bpf_verifier_env *env)
14222 {
14223 	struct tnum enforce_attach_type_range = tnum_unknown;
14224 	const struct bpf_prog *prog = env->prog;
14225 	struct bpf_reg_state *reg;
14226 	struct tnum range = tnum_range(0, 1);
14227 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14228 	int err;
14229 	struct bpf_func_state *frame = env->cur_state->frame[0];
14230 	const bool is_subprog = frame->subprogno;
14231 
14232 	/* LSM and struct_ops func-ptr's return type could be "void" */
14233 	if (!is_subprog) {
14234 		switch (prog_type) {
14235 		case BPF_PROG_TYPE_LSM:
14236 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14237 				/* See below, can be 0 or 0-1 depending on hook. */
14238 				break;
14239 			fallthrough;
14240 		case BPF_PROG_TYPE_STRUCT_OPS:
14241 			if (!prog->aux->attach_func_proto->type)
14242 				return 0;
14243 			break;
14244 		default:
14245 			break;
14246 		}
14247 	}
14248 
14249 	/* eBPF calling convention is such that R0 is used
14250 	 * to return the value from eBPF program.
14251 	 * Make sure that it's readable at this time
14252 	 * of bpf_exit, which means that program wrote
14253 	 * something into it earlier
14254 	 */
14255 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14256 	if (err)
14257 		return err;
14258 
14259 	if (is_pointer_value(env, BPF_REG_0)) {
14260 		verbose(env, "R0 leaks addr as return value\n");
14261 		return -EACCES;
14262 	}
14263 
14264 	reg = cur_regs(env) + BPF_REG_0;
14265 
14266 	if (frame->in_async_callback_fn) {
14267 		/* enforce return zero from async callbacks like timer */
14268 		if (reg->type != SCALAR_VALUE) {
14269 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14270 				reg_type_str(env, reg->type));
14271 			return -EINVAL;
14272 		}
14273 
14274 		if (!tnum_in(tnum_const(0), reg->var_off)) {
14275 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14276 			return -EINVAL;
14277 		}
14278 		return 0;
14279 	}
14280 
14281 	if (is_subprog) {
14282 		if (reg->type != SCALAR_VALUE) {
14283 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14284 				reg_type_str(env, reg->type));
14285 			return -EINVAL;
14286 		}
14287 		return 0;
14288 	}
14289 
14290 	switch (prog_type) {
14291 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14292 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14293 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14294 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14295 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14296 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14297 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14298 			range = tnum_range(1, 1);
14299 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14300 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14301 			range = tnum_range(0, 3);
14302 		break;
14303 	case BPF_PROG_TYPE_CGROUP_SKB:
14304 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14305 			range = tnum_range(0, 3);
14306 			enforce_attach_type_range = tnum_range(2, 3);
14307 		}
14308 		break;
14309 	case BPF_PROG_TYPE_CGROUP_SOCK:
14310 	case BPF_PROG_TYPE_SOCK_OPS:
14311 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14312 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14313 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14314 		break;
14315 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14316 		if (!env->prog->aux->attach_btf_id)
14317 			return 0;
14318 		range = tnum_const(0);
14319 		break;
14320 	case BPF_PROG_TYPE_TRACING:
14321 		switch (env->prog->expected_attach_type) {
14322 		case BPF_TRACE_FENTRY:
14323 		case BPF_TRACE_FEXIT:
14324 			range = tnum_const(0);
14325 			break;
14326 		case BPF_TRACE_RAW_TP:
14327 		case BPF_MODIFY_RETURN:
14328 			return 0;
14329 		case BPF_TRACE_ITER:
14330 			break;
14331 		default:
14332 			return -ENOTSUPP;
14333 		}
14334 		break;
14335 	case BPF_PROG_TYPE_SK_LOOKUP:
14336 		range = tnum_range(SK_DROP, SK_PASS);
14337 		break;
14338 
14339 	case BPF_PROG_TYPE_LSM:
14340 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14341 			/* Regular BPF_PROG_TYPE_LSM programs can return
14342 			 * any value.
14343 			 */
14344 			return 0;
14345 		}
14346 		if (!env->prog->aux->attach_func_proto->type) {
14347 			/* Make sure programs that attach to void
14348 			 * hooks don't try to modify return value.
14349 			 */
14350 			range = tnum_range(1, 1);
14351 		}
14352 		break;
14353 
14354 	case BPF_PROG_TYPE_NETFILTER:
14355 		range = tnum_range(NF_DROP, NF_ACCEPT);
14356 		break;
14357 	case BPF_PROG_TYPE_EXT:
14358 		/* freplace program can return anything as its return value
14359 		 * depends on the to-be-replaced kernel func or bpf program.
14360 		 */
14361 	default:
14362 		return 0;
14363 	}
14364 
14365 	if (reg->type != SCALAR_VALUE) {
14366 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14367 			reg_type_str(env, reg->type));
14368 		return -EINVAL;
14369 	}
14370 
14371 	if (!tnum_in(range, reg->var_off)) {
14372 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14373 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14374 		    prog_type == BPF_PROG_TYPE_LSM &&
14375 		    !prog->aux->attach_func_proto->type)
14376 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14377 		return -EINVAL;
14378 	}
14379 
14380 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14381 	    tnum_in(enforce_attach_type_range, reg->var_off))
14382 		env->prog->enforce_expected_attach_type = 1;
14383 	return 0;
14384 }
14385 
14386 /* non-recursive DFS pseudo code
14387  * 1  procedure DFS-iterative(G,v):
14388  * 2      label v as discovered
14389  * 3      let S be a stack
14390  * 4      S.push(v)
14391  * 5      while S is not empty
14392  * 6            t <- S.peek()
14393  * 7            if t is what we're looking for:
14394  * 8                return t
14395  * 9            for all edges e in G.adjacentEdges(t) do
14396  * 10               if edge e is already labelled
14397  * 11                   continue with the next edge
14398  * 12               w <- G.adjacentVertex(t,e)
14399  * 13               if vertex w is not discovered and not explored
14400  * 14                   label e as tree-edge
14401  * 15                   label w as discovered
14402  * 16                   S.push(w)
14403  * 17                   continue at 5
14404  * 18               else if vertex w is discovered
14405  * 19                   label e as back-edge
14406  * 20               else
14407  * 21                   // vertex w is explored
14408  * 22                   label e as forward- or cross-edge
14409  * 23           label t as explored
14410  * 24           S.pop()
14411  *
14412  * convention:
14413  * 0x10 - discovered
14414  * 0x11 - discovered and fall-through edge labelled
14415  * 0x12 - discovered and fall-through and branch edges labelled
14416  * 0x20 - explored
14417  */
14418 
14419 enum {
14420 	DISCOVERED = 0x10,
14421 	EXPLORED = 0x20,
14422 	FALLTHROUGH = 1,
14423 	BRANCH = 2,
14424 };
14425 
14426 static u32 state_htab_size(struct bpf_verifier_env *env)
14427 {
14428 	return env->prog->len;
14429 }
14430 
14431 static struct bpf_verifier_state_list **explored_state(
14432 					struct bpf_verifier_env *env,
14433 					int idx)
14434 {
14435 	struct bpf_verifier_state *cur = env->cur_state;
14436 	struct bpf_func_state *state = cur->frame[cur->curframe];
14437 
14438 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14439 }
14440 
14441 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14442 {
14443 	env->insn_aux_data[idx].prune_point = true;
14444 }
14445 
14446 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14447 {
14448 	return env->insn_aux_data[insn_idx].prune_point;
14449 }
14450 
14451 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14452 {
14453 	env->insn_aux_data[idx].force_checkpoint = true;
14454 }
14455 
14456 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14457 {
14458 	return env->insn_aux_data[insn_idx].force_checkpoint;
14459 }
14460 
14461 
14462 enum {
14463 	DONE_EXPLORING = 0,
14464 	KEEP_EXPLORING = 1,
14465 };
14466 
14467 /* t, w, e - match pseudo-code above:
14468  * t - index of current instruction
14469  * w - next instruction
14470  * e - edge
14471  */
14472 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14473 		     bool loop_ok)
14474 {
14475 	int *insn_stack = env->cfg.insn_stack;
14476 	int *insn_state = env->cfg.insn_state;
14477 
14478 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14479 		return DONE_EXPLORING;
14480 
14481 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14482 		return DONE_EXPLORING;
14483 
14484 	if (w < 0 || w >= env->prog->len) {
14485 		verbose_linfo(env, t, "%d: ", t);
14486 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14487 		return -EINVAL;
14488 	}
14489 
14490 	if (e == BRANCH) {
14491 		/* mark branch target for state pruning */
14492 		mark_prune_point(env, w);
14493 		mark_jmp_point(env, w);
14494 	}
14495 
14496 	if (insn_state[w] == 0) {
14497 		/* tree-edge */
14498 		insn_state[t] = DISCOVERED | e;
14499 		insn_state[w] = DISCOVERED;
14500 		if (env->cfg.cur_stack >= env->prog->len)
14501 			return -E2BIG;
14502 		insn_stack[env->cfg.cur_stack++] = w;
14503 		return KEEP_EXPLORING;
14504 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14505 		if (loop_ok && env->bpf_capable)
14506 			return DONE_EXPLORING;
14507 		verbose_linfo(env, t, "%d: ", t);
14508 		verbose_linfo(env, w, "%d: ", w);
14509 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14510 		return -EINVAL;
14511 	} else if (insn_state[w] == EXPLORED) {
14512 		/* forward- or cross-edge */
14513 		insn_state[t] = DISCOVERED | e;
14514 	} else {
14515 		verbose(env, "insn state internal bug\n");
14516 		return -EFAULT;
14517 	}
14518 	return DONE_EXPLORING;
14519 }
14520 
14521 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14522 				struct bpf_verifier_env *env,
14523 				bool visit_callee)
14524 {
14525 	int ret;
14526 
14527 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14528 	if (ret)
14529 		return ret;
14530 
14531 	mark_prune_point(env, t + 1);
14532 	/* when we exit from subprog, we need to record non-linear history */
14533 	mark_jmp_point(env, t + 1);
14534 
14535 	if (visit_callee) {
14536 		mark_prune_point(env, t);
14537 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14538 				/* It's ok to allow recursion from CFG point of
14539 				 * view. __check_func_call() will do the actual
14540 				 * check.
14541 				 */
14542 				bpf_pseudo_func(insns + t));
14543 	}
14544 	return ret;
14545 }
14546 
14547 /* Visits the instruction at index t and returns one of the following:
14548  *  < 0 - an error occurred
14549  *  DONE_EXPLORING - the instruction was fully explored
14550  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14551  */
14552 static int visit_insn(int t, struct bpf_verifier_env *env)
14553 {
14554 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14555 	int ret;
14556 
14557 	if (bpf_pseudo_func(insn))
14558 		return visit_func_call_insn(t, insns, env, true);
14559 
14560 	/* All non-branch instructions have a single fall-through edge. */
14561 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14562 	    BPF_CLASS(insn->code) != BPF_JMP32)
14563 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14564 
14565 	switch (BPF_OP(insn->code)) {
14566 	case BPF_EXIT:
14567 		return DONE_EXPLORING;
14568 
14569 	case BPF_CALL:
14570 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14571 			/* Mark this call insn as a prune point to trigger
14572 			 * is_state_visited() check before call itself is
14573 			 * processed by __check_func_call(). Otherwise new
14574 			 * async state will be pushed for further exploration.
14575 			 */
14576 			mark_prune_point(env, t);
14577 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14578 			struct bpf_kfunc_call_arg_meta meta;
14579 
14580 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14581 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14582 				mark_prune_point(env, t);
14583 				/* Checking and saving state checkpoints at iter_next() call
14584 				 * is crucial for fast convergence of open-coded iterator loop
14585 				 * logic, so we need to force it. If we don't do that,
14586 				 * is_state_visited() might skip saving a checkpoint, causing
14587 				 * unnecessarily long sequence of not checkpointed
14588 				 * instructions and jumps, leading to exhaustion of jump
14589 				 * history buffer, and potentially other undesired outcomes.
14590 				 * It is expected that with correct open-coded iterators
14591 				 * convergence will happen quickly, so we don't run a risk of
14592 				 * exhausting memory.
14593 				 */
14594 				mark_force_checkpoint(env, t);
14595 			}
14596 		}
14597 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14598 
14599 	case BPF_JA:
14600 		if (BPF_SRC(insn->code) != BPF_K)
14601 			return -EINVAL;
14602 
14603 		/* unconditional jump with single edge */
14604 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14605 				true);
14606 		if (ret)
14607 			return ret;
14608 
14609 		mark_prune_point(env, t + insn->off + 1);
14610 		mark_jmp_point(env, t + insn->off + 1);
14611 
14612 		return ret;
14613 
14614 	default:
14615 		/* conditional jump with two edges */
14616 		mark_prune_point(env, t);
14617 
14618 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14619 		if (ret)
14620 			return ret;
14621 
14622 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14623 	}
14624 }
14625 
14626 /* non-recursive depth-first-search to detect loops in BPF program
14627  * loop == back-edge in directed graph
14628  */
14629 static int check_cfg(struct bpf_verifier_env *env)
14630 {
14631 	int insn_cnt = env->prog->len;
14632 	int *insn_stack, *insn_state;
14633 	int ret = 0;
14634 	int i;
14635 
14636 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14637 	if (!insn_state)
14638 		return -ENOMEM;
14639 
14640 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14641 	if (!insn_stack) {
14642 		kvfree(insn_state);
14643 		return -ENOMEM;
14644 	}
14645 
14646 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14647 	insn_stack[0] = 0; /* 0 is the first instruction */
14648 	env->cfg.cur_stack = 1;
14649 
14650 	while (env->cfg.cur_stack > 0) {
14651 		int t = insn_stack[env->cfg.cur_stack - 1];
14652 
14653 		ret = visit_insn(t, env);
14654 		switch (ret) {
14655 		case DONE_EXPLORING:
14656 			insn_state[t] = EXPLORED;
14657 			env->cfg.cur_stack--;
14658 			break;
14659 		case KEEP_EXPLORING:
14660 			break;
14661 		default:
14662 			if (ret > 0) {
14663 				verbose(env, "visit_insn internal bug\n");
14664 				ret = -EFAULT;
14665 			}
14666 			goto err_free;
14667 		}
14668 	}
14669 
14670 	if (env->cfg.cur_stack < 0) {
14671 		verbose(env, "pop stack internal bug\n");
14672 		ret = -EFAULT;
14673 		goto err_free;
14674 	}
14675 
14676 	for (i = 0; i < insn_cnt; i++) {
14677 		if (insn_state[i] != EXPLORED) {
14678 			verbose(env, "unreachable insn %d\n", i);
14679 			ret = -EINVAL;
14680 			goto err_free;
14681 		}
14682 	}
14683 	ret = 0; /* cfg looks good */
14684 
14685 err_free:
14686 	kvfree(insn_state);
14687 	kvfree(insn_stack);
14688 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14689 	return ret;
14690 }
14691 
14692 static int check_abnormal_return(struct bpf_verifier_env *env)
14693 {
14694 	int i;
14695 
14696 	for (i = 1; i < env->subprog_cnt; i++) {
14697 		if (env->subprog_info[i].has_ld_abs) {
14698 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14699 			return -EINVAL;
14700 		}
14701 		if (env->subprog_info[i].has_tail_call) {
14702 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14703 			return -EINVAL;
14704 		}
14705 	}
14706 	return 0;
14707 }
14708 
14709 /* The minimum supported BTF func info size */
14710 #define MIN_BPF_FUNCINFO_SIZE	8
14711 #define MAX_FUNCINFO_REC_SIZE	252
14712 
14713 static int check_btf_func(struct bpf_verifier_env *env,
14714 			  const union bpf_attr *attr,
14715 			  bpfptr_t uattr)
14716 {
14717 	const struct btf_type *type, *func_proto, *ret_type;
14718 	u32 i, nfuncs, urec_size, min_size;
14719 	u32 krec_size = sizeof(struct bpf_func_info);
14720 	struct bpf_func_info *krecord;
14721 	struct bpf_func_info_aux *info_aux = NULL;
14722 	struct bpf_prog *prog;
14723 	const struct btf *btf;
14724 	bpfptr_t urecord;
14725 	u32 prev_offset = 0;
14726 	bool scalar_return;
14727 	int ret = -ENOMEM;
14728 
14729 	nfuncs = attr->func_info_cnt;
14730 	if (!nfuncs) {
14731 		if (check_abnormal_return(env))
14732 			return -EINVAL;
14733 		return 0;
14734 	}
14735 
14736 	if (nfuncs != env->subprog_cnt) {
14737 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14738 		return -EINVAL;
14739 	}
14740 
14741 	urec_size = attr->func_info_rec_size;
14742 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14743 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
14744 	    urec_size % sizeof(u32)) {
14745 		verbose(env, "invalid func info rec size %u\n", urec_size);
14746 		return -EINVAL;
14747 	}
14748 
14749 	prog = env->prog;
14750 	btf = prog->aux->btf;
14751 
14752 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14753 	min_size = min_t(u32, krec_size, urec_size);
14754 
14755 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14756 	if (!krecord)
14757 		return -ENOMEM;
14758 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14759 	if (!info_aux)
14760 		goto err_free;
14761 
14762 	for (i = 0; i < nfuncs; i++) {
14763 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14764 		if (ret) {
14765 			if (ret == -E2BIG) {
14766 				verbose(env, "nonzero tailing record in func info");
14767 				/* set the size kernel expects so loader can zero
14768 				 * out the rest of the record.
14769 				 */
14770 				if (copy_to_bpfptr_offset(uattr,
14771 							  offsetof(union bpf_attr, func_info_rec_size),
14772 							  &min_size, sizeof(min_size)))
14773 					ret = -EFAULT;
14774 			}
14775 			goto err_free;
14776 		}
14777 
14778 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14779 			ret = -EFAULT;
14780 			goto err_free;
14781 		}
14782 
14783 		/* check insn_off */
14784 		ret = -EINVAL;
14785 		if (i == 0) {
14786 			if (krecord[i].insn_off) {
14787 				verbose(env,
14788 					"nonzero insn_off %u for the first func info record",
14789 					krecord[i].insn_off);
14790 				goto err_free;
14791 			}
14792 		} else if (krecord[i].insn_off <= prev_offset) {
14793 			verbose(env,
14794 				"same or smaller insn offset (%u) than previous func info record (%u)",
14795 				krecord[i].insn_off, prev_offset);
14796 			goto err_free;
14797 		}
14798 
14799 		if (env->subprog_info[i].start != krecord[i].insn_off) {
14800 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14801 			goto err_free;
14802 		}
14803 
14804 		/* check type_id */
14805 		type = btf_type_by_id(btf, krecord[i].type_id);
14806 		if (!type || !btf_type_is_func(type)) {
14807 			verbose(env, "invalid type id %d in func info",
14808 				krecord[i].type_id);
14809 			goto err_free;
14810 		}
14811 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14812 
14813 		func_proto = btf_type_by_id(btf, type->type);
14814 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14815 			/* btf_func_check() already verified it during BTF load */
14816 			goto err_free;
14817 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14818 		scalar_return =
14819 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14820 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14821 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14822 			goto err_free;
14823 		}
14824 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14825 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14826 			goto err_free;
14827 		}
14828 
14829 		prev_offset = krecord[i].insn_off;
14830 		bpfptr_add(&urecord, urec_size);
14831 	}
14832 
14833 	prog->aux->func_info = krecord;
14834 	prog->aux->func_info_cnt = nfuncs;
14835 	prog->aux->func_info_aux = info_aux;
14836 	return 0;
14837 
14838 err_free:
14839 	kvfree(krecord);
14840 	kfree(info_aux);
14841 	return ret;
14842 }
14843 
14844 static void adjust_btf_func(struct bpf_verifier_env *env)
14845 {
14846 	struct bpf_prog_aux *aux = env->prog->aux;
14847 	int i;
14848 
14849 	if (!aux->func_info)
14850 		return;
14851 
14852 	for (i = 0; i < env->subprog_cnt; i++)
14853 		aux->func_info[i].insn_off = env->subprog_info[i].start;
14854 }
14855 
14856 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
14857 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
14858 
14859 static int check_btf_line(struct bpf_verifier_env *env,
14860 			  const union bpf_attr *attr,
14861 			  bpfptr_t uattr)
14862 {
14863 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14864 	struct bpf_subprog_info *sub;
14865 	struct bpf_line_info *linfo;
14866 	struct bpf_prog *prog;
14867 	const struct btf *btf;
14868 	bpfptr_t ulinfo;
14869 	int err;
14870 
14871 	nr_linfo = attr->line_info_cnt;
14872 	if (!nr_linfo)
14873 		return 0;
14874 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14875 		return -EINVAL;
14876 
14877 	rec_size = attr->line_info_rec_size;
14878 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14879 	    rec_size > MAX_LINEINFO_REC_SIZE ||
14880 	    rec_size & (sizeof(u32) - 1))
14881 		return -EINVAL;
14882 
14883 	/* Need to zero it in case the userspace may
14884 	 * pass in a smaller bpf_line_info object.
14885 	 */
14886 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14887 			 GFP_KERNEL | __GFP_NOWARN);
14888 	if (!linfo)
14889 		return -ENOMEM;
14890 
14891 	prog = env->prog;
14892 	btf = prog->aux->btf;
14893 
14894 	s = 0;
14895 	sub = env->subprog_info;
14896 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14897 	expected_size = sizeof(struct bpf_line_info);
14898 	ncopy = min_t(u32, expected_size, rec_size);
14899 	for (i = 0; i < nr_linfo; i++) {
14900 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14901 		if (err) {
14902 			if (err == -E2BIG) {
14903 				verbose(env, "nonzero tailing record in line_info");
14904 				if (copy_to_bpfptr_offset(uattr,
14905 							  offsetof(union bpf_attr, line_info_rec_size),
14906 							  &expected_size, sizeof(expected_size)))
14907 					err = -EFAULT;
14908 			}
14909 			goto err_free;
14910 		}
14911 
14912 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14913 			err = -EFAULT;
14914 			goto err_free;
14915 		}
14916 
14917 		/*
14918 		 * Check insn_off to ensure
14919 		 * 1) strictly increasing AND
14920 		 * 2) bounded by prog->len
14921 		 *
14922 		 * The linfo[0].insn_off == 0 check logically falls into
14923 		 * the later "missing bpf_line_info for func..." case
14924 		 * because the first linfo[0].insn_off must be the
14925 		 * first sub also and the first sub must have
14926 		 * subprog_info[0].start == 0.
14927 		 */
14928 		if ((i && linfo[i].insn_off <= prev_offset) ||
14929 		    linfo[i].insn_off >= prog->len) {
14930 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14931 				i, linfo[i].insn_off, prev_offset,
14932 				prog->len);
14933 			err = -EINVAL;
14934 			goto err_free;
14935 		}
14936 
14937 		if (!prog->insnsi[linfo[i].insn_off].code) {
14938 			verbose(env,
14939 				"Invalid insn code at line_info[%u].insn_off\n",
14940 				i);
14941 			err = -EINVAL;
14942 			goto err_free;
14943 		}
14944 
14945 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14946 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14947 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14948 			err = -EINVAL;
14949 			goto err_free;
14950 		}
14951 
14952 		if (s != env->subprog_cnt) {
14953 			if (linfo[i].insn_off == sub[s].start) {
14954 				sub[s].linfo_idx = i;
14955 				s++;
14956 			} else if (sub[s].start < linfo[i].insn_off) {
14957 				verbose(env, "missing bpf_line_info for func#%u\n", s);
14958 				err = -EINVAL;
14959 				goto err_free;
14960 			}
14961 		}
14962 
14963 		prev_offset = linfo[i].insn_off;
14964 		bpfptr_add(&ulinfo, rec_size);
14965 	}
14966 
14967 	if (s != env->subprog_cnt) {
14968 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14969 			env->subprog_cnt - s, s);
14970 		err = -EINVAL;
14971 		goto err_free;
14972 	}
14973 
14974 	prog->aux->linfo = linfo;
14975 	prog->aux->nr_linfo = nr_linfo;
14976 
14977 	return 0;
14978 
14979 err_free:
14980 	kvfree(linfo);
14981 	return err;
14982 }
14983 
14984 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
14985 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
14986 
14987 static int check_core_relo(struct bpf_verifier_env *env,
14988 			   const union bpf_attr *attr,
14989 			   bpfptr_t uattr)
14990 {
14991 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14992 	struct bpf_core_relo core_relo = {};
14993 	struct bpf_prog *prog = env->prog;
14994 	const struct btf *btf = prog->aux->btf;
14995 	struct bpf_core_ctx ctx = {
14996 		.log = &env->log,
14997 		.btf = btf,
14998 	};
14999 	bpfptr_t u_core_relo;
15000 	int err;
15001 
15002 	nr_core_relo = attr->core_relo_cnt;
15003 	if (!nr_core_relo)
15004 		return 0;
15005 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15006 		return -EINVAL;
15007 
15008 	rec_size = attr->core_relo_rec_size;
15009 	if (rec_size < MIN_CORE_RELO_SIZE ||
15010 	    rec_size > MAX_CORE_RELO_SIZE ||
15011 	    rec_size % sizeof(u32))
15012 		return -EINVAL;
15013 
15014 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15015 	expected_size = sizeof(struct bpf_core_relo);
15016 	ncopy = min_t(u32, expected_size, rec_size);
15017 
15018 	/* Unlike func_info and line_info, copy and apply each CO-RE
15019 	 * relocation record one at a time.
15020 	 */
15021 	for (i = 0; i < nr_core_relo; i++) {
15022 		/* future proofing when sizeof(bpf_core_relo) changes */
15023 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15024 		if (err) {
15025 			if (err == -E2BIG) {
15026 				verbose(env, "nonzero tailing record in core_relo");
15027 				if (copy_to_bpfptr_offset(uattr,
15028 							  offsetof(union bpf_attr, core_relo_rec_size),
15029 							  &expected_size, sizeof(expected_size)))
15030 					err = -EFAULT;
15031 			}
15032 			break;
15033 		}
15034 
15035 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15036 			err = -EFAULT;
15037 			break;
15038 		}
15039 
15040 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15041 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15042 				i, core_relo.insn_off, prog->len);
15043 			err = -EINVAL;
15044 			break;
15045 		}
15046 
15047 		err = bpf_core_apply(&ctx, &core_relo, i,
15048 				     &prog->insnsi[core_relo.insn_off / 8]);
15049 		if (err)
15050 			break;
15051 		bpfptr_add(&u_core_relo, rec_size);
15052 	}
15053 	return err;
15054 }
15055 
15056 static int check_btf_info(struct bpf_verifier_env *env,
15057 			  const union bpf_attr *attr,
15058 			  bpfptr_t uattr)
15059 {
15060 	struct btf *btf;
15061 	int err;
15062 
15063 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15064 		if (check_abnormal_return(env))
15065 			return -EINVAL;
15066 		return 0;
15067 	}
15068 
15069 	btf = btf_get_by_fd(attr->prog_btf_fd);
15070 	if (IS_ERR(btf))
15071 		return PTR_ERR(btf);
15072 	if (btf_is_kernel(btf)) {
15073 		btf_put(btf);
15074 		return -EACCES;
15075 	}
15076 	env->prog->aux->btf = btf;
15077 
15078 	err = check_btf_func(env, attr, uattr);
15079 	if (err)
15080 		return err;
15081 
15082 	err = check_btf_line(env, attr, uattr);
15083 	if (err)
15084 		return err;
15085 
15086 	err = check_core_relo(env, attr, uattr);
15087 	if (err)
15088 		return err;
15089 
15090 	return 0;
15091 }
15092 
15093 /* check %cur's range satisfies %old's */
15094 static bool range_within(struct bpf_reg_state *old,
15095 			 struct bpf_reg_state *cur)
15096 {
15097 	return old->umin_value <= cur->umin_value &&
15098 	       old->umax_value >= cur->umax_value &&
15099 	       old->smin_value <= cur->smin_value &&
15100 	       old->smax_value >= cur->smax_value &&
15101 	       old->u32_min_value <= cur->u32_min_value &&
15102 	       old->u32_max_value >= cur->u32_max_value &&
15103 	       old->s32_min_value <= cur->s32_min_value &&
15104 	       old->s32_max_value >= cur->s32_max_value;
15105 }
15106 
15107 /* If in the old state two registers had the same id, then they need to have
15108  * the same id in the new state as well.  But that id could be different from
15109  * the old state, so we need to track the mapping from old to new ids.
15110  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15111  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15112  * regs with a different old id could still have new id 9, we don't care about
15113  * that.
15114  * So we look through our idmap to see if this old id has been seen before.  If
15115  * so, we require the new id to match; otherwise, we add the id pair to the map.
15116  */
15117 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
15118 {
15119 	unsigned int i;
15120 
15121 	/* either both IDs should be set or both should be zero */
15122 	if (!!old_id != !!cur_id)
15123 		return false;
15124 
15125 	if (old_id == 0) /* cur_id == 0 as well */
15126 		return true;
15127 
15128 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15129 		if (!idmap[i].old) {
15130 			/* Reached an empty slot; haven't seen this id before */
15131 			idmap[i].old = old_id;
15132 			idmap[i].cur = cur_id;
15133 			return true;
15134 		}
15135 		if (idmap[i].old == old_id)
15136 			return idmap[i].cur == cur_id;
15137 	}
15138 	/* We ran out of idmap slots, which should be impossible */
15139 	WARN_ON_ONCE(1);
15140 	return false;
15141 }
15142 
15143 static void clean_func_state(struct bpf_verifier_env *env,
15144 			     struct bpf_func_state *st)
15145 {
15146 	enum bpf_reg_liveness live;
15147 	int i, j;
15148 
15149 	for (i = 0; i < BPF_REG_FP; i++) {
15150 		live = st->regs[i].live;
15151 		/* liveness must not touch this register anymore */
15152 		st->regs[i].live |= REG_LIVE_DONE;
15153 		if (!(live & REG_LIVE_READ))
15154 			/* since the register is unused, clear its state
15155 			 * to make further comparison simpler
15156 			 */
15157 			__mark_reg_not_init(env, &st->regs[i]);
15158 	}
15159 
15160 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15161 		live = st->stack[i].spilled_ptr.live;
15162 		/* liveness must not touch this stack slot anymore */
15163 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15164 		if (!(live & REG_LIVE_READ)) {
15165 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15166 			for (j = 0; j < BPF_REG_SIZE; j++)
15167 				st->stack[i].slot_type[j] = STACK_INVALID;
15168 		}
15169 	}
15170 }
15171 
15172 static void clean_verifier_state(struct bpf_verifier_env *env,
15173 				 struct bpf_verifier_state *st)
15174 {
15175 	int i;
15176 
15177 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15178 		/* all regs in this state in all frames were already marked */
15179 		return;
15180 
15181 	for (i = 0; i <= st->curframe; i++)
15182 		clean_func_state(env, st->frame[i]);
15183 }
15184 
15185 /* the parentage chains form a tree.
15186  * the verifier states are added to state lists at given insn and
15187  * pushed into state stack for future exploration.
15188  * when the verifier reaches bpf_exit insn some of the verifer states
15189  * stored in the state lists have their final liveness state already,
15190  * but a lot of states will get revised from liveness point of view when
15191  * the verifier explores other branches.
15192  * Example:
15193  * 1: r0 = 1
15194  * 2: if r1 == 100 goto pc+1
15195  * 3: r0 = 2
15196  * 4: exit
15197  * when the verifier reaches exit insn the register r0 in the state list of
15198  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15199  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15200  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15201  *
15202  * Since the verifier pushes the branch states as it sees them while exploring
15203  * the program the condition of walking the branch instruction for the second
15204  * time means that all states below this branch were already explored and
15205  * their final liveness marks are already propagated.
15206  * Hence when the verifier completes the search of state list in is_state_visited()
15207  * we can call this clean_live_states() function to mark all liveness states
15208  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15209  * will not be used.
15210  * This function also clears the registers and stack for states that !READ
15211  * to simplify state merging.
15212  *
15213  * Important note here that walking the same branch instruction in the callee
15214  * doesn't meant that the states are DONE. The verifier has to compare
15215  * the callsites
15216  */
15217 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15218 			      struct bpf_verifier_state *cur)
15219 {
15220 	struct bpf_verifier_state_list *sl;
15221 	int i;
15222 
15223 	sl = *explored_state(env, insn);
15224 	while (sl) {
15225 		if (sl->state.branches)
15226 			goto next;
15227 		if (sl->state.insn_idx != insn ||
15228 		    sl->state.curframe != cur->curframe)
15229 			goto next;
15230 		for (i = 0; i <= cur->curframe; i++)
15231 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15232 				goto next;
15233 		clean_verifier_state(env, &sl->state);
15234 next:
15235 		sl = sl->next;
15236 	}
15237 }
15238 
15239 static bool regs_exact(const struct bpf_reg_state *rold,
15240 		       const struct bpf_reg_state *rcur,
15241 		       struct bpf_id_pair *idmap)
15242 {
15243 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15244 	       check_ids(rold->id, rcur->id, idmap) &&
15245 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15246 }
15247 
15248 /* Returns true if (rold safe implies rcur safe) */
15249 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15250 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
15251 {
15252 	if (!(rold->live & REG_LIVE_READ))
15253 		/* explored state didn't use this */
15254 		return true;
15255 	if (rold->type == NOT_INIT)
15256 		/* explored state can't have used this */
15257 		return true;
15258 	if (rcur->type == NOT_INIT)
15259 		return false;
15260 
15261 	/* Enforce that register types have to match exactly, including their
15262 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15263 	 * rule.
15264 	 *
15265 	 * One can make a point that using a pointer register as unbounded
15266 	 * SCALAR would be technically acceptable, but this could lead to
15267 	 * pointer leaks because scalars are allowed to leak while pointers
15268 	 * are not. We could make this safe in special cases if root is
15269 	 * calling us, but it's probably not worth the hassle.
15270 	 *
15271 	 * Also, register types that are *not* MAYBE_NULL could technically be
15272 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15273 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15274 	 * to the same map).
15275 	 * However, if the old MAYBE_NULL register then got NULL checked,
15276 	 * doing so could have affected others with the same id, and we can't
15277 	 * check for that because we lost the id when we converted to
15278 	 * a non-MAYBE_NULL variant.
15279 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15280 	 * non-MAYBE_NULL registers as well.
15281 	 */
15282 	if (rold->type != rcur->type)
15283 		return false;
15284 
15285 	switch (base_type(rold->type)) {
15286 	case SCALAR_VALUE:
15287 		if (regs_exact(rold, rcur, idmap))
15288 			return true;
15289 		if (env->explore_alu_limits)
15290 			return false;
15291 		if (!rold->precise)
15292 			return true;
15293 		/* new val must satisfy old val knowledge */
15294 		return range_within(rold, rcur) &&
15295 		       tnum_in(rold->var_off, rcur->var_off);
15296 	case PTR_TO_MAP_KEY:
15297 	case PTR_TO_MAP_VALUE:
15298 	case PTR_TO_MEM:
15299 	case PTR_TO_BUF:
15300 	case PTR_TO_TP_BUFFER:
15301 		/* If the new min/max/var_off satisfy the old ones and
15302 		 * everything else matches, we are OK.
15303 		 */
15304 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15305 		       range_within(rold, rcur) &&
15306 		       tnum_in(rold->var_off, rcur->var_off) &&
15307 		       check_ids(rold->id, rcur->id, idmap) &&
15308 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15309 	case PTR_TO_PACKET_META:
15310 	case PTR_TO_PACKET:
15311 		/* We must have at least as much range as the old ptr
15312 		 * did, so that any accesses which were safe before are
15313 		 * still safe.  This is true even if old range < old off,
15314 		 * since someone could have accessed through (ptr - k), or
15315 		 * even done ptr -= k in a register, to get a safe access.
15316 		 */
15317 		if (rold->range > rcur->range)
15318 			return false;
15319 		/* If the offsets don't match, we can't trust our alignment;
15320 		 * nor can we be sure that we won't fall out of range.
15321 		 */
15322 		if (rold->off != rcur->off)
15323 			return false;
15324 		/* id relations must be preserved */
15325 		if (!check_ids(rold->id, rcur->id, idmap))
15326 			return false;
15327 		/* new val must satisfy old val knowledge */
15328 		return range_within(rold, rcur) &&
15329 		       tnum_in(rold->var_off, rcur->var_off);
15330 	case PTR_TO_STACK:
15331 		/* two stack pointers are equal only if they're pointing to
15332 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15333 		 */
15334 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15335 	default:
15336 		return regs_exact(rold, rcur, idmap);
15337 	}
15338 }
15339 
15340 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15341 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
15342 {
15343 	int i, spi;
15344 
15345 	/* walk slots of the explored stack and ignore any additional
15346 	 * slots in the current stack, since explored(safe) state
15347 	 * didn't use them
15348 	 */
15349 	for (i = 0; i < old->allocated_stack; i++) {
15350 		struct bpf_reg_state *old_reg, *cur_reg;
15351 
15352 		spi = i / BPF_REG_SIZE;
15353 
15354 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15355 			i += BPF_REG_SIZE - 1;
15356 			/* explored state didn't use this */
15357 			continue;
15358 		}
15359 
15360 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15361 			continue;
15362 
15363 		if (env->allow_uninit_stack &&
15364 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15365 			continue;
15366 
15367 		/* explored stack has more populated slots than current stack
15368 		 * and these slots were used
15369 		 */
15370 		if (i >= cur->allocated_stack)
15371 			return false;
15372 
15373 		/* if old state was safe with misc data in the stack
15374 		 * it will be safe with zero-initialized stack.
15375 		 * The opposite is not true
15376 		 */
15377 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15378 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15379 			continue;
15380 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15381 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15382 			/* Ex: old explored (safe) state has STACK_SPILL in
15383 			 * this stack slot, but current has STACK_MISC ->
15384 			 * this verifier states are not equivalent,
15385 			 * return false to continue verification of this path
15386 			 */
15387 			return false;
15388 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15389 			continue;
15390 		/* Both old and cur are having same slot_type */
15391 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15392 		case STACK_SPILL:
15393 			/* when explored and current stack slot are both storing
15394 			 * spilled registers, check that stored pointers types
15395 			 * are the same as well.
15396 			 * Ex: explored safe path could have stored
15397 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15398 			 * but current path has stored:
15399 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15400 			 * such verifier states are not equivalent.
15401 			 * return false to continue verification of this path
15402 			 */
15403 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15404 				     &cur->stack[spi].spilled_ptr, idmap))
15405 				return false;
15406 			break;
15407 		case STACK_DYNPTR:
15408 			old_reg = &old->stack[spi].spilled_ptr;
15409 			cur_reg = &cur->stack[spi].spilled_ptr;
15410 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15411 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15412 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15413 				return false;
15414 			break;
15415 		case STACK_ITER:
15416 			old_reg = &old->stack[spi].spilled_ptr;
15417 			cur_reg = &cur->stack[spi].spilled_ptr;
15418 			/* iter.depth is not compared between states as it
15419 			 * doesn't matter for correctness and would otherwise
15420 			 * prevent convergence; we maintain it only to prevent
15421 			 * infinite loop check triggering, see
15422 			 * iter_active_depths_differ()
15423 			 */
15424 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15425 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15426 			    old_reg->iter.state != cur_reg->iter.state ||
15427 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15428 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15429 				return false;
15430 			break;
15431 		case STACK_MISC:
15432 		case STACK_ZERO:
15433 		case STACK_INVALID:
15434 			continue;
15435 		/* Ensure that new unhandled slot types return false by default */
15436 		default:
15437 			return false;
15438 		}
15439 	}
15440 	return true;
15441 }
15442 
15443 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15444 		    struct bpf_id_pair *idmap)
15445 {
15446 	int i;
15447 
15448 	if (old->acquired_refs != cur->acquired_refs)
15449 		return false;
15450 
15451 	for (i = 0; i < old->acquired_refs; i++) {
15452 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15453 			return false;
15454 	}
15455 
15456 	return true;
15457 }
15458 
15459 /* compare two verifier states
15460  *
15461  * all states stored in state_list are known to be valid, since
15462  * verifier reached 'bpf_exit' instruction through them
15463  *
15464  * this function is called when verifier exploring different branches of
15465  * execution popped from the state stack. If it sees an old state that has
15466  * more strict register state and more strict stack state then this execution
15467  * branch doesn't need to be explored further, since verifier already
15468  * concluded that more strict state leads to valid finish.
15469  *
15470  * Therefore two states are equivalent if register state is more conservative
15471  * and explored stack state is more conservative than the current one.
15472  * Example:
15473  *       explored                   current
15474  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15475  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15476  *
15477  * In other words if current stack state (one being explored) has more
15478  * valid slots than old one that already passed validation, it means
15479  * the verifier can stop exploring and conclude that current state is valid too
15480  *
15481  * Similarly with registers. If explored state has register type as invalid
15482  * whereas register type in current state is meaningful, it means that
15483  * the current state will reach 'bpf_exit' instruction safely
15484  */
15485 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15486 			      struct bpf_func_state *cur)
15487 {
15488 	int i;
15489 
15490 	for (i = 0; i < MAX_BPF_REG; i++)
15491 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15492 			     env->idmap_scratch))
15493 			return false;
15494 
15495 	if (!stacksafe(env, old, cur, env->idmap_scratch))
15496 		return false;
15497 
15498 	if (!refsafe(old, cur, env->idmap_scratch))
15499 		return false;
15500 
15501 	return true;
15502 }
15503 
15504 static bool states_equal(struct bpf_verifier_env *env,
15505 			 struct bpf_verifier_state *old,
15506 			 struct bpf_verifier_state *cur)
15507 {
15508 	int i;
15509 
15510 	if (old->curframe != cur->curframe)
15511 		return false;
15512 
15513 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
15514 
15515 	/* Verification state from speculative execution simulation
15516 	 * must never prune a non-speculative execution one.
15517 	 */
15518 	if (old->speculative && !cur->speculative)
15519 		return false;
15520 
15521 	if (old->active_lock.ptr != cur->active_lock.ptr)
15522 		return false;
15523 
15524 	/* Old and cur active_lock's have to be either both present
15525 	 * or both absent.
15526 	 */
15527 	if (!!old->active_lock.id != !!cur->active_lock.id)
15528 		return false;
15529 
15530 	if (old->active_lock.id &&
15531 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
15532 		return false;
15533 
15534 	if (old->active_rcu_lock != cur->active_rcu_lock)
15535 		return false;
15536 
15537 	/* for states to be equal callsites have to be the same
15538 	 * and all frame states need to be equivalent
15539 	 */
15540 	for (i = 0; i <= old->curframe; i++) {
15541 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15542 			return false;
15543 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15544 			return false;
15545 	}
15546 	return true;
15547 }
15548 
15549 /* Return 0 if no propagation happened. Return negative error code if error
15550  * happened. Otherwise, return the propagated bit.
15551  */
15552 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15553 				  struct bpf_reg_state *reg,
15554 				  struct bpf_reg_state *parent_reg)
15555 {
15556 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15557 	u8 flag = reg->live & REG_LIVE_READ;
15558 	int err;
15559 
15560 	/* When comes here, read flags of PARENT_REG or REG could be any of
15561 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15562 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15563 	 */
15564 	if (parent_flag == REG_LIVE_READ64 ||
15565 	    /* Or if there is no read flag from REG. */
15566 	    !flag ||
15567 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15568 	    parent_flag == flag)
15569 		return 0;
15570 
15571 	err = mark_reg_read(env, reg, parent_reg, flag);
15572 	if (err)
15573 		return err;
15574 
15575 	return flag;
15576 }
15577 
15578 /* A write screens off any subsequent reads; but write marks come from the
15579  * straight-line code between a state and its parent.  When we arrive at an
15580  * equivalent state (jump target or such) we didn't arrive by the straight-line
15581  * code, so read marks in the state must propagate to the parent regardless
15582  * of the state's write marks. That's what 'parent == state->parent' comparison
15583  * in mark_reg_read() is for.
15584  */
15585 static int propagate_liveness(struct bpf_verifier_env *env,
15586 			      const struct bpf_verifier_state *vstate,
15587 			      struct bpf_verifier_state *vparent)
15588 {
15589 	struct bpf_reg_state *state_reg, *parent_reg;
15590 	struct bpf_func_state *state, *parent;
15591 	int i, frame, err = 0;
15592 
15593 	if (vparent->curframe != vstate->curframe) {
15594 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15595 		     vparent->curframe, vstate->curframe);
15596 		return -EFAULT;
15597 	}
15598 	/* Propagate read liveness of registers... */
15599 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15600 	for (frame = 0; frame <= vstate->curframe; frame++) {
15601 		parent = vparent->frame[frame];
15602 		state = vstate->frame[frame];
15603 		parent_reg = parent->regs;
15604 		state_reg = state->regs;
15605 		/* We don't need to worry about FP liveness, it's read-only */
15606 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15607 			err = propagate_liveness_reg(env, &state_reg[i],
15608 						     &parent_reg[i]);
15609 			if (err < 0)
15610 				return err;
15611 			if (err == REG_LIVE_READ64)
15612 				mark_insn_zext(env, &parent_reg[i]);
15613 		}
15614 
15615 		/* Propagate stack slots. */
15616 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15617 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15618 			parent_reg = &parent->stack[i].spilled_ptr;
15619 			state_reg = &state->stack[i].spilled_ptr;
15620 			err = propagate_liveness_reg(env, state_reg,
15621 						     parent_reg);
15622 			if (err < 0)
15623 				return err;
15624 		}
15625 	}
15626 	return 0;
15627 }
15628 
15629 /* find precise scalars in the previous equivalent state and
15630  * propagate them into the current state
15631  */
15632 static int propagate_precision(struct bpf_verifier_env *env,
15633 			       const struct bpf_verifier_state *old)
15634 {
15635 	struct bpf_reg_state *state_reg;
15636 	struct bpf_func_state *state;
15637 	int i, err = 0, fr;
15638 	bool first;
15639 
15640 	for (fr = old->curframe; fr >= 0; fr--) {
15641 		state = old->frame[fr];
15642 		state_reg = state->regs;
15643 		first = true;
15644 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15645 			if (state_reg->type != SCALAR_VALUE ||
15646 			    !state_reg->precise ||
15647 			    !(state_reg->live & REG_LIVE_READ))
15648 				continue;
15649 			if (env->log.level & BPF_LOG_LEVEL2) {
15650 				if (first)
15651 					verbose(env, "frame %d: propagating r%d", fr, i);
15652 				else
15653 					verbose(env, ",r%d", i);
15654 			}
15655 			bt_set_frame_reg(&env->bt, fr, i);
15656 			first = false;
15657 		}
15658 
15659 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15660 			if (!is_spilled_reg(&state->stack[i]))
15661 				continue;
15662 			state_reg = &state->stack[i].spilled_ptr;
15663 			if (state_reg->type != SCALAR_VALUE ||
15664 			    !state_reg->precise ||
15665 			    !(state_reg->live & REG_LIVE_READ))
15666 				continue;
15667 			if (env->log.level & BPF_LOG_LEVEL2) {
15668 				if (first)
15669 					verbose(env, "frame %d: propagating fp%d",
15670 						fr, (-i - 1) * BPF_REG_SIZE);
15671 				else
15672 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15673 			}
15674 			bt_set_frame_slot(&env->bt, fr, i);
15675 			first = false;
15676 		}
15677 		if (!first)
15678 			verbose(env, "\n");
15679 	}
15680 
15681 	err = mark_chain_precision_batch(env);
15682 	if (err < 0)
15683 		return err;
15684 
15685 	return 0;
15686 }
15687 
15688 static bool states_maybe_looping(struct bpf_verifier_state *old,
15689 				 struct bpf_verifier_state *cur)
15690 {
15691 	struct bpf_func_state *fold, *fcur;
15692 	int i, fr = cur->curframe;
15693 
15694 	if (old->curframe != fr)
15695 		return false;
15696 
15697 	fold = old->frame[fr];
15698 	fcur = cur->frame[fr];
15699 	for (i = 0; i < MAX_BPF_REG; i++)
15700 		if (memcmp(&fold->regs[i], &fcur->regs[i],
15701 			   offsetof(struct bpf_reg_state, parent)))
15702 			return false;
15703 	return true;
15704 }
15705 
15706 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15707 {
15708 	return env->insn_aux_data[insn_idx].is_iter_next;
15709 }
15710 
15711 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15712  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15713  * states to match, which otherwise would look like an infinite loop. So while
15714  * iter_next() calls are taken care of, we still need to be careful and
15715  * prevent erroneous and too eager declaration of "ininite loop", when
15716  * iterators are involved.
15717  *
15718  * Here's a situation in pseudo-BPF assembly form:
15719  *
15720  *   0: again:                          ; set up iter_next() call args
15721  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15722  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15723  *   3:   if r0 == 0 goto done
15724  *   4:   ... something useful here ...
15725  *   5:   goto again                    ; another iteration
15726  *   6: done:
15727  *   7:   r1 = &it
15728  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15729  *   9:   exit
15730  *
15731  * This is a typical loop. Let's assume that we have a prune point at 1:,
15732  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15733  * again`, assuming other heuristics don't get in a way).
15734  *
15735  * When we first time come to 1:, let's say we have some state X. We proceed
15736  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15737  * Now we come back to validate that forked ACTIVE state. We proceed through
15738  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15739  * are converging. But the problem is that we don't know that yet, as this
15740  * convergence has to happen at iter_next() call site only. So if nothing is
15741  * done, at 1: verifier will use bounded loop logic and declare infinite
15742  * looping (and would be *technically* correct, if not for iterator's
15743  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15744  * don't want that. So what we do in process_iter_next_call() when we go on
15745  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15746  * a different iteration. So when we suspect an infinite loop, we additionally
15747  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15748  * pretend we are not looping and wait for next iter_next() call.
15749  *
15750  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15751  * loop, because that would actually mean infinite loop, as DRAINED state is
15752  * "sticky", and so we'll keep returning into the same instruction with the
15753  * same state (at least in one of possible code paths).
15754  *
15755  * This approach allows to keep infinite loop heuristic even in the face of
15756  * active iterator. E.g., C snippet below is and will be detected as
15757  * inifintely looping:
15758  *
15759  *   struct bpf_iter_num it;
15760  *   int *p, x;
15761  *
15762  *   bpf_iter_num_new(&it, 0, 10);
15763  *   while ((p = bpf_iter_num_next(&t))) {
15764  *       x = p;
15765  *       while (x--) {} // <<-- infinite loop here
15766  *   }
15767  *
15768  */
15769 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15770 {
15771 	struct bpf_reg_state *slot, *cur_slot;
15772 	struct bpf_func_state *state;
15773 	int i, fr;
15774 
15775 	for (fr = old->curframe; fr >= 0; fr--) {
15776 		state = old->frame[fr];
15777 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15778 			if (state->stack[i].slot_type[0] != STACK_ITER)
15779 				continue;
15780 
15781 			slot = &state->stack[i].spilled_ptr;
15782 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15783 				continue;
15784 
15785 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15786 			if (cur_slot->iter.depth != slot->iter.depth)
15787 				return true;
15788 		}
15789 	}
15790 	return false;
15791 }
15792 
15793 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15794 {
15795 	struct bpf_verifier_state_list *new_sl;
15796 	struct bpf_verifier_state_list *sl, **pprev;
15797 	struct bpf_verifier_state *cur = env->cur_state, *new;
15798 	int i, j, err, states_cnt = 0;
15799 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15800 	bool add_new_state = force_new_state;
15801 
15802 	/* bpf progs typically have pruning point every 4 instructions
15803 	 * http://vger.kernel.org/bpfconf2019.html#session-1
15804 	 * Do not add new state for future pruning if the verifier hasn't seen
15805 	 * at least 2 jumps and at least 8 instructions.
15806 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15807 	 * In tests that amounts to up to 50% reduction into total verifier
15808 	 * memory consumption and 20% verifier time speedup.
15809 	 */
15810 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15811 	    env->insn_processed - env->prev_insn_processed >= 8)
15812 		add_new_state = true;
15813 
15814 	pprev = explored_state(env, insn_idx);
15815 	sl = *pprev;
15816 
15817 	clean_live_states(env, insn_idx, cur);
15818 
15819 	while (sl) {
15820 		states_cnt++;
15821 		if (sl->state.insn_idx != insn_idx)
15822 			goto next;
15823 
15824 		if (sl->state.branches) {
15825 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15826 
15827 			if (frame->in_async_callback_fn &&
15828 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15829 				/* Different async_entry_cnt means that the verifier is
15830 				 * processing another entry into async callback.
15831 				 * Seeing the same state is not an indication of infinite
15832 				 * loop or infinite recursion.
15833 				 * But finding the same state doesn't mean that it's safe
15834 				 * to stop processing the current state. The previous state
15835 				 * hasn't yet reached bpf_exit, since state.branches > 0.
15836 				 * Checking in_async_callback_fn alone is not enough either.
15837 				 * Since the verifier still needs to catch infinite loops
15838 				 * inside async callbacks.
15839 				 */
15840 				goto skip_inf_loop_check;
15841 			}
15842 			/* BPF open-coded iterators loop detection is special.
15843 			 * states_maybe_looping() logic is too simplistic in detecting
15844 			 * states that *might* be equivalent, because it doesn't know
15845 			 * about ID remapping, so don't even perform it.
15846 			 * See process_iter_next_call() and iter_active_depths_differ()
15847 			 * for overview of the logic. When current and one of parent
15848 			 * states are detected as equivalent, it's a good thing: we prove
15849 			 * convergence and can stop simulating further iterations.
15850 			 * It's safe to assume that iterator loop will finish, taking into
15851 			 * account iter_next() contract of eventually returning
15852 			 * sticky NULL result.
15853 			 */
15854 			if (is_iter_next_insn(env, insn_idx)) {
15855 				if (states_equal(env, &sl->state, cur)) {
15856 					struct bpf_func_state *cur_frame;
15857 					struct bpf_reg_state *iter_state, *iter_reg;
15858 					int spi;
15859 
15860 					cur_frame = cur->frame[cur->curframe];
15861 					/* btf_check_iter_kfuncs() enforces that
15862 					 * iter state pointer is always the first arg
15863 					 */
15864 					iter_reg = &cur_frame->regs[BPF_REG_1];
15865 					/* current state is valid due to states_equal(),
15866 					 * so we can assume valid iter and reg state,
15867 					 * no need for extra (re-)validations
15868 					 */
15869 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15870 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15871 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15872 						goto hit;
15873 				}
15874 				goto skip_inf_loop_check;
15875 			}
15876 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
15877 			if (states_maybe_looping(&sl->state, cur) &&
15878 			    states_equal(env, &sl->state, cur) &&
15879 			    !iter_active_depths_differ(&sl->state, cur)) {
15880 				verbose_linfo(env, insn_idx, "; ");
15881 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15882 				return -EINVAL;
15883 			}
15884 			/* if the verifier is processing a loop, avoid adding new state
15885 			 * too often, since different loop iterations have distinct
15886 			 * states and may not help future pruning.
15887 			 * This threshold shouldn't be too low to make sure that
15888 			 * a loop with large bound will be rejected quickly.
15889 			 * The most abusive loop will be:
15890 			 * r1 += 1
15891 			 * if r1 < 1000000 goto pc-2
15892 			 * 1M insn_procssed limit / 100 == 10k peak states.
15893 			 * This threshold shouldn't be too high either, since states
15894 			 * at the end of the loop are likely to be useful in pruning.
15895 			 */
15896 skip_inf_loop_check:
15897 			if (!force_new_state &&
15898 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
15899 			    env->insn_processed - env->prev_insn_processed < 100)
15900 				add_new_state = false;
15901 			goto miss;
15902 		}
15903 		if (states_equal(env, &sl->state, cur)) {
15904 hit:
15905 			sl->hit_cnt++;
15906 			/* reached equivalent register/stack state,
15907 			 * prune the search.
15908 			 * Registers read by the continuation are read by us.
15909 			 * If we have any write marks in env->cur_state, they
15910 			 * will prevent corresponding reads in the continuation
15911 			 * from reaching our parent (an explored_state).  Our
15912 			 * own state will get the read marks recorded, but
15913 			 * they'll be immediately forgotten as we're pruning
15914 			 * this state and will pop a new one.
15915 			 */
15916 			err = propagate_liveness(env, &sl->state, cur);
15917 
15918 			/* if previous state reached the exit with precision and
15919 			 * current state is equivalent to it (except precsion marks)
15920 			 * the precision needs to be propagated back in
15921 			 * the current state.
15922 			 */
15923 			err = err ? : push_jmp_history(env, cur);
15924 			err = err ? : propagate_precision(env, &sl->state);
15925 			if (err)
15926 				return err;
15927 			return 1;
15928 		}
15929 miss:
15930 		/* when new state is not going to be added do not increase miss count.
15931 		 * Otherwise several loop iterations will remove the state
15932 		 * recorded earlier. The goal of these heuristics is to have
15933 		 * states from some iterations of the loop (some in the beginning
15934 		 * and some at the end) to help pruning.
15935 		 */
15936 		if (add_new_state)
15937 			sl->miss_cnt++;
15938 		/* heuristic to determine whether this state is beneficial
15939 		 * to keep checking from state equivalence point of view.
15940 		 * Higher numbers increase max_states_per_insn and verification time,
15941 		 * but do not meaningfully decrease insn_processed.
15942 		 */
15943 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15944 			/* the state is unlikely to be useful. Remove it to
15945 			 * speed up verification
15946 			 */
15947 			*pprev = sl->next;
15948 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15949 				u32 br = sl->state.branches;
15950 
15951 				WARN_ONCE(br,
15952 					  "BUG live_done but branches_to_explore %d\n",
15953 					  br);
15954 				free_verifier_state(&sl->state, false);
15955 				kfree(sl);
15956 				env->peak_states--;
15957 			} else {
15958 				/* cannot free this state, since parentage chain may
15959 				 * walk it later. Add it for free_list instead to
15960 				 * be freed at the end of verification
15961 				 */
15962 				sl->next = env->free_list;
15963 				env->free_list = sl;
15964 			}
15965 			sl = *pprev;
15966 			continue;
15967 		}
15968 next:
15969 		pprev = &sl->next;
15970 		sl = *pprev;
15971 	}
15972 
15973 	if (env->max_states_per_insn < states_cnt)
15974 		env->max_states_per_insn = states_cnt;
15975 
15976 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15977 		return 0;
15978 
15979 	if (!add_new_state)
15980 		return 0;
15981 
15982 	/* There were no equivalent states, remember the current one.
15983 	 * Technically the current state is not proven to be safe yet,
15984 	 * but it will either reach outer most bpf_exit (which means it's safe)
15985 	 * or it will be rejected. When there are no loops the verifier won't be
15986 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15987 	 * again on the way to bpf_exit.
15988 	 * When looping the sl->state.branches will be > 0 and this state
15989 	 * will not be considered for equivalence until branches == 0.
15990 	 */
15991 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15992 	if (!new_sl)
15993 		return -ENOMEM;
15994 	env->total_states++;
15995 	env->peak_states++;
15996 	env->prev_jmps_processed = env->jmps_processed;
15997 	env->prev_insn_processed = env->insn_processed;
15998 
15999 	/* forget precise markings we inherited, see __mark_chain_precision */
16000 	if (env->bpf_capable)
16001 		mark_all_scalars_imprecise(env, cur);
16002 
16003 	/* add new state to the head of linked list */
16004 	new = &new_sl->state;
16005 	err = copy_verifier_state(new, cur);
16006 	if (err) {
16007 		free_verifier_state(new, false);
16008 		kfree(new_sl);
16009 		return err;
16010 	}
16011 	new->insn_idx = insn_idx;
16012 	WARN_ONCE(new->branches != 1,
16013 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16014 
16015 	cur->parent = new;
16016 	cur->first_insn_idx = insn_idx;
16017 	clear_jmp_history(cur);
16018 	new_sl->next = *explored_state(env, insn_idx);
16019 	*explored_state(env, insn_idx) = new_sl;
16020 	/* connect new state to parentage chain. Current frame needs all
16021 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16022 	 * to the stack implicitly by JITs) so in callers' frames connect just
16023 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16024 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16025 	 * from callee with its full parentage chain, anyway.
16026 	 */
16027 	/* clear write marks in current state: the writes we did are not writes
16028 	 * our child did, so they don't screen off its reads from us.
16029 	 * (There are no read marks in current state, because reads always mark
16030 	 * their parent and current state never has children yet.  Only
16031 	 * explored_states can get read marks.)
16032 	 */
16033 	for (j = 0; j <= cur->curframe; j++) {
16034 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16035 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16036 		for (i = 0; i < BPF_REG_FP; i++)
16037 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16038 	}
16039 
16040 	/* all stack frames are accessible from callee, clear them all */
16041 	for (j = 0; j <= cur->curframe; j++) {
16042 		struct bpf_func_state *frame = cur->frame[j];
16043 		struct bpf_func_state *newframe = new->frame[j];
16044 
16045 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16046 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16047 			frame->stack[i].spilled_ptr.parent =
16048 						&newframe->stack[i].spilled_ptr;
16049 		}
16050 	}
16051 	return 0;
16052 }
16053 
16054 /* Return true if it's OK to have the same insn return a different type. */
16055 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16056 {
16057 	switch (base_type(type)) {
16058 	case PTR_TO_CTX:
16059 	case PTR_TO_SOCKET:
16060 	case PTR_TO_SOCK_COMMON:
16061 	case PTR_TO_TCP_SOCK:
16062 	case PTR_TO_XDP_SOCK:
16063 	case PTR_TO_BTF_ID:
16064 		return false;
16065 	default:
16066 		return true;
16067 	}
16068 }
16069 
16070 /* If an instruction was previously used with particular pointer types, then we
16071  * need to be careful to avoid cases such as the below, where it may be ok
16072  * for one branch accessing the pointer, but not ok for the other branch:
16073  *
16074  * R1 = sock_ptr
16075  * goto X;
16076  * ...
16077  * R1 = some_other_valid_ptr;
16078  * goto X;
16079  * ...
16080  * R2 = *(u32 *)(R1 + 0);
16081  */
16082 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16083 {
16084 	return src != prev && (!reg_type_mismatch_ok(src) ||
16085 			       !reg_type_mismatch_ok(prev));
16086 }
16087 
16088 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16089 			     bool allow_trust_missmatch)
16090 {
16091 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16092 
16093 	if (*prev_type == NOT_INIT) {
16094 		/* Saw a valid insn
16095 		 * dst_reg = *(u32 *)(src_reg + off)
16096 		 * save type to validate intersecting paths
16097 		 */
16098 		*prev_type = type;
16099 	} else if (reg_type_mismatch(type, *prev_type)) {
16100 		/* Abuser program is trying to use the same insn
16101 		 * dst_reg = *(u32*) (src_reg + off)
16102 		 * with different pointer types:
16103 		 * src_reg == ctx in one branch and
16104 		 * src_reg == stack|map in some other branch.
16105 		 * Reject it.
16106 		 */
16107 		if (allow_trust_missmatch &&
16108 		    base_type(type) == PTR_TO_BTF_ID &&
16109 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16110 			/*
16111 			 * Have to support a use case when one path through
16112 			 * the program yields TRUSTED pointer while another
16113 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16114 			 * BPF_PROBE_MEM.
16115 			 */
16116 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16117 		} else {
16118 			verbose(env, "same insn cannot be used with different pointers\n");
16119 			return -EINVAL;
16120 		}
16121 	}
16122 
16123 	return 0;
16124 }
16125 
16126 static int do_check(struct bpf_verifier_env *env)
16127 {
16128 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16129 	struct bpf_verifier_state *state = env->cur_state;
16130 	struct bpf_insn *insns = env->prog->insnsi;
16131 	struct bpf_reg_state *regs;
16132 	int insn_cnt = env->prog->len;
16133 	bool do_print_state = false;
16134 	int prev_insn_idx = -1;
16135 
16136 	for (;;) {
16137 		struct bpf_insn *insn;
16138 		u8 class;
16139 		int err;
16140 
16141 		env->prev_insn_idx = prev_insn_idx;
16142 		if (env->insn_idx >= insn_cnt) {
16143 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16144 				env->insn_idx, insn_cnt);
16145 			return -EFAULT;
16146 		}
16147 
16148 		insn = &insns[env->insn_idx];
16149 		class = BPF_CLASS(insn->code);
16150 
16151 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16152 			verbose(env,
16153 				"BPF program is too large. Processed %d insn\n",
16154 				env->insn_processed);
16155 			return -E2BIG;
16156 		}
16157 
16158 		state->last_insn_idx = env->prev_insn_idx;
16159 
16160 		if (is_prune_point(env, env->insn_idx)) {
16161 			err = is_state_visited(env, env->insn_idx);
16162 			if (err < 0)
16163 				return err;
16164 			if (err == 1) {
16165 				/* found equivalent state, can prune the search */
16166 				if (env->log.level & BPF_LOG_LEVEL) {
16167 					if (do_print_state)
16168 						verbose(env, "\nfrom %d to %d%s: safe\n",
16169 							env->prev_insn_idx, env->insn_idx,
16170 							env->cur_state->speculative ?
16171 							" (speculative execution)" : "");
16172 					else
16173 						verbose(env, "%d: safe\n", env->insn_idx);
16174 				}
16175 				goto process_bpf_exit;
16176 			}
16177 		}
16178 
16179 		if (is_jmp_point(env, env->insn_idx)) {
16180 			err = push_jmp_history(env, state);
16181 			if (err)
16182 				return err;
16183 		}
16184 
16185 		if (signal_pending(current))
16186 			return -EAGAIN;
16187 
16188 		if (need_resched())
16189 			cond_resched();
16190 
16191 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16192 			verbose(env, "\nfrom %d to %d%s:",
16193 				env->prev_insn_idx, env->insn_idx,
16194 				env->cur_state->speculative ?
16195 				" (speculative execution)" : "");
16196 			print_verifier_state(env, state->frame[state->curframe], true);
16197 			do_print_state = false;
16198 		}
16199 
16200 		if (env->log.level & BPF_LOG_LEVEL) {
16201 			const struct bpf_insn_cbs cbs = {
16202 				.cb_call	= disasm_kfunc_name,
16203 				.cb_print	= verbose,
16204 				.private_data	= env,
16205 			};
16206 
16207 			if (verifier_state_scratched(env))
16208 				print_insn_state(env, state->frame[state->curframe]);
16209 
16210 			verbose_linfo(env, env->insn_idx, "; ");
16211 			env->prev_log_pos = env->log.end_pos;
16212 			verbose(env, "%d: ", env->insn_idx);
16213 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16214 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16215 			env->prev_log_pos = env->log.end_pos;
16216 		}
16217 
16218 		if (bpf_prog_is_offloaded(env->prog->aux)) {
16219 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16220 							   env->prev_insn_idx);
16221 			if (err)
16222 				return err;
16223 		}
16224 
16225 		regs = cur_regs(env);
16226 		sanitize_mark_insn_seen(env);
16227 		prev_insn_idx = env->insn_idx;
16228 
16229 		if (class == BPF_ALU || class == BPF_ALU64) {
16230 			err = check_alu_op(env, insn);
16231 			if (err)
16232 				return err;
16233 
16234 		} else if (class == BPF_LDX) {
16235 			enum bpf_reg_type src_reg_type;
16236 
16237 			/* check for reserved fields is already done */
16238 
16239 			/* check src operand */
16240 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16241 			if (err)
16242 				return err;
16243 
16244 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16245 			if (err)
16246 				return err;
16247 
16248 			src_reg_type = regs[insn->src_reg].type;
16249 
16250 			/* check that memory (src_reg + off) is readable,
16251 			 * the state of dst_reg will be updated by this func
16252 			 */
16253 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
16254 					       insn->off, BPF_SIZE(insn->code),
16255 					       BPF_READ, insn->dst_reg, false);
16256 			if (err)
16257 				return err;
16258 
16259 			err = save_aux_ptr_type(env, src_reg_type, true);
16260 			if (err)
16261 				return err;
16262 		} else if (class == BPF_STX) {
16263 			enum bpf_reg_type dst_reg_type;
16264 
16265 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16266 				err = check_atomic(env, env->insn_idx, insn);
16267 				if (err)
16268 					return err;
16269 				env->insn_idx++;
16270 				continue;
16271 			}
16272 
16273 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16274 				verbose(env, "BPF_STX uses reserved fields\n");
16275 				return -EINVAL;
16276 			}
16277 
16278 			/* check src1 operand */
16279 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16280 			if (err)
16281 				return err;
16282 			/* check src2 operand */
16283 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16284 			if (err)
16285 				return err;
16286 
16287 			dst_reg_type = regs[insn->dst_reg].type;
16288 
16289 			/* check that memory (dst_reg + off) is writeable */
16290 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16291 					       insn->off, BPF_SIZE(insn->code),
16292 					       BPF_WRITE, insn->src_reg, false);
16293 			if (err)
16294 				return err;
16295 
16296 			err = save_aux_ptr_type(env, dst_reg_type, false);
16297 			if (err)
16298 				return err;
16299 		} else if (class == BPF_ST) {
16300 			enum bpf_reg_type dst_reg_type;
16301 
16302 			if (BPF_MODE(insn->code) != BPF_MEM ||
16303 			    insn->src_reg != BPF_REG_0) {
16304 				verbose(env, "BPF_ST uses reserved fields\n");
16305 				return -EINVAL;
16306 			}
16307 			/* check src operand */
16308 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16309 			if (err)
16310 				return err;
16311 
16312 			dst_reg_type = regs[insn->dst_reg].type;
16313 
16314 			/* check that memory (dst_reg + off) is writeable */
16315 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16316 					       insn->off, BPF_SIZE(insn->code),
16317 					       BPF_WRITE, -1, false);
16318 			if (err)
16319 				return err;
16320 
16321 			err = save_aux_ptr_type(env, dst_reg_type, false);
16322 			if (err)
16323 				return err;
16324 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16325 			u8 opcode = BPF_OP(insn->code);
16326 
16327 			env->jmps_processed++;
16328 			if (opcode == BPF_CALL) {
16329 				if (BPF_SRC(insn->code) != BPF_K ||
16330 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16331 				     && insn->off != 0) ||
16332 				    (insn->src_reg != BPF_REG_0 &&
16333 				     insn->src_reg != BPF_PSEUDO_CALL &&
16334 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16335 				    insn->dst_reg != BPF_REG_0 ||
16336 				    class == BPF_JMP32) {
16337 					verbose(env, "BPF_CALL uses reserved fields\n");
16338 					return -EINVAL;
16339 				}
16340 
16341 				if (env->cur_state->active_lock.ptr) {
16342 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16343 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16344 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16345 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16346 						verbose(env, "function calls are not allowed while holding a lock\n");
16347 						return -EINVAL;
16348 					}
16349 				}
16350 				if (insn->src_reg == BPF_PSEUDO_CALL)
16351 					err = check_func_call(env, insn, &env->insn_idx);
16352 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16353 					err = check_kfunc_call(env, insn, &env->insn_idx);
16354 				else
16355 					err = check_helper_call(env, insn, &env->insn_idx);
16356 				if (err)
16357 					return err;
16358 
16359 				mark_reg_scratched(env, BPF_REG_0);
16360 			} else if (opcode == BPF_JA) {
16361 				if (BPF_SRC(insn->code) != BPF_K ||
16362 				    insn->imm != 0 ||
16363 				    insn->src_reg != BPF_REG_0 ||
16364 				    insn->dst_reg != BPF_REG_0 ||
16365 				    class == BPF_JMP32) {
16366 					verbose(env, "BPF_JA uses reserved fields\n");
16367 					return -EINVAL;
16368 				}
16369 
16370 				env->insn_idx += insn->off + 1;
16371 				continue;
16372 
16373 			} else if (opcode == BPF_EXIT) {
16374 				if (BPF_SRC(insn->code) != BPF_K ||
16375 				    insn->imm != 0 ||
16376 				    insn->src_reg != BPF_REG_0 ||
16377 				    insn->dst_reg != BPF_REG_0 ||
16378 				    class == BPF_JMP32) {
16379 					verbose(env, "BPF_EXIT uses reserved fields\n");
16380 					return -EINVAL;
16381 				}
16382 
16383 				if (env->cur_state->active_lock.ptr &&
16384 				    !in_rbtree_lock_required_cb(env)) {
16385 					verbose(env, "bpf_spin_unlock is missing\n");
16386 					return -EINVAL;
16387 				}
16388 
16389 				if (env->cur_state->active_rcu_lock) {
16390 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16391 					return -EINVAL;
16392 				}
16393 
16394 				/* We must do check_reference_leak here before
16395 				 * prepare_func_exit to handle the case when
16396 				 * state->curframe > 0, it may be a callback
16397 				 * function, for which reference_state must
16398 				 * match caller reference state when it exits.
16399 				 */
16400 				err = check_reference_leak(env);
16401 				if (err)
16402 					return err;
16403 
16404 				if (state->curframe) {
16405 					/* exit from nested function */
16406 					err = prepare_func_exit(env, &env->insn_idx);
16407 					if (err)
16408 						return err;
16409 					do_print_state = true;
16410 					continue;
16411 				}
16412 
16413 				err = check_return_code(env);
16414 				if (err)
16415 					return err;
16416 process_bpf_exit:
16417 				mark_verifier_state_scratched(env);
16418 				update_branch_counts(env, env->cur_state);
16419 				err = pop_stack(env, &prev_insn_idx,
16420 						&env->insn_idx, pop_log);
16421 				if (err < 0) {
16422 					if (err != -ENOENT)
16423 						return err;
16424 					break;
16425 				} else {
16426 					do_print_state = true;
16427 					continue;
16428 				}
16429 			} else {
16430 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16431 				if (err)
16432 					return err;
16433 			}
16434 		} else if (class == BPF_LD) {
16435 			u8 mode = BPF_MODE(insn->code);
16436 
16437 			if (mode == BPF_ABS || mode == BPF_IND) {
16438 				err = check_ld_abs(env, insn);
16439 				if (err)
16440 					return err;
16441 
16442 			} else if (mode == BPF_IMM) {
16443 				err = check_ld_imm(env, insn);
16444 				if (err)
16445 					return err;
16446 
16447 				env->insn_idx++;
16448 				sanitize_mark_insn_seen(env);
16449 			} else {
16450 				verbose(env, "invalid BPF_LD mode\n");
16451 				return -EINVAL;
16452 			}
16453 		} else {
16454 			verbose(env, "unknown insn class %d\n", class);
16455 			return -EINVAL;
16456 		}
16457 
16458 		env->insn_idx++;
16459 	}
16460 
16461 	return 0;
16462 }
16463 
16464 static int find_btf_percpu_datasec(struct btf *btf)
16465 {
16466 	const struct btf_type *t;
16467 	const char *tname;
16468 	int i, n;
16469 
16470 	/*
16471 	 * Both vmlinux and module each have their own ".data..percpu"
16472 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16473 	 * types to look at only module's own BTF types.
16474 	 */
16475 	n = btf_nr_types(btf);
16476 	if (btf_is_module(btf))
16477 		i = btf_nr_types(btf_vmlinux);
16478 	else
16479 		i = 1;
16480 
16481 	for(; i < n; i++) {
16482 		t = btf_type_by_id(btf, i);
16483 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16484 			continue;
16485 
16486 		tname = btf_name_by_offset(btf, t->name_off);
16487 		if (!strcmp(tname, ".data..percpu"))
16488 			return i;
16489 	}
16490 
16491 	return -ENOENT;
16492 }
16493 
16494 /* replace pseudo btf_id with kernel symbol address */
16495 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16496 			       struct bpf_insn *insn,
16497 			       struct bpf_insn_aux_data *aux)
16498 {
16499 	const struct btf_var_secinfo *vsi;
16500 	const struct btf_type *datasec;
16501 	struct btf_mod_pair *btf_mod;
16502 	const struct btf_type *t;
16503 	const char *sym_name;
16504 	bool percpu = false;
16505 	u32 type, id = insn->imm;
16506 	struct btf *btf;
16507 	s32 datasec_id;
16508 	u64 addr;
16509 	int i, btf_fd, err;
16510 
16511 	btf_fd = insn[1].imm;
16512 	if (btf_fd) {
16513 		btf = btf_get_by_fd(btf_fd);
16514 		if (IS_ERR(btf)) {
16515 			verbose(env, "invalid module BTF object FD specified.\n");
16516 			return -EINVAL;
16517 		}
16518 	} else {
16519 		if (!btf_vmlinux) {
16520 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16521 			return -EINVAL;
16522 		}
16523 		btf = btf_vmlinux;
16524 		btf_get(btf);
16525 	}
16526 
16527 	t = btf_type_by_id(btf, id);
16528 	if (!t) {
16529 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16530 		err = -ENOENT;
16531 		goto err_put;
16532 	}
16533 
16534 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16535 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16536 		err = -EINVAL;
16537 		goto err_put;
16538 	}
16539 
16540 	sym_name = btf_name_by_offset(btf, t->name_off);
16541 	addr = kallsyms_lookup_name(sym_name);
16542 	if (!addr) {
16543 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16544 			sym_name);
16545 		err = -ENOENT;
16546 		goto err_put;
16547 	}
16548 	insn[0].imm = (u32)addr;
16549 	insn[1].imm = addr >> 32;
16550 
16551 	if (btf_type_is_func(t)) {
16552 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16553 		aux->btf_var.mem_size = 0;
16554 		goto check_btf;
16555 	}
16556 
16557 	datasec_id = find_btf_percpu_datasec(btf);
16558 	if (datasec_id > 0) {
16559 		datasec = btf_type_by_id(btf, datasec_id);
16560 		for_each_vsi(i, datasec, vsi) {
16561 			if (vsi->type == id) {
16562 				percpu = true;
16563 				break;
16564 			}
16565 		}
16566 	}
16567 
16568 	type = t->type;
16569 	t = btf_type_skip_modifiers(btf, type, NULL);
16570 	if (percpu) {
16571 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16572 		aux->btf_var.btf = btf;
16573 		aux->btf_var.btf_id = type;
16574 	} else if (!btf_type_is_struct(t)) {
16575 		const struct btf_type *ret;
16576 		const char *tname;
16577 		u32 tsize;
16578 
16579 		/* resolve the type size of ksym. */
16580 		ret = btf_resolve_size(btf, t, &tsize);
16581 		if (IS_ERR(ret)) {
16582 			tname = btf_name_by_offset(btf, t->name_off);
16583 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16584 				tname, PTR_ERR(ret));
16585 			err = -EINVAL;
16586 			goto err_put;
16587 		}
16588 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16589 		aux->btf_var.mem_size = tsize;
16590 	} else {
16591 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16592 		aux->btf_var.btf = btf;
16593 		aux->btf_var.btf_id = type;
16594 	}
16595 check_btf:
16596 	/* check whether we recorded this BTF (and maybe module) already */
16597 	for (i = 0; i < env->used_btf_cnt; i++) {
16598 		if (env->used_btfs[i].btf == btf) {
16599 			btf_put(btf);
16600 			return 0;
16601 		}
16602 	}
16603 
16604 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16605 		err = -E2BIG;
16606 		goto err_put;
16607 	}
16608 
16609 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16610 	btf_mod->btf = btf;
16611 	btf_mod->module = NULL;
16612 
16613 	/* if we reference variables from kernel module, bump its refcount */
16614 	if (btf_is_module(btf)) {
16615 		btf_mod->module = btf_try_get_module(btf);
16616 		if (!btf_mod->module) {
16617 			err = -ENXIO;
16618 			goto err_put;
16619 		}
16620 	}
16621 
16622 	env->used_btf_cnt++;
16623 
16624 	return 0;
16625 err_put:
16626 	btf_put(btf);
16627 	return err;
16628 }
16629 
16630 static bool is_tracing_prog_type(enum bpf_prog_type type)
16631 {
16632 	switch (type) {
16633 	case BPF_PROG_TYPE_KPROBE:
16634 	case BPF_PROG_TYPE_TRACEPOINT:
16635 	case BPF_PROG_TYPE_PERF_EVENT:
16636 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16637 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16638 		return true;
16639 	default:
16640 		return false;
16641 	}
16642 }
16643 
16644 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16645 					struct bpf_map *map,
16646 					struct bpf_prog *prog)
16647 
16648 {
16649 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16650 
16651 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16652 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16653 		if (is_tracing_prog_type(prog_type)) {
16654 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16655 			return -EINVAL;
16656 		}
16657 	}
16658 
16659 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16660 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16661 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16662 			return -EINVAL;
16663 		}
16664 
16665 		if (is_tracing_prog_type(prog_type)) {
16666 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16667 			return -EINVAL;
16668 		}
16669 
16670 		if (prog->aux->sleepable) {
16671 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16672 			return -EINVAL;
16673 		}
16674 	}
16675 
16676 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16677 		if (is_tracing_prog_type(prog_type)) {
16678 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16679 			return -EINVAL;
16680 		}
16681 	}
16682 
16683 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16684 	    !bpf_offload_prog_map_match(prog, map)) {
16685 		verbose(env, "offload device mismatch between prog and map\n");
16686 		return -EINVAL;
16687 	}
16688 
16689 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16690 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16691 		return -EINVAL;
16692 	}
16693 
16694 	if (prog->aux->sleepable)
16695 		switch (map->map_type) {
16696 		case BPF_MAP_TYPE_HASH:
16697 		case BPF_MAP_TYPE_LRU_HASH:
16698 		case BPF_MAP_TYPE_ARRAY:
16699 		case BPF_MAP_TYPE_PERCPU_HASH:
16700 		case BPF_MAP_TYPE_PERCPU_ARRAY:
16701 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16702 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16703 		case BPF_MAP_TYPE_HASH_OF_MAPS:
16704 		case BPF_MAP_TYPE_RINGBUF:
16705 		case BPF_MAP_TYPE_USER_RINGBUF:
16706 		case BPF_MAP_TYPE_INODE_STORAGE:
16707 		case BPF_MAP_TYPE_SK_STORAGE:
16708 		case BPF_MAP_TYPE_TASK_STORAGE:
16709 		case BPF_MAP_TYPE_CGRP_STORAGE:
16710 			break;
16711 		default:
16712 			verbose(env,
16713 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16714 			return -EINVAL;
16715 		}
16716 
16717 	return 0;
16718 }
16719 
16720 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16721 {
16722 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16723 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16724 }
16725 
16726 /* find and rewrite pseudo imm in ld_imm64 instructions:
16727  *
16728  * 1. if it accesses map FD, replace it with actual map pointer.
16729  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16730  *
16731  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16732  */
16733 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16734 {
16735 	struct bpf_insn *insn = env->prog->insnsi;
16736 	int insn_cnt = env->prog->len;
16737 	int i, j, err;
16738 
16739 	err = bpf_prog_calc_tag(env->prog);
16740 	if (err)
16741 		return err;
16742 
16743 	for (i = 0; i < insn_cnt; i++, insn++) {
16744 		if (BPF_CLASS(insn->code) == BPF_LDX &&
16745 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16746 			verbose(env, "BPF_LDX uses reserved fields\n");
16747 			return -EINVAL;
16748 		}
16749 
16750 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16751 			struct bpf_insn_aux_data *aux;
16752 			struct bpf_map *map;
16753 			struct fd f;
16754 			u64 addr;
16755 			u32 fd;
16756 
16757 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
16758 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16759 			    insn[1].off != 0) {
16760 				verbose(env, "invalid bpf_ld_imm64 insn\n");
16761 				return -EINVAL;
16762 			}
16763 
16764 			if (insn[0].src_reg == 0)
16765 				/* valid generic load 64-bit imm */
16766 				goto next_insn;
16767 
16768 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16769 				aux = &env->insn_aux_data[i];
16770 				err = check_pseudo_btf_id(env, insn, aux);
16771 				if (err)
16772 					return err;
16773 				goto next_insn;
16774 			}
16775 
16776 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16777 				aux = &env->insn_aux_data[i];
16778 				aux->ptr_type = PTR_TO_FUNC;
16779 				goto next_insn;
16780 			}
16781 
16782 			/* In final convert_pseudo_ld_imm64() step, this is
16783 			 * converted into regular 64-bit imm load insn.
16784 			 */
16785 			switch (insn[0].src_reg) {
16786 			case BPF_PSEUDO_MAP_VALUE:
16787 			case BPF_PSEUDO_MAP_IDX_VALUE:
16788 				break;
16789 			case BPF_PSEUDO_MAP_FD:
16790 			case BPF_PSEUDO_MAP_IDX:
16791 				if (insn[1].imm == 0)
16792 					break;
16793 				fallthrough;
16794 			default:
16795 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16796 				return -EINVAL;
16797 			}
16798 
16799 			switch (insn[0].src_reg) {
16800 			case BPF_PSEUDO_MAP_IDX_VALUE:
16801 			case BPF_PSEUDO_MAP_IDX:
16802 				if (bpfptr_is_null(env->fd_array)) {
16803 					verbose(env, "fd_idx without fd_array is invalid\n");
16804 					return -EPROTO;
16805 				}
16806 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
16807 							    insn[0].imm * sizeof(fd),
16808 							    sizeof(fd)))
16809 					return -EFAULT;
16810 				break;
16811 			default:
16812 				fd = insn[0].imm;
16813 				break;
16814 			}
16815 
16816 			f = fdget(fd);
16817 			map = __bpf_map_get(f);
16818 			if (IS_ERR(map)) {
16819 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
16820 					insn[0].imm);
16821 				return PTR_ERR(map);
16822 			}
16823 
16824 			err = check_map_prog_compatibility(env, map, env->prog);
16825 			if (err) {
16826 				fdput(f);
16827 				return err;
16828 			}
16829 
16830 			aux = &env->insn_aux_data[i];
16831 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16832 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16833 				addr = (unsigned long)map;
16834 			} else {
16835 				u32 off = insn[1].imm;
16836 
16837 				if (off >= BPF_MAX_VAR_OFF) {
16838 					verbose(env, "direct value offset of %u is not allowed\n", off);
16839 					fdput(f);
16840 					return -EINVAL;
16841 				}
16842 
16843 				if (!map->ops->map_direct_value_addr) {
16844 					verbose(env, "no direct value access support for this map type\n");
16845 					fdput(f);
16846 					return -EINVAL;
16847 				}
16848 
16849 				err = map->ops->map_direct_value_addr(map, &addr, off);
16850 				if (err) {
16851 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16852 						map->value_size, off);
16853 					fdput(f);
16854 					return err;
16855 				}
16856 
16857 				aux->map_off = off;
16858 				addr += off;
16859 			}
16860 
16861 			insn[0].imm = (u32)addr;
16862 			insn[1].imm = addr >> 32;
16863 
16864 			/* check whether we recorded this map already */
16865 			for (j = 0; j < env->used_map_cnt; j++) {
16866 				if (env->used_maps[j] == map) {
16867 					aux->map_index = j;
16868 					fdput(f);
16869 					goto next_insn;
16870 				}
16871 			}
16872 
16873 			if (env->used_map_cnt >= MAX_USED_MAPS) {
16874 				fdput(f);
16875 				return -E2BIG;
16876 			}
16877 
16878 			/* hold the map. If the program is rejected by verifier,
16879 			 * the map will be released by release_maps() or it
16880 			 * will be used by the valid program until it's unloaded
16881 			 * and all maps are released in free_used_maps()
16882 			 */
16883 			bpf_map_inc(map);
16884 
16885 			aux->map_index = env->used_map_cnt;
16886 			env->used_maps[env->used_map_cnt++] = map;
16887 
16888 			if (bpf_map_is_cgroup_storage(map) &&
16889 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
16890 				verbose(env, "only one cgroup storage of each type is allowed\n");
16891 				fdput(f);
16892 				return -EBUSY;
16893 			}
16894 
16895 			fdput(f);
16896 next_insn:
16897 			insn++;
16898 			i++;
16899 			continue;
16900 		}
16901 
16902 		/* Basic sanity check before we invest more work here. */
16903 		if (!bpf_opcode_in_insntable(insn->code)) {
16904 			verbose(env, "unknown opcode %02x\n", insn->code);
16905 			return -EINVAL;
16906 		}
16907 	}
16908 
16909 	/* now all pseudo BPF_LD_IMM64 instructions load valid
16910 	 * 'struct bpf_map *' into a register instead of user map_fd.
16911 	 * These pointers will be used later by verifier to validate map access.
16912 	 */
16913 	return 0;
16914 }
16915 
16916 /* drop refcnt of maps used by the rejected program */
16917 static void release_maps(struct bpf_verifier_env *env)
16918 {
16919 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
16920 			     env->used_map_cnt);
16921 }
16922 
16923 /* drop refcnt of maps used by the rejected program */
16924 static void release_btfs(struct bpf_verifier_env *env)
16925 {
16926 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16927 			     env->used_btf_cnt);
16928 }
16929 
16930 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16931 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16932 {
16933 	struct bpf_insn *insn = env->prog->insnsi;
16934 	int insn_cnt = env->prog->len;
16935 	int i;
16936 
16937 	for (i = 0; i < insn_cnt; i++, insn++) {
16938 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16939 			continue;
16940 		if (insn->src_reg == BPF_PSEUDO_FUNC)
16941 			continue;
16942 		insn->src_reg = 0;
16943 	}
16944 }
16945 
16946 /* single env->prog->insni[off] instruction was replaced with the range
16947  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
16948  * [0, off) and [off, end) to new locations, so the patched range stays zero
16949  */
16950 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16951 				 struct bpf_insn_aux_data *new_data,
16952 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
16953 {
16954 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16955 	struct bpf_insn *insn = new_prog->insnsi;
16956 	u32 old_seen = old_data[off].seen;
16957 	u32 prog_len;
16958 	int i;
16959 
16960 	/* aux info at OFF always needs adjustment, no matter fast path
16961 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16962 	 * original insn at old prog.
16963 	 */
16964 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16965 
16966 	if (cnt == 1)
16967 		return;
16968 	prog_len = new_prog->len;
16969 
16970 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16971 	memcpy(new_data + off + cnt - 1, old_data + off,
16972 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16973 	for (i = off; i < off + cnt - 1; i++) {
16974 		/* Expand insni[off]'s seen count to the patched range. */
16975 		new_data[i].seen = old_seen;
16976 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
16977 	}
16978 	env->insn_aux_data = new_data;
16979 	vfree(old_data);
16980 }
16981 
16982 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16983 {
16984 	int i;
16985 
16986 	if (len == 1)
16987 		return;
16988 	/* NOTE: fake 'exit' subprog should be updated as well. */
16989 	for (i = 0; i <= env->subprog_cnt; i++) {
16990 		if (env->subprog_info[i].start <= off)
16991 			continue;
16992 		env->subprog_info[i].start += len - 1;
16993 	}
16994 }
16995 
16996 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16997 {
16998 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16999 	int i, sz = prog->aux->size_poke_tab;
17000 	struct bpf_jit_poke_descriptor *desc;
17001 
17002 	for (i = 0; i < sz; i++) {
17003 		desc = &tab[i];
17004 		if (desc->insn_idx <= off)
17005 			continue;
17006 		desc->insn_idx += len - 1;
17007 	}
17008 }
17009 
17010 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17011 					    const struct bpf_insn *patch, u32 len)
17012 {
17013 	struct bpf_prog *new_prog;
17014 	struct bpf_insn_aux_data *new_data = NULL;
17015 
17016 	if (len > 1) {
17017 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17018 					      sizeof(struct bpf_insn_aux_data)));
17019 		if (!new_data)
17020 			return NULL;
17021 	}
17022 
17023 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17024 	if (IS_ERR(new_prog)) {
17025 		if (PTR_ERR(new_prog) == -ERANGE)
17026 			verbose(env,
17027 				"insn %d cannot be patched due to 16-bit range\n",
17028 				env->insn_aux_data[off].orig_idx);
17029 		vfree(new_data);
17030 		return NULL;
17031 	}
17032 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17033 	adjust_subprog_starts(env, off, len);
17034 	adjust_poke_descs(new_prog, off, len);
17035 	return new_prog;
17036 }
17037 
17038 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17039 					      u32 off, u32 cnt)
17040 {
17041 	int i, j;
17042 
17043 	/* find first prog starting at or after off (first to remove) */
17044 	for (i = 0; i < env->subprog_cnt; i++)
17045 		if (env->subprog_info[i].start >= off)
17046 			break;
17047 	/* find first prog starting at or after off + cnt (first to stay) */
17048 	for (j = i; j < env->subprog_cnt; j++)
17049 		if (env->subprog_info[j].start >= off + cnt)
17050 			break;
17051 	/* if j doesn't start exactly at off + cnt, we are just removing
17052 	 * the front of previous prog
17053 	 */
17054 	if (env->subprog_info[j].start != off + cnt)
17055 		j--;
17056 
17057 	if (j > i) {
17058 		struct bpf_prog_aux *aux = env->prog->aux;
17059 		int move;
17060 
17061 		/* move fake 'exit' subprog as well */
17062 		move = env->subprog_cnt + 1 - j;
17063 
17064 		memmove(env->subprog_info + i,
17065 			env->subprog_info + j,
17066 			sizeof(*env->subprog_info) * move);
17067 		env->subprog_cnt -= j - i;
17068 
17069 		/* remove func_info */
17070 		if (aux->func_info) {
17071 			move = aux->func_info_cnt - j;
17072 
17073 			memmove(aux->func_info + i,
17074 				aux->func_info + j,
17075 				sizeof(*aux->func_info) * move);
17076 			aux->func_info_cnt -= j - i;
17077 			/* func_info->insn_off is set after all code rewrites,
17078 			 * in adjust_btf_func() - no need to adjust
17079 			 */
17080 		}
17081 	} else {
17082 		/* convert i from "first prog to remove" to "first to adjust" */
17083 		if (env->subprog_info[i].start == off)
17084 			i++;
17085 	}
17086 
17087 	/* update fake 'exit' subprog as well */
17088 	for (; i <= env->subprog_cnt; i++)
17089 		env->subprog_info[i].start -= cnt;
17090 
17091 	return 0;
17092 }
17093 
17094 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17095 				      u32 cnt)
17096 {
17097 	struct bpf_prog *prog = env->prog;
17098 	u32 i, l_off, l_cnt, nr_linfo;
17099 	struct bpf_line_info *linfo;
17100 
17101 	nr_linfo = prog->aux->nr_linfo;
17102 	if (!nr_linfo)
17103 		return 0;
17104 
17105 	linfo = prog->aux->linfo;
17106 
17107 	/* find first line info to remove, count lines to be removed */
17108 	for (i = 0; i < nr_linfo; i++)
17109 		if (linfo[i].insn_off >= off)
17110 			break;
17111 
17112 	l_off = i;
17113 	l_cnt = 0;
17114 	for (; i < nr_linfo; i++)
17115 		if (linfo[i].insn_off < off + cnt)
17116 			l_cnt++;
17117 		else
17118 			break;
17119 
17120 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17121 	 * last removed linfo.  prog is already modified, so prog->len == off
17122 	 * means no live instructions after (tail of the program was removed).
17123 	 */
17124 	if (prog->len != off && l_cnt &&
17125 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17126 		l_cnt--;
17127 		linfo[--i].insn_off = off + cnt;
17128 	}
17129 
17130 	/* remove the line info which refer to the removed instructions */
17131 	if (l_cnt) {
17132 		memmove(linfo + l_off, linfo + i,
17133 			sizeof(*linfo) * (nr_linfo - i));
17134 
17135 		prog->aux->nr_linfo -= l_cnt;
17136 		nr_linfo = prog->aux->nr_linfo;
17137 	}
17138 
17139 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17140 	for (i = l_off; i < nr_linfo; i++)
17141 		linfo[i].insn_off -= cnt;
17142 
17143 	/* fix up all subprogs (incl. 'exit') which start >= off */
17144 	for (i = 0; i <= env->subprog_cnt; i++)
17145 		if (env->subprog_info[i].linfo_idx > l_off) {
17146 			/* program may have started in the removed region but
17147 			 * may not be fully removed
17148 			 */
17149 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17150 				env->subprog_info[i].linfo_idx -= l_cnt;
17151 			else
17152 				env->subprog_info[i].linfo_idx = l_off;
17153 		}
17154 
17155 	return 0;
17156 }
17157 
17158 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17159 {
17160 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17161 	unsigned int orig_prog_len = env->prog->len;
17162 	int err;
17163 
17164 	if (bpf_prog_is_offloaded(env->prog->aux))
17165 		bpf_prog_offload_remove_insns(env, off, cnt);
17166 
17167 	err = bpf_remove_insns(env->prog, off, cnt);
17168 	if (err)
17169 		return err;
17170 
17171 	err = adjust_subprog_starts_after_remove(env, off, cnt);
17172 	if (err)
17173 		return err;
17174 
17175 	err = bpf_adj_linfo_after_remove(env, off, cnt);
17176 	if (err)
17177 		return err;
17178 
17179 	memmove(aux_data + off,	aux_data + off + cnt,
17180 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
17181 
17182 	return 0;
17183 }
17184 
17185 /* The verifier does more data flow analysis than llvm and will not
17186  * explore branches that are dead at run time. Malicious programs can
17187  * have dead code too. Therefore replace all dead at-run-time code
17188  * with 'ja -1'.
17189  *
17190  * Just nops are not optimal, e.g. if they would sit at the end of the
17191  * program and through another bug we would manage to jump there, then
17192  * we'd execute beyond program memory otherwise. Returning exception
17193  * code also wouldn't work since we can have subprogs where the dead
17194  * code could be located.
17195  */
17196 static void sanitize_dead_code(struct bpf_verifier_env *env)
17197 {
17198 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17199 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17200 	struct bpf_insn *insn = env->prog->insnsi;
17201 	const int insn_cnt = env->prog->len;
17202 	int i;
17203 
17204 	for (i = 0; i < insn_cnt; i++) {
17205 		if (aux_data[i].seen)
17206 			continue;
17207 		memcpy(insn + i, &trap, sizeof(trap));
17208 		aux_data[i].zext_dst = false;
17209 	}
17210 }
17211 
17212 static bool insn_is_cond_jump(u8 code)
17213 {
17214 	u8 op;
17215 
17216 	if (BPF_CLASS(code) == BPF_JMP32)
17217 		return true;
17218 
17219 	if (BPF_CLASS(code) != BPF_JMP)
17220 		return false;
17221 
17222 	op = BPF_OP(code);
17223 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17224 }
17225 
17226 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17227 {
17228 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17229 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17230 	struct bpf_insn *insn = env->prog->insnsi;
17231 	const int insn_cnt = env->prog->len;
17232 	int i;
17233 
17234 	for (i = 0; i < insn_cnt; i++, insn++) {
17235 		if (!insn_is_cond_jump(insn->code))
17236 			continue;
17237 
17238 		if (!aux_data[i + 1].seen)
17239 			ja.off = insn->off;
17240 		else if (!aux_data[i + 1 + insn->off].seen)
17241 			ja.off = 0;
17242 		else
17243 			continue;
17244 
17245 		if (bpf_prog_is_offloaded(env->prog->aux))
17246 			bpf_prog_offload_replace_insn(env, i, &ja);
17247 
17248 		memcpy(insn, &ja, sizeof(ja));
17249 	}
17250 }
17251 
17252 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17253 {
17254 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17255 	int insn_cnt = env->prog->len;
17256 	int i, err;
17257 
17258 	for (i = 0; i < insn_cnt; i++) {
17259 		int j;
17260 
17261 		j = 0;
17262 		while (i + j < insn_cnt && !aux_data[i + j].seen)
17263 			j++;
17264 		if (!j)
17265 			continue;
17266 
17267 		err = verifier_remove_insns(env, i, j);
17268 		if (err)
17269 			return err;
17270 		insn_cnt = env->prog->len;
17271 	}
17272 
17273 	return 0;
17274 }
17275 
17276 static int opt_remove_nops(struct bpf_verifier_env *env)
17277 {
17278 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17279 	struct bpf_insn *insn = env->prog->insnsi;
17280 	int insn_cnt = env->prog->len;
17281 	int i, err;
17282 
17283 	for (i = 0; i < insn_cnt; i++) {
17284 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17285 			continue;
17286 
17287 		err = verifier_remove_insns(env, i, 1);
17288 		if (err)
17289 			return err;
17290 		insn_cnt--;
17291 		i--;
17292 	}
17293 
17294 	return 0;
17295 }
17296 
17297 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17298 					 const union bpf_attr *attr)
17299 {
17300 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17301 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17302 	int i, patch_len, delta = 0, len = env->prog->len;
17303 	struct bpf_insn *insns = env->prog->insnsi;
17304 	struct bpf_prog *new_prog;
17305 	bool rnd_hi32;
17306 
17307 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17308 	zext_patch[1] = BPF_ZEXT_REG(0);
17309 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17310 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17311 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17312 	for (i = 0; i < len; i++) {
17313 		int adj_idx = i + delta;
17314 		struct bpf_insn insn;
17315 		int load_reg;
17316 
17317 		insn = insns[adj_idx];
17318 		load_reg = insn_def_regno(&insn);
17319 		if (!aux[adj_idx].zext_dst) {
17320 			u8 code, class;
17321 			u32 imm_rnd;
17322 
17323 			if (!rnd_hi32)
17324 				continue;
17325 
17326 			code = insn.code;
17327 			class = BPF_CLASS(code);
17328 			if (load_reg == -1)
17329 				continue;
17330 
17331 			/* NOTE: arg "reg" (the fourth one) is only used for
17332 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17333 			 *       here.
17334 			 */
17335 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17336 				if (class == BPF_LD &&
17337 				    BPF_MODE(code) == BPF_IMM)
17338 					i++;
17339 				continue;
17340 			}
17341 
17342 			/* ctx load could be transformed into wider load. */
17343 			if (class == BPF_LDX &&
17344 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17345 				continue;
17346 
17347 			imm_rnd = get_random_u32();
17348 			rnd_hi32_patch[0] = insn;
17349 			rnd_hi32_patch[1].imm = imm_rnd;
17350 			rnd_hi32_patch[3].dst_reg = load_reg;
17351 			patch = rnd_hi32_patch;
17352 			patch_len = 4;
17353 			goto apply_patch_buffer;
17354 		}
17355 
17356 		/* Add in an zero-extend instruction if a) the JIT has requested
17357 		 * it or b) it's a CMPXCHG.
17358 		 *
17359 		 * The latter is because: BPF_CMPXCHG always loads a value into
17360 		 * R0, therefore always zero-extends. However some archs'
17361 		 * equivalent instruction only does this load when the
17362 		 * comparison is successful. This detail of CMPXCHG is
17363 		 * orthogonal to the general zero-extension behaviour of the
17364 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17365 		 */
17366 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17367 			continue;
17368 
17369 		/* Zero-extension is done by the caller. */
17370 		if (bpf_pseudo_kfunc_call(&insn))
17371 			continue;
17372 
17373 		if (WARN_ON(load_reg == -1)) {
17374 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17375 			return -EFAULT;
17376 		}
17377 
17378 		zext_patch[0] = insn;
17379 		zext_patch[1].dst_reg = load_reg;
17380 		zext_patch[1].src_reg = load_reg;
17381 		patch = zext_patch;
17382 		patch_len = 2;
17383 apply_patch_buffer:
17384 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17385 		if (!new_prog)
17386 			return -ENOMEM;
17387 		env->prog = new_prog;
17388 		insns = new_prog->insnsi;
17389 		aux = env->insn_aux_data;
17390 		delta += patch_len - 1;
17391 	}
17392 
17393 	return 0;
17394 }
17395 
17396 /* convert load instructions that access fields of a context type into a
17397  * sequence of instructions that access fields of the underlying structure:
17398  *     struct __sk_buff    -> struct sk_buff
17399  *     struct bpf_sock_ops -> struct sock
17400  */
17401 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17402 {
17403 	const struct bpf_verifier_ops *ops = env->ops;
17404 	int i, cnt, size, ctx_field_size, delta = 0;
17405 	const int insn_cnt = env->prog->len;
17406 	struct bpf_insn insn_buf[16], *insn;
17407 	u32 target_size, size_default, off;
17408 	struct bpf_prog *new_prog;
17409 	enum bpf_access_type type;
17410 	bool is_narrower_load;
17411 
17412 	if (ops->gen_prologue || env->seen_direct_write) {
17413 		if (!ops->gen_prologue) {
17414 			verbose(env, "bpf verifier is misconfigured\n");
17415 			return -EINVAL;
17416 		}
17417 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17418 					env->prog);
17419 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17420 			verbose(env, "bpf verifier is misconfigured\n");
17421 			return -EINVAL;
17422 		} else if (cnt) {
17423 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17424 			if (!new_prog)
17425 				return -ENOMEM;
17426 
17427 			env->prog = new_prog;
17428 			delta += cnt - 1;
17429 		}
17430 	}
17431 
17432 	if (bpf_prog_is_offloaded(env->prog->aux))
17433 		return 0;
17434 
17435 	insn = env->prog->insnsi + delta;
17436 
17437 	for (i = 0; i < insn_cnt; i++, insn++) {
17438 		bpf_convert_ctx_access_t convert_ctx_access;
17439 
17440 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17441 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17442 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17443 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17444 			type = BPF_READ;
17445 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17446 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17447 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17448 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17449 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17450 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17451 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17452 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17453 			type = BPF_WRITE;
17454 		} else {
17455 			continue;
17456 		}
17457 
17458 		if (type == BPF_WRITE &&
17459 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17460 			struct bpf_insn patch[] = {
17461 				*insn,
17462 				BPF_ST_NOSPEC(),
17463 			};
17464 
17465 			cnt = ARRAY_SIZE(patch);
17466 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17467 			if (!new_prog)
17468 				return -ENOMEM;
17469 
17470 			delta    += cnt - 1;
17471 			env->prog = new_prog;
17472 			insn      = new_prog->insnsi + i + delta;
17473 			continue;
17474 		}
17475 
17476 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17477 		case PTR_TO_CTX:
17478 			if (!ops->convert_ctx_access)
17479 				continue;
17480 			convert_ctx_access = ops->convert_ctx_access;
17481 			break;
17482 		case PTR_TO_SOCKET:
17483 		case PTR_TO_SOCK_COMMON:
17484 			convert_ctx_access = bpf_sock_convert_ctx_access;
17485 			break;
17486 		case PTR_TO_TCP_SOCK:
17487 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17488 			break;
17489 		case PTR_TO_XDP_SOCK:
17490 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17491 			break;
17492 		case PTR_TO_BTF_ID:
17493 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17494 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17495 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17496 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17497 		 * any faults for loads into such types. BPF_WRITE is disallowed
17498 		 * for this case.
17499 		 */
17500 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17501 			if (type == BPF_READ) {
17502 				insn->code = BPF_LDX | BPF_PROBE_MEM |
17503 					BPF_SIZE((insn)->code);
17504 				env->prog->aux->num_exentries++;
17505 			}
17506 			continue;
17507 		default:
17508 			continue;
17509 		}
17510 
17511 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17512 		size = BPF_LDST_BYTES(insn);
17513 
17514 		/* If the read access is a narrower load of the field,
17515 		 * convert to a 4/8-byte load, to minimum program type specific
17516 		 * convert_ctx_access changes. If conversion is successful,
17517 		 * we will apply proper mask to the result.
17518 		 */
17519 		is_narrower_load = size < ctx_field_size;
17520 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17521 		off = insn->off;
17522 		if (is_narrower_load) {
17523 			u8 size_code;
17524 
17525 			if (type == BPF_WRITE) {
17526 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17527 				return -EINVAL;
17528 			}
17529 
17530 			size_code = BPF_H;
17531 			if (ctx_field_size == 4)
17532 				size_code = BPF_W;
17533 			else if (ctx_field_size == 8)
17534 				size_code = BPF_DW;
17535 
17536 			insn->off = off & ~(size_default - 1);
17537 			insn->code = BPF_LDX | BPF_MEM | size_code;
17538 		}
17539 
17540 		target_size = 0;
17541 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17542 					 &target_size);
17543 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17544 		    (ctx_field_size && !target_size)) {
17545 			verbose(env, "bpf verifier is misconfigured\n");
17546 			return -EINVAL;
17547 		}
17548 
17549 		if (is_narrower_load && size < target_size) {
17550 			u8 shift = bpf_ctx_narrow_access_offset(
17551 				off, size, size_default) * 8;
17552 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17553 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17554 				return -EINVAL;
17555 			}
17556 			if (ctx_field_size <= 4) {
17557 				if (shift)
17558 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17559 									insn->dst_reg,
17560 									shift);
17561 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17562 								(1 << size * 8) - 1);
17563 			} else {
17564 				if (shift)
17565 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17566 									insn->dst_reg,
17567 									shift);
17568 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17569 								(1ULL << size * 8) - 1);
17570 			}
17571 		}
17572 
17573 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17574 		if (!new_prog)
17575 			return -ENOMEM;
17576 
17577 		delta += cnt - 1;
17578 
17579 		/* keep walking new program and skip insns we just inserted */
17580 		env->prog = new_prog;
17581 		insn      = new_prog->insnsi + i + delta;
17582 	}
17583 
17584 	return 0;
17585 }
17586 
17587 static int jit_subprogs(struct bpf_verifier_env *env)
17588 {
17589 	struct bpf_prog *prog = env->prog, **func, *tmp;
17590 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17591 	struct bpf_map *map_ptr;
17592 	struct bpf_insn *insn;
17593 	void *old_bpf_func;
17594 	int err, num_exentries;
17595 
17596 	if (env->subprog_cnt <= 1)
17597 		return 0;
17598 
17599 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17600 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17601 			continue;
17602 
17603 		/* Upon error here we cannot fall back to interpreter but
17604 		 * need a hard reject of the program. Thus -EFAULT is
17605 		 * propagated in any case.
17606 		 */
17607 		subprog = find_subprog(env, i + insn->imm + 1);
17608 		if (subprog < 0) {
17609 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17610 				  i + insn->imm + 1);
17611 			return -EFAULT;
17612 		}
17613 		/* temporarily remember subprog id inside insn instead of
17614 		 * aux_data, since next loop will split up all insns into funcs
17615 		 */
17616 		insn->off = subprog;
17617 		/* remember original imm in case JIT fails and fallback
17618 		 * to interpreter will be needed
17619 		 */
17620 		env->insn_aux_data[i].call_imm = insn->imm;
17621 		/* point imm to __bpf_call_base+1 from JITs point of view */
17622 		insn->imm = 1;
17623 		if (bpf_pseudo_func(insn))
17624 			/* jit (e.g. x86_64) may emit fewer instructions
17625 			 * if it learns a u32 imm is the same as a u64 imm.
17626 			 * Force a non zero here.
17627 			 */
17628 			insn[1].imm = 1;
17629 	}
17630 
17631 	err = bpf_prog_alloc_jited_linfo(prog);
17632 	if (err)
17633 		goto out_undo_insn;
17634 
17635 	err = -ENOMEM;
17636 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17637 	if (!func)
17638 		goto out_undo_insn;
17639 
17640 	for (i = 0; i < env->subprog_cnt; i++) {
17641 		subprog_start = subprog_end;
17642 		subprog_end = env->subprog_info[i + 1].start;
17643 
17644 		len = subprog_end - subprog_start;
17645 		/* bpf_prog_run() doesn't call subprogs directly,
17646 		 * hence main prog stats include the runtime of subprogs.
17647 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17648 		 * func[i]->stats will never be accessed and stays NULL
17649 		 */
17650 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17651 		if (!func[i])
17652 			goto out_free;
17653 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17654 		       len * sizeof(struct bpf_insn));
17655 		func[i]->type = prog->type;
17656 		func[i]->len = len;
17657 		if (bpf_prog_calc_tag(func[i]))
17658 			goto out_free;
17659 		func[i]->is_func = 1;
17660 		func[i]->aux->func_idx = i;
17661 		/* Below members will be freed only at prog->aux */
17662 		func[i]->aux->btf = prog->aux->btf;
17663 		func[i]->aux->func_info = prog->aux->func_info;
17664 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17665 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17666 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17667 
17668 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17669 			struct bpf_jit_poke_descriptor *poke;
17670 
17671 			poke = &prog->aux->poke_tab[j];
17672 			if (poke->insn_idx < subprog_end &&
17673 			    poke->insn_idx >= subprog_start)
17674 				poke->aux = func[i]->aux;
17675 		}
17676 
17677 		func[i]->aux->name[0] = 'F';
17678 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17679 		func[i]->jit_requested = 1;
17680 		func[i]->blinding_requested = prog->blinding_requested;
17681 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17682 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17683 		func[i]->aux->linfo = prog->aux->linfo;
17684 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17685 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17686 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17687 		num_exentries = 0;
17688 		insn = func[i]->insnsi;
17689 		for (j = 0; j < func[i]->len; j++, insn++) {
17690 			if (BPF_CLASS(insn->code) == BPF_LDX &&
17691 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
17692 				num_exentries++;
17693 		}
17694 		func[i]->aux->num_exentries = num_exentries;
17695 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17696 		func[i] = bpf_int_jit_compile(func[i]);
17697 		if (!func[i]->jited) {
17698 			err = -ENOTSUPP;
17699 			goto out_free;
17700 		}
17701 		cond_resched();
17702 	}
17703 
17704 	/* at this point all bpf functions were successfully JITed
17705 	 * now populate all bpf_calls with correct addresses and
17706 	 * run last pass of JIT
17707 	 */
17708 	for (i = 0; i < env->subprog_cnt; i++) {
17709 		insn = func[i]->insnsi;
17710 		for (j = 0; j < func[i]->len; j++, insn++) {
17711 			if (bpf_pseudo_func(insn)) {
17712 				subprog = insn->off;
17713 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17714 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17715 				continue;
17716 			}
17717 			if (!bpf_pseudo_call(insn))
17718 				continue;
17719 			subprog = insn->off;
17720 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17721 		}
17722 
17723 		/* we use the aux data to keep a list of the start addresses
17724 		 * of the JITed images for each function in the program
17725 		 *
17726 		 * for some architectures, such as powerpc64, the imm field
17727 		 * might not be large enough to hold the offset of the start
17728 		 * address of the callee's JITed image from __bpf_call_base
17729 		 *
17730 		 * in such cases, we can lookup the start address of a callee
17731 		 * by using its subprog id, available from the off field of
17732 		 * the call instruction, as an index for this list
17733 		 */
17734 		func[i]->aux->func = func;
17735 		func[i]->aux->func_cnt = env->subprog_cnt;
17736 	}
17737 	for (i = 0; i < env->subprog_cnt; i++) {
17738 		old_bpf_func = func[i]->bpf_func;
17739 		tmp = bpf_int_jit_compile(func[i]);
17740 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17741 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17742 			err = -ENOTSUPP;
17743 			goto out_free;
17744 		}
17745 		cond_resched();
17746 	}
17747 
17748 	/* finally lock prog and jit images for all functions and
17749 	 * populate kallsysm
17750 	 */
17751 	for (i = 0; i < env->subprog_cnt; i++) {
17752 		bpf_prog_lock_ro(func[i]);
17753 		bpf_prog_kallsyms_add(func[i]);
17754 	}
17755 
17756 	/* Last step: make now unused interpreter insns from main
17757 	 * prog consistent for later dump requests, so they can
17758 	 * later look the same as if they were interpreted only.
17759 	 */
17760 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17761 		if (bpf_pseudo_func(insn)) {
17762 			insn[0].imm = env->insn_aux_data[i].call_imm;
17763 			insn[1].imm = insn->off;
17764 			insn->off = 0;
17765 			continue;
17766 		}
17767 		if (!bpf_pseudo_call(insn))
17768 			continue;
17769 		insn->off = env->insn_aux_data[i].call_imm;
17770 		subprog = find_subprog(env, i + insn->off + 1);
17771 		insn->imm = subprog;
17772 	}
17773 
17774 	prog->jited = 1;
17775 	prog->bpf_func = func[0]->bpf_func;
17776 	prog->jited_len = func[0]->jited_len;
17777 	prog->aux->func = func;
17778 	prog->aux->func_cnt = env->subprog_cnt;
17779 	bpf_prog_jit_attempt_done(prog);
17780 	return 0;
17781 out_free:
17782 	/* We failed JIT'ing, so at this point we need to unregister poke
17783 	 * descriptors from subprogs, so that kernel is not attempting to
17784 	 * patch it anymore as we're freeing the subprog JIT memory.
17785 	 */
17786 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17787 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17788 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17789 	}
17790 	/* At this point we're guaranteed that poke descriptors are not
17791 	 * live anymore. We can just unlink its descriptor table as it's
17792 	 * released with the main prog.
17793 	 */
17794 	for (i = 0; i < env->subprog_cnt; i++) {
17795 		if (!func[i])
17796 			continue;
17797 		func[i]->aux->poke_tab = NULL;
17798 		bpf_jit_free(func[i]);
17799 	}
17800 	kfree(func);
17801 out_undo_insn:
17802 	/* cleanup main prog to be interpreted */
17803 	prog->jit_requested = 0;
17804 	prog->blinding_requested = 0;
17805 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17806 		if (!bpf_pseudo_call(insn))
17807 			continue;
17808 		insn->off = 0;
17809 		insn->imm = env->insn_aux_data[i].call_imm;
17810 	}
17811 	bpf_prog_jit_attempt_done(prog);
17812 	return err;
17813 }
17814 
17815 static int fixup_call_args(struct bpf_verifier_env *env)
17816 {
17817 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17818 	struct bpf_prog *prog = env->prog;
17819 	struct bpf_insn *insn = prog->insnsi;
17820 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17821 	int i, depth;
17822 #endif
17823 	int err = 0;
17824 
17825 	if (env->prog->jit_requested &&
17826 	    !bpf_prog_is_offloaded(env->prog->aux)) {
17827 		err = jit_subprogs(env);
17828 		if (err == 0)
17829 			return 0;
17830 		if (err == -EFAULT)
17831 			return err;
17832 	}
17833 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17834 	if (has_kfunc_call) {
17835 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17836 		return -EINVAL;
17837 	}
17838 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17839 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
17840 		 * have to be rejected, since interpreter doesn't support them yet.
17841 		 */
17842 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17843 		return -EINVAL;
17844 	}
17845 	for (i = 0; i < prog->len; i++, insn++) {
17846 		if (bpf_pseudo_func(insn)) {
17847 			/* When JIT fails the progs with callback calls
17848 			 * have to be rejected, since interpreter doesn't support them yet.
17849 			 */
17850 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
17851 			return -EINVAL;
17852 		}
17853 
17854 		if (!bpf_pseudo_call(insn))
17855 			continue;
17856 		depth = get_callee_stack_depth(env, insn, i);
17857 		if (depth < 0)
17858 			return depth;
17859 		bpf_patch_call_args(insn, depth);
17860 	}
17861 	err = 0;
17862 #endif
17863 	return err;
17864 }
17865 
17866 /* replace a generic kfunc with a specialized version if necessary */
17867 static void specialize_kfunc(struct bpf_verifier_env *env,
17868 			     u32 func_id, u16 offset, unsigned long *addr)
17869 {
17870 	struct bpf_prog *prog = env->prog;
17871 	bool seen_direct_write;
17872 	void *xdp_kfunc;
17873 	bool is_rdonly;
17874 
17875 	if (bpf_dev_bound_kfunc_id(func_id)) {
17876 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17877 		if (xdp_kfunc) {
17878 			*addr = (unsigned long)xdp_kfunc;
17879 			return;
17880 		}
17881 		/* fallback to default kfunc when not supported by netdev */
17882 	}
17883 
17884 	if (offset)
17885 		return;
17886 
17887 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17888 		seen_direct_write = env->seen_direct_write;
17889 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17890 
17891 		if (is_rdonly)
17892 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17893 
17894 		/* restore env->seen_direct_write to its original value, since
17895 		 * may_access_direct_pkt_data mutates it
17896 		 */
17897 		env->seen_direct_write = seen_direct_write;
17898 	}
17899 }
17900 
17901 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17902 					    u16 struct_meta_reg,
17903 					    u16 node_offset_reg,
17904 					    struct bpf_insn *insn,
17905 					    struct bpf_insn *insn_buf,
17906 					    int *cnt)
17907 {
17908 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17909 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17910 
17911 	insn_buf[0] = addr[0];
17912 	insn_buf[1] = addr[1];
17913 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17914 	insn_buf[3] = *insn;
17915 	*cnt = 4;
17916 }
17917 
17918 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17919 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17920 {
17921 	const struct bpf_kfunc_desc *desc;
17922 
17923 	if (!insn->imm) {
17924 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17925 		return -EINVAL;
17926 	}
17927 
17928 	*cnt = 0;
17929 
17930 	/* insn->imm has the btf func_id. Replace it with an offset relative to
17931 	 * __bpf_call_base, unless the JIT needs to call functions that are
17932 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
17933 	 */
17934 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17935 	if (!desc) {
17936 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17937 			insn->imm);
17938 		return -EFAULT;
17939 	}
17940 
17941 	if (!bpf_jit_supports_far_kfunc_call())
17942 		insn->imm = BPF_CALL_IMM(desc->addr);
17943 	if (insn->off)
17944 		return 0;
17945 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17946 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17947 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17948 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17949 
17950 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17951 		insn_buf[1] = addr[0];
17952 		insn_buf[2] = addr[1];
17953 		insn_buf[3] = *insn;
17954 		*cnt = 4;
17955 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
17956 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
17957 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17958 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17959 
17960 		insn_buf[0] = addr[0];
17961 		insn_buf[1] = addr[1];
17962 		insn_buf[2] = *insn;
17963 		*cnt = 3;
17964 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
17965 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
17966 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17967 		int struct_meta_reg = BPF_REG_3;
17968 		int node_offset_reg = BPF_REG_4;
17969 
17970 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
17971 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
17972 			struct_meta_reg = BPF_REG_4;
17973 			node_offset_reg = BPF_REG_5;
17974 		}
17975 
17976 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
17977 						node_offset_reg, insn, insn_buf, cnt);
17978 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17979 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17980 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17981 		*cnt = 1;
17982 	}
17983 	return 0;
17984 }
17985 
17986 /* Do various post-verification rewrites in a single program pass.
17987  * These rewrites simplify JIT and interpreter implementations.
17988  */
17989 static int do_misc_fixups(struct bpf_verifier_env *env)
17990 {
17991 	struct bpf_prog *prog = env->prog;
17992 	enum bpf_attach_type eatype = prog->expected_attach_type;
17993 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17994 	struct bpf_insn *insn = prog->insnsi;
17995 	const struct bpf_func_proto *fn;
17996 	const int insn_cnt = prog->len;
17997 	const struct bpf_map_ops *ops;
17998 	struct bpf_insn_aux_data *aux;
17999 	struct bpf_insn insn_buf[16];
18000 	struct bpf_prog *new_prog;
18001 	struct bpf_map *map_ptr;
18002 	int i, ret, cnt, delta = 0;
18003 
18004 	for (i = 0; i < insn_cnt; i++, insn++) {
18005 		/* Make divide-by-zero exceptions impossible. */
18006 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18007 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18008 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18009 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18010 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18011 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18012 			struct bpf_insn *patchlet;
18013 			struct bpf_insn chk_and_div[] = {
18014 				/* [R,W]x div 0 -> 0 */
18015 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18016 					     BPF_JNE | BPF_K, insn->src_reg,
18017 					     0, 2, 0),
18018 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18019 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18020 				*insn,
18021 			};
18022 			struct bpf_insn chk_and_mod[] = {
18023 				/* [R,W]x mod 0 -> [R,W]x */
18024 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18025 					     BPF_JEQ | BPF_K, insn->src_reg,
18026 					     0, 1 + (is64 ? 0 : 1), 0),
18027 				*insn,
18028 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18029 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18030 			};
18031 
18032 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18033 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18034 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18035 
18036 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18037 			if (!new_prog)
18038 				return -ENOMEM;
18039 
18040 			delta    += cnt - 1;
18041 			env->prog = prog = new_prog;
18042 			insn      = new_prog->insnsi + i + delta;
18043 			continue;
18044 		}
18045 
18046 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18047 		if (BPF_CLASS(insn->code) == BPF_LD &&
18048 		    (BPF_MODE(insn->code) == BPF_ABS ||
18049 		     BPF_MODE(insn->code) == BPF_IND)) {
18050 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18051 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18052 				verbose(env, "bpf verifier is misconfigured\n");
18053 				return -EINVAL;
18054 			}
18055 
18056 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18057 			if (!new_prog)
18058 				return -ENOMEM;
18059 
18060 			delta    += cnt - 1;
18061 			env->prog = prog = new_prog;
18062 			insn      = new_prog->insnsi + i + delta;
18063 			continue;
18064 		}
18065 
18066 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18067 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18068 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18069 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18070 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18071 			struct bpf_insn *patch = &insn_buf[0];
18072 			bool issrc, isneg, isimm;
18073 			u32 off_reg;
18074 
18075 			aux = &env->insn_aux_data[i + delta];
18076 			if (!aux->alu_state ||
18077 			    aux->alu_state == BPF_ALU_NON_POINTER)
18078 				continue;
18079 
18080 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18081 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18082 				BPF_ALU_SANITIZE_SRC;
18083 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18084 
18085 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18086 			if (isimm) {
18087 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18088 			} else {
18089 				if (isneg)
18090 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18091 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18092 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18093 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18094 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18095 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18096 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18097 			}
18098 			if (!issrc)
18099 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18100 			insn->src_reg = BPF_REG_AX;
18101 			if (isneg)
18102 				insn->code = insn->code == code_add ?
18103 					     code_sub : code_add;
18104 			*patch++ = *insn;
18105 			if (issrc && isneg && !isimm)
18106 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18107 			cnt = patch - insn_buf;
18108 
18109 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18110 			if (!new_prog)
18111 				return -ENOMEM;
18112 
18113 			delta    += cnt - 1;
18114 			env->prog = prog = new_prog;
18115 			insn      = new_prog->insnsi + i + delta;
18116 			continue;
18117 		}
18118 
18119 		if (insn->code != (BPF_JMP | BPF_CALL))
18120 			continue;
18121 		if (insn->src_reg == BPF_PSEUDO_CALL)
18122 			continue;
18123 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18124 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18125 			if (ret)
18126 				return ret;
18127 			if (cnt == 0)
18128 				continue;
18129 
18130 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18131 			if (!new_prog)
18132 				return -ENOMEM;
18133 
18134 			delta	 += cnt - 1;
18135 			env->prog = prog = new_prog;
18136 			insn	  = new_prog->insnsi + i + delta;
18137 			continue;
18138 		}
18139 
18140 		if (insn->imm == BPF_FUNC_get_route_realm)
18141 			prog->dst_needed = 1;
18142 		if (insn->imm == BPF_FUNC_get_prandom_u32)
18143 			bpf_user_rnd_init_once();
18144 		if (insn->imm == BPF_FUNC_override_return)
18145 			prog->kprobe_override = 1;
18146 		if (insn->imm == BPF_FUNC_tail_call) {
18147 			/* If we tail call into other programs, we
18148 			 * cannot make any assumptions since they can
18149 			 * be replaced dynamically during runtime in
18150 			 * the program array.
18151 			 */
18152 			prog->cb_access = 1;
18153 			if (!allow_tail_call_in_subprogs(env))
18154 				prog->aux->stack_depth = MAX_BPF_STACK;
18155 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18156 
18157 			/* mark bpf_tail_call as different opcode to avoid
18158 			 * conditional branch in the interpreter for every normal
18159 			 * call and to prevent accidental JITing by JIT compiler
18160 			 * that doesn't support bpf_tail_call yet
18161 			 */
18162 			insn->imm = 0;
18163 			insn->code = BPF_JMP | BPF_TAIL_CALL;
18164 
18165 			aux = &env->insn_aux_data[i + delta];
18166 			if (env->bpf_capable && !prog->blinding_requested &&
18167 			    prog->jit_requested &&
18168 			    !bpf_map_key_poisoned(aux) &&
18169 			    !bpf_map_ptr_poisoned(aux) &&
18170 			    !bpf_map_ptr_unpriv(aux)) {
18171 				struct bpf_jit_poke_descriptor desc = {
18172 					.reason = BPF_POKE_REASON_TAIL_CALL,
18173 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18174 					.tail_call.key = bpf_map_key_immediate(aux),
18175 					.insn_idx = i + delta,
18176 				};
18177 
18178 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
18179 				if (ret < 0) {
18180 					verbose(env, "adding tail call poke descriptor failed\n");
18181 					return ret;
18182 				}
18183 
18184 				insn->imm = ret + 1;
18185 				continue;
18186 			}
18187 
18188 			if (!bpf_map_ptr_unpriv(aux))
18189 				continue;
18190 
18191 			/* instead of changing every JIT dealing with tail_call
18192 			 * emit two extra insns:
18193 			 * if (index >= max_entries) goto out;
18194 			 * index &= array->index_mask;
18195 			 * to avoid out-of-bounds cpu speculation
18196 			 */
18197 			if (bpf_map_ptr_poisoned(aux)) {
18198 				verbose(env, "tail_call abusing map_ptr\n");
18199 				return -EINVAL;
18200 			}
18201 
18202 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18203 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18204 						  map_ptr->max_entries, 2);
18205 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18206 						    container_of(map_ptr,
18207 								 struct bpf_array,
18208 								 map)->index_mask);
18209 			insn_buf[2] = *insn;
18210 			cnt = 3;
18211 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18212 			if (!new_prog)
18213 				return -ENOMEM;
18214 
18215 			delta    += cnt - 1;
18216 			env->prog = prog = new_prog;
18217 			insn      = new_prog->insnsi + i + delta;
18218 			continue;
18219 		}
18220 
18221 		if (insn->imm == BPF_FUNC_timer_set_callback) {
18222 			/* The verifier will process callback_fn as many times as necessary
18223 			 * with different maps and the register states prepared by
18224 			 * set_timer_callback_state will be accurate.
18225 			 *
18226 			 * The following use case is valid:
18227 			 *   map1 is shared by prog1, prog2, prog3.
18228 			 *   prog1 calls bpf_timer_init for some map1 elements
18229 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
18230 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
18231 			 *   prog3 calls bpf_timer_start for some map1 elements.
18232 			 *     Those that were not both bpf_timer_init-ed and
18233 			 *     bpf_timer_set_callback-ed will return -EINVAL.
18234 			 */
18235 			struct bpf_insn ld_addrs[2] = {
18236 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18237 			};
18238 
18239 			insn_buf[0] = ld_addrs[0];
18240 			insn_buf[1] = ld_addrs[1];
18241 			insn_buf[2] = *insn;
18242 			cnt = 3;
18243 
18244 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18245 			if (!new_prog)
18246 				return -ENOMEM;
18247 
18248 			delta    += cnt - 1;
18249 			env->prog = prog = new_prog;
18250 			insn      = new_prog->insnsi + i + delta;
18251 			goto patch_call_imm;
18252 		}
18253 
18254 		if (is_storage_get_function(insn->imm)) {
18255 			if (!env->prog->aux->sleepable ||
18256 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
18257 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18258 			else
18259 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18260 			insn_buf[1] = *insn;
18261 			cnt = 2;
18262 
18263 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18264 			if (!new_prog)
18265 				return -ENOMEM;
18266 
18267 			delta += cnt - 1;
18268 			env->prog = prog = new_prog;
18269 			insn = new_prog->insnsi + i + delta;
18270 			goto patch_call_imm;
18271 		}
18272 
18273 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18274 		 * and other inlining handlers are currently limited to 64 bit
18275 		 * only.
18276 		 */
18277 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18278 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
18279 		     insn->imm == BPF_FUNC_map_update_elem ||
18280 		     insn->imm == BPF_FUNC_map_delete_elem ||
18281 		     insn->imm == BPF_FUNC_map_push_elem   ||
18282 		     insn->imm == BPF_FUNC_map_pop_elem    ||
18283 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18284 		     insn->imm == BPF_FUNC_redirect_map    ||
18285 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18286 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18287 			aux = &env->insn_aux_data[i + delta];
18288 			if (bpf_map_ptr_poisoned(aux))
18289 				goto patch_call_imm;
18290 
18291 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18292 			ops = map_ptr->ops;
18293 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18294 			    ops->map_gen_lookup) {
18295 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18296 				if (cnt == -EOPNOTSUPP)
18297 					goto patch_map_ops_generic;
18298 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18299 					verbose(env, "bpf verifier is misconfigured\n");
18300 					return -EINVAL;
18301 				}
18302 
18303 				new_prog = bpf_patch_insn_data(env, i + delta,
18304 							       insn_buf, cnt);
18305 				if (!new_prog)
18306 					return -ENOMEM;
18307 
18308 				delta    += cnt - 1;
18309 				env->prog = prog = new_prog;
18310 				insn      = new_prog->insnsi + i + delta;
18311 				continue;
18312 			}
18313 
18314 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18315 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18316 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18317 				     (long (*)(struct bpf_map *map, void *key))NULL));
18318 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18319 				     (long (*)(struct bpf_map *map, void *key, void *value,
18320 					      u64 flags))NULL));
18321 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18322 				     (long (*)(struct bpf_map *map, void *value,
18323 					      u64 flags))NULL));
18324 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18325 				     (long (*)(struct bpf_map *map, void *value))NULL));
18326 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18327 				     (long (*)(struct bpf_map *map, void *value))NULL));
18328 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18329 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18330 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18331 				     (long (*)(struct bpf_map *map,
18332 					      bpf_callback_t callback_fn,
18333 					      void *callback_ctx,
18334 					      u64 flags))NULL));
18335 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18336 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18337 
18338 patch_map_ops_generic:
18339 			switch (insn->imm) {
18340 			case BPF_FUNC_map_lookup_elem:
18341 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18342 				continue;
18343 			case BPF_FUNC_map_update_elem:
18344 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18345 				continue;
18346 			case BPF_FUNC_map_delete_elem:
18347 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18348 				continue;
18349 			case BPF_FUNC_map_push_elem:
18350 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18351 				continue;
18352 			case BPF_FUNC_map_pop_elem:
18353 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18354 				continue;
18355 			case BPF_FUNC_map_peek_elem:
18356 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18357 				continue;
18358 			case BPF_FUNC_redirect_map:
18359 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18360 				continue;
18361 			case BPF_FUNC_for_each_map_elem:
18362 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18363 				continue;
18364 			case BPF_FUNC_map_lookup_percpu_elem:
18365 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18366 				continue;
18367 			}
18368 
18369 			goto patch_call_imm;
18370 		}
18371 
18372 		/* Implement bpf_jiffies64 inline. */
18373 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18374 		    insn->imm == BPF_FUNC_jiffies64) {
18375 			struct bpf_insn ld_jiffies_addr[2] = {
18376 				BPF_LD_IMM64(BPF_REG_0,
18377 					     (unsigned long)&jiffies),
18378 			};
18379 
18380 			insn_buf[0] = ld_jiffies_addr[0];
18381 			insn_buf[1] = ld_jiffies_addr[1];
18382 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18383 						  BPF_REG_0, 0);
18384 			cnt = 3;
18385 
18386 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18387 						       cnt);
18388 			if (!new_prog)
18389 				return -ENOMEM;
18390 
18391 			delta    += cnt - 1;
18392 			env->prog = prog = new_prog;
18393 			insn      = new_prog->insnsi + i + delta;
18394 			continue;
18395 		}
18396 
18397 		/* Implement bpf_get_func_arg inline. */
18398 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18399 		    insn->imm == BPF_FUNC_get_func_arg) {
18400 			/* Load nr_args from ctx - 8 */
18401 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18402 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18403 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18404 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18405 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18406 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18407 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18408 			insn_buf[7] = BPF_JMP_A(1);
18409 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18410 			cnt = 9;
18411 
18412 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18413 			if (!new_prog)
18414 				return -ENOMEM;
18415 
18416 			delta    += cnt - 1;
18417 			env->prog = prog = new_prog;
18418 			insn      = new_prog->insnsi + i + delta;
18419 			continue;
18420 		}
18421 
18422 		/* Implement bpf_get_func_ret inline. */
18423 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18424 		    insn->imm == BPF_FUNC_get_func_ret) {
18425 			if (eatype == BPF_TRACE_FEXIT ||
18426 			    eatype == BPF_MODIFY_RETURN) {
18427 				/* Load nr_args from ctx - 8 */
18428 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18429 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18430 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18431 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18432 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18433 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18434 				cnt = 6;
18435 			} else {
18436 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18437 				cnt = 1;
18438 			}
18439 
18440 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18441 			if (!new_prog)
18442 				return -ENOMEM;
18443 
18444 			delta    += cnt - 1;
18445 			env->prog = prog = new_prog;
18446 			insn      = new_prog->insnsi + i + delta;
18447 			continue;
18448 		}
18449 
18450 		/* Implement get_func_arg_cnt inline. */
18451 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18452 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18453 			/* Load nr_args from ctx - 8 */
18454 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18455 
18456 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18457 			if (!new_prog)
18458 				return -ENOMEM;
18459 
18460 			env->prog = prog = new_prog;
18461 			insn      = new_prog->insnsi + i + delta;
18462 			continue;
18463 		}
18464 
18465 		/* Implement bpf_get_func_ip inline. */
18466 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18467 		    insn->imm == BPF_FUNC_get_func_ip) {
18468 			/* Load IP address from ctx - 16 */
18469 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18470 
18471 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18472 			if (!new_prog)
18473 				return -ENOMEM;
18474 
18475 			env->prog = prog = new_prog;
18476 			insn      = new_prog->insnsi + i + delta;
18477 			continue;
18478 		}
18479 
18480 patch_call_imm:
18481 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18482 		/* all functions that have prototype and verifier allowed
18483 		 * programs to call them, must be real in-kernel functions
18484 		 */
18485 		if (!fn->func) {
18486 			verbose(env,
18487 				"kernel subsystem misconfigured func %s#%d\n",
18488 				func_id_name(insn->imm), insn->imm);
18489 			return -EFAULT;
18490 		}
18491 		insn->imm = fn->func - __bpf_call_base;
18492 	}
18493 
18494 	/* Since poke tab is now finalized, publish aux to tracker. */
18495 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18496 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18497 		if (!map_ptr->ops->map_poke_track ||
18498 		    !map_ptr->ops->map_poke_untrack ||
18499 		    !map_ptr->ops->map_poke_run) {
18500 			verbose(env, "bpf verifier is misconfigured\n");
18501 			return -EINVAL;
18502 		}
18503 
18504 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18505 		if (ret < 0) {
18506 			verbose(env, "tracking tail call prog failed\n");
18507 			return ret;
18508 		}
18509 	}
18510 
18511 	sort_kfunc_descs_by_imm_off(env->prog);
18512 
18513 	return 0;
18514 }
18515 
18516 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18517 					int position,
18518 					s32 stack_base,
18519 					u32 callback_subprogno,
18520 					u32 *cnt)
18521 {
18522 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18523 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18524 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18525 	int reg_loop_max = BPF_REG_6;
18526 	int reg_loop_cnt = BPF_REG_7;
18527 	int reg_loop_ctx = BPF_REG_8;
18528 
18529 	struct bpf_prog *new_prog;
18530 	u32 callback_start;
18531 	u32 call_insn_offset;
18532 	s32 callback_offset;
18533 
18534 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18535 	 * be careful to modify this code in sync.
18536 	 */
18537 	struct bpf_insn insn_buf[] = {
18538 		/* Return error and jump to the end of the patch if
18539 		 * expected number of iterations is too big.
18540 		 */
18541 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18542 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18543 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18544 		/* spill R6, R7, R8 to use these as loop vars */
18545 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18546 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18547 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18548 		/* initialize loop vars */
18549 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18550 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18551 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18552 		/* loop header,
18553 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18554 		 */
18555 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18556 		/* callback call,
18557 		 * correct callback offset would be set after patching
18558 		 */
18559 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18560 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18561 		BPF_CALL_REL(0),
18562 		/* increment loop counter */
18563 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18564 		/* jump to loop header if callback returned 0 */
18565 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18566 		/* return value of bpf_loop,
18567 		 * set R0 to the number of iterations
18568 		 */
18569 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18570 		/* restore original values of R6, R7, R8 */
18571 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18572 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18573 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18574 	};
18575 
18576 	*cnt = ARRAY_SIZE(insn_buf);
18577 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18578 	if (!new_prog)
18579 		return new_prog;
18580 
18581 	/* callback start is known only after patching */
18582 	callback_start = env->subprog_info[callback_subprogno].start;
18583 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18584 	call_insn_offset = position + 12;
18585 	callback_offset = callback_start - call_insn_offset - 1;
18586 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18587 
18588 	return new_prog;
18589 }
18590 
18591 static bool is_bpf_loop_call(struct bpf_insn *insn)
18592 {
18593 	return insn->code == (BPF_JMP | BPF_CALL) &&
18594 		insn->src_reg == 0 &&
18595 		insn->imm == BPF_FUNC_loop;
18596 }
18597 
18598 /* For all sub-programs in the program (including main) check
18599  * insn_aux_data to see if there are bpf_loop calls that require
18600  * inlining. If such calls are found the calls are replaced with a
18601  * sequence of instructions produced by `inline_bpf_loop` function and
18602  * subprog stack_depth is increased by the size of 3 registers.
18603  * This stack space is used to spill values of the R6, R7, R8.  These
18604  * registers are used to store the loop bound, counter and context
18605  * variables.
18606  */
18607 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18608 {
18609 	struct bpf_subprog_info *subprogs = env->subprog_info;
18610 	int i, cur_subprog = 0, cnt, delta = 0;
18611 	struct bpf_insn *insn = env->prog->insnsi;
18612 	int insn_cnt = env->prog->len;
18613 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18614 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18615 	u16 stack_depth_extra = 0;
18616 
18617 	for (i = 0; i < insn_cnt; i++, insn++) {
18618 		struct bpf_loop_inline_state *inline_state =
18619 			&env->insn_aux_data[i + delta].loop_inline_state;
18620 
18621 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18622 			struct bpf_prog *new_prog;
18623 
18624 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18625 			new_prog = inline_bpf_loop(env,
18626 						   i + delta,
18627 						   -(stack_depth + stack_depth_extra),
18628 						   inline_state->callback_subprogno,
18629 						   &cnt);
18630 			if (!new_prog)
18631 				return -ENOMEM;
18632 
18633 			delta     += cnt - 1;
18634 			env->prog  = new_prog;
18635 			insn       = new_prog->insnsi + i + delta;
18636 		}
18637 
18638 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18639 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18640 			cur_subprog++;
18641 			stack_depth = subprogs[cur_subprog].stack_depth;
18642 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18643 			stack_depth_extra = 0;
18644 		}
18645 	}
18646 
18647 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18648 
18649 	return 0;
18650 }
18651 
18652 static void free_states(struct bpf_verifier_env *env)
18653 {
18654 	struct bpf_verifier_state_list *sl, *sln;
18655 	int i;
18656 
18657 	sl = env->free_list;
18658 	while (sl) {
18659 		sln = sl->next;
18660 		free_verifier_state(&sl->state, false);
18661 		kfree(sl);
18662 		sl = sln;
18663 	}
18664 	env->free_list = NULL;
18665 
18666 	if (!env->explored_states)
18667 		return;
18668 
18669 	for (i = 0; i < state_htab_size(env); i++) {
18670 		sl = env->explored_states[i];
18671 
18672 		while (sl) {
18673 			sln = sl->next;
18674 			free_verifier_state(&sl->state, false);
18675 			kfree(sl);
18676 			sl = sln;
18677 		}
18678 		env->explored_states[i] = NULL;
18679 	}
18680 }
18681 
18682 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18683 {
18684 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18685 	struct bpf_verifier_state *state;
18686 	struct bpf_reg_state *regs;
18687 	int ret, i;
18688 
18689 	env->prev_linfo = NULL;
18690 	env->pass_cnt++;
18691 
18692 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18693 	if (!state)
18694 		return -ENOMEM;
18695 	state->curframe = 0;
18696 	state->speculative = false;
18697 	state->branches = 1;
18698 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18699 	if (!state->frame[0]) {
18700 		kfree(state);
18701 		return -ENOMEM;
18702 	}
18703 	env->cur_state = state;
18704 	init_func_state(env, state->frame[0],
18705 			BPF_MAIN_FUNC /* callsite */,
18706 			0 /* frameno */,
18707 			subprog);
18708 	state->first_insn_idx = env->subprog_info[subprog].start;
18709 	state->last_insn_idx = -1;
18710 
18711 	regs = state->frame[state->curframe]->regs;
18712 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18713 		ret = btf_prepare_func_args(env, subprog, regs);
18714 		if (ret)
18715 			goto out;
18716 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18717 			if (regs[i].type == PTR_TO_CTX)
18718 				mark_reg_known_zero(env, regs, i);
18719 			else if (regs[i].type == SCALAR_VALUE)
18720 				mark_reg_unknown(env, regs, i);
18721 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
18722 				const u32 mem_size = regs[i].mem_size;
18723 
18724 				mark_reg_known_zero(env, regs, i);
18725 				regs[i].mem_size = mem_size;
18726 				regs[i].id = ++env->id_gen;
18727 			}
18728 		}
18729 	} else {
18730 		/* 1st arg to a function */
18731 		regs[BPF_REG_1].type = PTR_TO_CTX;
18732 		mark_reg_known_zero(env, regs, BPF_REG_1);
18733 		ret = btf_check_subprog_arg_match(env, subprog, regs);
18734 		if (ret == -EFAULT)
18735 			/* unlikely verifier bug. abort.
18736 			 * ret == 0 and ret < 0 are sadly acceptable for
18737 			 * main() function due to backward compatibility.
18738 			 * Like socket filter program may be written as:
18739 			 * int bpf_prog(struct pt_regs *ctx)
18740 			 * and never dereference that ctx in the program.
18741 			 * 'struct pt_regs' is a type mismatch for socket
18742 			 * filter that should be using 'struct __sk_buff'.
18743 			 */
18744 			goto out;
18745 	}
18746 
18747 	ret = do_check(env);
18748 out:
18749 	/* check for NULL is necessary, since cur_state can be freed inside
18750 	 * do_check() under memory pressure.
18751 	 */
18752 	if (env->cur_state) {
18753 		free_verifier_state(env->cur_state, true);
18754 		env->cur_state = NULL;
18755 	}
18756 	while (!pop_stack(env, NULL, NULL, false));
18757 	if (!ret && pop_log)
18758 		bpf_vlog_reset(&env->log, 0);
18759 	free_states(env);
18760 	return ret;
18761 }
18762 
18763 /* Verify all global functions in a BPF program one by one based on their BTF.
18764  * All global functions must pass verification. Otherwise the whole program is rejected.
18765  * Consider:
18766  * int bar(int);
18767  * int foo(int f)
18768  * {
18769  *    return bar(f);
18770  * }
18771  * int bar(int b)
18772  * {
18773  *    ...
18774  * }
18775  * foo() will be verified first for R1=any_scalar_value. During verification it
18776  * will be assumed that bar() already verified successfully and call to bar()
18777  * from foo() will be checked for type match only. Later bar() will be verified
18778  * independently to check that it's safe for R1=any_scalar_value.
18779  */
18780 static int do_check_subprogs(struct bpf_verifier_env *env)
18781 {
18782 	struct bpf_prog_aux *aux = env->prog->aux;
18783 	int i, ret;
18784 
18785 	if (!aux->func_info)
18786 		return 0;
18787 
18788 	for (i = 1; i < env->subprog_cnt; i++) {
18789 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18790 			continue;
18791 		env->insn_idx = env->subprog_info[i].start;
18792 		WARN_ON_ONCE(env->insn_idx == 0);
18793 		ret = do_check_common(env, i);
18794 		if (ret) {
18795 			return ret;
18796 		} else if (env->log.level & BPF_LOG_LEVEL) {
18797 			verbose(env,
18798 				"Func#%d is safe for any args that match its prototype\n",
18799 				i);
18800 		}
18801 	}
18802 	return 0;
18803 }
18804 
18805 static int do_check_main(struct bpf_verifier_env *env)
18806 {
18807 	int ret;
18808 
18809 	env->insn_idx = 0;
18810 	ret = do_check_common(env, 0);
18811 	if (!ret)
18812 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18813 	return ret;
18814 }
18815 
18816 
18817 static void print_verification_stats(struct bpf_verifier_env *env)
18818 {
18819 	int i;
18820 
18821 	if (env->log.level & BPF_LOG_STATS) {
18822 		verbose(env, "verification time %lld usec\n",
18823 			div_u64(env->verification_time, 1000));
18824 		verbose(env, "stack depth ");
18825 		for (i = 0; i < env->subprog_cnt; i++) {
18826 			u32 depth = env->subprog_info[i].stack_depth;
18827 
18828 			verbose(env, "%d", depth);
18829 			if (i + 1 < env->subprog_cnt)
18830 				verbose(env, "+");
18831 		}
18832 		verbose(env, "\n");
18833 	}
18834 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18835 		"total_states %d peak_states %d mark_read %d\n",
18836 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18837 		env->max_states_per_insn, env->total_states,
18838 		env->peak_states, env->longest_mark_read_walk);
18839 }
18840 
18841 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18842 {
18843 	const struct btf_type *t, *func_proto;
18844 	const struct bpf_struct_ops *st_ops;
18845 	const struct btf_member *member;
18846 	struct bpf_prog *prog = env->prog;
18847 	u32 btf_id, member_idx;
18848 	const char *mname;
18849 
18850 	if (!prog->gpl_compatible) {
18851 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18852 		return -EINVAL;
18853 	}
18854 
18855 	btf_id = prog->aux->attach_btf_id;
18856 	st_ops = bpf_struct_ops_find(btf_id);
18857 	if (!st_ops) {
18858 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18859 			btf_id);
18860 		return -ENOTSUPP;
18861 	}
18862 
18863 	t = st_ops->type;
18864 	member_idx = prog->expected_attach_type;
18865 	if (member_idx >= btf_type_vlen(t)) {
18866 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18867 			member_idx, st_ops->name);
18868 		return -EINVAL;
18869 	}
18870 
18871 	member = &btf_type_member(t)[member_idx];
18872 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18873 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18874 					       NULL);
18875 	if (!func_proto) {
18876 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18877 			mname, member_idx, st_ops->name);
18878 		return -EINVAL;
18879 	}
18880 
18881 	if (st_ops->check_member) {
18882 		int err = st_ops->check_member(t, member, prog);
18883 
18884 		if (err) {
18885 			verbose(env, "attach to unsupported member %s of struct %s\n",
18886 				mname, st_ops->name);
18887 			return err;
18888 		}
18889 	}
18890 
18891 	prog->aux->attach_func_proto = func_proto;
18892 	prog->aux->attach_func_name = mname;
18893 	env->ops = st_ops->verifier_ops;
18894 
18895 	return 0;
18896 }
18897 #define SECURITY_PREFIX "security_"
18898 
18899 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18900 {
18901 	if (within_error_injection_list(addr) ||
18902 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18903 		return 0;
18904 
18905 	return -EINVAL;
18906 }
18907 
18908 /* list of non-sleepable functions that are otherwise on
18909  * ALLOW_ERROR_INJECTION list
18910  */
18911 BTF_SET_START(btf_non_sleepable_error_inject)
18912 /* Three functions below can be called from sleepable and non-sleepable context.
18913  * Assume non-sleepable from bpf safety point of view.
18914  */
18915 BTF_ID(func, __filemap_add_folio)
18916 BTF_ID(func, should_fail_alloc_page)
18917 BTF_ID(func, should_failslab)
18918 BTF_SET_END(btf_non_sleepable_error_inject)
18919 
18920 static int check_non_sleepable_error_inject(u32 btf_id)
18921 {
18922 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18923 }
18924 
18925 int bpf_check_attach_target(struct bpf_verifier_log *log,
18926 			    const struct bpf_prog *prog,
18927 			    const struct bpf_prog *tgt_prog,
18928 			    u32 btf_id,
18929 			    struct bpf_attach_target_info *tgt_info)
18930 {
18931 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18932 	const char prefix[] = "btf_trace_";
18933 	int ret = 0, subprog = -1, i;
18934 	const struct btf_type *t;
18935 	bool conservative = true;
18936 	const char *tname;
18937 	struct btf *btf;
18938 	long addr = 0;
18939 	struct module *mod = NULL;
18940 
18941 	if (!btf_id) {
18942 		bpf_log(log, "Tracing programs must provide btf_id\n");
18943 		return -EINVAL;
18944 	}
18945 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18946 	if (!btf) {
18947 		bpf_log(log,
18948 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18949 		return -EINVAL;
18950 	}
18951 	t = btf_type_by_id(btf, btf_id);
18952 	if (!t) {
18953 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18954 		return -EINVAL;
18955 	}
18956 	tname = btf_name_by_offset(btf, t->name_off);
18957 	if (!tname) {
18958 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18959 		return -EINVAL;
18960 	}
18961 	if (tgt_prog) {
18962 		struct bpf_prog_aux *aux = tgt_prog->aux;
18963 
18964 		if (bpf_prog_is_dev_bound(prog->aux) &&
18965 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18966 			bpf_log(log, "Target program bound device mismatch");
18967 			return -EINVAL;
18968 		}
18969 
18970 		for (i = 0; i < aux->func_info_cnt; i++)
18971 			if (aux->func_info[i].type_id == btf_id) {
18972 				subprog = i;
18973 				break;
18974 			}
18975 		if (subprog == -1) {
18976 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
18977 			return -EINVAL;
18978 		}
18979 		conservative = aux->func_info_aux[subprog].unreliable;
18980 		if (prog_extension) {
18981 			if (conservative) {
18982 				bpf_log(log,
18983 					"Cannot replace static functions\n");
18984 				return -EINVAL;
18985 			}
18986 			if (!prog->jit_requested) {
18987 				bpf_log(log,
18988 					"Extension programs should be JITed\n");
18989 				return -EINVAL;
18990 			}
18991 		}
18992 		if (!tgt_prog->jited) {
18993 			bpf_log(log, "Can attach to only JITed progs\n");
18994 			return -EINVAL;
18995 		}
18996 		if (tgt_prog->type == prog->type) {
18997 			/* Cannot fentry/fexit another fentry/fexit program.
18998 			 * Cannot attach program extension to another extension.
18999 			 * It's ok to attach fentry/fexit to extension program.
19000 			 */
19001 			bpf_log(log, "Cannot recursively attach\n");
19002 			return -EINVAL;
19003 		}
19004 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19005 		    prog_extension &&
19006 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19007 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19008 			/* Program extensions can extend all program types
19009 			 * except fentry/fexit. The reason is the following.
19010 			 * The fentry/fexit programs are used for performance
19011 			 * analysis, stats and can be attached to any program
19012 			 * type except themselves. When extension program is
19013 			 * replacing XDP function it is necessary to allow
19014 			 * performance analysis of all functions. Both original
19015 			 * XDP program and its program extension. Hence
19016 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19017 			 * allowed. If extending of fentry/fexit was allowed it
19018 			 * would be possible to create long call chain
19019 			 * fentry->extension->fentry->extension beyond
19020 			 * reasonable stack size. Hence extending fentry is not
19021 			 * allowed.
19022 			 */
19023 			bpf_log(log, "Cannot extend fentry/fexit\n");
19024 			return -EINVAL;
19025 		}
19026 	} else {
19027 		if (prog_extension) {
19028 			bpf_log(log, "Cannot replace kernel functions\n");
19029 			return -EINVAL;
19030 		}
19031 	}
19032 
19033 	switch (prog->expected_attach_type) {
19034 	case BPF_TRACE_RAW_TP:
19035 		if (tgt_prog) {
19036 			bpf_log(log,
19037 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19038 			return -EINVAL;
19039 		}
19040 		if (!btf_type_is_typedef(t)) {
19041 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19042 				btf_id);
19043 			return -EINVAL;
19044 		}
19045 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19046 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19047 				btf_id, tname);
19048 			return -EINVAL;
19049 		}
19050 		tname += sizeof(prefix) - 1;
19051 		t = btf_type_by_id(btf, t->type);
19052 		if (!btf_type_is_ptr(t))
19053 			/* should never happen in valid vmlinux build */
19054 			return -EINVAL;
19055 		t = btf_type_by_id(btf, t->type);
19056 		if (!btf_type_is_func_proto(t))
19057 			/* should never happen in valid vmlinux build */
19058 			return -EINVAL;
19059 
19060 		break;
19061 	case BPF_TRACE_ITER:
19062 		if (!btf_type_is_func(t)) {
19063 			bpf_log(log, "attach_btf_id %u is not a function\n",
19064 				btf_id);
19065 			return -EINVAL;
19066 		}
19067 		t = btf_type_by_id(btf, t->type);
19068 		if (!btf_type_is_func_proto(t))
19069 			return -EINVAL;
19070 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19071 		if (ret)
19072 			return ret;
19073 		break;
19074 	default:
19075 		if (!prog_extension)
19076 			return -EINVAL;
19077 		fallthrough;
19078 	case BPF_MODIFY_RETURN:
19079 	case BPF_LSM_MAC:
19080 	case BPF_LSM_CGROUP:
19081 	case BPF_TRACE_FENTRY:
19082 	case BPF_TRACE_FEXIT:
19083 		if (!btf_type_is_func(t)) {
19084 			bpf_log(log, "attach_btf_id %u is not a function\n",
19085 				btf_id);
19086 			return -EINVAL;
19087 		}
19088 		if (prog_extension &&
19089 		    btf_check_type_match(log, prog, btf, t))
19090 			return -EINVAL;
19091 		t = btf_type_by_id(btf, t->type);
19092 		if (!btf_type_is_func_proto(t))
19093 			return -EINVAL;
19094 
19095 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19096 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19097 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19098 			return -EINVAL;
19099 
19100 		if (tgt_prog && conservative)
19101 			t = NULL;
19102 
19103 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19104 		if (ret < 0)
19105 			return ret;
19106 
19107 		if (tgt_prog) {
19108 			if (subprog == 0)
19109 				addr = (long) tgt_prog->bpf_func;
19110 			else
19111 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19112 		} else {
19113 			if (btf_is_module(btf)) {
19114 				mod = btf_try_get_module(btf);
19115 				if (mod)
19116 					addr = find_kallsyms_symbol_value(mod, tname);
19117 				else
19118 					addr = 0;
19119 			} else {
19120 				addr = kallsyms_lookup_name(tname);
19121 			}
19122 			if (!addr) {
19123 				module_put(mod);
19124 				bpf_log(log,
19125 					"The address of function %s cannot be found\n",
19126 					tname);
19127 				return -ENOENT;
19128 			}
19129 		}
19130 
19131 		if (prog->aux->sleepable) {
19132 			ret = -EINVAL;
19133 			switch (prog->type) {
19134 			case BPF_PROG_TYPE_TRACING:
19135 
19136 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
19137 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19138 				 */
19139 				if (!check_non_sleepable_error_inject(btf_id) &&
19140 				    within_error_injection_list(addr))
19141 					ret = 0;
19142 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
19143 				 * in the fmodret id set with the KF_SLEEPABLE flag.
19144 				 */
19145 				else {
19146 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19147 										prog);
19148 
19149 					if (flags && (*flags & KF_SLEEPABLE))
19150 						ret = 0;
19151 				}
19152 				break;
19153 			case BPF_PROG_TYPE_LSM:
19154 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
19155 				 * Only some of them are sleepable.
19156 				 */
19157 				if (bpf_lsm_is_sleepable_hook(btf_id))
19158 					ret = 0;
19159 				break;
19160 			default:
19161 				break;
19162 			}
19163 			if (ret) {
19164 				module_put(mod);
19165 				bpf_log(log, "%s is not sleepable\n", tname);
19166 				return ret;
19167 			}
19168 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19169 			if (tgt_prog) {
19170 				module_put(mod);
19171 				bpf_log(log, "can't modify return codes of BPF programs\n");
19172 				return -EINVAL;
19173 			}
19174 			ret = -EINVAL;
19175 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19176 			    !check_attach_modify_return(addr, tname))
19177 				ret = 0;
19178 			if (ret) {
19179 				module_put(mod);
19180 				bpf_log(log, "%s() is not modifiable\n", tname);
19181 				return ret;
19182 			}
19183 		}
19184 
19185 		break;
19186 	}
19187 	tgt_info->tgt_addr = addr;
19188 	tgt_info->tgt_name = tname;
19189 	tgt_info->tgt_type = t;
19190 	tgt_info->tgt_mod = mod;
19191 	return 0;
19192 }
19193 
19194 BTF_SET_START(btf_id_deny)
19195 BTF_ID_UNUSED
19196 #ifdef CONFIG_SMP
19197 BTF_ID(func, migrate_disable)
19198 BTF_ID(func, migrate_enable)
19199 #endif
19200 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19201 BTF_ID(func, rcu_read_unlock_strict)
19202 #endif
19203 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19204 BTF_ID(func, preempt_count_add)
19205 BTF_ID(func, preempt_count_sub)
19206 #endif
19207 #ifdef CONFIG_PREEMPT_RCU
19208 BTF_ID(func, __rcu_read_lock)
19209 BTF_ID(func, __rcu_read_unlock)
19210 #endif
19211 BTF_SET_END(btf_id_deny)
19212 
19213 static bool can_be_sleepable(struct bpf_prog *prog)
19214 {
19215 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19216 		switch (prog->expected_attach_type) {
19217 		case BPF_TRACE_FENTRY:
19218 		case BPF_TRACE_FEXIT:
19219 		case BPF_MODIFY_RETURN:
19220 		case BPF_TRACE_ITER:
19221 			return true;
19222 		default:
19223 			return false;
19224 		}
19225 	}
19226 	return prog->type == BPF_PROG_TYPE_LSM ||
19227 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19228 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19229 }
19230 
19231 static int check_attach_btf_id(struct bpf_verifier_env *env)
19232 {
19233 	struct bpf_prog *prog = env->prog;
19234 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19235 	struct bpf_attach_target_info tgt_info = {};
19236 	u32 btf_id = prog->aux->attach_btf_id;
19237 	struct bpf_trampoline *tr;
19238 	int ret;
19239 	u64 key;
19240 
19241 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19242 		if (prog->aux->sleepable)
19243 			/* attach_btf_id checked to be zero already */
19244 			return 0;
19245 		verbose(env, "Syscall programs can only be sleepable\n");
19246 		return -EINVAL;
19247 	}
19248 
19249 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19250 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19251 		return -EINVAL;
19252 	}
19253 
19254 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19255 		return check_struct_ops_btf_id(env);
19256 
19257 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19258 	    prog->type != BPF_PROG_TYPE_LSM &&
19259 	    prog->type != BPF_PROG_TYPE_EXT)
19260 		return 0;
19261 
19262 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19263 	if (ret)
19264 		return ret;
19265 
19266 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19267 		/* to make freplace equivalent to their targets, they need to
19268 		 * inherit env->ops and expected_attach_type for the rest of the
19269 		 * verification
19270 		 */
19271 		env->ops = bpf_verifier_ops[tgt_prog->type];
19272 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19273 	}
19274 
19275 	/* store info about the attachment target that will be used later */
19276 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19277 	prog->aux->attach_func_name = tgt_info.tgt_name;
19278 	prog->aux->mod = tgt_info.tgt_mod;
19279 
19280 	if (tgt_prog) {
19281 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19282 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19283 	}
19284 
19285 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19286 		prog->aux->attach_btf_trace = true;
19287 		return 0;
19288 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19289 		if (!bpf_iter_prog_supported(prog))
19290 			return -EINVAL;
19291 		return 0;
19292 	}
19293 
19294 	if (prog->type == BPF_PROG_TYPE_LSM) {
19295 		ret = bpf_lsm_verify_prog(&env->log, prog);
19296 		if (ret < 0)
19297 			return ret;
19298 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19299 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19300 		return -EINVAL;
19301 	}
19302 
19303 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19304 	tr = bpf_trampoline_get(key, &tgt_info);
19305 	if (!tr)
19306 		return -ENOMEM;
19307 
19308 	prog->aux->dst_trampoline = tr;
19309 	return 0;
19310 }
19311 
19312 struct btf *bpf_get_btf_vmlinux(void)
19313 {
19314 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19315 		mutex_lock(&bpf_verifier_lock);
19316 		if (!btf_vmlinux)
19317 			btf_vmlinux = btf_parse_vmlinux();
19318 		mutex_unlock(&bpf_verifier_lock);
19319 	}
19320 	return btf_vmlinux;
19321 }
19322 
19323 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19324 {
19325 	u64 start_time = ktime_get_ns();
19326 	struct bpf_verifier_env *env;
19327 	int i, len, ret = -EINVAL, err;
19328 	u32 log_true_size;
19329 	bool is_priv;
19330 
19331 	/* no program is valid */
19332 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19333 		return -EINVAL;
19334 
19335 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19336 	 * allocate/free it every time bpf_check() is called
19337 	 */
19338 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19339 	if (!env)
19340 		return -ENOMEM;
19341 
19342 	env->bt.env = env;
19343 
19344 	len = (*prog)->len;
19345 	env->insn_aux_data =
19346 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19347 	ret = -ENOMEM;
19348 	if (!env->insn_aux_data)
19349 		goto err_free_env;
19350 	for (i = 0; i < len; i++)
19351 		env->insn_aux_data[i].orig_idx = i;
19352 	env->prog = *prog;
19353 	env->ops = bpf_verifier_ops[env->prog->type];
19354 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19355 	is_priv = bpf_capable();
19356 
19357 	bpf_get_btf_vmlinux();
19358 
19359 	/* grab the mutex to protect few globals used by verifier */
19360 	if (!is_priv)
19361 		mutex_lock(&bpf_verifier_lock);
19362 
19363 	/* user could have requested verbose verifier output
19364 	 * and supplied buffer to store the verification trace
19365 	 */
19366 	ret = bpf_vlog_init(&env->log, attr->log_level,
19367 			    (char __user *) (unsigned long) attr->log_buf,
19368 			    attr->log_size);
19369 	if (ret)
19370 		goto err_unlock;
19371 
19372 	mark_verifier_state_clean(env);
19373 
19374 	if (IS_ERR(btf_vmlinux)) {
19375 		/* Either gcc or pahole or kernel are broken. */
19376 		verbose(env, "in-kernel BTF is malformed\n");
19377 		ret = PTR_ERR(btf_vmlinux);
19378 		goto skip_full_check;
19379 	}
19380 
19381 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19382 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19383 		env->strict_alignment = true;
19384 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19385 		env->strict_alignment = false;
19386 
19387 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19388 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19389 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19390 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19391 	env->bpf_capable = bpf_capable();
19392 
19393 	if (is_priv)
19394 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19395 
19396 	env->explored_states = kvcalloc(state_htab_size(env),
19397 				       sizeof(struct bpf_verifier_state_list *),
19398 				       GFP_USER);
19399 	ret = -ENOMEM;
19400 	if (!env->explored_states)
19401 		goto skip_full_check;
19402 
19403 	ret = add_subprog_and_kfunc(env);
19404 	if (ret < 0)
19405 		goto skip_full_check;
19406 
19407 	ret = check_subprogs(env);
19408 	if (ret < 0)
19409 		goto skip_full_check;
19410 
19411 	ret = check_btf_info(env, attr, uattr);
19412 	if (ret < 0)
19413 		goto skip_full_check;
19414 
19415 	ret = check_attach_btf_id(env);
19416 	if (ret)
19417 		goto skip_full_check;
19418 
19419 	ret = resolve_pseudo_ldimm64(env);
19420 	if (ret < 0)
19421 		goto skip_full_check;
19422 
19423 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19424 		ret = bpf_prog_offload_verifier_prep(env->prog);
19425 		if (ret)
19426 			goto skip_full_check;
19427 	}
19428 
19429 	ret = check_cfg(env);
19430 	if (ret < 0)
19431 		goto skip_full_check;
19432 
19433 	ret = do_check_subprogs(env);
19434 	ret = ret ?: do_check_main(env);
19435 
19436 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19437 		ret = bpf_prog_offload_finalize(env);
19438 
19439 skip_full_check:
19440 	kvfree(env->explored_states);
19441 
19442 	if (ret == 0)
19443 		ret = check_max_stack_depth(env);
19444 
19445 	/* instruction rewrites happen after this point */
19446 	if (ret == 0)
19447 		ret = optimize_bpf_loop(env);
19448 
19449 	if (is_priv) {
19450 		if (ret == 0)
19451 			opt_hard_wire_dead_code_branches(env);
19452 		if (ret == 0)
19453 			ret = opt_remove_dead_code(env);
19454 		if (ret == 0)
19455 			ret = opt_remove_nops(env);
19456 	} else {
19457 		if (ret == 0)
19458 			sanitize_dead_code(env);
19459 	}
19460 
19461 	if (ret == 0)
19462 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19463 		ret = convert_ctx_accesses(env);
19464 
19465 	if (ret == 0)
19466 		ret = do_misc_fixups(env);
19467 
19468 	/* do 32-bit optimization after insn patching has done so those patched
19469 	 * insns could be handled correctly.
19470 	 */
19471 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19472 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19473 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19474 								     : false;
19475 	}
19476 
19477 	if (ret == 0)
19478 		ret = fixup_call_args(env);
19479 
19480 	env->verification_time = ktime_get_ns() - start_time;
19481 	print_verification_stats(env);
19482 	env->prog->aux->verified_insns = env->insn_processed;
19483 
19484 	/* preserve original error even if log finalization is successful */
19485 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19486 	if (err)
19487 		ret = err;
19488 
19489 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19490 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19491 				  &log_true_size, sizeof(log_true_size))) {
19492 		ret = -EFAULT;
19493 		goto err_release_maps;
19494 	}
19495 
19496 	if (ret)
19497 		goto err_release_maps;
19498 
19499 	if (env->used_map_cnt) {
19500 		/* if program passed verifier, update used_maps in bpf_prog_info */
19501 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19502 							  sizeof(env->used_maps[0]),
19503 							  GFP_KERNEL);
19504 
19505 		if (!env->prog->aux->used_maps) {
19506 			ret = -ENOMEM;
19507 			goto err_release_maps;
19508 		}
19509 
19510 		memcpy(env->prog->aux->used_maps, env->used_maps,
19511 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19512 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19513 	}
19514 	if (env->used_btf_cnt) {
19515 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19516 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19517 							  sizeof(env->used_btfs[0]),
19518 							  GFP_KERNEL);
19519 		if (!env->prog->aux->used_btfs) {
19520 			ret = -ENOMEM;
19521 			goto err_release_maps;
19522 		}
19523 
19524 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19525 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19526 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19527 	}
19528 	if (env->used_map_cnt || env->used_btf_cnt) {
19529 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19530 		 * bpf_ld_imm64 instructions
19531 		 */
19532 		convert_pseudo_ld_imm64(env);
19533 	}
19534 
19535 	adjust_btf_func(env);
19536 
19537 err_release_maps:
19538 	if (!env->prog->aux->used_maps)
19539 		/* if we didn't copy map pointers into bpf_prog_info, release
19540 		 * them now. Otherwise free_used_maps() will release them.
19541 		 */
19542 		release_maps(env);
19543 	if (!env->prog->aux->used_btfs)
19544 		release_btfs(env);
19545 
19546 	/* extension progs temporarily inherit the attach_type of their targets
19547 	   for verification purposes, so set it back to zero before returning
19548 	 */
19549 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19550 		env->prog->expected_attach_type = 0;
19551 
19552 	*prog = env->prog;
19553 err_unlock:
19554 	if (!is_priv)
19555 		mutex_unlock(&bpf_verifier_lock);
19556 	vfree(env->insn_aux_data);
19557 err_free_env:
19558 	kfree(env);
19559 	return ret;
19560 }
19561