xref: /openbmc/linux/kernel/bpf/verifier.c (revision 882cdb06)
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 		/* Break the relation on a narrowing spill. */
4349 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4350 			state->stack[spi].spilled_ptr.id = 0;
4351 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4352 		   insn->imm != 0 && env->bpf_capable) {
4353 		struct bpf_reg_state fake_reg = {};
4354 
4355 		__mark_reg_known(&fake_reg, (u32)insn->imm);
4356 		fake_reg.type = SCALAR_VALUE;
4357 		save_register_state(state, spi, &fake_reg, size);
4358 	} else if (reg && is_spillable_regtype(reg->type)) {
4359 		/* register containing pointer is being spilled into stack */
4360 		if (size != BPF_REG_SIZE) {
4361 			verbose_linfo(env, insn_idx, "; ");
4362 			verbose(env, "invalid size of register spill\n");
4363 			return -EACCES;
4364 		}
4365 		if (state != cur && reg->type == PTR_TO_STACK) {
4366 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4367 			return -EINVAL;
4368 		}
4369 		save_register_state(state, spi, reg, size);
4370 	} else {
4371 		u8 type = STACK_MISC;
4372 
4373 		/* regular write of data into stack destroys any spilled ptr */
4374 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4375 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4376 		if (is_stack_slot_special(&state->stack[spi]))
4377 			for (i = 0; i < BPF_REG_SIZE; i++)
4378 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4379 
4380 		/* only mark the slot as written if all 8 bytes were written
4381 		 * otherwise read propagation may incorrectly stop too soon
4382 		 * when stack slots are partially written.
4383 		 * This heuristic means that read propagation will be
4384 		 * conservative, since it will add reg_live_read marks
4385 		 * to stack slots all the way to first state when programs
4386 		 * writes+reads less than 8 bytes
4387 		 */
4388 		if (size == BPF_REG_SIZE)
4389 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4390 
4391 		/* when we zero initialize stack slots mark them as such */
4392 		if ((reg && register_is_null(reg)) ||
4393 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4394 			/* backtracking doesn't work for STACK_ZERO yet. */
4395 			err = mark_chain_precision(env, value_regno);
4396 			if (err)
4397 				return err;
4398 			type = STACK_ZERO;
4399 		}
4400 
4401 		/* Mark slots affected by this stack write. */
4402 		for (i = 0; i < size; i++)
4403 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4404 				type;
4405 	}
4406 	return 0;
4407 }
4408 
4409 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4410  * known to contain a variable offset.
4411  * This function checks whether the write is permitted and conservatively
4412  * tracks the effects of the write, considering that each stack slot in the
4413  * dynamic range is potentially written to.
4414  *
4415  * 'off' includes 'regno->off'.
4416  * 'value_regno' can be -1, meaning that an unknown value is being written to
4417  * the stack.
4418  *
4419  * Spilled pointers in range are not marked as written because we don't know
4420  * what's going to be actually written. This means that read propagation for
4421  * future reads cannot be terminated by this write.
4422  *
4423  * For privileged programs, uninitialized stack slots are considered
4424  * initialized by this write (even though we don't know exactly what offsets
4425  * are going to be written to). The idea is that we don't want the verifier to
4426  * reject future reads that access slots written to through variable offsets.
4427  */
4428 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4429 				     /* func where register points to */
4430 				     struct bpf_func_state *state,
4431 				     int ptr_regno, int off, int size,
4432 				     int value_regno, int insn_idx)
4433 {
4434 	struct bpf_func_state *cur; /* state of the current function */
4435 	int min_off, max_off;
4436 	int i, err;
4437 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4438 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4439 	bool writing_zero = false;
4440 	/* set if the fact that we're writing a zero is used to let any
4441 	 * stack slots remain STACK_ZERO
4442 	 */
4443 	bool zero_used = false;
4444 
4445 	cur = env->cur_state->frame[env->cur_state->curframe];
4446 	ptr_reg = &cur->regs[ptr_regno];
4447 	min_off = ptr_reg->smin_value + off;
4448 	max_off = ptr_reg->smax_value + off + size;
4449 	if (value_regno >= 0)
4450 		value_reg = &cur->regs[value_regno];
4451 	if ((value_reg && register_is_null(value_reg)) ||
4452 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4453 		writing_zero = true;
4454 
4455 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4456 	if (err)
4457 		return err;
4458 
4459 	for (i = min_off; i < max_off; i++) {
4460 		int spi;
4461 
4462 		spi = __get_spi(i);
4463 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4464 		if (err)
4465 			return err;
4466 	}
4467 
4468 	/* Variable offset writes destroy any spilled pointers in range. */
4469 	for (i = min_off; i < max_off; i++) {
4470 		u8 new_type, *stype;
4471 		int slot, spi;
4472 
4473 		slot = -i - 1;
4474 		spi = slot / BPF_REG_SIZE;
4475 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4476 		mark_stack_slot_scratched(env, spi);
4477 
4478 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4479 			/* Reject the write if range we may write to has not
4480 			 * been initialized beforehand. If we didn't reject
4481 			 * here, the ptr status would be erased below (even
4482 			 * though not all slots are actually overwritten),
4483 			 * possibly opening the door to leaks.
4484 			 *
4485 			 * We do however catch STACK_INVALID case below, and
4486 			 * only allow reading possibly uninitialized memory
4487 			 * later for CAP_PERFMON, as the write may not happen to
4488 			 * that slot.
4489 			 */
4490 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4491 				insn_idx, i);
4492 			return -EINVAL;
4493 		}
4494 
4495 		/* Erase all spilled pointers. */
4496 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4497 
4498 		/* Update the slot type. */
4499 		new_type = STACK_MISC;
4500 		if (writing_zero && *stype == STACK_ZERO) {
4501 			new_type = STACK_ZERO;
4502 			zero_used = true;
4503 		}
4504 		/* If the slot is STACK_INVALID, we check whether it's OK to
4505 		 * pretend that it will be initialized by this write. The slot
4506 		 * might not actually be written to, and so if we mark it as
4507 		 * initialized future reads might leak uninitialized memory.
4508 		 * For privileged programs, we will accept such reads to slots
4509 		 * that may or may not be written because, if we're reject
4510 		 * them, the error would be too confusing.
4511 		 */
4512 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4513 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4514 					insn_idx, i);
4515 			return -EINVAL;
4516 		}
4517 		*stype = new_type;
4518 	}
4519 	if (zero_used) {
4520 		/* backtracking doesn't work for STACK_ZERO yet. */
4521 		err = mark_chain_precision(env, value_regno);
4522 		if (err)
4523 			return err;
4524 	}
4525 	return 0;
4526 }
4527 
4528 /* When register 'dst_regno' is assigned some values from stack[min_off,
4529  * max_off), we set the register's type according to the types of the
4530  * respective stack slots. If all the stack values are known to be zeros, then
4531  * so is the destination reg. Otherwise, the register is considered to be
4532  * SCALAR. This function does not deal with register filling; the caller must
4533  * ensure that all spilled registers in the stack range have been marked as
4534  * read.
4535  */
4536 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4537 				/* func where src register points to */
4538 				struct bpf_func_state *ptr_state,
4539 				int min_off, int max_off, int dst_regno)
4540 {
4541 	struct bpf_verifier_state *vstate = env->cur_state;
4542 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4543 	int i, slot, spi;
4544 	u8 *stype;
4545 	int zeros = 0;
4546 
4547 	for (i = min_off; i < max_off; i++) {
4548 		slot = -i - 1;
4549 		spi = slot / BPF_REG_SIZE;
4550 		mark_stack_slot_scratched(env, spi);
4551 		stype = ptr_state->stack[spi].slot_type;
4552 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4553 			break;
4554 		zeros++;
4555 	}
4556 	if (zeros == max_off - min_off) {
4557 		/* any access_size read into register is zero extended,
4558 		 * so the whole register == const_zero
4559 		 */
4560 		__mark_reg_const_zero(&state->regs[dst_regno]);
4561 		/* backtracking doesn't support STACK_ZERO yet,
4562 		 * so mark it precise here, so that later
4563 		 * backtracking can stop here.
4564 		 * Backtracking may not need this if this register
4565 		 * doesn't participate in pointer adjustment.
4566 		 * Forward propagation of precise flag is not
4567 		 * necessary either. This mark is only to stop
4568 		 * backtracking. Any register that contributed
4569 		 * to const 0 was marked precise before spill.
4570 		 */
4571 		state->regs[dst_regno].precise = true;
4572 	} else {
4573 		/* have read misc data from the stack */
4574 		mark_reg_unknown(env, state->regs, dst_regno);
4575 	}
4576 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4577 }
4578 
4579 /* Read the stack at 'off' and put the results into the register indicated by
4580  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4581  * spilled reg.
4582  *
4583  * 'dst_regno' can be -1, meaning that the read value is not going to a
4584  * register.
4585  *
4586  * The access is assumed to be within the current stack bounds.
4587  */
4588 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4589 				      /* func where src register points to */
4590 				      struct bpf_func_state *reg_state,
4591 				      int off, int size, int dst_regno)
4592 {
4593 	struct bpf_verifier_state *vstate = env->cur_state;
4594 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4595 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4596 	struct bpf_reg_state *reg;
4597 	u8 *stype, type;
4598 
4599 	stype = reg_state->stack[spi].slot_type;
4600 	reg = &reg_state->stack[spi].spilled_ptr;
4601 
4602 	mark_stack_slot_scratched(env, spi);
4603 
4604 	if (is_spilled_reg(&reg_state->stack[spi])) {
4605 		u8 spill_size = 1;
4606 
4607 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4608 			spill_size++;
4609 
4610 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4611 			if (reg->type != SCALAR_VALUE) {
4612 				verbose_linfo(env, env->insn_idx, "; ");
4613 				verbose(env, "invalid size of register fill\n");
4614 				return -EACCES;
4615 			}
4616 
4617 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4618 			if (dst_regno < 0)
4619 				return 0;
4620 
4621 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4622 				/* The earlier check_reg_arg() has decided the
4623 				 * subreg_def for this insn.  Save it first.
4624 				 */
4625 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4626 
4627 				copy_register_state(&state->regs[dst_regno], reg);
4628 				state->regs[dst_regno].subreg_def = subreg_def;
4629 			} else {
4630 				for (i = 0; i < size; i++) {
4631 					type = stype[(slot - i) % BPF_REG_SIZE];
4632 					if (type == STACK_SPILL)
4633 						continue;
4634 					if (type == STACK_MISC)
4635 						continue;
4636 					if (type == STACK_INVALID && env->allow_uninit_stack)
4637 						continue;
4638 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4639 						off, i, size);
4640 					return -EACCES;
4641 				}
4642 				mark_reg_unknown(env, state->regs, dst_regno);
4643 			}
4644 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4645 			return 0;
4646 		}
4647 
4648 		if (dst_regno >= 0) {
4649 			/* restore register state from stack */
4650 			copy_register_state(&state->regs[dst_regno], reg);
4651 			/* mark reg as written since spilled pointer state likely
4652 			 * has its liveness marks cleared by is_state_visited()
4653 			 * which resets stack/reg liveness for state transitions
4654 			 */
4655 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4656 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4657 			/* If dst_regno==-1, the caller is asking us whether
4658 			 * it is acceptable to use this value as a SCALAR_VALUE
4659 			 * (e.g. for XADD).
4660 			 * We must not allow unprivileged callers to do that
4661 			 * with spilled pointers.
4662 			 */
4663 			verbose(env, "leaking pointer from stack off %d\n",
4664 				off);
4665 			return -EACCES;
4666 		}
4667 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4668 	} else {
4669 		for (i = 0; i < size; i++) {
4670 			type = stype[(slot - i) % BPF_REG_SIZE];
4671 			if (type == STACK_MISC)
4672 				continue;
4673 			if (type == STACK_ZERO)
4674 				continue;
4675 			if (type == STACK_INVALID && env->allow_uninit_stack)
4676 				continue;
4677 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4678 				off, i, size);
4679 			return -EACCES;
4680 		}
4681 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4682 		if (dst_regno >= 0)
4683 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4684 	}
4685 	return 0;
4686 }
4687 
4688 enum bpf_access_src {
4689 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4690 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4691 };
4692 
4693 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4694 					 int regno, int off, int access_size,
4695 					 bool zero_size_allowed,
4696 					 enum bpf_access_src type,
4697 					 struct bpf_call_arg_meta *meta);
4698 
4699 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4700 {
4701 	return cur_regs(env) + regno;
4702 }
4703 
4704 /* Read the stack at 'ptr_regno + off' and put the result into the register
4705  * 'dst_regno'.
4706  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4707  * but not its variable offset.
4708  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4709  *
4710  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4711  * filling registers (i.e. reads of spilled register cannot be detected when
4712  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4713  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4714  * offset; for a fixed offset check_stack_read_fixed_off should be used
4715  * instead.
4716  */
4717 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4718 				    int ptr_regno, int off, int size, int dst_regno)
4719 {
4720 	/* The state of the source register. */
4721 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4722 	struct bpf_func_state *ptr_state = func(env, reg);
4723 	int err;
4724 	int min_off, max_off;
4725 
4726 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4727 	 */
4728 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4729 					    false, ACCESS_DIRECT, NULL);
4730 	if (err)
4731 		return err;
4732 
4733 	min_off = reg->smin_value + off;
4734 	max_off = reg->smax_value + off;
4735 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4736 	return 0;
4737 }
4738 
4739 /* check_stack_read dispatches to check_stack_read_fixed_off or
4740  * check_stack_read_var_off.
4741  *
4742  * The caller must ensure that the offset falls within the allocated stack
4743  * bounds.
4744  *
4745  * 'dst_regno' is a register which will receive the value from the stack. It
4746  * can be -1, meaning that the read value is not going to a register.
4747  */
4748 static int check_stack_read(struct bpf_verifier_env *env,
4749 			    int ptr_regno, int off, int size,
4750 			    int dst_regno)
4751 {
4752 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4753 	struct bpf_func_state *state = func(env, reg);
4754 	int err;
4755 	/* Some accesses are only permitted with a static offset. */
4756 	bool var_off = !tnum_is_const(reg->var_off);
4757 
4758 	/* The offset is required to be static when reads don't go to a
4759 	 * register, in order to not leak pointers (see
4760 	 * check_stack_read_fixed_off).
4761 	 */
4762 	if (dst_regno < 0 && var_off) {
4763 		char tn_buf[48];
4764 
4765 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4766 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4767 			tn_buf, off, size);
4768 		return -EACCES;
4769 	}
4770 	/* Variable offset is prohibited for unprivileged mode for simplicity
4771 	 * since it requires corresponding support in Spectre masking for stack
4772 	 * ALU. See also retrieve_ptr_limit(). The check in
4773 	 * check_stack_access_for_ptr_arithmetic() called by
4774 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4775 	 * with variable offsets, therefore no check is required here. Further,
4776 	 * just checking it here would be insufficient as speculative stack
4777 	 * writes could still lead to unsafe speculative behaviour.
4778 	 */
4779 	if (!var_off) {
4780 		off += reg->var_off.value;
4781 		err = check_stack_read_fixed_off(env, state, off, size,
4782 						 dst_regno);
4783 	} else {
4784 		/* Variable offset stack reads need more conservative handling
4785 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4786 		 * branch.
4787 		 */
4788 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4789 					       dst_regno);
4790 	}
4791 	return err;
4792 }
4793 
4794 
4795 /* check_stack_write dispatches to check_stack_write_fixed_off or
4796  * check_stack_write_var_off.
4797  *
4798  * 'ptr_regno' is the register used as a pointer into the stack.
4799  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4800  * 'value_regno' is the register whose value we're writing to the stack. It can
4801  * be -1, meaning that we're not writing from a register.
4802  *
4803  * The caller must ensure that the offset falls within the maximum stack size.
4804  */
4805 static int check_stack_write(struct bpf_verifier_env *env,
4806 			     int ptr_regno, int off, int size,
4807 			     int value_regno, int insn_idx)
4808 {
4809 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4810 	struct bpf_func_state *state = func(env, reg);
4811 	int err;
4812 
4813 	if (tnum_is_const(reg->var_off)) {
4814 		off += reg->var_off.value;
4815 		err = check_stack_write_fixed_off(env, state, off, size,
4816 						  value_regno, insn_idx);
4817 	} else {
4818 		/* Variable offset stack reads need more conservative handling
4819 		 * than fixed offset ones.
4820 		 */
4821 		err = check_stack_write_var_off(env, state,
4822 						ptr_regno, off, size,
4823 						value_regno, insn_idx);
4824 	}
4825 	return err;
4826 }
4827 
4828 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4829 				 int off, int size, enum bpf_access_type type)
4830 {
4831 	struct bpf_reg_state *regs = cur_regs(env);
4832 	struct bpf_map *map = regs[regno].map_ptr;
4833 	u32 cap = bpf_map_flags_to_cap(map);
4834 
4835 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4836 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4837 			map->value_size, off, size);
4838 		return -EACCES;
4839 	}
4840 
4841 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4842 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4843 			map->value_size, off, size);
4844 		return -EACCES;
4845 	}
4846 
4847 	return 0;
4848 }
4849 
4850 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4851 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4852 			      int off, int size, u32 mem_size,
4853 			      bool zero_size_allowed)
4854 {
4855 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4856 	struct bpf_reg_state *reg;
4857 
4858 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4859 		return 0;
4860 
4861 	reg = &cur_regs(env)[regno];
4862 	switch (reg->type) {
4863 	case PTR_TO_MAP_KEY:
4864 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4865 			mem_size, off, size);
4866 		break;
4867 	case PTR_TO_MAP_VALUE:
4868 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4869 			mem_size, off, size);
4870 		break;
4871 	case PTR_TO_PACKET:
4872 	case PTR_TO_PACKET_META:
4873 	case PTR_TO_PACKET_END:
4874 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4875 			off, size, regno, reg->id, off, mem_size);
4876 		break;
4877 	case PTR_TO_MEM:
4878 	default:
4879 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4880 			mem_size, off, size);
4881 	}
4882 
4883 	return -EACCES;
4884 }
4885 
4886 /* check read/write into a memory region with possible variable offset */
4887 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4888 				   int off, int size, u32 mem_size,
4889 				   bool zero_size_allowed)
4890 {
4891 	struct bpf_verifier_state *vstate = env->cur_state;
4892 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4893 	struct bpf_reg_state *reg = &state->regs[regno];
4894 	int err;
4895 
4896 	/* We may have adjusted the register pointing to memory region, so we
4897 	 * need to try adding each of min_value and max_value to off
4898 	 * to make sure our theoretical access will be safe.
4899 	 *
4900 	 * The minimum value is only important with signed
4901 	 * comparisons where we can't assume the floor of a
4902 	 * value is 0.  If we are using signed variables for our
4903 	 * index'es we need to make sure that whatever we use
4904 	 * will have a set floor within our range.
4905 	 */
4906 	if (reg->smin_value < 0 &&
4907 	    (reg->smin_value == S64_MIN ||
4908 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4909 	      reg->smin_value + off < 0)) {
4910 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4911 			regno);
4912 		return -EACCES;
4913 	}
4914 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4915 				 mem_size, zero_size_allowed);
4916 	if (err) {
4917 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4918 			regno);
4919 		return err;
4920 	}
4921 
4922 	/* If we haven't set a max value then we need to bail since we can't be
4923 	 * sure we won't do bad things.
4924 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4925 	 */
4926 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4927 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4928 			regno);
4929 		return -EACCES;
4930 	}
4931 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4932 				 mem_size, zero_size_allowed);
4933 	if (err) {
4934 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4935 			regno);
4936 		return err;
4937 	}
4938 
4939 	return 0;
4940 }
4941 
4942 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4943 			       const struct bpf_reg_state *reg, int regno,
4944 			       bool fixed_off_ok)
4945 {
4946 	/* Access to this pointer-typed register or passing it to a helper
4947 	 * is only allowed in its original, unmodified form.
4948 	 */
4949 
4950 	if (reg->off < 0) {
4951 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4952 			reg_type_str(env, reg->type), regno, reg->off);
4953 		return -EACCES;
4954 	}
4955 
4956 	if (!fixed_off_ok && reg->off) {
4957 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4958 			reg_type_str(env, reg->type), regno, reg->off);
4959 		return -EACCES;
4960 	}
4961 
4962 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4963 		char tn_buf[48];
4964 
4965 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4966 		verbose(env, "variable %s access var_off=%s disallowed\n",
4967 			reg_type_str(env, reg->type), tn_buf);
4968 		return -EACCES;
4969 	}
4970 
4971 	return 0;
4972 }
4973 
4974 int check_ptr_off_reg(struct bpf_verifier_env *env,
4975 		      const struct bpf_reg_state *reg, int regno)
4976 {
4977 	return __check_ptr_off_reg(env, reg, regno, false);
4978 }
4979 
4980 static int map_kptr_match_type(struct bpf_verifier_env *env,
4981 			       struct btf_field *kptr_field,
4982 			       struct bpf_reg_state *reg, u32 regno)
4983 {
4984 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4985 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4986 	const char *reg_name = "";
4987 
4988 	/* Only unreferenced case accepts untrusted pointers */
4989 	if (kptr_field->type == BPF_KPTR_UNREF)
4990 		perm_flags |= PTR_UNTRUSTED;
4991 
4992 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4993 		goto bad_type;
4994 
4995 	if (!btf_is_kernel(reg->btf)) {
4996 		verbose(env, "R%d must point to kernel BTF\n", regno);
4997 		return -EINVAL;
4998 	}
4999 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5000 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5001 
5002 	/* For ref_ptr case, release function check should ensure we get one
5003 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5004 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5005 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5006 	 * reg->off and reg->ref_obj_id are not needed here.
5007 	 */
5008 	if (__check_ptr_off_reg(env, reg, regno, true))
5009 		return -EACCES;
5010 
5011 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
5012 	 * we also need to take into account the reg->off.
5013 	 *
5014 	 * We want to support cases like:
5015 	 *
5016 	 * struct foo {
5017 	 *         struct bar br;
5018 	 *         struct baz bz;
5019 	 * };
5020 	 *
5021 	 * struct foo *v;
5022 	 * v = func();	      // PTR_TO_BTF_ID
5023 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5024 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5025 	 *                    // first member type of struct after comparison fails
5026 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5027 	 *                    // to match type
5028 	 *
5029 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5030 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5031 	 * the struct to match type against first member of struct, i.e. reject
5032 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5033 	 * strict mode to true for type match.
5034 	 */
5035 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5036 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5037 				  kptr_field->type == BPF_KPTR_REF))
5038 		goto bad_type;
5039 	return 0;
5040 bad_type:
5041 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5042 		reg_type_str(env, reg->type), reg_name);
5043 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5044 	if (kptr_field->type == BPF_KPTR_UNREF)
5045 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5046 			targ_name);
5047 	else
5048 		verbose(env, "\n");
5049 	return -EINVAL;
5050 }
5051 
5052 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5053  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5054  */
5055 static bool in_rcu_cs(struct bpf_verifier_env *env)
5056 {
5057 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5058 }
5059 
5060 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5061 BTF_SET_START(rcu_protected_types)
5062 BTF_ID(struct, prog_test_ref_kfunc)
5063 BTF_ID(struct, cgroup)
5064 BTF_ID(struct, bpf_cpumask)
5065 BTF_ID(struct, task_struct)
5066 BTF_SET_END(rcu_protected_types)
5067 
5068 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5069 {
5070 	if (!btf_is_kernel(btf))
5071 		return false;
5072 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5073 }
5074 
5075 static bool rcu_safe_kptr(const struct btf_field *field)
5076 {
5077 	const struct btf_field_kptr *kptr = &field->kptr;
5078 
5079 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5080 }
5081 
5082 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5083 				 int value_regno, int insn_idx,
5084 				 struct btf_field *kptr_field)
5085 {
5086 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5087 	int class = BPF_CLASS(insn->code);
5088 	struct bpf_reg_state *val_reg;
5089 
5090 	/* Things we already checked for in check_map_access and caller:
5091 	 *  - Reject cases where variable offset may touch kptr
5092 	 *  - size of access (must be BPF_DW)
5093 	 *  - tnum_is_const(reg->var_off)
5094 	 *  - kptr_field->offset == off + reg->var_off.value
5095 	 */
5096 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5097 	if (BPF_MODE(insn->code) != BPF_MEM) {
5098 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5099 		return -EACCES;
5100 	}
5101 
5102 	/* We only allow loading referenced kptr, since it will be marked as
5103 	 * untrusted, similar to unreferenced kptr.
5104 	 */
5105 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5106 		verbose(env, "store to referenced kptr disallowed\n");
5107 		return -EACCES;
5108 	}
5109 
5110 	if (class == BPF_LDX) {
5111 		val_reg = reg_state(env, value_regno);
5112 		/* We can simply mark the value_regno receiving the pointer
5113 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5114 		 */
5115 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5116 				kptr_field->kptr.btf_id,
5117 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5118 				PTR_MAYBE_NULL | MEM_RCU :
5119 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5120 		/* For mark_ptr_or_null_reg */
5121 		val_reg->id = ++env->id_gen;
5122 	} else if (class == BPF_STX) {
5123 		val_reg = reg_state(env, value_regno);
5124 		if (!register_is_null(val_reg) &&
5125 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5126 			return -EACCES;
5127 	} else if (class == BPF_ST) {
5128 		if (insn->imm) {
5129 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5130 				kptr_field->offset);
5131 			return -EACCES;
5132 		}
5133 	} else {
5134 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5135 		return -EACCES;
5136 	}
5137 	return 0;
5138 }
5139 
5140 /* check read/write into a map element with possible variable offset */
5141 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5142 			    int off, int size, bool zero_size_allowed,
5143 			    enum bpf_access_src src)
5144 {
5145 	struct bpf_verifier_state *vstate = env->cur_state;
5146 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5147 	struct bpf_reg_state *reg = &state->regs[regno];
5148 	struct bpf_map *map = reg->map_ptr;
5149 	struct btf_record *rec;
5150 	int err, i;
5151 
5152 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5153 				      zero_size_allowed);
5154 	if (err)
5155 		return err;
5156 
5157 	if (IS_ERR_OR_NULL(map->record))
5158 		return 0;
5159 	rec = map->record;
5160 	for (i = 0; i < rec->cnt; i++) {
5161 		struct btf_field *field = &rec->fields[i];
5162 		u32 p = field->offset;
5163 
5164 		/* If any part of a field  can be touched by load/store, reject
5165 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5166 		 * it is sufficient to check x1 < y2 && y1 < x2.
5167 		 */
5168 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5169 		    p < reg->umax_value + off + size) {
5170 			switch (field->type) {
5171 			case BPF_KPTR_UNREF:
5172 			case BPF_KPTR_REF:
5173 				if (src != ACCESS_DIRECT) {
5174 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5175 					return -EACCES;
5176 				}
5177 				if (!tnum_is_const(reg->var_off)) {
5178 					verbose(env, "kptr access cannot have variable offset\n");
5179 					return -EACCES;
5180 				}
5181 				if (p != off + reg->var_off.value) {
5182 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5183 						p, off + reg->var_off.value);
5184 					return -EACCES;
5185 				}
5186 				if (size != bpf_size_to_bytes(BPF_DW)) {
5187 					verbose(env, "kptr access size must be BPF_DW\n");
5188 					return -EACCES;
5189 				}
5190 				break;
5191 			default:
5192 				verbose(env, "%s cannot be accessed directly by load/store\n",
5193 					btf_field_type_name(field->type));
5194 				return -EACCES;
5195 			}
5196 		}
5197 	}
5198 	return 0;
5199 }
5200 
5201 #define MAX_PACKET_OFF 0xffff
5202 
5203 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5204 				       const struct bpf_call_arg_meta *meta,
5205 				       enum bpf_access_type t)
5206 {
5207 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5208 
5209 	switch (prog_type) {
5210 	/* Program types only with direct read access go here! */
5211 	case BPF_PROG_TYPE_LWT_IN:
5212 	case BPF_PROG_TYPE_LWT_OUT:
5213 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5214 	case BPF_PROG_TYPE_SK_REUSEPORT:
5215 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5216 	case BPF_PROG_TYPE_CGROUP_SKB:
5217 		if (t == BPF_WRITE)
5218 			return false;
5219 		fallthrough;
5220 
5221 	/* Program types with direct read + write access go here! */
5222 	case BPF_PROG_TYPE_SCHED_CLS:
5223 	case BPF_PROG_TYPE_SCHED_ACT:
5224 	case BPF_PROG_TYPE_XDP:
5225 	case BPF_PROG_TYPE_LWT_XMIT:
5226 	case BPF_PROG_TYPE_SK_SKB:
5227 	case BPF_PROG_TYPE_SK_MSG:
5228 		if (meta)
5229 			return meta->pkt_access;
5230 
5231 		env->seen_direct_write = true;
5232 		return true;
5233 
5234 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5235 		if (t == BPF_WRITE)
5236 			env->seen_direct_write = true;
5237 
5238 		return true;
5239 
5240 	default:
5241 		return false;
5242 	}
5243 }
5244 
5245 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5246 			       int size, bool zero_size_allowed)
5247 {
5248 	struct bpf_reg_state *regs = cur_regs(env);
5249 	struct bpf_reg_state *reg = &regs[regno];
5250 	int err;
5251 
5252 	/* We may have added a variable offset to the packet pointer; but any
5253 	 * reg->range we have comes after that.  We are only checking the fixed
5254 	 * offset.
5255 	 */
5256 
5257 	/* We don't allow negative numbers, because we aren't tracking enough
5258 	 * detail to prove they're safe.
5259 	 */
5260 	if (reg->smin_value < 0) {
5261 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5262 			regno);
5263 		return -EACCES;
5264 	}
5265 
5266 	err = reg->range < 0 ? -EINVAL :
5267 	      __check_mem_access(env, regno, off, size, reg->range,
5268 				 zero_size_allowed);
5269 	if (err) {
5270 		verbose(env, "R%d offset is outside of the packet\n", regno);
5271 		return err;
5272 	}
5273 
5274 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5275 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5276 	 * otherwise find_good_pkt_pointers would have refused to set range info
5277 	 * that __check_mem_access would have rejected this pkt access.
5278 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5279 	 */
5280 	env->prog->aux->max_pkt_offset =
5281 		max_t(u32, env->prog->aux->max_pkt_offset,
5282 		      off + reg->umax_value + size - 1);
5283 
5284 	return err;
5285 }
5286 
5287 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5288 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5289 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5290 			    struct btf **btf, u32 *btf_id)
5291 {
5292 	struct bpf_insn_access_aux info = {
5293 		.reg_type = *reg_type,
5294 		.log = &env->log,
5295 	};
5296 
5297 	if (env->ops->is_valid_access &&
5298 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5299 		/* A non zero info.ctx_field_size indicates that this field is a
5300 		 * candidate for later verifier transformation to load the whole
5301 		 * field and then apply a mask when accessed with a narrower
5302 		 * access than actual ctx access size. A zero info.ctx_field_size
5303 		 * will only allow for whole field access and rejects any other
5304 		 * type of narrower access.
5305 		 */
5306 		*reg_type = info.reg_type;
5307 
5308 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5309 			*btf = info.btf;
5310 			*btf_id = info.btf_id;
5311 		} else {
5312 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5313 		}
5314 		/* remember the offset of last byte accessed in ctx */
5315 		if (env->prog->aux->max_ctx_offset < off + size)
5316 			env->prog->aux->max_ctx_offset = off + size;
5317 		return 0;
5318 	}
5319 
5320 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5321 	return -EACCES;
5322 }
5323 
5324 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5325 				  int size)
5326 {
5327 	if (size < 0 || off < 0 ||
5328 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5329 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5330 			off, size);
5331 		return -EACCES;
5332 	}
5333 	return 0;
5334 }
5335 
5336 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5337 			     u32 regno, int off, int size,
5338 			     enum bpf_access_type t)
5339 {
5340 	struct bpf_reg_state *regs = cur_regs(env);
5341 	struct bpf_reg_state *reg = &regs[regno];
5342 	struct bpf_insn_access_aux info = {};
5343 	bool valid;
5344 
5345 	if (reg->smin_value < 0) {
5346 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5347 			regno);
5348 		return -EACCES;
5349 	}
5350 
5351 	switch (reg->type) {
5352 	case PTR_TO_SOCK_COMMON:
5353 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5354 		break;
5355 	case PTR_TO_SOCKET:
5356 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5357 		break;
5358 	case PTR_TO_TCP_SOCK:
5359 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5360 		break;
5361 	case PTR_TO_XDP_SOCK:
5362 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5363 		break;
5364 	default:
5365 		valid = false;
5366 	}
5367 
5368 
5369 	if (valid) {
5370 		env->insn_aux_data[insn_idx].ctx_field_size =
5371 			info.ctx_field_size;
5372 		return 0;
5373 	}
5374 
5375 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5376 		regno, reg_type_str(env, reg->type), off, size);
5377 
5378 	return -EACCES;
5379 }
5380 
5381 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5382 {
5383 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5384 }
5385 
5386 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5387 {
5388 	const struct bpf_reg_state *reg = reg_state(env, regno);
5389 
5390 	return reg->type == PTR_TO_CTX;
5391 }
5392 
5393 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5394 {
5395 	const struct bpf_reg_state *reg = reg_state(env, regno);
5396 
5397 	return type_is_sk_pointer(reg->type);
5398 }
5399 
5400 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5401 {
5402 	const struct bpf_reg_state *reg = reg_state(env, regno);
5403 
5404 	return type_is_pkt_pointer(reg->type);
5405 }
5406 
5407 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5408 {
5409 	const struct bpf_reg_state *reg = reg_state(env, regno);
5410 
5411 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5412 	return reg->type == PTR_TO_FLOW_KEYS;
5413 }
5414 
5415 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5416 {
5417 	/* A referenced register is always trusted. */
5418 	if (reg->ref_obj_id)
5419 		return true;
5420 
5421 	/* If a register is not referenced, it is trusted if it has the
5422 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5423 	 * other type modifiers may be safe, but we elect to take an opt-in
5424 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5425 	 * not.
5426 	 *
5427 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5428 	 * for whether a register is trusted.
5429 	 */
5430 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5431 	       !bpf_type_has_unsafe_modifiers(reg->type);
5432 }
5433 
5434 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5435 {
5436 	return reg->type & MEM_RCU;
5437 }
5438 
5439 static void clear_trusted_flags(enum bpf_type_flag *flag)
5440 {
5441 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5442 }
5443 
5444 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5445 				   const struct bpf_reg_state *reg,
5446 				   int off, int size, bool strict)
5447 {
5448 	struct tnum reg_off;
5449 	int ip_align;
5450 
5451 	/* Byte size accesses are always allowed. */
5452 	if (!strict || size == 1)
5453 		return 0;
5454 
5455 	/* For platforms that do not have a Kconfig enabling
5456 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5457 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5458 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5459 	 * to this code only in strict mode where we want to emulate
5460 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5461 	 * unconditional IP align value of '2'.
5462 	 */
5463 	ip_align = 2;
5464 
5465 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5466 	if (!tnum_is_aligned(reg_off, size)) {
5467 		char tn_buf[48];
5468 
5469 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5470 		verbose(env,
5471 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5472 			ip_align, tn_buf, reg->off, off, size);
5473 		return -EACCES;
5474 	}
5475 
5476 	return 0;
5477 }
5478 
5479 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5480 				       const struct bpf_reg_state *reg,
5481 				       const char *pointer_desc,
5482 				       int off, int size, bool strict)
5483 {
5484 	struct tnum reg_off;
5485 
5486 	/* Byte size accesses are always allowed. */
5487 	if (!strict || size == 1)
5488 		return 0;
5489 
5490 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5491 	if (!tnum_is_aligned(reg_off, size)) {
5492 		char tn_buf[48];
5493 
5494 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5495 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5496 			pointer_desc, tn_buf, reg->off, off, size);
5497 		return -EACCES;
5498 	}
5499 
5500 	return 0;
5501 }
5502 
5503 static int check_ptr_alignment(struct bpf_verifier_env *env,
5504 			       const struct bpf_reg_state *reg, int off,
5505 			       int size, bool strict_alignment_once)
5506 {
5507 	bool strict = env->strict_alignment || strict_alignment_once;
5508 	const char *pointer_desc = "";
5509 
5510 	switch (reg->type) {
5511 	case PTR_TO_PACKET:
5512 	case PTR_TO_PACKET_META:
5513 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5514 		 * right in front, treat it the very same way.
5515 		 */
5516 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5517 	case PTR_TO_FLOW_KEYS:
5518 		pointer_desc = "flow keys ";
5519 		break;
5520 	case PTR_TO_MAP_KEY:
5521 		pointer_desc = "key ";
5522 		break;
5523 	case PTR_TO_MAP_VALUE:
5524 		pointer_desc = "value ";
5525 		break;
5526 	case PTR_TO_CTX:
5527 		pointer_desc = "context ";
5528 		break;
5529 	case PTR_TO_STACK:
5530 		pointer_desc = "stack ";
5531 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5532 		 * and check_stack_read_fixed_off() relies on stack accesses being
5533 		 * aligned.
5534 		 */
5535 		strict = true;
5536 		break;
5537 	case PTR_TO_SOCKET:
5538 		pointer_desc = "sock ";
5539 		break;
5540 	case PTR_TO_SOCK_COMMON:
5541 		pointer_desc = "sock_common ";
5542 		break;
5543 	case PTR_TO_TCP_SOCK:
5544 		pointer_desc = "tcp_sock ";
5545 		break;
5546 	case PTR_TO_XDP_SOCK:
5547 		pointer_desc = "xdp_sock ";
5548 		break;
5549 	default:
5550 		break;
5551 	}
5552 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5553 					   strict);
5554 }
5555 
5556 static int update_stack_depth(struct bpf_verifier_env *env,
5557 			      const struct bpf_func_state *func,
5558 			      int off)
5559 {
5560 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
5561 
5562 	if (stack >= -off)
5563 		return 0;
5564 
5565 	/* update known max for given subprogram */
5566 	env->subprog_info[func->subprogno].stack_depth = -off;
5567 	return 0;
5568 }
5569 
5570 /* starting from main bpf function walk all instructions of the function
5571  * and recursively walk all callees that given function can call.
5572  * Ignore jump and exit insns.
5573  * Since recursion is prevented by check_cfg() this algorithm
5574  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5575  */
5576 static int check_max_stack_depth(struct bpf_verifier_env *env)
5577 {
5578 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5579 	struct bpf_subprog_info *subprog = env->subprog_info;
5580 	struct bpf_insn *insn = env->prog->insnsi;
5581 	bool tail_call_reachable = false;
5582 	int ret_insn[MAX_CALL_FRAMES];
5583 	int ret_prog[MAX_CALL_FRAMES];
5584 	int j;
5585 
5586 process_func:
5587 	/* protect against potential stack overflow that might happen when
5588 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5589 	 * depth for such case down to 256 so that the worst case scenario
5590 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5591 	 * 8k).
5592 	 *
5593 	 * To get the idea what might happen, see an example:
5594 	 * func1 -> sub rsp, 128
5595 	 *  subfunc1 -> sub rsp, 256
5596 	 *  tailcall1 -> add rsp, 256
5597 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5598 	 *   subfunc2 -> sub rsp, 64
5599 	 *   subfunc22 -> sub rsp, 128
5600 	 *   tailcall2 -> add rsp, 128
5601 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5602 	 *
5603 	 * tailcall will unwind the current stack frame but it will not get rid
5604 	 * of caller's stack as shown on the example above.
5605 	 */
5606 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5607 		verbose(env,
5608 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5609 			depth);
5610 		return -EACCES;
5611 	}
5612 	/* round up to 32-bytes, since this is granularity
5613 	 * of interpreter stack size
5614 	 */
5615 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5616 	if (depth > MAX_BPF_STACK) {
5617 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5618 			frame + 1, depth);
5619 		return -EACCES;
5620 	}
5621 continue_func:
5622 	subprog_end = subprog[idx + 1].start;
5623 	for (; i < subprog_end; i++) {
5624 		int next_insn;
5625 
5626 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5627 			continue;
5628 		/* remember insn and function to return to */
5629 		ret_insn[frame] = i + 1;
5630 		ret_prog[frame] = idx;
5631 
5632 		/* find the callee */
5633 		next_insn = i + insn[i].imm + 1;
5634 		idx = find_subprog(env, next_insn);
5635 		if (idx < 0) {
5636 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5637 				  next_insn);
5638 			return -EFAULT;
5639 		}
5640 		if (subprog[idx].is_async_cb) {
5641 			if (subprog[idx].has_tail_call) {
5642 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5643 				return -EFAULT;
5644 			}
5645 			 /* async callbacks don't increase bpf prog stack size */
5646 			continue;
5647 		}
5648 		i = next_insn;
5649 
5650 		if (subprog[idx].has_tail_call)
5651 			tail_call_reachable = true;
5652 
5653 		frame++;
5654 		if (frame >= MAX_CALL_FRAMES) {
5655 			verbose(env, "the call stack of %d frames is too deep !\n",
5656 				frame);
5657 			return -E2BIG;
5658 		}
5659 		goto process_func;
5660 	}
5661 	/* if tail call got detected across bpf2bpf calls then mark each of the
5662 	 * currently present subprog frames as tail call reachable subprogs;
5663 	 * this info will be utilized by JIT so that we will be preserving the
5664 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5665 	 */
5666 	if (tail_call_reachable)
5667 		for (j = 0; j < frame; j++)
5668 			subprog[ret_prog[j]].tail_call_reachable = true;
5669 	if (subprog[0].tail_call_reachable)
5670 		env->prog->aux->tail_call_reachable = true;
5671 
5672 	/* end of for() loop means the last insn of the 'subprog'
5673 	 * was reached. Doesn't matter whether it was JA or EXIT
5674 	 */
5675 	if (frame == 0)
5676 		return 0;
5677 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5678 	frame--;
5679 	i = ret_insn[frame];
5680 	idx = ret_prog[frame];
5681 	goto continue_func;
5682 }
5683 
5684 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5685 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5686 				  const struct bpf_insn *insn, int idx)
5687 {
5688 	int start = idx + insn->imm + 1, subprog;
5689 
5690 	subprog = find_subprog(env, start);
5691 	if (subprog < 0) {
5692 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5693 			  start);
5694 		return -EFAULT;
5695 	}
5696 	return env->subprog_info[subprog].stack_depth;
5697 }
5698 #endif
5699 
5700 static int __check_buffer_access(struct bpf_verifier_env *env,
5701 				 const char *buf_info,
5702 				 const struct bpf_reg_state *reg,
5703 				 int regno, int off, int size)
5704 {
5705 	if (off < 0) {
5706 		verbose(env,
5707 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5708 			regno, buf_info, off, size);
5709 		return -EACCES;
5710 	}
5711 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5712 		char tn_buf[48];
5713 
5714 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5715 		verbose(env,
5716 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5717 			regno, off, tn_buf);
5718 		return -EACCES;
5719 	}
5720 
5721 	return 0;
5722 }
5723 
5724 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5725 				  const struct bpf_reg_state *reg,
5726 				  int regno, int off, int size)
5727 {
5728 	int err;
5729 
5730 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5731 	if (err)
5732 		return err;
5733 
5734 	if (off + size > env->prog->aux->max_tp_access)
5735 		env->prog->aux->max_tp_access = off + size;
5736 
5737 	return 0;
5738 }
5739 
5740 static int check_buffer_access(struct bpf_verifier_env *env,
5741 			       const struct bpf_reg_state *reg,
5742 			       int regno, int off, int size,
5743 			       bool zero_size_allowed,
5744 			       u32 *max_access)
5745 {
5746 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5747 	int err;
5748 
5749 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5750 	if (err)
5751 		return err;
5752 
5753 	if (off + size > *max_access)
5754 		*max_access = off + size;
5755 
5756 	return 0;
5757 }
5758 
5759 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5760 static void zext_32_to_64(struct bpf_reg_state *reg)
5761 {
5762 	reg->var_off = tnum_subreg(reg->var_off);
5763 	__reg_assign_32_into_64(reg);
5764 }
5765 
5766 /* truncate register to smaller size (in bytes)
5767  * must be called with size < BPF_REG_SIZE
5768  */
5769 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5770 {
5771 	u64 mask;
5772 
5773 	/* clear high bits in bit representation */
5774 	reg->var_off = tnum_cast(reg->var_off, size);
5775 
5776 	/* fix arithmetic bounds */
5777 	mask = ((u64)1 << (size * 8)) - 1;
5778 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5779 		reg->umin_value &= mask;
5780 		reg->umax_value &= mask;
5781 	} else {
5782 		reg->umin_value = 0;
5783 		reg->umax_value = mask;
5784 	}
5785 	reg->smin_value = reg->umin_value;
5786 	reg->smax_value = reg->umax_value;
5787 
5788 	/* If size is smaller than 32bit register the 32bit register
5789 	 * values are also truncated so we push 64-bit bounds into
5790 	 * 32-bit bounds. Above were truncated < 32-bits already.
5791 	 */
5792 	if (size >= 4)
5793 		return;
5794 	__reg_combine_64_into_32(reg);
5795 }
5796 
5797 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5798 {
5799 	/* A map is considered read-only if the following condition are true:
5800 	 *
5801 	 * 1) BPF program side cannot change any of the map content. The
5802 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5803 	 *    and was set at map creation time.
5804 	 * 2) The map value(s) have been initialized from user space by a
5805 	 *    loader and then "frozen", such that no new map update/delete
5806 	 *    operations from syscall side are possible for the rest of
5807 	 *    the map's lifetime from that point onwards.
5808 	 * 3) Any parallel/pending map update/delete operations from syscall
5809 	 *    side have been completed. Only after that point, it's safe to
5810 	 *    assume that map value(s) are immutable.
5811 	 */
5812 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5813 	       READ_ONCE(map->frozen) &&
5814 	       !bpf_map_write_active(map);
5815 }
5816 
5817 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5818 {
5819 	void *ptr;
5820 	u64 addr;
5821 	int err;
5822 
5823 	err = map->ops->map_direct_value_addr(map, &addr, off);
5824 	if (err)
5825 		return err;
5826 	ptr = (void *)(long)addr + off;
5827 
5828 	switch (size) {
5829 	case sizeof(u8):
5830 		*val = (u64)*(u8 *)ptr;
5831 		break;
5832 	case sizeof(u16):
5833 		*val = (u64)*(u16 *)ptr;
5834 		break;
5835 	case sizeof(u32):
5836 		*val = (u64)*(u32 *)ptr;
5837 		break;
5838 	case sizeof(u64):
5839 		*val = *(u64 *)ptr;
5840 		break;
5841 	default:
5842 		return -EINVAL;
5843 	}
5844 	return 0;
5845 }
5846 
5847 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5848 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5849 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5850 
5851 /*
5852  * Allow list few fields as RCU trusted or full trusted.
5853  * This logic doesn't allow mix tagging and will be removed once GCC supports
5854  * btf_type_tag.
5855  */
5856 
5857 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5858 BTF_TYPE_SAFE_RCU(struct task_struct) {
5859 	const cpumask_t *cpus_ptr;
5860 	struct css_set __rcu *cgroups;
5861 	struct task_struct __rcu *real_parent;
5862 	struct task_struct *group_leader;
5863 };
5864 
5865 BTF_TYPE_SAFE_RCU(struct cgroup) {
5866 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5867 	struct kernfs_node *kn;
5868 };
5869 
5870 BTF_TYPE_SAFE_RCU(struct css_set) {
5871 	struct cgroup *dfl_cgrp;
5872 };
5873 
5874 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5875 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5876 	struct file __rcu *exe_file;
5877 };
5878 
5879 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5880  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5881  */
5882 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5883 	struct sock *sk;
5884 };
5885 
5886 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5887 	struct sock *sk;
5888 };
5889 
5890 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5891 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5892 	struct seq_file *seq;
5893 };
5894 
5895 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5896 	struct bpf_iter_meta *meta;
5897 	struct task_struct *task;
5898 };
5899 
5900 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5901 	struct file *file;
5902 };
5903 
5904 BTF_TYPE_SAFE_TRUSTED(struct file) {
5905 	struct inode *f_inode;
5906 };
5907 
5908 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5909 	/* no negative dentry-s in places where bpf can see it */
5910 	struct inode *d_inode;
5911 };
5912 
5913 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5914 	struct sock *sk;
5915 };
5916 
5917 static bool type_is_rcu(struct bpf_verifier_env *env,
5918 			struct bpf_reg_state *reg,
5919 			const char *field_name, u32 btf_id)
5920 {
5921 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5922 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5923 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5924 
5925 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5926 }
5927 
5928 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5929 				struct bpf_reg_state *reg,
5930 				const char *field_name, u32 btf_id)
5931 {
5932 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5933 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5934 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5935 
5936 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5937 }
5938 
5939 static bool type_is_trusted(struct bpf_verifier_env *env,
5940 			    struct bpf_reg_state *reg,
5941 			    const char *field_name, u32 btf_id)
5942 {
5943 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5944 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5945 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5946 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5947 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5948 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5949 
5950 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5951 }
5952 
5953 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5954 				   struct bpf_reg_state *regs,
5955 				   int regno, int off, int size,
5956 				   enum bpf_access_type atype,
5957 				   int value_regno)
5958 {
5959 	struct bpf_reg_state *reg = regs + regno;
5960 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5961 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5962 	const char *field_name = NULL;
5963 	enum bpf_type_flag flag = 0;
5964 	u32 btf_id = 0;
5965 	int ret;
5966 
5967 	if (!env->allow_ptr_leaks) {
5968 		verbose(env,
5969 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5970 			tname);
5971 		return -EPERM;
5972 	}
5973 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5974 		verbose(env,
5975 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5976 			tname);
5977 		return -EINVAL;
5978 	}
5979 	if (off < 0) {
5980 		verbose(env,
5981 			"R%d is ptr_%s invalid negative access: off=%d\n",
5982 			regno, tname, off);
5983 		return -EACCES;
5984 	}
5985 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5986 		char tn_buf[48];
5987 
5988 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5989 		verbose(env,
5990 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5991 			regno, tname, off, tn_buf);
5992 		return -EACCES;
5993 	}
5994 
5995 	if (reg->type & MEM_USER) {
5996 		verbose(env,
5997 			"R%d is ptr_%s access user memory: off=%d\n",
5998 			regno, tname, off);
5999 		return -EACCES;
6000 	}
6001 
6002 	if (reg->type & MEM_PERCPU) {
6003 		verbose(env,
6004 			"R%d is ptr_%s access percpu memory: off=%d\n",
6005 			regno, tname, off);
6006 		return -EACCES;
6007 	}
6008 
6009 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6010 		if (!btf_is_kernel(reg->btf)) {
6011 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6012 			return -EFAULT;
6013 		}
6014 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6015 	} else {
6016 		/* Writes are permitted with default btf_struct_access for
6017 		 * program allocated objects (which always have ref_obj_id > 0),
6018 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6019 		 */
6020 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6021 			verbose(env, "only read is supported\n");
6022 			return -EACCES;
6023 		}
6024 
6025 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6026 		    !reg->ref_obj_id) {
6027 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6028 			return -EFAULT;
6029 		}
6030 
6031 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6032 	}
6033 
6034 	if (ret < 0)
6035 		return ret;
6036 
6037 	if (ret != PTR_TO_BTF_ID) {
6038 		/* just mark; */
6039 
6040 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6041 		/* If this is an untrusted pointer, all pointers formed by walking it
6042 		 * also inherit the untrusted flag.
6043 		 */
6044 		flag = PTR_UNTRUSTED;
6045 
6046 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6047 		/* By default any pointer obtained from walking a trusted pointer is no
6048 		 * longer trusted, unless the field being accessed has explicitly been
6049 		 * marked as inheriting its parent's state of trust (either full or RCU).
6050 		 * For example:
6051 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6052 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6053 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6054 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6055 		 *
6056 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6057 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6058 		 */
6059 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6060 			flag |= PTR_TRUSTED;
6061 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6062 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6063 				/* ignore __rcu tag and mark it MEM_RCU */
6064 				flag |= MEM_RCU;
6065 			} else if (flag & MEM_RCU ||
6066 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6067 				/* __rcu tagged pointers can be NULL */
6068 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6069 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6070 				/* keep as-is */
6071 			} else {
6072 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6073 				clear_trusted_flags(&flag);
6074 			}
6075 		} else {
6076 			/*
6077 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6078 			 * aggressively mark as untrusted otherwise such
6079 			 * pointers will be plain PTR_TO_BTF_ID without flags
6080 			 * and will be allowed to be passed into helpers for
6081 			 * compat reasons.
6082 			 */
6083 			flag = PTR_UNTRUSTED;
6084 		}
6085 	} else {
6086 		/* Old compat. Deprecated */
6087 		clear_trusted_flags(&flag);
6088 	}
6089 
6090 	if (atype == BPF_READ && value_regno >= 0)
6091 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6092 
6093 	return 0;
6094 }
6095 
6096 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6097 				   struct bpf_reg_state *regs,
6098 				   int regno, int off, int size,
6099 				   enum bpf_access_type atype,
6100 				   int value_regno)
6101 {
6102 	struct bpf_reg_state *reg = regs + regno;
6103 	struct bpf_map *map = reg->map_ptr;
6104 	struct bpf_reg_state map_reg;
6105 	enum bpf_type_flag flag = 0;
6106 	const struct btf_type *t;
6107 	const char *tname;
6108 	u32 btf_id;
6109 	int ret;
6110 
6111 	if (!btf_vmlinux) {
6112 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6113 		return -ENOTSUPP;
6114 	}
6115 
6116 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6117 		verbose(env, "map_ptr access not supported for map type %d\n",
6118 			map->map_type);
6119 		return -ENOTSUPP;
6120 	}
6121 
6122 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6123 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6124 
6125 	if (!env->allow_ptr_leaks) {
6126 		verbose(env,
6127 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6128 			tname);
6129 		return -EPERM;
6130 	}
6131 
6132 	if (off < 0) {
6133 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6134 			regno, tname, off);
6135 		return -EACCES;
6136 	}
6137 
6138 	if (atype != BPF_READ) {
6139 		verbose(env, "only read from %s is supported\n", tname);
6140 		return -EACCES;
6141 	}
6142 
6143 	/* Simulate access to a PTR_TO_BTF_ID */
6144 	memset(&map_reg, 0, sizeof(map_reg));
6145 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6146 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6147 	if (ret < 0)
6148 		return ret;
6149 
6150 	if (value_regno >= 0)
6151 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6152 
6153 	return 0;
6154 }
6155 
6156 /* Check that the stack access at the given offset is within bounds. The
6157  * maximum valid offset is -1.
6158  *
6159  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6160  * -state->allocated_stack for reads.
6161  */
6162 static int check_stack_slot_within_bounds(int off,
6163 					  struct bpf_func_state *state,
6164 					  enum bpf_access_type t)
6165 {
6166 	int min_valid_off;
6167 
6168 	if (t == BPF_WRITE)
6169 		min_valid_off = -MAX_BPF_STACK;
6170 	else
6171 		min_valid_off = -state->allocated_stack;
6172 
6173 	if (off < min_valid_off || off > -1)
6174 		return -EACCES;
6175 	return 0;
6176 }
6177 
6178 /* Check that the stack access at 'regno + off' falls within the maximum stack
6179  * bounds.
6180  *
6181  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6182  */
6183 static int check_stack_access_within_bounds(
6184 		struct bpf_verifier_env *env,
6185 		int regno, int off, int access_size,
6186 		enum bpf_access_src src, enum bpf_access_type type)
6187 {
6188 	struct bpf_reg_state *regs = cur_regs(env);
6189 	struct bpf_reg_state *reg = regs + regno;
6190 	struct bpf_func_state *state = func(env, reg);
6191 	int min_off, max_off;
6192 	int err;
6193 	char *err_extra;
6194 
6195 	if (src == ACCESS_HELPER)
6196 		/* We don't know if helpers are reading or writing (or both). */
6197 		err_extra = " indirect access to";
6198 	else if (type == BPF_READ)
6199 		err_extra = " read from";
6200 	else
6201 		err_extra = " write to";
6202 
6203 	if (tnum_is_const(reg->var_off)) {
6204 		min_off = reg->var_off.value + off;
6205 		if (access_size > 0)
6206 			max_off = min_off + access_size - 1;
6207 		else
6208 			max_off = min_off;
6209 	} else {
6210 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6211 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6212 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6213 				err_extra, regno);
6214 			return -EACCES;
6215 		}
6216 		min_off = reg->smin_value + off;
6217 		if (access_size > 0)
6218 			max_off = reg->smax_value + off + access_size - 1;
6219 		else
6220 			max_off = min_off;
6221 	}
6222 
6223 	err = check_stack_slot_within_bounds(min_off, state, type);
6224 	if (!err)
6225 		err = check_stack_slot_within_bounds(max_off, state, type);
6226 
6227 	if (err) {
6228 		if (tnum_is_const(reg->var_off)) {
6229 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6230 				err_extra, regno, off, access_size);
6231 		} else {
6232 			char tn_buf[48];
6233 
6234 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6235 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6236 				err_extra, regno, tn_buf, access_size);
6237 		}
6238 	}
6239 	return err;
6240 }
6241 
6242 /* check whether memory at (regno + off) is accessible for t = (read | write)
6243  * if t==write, value_regno is a register which value is stored into memory
6244  * if t==read, value_regno is a register which will receive the value from memory
6245  * if t==write && value_regno==-1, some unknown value is stored into memory
6246  * if t==read && value_regno==-1, don't care what we read from memory
6247  */
6248 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6249 			    int off, int bpf_size, enum bpf_access_type t,
6250 			    int value_regno, bool strict_alignment_once)
6251 {
6252 	struct bpf_reg_state *regs = cur_regs(env);
6253 	struct bpf_reg_state *reg = regs + regno;
6254 	struct bpf_func_state *state;
6255 	int size, err = 0;
6256 
6257 	size = bpf_size_to_bytes(bpf_size);
6258 	if (size < 0)
6259 		return size;
6260 
6261 	/* alignment checks will add in reg->off themselves */
6262 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6263 	if (err)
6264 		return err;
6265 
6266 	/* for access checks, reg->off is just part of off */
6267 	off += reg->off;
6268 
6269 	if (reg->type == PTR_TO_MAP_KEY) {
6270 		if (t == BPF_WRITE) {
6271 			verbose(env, "write to change key R%d not allowed\n", regno);
6272 			return -EACCES;
6273 		}
6274 
6275 		err = check_mem_region_access(env, regno, off, size,
6276 					      reg->map_ptr->key_size, false);
6277 		if (err)
6278 			return err;
6279 		if (value_regno >= 0)
6280 			mark_reg_unknown(env, regs, value_regno);
6281 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6282 		struct btf_field *kptr_field = NULL;
6283 
6284 		if (t == BPF_WRITE && value_regno >= 0 &&
6285 		    is_pointer_value(env, value_regno)) {
6286 			verbose(env, "R%d leaks addr into map\n", value_regno);
6287 			return -EACCES;
6288 		}
6289 		err = check_map_access_type(env, regno, off, size, t);
6290 		if (err)
6291 			return err;
6292 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6293 		if (err)
6294 			return err;
6295 		if (tnum_is_const(reg->var_off))
6296 			kptr_field = btf_record_find(reg->map_ptr->record,
6297 						     off + reg->var_off.value, BPF_KPTR);
6298 		if (kptr_field) {
6299 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6300 		} else if (t == BPF_READ && value_regno >= 0) {
6301 			struct bpf_map *map = reg->map_ptr;
6302 
6303 			/* if map is read-only, track its contents as scalars */
6304 			if (tnum_is_const(reg->var_off) &&
6305 			    bpf_map_is_rdonly(map) &&
6306 			    map->ops->map_direct_value_addr) {
6307 				int map_off = off + reg->var_off.value;
6308 				u64 val = 0;
6309 
6310 				err = bpf_map_direct_read(map, map_off, size,
6311 							  &val);
6312 				if (err)
6313 					return err;
6314 
6315 				regs[value_regno].type = SCALAR_VALUE;
6316 				__mark_reg_known(&regs[value_regno], val);
6317 			} else {
6318 				mark_reg_unknown(env, regs, value_regno);
6319 			}
6320 		}
6321 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6322 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6323 
6324 		if (type_may_be_null(reg->type)) {
6325 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6326 				reg_type_str(env, reg->type));
6327 			return -EACCES;
6328 		}
6329 
6330 		if (t == BPF_WRITE && rdonly_mem) {
6331 			verbose(env, "R%d cannot write into %s\n",
6332 				regno, reg_type_str(env, reg->type));
6333 			return -EACCES;
6334 		}
6335 
6336 		if (t == BPF_WRITE && value_regno >= 0 &&
6337 		    is_pointer_value(env, value_regno)) {
6338 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6339 			return -EACCES;
6340 		}
6341 
6342 		err = check_mem_region_access(env, regno, off, size,
6343 					      reg->mem_size, false);
6344 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6345 			mark_reg_unknown(env, regs, value_regno);
6346 	} else if (reg->type == PTR_TO_CTX) {
6347 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6348 		struct btf *btf = NULL;
6349 		u32 btf_id = 0;
6350 
6351 		if (t == BPF_WRITE && value_regno >= 0 &&
6352 		    is_pointer_value(env, value_regno)) {
6353 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6354 			return -EACCES;
6355 		}
6356 
6357 		err = check_ptr_off_reg(env, reg, regno);
6358 		if (err < 0)
6359 			return err;
6360 
6361 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6362 				       &btf_id);
6363 		if (err)
6364 			verbose_linfo(env, insn_idx, "; ");
6365 		if (!err && t == BPF_READ && value_regno >= 0) {
6366 			/* ctx access returns either a scalar, or a
6367 			 * PTR_TO_PACKET[_META,_END]. In the latter
6368 			 * case, we know the offset is zero.
6369 			 */
6370 			if (reg_type == SCALAR_VALUE) {
6371 				mark_reg_unknown(env, regs, value_regno);
6372 			} else {
6373 				mark_reg_known_zero(env, regs,
6374 						    value_regno);
6375 				if (type_may_be_null(reg_type))
6376 					regs[value_regno].id = ++env->id_gen;
6377 				/* A load of ctx field could have different
6378 				 * actual load size with the one encoded in the
6379 				 * insn. When the dst is PTR, it is for sure not
6380 				 * a sub-register.
6381 				 */
6382 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6383 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6384 					regs[value_regno].btf = btf;
6385 					regs[value_regno].btf_id = btf_id;
6386 				}
6387 			}
6388 			regs[value_regno].type = reg_type;
6389 		}
6390 
6391 	} else if (reg->type == PTR_TO_STACK) {
6392 		/* Basic bounds checks. */
6393 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6394 		if (err)
6395 			return err;
6396 
6397 		state = func(env, reg);
6398 		err = update_stack_depth(env, state, off);
6399 		if (err)
6400 			return err;
6401 
6402 		if (t == BPF_READ)
6403 			err = check_stack_read(env, regno, off, size,
6404 					       value_regno);
6405 		else
6406 			err = check_stack_write(env, regno, off, size,
6407 						value_regno, insn_idx);
6408 	} else if (reg_is_pkt_pointer(reg)) {
6409 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6410 			verbose(env, "cannot write into packet\n");
6411 			return -EACCES;
6412 		}
6413 		if (t == BPF_WRITE && value_regno >= 0 &&
6414 		    is_pointer_value(env, value_regno)) {
6415 			verbose(env, "R%d leaks addr into packet\n",
6416 				value_regno);
6417 			return -EACCES;
6418 		}
6419 		err = check_packet_access(env, regno, off, size, false);
6420 		if (!err && t == BPF_READ && value_regno >= 0)
6421 			mark_reg_unknown(env, regs, value_regno);
6422 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6423 		if (t == BPF_WRITE && value_regno >= 0 &&
6424 		    is_pointer_value(env, value_regno)) {
6425 			verbose(env, "R%d leaks addr into flow keys\n",
6426 				value_regno);
6427 			return -EACCES;
6428 		}
6429 
6430 		err = check_flow_keys_access(env, off, size);
6431 		if (!err && t == BPF_READ && value_regno >= 0)
6432 			mark_reg_unknown(env, regs, value_regno);
6433 	} else if (type_is_sk_pointer(reg->type)) {
6434 		if (t == BPF_WRITE) {
6435 			verbose(env, "R%d cannot write into %s\n",
6436 				regno, reg_type_str(env, reg->type));
6437 			return -EACCES;
6438 		}
6439 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6440 		if (!err && value_regno >= 0)
6441 			mark_reg_unknown(env, regs, value_regno);
6442 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6443 		err = check_tp_buffer_access(env, reg, regno, off, size);
6444 		if (!err && t == BPF_READ && value_regno >= 0)
6445 			mark_reg_unknown(env, regs, value_regno);
6446 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6447 		   !type_may_be_null(reg->type)) {
6448 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6449 					      value_regno);
6450 	} else if (reg->type == CONST_PTR_TO_MAP) {
6451 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6452 					      value_regno);
6453 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6454 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6455 		u32 *max_access;
6456 
6457 		if (rdonly_mem) {
6458 			if (t == BPF_WRITE) {
6459 				verbose(env, "R%d cannot write into %s\n",
6460 					regno, reg_type_str(env, reg->type));
6461 				return -EACCES;
6462 			}
6463 			max_access = &env->prog->aux->max_rdonly_access;
6464 		} else {
6465 			max_access = &env->prog->aux->max_rdwr_access;
6466 		}
6467 
6468 		err = check_buffer_access(env, reg, regno, off, size, false,
6469 					  max_access);
6470 
6471 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6472 			mark_reg_unknown(env, regs, value_regno);
6473 	} else {
6474 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6475 			reg_type_str(env, reg->type));
6476 		return -EACCES;
6477 	}
6478 
6479 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6480 	    regs[value_regno].type == SCALAR_VALUE) {
6481 		/* b/h/w load zero-extends, mark upper bits as known 0 */
6482 		coerce_reg_to_size(&regs[value_regno], size);
6483 	}
6484 	return err;
6485 }
6486 
6487 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6488 {
6489 	int load_reg;
6490 	int err;
6491 
6492 	switch (insn->imm) {
6493 	case BPF_ADD:
6494 	case BPF_ADD | BPF_FETCH:
6495 	case BPF_AND:
6496 	case BPF_AND | BPF_FETCH:
6497 	case BPF_OR:
6498 	case BPF_OR | BPF_FETCH:
6499 	case BPF_XOR:
6500 	case BPF_XOR | BPF_FETCH:
6501 	case BPF_XCHG:
6502 	case BPF_CMPXCHG:
6503 		break;
6504 	default:
6505 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6506 		return -EINVAL;
6507 	}
6508 
6509 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6510 		verbose(env, "invalid atomic operand size\n");
6511 		return -EINVAL;
6512 	}
6513 
6514 	/* check src1 operand */
6515 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6516 	if (err)
6517 		return err;
6518 
6519 	/* check src2 operand */
6520 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6521 	if (err)
6522 		return err;
6523 
6524 	if (insn->imm == BPF_CMPXCHG) {
6525 		/* Check comparison of R0 with memory location */
6526 		const u32 aux_reg = BPF_REG_0;
6527 
6528 		err = check_reg_arg(env, aux_reg, SRC_OP);
6529 		if (err)
6530 			return err;
6531 
6532 		if (is_pointer_value(env, aux_reg)) {
6533 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6534 			return -EACCES;
6535 		}
6536 	}
6537 
6538 	if (is_pointer_value(env, insn->src_reg)) {
6539 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6540 		return -EACCES;
6541 	}
6542 
6543 	if (is_ctx_reg(env, insn->dst_reg) ||
6544 	    is_pkt_reg(env, insn->dst_reg) ||
6545 	    is_flow_key_reg(env, insn->dst_reg) ||
6546 	    is_sk_reg(env, insn->dst_reg)) {
6547 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6548 			insn->dst_reg,
6549 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6550 		return -EACCES;
6551 	}
6552 
6553 	if (insn->imm & BPF_FETCH) {
6554 		if (insn->imm == BPF_CMPXCHG)
6555 			load_reg = BPF_REG_0;
6556 		else
6557 			load_reg = insn->src_reg;
6558 
6559 		/* check and record load of old value */
6560 		err = check_reg_arg(env, load_reg, DST_OP);
6561 		if (err)
6562 			return err;
6563 	} else {
6564 		/* This instruction accesses a memory location but doesn't
6565 		 * actually load it into a register.
6566 		 */
6567 		load_reg = -1;
6568 	}
6569 
6570 	/* Check whether we can read the memory, with second call for fetch
6571 	 * case to simulate the register fill.
6572 	 */
6573 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6574 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
6575 	if (!err && load_reg >= 0)
6576 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6577 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6578 				       true);
6579 	if (err)
6580 		return err;
6581 
6582 	/* Check whether we can write into the same memory. */
6583 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6584 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6585 	if (err)
6586 		return err;
6587 
6588 	return 0;
6589 }
6590 
6591 /* When register 'regno' is used to read the stack (either directly or through
6592  * a helper function) make sure that it's within stack boundary and, depending
6593  * on the access type, that all elements of the stack are initialized.
6594  *
6595  * 'off' includes 'regno->off', but not its dynamic part (if any).
6596  *
6597  * All registers that have been spilled on the stack in the slots within the
6598  * read offsets are marked as read.
6599  */
6600 static int check_stack_range_initialized(
6601 		struct bpf_verifier_env *env, int regno, int off,
6602 		int access_size, bool zero_size_allowed,
6603 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6604 {
6605 	struct bpf_reg_state *reg = reg_state(env, regno);
6606 	struct bpf_func_state *state = func(env, reg);
6607 	int err, min_off, max_off, i, j, slot, spi;
6608 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6609 	enum bpf_access_type bounds_check_type;
6610 	/* Some accesses can write anything into the stack, others are
6611 	 * read-only.
6612 	 */
6613 	bool clobber = false;
6614 
6615 	if (access_size == 0 && !zero_size_allowed) {
6616 		verbose(env, "invalid zero-sized read\n");
6617 		return -EACCES;
6618 	}
6619 
6620 	if (type == ACCESS_HELPER) {
6621 		/* The bounds checks for writes are more permissive than for
6622 		 * reads. However, if raw_mode is not set, we'll do extra
6623 		 * checks below.
6624 		 */
6625 		bounds_check_type = BPF_WRITE;
6626 		clobber = true;
6627 	} else {
6628 		bounds_check_type = BPF_READ;
6629 	}
6630 	err = check_stack_access_within_bounds(env, regno, off, access_size,
6631 					       type, bounds_check_type);
6632 	if (err)
6633 		return err;
6634 
6635 
6636 	if (tnum_is_const(reg->var_off)) {
6637 		min_off = max_off = reg->var_off.value + off;
6638 	} else {
6639 		/* Variable offset is prohibited for unprivileged mode for
6640 		 * simplicity since it requires corresponding support in
6641 		 * Spectre masking for stack ALU.
6642 		 * See also retrieve_ptr_limit().
6643 		 */
6644 		if (!env->bypass_spec_v1) {
6645 			char tn_buf[48];
6646 
6647 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6648 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6649 				regno, err_extra, tn_buf);
6650 			return -EACCES;
6651 		}
6652 		/* Only initialized buffer on stack is allowed to be accessed
6653 		 * with variable offset. With uninitialized buffer it's hard to
6654 		 * guarantee that whole memory is marked as initialized on
6655 		 * helper return since specific bounds are unknown what may
6656 		 * cause uninitialized stack leaking.
6657 		 */
6658 		if (meta && meta->raw_mode)
6659 			meta = NULL;
6660 
6661 		min_off = reg->smin_value + off;
6662 		max_off = reg->smax_value + off;
6663 	}
6664 
6665 	if (meta && meta->raw_mode) {
6666 		/* Ensure we won't be overwriting dynptrs when simulating byte
6667 		 * by byte access in check_helper_call using meta.access_size.
6668 		 * This would be a problem if we have a helper in the future
6669 		 * which takes:
6670 		 *
6671 		 *	helper(uninit_mem, len, dynptr)
6672 		 *
6673 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6674 		 * may end up writing to dynptr itself when touching memory from
6675 		 * arg 1. This can be relaxed on a case by case basis for known
6676 		 * safe cases, but reject due to the possibilitiy of aliasing by
6677 		 * default.
6678 		 */
6679 		for (i = min_off; i < max_off + access_size; i++) {
6680 			int stack_off = -i - 1;
6681 
6682 			spi = __get_spi(i);
6683 			/* raw_mode may write past allocated_stack */
6684 			if (state->allocated_stack <= stack_off)
6685 				continue;
6686 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6687 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6688 				return -EACCES;
6689 			}
6690 		}
6691 		meta->access_size = access_size;
6692 		meta->regno = regno;
6693 		return 0;
6694 	}
6695 
6696 	for (i = min_off; i < max_off + access_size; i++) {
6697 		u8 *stype;
6698 
6699 		slot = -i - 1;
6700 		spi = slot / BPF_REG_SIZE;
6701 		if (state->allocated_stack <= slot)
6702 			goto err;
6703 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6704 		if (*stype == STACK_MISC)
6705 			goto mark;
6706 		if ((*stype == STACK_ZERO) ||
6707 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6708 			if (clobber) {
6709 				/* helper can write anything into the stack */
6710 				*stype = STACK_MISC;
6711 			}
6712 			goto mark;
6713 		}
6714 
6715 		if (is_spilled_reg(&state->stack[spi]) &&
6716 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6717 		     env->allow_ptr_leaks)) {
6718 			if (clobber) {
6719 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6720 				for (j = 0; j < BPF_REG_SIZE; j++)
6721 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6722 			}
6723 			goto mark;
6724 		}
6725 
6726 err:
6727 		if (tnum_is_const(reg->var_off)) {
6728 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6729 				err_extra, regno, min_off, i - min_off, access_size);
6730 		} else {
6731 			char tn_buf[48];
6732 
6733 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6734 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6735 				err_extra, regno, tn_buf, i - min_off, access_size);
6736 		}
6737 		return -EACCES;
6738 mark:
6739 		/* reading any byte out of 8-byte 'spill_slot' will cause
6740 		 * the whole slot to be marked as 'read'
6741 		 */
6742 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6743 			      state->stack[spi].spilled_ptr.parent,
6744 			      REG_LIVE_READ64);
6745 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6746 		 * be sure that whether stack slot is written to or not. Hence,
6747 		 * we must still conservatively propagate reads upwards even if
6748 		 * helper may write to the entire memory range.
6749 		 */
6750 	}
6751 	return update_stack_depth(env, state, min_off);
6752 }
6753 
6754 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6755 				   int access_size, bool zero_size_allowed,
6756 				   struct bpf_call_arg_meta *meta)
6757 {
6758 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6759 	u32 *max_access;
6760 
6761 	switch (base_type(reg->type)) {
6762 	case PTR_TO_PACKET:
6763 	case PTR_TO_PACKET_META:
6764 		return check_packet_access(env, regno, reg->off, access_size,
6765 					   zero_size_allowed);
6766 	case PTR_TO_MAP_KEY:
6767 		if (meta && meta->raw_mode) {
6768 			verbose(env, "R%d cannot write into %s\n", regno,
6769 				reg_type_str(env, reg->type));
6770 			return -EACCES;
6771 		}
6772 		return check_mem_region_access(env, regno, reg->off, access_size,
6773 					       reg->map_ptr->key_size, false);
6774 	case PTR_TO_MAP_VALUE:
6775 		if (check_map_access_type(env, regno, reg->off, access_size,
6776 					  meta && meta->raw_mode ? BPF_WRITE :
6777 					  BPF_READ))
6778 			return -EACCES;
6779 		return check_map_access(env, regno, reg->off, access_size,
6780 					zero_size_allowed, ACCESS_HELPER);
6781 	case PTR_TO_MEM:
6782 		if (type_is_rdonly_mem(reg->type)) {
6783 			if (meta && meta->raw_mode) {
6784 				verbose(env, "R%d cannot write into %s\n", regno,
6785 					reg_type_str(env, reg->type));
6786 				return -EACCES;
6787 			}
6788 		}
6789 		return check_mem_region_access(env, regno, reg->off,
6790 					       access_size, reg->mem_size,
6791 					       zero_size_allowed);
6792 	case PTR_TO_BUF:
6793 		if (type_is_rdonly_mem(reg->type)) {
6794 			if (meta && meta->raw_mode) {
6795 				verbose(env, "R%d cannot write into %s\n", regno,
6796 					reg_type_str(env, reg->type));
6797 				return -EACCES;
6798 			}
6799 
6800 			max_access = &env->prog->aux->max_rdonly_access;
6801 		} else {
6802 			max_access = &env->prog->aux->max_rdwr_access;
6803 		}
6804 		return check_buffer_access(env, reg, regno, reg->off,
6805 					   access_size, zero_size_allowed,
6806 					   max_access);
6807 	case PTR_TO_STACK:
6808 		return check_stack_range_initialized(
6809 				env,
6810 				regno, reg->off, access_size,
6811 				zero_size_allowed, ACCESS_HELPER, meta);
6812 	case PTR_TO_BTF_ID:
6813 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
6814 					       access_size, BPF_READ, -1);
6815 	case PTR_TO_CTX:
6816 		/* in case the function doesn't know how to access the context,
6817 		 * (because we are in a program of type SYSCALL for example), we
6818 		 * can not statically check its size.
6819 		 * Dynamically check it now.
6820 		 */
6821 		if (!env->ops->convert_ctx_access) {
6822 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6823 			int offset = access_size - 1;
6824 
6825 			/* Allow zero-byte read from PTR_TO_CTX */
6826 			if (access_size == 0)
6827 				return zero_size_allowed ? 0 : -EACCES;
6828 
6829 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6830 						atype, -1, false);
6831 		}
6832 
6833 		fallthrough;
6834 	default: /* scalar_value or invalid ptr */
6835 		/* Allow zero-byte read from NULL, regardless of pointer type */
6836 		if (zero_size_allowed && access_size == 0 &&
6837 		    register_is_null(reg))
6838 			return 0;
6839 
6840 		verbose(env, "R%d type=%s ", regno,
6841 			reg_type_str(env, reg->type));
6842 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6843 		return -EACCES;
6844 	}
6845 }
6846 
6847 static int check_mem_size_reg(struct bpf_verifier_env *env,
6848 			      struct bpf_reg_state *reg, u32 regno,
6849 			      bool zero_size_allowed,
6850 			      struct bpf_call_arg_meta *meta)
6851 {
6852 	int err;
6853 
6854 	/* This is used to refine r0 return value bounds for helpers
6855 	 * that enforce this value as an upper bound on return values.
6856 	 * See do_refine_retval_range() for helpers that can refine
6857 	 * the return value. C type of helper is u32 so we pull register
6858 	 * bound from umax_value however, if negative verifier errors
6859 	 * out. Only upper bounds can be learned because retval is an
6860 	 * int type and negative retvals are allowed.
6861 	 */
6862 	meta->msize_max_value = reg->umax_value;
6863 
6864 	/* The register is SCALAR_VALUE; the access check
6865 	 * happens using its boundaries.
6866 	 */
6867 	if (!tnum_is_const(reg->var_off))
6868 		/* For unprivileged variable accesses, disable raw
6869 		 * mode so that the program is required to
6870 		 * initialize all the memory that the helper could
6871 		 * just partially fill up.
6872 		 */
6873 		meta = NULL;
6874 
6875 	if (reg->smin_value < 0) {
6876 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6877 			regno);
6878 		return -EACCES;
6879 	}
6880 
6881 	if (reg->umin_value == 0) {
6882 		err = check_helper_mem_access(env, regno - 1, 0,
6883 					      zero_size_allowed,
6884 					      meta);
6885 		if (err)
6886 			return err;
6887 	}
6888 
6889 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6890 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6891 			regno);
6892 		return -EACCES;
6893 	}
6894 	err = check_helper_mem_access(env, regno - 1,
6895 				      reg->umax_value,
6896 				      zero_size_allowed, meta);
6897 	if (!err)
6898 		err = mark_chain_precision(env, regno);
6899 	return err;
6900 }
6901 
6902 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6903 		   u32 regno, u32 mem_size)
6904 {
6905 	bool may_be_null = type_may_be_null(reg->type);
6906 	struct bpf_reg_state saved_reg;
6907 	struct bpf_call_arg_meta meta;
6908 	int err;
6909 
6910 	if (register_is_null(reg))
6911 		return 0;
6912 
6913 	memset(&meta, 0, sizeof(meta));
6914 	/* Assuming that the register contains a value check if the memory
6915 	 * access is safe. Temporarily save and restore the register's state as
6916 	 * the conversion shouldn't be visible to a caller.
6917 	 */
6918 	if (may_be_null) {
6919 		saved_reg = *reg;
6920 		mark_ptr_not_null_reg(reg);
6921 	}
6922 
6923 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6924 	/* Check access for BPF_WRITE */
6925 	meta.raw_mode = true;
6926 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6927 
6928 	if (may_be_null)
6929 		*reg = saved_reg;
6930 
6931 	return err;
6932 }
6933 
6934 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6935 				    u32 regno)
6936 {
6937 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6938 	bool may_be_null = type_may_be_null(mem_reg->type);
6939 	struct bpf_reg_state saved_reg;
6940 	struct bpf_call_arg_meta meta;
6941 	int err;
6942 
6943 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6944 
6945 	memset(&meta, 0, sizeof(meta));
6946 
6947 	if (may_be_null) {
6948 		saved_reg = *mem_reg;
6949 		mark_ptr_not_null_reg(mem_reg);
6950 	}
6951 
6952 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6953 	/* Check access for BPF_WRITE */
6954 	meta.raw_mode = true;
6955 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6956 
6957 	if (may_be_null)
6958 		*mem_reg = saved_reg;
6959 	return err;
6960 }
6961 
6962 /* Implementation details:
6963  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6964  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6965  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6966  * Two separate bpf_obj_new will also have different reg->id.
6967  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6968  * clears reg->id after value_or_null->value transition, since the verifier only
6969  * cares about the range of access to valid map value pointer and doesn't care
6970  * about actual address of the map element.
6971  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6972  * reg->id > 0 after value_or_null->value transition. By doing so
6973  * two bpf_map_lookups will be considered two different pointers that
6974  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6975  * returned from bpf_obj_new.
6976  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6977  * dead-locks.
6978  * Since only one bpf_spin_lock is allowed the checks are simpler than
6979  * reg_is_refcounted() logic. The verifier needs to remember only
6980  * one spin_lock instead of array of acquired_refs.
6981  * cur_state->active_lock remembers which map value element or allocated
6982  * object got locked and clears it after bpf_spin_unlock.
6983  */
6984 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6985 			     bool is_lock)
6986 {
6987 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6988 	struct bpf_verifier_state *cur = env->cur_state;
6989 	bool is_const = tnum_is_const(reg->var_off);
6990 	u64 val = reg->var_off.value;
6991 	struct bpf_map *map = NULL;
6992 	struct btf *btf = NULL;
6993 	struct btf_record *rec;
6994 
6995 	if (!is_const) {
6996 		verbose(env,
6997 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6998 			regno);
6999 		return -EINVAL;
7000 	}
7001 	if (reg->type == PTR_TO_MAP_VALUE) {
7002 		map = reg->map_ptr;
7003 		if (!map->btf) {
7004 			verbose(env,
7005 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7006 				map->name);
7007 			return -EINVAL;
7008 		}
7009 	} else {
7010 		btf = reg->btf;
7011 	}
7012 
7013 	rec = reg_btf_record(reg);
7014 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7015 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7016 			map ? map->name : "kptr");
7017 		return -EINVAL;
7018 	}
7019 	if (rec->spin_lock_off != val + reg->off) {
7020 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7021 			val + reg->off, rec->spin_lock_off);
7022 		return -EINVAL;
7023 	}
7024 	if (is_lock) {
7025 		if (cur->active_lock.ptr) {
7026 			verbose(env,
7027 				"Locking two bpf_spin_locks are not allowed\n");
7028 			return -EINVAL;
7029 		}
7030 		if (map)
7031 			cur->active_lock.ptr = map;
7032 		else
7033 			cur->active_lock.ptr = btf;
7034 		cur->active_lock.id = reg->id;
7035 	} else {
7036 		void *ptr;
7037 
7038 		if (map)
7039 			ptr = map;
7040 		else
7041 			ptr = btf;
7042 
7043 		if (!cur->active_lock.ptr) {
7044 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7045 			return -EINVAL;
7046 		}
7047 		if (cur->active_lock.ptr != ptr ||
7048 		    cur->active_lock.id != reg->id) {
7049 			verbose(env, "bpf_spin_unlock of different lock\n");
7050 			return -EINVAL;
7051 		}
7052 
7053 		invalidate_non_owning_refs(env);
7054 
7055 		cur->active_lock.ptr = NULL;
7056 		cur->active_lock.id = 0;
7057 	}
7058 	return 0;
7059 }
7060 
7061 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7062 			      struct bpf_call_arg_meta *meta)
7063 {
7064 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7065 	bool is_const = tnum_is_const(reg->var_off);
7066 	struct bpf_map *map = reg->map_ptr;
7067 	u64 val = reg->var_off.value;
7068 
7069 	if (!is_const) {
7070 		verbose(env,
7071 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7072 			regno);
7073 		return -EINVAL;
7074 	}
7075 	if (!map->btf) {
7076 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7077 			map->name);
7078 		return -EINVAL;
7079 	}
7080 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7081 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7082 		return -EINVAL;
7083 	}
7084 	if (map->record->timer_off != val + reg->off) {
7085 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7086 			val + reg->off, map->record->timer_off);
7087 		return -EINVAL;
7088 	}
7089 	if (meta->map_ptr) {
7090 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7091 		return -EFAULT;
7092 	}
7093 	meta->map_uid = reg->map_uid;
7094 	meta->map_ptr = map;
7095 	return 0;
7096 }
7097 
7098 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7099 			     struct bpf_call_arg_meta *meta)
7100 {
7101 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7102 	struct bpf_map *map_ptr = reg->map_ptr;
7103 	struct btf_field *kptr_field;
7104 	u32 kptr_off;
7105 
7106 	if (!tnum_is_const(reg->var_off)) {
7107 		verbose(env,
7108 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7109 			regno);
7110 		return -EINVAL;
7111 	}
7112 	if (!map_ptr->btf) {
7113 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7114 			map_ptr->name);
7115 		return -EINVAL;
7116 	}
7117 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7118 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7119 		return -EINVAL;
7120 	}
7121 
7122 	meta->map_ptr = map_ptr;
7123 	kptr_off = reg->off + reg->var_off.value;
7124 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7125 	if (!kptr_field) {
7126 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7127 		return -EACCES;
7128 	}
7129 	if (kptr_field->type != BPF_KPTR_REF) {
7130 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7131 		return -EACCES;
7132 	}
7133 	meta->kptr_field = kptr_field;
7134 	return 0;
7135 }
7136 
7137 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7138  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7139  *
7140  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7141  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7142  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7143  *
7144  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7145  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7146  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7147  * mutate the view of the dynptr and also possibly destroy it. In the latter
7148  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7149  * memory that dynptr points to.
7150  *
7151  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7152  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7153  * readonly dynptr view yet, hence only the first case is tracked and checked.
7154  *
7155  * This is consistent with how C applies the const modifier to a struct object,
7156  * where the pointer itself inside bpf_dynptr becomes const but not what it
7157  * points to.
7158  *
7159  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7160  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7161  */
7162 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7163 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7164 {
7165 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7166 	int err;
7167 
7168 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7169 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7170 	 */
7171 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7172 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7173 		return -EFAULT;
7174 	}
7175 
7176 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7177 	 *		 constructing a mutable bpf_dynptr object.
7178 	 *
7179 	 *		 Currently, this is only possible with PTR_TO_STACK
7180 	 *		 pointing to a region of at least 16 bytes which doesn't
7181 	 *		 contain an existing bpf_dynptr.
7182 	 *
7183 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7184 	 *		 mutated or destroyed. However, the memory it points to
7185 	 *		 may be mutated.
7186 	 *
7187 	 *  None       - Points to a initialized dynptr that can be mutated and
7188 	 *		 destroyed, including mutation of the memory it points
7189 	 *		 to.
7190 	 */
7191 	if (arg_type & MEM_UNINIT) {
7192 		int i;
7193 
7194 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7195 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7196 			return -EINVAL;
7197 		}
7198 
7199 		/* we write BPF_DW bits (8 bytes) at a time */
7200 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7201 			err = check_mem_access(env, insn_idx, regno,
7202 					       i, BPF_DW, BPF_WRITE, -1, false);
7203 			if (err)
7204 				return err;
7205 		}
7206 
7207 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7208 	} else /* MEM_RDONLY and None case from above */ {
7209 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7210 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7211 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7212 			return -EINVAL;
7213 		}
7214 
7215 		if (!is_dynptr_reg_valid_init(env, reg)) {
7216 			verbose(env,
7217 				"Expected an initialized dynptr as arg #%d\n",
7218 				regno);
7219 			return -EINVAL;
7220 		}
7221 
7222 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7223 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7224 			verbose(env,
7225 				"Expected a dynptr of type %s as arg #%d\n",
7226 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7227 			return -EINVAL;
7228 		}
7229 
7230 		err = mark_dynptr_read(env, reg);
7231 	}
7232 	return err;
7233 }
7234 
7235 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7236 {
7237 	struct bpf_func_state *state = func(env, reg);
7238 
7239 	return state->stack[spi].spilled_ptr.ref_obj_id;
7240 }
7241 
7242 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7243 {
7244 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7245 }
7246 
7247 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7248 {
7249 	return meta->kfunc_flags & KF_ITER_NEW;
7250 }
7251 
7252 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7253 {
7254 	return meta->kfunc_flags & KF_ITER_NEXT;
7255 }
7256 
7257 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7258 {
7259 	return meta->kfunc_flags & KF_ITER_DESTROY;
7260 }
7261 
7262 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7263 {
7264 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7265 	 * kfunc is iter state pointer
7266 	 */
7267 	return arg == 0 && is_iter_kfunc(meta);
7268 }
7269 
7270 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7271 			    struct bpf_kfunc_call_arg_meta *meta)
7272 {
7273 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7274 	const struct btf_type *t;
7275 	const struct btf_param *arg;
7276 	int spi, err, i, nr_slots;
7277 	u32 btf_id;
7278 
7279 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7280 	arg = &btf_params(meta->func_proto)[0];
7281 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7282 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7283 	nr_slots = t->size / BPF_REG_SIZE;
7284 
7285 	if (is_iter_new_kfunc(meta)) {
7286 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7287 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7288 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7289 				iter_type_str(meta->btf, btf_id), regno);
7290 			return -EINVAL;
7291 		}
7292 
7293 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7294 			err = check_mem_access(env, insn_idx, regno,
7295 					       i, BPF_DW, BPF_WRITE, -1, false);
7296 			if (err)
7297 				return err;
7298 		}
7299 
7300 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7301 		if (err)
7302 			return err;
7303 	} else {
7304 		/* iter_next() or iter_destroy() expect initialized iter state*/
7305 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7306 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7307 				iter_type_str(meta->btf, btf_id), regno);
7308 			return -EINVAL;
7309 		}
7310 
7311 		spi = iter_get_spi(env, reg, nr_slots);
7312 		if (spi < 0)
7313 			return spi;
7314 
7315 		err = mark_iter_read(env, reg, spi, nr_slots);
7316 		if (err)
7317 			return err;
7318 
7319 		/* remember meta->iter info for process_iter_next_call() */
7320 		meta->iter.spi = spi;
7321 		meta->iter.frameno = reg->frameno;
7322 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7323 
7324 		if (is_iter_destroy_kfunc(meta)) {
7325 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7326 			if (err)
7327 				return err;
7328 		}
7329 	}
7330 
7331 	return 0;
7332 }
7333 
7334 /* process_iter_next_call() is called when verifier gets to iterator's next
7335  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7336  * to it as just "iter_next()" in comments below.
7337  *
7338  * BPF verifier relies on a crucial contract for any iter_next()
7339  * implementation: it should *eventually* return NULL, and once that happens
7340  * it should keep returning NULL. That is, once iterator exhausts elements to
7341  * iterate, it should never reset or spuriously return new elements.
7342  *
7343  * With the assumption of such contract, process_iter_next_call() simulates
7344  * a fork in the verifier state to validate loop logic correctness and safety
7345  * without having to simulate infinite amount of iterations.
7346  *
7347  * In current state, we first assume that iter_next() returned NULL and
7348  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7349  * conditions we should not form an infinite loop and should eventually reach
7350  * exit.
7351  *
7352  * Besides that, we also fork current state and enqueue it for later
7353  * verification. In a forked state we keep iterator state as ACTIVE
7354  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7355  * also bump iteration depth to prevent erroneous infinite loop detection
7356  * later on (see iter_active_depths_differ() comment for details). In this
7357  * state we assume that we'll eventually loop back to another iter_next()
7358  * calls (it could be in exactly same location or in some other instruction,
7359  * it doesn't matter, we don't make any unnecessary assumptions about this,
7360  * everything revolves around iterator state in a stack slot, not which
7361  * instruction is calling iter_next()). When that happens, we either will come
7362  * to iter_next() with equivalent state and can conclude that next iteration
7363  * will proceed in exactly the same way as we just verified, so it's safe to
7364  * assume that loop converges. If not, we'll go on another iteration
7365  * simulation with a different input state, until all possible starting states
7366  * are validated or we reach maximum number of instructions limit.
7367  *
7368  * This way, we will either exhaustively discover all possible input states
7369  * that iterator loop can start with and eventually will converge, or we'll
7370  * effectively regress into bounded loop simulation logic and either reach
7371  * maximum number of instructions if loop is not provably convergent, or there
7372  * is some statically known limit on number of iterations (e.g., if there is
7373  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7374  *
7375  * One very subtle but very important aspect is that we *always* simulate NULL
7376  * condition first (as the current state) before we simulate non-NULL case.
7377  * This has to do with intricacies of scalar precision tracking. By simulating
7378  * "exit condition" of iter_next() returning NULL first, we make sure all the
7379  * relevant precision marks *that will be set **after** we exit iterator loop*
7380  * are propagated backwards to common parent state of NULL and non-NULL
7381  * branches. Thanks to that, state equivalence checks done later in forked
7382  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7383  * precision marks are finalized and won't change. Because simulating another
7384  * ACTIVE iterator iteration won't change them (because given same input
7385  * states we'll end up with exactly same output states which we are currently
7386  * comparing; and verification after the loop already propagated back what
7387  * needs to be **additionally** tracked as precise). It's subtle, grok
7388  * precision tracking for more intuitive understanding.
7389  */
7390 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7391 				  struct bpf_kfunc_call_arg_meta *meta)
7392 {
7393 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7394 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7395 	struct bpf_reg_state *cur_iter, *queued_iter;
7396 	int iter_frameno = meta->iter.frameno;
7397 	int iter_spi = meta->iter.spi;
7398 
7399 	BTF_TYPE_EMIT(struct bpf_iter);
7400 
7401 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7402 
7403 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7404 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7405 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7406 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7407 		return -EFAULT;
7408 	}
7409 
7410 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7411 		/* branch out active iter state */
7412 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7413 		if (!queued_st)
7414 			return -ENOMEM;
7415 
7416 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7417 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7418 		queued_iter->iter.depth++;
7419 
7420 		queued_fr = queued_st->frame[queued_st->curframe];
7421 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7422 	}
7423 
7424 	/* switch to DRAINED state, but keep the depth unchanged */
7425 	/* mark current iter state as drained and assume returned NULL */
7426 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7427 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7428 
7429 	return 0;
7430 }
7431 
7432 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7433 {
7434 	return type == ARG_CONST_SIZE ||
7435 	       type == ARG_CONST_SIZE_OR_ZERO;
7436 }
7437 
7438 static bool arg_type_is_release(enum bpf_arg_type type)
7439 {
7440 	return type & OBJ_RELEASE;
7441 }
7442 
7443 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7444 {
7445 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7446 }
7447 
7448 static int int_ptr_type_to_size(enum bpf_arg_type type)
7449 {
7450 	if (type == ARG_PTR_TO_INT)
7451 		return sizeof(u32);
7452 	else if (type == ARG_PTR_TO_LONG)
7453 		return sizeof(u64);
7454 
7455 	return -EINVAL;
7456 }
7457 
7458 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7459 				 const struct bpf_call_arg_meta *meta,
7460 				 enum bpf_arg_type *arg_type)
7461 {
7462 	if (!meta->map_ptr) {
7463 		/* kernel subsystem misconfigured verifier */
7464 		verbose(env, "invalid map_ptr to access map->type\n");
7465 		return -EACCES;
7466 	}
7467 
7468 	switch (meta->map_ptr->map_type) {
7469 	case BPF_MAP_TYPE_SOCKMAP:
7470 	case BPF_MAP_TYPE_SOCKHASH:
7471 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7472 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7473 		} else {
7474 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7475 			return -EINVAL;
7476 		}
7477 		break;
7478 	case BPF_MAP_TYPE_BLOOM_FILTER:
7479 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7480 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7481 		break;
7482 	default:
7483 		break;
7484 	}
7485 	return 0;
7486 }
7487 
7488 struct bpf_reg_types {
7489 	const enum bpf_reg_type types[10];
7490 	u32 *btf_id;
7491 };
7492 
7493 static const struct bpf_reg_types sock_types = {
7494 	.types = {
7495 		PTR_TO_SOCK_COMMON,
7496 		PTR_TO_SOCKET,
7497 		PTR_TO_TCP_SOCK,
7498 		PTR_TO_XDP_SOCK,
7499 	},
7500 };
7501 
7502 #ifdef CONFIG_NET
7503 static const struct bpf_reg_types btf_id_sock_common_types = {
7504 	.types = {
7505 		PTR_TO_SOCK_COMMON,
7506 		PTR_TO_SOCKET,
7507 		PTR_TO_TCP_SOCK,
7508 		PTR_TO_XDP_SOCK,
7509 		PTR_TO_BTF_ID,
7510 		PTR_TO_BTF_ID | PTR_TRUSTED,
7511 	},
7512 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7513 };
7514 #endif
7515 
7516 static const struct bpf_reg_types mem_types = {
7517 	.types = {
7518 		PTR_TO_STACK,
7519 		PTR_TO_PACKET,
7520 		PTR_TO_PACKET_META,
7521 		PTR_TO_MAP_KEY,
7522 		PTR_TO_MAP_VALUE,
7523 		PTR_TO_MEM,
7524 		PTR_TO_MEM | MEM_RINGBUF,
7525 		PTR_TO_BUF,
7526 		PTR_TO_BTF_ID | PTR_TRUSTED,
7527 	},
7528 };
7529 
7530 static const struct bpf_reg_types int_ptr_types = {
7531 	.types = {
7532 		PTR_TO_STACK,
7533 		PTR_TO_PACKET,
7534 		PTR_TO_PACKET_META,
7535 		PTR_TO_MAP_KEY,
7536 		PTR_TO_MAP_VALUE,
7537 	},
7538 };
7539 
7540 static const struct bpf_reg_types spin_lock_types = {
7541 	.types = {
7542 		PTR_TO_MAP_VALUE,
7543 		PTR_TO_BTF_ID | MEM_ALLOC,
7544 	}
7545 };
7546 
7547 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7548 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7549 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7550 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7551 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7552 static const struct bpf_reg_types btf_ptr_types = {
7553 	.types = {
7554 		PTR_TO_BTF_ID,
7555 		PTR_TO_BTF_ID | PTR_TRUSTED,
7556 		PTR_TO_BTF_ID | MEM_RCU,
7557 	},
7558 };
7559 static const struct bpf_reg_types percpu_btf_ptr_types = {
7560 	.types = {
7561 		PTR_TO_BTF_ID | MEM_PERCPU,
7562 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7563 	}
7564 };
7565 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7566 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7567 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7568 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7569 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7570 static const struct bpf_reg_types dynptr_types = {
7571 	.types = {
7572 		PTR_TO_STACK,
7573 		CONST_PTR_TO_DYNPTR,
7574 	}
7575 };
7576 
7577 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7578 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7579 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7580 	[ARG_CONST_SIZE]		= &scalar_types,
7581 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7582 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7583 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7584 	[ARG_PTR_TO_CTX]		= &context_types,
7585 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7586 #ifdef CONFIG_NET
7587 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7588 #endif
7589 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7590 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7591 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7592 	[ARG_PTR_TO_MEM]		= &mem_types,
7593 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7594 	[ARG_PTR_TO_INT]		= &int_ptr_types,
7595 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
7596 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7597 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7598 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7599 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7600 	[ARG_PTR_TO_TIMER]		= &timer_types,
7601 	[ARG_PTR_TO_KPTR]		= &kptr_types,
7602 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7603 };
7604 
7605 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7606 			  enum bpf_arg_type arg_type,
7607 			  const u32 *arg_btf_id,
7608 			  struct bpf_call_arg_meta *meta)
7609 {
7610 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7611 	enum bpf_reg_type expected, type = reg->type;
7612 	const struct bpf_reg_types *compatible;
7613 	int i, j;
7614 
7615 	compatible = compatible_reg_types[base_type(arg_type)];
7616 	if (!compatible) {
7617 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7618 		return -EFAULT;
7619 	}
7620 
7621 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7622 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7623 	 *
7624 	 * Same for MAYBE_NULL:
7625 	 *
7626 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7627 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7628 	 *
7629 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7630 	 *
7631 	 * Therefore we fold these flags depending on the arg_type before comparison.
7632 	 */
7633 	if (arg_type & MEM_RDONLY)
7634 		type &= ~MEM_RDONLY;
7635 	if (arg_type & PTR_MAYBE_NULL)
7636 		type &= ~PTR_MAYBE_NULL;
7637 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7638 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7639 
7640 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7641 		type &= ~MEM_ALLOC;
7642 
7643 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7644 		expected = compatible->types[i];
7645 		if (expected == NOT_INIT)
7646 			break;
7647 
7648 		if (type == expected)
7649 			goto found;
7650 	}
7651 
7652 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7653 	for (j = 0; j + 1 < i; j++)
7654 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7655 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7656 	return -EACCES;
7657 
7658 found:
7659 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7660 		return 0;
7661 
7662 	if (compatible == &mem_types) {
7663 		if (!(arg_type & MEM_RDONLY)) {
7664 			verbose(env,
7665 				"%s() may write into memory pointed by R%d type=%s\n",
7666 				func_id_name(meta->func_id),
7667 				regno, reg_type_str(env, reg->type));
7668 			return -EACCES;
7669 		}
7670 		return 0;
7671 	}
7672 
7673 	switch ((int)reg->type) {
7674 	case PTR_TO_BTF_ID:
7675 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7676 	case PTR_TO_BTF_ID | MEM_RCU:
7677 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7678 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7679 	{
7680 		/* For bpf_sk_release, it needs to match against first member
7681 		 * 'struct sock_common', hence make an exception for it. This
7682 		 * allows bpf_sk_release to work for multiple socket types.
7683 		 */
7684 		bool strict_type_match = arg_type_is_release(arg_type) &&
7685 					 meta->func_id != BPF_FUNC_sk_release;
7686 
7687 		if (type_may_be_null(reg->type) &&
7688 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7689 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7690 			return -EACCES;
7691 		}
7692 
7693 		if (!arg_btf_id) {
7694 			if (!compatible->btf_id) {
7695 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7696 				return -EFAULT;
7697 			}
7698 			arg_btf_id = compatible->btf_id;
7699 		}
7700 
7701 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7702 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7703 				return -EACCES;
7704 		} else {
7705 			if (arg_btf_id == BPF_PTR_POISON) {
7706 				verbose(env, "verifier internal error:");
7707 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7708 					regno);
7709 				return -EACCES;
7710 			}
7711 
7712 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7713 						  btf_vmlinux, *arg_btf_id,
7714 						  strict_type_match)) {
7715 				verbose(env, "R%d is of type %s but %s is expected\n",
7716 					regno, btf_type_name(reg->btf, reg->btf_id),
7717 					btf_type_name(btf_vmlinux, *arg_btf_id));
7718 				return -EACCES;
7719 			}
7720 		}
7721 		break;
7722 	}
7723 	case PTR_TO_BTF_ID | MEM_ALLOC:
7724 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7725 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7726 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7727 			return -EFAULT;
7728 		}
7729 		/* Handled by helper specific checks */
7730 		break;
7731 	case PTR_TO_BTF_ID | MEM_PERCPU:
7732 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7733 		/* Handled by helper specific checks */
7734 		break;
7735 	default:
7736 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7737 		return -EFAULT;
7738 	}
7739 	return 0;
7740 }
7741 
7742 static struct btf_field *
7743 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7744 {
7745 	struct btf_field *field;
7746 	struct btf_record *rec;
7747 
7748 	rec = reg_btf_record(reg);
7749 	if (!rec)
7750 		return NULL;
7751 
7752 	field = btf_record_find(rec, off, fields);
7753 	if (!field)
7754 		return NULL;
7755 
7756 	return field;
7757 }
7758 
7759 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7760 			   const struct bpf_reg_state *reg, int regno,
7761 			   enum bpf_arg_type arg_type)
7762 {
7763 	u32 type = reg->type;
7764 
7765 	/* When referenced register is passed to release function, its fixed
7766 	 * offset must be 0.
7767 	 *
7768 	 * We will check arg_type_is_release reg has ref_obj_id when storing
7769 	 * meta->release_regno.
7770 	 */
7771 	if (arg_type_is_release(arg_type)) {
7772 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7773 		 * may not directly point to the object being released, but to
7774 		 * dynptr pointing to such object, which might be at some offset
7775 		 * on the stack. In that case, we simply to fallback to the
7776 		 * default handling.
7777 		 */
7778 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7779 			return 0;
7780 
7781 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7782 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7783 				return __check_ptr_off_reg(env, reg, regno, true);
7784 
7785 			verbose(env, "R%d must have zero offset when passed to release func\n",
7786 				regno);
7787 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7788 				btf_type_name(reg->btf, reg->btf_id), reg->off);
7789 			return -EINVAL;
7790 		}
7791 
7792 		/* Doing check_ptr_off_reg check for the offset will catch this
7793 		 * because fixed_off_ok is false, but checking here allows us
7794 		 * to give the user a better error message.
7795 		 */
7796 		if (reg->off) {
7797 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7798 				regno);
7799 			return -EINVAL;
7800 		}
7801 		return __check_ptr_off_reg(env, reg, regno, false);
7802 	}
7803 
7804 	switch (type) {
7805 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
7806 	case PTR_TO_STACK:
7807 	case PTR_TO_PACKET:
7808 	case PTR_TO_PACKET_META:
7809 	case PTR_TO_MAP_KEY:
7810 	case PTR_TO_MAP_VALUE:
7811 	case PTR_TO_MEM:
7812 	case PTR_TO_MEM | MEM_RDONLY:
7813 	case PTR_TO_MEM | MEM_RINGBUF:
7814 	case PTR_TO_BUF:
7815 	case PTR_TO_BUF | MEM_RDONLY:
7816 	case SCALAR_VALUE:
7817 		return 0;
7818 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7819 	 * fixed offset.
7820 	 */
7821 	case PTR_TO_BTF_ID:
7822 	case PTR_TO_BTF_ID | MEM_ALLOC:
7823 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7824 	case PTR_TO_BTF_ID | MEM_RCU:
7825 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7826 		/* When referenced PTR_TO_BTF_ID is passed to release function,
7827 		 * its fixed offset must be 0. In the other cases, fixed offset
7828 		 * can be non-zero. This was already checked above. So pass
7829 		 * fixed_off_ok as true to allow fixed offset for all other
7830 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7831 		 * still need to do checks instead of returning.
7832 		 */
7833 		return __check_ptr_off_reg(env, reg, regno, true);
7834 	default:
7835 		return __check_ptr_off_reg(env, reg, regno, false);
7836 	}
7837 }
7838 
7839 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7840 						const struct bpf_func_proto *fn,
7841 						struct bpf_reg_state *regs)
7842 {
7843 	struct bpf_reg_state *state = NULL;
7844 	int i;
7845 
7846 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7847 		if (arg_type_is_dynptr(fn->arg_type[i])) {
7848 			if (state) {
7849 				verbose(env, "verifier internal error: multiple dynptr args\n");
7850 				return NULL;
7851 			}
7852 			state = &regs[BPF_REG_1 + i];
7853 		}
7854 
7855 	if (!state)
7856 		verbose(env, "verifier internal error: no dynptr arg found\n");
7857 
7858 	return state;
7859 }
7860 
7861 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7862 {
7863 	struct bpf_func_state *state = func(env, reg);
7864 	int spi;
7865 
7866 	if (reg->type == CONST_PTR_TO_DYNPTR)
7867 		return reg->id;
7868 	spi = dynptr_get_spi(env, reg);
7869 	if (spi < 0)
7870 		return spi;
7871 	return state->stack[spi].spilled_ptr.id;
7872 }
7873 
7874 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7875 {
7876 	struct bpf_func_state *state = func(env, reg);
7877 	int spi;
7878 
7879 	if (reg->type == CONST_PTR_TO_DYNPTR)
7880 		return reg->ref_obj_id;
7881 	spi = dynptr_get_spi(env, reg);
7882 	if (spi < 0)
7883 		return spi;
7884 	return state->stack[spi].spilled_ptr.ref_obj_id;
7885 }
7886 
7887 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7888 					    struct bpf_reg_state *reg)
7889 {
7890 	struct bpf_func_state *state = func(env, reg);
7891 	int spi;
7892 
7893 	if (reg->type == CONST_PTR_TO_DYNPTR)
7894 		return reg->dynptr.type;
7895 
7896 	spi = __get_spi(reg->off);
7897 	if (spi < 0) {
7898 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7899 		return BPF_DYNPTR_TYPE_INVALID;
7900 	}
7901 
7902 	return state->stack[spi].spilled_ptr.dynptr.type;
7903 }
7904 
7905 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7906 			  struct bpf_call_arg_meta *meta,
7907 			  const struct bpf_func_proto *fn,
7908 			  int insn_idx)
7909 {
7910 	u32 regno = BPF_REG_1 + arg;
7911 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7912 	enum bpf_arg_type arg_type = fn->arg_type[arg];
7913 	enum bpf_reg_type type = reg->type;
7914 	u32 *arg_btf_id = NULL;
7915 	int err = 0;
7916 
7917 	if (arg_type == ARG_DONTCARE)
7918 		return 0;
7919 
7920 	err = check_reg_arg(env, regno, SRC_OP);
7921 	if (err)
7922 		return err;
7923 
7924 	if (arg_type == ARG_ANYTHING) {
7925 		if (is_pointer_value(env, regno)) {
7926 			verbose(env, "R%d leaks addr into helper function\n",
7927 				regno);
7928 			return -EACCES;
7929 		}
7930 		return 0;
7931 	}
7932 
7933 	if (type_is_pkt_pointer(type) &&
7934 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7935 		verbose(env, "helper access to the packet is not allowed\n");
7936 		return -EACCES;
7937 	}
7938 
7939 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7940 		err = resolve_map_arg_type(env, meta, &arg_type);
7941 		if (err)
7942 			return err;
7943 	}
7944 
7945 	if (register_is_null(reg) && type_may_be_null(arg_type))
7946 		/* A NULL register has a SCALAR_VALUE type, so skip
7947 		 * type checking.
7948 		 */
7949 		goto skip_type_check;
7950 
7951 	/* arg_btf_id and arg_size are in a union. */
7952 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7953 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7954 		arg_btf_id = fn->arg_btf_id[arg];
7955 
7956 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7957 	if (err)
7958 		return err;
7959 
7960 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7961 	if (err)
7962 		return err;
7963 
7964 skip_type_check:
7965 	if (arg_type_is_release(arg_type)) {
7966 		if (arg_type_is_dynptr(arg_type)) {
7967 			struct bpf_func_state *state = func(env, reg);
7968 			int spi;
7969 
7970 			/* Only dynptr created on stack can be released, thus
7971 			 * the get_spi and stack state checks for spilled_ptr
7972 			 * should only be done before process_dynptr_func for
7973 			 * PTR_TO_STACK.
7974 			 */
7975 			if (reg->type == PTR_TO_STACK) {
7976 				spi = dynptr_get_spi(env, reg);
7977 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7978 					verbose(env, "arg %d is an unacquired reference\n", regno);
7979 					return -EINVAL;
7980 				}
7981 			} else {
7982 				verbose(env, "cannot release unowned const bpf_dynptr\n");
7983 				return -EINVAL;
7984 			}
7985 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
7986 			verbose(env, "R%d must be referenced when passed to release function\n",
7987 				regno);
7988 			return -EINVAL;
7989 		}
7990 		if (meta->release_regno) {
7991 			verbose(env, "verifier internal error: more than one release argument\n");
7992 			return -EFAULT;
7993 		}
7994 		meta->release_regno = regno;
7995 	}
7996 
7997 	if (reg->ref_obj_id) {
7998 		if (meta->ref_obj_id) {
7999 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8000 				regno, reg->ref_obj_id,
8001 				meta->ref_obj_id);
8002 			return -EFAULT;
8003 		}
8004 		meta->ref_obj_id = reg->ref_obj_id;
8005 	}
8006 
8007 	switch (base_type(arg_type)) {
8008 	case ARG_CONST_MAP_PTR:
8009 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8010 		if (meta->map_ptr) {
8011 			/* Use map_uid (which is unique id of inner map) to reject:
8012 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8013 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8014 			 * if (inner_map1 && inner_map2) {
8015 			 *     timer = bpf_map_lookup_elem(inner_map1);
8016 			 *     if (timer)
8017 			 *         // mismatch would have been allowed
8018 			 *         bpf_timer_init(timer, inner_map2);
8019 			 * }
8020 			 *
8021 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8022 			 */
8023 			if (meta->map_ptr != reg->map_ptr ||
8024 			    meta->map_uid != reg->map_uid) {
8025 				verbose(env,
8026 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8027 					meta->map_uid, reg->map_uid);
8028 				return -EINVAL;
8029 			}
8030 		}
8031 		meta->map_ptr = reg->map_ptr;
8032 		meta->map_uid = reg->map_uid;
8033 		break;
8034 	case ARG_PTR_TO_MAP_KEY:
8035 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8036 		 * check that [key, key + map->key_size) are within
8037 		 * stack limits and initialized
8038 		 */
8039 		if (!meta->map_ptr) {
8040 			/* in function declaration map_ptr must come before
8041 			 * map_key, so that it's verified and known before
8042 			 * we have to check map_key here. Otherwise it means
8043 			 * that kernel subsystem misconfigured verifier
8044 			 */
8045 			verbose(env, "invalid map_ptr to access map->key\n");
8046 			return -EACCES;
8047 		}
8048 		err = check_helper_mem_access(env, regno,
8049 					      meta->map_ptr->key_size, false,
8050 					      NULL);
8051 		break;
8052 	case ARG_PTR_TO_MAP_VALUE:
8053 		if (type_may_be_null(arg_type) && register_is_null(reg))
8054 			return 0;
8055 
8056 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8057 		 * check [value, value + map->value_size) validity
8058 		 */
8059 		if (!meta->map_ptr) {
8060 			/* kernel subsystem misconfigured verifier */
8061 			verbose(env, "invalid map_ptr to access map->value\n");
8062 			return -EACCES;
8063 		}
8064 		meta->raw_mode = arg_type & MEM_UNINIT;
8065 		err = check_helper_mem_access(env, regno,
8066 					      meta->map_ptr->value_size, false,
8067 					      meta);
8068 		break;
8069 	case ARG_PTR_TO_PERCPU_BTF_ID:
8070 		if (!reg->btf_id) {
8071 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8072 			return -EACCES;
8073 		}
8074 		meta->ret_btf = reg->btf;
8075 		meta->ret_btf_id = reg->btf_id;
8076 		break;
8077 	case ARG_PTR_TO_SPIN_LOCK:
8078 		if (in_rbtree_lock_required_cb(env)) {
8079 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8080 			return -EACCES;
8081 		}
8082 		if (meta->func_id == BPF_FUNC_spin_lock) {
8083 			err = process_spin_lock(env, regno, true);
8084 			if (err)
8085 				return err;
8086 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8087 			err = process_spin_lock(env, regno, false);
8088 			if (err)
8089 				return err;
8090 		} else {
8091 			verbose(env, "verifier internal error\n");
8092 			return -EFAULT;
8093 		}
8094 		break;
8095 	case ARG_PTR_TO_TIMER:
8096 		err = process_timer_func(env, regno, meta);
8097 		if (err)
8098 			return err;
8099 		break;
8100 	case ARG_PTR_TO_FUNC:
8101 		meta->subprogno = reg->subprogno;
8102 		break;
8103 	case ARG_PTR_TO_MEM:
8104 		/* The access to this pointer is only checked when we hit the
8105 		 * next is_mem_size argument below.
8106 		 */
8107 		meta->raw_mode = arg_type & MEM_UNINIT;
8108 		if (arg_type & MEM_FIXED_SIZE) {
8109 			err = check_helper_mem_access(env, regno,
8110 						      fn->arg_size[arg], false,
8111 						      meta);
8112 		}
8113 		break;
8114 	case ARG_CONST_SIZE:
8115 		err = check_mem_size_reg(env, reg, regno, false, meta);
8116 		break;
8117 	case ARG_CONST_SIZE_OR_ZERO:
8118 		err = check_mem_size_reg(env, reg, regno, true, meta);
8119 		break;
8120 	case ARG_PTR_TO_DYNPTR:
8121 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8122 		if (err)
8123 			return err;
8124 		break;
8125 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8126 		if (!tnum_is_const(reg->var_off)) {
8127 			verbose(env, "R%d is not a known constant'\n",
8128 				regno);
8129 			return -EACCES;
8130 		}
8131 		meta->mem_size = reg->var_off.value;
8132 		err = mark_chain_precision(env, regno);
8133 		if (err)
8134 			return err;
8135 		break;
8136 	case ARG_PTR_TO_INT:
8137 	case ARG_PTR_TO_LONG:
8138 	{
8139 		int size = int_ptr_type_to_size(arg_type);
8140 
8141 		err = check_helper_mem_access(env, regno, size, false, meta);
8142 		if (err)
8143 			return err;
8144 		err = check_ptr_alignment(env, reg, 0, size, true);
8145 		break;
8146 	}
8147 	case ARG_PTR_TO_CONST_STR:
8148 	{
8149 		struct bpf_map *map = reg->map_ptr;
8150 		int map_off;
8151 		u64 map_addr;
8152 		char *str_ptr;
8153 
8154 		if (!bpf_map_is_rdonly(map)) {
8155 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8156 			return -EACCES;
8157 		}
8158 
8159 		if (!tnum_is_const(reg->var_off)) {
8160 			verbose(env, "R%d is not a constant address'\n", regno);
8161 			return -EACCES;
8162 		}
8163 
8164 		if (!map->ops->map_direct_value_addr) {
8165 			verbose(env, "no direct value access support for this map type\n");
8166 			return -EACCES;
8167 		}
8168 
8169 		err = check_map_access(env, regno, reg->off,
8170 				       map->value_size - reg->off, false,
8171 				       ACCESS_HELPER);
8172 		if (err)
8173 			return err;
8174 
8175 		map_off = reg->off + reg->var_off.value;
8176 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8177 		if (err) {
8178 			verbose(env, "direct value access on string failed\n");
8179 			return err;
8180 		}
8181 
8182 		str_ptr = (char *)(long)(map_addr);
8183 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8184 			verbose(env, "string is not zero-terminated\n");
8185 			return -EINVAL;
8186 		}
8187 		break;
8188 	}
8189 	case ARG_PTR_TO_KPTR:
8190 		err = process_kptr_func(env, regno, meta);
8191 		if (err)
8192 			return err;
8193 		break;
8194 	}
8195 
8196 	return err;
8197 }
8198 
8199 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8200 {
8201 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8202 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8203 
8204 	if (func_id != BPF_FUNC_map_update_elem)
8205 		return false;
8206 
8207 	/* It's not possible to get access to a locked struct sock in these
8208 	 * contexts, so updating is safe.
8209 	 */
8210 	switch (type) {
8211 	case BPF_PROG_TYPE_TRACING:
8212 		if (eatype == BPF_TRACE_ITER)
8213 			return true;
8214 		break;
8215 	case BPF_PROG_TYPE_SOCKET_FILTER:
8216 	case BPF_PROG_TYPE_SCHED_CLS:
8217 	case BPF_PROG_TYPE_SCHED_ACT:
8218 	case BPF_PROG_TYPE_XDP:
8219 	case BPF_PROG_TYPE_SK_REUSEPORT:
8220 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8221 	case BPF_PROG_TYPE_SK_LOOKUP:
8222 		return true;
8223 	default:
8224 		break;
8225 	}
8226 
8227 	verbose(env, "cannot update sockmap in this context\n");
8228 	return false;
8229 }
8230 
8231 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8232 {
8233 	return env->prog->jit_requested &&
8234 	       bpf_jit_supports_subprog_tailcalls();
8235 }
8236 
8237 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8238 					struct bpf_map *map, int func_id)
8239 {
8240 	if (!map)
8241 		return 0;
8242 
8243 	/* We need a two way check, first is from map perspective ... */
8244 	switch (map->map_type) {
8245 	case BPF_MAP_TYPE_PROG_ARRAY:
8246 		if (func_id != BPF_FUNC_tail_call)
8247 			goto error;
8248 		break;
8249 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8250 		if (func_id != BPF_FUNC_perf_event_read &&
8251 		    func_id != BPF_FUNC_perf_event_output &&
8252 		    func_id != BPF_FUNC_skb_output &&
8253 		    func_id != BPF_FUNC_perf_event_read_value &&
8254 		    func_id != BPF_FUNC_xdp_output)
8255 			goto error;
8256 		break;
8257 	case BPF_MAP_TYPE_RINGBUF:
8258 		if (func_id != BPF_FUNC_ringbuf_output &&
8259 		    func_id != BPF_FUNC_ringbuf_reserve &&
8260 		    func_id != BPF_FUNC_ringbuf_query &&
8261 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8262 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8263 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8264 			goto error;
8265 		break;
8266 	case BPF_MAP_TYPE_USER_RINGBUF:
8267 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8268 			goto error;
8269 		break;
8270 	case BPF_MAP_TYPE_STACK_TRACE:
8271 		if (func_id != BPF_FUNC_get_stackid)
8272 			goto error;
8273 		break;
8274 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8275 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8276 		    func_id != BPF_FUNC_current_task_under_cgroup)
8277 			goto error;
8278 		break;
8279 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8280 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8281 		if (func_id != BPF_FUNC_get_local_storage)
8282 			goto error;
8283 		break;
8284 	case BPF_MAP_TYPE_DEVMAP:
8285 	case BPF_MAP_TYPE_DEVMAP_HASH:
8286 		if (func_id != BPF_FUNC_redirect_map &&
8287 		    func_id != BPF_FUNC_map_lookup_elem)
8288 			goto error;
8289 		break;
8290 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8291 	 * appear.
8292 	 */
8293 	case BPF_MAP_TYPE_CPUMAP:
8294 		if (func_id != BPF_FUNC_redirect_map)
8295 			goto error;
8296 		break;
8297 	case BPF_MAP_TYPE_XSKMAP:
8298 		if (func_id != BPF_FUNC_redirect_map &&
8299 		    func_id != BPF_FUNC_map_lookup_elem)
8300 			goto error;
8301 		break;
8302 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8303 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8304 		if (func_id != BPF_FUNC_map_lookup_elem)
8305 			goto error;
8306 		break;
8307 	case BPF_MAP_TYPE_SOCKMAP:
8308 		if (func_id != BPF_FUNC_sk_redirect_map &&
8309 		    func_id != BPF_FUNC_sock_map_update &&
8310 		    func_id != BPF_FUNC_map_delete_elem &&
8311 		    func_id != BPF_FUNC_msg_redirect_map &&
8312 		    func_id != BPF_FUNC_sk_select_reuseport &&
8313 		    func_id != BPF_FUNC_map_lookup_elem &&
8314 		    !may_update_sockmap(env, func_id))
8315 			goto error;
8316 		break;
8317 	case BPF_MAP_TYPE_SOCKHASH:
8318 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8319 		    func_id != BPF_FUNC_sock_hash_update &&
8320 		    func_id != BPF_FUNC_map_delete_elem &&
8321 		    func_id != BPF_FUNC_msg_redirect_hash &&
8322 		    func_id != BPF_FUNC_sk_select_reuseport &&
8323 		    func_id != BPF_FUNC_map_lookup_elem &&
8324 		    !may_update_sockmap(env, func_id))
8325 			goto error;
8326 		break;
8327 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8328 		if (func_id != BPF_FUNC_sk_select_reuseport)
8329 			goto error;
8330 		break;
8331 	case BPF_MAP_TYPE_QUEUE:
8332 	case BPF_MAP_TYPE_STACK:
8333 		if (func_id != BPF_FUNC_map_peek_elem &&
8334 		    func_id != BPF_FUNC_map_pop_elem &&
8335 		    func_id != BPF_FUNC_map_push_elem)
8336 			goto error;
8337 		break;
8338 	case BPF_MAP_TYPE_SK_STORAGE:
8339 		if (func_id != BPF_FUNC_sk_storage_get &&
8340 		    func_id != BPF_FUNC_sk_storage_delete &&
8341 		    func_id != BPF_FUNC_kptr_xchg)
8342 			goto error;
8343 		break;
8344 	case BPF_MAP_TYPE_INODE_STORAGE:
8345 		if (func_id != BPF_FUNC_inode_storage_get &&
8346 		    func_id != BPF_FUNC_inode_storage_delete &&
8347 		    func_id != BPF_FUNC_kptr_xchg)
8348 			goto error;
8349 		break;
8350 	case BPF_MAP_TYPE_TASK_STORAGE:
8351 		if (func_id != BPF_FUNC_task_storage_get &&
8352 		    func_id != BPF_FUNC_task_storage_delete &&
8353 		    func_id != BPF_FUNC_kptr_xchg)
8354 			goto error;
8355 		break;
8356 	case BPF_MAP_TYPE_CGRP_STORAGE:
8357 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8358 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8359 		    func_id != BPF_FUNC_kptr_xchg)
8360 			goto error;
8361 		break;
8362 	case BPF_MAP_TYPE_BLOOM_FILTER:
8363 		if (func_id != BPF_FUNC_map_peek_elem &&
8364 		    func_id != BPF_FUNC_map_push_elem)
8365 			goto error;
8366 		break;
8367 	default:
8368 		break;
8369 	}
8370 
8371 	/* ... and second from the function itself. */
8372 	switch (func_id) {
8373 	case BPF_FUNC_tail_call:
8374 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8375 			goto error;
8376 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8377 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8378 			return -EINVAL;
8379 		}
8380 		break;
8381 	case BPF_FUNC_perf_event_read:
8382 	case BPF_FUNC_perf_event_output:
8383 	case BPF_FUNC_perf_event_read_value:
8384 	case BPF_FUNC_skb_output:
8385 	case BPF_FUNC_xdp_output:
8386 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8387 			goto error;
8388 		break;
8389 	case BPF_FUNC_ringbuf_output:
8390 	case BPF_FUNC_ringbuf_reserve:
8391 	case BPF_FUNC_ringbuf_query:
8392 	case BPF_FUNC_ringbuf_reserve_dynptr:
8393 	case BPF_FUNC_ringbuf_submit_dynptr:
8394 	case BPF_FUNC_ringbuf_discard_dynptr:
8395 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8396 			goto error;
8397 		break;
8398 	case BPF_FUNC_user_ringbuf_drain:
8399 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8400 			goto error;
8401 		break;
8402 	case BPF_FUNC_get_stackid:
8403 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8404 			goto error;
8405 		break;
8406 	case BPF_FUNC_current_task_under_cgroup:
8407 	case BPF_FUNC_skb_under_cgroup:
8408 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8409 			goto error;
8410 		break;
8411 	case BPF_FUNC_redirect_map:
8412 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8413 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8414 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8415 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8416 			goto error;
8417 		break;
8418 	case BPF_FUNC_sk_redirect_map:
8419 	case BPF_FUNC_msg_redirect_map:
8420 	case BPF_FUNC_sock_map_update:
8421 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8422 			goto error;
8423 		break;
8424 	case BPF_FUNC_sk_redirect_hash:
8425 	case BPF_FUNC_msg_redirect_hash:
8426 	case BPF_FUNC_sock_hash_update:
8427 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8428 			goto error;
8429 		break;
8430 	case BPF_FUNC_get_local_storage:
8431 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8432 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8433 			goto error;
8434 		break;
8435 	case BPF_FUNC_sk_select_reuseport:
8436 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8437 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8438 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8439 			goto error;
8440 		break;
8441 	case BPF_FUNC_map_pop_elem:
8442 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8443 		    map->map_type != BPF_MAP_TYPE_STACK)
8444 			goto error;
8445 		break;
8446 	case BPF_FUNC_map_peek_elem:
8447 	case BPF_FUNC_map_push_elem:
8448 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8449 		    map->map_type != BPF_MAP_TYPE_STACK &&
8450 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8451 			goto error;
8452 		break;
8453 	case BPF_FUNC_map_lookup_percpu_elem:
8454 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8455 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8456 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8457 			goto error;
8458 		break;
8459 	case BPF_FUNC_sk_storage_get:
8460 	case BPF_FUNC_sk_storage_delete:
8461 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8462 			goto error;
8463 		break;
8464 	case BPF_FUNC_inode_storage_get:
8465 	case BPF_FUNC_inode_storage_delete:
8466 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8467 			goto error;
8468 		break;
8469 	case BPF_FUNC_task_storage_get:
8470 	case BPF_FUNC_task_storage_delete:
8471 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8472 			goto error;
8473 		break;
8474 	case BPF_FUNC_cgrp_storage_get:
8475 	case BPF_FUNC_cgrp_storage_delete:
8476 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8477 			goto error;
8478 		break;
8479 	default:
8480 		break;
8481 	}
8482 
8483 	return 0;
8484 error:
8485 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8486 		map->map_type, func_id_name(func_id), func_id);
8487 	return -EINVAL;
8488 }
8489 
8490 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8491 {
8492 	int count = 0;
8493 
8494 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8495 		count++;
8496 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8497 		count++;
8498 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8499 		count++;
8500 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8501 		count++;
8502 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8503 		count++;
8504 
8505 	/* We only support one arg being in raw mode at the moment,
8506 	 * which is sufficient for the helper functions we have
8507 	 * right now.
8508 	 */
8509 	return count <= 1;
8510 }
8511 
8512 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8513 {
8514 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8515 	bool has_size = fn->arg_size[arg] != 0;
8516 	bool is_next_size = false;
8517 
8518 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8519 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8520 
8521 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8522 		return is_next_size;
8523 
8524 	return has_size == is_next_size || is_next_size == is_fixed;
8525 }
8526 
8527 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8528 {
8529 	/* bpf_xxx(..., buf, len) call will access 'len'
8530 	 * bytes from memory 'buf'. Both arg types need
8531 	 * to be paired, so make sure there's no buggy
8532 	 * helper function specification.
8533 	 */
8534 	if (arg_type_is_mem_size(fn->arg1_type) ||
8535 	    check_args_pair_invalid(fn, 0) ||
8536 	    check_args_pair_invalid(fn, 1) ||
8537 	    check_args_pair_invalid(fn, 2) ||
8538 	    check_args_pair_invalid(fn, 3) ||
8539 	    check_args_pair_invalid(fn, 4))
8540 		return false;
8541 
8542 	return true;
8543 }
8544 
8545 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8546 {
8547 	int i;
8548 
8549 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8550 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8551 			return !!fn->arg_btf_id[i];
8552 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8553 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8554 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8555 		    /* arg_btf_id and arg_size are in a union. */
8556 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8557 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8558 			return false;
8559 	}
8560 
8561 	return true;
8562 }
8563 
8564 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8565 {
8566 	return check_raw_mode_ok(fn) &&
8567 	       check_arg_pair_ok(fn) &&
8568 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8569 }
8570 
8571 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8572  * are now invalid, so turn them into unknown SCALAR_VALUE.
8573  *
8574  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8575  * since these slices point to packet data.
8576  */
8577 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8578 {
8579 	struct bpf_func_state *state;
8580 	struct bpf_reg_state *reg;
8581 
8582 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8583 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8584 			mark_reg_invalid(env, reg);
8585 	}));
8586 }
8587 
8588 enum {
8589 	AT_PKT_END = -1,
8590 	BEYOND_PKT_END = -2,
8591 };
8592 
8593 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8594 {
8595 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8596 	struct bpf_reg_state *reg = &state->regs[regn];
8597 
8598 	if (reg->type != PTR_TO_PACKET)
8599 		/* PTR_TO_PACKET_META is not supported yet */
8600 		return;
8601 
8602 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8603 	 * How far beyond pkt_end it goes is unknown.
8604 	 * if (!range_open) it's the case of pkt >= pkt_end
8605 	 * if (range_open) it's the case of pkt > pkt_end
8606 	 * hence this pointer is at least 1 byte bigger than pkt_end
8607 	 */
8608 	if (range_open)
8609 		reg->range = BEYOND_PKT_END;
8610 	else
8611 		reg->range = AT_PKT_END;
8612 }
8613 
8614 /* The pointer with the specified id has released its reference to kernel
8615  * resources. Identify all copies of the same pointer and clear the reference.
8616  */
8617 static int release_reference(struct bpf_verifier_env *env,
8618 			     int ref_obj_id)
8619 {
8620 	struct bpf_func_state *state;
8621 	struct bpf_reg_state *reg;
8622 	int err;
8623 
8624 	err = release_reference_state(cur_func(env), ref_obj_id);
8625 	if (err)
8626 		return err;
8627 
8628 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8629 		if (reg->ref_obj_id == ref_obj_id)
8630 			mark_reg_invalid(env, reg);
8631 	}));
8632 
8633 	return 0;
8634 }
8635 
8636 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8637 {
8638 	struct bpf_func_state *unused;
8639 	struct bpf_reg_state *reg;
8640 
8641 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8642 		if (type_is_non_owning_ref(reg->type))
8643 			mark_reg_invalid(env, reg);
8644 	}));
8645 }
8646 
8647 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8648 				    struct bpf_reg_state *regs)
8649 {
8650 	int i;
8651 
8652 	/* after the call registers r0 - r5 were scratched */
8653 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8654 		mark_reg_not_init(env, regs, caller_saved[i]);
8655 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8656 	}
8657 }
8658 
8659 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8660 				   struct bpf_func_state *caller,
8661 				   struct bpf_func_state *callee,
8662 				   int insn_idx);
8663 
8664 static int set_callee_state(struct bpf_verifier_env *env,
8665 			    struct bpf_func_state *caller,
8666 			    struct bpf_func_state *callee, int insn_idx);
8667 
8668 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8669 			     int *insn_idx, int subprog,
8670 			     set_callee_state_fn set_callee_state_cb)
8671 {
8672 	struct bpf_verifier_state *state = env->cur_state;
8673 	struct bpf_func_state *caller, *callee;
8674 	int err;
8675 
8676 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8677 		verbose(env, "the call stack of %d frames is too deep\n",
8678 			state->curframe + 2);
8679 		return -E2BIG;
8680 	}
8681 
8682 	caller = state->frame[state->curframe];
8683 	if (state->frame[state->curframe + 1]) {
8684 		verbose(env, "verifier bug. Frame %d already allocated\n",
8685 			state->curframe + 1);
8686 		return -EFAULT;
8687 	}
8688 
8689 	err = btf_check_subprog_call(env, subprog, caller->regs);
8690 	if (err == -EFAULT)
8691 		return err;
8692 	if (subprog_is_global(env, subprog)) {
8693 		if (err) {
8694 			verbose(env, "Caller passes invalid args into func#%d\n",
8695 				subprog);
8696 			return err;
8697 		} else {
8698 			if (env->log.level & BPF_LOG_LEVEL)
8699 				verbose(env,
8700 					"Func#%d is global and valid. Skipping.\n",
8701 					subprog);
8702 			clear_caller_saved_regs(env, caller->regs);
8703 
8704 			/* All global functions return a 64-bit SCALAR_VALUE */
8705 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
8706 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8707 
8708 			/* continue with next insn after call */
8709 			return 0;
8710 		}
8711 	}
8712 
8713 	/* set_callee_state is used for direct subprog calls, but we are
8714 	 * interested in validating only BPF helpers that can call subprogs as
8715 	 * callbacks
8716 	 */
8717 	if (set_callee_state_cb != set_callee_state) {
8718 		if (bpf_pseudo_kfunc_call(insn) &&
8719 		    !is_callback_calling_kfunc(insn->imm)) {
8720 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8721 				func_id_name(insn->imm), insn->imm);
8722 			return -EFAULT;
8723 		} else if (!bpf_pseudo_kfunc_call(insn) &&
8724 			   !is_callback_calling_function(insn->imm)) { /* helper */
8725 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8726 				func_id_name(insn->imm), insn->imm);
8727 			return -EFAULT;
8728 		}
8729 	}
8730 
8731 	if (insn->code == (BPF_JMP | BPF_CALL) &&
8732 	    insn->src_reg == 0 &&
8733 	    insn->imm == BPF_FUNC_timer_set_callback) {
8734 		struct bpf_verifier_state *async_cb;
8735 
8736 		/* there is no real recursion here. timer callbacks are async */
8737 		env->subprog_info[subprog].is_async_cb = true;
8738 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8739 					 *insn_idx, subprog);
8740 		if (!async_cb)
8741 			return -EFAULT;
8742 		callee = async_cb->frame[0];
8743 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
8744 
8745 		/* Convert bpf_timer_set_callback() args into timer callback args */
8746 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
8747 		if (err)
8748 			return err;
8749 
8750 		clear_caller_saved_regs(env, caller->regs);
8751 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
8752 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8753 		/* continue with next insn after call */
8754 		return 0;
8755 	}
8756 
8757 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8758 	if (!callee)
8759 		return -ENOMEM;
8760 	state->frame[state->curframe + 1] = callee;
8761 
8762 	/* callee cannot access r0, r6 - r9 for reading and has to write
8763 	 * into its own stack before reading from it.
8764 	 * callee can read/write into caller's stack
8765 	 */
8766 	init_func_state(env, callee,
8767 			/* remember the callsite, it will be used by bpf_exit */
8768 			*insn_idx /* callsite */,
8769 			state->curframe + 1 /* frameno within this callchain */,
8770 			subprog /* subprog number within this prog */);
8771 
8772 	/* Transfer references to the callee */
8773 	err = copy_reference_state(callee, caller);
8774 	if (err)
8775 		goto err_out;
8776 
8777 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
8778 	if (err)
8779 		goto err_out;
8780 
8781 	clear_caller_saved_regs(env, caller->regs);
8782 
8783 	/* only increment it after check_reg_arg() finished */
8784 	state->curframe++;
8785 
8786 	/* and go analyze first insn of the callee */
8787 	*insn_idx = env->subprog_info[subprog].start - 1;
8788 
8789 	if (env->log.level & BPF_LOG_LEVEL) {
8790 		verbose(env, "caller:\n");
8791 		print_verifier_state(env, caller, true);
8792 		verbose(env, "callee:\n");
8793 		print_verifier_state(env, callee, true);
8794 	}
8795 	return 0;
8796 
8797 err_out:
8798 	free_func_state(callee);
8799 	state->frame[state->curframe + 1] = NULL;
8800 	return err;
8801 }
8802 
8803 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8804 				   struct bpf_func_state *caller,
8805 				   struct bpf_func_state *callee)
8806 {
8807 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8808 	 *      void *callback_ctx, u64 flags);
8809 	 * callback_fn(struct bpf_map *map, void *key, void *value,
8810 	 *      void *callback_ctx);
8811 	 */
8812 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8813 
8814 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8815 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8816 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8817 
8818 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8819 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8820 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8821 
8822 	/* pointer to stack or null */
8823 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8824 
8825 	/* unused */
8826 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8827 	return 0;
8828 }
8829 
8830 static int set_callee_state(struct bpf_verifier_env *env,
8831 			    struct bpf_func_state *caller,
8832 			    struct bpf_func_state *callee, int insn_idx)
8833 {
8834 	int i;
8835 
8836 	/* copy r1 - r5 args that callee can access.  The copy includes parent
8837 	 * pointers, which connects us up to the liveness chain
8838 	 */
8839 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8840 		callee->regs[i] = caller->regs[i];
8841 	return 0;
8842 }
8843 
8844 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8845 			   int *insn_idx)
8846 {
8847 	int subprog, target_insn;
8848 
8849 	target_insn = *insn_idx + insn->imm + 1;
8850 	subprog = find_subprog(env, target_insn);
8851 	if (subprog < 0) {
8852 		verbose(env, "verifier bug. No program starts at insn %d\n",
8853 			target_insn);
8854 		return -EFAULT;
8855 	}
8856 
8857 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8858 }
8859 
8860 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8861 				       struct bpf_func_state *caller,
8862 				       struct bpf_func_state *callee,
8863 				       int insn_idx)
8864 {
8865 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8866 	struct bpf_map *map;
8867 	int err;
8868 
8869 	if (bpf_map_ptr_poisoned(insn_aux)) {
8870 		verbose(env, "tail_call abusing map_ptr\n");
8871 		return -EINVAL;
8872 	}
8873 
8874 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8875 	if (!map->ops->map_set_for_each_callback_args ||
8876 	    !map->ops->map_for_each_callback) {
8877 		verbose(env, "callback function not allowed for map\n");
8878 		return -ENOTSUPP;
8879 	}
8880 
8881 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8882 	if (err)
8883 		return err;
8884 
8885 	callee->in_callback_fn = true;
8886 	callee->callback_ret_range = tnum_range(0, 1);
8887 	return 0;
8888 }
8889 
8890 static int set_loop_callback_state(struct bpf_verifier_env *env,
8891 				   struct bpf_func_state *caller,
8892 				   struct bpf_func_state *callee,
8893 				   int insn_idx)
8894 {
8895 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8896 	 *	    u64 flags);
8897 	 * callback_fn(u32 index, void *callback_ctx);
8898 	 */
8899 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8900 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8901 
8902 	/* unused */
8903 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8904 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8905 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8906 
8907 	callee->in_callback_fn = true;
8908 	callee->callback_ret_range = tnum_range(0, 1);
8909 	return 0;
8910 }
8911 
8912 static int set_timer_callback_state(struct bpf_verifier_env *env,
8913 				    struct bpf_func_state *caller,
8914 				    struct bpf_func_state *callee,
8915 				    int insn_idx)
8916 {
8917 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8918 
8919 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8920 	 * callback_fn(struct bpf_map *map, void *key, void *value);
8921 	 */
8922 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8923 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8924 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
8925 
8926 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8927 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8928 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
8929 
8930 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8931 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8932 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
8933 
8934 	/* unused */
8935 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8936 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8937 	callee->in_async_callback_fn = true;
8938 	callee->callback_ret_range = tnum_range(0, 1);
8939 	return 0;
8940 }
8941 
8942 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8943 				       struct bpf_func_state *caller,
8944 				       struct bpf_func_state *callee,
8945 				       int insn_idx)
8946 {
8947 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8948 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8949 	 * (callback_fn)(struct task_struct *task,
8950 	 *               struct vm_area_struct *vma, void *callback_ctx);
8951 	 */
8952 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8953 
8954 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8955 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8956 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8957 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8958 
8959 	/* pointer to stack or null */
8960 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8961 
8962 	/* unused */
8963 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8964 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8965 	callee->in_callback_fn = true;
8966 	callee->callback_ret_range = tnum_range(0, 1);
8967 	return 0;
8968 }
8969 
8970 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8971 					   struct bpf_func_state *caller,
8972 					   struct bpf_func_state *callee,
8973 					   int insn_idx)
8974 {
8975 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8976 	 *			  callback_ctx, u64 flags);
8977 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8978 	 */
8979 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8980 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8981 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8982 
8983 	/* unused */
8984 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8985 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8986 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8987 
8988 	callee->in_callback_fn = true;
8989 	callee->callback_ret_range = tnum_range(0, 1);
8990 	return 0;
8991 }
8992 
8993 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8994 					 struct bpf_func_state *caller,
8995 					 struct bpf_func_state *callee,
8996 					 int insn_idx)
8997 {
8998 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
8999 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9000 	 *
9001 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9002 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9003 	 * by this point, so look at 'root'
9004 	 */
9005 	struct btf_field *field;
9006 
9007 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9008 				      BPF_RB_ROOT);
9009 	if (!field || !field->graph_root.value_btf_id)
9010 		return -EFAULT;
9011 
9012 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9013 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9014 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9015 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9016 
9017 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9018 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9019 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9020 	callee->in_callback_fn = true;
9021 	callee->callback_ret_range = tnum_range(0, 1);
9022 	return 0;
9023 }
9024 
9025 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9026 
9027 /* Are we currently verifying the callback for a rbtree helper that must
9028  * be called with lock held? If so, no need to complain about unreleased
9029  * lock
9030  */
9031 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9032 {
9033 	struct bpf_verifier_state *state = env->cur_state;
9034 	struct bpf_insn *insn = env->prog->insnsi;
9035 	struct bpf_func_state *callee;
9036 	int kfunc_btf_id;
9037 
9038 	if (!state->curframe)
9039 		return false;
9040 
9041 	callee = state->frame[state->curframe];
9042 
9043 	if (!callee->in_callback_fn)
9044 		return false;
9045 
9046 	kfunc_btf_id = insn[callee->callsite].imm;
9047 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9048 }
9049 
9050 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9051 {
9052 	struct bpf_verifier_state *state = env->cur_state;
9053 	struct bpf_func_state *caller, *callee;
9054 	struct bpf_reg_state *r0;
9055 	int err;
9056 
9057 	callee = state->frame[state->curframe];
9058 	r0 = &callee->regs[BPF_REG_0];
9059 	if (r0->type == PTR_TO_STACK) {
9060 		/* technically it's ok to return caller's stack pointer
9061 		 * (or caller's caller's pointer) back to the caller,
9062 		 * since these pointers are valid. Only current stack
9063 		 * pointer will be invalid as soon as function exits,
9064 		 * but let's be conservative
9065 		 */
9066 		verbose(env, "cannot return stack pointer to the caller\n");
9067 		return -EINVAL;
9068 	}
9069 
9070 	caller = state->frame[state->curframe - 1];
9071 	if (callee->in_callback_fn) {
9072 		/* enforce R0 return value range [0, 1]. */
9073 		struct tnum range = callee->callback_ret_range;
9074 
9075 		if (r0->type != SCALAR_VALUE) {
9076 			verbose(env, "R0 not a scalar value\n");
9077 			return -EACCES;
9078 		}
9079 		if (!tnum_in(range, r0->var_off)) {
9080 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9081 			return -EINVAL;
9082 		}
9083 	} else {
9084 		/* return to the caller whatever r0 had in the callee */
9085 		caller->regs[BPF_REG_0] = *r0;
9086 	}
9087 
9088 	/* callback_fn frame should have released its own additions to parent's
9089 	 * reference state at this point, or check_reference_leak would
9090 	 * complain, hence it must be the same as the caller. There is no need
9091 	 * to copy it back.
9092 	 */
9093 	if (!callee->in_callback_fn) {
9094 		/* Transfer references to the caller */
9095 		err = copy_reference_state(caller, callee);
9096 		if (err)
9097 			return err;
9098 	}
9099 
9100 	*insn_idx = callee->callsite + 1;
9101 	if (env->log.level & BPF_LOG_LEVEL) {
9102 		verbose(env, "returning from callee:\n");
9103 		print_verifier_state(env, callee, true);
9104 		verbose(env, "to caller at %d:\n", *insn_idx);
9105 		print_verifier_state(env, caller, true);
9106 	}
9107 	/* clear everything in the callee */
9108 	free_func_state(callee);
9109 	state->frame[state->curframe--] = NULL;
9110 	return 0;
9111 }
9112 
9113 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9114 				   int func_id,
9115 				   struct bpf_call_arg_meta *meta)
9116 {
9117 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9118 
9119 	if (ret_type != RET_INTEGER ||
9120 	    (func_id != BPF_FUNC_get_stack &&
9121 	     func_id != BPF_FUNC_get_task_stack &&
9122 	     func_id != BPF_FUNC_probe_read_str &&
9123 	     func_id != BPF_FUNC_probe_read_kernel_str &&
9124 	     func_id != BPF_FUNC_probe_read_user_str))
9125 		return;
9126 
9127 	ret_reg->smax_value = meta->msize_max_value;
9128 	ret_reg->s32_max_value = meta->msize_max_value;
9129 	ret_reg->smin_value = -MAX_ERRNO;
9130 	ret_reg->s32_min_value = -MAX_ERRNO;
9131 	reg_bounds_sync(ret_reg);
9132 }
9133 
9134 static int
9135 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9136 		int func_id, int insn_idx)
9137 {
9138 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9139 	struct bpf_map *map = meta->map_ptr;
9140 
9141 	if (func_id != BPF_FUNC_tail_call &&
9142 	    func_id != BPF_FUNC_map_lookup_elem &&
9143 	    func_id != BPF_FUNC_map_update_elem &&
9144 	    func_id != BPF_FUNC_map_delete_elem &&
9145 	    func_id != BPF_FUNC_map_push_elem &&
9146 	    func_id != BPF_FUNC_map_pop_elem &&
9147 	    func_id != BPF_FUNC_map_peek_elem &&
9148 	    func_id != BPF_FUNC_for_each_map_elem &&
9149 	    func_id != BPF_FUNC_redirect_map &&
9150 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9151 		return 0;
9152 
9153 	if (map == NULL) {
9154 		verbose(env, "kernel subsystem misconfigured verifier\n");
9155 		return -EINVAL;
9156 	}
9157 
9158 	/* In case of read-only, some additional restrictions
9159 	 * need to be applied in order to prevent altering the
9160 	 * state of the map from program side.
9161 	 */
9162 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9163 	    (func_id == BPF_FUNC_map_delete_elem ||
9164 	     func_id == BPF_FUNC_map_update_elem ||
9165 	     func_id == BPF_FUNC_map_push_elem ||
9166 	     func_id == BPF_FUNC_map_pop_elem)) {
9167 		verbose(env, "write into map forbidden\n");
9168 		return -EACCES;
9169 	}
9170 
9171 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9172 		bpf_map_ptr_store(aux, meta->map_ptr,
9173 				  !meta->map_ptr->bypass_spec_v1);
9174 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9175 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9176 				  !meta->map_ptr->bypass_spec_v1);
9177 	return 0;
9178 }
9179 
9180 static int
9181 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9182 		int func_id, int insn_idx)
9183 {
9184 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9185 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9186 	struct bpf_map *map = meta->map_ptr;
9187 	u64 val, max;
9188 	int err;
9189 
9190 	if (func_id != BPF_FUNC_tail_call)
9191 		return 0;
9192 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9193 		verbose(env, "kernel subsystem misconfigured verifier\n");
9194 		return -EINVAL;
9195 	}
9196 
9197 	reg = &regs[BPF_REG_3];
9198 	val = reg->var_off.value;
9199 	max = map->max_entries;
9200 
9201 	if (!(register_is_const(reg) && val < max)) {
9202 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9203 		return 0;
9204 	}
9205 
9206 	err = mark_chain_precision(env, BPF_REG_3);
9207 	if (err)
9208 		return err;
9209 	if (bpf_map_key_unseen(aux))
9210 		bpf_map_key_store(aux, val);
9211 	else if (!bpf_map_key_poisoned(aux) &&
9212 		  bpf_map_key_immediate(aux) != val)
9213 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9214 	return 0;
9215 }
9216 
9217 static int check_reference_leak(struct bpf_verifier_env *env)
9218 {
9219 	struct bpf_func_state *state = cur_func(env);
9220 	bool refs_lingering = false;
9221 	int i;
9222 
9223 	if (state->frameno && !state->in_callback_fn)
9224 		return 0;
9225 
9226 	for (i = 0; i < state->acquired_refs; i++) {
9227 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9228 			continue;
9229 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9230 			state->refs[i].id, state->refs[i].insn_idx);
9231 		refs_lingering = true;
9232 	}
9233 	return refs_lingering ? -EINVAL : 0;
9234 }
9235 
9236 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9237 				   struct bpf_reg_state *regs)
9238 {
9239 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9240 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9241 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9242 	struct bpf_bprintf_data data = {};
9243 	int err, fmt_map_off, num_args;
9244 	u64 fmt_addr;
9245 	char *fmt;
9246 
9247 	/* data must be an array of u64 */
9248 	if (data_len_reg->var_off.value % 8)
9249 		return -EINVAL;
9250 	num_args = data_len_reg->var_off.value / 8;
9251 
9252 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9253 	 * and map_direct_value_addr is set.
9254 	 */
9255 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9256 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9257 						  fmt_map_off);
9258 	if (err) {
9259 		verbose(env, "verifier bug\n");
9260 		return -EFAULT;
9261 	}
9262 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9263 
9264 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9265 	 * can focus on validating the format specifiers.
9266 	 */
9267 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9268 	if (err < 0)
9269 		verbose(env, "Invalid format string\n");
9270 
9271 	return err;
9272 }
9273 
9274 static int check_get_func_ip(struct bpf_verifier_env *env)
9275 {
9276 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9277 	int func_id = BPF_FUNC_get_func_ip;
9278 
9279 	if (type == BPF_PROG_TYPE_TRACING) {
9280 		if (!bpf_prog_has_trampoline(env->prog)) {
9281 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9282 				func_id_name(func_id), func_id);
9283 			return -ENOTSUPP;
9284 		}
9285 		return 0;
9286 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9287 		return 0;
9288 	}
9289 
9290 	verbose(env, "func %s#%d not supported for program type %d\n",
9291 		func_id_name(func_id), func_id, type);
9292 	return -ENOTSUPP;
9293 }
9294 
9295 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9296 {
9297 	return &env->insn_aux_data[env->insn_idx];
9298 }
9299 
9300 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9301 {
9302 	struct bpf_reg_state *regs = cur_regs(env);
9303 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9304 	bool reg_is_null = register_is_null(reg);
9305 
9306 	if (reg_is_null)
9307 		mark_chain_precision(env, BPF_REG_4);
9308 
9309 	return reg_is_null;
9310 }
9311 
9312 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9313 {
9314 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9315 
9316 	if (!state->initialized) {
9317 		state->initialized = 1;
9318 		state->fit_for_inline = loop_flag_is_zero(env);
9319 		state->callback_subprogno = subprogno;
9320 		return;
9321 	}
9322 
9323 	if (!state->fit_for_inline)
9324 		return;
9325 
9326 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9327 				 state->callback_subprogno == subprogno);
9328 }
9329 
9330 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9331 			     int *insn_idx_p)
9332 {
9333 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9334 	const struct bpf_func_proto *fn = NULL;
9335 	enum bpf_return_type ret_type;
9336 	enum bpf_type_flag ret_flag;
9337 	struct bpf_reg_state *regs;
9338 	struct bpf_call_arg_meta meta;
9339 	int insn_idx = *insn_idx_p;
9340 	bool changes_data;
9341 	int i, err, func_id;
9342 
9343 	/* find function prototype */
9344 	func_id = insn->imm;
9345 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9346 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9347 			func_id);
9348 		return -EINVAL;
9349 	}
9350 
9351 	if (env->ops->get_func_proto)
9352 		fn = env->ops->get_func_proto(func_id, env->prog);
9353 	if (!fn) {
9354 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9355 			func_id);
9356 		return -EINVAL;
9357 	}
9358 
9359 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9360 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9361 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9362 		return -EINVAL;
9363 	}
9364 
9365 	if (fn->allowed && !fn->allowed(env->prog)) {
9366 		verbose(env, "helper call is not allowed in probe\n");
9367 		return -EINVAL;
9368 	}
9369 
9370 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9371 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9372 		return -EINVAL;
9373 	}
9374 
9375 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9376 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9377 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9378 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9379 			func_id_name(func_id), func_id);
9380 		return -EINVAL;
9381 	}
9382 
9383 	memset(&meta, 0, sizeof(meta));
9384 	meta.pkt_access = fn->pkt_access;
9385 
9386 	err = check_func_proto(fn, func_id);
9387 	if (err) {
9388 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9389 			func_id_name(func_id), func_id);
9390 		return err;
9391 	}
9392 
9393 	if (env->cur_state->active_rcu_lock) {
9394 		if (fn->might_sleep) {
9395 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9396 				func_id_name(func_id), func_id);
9397 			return -EINVAL;
9398 		}
9399 
9400 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9401 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9402 	}
9403 
9404 	meta.func_id = func_id;
9405 	/* check args */
9406 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9407 		err = check_func_arg(env, i, &meta, fn, insn_idx);
9408 		if (err)
9409 			return err;
9410 	}
9411 
9412 	err = record_func_map(env, &meta, func_id, insn_idx);
9413 	if (err)
9414 		return err;
9415 
9416 	err = record_func_key(env, &meta, func_id, insn_idx);
9417 	if (err)
9418 		return err;
9419 
9420 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
9421 	 * is inferred from register state.
9422 	 */
9423 	for (i = 0; i < meta.access_size; i++) {
9424 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9425 				       BPF_WRITE, -1, false);
9426 		if (err)
9427 			return err;
9428 	}
9429 
9430 	regs = cur_regs(env);
9431 
9432 	if (meta.release_regno) {
9433 		err = -EINVAL;
9434 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9435 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9436 		 * is safe to do directly.
9437 		 */
9438 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9439 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9440 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9441 				return -EFAULT;
9442 			}
9443 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9444 		} else if (meta.ref_obj_id) {
9445 			err = release_reference(env, meta.ref_obj_id);
9446 		} else if (register_is_null(&regs[meta.release_regno])) {
9447 			/* meta.ref_obj_id can only be 0 if register that is meant to be
9448 			 * released is NULL, which must be > R0.
9449 			 */
9450 			err = 0;
9451 		}
9452 		if (err) {
9453 			verbose(env, "func %s#%d reference has not been acquired before\n",
9454 				func_id_name(func_id), func_id);
9455 			return err;
9456 		}
9457 	}
9458 
9459 	switch (func_id) {
9460 	case BPF_FUNC_tail_call:
9461 		err = check_reference_leak(env);
9462 		if (err) {
9463 			verbose(env, "tail_call would lead to reference leak\n");
9464 			return err;
9465 		}
9466 		break;
9467 	case BPF_FUNC_get_local_storage:
9468 		/* check that flags argument in get_local_storage(map, flags) is 0,
9469 		 * this is required because get_local_storage() can't return an error.
9470 		 */
9471 		if (!register_is_null(&regs[BPF_REG_2])) {
9472 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9473 			return -EINVAL;
9474 		}
9475 		break;
9476 	case BPF_FUNC_for_each_map_elem:
9477 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9478 					set_map_elem_callback_state);
9479 		break;
9480 	case BPF_FUNC_timer_set_callback:
9481 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9482 					set_timer_callback_state);
9483 		break;
9484 	case BPF_FUNC_find_vma:
9485 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9486 					set_find_vma_callback_state);
9487 		break;
9488 	case BPF_FUNC_snprintf:
9489 		err = check_bpf_snprintf_call(env, regs);
9490 		break;
9491 	case BPF_FUNC_loop:
9492 		update_loop_inline_state(env, meta.subprogno);
9493 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9494 					set_loop_callback_state);
9495 		break;
9496 	case BPF_FUNC_dynptr_from_mem:
9497 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9498 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9499 				reg_type_str(env, regs[BPF_REG_1].type));
9500 			return -EACCES;
9501 		}
9502 		break;
9503 	case BPF_FUNC_set_retval:
9504 		if (prog_type == BPF_PROG_TYPE_LSM &&
9505 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9506 			if (!env->prog->aux->attach_func_proto->type) {
9507 				/* Make sure programs that attach to void
9508 				 * hooks don't try to modify return value.
9509 				 */
9510 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9511 				return -EINVAL;
9512 			}
9513 		}
9514 		break;
9515 	case BPF_FUNC_dynptr_data:
9516 	{
9517 		struct bpf_reg_state *reg;
9518 		int id, ref_obj_id;
9519 
9520 		reg = get_dynptr_arg_reg(env, fn, regs);
9521 		if (!reg)
9522 			return -EFAULT;
9523 
9524 
9525 		if (meta.dynptr_id) {
9526 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9527 			return -EFAULT;
9528 		}
9529 		if (meta.ref_obj_id) {
9530 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9531 			return -EFAULT;
9532 		}
9533 
9534 		id = dynptr_id(env, reg);
9535 		if (id < 0) {
9536 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9537 			return id;
9538 		}
9539 
9540 		ref_obj_id = dynptr_ref_obj_id(env, reg);
9541 		if (ref_obj_id < 0) {
9542 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9543 			return ref_obj_id;
9544 		}
9545 
9546 		meta.dynptr_id = id;
9547 		meta.ref_obj_id = ref_obj_id;
9548 
9549 		break;
9550 	}
9551 	case BPF_FUNC_dynptr_write:
9552 	{
9553 		enum bpf_dynptr_type dynptr_type;
9554 		struct bpf_reg_state *reg;
9555 
9556 		reg = get_dynptr_arg_reg(env, fn, regs);
9557 		if (!reg)
9558 			return -EFAULT;
9559 
9560 		dynptr_type = dynptr_get_type(env, reg);
9561 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9562 			return -EFAULT;
9563 
9564 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9565 			/* this will trigger clear_all_pkt_pointers(), which will
9566 			 * invalidate all dynptr slices associated with the skb
9567 			 */
9568 			changes_data = true;
9569 
9570 		break;
9571 	}
9572 	case BPF_FUNC_user_ringbuf_drain:
9573 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9574 					set_user_ringbuf_callback_state);
9575 		break;
9576 	}
9577 
9578 	if (err)
9579 		return err;
9580 
9581 	/* reset caller saved regs */
9582 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9583 		mark_reg_not_init(env, regs, caller_saved[i]);
9584 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9585 	}
9586 
9587 	/* helper call returns 64-bit value. */
9588 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9589 
9590 	/* update return register (already marked as written above) */
9591 	ret_type = fn->ret_type;
9592 	ret_flag = type_flag(ret_type);
9593 
9594 	switch (base_type(ret_type)) {
9595 	case RET_INTEGER:
9596 		/* sets type to SCALAR_VALUE */
9597 		mark_reg_unknown(env, regs, BPF_REG_0);
9598 		break;
9599 	case RET_VOID:
9600 		regs[BPF_REG_0].type = NOT_INIT;
9601 		break;
9602 	case RET_PTR_TO_MAP_VALUE:
9603 		/* There is no offset yet applied, variable or fixed */
9604 		mark_reg_known_zero(env, regs, BPF_REG_0);
9605 		/* remember map_ptr, so that check_map_access()
9606 		 * can check 'value_size' boundary of memory access
9607 		 * to map element returned from bpf_map_lookup_elem()
9608 		 */
9609 		if (meta.map_ptr == NULL) {
9610 			verbose(env,
9611 				"kernel subsystem misconfigured verifier\n");
9612 			return -EINVAL;
9613 		}
9614 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
9615 		regs[BPF_REG_0].map_uid = meta.map_uid;
9616 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9617 		if (!type_may_be_null(ret_type) &&
9618 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9619 			regs[BPF_REG_0].id = ++env->id_gen;
9620 		}
9621 		break;
9622 	case RET_PTR_TO_SOCKET:
9623 		mark_reg_known_zero(env, regs, BPF_REG_0);
9624 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9625 		break;
9626 	case RET_PTR_TO_SOCK_COMMON:
9627 		mark_reg_known_zero(env, regs, BPF_REG_0);
9628 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9629 		break;
9630 	case RET_PTR_TO_TCP_SOCK:
9631 		mark_reg_known_zero(env, regs, BPF_REG_0);
9632 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9633 		break;
9634 	case RET_PTR_TO_MEM:
9635 		mark_reg_known_zero(env, regs, BPF_REG_0);
9636 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9637 		regs[BPF_REG_0].mem_size = meta.mem_size;
9638 		break;
9639 	case RET_PTR_TO_MEM_OR_BTF_ID:
9640 	{
9641 		const struct btf_type *t;
9642 
9643 		mark_reg_known_zero(env, regs, BPF_REG_0);
9644 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9645 		if (!btf_type_is_struct(t)) {
9646 			u32 tsize;
9647 			const struct btf_type *ret;
9648 			const char *tname;
9649 
9650 			/* resolve the type size of ksym. */
9651 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9652 			if (IS_ERR(ret)) {
9653 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9654 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
9655 					tname, PTR_ERR(ret));
9656 				return -EINVAL;
9657 			}
9658 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9659 			regs[BPF_REG_0].mem_size = tsize;
9660 		} else {
9661 			/* MEM_RDONLY may be carried from ret_flag, but it
9662 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9663 			 * it will confuse the check of PTR_TO_BTF_ID in
9664 			 * check_mem_access().
9665 			 */
9666 			ret_flag &= ~MEM_RDONLY;
9667 
9668 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9669 			regs[BPF_REG_0].btf = meta.ret_btf;
9670 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9671 		}
9672 		break;
9673 	}
9674 	case RET_PTR_TO_BTF_ID:
9675 	{
9676 		struct btf *ret_btf;
9677 		int ret_btf_id;
9678 
9679 		mark_reg_known_zero(env, regs, BPF_REG_0);
9680 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9681 		if (func_id == BPF_FUNC_kptr_xchg) {
9682 			ret_btf = meta.kptr_field->kptr.btf;
9683 			ret_btf_id = meta.kptr_field->kptr.btf_id;
9684 			if (!btf_is_kernel(ret_btf))
9685 				regs[BPF_REG_0].type |= MEM_ALLOC;
9686 		} else {
9687 			if (fn->ret_btf_id == BPF_PTR_POISON) {
9688 				verbose(env, "verifier internal error:");
9689 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9690 					func_id_name(func_id));
9691 				return -EINVAL;
9692 			}
9693 			ret_btf = btf_vmlinux;
9694 			ret_btf_id = *fn->ret_btf_id;
9695 		}
9696 		if (ret_btf_id == 0) {
9697 			verbose(env, "invalid return type %u of func %s#%d\n",
9698 				base_type(ret_type), func_id_name(func_id),
9699 				func_id);
9700 			return -EINVAL;
9701 		}
9702 		regs[BPF_REG_0].btf = ret_btf;
9703 		regs[BPF_REG_0].btf_id = ret_btf_id;
9704 		break;
9705 	}
9706 	default:
9707 		verbose(env, "unknown return type %u of func %s#%d\n",
9708 			base_type(ret_type), func_id_name(func_id), func_id);
9709 		return -EINVAL;
9710 	}
9711 
9712 	if (type_may_be_null(regs[BPF_REG_0].type))
9713 		regs[BPF_REG_0].id = ++env->id_gen;
9714 
9715 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9716 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9717 			func_id_name(func_id), func_id);
9718 		return -EFAULT;
9719 	}
9720 
9721 	if (is_dynptr_ref_function(func_id))
9722 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9723 
9724 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9725 		/* For release_reference() */
9726 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9727 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
9728 		int id = acquire_reference_state(env, insn_idx);
9729 
9730 		if (id < 0)
9731 			return id;
9732 		/* For mark_ptr_or_null_reg() */
9733 		regs[BPF_REG_0].id = id;
9734 		/* For release_reference() */
9735 		regs[BPF_REG_0].ref_obj_id = id;
9736 	}
9737 
9738 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9739 
9740 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9741 	if (err)
9742 		return err;
9743 
9744 	if ((func_id == BPF_FUNC_get_stack ||
9745 	     func_id == BPF_FUNC_get_task_stack) &&
9746 	    !env->prog->has_callchain_buf) {
9747 		const char *err_str;
9748 
9749 #ifdef CONFIG_PERF_EVENTS
9750 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
9751 		err_str = "cannot get callchain buffer for func %s#%d\n";
9752 #else
9753 		err = -ENOTSUPP;
9754 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9755 #endif
9756 		if (err) {
9757 			verbose(env, err_str, func_id_name(func_id), func_id);
9758 			return err;
9759 		}
9760 
9761 		env->prog->has_callchain_buf = true;
9762 	}
9763 
9764 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9765 		env->prog->call_get_stack = true;
9766 
9767 	if (func_id == BPF_FUNC_get_func_ip) {
9768 		if (check_get_func_ip(env))
9769 			return -ENOTSUPP;
9770 		env->prog->call_get_func_ip = true;
9771 	}
9772 
9773 	if (changes_data)
9774 		clear_all_pkt_pointers(env);
9775 	return 0;
9776 }
9777 
9778 /* mark_btf_func_reg_size() is used when the reg size is determined by
9779  * the BTF func_proto's return value size and argument.
9780  */
9781 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9782 				   size_t reg_size)
9783 {
9784 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
9785 
9786 	if (regno == BPF_REG_0) {
9787 		/* Function return value */
9788 		reg->live |= REG_LIVE_WRITTEN;
9789 		reg->subreg_def = reg_size == sizeof(u64) ?
9790 			DEF_NOT_SUBREG : env->insn_idx + 1;
9791 	} else {
9792 		/* Function argument */
9793 		if (reg_size == sizeof(u64)) {
9794 			mark_insn_zext(env, reg);
9795 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9796 		} else {
9797 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9798 		}
9799 	}
9800 }
9801 
9802 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9803 {
9804 	return meta->kfunc_flags & KF_ACQUIRE;
9805 }
9806 
9807 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9808 {
9809 	return meta->kfunc_flags & KF_RELEASE;
9810 }
9811 
9812 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9813 {
9814 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9815 }
9816 
9817 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9818 {
9819 	return meta->kfunc_flags & KF_SLEEPABLE;
9820 }
9821 
9822 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9823 {
9824 	return meta->kfunc_flags & KF_DESTRUCTIVE;
9825 }
9826 
9827 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9828 {
9829 	return meta->kfunc_flags & KF_RCU;
9830 }
9831 
9832 static bool __kfunc_param_match_suffix(const struct btf *btf,
9833 				       const struct btf_param *arg,
9834 				       const char *suffix)
9835 {
9836 	int suffix_len = strlen(suffix), len;
9837 	const char *param_name;
9838 
9839 	/* In the future, this can be ported to use BTF tagging */
9840 	param_name = btf_name_by_offset(btf, arg->name_off);
9841 	if (str_is_empty(param_name))
9842 		return false;
9843 	len = strlen(param_name);
9844 	if (len < suffix_len)
9845 		return false;
9846 	param_name += len - suffix_len;
9847 	return !strncmp(param_name, suffix, suffix_len);
9848 }
9849 
9850 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9851 				  const struct btf_param *arg,
9852 				  const struct bpf_reg_state *reg)
9853 {
9854 	const struct btf_type *t;
9855 
9856 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9857 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9858 		return false;
9859 
9860 	return __kfunc_param_match_suffix(btf, arg, "__sz");
9861 }
9862 
9863 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9864 					const struct btf_param *arg,
9865 					const struct bpf_reg_state *reg)
9866 {
9867 	const struct btf_type *t;
9868 
9869 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9870 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9871 		return false;
9872 
9873 	return __kfunc_param_match_suffix(btf, arg, "__szk");
9874 }
9875 
9876 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9877 {
9878 	return __kfunc_param_match_suffix(btf, arg, "__opt");
9879 }
9880 
9881 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9882 {
9883 	return __kfunc_param_match_suffix(btf, arg, "__k");
9884 }
9885 
9886 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9887 {
9888 	return __kfunc_param_match_suffix(btf, arg, "__ign");
9889 }
9890 
9891 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9892 {
9893 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
9894 }
9895 
9896 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9897 {
9898 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
9899 }
9900 
9901 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9902 {
9903 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9904 }
9905 
9906 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9907 					  const struct btf_param *arg,
9908 					  const char *name)
9909 {
9910 	int len, target_len = strlen(name);
9911 	const char *param_name;
9912 
9913 	param_name = btf_name_by_offset(btf, arg->name_off);
9914 	if (str_is_empty(param_name))
9915 		return false;
9916 	len = strlen(param_name);
9917 	if (len != target_len)
9918 		return false;
9919 	if (strcmp(param_name, name))
9920 		return false;
9921 
9922 	return true;
9923 }
9924 
9925 enum {
9926 	KF_ARG_DYNPTR_ID,
9927 	KF_ARG_LIST_HEAD_ID,
9928 	KF_ARG_LIST_NODE_ID,
9929 	KF_ARG_RB_ROOT_ID,
9930 	KF_ARG_RB_NODE_ID,
9931 };
9932 
9933 BTF_ID_LIST(kf_arg_btf_ids)
9934 BTF_ID(struct, bpf_dynptr_kern)
9935 BTF_ID(struct, bpf_list_head)
9936 BTF_ID(struct, bpf_list_node)
9937 BTF_ID(struct, bpf_rb_root)
9938 BTF_ID(struct, bpf_rb_node)
9939 
9940 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9941 				    const struct btf_param *arg, int type)
9942 {
9943 	const struct btf_type *t;
9944 	u32 res_id;
9945 
9946 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9947 	if (!t)
9948 		return false;
9949 	if (!btf_type_is_ptr(t))
9950 		return false;
9951 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
9952 	if (!t)
9953 		return false;
9954 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9955 }
9956 
9957 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9958 {
9959 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9960 }
9961 
9962 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9963 {
9964 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9965 }
9966 
9967 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9968 {
9969 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9970 }
9971 
9972 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9973 {
9974 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9975 }
9976 
9977 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9978 {
9979 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9980 }
9981 
9982 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9983 				  const struct btf_param *arg)
9984 {
9985 	const struct btf_type *t;
9986 
9987 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9988 	if (!t)
9989 		return false;
9990 
9991 	return true;
9992 }
9993 
9994 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9995 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9996 					const struct btf *btf,
9997 					const struct btf_type *t, int rec)
9998 {
9999 	const struct btf_type *member_type;
10000 	const struct btf_member *member;
10001 	u32 i;
10002 
10003 	if (!btf_type_is_struct(t))
10004 		return false;
10005 
10006 	for_each_member(i, t, member) {
10007 		const struct btf_array *array;
10008 
10009 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10010 		if (btf_type_is_struct(member_type)) {
10011 			if (rec >= 3) {
10012 				verbose(env, "max struct nesting depth exceeded\n");
10013 				return false;
10014 			}
10015 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10016 				return false;
10017 			continue;
10018 		}
10019 		if (btf_type_is_array(member_type)) {
10020 			array = btf_array(member_type);
10021 			if (!array->nelems)
10022 				return false;
10023 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10024 			if (!btf_type_is_scalar(member_type))
10025 				return false;
10026 			continue;
10027 		}
10028 		if (!btf_type_is_scalar(member_type))
10029 			return false;
10030 	}
10031 	return true;
10032 }
10033 
10034 
10035 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
10036 #ifdef CONFIG_NET
10037 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
10038 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
10039 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
10040 #endif
10041 };
10042 
10043 enum kfunc_ptr_arg_type {
10044 	KF_ARG_PTR_TO_CTX,
10045 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10046 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10047 	KF_ARG_PTR_TO_DYNPTR,
10048 	KF_ARG_PTR_TO_ITER,
10049 	KF_ARG_PTR_TO_LIST_HEAD,
10050 	KF_ARG_PTR_TO_LIST_NODE,
10051 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10052 	KF_ARG_PTR_TO_MEM,
10053 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10054 	KF_ARG_PTR_TO_CALLBACK,
10055 	KF_ARG_PTR_TO_RB_ROOT,
10056 	KF_ARG_PTR_TO_RB_NODE,
10057 };
10058 
10059 enum special_kfunc_type {
10060 	KF_bpf_obj_new_impl,
10061 	KF_bpf_obj_drop_impl,
10062 	KF_bpf_refcount_acquire_impl,
10063 	KF_bpf_list_push_front_impl,
10064 	KF_bpf_list_push_back_impl,
10065 	KF_bpf_list_pop_front,
10066 	KF_bpf_list_pop_back,
10067 	KF_bpf_cast_to_kern_ctx,
10068 	KF_bpf_rdonly_cast,
10069 	KF_bpf_rcu_read_lock,
10070 	KF_bpf_rcu_read_unlock,
10071 	KF_bpf_rbtree_remove,
10072 	KF_bpf_rbtree_add_impl,
10073 	KF_bpf_rbtree_first,
10074 	KF_bpf_dynptr_from_skb,
10075 	KF_bpf_dynptr_from_xdp,
10076 	KF_bpf_dynptr_slice,
10077 	KF_bpf_dynptr_slice_rdwr,
10078 	KF_bpf_dynptr_clone,
10079 };
10080 
10081 BTF_SET_START(special_kfunc_set)
10082 BTF_ID(func, bpf_obj_new_impl)
10083 BTF_ID(func, bpf_obj_drop_impl)
10084 BTF_ID(func, bpf_refcount_acquire_impl)
10085 BTF_ID(func, bpf_list_push_front_impl)
10086 BTF_ID(func, bpf_list_push_back_impl)
10087 BTF_ID(func, bpf_list_pop_front)
10088 BTF_ID(func, bpf_list_pop_back)
10089 BTF_ID(func, bpf_cast_to_kern_ctx)
10090 BTF_ID(func, bpf_rdonly_cast)
10091 BTF_ID(func, bpf_rbtree_remove)
10092 BTF_ID(func, bpf_rbtree_add_impl)
10093 BTF_ID(func, bpf_rbtree_first)
10094 BTF_ID(func, bpf_dynptr_from_skb)
10095 BTF_ID(func, bpf_dynptr_from_xdp)
10096 BTF_ID(func, bpf_dynptr_slice)
10097 BTF_ID(func, bpf_dynptr_slice_rdwr)
10098 BTF_ID(func, bpf_dynptr_clone)
10099 BTF_SET_END(special_kfunc_set)
10100 
10101 BTF_ID_LIST(special_kfunc_list)
10102 BTF_ID(func, bpf_obj_new_impl)
10103 BTF_ID(func, bpf_obj_drop_impl)
10104 BTF_ID(func, bpf_refcount_acquire_impl)
10105 BTF_ID(func, bpf_list_push_front_impl)
10106 BTF_ID(func, bpf_list_push_back_impl)
10107 BTF_ID(func, bpf_list_pop_front)
10108 BTF_ID(func, bpf_list_pop_back)
10109 BTF_ID(func, bpf_cast_to_kern_ctx)
10110 BTF_ID(func, bpf_rdonly_cast)
10111 BTF_ID(func, bpf_rcu_read_lock)
10112 BTF_ID(func, bpf_rcu_read_unlock)
10113 BTF_ID(func, bpf_rbtree_remove)
10114 BTF_ID(func, bpf_rbtree_add_impl)
10115 BTF_ID(func, bpf_rbtree_first)
10116 BTF_ID(func, bpf_dynptr_from_skb)
10117 BTF_ID(func, bpf_dynptr_from_xdp)
10118 BTF_ID(func, bpf_dynptr_slice)
10119 BTF_ID(func, bpf_dynptr_slice_rdwr)
10120 BTF_ID(func, bpf_dynptr_clone)
10121 
10122 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10123 {
10124 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10125 	    meta->arg_owning_ref) {
10126 		return false;
10127 	}
10128 
10129 	return meta->kfunc_flags & KF_RET_NULL;
10130 }
10131 
10132 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10133 {
10134 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10135 }
10136 
10137 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10138 {
10139 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10140 }
10141 
10142 static enum kfunc_ptr_arg_type
10143 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10144 		       struct bpf_kfunc_call_arg_meta *meta,
10145 		       const struct btf_type *t, const struct btf_type *ref_t,
10146 		       const char *ref_tname, const struct btf_param *args,
10147 		       int argno, int nargs)
10148 {
10149 	u32 regno = argno + 1;
10150 	struct bpf_reg_state *regs = cur_regs(env);
10151 	struct bpf_reg_state *reg = &regs[regno];
10152 	bool arg_mem_size = false;
10153 
10154 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10155 		return KF_ARG_PTR_TO_CTX;
10156 
10157 	/* In this function, we verify the kfunc's BTF as per the argument type,
10158 	 * leaving the rest of the verification with respect to the register
10159 	 * type to our caller. When a set of conditions hold in the BTF type of
10160 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10161 	 */
10162 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10163 		return KF_ARG_PTR_TO_CTX;
10164 
10165 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10166 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10167 
10168 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10169 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10170 
10171 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10172 		return KF_ARG_PTR_TO_DYNPTR;
10173 
10174 	if (is_kfunc_arg_iter(meta, argno))
10175 		return KF_ARG_PTR_TO_ITER;
10176 
10177 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10178 		return KF_ARG_PTR_TO_LIST_HEAD;
10179 
10180 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10181 		return KF_ARG_PTR_TO_LIST_NODE;
10182 
10183 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10184 		return KF_ARG_PTR_TO_RB_ROOT;
10185 
10186 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10187 		return KF_ARG_PTR_TO_RB_NODE;
10188 
10189 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10190 		if (!btf_type_is_struct(ref_t)) {
10191 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10192 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10193 			return -EINVAL;
10194 		}
10195 		return KF_ARG_PTR_TO_BTF_ID;
10196 	}
10197 
10198 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10199 		return KF_ARG_PTR_TO_CALLBACK;
10200 
10201 
10202 	if (argno + 1 < nargs &&
10203 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10204 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10205 		arg_mem_size = true;
10206 
10207 	/* This is the catch all argument type of register types supported by
10208 	 * check_helper_mem_access. However, we only allow when argument type is
10209 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10210 	 * arg_mem_size is true, the pointer can be void *.
10211 	 */
10212 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10213 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10214 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10215 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10216 		return -EINVAL;
10217 	}
10218 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10219 }
10220 
10221 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10222 					struct bpf_reg_state *reg,
10223 					const struct btf_type *ref_t,
10224 					const char *ref_tname, u32 ref_id,
10225 					struct bpf_kfunc_call_arg_meta *meta,
10226 					int argno)
10227 {
10228 	const struct btf_type *reg_ref_t;
10229 	bool strict_type_match = false;
10230 	const struct btf *reg_btf;
10231 	const char *reg_ref_tname;
10232 	u32 reg_ref_id;
10233 
10234 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10235 		reg_btf = reg->btf;
10236 		reg_ref_id = reg->btf_id;
10237 	} else {
10238 		reg_btf = btf_vmlinux;
10239 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10240 	}
10241 
10242 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10243 	 * or releasing a reference, or are no-cast aliases. We do _not_
10244 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10245 	 * as we want to enable BPF programs to pass types that are bitwise
10246 	 * equivalent without forcing them to explicitly cast with something
10247 	 * like bpf_cast_to_kern_ctx().
10248 	 *
10249 	 * For example, say we had a type like the following:
10250 	 *
10251 	 * struct bpf_cpumask {
10252 	 *	cpumask_t cpumask;
10253 	 *	refcount_t usage;
10254 	 * };
10255 	 *
10256 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10257 	 * to a struct cpumask, so it would be safe to pass a struct
10258 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10259 	 *
10260 	 * The philosophy here is similar to how we allow scalars of different
10261 	 * types to be passed to kfuncs as long as the size is the same. The
10262 	 * only difference here is that we're simply allowing
10263 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10264 	 * resolve types.
10265 	 */
10266 	if (is_kfunc_acquire(meta) ||
10267 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10268 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10269 		strict_type_match = true;
10270 
10271 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10272 
10273 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10274 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10275 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10276 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10277 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10278 			btf_type_str(reg_ref_t), reg_ref_tname);
10279 		return -EINVAL;
10280 	}
10281 	return 0;
10282 }
10283 
10284 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10285 {
10286 	struct bpf_verifier_state *state = env->cur_state;
10287 
10288 	if (!state->active_lock.ptr) {
10289 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10290 		return -EFAULT;
10291 	}
10292 
10293 	if (type_flag(reg->type) & NON_OWN_REF) {
10294 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10295 		return -EFAULT;
10296 	}
10297 
10298 	reg->type |= NON_OWN_REF;
10299 	return 0;
10300 }
10301 
10302 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10303 {
10304 	struct bpf_func_state *state, *unused;
10305 	struct bpf_reg_state *reg;
10306 	int i;
10307 
10308 	state = cur_func(env);
10309 
10310 	if (!ref_obj_id) {
10311 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10312 			     "owning -> non-owning conversion\n");
10313 		return -EFAULT;
10314 	}
10315 
10316 	for (i = 0; i < state->acquired_refs; i++) {
10317 		if (state->refs[i].id != ref_obj_id)
10318 			continue;
10319 
10320 		/* Clear ref_obj_id here so release_reference doesn't clobber
10321 		 * the whole reg
10322 		 */
10323 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10324 			if (reg->ref_obj_id == ref_obj_id) {
10325 				reg->ref_obj_id = 0;
10326 				ref_set_non_owning(env, reg);
10327 			}
10328 		}));
10329 		return 0;
10330 	}
10331 
10332 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10333 	return -EFAULT;
10334 }
10335 
10336 /* Implementation details:
10337  *
10338  * Each register points to some region of memory, which we define as an
10339  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10340  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10341  * allocation. The lock and the data it protects are colocated in the same
10342  * memory region.
10343  *
10344  * Hence, everytime a register holds a pointer value pointing to such
10345  * allocation, the verifier preserves a unique reg->id for it.
10346  *
10347  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10348  * bpf_spin_lock is called.
10349  *
10350  * To enable this, lock state in the verifier captures two values:
10351  *	active_lock.ptr = Register's type specific pointer
10352  *	active_lock.id  = A unique ID for each register pointer value
10353  *
10354  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10355  * supported register types.
10356  *
10357  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10358  * allocated objects is the reg->btf pointer.
10359  *
10360  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10361  * can establish the provenance of the map value statically for each distinct
10362  * lookup into such maps. They always contain a single map value hence unique
10363  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10364  *
10365  * So, in case of global variables, they use array maps with max_entries = 1,
10366  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10367  * into the same map value as max_entries is 1, as described above).
10368  *
10369  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10370  * outer map pointer (in verifier context), but each lookup into an inner map
10371  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10372  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10373  * will get different reg->id assigned to each lookup, hence different
10374  * active_lock.id.
10375  *
10376  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10377  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10378  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10379  */
10380 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10381 {
10382 	void *ptr;
10383 	u32 id;
10384 
10385 	switch ((int)reg->type) {
10386 	case PTR_TO_MAP_VALUE:
10387 		ptr = reg->map_ptr;
10388 		break;
10389 	case PTR_TO_BTF_ID | MEM_ALLOC:
10390 		ptr = reg->btf;
10391 		break;
10392 	default:
10393 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
10394 		return -EFAULT;
10395 	}
10396 	id = reg->id;
10397 
10398 	if (!env->cur_state->active_lock.ptr)
10399 		return -EINVAL;
10400 	if (env->cur_state->active_lock.ptr != ptr ||
10401 	    env->cur_state->active_lock.id != id) {
10402 		verbose(env, "held lock and object are not in the same allocation\n");
10403 		return -EINVAL;
10404 	}
10405 	return 0;
10406 }
10407 
10408 static bool is_bpf_list_api_kfunc(u32 btf_id)
10409 {
10410 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10411 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10412 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10413 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10414 }
10415 
10416 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10417 {
10418 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10419 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10420 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10421 }
10422 
10423 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10424 {
10425 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10426 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10427 }
10428 
10429 static bool is_callback_calling_kfunc(u32 btf_id)
10430 {
10431 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10432 }
10433 
10434 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10435 {
10436 	return is_bpf_rbtree_api_kfunc(btf_id);
10437 }
10438 
10439 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10440 					  enum btf_field_type head_field_type,
10441 					  u32 kfunc_btf_id)
10442 {
10443 	bool ret;
10444 
10445 	switch (head_field_type) {
10446 	case BPF_LIST_HEAD:
10447 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10448 		break;
10449 	case BPF_RB_ROOT:
10450 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10451 		break;
10452 	default:
10453 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10454 			btf_field_type_name(head_field_type));
10455 		return false;
10456 	}
10457 
10458 	if (!ret)
10459 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10460 			btf_field_type_name(head_field_type));
10461 	return ret;
10462 }
10463 
10464 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10465 					  enum btf_field_type node_field_type,
10466 					  u32 kfunc_btf_id)
10467 {
10468 	bool ret;
10469 
10470 	switch (node_field_type) {
10471 	case BPF_LIST_NODE:
10472 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10473 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10474 		break;
10475 	case BPF_RB_NODE:
10476 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10477 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10478 		break;
10479 	default:
10480 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10481 			btf_field_type_name(node_field_type));
10482 		return false;
10483 	}
10484 
10485 	if (!ret)
10486 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10487 			btf_field_type_name(node_field_type));
10488 	return ret;
10489 }
10490 
10491 static int
10492 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10493 				   struct bpf_reg_state *reg, u32 regno,
10494 				   struct bpf_kfunc_call_arg_meta *meta,
10495 				   enum btf_field_type head_field_type,
10496 				   struct btf_field **head_field)
10497 {
10498 	const char *head_type_name;
10499 	struct btf_field *field;
10500 	struct btf_record *rec;
10501 	u32 head_off;
10502 
10503 	if (meta->btf != btf_vmlinux) {
10504 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10505 		return -EFAULT;
10506 	}
10507 
10508 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10509 		return -EFAULT;
10510 
10511 	head_type_name = btf_field_type_name(head_field_type);
10512 	if (!tnum_is_const(reg->var_off)) {
10513 		verbose(env,
10514 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10515 			regno, head_type_name);
10516 		return -EINVAL;
10517 	}
10518 
10519 	rec = reg_btf_record(reg);
10520 	head_off = reg->off + reg->var_off.value;
10521 	field = btf_record_find(rec, head_off, head_field_type);
10522 	if (!field) {
10523 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10524 		return -EINVAL;
10525 	}
10526 
10527 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10528 	if (check_reg_allocation_locked(env, reg)) {
10529 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10530 			rec->spin_lock_off, head_type_name);
10531 		return -EINVAL;
10532 	}
10533 
10534 	if (*head_field) {
10535 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10536 		return -EFAULT;
10537 	}
10538 	*head_field = field;
10539 	return 0;
10540 }
10541 
10542 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10543 					   struct bpf_reg_state *reg, u32 regno,
10544 					   struct bpf_kfunc_call_arg_meta *meta)
10545 {
10546 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10547 							  &meta->arg_list_head.field);
10548 }
10549 
10550 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10551 					     struct bpf_reg_state *reg, u32 regno,
10552 					     struct bpf_kfunc_call_arg_meta *meta)
10553 {
10554 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10555 							  &meta->arg_rbtree_root.field);
10556 }
10557 
10558 static int
10559 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10560 				   struct bpf_reg_state *reg, u32 regno,
10561 				   struct bpf_kfunc_call_arg_meta *meta,
10562 				   enum btf_field_type head_field_type,
10563 				   enum btf_field_type node_field_type,
10564 				   struct btf_field **node_field)
10565 {
10566 	const char *node_type_name;
10567 	const struct btf_type *et, *t;
10568 	struct btf_field *field;
10569 	u32 node_off;
10570 
10571 	if (meta->btf != btf_vmlinux) {
10572 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10573 		return -EFAULT;
10574 	}
10575 
10576 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10577 		return -EFAULT;
10578 
10579 	node_type_name = btf_field_type_name(node_field_type);
10580 	if (!tnum_is_const(reg->var_off)) {
10581 		verbose(env,
10582 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
10583 			regno, node_type_name);
10584 		return -EINVAL;
10585 	}
10586 
10587 	node_off = reg->off + reg->var_off.value;
10588 	field = reg_find_field_offset(reg, node_off, node_field_type);
10589 	if (!field || field->offset != node_off) {
10590 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10591 		return -EINVAL;
10592 	}
10593 
10594 	field = *node_field;
10595 
10596 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10597 	t = btf_type_by_id(reg->btf, reg->btf_id);
10598 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10599 				  field->graph_root.value_btf_id, true)) {
10600 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10601 			"in struct %s, but arg is at offset=%d in struct %s\n",
10602 			btf_field_type_name(head_field_type),
10603 			btf_field_type_name(node_field_type),
10604 			field->graph_root.node_offset,
10605 			btf_name_by_offset(field->graph_root.btf, et->name_off),
10606 			node_off, btf_name_by_offset(reg->btf, t->name_off));
10607 		return -EINVAL;
10608 	}
10609 	meta->arg_btf = reg->btf;
10610 	meta->arg_btf_id = reg->btf_id;
10611 
10612 	if (node_off != field->graph_root.node_offset) {
10613 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10614 			node_off, btf_field_type_name(node_field_type),
10615 			field->graph_root.node_offset,
10616 			btf_name_by_offset(field->graph_root.btf, et->name_off));
10617 		return -EINVAL;
10618 	}
10619 
10620 	return 0;
10621 }
10622 
10623 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10624 					   struct bpf_reg_state *reg, u32 regno,
10625 					   struct bpf_kfunc_call_arg_meta *meta)
10626 {
10627 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10628 						  BPF_LIST_HEAD, BPF_LIST_NODE,
10629 						  &meta->arg_list_head.field);
10630 }
10631 
10632 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10633 					     struct bpf_reg_state *reg, u32 regno,
10634 					     struct bpf_kfunc_call_arg_meta *meta)
10635 {
10636 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10637 						  BPF_RB_ROOT, BPF_RB_NODE,
10638 						  &meta->arg_rbtree_root.field);
10639 }
10640 
10641 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10642 			    int insn_idx)
10643 {
10644 	const char *func_name = meta->func_name, *ref_tname;
10645 	const struct btf *btf = meta->btf;
10646 	const struct btf_param *args;
10647 	struct btf_record *rec;
10648 	u32 i, nargs;
10649 	int ret;
10650 
10651 	args = (const struct btf_param *)(meta->func_proto + 1);
10652 	nargs = btf_type_vlen(meta->func_proto);
10653 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10654 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10655 			MAX_BPF_FUNC_REG_ARGS);
10656 		return -EINVAL;
10657 	}
10658 
10659 	/* Check that BTF function arguments match actual types that the
10660 	 * verifier sees.
10661 	 */
10662 	for (i = 0; i < nargs; i++) {
10663 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10664 		const struct btf_type *t, *ref_t, *resolve_ret;
10665 		enum bpf_arg_type arg_type = ARG_DONTCARE;
10666 		u32 regno = i + 1, ref_id, type_size;
10667 		bool is_ret_buf_sz = false;
10668 		int kf_arg_type;
10669 
10670 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10671 
10672 		if (is_kfunc_arg_ignore(btf, &args[i]))
10673 			continue;
10674 
10675 		if (btf_type_is_scalar(t)) {
10676 			if (reg->type != SCALAR_VALUE) {
10677 				verbose(env, "R%d is not a scalar\n", regno);
10678 				return -EINVAL;
10679 			}
10680 
10681 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10682 				if (meta->arg_constant.found) {
10683 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10684 					return -EFAULT;
10685 				}
10686 				if (!tnum_is_const(reg->var_off)) {
10687 					verbose(env, "R%d must be a known constant\n", regno);
10688 					return -EINVAL;
10689 				}
10690 				ret = mark_chain_precision(env, regno);
10691 				if (ret < 0)
10692 					return ret;
10693 				meta->arg_constant.found = true;
10694 				meta->arg_constant.value = reg->var_off.value;
10695 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10696 				meta->r0_rdonly = true;
10697 				is_ret_buf_sz = true;
10698 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10699 				is_ret_buf_sz = true;
10700 			}
10701 
10702 			if (is_ret_buf_sz) {
10703 				if (meta->r0_size) {
10704 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10705 					return -EINVAL;
10706 				}
10707 
10708 				if (!tnum_is_const(reg->var_off)) {
10709 					verbose(env, "R%d is not a const\n", regno);
10710 					return -EINVAL;
10711 				}
10712 
10713 				meta->r0_size = reg->var_off.value;
10714 				ret = mark_chain_precision(env, regno);
10715 				if (ret)
10716 					return ret;
10717 			}
10718 			continue;
10719 		}
10720 
10721 		if (!btf_type_is_ptr(t)) {
10722 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10723 			return -EINVAL;
10724 		}
10725 
10726 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10727 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
10728 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10729 			return -EACCES;
10730 		}
10731 
10732 		if (reg->ref_obj_id) {
10733 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
10734 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10735 					regno, reg->ref_obj_id,
10736 					meta->ref_obj_id);
10737 				return -EFAULT;
10738 			}
10739 			meta->ref_obj_id = reg->ref_obj_id;
10740 			if (is_kfunc_release(meta))
10741 				meta->release_regno = regno;
10742 		}
10743 
10744 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10745 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10746 
10747 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10748 		if (kf_arg_type < 0)
10749 			return kf_arg_type;
10750 
10751 		switch (kf_arg_type) {
10752 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10753 		case KF_ARG_PTR_TO_BTF_ID:
10754 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10755 				break;
10756 
10757 			if (!is_trusted_reg(reg)) {
10758 				if (!is_kfunc_rcu(meta)) {
10759 					verbose(env, "R%d must be referenced or trusted\n", regno);
10760 					return -EINVAL;
10761 				}
10762 				if (!is_rcu_reg(reg)) {
10763 					verbose(env, "R%d must be a rcu pointer\n", regno);
10764 					return -EINVAL;
10765 				}
10766 			}
10767 
10768 			fallthrough;
10769 		case KF_ARG_PTR_TO_CTX:
10770 			/* Trusted arguments have the same offset checks as release arguments */
10771 			arg_type |= OBJ_RELEASE;
10772 			break;
10773 		case KF_ARG_PTR_TO_DYNPTR:
10774 		case KF_ARG_PTR_TO_ITER:
10775 		case KF_ARG_PTR_TO_LIST_HEAD:
10776 		case KF_ARG_PTR_TO_LIST_NODE:
10777 		case KF_ARG_PTR_TO_RB_ROOT:
10778 		case KF_ARG_PTR_TO_RB_NODE:
10779 		case KF_ARG_PTR_TO_MEM:
10780 		case KF_ARG_PTR_TO_MEM_SIZE:
10781 		case KF_ARG_PTR_TO_CALLBACK:
10782 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10783 			/* Trusted by default */
10784 			break;
10785 		default:
10786 			WARN_ON_ONCE(1);
10787 			return -EFAULT;
10788 		}
10789 
10790 		if (is_kfunc_release(meta) && reg->ref_obj_id)
10791 			arg_type |= OBJ_RELEASE;
10792 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10793 		if (ret < 0)
10794 			return ret;
10795 
10796 		switch (kf_arg_type) {
10797 		case KF_ARG_PTR_TO_CTX:
10798 			if (reg->type != PTR_TO_CTX) {
10799 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10800 				return -EINVAL;
10801 			}
10802 
10803 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10804 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10805 				if (ret < 0)
10806 					return -EINVAL;
10807 				meta->ret_btf_id  = ret;
10808 			}
10809 			break;
10810 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10811 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10812 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10813 				return -EINVAL;
10814 			}
10815 			if (!reg->ref_obj_id) {
10816 				verbose(env, "allocated object must be referenced\n");
10817 				return -EINVAL;
10818 			}
10819 			if (meta->btf == btf_vmlinux &&
10820 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10821 				meta->arg_btf = reg->btf;
10822 				meta->arg_btf_id = reg->btf_id;
10823 			}
10824 			break;
10825 		case KF_ARG_PTR_TO_DYNPTR:
10826 		{
10827 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10828 			int clone_ref_obj_id = 0;
10829 
10830 			if (reg->type != PTR_TO_STACK &&
10831 			    reg->type != CONST_PTR_TO_DYNPTR) {
10832 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10833 				return -EINVAL;
10834 			}
10835 
10836 			if (reg->type == CONST_PTR_TO_DYNPTR)
10837 				dynptr_arg_type |= MEM_RDONLY;
10838 
10839 			if (is_kfunc_arg_uninit(btf, &args[i]))
10840 				dynptr_arg_type |= MEM_UNINIT;
10841 
10842 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10843 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
10844 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10845 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
10846 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10847 				   (dynptr_arg_type & MEM_UNINIT)) {
10848 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10849 
10850 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10851 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10852 					return -EFAULT;
10853 				}
10854 
10855 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10856 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10857 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10858 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10859 					return -EFAULT;
10860 				}
10861 			}
10862 
10863 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10864 			if (ret < 0)
10865 				return ret;
10866 
10867 			if (!(dynptr_arg_type & MEM_UNINIT)) {
10868 				int id = dynptr_id(env, reg);
10869 
10870 				if (id < 0) {
10871 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10872 					return id;
10873 				}
10874 				meta->initialized_dynptr.id = id;
10875 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10876 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10877 			}
10878 
10879 			break;
10880 		}
10881 		case KF_ARG_PTR_TO_ITER:
10882 			ret = process_iter_arg(env, regno, insn_idx, meta);
10883 			if (ret < 0)
10884 				return ret;
10885 			break;
10886 		case KF_ARG_PTR_TO_LIST_HEAD:
10887 			if (reg->type != PTR_TO_MAP_VALUE &&
10888 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10889 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10890 				return -EINVAL;
10891 			}
10892 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10893 				verbose(env, "allocated object must be referenced\n");
10894 				return -EINVAL;
10895 			}
10896 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10897 			if (ret < 0)
10898 				return ret;
10899 			break;
10900 		case KF_ARG_PTR_TO_RB_ROOT:
10901 			if (reg->type != PTR_TO_MAP_VALUE &&
10902 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10903 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10904 				return -EINVAL;
10905 			}
10906 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10907 				verbose(env, "allocated object must be referenced\n");
10908 				return -EINVAL;
10909 			}
10910 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10911 			if (ret < 0)
10912 				return ret;
10913 			break;
10914 		case KF_ARG_PTR_TO_LIST_NODE:
10915 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10916 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
10917 				return -EINVAL;
10918 			}
10919 			if (!reg->ref_obj_id) {
10920 				verbose(env, "allocated object must be referenced\n");
10921 				return -EINVAL;
10922 			}
10923 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10924 			if (ret < 0)
10925 				return ret;
10926 			break;
10927 		case KF_ARG_PTR_TO_RB_NODE:
10928 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10929 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10930 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
10931 					return -EINVAL;
10932 				}
10933 				if (in_rbtree_lock_required_cb(env)) {
10934 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10935 					return -EINVAL;
10936 				}
10937 			} else {
10938 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10939 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10940 					return -EINVAL;
10941 				}
10942 				if (!reg->ref_obj_id) {
10943 					verbose(env, "allocated object must be referenced\n");
10944 					return -EINVAL;
10945 				}
10946 			}
10947 
10948 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10949 			if (ret < 0)
10950 				return ret;
10951 			break;
10952 		case KF_ARG_PTR_TO_BTF_ID:
10953 			/* Only base_type is checked, further checks are done here */
10954 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10955 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10956 			    !reg2btf_ids[base_type(reg->type)]) {
10957 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10958 				verbose(env, "expected %s or socket\n",
10959 					reg_type_str(env, base_type(reg->type) |
10960 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10961 				return -EINVAL;
10962 			}
10963 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10964 			if (ret < 0)
10965 				return ret;
10966 			break;
10967 		case KF_ARG_PTR_TO_MEM:
10968 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10969 			if (IS_ERR(resolve_ret)) {
10970 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10971 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10972 				return -EINVAL;
10973 			}
10974 			ret = check_mem_reg(env, reg, regno, type_size);
10975 			if (ret < 0)
10976 				return ret;
10977 			break;
10978 		case KF_ARG_PTR_TO_MEM_SIZE:
10979 		{
10980 			struct bpf_reg_state *buff_reg = &regs[regno];
10981 			const struct btf_param *buff_arg = &args[i];
10982 			struct bpf_reg_state *size_reg = &regs[regno + 1];
10983 			const struct btf_param *size_arg = &args[i + 1];
10984 
10985 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
10986 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10987 				if (ret < 0) {
10988 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10989 					return ret;
10990 				}
10991 			}
10992 
10993 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10994 				if (meta->arg_constant.found) {
10995 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10996 					return -EFAULT;
10997 				}
10998 				if (!tnum_is_const(size_reg->var_off)) {
10999 					verbose(env, "R%d must be a known constant\n", regno + 1);
11000 					return -EINVAL;
11001 				}
11002 				meta->arg_constant.found = true;
11003 				meta->arg_constant.value = size_reg->var_off.value;
11004 			}
11005 
11006 			/* Skip next '__sz' or '__szk' argument */
11007 			i++;
11008 			break;
11009 		}
11010 		case KF_ARG_PTR_TO_CALLBACK:
11011 			meta->subprogno = reg->subprogno;
11012 			break;
11013 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11014 			if (!type_is_ptr_alloc_obj(reg->type)) {
11015 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11016 				return -EINVAL;
11017 			}
11018 			if (!type_is_non_owning_ref(reg->type))
11019 				meta->arg_owning_ref = true;
11020 
11021 			rec = reg_btf_record(reg);
11022 			if (!rec) {
11023 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11024 				return -EFAULT;
11025 			}
11026 
11027 			if (rec->refcount_off < 0) {
11028 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11029 				return -EINVAL;
11030 			}
11031 			if (rec->refcount_off >= 0) {
11032 				verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11033 				return -EINVAL;
11034 			}
11035 			meta->arg_btf = reg->btf;
11036 			meta->arg_btf_id = reg->btf_id;
11037 			break;
11038 		}
11039 	}
11040 
11041 	if (is_kfunc_release(meta) && !meta->release_regno) {
11042 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11043 			func_name);
11044 		return -EINVAL;
11045 	}
11046 
11047 	return 0;
11048 }
11049 
11050 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11051 			    struct bpf_insn *insn,
11052 			    struct bpf_kfunc_call_arg_meta *meta,
11053 			    const char **kfunc_name)
11054 {
11055 	const struct btf_type *func, *func_proto;
11056 	u32 func_id, *kfunc_flags;
11057 	const char *func_name;
11058 	struct btf *desc_btf;
11059 
11060 	if (kfunc_name)
11061 		*kfunc_name = NULL;
11062 
11063 	if (!insn->imm)
11064 		return -EINVAL;
11065 
11066 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11067 	if (IS_ERR(desc_btf))
11068 		return PTR_ERR(desc_btf);
11069 
11070 	func_id = insn->imm;
11071 	func = btf_type_by_id(desc_btf, func_id);
11072 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11073 	if (kfunc_name)
11074 		*kfunc_name = func_name;
11075 	func_proto = btf_type_by_id(desc_btf, func->type);
11076 
11077 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11078 	if (!kfunc_flags) {
11079 		return -EACCES;
11080 	}
11081 
11082 	memset(meta, 0, sizeof(*meta));
11083 	meta->btf = desc_btf;
11084 	meta->func_id = func_id;
11085 	meta->kfunc_flags = *kfunc_flags;
11086 	meta->func_proto = func_proto;
11087 	meta->func_name = func_name;
11088 
11089 	return 0;
11090 }
11091 
11092 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11093 			    int *insn_idx_p)
11094 {
11095 	const struct btf_type *t, *ptr_type;
11096 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11097 	struct bpf_reg_state *regs = cur_regs(env);
11098 	const char *func_name, *ptr_type_name;
11099 	bool sleepable, rcu_lock, rcu_unlock;
11100 	struct bpf_kfunc_call_arg_meta meta;
11101 	struct bpf_insn_aux_data *insn_aux;
11102 	int err, insn_idx = *insn_idx_p;
11103 	const struct btf_param *args;
11104 	const struct btf_type *ret_t;
11105 	struct btf *desc_btf;
11106 
11107 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11108 	if (!insn->imm)
11109 		return 0;
11110 
11111 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11112 	if (err == -EACCES && func_name)
11113 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11114 	if (err)
11115 		return err;
11116 	desc_btf = meta.btf;
11117 	insn_aux = &env->insn_aux_data[insn_idx];
11118 
11119 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11120 
11121 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11122 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11123 		return -EACCES;
11124 	}
11125 
11126 	sleepable = is_kfunc_sleepable(&meta);
11127 	if (sleepable && !env->prog->aux->sleepable) {
11128 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11129 		return -EACCES;
11130 	}
11131 
11132 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11133 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11134 
11135 	if (env->cur_state->active_rcu_lock) {
11136 		struct bpf_func_state *state;
11137 		struct bpf_reg_state *reg;
11138 
11139 		if (rcu_lock) {
11140 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11141 			return -EINVAL;
11142 		} else if (rcu_unlock) {
11143 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11144 				if (reg->type & MEM_RCU) {
11145 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11146 					reg->type |= PTR_UNTRUSTED;
11147 				}
11148 			}));
11149 			env->cur_state->active_rcu_lock = false;
11150 		} else if (sleepable) {
11151 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11152 			return -EACCES;
11153 		}
11154 	} else if (rcu_lock) {
11155 		env->cur_state->active_rcu_lock = true;
11156 	} else if (rcu_unlock) {
11157 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11158 		return -EINVAL;
11159 	}
11160 
11161 	/* Check the arguments */
11162 	err = check_kfunc_args(env, &meta, insn_idx);
11163 	if (err < 0)
11164 		return err;
11165 	/* In case of release function, we get register number of refcounted
11166 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11167 	 */
11168 	if (meta.release_regno) {
11169 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11170 		if (err) {
11171 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11172 				func_name, meta.func_id);
11173 			return err;
11174 		}
11175 	}
11176 
11177 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11178 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11179 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11180 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11181 		insn_aux->insert_off = regs[BPF_REG_2].off;
11182 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11183 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11184 		if (err) {
11185 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11186 				func_name, meta.func_id);
11187 			return err;
11188 		}
11189 
11190 		err = release_reference(env, release_ref_obj_id);
11191 		if (err) {
11192 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11193 				func_name, meta.func_id);
11194 			return err;
11195 		}
11196 	}
11197 
11198 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11199 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11200 					set_rbtree_add_callback_state);
11201 		if (err) {
11202 			verbose(env, "kfunc %s#%d failed callback verification\n",
11203 				func_name, meta.func_id);
11204 			return err;
11205 		}
11206 	}
11207 
11208 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11209 		mark_reg_not_init(env, regs, caller_saved[i]);
11210 
11211 	/* Check return type */
11212 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11213 
11214 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11215 		/* Only exception is bpf_obj_new_impl */
11216 		if (meta.btf != btf_vmlinux ||
11217 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11218 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11219 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11220 			return -EINVAL;
11221 		}
11222 	}
11223 
11224 	if (btf_type_is_scalar(t)) {
11225 		mark_reg_unknown(env, regs, BPF_REG_0);
11226 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11227 	} else if (btf_type_is_ptr(t)) {
11228 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11229 
11230 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11231 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11232 				struct btf *ret_btf;
11233 				u32 ret_btf_id;
11234 
11235 				if (unlikely(!bpf_global_ma_set))
11236 					return -ENOMEM;
11237 
11238 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11239 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11240 					return -EINVAL;
11241 				}
11242 
11243 				ret_btf = env->prog->aux->btf;
11244 				ret_btf_id = meta.arg_constant.value;
11245 
11246 				/* This may be NULL due to user not supplying a BTF */
11247 				if (!ret_btf) {
11248 					verbose(env, "bpf_obj_new requires prog BTF\n");
11249 					return -EINVAL;
11250 				}
11251 
11252 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11253 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11254 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11255 					return -EINVAL;
11256 				}
11257 
11258 				mark_reg_known_zero(env, regs, BPF_REG_0);
11259 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11260 				regs[BPF_REG_0].btf = ret_btf;
11261 				regs[BPF_REG_0].btf_id = ret_btf_id;
11262 
11263 				insn_aux->obj_new_size = ret_t->size;
11264 				insn_aux->kptr_struct_meta =
11265 					btf_find_struct_meta(ret_btf, ret_btf_id);
11266 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11267 				mark_reg_known_zero(env, regs, BPF_REG_0);
11268 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11269 				regs[BPF_REG_0].btf = meta.arg_btf;
11270 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11271 
11272 				insn_aux->kptr_struct_meta =
11273 					btf_find_struct_meta(meta.arg_btf,
11274 							     meta.arg_btf_id);
11275 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11276 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11277 				struct btf_field *field = meta.arg_list_head.field;
11278 
11279 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11280 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11281 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11282 				struct btf_field *field = meta.arg_rbtree_root.field;
11283 
11284 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11285 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11286 				mark_reg_known_zero(env, regs, BPF_REG_0);
11287 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11288 				regs[BPF_REG_0].btf = desc_btf;
11289 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11290 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11291 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11292 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11293 					verbose(env,
11294 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11295 					return -EINVAL;
11296 				}
11297 
11298 				mark_reg_known_zero(env, regs, BPF_REG_0);
11299 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11300 				regs[BPF_REG_0].btf = desc_btf;
11301 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11302 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11303 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11304 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11305 
11306 				mark_reg_known_zero(env, regs, BPF_REG_0);
11307 
11308 				if (!meta.arg_constant.found) {
11309 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11310 					return -EFAULT;
11311 				}
11312 
11313 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11314 
11315 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11316 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11317 
11318 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11319 					regs[BPF_REG_0].type |= MEM_RDONLY;
11320 				} else {
11321 					/* this will set env->seen_direct_write to true */
11322 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11323 						verbose(env, "the prog does not allow writes to packet data\n");
11324 						return -EINVAL;
11325 					}
11326 				}
11327 
11328 				if (!meta.initialized_dynptr.id) {
11329 					verbose(env, "verifier internal error: no dynptr id\n");
11330 					return -EFAULT;
11331 				}
11332 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11333 
11334 				/* we don't need to set BPF_REG_0's ref obj id
11335 				 * because packet slices are not refcounted (see
11336 				 * dynptr_type_refcounted)
11337 				 */
11338 			} else {
11339 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11340 					meta.func_name);
11341 				return -EFAULT;
11342 			}
11343 		} else if (!__btf_type_is_struct(ptr_type)) {
11344 			if (!meta.r0_size) {
11345 				__u32 sz;
11346 
11347 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11348 					meta.r0_size = sz;
11349 					meta.r0_rdonly = true;
11350 				}
11351 			}
11352 			if (!meta.r0_size) {
11353 				ptr_type_name = btf_name_by_offset(desc_btf,
11354 								   ptr_type->name_off);
11355 				verbose(env,
11356 					"kernel function %s returns pointer type %s %s is not supported\n",
11357 					func_name,
11358 					btf_type_str(ptr_type),
11359 					ptr_type_name);
11360 				return -EINVAL;
11361 			}
11362 
11363 			mark_reg_known_zero(env, regs, BPF_REG_0);
11364 			regs[BPF_REG_0].type = PTR_TO_MEM;
11365 			regs[BPF_REG_0].mem_size = meta.r0_size;
11366 
11367 			if (meta.r0_rdonly)
11368 				regs[BPF_REG_0].type |= MEM_RDONLY;
11369 
11370 			/* Ensures we don't access the memory after a release_reference() */
11371 			if (meta.ref_obj_id)
11372 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11373 		} else {
11374 			mark_reg_known_zero(env, regs, BPF_REG_0);
11375 			regs[BPF_REG_0].btf = desc_btf;
11376 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11377 			regs[BPF_REG_0].btf_id = ptr_type_id;
11378 		}
11379 
11380 		if (is_kfunc_ret_null(&meta)) {
11381 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11382 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11383 			regs[BPF_REG_0].id = ++env->id_gen;
11384 		}
11385 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11386 		if (is_kfunc_acquire(&meta)) {
11387 			int id = acquire_reference_state(env, insn_idx);
11388 
11389 			if (id < 0)
11390 				return id;
11391 			if (is_kfunc_ret_null(&meta))
11392 				regs[BPF_REG_0].id = id;
11393 			regs[BPF_REG_0].ref_obj_id = id;
11394 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11395 			ref_set_non_owning(env, &regs[BPF_REG_0]);
11396 		}
11397 
11398 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11399 			regs[BPF_REG_0].id = ++env->id_gen;
11400 	} else if (btf_type_is_void(t)) {
11401 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11402 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11403 				insn_aux->kptr_struct_meta =
11404 					btf_find_struct_meta(meta.arg_btf,
11405 							     meta.arg_btf_id);
11406 			}
11407 		}
11408 	}
11409 
11410 	nargs = btf_type_vlen(meta.func_proto);
11411 	args = (const struct btf_param *)(meta.func_proto + 1);
11412 	for (i = 0; i < nargs; i++) {
11413 		u32 regno = i + 1;
11414 
11415 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11416 		if (btf_type_is_ptr(t))
11417 			mark_btf_func_reg_size(env, regno, sizeof(void *));
11418 		else
11419 			/* scalar. ensured by btf_check_kfunc_arg_match() */
11420 			mark_btf_func_reg_size(env, regno, t->size);
11421 	}
11422 
11423 	if (is_iter_next_kfunc(&meta)) {
11424 		err = process_iter_next_call(env, insn_idx, &meta);
11425 		if (err)
11426 			return err;
11427 	}
11428 
11429 	return 0;
11430 }
11431 
11432 static bool signed_add_overflows(s64 a, s64 b)
11433 {
11434 	/* Do the add in u64, where overflow is well-defined */
11435 	s64 res = (s64)((u64)a + (u64)b);
11436 
11437 	if (b < 0)
11438 		return res > a;
11439 	return res < a;
11440 }
11441 
11442 static bool signed_add32_overflows(s32 a, s32 b)
11443 {
11444 	/* Do the add in u32, where overflow is well-defined */
11445 	s32 res = (s32)((u32)a + (u32)b);
11446 
11447 	if (b < 0)
11448 		return res > a;
11449 	return res < a;
11450 }
11451 
11452 static bool signed_sub_overflows(s64 a, s64 b)
11453 {
11454 	/* Do the sub in u64, where overflow is well-defined */
11455 	s64 res = (s64)((u64)a - (u64)b);
11456 
11457 	if (b < 0)
11458 		return res < a;
11459 	return res > a;
11460 }
11461 
11462 static bool signed_sub32_overflows(s32 a, s32 b)
11463 {
11464 	/* Do the sub in u32, where overflow is well-defined */
11465 	s32 res = (s32)((u32)a - (u32)b);
11466 
11467 	if (b < 0)
11468 		return res < a;
11469 	return res > a;
11470 }
11471 
11472 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11473 				  const struct bpf_reg_state *reg,
11474 				  enum bpf_reg_type type)
11475 {
11476 	bool known = tnum_is_const(reg->var_off);
11477 	s64 val = reg->var_off.value;
11478 	s64 smin = reg->smin_value;
11479 
11480 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11481 		verbose(env, "math between %s pointer and %lld is not allowed\n",
11482 			reg_type_str(env, type), val);
11483 		return false;
11484 	}
11485 
11486 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11487 		verbose(env, "%s pointer offset %d is not allowed\n",
11488 			reg_type_str(env, type), reg->off);
11489 		return false;
11490 	}
11491 
11492 	if (smin == S64_MIN) {
11493 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11494 			reg_type_str(env, type));
11495 		return false;
11496 	}
11497 
11498 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11499 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
11500 			smin, reg_type_str(env, type));
11501 		return false;
11502 	}
11503 
11504 	return true;
11505 }
11506 
11507 enum {
11508 	REASON_BOUNDS	= -1,
11509 	REASON_TYPE	= -2,
11510 	REASON_PATHS	= -3,
11511 	REASON_LIMIT	= -4,
11512 	REASON_STACK	= -5,
11513 };
11514 
11515 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11516 			      u32 *alu_limit, bool mask_to_left)
11517 {
11518 	u32 max = 0, ptr_limit = 0;
11519 
11520 	switch (ptr_reg->type) {
11521 	case PTR_TO_STACK:
11522 		/* Offset 0 is out-of-bounds, but acceptable start for the
11523 		 * left direction, see BPF_REG_FP. Also, unknown scalar
11524 		 * offset where we would need to deal with min/max bounds is
11525 		 * currently prohibited for unprivileged.
11526 		 */
11527 		max = MAX_BPF_STACK + mask_to_left;
11528 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11529 		break;
11530 	case PTR_TO_MAP_VALUE:
11531 		max = ptr_reg->map_ptr->value_size;
11532 		ptr_limit = (mask_to_left ?
11533 			     ptr_reg->smin_value :
11534 			     ptr_reg->umax_value) + ptr_reg->off;
11535 		break;
11536 	default:
11537 		return REASON_TYPE;
11538 	}
11539 
11540 	if (ptr_limit >= max)
11541 		return REASON_LIMIT;
11542 	*alu_limit = ptr_limit;
11543 	return 0;
11544 }
11545 
11546 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11547 				    const struct bpf_insn *insn)
11548 {
11549 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11550 }
11551 
11552 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11553 				       u32 alu_state, u32 alu_limit)
11554 {
11555 	/* If we arrived here from different branches with different
11556 	 * state or limits to sanitize, then this won't work.
11557 	 */
11558 	if (aux->alu_state &&
11559 	    (aux->alu_state != alu_state ||
11560 	     aux->alu_limit != alu_limit))
11561 		return REASON_PATHS;
11562 
11563 	/* Corresponding fixup done in do_misc_fixups(). */
11564 	aux->alu_state = alu_state;
11565 	aux->alu_limit = alu_limit;
11566 	return 0;
11567 }
11568 
11569 static int sanitize_val_alu(struct bpf_verifier_env *env,
11570 			    struct bpf_insn *insn)
11571 {
11572 	struct bpf_insn_aux_data *aux = cur_aux(env);
11573 
11574 	if (can_skip_alu_sanitation(env, insn))
11575 		return 0;
11576 
11577 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11578 }
11579 
11580 static bool sanitize_needed(u8 opcode)
11581 {
11582 	return opcode == BPF_ADD || opcode == BPF_SUB;
11583 }
11584 
11585 struct bpf_sanitize_info {
11586 	struct bpf_insn_aux_data aux;
11587 	bool mask_to_left;
11588 };
11589 
11590 static struct bpf_verifier_state *
11591 sanitize_speculative_path(struct bpf_verifier_env *env,
11592 			  const struct bpf_insn *insn,
11593 			  u32 next_idx, u32 curr_idx)
11594 {
11595 	struct bpf_verifier_state *branch;
11596 	struct bpf_reg_state *regs;
11597 
11598 	branch = push_stack(env, next_idx, curr_idx, true);
11599 	if (branch && insn) {
11600 		regs = branch->frame[branch->curframe]->regs;
11601 		if (BPF_SRC(insn->code) == BPF_K) {
11602 			mark_reg_unknown(env, regs, insn->dst_reg);
11603 		} else if (BPF_SRC(insn->code) == BPF_X) {
11604 			mark_reg_unknown(env, regs, insn->dst_reg);
11605 			mark_reg_unknown(env, regs, insn->src_reg);
11606 		}
11607 	}
11608 	return branch;
11609 }
11610 
11611 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11612 			    struct bpf_insn *insn,
11613 			    const struct bpf_reg_state *ptr_reg,
11614 			    const struct bpf_reg_state *off_reg,
11615 			    struct bpf_reg_state *dst_reg,
11616 			    struct bpf_sanitize_info *info,
11617 			    const bool commit_window)
11618 {
11619 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11620 	struct bpf_verifier_state *vstate = env->cur_state;
11621 	bool off_is_imm = tnum_is_const(off_reg->var_off);
11622 	bool off_is_neg = off_reg->smin_value < 0;
11623 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
11624 	u8 opcode = BPF_OP(insn->code);
11625 	u32 alu_state, alu_limit;
11626 	struct bpf_reg_state tmp;
11627 	bool ret;
11628 	int err;
11629 
11630 	if (can_skip_alu_sanitation(env, insn))
11631 		return 0;
11632 
11633 	/* We already marked aux for masking from non-speculative
11634 	 * paths, thus we got here in the first place. We only care
11635 	 * to explore bad access from here.
11636 	 */
11637 	if (vstate->speculative)
11638 		goto do_sim;
11639 
11640 	if (!commit_window) {
11641 		if (!tnum_is_const(off_reg->var_off) &&
11642 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11643 			return REASON_BOUNDS;
11644 
11645 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11646 				     (opcode == BPF_SUB && !off_is_neg);
11647 	}
11648 
11649 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11650 	if (err < 0)
11651 		return err;
11652 
11653 	if (commit_window) {
11654 		/* In commit phase we narrow the masking window based on
11655 		 * the observed pointer move after the simulated operation.
11656 		 */
11657 		alu_state = info->aux.alu_state;
11658 		alu_limit = abs(info->aux.alu_limit - alu_limit);
11659 	} else {
11660 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11661 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11662 		alu_state |= ptr_is_dst_reg ?
11663 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11664 
11665 		/* Limit pruning on unknown scalars to enable deep search for
11666 		 * potential masking differences from other program paths.
11667 		 */
11668 		if (!off_is_imm)
11669 			env->explore_alu_limits = true;
11670 	}
11671 
11672 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11673 	if (err < 0)
11674 		return err;
11675 do_sim:
11676 	/* If we're in commit phase, we're done here given we already
11677 	 * pushed the truncated dst_reg into the speculative verification
11678 	 * stack.
11679 	 *
11680 	 * Also, when register is a known constant, we rewrite register-based
11681 	 * operation to immediate-based, and thus do not need masking (and as
11682 	 * a consequence, do not need to simulate the zero-truncation either).
11683 	 */
11684 	if (commit_window || off_is_imm)
11685 		return 0;
11686 
11687 	/* Simulate and find potential out-of-bounds access under
11688 	 * speculative execution from truncation as a result of
11689 	 * masking when off was not within expected range. If off
11690 	 * sits in dst, then we temporarily need to move ptr there
11691 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11692 	 * for cases where we use K-based arithmetic in one direction
11693 	 * and truncated reg-based in the other in order to explore
11694 	 * bad access.
11695 	 */
11696 	if (!ptr_is_dst_reg) {
11697 		tmp = *dst_reg;
11698 		copy_register_state(dst_reg, ptr_reg);
11699 	}
11700 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11701 					env->insn_idx);
11702 	if (!ptr_is_dst_reg && ret)
11703 		*dst_reg = tmp;
11704 	return !ret ? REASON_STACK : 0;
11705 }
11706 
11707 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11708 {
11709 	struct bpf_verifier_state *vstate = env->cur_state;
11710 
11711 	/* If we simulate paths under speculation, we don't update the
11712 	 * insn as 'seen' such that when we verify unreachable paths in
11713 	 * the non-speculative domain, sanitize_dead_code() can still
11714 	 * rewrite/sanitize them.
11715 	 */
11716 	if (!vstate->speculative)
11717 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11718 }
11719 
11720 static int sanitize_err(struct bpf_verifier_env *env,
11721 			const struct bpf_insn *insn, int reason,
11722 			const struct bpf_reg_state *off_reg,
11723 			const struct bpf_reg_state *dst_reg)
11724 {
11725 	static const char *err = "pointer arithmetic with it prohibited for !root";
11726 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11727 	u32 dst = insn->dst_reg, src = insn->src_reg;
11728 
11729 	switch (reason) {
11730 	case REASON_BOUNDS:
11731 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11732 			off_reg == dst_reg ? dst : src, err);
11733 		break;
11734 	case REASON_TYPE:
11735 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11736 			off_reg == dst_reg ? src : dst, err);
11737 		break;
11738 	case REASON_PATHS:
11739 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11740 			dst, op, err);
11741 		break;
11742 	case REASON_LIMIT:
11743 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11744 			dst, op, err);
11745 		break;
11746 	case REASON_STACK:
11747 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11748 			dst, err);
11749 		break;
11750 	default:
11751 		verbose(env, "verifier internal error: unknown reason (%d)\n",
11752 			reason);
11753 		break;
11754 	}
11755 
11756 	return -EACCES;
11757 }
11758 
11759 /* check that stack access falls within stack limits and that 'reg' doesn't
11760  * have a variable offset.
11761  *
11762  * Variable offset is prohibited for unprivileged mode for simplicity since it
11763  * requires corresponding support in Spectre masking for stack ALU.  See also
11764  * retrieve_ptr_limit().
11765  *
11766  *
11767  * 'off' includes 'reg->off'.
11768  */
11769 static int check_stack_access_for_ptr_arithmetic(
11770 				struct bpf_verifier_env *env,
11771 				int regno,
11772 				const struct bpf_reg_state *reg,
11773 				int off)
11774 {
11775 	if (!tnum_is_const(reg->var_off)) {
11776 		char tn_buf[48];
11777 
11778 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11779 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11780 			regno, tn_buf, off);
11781 		return -EACCES;
11782 	}
11783 
11784 	if (off >= 0 || off < -MAX_BPF_STACK) {
11785 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
11786 			"prohibited for !root; off=%d\n", regno, off);
11787 		return -EACCES;
11788 	}
11789 
11790 	return 0;
11791 }
11792 
11793 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11794 				 const struct bpf_insn *insn,
11795 				 const struct bpf_reg_state *dst_reg)
11796 {
11797 	u32 dst = insn->dst_reg;
11798 
11799 	/* For unprivileged we require that resulting offset must be in bounds
11800 	 * in order to be able to sanitize access later on.
11801 	 */
11802 	if (env->bypass_spec_v1)
11803 		return 0;
11804 
11805 	switch (dst_reg->type) {
11806 	case PTR_TO_STACK:
11807 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11808 					dst_reg->off + dst_reg->var_off.value))
11809 			return -EACCES;
11810 		break;
11811 	case PTR_TO_MAP_VALUE:
11812 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11813 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11814 				"prohibited for !root\n", dst);
11815 			return -EACCES;
11816 		}
11817 		break;
11818 	default:
11819 		break;
11820 	}
11821 
11822 	return 0;
11823 }
11824 
11825 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11826  * Caller should also handle BPF_MOV case separately.
11827  * If we return -EACCES, caller may want to try again treating pointer as a
11828  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11829  */
11830 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11831 				   struct bpf_insn *insn,
11832 				   const struct bpf_reg_state *ptr_reg,
11833 				   const struct bpf_reg_state *off_reg)
11834 {
11835 	struct bpf_verifier_state *vstate = env->cur_state;
11836 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11837 	struct bpf_reg_state *regs = state->regs, *dst_reg;
11838 	bool known = tnum_is_const(off_reg->var_off);
11839 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11840 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11841 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11842 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11843 	struct bpf_sanitize_info info = {};
11844 	u8 opcode = BPF_OP(insn->code);
11845 	u32 dst = insn->dst_reg;
11846 	int ret;
11847 
11848 	dst_reg = &regs[dst];
11849 
11850 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11851 	    smin_val > smax_val || umin_val > umax_val) {
11852 		/* Taint dst register if offset had invalid bounds derived from
11853 		 * e.g. dead branches.
11854 		 */
11855 		__mark_reg_unknown(env, dst_reg);
11856 		return 0;
11857 	}
11858 
11859 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
11860 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
11861 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11862 			__mark_reg_unknown(env, dst_reg);
11863 			return 0;
11864 		}
11865 
11866 		verbose(env,
11867 			"R%d 32-bit pointer arithmetic prohibited\n",
11868 			dst);
11869 		return -EACCES;
11870 	}
11871 
11872 	if (ptr_reg->type & PTR_MAYBE_NULL) {
11873 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11874 			dst, reg_type_str(env, ptr_reg->type));
11875 		return -EACCES;
11876 	}
11877 
11878 	switch (base_type(ptr_reg->type)) {
11879 	case CONST_PTR_TO_MAP:
11880 		/* smin_val represents the known value */
11881 		if (known && smin_val == 0 && opcode == BPF_ADD)
11882 			break;
11883 		fallthrough;
11884 	case PTR_TO_PACKET_END:
11885 	case PTR_TO_SOCKET:
11886 	case PTR_TO_SOCK_COMMON:
11887 	case PTR_TO_TCP_SOCK:
11888 	case PTR_TO_XDP_SOCK:
11889 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11890 			dst, reg_type_str(env, ptr_reg->type));
11891 		return -EACCES;
11892 	default:
11893 		break;
11894 	}
11895 
11896 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11897 	 * The id may be overwritten later if we create a new variable offset.
11898 	 */
11899 	dst_reg->type = ptr_reg->type;
11900 	dst_reg->id = ptr_reg->id;
11901 
11902 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11903 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11904 		return -EINVAL;
11905 
11906 	/* pointer types do not carry 32-bit bounds at the moment. */
11907 	__mark_reg32_unbounded(dst_reg);
11908 
11909 	if (sanitize_needed(opcode)) {
11910 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11911 				       &info, false);
11912 		if (ret < 0)
11913 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11914 	}
11915 
11916 	switch (opcode) {
11917 	case BPF_ADD:
11918 		/* We can take a fixed offset as long as it doesn't overflow
11919 		 * the s32 'off' field
11920 		 */
11921 		if (known && (ptr_reg->off + smin_val ==
11922 			      (s64)(s32)(ptr_reg->off + smin_val))) {
11923 			/* pointer += K.  Accumulate it into fixed offset */
11924 			dst_reg->smin_value = smin_ptr;
11925 			dst_reg->smax_value = smax_ptr;
11926 			dst_reg->umin_value = umin_ptr;
11927 			dst_reg->umax_value = umax_ptr;
11928 			dst_reg->var_off = ptr_reg->var_off;
11929 			dst_reg->off = ptr_reg->off + smin_val;
11930 			dst_reg->raw = ptr_reg->raw;
11931 			break;
11932 		}
11933 		/* A new variable offset is created.  Note that off_reg->off
11934 		 * == 0, since it's a scalar.
11935 		 * dst_reg gets the pointer type and since some positive
11936 		 * integer value was added to the pointer, give it a new 'id'
11937 		 * if it's a PTR_TO_PACKET.
11938 		 * this creates a new 'base' pointer, off_reg (variable) gets
11939 		 * added into the variable offset, and we copy the fixed offset
11940 		 * from ptr_reg.
11941 		 */
11942 		if (signed_add_overflows(smin_ptr, smin_val) ||
11943 		    signed_add_overflows(smax_ptr, smax_val)) {
11944 			dst_reg->smin_value = S64_MIN;
11945 			dst_reg->smax_value = S64_MAX;
11946 		} else {
11947 			dst_reg->smin_value = smin_ptr + smin_val;
11948 			dst_reg->smax_value = smax_ptr + smax_val;
11949 		}
11950 		if (umin_ptr + umin_val < umin_ptr ||
11951 		    umax_ptr + umax_val < umax_ptr) {
11952 			dst_reg->umin_value = 0;
11953 			dst_reg->umax_value = U64_MAX;
11954 		} else {
11955 			dst_reg->umin_value = umin_ptr + umin_val;
11956 			dst_reg->umax_value = umax_ptr + umax_val;
11957 		}
11958 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11959 		dst_reg->off = ptr_reg->off;
11960 		dst_reg->raw = ptr_reg->raw;
11961 		if (reg_is_pkt_pointer(ptr_reg)) {
11962 			dst_reg->id = ++env->id_gen;
11963 			/* something was added to pkt_ptr, set range to zero */
11964 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11965 		}
11966 		break;
11967 	case BPF_SUB:
11968 		if (dst_reg == off_reg) {
11969 			/* scalar -= pointer.  Creates an unknown scalar */
11970 			verbose(env, "R%d tried to subtract pointer from scalar\n",
11971 				dst);
11972 			return -EACCES;
11973 		}
11974 		/* We don't allow subtraction from FP, because (according to
11975 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
11976 		 * be able to deal with it.
11977 		 */
11978 		if (ptr_reg->type == PTR_TO_STACK) {
11979 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
11980 				dst);
11981 			return -EACCES;
11982 		}
11983 		if (known && (ptr_reg->off - smin_val ==
11984 			      (s64)(s32)(ptr_reg->off - smin_val))) {
11985 			/* pointer -= K.  Subtract it from fixed offset */
11986 			dst_reg->smin_value = smin_ptr;
11987 			dst_reg->smax_value = smax_ptr;
11988 			dst_reg->umin_value = umin_ptr;
11989 			dst_reg->umax_value = umax_ptr;
11990 			dst_reg->var_off = ptr_reg->var_off;
11991 			dst_reg->id = ptr_reg->id;
11992 			dst_reg->off = ptr_reg->off - smin_val;
11993 			dst_reg->raw = ptr_reg->raw;
11994 			break;
11995 		}
11996 		/* A new variable offset is created.  If the subtrahend is known
11997 		 * nonnegative, then any reg->range we had before is still good.
11998 		 */
11999 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12000 		    signed_sub_overflows(smax_ptr, smin_val)) {
12001 			/* Overflow possible, we know nothing */
12002 			dst_reg->smin_value = S64_MIN;
12003 			dst_reg->smax_value = S64_MAX;
12004 		} else {
12005 			dst_reg->smin_value = smin_ptr - smax_val;
12006 			dst_reg->smax_value = smax_ptr - smin_val;
12007 		}
12008 		if (umin_ptr < umax_val) {
12009 			/* Overflow possible, we know nothing */
12010 			dst_reg->umin_value = 0;
12011 			dst_reg->umax_value = U64_MAX;
12012 		} else {
12013 			/* Cannot overflow (as long as bounds are consistent) */
12014 			dst_reg->umin_value = umin_ptr - umax_val;
12015 			dst_reg->umax_value = umax_ptr - umin_val;
12016 		}
12017 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12018 		dst_reg->off = ptr_reg->off;
12019 		dst_reg->raw = ptr_reg->raw;
12020 		if (reg_is_pkt_pointer(ptr_reg)) {
12021 			dst_reg->id = ++env->id_gen;
12022 			/* something was added to pkt_ptr, set range to zero */
12023 			if (smin_val < 0)
12024 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12025 		}
12026 		break;
12027 	case BPF_AND:
12028 	case BPF_OR:
12029 	case BPF_XOR:
12030 		/* bitwise ops on pointers are troublesome, prohibit. */
12031 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12032 			dst, bpf_alu_string[opcode >> 4]);
12033 		return -EACCES;
12034 	default:
12035 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12036 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12037 			dst, bpf_alu_string[opcode >> 4]);
12038 		return -EACCES;
12039 	}
12040 
12041 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12042 		return -EINVAL;
12043 	reg_bounds_sync(dst_reg);
12044 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12045 		return -EACCES;
12046 	if (sanitize_needed(opcode)) {
12047 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12048 				       &info, true);
12049 		if (ret < 0)
12050 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12051 	}
12052 
12053 	return 0;
12054 }
12055 
12056 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12057 				 struct bpf_reg_state *src_reg)
12058 {
12059 	s32 smin_val = src_reg->s32_min_value;
12060 	s32 smax_val = src_reg->s32_max_value;
12061 	u32 umin_val = src_reg->u32_min_value;
12062 	u32 umax_val = src_reg->u32_max_value;
12063 
12064 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12065 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12066 		dst_reg->s32_min_value = S32_MIN;
12067 		dst_reg->s32_max_value = S32_MAX;
12068 	} else {
12069 		dst_reg->s32_min_value += smin_val;
12070 		dst_reg->s32_max_value += smax_val;
12071 	}
12072 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12073 	    dst_reg->u32_max_value + umax_val < umax_val) {
12074 		dst_reg->u32_min_value = 0;
12075 		dst_reg->u32_max_value = U32_MAX;
12076 	} else {
12077 		dst_reg->u32_min_value += umin_val;
12078 		dst_reg->u32_max_value += umax_val;
12079 	}
12080 }
12081 
12082 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12083 			       struct bpf_reg_state *src_reg)
12084 {
12085 	s64 smin_val = src_reg->smin_value;
12086 	s64 smax_val = src_reg->smax_value;
12087 	u64 umin_val = src_reg->umin_value;
12088 	u64 umax_val = src_reg->umax_value;
12089 
12090 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12091 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12092 		dst_reg->smin_value = S64_MIN;
12093 		dst_reg->smax_value = S64_MAX;
12094 	} else {
12095 		dst_reg->smin_value += smin_val;
12096 		dst_reg->smax_value += smax_val;
12097 	}
12098 	if (dst_reg->umin_value + umin_val < umin_val ||
12099 	    dst_reg->umax_value + umax_val < umax_val) {
12100 		dst_reg->umin_value = 0;
12101 		dst_reg->umax_value = U64_MAX;
12102 	} else {
12103 		dst_reg->umin_value += umin_val;
12104 		dst_reg->umax_value += umax_val;
12105 	}
12106 }
12107 
12108 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12109 				 struct bpf_reg_state *src_reg)
12110 {
12111 	s32 smin_val = src_reg->s32_min_value;
12112 	s32 smax_val = src_reg->s32_max_value;
12113 	u32 umin_val = src_reg->u32_min_value;
12114 	u32 umax_val = src_reg->u32_max_value;
12115 
12116 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12117 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12118 		/* Overflow possible, we know nothing */
12119 		dst_reg->s32_min_value = S32_MIN;
12120 		dst_reg->s32_max_value = S32_MAX;
12121 	} else {
12122 		dst_reg->s32_min_value -= smax_val;
12123 		dst_reg->s32_max_value -= smin_val;
12124 	}
12125 	if (dst_reg->u32_min_value < umax_val) {
12126 		/* Overflow possible, we know nothing */
12127 		dst_reg->u32_min_value = 0;
12128 		dst_reg->u32_max_value = U32_MAX;
12129 	} else {
12130 		/* Cannot overflow (as long as bounds are consistent) */
12131 		dst_reg->u32_min_value -= umax_val;
12132 		dst_reg->u32_max_value -= umin_val;
12133 	}
12134 }
12135 
12136 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12137 			       struct bpf_reg_state *src_reg)
12138 {
12139 	s64 smin_val = src_reg->smin_value;
12140 	s64 smax_val = src_reg->smax_value;
12141 	u64 umin_val = src_reg->umin_value;
12142 	u64 umax_val = src_reg->umax_value;
12143 
12144 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12145 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12146 		/* Overflow possible, we know nothing */
12147 		dst_reg->smin_value = S64_MIN;
12148 		dst_reg->smax_value = S64_MAX;
12149 	} else {
12150 		dst_reg->smin_value -= smax_val;
12151 		dst_reg->smax_value -= smin_val;
12152 	}
12153 	if (dst_reg->umin_value < umax_val) {
12154 		/* Overflow possible, we know nothing */
12155 		dst_reg->umin_value = 0;
12156 		dst_reg->umax_value = U64_MAX;
12157 	} else {
12158 		/* Cannot overflow (as long as bounds are consistent) */
12159 		dst_reg->umin_value -= umax_val;
12160 		dst_reg->umax_value -= umin_val;
12161 	}
12162 }
12163 
12164 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12165 				 struct bpf_reg_state *src_reg)
12166 {
12167 	s32 smin_val = src_reg->s32_min_value;
12168 	u32 umin_val = src_reg->u32_min_value;
12169 	u32 umax_val = src_reg->u32_max_value;
12170 
12171 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12172 		/* Ain't nobody got time to multiply that sign */
12173 		__mark_reg32_unbounded(dst_reg);
12174 		return;
12175 	}
12176 	/* Both values are positive, so we can work with unsigned and
12177 	 * copy the result to signed (unless it exceeds S32_MAX).
12178 	 */
12179 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12180 		/* Potential overflow, we know nothing */
12181 		__mark_reg32_unbounded(dst_reg);
12182 		return;
12183 	}
12184 	dst_reg->u32_min_value *= umin_val;
12185 	dst_reg->u32_max_value *= umax_val;
12186 	if (dst_reg->u32_max_value > S32_MAX) {
12187 		/* Overflow possible, we know nothing */
12188 		dst_reg->s32_min_value = S32_MIN;
12189 		dst_reg->s32_max_value = S32_MAX;
12190 	} else {
12191 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12192 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12193 	}
12194 }
12195 
12196 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12197 			       struct bpf_reg_state *src_reg)
12198 {
12199 	s64 smin_val = src_reg->smin_value;
12200 	u64 umin_val = src_reg->umin_value;
12201 	u64 umax_val = src_reg->umax_value;
12202 
12203 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12204 		/* Ain't nobody got time to multiply that sign */
12205 		__mark_reg64_unbounded(dst_reg);
12206 		return;
12207 	}
12208 	/* Both values are positive, so we can work with unsigned and
12209 	 * copy the result to signed (unless it exceeds S64_MAX).
12210 	 */
12211 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12212 		/* Potential overflow, we know nothing */
12213 		__mark_reg64_unbounded(dst_reg);
12214 		return;
12215 	}
12216 	dst_reg->umin_value *= umin_val;
12217 	dst_reg->umax_value *= umax_val;
12218 	if (dst_reg->umax_value > S64_MAX) {
12219 		/* Overflow possible, we know nothing */
12220 		dst_reg->smin_value = S64_MIN;
12221 		dst_reg->smax_value = S64_MAX;
12222 	} else {
12223 		dst_reg->smin_value = dst_reg->umin_value;
12224 		dst_reg->smax_value = dst_reg->umax_value;
12225 	}
12226 }
12227 
12228 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12229 				 struct bpf_reg_state *src_reg)
12230 {
12231 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12232 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12233 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12234 	s32 smin_val = src_reg->s32_min_value;
12235 	u32 umax_val = src_reg->u32_max_value;
12236 
12237 	if (src_known && dst_known) {
12238 		__mark_reg32_known(dst_reg, var32_off.value);
12239 		return;
12240 	}
12241 
12242 	/* We get our minimum from the var_off, since that's inherently
12243 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12244 	 */
12245 	dst_reg->u32_min_value = var32_off.value;
12246 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12247 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12248 		/* Lose signed bounds when ANDing negative numbers,
12249 		 * ain't nobody got time for that.
12250 		 */
12251 		dst_reg->s32_min_value = S32_MIN;
12252 		dst_reg->s32_max_value = S32_MAX;
12253 	} else {
12254 		/* ANDing two positives gives a positive, so safe to
12255 		 * cast result into s64.
12256 		 */
12257 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12258 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12259 	}
12260 }
12261 
12262 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12263 			       struct bpf_reg_state *src_reg)
12264 {
12265 	bool src_known = tnum_is_const(src_reg->var_off);
12266 	bool dst_known = tnum_is_const(dst_reg->var_off);
12267 	s64 smin_val = src_reg->smin_value;
12268 	u64 umax_val = src_reg->umax_value;
12269 
12270 	if (src_known && dst_known) {
12271 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12272 		return;
12273 	}
12274 
12275 	/* We get our minimum from the var_off, since that's inherently
12276 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12277 	 */
12278 	dst_reg->umin_value = dst_reg->var_off.value;
12279 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12280 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12281 		/* Lose signed bounds when ANDing negative numbers,
12282 		 * ain't nobody got time for that.
12283 		 */
12284 		dst_reg->smin_value = S64_MIN;
12285 		dst_reg->smax_value = S64_MAX;
12286 	} else {
12287 		/* ANDing two positives gives a positive, so safe to
12288 		 * cast result into s64.
12289 		 */
12290 		dst_reg->smin_value = dst_reg->umin_value;
12291 		dst_reg->smax_value = dst_reg->umax_value;
12292 	}
12293 	/* We may learn something more from the var_off */
12294 	__update_reg_bounds(dst_reg);
12295 }
12296 
12297 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12298 				struct bpf_reg_state *src_reg)
12299 {
12300 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12301 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12302 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12303 	s32 smin_val = src_reg->s32_min_value;
12304 	u32 umin_val = src_reg->u32_min_value;
12305 
12306 	if (src_known && dst_known) {
12307 		__mark_reg32_known(dst_reg, var32_off.value);
12308 		return;
12309 	}
12310 
12311 	/* We get our maximum from the var_off, and our minimum is the
12312 	 * maximum of the operands' minima
12313 	 */
12314 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12315 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12316 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12317 		/* Lose signed bounds when ORing negative numbers,
12318 		 * ain't nobody got time for that.
12319 		 */
12320 		dst_reg->s32_min_value = S32_MIN;
12321 		dst_reg->s32_max_value = S32_MAX;
12322 	} else {
12323 		/* ORing two positives gives a positive, so safe to
12324 		 * cast result into s64.
12325 		 */
12326 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12327 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12328 	}
12329 }
12330 
12331 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12332 			      struct bpf_reg_state *src_reg)
12333 {
12334 	bool src_known = tnum_is_const(src_reg->var_off);
12335 	bool dst_known = tnum_is_const(dst_reg->var_off);
12336 	s64 smin_val = src_reg->smin_value;
12337 	u64 umin_val = src_reg->umin_value;
12338 
12339 	if (src_known && dst_known) {
12340 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12341 		return;
12342 	}
12343 
12344 	/* We get our maximum from the var_off, and our minimum is the
12345 	 * maximum of the operands' minima
12346 	 */
12347 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12348 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12349 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12350 		/* Lose signed bounds when ORing negative numbers,
12351 		 * ain't nobody got time for that.
12352 		 */
12353 		dst_reg->smin_value = S64_MIN;
12354 		dst_reg->smax_value = S64_MAX;
12355 	} else {
12356 		/* ORing two positives gives a positive, so safe to
12357 		 * cast result into s64.
12358 		 */
12359 		dst_reg->smin_value = dst_reg->umin_value;
12360 		dst_reg->smax_value = dst_reg->umax_value;
12361 	}
12362 	/* We may learn something more from the var_off */
12363 	__update_reg_bounds(dst_reg);
12364 }
12365 
12366 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12367 				 struct bpf_reg_state *src_reg)
12368 {
12369 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12370 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12371 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12372 	s32 smin_val = src_reg->s32_min_value;
12373 
12374 	if (src_known && dst_known) {
12375 		__mark_reg32_known(dst_reg, var32_off.value);
12376 		return;
12377 	}
12378 
12379 	/* We get both minimum and maximum from the var32_off. */
12380 	dst_reg->u32_min_value = var32_off.value;
12381 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12382 
12383 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12384 		/* XORing two positive sign numbers gives a positive,
12385 		 * so safe to cast u32 result into s32.
12386 		 */
12387 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12388 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12389 	} else {
12390 		dst_reg->s32_min_value = S32_MIN;
12391 		dst_reg->s32_max_value = S32_MAX;
12392 	}
12393 }
12394 
12395 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12396 			       struct bpf_reg_state *src_reg)
12397 {
12398 	bool src_known = tnum_is_const(src_reg->var_off);
12399 	bool dst_known = tnum_is_const(dst_reg->var_off);
12400 	s64 smin_val = src_reg->smin_value;
12401 
12402 	if (src_known && dst_known) {
12403 		/* dst_reg->var_off.value has been updated earlier */
12404 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12405 		return;
12406 	}
12407 
12408 	/* We get both minimum and maximum from the var_off. */
12409 	dst_reg->umin_value = dst_reg->var_off.value;
12410 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12411 
12412 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12413 		/* XORing two positive sign numbers gives a positive,
12414 		 * so safe to cast u64 result into s64.
12415 		 */
12416 		dst_reg->smin_value = dst_reg->umin_value;
12417 		dst_reg->smax_value = dst_reg->umax_value;
12418 	} else {
12419 		dst_reg->smin_value = S64_MIN;
12420 		dst_reg->smax_value = S64_MAX;
12421 	}
12422 
12423 	__update_reg_bounds(dst_reg);
12424 }
12425 
12426 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12427 				   u64 umin_val, u64 umax_val)
12428 {
12429 	/* We lose all sign bit information (except what we can pick
12430 	 * up from var_off)
12431 	 */
12432 	dst_reg->s32_min_value = S32_MIN;
12433 	dst_reg->s32_max_value = S32_MAX;
12434 	/* If we might shift our top bit out, then we know nothing */
12435 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12436 		dst_reg->u32_min_value = 0;
12437 		dst_reg->u32_max_value = U32_MAX;
12438 	} else {
12439 		dst_reg->u32_min_value <<= umin_val;
12440 		dst_reg->u32_max_value <<= umax_val;
12441 	}
12442 }
12443 
12444 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12445 				 struct bpf_reg_state *src_reg)
12446 {
12447 	u32 umax_val = src_reg->u32_max_value;
12448 	u32 umin_val = src_reg->u32_min_value;
12449 	/* u32 alu operation will zext upper bits */
12450 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12451 
12452 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12453 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12454 	/* Not required but being careful mark reg64 bounds as unknown so
12455 	 * that we are forced to pick them up from tnum and zext later and
12456 	 * if some path skips this step we are still safe.
12457 	 */
12458 	__mark_reg64_unbounded(dst_reg);
12459 	__update_reg32_bounds(dst_reg);
12460 }
12461 
12462 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12463 				   u64 umin_val, u64 umax_val)
12464 {
12465 	/* Special case <<32 because it is a common compiler pattern to sign
12466 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12467 	 * positive we know this shift will also be positive so we can track
12468 	 * bounds correctly. Otherwise we lose all sign bit information except
12469 	 * what we can pick up from var_off. Perhaps we can generalize this
12470 	 * later to shifts of any length.
12471 	 */
12472 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12473 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12474 	else
12475 		dst_reg->smax_value = S64_MAX;
12476 
12477 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12478 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12479 	else
12480 		dst_reg->smin_value = S64_MIN;
12481 
12482 	/* If we might shift our top bit out, then we know nothing */
12483 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12484 		dst_reg->umin_value = 0;
12485 		dst_reg->umax_value = U64_MAX;
12486 	} else {
12487 		dst_reg->umin_value <<= umin_val;
12488 		dst_reg->umax_value <<= umax_val;
12489 	}
12490 }
12491 
12492 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12493 			       struct bpf_reg_state *src_reg)
12494 {
12495 	u64 umax_val = src_reg->umax_value;
12496 	u64 umin_val = src_reg->umin_value;
12497 
12498 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
12499 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12500 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12501 
12502 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12503 	/* We may learn something more from the var_off */
12504 	__update_reg_bounds(dst_reg);
12505 }
12506 
12507 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12508 				 struct bpf_reg_state *src_reg)
12509 {
12510 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
12511 	u32 umax_val = src_reg->u32_max_value;
12512 	u32 umin_val = src_reg->u32_min_value;
12513 
12514 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12515 	 * be negative, then either:
12516 	 * 1) src_reg might be zero, so the sign bit of the result is
12517 	 *    unknown, so we lose our signed bounds
12518 	 * 2) it's known negative, thus the unsigned bounds capture the
12519 	 *    signed bounds
12520 	 * 3) the signed bounds cross zero, so they tell us nothing
12521 	 *    about the result
12522 	 * If the value in dst_reg is known nonnegative, then again the
12523 	 * unsigned bounds capture the signed bounds.
12524 	 * Thus, in all cases it suffices to blow away our signed bounds
12525 	 * and rely on inferring new ones from the unsigned bounds and
12526 	 * var_off of the result.
12527 	 */
12528 	dst_reg->s32_min_value = S32_MIN;
12529 	dst_reg->s32_max_value = S32_MAX;
12530 
12531 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
12532 	dst_reg->u32_min_value >>= umax_val;
12533 	dst_reg->u32_max_value >>= umin_val;
12534 
12535 	__mark_reg64_unbounded(dst_reg);
12536 	__update_reg32_bounds(dst_reg);
12537 }
12538 
12539 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12540 			       struct bpf_reg_state *src_reg)
12541 {
12542 	u64 umax_val = src_reg->umax_value;
12543 	u64 umin_val = src_reg->umin_value;
12544 
12545 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12546 	 * be negative, then either:
12547 	 * 1) src_reg might be zero, so the sign bit of the result is
12548 	 *    unknown, so we lose our signed bounds
12549 	 * 2) it's known negative, thus the unsigned bounds capture the
12550 	 *    signed bounds
12551 	 * 3) the signed bounds cross zero, so they tell us nothing
12552 	 *    about the result
12553 	 * If the value in dst_reg is known nonnegative, then again the
12554 	 * unsigned bounds capture the signed bounds.
12555 	 * Thus, in all cases it suffices to blow away our signed bounds
12556 	 * and rely on inferring new ones from the unsigned bounds and
12557 	 * var_off of the result.
12558 	 */
12559 	dst_reg->smin_value = S64_MIN;
12560 	dst_reg->smax_value = S64_MAX;
12561 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12562 	dst_reg->umin_value >>= umax_val;
12563 	dst_reg->umax_value >>= umin_val;
12564 
12565 	/* Its not easy to operate on alu32 bounds here because it depends
12566 	 * on bits being shifted in. Take easy way out and mark unbounded
12567 	 * so we can recalculate later from tnum.
12568 	 */
12569 	__mark_reg32_unbounded(dst_reg);
12570 	__update_reg_bounds(dst_reg);
12571 }
12572 
12573 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12574 				  struct bpf_reg_state *src_reg)
12575 {
12576 	u64 umin_val = src_reg->u32_min_value;
12577 
12578 	/* Upon reaching here, src_known is true and
12579 	 * umax_val is equal to umin_val.
12580 	 */
12581 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12582 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12583 
12584 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12585 
12586 	/* blow away the dst_reg umin_value/umax_value and rely on
12587 	 * dst_reg var_off to refine the result.
12588 	 */
12589 	dst_reg->u32_min_value = 0;
12590 	dst_reg->u32_max_value = U32_MAX;
12591 
12592 	__mark_reg64_unbounded(dst_reg);
12593 	__update_reg32_bounds(dst_reg);
12594 }
12595 
12596 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12597 				struct bpf_reg_state *src_reg)
12598 {
12599 	u64 umin_val = src_reg->umin_value;
12600 
12601 	/* Upon reaching here, src_known is true and umax_val is equal
12602 	 * to umin_val.
12603 	 */
12604 	dst_reg->smin_value >>= umin_val;
12605 	dst_reg->smax_value >>= umin_val;
12606 
12607 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12608 
12609 	/* blow away the dst_reg umin_value/umax_value and rely on
12610 	 * dst_reg var_off to refine the result.
12611 	 */
12612 	dst_reg->umin_value = 0;
12613 	dst_reg->umax_value = U64_MAX;
12614 
12615 	/* Its not easy to operate on alu32 bounds here because it depends
12616 	 * on bits being shifted in from upper 32-bits. Take easy way out
12617 	 * and mark unbounded so we can recalculate later from tnum.
12618 	 */
12619 	__mark_reg32_unbounded(dst_reg);
12620 	__update_reg_bounds(dst_reg);
12621 }
12622 
12623 /* WARNING: This function does calculations on 64-bit values, but the actual
12624  * execution may occur on 32-bit values. Therefore, things like bitshifts
12625  * need extra checks in the 32-bit case.
12626  */
12627 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12628 				      struct bpf_insn *insn,
12629 				      struct bpf_reg_state *dst_reg,
12630 				      struct bpf_reg_state src_reg)
12631 {
12632 	struct bpf_reg_state *regs = cur_regs(env);
12633 	u8 opcode = BPF_OP(insn->code);
12634 	bool src_known;
12635 	s64 smin_val, smax_val;
12636 	u64 umin_val, umax_val;
12637 	s32 s32_min_val, s32_max_val;
12638 	u32 u32_min_val, u32_max_val;
12639 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12640 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12641 	int ret;
12642 
12643 	smin_val = src_reg.smin_value;
12644 	smax_val = src_reg.smax_value;
12645 	umin_val = src_reg.umin_value;
12646 	umax_val = src_reg.umax_value;
12647 
12648 	s32_min_val = src_reg.s32_min_value;
12649 	s32_max_val = src_reg.s32_max_value;
12650 	u32_min_val = src_reg.u32_min_value;
12651 	u32_max_val = src_reg.u32_max_value;
12652 
12653 	if (alu32) {
12654 		src_known = tnum_subreg_is_const(src_reg.var_off);
12655 		if ((src_known &&
12656 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12657 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12658 			/* Taint dst register if offset had invalid bounds
12659 			 * derived from e.g. dead branches.
12660 			 */
12661 			__mark_reg_unknown(env, dst_reg);
12662 			return 0;
12663 		}
12664 	} else {
12665 		src_known = tnum_is_const(src_reg.var_off);
12666 		if ((src_known &&
12667 		     (smin_val != smax_val || umin_val != umax_val)) ||
12668 		    smin_val > smax_val || umin_val > umax_val) {
12669 			/* Taint dst register if offset had invalid bounds
12670 			 * derived from e.g. dead branches.
12671 			 */
12672 			__mark_reg_unknown(env, dst_reg);
12673 			return 0;
12674 		}
12675 	}
12676 
12677 	if (!src_known &&
12678 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12679 		__mark_reg_unknown(env, dst_reg);
12680 		return 0;
12681 	}
12682 
12683 	if (sanitize_needed(opcode)) {
12684 		ret = sanitize_val_alu(env, insn);
12685 		if (ret < 0)
12686 			return sanitize_err(env, insn, ret, NULL, NULL);
12687 	}
12688 
12689 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12690 	 * There are two classes of instructions: The first class we track both
12691 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
12692 	 * greatest amount of precision when alu operations are mixed with jmp32
12693 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12694 	 * and BPF_OR. This is possible because these ops have fairly easy to
12695 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12696 	 * See alu32 verifier tests for examples. The second class of
12697 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12698 	 * with regards to tracking sign/unsigned bounds because the bits may
12699 	 * cross subreg boundaries in the alu64 case. When this happens we mark
12700 	 * the reg unbounded in the subreg bound space and use the resulting
12701 	 * tnum to calculate an approximation of the sign/unsigned bounds.
12702 	 */
12703 	switch (opcode) {
12704 	case BPF_ADD:
12705 		scalar32_min_max_add(dst_reg, &src_reg);
12706 		scalar_min_max_add(dst_reg, &src_reg);
12707 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12708 		break;
12709 	case BPF_SUB:
12710 		scalar32_min_max_sub(dst_reg, &src_reg);
12711 		scalar_min_max_sub(dst_reg, &src_reg);
12712 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12713 		break;
12714 	case BPF_MUL:
12715 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12716 		scalar32_min_max_mul(dst_reg, &src_reg);
12717 		scalar_min_max_mul(dst_reg, &src_reg);
12718 		break;
12719 	case BPF_AND:
12720 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12721 		scalar32_min_max_and(dst_reg, &src_reg);
12722 		scalar_min_max_and(dst_reg, &src_reg);
12723 		break;
12724 	case BPF_OR:
12725 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12726 		scalar32_min_max_or(dst_reg, &src_reg);
12727 		scalar_min_max_or(dst_reg, &src_reg);
12728 		break;
12729 	case BPF_XOR:
12730 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12731 		scalar32_min_max_xor(dst_reg, &src_reg);
12732 		scalar_min_max_xor(dst_reg, &src_reg);
12733 		break;
12734 	case BPF_LSH:
12735 		if (umax_val >= insn_bitness) {
12736 			/* Shifts greater than 31 or 63 are undefined.
12737 			 * This includes shifts by a negative number.
12738 			 */
12739 			mark_reg_unknown(env, regs, insn->dst_reg);
12740 			break;
12741 		}
12742 		if (alu32)
12743 			scalar32_min_max_lsh(dst_reg, &src_reg);
12744 		else
12745 			scalar_min_max_lsh(dst_reg, &src_reg);
12746 		break;
12747 	case BPF_RSH:
12748 		if (umax_val >= insn_bitness) {
12749 			/* Shifts greater than 31 or 63 are undefined.
12750 			 * This includes shifts by a negative number.
12751 			 */
12752 			mark_reg_unknown(env, regs, insn->dst_reg);
12753 			break;
12754 		}
12755 		if (alu32)
12756 			scalar32_min_max_rsh(dst_reg, &src_reg);
12757 		else
12758 			scalar_min_max_rsh(dst_reg, &src_reg);
12759 		break;
12760 	case BPF_ARSH:
12761 		if (umax_val >= insn_bitness) {
12762 			/* Shifts greater than 31 or 63 are undefined.
12763 			 * This includes shifts by a negative number.
12764 			 */
12765 			mark_reg_unknown(env, regs, insn->dst_reg);
12766 			break;
12767 		}
12768 		if (alu32)
12769 			scalar32_min_max_arsh(dst_reg, &src_reg);
12770 		else
12771 			scalar_min_max_arsh(dst_reg, &src_reg);
12772 		break;
12773 	default:
12774 		mark_reg_unknown(env, regs, insn->dst_reg);
12775 		break;
12776 	}
12777 
12778 	/* ALU32 ops are zero extended into 64bit register */
12779 	if (alu32)
12780 		zext_32_to_64(dst_reg);
12781 	reg_bounds_sync(dst_reg);
12782 	return 0;
12783 }
12784 
12785 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12786  * and var_off.
12787  */
12788 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12789 				   struct bpf_insn *insn)
12790 {
12791 	struct bpf_verifier_state *vstate = env->cur_state;
12792 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12793 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12794 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12795 	u8 opcode = BPF_OP(insn->code);
12796 	int err;
12797 
12798 	dst_reg = &regs[insn->dst_reg];
12799 	src_reg = NULL;
12800 	if (dst_reg->type != SCALAR_VALUE)
12801 		ptr_reg = dst_reg;
12802 	else
12803 		/* Make sure ID is cleared otherwise dst_reg min/max could be
12804 		 * incorrectly propagated into other registers by find_equal_scalars()
12805 		 */
12806 		dst_reg->id = 0;
12807 	if (BPF_SRC(insn->code) == BPF_X) {
12808 		src_reg = &regs[insn->src_reg];
12809 		if (src_reg->type != SCALAR_VALUE) {
12810 			if (dst_reg->type != SCALAR_VALUE) {
12811 				/* Combining two pointers by any ALU op yields
12812 				 * an arbitrary scalar. Disallow all math except
12813 				 * pointer subtraction
12814 				 */
12815 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12816 					mark_reg_unknown(env, regs, insn->dst_reg);
12817 					return 0;
12818 				}
12819 				verbose(env, "R%d pointer %s pointer prohibited\n",
12820 					insn->dst_reg,
12821 					bpf_alu_string[opcode >> 4]);
12822 				return -EACCES;
12823 			} else {
12824 				/* scalar += pointer
12825 				 * This is legal, but we have to reverse our
12826 				 * src/dest handling in computing the range
12827 				 */
12828 				err = mark_chain_precision(env, insn->dst_reg);
12829 				if (err)
12830 					return err;
12831 				return adjust_ptr_min_max_vals(env, insn,
12832 							       src_reg, dst_reg);
12833 			}
12834 		} else if (ptr_reg) {
12835 			/* pointer += scalar */
12836 			err = mark_chain_precision(env, insn->src_reg);
12837 			if (err)
12838 				return err;
12839 			return adjust_ptr_min_max_vals(env, insn,
12840 						       dst_reg, src_reg);
12841 		} else if (dst_reg->precise) {
12842 			/* if dst_reg is precise, src_reg should be precise as well */
12843 			err = mark_chain_precision(env, insn->src_reg);
12844 			if (err)
12845 				return err;
12846 		}
12847 	} else {
12848 		/* Pretend the src is a reg with a known value, since we only
12849 		 * need to be able to read from this state.
12850 		 */
12851 		off_reg.type = SCALAR_VALUE;
12852 		__mark_reg_known(&off_reg, insn->imm);
12853 		src_reg = &off_reg;
12854 		if (ptr_reg) /* pointer += K */
12855 			return adjust_ptr_min_max_vals(env, insn,
12856 						       ptr_reg, src_reg);
12857 	}
12858 
12859 	/* Got here implies adding two SCALAR_VALUEs */
12860 	if (WARN_ON_ONCE(ptr_reg)) {
12861 		print_verifier_state(env, state, true);
12862 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
12863 		return -EINVAL;
12864 	}
12865 	if (WARN_ON(!src_reg)) {
12866 		print_verifier_state(env, state, true);
12867 		verbose(env, "verifier internal error: no src_reg\n");
12868 		return -EINVAL;
12869 	}
12870 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12871 }
12872 
12873 /* check validity of 32-bit and 64-bit arithmetic operations */
12874 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12875 {
12876 	struct bpf_reg_state *regs = cur_regs(env);
12877 	u8 opcode = BPF_OP(insn->code);
12878 	int err;
12879 
12880 	if (opcode == BPF_END || opcode == BPF_NEG) {
12881 		if (opcode == BPF_NEG) {
12882 			if (BPF_SRC(insn->code) != BPF_K ||
12883 			    insn->src_reg != BPF_REG_0 ||
12884 			    insn->off != 0 || insn->imm != 0) {
12885 				verbose(env, "BPF_NEG uses reserved fields\n");
12886 				return -EINVAL;
12887 			}
12888 		} else {
12889 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12890 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12891 			    BPF_CLASS(insn->code) == BPF_ALU64) {
12892 				verbose(env, "BPF_END uses reserved fields\n");
12893 				return -EINVAL;
12894 			}
12895 		}
12896 
12897 		/* check src operand */
12898 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12899 		if (err)
12900 			return err;
12901 
12902 		if (is_pointer_value(env, insn->dst_reg)) {
12903 			verbose(env, "R%d pointer arithmetic prohibited\n",
12904 				insn->dst_reg);
12905 			return -EACCES;
12906 		}
12907 
12908 		/* check dest operand */
12909 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
12910 		if (err)
12911 			return err;
12912 
12913 	} else if (opcode == BPF_MOV) {
12914 
12915 		if (BPF_SRC(insn->code) == BPF_X) {
12916 			if (insn->imm != 0 || insn->off != 0) {
12917 				verbose(env, "BPF_MOV uses reserved fields\n");
12918 				return -EINVAL;
12919 			}
12920 
12921 			/* check src operand */
12922 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12923 			if (err)
12924 				return err;
12925 		} else {
12926 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12927 				verbose(env, "BPF_MOV uses reserved fields\n");
12928 				return -EINVAL;
12929 			}
12930 		}
12931 
12932 		/* check dest operand, mark as required later */
12933 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12934 		if (err)
12935 			return err;
12936 
12937 		if (BPF_SRC(insn->code) == BPF_X) {
12938 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
12939 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12940 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
12941 				       !tnum_is_const(src_reg->var_off);
12942 
12943 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12944 				/* case: R1 = R2
12945 				 * copy register state to dest reg
12946 				 */
12947 				if (need_id)
12948 					/* Assign src and dst registers the same ID
12949 					 * that will be used by find_equal_scalars()
12950 					 * to propagate min/max range.
12951 					 */
12952 					src_reg->id = ++env->id_gen;
12953 				copy_register_state(dst_reg, src_reg);
12954 				dst_reg->live |= REG_LIVE_WRITTEN;
12955 				dst_reg->subreg_def = DEF_NOT_SUBREG;
12956 			} else {
12957 				/* R1 = (u32) R2 */
12958 				if (is_pointer_value(env, insn->src_reg)) {
12959 					verbose(env,
12960 						"R%d partial copy of pointer\n",
12961 						insn->src_reg);
12962 					return -EACCES;
12963 				} else if (src_reg->type == SCALAR_VALUE) {
12964 					bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12965 
12966 					if (is_src_reg_u32 && need_id)
12967 						src_reg->id = ++env->id_gen;
12968 					copy_register_state(dst_reg, src_reg);
12969 					/* Make sure ID is cleared if src_reg is not in u32 range otherwise
12970 					 * dst_reg min/max could be incorrectly
12971 					 * propagated into src_reg by find_equal_scalars()
12972 					 */
12973 					if (!is_src_reg_u32)
12974 						dst_reg->id = 0;
12975 					dst_reg->live |= REG_LIVE_WRITTEN;
12976 					dst_reg->subreg_def = env->insn_idx + 1;
12977 				} else {
12978 					mark_reg_unknown(env, regs,
12979 							 insn->dst_reg);
12980 				}
12981 				zext_32_to_64(dst_reg);
12982 				reg_bounds_sync(dst_reg);
12983 			}
12984 		} else {
12985 			/* case: R = imm
12986 			 * remember the value we stored into this reg
12987 			 */
12988 			/* clear any state __mark_reg_known doesn't set */
12989 			mark_reg_unknown(env, regs, insn->dst_reg);
12990 			regs[insn->dst_reg].type = SCALAR_VALUE;
12991 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
12992 				__mark_reg_known(regs + insn->dst_reg,
12993 						 insn->imm);
12994 			} else {
12995 				__mark_reg_known(regs + insn->dst_reg,
12996 						 (u32)insn->imm);
12997 			}
12998 		}
12999 
13000 	} else if (opcode > BPF_END) {
13001 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13002 		return -EINVAL;
13003 
13004 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13005 
13006 		if (BPF_SRC(insn->code) == BPF_X) {
13007 			if (insn->imm != 0 || insn->off != 0) {
13008 				verbose(env, "BPF_ALU uses reserved fields\n");
13009 				return -EINVAL;
13010 			}
13011 			/* check src1 operand */
13012 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13013 			if (err)
13014 				return err;
13015 		} else {
13016 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13017 				verbose(env, "BPF_ALU uses reserved fields\n");
13018 				return -EINVAL;
13019 			}
13020 		}
13021 
13022 		/* check src2 operand */
13023 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13024 		if (err)
13025 			return err;
13026 
13027 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13028 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13029 			verbose(env, "div by zero\n");
13030 			return -EINVAL;
13031 		}
13032 
13033 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13034 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13035 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13036 
13037 			if (insn->imm < 0 || insn->imm >= size) {
13038 				verbose(env, "invalid shift %d\n", insn->imm);
13039 				return -EINVAL;
13040 			}
13041 		}
13042 
13043 		/* check dest operand */
13044 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13045 		if (err)
13046 			return err;
13047 
13048 		return adjust_reg_min_max_vals(env, insn);
13049 	}
13050 
13051 	return 0;
13052 }
13053 
13054 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13055 				   struct bpf_reg_state *dst_reg,
13056 				   enum bpf_reg_type type,
13057 				   bool range_right_open)
13058 {
13059 	struct bpf_func_state *state;
13060 	struct bpf_reg_state *reg;
13061 	int new_range;
13062 
13063 	if (dst_reg->off < 0 ||
13064 	    (dst_reg->off == 0 && range_right_open))
13065 		/* This doesn't give us any range */
13066 		return;
13067 
13068 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13069 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13070 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13071 		 * than pkt_end, but that's because it's also less than pkt.
13072 		 */
13073 		return;
13074 
13075 	new_range = dst_reg->off;
13076 	if (range_right_open)
13077 		new_range++;
13078 
13079 	/* Examples for register markings:
13080 	 *
13081 	 * pkt_data in dst register:
13082 	 *
13083 	 *   r2 = r3;
13084 	 *   r2 += 8;
13085 	 *   if (r2 > pkt_end) goto <handle exception>
13086 	 *   <access okay>
13087 	 *
13088 	 *   r2 = r3;
13089 	 *   r2 += 8;
13090 	 *   if (r2 < pkt_end) goto <access okay>
13091 	 *   <handle exception>
13092 	 *
13093 	 *   Where:
13094 	 *     r2 == dst_reg, pkt_end == src_reg
13095 	 *     r2=pkt(id=n,off=8,r=0)
13096 	 *     r3=pkt(id=n,off=0,r=0)
13097 	 *
13098 	 * pkt_data in src register:
13099 	 *
13100 	 *   r2 = r3;
13101 	 *   r2 += 8;
13102 	 *   if (pkt_end >= r2) goto <access okay>
13103 	 *   <handle exception>
13104 	 *
13105 	 *   r2 = r3;
13106 	 *   r2 += 8;
13107 	 *   if (pkt_end <= r2) goto <handle exception>
13108 	 *   <access okay>
13109 	 *
13110 	 *   Where:
13111 	 *     pkt_end == dst_reg, r2 == src_reg
13112 	 *     r2=pkt(id=n,off=8,r=0)
13113 	 *     r3=pkt(id=n,off=0,r=0)
13114 	 *
13115 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13116 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13117 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13118 	 * the check.
13119 	 */
13120 
13121 	/* If our ids match, then we must have the same max_value.  And we
13122 	 * don't care about the other reg's fixed offset, since if it's too big
13123 	 * the range won't allow anything.
13124 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13125 	 */
13126 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13127 		if (reg->type == type && reg->id == dst_reg->id)
13128 			/* keep the maximum range already checked */
13129 			reg->range = max(reg->range, new_range);
13130 	}));
13131 }
13132 
13133 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13134 {
13135 	struct tnum subreg = tnum_subreg(reg->var_off);
13136 	s32 sval = (s32)val;
13137 
13138 	switch (opcode) {
13139 	case BPF_JEQ:
13140 		if (tnum_is_const(subreg))
13141 			return !!tnum_equals_const(subreg, val);
13142 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13143 			return 0;
13144 		break;
13145 	case BPF_JNE:
13146 		if (tnum_is_const(subreg))
13147 			return !tnum_equals_const(subreg, val);
13148 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13149 			return 1;
13150 		break;
13151 	case BPF_JSET:
13152 		if ((~subreg.mask & subreg.value) & val)
13153 			return 1;
13154 		if (!((subreg.mask | subreg.value) & val))
13155 			return 0;
13156 		break;
13157 	case BPF_JGT:
13158 		if (reg->u32_min_value > val)
13159 			return 1;
13160 		else if (reg->u32_max_value <= val)
13161 			return 0;
13162 		break;
13163 	case BPF_JSGT:
13164 		if (reg->s32_min_value > sval)
13165 			return 1;
13166 		else if (reg->s32_max_value <= sval)
13167 			return 0;
13168 		break;
13169 	case BPF_JLT:
13170 		if (reg->u32_max_value < val)
13171 			return 1;
13172 		else if (reg->u32_min_value >= val)
13173 			return 0;
13174 		break;
13175 	case BPF_JSLT:
13176 		if (reg->s32_max_value < sval)
13177 			return 1;
13178 		else if (reg->s32_min_value >= sval)
13179 			return 0;
13180 		break;
13181 	case BPF_JGE:
13182 		if (reg->u32_min_value >= val)
13183 			return 1;
13184 		else if (reg->u32_max_value < val)
13185 			return 0;
13186 		break;
13187 	case BPF_JSGE:
13188 		if (reg->s32_min_value >= sval)
13189 			return 1;
13190 		else if (reg->s32_max_value < sval)
13191 			return 0;
13192 		break;
13193 	case BPF_JLE:
13194 		if (reg->u32_max_value <= val)
13195 			return 1;
13196 		else if (reg->u32_min_value > val)
13197 			return 0;
13198 		break;
13199 	case BPF_JSLE:
13200 		if (reg->s32_max_value <= sval)
13201 			return 1;
13202 		else if (reg->s32_min_value > sval)
13203 			return 0;
13204 		break;
13205 	}
13206 
13207 	return -1;
13208 }
13209 
13210 
13211 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13212 {
13213 	s64 sval = (s64)val;
13214 
13215 	switch (opcode) {
13216 	case BPF_JEQ:
13217 		if (tnum_is_const(reg->var_off))
13218 			return !!tnum_equals_const(reg->var_off, val);
13219 		else if (val < reg->umin_value || val > reg->umax_value)
13220 			return 0;
13221 		break;
13222 	case BPF_JNE:
13223 		if (tnum_is_const(reg->var_off))
13224 			return !tnum_equals_const(reg->var_off, val);
13225 		else if (val < reg->umin_value || val > reg->umax_value)
13226 			return 1;
13227 		break;
13228 	case BPF_JSET:
13229 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13230 			return 1;
13231 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13232 			return 0;
13233 		break;
13234 	case BPF_JGT:
13235 		if (reg->umin_value > val)
13236 			return 1;
13237 		else if (reg->umax_value <= val)
13238 			return 0;
13239 		break;
13240 	case BPF_JSGT:
13241 		if (reg->smin_value > sval)
13242 			return 1;
13243 		else if (reg->smax_value <= sval)
13244 			return 0;
13245 		break;
13246 	case BPF_JLT:
13247 		if (reg->umax_value < val)
13248 			return 1;
13249 		else if (reg->umin_value >= val)
13250 			return 0;
13251 		break;
13252 	case BPF_JSLT:
13253 		if (reg->smax_value < sval)
13254 			return 1;
13255 		else if (reg->smin_value >= sval)
13256 			return 0;
13257 		break;
13258 	case BPF_JGE:
13259 		if (reg->umin_value >= val)
13260 			return 1;
13261 		else if (reg->umax_value < val)
13262 			return 0;
13263 		break;
13264 	case BPF_JSGE:
13265 		if (reg->smin_value >= sval)
13266 			return 1;
13267 		else if (reg->smax_value < sval)
13268 			return 0;
13269 		break;
13270 	case BPF_JLE:
13271 		if (reg->umax_value <= val)
13272 			return 1;
13273 		else if (reg->umin_value > val)
13274 			return 0;
13275 		break;
13276 	case BPF_JSLE:
13277 		if (reg->smax_value <= sval)
13278 			return 1;
13279 		else if (reg->smin_value > sval)
13280 			return 0;
13281 		break;
13282 	}
13283 
13284 	return -1;
13285 }
13286 
13287 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13288  * and return:
13289  *  1 - branch will be taken and "goto target" will be executed
13290  *  0 - branch will not be taken and fall-through to next insn
13291  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13292  *      range [0,10]
13293  */
13294 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13295 			   bool is_jmp32)
13296 {
13297 	if (__is_pointer_value(false, reg)) {
13298 		if (!reg_not_null(reg))
13299 			return -1;
13300 
13301 		/* If pointer is valid tests against zero will fail so we can
13302 		 * use this to direct branch taken.
13303 		 */
13304 		if (val != 0)
13305 			return -1;
13306 
13307 		switch (opcode) {
13308 		case BPF_JEQ:
13309 			return 0;
13310 		case BPF_JNE:
13311 			return 1;
13312 		default:
13313 			return -1;
13314 		}
13315 	}
13316 
13317 	if (is_jmp32)
13318 		return is_branch32_taken(reg, val, opcode);
13319 	return is_branch64_taken(reg, val, opcode);
13320 }
13321 
13322 static int flip_opcode(u32 opcode)
13323 {
13324 	/* How can we transform "a <op> b" into "b <op> a"? */
13325 	static const u8 opcode_flip[16] = {
13326 		/* these stay the same */
13327 		[BPF_JEQ  >> 4] = BPF_JEQ,
13328 		[BPF_JNE  >> 4] = BPF_JNE,
13329 		[BPF_JSET >> 4] = BPF_JSET,
13330 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
13331 		[BPF_JGE  >> 4] = BPF_JLE,
13332 		[BPF_JGT  >> 4] = BPF_JLT,
13333 		[BPF_JLE  >> 4] = BPF_JGE,
13334 		[BPF_JLT  >> 4] = BPF_JGT,
13335 		[BPF_JSGE >> 4] = BPF_JSLE,
13336 		[BPF_JSGT >> 4] = BPF_JSLT,
13337 		[BPF_JSLE >> 4] = BPF_JSGE,
13338 		[BPF_JSLT >> 4] = BPF_JSGT
13339 	};
13340 	return opcode_flip[opcode >> 4];
13341 }
13342 
13343 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13344 				   struct bpf_reg_state *src_reg,
13345 				   u8 opcode)
13346 {
13347 	struct bpf_reg_state *pkt;
13348 
13349 	if (src_reg->type == PTR_TO_PACKET_END) {
13350 		pkt = dst_reg;
13351 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
13352 		pkt = src_reg;
13353 		opcode = flip_opcode(opcode);
13354 	} else {
13355 		return -1;
13356 	}
13357 
13358 	if (pkt->range >= 0)
13359 		return -1;
13360 
13361 	switch (opcode) {
13362 	case BPF_JLE:
13363 		/* pkt <= pkt_end */
13364 		fallthrough;
13365 	case BPF_JGT:
13366 		/* pkt > pkt_end */
13367 		if (pkt->range == BEYOND_PKT_END)
13368 			/* pkt has at last one extra byte beyond pkt_end */
13369 			return opcode == BPF_JGT;
13370 		break;
13371 	case BPF_JLT:
13372 		/* pkt < pkt_end */
13373 		fallthrough;
13374 	case BPF_JGE:
13375 		/* pkt >= pkt_end */
13376 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13377 			return opcode == BPF_JGE;
13378 		break;
13379 	}
13380 	return -1;
13381 }
13382 
13383 /* Adjusts the register min/max values in the case that the dst_reg is the
13384  * variable register that we are working on, and src_reg is a constant or we're
13385  * simply doing a BPF_K check.
13386  * In JEQ/JNE cases we also adjust the var_off values.
13387  */
13388 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13389 			    struct bpf_reg_state *false_reg,
13390 			    u64 val, u32 val32,
13391 			    u8 opcode, bool is_jmp32)
13392 {
13393 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
13394 	struct tnum false_64off = false_reg->var_off;
13395 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
13396 	struct tnum true_64off = true_reg->var_off;
13397 	s64 sval = (s64)val;
13398 	s32 sval32 = (s32)val32;
13399 
13400 	/* If the dst_reg is a pointer, we can't learn anything about its
13401 	 * variable offset from the compare (unless src_reg were a pointer into
13402 	 * the same object, but we don't bother with that.
13403 	 * Since false_reg and true_reg have the same type by construction, we
13404 	 * only need to check one of them for pointerness.
13405 	 */
13406 	if (__is_pointer_value(false, false_reg))
13407 		return;
13408 
13409 	switch (opcode) {
13410 	/* JEQ/JNE comparison doesn't change the register equivalence.
13411 	 *
13412 	 * r1 = r2;
13413 	 * if (r1 == 42) goto label;
13414 	 * ...
13415 	 * label: // here both r1 and r2 are known to be 42.
13416 	 *
13417 	 * Hence when marking register as known preserve it's ID.
13418 	 */
13419 	case BPF_JEQ:
13420 		if (is_jmp32) {
13421 			__mark_reg32_known(true_reg, val32);
13422 			true_32off = tnum_subreg(true_reg->var_off);
13423 		} else {
13424 			___mark_reg_known(true_reg, val);
13425 			true_64off = true_reg->var_off;
13426 		}
13427 		break;
13428 	case BPF_JNE:
13429 		if (is_jmp32) {
13430 			__mark_reg32_known(false_reg, val32);
13431 			false_32off = tnum_subreg(false_reg->var_off);
13432 		} else {
13433 			___mark_reg_known(false_reg, val);
13434 			false_64off = false_reg->var_off;
13435 		}
13436 		break;
13437 	case BPF_JSET:
13438 		if (is_jmp32) {
13439 			false_32off = tnum_and(false_32off, tnum_const(~val32));
13440 			if (is_power_of_2(val32))
13441 				true_32off = tnum_or(true_32off,
13442 						     tnum_const(val32));
13443 		} else {
13444 			false_64off = tnum_and(false_64off, tnum_const(~val));
13445 			if (is_power_of_2(val))
13446 				true_64off = tnum_or(true_64off,
13447 						     tnum_const(val));
13448 		}
13449 		break;
13450 	case BPF_JGE:
13451 	case BPF_JGT:
13452 	{
13453 		if (is_jmp32) {
13454 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13455 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13456 
13457 			false_reg->u32_max_value = min(false_reg->u32_max_value,
13458 						       false_umax);
13459 			true_reg->u32_min_value = max(true_reg->u32_min_value,
13460 						      true_umin);
13461 		} else {
13462 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13463 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13464 
13465 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
13466 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
13467 		}
13468 		break;
13469 	}
13470 	case BPF_JSGE:
13471 	case BPF_JSGT:
13472 	{
13473 		if (is_jmp32) {
13474 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13475 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13476 
13477 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13478 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13479 		} else {
13480 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13481 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13482 
13483 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
13484 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
13485 		}
13486 		break;
13487 	}
13488 	case BPF_JLE:
13489 	case BPF_JLT:
13490 	{
13491 		if (is_jmp32) {
13492 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13493 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13494 
13495 			false_reg->u32_min_value = max(false_reg->u32_min_value,
13496 						       false_umin);
13497 			true_reg->u32_max_value = min(true_reg->u32_max_value,
13498 						      true_umax);
13499 		} else {
13500 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13501 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13502 
13503 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
13504 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
13505 		}
13506 		break;
13507 	}
13508 	case BPF_JSLE:
13509 	case BPF_JSLT:
13510 	{
13511 		if (is_jmp32) {
13512 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13513 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13514 
13515 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13516 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13517 		} else {
13518 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13519 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13520 
13521 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
13522 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
13523 		}
13524 		break;
13525 	}
13526 	default:
13527 		return;
13528 	}
13529 
13530 	if (is_jmp32) {
13531 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13532 					     tnum_subreg(false_32off));
13533 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13534 					    tnum_subreg(true_32off));
13535 		__reg_combine_32_into_64(false_reg);
13536 		__reg_combine_32_into_64(true_reg);
13537 	} else {
13538 		false_reg->var_off = false_64off;
13539 		true_reg->var_off = true_64off;
13540 		__reg_combine_64_into_32(false_reg);
13541 		__reg_combine_64_into_32(true_reg);
13542 	}
13543 }
13544 
13545 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13546  * the variable reg.
13547  */
13548 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13549 				struct bpf_reg_state *false_reg,
13550 				u64 val, u32 val32,
13551 				u8 opcode, bool is_jmp32)
13552 {
13553 	opcode = flip_opcode(opcode);
13554 	/* This uses zero as "not present in table"; luckily the zero opcode,
13555 	 * BPF_JA, can't get here.
13556 	 */
13557 	if (opcode)
13558 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13559 }
13560 
13561 /* Regs are known to be equal, so intersect their min/max/var_off */
13562 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13563 				  struct bpf_reg_state *dst_reg)
13564 {
13565 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13566 							dst_reg->umin_value);
13567 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13568 							dst_reg->umax_value);
13569 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13570 							dst_reg->smin_value);
13571 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13572 							dst_reg->smax_value);
13573 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13574 							     dst_reg->var_off);
13575 	reg_bounds_sync(src_reg);
13576 	reg_bounds_sync(dst_reg);
13577 }
13578 
13579 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13580 				struct bpf_reg_state *true_dst,
13581 				struct bpf_reg_state *false_src,
13582 				struct bpf_reg_state *false_dst,
13583 				u8 opcode)
13584 {
13585 	switch (opcode) {
13586 	case BPF_JEQ:
13587 		__reg_combine_min_max(true_src, true_dst);
13588 		break;
13589 	case BPF_JNE:
13590 		__reg_combine_min_max(false_src, false_dst);
13591 		break;
13592 	}
13593 }
13594 
13595 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13596 				 struct bpf_reg_state *reg, u32 id,
13597 				 bool is_null)
13598 {
13599 	if (type_may_be_null(reg->type) && reg->id == id &&
13600 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13601 		/* Old offset (both fixed and variable parts) should have been
13602 		 * known-zero, because we don't allow pointer arithmetic on
13603 		 * pointers that might be NULL. If we see this happening, don't
13604 		 * convert the register.
13605 		 *
13606 		 * But in some cases, some helpers that return local kptrs
13607 		 * advance offset for the returned pointer. In those cases, it
13608 		 * is fine to expect to see reg->off.
13609 		 */
13610 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13611 			return;
13612 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13613 		    WARN_ON_ONCE(reg->off))
13614 			return;
13615 
13616 		if (is_null) {
13617 			reg->type = SCALAR_VALUE;
13618 			/* We don't need id and ref_obj_id from this point
13619 			 * onwards anymore, thus we should better reset it,
13620 			 * so that state pruning has chances to take effect.
13621 			 */
13622 			reg->id = 0;
13623 			reg->ref_obj_id = 0;
13624 
13625 			return;
13626 		}
13627 
13628 		mark_ptr_not_null_reg(reg);
13629 
13630 		if (!reg_may_point_to_spin_lock(reg)) {
13631 			/* For not-NULL ptr, reg->ref_obj_id will be reset
13632 			 * in release_reference().
13633 			 *
13634 			 * reg->id is still used by spin_lock ptr. Other
13635 			 * than spin_lock ptr type, reg->id can be reset.
13636 			 */
13637 			reg->id = 0;
13638 		}
13639 	}
13640 }
13641 
13642 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13643  * be folded together at some point.
13644  */
13645 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13646 				  bool is_null)
13647 {
13648 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13649 	struct bpf_reg_state *regs = state->regs, *reg;
13650 	u32 ref_obj_id = regs[regno].ref_obj_id;
13651 	u32 id = regs[regno].id;
13652 
13653 	if (ref_obj_id && ref_obj_id == id && is_null)
13654 		/* regs[regno] is in the " == NULL" branch.
13655 		 * No one could have freed the reference state before
13656 		 * doing the NULL check.
13657 		 */
13658 		WARN_ON_ONCE(release_reference_state(state, id));
13659 
13660 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13661 		mark_ptr_or_null_reg(state, reg, id, is_null);
13662 	}));
13663 }
13664 
13665 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13666 				   struct bpf_reg_state *dst_reg,
13667 				   struct bpf_reg_state *src_reg,
13668 				   struct bpf_verifier_state *this_branch,
13669 				   struct bpf_verifier_state *other_branch)
13670 {
13671 	if (BPF_SRC(insn->code) != BPF_X)
13672 		return false;
13673 
13674 	/* Pointers are always 64-bit. */
13675 	if (BPF_CLASS(insn->code) == BPF_JMP32)
13676 		return false;
13677 
13678 	switch (BPF_OP(insn->code)) {
13679 	case BPF_JGT:
13680 		if ((dst_reg->type == PTR_TO_PACKET &&
13681 		     src_reg->type == PTR_TO_PACKET_END) ||
13682 		    (dst_reg->type == PTR_TO_PACKET_META &&
13683 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13684 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13685 			find_good_pkt_pointers(this_branch, dst_reg,
13686 					       dst_reg->type, false);
13687 			mark_pkt_end(other_branch, insn->dst_reg, true);
13688 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13689 			    src_reg->type == PTR_TO_PACKET) ||
13690 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13691 			    src_reg->type == PTR_TO_PACKET_META)) {
13692 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
13693 			find_good_pkt_pointers(other_branch, src_reg,
13694 					       src_reg->type, true);
13695 			mark_pkt_end(this_branch, insn->src_reg, false);
13696 		} else {
13697 			return false;
13698 		}
13699 		break;
13700 	case BPF_JLT:
13701 		if ((dst_reg->type == PTR_TO_PACKET &&
13702 		     src_reg->type == PTR_TO_PACKET_END) ||
13703 		    (dst_reg->type == PTR_TO_PACKET_META &&
13704 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13705 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13706 			find_good_pkt_pointers(other_branch, dst_reg,
13707 					       dst_reg->type, true);
13708 			mark_pkt_end(this_branch, insn->dst_reg, false);
13709 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13710 			    src_reg->type == PTR_TO_PACKET) ||
13711 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13712 			    src_reg->type == PTR_TO_PACKET_META)) {
13713 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
13714 			find_good_pkt_pointers(this_branch, src_reg,
13715 					       src_reg->type, false);
13716 			mark_pkt_end(other_branch, insn->src_reg, true);
13717 		} else {
13718 			return false;
13719 		}
13720 		break;
13721 	case BPF_JGE:
13722 		if ((dst_reg->type == PTR_TO_PACKET &&
13723 		     src_reg->type == PTR_TO_PACKET_END) ||
13724 		    (dst_reg->type == PTR_TO_PACKET_META &&
13725 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13726 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13727 			find_good_pkt_pointers(this_branch, dst_reg,
13728 					       dst_reg->type, true);
13729 			mark_pkt_end(other_branch, insn->dst_reg, false);
13730 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13731 			    src_reg->type == PTR_TO_PACKET) ||
13732 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13733 			    src_reg->type == PTR_TO_PACKET_META)) {
13734 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13735 			find_good_pkt_pointers(other_branch, src_reg,
13736 					       src_reg->type, false);
13737 			mark_pkt_end(this_branch, insn->src_reg, true);
13738 		} else {
13739 			return false;
13740 		}
13741 		break;
13742 	case BPF_JLE:
13743 		if ((dst_reg->type == PTR_TO_PACKET &&
13744 		     src_reg->type == PTR_TO_PACKET_END) ||
13745 		    (dst_reg->type == PTR_TO_PACKET_META &&
13746 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13747 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13748 			find_good_pkt_pointers(other_branch, dst_reg,
13749 					       dst_reg->type, false);
13750 			mark_pkt_end(this_branch, insn->dst_reg, true);
13751 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
13752 			    src_reg->type == PTR_TO_PACKET) ||
13753 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13754 			    src_reg->type == PTR_TO_PACKET_META)) {
13755 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13756 			find_good_pkt_pointers(this_branch, src_reg,
13757 					       src_reg->type, true);
13758 			mark_pkt_end(other_branch, insn->src_reg, false);
13759 		} else {
13760 			return false;
13761 		}
13762 		break;
13763 	default:
13764 		return false;
13765 	}
13766 
13767 	return true;
13768 }
13769 
13770 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13771 			       struct bpf_reg_state *known_reg)
13772 {
13773 	struct bpf_func_state *state;
13774 	struct bpf_reg_state *reg;
13775 
13776 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13777 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13778 			copy_register_state(reg, known_reg);
13779 	}));
13780 }
13781 
13782 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13783 			     struct bpf_insn *insn, int *insn_idx)
13784 {
13785 	struct bpf_verifier_state *this_branch = env->cur_state;
13786 	struct bpf_verifier_state *other_branch;
13787 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13788 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13789 	struct bpf_reg_state *eq_branch_regs;
13790 	u8 opcode = BPF_OP(insn->code);
13791 	bool is_jmp32;
13792 	int pred = -1;
13793 	int err;
13794 
13795 	/* Only conditional jumps are expected to reach here. */
13796 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
13797 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13798 		return -EINVAL;
13799 	}
13800 
13801 	if (BPF_SRC(insn->code) == BPF_X) {
13802 		if (insn->imm != 0) {
13803 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13804 			return -EINVAL;
13805 		}
13806 
13807 		/* check src1 operand */
13808 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13809 		if (err)
13810 			return err;
13811 
13812 		if (is_pointer_value(env, insn->src_reg)) {
13813 			verbose(env, "R%d pointer comparison prohibited\n",
13814 				insn->src_reg);
13815 			return -EACCES;
13816 		}
13817 		src_reg = &regs[insn->src_reg];
13818 	} else {
13819 		if (insn->src_reg != BPF_REG_0) {
13820 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13821 			return -EINVAL;
13822 		}
13823 	}
13824 
13825 	/* check src2 operand */
13826 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13827 	if (err)
13828 		return err;
13829 
13830 	dst_reg = &regs[insn->dst_reg];
13831 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13832 
13833 	if (BPF_SRC(insn->code) == BPF_K) {
13834 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13835 	} else if (src_reg->type == SCALAR_VALUE &&
13836 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13837 		pred = is_branch_taken(dst_reg,
13838 				       tnum_subreg(src_reg->var_off).value,
13839 				       opcode,
13840 				       is_jmp32);
13841 	} else if (src_reg->type == SCALAR_VALUE &&
13842 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13843 		pred = is_branch_taken(dst_reg,
13844 				       src_reg->var_off.value,
13845 				       opcode,
13846 				       is_jmp32);
13847 	} else if (dst_reg->type == SCALAR_VALUE &&
13848 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13849 		pred = is_branch_taken(src_reg,
13850 				       tnum_subreg(dst_reg->var_off).value,
13851 				       flip_opcode(opcode),
13852 				       is_jmp32);
13853 	} else if (dst_reg->type == SCALAR_VALUE &&
13854 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13855 		pred = is_branch_taken(src_reg,
13856 				       dst_reg->var_off.value,
13857 				       flip_opcode(opcode),
13858 				       is_jmp32);
13859 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
13860 		   reg_is_pkt_pointer_any(src_reg) &&
13861 		   !is_jmp32) {
13862 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13863 	}
13864 
13865 	if (pred >= 0) {
13866 		/* If we get here with a dst_reg pointer type it is because
13867 		 * above is_branch_taken() special cased the 0 comparison.
13868 		 */
13869 		if (!__is_pointer_value(false, dst_reg))
13870 			err = mark_chain_precision(env, insn->dst_reg);
13871 		if (BPF_SRC(insn->code) == BPF_X && !err &&
13872 		    !__is_pointer_value(false, src_reg))
13873 			err = mark_chain_precision(env, insn->src_reg);
13874 		if (err)
13875 			return err;
13876 	}
13877 
13878 	if (pred == 1) {
13879 		/* Only follow the goto, ignore fall-through. If needed, push
13880 		 * the fall-through branch for simulation under speculative
13881 		 * execution.
13882 		 */
13883 		if (!env->bypass_spec_v1 &&
13884 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
13885 					       *insn_idx))
13886 			return -EFAULT;
13887 		*insn_idx += insn->off;
13888 		return 0;
13889 	} else if (pred == 0) {
13890 		/* Only follow the fall-through branch, since that's where the
13891 		 * program will go. If needed, push the goto branch for
13892 		 * simulation under speculative execution.
13893 		 */
13894 		if (!env->bypass_spec_v1 &&
13895 		    !sanitize_speculative_path(env, insn,
13896 					       *insn_idx + insn->off + 1,
13897 					       *insn_idx))
13898 			return -EFAULT;
13899 		return 0;
13900 	}
13901 
13902 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13903 				  false);
13904 	if (!other_branch)
13905 		return -EFAULT;
13906 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13907 
13908 	/* detect if we are comparing against a constant value so we can adjust
13909 	 * our min/max values for our dst register.
13910 	 * this is only legit if both are scalars (or pointers to the same
13911 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13912 	 * because otherwise the different base pointers mean the offsets aren't
13913 	 * comparable.
13914 	 */
13915 	if (BPF_SRC(insn->code) == BPF_X) {
13916 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13917 
13918 		if (dst_reg->type == SCALAR_VALUE &&
13919 		    src_reg->type == SCALAR_VALUE) {
13920 			if (tnum_is_const(src_reg->var_off) ||
13921 			    (is_jmp32 &&
13922 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
13923 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
13924 						dst_reg,
13925 						src_reg->var_off.value,
13926 						tnum_subreg(src_reg->var_off).value,
13927 						opcode, is_jmp32);
13928 			else if (tnum_is_const(dst_reg->var_off) ||
13929 				 (is_jmp32 &&
13930 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
13931 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13932 						    src_reg,
13933 						    dst_reg->var_off.value,
13934 						    tnum_subreg(dst_reg->var_off).value,
13935 						    opcode, is_jmp32);
13936 			else if (!is_jmp32 &&
13937 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
13938 				/* Comparing for equality, we can combine knowledge */
13939 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
13940 						    &other_branch_regs[insn->dst_reg],
13941 						    src_reg, dst_reg, opcode);
13942 			if (src_reg->id &&
13943 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13944 				find_equal_scalars(this_branch, src_reg);
13945 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13946 			}
13947 
13948 		}
13949 	} else if (dst_reg->type == SCALAR_VALUE) {
13950 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
13951 					dst_reg, insn->imm, (u32)insn->imm,
13952 					opcode, is_jmp32);
13953 	}
13954 
13955 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13956 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13957 		find_equal_scalars(this_branch, dst_reg);
13958 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13959 	}
13960 
13961 	/* if one pointer register is compared to another pointer
13962 	 * register check if PTR_MAYBE_NULL could be lifted.
13963 	 * E.g. register A - maybe null
13964 	 *      register B - not null
13965 	 * for JNE A, B, ... - A is not null in the false branch;
13966 	 * for JEQ A, B, ... - A is not null in the true branch.
13967 	 *
13968 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
13969 	 * not need to be null checked by the BPF program, i.e.,
13970 	 * could be null even without PTR_MAYBE_NULL marking, so
13971 	 * only propagate nullness when neither reg is that type.
13972 	 */
13973 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13974 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13975 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13976 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
13977 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13978 		eq_branch_regs = NULL;
13979 		switch (opcode) {
13980 		case BPF_JEQ:
13981 			eq_branch_regs = other_branch_regs;
13982 			break;
13983 		case BPF_JNE:
13984 			eq_branch_regs = regs;
13985 			break;
13986 		default:
13987 			/* do nothing */
13988 			break;
13989 		}
13990 		if (eq_branch_regs) {
13991 			if (type_may_be_null(src_reg->type))
13992 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13993 			else
13994 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13995 		}
13996 	}
13997 
13998 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13999 	 * NOTE: these optimizations below are related with pointer comparison
14000 	 *       which will never be JMP32.
14001 	 */
14002 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14003 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14004 	    type_may_be_null(dst_reg->type)) {
14005 		/* Mark all identical registers in each branch as either
14006 		 * safe or unknown depending R == 0 or R != 0 conditional.
14007 		 */
14008 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14009 				      opcode == BPF_JNE);
14010 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14011 				      opcode == BPF_JEQ);
14012 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14013 					   this_branch, other_branch) &&
14014 		   is_pointer_value(env, insn->dst_reg)) {
14015 		verbose(env, "R%d pointer comparison prohibited\n",
14016 			insn->dst_reg);
14017 		return -EACCES;
14018 	}
14019 	if (env->log.level & BPF_LOG_LEVEL)
14020 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14021 	return 0;
14022 }
14023 
14024 /* verify BPF_LD_IMM64 instruction */
14025 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14026 {
14027 	struct bpf_insn_aux_data *aux = cur_aux(env);
14028 	struct bpf_reg_state *regs = cur_regs(env);
14029 	struct bpf_reg_state *dst_reg;
14030 	struct bpf_map *map;
14031 	int err;
14032 
14033 	if (BPF_SIZE(insn->code) != BPF_DW) {
14034 		verbose(env, "invalid BPF_LD_IMM insn\n");
14035 		return -EINVAL;
14036 	}
14037 	if (insn->off != 0) {
14038 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14039 		return -EINVAL;
14040 	}
14041 
14042 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14043 	if (err)
14044 		return err;
14045 
14046 	dst_reg = &regs[insn->dst_reg];
14047 	if (insn->src_reg == 0) {
14048 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14049 
14050 		dst_reg->type = SCALAR_VALUE;
14051 		__mark_reg_known(&regs[insn->dst_reg], imm);
14052 		return 0;
14053 	}
14054 
14055 	/* All special src_reg cases are listed below. From this point onwards
14056 	 * we either succeed and assign a corresponding dst_reg->type after
14057 	 * zeroing the offset, or fail and reject the program.
14058 	 */
14059 	mark_reg_known_zero(env, regs, insn->dst_reg);
14060 
14061 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14062 		dst_reg->type = aux->btf_var.reg_type;
14063 		switch (base_type(dst_reg->type)) {
14064 		case PTR_TO_MEM:
14065 			dst_reg->mem_size = aux->btf_var.mem_size;
14066 			break;
14067 		case PTR_TO_BTF_ID:
14068 			dst_reg->btf = aux->btf_var.btf;
14069 			dst_reg->btf_id = aux->btf_var.btf_id;
14070 			break;
14071 		default:
14072 			verbose(env, "bpf verifier is misconfigured\n");
14073 			return -EFAULT;
14074 		}
14075 		return 0;
14076 	}
14077 
14078 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14079 		struct bpf_prog_aux *aux = env->prog->aux;
14080 		u32 subprogno = find_subprog(env,
14081 					     env->insn_idx + insn->imm + 1);
14082 
14083 		if (!aux->func_info) {
14084 			verbose(env, "missing btf func_info\n");
14085 			return -EINVAL;
14086 		}
14087 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14088 			verbose(env, "callback function not static\n");
14089 			return -EINVAL;
14090 		}
14091 
14092 		dst_reg->type = PTR_TO_FUNC;
14093 		dst_reg->subprogno = subprogno;
14094 		return 0;
14095 	}
14096 
14097 	map = env->used_maps[aux->map_index];
14098 	dst_reg->map_ptr = map;
14099 
14100 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14101 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14102 		dst_reg->type = PTR_TO_MAP_VALUE;
14103 		dst_reg->off = aux->map_off;
14104 		WARN_ON_ONCE(map->max_entries != 1);
14105 		/* We want reg->id to be same (0) as map_value is not distinct */
14106 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14107 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14108 		dst_reg->type = CONST_PTR_TO_MAP;
14109 	} else {
14110 		verbose(env, "bpf verifier is misconfigured\n");
14111 		return -EINVAL;
14112 	}
14113 
14114 	return 0;
14115 }
14116 
14117 static bool may_access_skb(enum bpf_prog_type type)
14118 {
14119 	switch (type) {
14120 	case BPF_PROG_TYPE_SOCKET_FILTER:
14121 	case BPF_PROG_TYPE_SCHED_CLS:
14122 	case BPF_PROG_TYPE_SCHED_ACT:
14123 		return true;
14124 	default:
14125 		return false;
14126 	}
14127 }
14128 
14129 /* verify safety of LD_ABS|LD_IND instructions:
14130  * - they can only appear in the programs where ctx == skb
14131  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14132  *   preserve R6-R9, and store return value into R0
14133  *
14134  * Implicit input:
14135  *   ctx == skb == R6 == CTX
14136  *
14137  * Explicit input:
14138  *   SRC == any register
14139  *   IMM == 32-bit immediate
14140  *
14141  * Output:
14142  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14143  */
14144 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14145 {
14146 	struct bpf_reg_state *regs = cur_regs(env);
14147 	static const int ctx_reg = BPF_REG_6;
14148 	u8 mode = BPF_MODE(insn->code);
14149 	int i, err;
14150 
14151 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14152 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14153 		return -EINVAL;
14154 	}
14155 
14156 	if (!env->ops->gen_ld_abs) {
14157 		verbose(env, "bpf verifier is misconfigured\n");
14158 		return -EINVAL;
14159 	}
14160 
14161 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14162 	    BPF_SIZE(insn->code) == BPF_DW ||
14163 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14164 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14165 		return -EINVAL;
14166 	}
14167 
14168 	/* check whether implicit source operand (register R6) is readable */
14169 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14170 	if (err)
14171 		return err;
14172 
14173 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14174 	 * gen_ld_abs() may terminate the program at runtime, leading to
14175 	 * reference leak.
14176 	 */
14177 	err = check_reference_leak(env);
14178 	if (err) {
14179 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14180 		return err;
14181 	}
14182 
14183 	if (env->cur_state->active_lock.ptr) {
14184 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14185 		return -EINVAL;
14186 	}
14187 
14188 	if (env->cur_state->active_rcu_lock) {
14189 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14190 		return -EINVAL;
14191 	}
14192 
14193 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14194 		verbose(env,
14195 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14196 		return -EINVAL;
14197 	}
14198 
14199 	if (mode == BPF_IND) {
14200 		/* check explicit source operand */
14201 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14202 		if (err)
14203 			return err;
14204 	}
14205 
14206 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14207 	if (err < 0)
14208 		return err;
14209 
14210 	/* reset caller saved regs to unreadable */
14211 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14212 		mark_reg_not_init(env, regs, caller_saved[i]);
14213 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14214 	}
14215 
14216 	/* mark destination R0 register as readable, since it contains
14217 	 * the value fetched from the packet.
14218 	 * Already marked as written above.
14219 	 */
14220 	mark_reg_unknown(env, regs, BPF_REG_0);
14221 	/* ld_abs load up to 32-bit skb data. */
14222 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14223 	return 0;
14224 }
14225 
14226 static int check_return_code(struct bpf_verifier_env *env)
14227 {
14228 	struct tnum enforce_attach_type_range = tnum_unknown;
14229 	const struct bpf_prog *prog = env->prog;
14230 	struct bpf_reg_state *reg;
14231 	struct tnum range = tnum_range(0, 1);
14232 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14233 	int err;
14234 	struct bpf_func_state *frame = env->cur_state->frame[0];
14235 	const bool is_subprog = frame->subprogno;
14236 
14237 	/* LSM and struct_ops func-ptr's return type could be "void" */
14238 	if (!is_subprog) {
14239 		switch (prog_type) {
14240 		case BPF_PROG_TYPE_LSM:
14241 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14242 				/* See below, can be 0 or 0-1 depending on hook. */
14243 				break;
14244 			fallthrough;
14245 		case BPF_PROG_TYPE_STRUCT_OPS:
14246 			if (!prog->aux->attach_func_proto->type)
14247 				return 0;
14248 			break;
14249 		default:
14250 			break;
14251 		}
14252 	}
14253 
14254 	/* eBPF calling convention is such that R0 is used
14255 	 * to return the value from eBPF program.
14256 	 * Make sure that it's readable at this time
14257 	 * of bpf_exit, which means that program wrote
14258 	 * something into it earlier
14259 	 */
14260 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14261 	if (err)
14262 		return err;
14263 
14264 	if (is_pointer_value(env, BPF_REG_0)) {
14265 		verbose(env, "R0 leaks addr as return value\n");
14266 		return -EACCES;
14267 	}
14268 
14269 	reg = cur_regs(env) + BPF_REG_0;
14270 
14271 	if (frame->in_async_callback_fn) {
14272 		/* enforce return zero from async callbacks like timer */
14273 		if (reg->type != SCALAR_VALUE) {
14274 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14275 				reg_type_str(env, reg->type));
14276 			return -EINVAL;
14277 		}
14278 
14279 		if (!tnum_in(tnum_const(0), reg->var_off)) {
14280 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14281 			return -EINVAL;
14282 		}
14283 		return 0;
14284 	}
14285 
14286 	if (is_subprog) {
14287 		if (reg->type != SCALAR_VALUE) {
14288 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14289 				reg_type_str(env, reg->type));
14290 			return -EINVAL;
14291 		}
14292 		return 0;
14293 	}
14294 
14295 	switch (prog_type) {
14296 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14297 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14298 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14299 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14300 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14301 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14302 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14303 			range = tnum_range(1, 1);
14304 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14305 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14306 			range = tnum_range(0, 3);
14307 		break;
14308 	case BPF_PROG_TYPE_CGROUP_SKB:
14309 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14310 			range = tnum_range(0, 3);
14311 			enforce_attach_type_range = tnum_range(2, 3);
14312 		}
14313 		break;
14314 	case BPF_PROG_TYPE_CGROUP_SOCK:
14315 	case BPF_PROG_TYPE_SOCK_OPS:
14316 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14317 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14318 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14319 		break;
14320 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14321 		if (!env->prog->aux->attach_btf_id)
14322 			return 0;
14323 		range = tnum_const(0);
14324 		break;
14325 	case BPF_PROG_TYPE_TRACING:
14326 		switch (env->prog->expected_attach_type) {
14327 		case BPF_TRACE_FENTRY:
14328 		case BPF_TRACE_FEXIT:
14329 			range = tnum_const(0);
14330 			break;
14331 		case BPF_TRACE_RAW_TP:
14332 		case BPF_MODIFY_RETURN:
14333 			return 0;
14334 		case BPF_TRACE_ITER:
14335 			break;
14336 		default:
14337 			return -ENOTSUPP;
14338 		}
14339 		break;
14340 	case BPF_PROG_TYPE_SK_LOOKUP:
14341 		range = tnum_range(SK_DROP, SK_PASS);
14342 		break;
14343 
14344 	case BPF_PROG_TYPE_LSM:
14345 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14346 			/* Regular BPF_PROG_TYPE_LSM programs can return
14347 			 * any value.
14348 			 */
14349 			return 0;
14350 		}
14351 		if (!env->prog->aux->attach_func_proto->type) {
14352 			/* Make sure programs that attach to void
14353 			 * hooks don't try to modify return value.
14354 			 */
14355 			range = tnum_range(1, 1);
14356 		}
14357 		break;
14358 
14359 	case BPF_PROG_TYPE_NETFILTER:
14360 		range = tnum_range(NF_DROP, NF_ACCEPT);
14361 		break;
14362 	case BPF_PROG_TYPE_EXT:
14363 		/* freplace program can return anything as its return value
14364 		 * depends on the to-be-replaced kernel func or bpf program.
14365 		 */
14366 	default:
14367 		return 0;
14368 	}
14369 
14370 	if (reg->type != SCALAR_VALUE) {
14371 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14372 			reg_type_str(env, reg->type));
14373 		return -EINVAL;
14374 	}
14375 
14376 	if (!tnum_in(range, reg->var_off)) {
14377 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14378 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14379 		    prog_type == BPF_PROG_TYPE_LSM &&
14380 		    !prog->aux->attach_func_proto->type)
14381 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14382 		return -EINVAL;
14383 	}
14384 
14385 	if (!tnum_is_unknown(enforce_attach_type_range) &&
14386 	    tnum_in(enforce_attach_type_range, reg->var_off))
14387 		env->prog->enforce_expected_attach_type = 1;
14388 	return 0;
14389 }
14390 
14391 /* non-recursive DFS pseudo code
14392  * 1  procedure DFS-iterative(G,v):
14393  * 2      label v as discovered
14394  * 3      let S be a stack
14395  * 4      S.push(v)
14396  * 5      while S is not empty
14397  * 6            t <- S.peek()
14398  * 7            if t is what we're looking for:
14399  * 8                return t
14400  * 9            for all edges e in G.adjacentEdges(t) do
14401  * 10               if edge e is already labelled
14402  * 11                   continue with the next edge
14403  * 12               w <- G.adjacentVertex(t,e)
14404  * 13               if vertex w is not discovered and not explored
14405  * 14                   label e as tree-edge
14406  * 15                   label w as discovered
14407  * 16                   S.push(w)
14408  * 17                   continue at 5
14409  * 18               else if vertex w is discovered
14410  * 19                   label e as back-edge
14411  * 20               else
14412  * 21                   // vertex w is explored
14413  * 22                   label e as forward- or cross-edge
14414  * 23           label t as explored
14415  * 24           S.pop()
14416  *
14417  * convention:
14418  * 0x10 - discovered
14419  * 0x11 - discovered and fall-through edge labelled
14420  * 0x12 - discovered and fall-through and branch edges labelled
14421  * 0x20 - explored
14422  */
14423 
14424 enum {
14425 	DISCOVERED = 0x10,
14426 	EXPLORED = 0x20,
14427 	FALLTHROUGH = 1,
14428 	BRANCH = 2,
14429 };
14430 
14431 static u32 state_htab_size(struct bpf_verifier_env *env)
14432 {
14433 	return env->prog->len;
14434 }
14435 
14436 static struct bpf_verifier_state_list **explored_state(
14437 					struct bpf_verifier_env *env,
14438 					int idx)
14439 {
14440 	struct bpf_verifier_state *cur = env->cur_state;
14441 	struct bpf_func_state *state = cur->frame[cur->curframe];
14442 
14443 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14444 }
14445 
14446 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14447 {
14448 	env->insn_aux_data[idx].prune_point = true;
14449 }
14450 
14451 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14452 {
14453 	return env->insn_aux_data[insn_idx].prune_point;
14454 }
14455 
14456 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14457 {
14458 	env->insn_aux_data[idx].force_checkpoint = true;
14459 }
14460 
14461 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14462 {
14463 	return env->insn_aux_data[insn_idx].force_checkpoint;
14464 }
14465 
14466 
14467 enum {
14468 	DONE_EXPLORING = 0,
14469 	KEEP_EXPLORING = 1,
14470 };
14471 
14472 /* t, w, e - match pseudo-code above:
14473  * t - index of current instruction
14474  * w - next instruction
14475  * e - edge
14476  */
14477 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14478 		     bool loop_ok)
14479 {
14480 	int *insn_stack = env->cfg.insn_stack;
14481 	int *insn_state = env->cfg.insn_state;
14482 
14483 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14484 		return DONE_EXPLORING;
14485 
14486 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14487 		return DONE_EXPLORING;
14488 
14489 	if (w < 0 || w >= env->prog->len) {
14490 		verbose_linfo(env, t, "%d: ", t);
14491 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
14492 		return -EINVAL;
14493 	}
14494 
14495 	if (e == BRANCH) {
14496 		/* mark branch target for state pruning */
14497 		mark_prune_point(env, w);
14498 		mark_jmp_point(env, w);
14499 	}
14500 
14501 	if (insn_state[w] == 0) {
14502 		/* tree-edge */
14503 		insn_state[t] = DISCOVERED | e;
14504 		insn_state[w] = DISCOVERED;
14505 		if (env->cfg.cur_stack >= env->prog->len)
14506 			return -E2BIG;
14507 		insn_stack[env->cfg.cur_stack++] = w;
14508 		return KEEP_EXPLORING;
14509 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14510 		if (loop_ok && env->bpf_capable)
14511 			return DONE_EXPLORING;
14512 		verbose_linfo(env, t, "%d: ", t);
14513 		verbose_linfo(env, w, "%d: ", w);
14514 		verbose(env, "back-edge from insn %d to %d\n", t, w);
14515 		return -EINVAL;
14516 	} else if (insn_state[w] == EXPLORED) {
14517 		/* forward- or cross-edge */
14518 		insn_state[t] = DISCOVERED | e;
14519 	} else {
14520 		verbose(env, "insn state internal bug\n");
14521 		return -EFAULT;
14522 	}
14523 	return DONE_EXPLORING;
14524 }
14525 
14526 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14527 				struct bpf_verifier_env *env,
14528 				bool visit_callee)
14529 {
14530 	int ret;
14531 
14532 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14533 	if (ret)
14534 		return ret;
14535 
14536 	mark_prune_point(env, t + 1);
14537 	/* when we exit from subprog, we need to record non-linear history */
14538 	mark_jmp_point(env, t + 1);
14539 
14540 	if (visit_callee) {
14541 		mark_prune_point(env, t);
14542 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14543 				/* It's ok to allow recursion from CFG point of
14544 				 * view. __check_func_call() will do the actual
14545 				 * check.
14546 				 */
14547 				bpf_pseudo_func(insns + t));
14548 	}
14549 	return ret;
14550 }
14551 
14552 /* Visits the instruction at index t and returns one of the following:
14553  *  < 0 - an error occurred
14554  *  DONE_EXPLORING - the instruction was fully explored
14555  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14556  */
14557 static int visit_insn(int t, struct bpf_verifier_env *env)
14558 {
14559 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14560 	int ret;
14561 
14562 	if (bpf_pseudo_func(insn))
14563 		return visit_func_call_insn(t, insns, env, true);
14564 
14565 	/* All non-branch instructions have a single fall-through edge. */
14566 	if (BPF_CLASS(insn->code) != BPF_JMP &&
14567 	    BPF_CLASS(insn->code) != BPF_JMP32)
14568 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
14569 
14570 	switch (BPF_OP(insn->code)) {
14571 	case BPF_EXIT:
14572 		return DONE_EXPLORING;
14573 
14574 	case BPF_CALL:
14575 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14576 			/* Mark this call insn as a prune point to trigger
14577 			 * is_state_visited() check before call itself is
14578 			 * processed by __check_func_call(). Otherwise new
14579 			 * async state will be pushed for further exploration.
14580 			 */
14581 			mark_prune_point(env, t);
14582 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14583 			struct bpf_kfunc_call_arg_meta meta;
14584 
14585 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14586 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
14587 				mark_prune_point(env, t);
14588 				/* Checking and saving state checkpoints at iter_next() call
14589 				 * is crucial for fast convergence of open-coded iterator loop
14590 				 * logic, so we need to force it. If we don't do that,
14591 				 * is_state_visited() might skip saving a checkpoint, causing
14592 				 * unnecessarily long sequence of not checkpointed
14593 				 * instructions and jumps, leading to exhaustion of jump
14594 				 * history buffer, and potentially other undesired outcomes.
14595 				 * It is expected that with correct open-coded iterators
14596 				 * convergence will happen quickly, so we don't run a risk of
14597 				 * exhausting memory.
14598 				 */
14599 				mark_force_checkpoint(env, t);
14600 			}
14601 		}
14602 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14603 
14604 	case BPF_JA:
14605 		if (BPF_SRC(insn->code) != BPF_K)
14606 			return -EINVAL;
14607 
14608 		/* unconditional jump with single edge */
14609 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14610 				true);
14611 		if (ret)
14612 			return ret;
14613 
14614 		mark_prune_point(env, t + insn->off + 1);
14615 		mark_jmp_point(env, t + insn->off + 1);
14616 
14617 		return ret;
14618 
14619 	default:
14620 		/* conditional jump with two edges */
14621 		mark_prune_point(env, t);
14622 
14623 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14624 		if (ret)
14625 			return ret;
14626 
14627 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14628 	}
14629 }
14630 
14631 /* non-recursive depth-first-search to detect loops in BPF program
14632  * loop == back-edge in directed graph
14633  */
14634 static int check_cfg(struct bpf_verifier_env *env)
14635 {
14636 	int insn_cnt = env->prog->len;
14637 	int *insn_stack, *insn_state;
14638 	int ret = 0;
14639 	int i;
14640 
14641 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14642 	if (!insn_state)
14643 		return -ENOMEM;
14644 
14645 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14646 	if (!insn_stack) {
14647 		kvfree(insn_state);
14648 		return -ENOMEM;
14649 	}
14650 
14651 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14652 	insn_stack[0] = 0; /* 0 is the first instruction */
14653 	env->cfg.cur_stack = 1;
14654 
14655 	while (env->cfg.cur_stack > 0) {
14656 		int t = insn_stack[env->cfg.cur_stack - 1];
14657 
14658 		ret = visit_insn(t, env);
14659 		switch (ret) {
14660 		case DONE_EXPLORING:
14661 			insn_state[t] = EXPLORED;
14662 			env->cfg.cur_stack--;
14663 			break;
14664 		case KEEP_EXPLORING:
14665 			break;
14666 		default:
14667 			if (ret > 0) {
14668 				verbose(env, "visit_insn internal bug\n");
14669 				ret = -EFAULT;
14670 			}
14671 			goto err_free;
14672 		}
14673 	}
14674 
14675 	if (env->cfg.cur_stack < 0) {
14676 		verbose(env, "pop stack internal bug\n");
14677 		ret = -EFAULT;
14678 		goto err_free;
14679 	}
14680 
14681 	for (i = 0; i < insn_cnt; i++) {
14682 		if (insn_state[i] != EXPLORED) {
14683 			verbose(env, "unreachable insn %d\n", i);
14684 			ret = -EINVAL;
14685 			goto err_free;
14686 		}
14687 	}
14688 	ret = 0; /* cfg looks good */
14689 
14690 err_free:
14691 	kvfree(insn_state);
14692 	kvfree(insn_stack);
14693 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
14694 	return ret;
14695 }
14696 
14697 static int check_abnormal_return(struct bpf_verifier_env *env)
14698 {
14699 	int i;
14700 
14701 	for (i = 1; i < env->subprog_cnt; i++) {
14702 		if (env->subprog_info[i].has_ld_abs) {
14703 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14704 			return -EINVAL;
14705 		}
14706 		if (env->subprog_info[i].has_tail_call) {
14707 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14708 			return -EINVAL;
14709 		}
14710 	}
14711 	return 0;
14712 }
14713 
14714 /* The minimum supported BTF func info size */
14715 #define MIN_BPF_FUNCINFO_SIZE	8
14716 #define MAX_FUNCINFO_REC_SIZE	252
14717 
14718 static int check_btf_func(struct bpf_verifier_env *env,
14719 			  const union bpf_attr *attr,
14720 			  bpfptr_t uattr)
14721 {
14722 	const struct btf_type *type, *func_proto, *ret_type;
14723 	u32 i, nfuncs, urec_size, min_size;
14724 	u32 krec_size = sizeof(struct bpf_func_info);
14725 	struct bpf_func_info *krecord;
14726 	struct bpf_func_info_aux *info_aux = NULL;
14727 	struct bpf_prog *prog;
14728 	const struct btf *btf;
14729 	bpfptr_t urecord;
14730 	u32 prev_offset = 0;
14731 	bool scalar_return;
14732 	int ret = -ENOMEM;
14733 
14734 	nfuncs = attr->func_info_cnt;
14735 	if (!nfuncs) {
14736 		if (check_abnormal_return(env))
14737 			return -EINVAL;
14738 		return 0;
14739 	}
14740 
14741 	if (nfuncs != env->subprog_cnt) {
14742 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14743 		return -EINVAL;
14744 	}
14745 
14746 	urec_size = attr->func_info_rec_size;
14747 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14748 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
14749 	    urec_size % sizeof(u32)) {
14750 		verbose(env, "invalid func info rec size %u\n", urec_size);
14751 		return -EINVAL;
14752 	}
14753 
14754 	prog = env->prog;
14755 	btf = prog->aux->btf;
14756 
14757 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14758 	min_size = min_t(u32, krec_size, urec_size);
14759 
14760 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14761 	if (!krecord)
14762 		return -ENOMEM;
14763 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14764 	if (!info_aux)
14765 		goto err_free;
14766 
14767 	for (i = 0; i < nfuncs; i++) {
14768 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14769 		if (ret) {
14770 			if (ret == -E2BIG) {
14771 				verbose(env, "nonzero tailing record in func info");
14772 				/* set the size kernel expects so loader can zero
14773 				 * out the rest of the record.
14774 				 */
14775 				if (copy_to_bpfptr_offset(uattr,
14776 							  offsetof(union bpf_attr, func_info_rec_size),
14777 							  &min_size, sizeof(min_size)))
14778 					ret = -EFAULT;
14779 			}
14780 			goto err_free;
14781 		}
14782 
14783 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14784 			ret = -EFAULT;
14785 			goto err_free;
14786 		}
14787 
14788 		/* check insn_off */
14789 		ret = -EINVAL;
14790 		if (i == 0) {
14791 			if (krecord[i].insn_off) {
14792 				verbose(env,
14793 					"nonzero insn_off %u for the first func info record",
14794 					krecord[i].insn_off);
14795 				goto err_free;
14796 			}
14797 		} else if (krecord[i].insn_off <= prev_offset) {
14798 			verbose(env,
14799 				"same or smaller insn offset (%u) than previous func info record (%u)",
14800 				krecord[i].insn_off, prev_offset);
14801 			goto err_free;
14802 		}
14803 
14804 		if (env->subprog_info[i].start != krecord[i].insn_off) {
14805 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14806 			goto err_free;
14807 		}
14808 
14809 		/* check type_id */
14810 		type = btf_type_by_id(btf, krecord[i].type_id);
14811 		if (!type || !btf_type_is_func(type)) {
14812 			verbose(env, "invalid type id %d in func info",
14813 				krecord[i].type_id);
14814 			goto err_free;
14815 		}
14816 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14817 
14818 		func_proto = btf_type_by_id(btf, type->type);
14819 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14820 			/* btf_func_check() already verified it during BTF load */
14821 			goto err_free;
14822 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14823 		scalar_return =
14824 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14825 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14826 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14827 			goto err_free;
14828 		}
14829 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14830 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14831 			goto err_free;
14832 		}
14833 
14834 		prev_offset = krecord[i].insn_off;
14835 		bpfptr_add(&urecord, urec_size);
14836 	}
14837 
14838 	prog->aux->func_info = krecord;
14839 	prog->aux->func_info_cnt = nfuncs;
14840 	prog->aux->func_info_aux = info_aux;
14841 	return 0;
14842 
14843 err_free:
14844 	kvfree(krecord);
14845 	kfree(info_aux);
14846 	return ret;
14847 }
14848 
14849 static void adjust_btf_func(struct bpf_verifier_env *env)
14850 {
14851 	struct bpf_prog_aux *aux = env->prog->aux;
14852 	int i;
14853 
14854 	if (!aux->func_info)
14855 		return;
14856 
14857 	for (i = 0; i < env->subprog_cnt; i++)
14858 		aux->func_info[i].insn_off = env->subprog_info[i].start;
14859 }
14860 
14861 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
14862 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
14863 
14864 static int check_btf_line(struct bpf_verifier_env *env,
14865 			  const union bpf_attr *attr,
14866 			  bpfptr_t uattr)
14867 {
14868 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14869 	struct bpf_subprog_info *sub;
14870 	struct bpf_line_info *linfo;
14871 	struct bpf_prog *prog;
14872 	const struct btf *btf;
14873 	bpfptr_t ulinfo;
14874 	int err;
14875 
14876 	nr_linfo = attr->line_info_cnt;
14877 	if (!nr_linfo)
14878 		return 0;
14879 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14880 		return -EINVAL;
14881 
14882 	rec_size = attr->line_info_rec_size;
14883 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14884 	    rec_size > MAX_LINEINFO_REC_SIZE ||
14885 	    rec_size & (sizeof(u32) - 1))
14886 		return -EINVAL;
14887 
14888 	/* Need to zero it in case the userspace may
14889 	 * pass in a smaller bpf_line_info object.
14890 	 */
14891 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14892 			 GFP_KERNEL | __GFP_NOWARN);
14893 	if (!linfo)
14894 		return -ENOMEM;
14895 
14896 	prog = env->prog;
14897 	btf = prog->aux->btf;
14898 
14899 	s = 0;
14900 	sub = env->subprog_info;
14901 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14902 	expected_size = sizeof(struct bpf_line_info);
14903 	ncopy = min_t(u32, expected_size, rec_size);
14904 	for (i = 0; i < nr_linfo; i++) {
14905 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14906 		if (err) {
14907 			if (err == -E2BIG) {
14908 				verbose(env, "nonzero tailing record in line_info");
14909 				if (copy_to_bpfptr_offset(uattr,
14910 							  offsetof(union bpf_attr, line_info_rec_size),
14911 							  &expected_size, sizeof(expected_size)))
14912 					err = -EFAULT;
14913 			}
14914 			goto err_free;
14915 		}
14916 
14917 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14918 			err = -EFAULT;
14919 			goto err_free;
14920 		}
14921 
14922 		/*
14923 		 * Check insn_off to ensure
14924 		 * 1) strictly increasing AND
14925 		 * 2) bounded by prog->len
14926 		 *
14927 		 * The linfo[0].insn_off == 0 check logically falls into
14928 		 * the later "missing bpf_line_info for func..." case
14929 		 * because the first linfo[0].insn_off must be the
14930 		 * first sub also and the first sub must have
14931 		 * subprog_info[0].start == 0.
14932 		 */
14933 		if ((i && linfo[i].insn_off <= prev_offset) ||
14934 		    linfo[i].insn_off >= prog->len) {
14935 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14936 				i, linfo[i].insn_off, prev_offset,
14937 				prog->len);
14938 			err = -EINVAL;
14939 			goto err_free;
14940 		}
14941 
14942 		if (!prog->insnsi[linfo[i].insn_off].code) {
14943 			verbose(env,
14944 				"Invalid insn code at line_info[%u].insn_off\n",
14945 				i);
14946 			err = -EINVAL;
14947 			goto err_free;
14948 		}
14949 
14950 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14951 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14952 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14953 			err = -EINVAL;
14954 			goto err_free;
14955 		}
14956 
14957 		if (s != env->subprog_cnt) {
14958 			if (linfo[i].insn_off == sub[s].start) {
14959 				sub[s].linfo_idx = i;
14960 				s++;
14961 			} else if (sub[s].start < linfo[i].insn_off) {
14962 				verbose(env, "missing bpf_line_info for func#%u\n", s);
14963 				err = -EINVAL;
14964 				goto err_free;
14965 			}
14966 		}
14967 
14968 		prev_offset = linfo[i].insn_off;
14969 		bpfptr_add(&ulinfo, rec_size);
14970 	}
14971 
14972 	if (s != env->subprog_cnt) {
14973 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14974 			env->subprog_cnt - s, s);
14975 		err = -EINVAL;
14976 		goto err_free;
14977 	}
14978 
14979 	prog->aux->linfo = linfo;
14980 	prog->aux->nr_linfo = nr_linfo;
14981 
14982 	return 0;
14983 
14984 err_free:
14985 	kvfree(linfo);
14986 	return err;
14987 }
14988 
14989 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
14990 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
14991 
14992 static int check_core_relo(struct bpf_verifier_env *env,
14993 			   const union bpf_attr *attr,
14994 			   bpfptr_t uattr)
14995 {
14996 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14997 	struct bpf_core_relo core_relo = {};
14998 	struct bpf_prog *prog = env->prog;
14999 	const struct btf *btf = prog->aux->btf;
15000 	struct bpf_core_ctx ctx = {
15001 		.log = &env->log,
15002 		.btf = btf,
15003 	};
15004 	bpfptr_t u_core_relo;
15005 	int err;
15006 
15007 	nr_core_relo = attr->core_relo_cnt;
15008 	if (!nr_core_relo)
15009 		return 0;
15010 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15011 		return -EINVAL;
15012 
15013 	rec_size = attr->core_relo_rec_size;
15014 	if (rec_size < MIN_CORE_RELO_SIZE ||
15015 	    rec_size > MAX_CORE_RELO_SIZE ||
15016 	    rec_size % sizeof(u32))
15017 		return -EINVAL;
15018 
15019 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15020 	expected_size = sizeof(struct bpf_core_relo);
15021 	ncopy = min_t(u32, expected_size, rec_size);
15022 
15023 	/* Unlike func_info and line_info, copy and apply each CO-RE
15024 	 * relocation record one at a time.
15025 	 */
15026 	for (i = 0; i < nr_core_relo; i++) {
15027 		/* future proofing when sizeof(bpf_core_relo) changes */
15028 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15029 		if (err) {
15030 			if (err == -E2BIG) {
15031 				verbose(env, "nonzero tailing record in core_relo");
15032 				if (copy_to_bpfptr_offset(uattr,
15033 							  offsetof(union bpf_attr, core_relo_rec_size),
15034 							  &expected_size, sizeof(expected_size)))
15035 					err = -EFAULT;
15036 			}
15037 			break;
15038 		}
15039 
15040 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15041 			err = -EFAULT;
15042 			break;
15043 		}
15044 
15045 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15046 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15047 				i, core_relo.insn_off, prog->len);
15048 			err = -EINVAL;
15049 			break;
15050 		}
15051 
15052 		err = bpf_core_apply(&ctx, &core_relo, i,
15053 				     &prog->insnsi[core_relo.insn_off / 8]);
15054 		if (err)
15055 			break;
15056 		bpfptr_add(&u_core_relo, rec_size);
15057 	}
15058 	return err;
15059 }
15060 
15061 static int check_btf_info(struct bpf_verifier_env *env,
15062 			  const union bpf_attr *attr,
15063 			  bpfptr_t uattr)
15064 {
15065 	struct btf *btf;
15066 	int err;
15067 
15068 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15069 		if (check_abnormal_return(env))
15070 			return -EINVAL;
15071 		return 0;
15072 	}
15073 
15074 	btf = btf_get_by_fd(attr->prog_btf_fd);
15075 	if (IS_ERR(btf))
15076 		return PTR_ERR(btf);
15077 	if (btf_is_kernel(btf)) {
15078 		btf_put(btf);
15079 		return -EACCES;
15080 	}
15081 	env->prog->aux->btf = btf;
15082 
15083 	err = check_btf_func(env, attr, uattr);
15084 	if (err)
15085 		return err;
15086 
15087 	err = check_btf_line(env, attr, uattr);
15088 	if (err)
15089 		return err;
15090 
15091 	err = check_core_relo(env, attr, uattr);
15092 	if (err)
15093 		return err;
15094 
15095 	return 0;
15096 }
15097 
15098 /* check %cur's range satisfies %old's */
15099 static bool range_within(struct bpf_reg_state *old,
15100 			 struct bpf_reg_state *cur)
15101 {
15102 	return old->umin_value <= cur->umin_value &&
15103 	       old->umax_value >= cur->umax_value &&
15104 	       old->smin_value <= cur->smin_value &&
15105 	       old->smax_value >= cur->smax_value &&
15106 	       old->u32_min_value <= cur->u32_min_value &&
15107 	       old->u32_max_value >= cur->u32_max_value &&
15108 	       old->s32_min_value <= cur->s32_min_value &&
15109 	       old->s32_max_value >= cur->s32_max_value;
15110 }
15111 
15112 /* If in the old state two registers had the same id, then they need to have
15113  * the same id in the new state as well.  But that id could be different from
15114  * the old state, so we need to track the mapping from old to new ids.
15115  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15116  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15117  * regs with a different old id could still have new id 9, we don't care about
15118  * that.
15119  * So we look through our idmap to see if this old id has been seen before.  If
15120  * so, we require the new id to match; otherwise, we add the id pair to the map.
15121  */
15122 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15123 {
15124 	struct bpf_id_pair *map = idmap->map;
15125 	unsigned int i;
15126 
15127 	/* either both IDs should be set or both should be zero */
15128 	if (!!old_id != !!cur_id)
15129 		return false;
15130 
15131 	if (old_id == 0) /* cur_id == 0 as well */
15132 		return true;
15133 
15134 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15135 		if (!map[i].old) {
15136 			/* Reached an empty slot; haven't seen this id before */
15137 			map[i].old = old_id;
15138 			map[i].cur = cur_id;
15139 			return true;
15140 		}
15141 		if (map[i].old == old_id)
15142 			return map[i].cur == cur_id;
15143 		if (map[i].cur == cur_id)
15144 			return false;
15145 	}
15146 	/* We ran out of idmap slots, which should be impossible */
15147 	WARN_ON_ONCE(1);
15148 	return false;
15149 }
15150 
15151 /* Similar to check_ids(), but allocate a unique temporary ID
15152  * for 'old_id' or 'cur_id' of zero.
15153  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15154  */
15155 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15156 {
15157 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15158 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15159 
15160 	return check_ids(old_id, cur_id, idmap);
15161 }
15162 
15163 static void clean_func_state(struct bpf_verifier_env *env,
15164 			     struct bpf_func_state *st)
15165 {
15166 	enum bpf_reg_liveness live;
15167 	int i, j;
15168 
15169 	for (i = 0; i < BPF_REG_FP; i++) {
15170 		live = st->regs[i].live;
15171 		/* liveness must not touch this register anymore */
15172 		st->regs[i].live |= REG_LIVE_DONE;
15173 		if (!(live & REG_LIVE_READ))
15174 			/* since the register is unused, clear its state
15175 			 * to make further comparison simpler
15176 			 */
15177 			__mark_reg_not_init(env, &st->regs[i]);
15178 	}
15179 
15180 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15181 		live = st->stack[i].spilled_ptr.live;
15182 		/* liveness must not touch this stack slot anymore */
15183 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15184 		if (!(live & REG_LIVE_READ)) {
15185 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15186 			for (j = 0; j < BPF_REG_SIZE; j++)
15187 				st->stack[i].slot_type[j] = STACK_INVALID;
15188 		}
15189 	}
15190 }
15191 
15192 static void clean_verifier_state(struct bpf_verifier_env *env,
15193 				 struct bpf_verifier_state *st)
15194 {
15195 	int i;
15196 
15197 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15198 		/* all regs in this state in all frames were already marked */
15199 		return;
15200 
15201 	for (i = 0; i <= st->curframe; i++)
15202 		clean_func_state(env, st->frame[i]);
15203 }
15204 
15205 /* the parentage chains form a tree.
15206  * the verifier states are added to state lists at given insn and
15207  * pushed into state stack for future exploration.
15208  * when the verifier reaches bpf_exit insn some of the verifer states
15209  * stored in the state lists have their final liveness state already,
15210  * but a lot of states will get revised from liveness point of view when
15211  * the verifier explores other branches.
15212  * Example:
15213  * 1: r0 = 1
15214  * 2: if r1 == 100 goto pc+1
15215  * 3: r0 = 2
15216  * 4: exit
15217  * when the verifier reaches exit insn the register r0 in the state list of
15218  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15219  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15220  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15221  *
15222  * Since the verifier pushes the branch states as it sees them while exploring
15223  * the program the condition of walking the branch instruction for the second
15224  * time means that all states below this branch were already explored and
15225  * their final liveness marks are already propagated.
15226  * Hence when the verifier completes the search of state list in is_state_visited()
15227  * we can call this clean_live_states() function to mark all liveness states
15228  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15229  * will not be used.
15230  * This function also clears the registers and stack for states that !READ
15231  * to simplify state merging.
15232  *
15233  * Important note here that walking the same branch instruction in the callee
15234  * doesn't meant that the states are DONE. The verifier has to compare
15235  * the callsites
15236  */
15237 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15238 			      struct bpf_verifier_state *cur)
15239 {
15240 	struct bpf_verifier_state_list *sl;
15241 	int i;
15242 
15243 	sl = *explored_state(env, insn);
15244 	while (sl) {
15245 		if (sl->state.branches)
15246 			goto next;
15247 		if (sl->state.insn_idx != insn ||
15248 		    sl->state.curframe != cur->curframe)
15249 			goto next;
15250 		for (i = 0; i <= cur->curframe; i++)
15251 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15252 				goto next;
15253 		clean_verifier_state(env, &sl->state);
15254 next:
15255 		sl = sl->next;
15256 	}
15257 }
15258 
15259 static bool regs_exact(const struct bpf_reg_state *rold,
15260 		       const struct bpf_reg_state *rcur,
15261 		       struct bpf_idmap *idmap)
15262 {
15263 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15264 	       check_ids(rold->id, rcur->id, idmap) &&
15265 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15266 }
15267 
15268 /* Returns true if (rold safe implies rcur safe) */
15269 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15270 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15271 {
15272 	if (!(rold->live & REG_LIVE_READ))
15273 		/* explored state didn't use this */
15274 		return true;
15275 	if (rold->type == NOT_INIT)
15276 		/* explored state can't have used this */
15277 		return true;
15278 	if (rcur->type == NOT_INIT)
15279 		return false;
15280 
15281 	/* Enforce that register types have to match exactly, including their
15282 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15283 	 * rule.
15284 	 *
15285 	 * One can make a point that using a pointer register as unbounded
15286 	 * SCALAR would be technically acceptable, but this could lead to
15287 	 * pointer leaks because scalars are allowed to leak while pointers
15288 	 * are not. We could make this safe in special cases if root is
15289 	 * calling us, but it's probably not worth the hassle.
15290 	 *
15291 	 * Also, register types that are *not* MAYBE_NULL could technically be
15292 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15293 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15294 	 * to the same map).
15295 	 * However, if the old MAYBE_NULL register then got NULL checked,
15296 	 * doing so could have affected others with the same id, and we can't
15297 	 * check for that because we lost the id when we converted to
15298 	 * a non-MAYBE_NULL variant.
15299 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15300 	 * non-MAYBE_NULL registers as well.
15301 	 */
15302 	if (rold->type != rcur->type)
15303 		return false;
15304 
15305 	switch (base_type(rold->type)) {
15306 	case SCALAR_VALUE:
15307 		if (env->explore_alu_limits) {
15308 			/* explore_alu_limits disables tnum_in() and range_within()
15309 			 * logic and requires everything to be strict
15310 			 */
15311 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15312 			       check_scalar_ids(rold->id, rcur->id, idmap);
15313 		}
15314 		if (!rold->precise)
15315 			return true;
15316 		/* Why check_ids() for scalar registers?
15317 		 *
15318 		 * Consider the following BPF code:
15319 		 *   1: r6 = ... unbound scalar, ID=a ...
15320 		 *   2: r7 = ... unbound scalar, ID=b ...
15321 		 *   3: if (r6 > r7) goto +1
15322 		 *   4: r6 = r7
15323 		 *   5: if (r6 > X) goto ...
15324 		 *   6: ... memory operation using r7 ...
15325 		 *
15326 		 * First verification path is [1-6]:
15327 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15328 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15329 		 *   r7 <= X, because r6 and r7 share same id.
15330 		 * Next verification path is [1-4, 6].
15331 		 *
15332 		 * Instruction (6) would be reached in two states:
15333 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15334 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15335 		 *
15336 		 * Use check_ids() to distinguish these states.
15337 		 * ---
15338 		 * Also verify that new value satisfies old value range knowledge.
15339 		 */
15340 		return range_within(rold, rcur) &&
15341 		       tnum_in(rold->var_off, rcur->var_off) &&
15342 		       check_scalar_ids(rold->id, rcur->id, idmap);
15343 	case PTR_TO_MAP_KEY:
15344 	case PTR_TO_MAP_VALUE:
15345 	case PTR_TO_MEM:
15346 	case PTR_TO_BUF:
15347 	case PTR_TO_TP_BUFFER:
15348 		/* If the new min/max/var_off satisfy the old ones and
15349 		 * everything else matches, we are OK.
15350 		 */
15351 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15352 		       range_within(rold, rcur) &&
15353 		       tnum_in(rold->var_off, rcur->var_off) &&
15354 		       check_ids(rold->id, rcur->id, idmap) &&
15355 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15356 	case PTR_TO_PACKET_META:
15357 	case PTR_TO_PACKET:
15358 		/* We must have at least as much range as the old ptr
15359 		 * did, so that any accesses which were safe before are
15360 		 * still safe.  This is true even if old range < old off,
15361 		 * since someone could have accessed through (ptr - k), or
15362 		 * even done ptr -= k in a register, to get a safe access.
15363 		 */
15364 		if (rold->range > rcur->range)
15365 			return false;
15366 		/* If the offsets don't match, we can't trust our alignment;
15367 		 * nor can we be sure that we won't fall out of range.
15368 		 */
15369 		if (rold->off != rcur->off)
15370 			return false;
15371 		/* id relations must be preserved */
15372 		if (!check_ids(rold->id, rcur->id, idmap))
15373 			return false;
15374 		/* new val must satisfy old val knowledge */
15375 		return range_within(rold, rcur) &&
15376 		       tnum_in(rold->var_off, rcur->var_off);
15377 	case PTR_TO_STACK:
15378 		/* two stack pointers are equal only if they're pointing to
15379 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
15380 		 */
15381 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15382 	default:
15383 		return regs_exact(rold, rcur, idmap);
15384 	}
15385 }
15386 
15387 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15388 		      struct bpf_func_state *cur, struct bpf_idmap *idmap)
15389 {
15390 	int i, spi;
15391 
15392 	/* walk slots of the explored stack and ignore any additional
15393 	 * slots in the current stack, since explored(safe) state
15394 	 * didn't use them
15395 	 */
15396 	for (i = 0; i < old->allocated_stack; i++) {
15397 		struct bpf_reg_state *old_reg, *cur_reg;
15398 
15399 		spi = i / BPF_REG_SIZE;
15400 
15401 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15402 			i += BPF_REG_SIZE - 1;
15403 			/* explored state didn't use this */
15404 			continue;
15405 		}
15406 
15407 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15408 			continue;
15409 
15410 		if (env->allow_uninit_stack &&
15411 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15412 			continue;
15413 
15414 		/* explored stack has more populated slots than current stack
15415 		 * and these slots were used
15416 		 */
15417 		if (i >= cur->allocated_stack)
15418 			return false;
15419 
15420 		/* if old state was safe with misc data in the stack
15421 		 * it will be safe with zero-initialized stack.
15422 		 * The opposite is not true
15423 		 */
15424 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15425 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15426 			continue;
15427 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15428 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15429 			/* Ex: old explored (safe) state has STACK_SPILL in
15430 			 * this stack slot, but current has STACK_MISC ->
15431 			 * this verifier states are not equivalent,
15432 			 * return false to continue verification of this path
15433 			 */
15434 			return false;
15435 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15436 			continue;
15437 		/* Both old and cur are having same slot_type */
15438 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15439 		case STACK_SPILL:
15440 			/* when explored and current stack slot are both storing
15441 			 * spilled registers, check that stored pointers types
15442 			 * are the same as well.
15443 			 * Ex: explored safe path could have stored
15444 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15445 			 * but current path has stored:
15446 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15447 			 * such verifier states are not equivalent.
15448 			 * return false to continue verification of this path
15449 			 */
15450 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
15451 				     &cur->stack[spi].spilled_ptr, idmap))
15452 				return false;
15453 			break;
15454 		case STACK_DYNPTR:
15455 			old_reg = &old->stack[spi].spilled_ptr;
15456 			cur_reg = &cur->stack[spi].spilled_ptr;
15457 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15458 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15459 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15460 				return false;
15461 			break;
15462 		case STACK_ITER:
15463 			old_reg = &old->stack[spi].spilled_ptr;
15464 			cur_reg = &cur->stack[spi].spilled_ptr;
15465 			/* iter.depth is not compared between states as it
15466 			 * doesn't matter for correctness and would otherwise
15467 			 * prevent convergence; we maintain it only to prevent
15468 			 * infinite loop check triggering, see
15469 			 * iter_active_depths_differ()
15470 			 */
15471 			if (old_reg->iter.btf != cur_reg->iter.btf ||
15472 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15473 			    old_reg->iter.state != cur_reg->iter.state ||
15474 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
15475 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15476 				return false;
15477 			break;
15478 		case STACK_MISC:
15479 		case STACK_ZERO:
15480 		case STACK_INVALID:
15481 			continue;
15482 		/* Ensure that new unhandled slot types return false by default */
15483 		default:
15484 			return false;
15485 		}
15486 	}
15487 	return true;
15488 }
15489 
15490 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15491 		    struct bpf_idmap *idmap)
15492 {
15493 	int i;
15494 
15495 	if (old->acquired_refs != cur->acquired_refs)
15496 		return false;
15497 
15498 	for (i = 0; i < old->acquired_refs; i++) {
15499 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15500 			return false;
15501 	}
15502 
15503 	return true;
15504 }
15505 
15506 /* compare two verifier states
15507  *
15508  * all states stored in state_list are known to be valid, since
15509  * verifier reached 'bpf_exit' instruction through them
15510  *
15511  * this function is called when verifier exploring different branches of
15512  * execution popped from the state stack. If it sees an old state that has
15513  * more strict register state and more strict stack state then this execution
15514  * branch doesn't need to be explored further, since verifier already
15515  * concluded that more strict state leads to valid finish.
15516  *
15517  * Therefore two states are equivalent if register state is more conservative
15518  * and explored stack state is more conservative than the current one.
15519  * Example:
15520  *       explored                   current
15521  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15522  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15523  *
15524  * In other words if current stack state (one being explored) has more
15525  * valid slots than old one that already passed validation, it means
15526  * the verifier can stop exploring and conclude that current state is valid too
15527  *
15528  * Similarly with registers. If explored state has register type as invalid
15529  * whereas register type in current state is meaningful, it means that
15530  * the current state will reach 'bpf_exit' instruction safely
15531  */
15532 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15533 			      struct bpf_func_state *cur)
15534 {
15535 	int i;
15536 
15537 	for (i = 0; i < MAX_BPF_REG; i++)
15538 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
15539 			     &env->idmap_scratch))
15540 			return false;
15541 
15542 	if (!stacksafe(env, old, cur, &env->idmap_scratch))
15543 		return false;
15544 
15545 	if (!refsafe(old, cur, &env->idmap_scratch))
15546 		return false;
15547 
15548 	return true;
15549 }
15550 
15551 static bool states_equal(struct bpf_verifier_env *env,
15552 			 struct bpf_verifier_state *old,
15553 			 struct bpf_verifier_state *cur)
15554 {
15555 	int i;
15556 
15557 	if (old->curframe != cur->curframe)
15558 		return false;
15559 
15560 	env->idmap_scratch.tmp_id_gen = env->id_gen;
15561 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15562 
15563 	/* Verification state from speculative execution simulation
15564 	 * must never prune a non-speculative execution one.
15565 	 */
15566 	if (old->speculative && !cur->speculative)
15567 		return false;
15568 
15569 	if (old->active_lock.ptr != cur->active_lock.ptr)
15570 		return false;
15571 
15572 	/* Old and cur active_lock's have to be either both present
15573 	 * or both absent.
15574 	 */
15575 	if (!!old->active_lock.id != !!cur->active_lock.id)
15576 		return false;
15577 
15578 	if (old->active_lock.id &&
15579 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15580 		return false;
15581 
15582 	if (old->active_rcu_lock != cur->active_rcu_lock)
15583 		return false;
15584 
15585 	/* for states to be equal callsites have to be the same
15586 	 * and all frame states need to be equivalent
15587 	 */
15588 	for (i = 0; i <= old->curframe; i++) {
15589 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
15590 			return false;
15591 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15592 			return false;
15593 	}
15594 	return true;
15595 }
15596 
15597 /* Return 0 if no propagation happened. Return negative error code if error
15598  * happened. Otherwise, return the propagated bit.
15599  */
15600 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15601 				  struct bpf_reg_state *reg,
15602 				  struct bpf_reg_state *parent_reg)
15603 {
15604 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15605 	u8 flag = reg->live & REG_LIVE_READ;
15606 	int err;
15607 
15608 	/* When comes here, read flags of PARENT_REG or REG could be any of
15609 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15610 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15611 	 */
15612 	if (parent_flag == REG_LIVE_READ64 ||
15613 	    /* Or if there is no read flag from REG. */
15614 	    !flag ||
15615 	    /* Or if the read flag from REG is the same as PARENT_REG. */
15616 	    parent_flag == flag)
15617 		return 0;
15618 
15619 	err = mark_reg_read(env, reg, parent_reg, flag);
15620 	if (err)
15621 		return err;
15622 
15623 	return flag;
15624 }
15625 
15626 /* A write screens off any subsequent reads; but write marks come from the
15627  * straight-line code between a state and its parent.  When we arrive at an
15628  * equivalent state (jump target or such) we didn't arrive by the straight-line
15629  * code, so read marks in the state must propagate to the parent regardless
15630  * of the state's write marks. That's what 'parent == state->parent' comparison
15631  * in mark_reg_read() is for.
15632  */
15633 static int propagate_liveness(struct bpf_verifier_env *env,
15634 			      const struct bpf_verifier_state *vstate,
15635 			      struct bpf_verifier_state *vparent)
15636 {
15637 	struct bpf_reg_state *state_reg, *parent_reg;
15638 	struct bpf_func_state *state, *parent;
15639 	int i, frame, err = 0;
15640 
15641 	if (vparent->curframe != vstate->curframe) {
15642 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
15643 		     vparent->curframe, vstate->curframe);
15644 		return -EFAULT;
15645 	}
15646 	/* Propagate read liveness of registers... */
15647 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15648 	for (frame = 0; frame <= vstate->curframe; frame++) {
15649 		parent = vparent->frame[frame];
15650 		state = vstate->frame[frame];
15651 		parent_reg = parent->regs;
15652 		state_reg = state->regs;
15653 		/* We don't need to worry about FP liveness, it's read-only */
15654 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15655 			err = propagate_liveness_reg(env, &state_reg[i],
15656 						     &parent_reg[i]);
15657 			if (err < 0)
15658 				return err;
15659 			if (err == REG_LIVE_READ64)
15660 				mark_insn_zext(env, &parent_reg[i]);
15661 		}
15662 
15663 		/* Propagate stack slots. */
15664 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15665 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15666 			parent_reg = &parent->stack[i].spilled_ptr;
15667 			state_reg = &state->stack[i].spilled_ptr;
15668 			err = propagate_liveness_reg(env, state_reg,
15669 						     parent_reg);
15670 			if (err < 0)
15671 				return err;
15672 		}
15673 	}
15674 	return 0;
15675 }
15676 
15677 /* find precise scalars in the previous equivalent state and
15678  * propagate them into the current state
15679  */
15680 static int propagate_precision(struct bpf_verifier_env *env,
15681 			       const struct bpf_verifier_state *old)
15682 {
15683 	struct bpf_reg_state *state_reg;
15684 	struct bpf_func_state *state;
15685 	int i, err = 0, fr;
15686 	bool first;
15687 
15688 	for (fr = old->curframe; fr >= 0; fr--) {
15689 		state = old->frame[fr];
15690 		state_reg = state->regs;
15691 		first = true;
15692 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15693 			if (state_reg->type != SCALAR_VALUE ||
15694 			    !state_reg->precise ||
15695 			    !(state_reg->live & REG_LIVE_READ))
15696 				continue;
15697 			if (env->log.level & BPF_LOG_LEVEL2) {
15698 				if (first)
15699 					verbose(env, "frame %d: propagating r%d", fr, i);
15700 				else
15701 					verbose(env, ",r%d", i);
15702 			}
15703 			bt_set_frame_reg(&env->bt, fr, i);
15704 			first = false;
15705 		}
15706 
15707 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15708 			if (!is_spilled_reg(&state->stack[i]))
15709 				continue;
15710 			state_reg = &state->stack[i].spilled_ptr;
15711 			if (state_reg->type != SCALAR_VALUE ||
15712 			    !state_reg->precise ||
15713 			    !(state_reg->live & REG_LIVE_READ))
15714 				continue;
15715 			if (env->log.level & BPF_LOG_LEVEL2) {
15716 				if (first)
15717 					verbose(env, "frame %d: propagating fp%d",
15718 						fr, (-i - 1) * BPF_REG_SIZE);
15719 				else
15720 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15721 			}
15722 			bt_set_frame_slot(&env->bt, fr, i);
15723 			first = false;
15724 		}
15725 		if (!first)
15726 			verbose(env, "\n");
15727 	}
15728 
15729 	err = mark_chain_precision_batch(env);
15730 	if (err < 0)
15731 		return err;
15732 
15733 	return 0;
15734 }
15735 
15736 static bool states_maybe_looping(struct bpf_verifier_state *old,
15737 				 struct bpf_verifier_state *cur)
15738 {
15739 	struct bpf_func_state *fold, *fcur;
15740 	int i, fr = cur->curframe;
15741 
15742 	if (old->curframe != fr)
15743 		return false;
15744 
15745 	fold = old->frame[fr];
15746 	fcur = cur->frame[fr];
15747 	for (i = 0; i < MAX_BPF_REG; i++)
15748 		if (memcmp(&fold->regs[i], &fcur->regs[i],
15749 			   offsetof(struct bpf_reg_state, parent)))
15750 			return false;
15751 	return true;
15752 }
15753 
15754 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15755 {
15756 	return env->insn_aux_data[insn_idx].is_iter_next;
15757 }
15758 
15759 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15760  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15761  * states to match, which otherwise would look like an infinite loop. So while
15762  * iter_next() calls are taken care of, we still need to be careful and
15763  * prevent erroneous and too eager declaration of "ininite loop", when
15764  * iterators are involved.
15765  *
15766  * Here's a situation in pseudo-BPF assembly form:
15767  *
15768  *   0: again:                          ; set up iter_next() call args
15769  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15770  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15771  *   3:   if r0 == 0 goto done
15772  *   4:   ... something useful here ...
15773  *   5:   goto again                    ; another iteration
15774  *   6: done:
15775  *   7:   r1 = &it
15776  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15777  *   9:   exit
15778  *
15779  * This is a typical loop. Let's assume that we have a prune point at 1:,
15780  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15781  * again`, assuming other heuristics don't get in a way).
15782  *
15783  * When we first time come to 1:, let's say we have some state X. We proceed
15784  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15785  * Now we come back to validate that forked ACTIVE state. We proceed through
15786  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15787  * are converging. But the problem is that we don't know that yet, as this
15788  * convergence has to happen at iter_next() call site only. So if nothing is
15789  * done, at 1: verifier will use bounded loop logic and declare infinite
15790  * looping (and would be *technically* correct, if not for iterator's
15791  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15792  * don't want that. So what we do in process_iter_next_call() when we go on
15793  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15794  * a different iteration. So when we suspect an infinite loop, we additionally
15795  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15796  * pretend we are not looping and wait for next iter_next() call.
15797  *
15798  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15799  * loop, because that would actually mean infinite loop, as DRAINED state is
15800  * "sticky", and so we'll keep returning into the same instruction with the
15801  * same state (at least in one of possible code paths).
15802  *
15803  * This approach allows to keep infinite loop heuristic even in the face of
15804  * active iterator. E.g., C snippet below is and will be detected as
15805  * inifintely looping:
15806  *
15807  *   struct bpf_iter_num it;
15808  *   int *p, x;
15809  *
15810  *   bpf_iter_num_new(&it, 0, 10);
15811  *   while ((p = bpf_iter_num_next(&t))) {
15812  *       x = p;
15813  *       while (x--) {} // <<-- infinite loop here
15814  *   }
15815  *
15816  */
15817 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15818 {
15819 	struct bpf_reg_state *slot, *cur_slot;
15820 	struct bpf_func_state *state;
15821 	int i, fr;
15822 
15823 	for (fr = old->curframe; fr >= 0; fr--) {
15824 		state = old->frame[fr];
15825 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15826 			if (state->stack[i].slot_type[0] != STACK_ITER)
15827 				continue;
15828 
15829 			slot = &state->stack[i].spilled_ptr;
15830 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15831 				continue;
15832 
15833 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15834 			if (cur_slot->iter.depth != slot->iter.depth)
15835 				return true;
15836 		}
15837 	}
15838 	return false;
15839 }
15840 
15841 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15842 {
15843 	struct bpf_verifier_state_list *new_sl;
15844 	struct bpf_verifier_state_list *sl, **pprev;
15845 	struct bpf_verifier_state *cur = env->cur_state, *new;
15846 	int i, j, err, states_cnt = 0;
15847 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15848 	bool add_new_state = force_new_state;
15849 
15850 	/* bpf progs typically have pruning point every 4 instructions
15851 	 * http://vger.kernel.org/bpfconf2019.html#session-1
15852 	 * Do not add new state for future pruning if the verifier hasn't seen
15853 	 * at least 2 jumps and at least 8 instructions.
15854 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15855 	 * In tests that amounts to up to 50% reduction into total verifier
15856 	 * memory consumption and 20% verifier time speedup.
15857 	 */
15858 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15859 	    env->insn_processed - env->prev_insn_processed >= 8)
15860 		add_new_state = true;
15861 
15862 	pprev = explored_state(env, insn_idx);
15863 	sl = *pprev;
15864 
15865 	clean_live_states(env, insn_idx, cur);
15866 
15867 	while (sl) {
15868 		states_cnt++;
15869 		if (sl->state.insn_idx != insn_idx)
15870 			goto next;
15871 
15872 		if (sl->state.branches) {
15873 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15874 
15875 			if (frame->in_async_callback_fn &&
15876 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15877 				/* Different async_entry_cnt means that the verifier is
15878 				 * processing another entry into async callback.
15879 				 * Seeing the same state is not an indication of infinite
15880 				 * loop or infinite recursion.
15881 				 * But finding the same state doesn't mean that it's safe
15882 				 * to stop processing the current state. The previous state
15883 				 * hasn't yet reached bpf_exit, since state.branches > 0.
15884 				 * Checking in_async_callback_fn alone is not enough either.
15885 				 * Since the verifier still needs to catch infinite loops
15886 				 * inside async callbacks.
15887 				 */
15888 				goto skip_inf_loop_check;
15889 			}
15890 			/* BPF open-coded iterators loop detection is special.
15891 			 * states_maybe_looping() logic is too simplistic in detecting
15892 			 * states that *might* be equivalent, because it doesn't know
15893 			 * about ID remapping, so don't even perform it.
15894 			 * See process_iter_next_call() and iter_active_depths_differ()
15895 			 * for overview of the logic. When current and one of parent
15896 			 * states are detected as equivalent, it's a good thing: we prove
15897 			 * convergence and can stop simulating further iterations.
15898 			 * It's safe to assume that iterator loop will finish, taking into
15899 			 * account iter_next() contract of eventually returning
15900 			 * sticky NULL result.
15901 			 */
15902 			if (is_iter_next_insn(env, insn_idx)) {
15903 				if (states_equal(env, &sl->state, cur)) {
15904 					struct bpf_func_state *cur_frame;
15905 					struct bpf_reg_state *iter_state, *iter_reg;
15906 					int spi;
15907 
15908 					cur_frame = cur->frame[cur->curframe];
15909 					/* btf_check_iter_kfuncs() enforces that
15910 					 * iter state pointer is always the first arg
15911 					 */
15912 					iter_reg = &cur_frame->regs[BPF_REG_1];
15913 					/* current state is valid due to states_equal(),
15914 					 * so we can assume valid iter and reg state,
15915 					 * no need for extra (re-)validations
15916 					 */
15917 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15918 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15919 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15920 						goto hit;
15921 				}
15922 				goto skip_inf_loop_check;
15923 			}
15924 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
15925 			if (states_maybe_looping(&sl->state, cur) &&
15926 			    states_equal(env, &sl->state, cur) &&
15927 			    !iter_active_depths_differ(&sl->state, cur)) {
15928 				verbose_linfo(env, insn_idx, "; ");
15929 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15930 				return -EINVAL;
15931 			}
15932 			/* if the verifier is processing a loop, avoid adding new state
15933 			 * too often, since different loop iterations have distinct
15934 			 * states and may not help future pruning.
15935 			 * This threshold shouldn't be too low to make sure that
15936 			 * a loop with large bound will be rejected quickly.
15937 			 * The most abusive loop will be:
15938 			 * r1 += 1
15939 			 * if r1 < 1000000 goto pc-2
15940 			 * 1M insn_procssed limit / 100 == 10k peak states.
15941 			 * This threshold shouldn't be too high either, since states
15942 			 * at the end of the loop are likely to be useful in pruning.
15943 			 */
15944 skip_inf_loop_check:
15945 			if (!force_new_state &&
15946 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
15947 			    env->insn_processed - env->prev_insn_processed < 100)
15948 				add_new_state = false;
15949 			goto miss;
15950 		}
15951 		if (states_equal(env, &sl->state, cur)) {
15952 hit:
15953 			sl->hit_cnt++;
15954 			/* reached equivalent register/stack state,
15955 			 * prune the search.
15956 			 * Registers read by the continuation are read by us.
15957 			 * If we have any write marks in env->cur_state, they
15958 			 * will prevent corresponding reads in the continuation
15959 			 * from reaching our parent (an explored_state).  Our
15960 			 * own state will get the read marks recorded, but
15961 			 * they'll be immediately forgotten as we're pruning
15962 			 * this state and will pop a new one.
15963 			 */
15964 			err = propagate_liveness(env, &sl->state, cur);
15965 
15966 			/* if previous state reached the exit with precision and
15967 			 * current state is equivalent to it (except precsion marks)
15968 			 * the precision needs to be propagated back in
15969 			 * the current state.
15970 			 */
15971 			err = err ? : push_jmp_history(env, cur);
15972 			err = err ? : propagate_precision(env, &sl->state);
15973 			if (err)
15974 				return err;
15975 			return 1;
15976 		}
15977 miss:
15978 		/* when new state is not going to be added do not increase miss count.
15979 		 * Otherwise several loop iterations will remove the state
15980 		 * recorded earlier. The goal of these heuristics is to have
15981 		 * states from some iterations of the loop (some in the beginning
15982 		 * and some at the end) to help pruning.
15983 		 */
15984 		if (add_new_state)
15985 			sl->miss_cnt++;
15986 		/* heuristic to determine whether this state is beneficial
15987 		 * to keep checking from state equivalence point of view.
15988 		 * Higher numbers increase max_states_per_insn and verification time,
15989 		 * but do not meaningfully decrease insn_processed.
15990 		 */
15991 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15992 			/* the state is unlikely to be useful. Remove it to
15993 			 * speed up verification
15994 			 */
15995 			*pprev = sl->next;
15996 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15997 				u32 br = sl->state.branches;
15998 
15999 				WARN_ONCE(br,
16000 					  "BUG live_done but branches_to_explore %d\n",
16001 					  br);
16002 				free_verifier_state(&sl->state, false);
16003 				kfree(sl);
16004 				env->peak_states--;
16005 			} else {
16006 				/* cannot free this state, since parentage chain may
16007 				 * walk it later. Add it for free_list instead to
16008 				 * be freed at the end of verification
16009 				 */
16010 				sl->next = env->free_list;
16011 				env->free_list = sl;
16012 			}
16013 			sl = *pprev;
16014 			continue;
16015 		}
16016 next:
16017 		pprev = &sl->next;
16018 		sl = *pprev;
16019 	}
16020 
16021 	if (env->max_states_per_insn < states_cnt)
16022 		env->max_states_per_insn = states_cnt;
16023 
16024 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16025 		return 0;
16026 
16027 	if (!add_new_state)
16028 		return 0;
16029 
16030 	/* There were no equivalent states, remember the current one.
16031 	 * Technically the current state is not proven to be safe yet,
16032 	 * but it will either reach outer most bpf_exit (which means it's safe)
16033 	 * or it will be rejected. When there are no loops the verifier won't be
16034 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16035 	 * again on the way to bpf_exit.
16036 	 * When looping the sl->state.branches will be > 0 and this state
16037 	 * will not be considered for equivalence until branches == 0.
16038 	 */
16039 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16040 	if (!new_sl)
16041 		return -ENOMEM;
16042 	env->total_states++;
16043 	env->peak_states++;
16044 	env->prev_jmps_processed = env->jmps_processed;
16045 	env->prev_insn_processed = env->insn_processed;
16046 
16047 	/* forget precise markings we inherited, see __mark_chain_precision */
16048 	if (env->bpf_capable)
16049 		mark_all_scalars_imprecise(env, cur);
16050 
16051 	/* add new state to the head of linked list */
16052 	new = &new_sl->state;
16053 	err = copy_verifier_state(new, cur);
16054 	if (err) {
16055 		free_verifier_state(new, false);
16056 		kfree(new_sl);
16057 		return err;
16058 	}
16059 	new->insn_idx = insn_idx;
16060 	WARN_ONCE(new->branches != 1,
16061 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16062 
16063 	cur->parent = new;
16064 	cur->first_insn_idx = insn_idx;
16065 	clear_jmp_history(cur);
16066 	new_sl->next = *explored_state(env, insn_idx);
16067 	*explored_state(env, insn_idx) = new_sl;
16068 	/* connect new state to parentage chain. Current frame needs all
16069 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16070 	 * to the stack implicitly by JITs) so in callers' frames connect just
16071 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16072 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16073 	 * from callee with its full parentage chain, anyway.
16074 	 */
16075 	/* clear write marks in current state: the writes we did are not writes
16076 	 * our child did, so they don't screen off its reads from us.
16077 	 * (There are no read marks in current state, because reads always mark
16078 	 * their parent and current state never has children yet.  Only
16079 	 * explored_states can get read marks.)
16080 	 */
16081 	for (j = 0; j <= cur->curframe; j++) {
16082 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16083 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16084 		for (i = 0; i < BPF_REG_FP; i++)
16085 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16086 	}
16087 
16088 	/* all stack frames are accessible from callee, clear them all */
16089 	for (j = 0; j <= cur->curframe; j++) {
16090 		struct bpf_func_state *frame = cur->frame[j];
16091 		struct bpf_func_state *newframe = new->frame[j];
16092 
16093 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16094 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16095 			frame->stack[i].spilled_ptr.parent =
16096 						&newframe->stack[i].spilled_ptr;
16097 		}
16098 	}
16099 	return 0;
16100 }
16101 
16102 /* Return true if it's OK to have the same insn return a different type. */
16103 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16104 {
16105 	switch (base_type(type)) {
16106 	case PTR_TO_CTX:
16107 	case PTR_TO_SOCKET:
16108 	case PTR_TO_SOCK_COMMON:
16109 	case PTR_TO_TCP_SOCK:
16110 	case PTR_TO_XDP_SOCK:
16111 	case PTR_TO_BTF_ID:
16112 		return false;
16113 	default:
16114 		return true;
16115 	}
16116 }
16117 
16118 /* If an instruction was previously used with particular pointer types, then we
16119  * need to be careful to avoid cases such as the below, where it may be ok
16120  * for one branch accessing the pointer, but not ok for the other branch:
16121  *
16122  * R1 = sock_ptr
16123  * goto X;
16124  * ...
16125  * R1 = some_other_valid_ptr;
16126  * goto X;
16127  * ...
16128  * R2 = *(u32 *)(R1 + 0);
16129  */
16130 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16131 {
16132 	return src != prev && (!reg_type_mismatch_ok(src) ||
16133 			       !reg_type_mismatch_ok(prev));
16134 }
16135 
16136 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16137 			     bool allow_trust_missmatch)
16138 {
16139 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16140 
16141 	if (*prev_type == NOT_INIT) {
16142 		/* Saw a valid insn
16143 		 * dst_reg = *(u32 *)(src_reg + off)
16144 		 * save type to validate intersecting paths
16145 		 */
16146 		*prev_type = type;
16147 	} else if (reg_type_mismatch(type, *prev_type)) {
16148 		/* Abuser program is trying to use the same insn
16149 		 * dst_reg = *(u32*) (src_reg + off)
16150 		 * with different pointer types:
16151 		 * src_reg == ctx in one branch and
16152 		 * src_reg == stack|map in some other branch.
16153 		 * Reject it.
16154 		 */
16155 		if (allow_trust_missmatch &&
16156 		    base_type(type) == PTR_TO_BTF_ID &&
16157 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16158 			/*
16159 			 * Have to support a use case when one path through
16160 			 * the program yields TRUSTED pointer while another
16161 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16162 			 * BPF_PROBE_MEM.
16163 			 */
16164 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16165 		} else {
16166 			verbose(env, "same insn cannot be used with different pointers\n");
16167 			return -EINVAL;
16168 		}
16169 	}
16170 
16171 	return 0;
16172 }
16173 
16174 static int do_check(struct bpf_verifier_env *env)
16175 {
16176 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16177 	struct bpf_verifier_state *state = env->cur_state;
16178 	struct bpf_insn *insns = env->prog->insnsi;
16179 	struct bpf_reg_state *regs;
16180 	int insn_cnt = env->prog->len;
16181 	bool do_print_state = false;
16182 	int prev_insn_idx = -1;
16183 
16184 	for (;;) {
16185 		struct bpf_insn *insn;
16186 		u8 class;
16187 		int err;
16188 
16189 		env->prev_insn_idx = prev_insn_idx;
16190 		if (env->insn_idx >= insn_cnt) {
16191 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16192 				env->insn_idx, insn_cnt);
16193 			return -EFAULT;
16194 		}
16195 
16196 		insn = &insns[env->insn_idx];
16197 		class = BPF_CLASS(insn->code);
16198 
16199 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16200 			verbose(env,
16201 				"BPF program is too large. Processed %d insn\n",
16202 				env->insn_processed);
16203 			return -E2BIG;
16204 		}
16205 
16206 		state->last_insn_idx = env->prev_insn_idx;
16207 
16208 		if (is_prune_point(env, env->insn_idx)) {
16209 			err = is_state_visited(env, env->insn_idx);
16210 			if (err < 0)
16211 				return err;
16212 			if (err == 1) {
16213 				/* found equivalent state, can prune the search */
16214 				if (env->log.level & BPF_LOG_LEVEL) {
16215 					if (do_print_state)
16216 						verbose(env, "\nfrom %d to %d%s: safe\n",
16217 							env->prev_insn_idx, env->insn_idx,
16218 							env->cur_state->speculative ?
16219 							" (speculative execution)" : "");
16220 					else
16221 						verbose(env, "%d: safe\n", env->insn_idx);
16222 				}
16223 				goto process_bpf_exit;
16224 			}
16225 		}
16226 
16227 		if (is_jmp_point(env, env->insn_idx)) {
16228 			err = push_jmp_history(env, state);
16229 			if (err)
16230 				return err;
16231 		}
16232 
16233 		if (signal_pending(current))
16234 			return -EAGAIN;
16235 
16236 		if (need_resched())
16237 			cond_resched();
16238 
16239 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16240 			verbose(env, "\nfrom %d to %d%s:",
16241 				env->prev_insn_idx, env->insn_idx,
16242 				env->cur_state->speculative ?
16243 				" (speculative execution)" : "");
16244 			print_verifier_state(env, state->frame[state->curframe], true);
16245 			do_print_state = false;
16246 		}
16247 
16248 		if (env->log.level & BPF_LOG_LEVEL) {
16249 			const struct bpf_insn_cbs cbs = {
16250 				.cb_call	= disasm_kfunc_name,
16251 				.cb_print	= verbose,
16252 				.private_data	= env,
16253 			};
16254 
16255 			if (verifier_state_scratched(env))
16256 				print_insn_state(env, state->frame[state->curframe]);
16257 
16258 			verbose_linfo(env, env->insn_idx, "; ");
16259 			env->prev_log_pos = env->log.end_pos;
16260 			verbose(env, "%d: ", env->insn_idx);
16261 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16262 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16263 			env->prev_log_pos = env->log.end_pos;
16264 		}
16265 
16266 		if (bpf_prog_is_offloaded(env->prog->aux)) {
16267 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16268 							   env->prev_insn_idx);
16269 			if (err)
16270 				return err;
16271 		}
16272 
16273 		regs = cur_regs(env);
16274 		sanitize_mark_insn_seen(env);
16275 		prev_insn_idx = env->insn_idx;
16276 
16277 		if (class == BPF_ALU || class == BPF_ALU64) {
16278 			err = check_alu_op(env, insn);
16279 			if (err)
16280 				return err;
16281 
16282 		} else if (class == BPF_LDX) {
16283 			enum bpf_reg_type src_reg_type;
16284 
16285 			/* check for reserved fields is already done */
16286 
16287 			/* check src operand */
16288 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16289 			if (err)
16290 				return err;
16291 
16292 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16293 			if (err)
16294 				return err;
16295 
16296 			src_reg_type = regs[insn->src_reg].type;
16297 
16298 			/* check that memory (src_reg + off) is readable,
16299 			 * the state of dst_reg will be updated by this func
16300 			 */
16301 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
16302 					       insn->off, BPF_SIZE(insn->code),
16303 					       BPF_READ, insn->dst_reg, false);
16304 			if (err)
16305 				return err;
16306 
16307 			err = save_aux_ptr_type(env, src_reg_type, true);
16308 			if (err)
16309 				return err;
16310 		} else if (class == BPF_STX) {
16311 			enum bpf_reg_type dst_reg_type;
16312 
16313 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16314 				err = check_atomic(env, env->insn_idx, insn);
16315 				if (err)
16316 					return err;
16317 				env->insn_idx++;
16318 				continue;
16319 			}
16320 
16321 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16322 				verbose(env, "BPF_STX uses reserved fields\n");
16323 				return -EINVAL;
16324 			}
16325 
16326 			/* check src1 operand */
16327 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16328 			if (err)
16329 				return err;
16330 			/* check src2 operand */
16331 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16332 			if (err)
16333 				return err;
16334 
16335 			dst_reg_type = regs[insn->dst_reg].type;
16336 
16337 			/* check that memory (dst_reg + off) is writeable */
16338 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16339 					       insn->off, BPF_SIZE(insn->code),
16340 					       BPF_WRITE, insn->src_reg, false);
16341 			if (err)
16342 				return err;
16343 
16344 			err = save_aux_ptr_type(env, dst_reg_type, false);
16345 			if (err)
16346 				return err;
16347 		} else if (class == BPF_ST) {
16348 			enum bpf_reg_type dst_reg_type;
16349 
16350 			if (BPF_MODE(insn->code) != BPF_MEM ||
16351 			    insn->src_reg != BPF_REG_0) {
16352 				verbose(env, "BPF_ST uses reserved fields\n");
16353 				return -EINVAL;
16354 			}
16355 			/* check src operand */
16356 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16357 			if (err)
16358 				return err;
16359 
16360 			dst_reg_type = regs[insn->dst_reg].type;
16361 
16362 			/* check that memory (dst_reg + off) is writeable */
16363 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16364 					       insn->off, BPF_SIZE(insn->code),
16365 					       BPF_WRITE, -1, false);
16366 			if (err)
16367 				return err;
16368 
16369 			err = save_aux_ptr_type(env, dst_reg_type, false);
16370 			if (err)
16371 				return err;
16372 		} else if (class == BPF_JMP || class == BPF_JMP32) {
16373 			u8 opcode = BPF_OP(insn->code);
16374 
16375 			env->jmps_processed++;
16376 			if (opcode == BPF_CALL) {
16377 				if (BPF_SRC(insn->code) != BPF_K ||
16378 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16379 				     && insn->off != 0) ||
16380 				    (insn->src_reg != BPF_REG_0 &&
16381 				     insn->src_reg != BPF_PSEUDO_CALL &&
16382 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16383 				    insn->dst_reg != BPF_REG_0 ||
16384 				    class == BPF_JMP32) {
16385 					verbose(env, "BPF_CALL uses reserved fields\n");
16386 					return -EINVAL;
16387 				}
16388 
16389 				if (env->cur_state->active_lock.ptr) {
16390 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16391 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
16392 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16393 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16394 						verbose(env, "function calls are not allowed while holding a lock\n");
16395 						return -EINVAL;
16396 					}
16397 				}
16398 				if (insn->src_reg == BPF_PSEUDO_CALL)
16399 					err = check_func_call(env, insn, &env->insn_idx);
16400 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16401 					err = check_kfunc_call(env, insn, &env->insn_idx);
16402 				else
16403 					err = check_helper_call(env, insn, &env->insn_idx);
16404 				if (err)
16405 					return err;
16406 
16407 				mark_reg_scratched(env, BPF_REG_0);
16408 			} else if (opcode == BPF_JA) {
16409 				if (BPF_SRC(insn->code) != BPF_K ||
16410 				    insn->imm != 0 ||
16411 				    insn->src_reg != BPF_REG_0 ||
16412 				    insn->dst_reg != BPF_REG_0 ||
16413 				    class == BPF_JMP32) {
16414 					verbose(env, "BPF_JA uses reserved fields\n");
16415 					return -EINVAL;
16416 				}
16417 
16418 				env->insn_idx += insn->off + 1;
16419 				continue;
16420 
16421 			} else if (opcode == BPF_EXIT) {
16422 				if (BPF_SRC(insn->code) != BPF_K ||
16423 				    insn->imm != 0 ||
16424 				    insn->src_reg != BPF_REG_0 ||
16425 				    insn->dst_reg != BPF_REG_0 ||
16426 				    class == BPF_JMP32) {
16427 					verbose(env, "BPF_EXIT uses reserved fields\n");
16428 					return -EINVAL;
16429 				}
16430 
16431 				if (env->cur_state->active_lock.ptr &&
16432 				    !in_rbtree_lock_required_cb(env)) {
16433 					verbose(env, "bpf_spin_unlock is missing\n");
16434 					return -EINVAL;
16435 				}
16436 
16437 				if (env->cur_state->active_rcu_lock) {
16438 					verbose(env, "bpf_rcu_read_unlock is missing\n");
16439 					return -EINVAL;
16440 				}
16441 
16442 				/* We must do check_reference_leak here before
16443 				 * prepare_func_exit to handle the case when
16444 				 * state->curframe > 0, it may be a callback
16445 				 * function, for which reference_state must
16446 				 * match caller reference state when it exits.
16447 				 */
16448 				err = check_reference_leak(env);
16449 				if (err)
16450 					return err;
16451 
16452 				if (state->curframe) {
16453 					/* exit from nested function */
16454 					err = prepare_func_exit(env, &env->insn_idx);
16455 					if (err)
16456 						return err;
16457 					do_print_state = true;
16458 					continue;
16459 				}
16460 
16461 				err = check_return_code(env);
16462 				if (err)
16463 					return err;
16464 process_bpf_exit:
16465 				mark_verifier_state_scratched(env);
16466 				update_branch_counts(env, env->cur_state);
16467 				err = pop_stack(env, &prev_insn_idx,
16468 						&env->insn_idx, pop_log);
16469 				if (err < 0) {
16470 					if (err != -ENOENT)
16471 						return err;
16472 					break;
16473 				} else {
16474 					do_print_state = true;
16475 					continue;
16476 				}
16477 			} else {
16478 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
16479 				if (err)
16480 					return err;
16481 			}
16482 		} else if (class == BPF_LD) {
16483 			u8 mode = BPF_MODE(insn->code);
16484 
16485 			if (mode == BPF_ABS || mode == BPF_IND) {
16486 				err = check_ld_abs(env, insn);
16487 				if (err)
16488 					return err;
16489 
16490 			} else if (mode == BPF_IMM) {
16491 				err = check_ld_imm(env, insn);
16492 				if (err)
16493 					return err;
16494 
16495 				env->insn_idx++;
16496 				sanitize_mark_insn_seen(env);
16497 			} else {
16498 				verbose(env, "invalid BPF_LD mode\n");
16499 				return -EINVAL;
16500 			}
16501 		} else {
16502 			verbose(env, "unknown insn class %d\n", class);
16503 			return -EINVAL;
16504 		}
16505 
16506 		env->insn_idx++;
16507 	}
16508 
16509 	return 0;
16510 }
16511 
16512 static int find_btf_percpu_datasec(struct btf *btf)
16513 {
16514 	const struct btf_type *t;
16515 	const char *tname;
16516 	int i, n;
16517 
16518 	/*
16519 	 * Both vmlinux and module each have their own ".data..percpu"
16520 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16521 	 * types to look at only module's own BTF types.
16522 	 */
16523 	n = btf_nr_types(btf);
16524 	if (btf_is_module(btf))
16525 		i = btf_nr_types(btf_vmlinux);
16526 	else
16527 		i = 1;
16528 
16529 	for(; i < n; i++) {
16530 		t = btf_type_by_id(btf, i);
16531 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16532 			continue;
16533 
16534 		tname = btf_name_by_offset(btf, t->name_off);
16535 		if (!strcmp(tname, ".data..percpu"))
16536 			return i;
16537 	}
16538 
16539 	return -ENOENT;
16540 }
16541 
16542 /* replace pseudo btf_id with kernel symbol address */
16543 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16544 			       struct bpf_insn *insn,
16545 			       struct bpf_insn_aux_data *aux)
16546 {
16547 	const struct btf_var_secinfo *vsi;
16548 	const struct btf_type *datasec;
16549 	struct btf_mod_pair *btf_mod;
16550 	const struct btf_type *t;
16551 	const char *sym_name;
16552 	bool percpu = false;
16553 	u32 type, id = insn->imm;
16554 	struct btf *btf;
16555 	s32 datasec_id;
16556 	u64 addr;
16557 	int i, btf_fd, err;
16558 
16559 	btf_fd = insn[1].imm;
16560 	if (btf_fd) {
16561 		btf = btf_get_by_fd(btf_fd);
16562 		if (IS_ERR(btf)) {
16563 			verbose(env, "invalid module BTF object FD specified.\n");
16564 			return -EINVAL;
16565 		}
16566 	} else {
16567 		if (!btf_vmlinux) {
16568 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16569 			return -EINVAL;
16570 		}
16571 		btf = btf_vmlinux;
16572 		btf_get(btf);
16573 	}
16574 
16575 	t = btf_type_by_id(btf, id);
16576 	if (!t) {
16577 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16578 		err = -ENOENT;
16579 		goto err_put;
16580 	}
16581 
16582 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16583 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16584 		err = -EINVAL;
16585 		goto err_put;
16586 	}
16587 
16588 	sym_name = btf_name_by_offset(btf, t->name_off);
16589 	addr = kallsyms_lookup_name(sym_name);
16590 	if (!addr) {
16591 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16592 			sym_name);
16593 		err = -ENOENT;
16594 		goto err_put;
16595 	}
16596 	insn[0].imm = (u32)addr;
16597 	insn[1].imm = addr >> 32;
16598 
16599 	if (btf_type_is_func(t)) {
16600 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16601 		aux->btf_var.mem_size = 0;
16602 		goto check_btf;
16603 	}
16604 
16605 	datasec_id = find_btf_percpu_datasec(btf);
16606 	if (datasec_id > 0) {
16607 		datasec = btf_type_by_id(btf, datasec_id);
16608 		for_each_vsi(i, datasec, vsi) {
16609 			if (vsi->type == id) {
16610 				percpu = true;
16611 				break;
16612 			}
16613 		}
16614 	}
16615 
16616 	type = t->type;
16617 	t = btf_type_skip_modifiers(btf, type, NULL);
16618 	if (percpu) {
16619 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16620 		aux->btf_var.btf = btf;
16621 		aux->btf_var.btf_id = type;
16622 	} else if (!btf_type_is_struct(t)) {
16623 		const struct btf_type *ret;
16624 		const char *tname;
16625 		u32 tsize;
16626 
16627 		/* resolve the type size of ksym. */
16628 		ret = btf_resolve_size(btf, t, &tsize);
16629 		if (IS_ERR(ret)) {
16630 			tname = btf_name_by_offset(btf, t->name_off);
16631 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16632 				tname, PTR_ERR(ret));
16633 			err = -EINVAL;
16634 			goto err_put;
16635 		}
16636 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16637 		aux->btf_var.mem_size = tsize;
16638 	} else {
16639 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
16640 		aux->btf_var.btf = btf;
16641 		aux->btf_var.btf_id = type;
16642 	}
16643 check_btf:
16644 	/* check whether we recorded this BTF (and maybe module) already */
16645 	for (i = 0; i < env->used_btf_cnt; i++) {
16646 		if (env->used_btfs[i].btf == btf) {
16647 			btf_put(btf);
16648 			return 0;
16649 		}
16650 	}
16651 
16652 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
16653 		err = -E2BIG;
16654 		goto err_put;
16655 	}
16656 
16657 	btf_mod = &env->used_btfs[env->used_btf_cnt];
16658 	btf_mod->btf = btf;
16659 	btf_mod->module = NULL;
16660 
16661 	/* if we reference variables from kernel module, bump its refcount */
16662 	if (btf_is_module(btf)) {
16663 		btf_mod->module = btf_try_get_module(btf);
16664 		if (!btf_mod->module) {
16665 			err = -ENXIO;
16666 			goto err_put;
16667 		}
16668 	}
16669 
16670 	env->used_btf_cnt++;
16671 
16672 	return 0;
16673 err_put:
16674 	btf_put(btf);
16675 	return err;
16676 }
16677 
16678 static bool is_tracing_prog_type(enum bpf_prog_type type)
16679 {
16680 	switch (type) {
16681 	case BPF_PROG_TYPE_KPROBE:
16682 	case BPF_PROG_TYPE_TRACEPOINT:
16683 	case BPF_PROG_TYPE_PERF_EVENT:
16684 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16685 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16686 		return true;
16687 	default:
16688 		return false;
16689 	}
16690 }
16691 
16692 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16693 					struct bpf_map *map,
16694 					struct bpf_prog *prog)
16695 
16696 {
16697 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16698 
16699 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16700 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
16701 		if (is_tracing_prog_type(prog_type)) {
16702 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16703 			return -EINVAL;
16704 		}
16705 	}
16706 
16707 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16708 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16709 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16710 			return -EINVAL;
16711 		}
16712 
16713 		if (is_tracing_prog_type(prog_type)) {
16714 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16715 			return -EINVAL;
16716 		}
16717 
16718 		if (prog->aux->sleepable) {
16719 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16720 			return -EINVAL;
16721 		}
16722 	}
16723 
16724 	if (btf_record_has_field(map->record, BPF_TIMER)) {
16725 		if (is_tracing_prog_type(prog_type)) {
16726 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
16727 			return -EINVAL;
16728 		}
16729 	}
16730 
16731 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16732 	    !bpf_offload_prog_map_match(prog, map)) {
16733 		verbose(env, "offload device mismatch between prog and map\n");
16734 		return -EINVAL;
16735 	}
16736 
16737 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16738 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16739 		return -EINVAL;
16740 	}
16741 
16742 	if (prog->aux->sleepable)
16743 		switch (map->map_type) {
16744 		case BPF_MAP_TYPE_HASH:
16745 		case BPF_MAP_TYPE_LRU_HASH:
16746 		case BPF_MAP_TYPE_ARRAY:
16747 		case BPF_MAP_TYPE_PERCPU_HASH:
16748 		case BPF_MAP_TYPE_PERCPU_ARRAY:
16749 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16750 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16751 		case BPF_MAP_TYPE_HASH_OF_MAPS:
16752 		case BPF_MAP_TYPE_RINGBUF:
16753 		case BPF_MAP_TYPE_USER_RINGBUF:
16754 		case BPF_MAP_TYPE_INODE_STORAGE:
16755 		case BPF_MAP_TYPE_SK_STORAGE:
16756 		case BPF_MAP_TYPE_TASK_STORAGE:
16757 		case BPF_MAP_TYPE_CGRP_STORAGE:
16758 			break;
16759 		default:
16760 			verbose(env,
16761 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16762 			return -EINVAL;
16763 		}
16764 
16765 	return 0;
16766 }
16767 
16768 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16769 {
16770 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16771 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16772 }
16773 
16774 /* find and rewrite pseudo imm in ld_imm64 instructions:
16775  *
16776  * 1. if it accesses map FD, replace it with actual map pointer.
16777  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16778  *
16779  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16780  */
16781 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16782 {
16783 	struct bpf_insn *insn = env->prog->insnsi;
16784 	int insn_cnt = env->prog->len;
16785 	int i, j, err;
16786 
16787 	err = bpf_prog_calc_tag(env->prog);
16788 	if (err)
16789 		return err;
16790 
16791 	for (i = 0; i < insn_cnt; i++, insn++) {
16792 		if (BPF_CLASS(insn->code) == BPF_LDX &&
16793 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16794 			verbose(env, "BPF_LDX uses reserved fields\n");
16795 			return -EINVAL;
16796 		}
16797 
16798 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16799 			struct bpf_insn_aux_data *aux;
16800 			struct bpf_map *map;
16801 			struct fd f;
16802 			u64 addr;
16803 			u32 fd;
16804 
16805 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
16806 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16807 			    insn[1].off != 0) {
16808 				verbose(env, "invalid bpf_ld_imm64 insn\n");
16809 				return -EINVAL;
16810 			}
16811 
16812 			if (insn[0].src_reg == 0)
16813 				/* valid generic load 64-bit imm */
16814 				goto next_insn;
16815 
16816 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16817 				aux = &env->insn_aux_data[i];
16818 				err = check_pseudo_btf_id(env, insn, aux);
16819 				if (err)
16820 					return err;
16821 				goto next_insn;
16822 			}
16823 
16824 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16825 				aux = &env->insn_aux_data[i];
16826 				aux->ptr_type = PTR_TO_FUNC;
16827 				goto next_insn;
16828 			}
16829 
16830 			/* In final convert_pseudo_ld_imm64() step, this is
16831 			 * converted into regular 64-bit imm load insn.
16832 			 */
16833 			switch (insn[0].src_reg) {
16834 			case BPF_PSEUDO_MAP_VALUE:
16835 			case BPF_PSEUDO_MAP_IDX_VALUE:
16836 				break;
16837 			case BPF_PSEUDO_MAP_FD:
16838 			case BPF_PSEUDO_MAP_IDX:
16839 				if (insn[1].imm == 0)
16840 					break;
16841 				fallthrough;
16842 			default:
16843 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16844 				return -EINVAL;
16845 			}
16846 
16847 			switch (insn[0].src_reg) {
16848 			case BPF_PSEUDO_MAP_IDX_VALUE:
16849 			case BPF_PSEUDO_MAP_IDX:
16850 				if (bpfptr_is_null(env->fd_array)) {
16851 					verbose(env, "fd_idx without fd_array is invalid\n");
16852 					return -EPROTO;
16853 				}
16854 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
16855 							    insn[0].imm * sizeof(fd),
16856 							    sizeof(fd)))
16857 					return -EFAULT;
16858 				break;
16859 			default:
16860 				fd = insn[0].imm;
16861 				break;
16862 			}
16863 
16864 			f = fdget(fd);
16865 			map = __bpf_map_get(f);
16866 			if (IS_ERR(map)) {
16867 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
16868 					insn[0].imm);
16869 				return PTR_ERR(map);
16870 			}
16871 
16872 			err = check_map_prog_compatibility(env, map, env->prog);
16873 			if (err) {
16874 				fdput(f);
16875 				return err;
16876 			}
16877 
16878 			aux = &env->insn_aux_data[i];
16879 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16880 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16881 				addr = (unsigned long)map;
16882 			} else {
16883 				u32 off = insn[1].imm;
16884 
16885 				if (off >= BPF_MAX_VAR_OFF) {
16886 					verbose(env, "direct value offset of %u is not allowed\n", off);
16887 					fdput(f);
16888 					return -EINVAL;
16889 				}
16890 
16891 				if (!map->ops->map_direct_value_addr) {
16892 					verbose(env, "no direct value access support for this map type\n");
16893 					fdput(f);
16894 					return -EINVAL;
16895 				}
16896 
16897 				err = map->ops->map_direct_value_addr(map, &addr, off);
16898 				if (err) {
16899 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16900 						map->value_size, off);
16901 					fdput(f);
16902 					return err;
16903 				}
16904 
16905 				aux->map_off = off;
16906 				addr += off;
16907 			}
16908 
16909 			insn[0].imm = (u32)addr;
16910 			insn[1].imm = addr >> 32;
16911 
16912 			/* check whether we recorded this map already */
16913 			for (j = 0; j < env->used_map_cnt; j++) {
16914 				if (env->used_maps[j] == map) {
16915 					aux->map_index = j;
16916 					fdput(f);
16917 					goto next_insn;
16918 				}
16919 			}
16920 
16921 			if (env->used_map_cnt >= MAX_USED_MAPS) {
16922 				fdput(f);
16923 				return -E2BIG;
16924 			}
16925 
16926 			/* hold the map. If the program is rejected by verifier,
16927 			 * the map will be released by release_maps() or it
16928 			 * will be used by the valid program until it's unloaded
16929 			 * and all maps are released in free_used_maps()
16930 			 */
16931 			bpf_map_inc(map);
16932 
16933 			aux->map_index = env->used_map_cnt;
16934 			env->used_maps[env->used_map_cnt++] = map;
16935 
16936 			if (bpf_map_is_cgroup_storage(map) &&
16937 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
16938 				verbose(env, "only one cgroup storage of each type is allowed\n");
16939 				fdput(f);
16940 				return -EBUSY;
16941 			}
16942 
16943 			fdput(f);
16944 next_insn:
16945 			insn++;
16946 			i++;
16947 			continue;
16948 		}
16949 
16950 		/* Basic sanity check before we invest more work here. */
16951 		if (!bpf_opcode_in_insntable(insn->code)) {
16952 			verbose(env, "unknown opcode %02x\n", insn->code);
16953 			return -EINVAL;
16954 		}
16955 	}
16956 
16957 	/* now all pseudo BPF_LD_IMM64 instructions load valid
16958 	 * 'struct bpf_map *' into a register instead of user map_fd.
16959 	 * These pointers will be used later by verifier to validate map access.
16960 	 */
16961 	return 0;
16962 }
16963 
16964 /* drop refcnt of maps used by the rejected program */
16965 static void release_maps(struct bpf_verifier_env *env)
16966 {
16967 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
16968 			     env->used_map_cnt);
16969 }
16970 
16971 /* drop refcnt of maps used by the rejected program */
16972 static void release_btfs(struct bpf_verifier_env *env)
16973 {
16974 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16975 			     env->used_btf_cnt);
16976 }
16977 
16978 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16979 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16980 {
16981 	struct bpf_insn *insn = env->prog->insnsi;
16982 	int insn_cnt = env->prog->len;
16983 	int i;
16984 
16985 	for (i = 0; i < insn_cnt; i++, insn++) {
16986 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16987 			continue;
16988 		if (insn->src_reg == BPF_PSEUDO_FUNC)
16989 			continue;
16990 		insn->src_reg = 0;
16991 	}
16992 }
16993 
16994 /* single env->prog->insni[off] instruction was replaced with the range
16995  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
16996  * [0, off) and [off, end) to new locations, so the patched range stays zero
16997  */
16998 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16999 				 struct bpf_insn_aux_data *new_data,
17000 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17001 {
17002 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17003 	struct bpf_insn *insn = new_prog->insnsi;
17004 	u32 old_seen = old_data[off].seen;
17005 	u32 prog_len;
17006 	int i;
17007 
17008 	/* aux info at OFF always needs adjustment, no matter fast path
17009 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17010 	 * original insn at old prog.
17011 	 */
17012 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17013 
17014 	if (cnt == 1)
17015 		return;
17016 	prog_len = new_prog->len;
17017 
17018 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17019 	memcpy(new_data + off + cnt - 1, old_data + off,
17020 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17021 	for (i = off; i < off + cnt - 1; i++) {
17022 		/* Expand insni[off]'s seen count to the patched range. */
17023 		new_data[i].seen = old_seen;
17024 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17025 	}
17026 	env->insn_aux_data = new_data;
17027 	vfree(old_data);
17028 }
17029 
17030 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17031 {
17032 	int i;
17033 
17034 	if (len == 1)
17035 		return;
17036 	/* NOTE: fake 'exit' subprog should be updated as well. */
17037 	for (i = 0; i <= env->subprog_cnt; i++) {
17038 		if (env->subprog_info[i].start <= off)
17039 			continue;
17040 		env->subprog_info[i].start += len - 1;
17041 	}
17042 }
17043 
17044 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17045 {
17046 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17047 	int i, sz = prog->aux->size_poke_tab;
17048 	struct bpf_jit_poke_descriptor *desc;
17049 
17050 	for (i = 0; i < sz; i++) {
17051 		desc = &tab[i];
17052 		if (desc->insn_idx <= off)
17053 			continue;
17054 		desc->insn_idx += len - 1;
17055 	}
17056 }
17057 
17058 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17059 					    const struct bpf_insn *patch, u32 len)
17060 {
17061 	struct bpf_prog *new_prog;
17062 	struct bpf_insn_aux_data *new_data = NULL;
17063 
17064 	if (len > 1) {
17065 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17066 					      sizeof(struct bpf_insn_aux_data)));
17067 		if (!new_data)
17068 			return NULL;
17069 	}
17070 
17071 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17072 	if (IS_ERR(new_prog)) {
17073 		if (PTR_ERR(new_prog) == -ERANGE)
17074 			verbose(env,
17075 				"insn %d cannot be patched due to 16-bit range\n",
17076 				env->insn_aux_data[off].orig_idx);
17077 		vfree(new_data);
17078 		return NULL;
17079 	}
17080 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17081 	adjust_subprog_starts(env, off, len);
17082 	adjust_poke_descs(new_prog, off, len);
17083 	return new_prog;
17084 }
17085 
17086 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17087 					      u32 off, u32 cnt)
17088 {
17089 	int i, j;
17090 
17091 	/* find first prog starting at or after off (first to remove) */
17092 	for (i = 0; i < env->subprog_cnt; i++)
17093 		if (env->subprog_info[i].start >= off)
17094 			break;
17095 	/* find first prog starting at or after off + cnt (first to stay) */
17096 	for (j = i; j < env->subprog_cnt; j++)
17097 		if (env->subprog_info[j].start >= off + cnt)
17098 			break;
17099 	/* if j doesn't start exactly at off + cnt, we are just removing
17100 	 * the front of previous prog
17101 	 */
17102 	if (env->subprog_info[j].start != off + cnt)
17103 		j--;
17104 
17105 	if (j > i) {
17106 		struct bpf_prog_aux *aux = env->prog->aux;
17107 		int move;
17108 
17109 		/* move fake 'exit' subprog as well */
17110 		move = env->subprog_cnt + 1 - j;
17111 
17112 		memmove(env->subprog_info + i,
17113 			env->subprog_info + j,
17114 			sizeof(*env->subprog_info) * move);
17115 		env->subprog_cnt -= j - i;
17116 
17117 		/* remove func_info */
17118 		if (aux->func_info) {
17119 			move = aux->func_info_cnt - j;
17120 
17121 			memmove(aux->func_info + i,
17122 				aux->func_info + j,
17123 				sizeof(*aux->func_info) * move);
17124 			aux->func_info_cnt -= j - i;
17125 			/* func_info->insn_off is set after all code rewrites,
17126 			 * in adjust_btf_func() - no need to adjust
17127 			 */
17128 		}
17129 	} else {
17130 		/* convert i from "first prog to remove" to "first to adjust" */
17131 		if (env->subprog_info[i].start == off)
17132 			i++;
17133 	}
17134 
17135 	/* update fake 'exit' subprog as well */
17136 	for (; i <= env->subprog_cnt; i++)
17137 		env->subprog_info[i].start -= cnt;
17138 
17139 	return 0;
17140 }
17141 
17142 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17143 				      u32 cnt)
17144 {
17145 	struct bpf_prog *prog = env->prog;
17146 	u32 i, l_off, l_cnt, nr_linfo;
17147 	struct bpf_line_info *linfo;
17148 
17149 	nr_linfo = prog->aux->nr_linfo;
17150 	if (!nr_linfo)
17151 		return 0;
17152 
17153 	linfo = prog->aux->linfo;
17154 
17155 	/* find first line info to remove, count lines to be removed */
17156 	for (i = 0; i < nr_linfo; i++)
17157 		if (linfo[i].insn_off >= off)
17158 			break;
17159 
17160 	l_off = i;
17161 	l_cnt = 0;
17162 	for (; i < nr_linfo; i++)
17163 		if (linfo[i].insn_off < off + cnt)
17164 			l_cnt++;
17165 		else
17166 			break;
17167 
17168 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17169 	 * last removed linfo.  prog is already modified, so prog->len == off
17170 	 * means no live instructions after (tail of the program was removed).
17171 	 */
17172 	if (prog->len != off && l_cnt &&
17173 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17174 		l_cnt--;
17175 		linfo[--i].insn_off = off + cnt;
17176 	}
17177 
17178 	/* remove the line info which refer to the removed instructions */
17179 	if (l_cnt) {
17180 		memmove(linfo + l_off, linfo + i,
17181 			sizeof(*linfo) * (nr_linfo - i));
17182 
17183 		prog->aux->nr_linfo -= l_cnt;
17184 		nr_linfo = prog->aux->nr_linfo;
17185 	}
17186 
17187 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17188 	for (i = l_off; i < nr_linfo; i++)
17189 		linfo[i].insn_off -= cnt;
17190 
17191 	/* fix up all subprogs (incl. 'exit') which start >= off */
17192 	for (i = 0; i <= env->subprog_cnt; i++)
17193 		if (env->subprog_info[i].linfo_idx > l_off) {
17194 			/* program may have started in the removed region but
17195 			 * may not be fully removed
17196 			 */
17197 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17198 				env->subprog_info[i].linfo_idx -= l_cnt;
17199 			else
17200 				env->subprog_info[i].linfo_idx = l_off;
17201 		}
17202 
17203 	return 0;
17204 }
17205 
17206 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17207 {
17208 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17209 	unsigned int orig_prog_len = env->prog->len;
17210 	int err;
17211 
17212 	if (bpf_prog_is_offloaded(env->prog->aux))
17213 		bpf_prog_offload_remove_insns(env, off, cnt);
17214 
17215 	err = bpf_remove_insns(env->prog, off, cnt);
17216 	if (err)
17217 		return err;
17218 
17219 	err = adjust_subprog_starts_after_remove(env, off, cnt);
17220 	if (err)
17221 		return err;
17222 
17223 	err = bpf_adj_linfo_after_remove(env, off, cnt);
17224 	if (err)
17225 		return err;
17226 
17227 	memmove(aux_data + off,	aux_data + off + cnt,
17228 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
17229 
17230 	return 0;
17231 }
17232 
17233 /* The verifier does more data flow analysis than llvm and will not
17234  * explore branches that are dead at run time. Malicious programs can
17235  * have dead code too. Therefore replace all dead at-run-time code
17236  * with 'ja -1'.
17237  *
17238  * Just nops are not optimal, e.g. if they would sit at the end of the
17239  * program and through another bug we would manage to jump there, then
17240  * we'd execute beyond program memory otherwise. Returning exception
17241  * code also wouldn't work since we can have subprogs where the dead
17242  * code could be located.
17243  */
17244 static void sanitize_dead_code(struct bpf_verifier_env *env)
17245 {
17246 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17247 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17248 	struct bpf_insn *insn = env->prog->insnsi;
17249 	const int insn_cnt = env->prog->len;
17250 	int i;
17251 
17252 	for (i = 0; i < insn_cnt; i++) {
17253 		if (aux_data[i].seen)
17254 			continue;
17255 		memcpy(insn + i, &trap, sizeof(trap));
17256 		aux_data[i].zext_dst = false;
17257 	}
17258 }
17259 
17260 static bool insn_is_cond_jump(u8 code)
17261 {
17262 	u8 op;
17263 
17264 	if (BPF_CLASS(code) == BPF_JMP32)
17265 		return true;
17266 
17267 	if (BPF_CLASS(code) != BPF_JMP)
17268 		return false;
17269 
17270 	op = BPF_OP(code);
17271 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17272 }
17273 
17274 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17275 {
17276 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17277 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17278 	struct bpf_insn *insn = env->prog->insnsi;
17279 	const int insn_cnt = env->prog->len;
17280 	int i;
17281 
17282 	for (i = 0; i < insn_cnt; i++, insn++) {
17283 		if (!insn_is_cond_jump(insn->code))
17284 			continue;
17285 
17286 		if (!aux_data[i + 1].seen)
17287 			ja.off = insn->off;
17288 		else if (!aux_data[i + 1 + insn->off].seen)
17289 			ja.off = 0;
17290 		else
17291 			continue;
17292 
17293 		if (bpf_prog_is_offloaded(env->prog->aux))
17294 			bpf_prog_offload_replace_insn(env, i, &ja);
17295 
17296 		memcpy(insn, &ja, sizeof(ja));
17297 	}
17298 }
17299 
17300 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17301 {
17302 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17303 	int insn_cnt = env->prog->len;
17304 	int i, err;
17305 
17306 	for (i = 0; i < insn_cnt; i++) {
17307 		int j;
17308 
17309 		j = 0;
17310 		while (i + j < insn_cnt && !aux_data[i + j].seen)
17311 			j++;
17312 		if (!j)
17313 			continue;
17314 
17315 		err = verifier_remove_insns(env, i, j);
17316 		if (err)
17317 			return err;
17318 		insn_cnt = env->prog->len;
17319 	}
17320 
17321 	return 0;
17322 }
17323 
17324 static int opt_remove_nops(struct bpf_verifier_env *env)
17325 {
17326 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17327 	struct bpf_insn *insn = env->prog->insnsi;
17328 	int insn_cnt = env->prog->len;
17329 	int i, err;
17330 
17331 	for (i = 0; i < insn_cnt; i++) {
17332 		if (memcmp(&insn[i], &ja, sizeof(ja)))
17333 			continue;
17334 
17335 		err = verifier_remove_insns(env, i, 1);
17336 		if (err)
17337 			return err;
17338 		insn_cnt--;
17339 		i--;
17340 	}
17341 
17342 	return 0;
17343 }
17344 
17345 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17346 					 const union bpf_attr *attr)
17347 {
17348 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17349 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
17350 	int i, patch_len, delta = 0, len = env->prog->len;
17351 	struct bpf_insn *insns = env->prog->insnsi;
17352 	struct bpf_prog *new_prog;
17353 	bool rnd_hi32;
17354 
17355 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17356 	zext_patch[1] = BPF_ZEXT_REG(0);
17357 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17358 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17359 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17360 	for (i = 0; i < len; i++) {
17361 		int adj_idx = i + delta;
17362 		struct bpf_insn insn;
17363 		int load_reg;
17364 
17365 		insn = insns[adj_idx];
17366 		load_reg = insn_def_regno(&insn);
17367 		if (!aux[adj_idx].zext_dst) {
17368 			u8 code, class;
17369 			u32 imm_rnd;
17370 
17371 			if (!rnd_hi32)
17372 				continue;
17373 
17374 			code = insn.code;
17375 			class = BPF_CLASS(code);
17376 			if (load_reg == -1)
17377 				continue;
17378 
17379 			/* NOTE: arg "reg" (the fourth one) is only used for
17380 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
17381 			 *       here.
17382 			 */
17383 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17384 				if (class == BPF_LD &&
17385 				    BPF_MODE(code) == BPF_IMM)
17386 					i++;
17387 				continue;
17388 			}
17389 
17390 			/* ctx load could be transformed into wider load. */
17391 			if (class == BPF_LDX &&
17392 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
17393 				continue;
17394 
17395 			imm_rnd = get_random_u32();
17396 			rnd_hi32_patch[0] = insn;
17397 			rnd_hi32_patch[1].imm = imm_rnd;
17398 			rnd_hi32_patch[3].dst_reg = load_reg;
17399 			patch = rnd_hi32_patch;
17400 			patch_len = 4;
17401 			goto apply_patch_buffer;
17402 		}
17403 
17404 		/* Add in an zero-extend instruction if a) the JIT has requested
17405 		 * it or b) it's a CMPXCHG.
17406 		 *
17407 		 * The latter is because: BPF_CMPXCHG always loads a value into
17408 		 * R0, therefore always zero-extends. However some archs'
17409 		 * equivalent instruction only does this load when the
17410 		 * comparison is successful. This detail of CMPXCHG is
17411 		 * orthogonal to the general zero-extension behaviour of the
17412 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
17413 		 */
17414 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17415 			continue;
17416 
17417 		/* Zero-extension is done by the caller. */
17418 		if (bpf_pseudo_kfunc_call(&insn))
17419 			continue;
17420 
17421 		if (WARN_ON(load_reg == -1)) {
17422 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17423 			return -EFAULT;
17424 		}
17425 
17426 		zext_patch[0] = insn;
17427 		zext_patch[1].dst_reg = load_reg;
17428 		zext_patch[1].src_reg = load_reg;
17429 		patch = zext_patch;
17430 		patch_len = 2;
17431 apply_patch_buffer:
17432 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17433 		if (!new_prog)
17434 			return -ENOMEM;
17435 		env->prog = new_prog;
17436 		insns = new_prog->insnsi;
17437 		aux = env->insn_aux_data;
17438 		delta += patch_len - 1;
17439 	}
17440 
17441 	return 0;
17442 }
17443 
17444 /* convert load instructions that access fields of a context type into a
17445  * sequence of instructions that access fields of the underlying structure:
17446  *     struct __sk_buff    -> struct sk_buff
17447  *     struct bpf_sock_ops -> struct sock
17448  */
17449 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17450 {
17451 	const struct bpf_verifier_ops *ops = env->ops;
17452 	int i, cnt, size, ctx_field_size, delta = 0;
17453 	const int insn_cnt = env->prog->len;
17454 	struct bpf_insn insn_buf[16], *insn;
17455 	u32 target_size, size_default, off;
17456 	struct bpf_prog *new_prog;
17457 	enum bpf_access_type type;
17458 	bool is_narrower_load;
17459 
17460 	if (ops->gen_prologue || env->seen_direct_write) {
17461 		if (!ops->gen_prologue) {
17462 			verbose(env, "bpf verifier is misconfigured\n");
17463 			return -EINVAL;
17464 		}
17465 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17466 					env->prog);
17467 		if (cnt >= ARRAY_SIZE(insn_buf)) {
17468 			verbose(env, "bpf verifier is misconfigured\n");
17469 			return -EINVAL;
17470 		} else if (cnt) {
17471 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17472 			if (!new_prog)
17473 				return -ENOMEM;
17474 
17475 			env->prog = new_prog;
17476 			delta += cnt - 1;
17477 		}
17478 	}
17479 
17480 	if (bpf_prog_is_offloaded(env->prog->aux))
17481 		return 0;
17482 
17483 	insn = env->prog->insnsi + delta;
17484 
17485 	for (i = 0; i < insn_cnt; i++, insn++) {
17486 		bpf_convert_ctx_access_t convert_ctx_access;
17487 
17488 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17489 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17490 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17491 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17492 			type = BPF_READ;
17493 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17494 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17495 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17496 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17497 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17498 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17499 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17500 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17501 			type = BPF_WRITE;
17502 		} else {
17503 			continue;
17504 		}
17505 
17506 		if (type == BPF_WRITE &&
17507 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
17508 			struct bpf_insn patch[] = {
17509 				*insn,
17510 				BPF_ST_NOSPEC(),
17511 			};
17512 
17513 			cnt = ARRAY_SIZE(patch);
17514 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17515 			if (!new_prog)
17516 				return -ENOMEM;
17517 
17518 			delta    += cnt - 1;
17519 			env->prog = new_prog;
17520 			insn      = new_prog->insnsi + i + delta;
17521 			continue;
17522 		}
17523 
17524 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17525 		case PTR_TO_CTX:
17526 			if (!ops->convert_ctx_access)
17527 				continue;
17528 			convert_ctx_access = ops->convert_ctx_access;
17529 			break;
17530 		case PTR_TO_SOCKET:
17531 		case PTR_TO_SOCK_COMMON:
17532 			convert_ctx_access = bpf_sock_convert_ctx_access;
17533 			break;
17534 		case PTR_TO_TCP_SOCK:
17535 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17536 			break;
17537 		case PTR_TO_XDP_SOCK:
17538 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17539 			break;
17540 		case PTR_TO_BTF_ID:
17541 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17542 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17543 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17544 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17545 		 * any faults for loads into such types. BPF_WRITE is disallowed
17546 		 * for this case.
17547 		 */
17548 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17549 			if (type == BPF_READ) {
17550 				insn->code = BPF_LDX | BPF_PROBE_MEM |
17551 					BPF_SIZE((insn)->code);
17552 				env->prog->aux->num_exentries++;
17553 			}
17554 			continue;
17555 		default:
17556 			continue;
17557 		}
17558 
17559 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17560 		size = BPF_LDST_BYTES(insn);
17561 
17562 		/* If the read access is a narrower load of the field,
17563 		 * convert to a 4/8-byte load, to minimum program type specific
17564 		 * convert_ctx_access changes. If conversion is successful,
17565 		 * we will apply proper mask to the result.
17566 		 */
17567 		is_narrower_load = size < ctx_field_size;
17568 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17569 		off = insn->off;
17570 		if (is_narrower_load) {
17571 			u8 size_code;
17572 
17573 			if (type == BPF_WRITE) {
17574 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17575 				return -EINVAL;
17576 			}
17577 
17578 			size_code = BPF_H;
17579 			if (ctx_field_size == 4)
17580 				size_code = BPF_W;
17581 			else if (ctx_field_size == 8)
17582 				size_code = BPF_DW;
17583 
17584 			insn->off = off & ~(size_default - 1);
17585 			insn->code = BPF_LDX | BPF_MEM | size_code;
17586 		}
17587 
17588 		target_size = 0;
17589 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17590 					 &target_size);
17591 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17592 		    (ctx_field_size && !target_size)) {
17593 			verbose(env, "bpf verifier is misconfigured\n");
17594 			return -EINVAL;
17595 		}
17596 
17597 		if (is_narrower_load && size < target_size) {
17598 			u8 shift = bpf_ctx_narrow_access_offset(
17599 				off, size, size_default) * 8;
17600 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17601 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17602 				return -EINVAL;
17603 			}
17604 			if (ctx_field_size <= 4) {
17605 				if (shift)
17606 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17607 									insn->dst_reg,
17608 									shift);
17609 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17610 								(1 << size * 8) - 1);
17611 			} else {
17612 				if (shift)
17613 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17614 									insn->dst_reg,
17615 									shift);
17616 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17617 								(1ULL << size * 8) - 1);
17618 			}
17619 		}
17620 
17621 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17622 		if (!new_prog)
17623 			return -ENOMEM;
17624 
17625 		delta += cnt - 1;
17626 
17627 		/* keep walking new program and skip insns we just inserted */
17628 		env->prog = new_prog;
17629 		insn      = new_prog->insnsi + i + delta;
17630 	}
17631 
17632 	return 0;
17633 }
17634 
17635 static int jit_subprogs(struct bpf_verifier_env *env)
17636 {
17637 	struct bpf_prog *prog = env->prog, **func, *tmp;
17638 	int i, j, subprog_start, subprog_end = 0, len, subprog;
17639 	struct bpf_map *map_ptr;
17640 	struct bpf_insn *insn;
17641 	void *old_bpf_func;
17642 	int err, num_exentries;
17643 
17644 	if (env->subprog_cnt <= 1)
17645 		return 0;
17646 
17647 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17648 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17649 			continue;
17650 
17651 		/* Upon error here we cannot fall back to interpreter but
17652 		 * need a hard reject of the program. Thus -EFAULT is
17653 		 * propagated in any case.
17654 		 */
17655 		subprog = find_subprog(env, i + insn->imm + 1);
17656 		if (subprog < 0) {
17657 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17658 				  i + insn->imm + 1);
17659 			return -EFAULT;
17660 		}
17661 		/* temporarily remember subprog id inside insn instead of
17662 		 * aux_data, since next loop will split up all insns into funcs
17663 		 */
17664 		insn->off = subprog;
17665 		/* remember original imm in case JIT fails and fallback
17666 		 * to interpreter will be needed
17667 		 */
17668 		env->insn_aux_data[i].call_imm = insn->imm;
17669 		/* point imm to __bpf_call_base+1 from JITs point of view */
17670 		insn->imm = 1;
17671 		if (bpf_pseudo_func(insn))
17672 			/* jit (e.g. x86_64) may emit fewer instructions
17673 			 * if it learns a u32 imm is the same as a u64 imm.
17674 			 * Force a non zero here.
17675 			 */
17676 			insn[1].imm = 1;
17677 	}
17678 
17679 	err = bpf_prog_alloc_jited_linfo(prog);
17680 	if (err)
17681 		goto out_undo_insn;
17682 
17683 	err = -ENOMEM;
17684 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17685 	if (!func)
17686 		goto out_undo_insn;
17687 
17688 	for (i = 0; i < env->subprog_cnt; i++) {
17689 		subprog_start = subprog_end;
17690 		subprog_end = env->subprog_info[i + 1].start;
17691 
17692 		len = subprog_end - subprog_start;
17693 		/* bpf_prog_run() doesn't call subprogs directly,
17694 		 * hence main prog stats include the runtime of subprogs.
17695 		 * subprogs don't have IDs and not reachable via prog_get_next_id
17696 		 * func[i]->stats will never be accessed and stays NULL
17697 		 */
17698 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17699 		if (!func[i])
17700 			goto out_free;
17701 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17702 		       len * sizeof(struct bpf_insn));
17703 		func[i]->type = prog->type;
17704 		func[i]->len = len;
17705 		if (bpf_prog_calc_tag(func[i]))
17706 			goto out_free;
17707 		func[i]->is_func = 1;
17708 		func[i]->aux->func_idx = i;
17709 		/* Below members will be freed only at prog->aux */
17710 		func[i]->aux->btf = prog->aux->btf;
17711 		func[i]->aux->func_info = prog->aux->func_info;
17712 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17713 		func[i]->aux->poke_tab = prog->aux->poke_tab;
17714 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17715 
17716 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
17717 			struct bpf_jit_poke_descriptor *poke;
17718 
17719 			poke = &prog->aux->poke_tab[j];
17720 			if (poke->insn_idx < subprog_end &&
17721 			    poke->insn_idx >= subprog_start)
17722 				poke->aux = func[i]->aux;
17723 		}
17724 
17725 		func[i]->aux->name[0] = 'F';
17726 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17727 		func[i]->jit_requested = 1;
17728 		func[i]->blinding_requested = prog->blinding_requested;
17729 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17730 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17731 		func[i]->aux->linfo = prog->aux->linfo;
17732 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17733 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17734 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17735 		num_exentries = 0;
17736 		insn = func[i]->insnsi;
17737 		for (j = 0; j < func[i]->len; j++, insn++) {
17738 			if (BPF_CLASS(insn->code) == BPF_LDX &&
17739 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
17740 				num_exentries++;
17741 		}
17742 		func[i]->aux->num_exentries = num_exentries;
17743 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17744 		func[i] = bpf_int_jit_compile(func[i]);
17745 		if (!func[i]->jited) {
17746 			err = -ENOTSUPP;
17747 			goto out_free;
17748 		}
17749 		cond_resched();
17750 	}
17751 
17752 	/* at this point all bpf functions were successfully JITed
17753 	 * now populate all bpf_calls with correct addresses and
17754 	 * run last pass of JIT
17755 	 */
17756 	for (i = 0; i < env->subprog_cnt; i++) {
17757 		insn = func[i]->insnsi;
17758 		for (j = 0; j < func[i]->len; j++, insn++) {
17759 			if (bpf_pseudo_func(insn)) {
17760 				subprog = insn->off;
17761 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17762 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17763 				continue;
17764 			}
17765 			if (!bpf_pseudo_call(insn))
17766 				continue;
17767 			subprog = insn->off;
17768 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17769 		}
17770 
17771 		/* we use the aux data to keep a list of the start addresses
17772 		 * of the JITed images for each function in the program
17773 		 *
17774 		 * for some architectures, such as powerpc64, the imm field
17775 		 * might not be large enough to hold the offset of the start
17776 		 * address of the callee's JITed image from __bpf_call_base
17777 		 *
17778 		 * in such cases, we can lookup the start address of a callee
17779 		 * by using its subprog id, available from the off field of
17780 		 * the call instruction, as an index for this list
17781 		 */
17782 		func[i]->aux->func = func;
17783 		func[i]->aux->func_cnt = env->subprog_cnt;
17784 	}
17785 	for (i = 0; i < env->subprog_cnt; i++) {
17786 		old_bpf_func = func[i]->bpf_func;
17787 		tmp = bpf_int_jit_compile(func[i]);
17788 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17789 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17790 			err = -ENOTSUPP;
17791 			goto out_free;
17792 		}
17793 		cond_resched();
17794 	}
17795 
17796 	/* finally lock prog and jit images for all functions and
17797 	 * populate kallsysm. Begin at the first subprogram, since
17798 	 * bpf_prog_load will add the kallsyms for the main program.
17799 	 */
17800 	for (i = 1; i < env->subprog_cnt; i++) {
17801 		bpf_prog_lock_ro(func[i]);
17802 		bpf_prog_kallsyms_add(func[i]);
17803 	}
17804 
17805 	/* Last step: make now unused interpreter insns from main
17806 	 * prog consistent for later dump requests, so they can
17807 	 * later look the same as if they were interpreted only.
17808 	 */
17809 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17810 		if (bpf_pseudo_func(insn)) {
17811 			insn[0].imm = env->insn_aux_data[i].call_imm;
17812 			insn[1].imm = insn->off;
17813 			insn->off = 0;
17814 			continue;
17815 		}
17816 		if (!bpf_pseudo_call(insn))
17817 			continue;
17818 		insn->off = env->insn_aux_data[i].call_imm;
17819 		subprog = find_subprog(env, i + insn->off + 1);
17820 		insn->imm = subprog;
17821 	}
17822 
17823 	prog->jited = 1;
17824 	prog->bpf_func = func[0]->bpf_func;
17825 	prog->jited_len = func[0]->jited_len;
17826 	prog->aux->extable = func[0]->aux->extable;
17827 	prog->aux->num_exentries = func[0]->aux->num_exentries;
17828 	prog->aux->func = func;
17829 	prog->aux->func_cnt = env->subprog_cnt;
17830 	bpf_prog_jit_attempt_done(prog);
17831 	return 0;
17832 out_free:
17833 	/* We failed JIT'ing, so at this point we need to unregister poke
17834 	 * descriptors from subprogs, so that kernel is not attempting to
17835 	 * patch it anymore as we're freeing the subprog JIT memory.
17836 	 */
17837 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17838 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17839 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17840 	}
17841 	/* At this point we're guaranteed that poke descriptors are not
17842 	 * live anymore. We can just unlink its descriptor table as it's
17843 	 * released with the main prog.
17844 	 */
17845 	for (i = 0; i < env->subprog_cnt; i++) {
17846 		if (!func[i])
17847 			continue;
17848 		func[i]->aux->poke_tab = NULL;
17849 		bpf_jit_free(func[i]);
17850 	}
17851 	kfree(func);
17852 out_undo_insn:
17853 	/* cleanup main prog to be interpreted */
17854 	prog->jit_requested = 0;
17855 	prog->blinding_requested = 0;
17856 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17857 		if (!bpf_pseudo_call(insn))
17858 			continue;
17859 		insn->off = 0;
17860 		insn->imm = env->insn_aux_data[i].call_imm;
17861 	}
17862 	bpf_prog_jit_attempt_done(prog);
17863 	return err;
17864 }
17865 
17866 static int fixup_call_args(struct bpf_verifier_env *env)
17867 {
17868 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17869 	struct bpf_prog *prog = env->prog;
17870 	struct bpf_insn *insn = prog->insnsi;
17871 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17872 	int i, depth;
17873 #endif
17874 	int err = 0;
17875 
17876 	if (env->prog->jit_requested &&
17877 	    !bpf_prog_is_offloaded(env->prog->aux)) {
17878 		err = jit_subprogs(env);
17879 		if (err == 0)
17880 			return 0;
17881 		if (err == -EFAULT)
17882 			return err;
17883 	}
17884 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17885 	if (has_kfunc_call) {
17886 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17887 		return -EINVAL;
17888 	}
17889 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17890 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
17891 		 * have to be rejected, since interpreter doesn't support them yet.
17892 		 */
17893 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17894 		return -EINVAL;
17895 	}
17896 	for (i = 0; i < prog->len; i++, insn++) {
17897 		if (bpf_pseudo_func(insn)) {
17898 			/* When JIT fails the progs with callback calls
17899 			 * have to be rejected, since interpreter doesn't support them yet.
17900 			 */
17901 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
17902 			return -EINVAL;
17903 		}
17904 
17905 		if (!bpf_pseudo_call(insn))
17906 			continue;
17907 		depth = get_callee_stack_depth(env, insn, i);
17908 		if (depth < 0)
17909 			return depth;
17910 		bpf_patch_call_args(insn, depth);
17911 	}
17912 	err = 0;
17913 #endif
17914 	return err;
17915 }
17916 
17917 /* replace a generic kfunc with a specialized version if necessary */
17918 static void specialize_kfunc(struct bpf_verifier_env *env,
17919 			     u32 func_id, u16 offset, unsigned long *addr)
17920 {
17921 	struct bpf_prog *prog = env->prog;
17922 	bool seen_direct_write;
17923 	void *xdp_kfunc;
17924 	bool is_rdonly;
17925 
17926 	if (bpf_dev_bound_kfunc_id(func_id)) {
17927 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17928 		if (xdp_kfunc) {
17929 			*addr = (unsigned long)xdp_kfunc;
17930 			return;
17931 		}
17932 		/* fallback to default kfunc when not supported by netdev */
17933 	}
17934 
17935 	if (offset)
17936 		return;
17937 
17938 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17939 		seen_direct_write = env->seen_direct_write;
17940 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17941 
17942 		if (is_rdonly)
17943 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17944 
17945 		/* restore env->seen_direct_write to its original value, since
17946 		 * may_access_direct_pkt_data mutates it
17947 		 */
17948 		env->seen_direct_write = seen_direct_write;
17949 	}
17950 }
17951 
17952 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17953 					    u16 struct_meta_reg,
17954 					    u16 node_offset_reg,
17955 					    struct bpf_insn *insn,
17956 					    struct bpf_insn *insn_buf,
17957 					    int *cnt)
17958 {
17959 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17960 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17961 
17962 	insn_buf[0] = addr[0];
17963 	insn_buf[1] = addr[1];
17964 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17965 	insn_buf[3] = *insn;
17966 	*cnt = 4;
17967 }
17968 
17969 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17970 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17971 {
17972 	const struct bpf_kfunc_desc *desc;
17973 
17974 	if (!insn->imm) {
17975 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17976 		return -EINVAL;
17977 	}
17978 
17979 	*cnt = 0;
17980 
17981 	/* insn->imm has the btf func_id. Replace it with an offset relative to
17982 	 * __bpf_call_base, unless the JIT needs to call functions that are
17983 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
17984 	 */
17985 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17986 	if (!desc) {
17987 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17988 			insn->imm);
17989 		return -EFAULT;
17990 	}
17991 
17992 	if (!bpf_jit_supports_far_kfunc_call())
17993 		insn->imm = BPF_CALL_IMM(desc->addr);
17994 	if (insn->off)
17995 		return 0;
17996 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17997 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17998 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17999 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18000 
18001 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18002 		insn_buf[1] = addr[0];
18003 		insn_buf[2] = addr[1];
18004 		insn_buf[3] = *insn;
18005 		*cnt = 4;
18006 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18007 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18008 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18009 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18010 
18011 		insn_buf[0] = addr[0];
18012 		insn_buf[1] = addr[1];
18013 		insn_buf[2] = *insn;
18014 		*cnt = 3;
18015 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18016 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18017 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18018 		int struct_meta_reg = BPF_REG_3;
18019 		int node_offset_reg = BPF_REG_4;
18020 
18021 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18022 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18023 			struct_meta_reg = BPF_REG_4;
18024 			node_offset_reg = BPF_REG_5;
18025 		}
18026 
18027 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18028 						node_offset_reg, insn, insn_buf, cnt);
18029 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18030 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18031 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18032 		*cnt = 1;
18033 	}
18034 	return 0;
18035 }
18036 
18037 /* Do various post-verification rewrites in a single program pass.
18038  * These rewrites simplify JIT and interpreter implementations.
18039  */
18040 static int do_misc_fixups(struct bpf_verifier_env *env)
18041 {
18042 	struct bpf_prog *prog = env->prog;
18043 	enum bpf_attach_type eatype = prog->expected_attach_type;
18044 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18045 	struct bpf_insn *insn = prog->insnsi;
18046 	const struct bpf_func_proto *fn;
18047 	const int insn_cnt = prog->len;
18048 	const struct bpf_map_ops *ops;
18049 	struct bpf_insn_aux_data *aux;
18050 	struct bpf_insn insn_buf[16];
18051 	struct bpf_prog *new_prog;
18052 	struct bpf_map *map_ptr;
18053 	int i, ret, cnt, delta = 0;
18054 
18055 	for (i = 0; i < insn_cnt; i++, insn++) {
18056 		/* Make divide-by-zero exceptions impossible. */
18057 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18058 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18059 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18060 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18061 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18062 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18063 			struct bpf_insn *patchlet;
18064 			struct bpf_insn chk_and_div[] = {
18065 				/* [R,W]x div 0 -> 0 */
18066 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18067 					     BPF_JNE | BPF_K, insn->src_reg,
18068 					     0, 2, 0),
18069 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18070 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18071 				*insn,
18072 			};
18073 			struct bpf_insn chk_and_mod[] = {
18074 				/* [R,W]x mod 0 -> [R,W]x */
18075 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18076 					     BPF_JEQ | BPF_K, insn->src_reg,
18077 					     0, 1 + (is64 ? 0 : 1), 0),
18078 				*insn,
18079 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18080 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18081 			};
18082 
18083 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18084 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18085 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18086 
18087 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18088 			if (!new_prog)
18089 				return -ENOMEM;
18090 
18091 			delta    += cnt - 1;
18092 			env->prog = prog = new_prog;
18093 			insn      = new_prog->insnsi + i + delta;
18094 			continue;
18095 		}
18096 
18097 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18098 		if (BPF_CLASS(insn->code) == BPF_LD &&
18099 		    (BPF_MODE(insn->code) == BPF_ABS ||
18100 		     BPF_MODE(insn->code) == BPF_IND)) {
18101 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18102 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18103 				verbose(env, "bpf verifier is misconfigured\n");
18104 				return -EINVAL;
18105 			}
18106 
18107 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18108 			if (!new_prog)
18109 				return -ENOMEM;
18110 
18111 			delta    += cnt - 1;
18112 			env->prog = prog = new_prog;
18113 			insn      = new_prog->insnsi + i + delta;
18114 			continue;
18115 		}
18116 
18117 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18118 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18119 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18120 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18121 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18122 			struct bpf_insn *patch = &insn_buf[0];
18123 			bool issrc, isneg, isimm;
18124 			u32 off_reg;
18125 
18126 			aux = &env->insn_aux_data[i + delta];
18127 			if (!aux->alu_state ||
18128 			    aux->alu_state == BPF_ALU_NON_POINTER)
18129 				continue;
18130 
18131 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18132 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18133 				BPF_ALU_SANITIZE_SRC;
18134 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18135 
18136 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18137 			if (isimm) {
18138 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18139 			} else {
18140 				if (isneg)
18141 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18142 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18143 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18144 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18145 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18146 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18147 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18148 			}
18149 			if (!issrc)
18150 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18151 			insn->src_reg = BPF_REG_AX;
18152 			if (isneg)
18153 				insn->code = insn->code == code_add ?
18154 					     code_sub : code_add;
18155 			*patch++ = *insn;
18156 			if (issrc && isneg && !isimm)
18157 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18158 			cnt = patch - insn_buf;
18159 
18160 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18161 			if (!new_prog)
18162 				return -ENOMEM;
18163 
18164 			delta    += cnt - 1;
18165 			env->prog = prog = new_prog;
18166 			insn      = new_prog->insnsi + i + delta;
18167 			continue;
18168 		}
18169 
18170 		if (insn->code != (BPF_JMP | BPF_CALL))
18171 			continue;
18172 		if (insn->src_reg == BPF_PSEUDO_CALL)
18173 			continue;
18174 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18175 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18176 			if (ret)
18177 				return ret;
18178 			if (cnt == 0)
18179 				continue;
18180 
18181 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18182 			if (!new_prog)
18183 				return -ENOMEM;
18184 
18185 			delta	 += cnt - 1;
18186 			env->prog = prog = new_prog;
18187 			insn	  = new_prog->insnsi + i + delta;
18188 			continue;
18189 		}
18190 
18191 		if (insn->imm == BPF_FUNC_get_route_realm)
18192 			prog->dst_needed = 1;
18193 		if (insn->imm == BPF_FUNC_get_prandom_u32)
18194 			bpf_user_rnd_init_once();
18195 		if (insn->imm == BPF_FUNC_override_return)
18196 			prog->kprobe_override = 1;
18197 		if (insn->imm == BPF_FUNC_tail_call) {
18198 			/* If we tail call into other programs, we
18199 			 * cannot make any assumptions since they can
18200 			 * be replaced dynamically during runtime in
18201 			 * the program array.
18202 			 */
18203 			prog->cb_access = 1;
18204 			if (!allow_tail_call_in_subprogs(env))
18205 				prog->aux->stack_depth = MAX_BPF_STACK;
18206 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18207 
18208 			/* mark bpf_tail_call as different opcode to avoid
18209 			 * conditional branch in the interpreter for every normal
18210 			 * call and to prevent accidental JITing by JIT compiler
18211 			 * that doesn't support bpf_tail_call yet
18212 			 */
18213 			insn->imm = 0;
18214 			insn->code = BPF_JMP | BPF_TAIL_CALL;
18215 
18216 			aux = &env->insn_aux_data[i + delta];
18217 			if (env->bpf_capable && !prog->blinding_requested &&
18218 			    prog->jit_requested &&
18219 			    !bpf_map_key_poisoned(aux) &&
18220 			    !bpf_map_ptr_poisoned(aux) &&
18221 			    !bpf_map_ptr_unpriv(aux)) {
18222 				struct bpf_jit_poke_descriptor desc = {
18223 					.reason = BPF_POKE_REASON_TAIL_CALL,
18224 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18225 					.tail_call.key = bpf_map_key_immediate(aux),
18226 					.insn_idx = i + delta,
18227 				};
18228 
18229 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
18230 				if (ret < 0) {
18231 					verbose(env, "adding tail call poke descriptor failed\n");
18232 					return ret;
18233 				}
18234 
18235 				insn->imm = ret + 1;
18236 				continue;
18237 			}
18238 
18239 			if (!bpf_map_ptr_unpriv(aux))
18240 				continue;
18241 
18242 			/* instead of changing every JIT dealing with tail_call
18243 			 * emit two extra insns:
18244 			 * if (index >= max_entries) goto out;
18245 			 * index &= array->index_mask;
18246 			 * to avoid out-of-bounds cpu speculation
18247 			 */
18248 			if (bpf_map_ptr_poisoned(aux)) {
18249 				verbose(env, "tail_call abusing map_ptr\n");
18250 				return -EINVAL;
18251 			}
18252 
18253 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18254 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18255 						  map_ptr->max_entries, 2);
18256 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18257 						    container_of(map_ptr,
18258 								 struct bpf_array,
18259 								 map)->index_mask);
18260 			insn_buf[2] = *insn;
18261 			cnt = 3;
18262 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18263 			if (!new_prog)
18264 				return -ENOMEM;
18265 
18266 			delta    += cnt - 1;
18267 			env->prog = prog = new_prog;
18268 			insn      = new_prog->insnsi + i + delta;
18269 			continue;
18270 		}
18271 
18272 		if (insn->imm == BPF_FUNC_timer_set_callback) {
18273 			/* The verifier will process callback_fn as many times as necessary
18274 			 * with different maps and the register states prepared by
18275 			 * set_timer_callback_state will be accurate.
18276 			 *
18277 			 * The following use case is valid:
18278 			 *   map1 is shared by prog1, prog2, prog3.
18279 			 *   prog1 calls bpf_timer_init for some map1 elements
18280 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
18281 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
18282 			 *   prog3 calls bpf_timer_start for some map1 elements.
18283 			 *     Those that were not both bpf_timer_init-ed and
18284 			 *     bpf_timer_set_callback-ed will return -EINVAL.
18285 			 */
18286 			struct bpf_insn ld_addrs[2] = {
18287 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18288 			};
18289 
18290 			insn_buf[0] = ld_addrs[0];
18291 			insn_buf[1] = ld_addrs[1];
18292 			insn_buf[2] = *insn;
18293 			cnt = 3;
18294 
18295 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18296 			if (!new_prog)
18297 				return -ENOMEM;
18298 
18299 			delta    += cnt - 1;
18300 			env->prog = prog = new_prog;
18301 			insn      = new_prog->insnsi + i + delta;
18302 			goto patch_call_imm;
18303 		}
18304 
18305 		if (is_storage_get_function(insn->imm)) {
18306 			if (!env->prog->aux->sleepable ||
18307 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
18308 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18309 			else
18310 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18311 			insn_buf[1] = *insn;
18312 			cnt = 2;
18313 
18314 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18315 			if (!new_prog)
18316 				return -ENOMEM;
18317 
18318 			delta += cnt - 1;
18319 			env->prog = prog = new_prog;
18320 			insn = new_prog->insnsi + i + delta;
18321 			goto patch_call_imm;
18322 		}
18323 
18324 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18325 		 * and other inlining handlers are currently limited to 64 bit
18326 		 * only.
18327 		 */
18328 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18329 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
18330 		     insn->imm == BPF_FUNC_map_update_elem ||
18331 		     insn->imm == BPF_FUNC_map_delete_elem ||
18332 		     insn->imm == BPF_FUNC_map_push_elem   ||
18333 		     insn->imm == BPF_FUNC_map_pop_elem    ||
18334 		     insn->imm == BPF_FUNC_map_peek_elem   ||
18335 		     insn->imm == BPF_FUNC_redirect_map    ||
18336 		     insn->imm == BPF_FUNC_for_each_map_elem ||
18337 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18338 			aux = &env->insn_aux_data[i + delta];
18339 			if (bpf_map_ptr_poisoned(aux))
18340 				goto patch_call_imm;
18341 
18342 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18343 			ops = map_ptr->ops;
18344 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
18345 			    ops->map_gen_lookup) {
18346 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18347 				if (cnt == -EOPNOTSUPP)
18348 					goto patch_map_ops_generic;
18349 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18350 					verbose(env, "bpf verifier is misconfigured\n");
18351 					return -EINVAL;
18352 				}
18353 
18354 				new_prog = bpf_patch_insn_data(env, i + delta,
18355 							       insn_buf, cnt);
18356 				if (!new_prog)
18357 					return -ENOMEM;
18358 
18359 				delta    += cnt - 1;
18360 				env->prog = prog = new_prog;
18361 				insn      = new_prog->insnsi + i + delta;
18362 				continue;
18363 			}
18364 
18365 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18366 				     (void *(*)(struct bpf_map *map, void *key))NULL));
18367 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18368 				     (long (*)(struct bpf_map *map, void *key))NULL));
18369 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18370 				     (long (*)(struct bpf_map *map, void *key, void *value,
18371 					      u64 flags))NULL));
18372 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18373 				     (long (*)(struct bpf_map *map, void *value,
18374 					      u64 flags))NULL));
18375 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18376 				     (long (*)(struct bpf_map *map, void *value))NULL));
18377 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18378 				     (long (*)(struct bpf_map *map, void *value))NULL));
18379 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
18380 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18381 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18382 				     (long (*)(struct bpf_map *map,
18383 					      bpf_callback_t callback_fn,
18384 					      void *callback_ctx,
18385 					      u64 flags))NULL));
18386 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18387 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18388 
18389 patch_map_ops_generic:
18390 			switch (insn->imm) {
18391 			case BPF_FUNC_map_lookup_elem:
18392 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18393 				continue;
18394 			case BPF_FUNC_map_update_elem:
18395 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18396 				continue;
18397 			case BPF_FUNC_map_delete_elem:
18398 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18399 				continue;
18400 			case BPF_FUNC_map_push_elem:
18401 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18402 				continue;
18403 			case BPF_FUNC_map_pop_elem:
18404 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18405 				continue;
18406 			case BPF_FUNC_map_peek_elem:
18407 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18408 				continue;
18409 			case BPF_FUNC_redirect_map:
18410 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
18411 				continue;
18412 			case BPF_FUNC_for_each_map_elem:
18413 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18414 				continue;
18415 			case BPF_FUNC_map_lookup_percpu_elem:
18416 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18417 				continue;
18418 			}
18419 
18420 			goto patch_call_imm;
18421 		}
18422 
18423 		/* Implement bpf_jiffies64 inline. */
18424 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
18425 		    insn->imm == BPF_FUNC_jiffies64) {
18426 			struct bpf_insn ld_jiffies_addr[2] = {
18427 				BPF_LD_IMM64(BPF_REG_0,
18428 					     (unsigned long)&jiffies),
18429 			};
18430 
18431 			insn_buf[0] = ld_jiffies_addr[0];
18432 			insn_buf[1] = ld_jiffies_addr[1];
18433 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18434 						  BPF_REG_0, 0);
18435 			cnt = 3;
18436 
18437 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18438 						       cnt);
18439 			if (!new_prog)
18440 				return -ENOMEM;
18441 
18442 			delta    += cnt - 1;
18443 			env->prog = prog = new_prog;
18444 			insn      = new_prog->insnsi + i + delta;
18445 			continue;
18446 		}
18447 
18448 		/* Implement bpf_get_func_arg inline. */
18449 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18450 		    insn->imm == BPF_FUNC_get_func_arg) {
18451 			/* Load nr_args from ctx - 8 */
18452 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18453 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18454 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18455 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18456 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18457 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18458 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18459 			insn_buf[7] = BPF_JMP_A(1);
18460 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18461 			cnt = 9;
18462 
18463 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18464 			if (!new_prog)
18465 				return -ENOMEM;
18466 
18467 			delta    += cnt - 1;
18468 			env->prog = prog = new_prog;
18469 			insn      = new_prog->insnsi + i + delta;
18470 			continue;
18471 		}
18472 
18473 		/* Implement bpf_get_func_ret inline. */
18474 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18475 		    insn->imm == BPF_FUNC_get_func_ret) {
18476 			if (eatype == BPF_TRACE_FEXIT ||
18477 			    eatype == BPF_MODIFY_RETURN) {
18478 				/* Load nr_args from ctx - 8 */
18479 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18480 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18481 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18482 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18483 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18484 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18485 				cnt = 6;
18486 			} else {
18487 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18488 				cnt = 1;
18489 			}
18490 
18491 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18492 			if (!new_prog)
18493 				return -ENOMEM;
18494 
18495 			delta    += cnt - 1;
18496 			env->prog = prog = new_prog;
18497 			insn      = new_prog->insnsi + i + delta;
18498 			continue;
18499 		}
18500 
18501 		/* Implement get_func_arg_cnt inline. */
18502 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18503 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
18504 			/* Load nr_args from ctx - 8 */
18505 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18506 
18507 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18508 			if (!new_prog)
18509 				return -ENOMEM;
18510 
18511 			env->prog = prog = new_prog;
18512 			insn      = new_prog->insnsi + i + delta;
18513 			continue;
18514 		}
18515 
18516 		/* Implement bpf_get_func_ip inline. */
18517 		if (prog_type == BPF_PROG_TYPE_TRACING &&
18518 		    insn->imm == BPF_FUNC_get_func_ip) {
18519 			/* Load IP address from ctx - 16 */
18520 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18521 
18522 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18523 			if (!new_prog)
18524 				return -ENOMEM;
18525 
18526 			env->prog = prog = new_prog;
18527 			insn      = new_prog->insnsi + i + delta;
18528 			continue;
18529 		}
18530 
18531 patch_call_imm:
18532 		fn = env->ops->get_func_proto(insn->imm, env->prog);
18533 		/* all functions that have prototype and verifier allowed
18534 		 * programs to call them, must be real in-kernel functions
18535 		 */
18536 		if (!fn->func) {
18537 			verbose(env,
18538 				"kernel subsystem misconfigured func %s#%d\n",
18539 				func_id_name(insn->imm), insn->imm);
18540 			return -EFAULT;
18541 		}
18542 		insn->imm = fn->func - __bpf_call_base;
18543 	}
18544 
18545 	/* Since poke tab is now finalized, publish aux to tracker. */
18546 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18547 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18548 		if (!map_ptr->ops->map_poke_track ||
18549 		    !map_ptr->ops->map_poke_untrack ||
18550 		    !map_ptr->ops->map_poke_run) {
18551 			verbose(env, "bpf verifier is misconfigured\n");
18552 			return -EINVAL;
18553 		}
18554 
18555 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18556 		if (ret < 0) {
18557 			verbose(env, "tracking tail call prog failed\n");
18558 			return ret;
18559 		}
18560 	}
18561 
18562 	sort_kfunc_descs_by_imm_off(env->prog);
18563 
18564 	return 0;
18565 }
18566 
18567 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18568 					int position,
18569 					s32 stack_base,
18570 					u32 callback_subprogno,
18571 					u32 *cnt)
18572 {
18573 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18574 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18575 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18576 	int reg_loop_max = BPF_REG_6;
18577 	int reg_loop_cnt = BPF_REG_7;
18578 	int reg_loop_ctx = BPF_REG_8;
18579 
18580 	struct bpf_prog *new_prog;
18581 	u32 callback_start;
18582 	u32 call_insn_offset;
18583 	s32 callback_offset;
18584 
18585 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
18586 	 * be careful to modify this code in sync.
18587 	 */
18588 	struct bpf_insn insn_buf[] = {
18589 		/* Return error and jump to the end of the patch if
18590 		 * expected number of iterations is too big.
18591 		 */
18592 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18593 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18594 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18595 		/* spill R6, R7, R8 to use these as loop vars */
18596 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18597 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18598 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18599 		/* initialize loop vars */
18600 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18601 		BPF_MOV32_IMM(reg_loop_cnt, 0),
18602 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18603 		/* loop header,
18604 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
18605 		 */
18606 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18607 		/* callback call,
18608 		 * correct callback offset would be set after patching
18609 		 */
18610 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18611 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18612 		BPF_CALL_REL(0),
18613 		/* increment loop counter */
18614 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18615 		/* jump to loop header if callback returned 0 */
18616 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18617 		/* return value of bpf_loop,
18618 		 * set R0 to the number of iterations
18619 		 */
18620 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18621 		/* restore original values of R6, R7, R8 */
18622 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18623 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18624 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18625 	};
18626 
18627 	*cnt = ARRAY_SIZE(insn_buf);
18628 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18629 	if (!new_prog)
18630 		return new_prog;
18631 
18632 	/* callback start is known only after patching */
18633 	callback_start = env->subprog_info[callback_subprogno].start;
18634 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18635 	call_insn_offset = position + 12;
18636 	callback_offset = callback_start - call_insn_offset - 1;
18637 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
18638 
18639 	return new_prog;
18640 }
18641 
18642 static bool is_bpf_loop_call(struct bpf_insn *insn)
18643 {
18644 	return insn->code == (BPF_JMP | BPF_CALL) &&
18645 		insn->src_reg == 0 &&
18646 		insn->imm == BPF_FUNC_loop;
18647 }
18648 
18649 /* For all sub-programs in the program (including main) check
18650  * insn_aux_data to see if there are bpf_loop calls that require
18651  * inlining. If such calls are found the calls are replaced with a
18652  * sequence of instructions produced by `inline_bpf_loop` function and
18653  * subprog stack_depth is increased by the size of 3 registers.
18654  * This stack space is used to spill values of the R6, R7, R8.  These
18655  * registers are used to store the loop bound, counter and context
18656  * variables.
18657  */
18658 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18659 {
18660 	struct bpf_subprog_info *subprogs = env->subprog_info;
18661 	int i, cur_subprog = 0, cnt, delta = 0;
18662 	struct bpf_insn *insn = env->prog->insnsi;
18663 	int insn_cnt = env->prog->len;
18664 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
18665 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18666 	u16 stack_depth_extra = 0;
18667 
18668 	for (i = 0; i < insn_cnt; i++, insn++) {
18669 		struct bpf_loop_inline_state *inline_state =
18670 			&env->insn_aux_data[i + delta].loop_inline_state;
18671 
18672 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18673 			struct bpf_prog *new_prog;
18674 
18675 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18676 			new_prog = inline_bpf_loop(env,
18677 						   i + delta,
18678 						   -(stack_depth + stack_depth_extra),
18679 						   inline_state->callback_subprogno,
18680 						   &cnt);
18681 			if (!new_prog)
18682 				return -ENOMEM;
18683 
18684 			delta     += cnt - 1;
18685 			env->prog  = new_prog;
18686 			insn       = new_prog->insnsi + i + delta;
18687 		}
18688 
18689 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18690 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
18691 			cur_subprog++;
18692 			stack_depth = subprogs[cur_subprog].stack_depth;
18693 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18694 			stack_depth_extra = 0;
18695 		}
18696 	}
18697 
18698 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18699 
18700 	return 0;
18701 }
18702 
18703 static void free_states(struct bpf_verifier_env *env)
18704 {
18705 	struct bpf_verifier_state_list *sl, *sln;
18706 	int i;
18707 
18708 	sl = env->free_list;
18709 	while (sl) {
18710 		sln = sl->next;
18711 		free_verifier_state(&sl->state, false);
18712 		kfree(sl);
18713 		sl = sln;
18714 	}
18715 	env->free_list = NULL;
18716 
18717 	if (!env->explored_states)
18718 		return;
18719 
18720 	for (i = 0; i < state_htab_size(env); i++) {
18721 		sl = env->explored_states[i];
18722 
18723 		while (sl) {
18724 			sln = sl->next;
18725 			free_verifier_state(&sl->state, false);
18726 			kfree(sl);
18727 			sl = sln;
18728 		}
18729 		env->explored_states[i] = NULL;
18730 	}
18731 }
18732 
18733 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18734 {
18735 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18736 	struct bpf_verifier_state *state;
18737 	struct bpf_reg_state *regs;
18738 	int ret, i;
18739 
18740 	env->prev_linfo = NULL;
18741 	env->pass_cnt++;
18742 
18743 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18744 	if (!state)
18745 		return -ENOMEM;
18746 	state->curframe = 0;
18747 	state->speculative = false;
18748 	state->branches = 1;
18749 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18750 	if (!state->frame[0]) {
18751 		kfree(state);
18752 		return -ENOMEM;
18753 	}
18754 	env->cur_state = state;
18755 	init_func_state(env, state->frame[0],
18756 			BPF_MAIN_FUNC /* callsite */,
18757 			0 /* frameno */,
18758 			subprog);
18759 	state->first_insn_idx = env->subprog_info[subprog].start;
18760 	state->last_insn_idx = -1;
18761 
18762 	regs = state->frame[state->curframe]->regs;
18763 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18764 		ret = btf_prepare_func_args(env, subprog, regs);
18765 		if (ret)
18766 			goto out;
18767 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18768 			if (regs[i].type == PTR_TO_CTX)
18769 				mark_reg_known_zero(env, regs, i);
18770 			else if (regs[i].type == SCALAR_VALUE)
18771 				mark_reg_unknown(env, regs, i);
18772 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
18773 				const u32 mem_size = regs[i].mem_size;
18774 
18775 				mark_reg_known_zero(env, regs, i);
18776 				regs[i].mem_size = mem_size;
18777 				regs[i].id = ++env->id_gen;
18778 			}
18779 		}
18780 	} else {
18781 		/* 1st arg to a function */
18782 		regs[BPF_REG_1].type = PTR_TO_CTX;
18783 		mark_reg_known_zero(env, regs, BPF_REG_1);
18784 		ret = btf_check_subprog_arg_match(env, subprog, regs);
18785 		if (ret == -EFAULT)
18786 			/* unlikely verifier bug. abort.
18787 			 * ret == 0 and ret < 0 are sadly acceptable for
18788 			 * main() function due to backward compatibility.
18789 			 * Like socket filter program may be written as:
18790 			 * int bpf_prog(struct pt_regs *ctx)
18791 			 * and never dereference that ctx in the program.
18792 			 * 'struct pt_regs' is a type mismatch for socket
18793 			 * filter that should be using 'struct __sk_buff'.
18794 			 */
18795 			goto out;
18796 	}
18797 
18798 	ret = do_check(env);
18799 out:
18800 	/* check for NULL is necessary, since cur_state can be freed inside
18801 	 * do_check() under memory pressure.
18802 	 */
18803 	if (env->cur_state) {
18804 		free_verifier_state(env->cur_state, true);
18805 		env->cur_state = NULL;
18806 	}
18807 	while (!pop_stack(env, NULL, NULL, false));
18808 	if (!ret && pop_log)
18809 		bpf_vlog_reset(&env->log, 0);
18810 	free_states(env);
18811 	return ret;
18812 }
18813 
18814 /* Verify all global functions in a BPF program one by one based on their BTF.
18815  * All global functions must pass verification. Otherwise the whole program is rejected.
18816  * Consider:
18817  * int bar(int);
18818  * int foo(int f)
18819  * {
18820  *    return bar(f);
18821  * }
18822  * int bar(int b)
18823  * {
18824  *    ...
18825  * }
18826  * foo() will be verified first for R1=any_scalar_value. During verification it
18827  * will be assumed that bar() already verified successfully and call to bar()
18828  * from foo() will be checked for type match only. Later bar() will be verified
18829  * independently to check that it's safe for R1=any_scalar_value.
18830  */
18831 static int do_check_subprogs(struct bpf_verifier_env *env)
18832 {
18833 	struct bpf_prog_aux *aux = env->prog->aux;
18834 	int i, ret;
18835 
18836 	if (!aux->func_info)
18837 		return 0;
18838 
18839 	for (i = 1; i < env->subprog_cnt; i++) {
18840 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18841 			continue;
18842 		env->insn_idx = env->subprog_info[i].start;
18843 		WARN_ON_ONCE(env->insn_idx == 0);
18844 		ret = do_check_common(env, i);
18845 		if (ret) {
18846 			return ret;
18847 		} else if (env->log.level & BPF_LOG_LEVEL) {
18848 			verbose(env,
18849 				"Func#%d is safe for any args that match its prototype\n",
18850 				i);
18851 		}
18852 	}
18853 	return 0;
18854 }
18855 
18856 static int do_check_main(struct bpf_verifier_env *env)
18857 {
18858 	int ret;
18859 
18860 	env->insn_idx = 0;
18861 	ret = do_check_common(env, 0);
18862 	if (!ret)
18863 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18864 	return ret;
18865 }
18866 
18867 
18868 static void print_verification_stats(struct bpf_verifier_env *env)
18869 {
18870 	int i;
18871 
18872 	if (env->log.level & BPF_LOG_STATS) {
18873 		verbose(env, "verification time %lld usec\n",
18874 			div_u64(env->verification_time, 1000));
18875 		verbose(env, "stack depth ");
18876 		for (i = 0; i < env->subprog_cnt; i++) {
18877 			u32 depth = env->subprog_info[i].stack_depth;
18878 
18879 			verbose(env, "%d", depth);
18880 			if (i + 1 < env->subprog_cnt)
18881 				verbose(env, "+");
18882 		}
18883 		verbose(env, "\n");
18884 	}
18885 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18886 		"total_states %d peak_states %d mark_read %d\n",
18887 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18888 		env->max_states_per_insn, env->total_states,
18889 		env->peak_states, env->longest_mark_read_walk);
18890 }
18891 
18892 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18893 {
18894 	const struct btf_type *t, *func_proto;
18895 	const struct bpf_struct_ops *st_ops;
18896 	const struct btf_member *member;
18897 	struct bpf_prog *prog = env->prog;
18898 	u32 btf_id, member_idx;
18899 	const char *mname;
18900 
18901 	if (!prog->gpl_compatible) {
18902 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18903 		return -EINVAL;
18904 	}
18905 
18906 	btf_id = prog->aux->attach_btf_id;
18907 	st_ops = bpf_struct_ops_find(btf_id);
18908 	if (!st_ops) {
18909 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18910 			btf_id);
18911 		return -ENOTSUPP;
18912 	}
18913 
18914 	t = st_ops->type;
18915 	member_idx = prog->expected_attach_type;
18916 	if (member_idx >= btf_type_vlen(t)) {
18917 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18918 			member_idx, st_ops->name);
18919 		return -EINVAL;
18920 	}
18921 
18922 	member = &btf_type_member(t)[member_idx];
18923 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18924 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18925 					       NULL);
18926 	if (!func_proto) {
18927 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18928 			mname, member_idx, st_ops->name);
18929 		return -EINVAL;
18930 	}
18931 
18932 	if (st_ops->check_member) {
18933 		int err = st_ops->check_member(t, member, prog);
18934 
18935 		if (err) {
18936 			verbose(env, "attach to unsupported member %s of struct %s\n",
18937 				mname, st_ops->name);
18938 			return err;
18939 		}
18940 	}
18941 
18942 	prog->aux->attach_func_proto = func_proto;
18943 	prog->aux->attach_func_name = mname;
18944 	env->ops = st_ops->verifier_ops;
18945 
18946 	return 0;
18947 }
18948 #define SECURITY_PREFIX "security_"
18949 
18950 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18951 {
18952 	if (within_error_injection_list(addr) ||
18953 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18954 		return 0;
18955 
18956 	return -EINVAL;
18957 }
18958 
18959 /* list of non-sleepable functions that are otherwise on
18960  * ALLOW_ERROR_INJECTION list
18961  */
18962 BTF_SET_START(btf_non_sleepable_error_inject)
18963 /* Three functions below can be called from sleepable and non-sleepable context.
18964  * Assume non-sleepable from bpf safety point of view.
18965  */
18966 BTF_ID(func, __filemap_add_folio)
18967 BTF_ID(func, should_fail_alloc_page)
18968 BTF_ID(func, should_failslab)
18969 BTF_SET_END(btf_non_sleepable_error_inject)
18970 
18971 static int check_non_sleepable_error_inject(u32 btf_id)
18972 {
18973 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18974 }
18975 
18976 int bpf_check_attach_target(struct bpf_verifier_log *log,
18977 			    const struct bpf_prog *prog,
18978 			    const struct bpf_prog *tgt_prog,
18979 			    u32 btf_id,
18980 			    struct bpf_attach_target_info *tgt_info)
18981 {
18982 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18983 	const char prefix[] = "btf_trace_";
18984 	int ret = 0, subprog = -1, i;
18985 	const struct btf_type *t;
18986 	bool conservative = true;
18987 	const char *tname;
18988 	struct btf *btf;
18989 	long addr = 0;
18990 	struct module *mod = NULL;
18991 
18992 	if (!btf_id) {
18993 		bpf_log(log, "Tracing programs must provide btf_id\n");
18994 		return -EINVAL;
18995 	}
18996 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18997 	if (!btf) {
18998 		bpf_log(log,
18999 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19000 		return -EINVAL;
19001 	}
19002 	t = btf_type_by_id(btf, btf_id);
19003 	if (!t) {
19004 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19005 		return -EINVAL;
19006 	}
19007 	tname = btf_name_by_offset(btf, t->name_off);
19008 	if (!tname) {
19009 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19010 		return -EINVAL;
19011 	}
19012 	if (tgt_prog) {
19013 		struct bpf_prog_aux *aux = tgt_prog->aux;
19014 
19015 		if (bpf_prog_is_dev_bound(prog->aux) &&
19016 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19017 			bpf_log(log, "Target program bound device mismatch");
19018 			return -EINVAL;
19019 		}
19020 
19021 		for (i = 0; i < aux->func_info_cnt; i++)
19022 			if (aux->func_info[i].type_id == btf_id) {
19023 				subprog = i;
19024 				break;
19025 			}
19026 		if (subprog == -1) {
19027 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19028 			return -EINVAL;
19029 		}
19030 		conservative = aux->func_info_aux[subprog].unreliable;
19031 		if (prog_extension) {
19032 			if (conservative) {
19033 				bpf_log(log,
19034 					"Cannot replace static functions\n");
19035 				return -EINVAL;
19036 			}
19037 			if (!prog->jit_requested) {
19038 				bpf_log(log,
19039 					"Extension programs should be JITed\n");
19040 				return -EINVAL;
19041 			}
19042 		}
19043 		if (!tgt_prog->jited) {
19044 			bpf_log(log, "Can attach to only JITed progs\n");
19045 			return -EINVAL;
19046 		}
19047 		if (tgt_prog->type == prog->type) {
19048 			/* Cannot fentry/fexit another fentry/fexit program.
19049 			 * Cannot attach program extension to another extension.
19050 			 * It's ok to attach fentry/fexit to extension program.
19051 			 */
19052 			bpf_log(log, "Cannot recursively attach\n");
19053 			return -EINVAL;
19054 		}
19055 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19056 		    prog_extension &&
19057 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19058 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19059 			/* Program extensions can extend all program types
19060 			 * except fentry/fexit. The reason is the following.
19061 			 * The fentry/fexit programs are used for performance
19062 			 * analysis, stats and can be attached to any program
19063 			 * type except themselves. When extension program is
19064 			 * replacing XDP function it is necessary to allow
19065 			 * performance analysis of all functions. Both original
19066 			 * XDP program and its program extension. Hence
19067 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19068 			 * allowed. If extending of fentry/fexit was allowed it
19069 			 * would be possible to create long call chain
19070 			 * fentry->extension->fentry->extension beyond
19071 			 * reasonable stack size. Hence extending fentry is not
19072 			 * allowed.
19073 			 */
19074 			bpf_log(log, "Cannot extend fentry/fexit\n");
19075 			return -EINVAL;
19076 		}
19077 	} else {
19078 		if (prog_extension) {
19079 			bpf_log(log, "Cannot replace kernel functions\n");
19080 			return -EINVAL;
19081 		}
19082 	}
19083 
19084 	switch (prog->expected_attach_type) {
19085 	case BPF_TRACE_RAW_TP:
19086 		if (tgt_prog) {
19087 			bpf_log(log,
19088 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19089 			return -EINVAL;
19090 		}
19091 		if (!btf_type_is_typedef(t)) {
19092 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19093 				btf_id);
19094 			return -EINVAL;
19095 		}
19096 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19097 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19098 				btf_id, tname);
19099 			return -EINVAL;
19100 		}
19101 		tname += sizeof(prefix) - 1;
19102 		t = btf_type_by_id(btf, t->type);
19103 		if (!btf_type_is_ptr(t))
19104 			/* should never happen in valid vmlinux build */
19105 			return -EINVAL;
19106 		t = btf_type_by_id(btf, t->type);
19107 		if (!btf_type_is_func_proto(t))
19108 			/* should never happen in valid vmlinux build */
19109 			return -EINVAL;
19110 
19111 		break;
19112 	case BPF_TRACE_ITER:
19113 		if (!btf_type_is_func(t)) {
19114 			bpf_log(log, "attach_btf_id %u is not a function\n",
19115 				btf_id);
19116 			return -EINVAL;
19117 		}
19118 		t = btf_type_by_id(btf, t->type);
19119 		if (!btf_type_is_func_proto(t))
19120 			return -EINVAL;
19121 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19122 		if (ret)
19123 			return ret;
19124 		break;
19125 	default:
19126 		if (!prog_extension)
19127 			return -EINVAL;
19128 		fallthrough;
19129 	case BPF_MODIFY_RETURN:
19130 	case BPF_LSM_MAC:
19131 	case BPF_LSM_CGROUP:
19132 	case BPF_TRACE_FENTRY:
19133 	case BPF_TRACE_FEXIT:
19134 		if (!btf_type_is_func(t)) {
19135 			bpf_log(log, "attach_btf_id %u is not a function\n",
19136 				btf_id);
19137 			return -EINVAL;
19138 		}
19139 		if (prog_extension &&
19140 		    btf_check_type_match(log, prog, btf, t))
19141 			return -EINVAL;
19142 		t = btf_type_by_id(btf, t->type);
19143 		if (!btf_type_is_func_proto(t))
19144 			return -EINVAL;
19145 
19146 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19147 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19148 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19149 			return -EINVAL;
19150 
19151 		if (tgt_prog && conservative)
19152 			t = NULL;
19153 
19154 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19155 		if (ret < 0)
19156 			return ret;
19157 
19158 		if (tgt_prog) {
19159 			if (subprog == 0)
19160 				addr = (long) tgt_prog->bpf_func;
19161 			else
19162 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19163 		} else {
19164 			if (btf_is_module(btf)) {
19165 				mod = btf_try_get_module(btf);
19166 				if (mod)
19167 					addr = find_kallsyms_symbol_value(mod, tname);
19168 				else
19169 					addr = 0;
19170 			} else {
19171 				addr = kallsyms_lookup_name(tname);
19172 			}
19173 			if (!addr) {
19174 				module_put(mod);
19175 				bpf_log(log,
19176 					"The address of function %s cannot be found\n",
19177 					tname);
19178 				return -ENOENT;
19179 			}
19180 		}
19181 
19182 		if (prog->aux->sleepable) {
19183 			ret = -EINVAL;
19184 			switch (prog->type) {
19185 			case BPF_PROG_TYPE_TRACING:
19186 
19187 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
19188 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19189 				 */
19190 				if (!check_non_sleepable_error_inject(btf_id) &&
19191 				    within_error_injection_list(addr))
19192 					ret = 0;
19193 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
19194 				 * in the fmodret id set with the KF_SLEEPABLE flag.
19195 				 */
19196 				else {
19197 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19198 										prog);
19199 
19200 					if (flags && (*flags & KF_SLEEPABLE))
19201 						ret = 0;
19202 				}
19203 				break;
19204 			case BPF_PROG_TYPE_LSM:
19205 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
19206 				 * Only some of them are sleepable.
19207 				 */
19208 				if (bpf_lsm_is_sleepable_hook(btf_id))
19209 					ret = 0;
19210 				break;
19211 			default:
19212 				break;
19213 			}
19214 			if (ret) {
19215 				module_put(mod);
19216 				bpf_log(log, "%s is not sleepable\n", tname);
19217 				return ret;
19218 			}
19219 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19220 			if (tgt_prog) {
19221 				module_put(mod);
19222 				bpf_log(log, "can't modify return codes of BPF programs\n");
19223 				return -EINVAL;
19224 			}
19225 			ret = -EINVAL;
19226 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19227 			    !check_attach_modify_return(addr, tname))
19228 				ret = 0;
19229 			if (ret) {
19230 				module_put(mod);
19231 				bpf_log(log, "%s() is not modifiable\n", tname);
19232 				return ret;
19233 			}
19234 		}
19235 
19236 		break;
19237 	}
19238 	tgt_info->tgt_addr = addr;
19239 	tgt_info->tgt_name = tname;
19240 	tgt_info->tgt_type = t;
19241 	tgt_info->tgt_mod = mod;
19242 	return 0;
19243 }
19244 
19245 BTF_SET_START(btf_id_deny)
19246 BTF_ID_UNUSED
19247 #ifdef CONFIG_SMP
19248 BTF_ID(func, migrate_disable)
19249 BTF_ID(func, migrate_enable)
19250 #endif
19251 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19252 BTF_ID(func, rcu_read_unlock_strict)
19253 #endif
19254 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19255 BTF_ID(func, preempt_count_add)
19256 BTF_ID(func, preempt_count_sub)
19257 #endif
19258 #ifdef CONFIG_PREEMPT_RCU
19259 BTF_ID(func, __rcu_read_lock)
19260 BTF_ID(func, __rcu_read_unlock)
19261 #endif
19262 BTF_SET_END(btf_id_deny)
19263 
19264 static bool can_be_sleepable(struct bpf_prog *prog)
19265 {
19266 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19267 		switch (prog->expected_attach_type) {
19268 		case BPF_TRACE_FENTRY:
19269 		case BPF_TRACE_FEXIT:
19270 		case BPF_MODIFY_RETURN:
19271 		case BPF_TRACE_ITER:
19272 			return true;
19273 		default:
19274 			return false;
19275 		}
19276 	}
19277 	return prog->type == BPF_PROG_TYPE_LSM ||
19278 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19279 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19280 }
19281 
19282 static int check_attach_btf_id(struct bpf_verifier_env *env)
19283 {
19284 	struct bpf_prog *prog = env->prog;
19285 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19286 	struct bpf_attach_target_info tgt_info = {};
19287 	u32 btf_id = prog->aux->attach_btf_id;
19288 	struct bpf_trampoline *tr;
19289 	int ret;
19290 	u64 key;
19291 
19292 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19293 		if (prog->aux->sleepable)
19294 			/* attach_btf_id checked to be zero already */
19295 			return 0;
19296 		verbose(env, "Syscall programs can only be sleepable\n");
19297 		return -EINVAL;
19298 	}
19299 
19300 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19301 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19302 		return -EINVAL;
19303 	}
19304 
19305 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19306 		return check_struct_ops_btf_id(env);
19307 
19308 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19309 	    prog->type != BPF_PROG_TYPE_LSM &&
19310 	    prog->type != BPF_PROG_TYPE_EXT)
19311 		return 0;
19312 
19313 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19314 	if (ret)
19315 		return ret;
19316 
19317 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19318 		/* to make freplace equivalent to their targets, they need to
19319 		 * inherit env->ops and expected_attach_type for the rest of the
19320 		 * verification
19321 		 */
19322 		env->ops = bpf_verifier_ops[tgt_prog->type];
19323 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19324 	}
19325 
19326 	/* store info about the attachment target that will be used later */
19327 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19328 	prog->aux->attach_func_name = tgt_info.tgt_name;
19329 	prog->aux->mod = tgt_info.tgt_mod;
19330 
19331 	if (tgt_prog) {
19332 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19333 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19334 	}
19335 
19336 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19337 		prog->aux->attach_btf_trace = true;
19338 		return 0;
19339 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19340 		if (!bpf_iter_prog_supported(prog))
19341 			return -EINVAL;
19342 		return 0;
19343 	}
19344 
19345 	if (prog->type == BPF_PROG_TYPE_LSM) {
19346 		ret = bpf_lsm_verify_prog(&env->log, prog);
19347 		if (ret < 0)
19348 			return ret;
19349 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19350 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19351 		return -EINVAL;
19352 	}
19353 
19354 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19355 	tr = bpf_trampoline_get(key, &tgt_info);
19356 	if (!tr)
19357 		return -ENOMEM;
19358 
19359 	prog->aux->dst_trampoline = tr;
19360 	return 0;
19361 }
19362 
19363 struct btf *bpf_get_btf_vmlinux(void)
19364 {
19365 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19366 		mutex_lock(&bpf_verifier_lock);
19367 		if (!btf_vmlinux)
19368 			btf_vmlinux = btf_parse_vmlinux();
19369 		mutex_unlock(&bpf_verifier_lock);
19370 	}
19371 	return btf_vmlinux;
19372 }
19373 
19374 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19375 {
19376 	u64 start_time = ktime_get_ns();
19377 	struct bpf_verifier_env *env;
19378 	int i, len, ret = -EINVAL, err;
19379 	u32 log_true_size;
19380 	bool is_priv;
19381 
19382 	/* no program is valid */
19383 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19384 		return -EINVAL;
19385 
19386 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19387 	 * allocate/free it every time bpf_check() is called
19388 	 */
19389 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19390 	if (!env)
19391 		return -ENOMEM;
19392 
19393 	env->bt.env = env;
19394 
19395 	len = (*prog)->len;
19396 	env->insn_aux_data =
19397 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19398 	ret = -ENOMEM;
19399 	if (!env->insn_aux_data)
19400 		goto err_free_env;
19401 	for (i = 0; i < len; i++)
19402 		env->insn_aux_data[i].orig_idx = i;
19403 	env->prog = *prog;
19404 	env->ops = bpf_verifier_ops[env->prog->type];
19405 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19406 	is_priv = bpf_capable();
19407 
19408 	bpf_get_btf_vmlinux();
19409 
19410 	/* grab the mutex to protect few globals used by verifier */
19411 	if (!is_priv)
19412 		mutex_lock(&bpf_verifier_lock);
19413 
19414 	/* user could have requested verbose verifier output
19415 	 * and supplied buffer to store the verification trace
19416 	 */
19417 	ret = bpf_vlog_init(&env->log, attr->log_level,
19418 			    (char __user *) (unsigned long) attr->log_buf,
19419 			    attr->log_size);
19420 	if (ret)
19421 		goto err_unlock;
19422 
19423 	mark_verifier_state_clean(env);
19424 
19425 	if (IS_ERR(btf_vmlinux)) {
19426 		/* Either gcc or pahole or kernel are broken. */
19427 		verbose(env, "in-kernel BTF is malformed\n");
19428 		ret = PTR_ERR(btf_vmlinux);
19429 		goto skip_full_check;
19430 	}
19431 
19432 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19433 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19434 		env->strict_alignment = true;
19435 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19436 		env->strict_alignment = false;
19437 
19438 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19439 	env->allow_uninit_stack = bpf_allow_uninit_stack();
19440 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
19441 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
19442 	env->bpf_capable = bpf_capable();
19443 
19444 	if (is_priv)
19445 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19446 
19447 	env->explored_states = kvcalloc(state_htab_size(env),
19448 				       sizeof(struct bpf_verifier_state_list *),
19449 				       GFP_USER);
19450 	ret = -ENOMEM;
19451 	if (!env->explored_states)
19452 		goto skip_full_check;
19453 
19454 	ret = add_subprog_and_kfunc(env);
19455 	if (ret < 0)
19456 		goto skip_full_check;
19457 
19458 	ret = check_subprogs(env);
19459 	if (ret < 0)
19460 		goto skip_full_check;
19461 
19462 	ret = check_btf_info(env, attr, uattr);
19463 	if (ret < 0)
19464 		goto skip_full_check;
19465 
19466 	ret = check_attach_btf_id(env);
19467 	if (ret)
19468 		goto skip_full_check;
19469 
19470 	ret = resolve_pseudo_ldimm64(env);
19471 	if (ret < 0)
19472 		goto skip_full_check;
19473 
19474 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19475 		ret = bpf_prog_offload_verifier_prep(env->prog);
19476 		if (ret)
19477 			goto skip_full_check;
19478 	}
19479 
19480 	ret = check_cfg(env);
19481 	if (ret < 0)
19482 		goto skip_full_check;
19483 
19484 	ret = do_check_subprogs(env);
19485 	ret = ret ?: do_check_main(env);
19486 
19487 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19488 		ret = bpf_prog_offload_finalize(env);
19489 
19490 skip_full_check:
19491 	kvfree(env->explored_states);
19492 
19493 	if (ret == 0)
19494 		ret = check_max_stack_depth(env);
19495 
19496 	/* instruction rewrites happen after this point */
19497 	if (ret == 0)
19498 		ret = optimize_bpf_loop(env);
19499 
19500 	if (is_priv) {
19501 		if (ret == 0)
19502 			opt_hard_wire_dead_code_branches(env);
19503 		if (ret == 0)
19504 			ret = opt_remove_dead_code(env);
19505 		if (ret == 0)
19506 			ret = opt_remove_nops(env);
19507 	} else {
19508 		if (ret == 0)
19509 			sanitize_dead_code(env);
19510 	}
19511 
19512 	if (ret == 0)
19513 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19514 		ret = convert_ctx_accesses(env);
19515 
19516 	if (ret == 0)
19517 		ret = do_misc_fixups(env);
19518 
19519 	/* do 32-bit optimization after insn patching has done so those patched
19520 	 * insns could be handled correctly.
19521 	 */
19522 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19523 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19524 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19525 								     : false;
19526 	}
19527 
19528 	if (ret == 0)
19529 		ret = fixup_call_args(env);
19530 
19531 	env->verification_time = ktime_get_ns() - start_time;
19532 	print_verification_stats(env);
19533 	env->prog->aux->verified_insns = env->insn_processed;
19534 
19535 	/* preserve original error even if log finalization is successful */
19536 	err = bpf_vlog_finalize(&env->log, &log_true_size);
19537 	if (err)
19538 		ret = err;
19539 
19540 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19541 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19542 				  &log_true_size, sizeof(log_true_size))) {
19543 		ret = -EFAULT;
19544 		goto err_release_maps;
19545 	}
19546 
19547 	if (ret)
19548 		goto err_release_maps;
19549 
19550 	if (env->used_map_cnt) {
19551 		/* if program passed verifier, update used_maps in bpf_prog_info */
19552 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19553 							  sizeof(env->used_maps[0]),
19554 							  GFP_KERNEL);
19555 
19556 		if (!env->prog->aux->used_maps) {
19557 			ret = -ENOMEM;
19558 			goto err_release_maps;
19559 		}
19560 
19561 		memcpy(env->prog->aux->used_maps, env->used_maps,
19562 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
19563 		env->prog->aux->used_map_cnt = env->used_map_cnt;
19564 	}
19565 	if (env->used_btf_cnt) {
19566 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
19567 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19568 							  sizeof(env->used_btfs[0]),
19569 							  GFP_KERNEL);
19570 		if (!env->prog->aux->used_btfs) {
19571 			ret = -ENOMEM;
19572 			goto err_release_maps;
19573 		}
19574 
19575 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
19576 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19577 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19578 	}
19579 	if (env->used_map_cnt || env->used_btf_cnt) {
19580 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
19581 		 * bpf_ld_imm64 instructions
19582 		 */
19583 		convert_pseudo_ld_imm64(env);
19584 	}
19585 
19586 	adjust_btf_func(env);
19587 
19588 err_release_maps:
19589 	if (!env->prog->aux->used_maps)
19590 		/* if we didn't copy map pointers into bpf_prog_info, release
19591 		 * them now. Otherwise free_used_maps() will release them.
19592 		 */
19593 		release_maps(env);
19594 	if (!env->prog->aux->used_btfs)
19595 		release_btfs(env);
19596 
19597 	/* extension progs temporarily inherit the attach_type of their targets
19598 	   for verification purposes, so set it back to zero before returning
19599 	 */
19600 	if (env->prog->type == BPF_PROG_TYPE_EXT)
19601 		env->prog->expected_attach_type = 0;
19602 
19603 	*prog = env->prog;
19604 err_unlock:
19605 	if (!is_priv)
19606 		mutex_unlock(&bpf_verifier_lock);
19607 	vfree(env->insn_aux_data);
19608 err_free_env:
19609 	kfree(env);
19610 	return ret;
19611 }
19612