xref: /openbmc/linux/kernel/bpf/verifier.c (revision ed4c7d61)
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 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
194 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
195 static int ref_set_non_owning(struct bpf_verifier_env *env,
196 			      struct bpf_reg_state *reg);
197 
198 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
199 {
200 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
201 }
202 
203 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
204 {
205 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
206 }
207 
208 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
209 			      const struct bpf_map *map, bool unpriv)
210 {
211 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
212 	unpriv |= bpf_map_ptr_unpriv(aux);
213 	aux->map_ptr_state = (unsigned long)map |
214 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
215 }
216 
217 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
218 {
219 	return aux->map_key_state & BPF_MAP_KEY_POISON;
220 }
221 
222 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
223 {
224 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
225 }
226 
227 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
228 {
229 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
230 }
231 
232 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
233 {
234 	bool poisoned = bpf_map_key_poisoned(aux);
235 
236 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
237 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
238 }
239 
240 static bool bpf_pseudo_call(const struct bpf_insn *insn)
241 {
242 	return insn->code == (BPF_JMP | BPF_CALL) &&
243 	       insn->src_reg == BPF_PSEUDO_CALL;
244 }
245 
246 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
250 }
251 
252 struct bpf_call_arg_meta {
253 	struct bpf_map *map_ptr;
254 	bool raw_mode;
255 	bool pkt_access;
256 	u8 release_regno;
257 	int regno;
258 	int access_size;
259 	int mem_size;
260 	u64 msize_max_value;
261 	int ref_obj_id;
262 	int dynptr_id;
263 	int map_uid;
264 	int func_id;
265 	struct btf *btf;
266 	u32 btf_id;
267 	struct btf *ret_btf;
268 	u32 ret_btf_id;
269 	u32 subprogno;
270 	struct btf_field *kptr_field;
271 };
272 
273 struct bpf_kfunc_call_arg_meta {
274 	/* In parameters */
275 	struct btf *btf;
276 	u32 func_id;
277 	u32 kfunc_flags;
278 	const struct btf_type *func_proto;
279 	const char *func_name;
280 	/* Out parameters */
281 	u32 ref_obj_id;
282 	u8 release_regno;
283 	bool r0_rdonly;
284 	u32 ret_btf_id;
285 	u64 r0_size;
286 	u32 subprogno;
287 	struct {
288 		u64 value;
289 		bool found;
290 	} arg_constant;
291 	struct {
292 		struct btf *btf;
293 		u32 btf_id;
294 	} arg_obj_drop;
295 	struct {
296 		struct btf_field *field;
297 	} arg_list_head;
298 	struct {
299 		struct btf_field *field;
300 	} arg_rbtree_root;
301 	struct {
302 		enum bpf_dynptr_type type;
303 		u32 id;
304 	} initialized_dynptr;
305 	u64 mem_size;
306 };
307 
308 struct btf *btf_vmlinux;
309 
310 static DEFINE_MUTEX(bpf_verifier_lock);
311 
312 static const struct bpf_line_info *
313 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
314 {
315 	const struct bpf_line_info *linfo;
316 	const struct bpf_prog *prog;
317 	u32 i, nr_linfo;
318 
319 	prog = env->prog;
320 	nr_linfo = prog->aux->nr_linfo;
321 
322 	if (!nr_linfo || insn_off >= prog->len)
323 		return NULL;
324 
325 	linfo = prog->aux->linfo;
326 	for (i = 1; i < nr_linfo; i++)
327 		if (insn_off < linfo[i].insn_off)
328 			break;
329 
330 	return &linfo[i - 1];
331 }
332 
333 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
334 		       va_list args)
335 {
336 	unsigned int n;
337 
338 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
339 
340 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
341 		  "verifier log line truncated - local buffer too short\n");
342 
343 	if (log->level == BPF_LOG_KERNEL) {
344 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
345 
346 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
347 		return;
348 	}
349 
350 	n = min(log->len_total - log->len_used - 1, n);
351 	log->kbuf[n] = '\0';
352 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
353 		log->len_used += n;
354 	else
355 		log->ubuf = NULL;
356 }
357 
358 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
359 {
360 	char zero = 0;
361 
362 	if (!bpf_verifier_log_needed(log))
363 		return;
364 
365 	log->len_used = new_pos;
366 	if (put_user(zero, log->ubuf + new_pos))
367 		log->ubuf = NULL;
368 }
369 
370 /* log_level controls verbosity level of eBPF verifier.
371  * bpf_verifier_log_write() is used to dump the verification trace to the log,
372  * so the user can figure out what's wrong with the program
373  */
374 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
375 					   const char *fmt, ...)
376 {
377 	va_list args;
378 
379 	if (!bpf_verifier_log_needed(&env->log))
380 		return;
381 
382 	va_start(args, fmt);
383 	bpf_verifier_vlog(&env->log, fmt, args);
384 	va_end(args);
385 }
386 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
387 
388 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
389 {
390 	struct bpf_verifier_env *env = private_data;
391 	va_list args;
392 
393 	if (!bpf_verifier_log_needed(&env->log))
394 		return;
395 
396 	va_start(args, fmt);
397 	bpf_verifier_vlog(&env->log, fmt, args);
398 	va_end(args);
399 }
400 
401 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
402 			    const char *fmt, ...)
403 {
404 	va_list args;
405 
406 	if (!bpf_verifier_log_needed(log))
407 		return;
408 
409 	va_start(args, fmt);
410 	bpf_verifier_vlog(log, fmt, args);
411 	va_end(args);
412 }
413 EXPORT_SYMBOL_GPL(bpf_log);
414 
415 static const char *ltrim(const char *s)
416 {
417 	while (isspace(*s))
418 		s++;
419 
420 	return s;
421 }
422 
423 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
424 					 u32 insn_off,
425 					 const char *prefix_fmt, ...)
426 {
427 	const struct bpf_line_info *linfo;
428 
429 	if (!bpf_verifier_log_needed(&env->log))
430 		return;
431 
432 	linfo = find_linfo(env, insn_off);
433 	if (!linfo || linfo == env->prev_linfo)
434 		return;
435 
436 	if (prefix_fmt) {
437 		va_list args;
438 
439 		va_start(args, prefix_fmt);
440 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
441 		va_end(args);
442 	}
443 
444 	verbose(env, "%s\n",
445 		ltrim(btf_name_by_offset(env->prog->aux->btf,
446 					 linfo->line_off)));
447 
448 	env->prev_linfo = linfo;
449 }
450 
451 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
452 				   struct bpf_reg_state *reg,
453 				   struct tnum *range, const char *ctx,
454 				   const char *reg_name)
455 {
456 	char tn_buf[48];
457 
458 	verbose(env, "At %s the register %s ", ctx, reg_name);
459 	if (!tnum_is_unknown(reg->var_off)) {
460 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
461 		verbose(env, "has value %s", tn_buf);
462 	} else {
463 		verbose(env, "has unknown scalar value");
464 	}
465 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
466 	verbose(env, " should have been in %s\n", tn_buf);
467 }
468 
469 static bool type_is_pkt_pointer(enum bpf_reg_type type)
470 {
471 	type = base_type(type);
472 	return type == PTR_TO_PACKET ||
473 	       type == PTR_TO_PACKET_META;
474 }
475 
476 static bool type_is_sk_pointer(enum bpf_reg_type type)
477 {
478 	return type == PTR_TO_SOCKET ||
479 		type == PTR_TO_SOCK_COMMON ||
480 		type == PTR_TO_TCP_SOCK ||
481 		type == PTR_TO_XDP_SOCK;
482 }
483 
484 static bool reg_type_not_null(enum bpf_reg_type type)
485 {
486 	return type == PTR_TO_SOCKET ||
487 		type == PTR_TO_TCP_SOCK ||
488 		type == PTR_TO_MAP_VALUE ||
489 		type == PTR_TO_MAP_KEY ||
490 		type == PTR_TO_SOCK_COMMON ||
491 		type == PTR_TO_MEM;
492 }
493 
494 static bool type_is_ptr_alloc_obj(u32 type)
495 {
496 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
497 }
498 
499 static bool type_is_non_owning_ref(u32 type)
500 {
501 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
502 }
503 
504 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
505 {
506 	struct btf_record *rec = NULL;
507 	struct btf_struct_meta *meta;
508 
509 	if (reg->type == PTR_TO_MAP_VALUE) {
510 		rec = reg->map_ptr->record;
511 	} else if (type_is_ptr_alloc_obj(reg->type)) {
512 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
513 		if (meta)
514 			rec = meta->record;
515 	}
516 	return rec;
517 }
518 
519 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
520 {
521 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
522 }
523 
524 static bool type_is_rdonly_mem(u32 type)
525 {
526 	return type & MEM_RDONLY;
527 }
528 
529 static bool type_may_be_null(u32 type)
530 {
531 	return type & PTR_MAYBE_NULL;
532 }
533 
534 static bool is_acquire_function(enum bpf_func_id func_id,
535 				const struct bpf_map *map)
536 {
537 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
538 
539 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
540 	    func_id == BPF_FUNC_sk_lookup_udp ||
541 	    func_id == BPF_FUNC_skc_lookup_tcp ||
542 	    func_id == BPF_FUNC_ringbuf_reserve ||
543 	    func_id == BPF_FUNC_kptr_xchg)
544 		return true;
545 
546 	if (func_id == BPF_FUNC_map_lookup_elem &&
547 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
548 	     map_type == BPF_MAP_TYPE_SOCKHASH))
549 		return true;
550 
551 	return false;
552 }
553 
554 static bool is_ptr_cast_function(enum bpf_func_id func_id)
555 {
556 	return func_id == BPF_FUNC_tcp_sock ||
557 		func_id == BPF_FUNC_sk_fullsock ||
558 		func_id == BPF_FUNC_skc_to_tcp_sock ||
559 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
560 		func_id == BPF_FUNC_skc_to_udp6_sock ||
561 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
562 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
563 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
564 }
565 
566 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
567 {
568 	return func_id == BPF_FUNC_dynptr_data;
569 }
570 
571 static bool is_callback_calling_function(enum bpf_func_id func_id)
572 {
573 	return func_id == BPF_FUNC_for_each_map_elem ||
574 	       func_id == BPF_FUNC_timer_set_callback ||
575 	       func_id == BPF_FUNC_find_vma ||
576 	       func_id == BPF_FUNC_loop ||
577 	       func_id == BPF_FUNC_user_ringbuf_drain;
578 }
579 
580 static bool is_storage_get_function(enum bpf_func_id func_id)
581 {
582 	return func_id == BPF_FUNC_sk_storage_get ||
583 	       func_id == BPF_FUNC_inode_storage_get ||
584 	       func_id == BPF_FUNC_task_storage_get ||
585 	       func_id == BPF_FUNC_cgrp_storage_get;
586 }
587 
588 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
589 					const struct bpf_map *map)
590 {
591 	int ref_obj_uses = 0;
592 
593 	if (is_ptr_cast_function(func_id))
594 		ref_obj_uses++;
595 	if (is_acquire_function(func_id, map))
596 		ref_obj_uses++;
597 	if (is_dynptr_ref_function(func_id))
598 		ref_obj_uses++;
599 
600 	return ref_obj_uses > 1;
601 }
602 
603 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
604 {
605 	return BPF_CLASS(insn->code) == BPF_STX &&
606 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
607 	       insn->imm == BPF_CMPXCHG;
608 }
609 
610 /* string representation of 'enum bpf_reg_type'
611  *
612  * Note that reg_type_str() can not appear more than once in a single verbose()
613  * statement.
614  */
615 static const char *reg_type_str(struct bpf_verifier_env *env,
616 				enum bpf_reg_type type)
617 {
618 	char postfix[16] = {0}, prefix[64] = {0};
619 	static const char * const str[] = {
620 		[NOT_INIT]		= "?",
621 		[SCALAR_VALUE]		= "scalar",
622 		[PTR_TO_CTX]		= "ctx",
623 		[CONST_PTR_TO_MAP]	= "map_ptr",
624 		[PTR_TO_MAP_VALUE]	= "map_value",
625 		[PTR_TO_STACK]		= "fp",
626 		[PTR_TO_PACKET]		= "pkt",
627 		[PTR_TO_PACKET_META]	= "pkt_meta",
628 		[PTR_TO_PACKET_END]	= "pkt_end",
629 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
630 		[PTR_TO_SOCKET]		= "sock",
631 		[PTR_TO_SOCK_COMMON]	= "sock_common",
632 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
633 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
634 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
635 		[PTR_TO_BTF_ID]		= "ptr_",
636 		[PTR_TO_MEM]		= "mem",
637 		[PTR_TO_BUF]		= "buf",
638 		[PTR_TO_FUNC]		= "func",
639 		[PTR_TO_MAP_KEY]	= "map_key",
640 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
641 	};
642 
643 	if (type & PTR_MAYBE_NULL) {
644 		if (base_type(type) == PTR_TO_BTF_ID)
645 			strncpy(postfix, "or_null_", 16);
646 		else
647 			strncpy(postfix, "_or_null", 16);
648 	}
649 
650 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
651 		 type & MEM_RDONLY ? "rdonly_" : "",
652 		 type & MEM_RINGBUF ? "ringbuf_" : "",
653 		 type & MEM_USER ? "user_" : "",
654 		 type & MEM_PERCPU ? "percpu_" : "",
655 		 type & MEM_RCU ? "rcu_" : "",
656 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
657 		 type & PTR_TRUSTED ? "trusted_" : ""
658 	);
659 
660 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
661 		 prefix, str[base_type(type)], postfix);
662 	return env->type_str_buf;
663 }
664 
665 static char slot_type_char[] = {
666 	[STACK_INVALID]	= '?',
667 	[STACK_SPILL]	= 'r',
668 	[STACK_MISC]	= 'm',
669 	[STACK_ZERO]	= '0',
670 	[STACK_DYNPTR]	= 'd',
671 };
672 
673 static void print_liveness(struct bpf_verifier_env *env,
674 			   enum bpf_reg_liveness live)
675 {
676 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
677 	    verbose(env, "_");
678 	if (live & REG_LIVE_READ)
679 		verbose(env, "r");
680 	if (live & REG_LIVE_WRITTEN)
681 		verbose(env, "w");
682 	if (live & REG_LIVE_DONE)
683 		verbose(env, "D");
684 }
685 
686 static int __get_spi(s32 off)
687 {
688 	return (-off - 1) / BPF_REG_SIZE;
689 }
690 
691 static struct bpf_func_state *func(struct bpf_verifier_env *env,
692 				   const struct bpf_reg_state *reg)
693 {
694 	struct bpf_verifier_state *cur = env->cur_state;
695 
696 	return cur->frame[reg->frameno];
697 }
698 
699 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
700 {
701        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
702 
703        /* We need to check that slots between [spi - nr_slots + 1, spi] are
704 	* within [0, allocated_stack).
705 	*
706 	* Please note that the spi grows downwards. For example, a dynptr
707 	* takes the size of two stack slots; the first slot will be at
708 	* spi and the second slot will be at spi - 1.
709 	*/
710        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
711 }
712 
713 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
714 			          const char *obj_kind, int nr_slots)
715 {
716 	int off, spi;
717 
718 	if (!tnum_is_const(reg->var_off)) {
719 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
720 		return -EINVAL;
721 	}
722 
723 	off = reg->off + reg->var_off.value;
724 	if (off % BPF_REG_SIZE) {
725 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
726 		return -EINVAL;
727 	}
728 
729 	spi = __get_spi(off);
730 	if (spi + 1 < nr_slots) {
731 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
732 		return -EINVAL;
733 	}
734 
735 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
736 		return -ERANGE;
737 	return spi;
738 }
739 
740 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
741 {
742 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
743 }
744 
745 static const char *kernel_type_name(const struct btf* btf, u32 id)
746 {
747 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
748 }
749 
750 static const char *dynptr_type_str(enum bpf_dynptr_type type)
751 {
752 	switch (type) {
753 	case BPF_DYNPTR_TYPE_LOCAL:
754 		return "local";
755 	case BPF_DYNPTR_TYPE_RINGBUF:
756 		return "ringbuf";
757 	case BPF_DYNPTR_TYPE_SKB:
758 		return "skb";
759 	case BPF_DYNPTR_TYPE_XDP:
760 		return "xdp";
761 	case BPF_DYNPTR_TYPE_INVALID:
762 		return "<invalid>";
763 	default:
764 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
765 		return "<unknown>";
766 	}
767 }
768 
769 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
770 {
771 	env->scratched_regs |= 1U << regno;
772 }
773 
774 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
775 {
776 	env->scratched_stack_slots |= 1ULL << spi;
777 }
778 
779 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
780 {
781 	return (env->scratched_regs >> regno) & 1;
782 }
783 
784 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
785 {
786 	return (env->scratched_stack_slots >> regno) & 1;
787 }
788 
789 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
790 {
791 	return env->scratched_regs || env->scratched_stack_slots;
792 }
793 
794 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
795 {
796 	env->scratched_regs = 0U;
797 	env->scratched_stack_slots = 0ULL;
798 }
799 
800 /* Used for printing the entire verifier state. */
801 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
802 {
803 	env->scratched_regs = ~0U;
804 	env->scratched_stack_slots = ~0ULL;
805 }
806 
807 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
808 {
809 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
810 	case DYNPTR_TYPE_LOCAL:
811 		return BPF_DYNPTR_TYPE_LOCAL;
812 	case DYNPTR_TYPE_RINGBUF:
813 		return BPF_DYNPTR_TYPE_RINGBUF;
814 	case DYNPTR_TYPE_SKB:
815 		return BPF_DYNPTR_TYPE_SKB;
816 	case DYNPTR_TYPE_XDP:
817 		return BPF_DYNPTR_TYPE_XDP;
818 	default:
819 		return BPF_DYNPTR_TYPE_INVALID;
820 	}
821 }
822 
823 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
824 {
825 	switch (type) {
826 	case BPF_DYNPTR_TYPE_LOCAL:
827 		return DYNPTR_TYPE_LOCAL;
828 	case BPF_DYNPTR_TYPE_RINGBUF:
829 		return DYNPTR_TYPE_RINGBUF;
830 	case BPF_DYNPTR_TYPE_SKB:
831 		return DYNPTR_TYPE_SKB;
832 	case BPF_DYNPTR_TYPE_XDP:
833 		return DYNPTR_TYPE_XDP;
834 	default:
835 		return 0;
836 	}
837 }
838 
839 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
840 {
841 	return type == BPF_DYNPTR_TYPE_RINGBUF;
842 }
843 
844 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
845 			      enum bpf_dynptr_type type,
846 			      bool first_slot, int dynptr_id);
847 
848 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
849 				struct bpf_reg_state *reg);
850 
851 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
852 				   struct bpf_reg_state *sreg1,
853 				   struct bpf_reg_state *sreg2,
854 				   enum bpf_dynptr_type type)
855 {
856 	int id = ++env->id_gen;
857 
858 	__mark_dynptr_reg(sreg1, type, true, id);
859 	__mark_dynptr_reg(sreg2, type, false, id);
860 }
861 
862 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
863 			       struct bpf_reg_state *reg,
864 			       enum bpf_dynptr_type type)
865 {
866 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
867 }
868 
869 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
870 				        struct bpf_func_state *state, int spi);
871 
872 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
873 				   enum bpf_arg_type arg_type, int insn_idx)
874 {
875 	struct bpf_func_state *state = func(env, reg);
876 	enum bpf_dynptr_type type;
877 	int spi, i, id, err;
878 
879 	spi = dynptr_get_spi(env, reg);
880 	if (spi < 0)
881 		return spi;
882 
883 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
884 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
885 	 * to ensure that for the following example:
886 	 *	[d1][d1][d2][d2]
887 	 * spi    3   2   1   0
888 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
889 	 * case they do belong to same dynptr, second call won't see slot_type
890 	 * as STACK_DYNPTR and will simply skip destruction.
891 	 */
892 	err = destroy_if_dynptr_stack_slot(env, state, spi);
893 	if (err)
894 		return err;
895 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
896 	if (err)
897 		return err;
898 
899 	for (i = 0; i < BPF_REG_SIZE; i++) {
900 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
901 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
902 	}
903 
904 	type = arg_to_dynptr_type(arg_type);
905 	if (type == BPF_DYNPTR_TYPE_INVALID)
906 		return -EINVAL;
907 
908 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
909 			       &state->stack[spi - 1].spilled_ptr, type);
910 
911 	if (dynptr_type_refcounted(type)) {
912 		/* The id is used to track proper releasing */
913 		id = acquire_reference_state(env, insn_idx);
914 		if (id < 0)
915 			return id;
916 
917 		state->stack[spi].spilled_ptr.ref_obj_id = id;
918 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
919 	}
920 
921 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
922 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
923 
924 	return 0;
925 }
926 
927 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
928 {
929 	struct bpf_func_state *state = func(env, reg);
930 	int spi, i;
931 
932 	spi = dynptr_get_spi(env, reg);
933 	if (spi < 0)
934 		return spi;
935 
936 	for (i = 0; i < BPF_REG_SIZE; i++) {
937 		state->stack[spi].slot_type[i] = STACK_INVALID;
938 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
939 	}
940 
941 	/* Invalidate any slices associated with this dynptr */
942 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
943 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
944 
945 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
946 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
947 
948 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
949 	 *
950 	 * While we don't allow reading STACK_INVALID, it is still possible to
951 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
952 	 * helpers or insns can do partial read of that part without failing,
953 	 * but check_stack_range_initialized, check_stack_read_var_off, and
954 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
955 	 * the slot conservatively. Hence we need to prevent those liveness
956 	 * marking walks.
957 	 *
958 	 * This was not a problem before because STACK_INVALID is only set by
959 	 * default (where the default reg state has its reg->parent as NULL), or
960 	 * in clean_live_states after REG_LIVE_DONE (at which point
961 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
962 	 * verifier state exploration (like we did above). Hence, for our case
963 	 * parentage chain will still be live (i.e. reg->parent may be
964 	 * non-NULL), while earlier reg->parent was NULL, so we need
965 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
966 	 * done later on reads or by mark_dynptr_read as well to unnecessary
967 	 * mark registers in verifier state.
968 	 */
969 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
970 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
971 
972 	return 0;
973 }
974 
975 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
976 			       struct bpf_reg_state *reg);
977 
978 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
979 {
980 	if (!env->allow_ptr_leaks)
981 		__mark_reg_not_init(env, reg);
982 	else
983 		__mark_reg_unknown(env, reg);
984 }
985 
986 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
987 				        struct bpf_func_state *state, int spi)
988 {
989 	struct bpf_func_state *fstate;
990 	struct bpf_reg_state *dreg;
991 	int i, dynptr_id;
992 
993 	/* We always ensure that STACK_DYNPTR is never set partially,
994 	 * hence just checking for slot_type[0] is enough. This is
995 	 * different for STACK_SPILL, where it may be only set for
996 	 * 1 byte, so code has to use is_spilled_reg.
997 	 */
998 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
999 		return 0;
1000 
1001 	/* Reposition spi to first slot */
1002 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1003 		spi = spi + 1;
1004 
1005 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1006 		verbose(env, "cannot overwrite referenced dynptr\n");
1007 		return -EINVAL;
1008 	}
1009 
1010 	mark_stack_slot_scratched(env, spi);
1011 	mark_stack_slot_scratched(env, spi - 1);
1012 
1013 	/* Writing partially to one dynptr stack slot destroys both. */
1014 	for (i = 0; i < BPF_REG_SIZE; i++) {
1015 		state->stack[spi].slot_type[i] = STACK_INVALID;
1016 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1017 	}
1018 
1019 	dynptr_id = state->stack[spi].spilled_ptr.id;
1020 	/* Invalidate any slices associated with this dynptr */
1021 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1022 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1023 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1024 			continue;
1025 		if (dreg->dynptr_id == dynptr_id)
1026 			mark_reg_invalid(env, dreg);
1027 	}));
1028 
1029 	/* Do not release reference state, we are destroying dynptr on stack,
1030 	 * not using some helper to release it. Just reset register.
1031 	 */
1032 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1033 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1034 
1035 	/* Same reason as unmark_stack_slots_dynptr above */
1036 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1037 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1038 
1039 	return 0;
1040 }
1041 
1042 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1043 {
1044 	int spi;
1045 
1046 	if (reg->type == CONST_PTR_TO_DYNPTR)
1047 		return false;
1048 
1049 	spi = dynptr_get_spi(env, reg);
1050 
1051 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1052 	 * error because this just means the stack state hasn't been updated yet.
1053 	 * We will do check_mem_access to check and update stack bounds later.
1054 	 */
1055 	if (spi < 0 && spi != -ERANGE)
1056 		return false;
1057 
1058 	/* We don't need to check if the stack slots are marked by previous
1059 	 * dynptr initializations because we allow overwriting existing unreferenced
1060 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1061 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1062 	 * touching are completely destructed before we reinitialize them for a new
1063 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1064 	 * instead of delaying it until the end where the user will get "Unreleased
1065 	 * reference" error.
1066 	 */
1067 	return true;
1068 }
1069 
1070 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1071 {
1072 	struct bpf_func_state *state = func(env, reg);
1073 	int i, spi;
1074 
1075 	/* This already represents first slot of initialized bpf_dynptr.
1076 	 *
1077 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1078 	 * check_func_arg_reg_off's logic, so we don't need to check its
1079 	 * offset and alignment.
1080 	 */
1081 	if (reg->type == CONST_PTR_TO_DYNPTR)
1082 		return true;
1083 
1084 	spi = dynptr_get_spi(env, reg);
1085 	if (spi < 0)
1086 		return false;
1087 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1088 		return false;
1089 
1090 	for (i = 0; i < BPF_REG_SIZE; i++) {
1091 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1092 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1093 			return false;
1094 	}
1095 
1096 	return true;
1097 }
1098 
1099 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1100 				    enum bpf_arg_type arg_type)
1101 {
1102 	struct bpf_func_state *state = func(env, reg);
1103 	enum bpf_dynptr_type dynptr_type;
1104 	int spi;
1105 
1106 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1107 	if (arg_type == ARG_PTR_TO_DYNPTR)
1108 		return true;
1109 
1110 	dynptr_type = arg_to_dynptr_type(arg_type);
1111 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1112 		return reg->dynptr.type == dynptr_type;
1113 	} else {
1114 		spi = dynptr_get_spi(env, reg);
1115 		if (spi < 0)
1116 			return false;
1117 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1118 	}
1119 }
1120 
1121 /* The reg state of a pointer or a bounded scalar was saved when
1122  * it was spilled to the stack.
1123  */
1124 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1125 {
1126 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1127 }
1128 
1129 static void scrub_spilled_slot(u8 *stype)
1130 {
1131 	if (*stype != STACK_INVALID)
1132 		*stype = STACK_MISC;
1133 }
1134 
1135 static void print_verifier_state(struct bpf_verifier_env *env,
1136 				 const struct bpf_func_state *state,
1137 				 bool print_all)
1138 {
1139 	const struct bpf_reg_state *reg;
1140 	enum bpf_reg_type t;
1141 	int i;
1142 
1143 	if (state->frameno)
1144 		verbose(env, " frame%d:", state->frameno);
1145 	for (i = 0; i < MAX_BPF_REG; i++) {
1146 		reg = &state->regs[i];
1147 		t = reg->type;
1148 		if (t == NOT_INIT)
1149 			continue;
1150 		if (!print_all && !reg_scratched(env, i))
1151 			continue;
1152 		verbose(env, " R%d", i);
1153 		print_liveness(env, reg->live);
1154 		verbose(env, "=");
1155 		if (t == SCALAR_VALUE && reg->precise)
1156 			verbose(env, "P");
1157 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1158 		    tnum_is_const(reg->var_off)) {
1159 			/* reg->off should be 0 for SCALAR_VALUE */
1160 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1161 			verbose(env, "%lld", reg->var_off.value + reg->off);
1162 		} else {
1163 			const char *sep = "";
1164 
1165 			verbose(env, "%s", reg_type_str(env, t));
1166 			if (base_type(t) == PTR_TO_BTF_ID)
1167 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
1168 			verbose(env, "(");
1169 /*
1170  * _a stands for append, was shortened to avoid multiline statements below.
1171  * This macro is used to output a comma separated list of attributes.
1172  */
1173 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1174 
1175 			if (reg->id)
1176 				verbose_a("id=%d", reg->id);
1177 			if (reg->ref_obj_id)
1178 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1179 			if (type_is_non_owning_ref(reg->type))
1180 				verbose_a("%s", "non_own_ref");
1181 			if (t != SCALAR_VALUE)
1182 				verbose_a("off=%d", reg->off);
1183 			if (type_is_pkt_pointer(t))
1184 				verbose_a("r=%d", reg->range);
1185 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1186 				 base_type(t) == PTR_TO_MAP_KEY ||
1187 				 base_type(t) == PTR_TO_MAP_VALUE)
1188 				verbose_a("ks=%d,vs=%d",
1189 					  reg->map_ptr->key_size,
1190 					  reg->map_ptr->value_size);
1191 			if (tnum_is_const(reg->var_off)) {
1192 				/* Typically an immediate SCALAR_VALUE, but
1193 				 * could be a pointer whose offset is too big
1194 				 * for reg->off
1195 				 */
1196 				verbose_a("imm=%llx", reg->var_off.value);
1197 			} else {
1198 				if (reg->smin_value != reg->umin_value &&
1199 				    reg->smin_value != S64_MIN)
1200 					verbose_a("smin=%lld", (long long)reg->smin_value);
1201 				if (reg->smax_value != reg->umax_value &&
1202 				    reg->smax_value != S64_MAX)
1203 					verbose_a("smax=%lld", (long long)reg->smax_value);
1204 				if (reg->umin_value != 0)
1205 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1206 				if (reg->umax_value != U64_MAX)
1207 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1208 				if (!tnum_is_unknown(reg->var_off)) {
1209 					char tn_buf[48];
1210 
1211 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1212 					verbose_a("var_off=%s", tn_buf);
1213 				}
1214 				if (reg->s32_min_value != reg->smin_value &&
1215 				    reg->s32_min_value != S32_MIN)
1216 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1217 				if (reg->s32_max_value != reg->smax_value &&
1218 				    reg->s32_max_value != S32_MAX)
1219 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1220 				if (reg->u32_min_value != reg->umin_value &&
1221 				    reg->u32_min_value != U32_MIN)
1222 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1223 				if (reg->u32_max_value != reg->umax_value &&
1224 				    reg->u32_max_value != U32_MAX)
1225 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1226 			}
1227 #undef verbose_a
1228 
1229 			verbose(env, ")");
1230 		}
1231 	}
1232 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1233 		char types_buf[BPF_REG_SIZE + 1];
1234 		bool valid = false;
1235 		int j;
1236 
1237 		for (j = 0; j < BPF_REG_SIZE; j++) {
1238 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1239 				valid = true;
1240 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1241 		}
1242 		types_buf[BPF_REG_SIZE] = 0;
1243 		if (!valid)
1244 			continue;
1245 		if (!print_all && !stack_slot_scratched(env, i))
1246 			continue;
1247 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1248 		case STACK_SPILL:
1249 			reg = &state->stack[i].spilled_ptr;
1250 			t = reg->type;
1251 
1252 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1253 			print_liveness(env, reg->live);
1254 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1255 			if (t == SCALAR_VALUE && reg->precise)
1256 				verbose(env, "P");
1257 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1258 				verbose(env, "%lld", reg->var_off.value + reg->off);
1259 			break;
1260 		case STACK_DYNPTR:
1261 			i += BPF_DYNPTR_NR_SLOTS - 1;
1262 			reg = &state->stack[i].spilled_ptr;
1263 
1264 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1265 			print_liveness(env, reg->live);
1266 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1267 			if (reg->ref_obj_id)
1268 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1269 			break;
1270 		case STACK_MISC:
1271 		case STACK_ZERO:
1272 		default:
1273 			reg = &state->stack[i].spilled_ptr;
1274 
1275 			for (j = 0; j < BPF_REG_SIZE; j++)
1276 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1277 			types_buf[BPF_REG_SIZE] = 0;
1278 
1279 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1280 			print_liveness(env, reg->live);
1281 			verbose(env, "=%s", types_buf);
1282 			break;
1283 		}
1284 	}
1285 	if (state->acquired_refs && state->refs[0].id) {
1286 		verbose(env, " refs=%d", state->refs[0].id);
1287 		for (i = 1; i < state->acquired_refs; i++)
1288 			if (state->refs[i].id)
1289 				verbose(env, ",%d", state->refs[i].id);
1290 	}
1291 	if (state->in_callback_fn)
1292 		verbose(env, " cb");
1293 	if (state->in_async_callback_fn)
1294 		verbose(env, " async_cb");
1295 	verbose(env, "\n");
1296 	mark_verifier_state_clean(env);
1297 }
1298 
1299 static inline u32 vlog_alignment(u32 pos)
1300 {
1301 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1302 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1303 }
1304 
1305 static void print_insn_state(struct bpf_verifier_env *env,
1306 			     const struct bpf_func_state *state)
1307 {
1308 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1309 		/* remove new line character */
1310 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1311 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1312 	} else {
1313 		verbose(env, "%d:", env->insn_idx);
1314 	}
1315 	print_verifier_state(env, state, false);
1316 }
1317 
1318 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1319  * small to hold src. This is different from krealloc since we don't want to preserve
1320  * the contents of dst.
1321  *
1322  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1323  * not be allocated.
1324  */
1325 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1326 {
1327 	size_t alloc_bytes;
1328 	void *orig = dst;
1329 	size_t bytes;
1330 
1331 	if (ZERO_OR_NULL_PTR(src))
1332 		goto out;
1333 
1334 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1335 		return NULL;
1336 
1337 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1338 	dst = krealloc(orig, alloc_bytes, flags);
1339 	if (!dst) {
1340 		kfree(orig);
1341 		return NULL;
1342 	}
1343 
1344 	memcpy(dst, src, bytes);
1345 out:
1346 	return dst ? dst : ZERO_SIZE_PTR;
1347 }
1348 
1349 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1350  * small to hold new_n items. new items are zeroed out if the array grows.
1351  *
1352  * Contrary to krealloc_array, does not free arr if new_n is zero.
1353  */
1354 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1355 {
1356 	size_t alloc_size;
1357 	void *new_arr;
1358 
1359 	if (!new_n || old_n == new_n)
1360 		goto out;
1361 
1362 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1363 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1364 	if (!new_arr) {
1365 		kfree(arr);
1366 		return NULL;
1367 	}
1368 	arr = new_arr;
1369 
1370 	if (new_n > old_n)
1371 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1372 
1373 out:
1374 	return arr ? arr : ZERO_SIZE_PTR;
1375 }
1376 
1377 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1378 {
1379 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1380 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1381 	if (!dst->refs)
1382 		return -ENOMEM;
1383 
1384 	dst->acquired_refs = src->acquired_refs;
1385 	return 0;
1386 }
1387 
1388 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1389 {
1390 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1391 
1392 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1393 				GFP_KERNEL);
1394 	if (!dst->stack)
1395 		return -ENOMEM;
1396 
1397 	dst->allocated_stack = src->allocated_stack;
1398 	return 0;
1399 }
1400 
1401 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1402 {
1403 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1404 				    sizeof(struct bpf_reference_state));
1405 	if (!state->refs)
1406 		return -ENOMEM;
1407 
1408 	state->acquired_refs = n;
1409 	return 0;
1410 }
1411 
1412 static int grow_stack_state(struct bpf_func_state *state, int size)
1413 {
1414 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1415 
1416 	if (old_n >= n)
1417 		return 0;
1418 
1419 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1420 	if (!state->stack)
1421 		return -ENOMEM;
1422 
1423 	state->allocated_stack = size;
1424 	return 0;
1425 }
1426 
1427 /* Acquire a pointer id from the env and update the state->refs to include
1428  * this new pointer reference.
1429  * On success, returns a valid pointer id to associate with the register
1430  * On failure, returns a negative errno.
1431  */
1432 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1433 {
1434 	struct bpf_func_state *state = cur_func(env);
1435 	int new_ofs = state->acquired_refs;
1436 	int id, err;
1437 
1438 	err = resize_reference_state(state, state->acquired_refs + 1);
1439 	if (err)
1440 		return err;
1441 	id = ++env->id_gen;
1442 	state->refs[new_ofs].id = id;
1443 	state->refs[new_ofs].insn_idx = insn_idx;
1444 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1445 
1446 	return id;
1447 }
1448 
1449 /* release function corresponding to acquire_reference_state(). Idempotent. */
1450 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1451 {
1452 	int i, last_idx;
1453 
1454 	last_idx = state->acquired_refs - 1;
1455 	for (i = 0; i < state->acquired_refs; i++) {
1456 		if (state->refs[i].id == ptr_id) {
1457 			/* Cannot release caller references in callbacks */
1458 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1459 				return -EINVAL;
1460 			if (last_idx && i != last_idx)
1461 				memcpy(&state->refs[i], &state->refs[last_idx],
1462 				       sizeof(*state->refs));
1463 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1464 			state->acquired_refs--;
1465 			return 0;
1466 		}
1467 	}
1468 	return -EINVAL;
1469 }
1470 
1471 static void free_func_state(struct bpf_func_state *state)
1472 {
1473 	if (!state)
1474 		return;
1475 	kfree(state->refs);
1476 	kfree(state->stack);
1477 	kfree(state);
1478 }
1479 
1480 static void clear_jmp_history(struct bpf_verifier_state *state)
1481 {
1482 	kfree(state->jmp_history);
1483 	state->jmp_history = NULL;
1484 	state->jmp_history_cnt = 0;
1485 }
1486 
1487 static void free_verifier_state(struct bpf_verifier_state *state,
1488 				bool free_self)
1489 {
1490 	int i;
1491 
1492 	for (i = 0; i <= state->curframe; i++) {
1493 		free_func_state(state->frame[i]);
1494 		state->frame[i] = NULL;
1495 	}
1496 	clear_jmp_history(state);
1497 	if (free_self)
1498 		kfree(state);
1499 }
1500 
1501 /* copy verifier state from src to dst growing dst stack space
1502  * when necessary to accommodate larger src stack
1503  */
1504 static int copy_func_state(struct bpf_func_state *dst,
1505 			   const struct bpf_func_state *src)
1506 {
1507 	int err;
1508 
1509 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1510 	err = copy_reference_state(dst, src);
1511 	if (err)
1512 		return err;
1513 	return copy_stack_state(dst, src);
1514 }
1515 
1516 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1517 			       const struct bpf_verifier_state *src)
1518 {
1519 	struct bpf_func_state *dst;
1520 	int i, err;
1521 
1522 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1523 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1524 					    GFP_USER);
1525 	if (!dst_state->jmp_history)
1526 		return -ENOMEM;
1527 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1528 
1529 	/* if dst has more stack frames then src frame, free them */
1530 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1531 		free_func_state(dst_state->frame[i]);
1532 		dst_state->frame[i] = NULL;
1533 	}
1534 	dst_state->speculative = src->speculative;
1535 	dst_state->active_rcu_lock = src->active_rcu_lock;
1536 	dst_state->curframe = src->curframe;
1537 	dst_state->active_lock.ptr = src->active_lock.ptr;
1538 	dst_state->active_lock.id = src->active_lock.id;
1539 	dst_state->branches = src->branches;
1540 	dst_state->parent = src->parent;
1541 	dst_state->first_insn_idx = src->first_insn_idx;
1542 	dst_state->last_insn_idx = src->last_insn_idx;
1543 	for (i = 0; i <= src->curframe; i++) {
1544 		dst = dst_state->frame[i];
1545 		if (!dst) {
1546 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1547 			if (!dst)
1548 				return -ENOMEM;
1549 			dst_state->frame[i] = dst;
1550 		}
1551 		err = copy_func_state(dst, src->frame[i]);
1552 		if (err)
1553 			return err;
1554 	}
1555 	return 0;
1556 }
1557 
1558 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1559 {
1560 	while (st) {
1561 		u32 br = --st->branches;
1562 
1563 		/* WARN_ON(br > 1) technically makes sense here,
1564 		 * but see comment in push_stack(), hence:
1565 		 */
1566 		WARN_ONCE((int)br < 0,
1567 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1568 			  br);
1569 		if (br)
1570 			break;
1571 		st = st->parent;
1572 	}
1573 }
1574 
1575 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1576 		     int *insn_idx, bool pop_log)
1577 {
1578 	struct bpf_verifier_state *cur = env->cur_state;
1579 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1580 	int err;
1581 
1582 	if (env->head == NULL)
1583 		return -ENOENT;
1584 
1585 	if (cur) {
1586 		err = copy_verifier_state(cur, &head->st);
1587 		if (err)
1588 			return err;
1589 	}
1590 	if (pop_log)
1591 		bpf_vlog_reset(&env->log, head->log_pos);
1592 	if (insn_idx)
1593 		*insn_idx = head->insn_idx;
1594 	if (prev_insn_idx)
1595 		*prev_insn_idx = head->prev_insn_idx;
1596 	elem = head->next;
1597 	free_verifier_state(&head->st, false);
1598 	kfree(head);
1599 	env->head = elem;
1600 	env->stack_size--;
1601 	return 0;
1602 }
1603 
1604 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1605 					     int insn_idx, int prev_insn_idx,
1606 					     bool speculative)
1607 {
1608 	struct bpf_verifier_state *cur = env->cur_state;
1609 	struct bpf_verifier_stack_elem *elem;
1610 	int err;
1611 
1612 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1613 	if (!elem)
1614 		goto err;
1615 
1616 	elem->insn_idx = insn_idx;
1617 	elem->prev_insn_idx = prev_insn_idx;
1618 	elem->next = env->head;
1619 	elem->log_pos = env->log.len_used;
1620 	env->head = elem;
1621 	env->stack_size++;
1622 	err = copy_verifier_state(&elem->st, cur);
1623 	if (err)
1624 		goto err;
1625 	elem->st.speculative |= speculative;
1626 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1627 		verbose(env, "The sequence of %d jumps is too complex.\n",
1628 			env->stack_size);
1629 		goto err;
1630 	}
1631 	if (elem->st.parent) {
1632 		++elem->st.parent->branches;
1633 		/* WARN_ON(branches > 2) technically makes sense here,
1634 		 * but
1635 		 * 1. speculative states will bump 'branches' for non-branch
1636 		 * instructions
1637 		 * 2. is_state_visited() heuristics may decide not to create
1638 		 * a new state for a sequence of branches and all such current
1639 		 * and cloned states will be pointing to a single parent state
1640 		 * which might have large 'branches' count.
1641 		 */
1642 	}
1643 	return &elem->st;
1644 err:
1645 	free_verifier_state(env->cur_state, true);
1646 	env->cur_state = NULL;
1647 	/* pop all elements and return */
1648 	while (!pop_stack(env, NULL, NULL, false));
1649 	return NULL;
1650 }
1651 
1652 #define CALLER_SAVED_REGS 6
1653 static const int caller_saved[CALLER_SAVED_REGS] = {
1654 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1655 };
1656 
1657 /* This helper doesn't clear reg->id */
1658 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1659 {
1660 	reg->var_off = tnum_const(imm);
1661 	reg->smin_value = (s64)imm;
1662 	reg->smax_value = (s64)imm;
1663 	reg->umin_value = imm;
1664 	reg->umax_value = imm;
1665 
1666 	reg->s32_min_value = (s32)imm;
1667 	reg->s32_max_value = (s32)imm;
1668 	reg->u32_min_value = (u32)imm;
1669 	reg->u32_max_value = (u32)imm;
1670 }
1671 
1672 /* Mark the unknown part of a register (variable offset or scalar value) as
1673  * known to have the value @imm.
1674  */
1675 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1676 {
1677 	/* Clear off and union(map_ptr, range) */
1678 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1679 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1680 	reg->id = 0;
1681 	reg->ref_obj_id = 0;
1682 	___mark_reg_known(reg, imm);
1683 }
1684 
1685 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1686 {
1687 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1688 	reg->s32_min_value = (s32)imm;
1689 	reg->s32_max_value = (s32)imm;
1690 	reg->u32_min_value = (u32)imm;
1691 	reg->u32_max_value = (u32)imm;
1692 }
1693 
1694 /* Mark the 'variable offset' part of a register as zero.  This should be
1695  * used only on registers holding a pointer type.
1696  */
1697 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1698 {
1699 	__mark_reg_known(reg, 0);
1700 }
1701 
1702 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1703 {
1704 	__mark_reg_known(reg, 0);
1705 	reg->type = SCALAR_VALUE;
1706 }
1707 
1708 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1709 				struct bpf_reg_state *regs, u32 regno)
1710 {
1711 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1712 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1713 		/* Something bad happened, let's kill all regs */
1714 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1715 			__mark_reg_not_init(env, regs + regno);
1716 		return;
1717 	}
1718 	__mark_reg_known_zero(regs + regno);
1719 }
1720 
1721 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1722 			      bool first_slot, int dynptr_id)
1723 {
1724 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1725 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1726 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1727 	 */
1728 	__mark_reg_known_zero(reg);
1729 	reg->type = CONST_PTR_TO_DYNPTR;
1730 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1731 	reg->id = dynptr_id;
1732 	reg->dynptr.type = type;
1733 	reg->dynptr.first_slot = first_slot;
1734 }
1735 
1736 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1737 {
1738 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1739 		const struct bpf_map *map = reg->map_ptr;
1740 
1741 		if (map->inner_map_meta) {
1742 			reg->type = CONST_PTR_TO_MAP;
1743 			reg->map_ptr = map->inner_map_meta;
1744 			/* transfer reg's id which is unique for every map_lookup_elem
1745 			 * as UID of the inner map.
1746 			 */
1747 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1748 				reg->map_uid = reg->id;
1749 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1750 			reg->type = PTR_TO_XDP_SOCK;
1751 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1752 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1753 			reg->type = PTR_TO_SOCKET;
1754 		} else {
1755 			reg->type = PTR_TO_MAP_VALUE;
1756 		}
1757 		return;
1758 	}
1759 
1760 	reg->type &= ~PTR_MAYBE_NULL;
1761 }
1762 
1763 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1764 				struct btf_field_graph_root *ds_head)
1765 {
1766 	__mark_reg_known_zero(&regs[regno]);
1767 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1768 	regs[regno].btf = ds_head->btf;
1769 	regs[regno].btf_id = ds_head->value_btf_id;
1770 	regs[regno].off = ds_head->node_offset;
1771 }
1772 
1773 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1774 {
1775 	return type_is_pkt_pointer(reg->type);
1776 }
1777 
1778 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1779 {
1780 	return reg_is_pkt_pointer(reg) ||
1781 	       reg->type == PTR_TO_PACKET_END;
1782 }
1783 
1784 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1785 {
1786 	return base_type(reg->type) == PTR_TO_MEM &&
1787 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1788 }
1789 
1790 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1791 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1792 				    enum bpf_reg_type which)
1793 {
1794 	/* The register can already have a range from prior markings.
1795 	 * This is fine as long as it hasn't been advanced from its
1796 	 * origin.
1797 	 */
1798 	return reg->type == which &&
1799 	       reg->id == 0 &&
1800 	       reg->off == 0 &&
1801 	       tnum_equals_const(reg->var_off, 0);
1802 }
1803 
1804 /* Reset the min/max bounds of a register */
1805 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1806 {
1807 	reg->smin_value = S64_MIN;
1808 	reg->smax_value = S64_MAX;
1809 	reg->umin_value = 0;
1810 	reg->umax_value = U64_MAX;
1811 
1812 	reg->s32_min_value = S32_MIN;
1813 	reg->s32_max_value = S32_MAX;
1814 	reg->u32_min_value = 0;
1815 	reg->u32_max_value = U32_MAX;
1816 }
1817 
1818 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1819 {
1820 	reg->smin_value = S64_MIN;
1821 	reg->smax_value = S64_MAX;
1822 	reg->umin_value = 0;
1823 	reg->umax_value = U64_MAX;
1824 }
1825 
1826 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1827 {
1828 	reg->s32_min_value = S32_MIN;
1829 	reg->s32_max_value = S32_MAX;
1830 	reg->u32_min_value = 0;
1831 	reg->u32_max_value = U32_MAX;
1832 }
1833 
1834 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1835 {
1836 	struct tnum var32_off = tnum_subreg(reg->var_off);
1837 
1838 	/* min signed is max(sign bit) | min(other bits) */
1839 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1840 			var32_off.value | (var32_off.mask & S32_MIN));
1841 	/* max signed is min(sign bit) | max(other bits) */
1842 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1843 			var32_off.value | (var32_off.mask & S32_MAX));
1844 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1845 	reg->u32_max_value = min(reg->u32_max_value,
1846 				 (u32)(var32_off.value | var32_off.mask));
1847 }
1848 
1849 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1850 {
1851 	/* min signed is max(sign bit) | min(other bits) */
1852 	reg->smin_value = max_t(s64, reg->smin_value,
1853 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1854 	/* max signed is min(sign bit) | max(other bits) */
1855 	reg->smax_value = min_t(s64, reg->smax_value,
1856 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1857 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1858 	reg->umax_value = min(reg->umax_value,
1859 			      reg->var_off.value | reg->var_off.mask);
1860 }
1861 
1862 static void __update_reg_bounds(struct bpf_reg_state *reg)
1863 {
1864 	__update_reg32_bounds(reg);
1865 	__update_reg64_bounds(reg);
1866 }
1867 
1868 /* Uses signed min/max values to inform unsigned, and vice-versa */
1869 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1870 {
1871 	/* Learn sign from signed bounds.
1872 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1873 	 * are the same, so combine.  This works even in the negative case, e.g.
1874 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1875 	 */
1876 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1877 		reg->s32_min_value = reg->u32_min_value =
1878 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1879 		reg->s32_max_value = reg->u32_max_value =
1880 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1881 		return;
1882 	}
1883 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1884 	 * boundary, so we must be careful.
1885 	 */
1886 	if ((s32)reg->u32_max_value >= 0) {
1887 		/* Positive.  We can't learn anything from the smin, but smax
1888 		 * is positive, hence safe.
1889 		 */
1890 		reg->s32_min_value = reg->u32_min_value;
1891 		reg->s32_max_value = reg->u32_max_value =
1892 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1893 	} else if ((s32)reg->u32_min_value < 0) {
1894 		/* Negative.  We can't learn anything from the smax, but smin
1895 		 * is negative, hence safe.
1896 		 */
1897 		reg->s32_min_value = reg->u32_min_value =
1898 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1899 		reg->s32_max_value = reg->u32_max_value;
1900 	}
1901 }
1902 
1903 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1904 {
1905 	/* Learn sign from signed bounds.
1906 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1907 	 * are the same, so combine.  This works even in the negative case, e.g.
1908 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1909 	 */
1910 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1911 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1912 							  reg->umin_value);
1913 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1914 							  reg->umax_value);
1915 		return;
1916 	}
1917 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1918 	 * boundary, so we must be careful.
1919 	 */
1920 	if ((s64)reg->umax_value >= 0) {
1921 		/* Positive.  We can't learn anything from the smin, but smax
1922 		 * is positive, hence safe.
1923 		 */
1924 		reg->smin_value = reg->umin_value;
1925 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1926 							  reg->umax_value);
1927 	} else if ((s64)reg->umin_value < 0) {
1928 		/* Negative.  We can't learn anything from the smax, but smin
1929 		 * is negative, hence safe.
1930 		 */
1931 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1932 							  reg->umin_value);
1933 		reg->smax_value = reg->umax_value;
1934 	}
1935 }
1936 
1937 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1938 {
1939 	__reg32_deduce_bounds(reg);
1940 	__reg64_deduce_bounds(reg);
1941 }
1942 
1943 /* Attempts to improve var_off based on unsigned min/max information */
1944 static void __reg_bound_offset(struct bpf_reg_state *reg)
1945 {
1946 	struct tnum var64_off = tnum_intersect(reg->var_off,
1947 					       tnum_range(reg->umin_value,
1948 							  reg->umax_value));
1949 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1950 						tnum_range(reg->u32_min_value,
1951 							   reg->u32_max_value));
1952 
1953 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1954 }
1955 
1956 static void reg_bounds_sync(struct bpf_reg_state *reg)
1957 {
1958 	/* We might have learned new bounds from the var_off. */
1959 	__update_reg_bounds(reg);
1960 	/* We might have learned something about the sign bit. */
1961 	__reg_deduce_bounds(reg);
1962 	/* We might have learned some bits from the bounds. */
1963 	__reg_bound_offset(reg);
1964 	/* Intersecting with the old var_off might have improved our bounds
1965 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1966 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1967 	 */
1968 	__update_reg_bounds(reg);
1969 }
1970 
1971 static bool __reg32_bound_s64(s32 a)
1972 {
1973 	return a >= 0 && a <= S32_MAX;
1974 }
1975 
1976 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1977 {
1978 	reg->umin_value = reg->u32_min_value;
1979 	reg->umax_value = reg->u32_max_value;
1980 
1981 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1982 	 * be positive otherwise set to worse case bounds and refine later
1983 	 * from tnum.
1984 	 */
1985 	if (__reg32_bound_s64(reg->s32_min_value) &&
1986 	    __reg32_bound_s64(reg->s32_max_value)) {
1987 		reg->smin_value = reg->s32_min_value;
1988 		reg->smax_value = reg->s32_max_value;
1989 	} else {
1990 		reg->smin_value = 0;
1991 		reg->smax_value = U32_MAX;
1992 	}
1993 }
1994 
1995 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1996 {
1997 	/* special case when 64-bit register has upper 32-bit register
1998 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1999 	 * allowing us to use 32-bit bounds directly,
2000 	 */
2001 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2002 		__reg_assign_32_into_64(reg);
2003 	} else {
2004 		/* Otherwise the best we can do is push lower 32bit known and
2005 		 * unknown bits into register (var_off set from jmp logic)
2006 		 * then learn as much as possible from the 64-bit tnum
2007 		 * known and unknown bits. The previous smin/smax bounds are
2008 		 * invalid here because of jmp32 compare so mark them unknown
2009 		 * so they do not impact tnum bounds calculation.
2010 		 */
2011 		__mark_reg64_unbounded(reg);
2012 	}
2013 	reg_bounds_sync(reg);
2014 }
2015 
2016 static bool __reg64_bound_s32(s64 a)
2017 {
2018 	return a >= S32_MIN && a <= S32_MAX;
2019 }
2020 
2021 static bool __reg64_bound_u32(u64 a)
2022 {
2023 	return a >= U32_MIN && a <= U32_MAX;
2024 }
2025 
2026 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2027 {
2028 	__mark_reg32_unbounded(reg);
2029 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2030 		reg->s32_min_value = (s32)reg->smin_value;
2031 		reg->s32_max_value = (s32)reg->smax_value;
2032 	}
2033 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2034 		reg->u32_min_value = (u32)reg->umin_value;
2035 		reg->u32_max_value = (u32)reg->umax_value;
2036 	}
2037 	reg_bounds_sync(reg);
2038 }
2039 
2040 /* Mark a register as having a completely unknown (scalar) value. */
2041 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2042 			       struct bpf_reg_state *reg)
2043 {
2044 	/*
2045 	 * Clear type, off, and union(map_ptr, range) and
2046 	 * padding between 'type' and union
2047 	 */
2048 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2049 	reg->type = SCALAR_VALUE;
2050 	reg->id = 0;
2051 	reg->ref_obj_id = 0;
2052 	reg->var_off = tnum_unknown;
2053 	reg->frameno = 0;
2054 	reg->precise = !env->bpf_capable;
2055 	__mark_reg_unbounded(reg);
2056 }
2057 
2058 static void mark_reg_unknown(struct bpf_verifier_env *env,
2059 			     struct bpf_reg_state *regs, u32 regno)
2060 {
2061 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2062 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2063 		/* Something bad happened, let's kill all regs except FP */
2064 		for (regno = 0; regno < BPF_REG_FP; regno++)
2065 			__mark_reg_not_init(env, regs + regno);
2066 		return;
2067 	}
2068 	__mark_reg_unknown(env, regs + regno);
2069 }
2070 
2071 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2072 				struct bpf_reg_state *reg)
2073 {
2074 	__mark_reg_unknown(env, reg);
2075 	reg->type = NOT_INIT;
2076 }
2077 
2078 static void mark_reg_not_init(struct bpf_verifier_env *env,
2079 			      struct bpf_reg_state *regs, u32 regno)
2080 {
2081 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2082 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2083 		/* Something bad happened, let's kill all regs except FP */
2084 		for (regno = 0; regno < BPF_REG_FP; regno++)
2085 			__mark_reg_not_init(env, regs + regno);
2086 		return;
2087 	}
2088 	__mark_reg_not_init(env, regs + regno);
2089 }
2090 
2091 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2092 			    struct bpf_reg_state *regs, u32 regno,
2093 			    enum bpf_reg_type reg_type,
2094 			    struct btf *btf, u32 btf_id,
2095 			    enum bpf_type_flag flag)
2096 {
2097 	if (reg_type == SCALAR_VALUE) {
2098 		mark_reg_unknown(env, regs, regno);
2099 		return;
2100 	}
2101 	mark_reg_known_zero(env, regs, regno);
2102 	regs[regno].type = PTR_TO_BTF_ID | flag;
2103 	regs[regno].btf = btf;
2104 	regs[regno].btf_id = btf_id;
2105 }
2106 
2107 #define DEF_NOT_SUBREG	(0)
2108 static void init_reg_state(struct bpf_verifier_env *env,
2109 			   struct bpf_func_state *state)
2110 {
2111 	struct bpf_reg_state *regs = state->regs;
2112 	int i;
2113 
2114 	for (i = 0; i < MAX_BPF_REG; i++) {
2115 		mark_reg_not_init(env, regs, i);
2116 		regs[i].live = REG_LIVE_NONE;
2117 		regs[i].parent = NULL;
2118 		regs[i].subreg_def = DEF_NOT_SUBREG;
2119 	}
2120 
2121 	/* frame pointer */
2122 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2123 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2124 	regs[BPF_REG_FP].frameno = state->frameno;
2125 }
2126 
2127 #define BPF_MAIN_FUNC (-1)
2128 static void init_func_state(struct bpf_verifier_env *env,
2129 			    struct bpf_func_state *state,
2130 			    int callsite, int frameno, int subprogno)
2131 {
2132 	state->callsite = callsite;
2133 	state->frameno = frameno;
2134 	state->subprogno = subprogno;
2135 	state->callback_ret_range = tnum_range(0, 0);
2136 	init_reg_state(env, state);
2137 	mark_verifier_state_scratched(env);
2138 }
2139 
2140 /* Similar to push_stack(), but for async callbacks */
2141 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2142 						int insn_idx, int prev_insn_idx,
2143 						int subprog)
2144 {
2145 	struct bpf_verifier_stack_elem *elem;
2146 	struct bpf_func_state *frame;
2147 
2148 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2149 	if (!elem)
2150 		goto err;
2151 
2152 	elem->insn_idx = insn_idx;
2153 	elem->prev_insn_idx = prev_insn_idx;
2154 	elem->next = env->head;
2155 	elem->log_pos = env->log.len_used;
2156 	env->head = elem;
2157 	env->stack_size++;
2158 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2159 		verbose(env,
2160 			"The sequence of %d jumps is too complex for async cb.\n",
2161 			env->stack_size);
2162 		goto err;
2163 	}
2164 	/* Unlike push_stack() do not copy_verifier_state().
2165 	 * The caller state doesn't matter.
2166 	 * This is async callback. It starts in a fresh stack.
2167 	 * Initialize it similar to do_check_common().
2168 	 */
2169 	elem->st.branches = 1;
2170 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2171 	if (!frame)
2172 		goto err;
2173 	init_func_state(env, frame,
2174 			BPF_MAIN_FUNC /* callsite */,
2175 			0 /* frameno within this callchain */,
2176 			subprog /* subprog number within this prog */);
2177 	elem->st.frame[0] = frame;
2178 	return &elem->st;
2179 err:
2180 	free_verifier_state(env->cur_state, true);
2181 	env->cur_state = NULL;
2182 	/* pop all elements and return */
2183 	while (!pop_stack(env, NULL, NULL, false));
2184 	return NULL;
2185 }
2186 
2187 
2188 enum reg_arg_type {
2189 	SRC_OP,		/* register is used as source operand */
2190 	DST_OP,		/* register is used as destination operand */
2191 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2192 };
2193 
2194 static int cmp_subprogs(const void *a, const void *b)
2195 {
2196 	return ((struct bpf_subprog_info *)a)->start -
2197 	       ((struct bpf_subprog_info *)b)->start;
2198 }
2199 
2200 static int find_subprog(struct bpf_verifier_env *env, int off)
2201 {
2202 	struct bpf_subprog_info *p;
2203 
2204 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2205 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2206 	if (!p)
2207 		return -ENOENT;
2208 	return p - env->subprog_info;
2209 
2210 }
2211 
2212 static int add_subprog(struct bpf_verifier_env *env, int off)
2213 {
2214 	int insn_cnt = env->prog->len;
2215 	int ret;
2216 
2217 	if (off >= insn_cnt || off < 0) {
2218 		verbose(env, "call to invalid destination\n");
2219 		return -EINVAL;
2220 	}
2221 	ret = find_subprog(env, off);
2222 	if (ret >= 0)
2223 		return ret;
2224 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2225 		verbose(env, "too many subprograms\n");
2226 		return -E2BIG;
2227 	}
2228 	/* determine subprog starts. The end is one before the next starts */
2229 	env->subprog_info[env->subprog_cnt++].start = off;
2230 	sort(env->subprog_info, env->subprog_cnt,
2231 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2232 	return env->subprog_cnt - 1;
2233 }
2234 
2235 #define MAX_KFUNC_DESCS 256
2236 #define MAX_KFUNC_BTFS	256
2237 
2238 struct bpf_kfunc_desc {
2239 	struct btf_func_model func_model;
2240 	u32 func_id;
2241 	s32 imm;
2242 	u16 offset;
2243 };
2244 
2245 struct bpf_kfunc_btf {
2246 	struct btf *btf;
2247 	struct module *module;
2248 	u16 offset;
2249 };
2250 
2251 struct bpf_kfunc_desc_tab {
2252 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2253 	u32 nr_descs;
2254 };
2255 
2256 struct bpf_kfunc_btf_tab {
2257 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2258 	u32 nr_descs;
2259 };
2260 
2261 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2262 {
2263 	const struct bpf_kfunc_desc *d0 = a;
2264 	const struct bpf_kfunc_desc *d1 = b;
2265 
2266 	/* func_id is not greater than BTF_MAX_TYPE */
2267 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2268 }
2269 
2270 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2271 {
2272 	const struct bpf_kfunc_btf *d0 = a;
2273 	const struct bpf_kfunc_btf *d1 = b;
2274 
2275 	return d0->offset - d1->offset;
2276 }
2277 
2278 static const struct bpf_kfunc_desc *
2279 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2280 {
2281 	struct bpf_kfunc_desc desc = {
2282 		.func_id = func_id,
2283 		.offset = offset,
2284 	};
2285 	struct bpf_kfunc_desc_tab *tab;
2286 
2287 	tab = prog->aux->kfunc_tab;
2288 	return bsearch(&desc, tab->descs, tab->nr_descs,
2289 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2290 }
2291 
2292 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2293 					 s16 offset)
2294 {
2295 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2296 	struct bpf_kfunc_btf_tab *tab;
2297 	struct bpf_kfunc_btf *b;
2298 	struct module *mod;
2299 	struct btf *btf;
2300 	int btf_fd;
2301 
2302 	tab = env->prog->aux->kfunc_btf_tab;
2303 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2304 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2305 	if (!b) {
2306 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2307 			verbose(env, "too many different module BTFs\n");
2308 			return ERR_PTR(-E2BIG);
2309 		}
2310 
2311 		if (bpfptr_is_null(env->fd_array)) {
2312 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2313 			return ERR_PTR(-EPROTO);
2314 		}
2315 
2316 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2317 					    offset * sizeof(btf_fd),
2318 					    sizeof(btf_fd)))
2319 			return ERR_PTR(-EFAULT);
2320 
2321 		btf = btf_get_by_fd(btf_fd);
2322 		if (IS_ERR(btf)) {
2323 			verbose(env, "invalid module BTF fd specified\n");
2324 			return btf;
2325 		}
2326 
2327 		if (!btf_is_module(btf)) {
2328 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2329 			btf_put(btf);
2330 			return ERR_PTR(-EINVAL);
2331 		}
2332 
2333 		mod = btf_try_get_module(btf);
2334 		if (!mod) {
2335 			btf_put(btf);
2336 			return ERR_PTR(-ENXIO);
2337 		}
2338 
2339 		b = &tab->descs[tab->nr_descs++];
2340 		b->btf = btf;
2341 		b->module = mod;
2342 		b->offset = offset;
2343 
2344 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2345 		     kfunc_btf_cmp_by_off, NULL);
2346 	}
2347 	return b->btf;
2348 }
2349 
2350 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2351 {
2352 	if (!tab)
2353 		return;
2354 
2355 	while (tab->nr_descs--) {
2356 		module_put(tab->descs[tab->nr_descs].module);
2357 		btf_put(tab->descs[tab->nr_descs].btf);
2358 	}
2359 	kfree(tab);
2360 }
2361 
2362 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2363 {
2364 	if (offset) {
2365 		if (offset < 0) {
2366 			/* In the future, this can be allowed to increase limit
2367 			 * of fd index into fd_array, interpreted as u16.
2368 			 */
2369 			verbose(env, "negative offset disallowed for kernel module function call\n");
2370 			return ERR_PTR(-EINVAL);
2371 		}
2372 
2373 		return __find_kfunc_desc_btf(env, offset);
2374 	}
2375 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2376 }
2377 
2378 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2379 {
2380 	const struct btf_type *func, *func_proto;
2381 	struct bpf_kfunc_btf_tab *btf_tab;
2382 	struct bpf_kfunc_desc_tab *tab;
2383 	struct bpf_prog_aux *prog_aux;
2384 	struct bpf_kfunc_desc *desc;
2385 	const char *func_name;
2386 	struct btf *desc_btf;
2387 	unsigned long call_imm;
2388 	unsigned long addr;
2389 	int err;
2390 
2391 	prog_aux = env->prog->aux;
2392 	tab = prog_aux->kfunc_tab;
2393 	btf_tab = prog_aux->kfunc_btf_tab;
2394 	if (!tab) {
2395 		if (!btf_vmlinux) {
2396 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2397 			return -ENOTSUPP;
2398 		}
2399 
2400 		if (!env->prog->jit_requested) {
2401 			verbose(env, "JIT is required for calling kernel function\n");
2402 			return -ENOTSUPP;
2403 		}
2404 
2405 		if (!bpf_jit_supports_kfunc_call()) {
2406 			verbose(env, "JIT does not support calling kernel function\n");
2407 			return -ENOTSUPP;
2408 		}
2409 
2410 		if (!env->prog->gpl_compatible) {
2411 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2412 			return -EINVAL;
2413 		}
2414 
2415 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2416 		if (!tab)
2417 			return -ENOMEM;
2418 		prog_aux->kfunc_tab = tab;
2419 	}
2420 
2421 	/* func_id == 0 is always invalid, but instead of returning an error, be
2422 	 * conservative and wait until the code elimination pass before returning
2423 	 * error, so that invalid calls that get pruned out can be in BPF programs
2424 	 * loaded from userspace.  It is also required that offset be untouched
2425 	 * for such calls.
2426 	 */
2427 	if (!func_id && !offset)
2428 		return 0;
2429 
2430 	if (!btf_tab && offset) {
2431 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2432 		if (!btf_tab)
2433 			return -ENOMEM;
2434 		prog_aux->kfunc_btf_tab = btf_tab;
2435 	}
2436 
2437 	desc_btf = find_kfunc_desc_btf(env, offset);
2438 	if (IS_ERR(desc_btf)) {
2439 		verbose(env, "failed to find BTF for kernel function\n");
2440 		return PTR_ERR(desc_btf);
2441 	}
2442 
2443 	if (find_kfunc_desc(env->prog, func_id, offset))
2444 		return 0;
2445 
2446 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2447 		verbose(env, "too many different kernel function calls\n");
2448 		return -E2BIG;
2449 	}
2450 
2451 	func = btf_type_by_id(desc_btf, func_id);
2452 	if (!func || !btf_type_is_func(func)) {
2453 		verbose(env, "kernel btf_id %u is not a function\n",
2454 			func_id);
2455 		return -EINVAL;
2456 	}
2457 	func_proto = btf_type_by_id(desc_btf, func->type);
2458 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2459 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2460 			func_id);
2461 		return -EINVAL;
2462 	}
2463 
2464 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2465 	addr = kallsyms_lookup_name(func_name);
2466 	if (!addr) {
2467 		verbose(env, "cannot find address for kernel function %s\n",
2468 			func_name);
2469 		return -EINVAL;
2470 	}
2471 
2472 	call_imm = BPF_CALL_IMM(addr);
2473 	/* Check whether or not the relative offset overflows desc->imm */
2474 	if ((unsigned long)(s32)call_imm != call_imm) {
2475 		verbose(env, "address of kernel function %s is out of range\n",
2476 			func_name);
2477 		return -EINVAL;
2478 	}
2479 
2480 	if (bpf_dev_bound_kfunc_id(func_id)) {
2481 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2482 		if (err)
2483 			return err;
2484 	}
2485 
2486 	desc = &tab->descs[tab->nr_descs++];
2487 	desc->func_id = func_id;
2488 	desc->imm = call_imm;
2489 	desc->offset = offset;
2490 	err = btf_distill_func_proto(&env->log, desc_btf,
2491 				     func_proto, func_name,
2492 				     &desc->func_model);
2493 	if (!err)
2494 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2495 		     kfunc_desc_cmp_by_id_off, NULL);
2496 	return err;
2497 }
2498 
2499 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2500 {
2501 	const struct bpf_kfunc_desc *d0 = a;
2502 	const struct bpf_kfunc_desc *d1 = b;
2503 
2504 	if (d0->imm > d1->imm)
2505 		return 1;
2506 	else if (d0->imm < d1->imm)
2507 		return -1;
2508 	return 0;
2509 }
2510 
2511 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2512 {
2513 	struct bpf_kfunc_desc_tab *tab;
2514 
2515 	tab = prog->aux->kfunc_tab;
2516 	if (!tab)
2517 		return;
2518 
2519 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2520 	     kfunc_desc_cmp_by_imm, NULL);
2521 }
2522 
2523 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2524 {
2525 	return !!prog->aux->kfunc_tab;
2526 }
2527 
2528 const struct btf_func_model *
2529 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2530 			 const struct bpf_insn *insn)
2531 {
2532 	const struct bpf_kfunc_desc desc = {
2533 		.imm = insn->imm,
2534 	};
2535 	const struct bpf_kfunc_desc *res;
2536 	struct bpf_kfunc_desc_tab *tab;
2537 
2538 	tab = prog->aux->kfunc_tab;
2539 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2540 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2541 
2542 	return res ? &res->func_model : NULL;
2543 }
2544 
2545 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2546 {
2547 	struct bpf_subprog_info *subprog = env->subprog_info;
2548 	struct bpf_insn *insn = env->prog->insnsi;
2549 	int i, ret, insn_cnt = env->prog->len;
2550 
2551 	/* Add entry function. */
2552 	ret = add_subprog(env, 0);
2553 	if (ret)
2554 		return ret;
2555 
2556 	for (i = 0; i < insn_cnt; i++, insn++) {
2557 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2558 		    !bpf_pseudo_kfunc_call(insn))
2559 			continue;
2560 
2561 		if (!env->bpf_capable) {
2562 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2563 			return -EPERM;
2564 		}
2565 
2566 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2567 			ret = add_subprog(env, i + insn->imm + 1);
2568 		else
2569 			ret = add_kfunc_call(env, insn->imm, insn->off);
2570 
2571 		if (ret < 0)
2572 			return ret;
2573 	}
2574 
2575 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2576 	 * logic. 'subprog_cnt' should not be increased.
2577 	 */
2578 	subprog[env->subprog_cnt].start = insn_cnt;
2579 
2580 	if (env->log.level & BPF_LOG_LEVEL2)
2581 		for (i = 0; i < env->subprog_cnt; i++)
2582 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2583 
2584 	return 0;
2585 }
2586 
2587 static int check_subprogs(struct bpf_verifier_env *env)
2588 {
2589 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2590 	struct bpf_subprog_info *subprog = env->subprog_info;
2591 	struct bpf_insn *insn = env->prog->insnsi;
2592 	int insn_cnt = env->prog->len;
2593 
2594 	/* now check that all jumps are within the same subprog */
2595 	subprog_start = subprog[cur_subprog].start;
2596 	subprog_end = subprog[cur_subprog + 1].start;
2597 	for (i = 0; i < insn_cnt; i++) {
2598 		u8 code = insn[i].code;
2599 
2600 		if (code == (BPF_JMP | BPF_CALL) &&
2601 		    insn[i].src_reg == 0 &&
2602 		    insn[i].imm == BPF_FUNC_tail_call)
2603 			subprog[cur_subprog].has_tail_call = true;
2604 		if (BPF_CLASS(code) == BPF_LD &&
2605 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2606 			subprog[cur_subprog].has_ld_abs = true;
2607 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2608 			goto next;
2609 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2610 			goto next;
2611 		off = i + insn[i].off + 1;
2612 		if (off < subprog_start || off >= subprog_end) {
2613 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2614 			return -EINVAL;
2615 		}
2616 next:
2617 		if (i == subprog_end - 1) {
2618 			/* to avoid fall-through from one subprog into another
2619 			 * the last insn of the subprog should be either exit
2620 			 * or unconditional jump back
2621 			 */
2622 			if (code != (BPF_JMP | BPF_EXIT) &&
2623 			    code != (BPF_JMP | BPF_JA)) {
2624 				verbose(env, "last insn is not an exit or jmp\n");
2625 				return -EINVAL;
2626 			}
2627 			subprog_start = subprog_end;
2628 			cur_subprog++;
2629 			if (cur_subprog < env->subprog_cnt)
2630 				subprog_end = subprog[cur_subprog + 1].start;
2631 		}
2632 	}
2633 	return 0;
2634 }
2635 
2636 /* Parentage chain of this register (or stack slot) should take care of all
2637  * issues like callee-saved registers, stack slot allocation time, etc.
2638  */
2639 static int mark_reg_read(struct bpf_verifier_env *env,
2640 			 const struct bpf_reg_state *state,
2641 			 struct bpf_reg_state *parent, u8 flag)
2642 {
2643 	bool writes = parent == state->parent; /* Observe write marks */
2644 	int cnt = 0;
2645 
2646 	while (parent) {
2647 		/* if read wasn't screened by an earlier write ... */
2648 		if (writes && state->live & REG_LIVE_WRITTEN)
2649 			break;
2650 		if (parent->live & REG_LIVE_DONE) {
2651 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2652 				reg_type_str(env, parent->type),
2653 				parent->var_off.value, parent->off);
2654 			return -EFAULT;
2655 		}
2656 		/* The first condition is more likely to be true than the
2657 		 * second, checked it first.
2658 		 */
2659 		if ((parent->live & REG_LIVE_READ) == flag ||
2660 		    parent->live & REG_LIVE_READ64)
2661 			/* The parentage chain never changes and
2662 			 * this parent was already marked as LIVE_READ.
2663 			 * There is no need to keep walking the chain again and
2664 			 * keep re-marking all parents as LIVE_READ.
2665 			 * This case happens when the same register is read
2666 			 * multiple times without writes into it in-between.
2667 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2668 			 * then no need to set the weak REG_LIVE_READ32.
2669 			 */
2670 			break;
2671 		/* ... then we depend on parent's value */
2672 		parent->live |= flag;
2673 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2674 		if (flag == REG_LIVE_READ64)
2675 			parent->live &= ~REG_LIVE_READ32;
2676 		state = parent;
2677 		parent = state->parent;
2678 		writes = true;
2679 		cnt++;
2680 	}
2681 
2682 	if (env->longest_mark_read_walk < cnt)
2683 		env->longest_mark_read_walk = cnt;
2684 	return 0;
2685 }
2686 
2687 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2688 {
2689 	struct bpf_func_state *state = func(env, reg);
2690 	int spi, ret;
2691 
2692 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
2693 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2694 	 * check_kfunc_call.
2695 	 */
2696 	if (reg->type == CONST_PTR_TO_DYNPTR)
2697 		return 0;
2698 	spi = dynptr_get_spi(env, reg);
2699 	if (spi < 0)
2700 		return spi;
2701 	/* Caller ensures dynptr is valid and initialized, which means spi is in
2702 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2703 	 * read.
2704 	 */
2705 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2706 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2707 	if (ret)
2708 		return ret;
2709 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2710 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2711 }
2712 
2713 /* This function is supposed to be used by the following 32-bit optimization
2714  * code only. It returns TRUE if the source or destination register operates
2715  * on 64-bit, otherwise return FALSE.
2716  */
2717 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2718 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2719 {
2720 	u8 code, class, op;
2721 
2722 	code = insn->code;
2723 	class = BPF_CLASS(code);
2724 	op = BPF_OP(code);
2725 	if (class == BPF_JMP) {
2726 		/* BPF_EXIT for "main" will reach here. Return TRUE
2727 		 * conservatively.
2728 		 */
2729 		if (op == BPF_EXIT)
2730 			return true;
2731 		if (op == BPF_CALL) {
2732 			/* BPF to BPF call will reach here because of marking
2733 			 * caller saved clobber with DST_OP_NO_MARK for which we
2734 			 * don't care the register def because they are anyway
2735 			 * marked as NOT_INIT already.
2736 			 */
2737 			if (insn->src_reg == BPF_PSEUDO_CALL)
2738 				return false;
2739 			/* Helper call will reach here because of arg type
2740 			 * check, conservatively return TRUE.
2741 			 */
2742 			if (t == SRC_OP)
2743 				return true;
2744 
2745 			return false;
2746 		}
2747 	}
2748 
2749 	if (class == BPF_ALU64 || class == BPF_JMP ||
2750 	    /* BPF_END always use BPF_ALU class. */
2751 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2752 		return true;
2753 
2754 	if (class == BPF_ALU || class == BPF_JMP32)
2755 		return false;
2756 
2757 	if (class == BPF_LDX) {
2758 		if (t != SRC_OP)
2759 			return BPF_SIZE(code) == BPF_DW;
2760 		/* LDX source must be ptr. */
2761 		return true;
2762 	}
2763 
2764 	if (class == BPF_STX) {
2765 		/* BPF_STX (including atomic variants) has multiple source
2766 		 * operands, one of which is a ptr. Check whether the caller is
2767 		 * asking about it.
2768 		 */
2769 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2770 			return true;
2771 		return BPF_SIZE(code) == BPF_DW;
2772 	}
2773 
2774 	if (class == BPF_LD) {
2775 		u8 mode = BPF_MODE(code);
2776 
2777 		/* LD_IMM64 */
2778 		if (mode == BPF_IMM)
2779 			return true;
2780 
2781 		/* Both LD_IND and LD_ABS return 32-bit data. */
2782 		if (t != SRC_OP)
2783 			return  false;
2784 
2785 		/* Implicit ctx ptr. */
2786 		if (regno == BPF_REG_6)
2787 			return true;
2788 
2789 		/* Explicit source could be any width. */
2790 		return true;
2791 	}
2792 
2793 	if (class == BPF_ST)
2794 		/* The only source register for BPF_ST is a ptr. */
2795 		return true;
2796 
2797 	/* Conservatively return true at default. */
2798 	return true;
2799 }
2800 
2801 /* Return the regno defined by the insn, or -1. */
2802 static int insn_def_regno(const struct bpf_insn *insn)
2803 {
2804 	switch (BPF_CLASS(insn->code)) {
2805 	case BPF_JMP:
2806 	case BPF_JMP32:
2807 	case BPF_ST:
2808 		return -1;
2809 	case BPF_STX:
2810 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2811 		    (insn->imm & BPF_FETCH)) {
2812 			if (insn->imm == BPF_CMPXCHG)
2813 				return BPF_REG_0;
2814 			else
2815 				return insn->src_reg;
2816 		} else {
2817 			return -1;
2818 		}
2819 	default:
2820 		return insn->dst_reg;
2821 	}
2822 }
2823 
2824 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2825 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2826 {
2827 	int dst_reg = insn_def_regno(insn);
2828 
2829 	if (dst_reg == -1)
2830 		return false;
2831 
2832 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2833 }
2834 
2835 static void mark_insn_zext(struct bpf_verifier_env *env,
2836 			   struct bpf_reg_state *reg)
2837 {
2838 	s32 def_idx = reg->subreg_def;
2839 
2840 	if (def_idx == DEF_NOT_SUBREG)
2841 		return;
2842 
2843 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2844 	/* The dst will be zero extended, so won't be sub-register anymore. */
2845 	reg->subreg_def = DEF_NOT_SUBREG;
2846 }
2847 
2848 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2849 			 enum reg_arg_type t)
2850 {
2851 	struct bpf_verifier_state *vstate = env->cur_state;
2852 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2853 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2854 	struct bpf_reg_state *reg, *regs = state->regs;
2855 	bool rw64;
2856 
2857 	if (regno >= MAX_BPF_REG) {
2858 		verbose(env, "R%d is invalid\n", regno);
2859 		return -EINVAL;
2860 	}
2861 
2862 	mark_reg_scratched(env, regno);
2863 
2864 	reg = &regs[regno];
2865 	rw64 = is_reg64(env, insn, regno, reg, t);
2866 	if (t == SRC_OP) {
2867 		/* check whether register used as source operand can be read */
2868 		if (reg->type == NOT_INIT) {
2869 			verbose(env, "R%d !read_ok\n", regno);
2870 			return -EACCES;
2871 		}
2872 		/* We don't need to worry about FP liveness because it's read-only */
2873 		if (regno == BPF_REG_FP)
2874 			return 0;
2875 
2876 		if (rw64)
2877 			mark_insn_zext(env, reg);
2878 
2879 		return mark_reg_read(env, reg, reg->parent,
2880 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2881 	} else {
2882 		/* check whether register used as dest operand can be written to */
2883 		if (regno == BPF_REG_FP) {
2884 			verbose(env, "frame pointer is read only\n");
2885 			return -EACCES;
2886 		}
2887 		reg->live |= REG_LIVE_WRITTEN;
2888 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2889 		if (t == DST_OP)
2890 			mark_reg_unknown(env, regs, regno);
2891 	}
2892 	return 0;
2893 }
2894 
2895 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2896 {
2897 	env->insn_aux_data[idx].jmp_point = true;
2898 }
2899 
2900 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2901 {
2902 	return env->insn_aux_data[insn_idx].jmp_point;
2903 }
2904 
2905 /* for any branch, call, exit record the history of jmps in the given state */
2906 static int push_jmp_history(struct bpf_verifier_env *env,
2907 			    struct bpf_verifier_state *cur)
2908 {
2909 	u32 cnt = cur->jmp_history_cnt;
2910 	struct bpf_idx_pair *p;
2911 	size_t alloc_size;
2912 
2913 	if (!is_jmp_point(env, env->insn_idx))
2914 		return 0;
2915 
2916 	cnt++;
2917 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2918 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2919 	if (!p)
2920 		return -ENOMEM;
2921 	p[cnt - 1].idx = env->insn_idx;
2922 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2923 	cur->jmp_history = p;
2924 	cur->jmp_history_cnt = cnt;
2925 	return 0;
2926 }
2927 
2928 /* Backtrack one insn at a time. If idx is not at the top of recorded
2929  * history then previous instruction came from straight line execution.
2930  */
2931 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2932 			     u32 *history)
2933 {
2934 	u32 cnt = *history;
2935 
2936 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2937 		i = st->jmp_history[cnt - 1].prev_idx;
2938 		(*history)--;
2939 	} else {
2940 		i--;
2941 	}
2942 	return i;
2943 }
2944 
2945 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2946 {
2947 	const struct btf_type *func;
2948 	struct btf *desc_btf;
2949 
2950 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2951 		return NULL;
2952 
2953 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2954 	if (IS_ERR(desc_btf))
2955 		return "<error>";
2956 
2957 	func = btf_type_by_id(desc_btf, insn->imm);
2958 	return btf_name_by_offset(desc_btf, func->name_off);
2959 }
2960 
2961 /* For given verifier state backtrack_insn() is called from the last insn to
2962  * the first insn. Its purpose is to compute a bitmask of registers and
2963  * stack slots that needs precision in the parent verifier state.
2964  */
2965 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2966 			  u32 *reg_mask, u64 *stack_mask)
2967 {
2968 	const struct bpf_insn_cbs cbs = {
2969 		.cb_call	= disasm_kfunc_name,
2970 		.cb_print	= verbose,
2971 		.private_data	= env,
2972 	};
2973 	struct bpf_insn *insn = env->prog->insnsi + idx;
2974 	u8 class = BPF_CLASS(insn->code);
2975 	u8 opcode = BPF_OP(insn->code);
2976 	u8 mode = BPF_MODE(insn->code);
2977 	u32 dreg = 1u << insn->dst_reg;
2978 	u32 sreg = 1u << insn->src_reg;
2979 	u32 spi;
2980 
2981 	if (insn->code == 0)
2982 		return 0;
2983 	if (env->log.level & BPF_LOG_LEVEL2) {
2984 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2985 		verbose(env, "%d: ", idx);
2986 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2987 	}
2988 
2989 	if (class == BPF_ALU || class == BPF_ALU64) {
2990 		if (!(*reg_mask & dreg))
2991 			return 0;
2992 		if (opcode == BPF_MOV) {
2993 			if (BPF_SRC(insn->code) == BPF_X) {
2994 				/* dreg = sreg
2995 				 * dreg needs precision after this insn
2996 				 * sreg needs precision before this insn
2997 				 */
2998 				*reg_mask &= ~dreg;
2999 				*reg_mask |= sreg;
3000 			} else {
3001 				/* dreg = K
3002 				 * dreg needs precision after this insn.
3003 				 * Corresponding register is already marked
3004 				 * as precise=true in this verifier state.
3005 				 * No further markings in parent are necessary
3006 				 */
3007 				*reg_mask &= ~dreg;
3008 			}
3009 		} else {
3010 			if (BPF_SRC(insn->code) == BPF_X) {
3011 				/* dreg += sreg
3012 				 * both dreg and sreg need precision
3013 				 * before this insn
3014 				 */
3015 				*reg_mask |= sreg;
3016 			} /* else dreg += K
3017 			   * dreg still needs precision before this insn
3018 			   */
3019 		}
3020 	} else if (class == BPF_LDX) {
3021 		if (!(*reg_mask & dreg))
3022 			return 0;
3023 		*reg_mask &= ~dreg;
3024 
3025 		/* scalars can only be spilled into stack w/o losing precision.
3026 		 * Load from any other memory can be zero extended.
3027 		 * The desire to keep that precision is already indicated
3028 		 * by 'precise' mark in corresponding register of this state.
3029 		 * No further tracking necessary.
3030 		 */
3031 		if (insn->src_reg != BPF_REG_FP)
3032 			return 0;
3033 
3034 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3035 		 * that [fp - off] slot contains scalar that needs to be
3036 		 * tracked with precision
3037 		 */
3038 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3039 		if (spi >= 64) {
3040 			verbose(env, "BUG spi %d\n", spi);
3041 			WARN_ONCE(1, "verifier backtracking bug");
3042 			return -EFAULT;
3043 		}
3044 		*stack_mask |= 1ull << spi;
3045 	} else if (class == BPF_STX || class == BPF_ST) {
3046 		if (*reg_mask & dreg)
3047 			/* stx & st shouldn't be using _scalar_ dst_reg
3048 			 * to access memory. It means backtracking
3049 			 * encountered a case of pointer subtraction.
3050 			 */
3051 			return -ENOTSUPP;
3052 		/* scalars can only be spilled into stack */
3053 		if (insn->dst_reg != BPF_REG_FP)
3054 			return 0;
3055 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3056 		if (spi >= 64) {
3057 			verbose(env, "BUG spi %d\n", spi);
3058 			WARN_ONCE(1, "verifier backtracking bug");
3059 			return -EFAULT;
3060 		}
3061 		if (!(*stack_mask & (1ull << spi)))
3062 			return 0;
3063 		*stack_mask &= ~(1ull << spi);
3064 		if (class == BPF_STX)
3065 			*reg_mask |= sreg;
3066 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3067 		if (opcode == BPF_CALL) {
3068 			if (insn->src_reg == BPF_PSEUDO_CALL)
3069 				return -ENOTSUPP;
3070 			/* BPF helpers that invoke callback subprogs are
3071 			 * equivalent to BPF_PSEUDO_CALL above
3072 			 */
3073 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3074 				return -ENOTSUPP;
3075 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3076 			 * catch this error later. Make backtracking conservative
3077 			 * with ENOTSUPP.
3078 			 */
3079 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3080 				return -ENOTSUPP;
3081 			/* regular helper call sets R0 */
3082 			*reg_mask &= ~1;
3083 			if (*reg_mask & 0x3f) {
3084 				/* if backtracing was looking for registers R1-R5
3085 				 * they should have been found already.
3086 				 */
3087 				verbose(env, "BUG regs %x\n", *reg_mask);
3088 				WARN_ONCE(1, "verifier backtracking bug");
3089 				return -EFAULT;
3090 			}
3091 		} else if (opcode == BPF_EXIT) {
3092 			return -ENOTSUPP;
3093 		}
3094 	} else if (class == BPF_LD) {
3095 		if (!(*reg_mask & dreg))
3096 			return 0;
3097 		*reg_mask &= ~dreg;
3098 		/* It's ld_imm64 or ld_abs or ld_ind.
3099 		 * For ld_imm64 no further tracking of precision
3100 		 * into parent is necessary
3101 		 */
3102 		if (mode == BPF_IND || mode == BPF_ABS)
3103 			/* to be analyzed */
3104 			return -ENOTSUPP;
3105 	}
3106 	return 0;
3107 }
3108 
3109 /* the scalar precision tracking algorithm:
3110  * . at the start all registers have precise=false.
3111  * . scalar ranges are tracked as normal through alu and jmp insns.
3112  * . once precise value of the scalar register is used in:
3113  *   .  ptr + scalar alu
3114  *   . if (scalar cond K|scalar)
3115  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3116  *   backtrack through the verifier states and mark all registers and
3117  *   stack slots with spilled constants that these scalar regisers
3118  *   should be precise.
3119  * . during state pruning two registers (or spilled stack slots)
3120  *   are equivalent if both are not precise.
3121  *
3122  * Note the verifier cannot simply walk register parentage chain,
3123  * since many different registers and stack slots could have been
3124  * used to compute single precise scalar.
3125  *
3126  * The approach of starting with precise=true for all registers and then
3127  * backtrack to mark a register as not precise when the verifier detects
3128  * that program doesn't care about specific value (e.g., when helper
3129  * takes register as ARG_ANYTHING parameter) is not safe.
3130  *
3131  * It's ok to walk single parentage chain of the verifier states.
3132  * It's possible that this backtracking will go all the way till 1st insn.
3133  * All other branches will be explored for needing precision later.
3134  *
3135  * The backtracking needs to deal with cases like:
3136  *   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)
3137  * r9 -= r8
3138  * r5 = r9
3139  * if r5 > 0x79f goto pc+7
3140  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3141  * r5 += 1
3142  * ...
3143  * call bpf_perf_event_output#25
3144  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3145  *
3146  * and this case:
3147  * r6 = 1
3148  * call foo // uses callee's r6 inside to compute r0
3149  * r0 += r6
3150  * if r0 == 0 goto
3151  *
3152  * to track above reg_mask/stack_mask needs to be independent for each frame.
3153  *
3154  * Also if parent's curframe > frame where backtracking started,
3155  * the verifier need to mark registers in both frames, otherwise callees
3156  * may incorrectly prune callers. This is similar to
3157  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3158  *
3159  * For now backtracking falls back into conservative marking.
3160  */
3161 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3162 				     struct bpf_verifier_state *st)
3163 {
3164 	struct bpf_func_state *func;
3165 	struct bpf_reg_state *reg;
3166 	int i, j;
3167 
3168 	/* big hammer: mark all scalars precise in this path.
3169 	 * pop_stack may still get !precise scalars.
3170 	 * We also skip current state and go straight to first parent state,
3171 	 * because precision markings in current non-checkpointed state are
3172 	 * not needed. See why in the comment in __mark_chain_precision below.
3173 	 */
3174 	for (st = st->parent; st; st = st->parent) {
3175 		for (i = 0; i <= st->curframe; i++) {
3176 			func = st->frame[i];
3177 			for (j = 0; j < BPF_REG_FP; j++) {
3178 				reg = &func->regs[j];
3179 				if (reg->type != SCALAR_VALUE)
3180 					continue;
3181 				reg->precise = true;
3182 			}
3183 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3184 				if (!is_spilled_reg(&func->stack[j]))
3185 					continue;
3186 				reg = &func->stack[j].spilled_ptr;
3187 				if (reg->type != SCALAR_VALUE)
3188 					continue;
3189 				reg->precise = true;
3190 			}
3191 		}
3192 	}
3193 }
3194 
3195 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3196 {
3197 	struct bpf_func_state *func;
3198 	struct bpf_reg_state *reg;
3199 	int i, j;
3200 
3201 	for (i = 0; i <= st->curframe; i++) {
3202 		func = st->frame[i];
3203 		for (j = 0; j < BPF_REG_FP; j++) {
3204 			reg = &func->regs[j];
3205 			if (reg->type != SCALAR_VALUE)
3206 				continue;
3207 			reg->precise = false;
3208 		}
3209 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3210 			if (!is_spilled_reg(&func->stack[j]))
3211 				continue;
3212 			reg = &func->stack[j].spilled_ptr;
3213 			if (reg->type != SCALAR_VALUE)
3214 				continue;
3215 			reg->precise = false;
3216 		}
3217 	}
3218 }
3219 
3220 /*
3221  * __mark_chain_precision() backtracks BPF program instruction sequence and
3222  * chain of verifier states making sure that register *regno* (if regno >= 0)
3223  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3224  * SCALARS, as well as any other registers and slots that contribute to
3225  * a tracked state of given registers/stack slots, depending on specific BPF
3226  * assembly instructions (see backtrack_insns() for exact instruction handling
3227  * logic). This backtracking relies on recorded jmp_history and is able to
3228  * traverse entire chain of parent states. This process ends only when all the
3229  * necessary registers/slots and their transitive dependencies are marked as
3230  * precise.
3231  *
3232  * One important and subtle aspect is that precise marks *do not matter* in
3233  * the currently verified state (current state). It is important to understand
3234  * why this is the case.
3235  *
3236  * First, note that current state is the state that is not yet "checkpointed",
3237  * i.e., it is not yet put into env->explored_states, and it has no children
3238  * states as well. It's ephemeral, and can end up either a) being discarded if
3239  * compatible explored state is found at some point or BPF_EXIT instruction is
3240  * reached or b) checkpointed and put into env->explored_states, branching out
3241  * into one or more children states.
3242  *
3243  * In the former case, precise markings in current state are completely
3244  * ignored by state comparison code (see regsafe() for details). Only
3245  * checkpointed ("old") state precise markings are important, and if old
3246  * state's register/slot is precise, regsafe() assumes current state's
3247  * register/slot as precise and checks value ranges exactly and precisely. If
3248  * states turn out to be compatible, current state's necessary precise
3249  * markings and any required parent states' precise markings are enforced
3250  * after the fact with propagate_precision() logic, after the fact. But it's
3251  * important to realize that in this case, even after marking current state
3252  * registers/slots as precise, we immediately discard current state. So what
3253  * actually matters is any of the precise markings propagated into current
3254  * state's parent states, which are always checkpointed (due to b) case above).
3255  * As such, for scenario a) it doesn't matter if current state has precise
3256  * markings set or not.
3257  *
3258  * Now, for the scenario b), checkpointing and forking into child(ren)
3259  * state(s). Note that before current state gets to checkpointing step, any
3260  * processed instruction always assumes precise SCALAR register/slot
3261  * knowledge: if precise value or range is useful to prune jump branch, BPF
3262  * verifier takes this opportunity enthusiastically. Similarly, when
3263  * register's value is used to calculate offset or memory address, exact
3264  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3265  * what we mentioned above about state comparison ignoring precise markings
3266  * during state comparison, BPF verifier ignores and also assumes precise
3267  * markings *at will* during instruction verification process. But as verifier
3268  * assumes precision, it also propagates any precision dependencies across
3269  * parent states, which are not yet finalized, so can be further restricted
3270  * based on new knowledge gained from restrictions enforced by their children
3271  * states. This is so that once those parent states are finalized, i.e., when
3272  * they have no more active children state, state comparison logic in
3273  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3274  * required for correctness.
3275  *
3276  * To build a bit more intuition, note also that once a state is checkpointed,
3277  * the path we took to get to that state is not important. This is crucial
3278  * property for state pruning. When state is checkpointed and finalized at
3279  * some instruction index, it can be correctly and safely used to "short
3280  * circuit" any *compatible* state that reaches exactly the same instruction
3281  * index. I.e., if we jumped to that instruction from a completely different
3282  * code path than original finalized state was derived from, it doesn't
3283  * matter, current state can be discarded because from that instruction
3284  * forward having a compatible state will ensure we will safely reach the
3285  * exit. States describe preconditions for further exploration, but completely
3286  * forget the history of how we got here.
3287  *
3288  * This also means that even if we needed precise SCALAR range to get to
3289  * finalized state, but from that point forward *that same* SCALAR register is
3290  * never used in a precise context (i.e., it's precise value is not needed for
3291  * correctness), it's correct and safe to mark such register as "imprecise"
3292  * (i.e., precise marking set to false). This is what we rely on when we do
3293  * not set precise marking in current state. If no child state requires
3294  * precision for any given SCALAR register, it's safe to dictate that it can
3295  * be imprecise. If any child state does require this register to be precise,
3296  * we'll mark it precise later retroactively during precise markings
3297  * propagation from child state to parent states.
3298  *
3299  * Skipping precise marking setting in current state is a mild version of
3300  * relying on the above observation. But we can utilize this property even
3301  * more aggressively by proactively forgetting any precise marking in the
3302  * current state (which we inherited from the parent state), right before we
3303  * checkpoint it and branch off into new child state. This is done by
3304  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3305  * finalized states which help in short circuiting more future states.
3306  */
3307 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3308 				  int spi)
3309 {
3310 	struct bpf_verifier_state *st = env->cur_state;
3311 	int first_idx = st->first_insn_idx;
3312 	int last_idx = env->insn_idx;
3313 	struct bpf_func_state *func;
3314 	struct bpf_reg_state *reg;
3315 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3316 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3317 	bool skip_first = true;
3318 	bool new_marks = false;
3319 	int i, err;
3320 
3321 	if (!env->bpf_capable)
3322 		return 0;
3323 
3324 	/* Do sanity checks against current state of register and/or stack
3325 	 * slot, but don't set precise flag in current state, as precision
3326 	 * tracking in the current state is unnecessary.
3327 	 */
3328 	func = st->frame[frame];
3329 	if (regno >= 0) {
3330 		reg = &func->regs[regno];
3331 		if (reg->type != SCALAR_VALUE) {
3332 			WARN_ONCE(1, "backtracing misuse");
3333 			return -EFAULT;
3334 		}
3335 		new_marks = true;
3336 	}
3337 
3338 	while (spi >= 0) {
3339 		if (!is_spilled_reg(&func->stack[spi])) {
3340 			stack_mask = 0;
3341 			break;
3342 		}
3343 		reg = &func->stack[spi].spilled_ptr;
3344 		if (reg->type != SCALAR_VALUE) {
3345 			stack_mask = 0;
3346 			break;
3347 		}
3348 		new_marks = true;
3349 		break;
3350 	}
3351 
3352 	if (!new_marks)
3353 		return 0;
3354 	if (!reg_mask && !stack_mask)
3355 		return 0;
3356 
3357 	for (;;) {
3358 		DECLARE_BITMAP(mask, 64);
3359 		u32 history = st->jmp_history_cnt;
3360 
3361 		if (env->log.level & BPF_LOG_LEVEL2)
3362 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3363 
3364 		if (last_idx < 0) {
3365 			/* we are at the entry into subprog, which
3366 			 * is expected for global funcs, but only if
3367 			 * requested precise registers are R1-R5
3368 			 * (which are global func's input arguments)
3369 			 */
3370 			if (st->curframe == 0 &&
3371 			    st->frame[0]->subprogno > 0 &&
3372 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3373 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3374 				bitmap_from_u64(mask, reg_mask);
3375 				for_each_set_bit(i, mask, 32) {
3376 					reg = &st->frame[0]->regs[i];
3377 					if (reg->type != SCALAR_VALUE) {
3378 						reg_mask &= ~(1u << i);
3379 						continue;
3380 					}
3381 					reg->precise = true;
3382 				}
3383 				return 0;
3384 			}
3385 
3386 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3387 				st->frame[0]->subprogno, reg_mask, stack_mask);
3388 			WARN_ONCE(1, "verifier backtracking bug");
3389 			return -EFAULT;
3390 		}
3391 
3392 		for (i = last_idx;;) {
3393 			if (skip_first) {
3394 				err = 0;
3395 				skip_first = false;
3396 			} else {
3397 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3398 			}
3399 			if (err == -ENOTSUPP) {
3400 				mark_all_scalars_precise(env, st);
3401 				return 0;
3402 			} else if (err) {
3403 				return err;
3404 			}
3405 			if (!reg_mask && !stack_mask)
3406 				/* Found assignment(s) into tracked register in this state.
3407 				 * Since this state is already marked, just return.
3408 				 * Nothing to be tracked further in the parent state.
3409 				 */
3410 				return 0;
3411 			if (i == first_idx)
3412 				break;
3413 			i = get_prev_insn_idx(st, i, &history);
3414 			if (i >= env->prog->len) {
3415 				/* This can happen if backtracking reached insn 0
3416 				 * and there are still reg_mask or stack_mask
3417 				 * to backtrack.
3418 				 * It means the backtracking missed the spot where
3419 				 * particular register was initialized with a constant.
3420 				 */
3421 				verbose(env, "BUG backtracking idx %d\n", i);
3422 				WARN_ONCE(1, "verifier backtracking bug");
3423 				return -EFAULT;
3424 			}
3425 		}
3426 		st = st->parent;
3427 		if (!st)
3428 			break;
3429 
3430 		new_marks = false;
3431 		func = st->frame[frame];
3432 		bitmap_from_u64(mask, reg_mask);
3433 		for_each_set_bit(i, mask, 32) {
3434 			reg = &func->regs[i];
3435 			if (reg->type != SCALAR_VALUE) {
3436 				reg_mask &= ~(1u << i);
3437 				continue;
3438 			}
3439 			if (!reg->precise)
3440 				new_marks = true;
3441 			reg->precise = true;
3442 		}
3443 
3444 		bitmap_from_u64(mask, stack_mask);
3445 		for_each_set_bit(i, mask, 64) {
3446 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3447 				/* the sequence of instructions:
3448 				 * 2: (bf) r3 = r10
3449 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3450 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3451 				 * doesn't contain jmps. It's backtracked
3452 				 * as a single block.
3453 				 * During backtracking insn 3 is not recognized as
3454 				 * stack access, so at the end of backtracking
3455 				 * stack slot fp-8 is still marked in stack_mask.
3456 				 * However the parent state may not have accessed
3457 				 * fp-8 and it's "unallocated" stack space.
3458 				 * In such case fallback to conservative.
3459 				 */
3460 				mark_all_scalars_precise(env, st);
3461 				return 0;
3462 			}
3463 
3464 			if (!is_spilled_reg(&func->stack[i])) {
3465 				stack_mask &= ~(1ull << i);
3466 				continue;
3467 			}
3468 			reg = &func->stack[i].spilled_ptr;
3469 			if (reg->type != SCALAR_VALUE) {
3470 				stack_mask &= ~(1ull << i);
3471 				continue;
3472 			}
3473 			if (!reg->precise)
3474 				new_marks = true;
3475 			reg->precise = true;
3476 		}
3477 		if (env->log.level & BPF_LOG_LEVEL2) {
3478 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3479 				new_marks ? "didn't have" : "already had",
3480 				reg_mask, stack_mask);
3481 			print_verifier_state(env, func, true);
3482 		}
3483 
3484 		if (!reg_mask && !stack_mask)
3485 			break;
3486 		if (!new_marks)
3487 			break;
3488 
3489 		last_idx = st->last_insn_idx;
3490 		first_idx = st->first_insn_idx;
3491 	}
3492 	return 0;
3493 }
3494 
3495 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3496 {
3497 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3498 }
3499 
3500 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3501 {
3502 	return __mark_chain_precision(env, frame, regno, -1);
3503 }
3504 
3505 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3506 {
3507 	return __mark_chain_precision(env, frame, -1, spi);
3508 }
3509 
3510 static bool is_spillable_regtype(enum bpf_reg_type type)
3511 {
3512 	switch (base_type(type)) {
3513 	case PTR_TO_MAP_VALUE:
3514 	case PTR_TO_STACK:
3515 	case PTR_TO_CTX:
3516 	case PTR_TO_PACKET:
3517 	case PTR_TO_PACKET_META:
3518 	case PTR_TO_PACKET_END:
3519 	case PTR_TO_FLOW_KEYS:
3520 	case CONST_PTR_TO_MAP:
3521 	case PTR_TO_SOCKET:
3522 	case PTR_TO_SOCK_COMMON:
3523 	case PTR_TO_TCP_SOCK:
3524 	case PTR_TO_XDP_SOCK:
3525 	case PTR_TO_BTF_ID:
3526 	case PTR_TO_BUF:
3527 	case PTR_TO_MEM:
3528 	case PTR_TO_FUNC:
3529 	case PTR_TO_MAP_KEY:
3530 		return true;
3531 	default:
3532 		return false;
3533 	}
3534 }
3535 
3536 /* Does this register contain a constant zero? */
3537 static bool register_is_null(struct bpf_reg_state *reg)
3538 {
3539 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3540 }
3541 
3542 static bool register_is_const(struct bpf_reg_state *reg)
3543 {
3544 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3545 }
3546 
3547 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3548 {
3549 	return tnum_is_unknown(reg->var_off) &&
3550 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3551 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3552 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3553 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3554 }
3555 
3556 static bool register_is_bounded(struct bpf_reg_state *reg)
3557 {
3558 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3559 }
3560 
3561 static bool __is_pointer_value(bool allow_ptr_leaks,
3562 			       const struct bpf_reg_state *reg)
3563 {
3564 	if (allow_ptr_leaks)
3565 		return false;
3566 
3567 	return reg->type != SCALAR_VALUE;
3568 }
3569 
3570 /* Copy src state preserving dst->parent and dst->live fields */
3571 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3572 {
3573 	struct bpf_reg_state *parent = dst->parent;
3574 	enum bpf_reg_liveness live = dst->live;
3575 
3576 	*dst = *src;
3577 	dst->parent = parent;
3578 	dst->live = live;
3579 }
3580 
3581 static void save_register_state(struct bpf_func_state *state,
3582 				int spi, struct bpf_reg_state *reg,
3583 				int size)
3584 {
3585 	int i;
3586 
3587 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
3588 	if (size == BPF_REG_SIZE)
3589 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3590 
3591 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3592 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3593 
3594 	/* size < 8 bytes spill */
3595 	for (; i; i--)
3596 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3597 }
3598 
3599 static bool is_bpf_st_mem(struct bpf_insn *insn)
3600 {
3601 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3602 }
3603 
3604 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3605  * stack boundary and alignment are checked in check_mem_access()
3606  */
3607 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3608 				       /* stack frame we're writing to */
3609 				       struct bpf_func_state *state,
3610 				       int off, int size, int value_regno,
3611 				       int insn_idx)
3612 {
3613 	struct bpf_func_state *cur; /* state of the current function */
3614 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3615 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3616 	struct bpf_reg_state *reg = NULL;
3617 	u32 dst_reg = insn->dst_reg;
3618 
3619 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3620 	if (err)
3621 		return err;
3622 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3623 	 * so it's aligned access and [off, off + size) are within stack limits
3624 	 */
3625 	if (!env->allow_ptr_leaks &&
3626 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3627 	    size != BPF_REG_SIZE) {
3628 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3629 		return -EACCES;
3630 	}
3631 
3632 	cur = env->cur_state->frame[env->cur_state->curframe];
3633 	if (value_regno >= 0)
3634 		reg = &cur->regs[value_regno];
3635 	if (!env->bypass_spec_v4) {
3636 		bool sanitize = reg && is_spillable_regtype(reg->type);
3637 
3638 		for (i = 0; i < size; i++) {
3639 			u8 type = state->stack[spi].slot_type[i];
3640 
3641 			if (type != STACK_MISC && type != STACK_ZERO) {
3642 				sanitize = true;
3643 				break;
3644 			}
3645 		}
3646 
3647 		if (sanitize)
3648 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3649 	}
3650 
3651 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3652 	if (err)
3653 		return err;
3654 
3655 	mark_stack_slot_scratched(env, spi);
3656 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3657 	    !register_is_null(reg) && env->bpf_capable) {
3658 		if (dst_reg != BPF_REG_FP) {
3659 			/* The backtracking logic can only recognize explicit
3660 			 * stack slot address like [fp - 8]. Other spill of
3661 			 * scalar via different register has to be conservative.
3662 			 * Backtrack from here and mark all registers as precise
3663 			 * that contributed into 'reg' being a constant.
3664 			 */
3665 			err = mark_chain_precision(env, value_regno);
3666 			if (err)
3667 				return err;
3668 		}
3669 		save_register_state(state, spi, reg, size);
3670 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3671 		   insn->imm != 0 && env->bpf_capable) {
3672 		struct bpf_reg_state fake_reg = {};
3673 
3674 		__mark_reg_known(&fake_reg, (u32)insn->imm);
3675 		fake_reg.type = SCALAR_VALUE;
3676 		save_register_state(state, spi, &fake_reg, size);
3677 	} else if (reg && is_spillable_regtype(reg->type)) {
3678 		/* register containing pointer is being spilled into stack */
3679 		if (size != BPF_REG_SIZE) {
3680 			verbose_linfo(env, insn_idx, "; ");
3681 			verbose(env, "invalid size of register spill\n");
3682 			return -EACCES;
3683 		}
3684 		if (state != cur && reg->type == PTR_TO_STACK) {
3685 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3686 			return -EINVAL;
3687 		}
3688 		save_register_state(state, spi, reg, size);
3689 	} else {
3690 		u8 type = STACK_MISC;
3691 
3692 		/* regular write of data into stack destroys any spilled ptr */
3693 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3694 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3695 		if (is_spilled_reg(&state->stack[spi]))
3696 			for (i = 0; i < BPF_REG_SIZE; i++)
3697 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3698 
3699 		/* only mark the slot as written if all 8 bytes were written
3700 		 * otherwise read propagation may incorrectly stop too soon
3701 		 * when stack slots are partially written.
3702 		 * This heuristic means that read propagation will be
3703 		 * conservative, since it will add reg_live_read marks
3704 		 * to stack slots all the way to first state when programs
3705 		 * writes+reads less than 8 bytes
3706 		 */
3707 		if (size == BPF_REG_SIZE)
3708 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3709 
3710 		/* when we zero initialize stack slots mark them as such */
3711 		if ((reg && register_is_null(reg)) ||
3712 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3713 			/* backtracking doesn't work for STACK_ZERO yet. */
3714 			err = mark_chain_precision(env, value_regno);
3715 			if (err)
3716 				return err;
3717 			type = STACK_ZERO;
3718 		}
3719 
3720 		/* Mark slots affected by this stack write. */
3721 		for (i = 0; i < size; i++)
3722 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3723 				type;
3724 	}
3725 	return 0;
3726 }
3727 
3728 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3729  * known to contain a variable offset.
3730  * This function checks whether the write is permitted and conservatively
3731  * tracks the effects of the write, considering that each stack slot in the
3732  * dynamic range is potentially written to.
3733  *
3734  * 'off' includes 'regno->off'.
3735  * 'value_regno' can be -1, meaning that an unknown value is being written to
3736  * the stack.
3737  *
3738  * Spilled pointers in range are not marked as written because we don't know
3739  * what's going to be actually written. This means that read propagation for
3740  * future reads cannot be terminated by this write.
3741  *
3742  * For privileged programs, uninitialized stack slots are considered
3743  * initialized by this write (even though we don't know exactly what offsets
3744  * are going to be written to). The idea is that we don't want the verifier to
3745  * reject future reads that access slots written to through variable offsets.
3746  */
3747 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3748 				     /* func where register points to */
3749 				     struct bpf_func_state *state,
3750 				     int ptr_regno, int off, int size,
3751 				     int value_regno, int insn_idx)
3752 {
3753 	struct bpf_func_state *cur; /* state of the current function */
3754 	int min_off, max_off;
3755 	int i, err;
3756 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3757 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3758 	bool writing_zero = false;
3759 	/* set if the fact that we're writing a zero is used to let any
3760 	 * stack slots remain STACK_ZERO
3761 	 */
3762 	bool zero_used = false;
3763 
3764 	cur = env->cur_state->frame[env->cur_state->curframe];
3765 	ptr_reg = &cur->regs[ptr_regno];
3766 	min_off = ptr_reg->smin_value + off;
3767 	max_off = ptr_reg->smax_value + off + size;
3768 	if (value_regno >= 0)
3769 		value_reg = &cur->regs[value_regno];
3770 	if ((value_reg && register_is_null(value_reg)) ||
3771 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3772 		writing_zero = true;
3773 
3774 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3775 	if (err)
3776 		return err;
3777 
3778 	for (i = min_off; i < max_off; i++) {
3779 		int spi;
3780 
3781 		spi = __get_spi(i);
3782 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3783 		if (err)
3784 			return err;
3785 	}
3786 
3787 	/* Variable offset writes destroy any spilled pointers in range. */
3788 	for (i = min_off; i < max_off; i++) {
3789 		u8 new_type, *stype;
3790 		int slot, spi;
3791 
3792 		slot = -i - 1;
3793 		spi = slot / BPF_REG_SIZE;
3794 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3795 		mark_stack_slot_scratched(env, spi);
3796 
3797 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3798 			/* Reject the write if range we may write to has not
3799 			 * been initialized beforehand. If we didn't reject
3800 			 * here, the ptr status would be erased below (even
3801 			 * though not all slots are actually overwritten),
3802 			 * possibly opening the door to leaks.
3803 			 *
3804 			 * We do however catch STACK_INVALID case below, and
3805 			 * only allow reading possibly uninitialized memory
3806 			 * later for CAP_PERFMON, as the write may not happen to
3807 			 * that slot.
3808 			 */
3809 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3810 				insn_idx, i);
3811 			return -EINVAL;
3812 		}
3813 
3814 		/* Erase all spilled pointers. */
3815 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3816 
3817 		/* Update the slot type. */
3818 		new_type = STACK_MISC;
3819 		if (writing_zero && *stype == STACK_ZERO) {
3820 			new_type = STACK_ZERO;
3821 			zero_used = true;
3822 		}
3823 		/* If the slot is STACK_INVALID, we check whether it's OK to
3824 		 * pretend that it will be initialized by this write. The slot
3825 		 * might not actually be written to, and so if we mark it as
3826 		 * initialized future reads might leak uninitialized memory.
3827 		 * For privileged programs, we will accept such reads to slots
3828 		 * that may or may not be written because, if we're reject
3829 		 * them, the error would be too confusing.
3830 		 */
3831 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3832 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3833 					insn_idx, i);
3834 			return -EINVAL;
3835 		}
3836 		*stype = new_type;
3837 	}
3838 	if (zero_used) {
3839 		/* backtracking doesn't work for STACK_ZERO yet. */
3840 		err = mark_chain_precision(env, value_regno);
3841 		if (err)
3842 			return err;
3843 	}
3844 	return 0;
3845 }
3846 
3847 /* When register 'dst_regno' is assigned some values from stack[min_off,
3848  * max_off), we set the register's type according to the types of the
3849  * respective stack slots. If all the stack values are known to be zeros, then
3850  * so is the destination reg. Otherwise, the register is considered to be
3851  * SCALAR. This function does not deal with register filling; the caller must
3852  * ensure that all spilled registers in the stack range have been marked as
3853  * read.
3854  */
3855 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3856 				/* func where src register points to */
3857 				struct bpf_func_state *ptr_state,
3858 				int min_off, int max_off, int dst_regno)
3859 {
3860 	struct bpf_verifier_state *vstate = env->cur_state;
3861 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3862 	int i, slot, spi;
3863 	u8 *stype;
3864 	int zeros = 0;
3865 
3866 	for (i = min_off; i < max_off; i++) {
3867 		slot = -i - 1;
3868 		spi = slot / BPF_REG_SIZE;
3869 		stype = ptr_state->stack[spi].slot_type;
3870 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3871 			break;
3872 		zeros++;
3873 	}
3874 	if (zeros == max_off - min_off) {
3875 		/* any access_size read into register is zero extended,
3876 		 * so the whole register == const_zero
3877 		 */
3878 		__mark_reg_const_zero(&state->regs[dst_regno]);
3879 		/* backtracking doesn't support STACK_ZERO yet,
3880 		 * so mark it precise here, so that later
3881 		 * backtracking can stop here.
3882 		 * Backtracking may not need this if this register
3883 		 * doesn't participate in pointer adjustment.
3884 		 * Forward propagation of precise flag is not
3885 		 * necessary either. This mark is only to stop
3886 		 * backtracking. Any register that contributed
3887 		 * to const 0 was marked precise before spill.
3888 		 */
3889 		state->regs[dst_regno].precise = true;
3890 	} else {
3891 		/* have read misc data from the stack */
3892 		mark_reg_unknown(env, state->regs, dst_regno);
3893 	}
3894 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3895 }
3896 
3897 /* Read the stack at 'off' and put the results into the register indicated by
3898  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3899  * spilled reg.
3900  *
3901  * 'dst_regno' can be -1, meaning that the read value is not going to a
3902  * register.
3903  *
3904  * The access is assumed to be within the current stack bounds.
3905  */
3906 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3907 				      /* func where src register points to */
3908 				      struct bpf_func_state *reg_state,
3909 				      int off, int size, int dst_regno)
3910 {
3911 	struct bpf_verifier_state *vstate = env->cur_state;
3912 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3913 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3914 	struct bpf_reg_state *reg;
3915 	u8 *stype, type;
3916 
3917 	stype = reg_state->stack[spi].slot_type;
3918 	reg = &reg_state->stack[spi].spilled_ptr;
3919 
3920 	if (is_spilled_reg(&reg_state->stack[spi])) {
3921 		u8 spill_size = 1;
3922 
3923 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3924 			spill_size++;
3925 
3926 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3927 			if (reg->type != SCALAR_VALUE) {
3928 				verbose_linfo(env, env->insn_idx, "; ");
3929 				verbose(env, "invalid size of register fill\n");
3930 				return -EACCES;
3931 			}
3932 
3933 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3934 			if (dst_regno < 0)
3935 				return 0;
3936 
3937 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3938 				/* The earlier check_reg_arg() has decided the
3939 				 * subreg_def for this insn.  Save it first.
3940 				 */
3941 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3942 
3943 				copy_register_state(&state->regs[dst_regno], reg);
3944 				state->regs[dst_regno].subreg_def = subreg_def;
3945 			} else {
3946 				for (i = 0; i < size; i++) {
3947 					type = stype[(slot - i) % BPF_REG_SIZE];
3948 					if (type == STACK_SPILL)
3949 						continue;
3950 					if (type == STACK_MISC)
3951 						continue;
3952 					if (type == STACK_INVALID && env->allow_uninit_stack)
3953 						continue;
3954 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3955 						off, i, size);
3956 					return -EACCES;
3957 				}
3958 				mark_reg_unknown(env, state->regs, dst_regno);
3959 			}
3960 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3961 			return 0;
3962 		}
3963 
3964 		if (dst_regno >= 0) {
3965 			/* restore register state from stack */
3966 			copy_register_state(&state->regs[dst_regno], reg);
3967 			/* mark reg as written since spilled pointer state likely
3968 			 * has its liveness marks cleared by is_state_visited()
3969 			 * which resets stack/reg liveness for state transitions
3970 			 */
3971 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3972 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3973 			/* If dst_regno==-1, the caller is asking us whether
3974 			 * it is acceptable to use this value as a SCALAR_VALUE
3975 			 * (e.g. for XADD).
3976 			 * We must not allow unprivileged callers to do that
3977 			 * with spilled pointers.
3978 			 */
3979 			verbose(env, "leaking pointer from stack off %d\n",
3980 				off);
3981 			return -EACCES;
3982 		}
3983 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3984 	} else {
3985 		for (i = 0; i < size; i++) {
3986 			type = stype[(slot - i) % BPF_REG_SIZE];
3987 			if (type == STACK_MISC)
3988 				continue;
3989 			if (type == STACK_ZERO)
3990 				continue;
3991 			if (type == STACK_INVALID && env->allow_uninit_stack)
3992 				continue;
3993 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3994 				off, i, size);
3995 			return -EACCES;
3996 		}
3997 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3998 		if (dst_regno >= 0)
3999 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4000 	}
4001 	return 0;
4002 }
4003 
4004 enum bpf_access_src {
4005 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4006 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4007 };
4008 
4009 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4010 					 int regno, int off, int access_size,
4011 					 bool zero_size_allowed,
4012 					 enum bpf_access_src type,
4013 					 struct bpf_call_arg_meta *meta);
4014 
4015 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4016 {
4017 	return cur_regs(env) + regno;
4018 }
4019 
4020 /* Read the stack at 'ptr_regno + off' and put the result into the register
4021  * 'dst_regno'.
4022  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4023  * but not its variable offset.
4024  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4025  *
4026  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4027  * filling registers (i.e. reads of spilled register cannot be detected when
4028  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4029  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4030  * offset; for a fixed offset check_stack_read_fixed_off should be used
4031  * instead.
4032  */
4033 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4034 				    int ptr_regno, int off, int size, int dst_regno)
4035 {
4036 	/* The state of the source register. */
4037 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4038 	struct bpf_func_state *ptr_state = func(env, reg);
4039 	int err;
4040 	int min_off, max_off;
4041 
4042 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4043 	 */
4044 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4045 					    false, ACCESS_DIRECT, NULL);
4046 	if (err)
4047 		return err;
4048 
4049 	min_off = reg->smin_value + off;
4050 	max_off = reg->smax_value + off;
4051 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4052 	return 0;
4053 }
4054 
4055 /* check_stack_read dispatches to check_stack_read_fixed_off or
4056  * check_stack_read_var_off.
4057  *
4058  * The caller must ensure that the offset falls within the allocated stack
4059  * bounds.
4060  *
4061  * 'dst_regno' is a register which will receive the value from the stack. It
4062  * can be -1, meaning that the read value is not going to a register.
4063  */
4064 static int check_stack_read(struct bpf_verifier_env *env,
4065 			    int ptr_regno, int off, int size,
4066 			    int dst_regno)
4067 {
4068 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4069 	struct bpf_func_state *state = func(env, reg);
4070 	int err;
4071 	/* Some accesses are only permitted with a static offset. */
4072 	bool var_off = !tnum_is_const(reg->var_off);
4073 
4074 	/* The offset is required to be static when reads don't go to a
4075 	 * register, in order to not leak pointers (see
4076 	 * check_stack_read_fixed_off).
4077 	 */
4078 	if (dst_regno < 0 && var_off) {
4079 		char tn_buf[48];
4080 
4081 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4082 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4083 			tn_buf, off, size);
4084 		return -EACCES;
4085 	}
4086 	/* Variable offset is prohibited for unprivileged mode for simplicity
4087 	 * since it requires corresponding support in Spectre masking for stack
4088 	 * ALU. See also retrieve_ptr_limit().
4089 	 */
4090 	if (!env->bypass_spec_v1 && var_off) {
4091 		char tn_buf[48];
4092 
4093 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4094 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
4095 				ptr_regno, tn_buf);
4096 		return -EACCES;
4097 	}
4098 
4099 	if (!var_off) {
4100 		off += reg->var_off.value;
4101 		err = check_stack_read_fixed_off(env, state, off, size,
4102 						 dst_regno);
4103 	} else {
4104 		/* Variable offset stack reads need more conservative handling
4105 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4106 		 * branch.
4107 		 */
4108 		err = check_stack_read_var_off(env, ptr_regno, off, size,
4109 					       dst_regno);
4110 	}
4111 	return err;
4112 }
4113 
4114 
4115 /* check_stack_write dispatches to check_stack_write_fixed_off or
4116  * check_stack_write_var_off.
4117  *
4118  * 'ptr_regno' is the register used as a pointer into the stack.
4119  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4120  * 'value_regno' is the register whose value we're writing to the stack. It can
4121  * be -1, meaning that we're not writing from a register.
4122  *
4123  * The caller must ensure that the offset falls within the maximum stack size.
4124  */
4125 static int check_stack_write(struct bpf_verifier_env *env,
4126 			     int ptr_regno, int off, int size,
4127 			     int value_regno, int insn_idx)
4128 {
4129 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4130 	struct bpf_func_state *state = func(env, reg);
4131 	int err;
4132 
4133 	if (tnum_is_const(reg->var_off)) {
4134 		off += reg->var_off.value;
4135 		err = check_stack_write_fixed_off(env, state, off, size,
4136 						  value_regno, insn_idx);
4137 	} else {
4138 		/* Variable offset stack reads need more conservative handling
4139 		 * than fixed offset ones.
4140 		 */
4141 		err = check_stack_write_var_off(env, state,
4142 						ptr_regno, off, size,
4143 						value_regno, insn_idx);
4144 	}
4145 	return err;
4146 }
4147 
4148 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4149 				 int off, int size, enum bpf_access_type type)
4150 {
4151 	struct bpf_reg_state *regs = cur_regs(env);
4152 	struct bpf_map *map = regs[regno].map_ptr;
4153 	u32 cap = bpf_map_flags_to_cap(map);
4154 
4155 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4156 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4157 			map->value_size, off, size);
4158 		return -EACCES;
4159 	}
4160 
4161 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4162 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4163 			map->value_size, off, size);
4164 		return -EACCES;
4165 	}
4166 
4167 	return 0;
4168 }
4169 
4170 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4171 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4172 			      int off, int size, u32 mem_size,
4173 			      bool zero_size_allowed)
4174 {
4175 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4176 	struct bpf_reg_state *reg;
4177 
4178 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4179 		return 0;
4180 
4181 	reg = &cur_regs(env)[regno];
4182 	switch (reg->type) {
4183 	case PTR_TO_MAP_KEY:
4184 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4185 			mem_size, off, size);
4186 		break;
4187 	case PTR_TO_MAP_VALUE:
4188 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4189 			mem_size, off, size);
4190 		break;
4191 	case PTR_TO_PACKET:
4192 	case PTR_TO_PACKET_META:
4193 	case PTR_TO_PACKET_END:
4194 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4195 			off, size, regno, reg->id, off, mem_size);
4196 		break;
4197 	case PTR_TO_MEM:
4198 	default:
4199 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4200 			mem_size, off, size);
4201 	}
4202 
4203 	return -EACCES;
4204 }
4205 
4206 /* check read/write into a memory region with possible variable offset */
4207 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4208 				   int off, int size, u32 mem_size,
4209 				   bool zero_size_allowed)
4210 {
4211 	struct bpf_verifier_state *vstate = env->cur_state;
4212 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4213 	struct bpf_reg_state *reg = &state->regs[regno];
4214 	int err;
4215 
4216 	/* We may have adjusted the register pointing to memory region, so we
4217 	 * need to try adding each of min_value and max_value to off
4218 	 * to make sure our theoretical access will be safe.
4219 	 *
4220 	 * The minimum value is only important with signed
4221 	 * comparisons where we can't assume the floor of a
4222 	 * value is 0.  If we are using signed variables for our
4223 	 * index'es we need to make sure that whatever we use
4224 	 * will have a set floor within our range.
4225 	 */
4226 	if (reg->smin_value < 0 &&
4227 	    (reg->smin_value == S64_MIN ||
4228 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4229 	      reg->smin_value + off < 0)) {
4230 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4231 			regno);
4232 		return -EACCES;
4233 	}
4234 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
4235 				 mem_size, zero_size_allowed);
4236 	if (err) {
4237 		verbose(env, "R%d min value is outside of the allowed memory range\n",
4238 			regno);
4239 		return err;
4240 	}
4241 
4242 	/* If we haven't set a max value then we need to bail since we can't be
4243 	 * sure we won't do bad things.
4244 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
4245 	 */
4246 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4247 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4248 			regno);
4249 		return -EACCES;
4250 	}
4251 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
4252 				 mem_size, zero_size_allowed);
4253 	if (err) {
4254 		verbose(env, "R%d max value is outside of the allowed memory range\n",
4255 			regno);
4256 		return err;
4257 	}
4258 
4259 	return 0;
4260 }
4261 
4262 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4263 			       const struct bpf_reg_state *reg, int regno,
4264 			       bool fixed_off_ok)
4265 {
4266 	/* Access to this pointer-typed register or passing it to a helper
4267 	 * is only allowed in its original, unmodified form.
4268 	 */
4269 
4270 	if (reg->off < 0) {
4271 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4272 			reg_type_str(env, reg->type), regno, reg->off);
4273 		return -EACCES;
4274 	}
4275 
4276 	if (!fixed_off_ok && reg->off) {
4277 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4278 			reg_type_str(env, reg->type), regno, reg->off);
4279 		return -EACCES;
4280 	}
4281 
4282 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4283 		char tn_buf[48];
4284 
4285 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4286 		verbose(env, "variable %s access var_off=%s disallowed\n",
4287 			reg_type_str(env, reg->type), tn_buf);
4288 		return -EACCES;
4289 	}
4290 
4291 	return 0;
4292 }
4293 
4294 int check_ptr_off_reg(struct bpf_verifier_env *env,
4295 		      const struct bpf_reg_state *reg, int regno)
4296 {
4297 	return __check_ptr_off_reg(env, reg, regno, false);
4298 }
4299 
4300 static int map_kptr_match_type(struct bpf_verifier_env *env,
4301 			       struct btf_field *kptr_field,
4302 			       struct bpf_reg_state *reg, u32 regno)
4303 {
4304 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4305 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4306 	const char *reg_name = "";
4307 
4308 	/* Only unreferenced case accepts untrusted pointers */
4309 	if (kptr_field->type == BPF_KPTR_UNREF)
4310 		perm_flags |= PTR_UNTRUSTED;
4311 
4312 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4313 		goto bad_type;
4314 
4315 	if (!btf_is_kernel(reg->btf)) {
4316 		verbose(env, "R%d must point to kernel BTF\n", regno);
4317 		return -EINVAL;
4318 	}
4319 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4320 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
4321 
4322 	/* For ref_ptr case, release function check should ensure we get one
4323 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4324 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4325 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4326 	 * reg->off and reg->ref_obj_id are not needed here.
4327 	 */
4328 	if (__check_ptr_off_reg(env, reg, regno, true))
4329 		return -EACCES;
4330 
4331 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
4332 	 * we also need to take into account the reg->off.
4333 	 *
4334 	 * We want to support cases like:
4335 	 *
4336 	 * struct foo {
4337 	 *         struct bar br;
4338 	 *         struct baz bz;
4339 	 * };
4340 	 *
4341 	 * struct foo *v;
4342 	 * v = func();	      // PTR_TO_BTF_ID
4343 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
4344 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4345 	 *                    // first member type of struct after comparison fails
4346 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4347 	 *                    // to match type
4348 	 *
4349 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4350 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4351 	 * the struct to match type against first member of struct, i.e. reject
4352 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4353 	 * strict mode to true for type match.
4354 	 */
4355 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4356 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4357 				  kptr_field->type == BPF_KPTR_REF))
4358 		goto bad_type;
4359 	return 0;
4360 bad_type:
4361 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4362 		reg_type_str(env, reg->type), reg_name);
4363 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4364 	if (kptr_field->type == BPF_KPTR_UNREF)
4365 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4366 			targ_name);
4367 	else
4368 		verbose(env, "\n");
4369 	return -EINVAL;
4370 }
4371 
4372 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4373  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4374  */
4375 static bool in_rcu_cs(struct bpf_verifier_env *env)
4376 {
4377 	return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4378 }
4379 
4380 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4381 BTF_SET_START(rcu_protected_types)
4382 BTF_ID(struct, prog_test_ref_kfunc)
4383 BTF_ID(struct, cgroup)
4384 BTF_SET_END(rcu_protected_types)
4385 
4386 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4387 {
4388 	if (!btf_is_kernel(btf))
4389 		return false;
4390 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4391 }
4392 
4393 static bool rcu_safe_kptr(const struct btf_field *field)
4394 {
4395 	const struct btf_field_kptr *kptr = &field->kptr;
4396 
4397 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4398 }
4399 
4400 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4401 				 int value_regno, int insn_idx,
4402 				 struct btf_field *kptr_field)
4403 {
4404 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4405 	int class = BPF_CLASS(insn->code);
4406 	struct bpf_reg_state *val_reg;
4407 
4408 	/* Things we already checked for in check_map_access and caller:
4409 	 *  - Reject cases where variable offset may touch kptr
4410 	 *  - size of access (must be BPF_DW)
4411 	 *  - tnum_is_const(reg->var_off)
4412 	 *  - kptr_field->offset == off + reg->var_off.value
4413 	 */
4414 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4415 	if (BPF_MODE(insn->code) != BPF_MEM) {
4416 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4417 		return -EACCES;
4418 	}
4419 
4420 	/* We only allow loading referenced kptr, since it will be marked as
4421 	 * untrusted, similar to unreferenced kptr.
4422 	 */
4423 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4424 		verbose(env, "store to referenced kptr disallowed\n");
4425 		return -EACCES;
4426 	}
4427 
4428 	if (class == BPF_LDX) {
4429 		val_reg = reg_state(env, value_regno);
4430 		/* We can simply mark the value_regno receiving the pointer
4431 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4432 		 */
4433 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4434 				kptr_field->kptr.btf_id,
4435 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4436 				PTR_MAYBE_NULL | MEM_RCU :
4437 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
4438 		/* For mark_ptr_or_null_reg */
4439 		val_reg->id = ++env->id_gen;
4440 	} else if (class == BPF_STX) {
4441 		val_reg = reg_state(env, value_regno);
4442 		if (!register_is_null(val_reg) &&
4443 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4444 			return -EACCES;
4445 	} else if (class == BPF_ST) {
4446 		if (insn->imm) {
4447 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4448 				kptr_field->offset);
4449 			return -EACCES;
4450 		}
4451 	} else {
4452 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4453 		return -EACCES;
4454 	}
4455 	return 0;
4456 }
4457 
4458 /* check read/write into a map element with possible variable offset */
4459 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4460 			    int off, int size, bool zero_size_allowed,
4461 			    enum bpf_access_src src)
4462 {
4463 	struct bpf_verifier_state *vstate = env->cur_state;
4464 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4465 	struct bpf_reg_state *reg = &state->regs[regno];
4466 	struct bpf_map *map = reg->map_ptr;
4467 	struct btf_record *rec;
4468 	int err, i;
4469 
4470 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4471 				      zero_size_allowed);
4472 	if (err)
4473 		return err;
4474 
4475 	if (IS_ERR_OR_NULL(map->record))
4476 		return 0;
4477 	rec = map->record;
4478 	for (i = 0; i < rec->cnt; i++) {
4479 		struct btf_field *field = &rec->fields[i];
4480 		u32 p = field->offset;
4481 
4482 		/* If any part of a field  can be touched by load/store, reject
4483 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4484 		 * it is sufficient to check x1 < y2 && y1 < x2.
4485 		 */
4486 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4487 		    p < reg->umax_value + off + size) {
4488 			switch (field->type) {
4489 			case BPF_KPTR_UNREF:
4490 			case BPF_KPTR_REF:
4491 				if (src != ACCESS_DIRECT) {
4492 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4493 					return -EACCES;
4494 				}
4495 				if (!tnum_is_const(reg->var_off)) {
4496 					verbose(env, "kptr access cannot have variable offset\n");
4497 					return -EACCES;
4498 				}
4499 				if (p != off + reg->var_off.value) {
4500 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4501 						p, off + reg->var_off.value);
4502 					return -EACCES;
4503 				}
4504 				if (size != bpf_size_to_bytes(BPF_DW)) {
4505 					verbose(env, "kptr access size must be BPF_DW\n");
4506 					return -EACCES;
4507 				}
4508 				break;
4509 			default:
4510 				verbose(env, "%s cannot be accessed directly by load/store\n",
4511 					btf_field_type_name(field->type));
4512 				return -EACCES;
4513 			}
4514 		}
4515 	}
4516 	return 0;
4517 }
4518 
4519 #define MAX_PACKET_OFF 0xffff
4520 
4521 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4522 				       const struct bpf_call_arg_meta *meta,
4523 				       enum bpf_access_type t)
4524 {
4525 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4526 
4527 	switch (prog_type) {
4528 	/* Program types only with direct read access go here! */
4529 	case BPF_PROG_TYPE_LWT_IN:
4530 	case BPF_PROG_TYPE_LWT_OUT:
4531 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4532 	case BPF_PROG_TYPE_SK_REUSEPORT:
4533 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4534 	case BPF_PROG_TYPE_CGROUP_SKB:
4535 		if (t == BPF_WRITE)
4536 			return false;
4537 		fallthrough;
4538 
4539 	/* Program types with direct read + write access go here! */
4540 	case BPF_PROG_TYPE_SCHED_CLS:
4541 	case BPF_PROG_TYPE_SCHED_ACT:
4542 	case BPF_PROG_TYPE_XDP:
4543 	case BPF_PROG_TYPE_LWT_XMIT:
4544 	case BPF_PROG_TYPE_SK_SKB:
4545 	case BPF_PROG_TYPE_SK_MSG:
4546 		if (meta)
4547 			return meta->pkt_access;
4548 
4549 		env->seen_direct_write = true;
4550 		return true;
4551 
4552 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4553 		if (t == BPF_WRITE)
4554 			env->seen_direct_write = true;
4555 
4556 		return true;
4557 
4558 	default:
4559 		return false;
4560 	}
4561 }
4562 
4563 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4564 			       int size, bool zero_size_allowed)
4565 {
4566 	struct bpf_reg_state *regs = cur_regs(env);
4567 	struct bpf_reg_state *reg = &regs[regno];
4568 	int err;
4569 
4570 	/* We may have added a variable offset to the packet pointer; but any
4571 	 * reg->range we have comes after that.  We are only checking the fixed
4572 	 * offset.
4573 	 */
4574 
4575 	/* We don't allow negative numbers, because we aren't tracking enough
4576 	 * detail to prove they're safe.
4577 	 */
4578 	if (reg->smin_value < 0) {
4579 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4580 			regno);
4581 		return -EACCES;
4582 	}
4583 
4584 	err = reg->range < 0 ? -EINVAL :
4585 	      __check_mem_access(env, regno, off, size, reg->range,
4586 				 zero_size_allowed);
4587 	if (err) {
4588 		verbose(env, "R%d offset is outside of the packet\n", regno);
4589 		return err;
4590 	}
4591 
4592 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4593 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4594 	 * otherwise find_good_pkt_pointers would have refused to set range info
4595 	 * that __check_mem_access would have rejected this pkt access.
4596 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4597 	 */
4598 	env->prog->aux->max_pkt_offset =
4599 		max_t(u32, env->prog->aux->max_pkt_offset,
4600 		      off + reg->umax_value + size - 1);
4601 
4602 	return err;
4603 }
4604 
4605 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4606 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4607 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4608 			    struct btf **btf, u32 *btf_id)
4609 {
4610 	struct bpf_insn_access_aux info = {
4611 		.reg_type = *reg_type,
4612 		.log = &env->log,
4613 	};
4614 
4615 	if (env->ops->is_valid_access &&
4616 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4617 		/* A non zero info.ctx_field_size indicates that this field is a
4618 		 * candidate for later verifier transformation to load the whole
4619 		 * field and then apply a mask when accessed with a narrower
4620 		 * access than actual ctx access size. A zero info.ctx_field_size
4621 		 * will only allow for whole field access and rejects any other
4622 		 * type of narrower access.
4623 		 */
4624 		*reg_type = info.reg_type;
4625 
4626 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4627 			*btf = info.btf;
4628 			*btf_id = info.btf_id;
4629 		} else {
4630 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4631 		}
4632 		/* remember the offset of last byte accessed in ctx */
4633 		if (env->prog->aux->max_ctx_offset < off + size)
4634 			env->prog->aux->max_ctx_offset = off + size;
4635 		return 0;
4636 	}
4637 
4638 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4639 	return -EACCES;
4640 }
4641 
4642 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4643 				  int size)
4644 {
4645 	if (size < 0 || off < 0 ||
4646 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4647 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4648 			off, size);
4649 		return -EACCES;
4650 	}
4651 	return 0;
4652 }
4653 
4654 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4655 			     u32 regno, int off, int size,
4656 			     enum bpf_access_type t)
4657 {
4658 	struct bpf_reg_state *regs = cur_regs(env);
4659 	struct bpf_reg_state *reg = &regs[regno];
4660 	struct bpf_insn_access_aux info = {};
4661 	bool valid;
4662 
4663 	if (reg->smin_value < 0) {
4664 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4665 			regno);
4666 		return -EACCES;
4667 	}
4668 
4669 	switch (reg->type) {
4670 	case PTR_TO_SOCK_COMMON:
4671 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4672 		break;
4673 	case PTR_TO_SOCKET:
4674 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4675 		break;
4676 	case PTR_TO_TCP_SOCK:
4677 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4678 		break;
4679 	case PTR_TO_XDP_SOCK:
4680 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4681 		break;
4682 	default:
4683 		valid = false;
4684 	}
4685 
4686 
4687 	if (valid) {
4688 		env->insn_aux_data[insn_idx].ctx_field_size =
4689 			info.ctx_field_size;
4690 		return 0;
4691 	}
4692 
4693 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4694 		regno, reg_type_str(env, reg->type), off, size);
4695 
4696 	return -EACCES;
4697 }
4698 
4699 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4700 {
4701 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4702 }
4703 
4704 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4705 {
4706 	const struct bpf_reg_state *reg = reg_state(env, regno);
4707 
4708 	return reg->type == PTR_TO_CTX;
4709 }
4710 
4711 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4712 {
4713 	const struct bpf_reg_state *reg = reg_state(env, regno);
4714 
4715 	return type_is_sk_pointer(reg->type);
4716 }
4717 
4718 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4719 {
4720 	const struct bpf_reg_state *reg = reg_state(env, regno);
4721 
4722 	return type_is_pkt_pointer(reg->type);
4723 }
4724 
4725 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4726 {
4727 	const struct bpf_reg_state *reg = reg_state(env, regno);
4728 
4729 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4730 	return reg->type == PTR_TO_FLOW_KEYS;
4731 }
4732 
4733 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4734 {
4735 	/* A referenced register is always trusted. */
4736 	if (reg->ref_obj_id)
4737 		return true;
4738 
4739 	/* If a register is not referenced, it is trusted if it has the
4740 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4741 	 * other type modifiers may be safe, but we elect to take an opt-in
4742 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4743 	 * not.
4744 	 *
4745 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4746 	 * for whether a register is trusted.
4747 	 */
4748 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4749 	       !bpf_type_has_unsafe_modifiers(reg->type);
4750 }
4751 
4752 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4753 {
4754 	return reg->type & MEM_RCU;
4755 }
4756 
4757 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4758 				   const struct bpf_reg_state *reg,
4759 				   int off, int size, bool strict)
4760 {
4761 	struct tnum reg_off;
4762 	int ip_align;
4763 
4764 	/* Byte size accesses are always allowed. */
4765 	if (!strict || size == 1)
4766 		return 0;
4767 
4768 	/* For platforms that do not have a Kconfig enabling
4769 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4770 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4771 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4772 	 * to this code only in strict mode where we want to emulate
4773 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4774 	 * unconditional IP align value of '2'.
4775 	 */
4776 	ip_align = 2;
4777 
4778 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4779 	if (!tnum_is_aligned(reg_off, size)) {
4780 		char tn_buf[48];
4781 
4782 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4783 		verbose(env,
4784 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4785 			ip_align, tn_buf, reg->off, off, size);
4786 		return -EACCES;
4787 	}
4788 
4789 	return 0;
4790 }
4791 
4792 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4793 				       const struct bpf_reg_state *reg,
4794 				       const char *pointer_desc,
4795 				       int off, int size, bool strict)
4796 {
4797 	struct tnum reg_off;
4798 
4799 	/* Byte size accesses are always allowed. */
4800 	if (!strict || size == 1)
4801 		return 0;
4802 
4803 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4804 	if (!tnum_is_aligned(reg_off, size)) {
4805 		char tn_buf[48];
4806 
4807 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4808 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4809 			pointer_desc, tn_buf, reg->off, off, size);
4810 		return -EACCES;
4811 	}
4812 
4813 	return 0;
4814 }
4815 
4816 static int check_ptr_alignment(struct bpf_verifier_env *env,
4817 			       const struct bpf_reg_state *reg, int off,
4818 			       int size, bool strict_alignment_once)
4819 {
4820 	bool strict = env->strict_alignment || strict_alignment_once;
4821 	const char *pointer_desc = "";
4822 
4823 	switch (reg->type) {
4824 	case PTR_TO_PACKET:
4825 	case PTR_TO_PACKET_META:
4826 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4827 		 * right in front, treat it the very same way.
4828 		 */
4829 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4830 	case PTR_TO_FLOW_KEYS:
4831 		pointer_desc = "flow keys ";
4832 		break;
4833 	case PTR_TO_MAP_KEY:
4834 		pointer_desc = "key ";
4835 		break;
4836 	case PTR_TO_MAP_VALUE:
4837 		pointer_desc = "value ";
4838 		break;
4839 	case PTR_TO_CTX:
4840 		pointer_desc = "context ";
4841 		break;
4842 	case PTR_TO_STACK:
4843 		pointer_desc = "stack ";
4844 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4845 		 * and check_stack_read_fixed_off() relies on stack accesses being
4846 		 * aligned.
4847 		 */
4848 		strict = true;
4849 		break;
4850 	case PTR_TO_SOCKET:
4851 		pointer_desc = "sock ";
4852 		break;
4853 	case PTR_TO_SOCK_COMMON:
4854 		pointer_desc = "sock_common ";
4855 		break;
4856 	case PTR_TO_TCP_SOCK:
4857 		pointer_desc = "tcp_sock ";
4858 		break;
4859 	case PTR_TO_XDP_SOCK:
4860 		pointer_desc = "xdp_sock ";
4861 		break;
4862 	default:
4863 		break;
4864 	}
4865 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4866 					   strict);
4867 }
4868 
4869 static int update_stack_depth(struct bpf_verifier_env *env,
4870 			      const struct bpf_func_state *func,
4871 			      int off)
4872 {
4873 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4874 
4875 	if (stack >= -off)
4876 		return 0;
4877 
4878 	/* update known max for given subprogram */
4879 	env->subprog_info[func->subprogno].stack_depth = -off;
4880 	return 0;
4881 }
4882 
4883 /* starting from main bpf function walk all instructions of the function
4884  * and recursively walk all callees that given function can call.
4885  * Ignore jump and exit insns.
4886  * Since recursion is prevented by check_cfg() this algorithm
4887  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4888  */
4889 static int check_max_stack_depth(struct bpf_verifier_env *env)
4890 {
4891 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4892 	struct bpf_subprog_info *subprog = env->subprog_info;
4893 	struct bpf_insn *insn = env->prog->insnsi;
4894 	bool tail_call_reachable = false;
4895 	int ret_insn[MAX_CALL_FRAMES];
4896 	int ret_prog[MAX_CALL_FRAMES];
4897 	int j;
4898 
4899 process_func:
4900 	/* protect against potential stack overflow that might happen when
4901 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4902 	 * depth for such case down to 256 so that the worst case scenario
4903 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4904 	 * 8k).
4905 	 *
4906 	 * To get the idea what might happen, see an example:
4907 	 * func1 -> sub rsp, 128
4908 	 *  subfunc1 -> sub rsp, 256
4909 	 *  tailcall1 -> add rsp, 256
4910 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4911 	 *   subfunc2 -> sub rsp, 64
4912 	 *   subfunc22 -> sub rsp, 128
4913 	 *   tailcall2 -> add rsp, 128
4914 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4915 	 *
4916 	 * tailcall will unwind the current stack frame but it will not get rid
4917 	 * of caller's stack as shown on the example above.
4918 	 */
4919 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4920 		verbose(env,
4921 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4922 			depth);
4923 		return -EACCES;
4924 	}
4925 	/* round up to 32-bytes, since this is granularity
4926 	 * of interpreter stack size
4927 	 */
4928 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4929 	if (depth > MAX_BPF_STACK) {
4930 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4931 			frame + 1, depth);
4932 		return -EACCES;
4933 	}
4934 continue_func:
4935 	subprog_end = subprog[idx + 1].start;
4936 	for (; i < subprog_end; i++) {
4937 		int next_insn;
4938 
4939 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4940 			continue;
4941 		/* remember insn and function to return to */
4942 		ret_insn[frame] = i + 1;
4943 		ret_prog[frame] = idx;
4944 
4945 		/* find the callee */
4946 		next_insn = i + insn[i].imm + 1;
4947 		idx = find_subprog(env, next_insn);
4948 		if (idx < 0) {
4949 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4950 				  next_insn);
4951 			return -EFAULT;
4952 		}
4953 		if (subprog[idx].is_async_cb) {
4954 			if (subprog[idx].has_tail_call) {
4955 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4956 				return -EFAULT;
4957 			}
4958 			 /* async callbacks don't increase bpf prog stack size */
4959 			continue;
4960 		}
4961 		i = next_insn;
4962 
4963 		if (subprog[idx].has_tail_call)
4964 			tail_call_reachable = true;
4965 
4966 		frame++;
4967 		if (frame >= MAX_CALL_FRAMES) {
4968 			verbose(env, "the call stack of %d frames is too deep !\n",
4969 				frame);
4970 			return -E2BIG;
4971 		}
4972 		goto process_func;
4973 	}
4974 	/* if tail call got detected across bpf2bpf calls then mark each of the
4975 	 * currently present subprog frames as tail call reachable subprogs;
4976 	 * this info will be utilized by JIT so that we will be preserving the
4977 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4978 	 */
4979 	if (tail_call_reachable)
4980 		for (j = 0; j < frame; j++)
4981 			subprog[ret_prog[j]].tail_call_reachable = true;
4982 	if (subprog[0].tail_call_reachable)
4983 		env->prog->aux->tail_call_reachable = true;
4984 
4985 	/* end of for() loop means the last insn of the 'subprog'
4986 	 * was reached. Doesn't matter whether it was JA or EXIT
4987 	 */
4988 	if (frame == 0)
4989 		return 0;
4990 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4991 	frame--;
4992 	i = ret_insn[frame];
4993 	idx = ret_prog[frame];
4994 	goto continue_func;
4995 }
4996 
4997 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4998 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4999 				  const struct bpf_insn *insn, int idx)
5000 {
5001 	int start = idx + insn->imm + 1, subprog;
5002 
5003 	subprog = find_subprog(env, start);
5004 	if (subprog < 0) {
5005 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5006 			  start);
5007 		return -EFAULT;
5008 	}
5009 	return env->subprog_info[subprog].stack_depth;
5010 }
5011 #endif
5012 
5013 static int __check_buffer_access(struct bpf_verifier_env *env,
5014 				 const char *buf_info,
5015 				 const struct bpf_reg_state *reg,
5016 				 int regno, int off, int size)
5017 {
5018 	if (off < 0) {
5019 		verbose(env,
5020 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5021 			regno, buf_info, off, size);
5022 		return -EACCES;
5023 	}
5024 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5025 		char tn_buf[48];
5026 
5027 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5028 		verbose(env,
5029 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5030 			regno, off, tn_buf);
5031 		return -EACCES;
5032 	}
5033 
5034 	return 0;
5035 }
5036 
5037 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5038 				  const struct bpf_reg_state *reg,
5039 				  int regno, int off, int size)
5040 {
5041 	int err;
5042 
5043 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5044 	if (err)
5045 		return err;
5046 
5047 	if (off + size > env->prog->aux->max_tp_access)
5048 		env->prog->aux->max_tp_access = off + size;
5049 
5050 	return 0;
5051 }
5052 
5053 static int check_buffer_access(struct bpf_verifier_env *env,
5054 			       const struct bpf_reg_state *reg,
5055 			       int regno, int off, int size,
5056 			       bool zero_size_allowed,
5057 			       u32 *max_access)
5058 {
5059 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5060 	int err;
5061 
5062 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5063 	if (err)
5064 		return err;
5065 
5066 	if (off + size > *max_access)
5067 		*max_access = off + size;
5068 
5069 	return 0;
5070 }
5071 
5072 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5073 static void zext_32_to_64(struct bpf_reg_state *reg)
5074 {
5075 	reg->var_off = tnum_subreg(reg->var_off);
5076 	__reg_assign_32_into_64(reg);
5077 }
5078 
5079 /* truncate register to smaller size (in bytes)
5080  * must be called with size < BPF_REG_SIZE
5081  */
5082 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5083 {
5084 	u64 mask;
5085 
5086 	/* clear high bits in bit representation */
5087 	reg->var_off = tnum_cast(reg->var_off, size);
5088 
5089 	/* fix arithmetic bounds */
5090 	mask = ((u64)1 << (size * 8)) - 1;
5091 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5092 		reg->umin_value &= mask;
5093 		reg->umax_value &= mask;
5094 	} else {
5095 		reg->umin_value = 0;
5096 		reg->umax_value = mask;
5097 	}
5098 	reg->smin_value = reg->umin_value;
5099 	reg->smax_value = reg->umax_value;
5100 
5101 	/* If size is smaller than 32bit register the 32bit register
5102 	 * values are also truncated so we push 64-bit bounds into
5103 	 * 32-bit bounds. Above were truncated < 32-bits already.
5104 	 */
5105 	if (size >= 4)
5106 		return;
5107 	__reg_combine_64_into_32(reg);
5108 }
5109 
5110 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5111 {
5112 	/* A map is considered read-only if the following condition are true:
5113 	 *
5114 	 * 1) BPF program side cannot change any of the map content. The
5115 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5116 	 *    and was set at map creation time.
5117 	 * 2) The map value(s) have been initialized from user space by a
5118 	 *    loader and then "frozen", such that no new map update/delete
5119 	 *    operations from syscall side are possible for the rest of
5120 	 *    the map's lifetime from that point onwards.
5121 	 * 3) Any parallel/pending map update/delete operations from syscall
5122 	 *    side have been completed. Only after that point, it's safe to
5123 	 *    assume that map value(s) are immutable.
5124 	 */
5125 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5126 	       READ_ONCE(map->frozen) &&
5127 	       !bpf_map_write_active(map);
5128 }
5129 
5130 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5131 {
5132 	void *ptr;
5133 	u64 addr;
5134 	int err;
5135 
5136 	err = map->ops->map_direct_value_addr(map, &addr, off);
5137 	if (err)
5138 		return err;
5139 	ptr = (void *)(long)addr + off;
5140 
5141 	switch (size) {
5142 	case sizeof(u8):
5143 		*val = (u64)*(u8 *)ptr;
5144 		break;
5145 	case sizeof(u16):
5146 		*val = (u64)*(u16 *)ptr;
5147 		break;
5148 	case sizeof(u32):
5149 		*val = (u64)*(u32 *)ptr;
5150 		break;
5151 	case sizeof(u64):
5152 		*val = *(u64 *)ptr;
5153 		break;
5154 	default:
5155 		return -EINVAL;
5156 	}
5157 	return 0;
5158 }
5159 
5160 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5161 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5162 
5163 /*
5164  * Allow list few fields as RCU trusted or full trusted.
5165  * This logic doesn't allow mix tagging and will be removed once GCC supports
5166  * btf_type_tag.
5167  */
5168 
5169 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5170 BTF_TYPE_SAFE_RCU(struct task_struct) {
5171 	const cpumask_t *cpus_ptr;
5172 	struct css_set __rcu *cgroups;
5173 	struct task_struct __rcu *real_parent;
5174 	struct task_struct *group_leader;
5175 };
5176 
5177 BTF_TYPE_SAFE_RCU(struct css_set) {
5178 	struct cgroup *dfl_cgrp;
5179 };
5180 
5181 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5182 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5183 	__bpf_md_ptr(struct seq_file *, seq);
5184 };
5185 
5186 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5187 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
5188 	__bpf_md_ptr(struct task_struct *, task);
5189 };
5190 
5191 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5192 	struct file *file;
5193 };
5194 
5195 BTF_TYPE_SAFE_TRUSTED(struct file) {
5196 	struct inode *f_inode;
5197 };
5198 
5199 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5200 	/* no negative dentry-s in places where bpf can see it */
5201 	struct inode *d_inode;
5202 };
5203 
5204 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5205 	struct sock *sk;
5206 };
5207 
5208 static bool type_is_rcu(struct bpf_verifier_env *env,
5209 			struct bpf_reg_state *reg,
5210 			int off)
5211 {
5212 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5213 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5214 
5215 	return btf_nested_type_is_trusted(&env->log, reg, off, "__safe_rcu");
5216 }
5217 
5218 static bool type_is_trusted(struct bpf_verifier_env *env,
5219 			    struct bpf_reg_state *reg,
5220 			    int off)
5221 {
5222 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5223 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5224 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5225 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5226 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5227 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5228 
5229 	return btf_nested_type_is_trusted(&env->log, reg, off, "__safe_trusted");
5230 }
5231 
5232 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5233 				   struct bpf_reg_state *regs,
5234 				   int regno, int off, int size,
5235 				   enum bpf_access_type atype,
5236 				   int value_regno)
5237 {
5238 	struct bpf_reg_state *reg = regs + regno;
5239 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5240 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5241 	enum bpf_type_flag flag = 0;
5242 	u32 btf_id;
5243 	int ret;
5244 
5245 	if (!env->allow_ptr_leaks) {
5246 		verbose(env,
5247 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5248 			tname);
5249 		return -EPERM;
5250 	}
5251 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5252 		verbose(env,
5253 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5254 			tname);
5255 		return -EINVAL;
5256 	}
5257 	if (off < 0) {
5258 		verbose(env,
5259 			"R%d is ptr_%s invalid negative access: off=%d\n",
5260 			regno, tname, off);
5261 		return -EACCES;
5262 	}
5263 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5264 		char tn_buf[48];
5265 
5266 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5267 		verbose(env,
5268 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5269 			regno, tname, off, tn_buf);
5270 		return -EACCES;
5271 	}
5272 
5273 	if (reg->type & MEM_USER) {
5274 		verbose(env,
5275 			"R%d is ptr_%s access user memory: off=%d\n",
5276 			regno, tname, off);
5277 		return -EACCES;
5278 	}
5279 
5280 	if (reg->type & MEM_PERCPU) {
5281 		verbose(env,
5282 			"R%d is ptr_%s access percpu memory: off=%d\n",
5283 			regno, tname, off);
5284 		return -EACCES;
5285 	}
5286 
5287 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5288 		if (!btf_is_kernel(reg->btf)) {
5289 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5290 			return -EFAULT;
5291 		}
5292 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5293 	} else {
5294 		/* Writes are permitted with default btf_struct_access for
5295 		 * program allocated objects (which always have ref_obj_id > 0),
5296 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5297 		 */
5298 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5299 			verbose(env, "only read is supported\n");
5300 			return -EACCES;
5301 		}
5302 
5303 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5304 		    !reg->ref_obj_id) {
5305 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5306 			return -EFAULT;
5307 		}
5308 
5309 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5310 	}
5311 
5312 	if (ret < 0)
5313 		return ret;
5314 
5315 	if (ret != PTR_TO_BTF_ID) {
5316 		/* just mark; */
5317 
5318 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5319 		/* If this is an untrusted pointer, all pointers formed by walking it
5320 		 * also inherit the untrusted flag.
5321 		 */
5322 		flag = PTR_UNTRUSTED;
5323 
5324 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5325 		/* By default any pointer obtained from walking a trusted pointer is no
5326 		 * longer trusted, unless the field being accessed has explicitly been
5327 		 * marked as inheriting its parent's state of trust (either full or RCU).
5328 		 * For example:
5329 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
5330 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
5331 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5332 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5333 		 *
5334 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
5335 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
5336 		 */
5337 		if (type_is_trusted(env, reg, off)) {
5338 			flag |= PTR_TRUSTED;
5339 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5340 			if (type_is_rcu(env, reg, off)) {
5341 				/* ignore __rcu tag and mark it MEM_RCU */
5342 				flag |= MEM_RCU;
5343 			} else if (flag & MEM_RCU) {
5344 				/* __rcu tagged pointers can be NULL */
5345 				flag |= PTR_MAYBE_NULL;
5346 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
5347 				/* keep as-is */
5348 			} else {
5349 				/* walking unknown pointers yields untrusted pointer */
5350 				flag = PTR_UNTRUSTED;
5351 			}
5352 		} else {
5353 			/*
5354 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
5355 			 * aggressively mark as untrusted otherwise such
5356 			 * pointers will be plain PTR_TO_BTF_ID without flags
5357 			 * and will be allowed to be passed into helpers for
5358 			 * compat reasons.
5359 			 */
5360 			flag = PTR_UNTRUSTED;
5361 		}
5362 	} else {
5363 		/* Old compat. Deprecated */
5364 		flag &= ~PTR_TRUSTED;
5365 	}
5366 
5367 	if (atype == BPF_READ && value_regno >= 0)
5368 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5369 
5370 	return 0;
5371 }
5372 
5373 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5374 				   struct bpf_reg_state *regs,
5375 				   int regno, int off, int size,
5376 				   enum bpf_access_type atype,
5377 				   int value_regno)
5378 {
5379 	struct bpf_reg_state *reg = regs + regno;
5380 	struct bpf_map *map = reg->map_ptr;
5381 	struct bpf_reg_state map_reg;
5382 	enum bpf_type_flag flag = 0;
5383 	const struct btf_type *t;
5384 	const char *tname;
5385 	u32 btf_id;
5386 	int ret;
5387 
5388 	if (!btf_vmlinux) {
5389 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5390 		return -ENOTSUPP;
5391 	}
5392 
5393 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5394 		verbose(env, "map_ptr access not supported for map type %d\n",
5395 			map->map_type);
5396 		return -ENOTSUPP;
5397 	}
5398 
5399 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5400 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5401 
5402 	if (!env->allow_ptr_leaks) {
5403 		verbose(env,
5404 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5405 			tname);
5406 		return -EPERM;
5407 	}
5408 
5409 	if (off < 0) {
5410 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
5411 			regno, tname, off);
5412 		return -EACCES;
5413 	}
5414 
5415 	if (atype != BPF_READ) {
5416 		verbose(env, "only read from %s is supported\n", tname);
5417 		return -EACCES;
5418 	}
5419 
5420 	/* Simulate access to a PTR_TO_BTF_ID */
5421 	memset(&map_reg, 0, sizeof(map_reg));
5422 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5423 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5424 	if (ret < 0)
5425 		return ret;
5426 
5427 	if (value_regno >= 0)
5428 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5429 
5430 	return 0;
5431 }
5432 
5433 /* Check that the stack access at the given offset is within bounds. The
5434  * maximum valid offset is -1.
5435  *
5436  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5437  * -state->allocated_stack for reads.
5438  */
5439 static int check_stack_slot_within_bounds(int off,
5440 					  struct bpf_func_state *state,
5441 					  enum bpf_access_type t)
5442 {
5443 	int min_valid_off;
5444 
5445 	if (t == BPF_WRITE)
5446 		min_valid_off = -MAX_BPF_STACK;
5447 	else
5448 		min_valid_off = -state->allocated_stack;
5449 
5450 	if (off < min_valid_off || off > -1)
5451 		return -EACCES;
5452 	return 0;
5453 }
5454 
5455 /* Check that the stack access at 'regno + off' falls within the maximum stack
5456  * bounds.
5457  *
5458  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5459  */
5460 static int check_stack_access_within_bounds(
5461 		struct bpf_verifier_env *env,
5462 		int regno, int off, int access_size,
5463 		enum bpf_access_src src, enum bpf_access_type type)
5464 {
5465 	struct bpf_reg_state *regs = cur_regs(env);
5466 	struct bpf_reg_state *reg = regs + regno;
5467 	struct bpf_func_state *state = func(env, reg);
5468 	int min_off, max_off;
5469 	int err;
5470 	char *err_extra;
5471 
5472 	if (src == ACCESS_HELPER)
5473 		/* We don't know if helpers are reading or writing (or both). */
5474 		err_extra = " indirect access to";
5475 	else if (type == BPF_READ)
5476 		err_extra = " read from";
5477 	else
5478 		err_extra = " write to";
5479 
5480 	if (tnum_is_const(reg->var_off)) {
5481 		min_off = reg->var_off.value + off;
5482 		if (access_size > 0)
5483 			max_off = min_off + access_size - 1;
5484 		else
5485 			max_off = min_off;
5486 	} else {
5487 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5488 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
5489 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5490 				err_extra, regno);
5491 			return -EACCES;
5492 		}
5493 		min_off = reg->smin_value + off;
5494 		if (access_size > 0)
5495 			max_off = reg->smax_value + off + access_size - 1;
5496 		else
5497 			max_off = min_off;
5498 	}
5499 
5500 	err = check_stack_slot_within_bounds(min_off, state, type);
5501 	if (!err)
5502 		err = check_stack_slot_within_bounds(max_off, state, type);
5503 
5504 	if (err) {
5505 		if (tnum_is_const(reg->var_off)) {
5506 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5507 				err_extra, regno, off, access_size);
5508 		} else {
5509 			char tn_buf[48];
5510 
5511 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5512 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5513 				err_extra, regno, tn_buf, access_size);
5514 		}
5515 	}
5516 	return err;
5517 }
5518 
5519 /* check whether memory at (regno + off) is accessible for t = (read | write)
5520  * if t==write, value_regno is a register which value is stored into memory
5521  * if t==read, value_regno is a register which will receive the value from memory
5522  * if t==write && value_regno==-1, some unknown value is stored into memory
5523  * if t==read && value_regno==-1, don't care what we read from memory
5524  */
5525 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5526 			    int off, int bpf_size, enum bpf_access_type t,
5527 			    int value_regno, bool strict_alignment_once)
5528 {
5529 	struct bpf_reg_state *regs = cur_regs(env);
5530 	struct bpf_reg_state *reg = regs + regno;
5531 	struct bpf_func_state *state;
5532 	int size, err = 0;
5533 
5534 	size = bpf_size_to_bytes(bpf_size);
5535 	if (size < 0)
5536 		return size;
5537 
5538 	/* alignment checks will add in reg->off themselves */
5539 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5540 	if (err)
5541 		return err;
5542 
5543 	/* for access checks, reg->off is just part of off */
5544 	off += reg->off;
5545 
5546 	if (reg->type == PTR_TO_MAP_KEY) {
5547 		if (t == BPF_WRITE) {
5548 			verbose(env, "write to change key R%d not allowed\n", regno);
5549 			return -EACCES;
5550 		}
5551 
5552 		err = check_mem_region_access(env, regno, off, size,
5553 					      reg->map_ptr->key_size, false);
5554 		if (err)
5555 			return err;
5556 		if (value_regno >= 0)
5557 			mark_reg_unknown(env, regs, value_regno);
5558 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5559 		struct btf_field *kptr_field = NULL;
5560 
5561 		if (t == BPF_WRITE && value_regno >= 0 &&
5562 		    is_pointer_value(env, value_regno)) {
5563 			verbose(env, "R%d leaks addr into map\n", value_regno);
5564 			return -EACCES;
5565 		}
5566 		err = check_map_access_type(env, regno, off, size, t);
5567 		if (err)
5568 			return err;
5569 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5570 		if (err)
5571 			return err;
5572 		if (tnum_is_const(reg->var_off))
5573 			kptr_field = btf_record_find(reg->map_ptr->record,
5574 						     off + reg->var_off.value, BPF_KPTR);
5575 		if (kptr_field) {
5576 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5577 		} else if (t == BPF_READ && value_regno >= 0) {
5578 			struct bpf_map *map = reg->map_ptr;
5579 
5580 			/* if map is read-only, track its contents as scalars */
5581 			if (tnum_is_const(reg->var_off) &&
5582 			    bpf_map_is_rdonly(map) &&
5583 			    map->ops->map_direct_value_addr) {
5584 				int map_off = off + reg->var_off.value;
5585 				u64 val = 0;
5586 
5587 				err = bpf_map_direct_read(map, map_off, size,
5588 							  &val);
5589 				if (err)
5590 					return err;
5591 
5592 				regs[value_regno].type = SCALAR_VALUE;
5593 				__mark_reg_known(&regs[value_regno], val);
5594 			} else {
5595 				mark_reg_unknown(env, regs, value_regno);
5596 			}
5597 		}
5598 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5599 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5600 
5601 		if (type_may_be_null(reg->type)) {
5602 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5603 				reg_type_str(env, reg->type));
5604 			return -EACCES;
5605 		}
5606 
5607 		if (t == BPF_WRITE && rdonly_mem) {
5608 			verbose(env, "R%d cannot write into %s\n",
5609 				regno, reg_type_str(env, reg->type));
5610 			return -EACCES;
5611 		}
5612 
5613 		if (t == BPF_WRITE && value_regno >= 0 &&
5614 		    is_pointer_value(env, value_regno)) {
5615 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5616 			return -EACCES;
5617 		}
5618 
5619 		err = check_mem_region_access(env, regno, off, size,
5620 					      reg->mem_size, false);
5621 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5622 			mark_reg_unknown(env, regs, value_regno);
5623 	} else if (reg->type == PTR_TO_CTX) {
5624 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5625 		struct btf *btf = NULL;
5626 		u32 btf_id = 0;
5627 
5628 		if (t == BPF_WRITE && value_regno >= 0 &&
5629 		    is_pointer_value(env, value_regno)) {
5630 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5631 			return -EACCES;
5632 		}
5633 
5634 		err = check_ptr_off_reg(env, reg, regno);
5635 		if (err < 0)
5636 			return err;
5637 
5638 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5639 				       &btf_id);
5640 		if (err)
5641 			verbose_linfo(env, insn_idx, "; ");
5642 		if (!err && t == BPF_READ && value_regno >= 0) {
5643 			/* ctx access returns either a scalar, or a
5644 			 * PTR_TO_PACKET[_META,_END]. In the latter
5645 			 * case, we know the offset is zero.
5646 			 */
5647 			if (reg_type == SCALAR_VALUE) {
5648 				mark_reg_unknown(env, regs, value_regno);
5649 			} else {
5650 				mark_reg_known_zero(env, regs,
5651 						    value_regno);
5652 				if (type_may_be_null(reg_type))
5653 					regs[value_regno].id = ++env->id_gen;
5654 				/* A load of ctx field could have different
5655 				 * actual load size with the one encoded in the
5656 				 * insn. When the dst is PTR, it is for sure not
5657 				 * a sub-register.
5658 				 */
5659 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5660 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5661 					regs[value_regno].btf = btf;
5662 					regs[value_regno].btf_id = btf_id;
5663 				}
5664 			}
5665 			regs[value_regno].type = reg_type;
5666 		}
5667 
5668 	} else if (reg->type == PTR_TO_STACK) {
5669 		/* Basic bounds checks. */
5670 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5671 		if (err)
5672 			return err;
5673 
5674 		state = func(env, reg);
5675 		err = update_stack_depth(env, state, off);
5676 		if (err)
5677 			return err;
5678 
5679 		if (t == BPF_READ)
5680 			err = check_stack_read(env, regno, off, size,
5681 					       value_regno);
5682 		else
5683 			err = check_stack_write(env, regno, off, size,
5684 						value_regno, insn_idx);
5685 	} else if (reg_is_pkt_pointer(reg)) {
5686 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5687 			verbose(env, "cannot write into packet\n");
5688 			return -EACCES;
5689 		}
5690 		if (t == BPF_WRITE && value_regno >= 0 &&
5691 		    is_pointer_value(env, value_regno)) {
5692 			verbose(env, "R%d leaks addr into packet\n",
5693 				value_regno);
5694 			return -EACCES;
5695 		}
5696 		err = check_packet_access(env, regno, off, size, false);
5697 		if (!err && t == BPF_READ && value_regno >= 0)
5698 			mark_reg_unknown(env, regs, value_regno);
5699 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5700 		if (t == BPF_WRITE && value_regno >= 0 &&
5701 		    is_pointer_value(env, value_regno)) {
5702 			verbose(env, "R%d leaks addr into flow keys\n",
5703 				value_regno);
5704 			return -EACCES;
5705 		}
5706 
5707 		err = check_flow_keys_access(env, off, size);
5708 		if (!err && t == BPF_READ && value_regno >= 0)
5709 			mark_reg_unknown(env, regs, value_regno);
5710 	} else if (type_is_sk_pointer(reg->type)) {
5711 		if (t == BPF_WRITE) {
5712 			verbose(env, "R%d cannot write into %s\n",
5713 				regno, reg_type_str(env, reg->type));
5714 			return -EACCES;
5715 		}
5716 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5717 		if (!err && value_regno >= 0)
5718 			mark_reg_unknown(env, regs, value_regno);
5719 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5720 		err = check_tp_buffer_access(env, reg, regno, off, size);
5721 		if (!err && t == BPF_READ && value_regno >= 0)
5722 			mark_reg_unknown(env, regs, value_regno);
5723 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5724 		   !type_may_be_null(reg->type)) {
5725 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5726 					      value_regno);
5727 	} else if (reg->type == CONST_PTR_TO_MAP) {
5728 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5729 					      value_regno);
5730 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5731 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5732 		u32 *max_access;
5733 
5734 		if (rdonly_mem) {
5735 			if (t == BPF_WRITE) {
5736 				verbose(env, "R%d cannot write into %s\n",
5737 					regno, reg_type_str(env, reg->type));
5738 				return -EACCES;
5739 			}
5740 			max_access = &env->prog->aux->max_rdonly_access;
5741 		} else {
5742 			max_access = &env->prog->aux->max_rdwr_access;
5743 		}
5744 
5745 		err = check_buffer_access(env, reg, regno, off, size, false,
5746 					  max_access);
5747 
5748 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5749 			mark_reg_unknown(env, regs, value_regno);
5750 	} else {
5751 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5752 			reg_type_str(env, reg->type));
5753 		return -EACCES;
5754 	}
5755 
5756 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5757 	    regs[value_regno].type == SCALAR_VALUE) {
5758 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5759 		coerce_reg_to_size(&regs[value_regno], size);
5760 	}
5761 	return err;
5762 }
5763 
5764 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5765 {
5766 	int load_reg;
5767 	int err;
5768 
5769 	switch (insn->imm) {
5770 	case BPF_ADD:
5771 	case BPF_ADD | BPF_FETCH:
5772 	case BPF_AND:
5773 	case BPF_AND | BPF_FETCH:
5774 	case BPF_OR:
5775 	case BPF_OR | BPF_FETCH:
5776 	case BPF_XOR:
5777 	case BPF_XOR | BPF_FETCH:
5778 	case BPF_XCHG:
5779 	case BPF_CMPXCHG:
5780 		break;
5781 	default:
5782 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5783 		return -EINVAL;
5784 	}
5785 
5786 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5787 		verbose(env, "invalid atomic operand size\n");
5788 		return -EINVAL;
5789 	}
5790 
5791 	/* check src1 operand */
5792 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5793 	if (err)
5794 		return err;
5795 
5796 	/* check src2 operand */
5797 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5798 	if (err)
5799 		return err;
5800 
5801 	if (insn->imm == BPF_CMPXCHG) {
5802 		/* Check comparison of R0 with memory location */
5803 		const u32 aux_reg = BPF_REG_0;
5804 
5805 		err = check_reg_arg(env, aux_reg, SRC_OP);
5806 		if (err)
5807 			return err;
5808 
5809 		if (is_pointer_value(env, aux_reg)) {
5810 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5811 			return -EACCES;
5812 		}
5813 	}
5814 
5815 	if (is_pointer_value(env, insn->src_reg)) {
5816 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5817 		return -EACCES;
5818 	}
5819 
5820 	if (is_ctx_reg(env, insn->dst_reg) ||
5821 	    is_pkt_reg(env, insn->dst_reg) ||
5822 	    is_flow_key_reg(env, insn->dst_reg) ||
5823 	    is_sk_reg(env, insn->dst_reg)) {
5824 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5825 			insn->dst_reg,
5826 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5827 		return -EACCES;
5828 	}
5829 
5830 	if (insn->imm & BPF_FETCH) {
5831 		if (insn->imm == BPF_CMPXCHG)
5832 			load_reg = BPF_REG_0;
5833 		else
5834 			load_reg = insn->src_reg;
5835 
5836 		/* check and record load of old value */
5837 		err = check_reg_arg(env, load_reg, DST_OP);
5838 		if (err)
5839 			return err;
5840 	} else {
5841 		/* This instruction accesses a memory location but doesn't
5842 		 * actually load it into a register.
5843 		 */
5844 		load_reg = -1;
5845 	}
5846 
5847 	/* Check whether we can read the memory, with second call for fetch
5848 	 * case to simulate the register fill.
5849 	 */
5850 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5851 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5852 	if (!err && load_reg >= 0)
5853 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5854 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5855 				       true);
5856 	if (err)
5857 		return err;
5858 
5859 	/* Check whether we can write into the same memory. */
5860 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5861 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5862 	if (err)
5863 		return err;
5864 
5865 	return 0;
5866 }
5867 
5868 /* When register 'regno' is used to read the stack (either directly or through
5869  * a helper function) make sure that it's within stack boundary and, depending
5870  * on the access type, that all elements of the stack are initialized.
5871  *
5872  * 'off' includes 'regno->off', but not its dynamic part (if any).
5873  *
5874  * All registers that have been spilled on the stack in the slots within the
5875  * read offsets are marked as read.
5876  */
5877 static int check_stack_range_initialized(
5878 		struct bpf_verifier_env *env, int regno, int off,
5879 		int access_size, bool zero_size_allowed,
5880 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5881 {
5882 	struct bpf_reg_state *reg = reg_state(env, regno);
5883 	struct bpf_func_state *state = func(env, reg);
5884 	int err, min_off, max_off, i, j, slot, spi;
5885 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5886 	enum bpf_access_type bounds_check_type;
5887 	/* Some accesses can write anything into the stack, others are
5888 	 * read-only.
5889 	 */
5890 	bool clobber = false;
5891 
5892 	if (access_size == 0 && !zero_size_allowed) {
5893 		verbose(env, "invalid zero-sized read\n");
5894 		return -EACCES;
5895 	}
5896 
5897 	if (type == ACCESS_HELPER) {
5898 		/* The bounds checks for writes are more permissive than for
5899 		 * reads. However, if raw_mode is not set, we'll do extra
5900 		 * checks below.
5901 		 */
5902 		bounds_check_type = BPF_WRITE;
5903 		clobber = true;
5904 	} else {
5905 		bounds_check_type = BPF_READ;
5906 	}
5907 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5908 					       type, bounds_check_type);
5909 	if (err)
5910 		return err;
5911 
5912 
5913 	if (tnum_is_const(reg->var_off)) {
5914 		min_off = max_off = reg->var_off.value + off;
5915 	} else {
5916 		/* Variable offset is prohibited for unprivileged mode for
5917 		 * simplicity since it requires corresponding support in
5918 		 * Spectre masking for stack ALU.
5919 		 * See also retrieve_ptr_limit().
5920 		 */
5921 		if (!env->bypass_spec_v1) {
5922 			char tn_buf[48];
5923 
5924 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5925 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5926 				regno, err_extra, tn_buf);
5927 			return -EACCES;
5928 		}
5929 		/* Only initialized buffer on stack is allowed to be accessed
5930 		 * with variable offset. With uninitialized buffer it's hard to
5931 		 * guarantee that whole memory is marked as initialized on
5932 		 * helper return since specific bounds are unknown what may
5933 		 * cause uninitialized stack leaking.
5934 		 */
5935 		if (meta && meta->raw_mode)
5936 			meta = NULL;
5937 
5938 		min_off = reg->smin_value + off;
5939 		max_off = reg->smax_value + off;
5940 	}
5941 
5942 	if (meta && meta->raw_mode) {
5943 		/* Ensure we won't be overwriting dynptrs when simulating byte
5944 		 * by byte access in check_helper_call using meta.access_size.
5945 		 * This would be a problem if we have a helper in the future
5946 		 * which takes:
5947 		 *
5948 		 *	helper(uninit_mem, len, dynptr)
5949 		 *
5950 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5951 		 * may end up writing to dynptr itself when touching memory from
5952 		 * arg 1. This can be relaxed on a case by case basis for known
5953 		 * safe cases, but reject due to the possibilitiy of aliasing by
5954 		 * default.
5955 		 */
5956 		for (i = min_off; i < max_off + access_size; i++) {
5957 			int stack_off = -i - 1;
5958 
5959 			spi = __get_spi(i);
5960 			/* raw_mode may write past allocated_stack */
5961 			if (state->allocated_stack <= stack_off)
5962 				continue;
5963 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5964 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5965 				return -EACCES;
5966 			}
5967 		}
5968 		meta->access_size = access_size;
5969 		meta->regno = regno;
5970 		return 0;
5971 	}
5972 
5973 	for (i = min_off; i < max_off + access_size; i++) {
5974 		u8 *stype;
5975 
5976 		slot = -i - 1;
5977 		spi = slot / BPF_REG_SIZE;
5978 		if (state->allocated_stack <= slot)
5979 			goto err;
5980 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5981 		if (*stype == STACK_MISC)
5982 			goto mark;
5983 		if ((*stype == STACK_ZERO) ||
5984 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
5985 			if (clobber) {
5986 				/* helper can write anything into the stack */
5987 				*stype = STACK_MISC;
5988 			}
5989 			goto mark;
5990 		}
5991 
5992 		if (is_spilled_reg(&state->stack[spi]) &&
5993 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5994 		     env->allow_ptr_leaks)) {
5995 			if (clobber) {
5996 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5997 				for (j = 0; j < BPF_REG_SIZE; j++)
5998 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5999 			}
6000 			goto mark;
6001 		}
6002 
6003 err:
6004 		if (tnum_is_const(reg->var_off)) {
6005 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6006 				err_extra, regno, min_off, i - min_off, access_size);
6007 		} else {
6008 			char tn_buf[48];
6009 
6010 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6011 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6012 				err_extra, regno, tn_buf, i - min_off, access_size);
6013 		}
6014 		return -EACCES;
6015 mark:
6016 		/* reading any byte out of 8-byte 'spill_slot' will cause
6017 		 * the whole slot to be marked as 'read'
6018 		 */
6019 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
6020 			      state->stack[spi].spilled_ptr.parent,
6021 			      REG_LIVE_READ64);
6022 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6023 		 * be sure that whether stack slot is written to or not. Hence,
6024 		 * we must still conservatively propagate reads upwards even if
6025 		 * helper may write to the entire memory range.
6026 		 */
6027 	}
6028 	return update_stack_depth(env, state, min_off);
6029 }
6030 
6031 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6032 				   int access_size, bool zero_size_allowed,
6033 				   struct bpf_call_arg_meta *meta)
6034 {
6035 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6036 	u32 *max_access;
6037 
6038 	switch (base_type(reg->type)) {
6039 	case PTR_TO_PACKET:
6040 	case PTR_TO_PACKET_META:
6041 		return check_packet_access(env, regno, reg->off, access_size,
6042 					   zero_size_allowed);
6043 	case PTR_TO_MAP_KEY:
6044 		if (meta && meta->raw_mode) {
6045 			verbose(env, "R%d cannot write into %s\n", regno,
6046 				reg_type_str(env, reg->type));
6047 			return -EACCES;
6048 		}
6049 		return check_mem_region_access(env, regno, reg->off, access_size,
6050 					       reg->map_ptr->key_size, false);
6051 	case PTR_TO_MAP_VALUE:
6052 		if (check_map_access_type(env, regno, reg->off, access_size,
6053 					  meta && meta->raw_mode ? BPF_WRITE :
6054 					  BPF_READ))
6055 			return -EACCES;
6056 		return check_map_access(env, regno, reg->off, access_size,
6057 					zero_size_allowed, ACCESS_HELPER);
6058 	case PTR_TO_MEM:
6059 		if (type_is_rdonly_mem(reg->type)) {
6060 			if (meta && meta->raw_mode) {
6061 				verbose(env, "R%d cannot write into %s\n", regno,
6062 					reg_type_str(env, reg->type));
6063 				return -EACCES;
6064 			}
6065 		}
6066 		return check_mem_region_access(env, regno, reg->off,
6067 					       access_size, reg->mem_size,
6068 					       zero_size_allowed);
6069 	case PTR_TO_BUF:
6070 		if (type_is_rdonly_mem(reg->type)) {
6071 			if (meta && meta->raw_mode) {
6072 				verbose(env, "R%d cannot write into %s\n", regno,
6073 					reg_type_str(env, reg->type));
6074 				return -EACCES;
6075 			}
6076 
6077 			max_access = &env->prog->aux->max_rdonly_access;
6078 		} else {
6079 			max_access = &env->prog->aux->max_rdwr_access;
6080 		}
6081 		return check_buffer_access(env, reg, regno, reg->off,
6082 					   access_size, zero_size_allowed,
6083 					   max_access);
6084 	case PTR_TO_STACK:
6085 		return check_stack_range_initialized(
6086 				env,
6087 				regno, reg->off, access_size,
6088 				zero_size_allowed, ACCESS_HELPER, meta);
6089 	case PTR_TO_CTX:
6090 		/* in case the function doesn't know how to access the context,
6091 		 * (because we are in a program of type SYSCALL for example), we
6092 		 * can not statically check its size.
6093 		 * Dynamically check it now.
6094 		 */
6095 		if (!env->ops->convert_ctx_access) {
6096 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6097 			int offset = access_size - 1;
6098 
6099 			/* Allow zero-byte read from PTR_TO_CTX */
6100 			if (access_size == 0)
6101 				return zero_size_allowed ? 0 : -EACCES;
6102 
6103 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6104 						atype, -1, false);
6105 		}
6106 
6107 		fallthrough;
6108 	default: /* scalar_value or invalid ptr */
6109 		/* Allow zero-byte read from NULL, regardless of pointer type */
6110 		if (zero_size_allowed && access_size == 0 &&
6111 		    register_is_null(reg))
6112 			return 0;
6113 
6114 		verbose(env, "R%d type=%s ", regno,
6115 			reg_type_str(env, reg->type));
6116 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6117 		return -EACCES;
6118 	}
6119 }
6120 
6121 static int check_mem_size_reg(struct bpf_verifier_env *env,
6122 			      struct bpf_reg_state *reg, u32 regno,
6123 			      bool zero_size_allowed,
6124 			      struct bpf_call_arg_meta *meta)
6125 {
6126 	int err;
6127 
6128 	/* This is used to refine r0 return value bounds for helpers
6129 	 * that enforce this value as an upper bound on return values.
6130 	 * See do_refine_retval_range() for helpers that can refine
6131 	 * the return value. C type of helper is u32 so we pull register
6132 	 * bound from umax_value however, if negative verifier errors
6133 	 * out. Only upper bounds can be learned because retval is an
6134 	 * int type and negative retvals are allowed.
6135 	 */
6136 	meta->msize_max_value = reg->umax_value;
6137 
6138 	/* The register is SCALAR_VALUE; the access check
6139 	 * happens using its boundaries.
6140 	 */
6141 	if (!tnum_is_const(reg->var_off))
6142 		/* For unprivileged variable accesses, disable raw
6143 		 * mode so that the program is required to
6144 		 * initialize all the memory that the helper could
6145 		 * just partially fill up.
6146 		 */
6147 		meta = NULL;
6148 
6149 	if (reg->smin_value < 0) {
6150 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6151 			regno);
6152 		return -EACCES;
6153 	}
6154 
6155 	if (reg->umin_value == 0) {
6156 		err = check_helper_mem_access(env, regno - 1, 0,
6157 					      zero_size_allowed,
6158 					      meta);
6159 		if (err)
6160 			return err;
6161 	}
6162 
6163 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6164 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6165 			regno);
6166 		return -EACCES;
6167 	}
6168 	err = check_helper_mem_access(env, regno - 1,
6169 				      reg->umax_value,
6170 				      zero_size_allowed, meta);
6171 	if (!err)
6172 		err = mark_chain_precision(env, regno);
6173 	return err;
6174 }
6175 
6176 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6177 		   u32 regno, u32 mem_size)
6178 {
6179 	bool may_be_null = type_may_be_null(reg->type);
6180 	struct bpf_reg_state saved_reg;
6181 	struct bpf_call_arg_meta meta;
6182 	int err;
6183 
6184 	if (register_is_null(reg))
6185 		return 0;
6186 
6187 	memset(&meta, 0, sizeof(meta));
6188 	/* Assuming that the register contains a value check if the memory
6189 	 * access is safe. Temporarily save and restore the register's state as
6190 	 * the conversion shouldn't be visible to a caller.
6191 	 */
6192 	if (may_be_null) {
6193 		saved_reg = *reg;
6194 		mark_ptr_not_null_reg(reg);
6195 	}
6196 
6197 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6198 	/* Check access for BPF_WRITE */
6199 	meta.raw_mode = true;
6200 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6201 
6202 	if (may_be_null)
6203 		*reg = saved_reg;
6204 
6205 	return err;
6206 }
6207 
6208 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6209 				    u32 regno)
6210 {
6211 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6212 	bool may_be_null = type_may_be_null(mem_reg->type);
6213 	struct bpf_reg_state saved_reg;
6214 	struct bpf_call_arg_meta meta;
6215 	int err;
6216 
6217 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6218 
6219 	memset(&meta, 0, sizeof(meta));
6220 
6221 	if (may_be_null) {
6222 		saved_reg = *mem_reg;
6223 		mark_ptr_not_null_reg(mem_reg);
6224 	}
6225 
6226 	err = check_mem_size_reg(env, reg, regno, true, &meta);
6227 	/* Check access for BPF_WRITE */
6228 	meta.raw_mode = true;
6229 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6230 
6231 	if (may_be_null)
6232 		*mem_reg = saved_reg;
6233 	return err;
6234 }
6235 
6236 /* Implementation details:
6237  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6238  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6239  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6240  * Two separate bpf_obj_new will also have different reg->id.
6241  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6242  * clears reg->id after value_or_null->value transition, since the verifier only
6243  * cares about the range of access to valid map value pointer and doesn't care
6244  * about actual address of the map element.
6245  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6246  * reg->id > 0 after value_or_null->value transition. By doing so
6247  * two bpf_map_lookups will be considered two different pointers that
6248  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6249  * returned from bpf_obj_new.
6250  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6251  * dead-locks.
6252  * Since only one bpf_spin_lock is allowed the checks are simpler than
6253  * reg_is_refcounted() logic. The verifier needs to remember only
6254  * one spin_lock instead of array of acquired_refs.
6255  * cur_state->active_lock remembers which map value element or allocated
6256  * object got locked and clears it after bpf_spin_unlock.
6257  */
6258 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6259 			     bool is_lock)
6260 {
6261 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6262 	struct bpf_verifier_state *cur = env->cur_state;
6263 	bool is_const = tnum_is_const(reg->var_off);
6264 	u64 val = reg->var_off.value;
6265 	struct bpf_map *map = NULL;
6266 	struct btf *btf = NULL;
6267 	struct btf_record *rec;
6268 
6269 	if (!is_const) {
6270 		verbose(env,
6271 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6272 			regno);
6273 		return -EINVAL;
6274 	}
6275 	if (reg->type == PTR_TO_MAP_VALUE) {
6276 		map = reg->map_ptr;
6277 		if (!map->btf) {
6278 			verbose(env,
6279 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
6280 				map->name);
6281 			return -EINVAL;
6282 		}
6283 	} else {
6284 		btf = reg->btf;
6285 	}
6286 
6287 	rec = reg_btf_record(reg);
6288 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6289 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6290 			map ? map->name : "kptr");
6291 		return -EINVAL;
6292 	}
6293 	if (rec->spin_lock_off != val + reg->off) {
6294 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6295 			val + reg->off, rec->spin_lock_off);
6296 		return -EINVAL;
6297 	}
6298 	if (is_lock) {
6299 		if (cur->active_lock.ptr) {
6300 			verbose(env,
6301 				"Locking two bpf_spin_locks are not allowed\n");
6302 			return -EINVAL;
6303 		}
6304 		if (map)
6305 			cur->active_lock.ptr = map;
6306 		else
6307 			cur->active_lock.ptr = btf;
6308 		cur->active_lock.id = reg->id;
6309 	} else {
6310 		void *ptr;
6311 
6312 		if (map)
6313 			ptr = map;
6314 		else
6315 			ptr = btf;
6316 
6317 		if (!cur->active_lock.ptr) {
6318 			verbose(env, "bpf_spin_unlock without taking a lock\n");
6319 			return -EINVAL;
6320 		}
6321 		if (cur->active_lock.ptr != ptr ||
6322 		    cur->active_lock.id != reg->id) {
6323 			verbose(env, "bpf_spin_unlock of different lock\n");
6324 			return -EINVAL;
6325 		}
6326 
6327 		invalidate_non_owning_refs(env);
6328 
6329 		cur->active_lock.ptr = NULL;
6330 		cur->active_lock.id = 0;
6331 	}
6332 	return 0;
6333 }
6334 
6335 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6336 			      struct bpf_call_arg_meta *meta)
6337 {
6338 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6339 	bool is_const = tnum_is_const(reg->var_off);
6340 	struct bpf_map *map = reg->map_ptr;
6341 	u64 val = reg->var_off.value;
6342 
6343 	if (!is_const) {
6344 		verbose(env,
6345 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6346 			regno);
6347 		return -EINVAL;
6348 	}
6349 	if (!map->btf) {
6350 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6351 			map->name);
6352 		return -EINVAL;
6353 	}
6354 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
6355 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6356 		return -EINVAL;
6357 	}
6358 	if (map->record->timer_off != val + reg->off) {
6359 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6360 			val + reg->off, map->record->timer_off);
6361 		return -EINVAL;
6362 	}
6363 	if (meta->map_ptr) {
6364 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6365 		return -EFAULT;
6366 	}
6367 	meta->map_uid = reg->map_uid;
6368 	meta->map_ptr = map;
6369 	return 0;
6370 }
6371 
6372 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6373 			     struct bpf_call_arg_meta *meta)
6374 {
6375 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6376 	struct bpf_map *map_ptr = reg->map_ptr;
6377 	struct btf_field *kptr_field;
6378 	u32 kptr_off;
6379 
6380 	if (!tnum_is_const(reg->var_off)) {
6381 		verbose(env,
6382 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6383 			regno);
6384 		return -EINVAL;
6385 	}
6386 	if (!map_ptr->btf) {
6387 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6388 			map_ptr->name);
6389 		return -EINVAL;
6390 	}
6391 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6392 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6393 		return -EINVAL;
6394 	}
6395 
6396 	meta->map_ptr = map_ptr;
6397 	kptr_off = reg->off + reg->var_off.value;
6398 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6399 	if (!kptr_field) {
6400 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6401 		return -EACCES;
6402 	}
6403 	if (kptr_field->type != BPF_KPTR_REF) {
6404 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6405 		return -EACCES;
6406 	}
6407 	meta->kptr_field = kptr_field;
6408 	return 0;
6409 }
6410 
6411 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6412  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6413  *
6414  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6415  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6416  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6417  *
6418  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6419  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6420  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6421  * mutate the view of the dynptr and also possibly destroy it. In the latter
6422  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6423  * memory that dynptr points to.
6424  *
6425  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6426  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6427  * readonly dynptr view yet, hence only the first case is tracked and checked.
6428  *
6429  * This is consistent with how C applies the const modifier to a struct object,
6430  * where the pointer itself inside bpf_dynptr becomes const but not what it
6431  * points to.
6432  *
6433  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6434  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6435  */
6436 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6437 			       enum bpf_arg_type arg_type)
6438 {
6439 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6440 	int err;
6441 
6442 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6443 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6444 	 */
6445 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6446 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6447 		return -EFAULT;
6448 	}
6449 
6450 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6451 	 *		 constructing a mutable bpf_dynptr object.
6452 	 *
6453 	 *		 Currently, this is only possible with PTR_TO_STACK
6454 	 *		 pointing to a region of at least 16 bytes which doesn't
6455 	 *		 contain an existing bpf_dynptr.
6456 	 *
6457 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6458 	 *		 mutated or destroyed. However, the memory it points to
6459 	 *		 may be mutated.
6460 	 *
6461 	 *  None       - Points to a initialized dynptr that can be mutated and
6462 	 *		 destroyed, including mutation of the memory it points
6463 	 *		 to.
6464 	 */
6465 	if (arg_type & MEM_UNINIT) {
6466 		int i;
6467 
6468 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
6469 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6470 			return -EINVAL;
6471 		}
6472 
6473 		/* we write BPF_DW bits (8 bytes) at a time */
6474 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6475 			err = check_mem_access(env, insn_idx, regno,
6476 					       i, BPF_DW, BPF_WRITE, -1, false);
6477 			if (err)
6478 				return err;
6479 		}
6480 
6481 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6482 	} else /* MEM_RDONLY and None case from above */ {
6483 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6484 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6485 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6486 			return -EINVAL;
6487 		}
6488 
6489 		if (!is_dynptr_reg_valid_init(env, reg)) {
6490 			verbose(env,
6491 				"Expected an initialized dynptr as arg #%d\n",
6492 				regno);
6493 			return -EINVAL;
6494 		}
6495 
6496 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6497 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6498 			verbose(env,
6499 				"Expected a dynptr of type %s as arg #%d\n",
6500 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6501 			return -EINVAL;
6502 		}
6503 
6504 		err = mark_dynptr_read(env, reg);
6505 	}
6506 	return err;
6507 }
6508 
6509 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6510 {
6511 	return type == ARG_CONST_SIZE ||
6512 	       type == ARG_CONST_SIZE_OR_ZERO;
6513 }
6514 
6515 static bool arg_type_is_release(enum bpf_arg_type type)
6516 {
6517 	return type & OBJ_RELEASE;
6518 }
6519 
6520 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6521 {
6522 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6523 }
6524 
6525 static int int_ptr_type_to_size(enum bpf_arg_type type)
6526 {
6527 	if (type == ARG_PTR_TO_INT)
6528 		return sizeof(u32);
6529 	else if (type == ARG_PTR_TO_LONG)
6530 		return sizeof(u64);
6531 
6532 	return -EINVAL;
6533 }
6534 
6535 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6536 				 const struct bpf_call_arg_meta *meta,
6537 				 enum bpf_arg_type *arg_type)
6538 {
6539 	if (!meta->map_ptr) {
6540 		/* kernel subsystem misconfigured verifier */
6541 		verbose(env, "invalid map_ptr to access map->type\n");
6542 		return -EACCES;
6543 	}
6544 
6545 	switch (meta->map_ptr->map_type) {
6546 	case BPF_MAP_TYPE_SOCKMAP:
6547 	case BPF_MAP_TYPE_SOCKHASH:
6548 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6549 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6550 		} else {
6551 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6552 			return -EINVAL;
6553 		}
6554 		break;
6555 	case BPF_MAP_TYPE_BLOOM_FILTER:
6556 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6557 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6558 		break;
6559 	default:
6560 		break;
6561 	}
6562 	return 0;
6563 }
6564 
6565 struct bpf_reg_types {
6566 	const enum bpf_reg_type types[10];
6567 	u32 *btf_id;
6568 };
6569 
6570 static const struct bpf_reg_types sock_types = {
6571 	.types = {
6572 		PTR_TO_SOCK_COMMON,
6573 		PTR_TO_SOCKET,
6574 		PTR_TO_TCP_SOCK,
6575 		PTR_TO_XDP_SOCK,
6576 	},
6577 };
6578 
6579 #ifdef CONFIG_NET
6580 static const struct bpf_reg_types btf_id_sock_common_types = {
6581 	.types = {
6582 		PTR_TO_SOCK_COMMON,
6583 		PTR_TO_SOCKET,
6584 		PTR_TO_TCP_SOCK,
6585 		PTR_TO_XDP_SOCK,
6586 		PTR_TO_BTF_ID,
6587 		PTR_TO_BTF_ID | PTR_TRUSTED,
6588 	},
6589 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6590 };
6591 #endif
6592 
6593 static const struct bpf_reg_types mem_types = {
6594 	.types = {
6595 		PTR_TO_STACK,
6596 		PTR_TO_PACKET,
6597 		PTR_TO_PACKET_META,
6598 		PTR_TO_MAP_KEY,
6599 		PTR_TO_MAP_VALUE,
6600 		PTR_TO_MEM,
6601 		PTR_TO_MEM | MEM_RINGBUF,
6602 		PTR_TO_BUF,
6603 	},
6604 };
6605 
6606 static const struct bpf_reg_types int_ptr_types = {
6607 	.types = {
6608 		PTR_TO_STACK,
6609 		PTR_TO_PACKET,
6610 		PTR_TO_PACKET_META,
6611 		PTR_TO_MAP_KEY,
6612 		PTR_TO_MAP_VALUE,
6613 	},
6614 };
6615 
6616 static const struct bpf_reg_types spin_lock_types = {
6617 	.types = {
6618 		PTR_TO_MAP_VALUE,
6619 		PTR_TO_BTF_ID | MEM_ALLOC,
6620 	}
6621 };
6622 
6623 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6624 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6625 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6626 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6627 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6628 static const struct bpf_reg_types btf_ptr_types = {
6629 	.types = {
6630 		PTR_TO_BTF_ID,
6631 		PTR_TO_BTF_ID | PTR_TRUSTED,
6632 		PTR_TO_BTF_ID | MEM_RCU,
6633 	},
6634 };
6635 static const struct bpf_reg_types percpu_btf_ptr_types = {
6636 	.types = {
6637 		PTR_TO_BTF_ID | MEM_PERCPU,
6638 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6639 	}
6640 };
6641 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6642 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6643 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6644 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6645 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6646 static const struct bpf_reg_types dynptr_types = {
6647 	.types = {
6648 		PTR_TO_STACK,
6649 		CONST_PTR_TO_DYNPTR,
6650 	}
6651 };
6652 
6653 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6654 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6655 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6656 	[ARG_CONST_SIZE]		= &scalar_types,
6657 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6658 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6659 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6660 	[ARG_PTR_TO_CTX]		= &context_types,
6661 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6662 #ifdef CONFIG_NET
6663 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6664 #endif
6665 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6666 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6667 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6668 	[ARG_PTR_TO_MEM]		= &mem_types,
6669 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6670 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6671 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6672 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6673 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6674 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6675 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6676 	[ARG_PTR_TO_TIMER]		= &timer_types,
6677 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6678 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6679 };
6680 
6681 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6682 			  enum bpf_arg_type arg_type,
6683 			  const u32 *arg_btf_id,
6684 			  struct bpf_call_arg_meta *meta)
6685 {
6686 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6687 	enum bpf_reg_type expected, type = reg->type;
6688 	const struct bpf_reg_types *compatible;
6689 	int i, j;
6690 
6691 	compatible = compatible_reg_types[base_type(arg_type)];
6692 	if (!compatible) {
6693 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6694 		return -EFAULT;
6695 	}
6696 
6697 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6698 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6699 	 *
6700 	 * Same for MAYBE_NULL:
6701 	 *
6702 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6703 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6704 	 *
6705 	 * Therefore we fold these flags depending on the arg_type before comparison.
6706 	 */
6707 	if (arg_type & MEM_RDONLY)
6708 		type &= ~MEM_RDONLY;
6709 	if (arg_type & PTR_MAYBE_NULL)
6710 		type &= ~PTR_MAYBE_NULL;
6711 
6712 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6713 		expected = compatible->types[i];
6714 		if (expected == NOT_INIT)
6715 			break;
6716 
6717 		if (type == expected)
6718 			goto found;
6719 	}
6720 
6721 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6722 	for (j = 0; j + 1 < i; j++)
6723 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6724 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6725 	return -EACCES;
6726 
6727 found:
6728 	if (base_type(reg->type) != PTR_TO_BTF_ID)
6729 		return 0;
6730 
6731 	switch ((int)reg->type) {
6732 	case PTR_TO_BTF_ID:
6733 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6734 	case PTR_TO_BTF_ID | MEM_RCU:
6735 	{
6736 		/* For bpf_sk_release, it needs to match against first member
6737 		 * 'struct sock_common', hence make an exception for it. This
6738 		 * allows bpf_sk_release to work for multiple socket types.
6739 		 */
6740 		bool strict_type_match = arg_type_is_release(arg_type) &&
6741 					 meta->func_id != BPF_FUNC_sk_release;
6742 
6743 		if (!arg_btf_id) {
6744 			if (!compatible->btf_id) {
6745 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6746 				return -EFAULT;
6747 			}
6748 			arg_btf_id = compatible->btf_id;
6749 		}
6750 
6751 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6752 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6753 				return -EACCES;
6754 		} else {
6755 			if (arg_btf_id == BPF_PTR_POISON) {
6756 				verbose(env, "verifier internal error:");
6757 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6758 					regno);
6759 				return -EACCES;
6760 			}
6761 
6762 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6763 						  btf_vmlinux, *arg_btf_id,
6764 						  strict_type_match)) {
6765 				verbose(env, "R%d is of type %s but %s is expected\n",
6766 					regno, kernel_type_name(reg->btf, reg->btf_id),
6767 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6768 				return -EACCES;
6769 			}
6770 		}
6771 		break;
6772 	}
6773 	case PTR_TO_BTF_ID | MEM_ALLOC:
6774 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6775 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6776 			return -EFAULT;
6777 		}
6778 		/* Handled by helper specific checks */
6779 		break;
6780 	case PTR_TO_BTF_ID | MEM_PERCPU:
6781 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
6782 		/* Handled by helper specific checks */
6783 		break;
6784 	default:
6785 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
6786 		return -EFAULT;
6787 	}
6788 	return 0;
6789 }
6790 
6791 static struct btf_field *
6792 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
6793 {
6794 	struct btf_field *field;
6795 	struct btf_record *rec;
6796 
6797 	rec = reg_btf_record(reg);
6798 	if (!rec)
6799 		return NULL;
6800 
6801 	field = btf_record_find(rec, off, fields);
6802 	if (!field)
6803 		return NULL;
6804 
6805 	return field;
6806 }
6807 
6808 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6809 			   const struct bpf_reg_state *reg, int regno,
6810 			   enum bpf_arg_type arg_type)
6811 {
6812 	u32 type = reg->type;
6813 
6814 	/* When referenced register is passed to release function, its fixed
6815 	 * offset must be 0.
6816 	 *
6817 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6818 	 * meta->release_regno.
6819 	 */
6820 	if (arg_type_is_release(arg_type)) {
6821 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6822 		 * may not directly point to the object being released, but to
6823 		 * dynptr pointing to such object, which might be at some offset
6824 		 * on the stack. In that case, we simply to fallback to the
6825 		 * default handling.
6826 		 */
6827 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6828 			return 0;
6829 
6830 		if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
6831 			if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
6832 				return __check_ptr_off_reg(env, reg, regno, true);
6833 
6834 			verbose(env, "R%d must have zero offset when passed to release func\n",
6835 				regno);
6836 			verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
6837 				kernel_type_name(reg->btf, reg->btf_id), reg->off);
6838 			return -EINVAL;
6839 		}
6840 
6841 		/* Doing check_ptr_off_reg check for the offset will catch this
6842 		 * because fixed_off_ok is false, but checking here allows us
6843 		 * to give the user a better error message.
6844 		 */
6845 		if (reg->off) {
6846 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6847 				regno);
6848 			return -EINVAL;
6849 		}
6850 		return __check_ptr_off_reg(env, reg, regno, false);
6851 	}
6852 
6853 	switch (type) {
6854 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6855 	case PTR_TO_STACK:
6856 	case PTR_TO_PACKET:
6857 	case PTR_TO_PACKET_META:
6858 	case PTR_TO_MAP_KEY:
6859 	case PTR_TO_MAP_VALUE:
6860 	case PTR_TO_MEM:
6861 	case PTR_TO_MEM | MEM_RDONLY:
6862 	case PTR_TO_MEM | MEM_RINGBUF:
6863 	case PTR_TO_BUF:
6864 	case PTR_TO_BUF | MEM_RDONLY:
6865 	case SCALAR_VALUE:
6866 		return 0;
6867 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6868 	 * fixed offset.
6869 	 */
6870 	case PTR_TO_BTF_ID:
6871 	case PTR_TO_BTF_ID | MEM_ALLOC:
6872 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6873 	case PTR_TO_BTF_ID | MEM_RCU:
6874 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
6875 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6876 		 * its fixed offset must be 0. In the other cases, fixed offset
6877 		 * can be non-zero. This was already checked above. So pass
6878 		 * fixed_off_ok as true to allow fixed offset for all other
6879 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6880 		 * still need to do checks instead of returning.
6881 		 */
6882 		return __check_ptr_off_reg(env, reg, regno, true);
6883 	default:
6884 		return __check_ptr_off_reg(env, reg, regno, false);
6885 	}
6886 }
6887 
6888 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
6889 						const struct bpf_func_proto *fn,
6890 						struct bpf_reg_state *regs)
6891 {
6892 	struct bpf_reg_state *state = NULL;
6893 	int i;
6894 
6895 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
6896 		if (arg_type_is_dynptr(fn->arg_type[i])) {
6897 			if (state) {
6898 				verbose(env, "verifier internal error: multiple dynptr args\n");
6899 				return NULL;
6900 			}
6901 			state = &regs[BPF_REG_1 + i];
6902 		}
6903 
6904 	if (!state)
6905 		verbose(env, "verifier internal error: no dynptr arg found\n");
6906 
6907 	return state;
6908 }
6909 
6910 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6911 {
6912 	struct bpf_func_state *state = func(env, reg);
6913 	int spi;
6914 
6915 	if (reg->type == CONST_PTR_TO_DYNPTR)
6916 		return reg->id;
6917 	spi = dynptr_get_spi(env, reg);
6918 	if (spi < 0)
6919 		return spi;
6920 	return state->stack[spi].spilled_ptr.id;
6921 }
6922 
6923 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6924 {
6925 	struct bpf_func_state *state = func(env, reg);
6926 	int spi;
6927 
6928 	if (reg->type == CONST_PTR_TO_DYNPTR)
6929 		return reg->ref_obj_id;
6930 	spi = dynptr_get_spi(env, reg);
6931 	if (spi < 0)
6932 		return spi;
6933 	return state->stack[spi].spilled_ptr.ref_obj_id;
6934 }
6935 
6936 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
6937 					    struct bpf_reg_state *reg)
6938 {
6939 	struct bpf_func_state *state = func(env, reg);
6940 	int spi;
6941 
6942 	if (reg->type == CONST_PTR_TO_DYNPTR)
6943 		return reg->dynptr.type;
6944 
6945 	spi = __get_spi(reg->off);
6946 	if (spi < 0) {
6947 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
6948 		return BPF_DYNPTR_TYPE_INVALID;
6949 	}
6950 
6951 	return state->stack[spi].spilled_ptr.dynptr.type;
6952 }
6953 
6954 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6955 			  struct bpf_call_arg_meta *meta,
6956 			  const struct bpf_func_proto *fn,
6957 			  int insn_idx)
6958 {
6959 	u32 regno = BPF_REG_1 + arg;
6960 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6961 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6962 	enum bpf_reg_type type = reg->type;
6963 	u32 *arg_btf_id = NULL;
6964 	int err = 0;
6965 
6966 	if (arg_type == ARG_DONTCARE)
6967 		return 0;
6968 
6969 	err = check_reg_arg(env, regno, SRC_OP);
6970 	if (err)
6971 		return err;
6972 
6973 	if (arg_type == ARG_ANYTHING) {
6974 		if (is_pointer_value(env, regno)) {
6975 			verbose(env, "R%d leaks addr into helper function\n",
6976 				regno);
6977 			return -EACCES;
6978 		}
6979 		return 0;
6980 	}
6981 
6982 	if (type_is_pkt_pointer(type) &&
6983 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6984 		verbose(env, "helper access to the packet is not allowed\n");
6985 		return -EACCES;
6986 	}
6987 
6988 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6989 		err = resolve_map_arg_type(env, meta, &arg_type);
6990 		if (err)
6991 			return err;
6992 	}
6993 
6994 	if (register_is_null(reg) && type_may_be_null(arg_type))
6995 		/* A NULL register has a SCALAR_VALUE type, so skip
6996 		 * type checking.
6997 		 */
6998 		goto skip_type_check;
6999 
7000 	/* arg_btf_id and arg_size are in a union. */
7001 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7002 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7003 		arg_btf_id = fn->arg_btf_id[arg];
7004 
7005 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7006 	if (err)
7007 		return err;
7008 
7009 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
7010 	if (err)
7011 		return err;
7012 
7013 skip_type_check:
7014 	if (arg_type_is_release(arg_type)) {
7015 		if (arg_type_is_dynptr(arg_type)) {
7016 			struct bpf_func_state *state = func(env, reg);
7017 			int spi;
7018 
7019 			/* Only dynptr created on stack can be released, thus
7020 			 * the get_spi and stack state checks for spilled_ptr
7021 			 * should only be done before process_dynptr_func for
7022 			 * PTR_TO_STACK.
7023 			 */
7024 			if (reg->type == PTR_TO_STACK) {
7025 				spi = dynptr_get_spi(env, reg);
7026 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7027 					verbose(env, "arg %d is an unacquired reference\n", regno);
7028 					return -EINVAL;
7029 				}
7030 			} else {
7031 				verbose(env, "cannot release unowned const bpf_dynptr\n");
7032 				return -EINVAL;
7033 			}
7034 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
7035 			verbose(env, "R%d must be referenced when passed to release function\n",
7036 				regno);
7037 			return -EINVAL;
7038 		}
7039 		if (meta->release_regno) {
7040 			verbose(env, "verifier internal error: more than one release argument\n");
7041 			return -EFAULT;
7042 		}
7043 		meta->release_regno = regno;
7044 	}
7045 
7046 	if (reg->ref_obj_id) {
7047 		if (meta->ref_obj_id) {
7048 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7049 				regno, reg->ref_obj_id,
7050 				meta->ref_obj_id);
7051 			return -EFAULT;
7052 		}
7053 		meta->ref_obj_id = reg->ref_obj_id;
7054 	}
7055 
7056 	switch (base_type(arg_type)) {
7057 	case ARG_CONST_MAP_PTR:
7058 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7059 		if (meta->map_ptr) {
7060 			/* Use map_uid (which is unique id of inner map) to reject:
7061 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7062 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7063 			 * if (inner_map1 && inner_map2) {
7064 			 *     timer = bpf_map_lookup_elem(inner_map1);
7065 			 *     if (timer)
7066 			 *         // mismatch would have been allowed
7067 			 *         bpf_timer_init(timer, inner_map2);
7068 			 * }
7069 			 *
7070 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
7071 			 */
7072 			if (meta->map_ptr != reg->map_ptr ||
7073 			    meta->map_uid != reg->map_uid) {
7074 				verbose(env,
7075 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7076 					meta->map_uid, reg->map_uid);
7077 				return -EINVAL;
7078 			}
7079 		}
7080 		meta->map_ptr = reg->map_ptr;
7081 		meta->map_uid = reg->map_uid;
7082 		break;
7083 	case ARG_PTR_TO_MAP_KEY:
7084 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
7085 		 * check that [key, key + map->key_size) are within
7086 		 * stack limits and initialized
7087 		 */
7088 		if (!meta->map_ptr) {
7089 			/* in function declaration map_ptr must come before
7090 			 * map_key, so that it's verified and known before
7091 			 * we have to check map_key here. Otherwise it means
7092 			 * that kernel subsystem misconfigured verifier
7093 			 */
7094 			verbose(env, "invalid map_ptr to access map->key\n");
7095 			return -EACCES;
7096 		}
7097 		err = check_helper_mem_access(env, regno,
7098 					      meta->map_ptr->key_size, false,
7099 					      NULL);
7100 		break;
7101 	case ARG_PTR_TO_MAP_VALUE:
7102 		if (type_may_be_null(arg_type) && register_is_null(reg))
7103 			return 0;
7104 
7105 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
7106 		 * check [value, value + map->value_size) validity
7107 		 */
7108 		if (!meta->map_ptr) {
7109 			/* kernel subsystem misconfigured verifier */
7110 			verbose(env, "invalid map_ptr to access map->value\n");
7111 			return -EACCES;
7112 		}
7113 		meta->raw_mode = arg_type & MEM_UNINIT;
7114 		err = check_helper_mem_access(env, regno,
7115 					      meta->map_ptr->value_size, false,
7116 					      meta);
7117 		break;
7118 	case ARG_PTR_TO_PERCPU_BTF_ID:
7119 		if (!reg->btf_id) {
7120 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7121 			return -EACCES;
7122 		}
7123 		meta->ret_btf = reg->btf;
7124 		meta->ret_btf_id = reg->btf_id;
7125 		break;
7126 	case ARG_PTR_TO_SPIN_LOCK:
7127 		if (in_rbtree_lock_required_cb(env)) {
7128 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7129 			return -EACCES;
7130 		}
7131 		if (meta->func_id == BPF_FUNC_spin_lock) {
7132 			err = process_spin_lock(env, regno, true);
7133 			if (err)
7134 				return err;
7135 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
7136 			err = process_spin_lock(env, regno, false);
7137 			if (err)
7138 				return err;
7139 		} else {
7140 			verbose(env, "verifier internal error\n");
7141 			return -EFAULT;
7142 		}
7143 		break;
7144 	case ARG_PTR_TO_TIMER:
7145 		err = process_timer_func(env, regno, meta);
7146 		if (err)
7147 			return err;
7148 		break;
7149 	case ARG_PTR_TO_FUNC:
7150 		meta->subprogno = reg->subprogno;
7151 		break;
7152 	case ARG_PTR_TO_MEM:
7153 		/* The access to this pointer is only checked when we hit the
7154 		 * next is_mem_size argument below.
7155 		 */
7156 		meta->raw_mode = arg_type & MEM_UNINIT;
7157 		if (arg_type & MEM_FIXED_SIZE) {
7158 			err = check_helper_mem_access(env, regno,
7159 						      fn->arg_size[arg], false,
7160 						      meta);
7161 		}
7162 		break;
7163 	case ARG_CONST_SIZE:
7164 		err = check_mem_size_reg(env, reg, regno, false, meta);
7165 		break;
7166 	case ARG_CONST_SIZE_OR_ZERO:
7167 		err = check_mem_size_reg(env, reg, regno, true, meta);
7168 		break;
7169 	case ARG_PTR_TO_DYNPTR:
7170 		err = process_dynptr_func(env, regno, insn_idx, arg_type);
7171 		if (err)
7172 			return err;
7173 		break;
7174 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7175 		if (!tnum_is_const(reg->var_off)) {
7176 			verbose(env, "R%d is not a known constant'\n",
7177 				regno);
7178 			return -EACCES;
7179 		}
7180 		meta->mem_size = reg->var_off.value;
7181 		err = mark_chain_precision(env, regno);
7182 		if (err)
7183 			return err;
7184 		break;
7185 	case ARG_PTR_TO_INT:
7186 	case ARG_PTR_TO_LONG:
7187 	{
7188 		int size = int_ptr_type_to_size(arg_type);
7189 
7190 		err = check_helper_mem_access(env, regno, size, false, meta);
7191 		if (err)
7192 			return err;
7193 		err = check_ptr_alignment(env, reg, 0, size, true);
7194 		break;
7195 	}
7196 	case ARG_PTR_TO_CONST_STR:
7197 	{
7198 		struct bpf_map *map = reg->map_ptr;
7199 		int map_off;
7200 		u64 map_addr;
7201 		char *str_ptr;
7202 
7203 		if (!bpf_map_is_rdonly(map)) {
7204 			verbose(env, "R%d does not point to a readonly map'\n", regno);
7205 			return -EACCES;
7206 		}
7207 
7208 		if (!tnum_is_const(reg->var_off)) {
7209 			verbose(env, "R%d is not a constant address'\n", regno);
7210 			return -EACCES;
7211 		}
7212 
7213 		if (!map->ops->map_direct_value_addr) {
7214 			verbose(env, "no direct value access support for this map type\n");
7215 			return -EACCES;
7216 		}
7217 
7218 		err = check_map_access(env, regno, reg->off,
7219 				       map->value_size - reg->off, false,
7220 				       ACCESS_HELPER);
7221 		if (err)
7222 			return err;
7223 
7224 		map_off = reg->off + reg->var_off.value;
7225 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7226 		if (err) {
7227 			verbose(env, "direct value access on string failed\n");
7228 			return err;
7229 		}
7230 
7231 		str_ptr = (char *)(long)(map_addr);
7232 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7233 			verbose(env, "string is not zero-terminated\n");
7234 			return -EINVAL;
7235 		}
7236 		break;
7237 	}
7238 	case ARG_PTR_TO_KPTR:
7239 		err = process_kptr_func(env, regno, meta);
7240 		if (err)
7241 			return err;
7242 		break;
7243 	}
7244 
7245 	return err;
7246 }
7247 
7248 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7249 {
7250 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
7251 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7252 
7253 	if (func_id != BPF_FUNC_map_update_elem)
7254 		return false;
7255 
7256 	/* It's not possible to get access to a locked struct sock in these
7257 	 * contexts, so updating is safe.
7258 	 */
7259 	switch (type) {
7260 	case BPF_PROG_TYPE_TRACING:
7261 		if (eatype == BPF_TRACE_ITER)
7262 			return true;
7263 		break;
7264 	case BPF_PROG_TYPE_SOCKET_FILTER:
7265 	case BPF_PROG_TYPE_SCHED_CLS:
7266 	case BPF_PROG_TYPE_SCHED_ACT:
7267 	case BPF_PROG_TYPE_XDP:
7268 	case BPF_PROG_TYPE_SK_REUSEPORT:
7269 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
7270 	case BPF_PROG_TYPE_SK_LOOKUP:
7271 		return true;
7272 	default:
7273 		break;
7274 	}
7275 
7276 	verbose(env, "cannot update sockmap in this context\n");
7277 	return false;
7278 }
7279 
7280 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7281 {
7282 	return env->prog->jit_requested &&
7283 	       bpf_jit_supports_subprog_tailcalls();
7284 }
7285 
7286 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7287 					struct bpf_map *map, int func_id)
7288 {
7289 	if (!map)
7290 		return 0;
7291 
7292 	/* We need a two way check, first is from map perspective ... */
7293 	switch (map->map_type) {
7294 	case BPF_MAP_TYPE_PROG_ARRAY:
7295 		if (func_id != BPF_FUNC_tail_call)
7296 			goto error;
7297 		break;
7298 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7299 		if (func_id != BPF_FUNC_perf_event_read &&
7300 		    func_id != BPF_FUNC_perf_event_output &&
7301 		    func_id != BPF_FUNC_skb_output &&
7302 		    func_id != BPF_FUNC_perf_event_read_value &&
7303 		    func_id != BPF_FUNC_xdp_output)
7304 			goto error;
7305 		break;
7306 	case BPF_MAP_TYPE_RINGBUF:
7307 		if (func_id != BPF_FUNC_ringbuf_output &&
7308 		    func_id != BPF_FUNC_ringbuf_reserve &&
7309 		    func_id != BPF_FUNC_ringbuf_query &&
7310 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7311 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7312 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
7313 			goto error;
7314 		break;
7315 	case BPF_MAP_TYPE_USER_RINGBUF:
7316 		if (func_id != BPF_FUNC_user_ringbuf_drain)
7317 			goto error;
7318 		break;
7319 	case BPF_MAP_TYPE_STACK_TRACE:
7320 		if (func_id != BPF_FUNC_get_stackid)
7321 			goto error;
7322 		break;
7323 	case BPF_MAP_TYPE_CGROUP_ARRAY:
7324 		if (func_id != BPF_FUNC_skb_under_cgroup &&
7325 		    func_id != BPF_FUNC_current_task_under_cgroup)
7326 			goto error;
7327 		break;
7328 	case BPF_MAP_TYPE_CGROUP_STORAGE:
7329 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7330 		if (func_id != BPF_FUNC_get_local_storage)
7331 			goto error;
7332 		break;
7333 	case BPF_MAP_TYPE_DEVMAP:
7334 	case BPF_MAP_TYPE_DEVMAP_HASH:
7335 		if (func_id != BPF_FUNC_redirect_map &&
7336 		    func_id != BPF_FUNC_map_lookup_elem)
7337 			goto error;
7338 		break;
7339 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
7340 	 * appear.
7341 	 */
7342 	case BPF_MAP_TYPE_CPUMAP:
7343 		if (func_id != BPF_FUNC_redirect_map)
7344 			goto error;
7345 		break;
7346 	case BPF_MAP_TYPE_XSKMAP:
7347 		if (func_id != BPF_FUNC_redirect_map &&
7348 		    func_id != BPF_FUNC_map_lookup_elem)
7349 			goto error;
7350 		break;
7351 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7352 	case BPF_MAP_TYPE_HASH_OF_MAPS:
7353 		if (func_id != BPF_FUNC_map_lookup_elem)
7354 			goto error;
7355 		break;
7356 	case BPF_MAP_TYPE_SOCKMAP:
7357 		if (func_id != BPF_FUNC_sk_redirect_map &&
7358 		    func_id != BPF_FUNC_sock_map_update &&
7359 		    func_id != BPF_FUNC_map_delete_elem &&
7360 		    func_id != BPF_FUNC_msg_redirect_map &&
7361 		    func_id != BPF_FUNC_sk_select_reuseport &&
7362 		    func_id != BPF_FUNC_map_lookup_elem &&
7363 		    !may_update_sockmap(env, func_id))
7364 			goto error;
7365 		break;
7366 	case BPF_MAP_TYPE_SOCKHASH:
7367 		if (func_id != BPF_FUNC_sk_redirect_hash &&
7368 		    func_id != BPF_FUNC_sock_hash_update &&
7369 		    func_id != BPF_FUNC_map_delete_elem &&
7370 		    func_id != BPF_FUNC_msg_redirect_hash &&
7371 		    func_id != BPF_FUNC_sk_select_reuseport &&
7372 		    func_id != BPF_FUNC_map_lookup_elem &&
7373 		    !may_update_sockmap(env, func_id))
7374 			goto error;
7375 		break;
7376 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7377 		if (func_id != BPF_FUNC_sk_select_reuseport)
7378 			goto error;
7379 		break;
7380 	case BPF_MAP_TYPE_QUEUE:
7381 	case BPF_MAP_TYPE_STACK:
7382 		if (func_id != BPF_FUNC_map_peek_elem &&
7383 		    func_id != BPF_FUNC_map_pop_elem &&
7384 		    func_id != BPF_FUNC_map_push_elem)
7385 			goto error;
7386 		break;
7387 	case BPF_MAP_TYPE_SK_STORAGE:
7388 		if (func_id != BPF_FUNC_sk_storage_get &&
7389 		    func_id != BPF_FUNC_sk_storage_delete &&
7390 		    func_id != BPF_FUNC_kptr_xchg)
7391 			goto error;
7392 		break;
7393 	case BPF_MAP_TYPE_INODE_STORAGE:
7394 		if (func_id != BPF_FUNC_inode_storage_get &&
7395 		    func_id != BPF_FUNC_inode_storage_delete &&
7396 		    func_id != BPF_FUNC_kptr_xchg)
7397 			goto error;
7398 		break;
7399 	case BPF_MAP_TYPE_TASK_STORAGE:
7400 		if (func_id != BPF_FUNC_task_storage_get &&
7401 		    func_id != BPF_FUNC_task_storage_delete &&
7402 		    func_id != BPF_FUNC_kptr_xchg)
7403 			goto error;
7404 		break;
7405 	case BPF_MAP_TYPE_CGRP_STORAGE:
7406 		if (func_id != BPF_FUNC_cgrp_storage_get &&
7407 		    func_id != BPF_FUNC_cgrp_storage_delete &&
7408 		    func_id != BPF_FUNC_kptr_xchg)
7409 			goto error;
7410 		break;
7411 	case BPF_MAP_TYPE_BLOOM_FILTER:
7412 		if (func_id != BPF_FUNC_map_peek_elem &&
7413 		    func_id != BPF_FUNC_map_push_elem)
7414 			goto error;
7415 		break;
7416 	default:
7417 		break;
7418 	}
7419 
7420 	/* ... and second from the function itself. */
7421 	switch (func_id) {
7422 	case BPF_FUNC_tail_call:
7423 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7424 			goto error;
7425 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7426 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7427 			return -EINVAL;
7428 		}
7429 		break;
7430 	case BPF_FUNC_perf_event_read:
7431 	case BPF_FUNC_perf_event_output:
7432 	case BPF_FUNC_perf_event_read_value:
7433 	case BPF_FUNC_skb_output:
7434 	case BPF_FUNC_xdp_output:
7435 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7436 			goto error;
7437 		break;
7438 	case BPF_FUNC_ringbuf_output:
7439 	case BPF_FUNC_ringbuf_reserve:
7440 	case BPF_FUNC_ringbuf_query:
7441 	case BPF_FUNC_ringbuf_reserve_dynptr:
7442 	case BPF_FUNC_ringbuf_submit_dynptr:
7443 	case BPF_FUNC_ringbuf_discard_dynptr:
7444 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7445 			goto error;
7446 		break;
7447 	case BPF_FUNC_user_ringbuf_drain:
7448 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7449 			goto error;
7450 		break;
7451 	case BPF_FUNC_get_stackid:
7452 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7453 			goto error;
7454 		break;
7455 	case BPF_FUNC_current_task_under_cgroup:
7456 	case BPF_FUNC_skb_under_cgroup:
7457 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7458 			goto error;
7459 		break;
7460 	case BPF_FUNC_redirect_map:
7461 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7462 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7463 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
7464 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
7465 			goto error;
7466 		break;
7467 	case BPF_FUNC_sk_redirect_map:
7468 	case BPF_FUNC_msg_redirect_map:
7469 	case BPF_FUNC_sock_map_update:
7470 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7471 			goto error;
7472 		break;
7473 	case BPF_FUNC_sk_redirect_hash:
7474 	case BPF_FUNC_msg_redirect_hash:
7475 	case BPF_FUNC_sock_hash_update:
7476 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7477 			goto error;
7478 		break;
7479 	case BPF_FUNC_get_local_storage:
7480 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7481 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7482 			goto error;
7483 		break;
7484 	case BPF_FUNC_sk_select_reuseport:
7485 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7486 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7487 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
7488 			goto error;
7489 		break;
7490 	case BPF_FUNC_map_pop_elem:
7491 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7492 		    map->map_type != BPF_MAP_TYPE_STACK)
7493 			goto error;
7494 		break;
7495 	case BPF_FUNC_map_peek_elem:
7496 	case BPF_FUNC_map_push_elem:
7497 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7498 		    map->map_type != BPF_MAP_TYPE_STACK &&
7499 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7500 			goto error;
7501 		break;
7502 	case BPF_FUNC_map_lookup_percpu_elem:
7503 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7504 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7505 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7506 			goto error;
7507 		break;
7508 	case BPF_FUNC_sk_storage_get:
7509 	case BPF_FUNC_sk_storage_delete:
7510 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7511 			goto error;
7512 		break;
7513 	case BPF_FUNC_inode_storage_get:
7514 	case BPF_FUNC_inode_storage_delete:
7515 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7516 			goto error;
7517 		break;
7518 	case BPF_FUNC_task_storage_get:
7519 	case BPF_FUNC_task_storage_delete:
7520 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7521 			goto error;
7522 		break;
7523 	case BPF_FUNC_cgrp_storage_get:
7524 	case BPF_FUNC_cgrp_storage_delete:
7525 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7526 			goto error;
7527 		break;
7528 	default:
7529 		break;
7530 	}
7531 
7532 	return 0;
7533 error:
7534 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
7535 		map->map_type, func_id_name(func_id), func_id);
7536 	return -EINVAL;
7537 }
7538 
7539 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7540 {
7541 	int count = 0;
7542 
7543 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7544 		count++;
7545 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7546 		count++;
7547 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7548 		count++;
7549 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7550 		count++;
7551 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7552 		count++;
7553 
7554 	/* We only support one arg being in raw mode at the moment,
7555 	 * which is sufficient for the helper functions we have
7556 	 * right now.
7557 	 */
7558 	return count <= 1;
7559 }
7560 
7561 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7562 {
7563 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7564 	bool has_size = fn->arg_size[arg] != 0;
7565 	bool is_next_size = false;
7566 
7567 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7568 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7569 
7570 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7571 		return is_next_size;
7572 
7573 	return has_size == is_next_size || is_next_size == is_fixed;
7574 }
7575 
7576 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7577 {
7578 	/* bpf_xxx(..., buf, len) call will access 'len'
7579 	 * bytes from memory 'buf'. Both arg types need
7580 	 * to be paired, so make sure there's no buggy
7581 	 * helper function specification.
7582 	 */
7583 	if (arg_type_is_mem_size(fn->arg1_type) ||
7584 	    check_args_pair_invalid(fn, 0) ||
7585 	    check_args_pair_invalid(fn, 1) ||
7586 	    check_args_pair_invalid(fn, 2) ||
7587 	    check_args_pair_invalid(fn, 3) ||
7588 	    check_args_pair_invalid(fn, 4))
7589 		return false;
7590 
7591 	return true;
7592 }
7593 
7594 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7595 {
7596 	int i;
7597 
7598 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7599 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7600 			return !!fn->arg_btf_id[i];
7601 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7602 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
7603 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7604 		    /* arg_btf_id and arg_size are in a union. */
7605 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7606 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7607 			return false;
7608 	}
7609 
7610 	return true;
7611 }
7612 
7613 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7614 {
7615 	return check_raw_mode_ok(fn) &&
7616 	       check_arg_pair_ok(fn) &&
7617 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7618 }
7619 
7620 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7621  * are now invalid, so turn them into unknown SCALAR_VALUE.
7622  *
7623  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
7624  * since these slices point to packet data.
7625  */
7626 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7627 {
7628 	struct bpf_func_state *state;
7629 	struct bpf_reg_state *reg;
7630 
7631 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7632 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
7633 			mark_reg_invalid(env, reg);
7634 	}));
7635 }
7636 
7637 enum {
7638 	AT_PKT_END = -1,
7639 	BEYOND_PKT_END = -2,
7640 };
7641 
7642 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7643 {
7644 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7645 	struct bpf_reg_state *reg = &state->regs[regn];
7646 
7647 	if (reg->type != PTR_TO_PACKET)
7648 		/* PTR_TO_PACKET_META is not supported yet */
7649 		return;
7650 
7651 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7652 	 * How far beyond pkt_end it goes is unknown.
7653 	 * if (!range_open) it's the case of pkt >= pkt_end
7654 	 * if (range_open) it's the case of pkt > pkt_end
7655 	 * hence this pointer is at least 1 byte bigger than pkt_end
7656 	 */
7657 	if (range_open)
7658 		reg->range = BEYOND_PKT_END;
7659 	else
7660 		reg->range = AT_PKT_END;
7661 }
7662 
7663 /* The pointer with the specified id has released its reference to kernel
7664  * resources. Identify all copies of the same pointer and clear the reference.
7665  */
7666 static int release_reference(struct bpf_verifier_env *env,
7667 			     int ref_obj_id)
7668 {
7669 	struct bpf_func_state *state;
7670 	struct bpf_reg_state *reg;
7671 	int err;
7672 
7673 	err = release_reference_state(cur_func(env), ref_obj_id);
7674 	if (err)
7675 		return err;
7676 
7677 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7678 		if (reg->ref_obj_id == ref_obj_id)
7679 			mark_reg_invalid(env, reg);
7680 	}));
7681 
7682 	return 0;
7683 }
7684 
7685 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
7686 {
7687 	struct bpf_func_state *unused;
7688 	struct bpf_reg_state *reg;
7689 
7690 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
7691 		if (type_is_non_owning_ref(reg->type))
7692 			mark_reg_invalid(env, reg);
7693 	}));
7694 }
7695 
7696 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7697 				    struct bpf_reg_state *regs)
7698 {
7699 	int i;
7700 
7701 	/* after the call registers r0 - r5 were scratched */
7702 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7703 		mark_reg_not_init(env, regs, caller_saved[i]);
7704 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7705 	}
7706 }
7707 
7708 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7709 				   struct bpf_func_state *caller,
7710 				   struct bpf_func_state *callee,
7711 				   int insn_idx);
7712 
7713 static int set_callee_state(struct bpf_verifier_env *env,
7714 			    struct bpf_func_state *caller,
7715 			    struct bpf_func_state *callee, int insn_idx);
7716 
7717 static bool is_callback_calling_kfunc(u32 btf_id);
7718 
7719 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7720 			     int *insn_idx, int subprog,
7721 			     set_callee_state_fn set_callee_state_cb)
7722 {
7723 	struct bpf_verifier_state *state = env->cur_state;
7724 	struct bpf_func_info_aux *func_info_aux;
7725 	struct bpf_func_state *caller, *callee;
7726 	int err;
7727 	bool is_global = false;
7728 
7729 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7730 		verbose(env, "the call stack of %d frames is too deep\n",
7731 			state->curframe + 2);
7732 		return -E2BIG;
7733 	}
7734 
7735 	caller = state->frame[state->curframe];
7736 	if (state->frame[state->curframe + 1]) {
7737 		verbose(env, "verifier bug. Frame %d already allocated\n",
7738 			state->curframe + 1);
7739 		return -EFAULT;
7740 	}
7741 
7742 	func_info_aux = env->prog->aux->func_info_aux;
7743 	if (func_info_aux)
7744 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7745 	err = btf_check_subprog_call(env, subprog, caller->regs);
7746 	if (err == -EFAULT)
7747 		return err;
7748 	if (is_global) {
7749 		if (err) {
7750 			verbose(env, "Caller passes invalid args into func#%d\n",
7751 				subprog);
7752 			return err;
7753 		} else {
7754 			if (env->log.level & BPF_LOG_LEVEL)
7755 				verbose(env,
7756 					"Func#%d is global and valid. Skipping.\n",
7757 					subprog);
7758 			clear_caller_saved_regs(env, caller->regs);
7759 
7760 			/* All global functions return a 64-bit SCALAR_VALUE */
7761 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7762 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7763 
7764 			/* continue with next insn after call */
7765 			return 0;
7766 		}
7767 	}
7768 
7769 	/* set_callee_state is used for direct subprog calls, but we are
7770 	 * interested in validating only BPF helpers that can call subprogs as
7771 	 * callbacks
7772 	 */
7773 	if (set_callee_state_cb != set_callee_state) {
7774 		if (bpf_pseudo_kfunc_call(insn) &&
7775 		    !is_callback_calling_kfunc(insn->imm)) {
7776 			verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
7777 				func_id_name(insn->imm), insn->imm);
7778 			return -EFAULT;
7779 		} else if (!bpf_pseudo_kfunc_call(insn) &&
7780 			   !is_callback_calling_function(insn->imm)) { /* helper */
7781 			verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
7782 				func_id_name(insn->imm), insn->imm);
7783 			return -EFAULT;
7784 		}
7785 	}
7786 
7787 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7788 	    insn->src_reg == 0 &&
7789 	    insn->imm == BPF_FUNC_timer_set_callback) {
7790 		struct bpf_verifier_state *async_cb;
7791 
7792 		/* there is no real recursion here. timer callbacks are async */
7793 		env->subprog_info[subprog].is_async_cb = true;
7794 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7795 					 *insn_idx, subprog);
7796 		if (!async_cb)
7797 			return -EFAULT;
7798 		callee = async_cb->frame[0];
7799 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7800 
7801 		/* Convert bpf_timer_set_callback() args into timer callback args */
7802 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7803 		if (err)
7804 			return err;
7805 
7806 		clear_caller_saved_regs(env, caller->regs);
7807 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7808 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7809 		/* continue with next insn after call */
7810 		return 0;
7811 	}
7812 
7813 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7814 	if (!callee)
7815 		return -ENOMEM;
7816 	state->frame[state->curframe + 1] = callee;
7817 
7818 	/* callee cannot access r0, r6 - r9 for reading and has to write
7819 	 * into its own stack before reading from it.
7820 	 * callee can read/write into caller's stack
7821 	 */
7822 	init_func_state(env, callee,
7823 			/* remember the callsite, it will be used by bpf_exit */
7824 			*insn_idx /* callsite */,
7825 			state->curframe + 1 /* frameno within this callchain */,
7826 			subprog /* subprog number within this prog */);
7827 
7828 	/* Transfer references to the callee */
7829 	err = copy_reference_state(callee, caller);
7830 	if (err)
7831 		goto err_out;
7832 
7833 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7834 	if (err)
7835 		goto err_out;
7836 
7837 	clear_caller_saved_regs(env, caller->regs);
7838 
7839 	/* only increment it after check_reg_arg() finished */
7840 	state->curframe++;
7841 
7842 	/* and go analyze first insn of the callee */
7843 	*insn_idx = env->subprog_info[subprog].start - 1;
7844 
7845 	if (env->log.level & BPF_LOG_LEVEL) {
7846 		verbose(env, "caller:\n");
7847 		print_verifier_state(env, caller, true);
7848 		verbose(env, "callee:\n");
7849 		print_verifier_state(env, callee, true);
7850 	}
7851 	return 0;
7852 
7853 err_out:
7854 	free_func_state(callee);
7855 	state->frame[state->curframe + 1] = NULL;
7856 	return err;
7857 }
7858 
7859 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7860 				   struct bpf_func_state *caller,
7861 				   struct bpf_func_state *callee)
7862 {
7863 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7864 	 *      void *callback_ctx, u64 flags);
7865 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7866 	 *      void *callback_ctx);
7867 	 */
7868 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7869 
7870 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7871 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7872 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7873 
7874 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7875 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7876 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7877 
7878 	/* pointer to stack or null */
7879 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7880 
7881 	/* unused */
7882 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7883 	return 0;
7884 }
7885 
7886 static int set_callee_state(struct bpf_verifier_env *env,
7887 			    struct bpf_func_state *caller,
7888 			    struct bpf_func_state *callee, int insn_idx)
7889 {
7890 	int i;
7891 
7892 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7893 	 * pointers, which connects us up to the liveness chain
7894 	 */
7895 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7896 		callee->regs[i] = caller->regs[i];
7897 	return 0;
7898 }
7899 
7900 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7901 			   int *insn_idx)
7902 {
7903 	int subprog, target_insn;
7904 
7905 	target_insn = *insn_idx + insn->imm + 1;
7906 	subprog = find_subprog(env, target_insn);
7907 	if (subprog < 0) {
7908 		verbose(env, "verifier bug. No program starts at insn %d\n",
7909 			target_insn);
7910 		return -EFAULT;
7911 	}
7912 
7913 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7914 }
7915 
7916 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7917 				       struct bpf_func_state *caller,
7918 				       struct bpf_func_state *callee,
7919 				       int insn_idx)
7920 {
7921 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7922 	struct bpf_map *map;
7923 	int err;
7924 
7925 	if (bpf_map_ptr_poisoned(insn_aux)) {
7926 		verbose(env, "tail_call abusing map_ptr\n");
7927 		return -EINVAL;
7928 	}
7929 
7930 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7931 	if (!map->ops->map_set_for_each_callback_args ||
7932 	    !map->ops->map_for_each_callback) {
7933 		verbose(env, "callback function not allowed for map\n");
7934 		return -ENOTSUPP;
7935 	}
7936 
7937 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7938 	if (err)
7939 		return err;
7940 
7941 	callee->in_callback_fn = true;
7942 	callee->callback_ret_range = tnum_range(0, 1);
7943 	return 0;
7944 }
7945 
7946 static int set_loop_callback_state(struct bpf_verifier_env *env,
7947 				   struct bpf_func_state *caller,
7948 				   struct bpf_func_state *callee,
7949 				   int insn_idx)
7950 {
7951 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7952 	 *	    u64 flags);
7953 	 * callback_fn(u32 index, void *callback_ctx);
7954 	 */
7955 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7956 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7957 
7958 	/* unused */
7959 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7960 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7961 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7962 
7963 	callee->in_callback_fn = true;
7964 	callee->callback_ret_range = tnum_range(0, 1);
7965 	return 0;
7966 }
7967 
7968 static int set_timer_callback_state(struct bpf_verifier_env *env,
7969 				    struct bpf_func_state *caller,
7970 				    struct bpf_func_state *callee,
7971 				    int insn_idx)
7972 {
7973 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7974 
7975 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7976 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7977 	 */
7978 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7979 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7980 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7981 
7982 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7983 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7984 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7985 
7986 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7987 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7988 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7989 
7990 	/* unused */
7991 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7992 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7993 	callee->in_async_callback_fn = true;
7994 	callee->callback_ret_range = tnum_range(0, 1);
7995 	return 0;
7996 }
7997 
7998 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7999 				       struct bpf_func_state *caller,
8000 				       struct bpf_func_state *callee,
8001 				       int insn_idx)
8002 {
8003 	/* bpf_find_vma(struct task_struct *task, u64 addr,
8004 	 *               void *callback_fn, void *callback_ctx, u64 flags)
8005 	 * (callback_fn)(struct task_struct *task,
8006 	 *               struct vm_area_struct *vma, void *callback_ctx);
8007 	 */
8008 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8009 
8010 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8011 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8012 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8013 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8014 
8015 	/* pointer to stack or null */
8016 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8017 
8018 	/* unused */
8019 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8020 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8021 	callee->in_callback_fn = true;
8022 	callee->callback_ret_range = tnum_range(0, 1);
8023 	return 0;
8024 }
8025 
8026 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8027 					   struct bpf_func_state *caller,
8028 					   struct bpf_func_state *callee,
8029 					   int insn_idx)
8030 {
8031 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8032 	 *			  callback_ctx, u64 flags);
8033 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8034 	 */
8035 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8036 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8037 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8038 
8039 	/* unused */
8040 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8041 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8042 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8043 
8044 	callee->in_callback_fn = true;
8045 	callee->callback_ret_range = tnum_range(0, 1);
8046 	return 0;
8047 }
8048 
8049 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8050 					 struct bpf_func_state *caller,
8051 					 struct bpf_func_state *callee,
8052 					 int insn_idx)
8053 {
8054 	/* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8055 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8056 	 *
8057 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8058 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8059 	 * by this point, so look at 'root'
8060 	 */
8061 	struct btf_field *field;
8062 
8063 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8064 				      BPF_RB_ROOT);
8065 	if (!field || !field->graph_root.value_btf_id)
8066 		return -EFAULT;
8067 
8068 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8069 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8070 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8071 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8072 
8073 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8074 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8075 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8076 	callee->in_callback_fn = true;
8077 	callee->callback_ret_range = tnum_range(0, 1);
8078 	return 0;
8079 }
8080 
8081 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8082 
8083 /* Are we currently verifying the callback for a rbtree helper that must
8084  * be called with lock held? If so, no need to complain about unreleased
8085  * lock
8086  */
8087 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8088 {
8089 	struct bpf_verifier_state *state = env->cur_state;
8090 	struct bpf_insn *insn = env->prog->insnsi;
8091 	struct bpf_func_state *callee;
8092 	int kfunc_btf_id;
8093 
8094 	if (!state->curframe)
8095 		return false;
8096 
8097 	callee = state->frame[state->curframe];
8098 
8099 	if (!callee->in_callback_fn)
8100 		return false;
8101 
8102 	kfunc_btf_id = insn[callee->callsite].imm;
8103 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8104 }
8105 
8106 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8107 {
8108 	struct bpf_verifier_state *state = env->cur_state;
8109 	struct bpf_func_state *caller, *callee;
8110 	struct bpf_reg_state *r0;
8111 	int err;
8112 
8113 	callee = state->frame[state->curframe];
8114 	r0 = &callee->regs[BPF_REG_0];
8115 	if (r0->type == PTR_TO_STACK) {
8116 		/* technically it's ok to return caller's stack pointer
8117 		 * (or caller's caller's pointer) back to the caller,
8118 		 * since these pointers are valid. Only current stack
8119 		 * pointer will be invalid as soon as function exits,
8120 		 * but let's be conservative
8121 		 */
8122 		verbose(env, "cannot return stack pointer to the caller\n");
8123 		return -EINVAL;
8124 	}
8125 
8126 	caller = state->frame[state->curframe - 1];
8127 	if (callee->in_callback_fn) {
8128 		/* enforce R0 return value range [0, 1]. */
8129 		struct tnum range = callee->callback_ret_range;
8130 
8131 		if (r0->type != SCALAR_VALUE) {
8132 			verbose(env, "R0 not a scalar value\n");
8133 			return -EACCES;
8134 		}
8135 		if (!tnum_in(range, r0->var_off)) {
8136 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8137 			return -EINVAL;
8138 		}
8139 	} else {
8140 		/* return to the caller whatever r0 had in the callee */
8141 		caller->regs[BPF_REG_0] = *r0;
8142 	}
8143 
8144 	/* callback_fn frame should have released its own additions to parent's
8145 	 * reference state at this point, or check_reference_leak would
8146 	 * complain, hence it must be the same as the caller. There is no need
8147 	 * to copy it back.
8148 	 */
8149 	if (!callee->in_callback_fn) {
8150 		/* Transfer references to the caller */
8151 		err = copy_reference_state(caller, callee);
8152 		if (err)
8153 			return err;
8154 	}
8155 
8156 	*insn_idx = callee->callsite + 1;
8157 	if (env->log.level & BPF_LOG_LEVEL) {
8158 		verbose(env, "returning from callee:\n");
8159 		print_verifier_state(env, callee, true);
8160 		verbose(env, "to caller at %d:\n", *insn_idx);
8161 		print_verifier_state(env, caller, true);
8162 	}
8163 	/* clear everything in the callee */
8164 	free_func_state(callee);
8165 	state->frame[state->curframe--] = NULL;
8166 	return 0;
8167 }
8168 
8169 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8170 				   int func_id,
8171 				   struct bpf_call_arg_meta *meta)
8172 {
8173 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8174 
8175 	if (ret_type != RET_INTEGER ||
8176 	    (func_id != BPF_FUNC_get_stack &&
8177 	     func_id != BPF_FUNC_get_task_stack &&
8178 	     func_id != BPF_FUNC_probe_read_str &&
8179 	     func_id != BPF_FUNC_probe_read_kernel_str &&
8180 	     func_id != BPF_FUNC_probe_read_user_str))
8181 		return;
8182 
8183 	ret_reg->smax_value = meta->msize_max_value;
8184 	ret_reg->s32_max_value = meta->msize_max_value;
8185 	ret_reg->smin_value = -MAX_ERRNO;
8186 	ret_reg->s32_min_value = -MAX_ERRNO;
8187 	reg_bounds_sync(ret_reg);
8188 }
8189 
8190 static int
8191 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8192 		int func_id, int insn_idx)
8193 {
8194 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8195 	struct bpf_map *map = meta->map_ptr;
8196 
8197 	if (func_id != BPF_FUNC_tail_call &&
8198 	    func_id != BPF_FUNC_map_lookup_elem &&
8199 	    func_id != BPF_FUNC_map_update_elem &&
8200 	    func_id != BPF_FUNC_map_delete_elem &&
8201 	    func_id != BPF_FUNC_map_push_elem &&
8202 	    func_id != BPF_FUNC_map_pop_elem &&
8203 	    func_id != BPF_FUNC_map_peek_elem &&
8204 	    func_id != BPF_FUNC_for_each_map_elem &&
8205 	    func_id != BPF_FUNC_redirect_map &&
8206 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
8207 		return 0;
8208 
8209 	if (map == NULL) {
8210 		verbose(env, "kernel subsystem misconfigured verifier\n");
8211 		return -EINVAL;
8212 	}
8213 
8214 	/* In case of read-only, some additional restrictions
8215 	 * need to be applied in order to prevent altering the
8216 	 * state of the map from program side.
8217 	 */
8218 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8219 	    (func_id == BPF_FUNC_map_delete_elem ||
8220 	     func_id == BPF_FUNC_map_update_elem ||
8221 	     func_id == BPF_FUNC_map_push_elem ||
8222 	     func_id == BPF_FUNC_map_pop_elem)) {
8223 		verbose(env, "write into map forbidden\n");
8224 		return -EACCES;
8225 	}
8226 
8227 	if (!BPF_MAP_PTR(aux->map_ptr_state))
8228 		bpf_map_ptr_store(aux, meta->map_ptr,
8229 				  !meta->map_ptr->bypass_spec_v1);
8230 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8231 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8232 				  !meta->map_ptr->bypass_spec_v1);
8233 	return 0;
8234 }
8235 
8236 static int
8237 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8238 		int func_id, int insn_idx)
8239 {
8240 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8241 	struct bpf_reg_state *regs = cur_regs(env), *reg;
8242 	struct bpf_map *map = meta->map_ptr;
8243 	u64 val, max;
8244 	int err;
8245 
8246 	if (func_id != BPF_FUNC_tail_call)
8247 		return 0;
8248 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8249 		verbose(env, "kernel subsystem misconfigured verifier\n");
8250 		return -EINVAL;
8251 	}
8252 
8253 	reg = &regs[BPF_REG_3];
8254 	val = reg->var_off.value;
8255 	max = map->max_entries;
8256 
8257 	if (!(register_is_const(reg) && val < max)) {
8258 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8259 		return 0;
8260 	}
8261 
8262 	err = mark_chain_precision(env, BPF_REG_3);
8263 	if (err)
8264 		return err;
8265 	if (bpf_map_key_unseen(aux))
8266 		bpf_map_key_store(aux, val);
8267 	else if (!bpf_map_key_poisoned(aux) &&
8268 		  bpf_map_key_immediate(aux) != val)
8269 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8270 	return 0;
8271 }
8272 
8273 static int check_reference_leak(struct bpf_verifier_env *env)
8274 {
8275 	struct bpf_func_state *state = cur_func(env);
8276 	bool refs_lingering = false;
8277 	int i;
8278 
8279 	if (state->frameno && !state->in_callback_fn)
8280 		return 0;
8281 
8282 	for (i = 0; i < state->acquired_refs; i++) {
8283 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8284 			continue;
8285 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8286 			state->refs[i].id, state->refs[i].insn_idx);
8287 		refs_lingering = true;
8288 	}
8289 	return refs_lingering ? -EINVAL : 0;
8290 }
8291 
8292 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8293 				   struct bpf_reg_state *regs)
8294 {
8295 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8296 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8297 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
8298 	struct bpf_bprintf_data data = {};
8299 	int err, fmt_map_off, num_args;
8300 	u64 fmt_addr;
8301 	char *fmt;
8302 
8303 	/* data must be an array of u64 */
8304 	if (data_len_reg->var_off.value % 8)
8305 		return -EINVAL;
8306 	num_args = data_len_reg->var_off.value / 8;
8307 
8308 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8309 	 * and map_direct_value_addr is set.
8310 	 */
8311 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8312 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8313 						  fmt_map_off);
8314 	if (err) {
8315 		verbose(env, "verifier bug\n");
8316 		return -EFAULT;
8317 	}
8318 	fmt = (char *)(long)fmt_addr + fmt_map_off;
8319 
8320 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8321 	 * can focus on validating the format specifiers.
8322 	 */
8323 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8324 	if (err < 0)
8325 		verbose(env, "Invalid format string\n");
8326 
8327 	return err;
8328 }
8329 
8330 static int check_get_func_ip(struct bpf_verifier_env *env)
8331 {
8332 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8333 	int func_id = BPF_FUNC_get_func_ip;
8334 
8335 	if (type == BPF_PROG_TYPE_TRACING) {
8336 		if (!bpf_prog_has_trampoline(env->prog)) {
8337 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8338 				func_id_name(func_id), func_id);
8339 			return -ENOTSUPP;
8340 		}
8341 		return 0;
8342 	} else if (type == BPF_PROG_TYPE_KPROBE) {
8343 		return 0;
8344 	}
8345 
8346 	verbose(env, "func %s#%d not supported for program type %d\n",
8347 		func_id_name(func_id), func_id, type);
8348 	return -ENOTSUPP;
8349 }
8350 
8351 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8352 {
8353 	return &env->insn_aux_data[env->insn_idx];
8354 }
8355 
8356 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8357 {
8358 	struct bpf_reg_state *regs = cur_regs(env);
8359 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
8360 	bool reg_is_null = register_is_null(reg);
8361 
8362 	if (reg_is_null)
8363 		mark_chain_precision(env, BPF_REG_4);
8364 
8365 	return reg_is_null;
8366 }
8367 
8368 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8369 {
8370 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8371 
8372 	if (!state->initialized) {
8373 		state->initialized = 1;
8374 		state->fit_for_inline = loop_flag_is_zero(env);
8375 		state->callback_subprogno = subprogno;
8376 		return;
8377 	}
8378 
8379 	if (!state->fit_for_inline)
8380 		return;
8381 
8382 	state->fit_for_inline = (loop_flag_is_zero(env) &&
8383 				 state->callback_subprogno == subprogno);
8384 }
8385 
8386 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8387 			     int *insn_idx_p)
8388 {
8389 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8390 	const struct bpf_func_proto *fn = NULL;
8391 	enum bpf_return_type ret_type;
8392 	enum bpf_type_flag ret_flag;
8393 	struct bpf_reg_state *regs;
8394 	struct bpf_call_arg_meta meta;
8395 	int insn_idx = *insn_idx_p;
8396 	bool changes_data;
8397 	int i, err, func_id;
8398 
8399 	/* find function prototype */
8400 	func_id = insn->imm;
8401 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8402 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8403 			func_id);
8404 		return -EINVAL;
8405 	}
8406 
8407 	if (env->ops->get_func_proto)
8408 		fn = env->ops->get_func_proto(func_id, env->prog);
8409 	if (!fn) {
8410 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8411 			func_id);
8412 		return -EINVAL;
8413 	}
8414 
8415 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
8416 	if (!env->prog->gpl_compatible && fn->gpl_only) {
8417 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8418 		return -EINVAL;
8419 	}
8420 
8421 	if (fn->allowed && !fn->allowed(env->prog)) {
8422 		verbose(env, "helper call is not allowed in probe\n");
8423 		return -EINVAL;
8424 	}
8425 
8426 	if (!env->prog->aux->sleepable && fn->might_sleep) {
8427 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
8428 		return -EINVAL;
8429 	}
8430 
8431 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
8432 	changes_data = bpf_helper_changes_pkt_data(fn->func);
8433 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8434 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8435 			func_id_name(func_id), func_id);
8436 		return -EINVAL;
8437 	}
8438 
8439 	memset(&meta, 0, sizeof(meta));
8440 	meta.pkt_access = fn->pkt_access;
8441 
8442 	err = check_func_proto(fn, func_id);
8443 	if (err) {
8444 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8445 			func_id_name(func_id), func_id);
8446 		return err;
8447 	}
8448 
8449 	if (env->cur_state->active_rcu_lock) {
8450 		if (fn->might_sleep) {
8451 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8452 				func_id_name(func_id), func_id);
8453 			return -EINVAL;
8454 		}
8455 
8456 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8457 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8458 	}
8459 
8460 	meta.func_id = func_id;
8461 	/* check args */
8462 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8463 		err = check_func_arg(env, i, &meta, fn, insn_idx);
8464 		if (err)
8465 			return err;
8466 	}
8467 
8468 	err = record_func_map(env, &meta, func_id, insn_idx);
8469 	if (err)
8470 		return err;
8471 
8472 	err = record_func_key(env, &meta, func_id, insn_idx);
8473 	if (err)
8474 		return err;
8475 
8476 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
8477 	 * is inferred from register state.
8478 	 */
8479 	for (i = 0; i < meta.access_size; i++) {
8480 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8481 				       BPF_WRITE, -1, false);
8482 		if (err)
8483 			return err;
8484 	}
8485 
8486 	regs = cur_regs(env);
8487 
8488 	if (meta.release_regno) {
8489 		err = -EINVAL;
8490 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8491 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8492 		 * is safe to do directly.
8493 		 */
8494 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8495 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8496 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8497 				return -EFAULT;
8498 			}
8499 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8500 		} else if (meta.ref_obj_id) {
8501 			err = release_reference(env, meta.ref_obj_id);
8502 		} else if (register_is_null(&regs[meta.release_regno])) {
8503 			/* meta.ref_obj_id can only be 0 if register that is meant to be
8504 			 * released is NULL, which must be > R0.
8505 			 */
8506 			err = 0;
8507 		}
8508 		if (err) {
8509 			verbose(env, "func %s#%d reference has not been acquired before\n",
8510 				func_id_name(func_id), func_id);
8511 			return err;
8512 		}
8513 	}
8514 
8515 	switch (func_id) {
8516 	case BPF_FUNC_tail_call:
8517 		err = check_reference_leak(env);
8518 		if (err) {
8519 			verbose(env, "tail_call would lead to reference leak\n");
8520 			return err;
8521 		}
8522 		break;
8523 	case BPF_FUNC_get_local_storage:
8524 		/* check that flags argument in get_local_storage(map, flags) is 0,
8525 		 * this is required because get_local_storage() can't return an error.
8526 		 */
8527 		if (!register_is_null(&regs[BPF_REG_2])) {
8528 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8529 			return -EINVAL;
8530 		}
8531 		break;
8532 	case BPF_FUNC_for_each_map_elem:
8533 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8534 					set_map_elem_callback_state);
8535 		break;
8536 	case BPF_FUNC_timer_set_callback:
8537 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8538 					set_timer_callback_state);
8539 		break;
8540 	case BPF_FUNC_find_vma:
8541 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8542 					set_find_vma_callback_state);
8543 		break;
8544 	case BPF_FUNC_snprintf:
8545 		err = check_bpf_snprintf_call(env, regs);
8546 		break;
8547 	case BPF_FUNC_loop:
8548 		update_loop_inline_state(env, meta.subprogno);
8549 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8550 					set_loop_callback_state);
8551 		break;
8552 	case BPF_FUNC_dynptr_from_mem:
8553 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8554 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8555 				reg_type_str(env, regs[BPF_REG_1].type));
8556 			return -EACCES;
8557 		}
8558 		break;
8559 	case BPF_FUNC_set_retval:
8560 		if (prog_type == BPF_PROG_TYPE_LSM &&
8561 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8562 			if (!env->prog->aux->attach_func_proto->type) {
8563 				/* Make sure programs that attach to void
8564 				 * hooks don't try to modify return value.
8565 				 */
8566 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8567 				return -EINVAL;
8568 			}
8569 		}
8570 		break;
8571 	case BPF_FUNC_dynptr_data:
8572 	{
8573 		struct bpf_reg_state *reg;
8574 		int id, ref_obj_id;
8575 
8576 		reg = get_dynptr_arg_reg(env, fn, regs);
8577 		if (!reg)
8578 			return -EFAULT;
8579 
8580 
8581 		if (meta.dynptr_id) {
8582 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8583 			return -EFAULT;
8584 		}
8585 		if (meta.ref_obj_id) {
8586 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8587 			return -EFAULT;
8588 		}
8589 
8590 		id = dynptr_id(env, reg);
8591 		if (id < 0) {
8592 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8593 			return id;
8594 		}
8595 
8596 		ref_obj_id = dynptr_ref_obj_id(env, reg);
8597 		if (ref_obj_id < 0) {
8598 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8599 			return ref_obj_id;
8600 		}
8601 
8602 		meta.dynptr_id = id;
8603 		meta.ref_obj_id = ref_obj_id;
8604 
8605 		break;
8606 	}
8607 	case BPF_FUNC_dynptr_write:
8608 	{
8609 		enum bpf_dynptr_type dynptr_type;
8610 		struct bpf_reg_state *reg;
8611 
8612 		reg = get_dynptr_arg_reg(env, fn, regs);
8613 		if (!reg)
8614 			return -EFAULT;
8615 
8616 		dynptr_type = dynptr_get_type(env, reg);
8617 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
8618 			return -EFAULT;
8619 
8620 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
8621 			/* this will trigger clear_all_pkt_pointers(), which will
8622 			 * invalidate all dynptr slices associated with the skb
8623 			 */
8624 			changes_data = true;
8625 
8626 		break;
8627 	}
8628 	case BPF_FUNC_user_ringbuf_drain:
8629 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8630 					set_user_ringbuf_callback_state);
8631 		break;
8632 	}
8633 
8634 	if (err)
8635 		return err;
8636 
8637 	/* reset caller saved regs */
8638 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8639 		mark_reg_not_init(env, regs, caller_saved[i]);
8640 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8641 	}
8642 
8643 	/* helper call returns 64-bit value. */
8644 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8645 
8646 	/* update return register (already marked as written above) */
8647 	ret_type = fn->ret_type;
8648 	ret_flag = type_flag(ret_type);
8649 
8650 	switch (base_type(ret_type)) {
8651 	case RET_INTEGER:
8652 		/* sets type to SCALAR_VALUE */
8653 		mark_reg_unknown(env, regs, BPF_REG_0);
8654 		break;
8655 	case RET_VOID:
8656 		regs[BPF_REG_0].type = NOT_INIT;
8657 		break;
8658 	case RET_PTR_TO_MAP_VALUE:
8659 		/* There is no offset yet applied, variable or fixed */
8660 		mark_reg_known_zero(env, regs, BPF_REG_0);
8661 		/* remember map_ptr, so that check_map_access()
8662 		 * can check 'value_size' boundary of memory access
8663 		 * to map element returned from bpf_map_lookup_elem()
8664 		 */
8665 		if (meta.map_ptr == NULL) {
8666 			verbose(env,
8667 				"kernel subsystem misconfigured verifier\n");
8668 			return -EINVAL;
8669 		}
8670 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
8671 		regs[BPF_REG_0].map_uid = meta.map_uid;
8672 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8673 		if (!type_may_be_null(ret_type) &&
8674 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8675 			regs[BPF_REG_0].id = ++env->id_gen;
8676 		}
8677 		break;
8678 	case RET_PTR_TO_SOCKET:
8679 		mark_reg_known_zero(env, regs, BPF_REG_0);
8680 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8681 		break;
8682 	case RET_PTR_TO_SOCK_COMMON:
8683 		mark_reg_known_zero(env, regs, BPF_REG_0);
8684 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8685 		break;
8686 	case RET_PTR_TO_TCP_SOCK:
8687 		mark_reg_known_zero(env, regs, BPF_REG_0);
8688 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8689 		break;
8690 	case RET_PTR_TO_MEM:
8691 		mark_reg_known_zero(env, regs, BPF_REG_0);
8692 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8693 		regs[BPF_REG_0].mem_size = meta.mem_size;
8694 		break;
8695 	case RET_PTR_TO_MEM_OR_BTF_ID:
8696 	{
8697 		const struct btf_type *t;
8698 
8699 		mark_reg_known_zero(env, regs, BPF_REG_0);
8700 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8701 		if (!btf_type_is_struct(t)) {
8702 			u32 tsize;
8703 			const struct btf_type *ret;
8704 			const char *tname;
8705 
8706 			/* resolve the type size of ksym. */
8707 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8708 			if (IS_ERR(ret)) {
8709 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8710 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8711 					tname, PTR_ERR(ret));
8712 				return -EINVAL;
8713 			}
8714 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8715 			regs[BPF_REG_0].mem_size = tsize;
8716 		} else {
8717 			/* MEM_RDONLY may be carried from ret_flag, but it
8718 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8719 			 * it will confuse the check of PTR_TO_BTF_ID in
8720 			 * check_mem_access().
8721 			 */
8722 			ret_flag &= ~MEM_RDONLY;
8723 
8724 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8725 			regs[BPF_REG_0].btf = meta.ret_btf;
8726 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8727 		}
8728 		break;
8729 	}
8730 	case RET_PTR_TO_BTF_ID:
8731 	{
8732 		struct btf *ret_btf;
8733 		int ret_btf_id;
8734 
8735 		mark_reg_known_zero(env, regs, BPF_REG_0);
8736 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8737 		if (func_id == BPF_FUNC_kptr_xchg) {
8738 			ret_btf = meta.kptr_field->kptr.btf;
8739 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8740 		} else {
8741 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8742 				verbose(env, "verifier internal error:");
8743 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8744 					func_id_name(func_id));
8745 				return -EINVAL;
8746 			}
8747 			ret_btf = btf_vmlinux;
8748 			ret_btf_id = *fn->ret_btf_id;
8749 		}
8750 		if (ret_btf_id == 0) {
8751 			verbose(env, "invalid return type %u of func %s#%d\n",
8752 				base_type(ret_type), func_id_name(func_id),
8753 				func_id);
8754 			return -EINVAL;
8755 		}
8756 		regs[BPF_REG_0].btf = ret_btf;
8757 		regs[BPF_REG_0].btf_id = ret_btf_id;
8758 		break;
8759 	}
8760 	default:
8761 		verbose(env, "unknown return type %u of func %s#%d\n",
8762 			base_type(ret_type), func_id_name(func_id), func_id);
8763 		return -EINVAL;
8764 	}
8765 
8766 	if (type_may_be_null(regs[BPF_REG_0].type))
8767 		regs[BPF_REG_0].id = ++env->id_gen;
8768 
8769 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8770 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8771 			func_id_name(func_id), func_id);
8772 		return -EFAULT;
8773 	}
8774 
8775 	if (is_dynptr_ref_function(func_id))
8776 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8777 
8778 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8779 		/* For release_reference() */
8780 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8781 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8782 		int id = acquire_reference_state(env, insn_idx);
8783 
8784 		if (id < 0)
8785 			return id;
8786 		/* For mark_ptr_or_null_reg() */
8787 		regs[BPF_REG_0].id = id;
8788 		/* For release_reference() */
8789 		regs[BPF_REG_0].ref_obj_id = id;
8790 	}
8791 
8792 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8793 
8794 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8795 	if (err)
8796 		return err;
8797 
8798 	if ((func_id == BPF_FUNC_get_stack ||
8799 	     func_id == BPF_FUNC_get_task_stack) &&
8800 	    !env->prog->has_callchain_buf) {
8801 		const char *err_str;
8802 
8803 #ifdef CONFIG_PERF_EVENTS
8804 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8805 		err_str = "cannot get callchain buffer for func %s#%d\n";
8806 #else
8807 		err = -ENOTSUPP;
8808 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8809 #endif
8810 		if (err) {
8811 			verbose(env, err_str, func_id_name(func_id), func_id);
8812 			return err;
8813 		}
8814 
8815 		env->prog->has_callchain_buf = true;
8816 	}
8817 
8818 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8819 		env->prog->call_get_stack = true;
8820 
8821 	if (func_id == BPF_FUNC_get_func_ip) {
8822 		if (check_get_func_ip(env))
8823 			return -ENOTSUPP;
8824 		env->prog->call_get_func_ip = true;
8825 	}
8826 
8827 	if (changes_data)
8828 		clear_all_pkt_pointers(env);
8829 	return 0;
8830 }
8831 
8832 /* mark_btf_func_reg_size() is used when the reg size is determined by
8833  * the BTF func_proto's return value size and argument.
8834  */
8835 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8836 				   size_t reg_size)
8837 {
8838 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8839 
8840 	if (regno == BPF_REG_0) {
8841 		/* Function return value */
8842 		reg->live |= REG_LIVE_WRITTEN;
8843 		reg->subreg_def = reg_size == sizeof(u64) ?
8844 			DEF_NOT_SUBREG : env->insn_idx + 1;
8845 	} else {
8846 		/* Function argument */
8847 		if (reg_size == sizeof(u64)) {
8848 			mark_insn_zext(env, reg);
8849 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8850 		} else {
8851 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8852 		}
8853 	}
8854 }
8855 
8856 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8857 {
8858 	return meta->kfunc_flags & KF_ACQUIRE;
8859 }
8860 
8861 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8862 {
8863 	return meta->kfunc_flags & KF_RET_NULL;
8864 }
8865 
8866 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8867 {
8868 	return meta->kfunc_flags & KF_RELEASE;
8869 }
8870 
8871 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8872 {
8873 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8874 }
8875 
8876 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8877 {
8878 	return meta->kfunc_flags & KF_SLEEPABLE;
8879 }
8880 
8881 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8882 {
8883 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8884 }
8885 
8886 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8887 {
8888 	return meta->kfunc_flags & KF_RCU;
8889 }
8890 
8891 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8892 {
8893 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8894 }
8895 
8896 static bool __kfunc_param_match_suffix(const struct btf *btf,
8897 				       const struct btf_param *arg,
8898 				       const char *suffix)
8899 {
8900 	int suffix_len = strlen(suffix), len;
8901 	const char *param_name;
8902 
8903 	/* In the future, this can be ported to use BTF tagging */
8904 	param_name = btf_name_by_offset(btf, arg->name_off);
8905 	if (str_is_empty(param_name))
8906 		return false;
8907 	len = strlen(param_name);
8908 	if (len < suffix_len)
8909 		return false;
8910 	param_name += len - suffix_len;
8911 	return !strncmp(param_name, suffix, suffix_len);
8912 }
8913 
8914 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8915 				  const struct btf_param *arg,
8916 				  const struct bpf_reg_state *reg)
8917 {
8918 	const struct btf_type *t;
8919 
8920 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8921 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8922 		return false;
8923 
8924 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8925 }
8926 
8927 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
8928 					const struct btf_param *arg,
8929 					const struct bpf_reg_state *reg)
8930 {
8931 	const struct btf_type *t;
8932 
8933 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8934 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8935 		return false;
8936 
8937 	return __kfunc_param_match_suffix(btf, arg, "__szk");
8938 }
8939 
8940 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8941 {
8942 	return __kfunc_param_match_suffix(btf, arg, "__k");
8943 }
8944 
8945 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8946 {
8947 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8948 }
8949 
8950 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8951 {
8952 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8953 }
8954 
8955 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
8956 {
8957 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
8958 }
8959 
8960 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8961 					  const struct btf_param *arg,
8962 					  const char *name)
8963 {
8964 	int len, target_len = strlen(name);
8965 	const char *param_name;
8966 
8967 	param_name = btf_name_by_offset(btf, arg->name_off);
8968 	if (str_is_empty(param_name))
8969 		return false;
8970 	len = strlen(param_name);
8971 	if (len != target_len)
8972 		return false;
8973 	if (strcmp(param_name, name))
8974 		return false;
8975 
8976 	return true;
8977 }
8978 
8979 enum {
8980 	KF_ARG_DYNPTR_ID,
8981 	KF_ARG_LIST_HEAD_ID,
8982 	KF_ARG_LIST_NODE_ID,
8983 	KF_ARG_RB_ROOT_ID,
8984 	KF_ARG_RB_NODE_ID,
8985 };
8986 
8987 BTF_ID_LIST(kf_arg_btf_ids)
8988 BTF_ID(struct, bpf_dynptr_kern)
8989 BTF_ID(struct, bpf_list_head)
8990 BTF_ID(struct, bpf_list_node)
8991 BTF_ID(struct, bpf_rb_root)
8992 BTF_ID(struct, bpf_rb_node)
8993 
8994 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8995 				    const struct btf_param *arg, int type)
8996 {
8997 	const struct btf_type *t;
8998 	u32 res_id;
8999 
9000 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9001 	if (!t)
9002 		return false;
9003 	if (!btf_type_is_ptr(t))
9004 		return false;
9005 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
9006 	if (!t)
9007 		return false;
9008 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9009 }
9010 
9011 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9012 {
9013 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9014 }
9015 
9016 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9017 {
9018 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9019 }
9020 
9021 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9022 {
9023 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9024 }
9025 
9026 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9027 {
9028 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9029 }
9030 
9031 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9032 {
9033 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9034 }
9035 
9036 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9037 				  const struct btf_param *arg)
9038 {
9039 	const struct btf_type *t;
9040 
9041 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9042 	if (!t)
9043 		return false;
9044 
9045 	return true;
9046 }
9047 
9048 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9049 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9050 					const struct btf *btf,
9051 					const struct btf_type *t, int rec)
9052 {
9053 	const struct btf_type *member_type;
9054 	const struct btf_member *member;
9055 	u32 i;
9056 
9057 	if (!btf_type_is_struct(t))
9058 		return false;
9059 
9060 	for_each_member(i, t, member) {
9061 		const struct btf_array *array;
9062 
9063 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9064 		if (btf_type_is_struct(member_type)) {
9065 			if (rec >= 3) {
9066 				verbose(env, "max struct nesting depth exceeded\n");
9067 				return false;
9068 			}
9069 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9070 				return false;
9071 			continue;
9072 		}
9073 		if (btf_type_is_array(member_type)) {
9074 			array = btf_array(member_type);
9075 			if (!array->nelems)
9076 				return false;
9077 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9078 			if (!btf_type_is_scalar(member_type))
9079 				return false;
9080 			continue;
9081 		}
9082 		if (!btf_type_is_scalar(member_type))
9083 			return false;
9084 	}
9085 	return true;
9086 }
9087 
9088 
9089 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9090 #ifdef CONFIG_NET
9091 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9092 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9093 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9094 #endif
9095 };
9096 
9097 enum kfunc_ptr_arg_type {
9098 	KF_ARG_PTR_TO_CTX,
9099 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
9100 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
9101 	KF_ARG_PTR_TO_DYNPTR,
9102 	KF_ARG_PTR_TO_LIST_HEAD,
9103 	KF_ARG_PTR_TO_LIST_NODE,
9104 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
9105 	KF_ARG_PTR_TO_MEM,
9106 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
9107 	KF_ARG_PTR_TO_CALLBACK,
9108 	KF_ARG_PTR_TO_RB_ROOT,
9109 	KF_ARG_PTR_TO_RB_NODE,
9110 };
9111 
9112 enum special_kfunc_type {
9113 	KF_bpf_obj_new_impl,
9114 	KF_bpf_obj_drop_impl,
9115 	KF_bpf_list_push_front,
9116 	KF_bpf_list_push_back,
9117 	KF_bpf_list_pop_front,
9118 	KF_bpf_list_pop_back,
9119 	KF_bpf_cast_to_kern_ctx,
9120 	KF_bpf_rdonly_cast,
9121 	KF_bpf_rcu_read_lock,
9122 	KF_bpf_rcu_read_unlock,
9123 	KF_bpf_rbtree_remove,
9124 	KF_bpf_rbtree_add,
9125 	KF_bpf_rbtree_first,
9126 	KF_bpf_dynptr_from_skb,
9127 	KF_bpf_dynptr_from_xdp,
9128 	KF_bpf_dynptr_slice,
9129 	KF_bpf_dynptr_slice_rdwr,
9130 };
9131 
9132 BTF_SET_START(special_kfunc_set)
9133 BTF_ID(func, bpf_obj_new_impl)
9134 BTF_ID(func, bpf_obj_drop_impl)
9135 BTF_ID(func, bpf_list_push_front)
9136 BTF_ID(func, bpf_list_push_back)
9137 BTF_ID(func, bpf_list_pop_front)
9138 BTF_ID(func, bpf_list_pop_back)
9139 BTF_ID(func, bpf_cast_to_kern_ctx)
9140 BTF_ID(func, bpf_rdonly_cast)
9141 BTF_ID(func, bpf_rbtree_remove)
9142 BTF_ID(func, bpf_rbtree_add)
9143 BTF_ID(func, bpf_rbtree_first)
9144 BTF_ID(func, bpf_dynptr_from_skb)
9145 BTF_ID(func, bpf_dynptr_from_xdp)
9146 BTF_ID(func, bpf_dynptr_slice)
9147 BTF_ID(func, bpf_dynptr_slice_rdwr)
9148 BTF_SET_END(special_kfunc_set)
9149 
9150 BTF_ID_LIST(special_kfunc_list)
9151 BTF_ID(func, bpf_obj_new_impl)
9152 BTF_ID(func, bpf_obj_drop_impl)
9153 BTF_ID(func, bpf_list_push_front)
9154 BTF_ID(func, bpf_list_push_back)
9155 BTF_ID(func, bpf_list_pop_front)
9156 BTF_ID(func, bpf_list_pop_back)
9157 BTF_ID(func, bpf_cast_to_kern_ctx)
9158 BTF_ID(func, bpf_rdonly_cast)
9159 BTF_ID(func, bpf_rcu_read_lock)
9160 BTF_ID(func, bpf_rcu_read_unlock)
9161 BTF_ID(func, bpf_rbtree_remove)
9162 BTF_ID(func, bpf_rbtree_add)
9163 BTF_ID(func, bpf_rbtree_first)
9164 BTF_ID(func, bpf_dynptr_from_skb)
9165 BTF_ID(func, bpf_dynptr_from_xdp)
9166 BTF_ID(func, bpf_dynptr_slice)
9167 BTF_ID(func, bpf_dynptr_slice_rdwr)
9168 
9169 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9170 {
9171 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9172 }
9173 
9174 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9175 {
9176 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9177 }
9178 
9179 static enum kfunc_ptr_arg_type
9180 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9181 		       struct bpf_kfunc_call_arg_meta *meta,
9182 		       const struct btf_type *t, const struct btf_type *ref_t,
9183 		       const char *ref_tname, const struct btf_param *args,
9184 		       int argno, int nargs)
9185 {
9186 	u32 regno = argno + 1;
9187 	struct bpf_reg_state *regs = cur_regs(env);
9188 	struct bpf_reg_state *reg = &regs[regno];
9189 	bool arg_mem_size = false;
9190 
9191 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9192 		return KF_ARG_PTR_TO_CTX;
9193 
9194 	/* In this function, we verify the kfunc's BTF as per the argument type,
9195 	 * leaving the rest of the verification with respect to the register
9196 	 * type to our caller. When a set of conditions hold in the BTF type of
9197 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
9198 	 */
9199 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9200 		return KF_ARG_PTR_TO_CTX;
9201 
9202 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9203 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9204 
9205 	if (is_kfunc_arg_kptr_get(meta, argno)) {
9206 		if (!btf_type_is_ptr(ref_t)) {
9207 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9208 			return -EINVAL;
9209 		}
9210 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
9211 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9212 		if (!btf_type_is_struct(ref_t)) {
9213 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9214 				meta->func_name, btf_type_str(ref_t), ref_tname);
9215 			return -EINVAL;
9216 		}
9217 		return KF_ARG_PTR_TO_KPTR;
9218 	}
9219 
9220 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9221 		return KF_ARG_PTR_TO_DYNPTR;
9222 
9223 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9224 		return KF_ARG_PTR_TO_LIST_HEAD;
9225 
9226 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9227 		return KF_ARG_PTR_TO_LIST_NODE;
9228 
9229 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9230 		return KF_ARG_PTR_TO_RB_ROOT;
9231 
9232 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9233 		return KF_ARG_PTR_TO_RB_NODE;
9234 
9235 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9236 		if (!btf_type_is_struct(ref_t)) {
9237 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9238 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9239 			return -EINVAL;
9240 		}
9241 		return KF_ARG_PTR_TO_BTF_ID;
9242 	}
9243 
9244 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9245 		return KF_ARG_PTR_TO_CALLBACK;
9246 
9247 
9248 	if (argno + 1 < nargs &&
9249 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
9250 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
9251 		arg_mem_size = true;
9252 
9253 	/* This is the catch all argument type of register types supported by
9254 	 * check_helper_mem_access. However, we only allow when argument type is
9255 	 * pointer to scalar, or struct composed (recursively) of scalars. When
9256 	 * arg_mem_size is true, the pointer can be void *.
9257 	 */
9258 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9259 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9260 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9261 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9262 		return -EINVAL;
9263 	}
9264 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9265 }
9266 
9267 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9268 					struct bpf_reg_state *reg,
9269 					const struct btf_type *ref_t,
9270 					const char *ref_tname, u32 ref_id,
9271 					struct bpf_kfunc_call_arg_meta *meta,
9272 					int argno)
9273 {
9274 	const struct btf_type *reg_ref_t;
9275 	bool strict_type_match = false;
9276 	const struct btf *reg_btf;
9277 	const char *reg_ref_tname;
9278 	u32 reg_ref_id;
9279 
9280 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
9281 		reg_btf = reg->btf;
9282 		reg_ref_id = reg->btf_id;
9283 	} else {
9284 		reg_btf = btf_vmlinux;
9285 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9286 	}
9287 
9288 	/* Enforce strict type matching for calls to kfuncs that are acquiring
9289 	 * or releasing a reference, or are no-cast aliases. We do _not_
9290 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9291 	 * as we want to enable BPF programs to pass types that are bitwise
9292 	 * equivalent without forcing them to explicitly cast with something
9293 	 * like bpf_cast_to_kern_ctx().
9294 	 *
9295 	 * For example, say we had a type like the following:
9296 	 *
9297 	 * struct bpf_cpumask {
9298 	 *	cpumask_t cpumask;
9299 	 *	refcount_t usage;
9300 	 * };
9301 	 *
9302 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9303 	 * to a struct cpumask, so it would be safe to pass a struct
9304 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9305 	 *
9306 	 * The philosophy here is similar to how we allow scalars of different
9307 	 * types to be passed to kfuncs as long as the size is the same. The
9308 	 * only difference here is that we're simply allowing
9309 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9310 	 * resolve types.
9311 	 */
9312 	if (is_kfunc_acquire(meta) ||
9313 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
9314 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9315 		strict_type_match = true;
9316 
9317 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9318 
9319 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9320 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9321 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9322 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9323 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9324 			btf_type_str(reg_ref_t), reg_ref_tname);
9325 		return -EINVAL;
9326 	}
9327 	return 0;
9328 }
9329 
9330 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9331 				      struct bpf_reg_state *reg,
9332 				      const struct btf_type *ref_t,
9333 				      const char *ref_tname,
9334 				      struct bpf_kfunc_call_arg_meta *meta,
9335 				      int argno)
9336 {
9337 	struct btf_field *kptr_field;
9338 
9339 	/* check_func_arg_reg_off allows var_off for
9340 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9341 	 * off_desc.
9342 	 */
9343 	if (!tnum_is_const(reg->var_off)) {
9344 		verbose(env, "arg#0 must have constant offset\n");
9345 		return -EINVAL;
9346 	}
9347 
9348 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9349 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9350 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9351 			reg->off + reg->var_off.value);
9352 		return -EINVAL;
9353 	}
9354 
9355 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9356 				  kptr_field->kptr.btf_id, true)) {
9357 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9358 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9359 		return -EINVAL;
9360 	}
9361 	return 0;
9362 }
9363 
9364 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9365 {
9366 	struct bpf_verifier_state *state = env->cur_state;
9367 
9368 	if (!state->active_lock.ptr) {
9369 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9370 		return -EFAULT;
9371 	}
9372 
9373 	if (type_flag(reg->type) & NON_OWN_REF) {
9374 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9375 		return -EFAULT;
9376 	}
9377 
9378 	reg->type |= NON_OWN_REF;
9379 	return 0;
9380 }
9381 
9382 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9383 {
9384 	struct bpf_func_state *state, *unused;
9385 	struct bpf_reg_state *reg;
9386 	int i;
9387 
9388 	state = cur_func(env);
9389 
9390 	if (!ref_obj_id) {
9391 		verbose(env, "verifier internal error: ref_obj_id is zero for "
9392 			     "owning -> non-owning conversion\n");
9393 		return -EFAULT;
9394 	}
9395 
9396 	for (i = 0; i < state->acquired_refs; i++) {
9397 		if (state->refs[i].id != ref_obj_id)
9398 			continue;
9399 
9400 		/* Clear ref_obj_id here so release_reference doesn't clobber
9401 		 * the whole reg
9402 		 */
9403 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9404 			if (reg->ref_obj_id == ref_obj_id) {
9405 				reg->ref_obj_id = 0;
9406 				ref_set_non_owning(env, reg);
9407 			}
9408 		}));
9409 		return 0;
9410 	}
9411 
9412 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9413 	return -EFAULT;
9414 }
9415 
9416 /* Implementation details:
9417  *
9418  * Each register points to some region of memory, which we define as an
9419  * allocation. Each allocation may embed a bpf_spin_lock which protects any
9420  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9421  * allocation. The lock and the data it protects are colocated in the same
9422  * memory region.
9423  *
9424  * Hence, everytime a register holds a pointer value pointing to such
9425  * allocation, the verifier preserves a unique reg->id for it.
9426  *
9427  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9428  * bpf_spin_lock is called.
9429  *
9430  * To enable this, lock state in the verifier captures two values:
9431  *	active_lock.ptr = Register's type specific pointer
9432  *	active_lock.id  = A unique ID for each register pointer value
9433  *
9434  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9435  * supported register types.
9436  *
9437  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9438  * allocated objects is the reg->btf pointer.
9439  *
9440  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9441  * can establish the provenance of the map value statically for each distinct
9442  * lookup into such maps. They always contain a single map value hence unique
9443  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9444  *
9445  * So, in case of global variables, they use array maps with max_entries = 1,
9446  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9447  * into the same map value as max_entries is 1, as described above).
9448  *
9449  * In case of inner map lookups, the inner map pointer has same map_ptr as the
9450  * outer map pointer (in verifier context), but each lookup into an inner map
9451  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9452  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9453  * will get different reg->id assigned to each lookup, hence different
9454  * active_lock.id.
9455  *
9456  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9457  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9458  * returned from bpf_obj_new. Each allocation receives a new reg->id.
9459  */
9460 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9461 {
9462 	void *ptr;
9463 	u32 id;
9464 
9465 	switch ((int)reg->type) {
9466 	case PTR_TO_MAP_VALUE:
9467 		ptr = reg->map_ptr;
9468 		break;
9469 	case PTR_TO_BTF_ID | MEM_ALLOC:
9470 		ptr = reg->btf;
9471 		break;
9472 	default:
9473 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
9474 		return -EFAULT;
9475 	}
9476 	id = reg->id;
9477 
9478 	if (!env->cur_state->active_lock.ptr)
9479 		return -EINVAL;
9480 	if (env->cur_state->active_lock.ptr != ptr ||
9481 	    env->cur_state->active_lock.id != id) {
9482 		verbose(env, "held lock and object are not in the same allocation\n");
9483 		return -EINVAL;
9484 	}
9485 	return 0;
9486 }
9487 
9488 static bool is_bpf_list_api_kfunc(u32 btf_id)
9489 {
9490 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9491 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9492 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9493 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9494 }
9495 
9496 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9497 {
9498 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9499 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9500 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9501 }
9502 
9503 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9504 {
9505 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9506 }
9507 
9508 static bool is_callback_calling_kfunc(u32 btf_id)
9509 {
9510 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9511 }
9512 
9513 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9514 {
9515 	return is_bpf_rbtree_api_kfunc(btf_id);
9516 }
9517 
9518 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9519 					  enum btf_field_type head_field_type,
9520 					  u32 kfunc_btf_id)
9521 {
9522 	bool ret;
9523 
9524 	switch (head_field_type) {
9525 	case BPF_LIST_HEAD:
9526 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9527 		break;
9528 	case BPF_RB_ROOT:
9529 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9530 		break;
9531 	default:
9532 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9533 			btf_field_type_name(head_field_type));
9534 		return false;
9535 	}
9536 
9537 	if (!ret)
9538 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9539 			btf_field_type_name(head_field_type));
9540 	return ret;
9541 }
9542 
9543 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9544 					  enum btf_field_type node_field_type,
9545 					  u32 kfunc_btf_id)
9546 {
9547 	bool ret;
9548 
9549 	switch (node_field_type) {
9550 	case BPF_LIST_NODE:
9551 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9552 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9553 		break;
9554 	case BPF_RB_NODE:
9555 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9556 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9557 		break;
9558 	default:
9559 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9560 			btf_field_type_name(node_field_type));
9561 		return false;
9562 	}
9563 
9564 	if (!ret)
9565 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
9566 			btf_field_type_name(node_field_type));
9567 	return ret;
9568 }
9569 
9570 static int
9571 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
9572 				   struct bpf_reg_state *reg, u32 regno,
9573 				   struct bpf_kfunc_call_arg_meta *meta,
9574 				   enum btf_field_type head_field_type,
9575 				   struct btf_field **head_field)
9576 {
9577 	const char *head_type_name;
9578 	struct btf_field *field;
9579 	struct btf_record *rec;
9580 	u32 head_off;
9581 
9582 	if (meta->btf != btf_vmlinux) {
9583 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9584 		return -EFAULT;
9585 	}
9586 
9587 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
9588 		return -EFAULT;
9589 
9590 	head_type_name = btf_field_type_name(head_field_type);
9591 	if (!tnum_is_const(reg->var_off)) {
9592 		verbose(env,
9593 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9594 			regno, head_type_name);
9595 		return -EINVAL;
9596 	}
9597 
9598 	rec = reg_btf_record(reg);
9599 	head_off = reg->off + reg->var_off.value;
9600 	field = btf_record_find(rec, head_off, head_field_type);
9601 	if (!field) {
9602 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
9603 		return -EINVAL;
9604 	}
9605 
9606 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9607 	if (check_reg_allocation_locked(env, reg)) {
9608 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
9609 			rec->spin_lock_off, head_type_name);
9610 		return -EINVAL;
9611 	}
9612 
9613 	if (*head_field) {
9614 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
9615 		return -EFAULT;
9616 	}
9617 	*head_field = field;
9618 	return 0;
9619 }
9620 
9621 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9622 					   struct bpf_reg_state *reg, u32 regno,
9623 					   struct bpf_kfunc_call_arg_meta *meta)
9624 {
9625 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
9626 							  &meta->arg_list_head.field);
9627 }
9628 
9629 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9630 					     struct bpf_reg_state *reg, u32 regno,
9631 					     struct bpf_kfunc_call_arg_meta *meta)
9632 {
9633 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
9634 							  &meta->arg_rbtree_root.field);
9635 }
9636 
9637 static int
9638 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
9639 				   struct bpf_reg_state *reg, u32 regno,
9640 				   struct bpf_kfunc_call_arg_meta *meta,
9641 				   enum btf_field_type head_field_type,
9642 				   enum btf_field_type node_field_type,
9643 				   struct btf_field **node_field)
9644 {
9645 	const char *node_type_name;
9646 	const struct btf_type *et, *t;
9647 	struct btf_field *field;
9648 	u32 node_off;
9649 
9650 	if (meta->btf != btf_vmlinux) {
9651 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9652 		return -EFAULT;
9653 	}
9654 
9655 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
9656 		return -EFAULT;
9657 
9658 	node_type_name = btf_field_type_name(node_field_type);
9659 	if (!tnum_is_const(reg->var_off)) {
9660 		verbose(env,
9661 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
9662 			regno, node_type_name);
9663 		return -EINVAL;
9664 	}
9665 
9666 	node_off = reg->off + reg->var_off.value;
9667 	field = reg_find_field_offset(reg, node_off, node_field_type);
9668 	if (!field || field->offset != node_off) {
9669 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
9670 		return -EINVAL;
9671 	}
9672 
9673 	field = *node_field;
9674 
9675 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9676 	t = btf_type_by_id(reg->btf, reg->btf_id);
9677 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9678 				  field->graph_root.value_btf_id, true)) {
9679 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
9680 			"in struct %s, but arg is at offset=%d in struct %s\n",
9681 			btf_field_type_name(head_field_type),
9682 			btf_field_type_name(node_field_type),
9683 			field->graph_root.node_offset,
9684 			btf_name_by_offset(field->graph_root.btf, et->name_off),
9685 			node_off, btf_name_by_offset(reg->btf, t->name_off));
9686 		return -EINVAL;
9687 	}
9688 
9689 	if (node_off != field->graph_root.node_offset) {
9690 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
9691 			node_off, btf_field_type_name(node_field_type),
9692 			field->graph_root.node_offset,
9693 			btf_name_by_offset(field->graph_root.btf, et->name_off));
9694 		return -EINVAL;
9695 	}
9696 
9697 	return 0;
9698 }
9699 
9700 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9701 					   struct bpf_reg_state *reg, u32 regno,
9702 					   struct bpf_kfunc_call_arg_meta *meta)
9703 {
9704 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9705 						  BPF_LIST_HEAD, BPF_LIST_NODE,
9706 						  &meta->arg_list_head.field);
9707 }
9708 
9709 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9710 					     struct bpf_reg_state *reg, u32 regno,
9711 					     struct bpf_kfunc_call_arg_meta *meta)
9712 {
9713 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9714 						  BPF_RB_ROOT, BPF_RB_NODE,
9715 						  &meta->arg_rbtree_root.field);
9716 }
9717 
9718 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
9719 			    int insn_idx)
9720 {
9721 	const char *func_name = meta->func_name, *ref_tname;
9722 	const struct btf *btf = meta->btf;
9723 	const struct btf_param *args;
9724 	u32 i, nargs;
9725 	int ret;
9726 
9727 	args = (const struct btf_param *)(meta->func_proto + 1);
9728 	nargs = btf_type_vlen(meta->func_proto);
9729 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9730 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9731 			MAX_BPF_FUNC_REG_ARGS);
9732 		return -EINVAL;
9733 	}
9734 
9735 	/* Check that BTF function arguments match actual types that the
9736 	 * verifier sees.
9737 	 */
9738 	for (i = 0; i < nargs; i++) {
9739 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
9740 		const struct btf_type *t, *ref_t, *resolve_ret;
9741 		enum bpf_arg_type arg_type = ARG_DONTCARE;
9742 		u32 regno = i + 1, ref_id, type_size;
9743 		bool is_ret_buf_sz = false;
9744 		int kf_arg_type;
9745 
9746 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9747 
9748 		if (is_kfunc_arg_ignore(btf, &args[i]))
9749 			continue;
9750 
9751 		if (btf_type_is_scalar(t)) {
9752 			if (reg->type != SCALAR_VALUE) {
9753 				verbose(env, "R%d is not a scalar\n", regno);
9754 				return -EINVAL;
9755 			}
9756 
9757 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9758 				if (meta->arg_constant.found) {
9759 					verbose(env, "verifier internal error: only one constant argument permitted\n");
9760 					return -EFAULT;
9761 				}
9762 				if (!tnum_is_const(reg->var_off)) {
9763 					verbose(env, "R%d must be a known constant\n", regno);
9764 					return -EINVAL;
9765 				}
9766 				ret = mark_chain_precision(env, regno);
9767 				if (ret < 0)
9768 					return ret;
9769 				meta->arg_constant.found = true;
9770 				meta->arg_constant.value = reg->var_off.value;
9771 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9772 				meta->r0_rdonly = true;
9773 				is_ret_buf_sz = true;
9774 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9775 				is_ret_buf_sz = true;
9776 			}
9777 
9778 			if (is_ret_buf_sz) {
9779 				if (meta->r0_size) {
9780 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9781 					return -EINVAL;
9782 				}
9783 
9784 				if (!tnum_is_const(reg->var_off)) {
9785 					verbose(env, "R%d is not a const\n", regno);
9786 					return -EINVAL;
9787 				}
9788 
9789 				meta->r0_size = reg->var_off.value;
9790 				ret = mark_chain_precision(env, regno);
9791 				if (ret)
9792 					return ret;
9793 			}
9794 			continue;
9795 		}
9796 
9797 		if (!btf_type_is_ptr(t)) {
9798 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9799 			return -EINVAL;
9800 		}
9801 
9802 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
9803 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
9804 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9805 			return -EACCES;
9806 		}
9807 
9808 		if (reg->ref_obj_id) {
9809 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
9810 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9811 					regno, reg->ref_obj_id,
9812 					meta->ref_obj_id);
9813 				return -EFAULT;
9814 			}
9815 			meta->ref_obj_id = reg->ref_obj_id;
9816 			if (is_kfunc_release(meta))
9817 				meta->release_regno = regno;
9818 		}
9819 
9820 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9821 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9822 
9823 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9824 		if (kf_arg_type < 0)
9825 			return kf_arg_type;
9826 
9827 		switch (kf_arg_type) {
9828 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9829 		case KF_ARG_PTR_TO_BTF_ID:
9830 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9831 				break;
9832 
9833 			if (!is_trusted_reg(reg)) {
9834 				if (!is_kfunc_rcu(meta)) {
9835 					verbose(env, "R%d must be referenced or trusted\n", regno);
9836 					return -EINVAL;
9837 				}
9838 				if (!is_rcu_reg(reg)) {
9839 					verbose(env, "R%d must be a rcu pointer\n", regno);
9840 					return -EINVAL;
9841 				}
9842 			}
9843 
9844 			fallthrough;
9845 		case KF_ARG_PTR_TO_CTX:
9846 			/* Trusted arguments have the same offset checks as release arguments */
9847 			arg_type |= OBJ_RELEASE;
9848 			break;
9849 		case KF_ARG_PTR_TO_KPTR:
9850 		case KF_ARG_PTR_TO_DYNPTR:
9851 		case KF_ARG_PTR_TO_LIST_HEAD:
9852 		case KF_ARG_PTR_TO_LIST_NODE:
9853 		case KF_ARG_PTR_TO_RB_ROOT:
9854 		case KF_ARG_PTR_TO_RB_NODE:
9855 		case KF_ARG_PTR_TO_MEM:
9856 		case KF_ARG_PTR_TO_MEM_SIZE:
9857 		case KF_ARG_PTR_TO_CALLBACK:
9858 			/* Trusted by default */
9859 			break;
9860 		default:
9861 			WARN_ON_ONCE(1);
9862 			return -EFAULT;
9863 		}
9864 
9865 		if (is_kfunc_release(meta) && reg->ref_obj_id)
9866 			arg_type |= OBJ_RELEASE;
9867 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9868 		if (ret < 0)
9869 			return ret;
9870 
9871 		switch (kf_arg_type) {
9872 		case KF_ARG_PTR_TO_CTX:
9873 			if (reg->type != PTR_TO_CTX) {
9874 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9875 				return -EINVAL;
9876 			}
9877 
9878 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9879 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9880 				if (ret < 0)
9881 					return -EINVAL;
9882 				meta->ret_btf_id  = ret;
9883 			}
9884 			break;
9885 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9886 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9887 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9888 				return -EINVAL;
9889 			}
9890 			if (!reg->ref_obj_id) {
9891 				verbose(env, "allocated object must be referenced\n");
9892 				return -EINVAL;
9893 			}
9894 			if (meta->btf == btf_vmlinux &&
9895 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9896 				meta->arg_obj_drop.btf = reg->btf;
9897 				meta->arg_obj_drop.btf_id = reg->btf_id;
9898 			}
9899 			break;
9900 		case KF_ARG_PTR_TO_KPTR:
9901 			if (reg->type != PTR_TO_MAP_VALUE) {
9902 				verbose(env, "arg#0 expected pointer to map value\n");
9903 				return -EINVAL;
9904 			}
9905 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9906 			if (ret < 0)
9907 				return ret;
9908 			break;
9909 		case KF_ARG_PTR_TO_DYNPTR:
9910 		{
9911 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
9912 
9913 			if (reg->type != PTR_TO_STACK &&
9914 			    reg->type != CONST_PTR_TO_DYNPTR) {
9915 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9916 				return -EINVAL;
9917 			}
9918 
9919 			if (reg->type == CONST_PTR_TO_DYNPTR)
9920 				dynptr_arg_type |= MEM_RDONLY;
9921 
9922 			if (is_kfunc_arg_uninit(btf, &args[i]))
9923 				dynptr_arg_type |= MEM_UNINIT;
9924 
9925 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
9926 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
9927 			else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
9928 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
9929 
9930 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
9931 			if (ret < 0)
9932 				return ret;
9933 
9934 			if (!(dynptr_arg_type & MEM_UNINIT)) {
9935 				int id = dynptr_id(env, reg);
9936 
9937 				if (id < 0) {
9938 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9939 					return id;
9940 				}
9941 				meta->initialized_dynptr.id = id;
9942 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
9943 			}
9944 
9945 			break;
9946 		}
9947 		case KF_ARG_PTR_TO_LIST_HEAD:
9948 			if (reg->type != PTR_TO_MAP_VALUE &&
9949 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9950 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9951 				return -EINVAL;
9952 			}
9953 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9954 				verbose(env, "allocated object must be referenced\n");
9955 				return -EINVAL;
9956 			}
9957 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9958 			if (ret < 0)
9959 				return ret;
9960 			break;
9961 		case KF_ARG_PTR_TO_RB_ROOT:
9962 			if (reg->type != PTR_TO_MAP_VALUE &&
9963 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9964 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9965 				return -EINVAL;
9966 			}
9967 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9968 				verbose(env, "allocated object must be referenced\n");
9969 				return -EINVAL;
9970 			}
9971 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
9972 			if (ret < 0)
9973 				return ret;
9974 			break;
9975 		case KF_ARG_PTR_TO_LIST_NODE:
9976 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9977 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9978 				return -EINVAL;
9979 			}
9980 			if (!reg->ref_obj_id) {
9981 				verbose(env, "allocated object must be referenced\n");
9982 				return -EINVAL;
9983 			}
9984 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9985 			if (ret < 0)
9986 				return ret;
9987 			break;
9988 		case KF_ARG_PTR_TO_RB_NODE:
9989 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
9990 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
9991 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
9992 					return -EINVAL;
9993 				}
9994 				if (in_rbtree_lock_required_cb(env)) {
9995 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
9996 					return -EINVAL;
9997 				}
9998 			} else {
9999 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10000 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
10001 					return -EINVAL;
10002 				}
10003 				if (!reg->ref_obj_id) {
10004 					verbose(env, "allocated object must be referenced\n");
10005 					return -EINVAL;
10006 				}
10007 			}
10008 
10009 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10010 			if (ret < 0)
10011 				return ret;
10012 			break;
10013 		case KF_ARG_PTR_TO_BTF_ID:
10014 			/* Only base_type is checked, further checks are done here */
10015 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10016 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10017 			    !reg2btf_ids[base_type(reg->type)]) {
10018 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10019 				verbose(env, "expected %s or socket\n",
10020 					reg_type_str(env, base_type(reg->type) |
10021 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10022 				return -EINVAL;
10023 			}
10024 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10025 			if (ret < 0)
10026 				return ret;
10027 			break;
10028 		case KF_ARG_PTR_TO_MEM:
10029 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10030 			if (IS_ERR(resolve_ret)) {
10031 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10032 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10033 				return -EINVAL;
10034 			}
10035 			ret = check_mem_reg(env, reg, regno, type_size);
10036 			if (ret < 0)
10037 				return ret;
10038 			break;
10039 		case KF_ARG_PTR_TO_MEM_SIZE:
10040 		{
10041 			struct bpf_reg_state *size_reg = &regs[regno + 1];
10042 			const struct btf_param *size_arg = &args[i + 1];
10043 
10044 			ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10045 			if (ret < 0) {
10046 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10047 				return ret;
10048 			}
10049 
10050 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10051 				if (meta->arg_constant.found) {
10052 					verbose(env, "verifier internal error: only one constant argument permitted\n");
10053 					return -EFAULT;
10054 				}
10055 				if (!tnum_is_const(size_reg->var_off)) {
10056 					verbose(env, "R%d must be a known constant\n", regno + 1);
10057 					return -EINVAL;
10058 				}
10059 				meta->arg_constant.found = true;
10060 				meta->arg_constant.value = size_reg->var_off.value;
10061 			}
10062 
10063 			/* Skip next '__sz' or '__szk' argument */
10064 			i++;
10065 			break;
10066 		}
10067 		case KF_ARG_PTR_TO_CALLBACK:
10068 			meta->subprogno = reg->subprogno;
10069 			break;
10070 		}
10071 	}
10072 
10073 	if (is_kfunc_release(meta) && !meta->release_regno) {
10074 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10075 			func_name);
10076 		return -EINVAL;
10077 	}
10078 
10079 	return 0;
10080 }
10081 
10082 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10083 			    int *insn_idx_p)
10084 {
10085 	const struct btf_type *t, *func, *func_proto, *ptr_type;
10086 	u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id;
10087 	struct bpf_reg_state *regs = cur_regs(env);
10088 	const char *func_name, *ptr_type_name;
10089 	bool sleepable, rcu_lock, rcu_unlock;
10090 	struct bpf_kfunc_call_arg_meta meta;
10091 	int err, insn_idx = *insn_idx_p;
10092 	const struct btf_param *args;
10093 	const struct btf_type *ret_t;
10094 	struct btf *desc_btf;
10095 	u32 *kfunc_flags;
10096 
10097 	/* skip for now, but return error when we find this in fixup_kfunc_call */
10098 	if (!insn->imm)
10099 		return 0;
10100 
10101 	desc_btf = find_kfunc_desc_btf(env, insn->off);
10102 	if (IS_ERR(desc_btf))
10103 		return PTR_ERR(desc_btf);
10104 
10105 	func_id = insn->imm;
10106 	func = btf_type_by_id(desc_btf, func_id);
10107 	func_name = btf_name_by_offset(desc_btf, func->name_off);
10108 	func_proto = btf_type_by_id(desc_btf, func->type);
10109 
10110 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10111 	if (!kfunc_flags) {
10112 		verbose(env, "calling kernel function %s is not allowed\n",
10113 			func_name);
10114 		return -EACCES;
10115 	}
10116 
10117 	/* Prepare kfunc call metadata */
10118 	memset(&meta, 0, sizeof(meta));
10119 	meta.btf = desc_btf;
10120 	meta.func_id = func_id;
10121 	meta.kfunc_flags = *kfunc_flags;
10122 	meta.func_proto = func_proto;
10123 	meta.func_name = func_name;
10124 
10125 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10126 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10127 		return -EACCES;
10128 	}
10129 
10130 	sleepable = is_kfunc_sleepable(&meta);
10131 	if (sleepable && !env->prog->aux->sleepable) {
10132 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10133 		return -EACCES;
10134 	}
10135 
10136 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10137 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10138 
10139 	if (env->cur_state->active_rcu_lock) {
10140 		struct bpf_func_state *state;
10141 		struct bpf_reg_state *reg;
10142 
10143 		if (rcu_lock) {
10144 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10145 			return -EINVAL;
10146 		} else if (rcu_unlock) {
10147 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10148 				if (reg->type & MEM_RCU) {
10149 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10150 					reg->type |= PTR_UNTRUSTED;
10151 				}
10152 			}));
10153 			env->cur_state->active_rcu_lock = false;
10154 		} else if (sleepable) {
10155 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10156 			return -EACCES;
10157 		}
10158 	} else if (rcu_lock) {
10159 		env->cur_state->active_rcu_lock = true;
10160 	} else if (rcu_unlock) {
10161 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10162 		return -EINVAL;
10163 	}
10164 
10165 	/* Check the arguments */
10166 	err = check_kfunc_args(env, &meta, insn_idx);
10167 	if (err < 0)
10168 		return err;
10169 	/* In case of release function, we get register number of refcounted
10170 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10171 	 */
10172 	if (meta.release_regno) {
10173 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10174 		if (err) {
10175 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10176 				func_name, func_id);
10177 			return err;
10178 		}
10179 	}
10180 
10181 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
10182 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10183 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10184 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10185 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10186 		if (err) {
10187 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10188 				func_name, func_id);
10189 			return err;
10190 		}
10191 
10192 		err = release_reference(env, release_ref_obj_id);
10193 		if (err) {
10194 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10195 				func_name, func_id);
10196 			return err;
10197 		}
10198 	}
10199 
10200 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10201 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10202 					set_rbtree_add_callback_state);
10203 		if (err) {
10204 			verbose(env, "kfunc %s#%d failed callback verification\n",
10205 				func_name, func_id);
10206 			return err;
10207 		}
10208 	}
10209 
10210 	for (i = 0; i < CALLER_SAVED_REGS; i++)
10211 		mark_reg_not_init(env, regs, caller_saved[i]);
10212 
10213 	/* Check return type */
10214 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
10215 
10216 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10217 		/* Only exception is bpf_obj_new_impl */
10218 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10219 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10220 			return -EINVAL;
10221 		}
10222 	}
10223 
10224 	if (btf_type_is_scalar(t)) {
10225 		mark_reg_unknown(env, regs, BPF_REG_0);
10226 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10227 	} else if (btf_type_is_ptr(t)) {
10228 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10229 
10230 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10231 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10232 				struct btf *ret_btf;
10233 				u32 ret_btf_id;
10234 
10235 				if (unlikely(!bpf_global_ma_set))
10236 					return -ENOMEM;
10237 
10238 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10239 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10240 					return -EINVAL;
10241 				}
10242 
10243 				ret_btf = env->prog->aux->btf;
10244 				ret_btf_id = meta.arg_constant.value;
10245 
10246 				/* This may be NULL due to user not supplying a BTF */
10247 				if (!ret_btf) {
10248 					verbose(env, "bpf_obj_new requires prog BTF\n");
10249 					return -EINVAL;
10250 				}
10251 
10252 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10253 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
10254 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10255 					return -EINVAL;
10256 				}
10257 
10258 				mark_reg_known_zero(env, regs, BPF_REG_0);
10259 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10260 				regs[BPF_REG_0].btf = ret_btf;
10261 				regs[BPF_REG_0].btf_id = ret_btf_id;
10262 
10263 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
10264 				env->insn_aux_data[insn_idx].kptr_struct_meta =
10265 					btf_find_struct_meta(ret_btf, ret_btf_id);
10266 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10267 				env->insn_aux_data[insn_idx].kptr_struct_meta =
10268 					btf_find_struct_meta(meta.arg_obj_drop.btf,
10269 							     meta.arg_obj_drop.btf_id);
10270 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10271 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10272 				struct btf_field *field = meta.arg_list_head.field;
10273 
10274 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10275 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10276 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10277 				struct btf_field *field = meta.arg_rbtree_root.field;
10278 
10279 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10280 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10281 				mark_reg_known_zero(env, regs, BPF_REG_0);
10282 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10283 				regs[BPF_REG_0].btf = desc_btf;
10284 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10285 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10286 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10287 				if (!ret_t || !btf_type_is_struct(ret_t)) {
10288 					verbose(env,
10289 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10290 					return -EINVAL;
10291 				}
10292 
10293 				mark_reg_known_zero(env, regs, BPF_REG_0);
10294 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10295 				regs[BPF_REG_0].btf = desc_btf;
10296 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
10297 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10298 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10299 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10300 
10301 				mark_reg_known_zero(env, regs, BPF_REG_0);
10302 
10303 				if (!meta.arg_constant.found) {
10304 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10305 					return -EFAULT;
10306 				}
10307 
10308 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10309 
10310 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10311 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10312 
10313 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10314 					regs[BPF_REG_0].type |= MEM_RDONLY;
10315 				} else {
10316 					/* this will set env->seen_direct_write to true */
10317 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10318 						verbose(env, "the prog does not allow writes to packet data\n");
10319 						return -EINVAL;
10320 					}
10321 				}
10322 
10323 				if (!meta.initialized_dynptr.id) {
10324 					verbose(env, "verifier internal error: no dynptr id\n");
10325 					return -EFAULT;
10326 				}
10327 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10328 
10329 				/* we don't need to set BPF_REG_0's ref obj id
10330 				 * because packet slices are not refcounted (see
10331 				 * dynptr_type_refcounted)
10332 				 */
10333 			} else {
10334 				verbose(env, "kernel function %s unhandled dynamic return type\n",
10335 					meta.func_name);
10336 				return -EFAULT;
10337 			}
10338 		} else if (!__btf_type_is_struct(ptr_type)) {
10339 			if (!meta.r0_size) {
10340 				__u32 sz;
10341 
10342 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
10343 					meta.r0_size = sz;
10344 					meta.r0_rdonly = true;
10345 				}
10346 			}
10347 			if (!meta.r0_size) {
10348 				ptr_type_name = btf_name_by_offset(desc_btf,
10349 								   ptr_type->name_off);
10350 				verbose(env,
10351 					"kernel function %s returns pointer type %s %s is not supported\n",
10352 					func_name,
10353 					btf_type_str(ptr_type),
10354 					ptr_type_name);
10355 				return -EINVAL;
10356 			}
10357 
10358 			mark_reg_known_zero(env, regs, BPF_REG_0);
10359 			regs[BPF_REG_0].type = PTR_TO_MEM;
10360 			regs[BPF_REG_0].mem_size = meta.r0_size;
10361 
10362 			if (meta.r0_rdonly)
10363 				regs[BPF_REG_0].type |= MEM_RDONLY;
10364 
10365 			/* Ensures we don't access the memory after a release_reference() */
10366 			if (meta.ref_obj_id)
10367 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10368 		} else {
10369 			mark_reg_known_zero(env, regs, BPF_REG_0);
10370 			regs[BPF_REG_0].btf = desc_btf;
10371 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10372 			regs[BPF_REG_0].btf_id = ptr_type_id;
10373 		}
10374 
10375 		if (is_kfunc_ret_null(&meta)) {
10376 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10377 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10378 			regs[BPF_REG_0].id = ++env->id_gen;
10379 		}
10380 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10381 		if (is_kfunc_acquire(&meta)) {
10382 			int id = acquire_reference_state(env, insn_idx);
10383 
10384 			if (id < 0)
10385 				return id;
10386 			if (is_kfunc_ret_null(&meta))
10387 				regs[BPF_REG_0].id = id;
10388 			regs[BPF_REG_0].ref_obj_id = id;
10389 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10390 			ref_set_non_owning(env, &regs[BPF_REG_0]);
10391 		}
10392 
10393 		if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10394 			invalidate_non_owning_refs(env);
10395 
10396 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10397 			regs[BPF_REG_0].id = ++env->id_gen;
10398 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
10399 
10400 	nargs = btf_type_vlen(func_proto);
10401 	args = (const struct btf_param *)(func_proto + 1);
10402 	for (i = 0; i < nargs; i++) {
10403 		u32 regno = i + 1;
10404 
10405 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10406 		if (btf_type_is_ptr(t))
10407 			mark_btf_func_reg_size(env, regno, sizeof(void *));
10408 		else
10409 			/* scalar. ensured by btf_check_kfunc_arg_match() */
10410 			mark_btf_func_reg_size(env, regno, t->size);
10411 	}
10412 
10413 	return 0;
10414 }
10415 
10416 static bool signed_add_overflows(s64 a, s64 b)
10417 {
10418 	/* Do the add in u64, where overflow is well-defined */
10419 	s64 res = (s64)((u64)a + (u64)b);
10420 
10421 	if (b < 0)
10422 		return res > a;
10423 	return res < a;
10424 }
10425 
10426 static bool signed_add32_overflows(s32 a, s32 b)
10427 {
10428 	/* Do the add in u32, where overflow is well-defined */
10429 	s32 res = (s32)((u32)a + (u32)b);
10430 
10431 	if (b < 0)
10432 		return res > a;
10433 	return res < a;
10434 }
10435 
10436 static bool signed_sub_overflows(s64 a, s64 b)
10437 {
10438 	/* Do the sub in u64, where overflow is well-defined */
10439 	s64 res = (s64)((u64)a - (u64)b);
10440 
10441 	if (b < 0)
10442 		return res < a;
10443 	return res > a;
10444 }
10445 
10446 static bool signed_sub32_overflows(s32 a, s32 b)
10447 {
10448 	/* Do the sub in u32, where overflow is well-defined */
10449 	s32 res = (s32)((u32)a - (u32)b);
10450 
10451 	if (b < 0)
10452 		return res < a;
10453 	return res > a;
10454 }
10455 
10456 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10457 				  const struct bpf_reg_state *reg,
10458 				  enum bpf_reg_type type)
10459 {
10460 	bool known = tnum_is_const(reg->var_off);
10461 	s64 val = reg->var_off.value;
10462 	s64 smin = reg->smin_value;
10463 
10464 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10465 		verbose(env, "math between %s pointer and %lld is not allowed\n",
10466 			reg_type_str(env, type), val);
10467 		return false;
10468 	}
10469 
10470 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10471 		verbose(env, "%s pointer offset %d is not allowed\n",
10472 			reg_type_str(env, type), reg->off);
10473 		return false;
10474 	}
10475 
10476 	if (smin == S64_MIN) {
10477 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10478 			reg_type_str(env, type));
10479 		return false;
10480 	}
10481 
10482 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10483 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
10484 			smin, reg_type_str(env, type));
10485 		return false;
10486 	}
10487 
10488 	return true;
10489 }
10490 
10491 enum {
10492 	REASON_BOUNDS	= -1,
10493 	REASON_TYPE	= -2,
10494 	REASON_PATHS	= -3,
10495 	REASON_LIMIT	= -4,
10496 	REASON_STACK	= -5,
10497 };
10498 
10499 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10500 			      u32 *alu_limit, bool mask_to_left)
10501 {
10502 	u32 max = 0, ptr_limit = 0;
10503 
10504 	switch (ptr_reg->type) {
10505 	case PTR_TO_STACK:
10506 		/* Offset 0 is out-of-bounds, but acceptable start for the
10507 		 * left direction, see BPF_REG_FP. Also, unknown scalar
10508 		 * offset where we would need to deal with min/max bounds is
10509 		 * currently prohibited for unprivileged.
10510 		 */
10511 		max = MAX_BPF_STACK + mask_to_left;
10512 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10513 		break;
10514 	case PTR_TO_MAP_VALUE:
10515 		max = ptr_reg->map_ptr->value_size;
10516 		ptr_limit = (mask_to_left ?
10517 			     ptr_reg->smin_value :
10518 			     ptr_reg->umax_value) + ptr_reg->off;
10519 		break;
10520 	default:
10521 		return REASON_TYPE;
10522 	}
10523 
10524 	if (ptr_limit >= max)
10525 		return REASON_LIMIT;
10526 	*alu_limit = ptr_limit;
10527 	return 0;
10528 }
10529 
10530 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
10531 				    const struct bpf_insn *insn)
10532 {
10533 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
10534 }
10535 
10536 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
10537 				       u32 alu_state, u32 alu_limit)
10538 {
10539 	/* If we arrived here from different branches with different
10540 	 * state or limits to sanitize, then this won't work.
10541 	 */
10542 	if (aux->alu_state &&
10543 	    (aux->alu_state != alu_state ||
10544 	     aux->alu_limit != alu_limit))
10545 		return REASON_PATHS;
10546 
10547 	/* Corresponding fixup done in do_misc_fixups(). */
10548 	aux->alu_state = alu_state;
10549 	aux->alu_limit = alu_limit;
10550 	return 0;
10551 }
10552 
10553 static int sanitize_val_alu(struct bpf_verifier_env *env,
10554 			    struct bpf_insn *insn)
10555 {
10556 	struct bpf_insn_aux_data *aux = cur_aux(env);
10557 
10558 	if (can_skip_alu_sanitation(env, insn))
10559 		return 0;
10560 
10561 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
10562 }
10563 
10564 static bool sanitize_needed(u8 opcode)
10565 {
10566 	return opcode == BPF_ADD || opcode == BPF_SUB;
10567 }
10568 
10569 struct bpf_sanitize_info {
10570 	struct bpf_insn_aux_data aux;
10571 	bool mask_to_left;
10572 };
10573 
10574 static struct bpf_verifier_state *
10575 sanitize_speculative_path(struct bpf_verifier_env *env,
10576 			  const struct bpf_insn *insn,
10577 			  u32 next_idx, u32 curr_idx)
10578 {
10579 	struct bpf_verifier_state *branch;
10580 	struct bpf_reg_state *regs;
10581 
10582 	branch = push_stack(env, next_idx, curr_idx, true);
10583 	if (branch && insn) {
10584 		regs = branch->frame[branch->curframe]->regs;
10585 		if (BPF_SRC(insn->code) == BPF_K) {
10586 			mark_reg_unknown(env, regs, insn->dst_reg);
10587 		} else if (BPF_SRC(insn->code) == BPF_X) {
10588 			mark_reg_unknown(env, regs, insn->dst_reg);
10589 			mark_reg_unknown(env, regs, insn->src_reg);
10590 		}
10591 	}
10592 	return branch;
10593 }
10594 
10595 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
10596 			    struct bpf_insn *insn,
10597 			    const struct bpf_reg_state *ptr_reg,
10598 			    const struct bpf_reg_state *off_reg,
10599 			    struct bpf_reg_state *dst_reg,
10600 			    struct bpf_sanitize_info *info,
10601 			    const bool commit_window)
10602 {
10603 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
10604 	struct bpf_verifier_state *vstate = env->cur_state;
10605 	bool off_is_imm = tnum_is_const(off_reg->var_off);
10606 	bool off_is_neg = off_reg->smin_value < 0;
10607 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
10608 	u8 opcode = BPF_OP(insn->code);
10609 	u32 alu_state, alu_limit;
10610 	struct bpf_reg_state tmp;
10611 	bool ret;
10612 	int err;
10613 
10614 	if (can_skip_alu_sanitation(env, insn))
10615 		return 0;
10616 
10617 	/* We already marked aux for masking from non-speculative
10618 	 * paths, thus we got here in the first place. We only care
10619 	 * to explore bad access from here.
10620 	 */
10621 	if (vstate->speculative)
10622 		goto do_sim;
10623 
10624 	if (!commit_window) {
10625 		if (!tnum_is_const(off_reg->var_off) &&
10626 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
10627 			return REASON_BOUNDS;
10628 
10629 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
10630 				     (opcode == BPF_SUB && !off_is_neg);
10631 	}
10632 
10633 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
10634 	if (err < 0)
10635 		return err;
10636 
10637 	if (commit_window) {
10638 		/* In commit phase we narrow the masking window based on
10639 		 * the observed pointer move after the simulated operation.
10640 		 */
10641 		alu_state = info->aux.alu_state;
10642 		alu_limit = abs(info->aux.alu_limit - alu_limit);
10643 	} else {
10644 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
10645 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
10646 		alu_state |= ptr_is_dst_reg ?
10647 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
10648 
10649 		/* Limit pruning on unknown scalars to enable deep search for
10650 		 * potential masking differences from other program paths.
10651 		 */
10652 		if (!off_is_imm)
10653 			env->explore_alu_limits = true;
10654 	}
10655 
10656 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
10657 	if (err < 0)
10658 		return err;
10659 do_sim:
10660 	/* If we're in commit phase, we're done here given we already
10661 	 * pushed the truncated dst_reg into the speculative verification
10662 	 * stack.
10663 	 *
10664 	 * Also, when register is a known constant, we rewrite register-based
10665 	 * operation to immediate-based, and thus do not need masking (and as
10666 	 * a consequence, do not need to simulate the zero-truncation either).
10667 	 */
10668 	if (commit_window || off_is_imm)
10669 		return 0;
10670 
10671 	/* Simulate and find potential out-of-bounds access under
10672 	 * speculative execution from truncation as a result of
10673 	 * masking when off was not within expected range. If off
10674 	 * sits in dst, then we temporarily need to move ptr there
10675 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
10676 	 * for cases where we use K-based arithmetic in one direction
10677 	 * and truncated reg-based in the other in order to explore
10678 	 * bad access.
10679 	 */
10680 	if (!ptr_is_dst_reg) {
10681 		tmp = *dst_reg;
10682 		copy_register_state(dst_reg, ptr_reg);
10683 	}
10684 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
10685 					env->insn_idx);
10686 	if (!ptr_is_dst_reg && ret)
10687 		*dst_reg = tmp;
10688 	return !ret ? REASON_STACK : 0;
10689 }
10690 
10691 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
10692 {
10693 	struct bpf_verifier_state *vstate = env->cur_state;
10694 
10695 	/* If we simulate paths under speculation, we don't update the
10696 	 * insn as 'seen' such that when we verify unreachable paths in
10697 	 * the non-speculative domain, sanitize_dead_code() can still
10698 	 * rewrite/sanitize them.
10699 	 */
10700 	if (!vstate->speculative)
10701 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10702 }
10703 
10704 static int sanitize_err(struct bpf_verifier_env *env,
10705 			const struct bpf_insn *insn, int reason,
10706 			const struct bpf_reg_state *off_reg,
10707 			const struct bpf_reg_state *dst_reg)
10708 {
10709 	static const char *err = "pointer arithmetic with it prohibited for !root";
10710 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
10711 	u32 dst = insn->dst_reg, src = insn->src_reg;
10712 
10713 	switch (reason) {
10714 	case REASON_BOUNDS:
10715 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
10716 			off_reg == dst_reg ? dst : src, err);
10717 		break;
10718 	case REASON_TYPE:
10719 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
10720 			off_reg == dst_reg ? src : dst, err);
10721 		break;
10722 	case REASON_PATHS:
10723 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
10724 			dst, op, err);
10725 		break;
10726 	case REASON_LIMIT:
10727 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
10728 			dst, op, err);
10729 		break;
10730 	case REASON_STACK:
10731 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
10732 			dst, err);
10733 		break;
10734 	default:
10735 		verbose(env, "verifier internal error: unknown reason (%d)\n",
10736 			reason);
10737 		break;
10738 	}
10739 
10740 	return -EACCES;
10741 }
10742 
10743 /* check that stack access falls within stack limits and that 'reg' doesn't
10744  * have a variable offset.
10745  *
10746  * Variable offset is prohibited for unprivileged mode for simplicity since it
10747  * requires corresponding support in Spectre masking for stack ALU.  See also
10748  * retrieve_ptr_limit().
10749  *
10750  *
10751  * 'off' includes 'reg->off'.
10752  */
10753 static int check_stack_access_for_ptr_arithmetic(
10754 				struct bpf_verifier_env *env,
10755 				int regno,
10756 				const struct bpf_reg_state *reg,
10757 				int off)
10758 {
10759 	if (!tnum_is_const(reg->var_off)) {
10760 		char tn_buf[48];
10761 
10762 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
10763 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10764 			regno, tn_buf, off);
10765 		return -EACCES;
10766 	}
10767 
10768 	if (off >= 0 || off < -MAX_BPF_STACK) {
10769 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
10770 			"prohibited for !root; off=%d\n", regno, off);
10771 		return -EACCES;
10772 	}
10773 
10774 	return 0;
10775 }
10776 
10777 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10778 				 const struct bpf_insn *insn,
10779 				 const struct bpf_reg_state *dst_reg)
10780 {
10781 	u32 dst = insn->dst_reg;
10782 
10783 	/* For unprivileged we require that resulting offset must be in bounds
10784 	 * in order to be able to sanitize access later on.
10785 	 */
10786 	if (env->bypass_spec_v1)
10787 		return 0;
10788 
10789 	switch (dst_reg->type) {
10790 	case PTR_TO_STACK:
10791 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10792 					dst_reg->off + dst_reg->var_off.value))
10793 			return -EACCES;
10794 		break;
10795 	case PTR_TO_MAP_VALUE:
10796 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10797 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10798 				"prohibited for !root\n", dst);
10799 			return -EACCES;
10800 		}
10801 		break;
10802 	default:
10803 		break;
10804 	}
10805 
10806 	return 0;
10807 }
10808 
10809 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10810  * Caller should also handle BPF_MOV case separately.
10811  * If we return -EACCES, caller may want to try again treating pointer as a
10812  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
10813  */
10814 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10815 				   struct bpf_insn *insn,
10816 				   const struct bpf_reg_state *ptr_reg,
10817 				   const struct bpf_reg_state *off_reg)
10818 {
10819 	struct bpf_verifier_state *vstate = env->cur_state;
10820 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10821 	struct bpf_reg_state *regs = state->regs, *dst_reg;
10822 	bool known = tnum_is_const(off_reg->var_off);
10823 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10824 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10825 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10826 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10827 	struct bpf_sanitize_info info = {};
10828 	u8 opcode = BPF_OP(insn->code);
10829 	u32 dst = insn->dst_reg;
10830 	int ret;
10831 
10832 	dst_reg = &regs[dst];
10833 
10834 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10835 	    smin_val > smax_val || umin_val > umax_val) {
10836 		/* Taint dst register if offset had invalid bounds derived from
10837 		 * e.g. dead branches.
10838 		 */
10839 		__mark_reg_unknown(env, dst_reg);
10840 		return 0;
10841 	}
10842 
10843 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
10844 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
10845 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10846 			__mark_reg_unknown(env, dst_reg);
10847 			return 0;
10848 		}
10849 
10850 		verbose(env,
10851 			"R%d 32-bit pointer arithmetic prohibited\n",
10852 			dst);
10853 		return -EACCES;
10854 	}
10855 
10856 	if (ptr_reg->type & PTR_MAYBE_NULL) {
10857 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10858 			dst, reg_type_str(env, ptr_reg->type));
10859 		return -EACCES;
10860 	}
10861 
10862 	switch (base_type(ptr_reg->type)) {
10863 	case CONST_PTR_TO_MAP:
10864 		/* smin_val represents the known value */
10865 		if (known && smin_val == 0 && opcode == BPF_ADD)
10866 			break;
10867 		fallthrough;
10868 	case PTR_TO_PACKET_END:
10869 	case PTR_TO_SOCKET:
10870 	case PTR_TO_SOCK_COMMON:
10871 	case PTR_TO_TCP_SOCK:
10872 	case PTR_TO_XDP_SOCK:
10873 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10874 			dst, reg_type_str(env, ptr_reg->type));
10875 		return -EACCES;
10876 	default:
10877 		break;
10878 	}
10879 
10880 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10881 	 * The id may be overwritten later if we create a new variable offset.
10882 	 */
10883 	dst_reg->type = ptr_reg->type;
10884 	dst_reg->id = ptr_reg->id;
10885 
10886 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10887 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10888 		return -EINVAL;
10889 
10890 	/* pointer types do not carry 32-bit bounds at the moment. */
10891 	__mark_reg32_unbounded(dst_reg);
10892 
10893 	if (sanitize_needed(opcode)) {
10894 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10895 				       &info, false);
10896 		if (ret < 0)
10897 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
10898 	}
10899 
10900 	switch (opcode) {
10901 	case BPF_ADD:
10902 		/* We can take a fixed offset as long as it doesn't overflow
10903 		 * the s32 'off' field
10904 		 */
10905 		if (known && (ptr_reg->off + smin_val ==
10906 			      (s64)(s32)(ptr_reg->off + smin_val))) {
10907 			/* pointer += K.  Accumulate it into fixed offset */
10908 			dst_reg->smin_value = smin_ptr;
10909 			dst_reg->smax_value = smax_ptr;
10910 			dst_reg->umin_value = umin_ptr;
10911 			dst_reg->umax_value = umax_ptr;
10912 			dst_reg->var_off = ptr_reg->var_off;
10913 			dst_reg->off = ptr_reg->off + smin_val;
10914 			dst_reg->raw = ptr_reg->raw;
10915 			break;
10916 		}
10917 		/* A new variable offset is created.  Note that off_reg->off
10918 		 * == 0, since it's a scalar.
10919 		 * dst_reg gets the pointer type and since some positive
10920 		 * integer value was added to the pointer, give it a new 'id'
10921 		 * if it's a PTR_TO_PACKET.
10922 		 * this creates a new 'base' pointer, off_reg (variable) gets
10923 		 * added into the variable offset, and we copy the fixed offset
10924 		 * from ptr_reg.
10925 		 */
10926 		if (signed_add_overflows(smin_ptr, smin_val) ||
10927 		    signed_add_overflows(smax_ptr, smax_val)) {
10928 			dst_reg->smin_value = S64_MIN;
10929 			dst_reg->smax_value = S64_MAX;
10930 		} else {
10931 			dst_reg->smin_value = smin_ptr + smin_val;
10932 			dst_reg->smax_value = smax_ptr + smax_val;
10933 		}
10934 		if (umin_ptr + umin_val < umin_ptr ||
10935 		    umax_ptr + umax_val < umax_ptr) {
10936 			dst_reg->umin_value = 0;
10937 			dst_reg->umax_value = U64_MAX;
10938 		} else {
10939 			dst_reg->umin_value = umin_ptr + umin_val;
10940 			dst_reg->umax_value = umax_ptr + umax_val;
10941 		}
10942 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10943 		dst_reg->off = ptr_reg->off;
10944 		dst_reg->raw = ptr_reg->raw;
10945 		if (reg_is_pkt_pointer(ptr_reg)) {
10946 			dst_reg->id = ++env->id_gen;
10947 			/* something was added to pkt_ptr, set range to zero */
10948 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10949 		}
10950 		break;
10951 	case BPF_SUB:
10952 		if (dst_reg == off_reg) {
10953 			/* scalar -= pointer.  Creates an unknown scalar */
10954 			verbose(env, "R%d tried to subtract pointer from scalar\n",
10955 				dst);
10956 			return -EACCES;
10957 		}
10958 		/* We don't allow subtraction from FP, because (according to
10959 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
10960 		 * be able to deal with it.
10961 		 */
10962 		if (ptr_reg->type == PTR_TO_STACK) {
10963 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
10964 				dst);
10965 			return -EACCES;
10966 		}
10967 		if (known && (ptr_reg->off - smin_val ==
10968 			      (s64)(s32)(ptr_reg->off - smin_val))) {
10969 			/* pointer -= K.  Subtract it from fixed offset */
10970 			dst_reg->smin_value = smin_ptr;
10971 			dst_reg->smax_value = smax_ptr;
10972 			dst_reg->umin_value = umin_ptr;
10973 			dst_reg->umax_value = umax_ptr;
10974 			dst_reg->var_off = ptr_reg->var_off;
10975 			dst_reg->id = ptr_reg->id;
10976 			dst_reg->off = ptr_reg->off - smin_val;
10977 			dst_reg->raw = ptr_reg->raw;
10978 			break;
10979 		}
10980 		/* A new variable offset is created.  If the subtrahend is known
10981 		 * nonnegative, then any reg->range we had before is still good.
10982 		 */
10983 		if (signed_sub_overflows(smin_ptr, smax_val) ||
10984 		    signed_sub_overflows(smax_ptr, smin_val)) {
10985 			/* Overflow possible, we know nothing */
10986 			dst_reg->smin_value = S64_MIN;
10987 			dst_reg->smax_value = S64_MAX;
10988 		} else {
10989 			dst_reg->smin_value = smin_ptr - smax_val;
10990 			dst_reg->smax_value = smax_ptr - smin_val;
10991 		}
10992 		if (umin_ptr < umax_val) {
10993 			/* Overflow possible, we know nothing */
10994 			dst_reg->umin_value = 0;
10995 			dst_reg->umax_value = U64_MAX;
10996 		} else {
10997 			/* Cannot overflow (as long as bounds are consistent) */
10998 			dst_reg->umin_value = umin_ptr - umax_val;
10999 			dst_reg->umax_value = umax_ptr - umin_val;
11000 		}
11001 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11002 		dst_reg->off = ptr_reg->off;
11003 		dst_reg->raw = ptr_reg->raw;
11004 		if (reg_is_pkt_pointer(ptr_reg)) {
11005 			dst_reg->id = ++env->id_gen;
11006 			/* something was added to pkt_ptr, set range to zero */
11007 			if (smin_val < 0)
11008 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11009 		}
11010 		break;
11011 	case BPF_AND:
11012 	case BPF_OR:
11013 	case BPF_XOR:
11014 		/* bitwise ops on pointers are troublesome, prohibit. */
11015 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11016 			dst, bpf_alu_string[opcode >> 4]);
11017 		return -EACCES;
11018 	default:
11019 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
11020 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11021 			dst, bpf_alu_string[opcode >> 4]);
11022 		return -EACCES;
11023 	}
11024 
11025 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11026 		return -EINVAL;
11027 	reg_bounds_sync(dst_reg);
11028 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11029 		return -EACCES;
11030 	if (sanitize_needed(opcode)) {
11031 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11032 				       &info, true);
11033 		if (ret < 0)
11034 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
11035 	}
11036 
11037 	return 0;
11038 }
11039 
11040 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11041 				 struct bpf_reg_state *src_reg)
11042 {
11043 	s32 smin_val = src_reg->s32_min_value;
11044 	s32 smax_val = src_reg->s32_max_value;
11045 	u32 umin_val = src_reg->u32_min_value;
11046 	u32 umax_val = src_reg->u32_max_value;
11047 
11048 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11049 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11050 		dst_reg->s32_min_value = S32_MIN;
11051 		dst_reg->s32_max_value = S32_MAX;
11052 	} else {
11053 		dst_reg->s32_min_value += smin_val;
11054 		dst_reg->s32_max_value += smax_val;
11055 	}
11056 	if (dst_reg->u32_min_value + umin_val < umin_val ||
11057 	    dst_reg->u32_max_value + umax_val < umax_val) {
11058 		dst_reg->u32_min_value = 0;
11059 		dst_reg->u32_max_value = U32_MAX;
11060 	} else {
11061 		dst_reg->u32_min_value += umin_val;
11062 		dst_reg->u32_max_value += umax_val;
11063 	}
11064 }
11065 
11066 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11067 			       struct bpf_reg_state *src_reg)
11068 {
11069 	s64 smin_val = src_reg->smin_value;
11070 	s64 smax_val = src_reg->smax_value;
11071 	u64 umin_val = src_reg->umin_value;
11072 	u64 umax_val = src_reg->umax_value;
11073 
11074 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11075 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
11076 		dst_reg->smin_value = S64_MIN;
11077 		dst_reg->smax_value = S64_MAX;
11078 	} else {
11079 		dst_reg->smin_value += smin_val;
11080 		dst_reg->smax_value += smax_val;
11081 	}
11082 	if (dst_reg->umin_value + umin_val < umin_val ||
11083 	    dst_reg->umax_value + umax_val < umax_val) {
11084 		dst_reg->umin_value = 0;
11085 		dst_reg->umax_value = U64_MAX;
11086 	} else {
11087 		dst_reg->umin_value += umin_val;
11088 		dst_reg->umax_value += umax_val;
11089 	}
11090 }
11091 
11092 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11093 				 struct bpf_reg_state *src_reg)
11094 {
11095 	s32 smin_val = src_reg->s32_min_value;
11096 	s32 smax_val = src_reg->s32_max_value;
11097 	u32 umin_val = src_reg->u32_min_value;
11098 	u32 umax_val = src_reg->u32_max_value;
11099 
11100 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11101 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11102 		/* Overflow possible, we know nothing */
11103 		dst_reg->s32_min_value = S32_MIN;
11104 		dst_reg->s32_max_value = S32_MAX;
11105 	} else {
11106 		dst_reg->s32_min_value -= smax_val;
11107 		dst_reg->s32_max_value -= smin_val;
11108 	}
11109 	if (dst_reg->u32_min_value < umax_val) {
11110 		/* Overflow possible, we know nothing */
11111 		dst_reg->u32_min_value = 0;
11112 		dst_reg->u32_max_value = U32_MAX;
11113 	} else {
11114 		/* Cannot overflow (as long as bounds are consistent) */
11115 		dst_reg->u32_min_value -= umax_val;
11116 		dst_reg->u32_max_value -= umin_val;
11117 	}
11118 }
11119 
11120 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11121 			       struct bpf_reg_state *src_reg)
11122 {
11123 	s64 smin_val = src_reg->smin_value;
11124 	s64 smax_val = src_reg->smax_value;
11125 	u64 umin_val = src_reg->umin_value;
11126 	u64 umax_val = src_reg->umax_value;
11127 
11128 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11129 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11130 		/* Overflow possible, we know nothing */
11131 		dst_reg->smin_value = S64_MIN;
11132 		dst_reg->smax_value = S64_MAX;
11133 	} else {
11134 		dst_reg->smin_value -= smax_val;
11135 		dst_reg->smax_value -= smin_val;
11136 	}
11137 	if (dst_reg->umin_value < umax_val) {
11138 		/* Overflow possible, we know nothing */
11139 		dst_reg->umin_value = 0;
11140 		dst_reg->umax_value = U64_MAX;
11141 	} else {
11142 		/* Cannot overflow (as long as bounds are consistent) */
11143 		dst_reg->umin_value -= umax_val;
11144 		dst_reg->umax_value -= umin_val;
11145 	}
11146 }
11147 
11148 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11149 				 struct bpf_reg_state *src_reg)
11150 {
11151 	s32 smin_val = src_reg->s32_min_value;
11152 	u32 umin_val = src_reg->u32_min_value;
11153 	u32 umax_val = src_reg->u32_max_value;
11154 
11155 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11156 		/* Ain't nobody got time to multiply that sign */
11157 		__mark_reg32_unbounded(dst_reg);
11158 		return;
11159 	}
11160 	/* Both values are positive, so we can work with unsigned and
11161 	 * copy the result to signed (unless it exceeds S32_MAX).
11162 	 */
11163 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11164 		/* Potential overflow, we know nothing */
11165 		__mark_reg32_unbounded(dst_reg);
11166 		return;
11167 	}
11168 	dst_reg->u32_min_value *= umin_val;
11169 	dst_reg->u32_max_value *= umax_val;
11170 	if (dst_reg->u32_max_value > S32_MAX) {
11171 		/* Overflow possible, we know nothing */
11172 		dst_reg->s32_min_value = S32_MIN;
11173 		dst_reg->s32_max_value = S32_MAX;
11174 	} else {
11175 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11176 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11177 	}
11178 }
11179 
11180 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11181 			       struct bpf_reg_state *src_reg)
11182 {
11183 	s64 smin_val = src_reg->smin_value;
11184 	u64 umin_val = src_reg->umin_value;
11185 	u64 umax_val = src_reg->umax_value;
11186 
11187 	if (smin_val < 0 || dst_reg->smin_value < 0) {
11188 		/* Ain't nobody got time to multiply that sign */
11189 		__mark_reg64_unbounded(dst_reg);
11190 		return;
11191 	}
11192 	/* Both values are positive, so we can work with unsigned and
11193 	 * copy the result to signed (unless it exceeds S64_MAX).
11194 	 */
11195 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11196 		/* Potential overflow, we know nothing */
11197 		__mark_reg64_unbounded(dst_reg);
11198 		return;
11199 	}
11200 	dst_reg->umin_value *= umin_val;
11201 	dst_reg->umax_value *= umax_val;
11202 	if (dst_reg->umax_value > S64_MAX) {
11203 		/* Overflow possible, we know nothing */
11204 		dst_reg->smin_value = S64_MIN;
11205 		dst_reg->smax_value = S64_MAX;
11206 	} else {
11207 		dst_reg->smin_value = dst_reg->umin_value;
11208 		dst_reg->smax_value = dst_reg->umax_value;
11209 	}
11210 }
11211 
11212 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11213 				 struct bpf_reg_state *src_reg)
11214 {
11215 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
11216 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11217 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11218 	s32 smin_val = src_reg->s32_min_value;
11219 	u32 umax_val = src_reg->u32_max_value;
11220 
11221 	if (src_known && dst_known) {
11222 		__mark_reg32_known(dst_reg, var32_off.value);
11223 		return;
11224 	}
11225 
11226 	/* We get our minimum from the var_off, since that's inherently
11227 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
11228 	 */
11229 	dst_reg->u32_min_value = var32_off.value;
11230 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11231 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11232 		/* Lose signed bounds when ANDing negative numbers,
11233 		 * ain't nobody got time for that.
11234 		 */
11235 		dst_reg->s32_min_value = S32_MIN;
11236 		dst_reg->s32_max_value = S32_MAX;
11237 	} else {
11238 		/* ANDing two positives gives a positive, so safe to
11239 		 * cast result into s64.
11240 		 */
11241 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11242 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11243 	}
11244 }
11245 
11246 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11247 			       struct bpf_reg_state *src_reg)
11248 {
11249 	bool src_known = tnum_is_const(src_reg->var_off);
11250 	bool dst_known = tnum_is_const(dst_reg->var_off);
11251 	s64 smin_val = src_reg->smin_value;
11252 	u64 umax_val = src_reg->umax_value;
11253 
11254 	if (src_known && dst_known) {
11255 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11256 		return;
11257 	}
11258 
11259 	/* We get our minimum from the var_off, since that's inherently
11260 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
11261 	 */
11262 	dst_reg->umin_value = dst_reg->var_off.value;
11263 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11264 	if (dst_reg->smin_value < 0 || smin_val < 0) {
11265 		/* Lose signed bounds when ANDing negative numbers,
11266 		 * ain't nobody got time for that.
11267 		 */
11268 		dst_reg->smin_value = S64_MIN;
11269 		dst_reg->smax_value = S64_MAX;
11270 	} else {
11271 		/* ANDing two positives gives a positive, so safe to
11272 		 * cast result into s64.
11273 		 */
11274 		dst_reg->smin_value = dst_reg->umin_value;
11275 		dst_reg->smax_value = dst_reg->umax_value;
11276 	}
11277 	/* We may learn something more from the var_off */
11278 	__update_reg_bounds(dst_reg);
11279 }
11280 
11281 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11282 				struct bpf_reg_state *src_reg)
11283 {
11284 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
11285 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11286 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11287 	s32 smin_val = src_reg->s32_min_value;
11288 	u32 umin_val = src_reg->u32_min_value;
11289 
11290 	if (src_known && dst_known) {
11291 		__mark_reg32_known(dst_reg, var32_off.value);
11292 		return;
11293 	}
11294 
11295 	/* We get our maximum from the var_off, and our minimum is the
11296 	 * maximum of the operands' minima
11297 	 */
11298 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11299 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11300 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11301 		/* Lose signed bounds when ORing negative numbers,
11302 		 * ain't nobody got time for that.
11303 		 */
11304 		dst_reg->s32_min_value = S32_MIN;
11305 		dst_reg->s32_max_value = S32_MAX;
11306 	} else {
11307 		/* ORing two positives gives a positive, so safe to
11308 		 * cast result into s64.
11309 		 */
11310 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11311 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11312 	}
11313 }
11314 
11315 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11316 			      struct bpf_reg_state *src_reg)
11317 {
11318 	bool src_known = tnum_is_const(src_reg->var_off);
11319 	bool dst_known = tnum_is_const(dst_reg->var_off);
11320 	s64 smin_val = src_reg->smin_value;
11321 	u64 umin_val = src_reg->umin_value;
11322 
11323 	if (src_known && dst_known) {
11324 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11325 		return;
11326 	}
11327 
11328 	/* We get our maximum from the var_off, and our minimum is the
11329 	 * maximum of the operands' minima
11330 	 */
11331 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11332 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11333 	if (dst_reg->smin_value < 0 || smin_val < 0) {
11334 		/* Lose signed bounds when ORing negative numbers,
11335 		 * ain't nobody got time for that.
11336 		 */
11337 		dst_reg->smin_value = S64_MIN;
11338 		dst_reg->smax_value = S64_MAX;
11339 	} else {
11340 		/* ORing two positives gives a positive, so safe to
11341 		 * cast result into s64.
11342 		 */
11343 		dst_reg->smin_value = dst_reg->umin_value;
11344 		dst_reg->smax_value = dst_reg->umax_value;
11345 	}
11346 	/* We may learn something more from the var_off */
11347 	__update_reg_bounds(dst_reg);
11348 }
11349 
11350 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11351 				 struct bpf_reg_state *src_reg)
11352 {
11353 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
11354 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11355 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11356 	s32 smin_val = src_reg->s32_min_value;
11357 
11358 	if (src_known && dst_known) {
11359 		__mark_reg32_known(dst_reg, var32_off.value);
11360 		return;
11361 	}
11362 
11363 	/* We get both minimum and maximum from the var32_off. */
11364 	dst_reg->u32_min_value = var32_off.value;
11365 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11366 
11367 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11368 		/* XORing two positive sign numbers gives a positive,
11369 		 * so safe to cast u32 result into s32.
11370 		 */
11371 		dst_reg->s32_min_value = dst_reg->u32_min_value;
11372 		dst_reg->s32_max_value = dst_reg->u32_max_value;
11373 	} else {
11374 		dst_reg->s32_min_value = S32_MIN;
11375 		dst_reg->s32_max_value = S32_MAX;
11376 	}
11377 }
11378 
11379 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11380 			       struct bpf_reg_state *src_reg)
11381 {
11382 	bool src_known = tnum_is_const(src_reg->var_off);
11383 	bool dst_known = tnum_is_const(dst_reg->var_off);
11384 	s64 smin_val = src_reg->smin_value;
11385 
11386 	if (src_known && dst_known) {
11387 		/* dst_reg->var_off.value has been updated earlier */
11388 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
11389 		return;
11390 	}
11391 
11392 	/* We get both minimum and maximum from the var_off. */
11393 	dst_reg->umin_value = dst_reg->var_off.value;
11394 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11395 
11396 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11397 		/* XORing two positive sign numbers gives a positive,
11398 		 * so safe to cast u64 result into s64.
11399 		 */
11400 		dst_reg->smin_value = dst_reg->umin_value;
11401 		dst_reg->smax_value = dst_reg->umax_value;
11402 	} else {
11403 		dst_reg->smin_value = S64_MIN;
11404 		dst_reg->smax_value = S64_MAX;
11405 	}
11406 
11407 	__update_reg_bounds(dst_reg);
11408 }
11409 
11410 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11411 				   u64 umin_val, u64 umax_val)
11412 {
11413 	/* We lose all sign bit information (except what we can pick
11414 	 * up from var_off)
11415 	 */
11416 	dst_reg->s32_min_value = S32_MIN;
11417 	dst_reg->s32_max_value = S32_MAX;
11418 	/* If we might shift our top bit out, then we know nothing */
11419 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11420 		dst_reg->u32_min_value = 0;
11421 		dst_reg->u32_max_value = U32_MAX;
11422 	} else {
11423 		dst_reg->u32_min_value <<= umin_val;
11424 		dst_reg->u32_max_value <<= umax_val;
11425 	}
11426 }
11427 
11428 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11429 				 struct bpf_reg_state *src_reg)
11430 {
11431 	u32 umax_val = src_reg->u32_max_value;
11432 	u32 umin_val = src_reg->u32_min_value;
11433 	/* u32 alu operation will zext upper bits */
11434 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11435 
11436 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11437 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11438 	/* Not required but being careful mark reg64 bounds as unknown so
11439 	 * that we are forced to pick them up from tnum and zext later and
11440 	 * if some path skips this step we are still safe.
11441 	 */
11442 	__mark_reg64_unbounded(dst_reg);
11443 	__update_reg32_bounds(dst_reg);
11444 }
11445 
11446 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11447 				   u64 umin_val, u64 umax_val)
11448 {
11449 	/* Special case <<32 because it is a common compiler pattern to sign
11450 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11451 	 * positive we know this shift will also be positive so we can track
11452 	 * bounds correctly. Otherwise we lose all sign bit information except
11453 	 * what we can pick up from var_off. Perhaps we can generalize this
11454 	 * later to shifts of any length.
11455 	 */
11456 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11457 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11458 	else
11459 		dst_reg->smax_value = S64_MAX;
11460 
11461 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11462 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11463 	else
11464 		dst_reg->smin_value = S64_MIN;
11465 
11466 	/* If we might shift our top bit out, then we know nothing */
11467 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11468 		dst_reg->umin_value = 0;
11469 		dst_reg->umax_value = U64_MAX;
11470 	} else {
11471 		dst_reg->umin_value <<= umin_val;
11472 		dst_reg->umax_value <<= umax_val;
11473 	}
11474 }
11475 
11476 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11477 			       struct bpf_reg_state *src_reg)
11478 {
11479 	u64 umax_val = src_reg->umax_value;
11480 	u64 umin_val = src_reg->umin_value;
11481 
11482 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
11483 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11484 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11485 
11486 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11487 	/* We may learn something more from the var_off */
11488 	__update_reg_bounds(dst_reg);
11489 }
11490 
11491 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11492 				 struct bpf_reg_state *src_reg)
11493 {
11494 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
11495 	u32 umax_val = src_reg->u32_max_value;
11496 	u32 umin_val = src_reg->u32_min_value;
11497 
11498 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11499 	 * be negative, then either:
11500 	 * 1) src_reg might be zero, so the sign bit of the result is
11501 	 *    unknown, so we lose our signed bounds
11502 	 * 2) it's known negative, thus the unsigned bounds capture the
11503 	 *    signed bounds
11504 	 * 3) the signed bounds cross zero, so they tell us nothing
11505 	 *    about the result
11506 	 * If the value in dst_reg is known nonnegative, then again the
11507 	 * unsigned bounds capture the signed bounds.
11508 	 * Thus, in all cases it suffices to blow away our signed bounds
11509 	 * and rely on inferring new ones from the unsigned bounds and
11510 	 * var_off of the result.
11511 	 */
11512 	dst_reg->s32_min_value = S32_MIN;
11513 	dst_reg->s32_max_value = S32_MAX;
11514 
11515 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
11516 	dst_reg->u32_min_value >>= umax_val;
11517 	dst_reg->u32_max_value >>= umin_val;
11518 
11519 	__mark_reg64_unbounded(dst_reg);
11520 	__update_reg32_bounds(dst_reg);
11521 }
11522 
11523 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
11524 			       struct bpf_reg_state *src_reg)
11525 {
11526 	u64 umax_val = src_reg->umax_value;
11527 	u64 umin_val = src_reg->umin_value;
11528 
11529 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11530 	 * be negative, then either:
11531 	 * 1) src_reg might be zero, so the sign bit of the result is
11532 	 *    unknown, so we lose our signed bounds
11533 	 * 2) it's known negative, thus the unsigned bounds capture the
11534 	 *    signed bounds
11535 	 * 3) the signed bounds cross zero, so they tell us nothing
11536 	 *    about the result
11537 	 * If the value in dst_reg is known nonnegative, then again the
11538 	 * unsigned bounds capture the signed bounds.
11539 	 * Thus, in all cases it suffices to blow away our signed bounds
11540 	 * and rely on inferring new ones from the unsigned bounds and
11541 	 * var_off of the result.
11542 	 */
11543 	dst_reg->smin_value = S64_MIN;
11544 	dst_reg->smax_value = S64_MAX;
11545 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
11546 	dst_reg->umin_value >>= umax_val;
11547 	dst_reg->umax_value >>= umin_val;
11548 
11549 	/* Its not easy to operate on alu32 bounds here because it depends
11550 	 * on bits being shifted in. Take easy way out and mark unbounded
11551 	 * so we can recalculate later from tnum.
11552 	 */
11553 	__mark_reg32_unbounded(dst_reg);
11554 	__update_reg_bounds(dst_reg);
11555 }
11556 
11557 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
11558 				  struct bpf_reg_state *src_reg)
11559 {
11560 	u64 umin_val = src_reg->u32_min_value;
11561 
11562 	/* Upon reaching here, src_known is true and
11563 	 * umax_val is equal to umin_val.
11564 	 */
11565 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
11566 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
11567 
11568 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
11569 
11570 	/* blow away the dst_reg umin_value/umax_value and rely on
11571 	 * dst_reg var_off to refine the result.
11572 	 */
11573 	dst_reg->u32_min_value = 0;
11574 	dst_reg->u32_max_value = U32_MAX;
11575 
11576 	__mark_reg64_unbounded(dst_reg);
11577 	__update_reg32_bounds(dst_reg);
11578 }
11579 
11580 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
11581 				struct bpf_reg_state *src_reg)
11582 {
11583 	u64 umin_val = src_reg->umin_value;
11584 
11585 	/* Upon reaching here, src_known is true and umax_val is equal
11586 	 * to umin_val.
11587 	 */
11588 	dst_reg->smin_value >>= umin_val;
11589 	dst_reg->smax_value >>= umin_val;
11590 
11591 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
11592 
11593 	/* blow away the dst_reg umin_value/umax_value and rely on
11594 	 * dst_reg var_off to refine the result.
11595 	 */
11596 	dst_reg->umin_value = 0;
11597 	dst_reg->umax_value = U64_MAX;
11598 
11599 	/* Its not easy to operate on alu32 bounds here because it depends
11600 	 * on bits being shifted in from upper 32-bits. Take easy way out
11601 	 * and mark unbounded so we can recalculate later from tnum.
11602 	 */
11603 	__mark_reg32_unbounded(dst_reg);
11604 	__update_reg_bounds(dst_reg);
11605 }
11606 
11607 /* WARNING: This function does calculations on 64-bit values, but the actual
11608  * execution may occur on 32-bit values. Therefore, things like bitshifts
11609  * need extra checks in the 32-bit case.
11610  */
11611 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
11612 				      struct bpf_insn *insn,
11613 				      struct bpf_reg_state *dst_reg,
11614 				      struct bpf_reg_state src_reg)
11615 {
11616 	struct bpf_reg_state *regs = cur_regs(env);
11617 	u8 opcode = BPF_OP(insn->code);
11618 	bool src_known;
11619 	s64 smin_val, smax_val;
11620 	u64 umin_val, umax_val;
11621 	s32 s32_min_val, s32_max_val;
11622 	u32 u32_min_val, u32_max_val;
11623 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
11624 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
11625 	int ret;
11626 
11627 	smin_val = src_reg.smin_value;
11628 	smax_val = src_reg.smax_value;
11629 	umin_val = src_reg.umin_value;
11630 	umax_val = src_reg.umax_value;
11631 
11632 	s32_min_val = src_reg.s32_min_value;
11633 	s32_max_val = src_reg.s32_max_value;
11634 	u32_min_val = src_reg.u32_min_value;
11635 	u32_max_val = src_reg.u32_max_value;
11636 
11637 	if (alu32) {
11638 		src_known = tnum_subreg_is_const(src_reg.var_off);
11639 		if ((src_known &&
11640 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
11641 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
11642 			/* Taint dst register if offset had invalid bounds
11643 			 * derived from e.g. dead branches.
11644 			 */
11645 			__mark_reg_unknown(env, dst_reg);
11646 			return 0;
11647 		}
11648 	} else {
11649 		src_known = tnum_is_const(src_reg.var_off);
11650 		if ((src_known &&
11651 		     (smin_val != smax_val || umin_val != umax_val)) ||
11652 		    smin_val > smax_val || umin_val > umax_val) {
11653 			/* Taint dst register if offset had invalid bounds
11654 			 * derived from e.g. dead branches.
11655 			 */
11656 			__mark_reg_unknown(env, dst_reg);
11657 			return 0;
11658 		}
11659 	}
11660 
11661 	if (!src_known &&
11662 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
11663 		__mark_reg_unknown(env, dst_reg);
11664 		return 0;
11665 	}
11666 
11667 	if (sanitize_needed(opcode)) {
11668 		ret = sanitize_val_alu(env, insn);
11669 		if (ret < 0)
11670 			return sanitize_err(env, insn, ret, NULL, NULL);
11671 	}
11672 
11673 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
11674 	 * There are two classes of instructions: The first class we track both
11675 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
11676 	 * greatest amount of precision when alu operations are mixed with jmp32
11677 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
11678 	 * and BPF_OR. This is possible because these ops have fairly easy to
11679 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
11680 	 * See alu32 verifier tests for examples. The second class of
11681 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
11682 	 * with regards to tracking sign/unsigned bounds because the bits may
11683 	 * cross subreg boundaries in the alu64 case. When this happens we mark
11684 	 * the reg unbounded in the subreg bound space and use the resulting
11685 	 * tnum to calculate an approximation of the sign/unsigned bounds.
11686 	 */
11687 	switch (opcode) {
11688 	case BPF_ADD:
11689 		scalar32_min_max_add(dst_reg, &src_reg);
11690 		scalar_min_max_add(dst_reg, &src_reg);
11691 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
11692 		break;
11693 	case BPF_SUB:
11694 		scalar32_min_max_sub(dst_reg, &src_reg);
11695 		scalar_min_max_sub(dst_reg, &src_reg);
11696 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
11697 		break;
11698 	case BPF_MUL:
11699 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
11700 		scalar32_min_max_mul(dst_reg, &src_reg);
11701 		scalar_min_max_mul(dst_reg, &src_reg);
11702 		break;
11703 	case BPF_AND:
11704 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
11705 		scalar32_min_max_and(dst_reg, &src_reg);
11706 		scalar_min_max_and(dst_reg, &src_reg);
11707 		break;
11708 	case BPF_OR:
11709 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
11710 		scalar32_min_max_or(dst_reg, &src_reg);
11711 		scalar_min_max_or(dst_reg, &src_reg);
11712 		break;
11713 	case BPF_XOR:
11714 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
11715 		scalar32_min_max_xor(dst_reg, &src_reg);
11716 		scalar_min_max_xor(dst_reg, &src_reg);
11717 		break;
11718 	case BPF_LSH:
11719 		if (umax_val >= insn_bitness) {
11720 			/* Shifts greater than 31 or 63 are undefined.
11721 			 * This includes shifts by a negative number.
11722 			 */
11723 			mark_reg_unknown(env, regs, insn->dst_reg);
11724 			break;
11725 		}
11726 		if (alu32)
11727 			scalar32_min_max_lsh(dst_reg, &src_reg);
11728 		else
11729 			scalar_min_max_lsh(dst_reg, &src_reg);
11730 		break;
11731 	case BPF_RSH:
11732 		if (umax_val >= insn_bitness) {
11733 			/* Shifts greater than 31 or 63 are undefined.
11734 			 * This includes shifts by a negative number.
11735 			 */
11736 			mark_reg_unknown(env, regs, insn->dst_reg);
11737 			break;
11738 		}
11739 		if (alu32)
11740 			scalar32_min_max_rsh(dst_reg, &src_reg);
11741 		else
11742 			scalar_min_max_rsh(dst_reg, &src_reg);
11743 		break;
11744 	case BPF_ARSH:
11745 		if (umax_val >= insn_bitness) {
11746 			/* Shifts greater than 31 or 63 are undefined.
11747 			 * This includes shifts by a negative number.
11748 			 */
11749 			mark_reg_unknown(env, regs, insn->dst_reg);
11750 			break;
11751 		}
11752 		if (alu32)
11753 			scalar32_min_max_arsh(dst_reg, &src_reg);
11754 		else
11755 			scalar_min_max_arsh(dst_reg, &src_reg);
11756 		break;
11757 	default:
11758 		mark_reg_unknown(env, regs, insn->dst_reg);
11759 		break;
11760 	}
11761 
11762 	/* ALU32 ops are zero extended into 64bit register */
11763 	if (alu32)
11764 		zext_32_to_64(dst_reg);
11765 	reg_bounds_sync(dst_reg);
11766 	return 0;
11767 }
11768 
11769 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11770  * and var_off.
11771  */
11772 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11773 				   struct bpf_insn *insn)
11774 {
11775 	struct bpf_verifier_state *vstate = env->cur_state;
11776 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11777 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11778 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11779 	u8 opcode = BPF_OP(insn->code);
11780 	int err;
11781 
11782 	dst_reg = &regs[insn->dst_reg];
11783 	src_reg = NULL;
11784 	if (dst_reg->type != SCALAR_VALUE)
11785 		ptr_reg = dst_reg;
11786 	else
11787 		/* Make sure ID is cleared otherwise dst_reg min/max could be
11788 		 * incorrectly propagated into other registers by find_equal_scalars()
11789 		 */
11790 		dst_reg->id = 0;
11791 	if (BPF_SRC(insn->code) == BPF_X) {
11792 		src_reg = &regs[insn->src_reg];
11793 		if (src_reg->type != SCALAR_VALUE) {
11794 			if (dst_reg->type != SCALAR_VALUE) {
11795 				/* Combining two pointers by any ALU op yields
11796 				 * an arbitrary scalar. Disallow all math except
11797 				 * pointer subtraction
11798 				 */
11799 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11800 					mark_reg_unknown(env, regs, insn->dst_reg);
11801 					return 0;
11802 				}
11803 				verbose(env, "R%d pointer %s pointer prohibited\n",
11804 					insn->dst_reg,
11805 					bpf_alu_string[opcode >> 4]);
11806 				return -EACCES;
11807 			} else {
11808 				/* scalar += pointer
11809 				 * This is legal, but we have to reverse our
11810 				 * src/dest handling in computing the range
11811 				 */
11812 				err = mark_chain_precision(env, insn->dst_reg);
11813 				if (err)
11814 					return err;
11815 				return adjust_ptr_min_max_vals(env, insn,
11816 							       src_reg, dst_reg);
11817 			}
11818 		} else if (ptr_reg) {
11819 			/* pointer += scalar */
11820 			err = mark_chain_precision(env, insn->src_reg);
11821 			if (err)
11822 				return err;
11823 			return adjust_ptr_min_max_vals(env, insn,
11824 						       dst_reg, src_reg);
11825 		} else if (dst_reg->precise) {
11826 			/* if dst_reg is precise, src_reg should be precise as well */
11827 			err = mark_chain_precision(env, insn->src_reg);
11828 			if (err)
11829 				return err;
11830 		}
11831 	} else {
11832 		/* Pretend the src is a reg with a known value, since we only
11833 		 * need to be able to read from this state.
11834 		 */
11835 		off_reg.type = SCALAR_VALUE;
11836 		__mark_reg_known(&off_reg, insn->imm);
11837 		src_reg = &off_reg;
11838 		if (ptr_reg) /* pointer += K */
11839 			return adjust_ptr_min_max_vals(env, insn,
11840 						       ptr_reg, src_reg);
11841 	}
11842 
11843 	/* Got here implies adding two SCALAR_VALUEs */
11844 	if (WARN_ON_ONCE(ptr_reg)) {
11845 		print_verifier_state(env, state, true);
11846 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
11847 		return -EINVAL;
11848 	}
11849 	if (WARN_ON(!src_reg)) {
11850 		print_verifier_state(env, state, true);
11851 		verbose(env, "verifier internal error: no src_reg\n");
11852 		return -EINVAL;
11853 	}
11854 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11855 }
11856 
11857 /* check validity of 32-bit and 64-bit arithmetic operations */
11858 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11859 {
11860 	struct bpf_reg_state *regs = cur_regs(env);
11861 	u8 opcode = BPF_OP(insn->code);
11862 	int err;
11863 
11864 	if (opcode == BPF_END || opcode == BPF_NEG) {
11865 		if (opcode == BPF_NEG) {
11866 			if (BPF_SRC(insn->code) != BPF_K ||
11867 			    insn->src_reg != BPF_REG_0 ||
11868 			    insn->off != 0 || insn->imm != 0) {
11869 				verbose(env, "BPF_NEG uses reserved fields\n");
11870 				return -EINVAL;
11871 			}
11872 		} else {
11873 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11874 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11875 			    BPF_CLASS(insn->code) == BPF_ALU64) {
11876 				verbose(env, "BPF_END uses reserved fields\n");
11877 				return -EINVAL;
11878 			}
11879 		}
11880 
11881 		/* check src operand */
11882 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11883 		if (err)
11884 			return err;
11885 
11886 		if (is_pointer_value(env, insn->dst_reg)) {
11887 			verbose(env, "R%d pointer arithmetic prohibited\n",
11888 				insn->dst_reg);
11889 			return -EACCES;
11890 		}
11891 
11892 		/* check dest operand */
11893 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
11894 		if (err)
11895 			return err;
11896 
11897 	} else if (opcode == BPF_MOV) {
11898 
11899 		if (BPF_SRC(insn->code) == BPF_X) {
11900 			if (insn->imm != 0 || insn->off != 0) {
11901 				verbose(env, "BPF_MOV uses reserved fields\n");
11902 				return -EINVAL;
11903 			}
11904 
11905 			/* check src operand */
11906 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11907 			if (err)
11908 				return err;
11909 		} else {
11910 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11911 				verbose(env, "BPF_MOV uses reserved fields\n");
11912 				return -EINVAL;
11913 			}
11914 		}
11915 
11916 		/* check dest operand, mark as required later */
11917 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11918 		if (err)
11919 			return err;
11920 
11921 		if (BPF_SRC(insn->code) == BPF_X) {
11922 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
11923 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11924 
11925 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11926 				/* case: R1 = R2
11927 				 * copy register state to dest reg
11928 				 */
11929 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11930 					/* Assign src and dst registers the same ID
11931 					 * that will be used by find_equal_scalars()
11932 					 * to propagate min/max range.
11933 					 */
11934 					src_reg->id = ++env->id_gen;
11935 				copy_register_state(dst_reg, src_reg);
11936 				dst_reg->live |= REG_LIVE_WRITTEN;
11937 				dst_reg->subreg_def = DEF_NOT_SUBREG;
11938 			} else {
11939 				/* R1 = (u32) R2 */
11940 				if (is_pointer_value(env, insn->src_reg)) {
11941 					verbose(env,
11942 						"R%d partial copy of pointer\n",
11943 						insn->src_reg);
11944 					return -EACCES;
11945 				} else if (src_reg->type == SCALAR_VALUE) {
11946 					copy_register_state(dst_reg, src_reg);
11947 					/* Make sure ID is cleared otherwise
11948 					 * dst_reg min/max could be incorrectly
11949 					 * propagated into src_reg by find_equal_scalars()
11950 					 */
11951 					dst_reg->id = 0;
11952 					dst_reg->live |= REG_LIVE_WRITTEN;
11953 					dst_reg->subreg_def = env->insn_idx + 1;
11954 				} else {
11955 					mark_reg_unknown(env, regs,
11956 							 insn->dst_reg);
11957 				}
11958 				zext_32_to_64(dst_reg);
11959 				reg_bounds_sync(dst_reg);
11960 			}
11961 		} else {
11962 			/* case: R = imm
11963 			 * remember the value we stored into this reg
11964 			 */
11965 			/* clear any state __mark_reg_known doesn't set */
11966 			mark_reg_unknown(env, regs, insn->dst_reg);
11967 			regs[insn->dst_reg].type = SCALAR_VALUE;
11968 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
11969 				__mark_reg_known(regs + insn->dst_reg,
11970 						 insn->imm);
11971 			} else {
11972 				__mark_reg_known(regs + insn->dst_reg,
11973 						 (u32)insn->imm);
11974 			}
11975 		}
11976 
11977 	} else if (opcode > BPF_END) {
11978 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11979 		return -EINVAL;
11980 
11981 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
11982 
11983 		if (BPF_SRC(insn->code) == BPF_X) {
11984 			if (insn->imm != 0 || insn->off != 0) {
11985 				verbose(env, "BPF_ALU uses reserved fields\n");
11986 				return -EINVAL;
11987 			}
11988 			/* check src1 operand */
11989 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11990 			if (err)
11991 				return err;
11992 		} else {
11993 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11994 				verbose(env, "BPF_ALU uses reserved fields\n");
11995 				return -EINVAL;
11996 			}
11997 		}
11998 
11999 		/* check src2 operand */
12000 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12001 		if (err)
12002 			return err;
12003 
12004 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12005 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12006 			verbose(env, "div by zero\n");
12007 			return -EINVAL;
12008 		}
12009 
12010 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12011 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12012 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12013 
12014 			if (insn->imm < 0 || insn->imm >= size) {
12015 				verbose(env, "invalid shift %d\n", insn->imm);
12016 				return -EINVAL;
12017 			}
12018 		}
12019 
12020 		/* check dest operand */
12021 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12022 		if (err)
12023 			return err;
12024 
12025 		return adjust_reg_min_max_vals(env, insn);
12026 	}
12027 
12028 	return 0;
12029 }
12030 
12031 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12032 				   struct bpf_reg_state *dst_reg,
12033 				   enum bpf_reg_type type,
12034 				   bool range_right_open)
12035 {
12036 	struct bpf_func_state *state;
12037 	struct bpf_reg_state *reg;
12038 	int new_range;
12039 
12040 	if (dst_reg->off < 0 ||
12041 	    (dst_reg->off == 0 && range_right_open))
12042 		/* This doesn't give us any range */
12043 		return;
12044 
12045 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
12046 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12047 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
12048 		 * than pkt_end, but that's because it's also less than pkt.
12049 		 */
12050 		return;
12051 
12052 	new_range = dst_reg->off;
12053 	if (range_right_open)
12054 		new_range++;
12055 
12056 	/* Examples for register markings:
12057 	 *
12058 	 * pkt_data in dst register:
12059 	 *
12060 	 *   r2 = r3;
12061 	 *   r2 += 8;
12062 	 *   if (r2 > pkt_end) goto <handle exception>
12063 	 *   <access okay>
12064 	 *
12065 	 *   r2 = r3;
12066 	 *   r2 += 8;
12067 	 *   if (r2 < pkt_end) goto <access okay>
12068 	 *   <handle exception>
12069 	 *
12070 	 *   Where:
12071 	 *     r2 == dst_reg, pkt_end == src_reg
12072 	 *     r2=pkt(id=n,off=8,r=0)
12073 	 *     r3=pkt(id=n,off=0,r=0)
12074 	 *
12075 	 * pkt_data in src register:
12076 	 *
12077 	 *   r2 = r3;
12078 	 *   r2 += 8;
12079 	 *   if (pkt_end >= r2) goto <access okay>
12080 	 *   <handle exception>
12081 	 *
12082 	 *   r2 = r3;
12083 	 *   r2 += 8;
12084 	 *   if (pkt_end <= r2) goto <handle exception>
12085 	 *   <access okay>
12086 	 *
12087 	 *   Where:
12088 	 *     pkt_end == dst_reg, r2 == src_reg
12089 	 *     r2=pkt(id=n,off=8,r=0)
12090 	 *     r3=pkt(id=n,off=0,r=0)
12091 	 *
12092 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12093 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12094 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
12095 	 * the check.
12096 	 */
12097 
12098 	/* If our ids match, then we must have the same max_value.  And we
12099 	 * don't care about the other reg's fixed offset, since if it's too big
12100 	 * the range won't allow anything.
12101 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12102 	 */
12103 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12104 		if (reg->type == type && reg->id == dst_reg->id)
12105 			/* keep the maximum range already checked */
12106 			reg->range = max(reg->range, new_range);
12107 	}));
12108 }
12109 
12110 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12111 {
12112 	struct tnum subreg = tnum_subreg(reg->var_off);
12113 	s32 sval = (s32)val;
12114 
12115 	switch (opcode) {
12116 	case BPF_JEQ:
12117 		if (tnum_is_const(subreg))
12118 			return !!tnum_equals_const(subreg, val);
12119 		break;
12120 	case BPF_JNE:
12121 		if (tnum_is_const(subreg))
12122 			return !tnum_equals_const(subreg, val);
12123 		break;
12124 	case BPF_JSET:
12125 		if ((~subreg.mask & subreg.value) & val)
12126 			return 1;
12127 		if (!((subreg.mask | subreg.value) & val))
12128 			return 0;
12129 		break;
12130 	case BPF_JGT:
12131 		if (reg->u32_min_value > val)
12132 			return 1;
12133 		else if (reg->u32_max_value <= val)
12134 			return 0;
12135 		break;
12136 	case BPF_JSGT:
12137 		if (reg->s32_min_value > sval)
12138 			return 1;
12139 		else if (reg->s32_max_value <= sval)
12140 			return 0;
12141 		break;
12142 	case BPF_JLT:
12143 		if (reg->u32_max_value < val)
12144 			return 1;
12145 		else if (reg->u32_min_value >= val)
12146 			return 0;
12147 		break;
12148 	case BPF_JSLT:
12149 		if (reg->s32_max_value < sval)
12150 			return 1;
12151 		else if (reg->s32_min_value >= sval)
12152 			return 0;
12153 		break;
12154 	case BPF_JGE:
12155 		if (reg->u32_min_value >= val)
12156 			return 1;
12157 		else if (reg->u32_max_value < val)
12158 			return 0;
12159 		break;
12160 	case BPF_JSGE:
12161 		if (reg->s32_min_value >= sval)
12162 			return 1;
12163 		else if (reg->s32_max_value < sval)
12164 			return 0;
12165 		break;
12166 	case BPF_JLE:
12167 		if (reg->u32_max_value <= val)
12168 			return 1;
12169 		else if (reg->u32_min_value > val)
12170 			return 0;
12171 		break;
12172 	case BPF_JSLE:
12173 		if (reg->s32_max_value <= sval)
12174 			return 1;
12175 		else if (reg->s32_min_value > sval)
12176 			return 0;
12177 		break;
12178 	}
12179 
12180 	return -1;
12181 }
12182 
12183 
12184 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12185 {
12186 	s64 sval = (s64)val;
12187 
12188 	switch (opcode) {
12189 	case BPF_JEQ:
12190 		if (tnum_is_const(reg->var_off))
12191 			return !!tnum_equals_const(reg->var_off, val);
12192 		break;
12193 	case BPF_JNE:
12194 		if (tnum_is_const(reg->var_off))
12195 			return !tnum_equals_const(reg->var_off, val);
12196 		break;
12197 	case BPF_JSET:
12198 		if ((~reg->var_off.mask & reg->var_off.value) & val)
12199 			return 1;
12200 		if (!((reg->var_off.mask | reg->var_off.value) & val))
12201 			return 0;
12202 		break;
12203 	case BPF_JGT:
12204 		if (reg->umin_value > val)
12205 			return 1;
12206 		else if (reg->umax_value <= val)
12207 			return 0;
12208 		break;
12209 	case BPF_JSGT:
12210 		if (reg->smin_value > sval)
12211 			return 1;
12212 		else if (reg->smax_value <= sval)
12213 			return 0;
12214 		break;
12215 	case BPF_JLT:
12216 		if (reg->umax_value < val)
12217 			return 1;
12218 		else if (reg->umin_value >= val)
12219 			return 0;
12220 		break;
12221 	case BPF_JSLT:
12222 		if (reg->smax_value < sval)
12223 			return 1;
12224 		else if (reg->smin_value >= sval)
12225 			return 0;
12226 		break;
12227 	case BPF_JGE:
12228 		if (reg->umin_value >= val)
12229 			return 1;
12230 		else if (reg->umax_value < val)
12231 			return 0;
12232 		break;
12233 	case BPF_JSGE:
12234 		if (reg->smin_value >= sval)
12235 			return 1;
12236 		else if (reg->smax_value < sval)
12237 			return 0;
12238 		break;
12239 	case BPF_JLE:
12240 		if (reg->umax_value <= val)
12241 			return 1;
12242 		else if (reg->umin_value > val)
12243 			return 0;
12244 		break;
12245 	case BPF_JSLE:
12246 		if (reg->smax_value <= sval)
12247 			return 1;
12248 		else if (reg->smin_value > sval)
12249 			return 0;
12250 		break;
12251 	}
12252 
12253 	return -1;
12254 }
12255 
12256 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12257  * and return:
12258  *  1 - branch will be taken and "goto target" will be executed
12259  *  0 - branch will not be taken and fall-through to next insn
12260  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12261  *      range [0,10]
12262  */
12263 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12264 			   bool is_jmp32)
12265 {
12266 	if (__is_pointer_value(false, reg)) {
12267 		if (!reg_type_not_null(reg->type))
12268 			return -1;
12269 
12270 		/* If pointer is valid tests against zero will fail so we can
12271 		 * use this to direct branch taken.
12272 		 */
12273 		if (val != 0)
12274 			return -1;
12275 
12276 		switch (opcode) {
12277 		case BPF_JEQ:
12278 			return 0;
12279 		case BPF_JNE:
12280 			return 1;
12281 		default:
12282 			return -1;
12283 		}
12284 	}
12285 
12286 	if (is_jmp32)
12287 		return is_branch32_taken(reg, val, opcode);
12288 	return is_branch64_taken(reg, val, opcode);
12289 }
12290 
12291 static int flip_opcode(u32 opcode)
12292 {
12293 	/* How can we transform "a <op> b" into "b <op> a"? */
12294 	static const u8 opcode_flip[16] = {
12295 		/* these stay the same */
12296 		[BPF_JEQ  >> 4] = BPF_JEQ,
12297 		[BPF_JNE  >> 4] = BPF_JNE,
12298 		[BPF_JSET >> 4] = BPF_JSET,
12299 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
12300 		[BPF_JGE  >> 4] = BPF_JLE,
12301 		[BPF_JGT  >> 4] = BPF_JLT,
12302 		[BPF_JLE  >> 4] = BPF_JGE,
12303 		[BPF_JLT  >> 4] = BPF_JGT,
12304 		[BPF_JSGE >> 4] = BPF_JSLE,
12305 		[BPF_JSGT >> 4] = BPF_JSLT,
12306 		[BPF_JSLE >> 4] = BPF_JSGE,
12307 		[BPF_JSLT >> 4] = BPF_JSGT
12308 	};
12309 	return opcode_flip[opcode >> 4];
12310 }
12311 
12312 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12313 				   struct bpf_reg_state *src_reg,
12314 				   u8 opcode)
12315 {
12316 	struct bpf_reg_state *pkt;
12317 
12318 	if (src_reg->type == PTR_TO_PACKET_END) {
12319 		pkt = dst_reg;
12320 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
12321 		pkt = src_reg;
12322 		opcode = flip_opcode(opcode);
12323 	} else {
12324 		return -1;
12325 	}
12326 
12327 	if (pkt->range >= 0)
12328 		return -1;
12329 
12330 	switch (opcode) {
12331 	case BPF_JLE:
12332 		/* pkt <= pkt_end */
12333 		fallthrough;
12334 	case BPF_JGT:
12335 		/* pkt > pkt_end */
12336 		if (pkt->range == BEYOND_PKT_END)
12337 			/* pkt has at last one extra byte beyond pkt_end */
12338 			return opcode == BPF_JGT;
12339 		break;
12340 	case BPF_JLT:
12341 		/* pkt < pkt_end */
12342 		fallthrough;
12343 	case BPF_JGE:
12344 		/* pkt >= pkt_end */
12345 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12346 			return opcode == BPF_JGE;
12347 		break;
12348 	}
12349 	return -1;
12350 }
12351 
12352 /* Adjusts the register min/max values in the case that the dst_reg is the
12353  * variable register that we are working on, and src_reg is a constant or we're
12354  * simply doing a BPF_K check.
12355  * In JEQ/JNE cases we also adjust the var_off values.
12356  */
12357 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12358 			    struct bpf_reg_state *false_reg,
12359 			    u64 val, u32 val32,
12360 			    u8 opcode, bool is_jmp32)
12361 {
12362 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
12363 	struct tnum false_64off = false_reg->var_off;
12364 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
12365 	struct tnum true_64off = true_reg->var_off;
12366 	s64 sval = (s64)val;
12367 	s32 sval32 = (s32)val32;
12368 
12369 	/* If the dst_reg is a pointer, we can't learn anything about its
12370 	 * variable offset from the compare (unless src_reg were a pointer into
12371 	 * the same object, but we don't bother with that.
12372 	 * Since false_reg and true_reg have the same type by construction, we
12373 	 * only need to check one of them for pointerness.
12374 	 */
12375 	if (__is_pointer_value(false, false_reg))
12376 		return;
12377 
12378 	switch (opcode) {
12379 	/* JEQ/JNE comparison doesn't change the register equivalence.
12380 	 *
12381 	 * r1 = r2;
12382 	 * if (r1 == 42) goto label;
12383 	 * ...
12384 	 * label: // here both r1 and r2 are known to be 42.
12385 	 *
12386 	 * Hence when marking register as known preserve it's ID.
12387 	 */
12388 	case BPF_JEQ:
12389 		if (is_jmp32) {
12390 			__mark_reg32_known(true_reg, val32);
12391 			true_32off = tnum_subreg(true_reg->var_off);
12392 		} else {
12393 			___mark_reg_known(true_reg, val);
12394 			true_64off = true_reg->var_off;
12395 		}
12396 		break;
12397 	case BPF_JNE:
12398 		if (is_jmp32) {
12399 			__mark_reg32_known(false_reg, val32);
12400 			false_32off = tnum_subreg(false_reg->var_off);
12401 		} else {
12402 			___mark_reg_known(false_reg, val);
12403 			false_64off = false_reg->var_off;
12404 		}
12405 		break;
12406 	case BPF_JSET:
12407 		if (is_jmp32) {
12408 			false_32off = tnum_and(false_32off, tnum_const(~val32));
12409 			if (is_power_of_2(val32))
12410 				true_32off = tnum_or(true_32off,
12411 						     tnum_const(val32));
12412 		} else {
12413 			false_64off = tnum_and(false_64off, tnum_const(~val));
12414 			if (is_power_of_2(val))
12415 				true_64off = tnum_or(true_64off,
12416 						     tnum_const(val));
12417 		}
12418 		break;
12419 	case BPF_JGE:
12420 	case BPF_JGT:
12421 	{
12422 		if (is_jmp32) {
12423 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
12424 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12425 
12426 			false_reg->u32_max_value = min(false_reg->u32_max_value,
12427 						       false_umax);
12428 			true_reg->u32_min_value = max(true_reg->u32_min_value,
12429 						      true_umin);
12430 		} else {
12431 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
12432 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12433 
12434 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
12435 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
12436 		}
12437 		break;
12438 	}
12439 	case BPF_JSGE:
12440 	case BPF_JSGT:
12441 	{
12442 		if (is_jmp32) {
12443 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
12444 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12445 
12446 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12447 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12448 		} else {
12449 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
12450 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12451 
12452 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
12453 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
12454 		}
12455 		break;
12456 	}
12457 	case BPF_JLE:
12458 	case BPF_JLT:
12459 	{
12460 		if (is_jmp32) {
12461 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
12462 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12463 
12464 			false_reg->u32_min_value = max(false_reg->u32_min_value,
12465 						       false_umin);
12466 			true_reg->u32_max_value = min(true_reg->u32_max_value,
12467 						      true_umax);
12468 		} else {
12469 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
12470 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12471 
12472 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
12473 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
12474 		}
12475 		break;
12476 	}
12477 	case BPF_JSLE:
12478 	case BPF_JSLT:
12479 	{
12480 		if (is_jmp32) {
12481 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
12482 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12483 
12484 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12485 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12486 		} else {
12487 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
12488 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12489 
12490 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
12491 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
12492 		}
12493 		break;
12494 	}
12495 	default:
12496 		return;
12497 	}
12498 
12499 	if (is_jmp32) {
12500 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12501 					     tnum_subreg(false_32off));
12502 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12503 					    tnum_subreg(true_32off));
12504 		__reg_combine_32_into_64(false_reg);
12505 		__reg_combine_32_into_64(true_reg);
12506 	} else {
12507 		false_reg->var_off = false_64off;
12508 		true_reg->var_off = true_64off;
12509 		__reg_combine_64_into_32(false_reg);
12510 		__reg_combine_64_into_32(true_reg);
12511 	}
12512 }
12513 
12514 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
12515  * the variable reg.
12516  */
12517 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
12518 				struct bpf_reg_state *false_reg,
12519 				u64 val, u32 val32,
12520 				u8 opcode, bool is_jmp32)
12521 {
12522 	opcode = flip_opcode(opcode);
12523 	/* This uses zero as "not present in table"; luckily the zero opcode,
12524 	 * BPF_JA, can't get here.
12525 	 */
12526 	if (opcode)
12527 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
12528 }
12529 
12530 /* Regs are known to be equal, so intersect their min/max/var_off */
12531 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
12532 				  struct bpf_reg_state *dst_reg)
12533 {
12534 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
12535 							dst_reg->umin_value);
12536 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
12537 							dst_reg->umax_value);
12538 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
12539 							dst_reg->smin_value);
12540 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
12541 							dst_reg->smax_value);
12542 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
12543 							     dst_reg->var_off);
12544 	reg_bounds_sync(src_reg);
12545 	reg_bounds_sync(dst_reg);
12546 }
12547 
12548 static void reg_combine_min_max(struct bpf_reg_state *true_src,
12549 				struct bpf_reg_state *true_dst,
12550 				struct bpf_reg_state *false_src,
12551 				struct bpf_reg_state *false_dst,
12552 				u8 opcode)
12553 {
12554 	switch (opcode) {
12555 	case BPF_JEQ:
12556 		__reg_combine_min_max(true_src, true_dst);
12557 		break;
12558 	case BPF_JNE:
12559 		__reg_combine_min_max(false_src, false_dst);
12560 		break;
12561 	}
12562 }
12563 
12564 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
12565 				 struct bpf_reg_state *reg, u32 id,
12566 				 bool is_null)
12567 {
12568 	if (type_may_be_null(reg->type) && reg->id == id &&
12569 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
12570 		/* Old offset (both fixed and variable parts) should have been
12571 		 * known-zero, because we don't allow pointer arithmetic on
12572 		 * pointers that might be NULL. If we see this happening, don't
12573 		 * convert the register.
12574 		 *
12575 		 * But in some cases, some helpers that return local kptrs
12576 		 * advance offset for the returned pointer. In those cases, it
12577 		 * is fine to expect to see reg->off.
12578 		 */
12579 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
12580 			return;
12581 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
12582 		    WARN_ON_ONCE(reg->off))
12583 			return;
12584 
12585 		if (is_null) {
12586 			reg->type = SCALAR_VALUE;
12587 			/* We don't need id and ref_obj_id from this point
12588 			 * onwards anymore, thus we should better reset it,
12589 			 * so that state pruning has chances to take effect.
12590 			 */
12591 			reg->id = 0;
12592 			reg->ref_obj_id = 0;
12593 
12594 			return;
12595 		}
12596 
12597 		mark_ptr_not_null_reg(reg);
12598 
12599 		if (!reg_may_point_to_spin_lock(reg)) {
12600 			/* For not-NULL ptr, reg->ref_obj_id will be reset
12601 			 * in release_reference().
12602 			 *
12603 			 * reg->id is still used by spin_lock ptr. Other
12604 			 * than spin_lock ptr type, reg->id can be reset.
12605 			 */
12606 			reg->id = 0;
12607 		}
12608 	}
12609 }
12610 
12611 /* The logic is similar to find_good_pkt_pointers(), both could eventually
12612  * be folded together at some point.
12613  */
12614 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
12615 				  bool is_null)
12616 {
12617 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12618 	struct bpf_reg_state *regs = state->regs, *reg;
12619 	u32 ref_obj_id = regs[regno].ref_obj_id;
12620 	u32 id = regs[regno].id;
12621 
12622 	if (ref_obj_id && ref_obj_id == id && is_null)
12623 		/* regs[regno] is in the " == NULL" branch.
12624 		 * No one could have freed the reference state before
12625 		 * doing the NULL check.
12626 		 */
12627 		WARN_ON_ONCE(release_reference_state(state, id));
12628 
12629 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12630 		mark_ptr_or_null_reg(state, reg, id, is_null);
12631 	}));
12632 }
12633 
12634 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
12635 				   struct bpf_reg_state *dst_reg,
12636 				   struct bpf_reg_state *src_reg,
12637 				   struct bpf_verifier_state *this_branch,
12638 				   struct bpf_verifier_state *other_branch)
12639 {
12640 	if (BPF_SRC(insn->code) != BPF_X)
12641 		return false;
12642 
12643 	/* Pointers are always 64-bit. */
12644 	if (BPF_CLASS(insn->code) == BPF_JMP32)
12645 		return false;
12646 
12647 	switch (BPF_OP(insn->code)) {
12648 	case BPF_JGT:
12649 		if ((dst_reg->type == PTR_TO_PACKET &&
12650 		     src_reg->type == PTR_TO_PACKET_END) ||
12651 		    (dst_reg->type == PTR_TO_PACKET_META &&
12652 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12653 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
12654 			find_good_pkt_pointers(this_branch, dst_reg,
12655 					       dst_reg->type, false);
12656 			mark_pkt_end(other_branch, insn->dst_reg, true);
12657 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12658 			    src_reg->type == PTR_TO_PACKET) ||
12659 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12660 			    src_reg->type == PTR_TO_PACKET_META)) {
12661 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
12662 			find_good_pkt_pointers(other_branch, src_reg,
12663 					       src_reg->type, true);
12664 			mark_pkt_end(this_branch, insn->src_reg, false);
12665 		} else {
12666 			return false;
12667 		}
12668 		break;
12669 	case BPF_JLT:
12670 		if ((dst_reg->type == PTR_TO_PACKET &&
12671 		     src_reg->type == PTR_TO_PACKET_END) ||
12672 		    (dst_reg->type == PTR_TO_PACKET_META &&
12673 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12674 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
12675 			find_good_pkt_pointers(other_branch, dst_reg,
12676 					       dst_reg->type, true);
12677 			mark_pkt_end(this_branch, insn->dst_reg, false);
12678 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12679 			    src_reg->type == PTR_TO_PACKET) ||
12680 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12681 			    src_reg->type == PTR_TO_PACKET_META)) {
12682 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
12683 			find_good_pkt_pointers(this_branch, src_reg,
12684 					       src_reg->type, false);
12685 			mark_pkt_end(other_branch, insn->src_reg, true);
12686 		} else {
12687 			return false;
12688 		}
12689 		break;
12690 	case BPF_JGE:
12691 		if ((dst_reg->type == PTR_TO_PACKET &&
12692 		     src_reg->type == PTR_TO_PACKET_END) ||
12693 		    (dst_reg->type == PTR_TO_PACKET_META &&
12694 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12695 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
12696 			find_good_pkt_pointers(this_branch, dst_reg,
12697 					       dst_reg->type, true);
12698 			mark_pkt_end(other_branch, insn->dst_reg, false);
12699 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12700 			    src_reg->type == PTR_TO_PACKET) ||
12701 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12702 			    src_reg->type == PTR_TO_PACKET_META)) {
12703 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
12704 			find_good_pkt_pointers(other_branch, src_reg,
12705 					       src_reg->type, false);
12706 			mark_pkt_end(this_branch, insn->src_reg, true);
12707 		} else {
12708 			return false;
12709 		}
12710 		break;
12711 	case BPF_JLE:
12712 		if ((dst_reg->type == PTR_TO_PACKET &&
12713 		     src_reg->type == PTR_TO_PACKET_END) ||
12714 		    (dst_reg->type == PTR_TO_PACKET_META &&
12715 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12716 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
12717 			find_good_pkt_pointers(other_branch, dst_reg,
12718 					       dst_reg->type, false);
12719 			mark_pkt_end(this_branch, insn->dst_reg, true);
12720 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
12721 			    src_reg->type == PTR_TO_PACKET) ||
12722 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12723 			    src_reg->type == PTR_TO_PACKET_META)) {
12724 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
12725 			find_good_pkt_pointers(this_branch, src_reg,
12726 					       src_reg->type, true);
12727 			mark_pkt_end(other_branch, insn->src_reg, false);
12728 		} else {
12729 			return false;
12730 		}
12731 		break;
12732 	default:
12733 		return false;
12734 	}
12735 
12736 	return true;
12737 }
12738 
12739 static void find_equal_scalars(struct bpf_verifier_state *vstate,
12740 			       struct bpf_reg_state *known_reg)
12741 {
12742 	struct bpf_func_state *state;
12743 	struct bpf_reg_state *reg;
12744 
12745 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12746 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
12747 			copy_register_state(reg, known_reg);
12748 	}));
12749 }
12750 
12751 static int check_cond_jmp_op(struct bpf_verifier_env *env,
12752 			     struct bpf_insn *insn, int *insn_idx)
12753 {
12754 	struct bpf_verifier_state *this_branch = env->cur_state;
12755 	struct bpf_verifier_state *other_branch;
12756 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
12757 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
12758 	struct bpf_reg_state *eq_branch_regs;
12759 	u8 opcode = BPF_OP(insn->code);
12760 	bool is_jmp32;
12761 	int pred = -1;
12762 	int err;
12763 
12764 	/* Only conditional jumps are expected to reach here. */
12765 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
12766 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12767 		return -EINVAL;
12768 	}
12769 
12770 	if (BPF_SRC(insn->code) == BPF_X) {
12771 		if (insn->imm != 0) {
12772 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12773 			return -EINVAL;
12774 		}
12775 
12776 		/* check src1 operand */
12777 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12778 		if (err)
12779 			return err;
12780 
12781 		if (is_pointer_value(env, insn->src_reg)) {
12782 			verbose(env, "R%d pointer comparison prohibited\n",
12783 				insn->src_reg);
12784 			return -EACCES;
12785 		}
12786 		src_reg = &regs[insn->src_reg];
12787 	} else {
12788 		if (insn->src_reg != BPF_REG_0) {
12789 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12790 			return -EINVAL;
12791 		}
12792 	}
12793 
12794 	/* check src2 operand */
12795 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12796 	if (err)
12797 		return err;
12798 
12799 	dst_reg = &regs[insn->dst_reg];
12800 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12801 
12802 	if (BPF_SRC(insn->code) == BPF_K) {
12803 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12804 	} else if (src_reg->type == SCALAR_VALUE &&
12805 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12806 		pred = is_branch_taken(dst_reg,
12807 				       tnum_subreg(src_reg->var_off).value,
12808 				       opcode,
12809 				       is_jmp32);
12810 	} else if (src_reg->type == SCALAR_VALUE &&
12811 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12812 		pred = is_branch_taken(dst_reg,
12813 				       src_reg->var_off.value,
12814 				       opcode,
12815 				       is_jmp32);
12816 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
12817 		   reg_is_pkt_pointer_any(src_reg) &&
12818 		   !is_jmp32) {
12819 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12820 	}
12821 
12822 	if (pred >= 0) {
12823 		/* If we get here with a dst_reg pointer type it is because
12824 		 * above is_branch_taken() special cased the 0 comparison.
12825 		 */
12826 		if (!__is_pointer_value(false, dst_reg))
12827 			err = mark_chain_precision(env, insn->dst_reg);
12828 		if (BPF_SRC(insn->code) == BPF_X && !err &&
12829 		    !__is_pointer_value(false, src_reg))
12830 			err = mark_chain_precision(env, insn->src_reg);
12831 		if (err)
12832 			return err;
12833 	}
12834 
12835 	if (pred == 1) {
12836 		/* Only follow the goto, ignore fall-through. If needed, push
12837 		 * the fall-through branch for simulation under speculative
12838 		 * execution.
12839 		 */
12840 		if (!env->bypass_spec_v1 &&
12841 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
12842 					       *insn_idx))
12843 			return -EFAULT;
12844 		*insn_idx += insn->off;
12845 		return 0;
12846 	} else if (pred == 0) {
12847 		/* Only follow the fall-through branch, since that's where the
12848 		 * program will go. If needed, push the goto branch for
12849 		 * simulation under speculative execution.
12850 		 */
12851 		if (!env->bypass_spec_v1 &&
12852 		    !sanitize_speculative_path(env, insn,
12853 					       *insn_idx + insn->off + 1,
12854 					       *insn_idx))
12855 			return -EFAULT;
12856 		return 0;
12857 	}
12858 
12859 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12860 				  false);
12861 	if (!other_branch)
12862 		return -EFAULT;
12863 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12864 
12865 	/* detect if we are comparing against a constant value so we can adjust
12866 	 * our min/max values for our dst register.
12867 	 * this is only legit if both are scalars (or pointers to the same
12868 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12869 	 * because otherwise the different base pointers mean the offsets aren't
12870 	 * comparable.
12871 	 */
12872 	if (BPF_SRC(insn->code) == BPF_X) {
12873 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
12874 
12875 		if (dst_reg->type == SCALAR_VALUE &&
12876 		    src_reg->type == SCALAR_VALUE) {
12877 			if (tnum_is_const(src_reg->var_off) ||
12878 			    (is_jmp32 &&
12879 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
12880 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
12881 						dst_reg,
12882 						src_reg->var_off.value,
12883 						tnum_subreg(src_reg->var_off).value,
12884 						opcode, is_jmp32);
12885 			else if (tnum_is_const(dst_reg->var_off) ||
12886 				 (is_jmp32 &&
12887 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
12888 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12889 						    src_reg,
12890 						    dst_reg->var_off.value,
12891 						    tnum_subreg(dst_reg->var_off).value,
12892 						    opcode, is_jmp32);
12893 			else if (!is_jmp32 &&
12894 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
12895 				/* Comparing for equality, we can combine knowledge */
12896 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
12897 						    &other_branch_regs[insn->dst_reg],
12898 						    src_reg, dst_reg, opcode);
12899 			if (src_reg->id &&
12900 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12901 				find_equal_scalars(this_branch, src_reg);
12902 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12903 			}
12904 
12905 		}
12906 	} else if (dst_reg->type == SCALAR_VALUE) {
12907 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
12908 					dst_reg, insn->imm, (u32)insn->imm,
12909 					opcode, is_jmp32);
12910 	}
12911 
12912 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12913 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12914 		find_equal_scalars(this_branch, dst_reg);
12915 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12916 	}
12917 
12918 	/* if one pointer register is compared to another pointer
12919 	 * register check if PTR_MAYBE_NULL could be lifted.
12920 	 * E.g. register A - maybe null
12921 	 *      register B - not null
12922 	 * for JNE A, B, ... - A is not null in the false branch;
12923 	 * for JEQ A, B, ... - A is not null in the true branch.
12924 	 *
12925 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
12926 	 * not need to be null checked by the BPF program, i.e.,
12927 	 * could be null even without PTR_MAYBE_NULL marking, so
12928 	 * only propagate nullness when neither reg is that type.
12929 	 */
12930 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12931 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12932 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12933 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
12934 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12935 		eq_branch_regs = NULL;
12936 		switch (opcode) {
12937 		case BPF_JEQ:
12938 			eq_branch_regs = other_branch_regs;
12939 			break;
12940 		case BPF_JNE:
12941 			eq_branch_regs = regs;
12942 			break;
12943 		default:
12944 			/* do nothing */
12945 			break;
12946 		}
12947 		if (eq_branch_regs) {
12948 			if (type_may_be_null(src_reg->type))
12949 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12950 			else
12951 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12952 		}
12953 	}
12954 
12955 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12956 	 * NOTE: these optimizations below are related with pointer comparison
12957 	 *       which will never be JMP32.
12958 	 */
12959 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12960 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12961 	    type_may_be_null(dst_reg->type)) {
12962 		/* Mark all identical registers in each branch as either
12963 		 * safe or unknown depending R == 0 or R != 0 conditional.
12964 		 */
12965 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12966 				      opcode == BPF_JNE);
12967 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12968 				      opcode == BPF_JEQ);
12969 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
12970 					   this_branch, other_branch) &&
12971 		   is_pointer_value(env, insn->dst_reg)) {
12972 		verbose(env, "R%d pointer comparison prohibited\n",
12973 			insn->dst_reg);
12974 		return -EACCES;
12975 	}
12976 	if (env->log.level & BPF_LOG_LEVEL)
12977 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
12978 	return 0;
12979 }
12980 
12981 /* verify BPF_LD_IMM64 instruction */
12982 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12983 {
12984 	struct bpf_insn_aux_data *aux = cur_aux(env);
12985 	struct bpf_reg_state *regs = cur_regs(env);
12986 	struct bpf_reg_state *dst_reg;
12987 	struct bpf_map *map;
12988 	int err;
12989 
12990 	if (BPF_SIZE(insn->code) != BPF_DW) {
12991 		verbose(env, "invalid BPF_LD_IMM insn\n");
12992 		return -EINVAL;
12993 	}
12994 	if (insn->off != 0) {
12995 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12996 		return -EINVAL;
12997 	}
12998 
12999 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
13000 	if (err)
13001 		return err;
13002 
13003 	dst_reg = &regs[insn->dst_reg];
13004 	if (insn->src_reg == 0) {
13005 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13006 
13007 		dst_reg->type = SCALAR_VALUE;
13008 		__mark_reg_known(&regs[insn->dst_reg], imm);
13009 		return 0;
13010 	}
13011 
13012 	/* All special src_reg cases are listed below. From this point onwards
13013 	 * we either succeed and assign a corresponding dst_reg->type after
13014 	 * zeroing the offset, or fail and reject the program.
13015 	 */
13016 	mark_reg_known_zero(env, regs, insn->dst_reg);
13017 
13018 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13019 		dst_reg->type = aux->btf_var.reg_type;
13020 		switch (base_type(dst_reg->type)) {
13021 		case PTR_TO_MEM:
13022 			dst_reg->mem_size = aux->btf_var.mem_size;
13023 			break;
13024 		case PTR_TO_BTF_ID:
13025 			dst_reg->btf = aux->btf_var.btf;
13026 			dst_reg->btf_id = aux->btf_var.btf_id;
13027 			break;
13028 		default:
13029 			verbose(env, "bpf verifier is misconfigured\n");
13030 			return -EFAULT;
13031 		}
13032 		return 0;
13033 	}
13034 
13035 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
13036 		struct bpf_prog_aux *aux = env->prog->aux;
13037 		u32 subprogno = find_subprog(env,
13038 					     env->insn_idx + insn->imm + 1);
13039 
13040 		if (!aux->func_info) {
13041 			verbose(env, "missing btf func_info\n");
13042 			return -EINVAL;
13043 		}
13044 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13045 			verbose(env, "callback function not static\n");
13046 			return -EINVAL;
13047 		}
13048 
13049 		dst_reg->type = PTR_TO_FUNC;
13050 		dst_reg->subprogno = subprogno;
13051 		return 0;
13052 	}
13053 
13054 	map = env->used_maps[aux->map_index];
13055 	dst_reg->map_ptr = map;
13056 
13057 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13058 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13059 		dst_reg->type = PTR_TO_MAP_VALUE;
13060 		dst_reg->off = aux->map_off;
13061 		WARN_ON_ONCE(map->max_entries != 1);
13062 		/* We want reg->id to be same (0) as map_value is not distinct */
13063 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13064 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13065 		dst_reg->type = CONST_PTR_TO_MAP;
13066 	} else {
13067 		verbose(env, "bpf verifier is misconfigured\n");
13068 		return -EINVAL;
13069 	}
13070 
13071 	return 0;
13072 }
13073 
13074 static bool may_access_skb(enum bpf_prog_type type)
13075 {
13076 	switch (type) {
13077 	case BPF_PROG_TYPE_SOCKET_FILTER:
13078 	case BPF_PROG_TYPE_SCHED_CLS:
13079 	case BPF_PROG_TYPE_SCHED_ACT:
13080 		return true;
13081 	default:
13082 		return false;
13083 	}
13084 }
13085 
13086 /* verify safety of LD_ABS|LD_IND instructions:
13087  * - they can only appear in the programs where ctx == skb
13088  * - since they are wrappers of function calls, they scratch R1-R5 registers,
13089  *   preserve R6-R9, and store return value into R0
13090  *
13091  * Implicit input:
13092  *   ctx == skb == R6 == CTX
13093  *
13094  * Explicit input:
13095  *   SRC == any register
13096  *   IMM == 32-bit immediate
13097  *
13098  * Output:
13099  *   R0 - 8/16/32-bit skb data converted to cpu endianness
13100  */
13101 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13102 {
13103 	struct bpf_reg_state *regs = cur_regs(env);
13104 	static const int ctx_reg = BPF_REG_6;
13105 	u8 mode = BPF_MODE(insn->code);
13106 	int i, err;
13107 
13108 	if (!may_access_skb(resolve_prog_type(env->prog))) {
13109 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13110 		return -EINVAL;
13111 	}
13112 
13113 	if (!env->ops->gen_ld_abs) {
13114 		verbose(env, "bpf verifier is misconfigured\n");
13115 		return -EINVAL;
13116 	}
13117 
13118 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13119 	    BPF_SIZE(insn->code) == BPF_DW ||
13120 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13121 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13122 		return -EINVAL;
13123 	}
13124 
13125 	/* check whether implicit source operand (register R6) is readable */
13126 	err = check_reg_arg(env, ctx_reg, SRC_OP);
13127 	if (err)
13128 		return err;
13129 
13130 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13131 	 * gen_ld_abs() may terminate the program at runtime, leading to
13132 	 * reference leak.
13133 	 */
13134 	err = check_reference_leak(env);
13135 	if (err) {
13136 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13137 		return err;
13138 	}
13139 
13140 	if (env->cur_state->active_lock.ptr) {
13141 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13142 		return -EINVAL;
13143 	}
13144 
13145 	if (env->cur_state->active_rcu_lock) {
13146 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13147 		return -EINVAL;
13148 	}
13149 
13150 	if (regs[ctx_reg].type != PTR_TO_CTX) {
13151 		verbose(env,
13152 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13153 		return -EINVAL;
13154 	}
13155 
13156 	if (mode == BPF_IND) {
13157 		/* check explicit source operand */
13158 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
13159 		if (err)
13160 			return err;
13161 	}
13162 
13163 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
13164 	if (err < 0)
13165 		return err;
13166 
13167 	/* reset caller saved regs to unreadable */
13168 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
13169 		mark_reg_not_init(env, regs, caller_saved[i]);
13170 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13171 	}
13172 
13173 	/* mark destination R0 register as readable, since it contains
13174 	 * the value fetched from the packet.
13175 	 * Already marked as written above.
13176 	 */
13177 	mark_reg_unknown(env, regs, BPF_REG_0);
13178 	/* ld_abs load up to 32-bit skb data. */
13179 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13180 	return 0;
13181 }
13182 
13183 static int check_return_code(struct bpf_verifier_env *env)
13184 {
13185 	struct tnum enforce_attach_type_range = tnum_unknown;
13186 	const struct bpf_prog *prog = env->prog;
13187 	struct bpf_reg_state *reg;
13188 	struct tnum range = tnum_range(0, 1);
13189 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13190 	int err;
13191 	struct bpf_func_state *frame = env->cur_state->frame[0];
13192 	const bool is_subprog = frame->subprogno;
13193 
13194 	/* LSM and struct_ops func-ptr's return type could be "void" */
13195 	if (!is_subprog) {
13196 		switch (prog_type) {
13197 		case BPF_PROG_TYPE_LSM:
13198 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
13199 				/* See below, can be 0 or 0-1 depending on hook. */
13200 				break;
13201 			fallthrough;
13202 		case BPF_PROG_TYPE_STRUCT_OPS:
13203 			if (!prog->aux->attach_func_proto->type)
13204 				return 0;
13205 			break;
13206 		default:
13207 			break;
13208 		}
13209 	}
13210 
13211 	/* eBPF calling convention is such that R0 is used
13212 	 * to return the value from eBPF program.
13213 	 * Make sure that it's readable at this time
13214 	 * of bpf_exit, which means that program wrote
13215 	 * something into it earlier
13216 	 */
13217 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13218 	if (err)
13219 		return err;
13220 
13221 	if (is_pointer_value(env, BPF_REG_0)) {
13222 		verbose(env, "R0 leaks addr as return value\n");
13223 		return -EACCES;
13224 	}
13225 
13226 	reg = cur_regs(env) + BPF_REG_0;
13227 
13228 	if (frame->in_async_callback_fn) {
13229 		/* enforce return zero from async callbacks like timer */
13230 		if (reg->type != SCALAR_VALUE) {
13231 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13232 				reg_type_str(env, reg->type));
13233 			return -EINVAL;
13234 		}
13235 
13236 		if (!tnum_in(tnum_const(0), reg->var_off)) {
13237 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13238 			return -EINVAL;
13239 		}
13240 		return 0;
13241 	}
13242 
13243 	if (is_subprog) {
13244 		if (reg->type != SCALAR_VALUE) {
13245 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
13246 				reg_type_str(env, reg->type));
13247 			return -EINVAL;
13248 		}
13249 		return 0;
13250 	}
13251 
13252 	switch (prog_type) {
13253 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13254 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
13255 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13256 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13257 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13258 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13259 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
13260 			range = tnum_range(1, 1);
13261 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13262 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13263 			range = tnum_range(0, 3);
13264 		break;
13265 	case BPF_PROG_TYPE_CGROUP_SKB:
13266 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13267 			range = tnum_range(0, 3);
13268 			enforce_attach_type_range = tnum_range(2, 3);
13269 		}
13270 		break;
13271 	case BPF_PROG_TYPE_CGROUP_SOCK:
13272 	case BPF_PROG_TYPE_SOCK_OPS:
13273 	case BPF_PROG_TYPE_CGROUP_DEVICE:
13274 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
13275 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
13276 		break;
13277 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
13278 		if (!env->prog->aux->attach_btf_id)
13279 			return 0;
13280 		range = tnum_const(0);
13281 		break;
13282 	case BPF_PROG_TYPE_TRACING:
13283 		switch (env->prog->expected_attach_type) {
13284 		case BPF_TRACE_FENTRY:
13285 		case BPF_TRACE_FEXIT:
13286 			range = tnum_const(0);
13287 			break;
13288 		case BPF_TRACE_RAW_TP:
13289 		case BPF_MODIFY_RETURN:
13290 			return 0;
13291 		case BPF_TRACE_ITER:
13292 			break;
13293 		default:
13294 			return -ENOTSUPP;
13295 		}
13296 		break;
13297 	case BPF_PROG_TYPE_SK_LOOKUP:
13298 		range = tnum_range(SK_DROP, SK_PASS);
13299 		break;
13300 
13301 	case BPF_PROG_TYPE_LSM:
13302 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13303 			/* Regular BPF_PROG_TYPE_LSM programs can return
13304 			 * any value.
13305 			 */
13306 			return 0;
13307 		}
13308 		if (!env->prog->aux->attach_func_proto->type) {
13309 			/* Make sure programs that attach to void
13310 			 * hooks don't try to modify return value.
13311 			 */
13312 			range = tnum_range(1, 1);
13313 		}
13314 		break;
13315 
13316 	case BPF_PROG_TYPE_EXT:
13317 		/* freplace program can return anything as its return value
13318 		 * depends on the to-be-replaced kernel func or bpf program.
13319 		 */
13320 	default:
13321 		return 0;
13322 	}
13323 
13324 	if (reg->type != SCALAR_VALUE) {
13325 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
13326 			reg_type_str(env, reg->type));
13327 		return -EINVAL;
13328 	}
13329 
13330 	if (!tnum_in(range, reg->var_off)) {
13331 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
13332 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
13333 		    prog_type == BPF_PROG_TYPE_LSM &&
13334 		    !prog->aux->attach_func_proto->type)
13335 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
13336 		return -EINVAL;
13337 	}
13338 
13339 	if (!tnum_is_unknown(enforce_attach_type_range) &&
13340 	    tnum_in(enforce_attach_type_range, reg->var_off))
13341 		env->prog->enforce_expected_attach_type = 1;
13342 	return 0;
13343 }
13344 
13345 /* non-recursive DFS pseudo code
13346  * 1  procedure DFS-iterative(G,v):
13347  * 2      label v as discovered
13348  * 3      let S be a stack
13349  * 4      S.push(v)
13350  * 5      while S is not empty
13351  * 6            t <- S.peek()
13352  * 7            if t is what we're looking for:
13353  * 8                return t
13354  * 9            for all edges e in G.adjacentEdges(t) do
13355  * 10               if edge e is already labelled
13356  * 11                   continue with the next edge
13357  * 12               w <- G.adjacentVertex(t,e)
13358  * 13               if vertex w is not discovered and not explored
13359  * 14                   label e as tree-edge
13360  * 15                   label w as discovered
13361  * 16                   S.push(w)
13362  * 17                   continue at 5
13363  * 18               else if vertex w is discovered
13364  * 19                   label e as back-edge
13365  * 20               else
13366  * 21                   // vertex w is explored
13367  * 22                   label e as forward- or cross-edge
13368  * 23           label t as explored
13369  * 24           S.pop()
13370  *
13371  * convention:
13372  * 0x10 - discovered
13373  * 0x11 - discovered and fall-through edge labelled
13374  * 0x12 - discovered and fall-through and branch edges labelled
13375  * 0x20 - explored
13376  */
13377 
13378 enum {
13379 	DISCOVERED = 0x10,
13380 	EXPLORED = 0x20,
13381 	FALLTHROUGH = 1,
13382 	BRANCH = 2,
13383 };
13384 
13385 static u32 state_htab_size(struct bpf_verifier_env *env)
13386 {
13387 	return env->prog->len;
13388 }
13389 
13390 static struct bpf_verifier_state_list **explored_state(
13391 					struct bpf_verifier_env *env,
13392 					int idx)
13393 {
13394 	struct bpf_verifier_state *cur = env->cur_state;
13395 	struct bpf_func_state *state = cur->frame[cur->curframe];
13396 
13397 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13398 }
13399 
13400 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13401 {
13402 	env->insn_aux_data[idx].prune_point = true;
13403 }
13404 
13405 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13406 {
13407 	return env->insn_aux_data[insn_idx].prune_point;
13408 }
13409 
13410 enum {
13411 	DONE_EXPLORING = 0,
13412 	KEEP_EXPLORING = 1,
13413 };
13414 
13415 /* t, w, e - match pseudo-code above:
13416  * t - index of current instruction
13417  * w - next instruction
13418  * e - edge
13419  */
13420 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13421 		     bool loop_ok)
13422 {
13423 	int *insn_stack = env->cfg.insn_stack;
13424 	int *insn_state = env->cfg.insn_state;
13425 
13426 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13427 		return DONE_EXPLORING;
13428 
13429 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13430 		return DONE_EXPLORING;
13431 
13432 	if (w < 0 || w >= env->prog->len) {
13433 		verbose_linfo(env, t, "%d: ", t);
13434 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
13435 		return -EINVAL;
13436 	}
13437 
13438 	if (e == BRANCH) {
13439 		/* mark branch target for state pruning */
13440 		mark_prune_point(env, w);
13441 		mark_jmp_point(env, w);
13442 	}
13443 
13444 	if (insn_state[w] == 0) {
13445 		/* tree-edge */
13446 		insn_state[t] = DISCOVERED | e;
13447 		insn_state[w] = DISCOVERED;
13448 		if (env->cfg.cur_stack >= env->prog->len)
13449 			return -E2BIG;
13450 		insn_stack[env->cfg.cur_stack++] = w;
13451 		return KEEP_EXPLORING;
13452 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13453 		if (loop_ok && env->bpf_capable)
13454 			return DONE_EXPLORING;
13455 		verbose_linfo(env, t, "%d: ", t);
13456 		verbose_linfo(env, w, "%d: ", w);
13457 		verbose(env, "back-edge from insn %d to %d\n", t, w);
13458 		return -EINVAL;
13459 	} else if (insn_state[w] == EXPLORED) {
13460 		/* forward- or cross-edge */
13461 		insn_state[t] = DISCOVERED | e;
13462 	} else {
13463 		verbose(env, "insn state internal bug\n");
13464 		return -EFAULT;
13465 	}
13466 	return DONE_EXPLORING;
13467 }
13468 
13469 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13470 				struct bpf_verifier_env *env,
13471 				bool visit_callee)
13472 {
13473 	int ret;
13474 
13475 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13476 	if (ret)
13477 		return ret;
13478 
13479 	mark_prune_point(env, t + 1);
13480 	/* when we exit from subprog, we need to record non-linear history */
13481 	mark_jmp_point(env, t + 1);
13482 
13483 	if (visit_callee) {
13484 		mark_prune_point(env, t);
13485 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13486 				/* It's ok to allow recursion from CFG point of
13487 				 * view. __check_func_call() will do the actual
13488 				 * check.
13489 				 */
13490 				bpf_pseudo_func(insns + t));
13491 	}
13492 	return ret;
13493 }
13494 
13495 /* Visits the instruction at index t and returns one of the following:
13496  *  < 0 - an error occurred
13497  *  DONE_EXPLORING - the instruction was fully explored
13498  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
13499  */
13500 static int visit_insn(int t, struct bpf_verifier_env *env)
13501 {
13502 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
13503 	int ret;
13504 
13505 	if (bpf_pseudo_func(insn))
13506 		return visit_func_call_insn(t, insns, env, true);
13507 
13508 	/* All non-branch instructions have a single fall-through edge. */
13509 	if (BPF_CLASS(insn->code) != BPF_JMP &&
13510 	    BPF_CLASS(insn->code) != BPF_JMP32)
13511 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
13512 
13513 	switch (BPF_OP(insn->code)) {
13514 	case BPF_EXIT:
13515 		return DONE_EXPLORING;
13516 
13517 	case BPF_CALL:
13518 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
13519 			/* Mark this call insn as a prune point to trigger
13520 			 * is_state_visited() check before call itself is
13521 			 * processed by __check_func_call(). Otherwise new
13522 			 * async state will be pushed for further exploration.
13523 			 */
13524 			mark_prune_point(env, t);
13525 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
13526 
13527 	case BPF_JA:
13528 		if (BPF_SRC(insn->code) != BPF_K)
13529 			return -EINVAL;
13530 
13531 		/* unconditional jump with single edge */
13532 		ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
13533 				true);
13534 		if (ret)
13535 			return ret;
13536 
13537 		mark_prune_point(env, t + insn->off + 1);
13538 		mark_jmp_point(env, t + insn->off + 1);
13539 
13540 		return ret;
13541 
13542 	default:
13543 		/* conditional jump with two edges */
13544 		mark_prune_point(env, t);
13545 
13546 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
13547 		if (ret)
13548 			return ret;
13549 
13550 		return push_insn(t, t + insn->off + 1, BRANCH, env, true);
13551 	}
13552 }
13553 
13554 /* non-recursive depth-first-search to detect loops in BPF program
13555  * loop == back-edge in directed graph
13556  */
13557 static int check_cfg(struct bpf_verifier_env *env)
13558 {
13559 	int insn_cnt = env->prog->len;
13560 	int *insn_stack, *insn_state;
13561 	int ret = 0;
13562 	int i;
13563 
13564 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13565 	if (!insn_state)
13566 		return -ENOMEM;
13567 
13568 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13569 	if (!insn_stack) {
13570 		kvfree(insn_state);
13571 		return -ENOMEM;
13572 	}
13573 
13574 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
13575 	insn_stack[0] = 0; /* 0 is the first instruction */
13576 	env->cfg.cur_stack = 1;
13577 
13578 	while (env->cfg.cur_stack > 0) {
13579 		int t = insn_stack[env->cfg.cur_stack - 1];
13580 
13581 		ret = visit_insn(t, env);
13582 		switch (ret) {
13583 		case DONE_EXPLORING:
13584 			insn_state[t] = EXPLORED;
13585 			env->cfg.cur_stack--;
13586 			break;
13587 		case KEEP_EXPLORING:
13588 			break;
13589 		default:
13590 			if (ret > 0) {
13591 				verbose(env, "visit_insn internal bug\n");
13592 				ret = -EFAULT;
13593 			}
13594 			goto err_free;
13595 		}
13596 	}
13597 
13598 	if (env->cfg.cur_stack < 0) {
13599 		verbose(env, "pop stack internal bug\n");
13600 		ret = -EFAULT;
13601 		goto err_free;
13602 	}
13603 
13604 	for (i = 0; i < insn_cnt; i++) {
13605 		if (insn_state[i] != EXPLORED) {
13606 			verbose(env, "unreachable insn %d\n", i);
13607 			ret = -EINVAL;
13608 			goto err_free;
13609 		}
13610 	}
13611 	ret = 0; /* cfg looks good */
13612 
13613 err_free:
13614 	kvfree(insn_state);
13615 	kvfree(insn_stack);
13616 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
13617 	return ret;
13618 }
13619 
13620 static int check_abnormal_return(struct bpf_verifier_env *env)
13621 {
13622 	int i;
13623 
13624 	for (i = 1; i < env->subprog_cnt; i++) {
13625 		if (env->subprog_info[i].has_ld_abs) {
13626 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
13627 			return -EINVAL;
13628 		}
13629 		if (env->subprog_info[i].has_tail_call) {
13630 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
13631 			return -EINVAL;
13632 		}
13633 	}
13634 	return 0;
13635 }
13636 
13637 /* The minimum supported BTF func info size */
13638 #define MIN_BPF_FUNCINFO_SIZE	8
13639 #define MAX_FUNCINFO_REC_SIZE	252
13640 
13641 static int check_btf_func(struct bpf_verifier_env *env,
13642 			  const union bpf_attr *attr,
13643 			  bpfptr_t uattr)
13644 {
13645 	const struct btf_type *type, *func_proto, *ret_type;
13646 	u32 i, nfuncs, urec_size, min_size;
13647 	u32 krec_size = sizeof(struct bpf_func_info);
13648 	struct bpf_func_info *krecord;
13649 	struct bpf_func_info_aux *info_aux = NULL;
13650 	struct bpf_prog *prog;
13651 	const struct btf *btf;
13652 	bpfptr_t urecord;
13653 	u32 prev_offset = 0;
13654 	bool scalar_return;
13655 	int ret = -ENOMEM;
13656 
13657 	nfuncs = attr->func_info_cnt;
13658 	if (!nfuncs) {
13659 		if (check_abnormal_return(env))
13660 			return -EINVAL;
13661 		return 0;
13662 	}
13663 
13664 	if (nfuncs != env->subprog_cnt) {
13665 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
13666 		return -EINVAL;
13667 	}
13668 
13669 	urec_size = attr->func_info_rec_size;
13670 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
13671 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
13672 	    urec_size % sizeof(u32)) {
13673 		verbose(env, "invalid func info rec size %u\n", urec_size);
13674 		return -EINVAL;
13675 	}
13676 
13677 	prog = env->prog;
13678 	btf = prog->aux->btf;
13679 
13680 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
13681 	min_size = min_t(u32, krec_size, urec_size);
13682 
13683 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
13684 	if (!krecord)
13685 		return -ENOMEM;
13686 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
13687 	if (!info_aux)
13688 		goto err_free;
13689 
13690 	for (i = 0; i < nfuncs; i++) {
13691 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
13692 		if (ret) {
13693 			if (ret == -E2BIG) {
13694 				verbose(env, "nonzero tailing record in func info");
13695 				/* set the size kernel expects so loader can zero
13696 				 * out the rest of the record.
13697 				 */
13698 				if (copy_to_bpfptr_offset(uattr,
13699 							  offsetof(union bpf_attr, func_info_rec_size),
13700 							  &min_size, sizeof(min_size)))
13701 					ret = -EFAULT;
13702 			}
13703 			goto err_free;
13704 		}
13705 
13706 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
13707 			ret = -EFAULT;
13708 			goto err_free;
13709 		}
13710 
13711 		/* check insn_off */
13712 		ret = -EINVAL;
13713 		if (i == 0) {
13714 			if (krecord[i].insn_off) {
13715 				verbose(env,
13716 					"nonzero insn_off %u for the first func info record",
13717 					krecord[i].insn_off);
13718 				goto err_free;
13719 			}
13720 		} else if (krecord[i].insn_off <= prev_offset) {
13721 			verbose(env,
13722 				"same or smaller insn offset (%u) than previous func info record (%u)",
13723 				krecord[i].insn_off, prev_offset);
13724 			goto err_free;
13725 		}
13726 
13727 		if (env->subprog_info[i].start != krecord[i].insn_off) {
13728 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
13729 			goto err_free;
13730 		}
13731 
13732 		/* check type_id */
13733 		type = btf_type_by_id(btf, krecord[i].type_id);
13734 		if (!type || !btf_type_is_func(type)) {
13735 			verbose(env, "invalid type id %d in func info",
13736 				krecord[i].type_id);
13737 			goto err_free;
13738 		}
13739 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
13740 
13741 		func_proto = btf_type_by_id(btf, type->type);
13742 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
13743 			/* btf_func_check() already verified it during BTF load */
13744 			goto err_free;
13745 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
13746 		scalar_return =
13747 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
13748 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
13749 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
13750 			goto err_free;
13751 		}
13752 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
13753 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
13754 			goto err_free;
13755 		}
13756 
13757 		prev_offset = krecord[i].insn_off;
13758 		bpfptr_add(&urecord, urec_size);
13759 	}
13760 
13761 	prog->aux->func_info = krecord;
13762 	prog->aux->func_info_cnt = nfuncs;
13763 	prog->aux->func_info_aux = info_aux;
13764 	return 0;
13765 
13766 err_free:
13767 	kvfree(krecord);
13768 	kfree(info_aux);
13769 	return ret;
13770 }
13771 
13772 static void adjust_btf_func(struct bpf_verifier_env *env)
13773 {
13774 	struct bpf_prog_aux *aux = env->prog->aux;
13775 	int i;
13776 
13777 	if (!aux->func_info)
13778 		return;
13779 
13780 	for (i = 0; i < env->subprog_cnt; i++)
13781 		aux->func_info[i].insn_off = env->subprog_info[i].start;
13782 }
13783 
13784 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
13785 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
13786 
13787 static int check_btf_line(struct bpf_verifier_env *env,
13788 			  const union bpf_attr *attr,
13789 			  bpfptr_t uattr)
13790 {
13791 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13792 	struct bpf_subprog_info *sub;
13793 	struct bpf_line_info *linfo;
13794 	struct bpf_prog *prog;
13795 	const struct btf *btf;
13796 	bpfptr_t ulinfo;
13797 	int err;
13798 
13799 	nr_linfo = attr->line_info_cnt;
13800 	if (!nr_linfo)
13801 		return 0;
13802 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13803 		return -EINVAL;
13804 
13805 	rec_size = attr->line_info_rec_size;
13806 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13807 	    rec_size > MAX_LINEINFO_REC_SIZE ||
13808 	    rec_size & (sizeof(u32) - 1))
13809 		return -EINVAL;
13810 
13811 	/* Need to zero it in case the userspace may
13812 	 * pass in a smaller bpf_line_info object.
13813 	 */
13814 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13815 			 GFP_KERNEL | __GFP_NOWARN);
13816 	if (!linfo)
13817 		return -ENOMEM;
13818 
13819 	prog = env->prog;
13820 	btf = prog->aux->btf;
13821 
13822 	s = 0;
13823 	sub = env->subprog_info;
13824 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13825 	expected_size = sizeof(struct bpf_line_info);
13826 	ncopy = min_t(u32, expected_size, rec_size);
13827 	for (i = 0; i < nr_linfo; i++) {
13828 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13829 		if (err) {
13830 			if (err == -E2BIG) {
13831 				verbose(env, "nonzero tailing record in line_info");
13832 				if (copy_to_bpfptr_offset(uattr,
13833 							  offsetof(union bpf_attr, line_info_rec_size),
13834 							  &expected_size, sizeof(expected_size)))
13835 					err = -EFAULT;
13836 			}
13837 			goto err_free;
13838 		}
13839 
13840 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13841 			err = -EFAULT;
13842 			goto err_free;
13843 		}
13844 
13845 		/*
13846 		 * Check insn_off to ensure
13847 		 * 1) strictly increasing AND
13848 		 * 2) bounded by prog->len
13849 		 *
13850 		 * The linfo[0].insn_off == 0 check logically falls into
13851 		 * the later "missing bpf_line_info for func..." case
13852 		 * because the first linfo[0].insn_off must be the
13853 		 * first sub also and the first sub must have
13854 		 * subprog_info[0].start == 0.
13855 		 */
13856 		if ((i && linfo[i].insn_off <= prev_offset) ||
13857 		    linfo[i].insn_off >= prog->len) {
13858 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13859 				i, linfo[i].insn_off, prev_offset,
13860 				prog->len);
13861 			err = -EINVAL;
13862 			goto err_free;
13863 		}
13864 
13865 		if (!prog->insnsi[linfo[i].insn_off].code) {
13866 			verbose(env,
13867 				"Invalid insn code at line_info[%u].insn_off\n",
13868 				i);
13869 			err = -EINVAL;
13870 			goto err_free;
13871 		}
13872 
13873 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13874 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13875 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13876 			err = -EINVAL;
13877 			goto err_free;
13878 		}
13879 
13880 		if (s != env->subprog_cnt) {
13881 			if (linfo[i].insn_off == sub[s].start) {
13882 				sub[s].linfo_idx = i;
13883 				s++;
13884 			} else if (sub[s].start < linfo[i].insn_off) {
13885 				verbose(env, "missing bpf_line_info for func#%u\n", s);
13886 				err = -EINVAL;
13887 				goto err_free;
13888 			}
13889 		}
13890 
13891 		prev_offset = linfo[i].insn_off;
13892 		bpfptr_add(&ulinfo, rec_size);
13893 	}
13894 
13895 	if (s != env->subprog_cnt) {
13896 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13897 			env->subprog_cnt - s, s);
13898 		err = -EINVAL;
13899 		goto err_free;
13900 	}
13901 
13902 	prog->aux->linfo = linfo;
13903 	prog->aux->nr_linfo = nr_linfo;
13904 
13905 	return 0;
13906 
13907 err_free:
13908 	kvfree(linfo);
13909 	return err;
13910 }
13911 
13912 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
13913 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
13914 
13915 static int check_core_relo(struct bpf_verifier_env *env,
13916 			   const union bpf_attr *attr,
13917 			   bpfptr_t uattr)
13918 {
13919 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13920 	struct bpf_core_relo core_relo = {};
13921 	struct bpf_prog *prog = env->prog;
13922 	const struct btf *btf = prog->aux->btf;
13923 	struct bpf_core_ctx ctx = {
13924 		.log = &env->log,
13925 		.btf = btf,
13926 	};
13927 	bpfptr_t u_core_relo;
13928 	int err;
13929 
13930 	nr_core_relo = attr->core_relo_cnt;
13931 	if (!nr_core_relo)
13932 		return 0;
13933 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13934 		return -EINVAL;
13935 
13936 	rec_size = attr->core_relo_rec_size;
13937 	if (rec_size < MIN_CORE_RELO_SIZE ||
13938 	    rec_size > MAX_CORE_RELO_SIZE ||
13939 	    rec_size % sizeof(u32))
13940 		return -EINVAL;
13941 
13942 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13943 	expected_size = sizeof(struct bpf_core_relo);
13944 	ncopy = min_t(u32, expected_size, rec_size);
13945 
13946 	/* Unlike func_info and line_info, copy and apply each CO-RE
13947 	 * relocation record one at a time.
13948 	 */
13949 	for (i = 0; i < nr_core_relo; i++) {
13950 		/* future proofing when sizeof(bpf_core_relo) changes */
13951 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13952 		if (err) {
13953 			if (err == -E2BIG) {
13954 				verbose(env, "nonzero tailing record in core_relo");
13955 				if (copy_to_bpfptr_offset(uattr,
13956 							  offsetof(union bpf_attr, core_relo_rec_size),
13957 							  &expected_size, sizeof(expected_size)))
13958 					err = -EFAULT;
13959 			}
13960 			break;
13961 		}
13962 
13963 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13964 			err = -EFAULT;
13965 			break;
13966 		}
13967 
13968 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13969 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13970 				i, core_relo.insn_off, prog->len);
13971 			err = -EINVAL;
13972 			break;
13973 		}
13974 
13975 		err = bpf_core_apply(&ctx, &core_relo, i,
13976 				     &prog->insnsi[core_relo.insn_off / 8]);
13977 		if (err)
13978 			break;
13979 		bpfptr_add(&u_core_relo, rec_size);
13980 	}
13981 	return err;
13982 }
13983 
13984 static int check_btf_info(struct bpf_verifier_env *env,
13985 			  const union bpf_attr *attr,
13986 			  bpfptr_t uattr)
13987 {
13988 	struct btf *btf;
13989 	int err;
13990 
13991 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
13992 		if (check_abnormal_return(env))
13993 			return -EINVAL;
13994 		return 0;
13995 	}
13996 
13997 	btf = btf_get_by_fd(attr->prog_btf_fd);
13998 	if (IS_ERR(btf))
13999 		return PTR_ERR(btf);
14000 	if (btf_is_kernel(btf)) {
14001 		btf_put(btf);
14002 		return -EACCES;
14003 	}
14004 	env->prog->aux->btf = btf;
14005 
14006 	err = check_btf_func(env, attr, uattr);
14007 	if (err)
14008 		return err;
14009 
14010 	err = check_btf_line(env, attr, uattr);
14011 	if (err)
14012 		return err;
14013 
14014 	err = check_core_relo(env, attr, uattr);
14015 	if (err)
14016 		return err;
14017 
14018 	return 0;
14019 }
14020 
14021 /* check %cur's range satisfies %old's */
14022 static bool range_within(struct bpf_reg_state *old,
14023 			 struct bpf_reg_state *cur)
14024 {
14025 	return old->umin_value <= cur->umin_value &&
14026 	       old->umax_value >= cur->umax_value &&
14027 	       old->smin_value <= cur->smin_value &&
14028 	       old->smax_value >= cur->smax_value &&
14029 	       old->u32_min_value <= cur->u32_min_value &&
14030 	       old->u32_max_value >= cur->u32_max_value &&
14031 	       old->s32_min_value <= cur->s32_min_value &&
14032 	       old->s32_max_value >= cur->s32_max_value;
14033 }
14034 
14035 /* If in the old state two registers had the same id, then they need to have
14036  * the same id in the new state as well.  But that id could be different from
14037  * the old state, so we need to track the mapping from old to new ids.
14038  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14039  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
14040  * regs with a different old id could still have new id 9, we don't care about
14041  * that.
14042  * So we look through our idmap to see if this old id has been seen before.  If
14043  * so, we require the new id to match; otherwise, we add the id pair to the map.
14044  */
14045 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14046 {
14047 	unsigned int i;
14048 
14049 	/* either both IDs should be set or both should be zero */
14050 	if (!!old_id != !!cur_id)
14051 		return false;
14052 
14053 	if (old_id == 0) /* cur_id == 0 as well */
14054 		return true;
14055 
14056 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14057 		if (!idmap[i].old) {
14058 			/* Reached an empty slot; haven't seen this id before */
14059 			idmap[i].old = old_id;
14060 			idmap[i].cur = cur_id;
14061 			return true;
14062 		}
14063 		if (idmap[i].old == old_id)
14064 			return idmap[i].cur == cur_id;
14065 	}
14066 	/* We ran out of idmap slots, which should be impossible */
14067 	WARN_ON_ONCE(1);
14068 	return false;
14069 }
14070 
14071 static void clean_func_state(struct bpf_verifier_env *env,
14072 			     struct bpf_func_state *st)
14073 {
14074 	enum bpf_reg_liveness live;
14075 	int i, j;
14076 
14077 	for (i = 0; i < BPF_REG_FP; i++) {
14078 		live = st->regs[i].live;
14079 		/* liveness must not touch this register anymore */
14080 		st->regs[i].live |= REG_LIVE_DONE;
14081 		if (!(live & REG_LIVE_READ))
14082 			/* since the register is unused, clear its state
14083 			 * to make further comparison simpler
14084 			 */
14085 			__mark_reg_not_init(env, &st->regs[i]);
14086 	}
14087 
14088 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14089 		live = st->stack[i].spilled_ptr.live;
14090 		/* liveness must not touch this stack slot anymore */
14091 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14092 		if (!(live & REG_LIVE_READ)) {
14093 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14094 			for (j = 0; j < BPF_REG_SIZE; j++)
14095 				st->stack[i].slot_type[j] = STACK_INVALID;
14096 		}
14097 	}
14098 }
14099 
14100 static void clean_verifier_state(struct bpf_verifier_env *env,
14101 				 struct bpf_verifier_state *st)
14102 {
14103 	int i;
14104 
14105 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14106 		/* all regs in this state in all frames were already marked */
14107 		return;
14108 
14109 	for (i = 0; i <= st->curframe; i++)
14110 		clean_func_state(env, st->frame[i]);
14111 }
14112 
14113 /* the parentage chains form a tree.
14114  * the verifier states are added to state lists at given insn and
14115  * pushed into state stack for future exploration.
14116  * when the verifier reaches bpf_exit insn some of the verifer states
14117  * stored in the state lists have their final liveness state already,
14118  * but a lot of states will get revised from liveness point of view when
14119  * the verifier explores other branches.
14120  * Example:
14121  * 1: r0 = 1
14122  * 2: if r1 == 100 goto pc+1
14123  * 3: r0 = 2
14124  * 4: exit
14125  * when the verifier reaches exit insn the register r0 in the state list of
14126  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14127  * of insn 2 and goes exploring further. At the insn 4 it will walk the
14128  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14129  *
14130  * Since the verifier pushes the branch states as it sees them while exploring
14131  * the program the condition of walking the branch instruction for the second
14132  * time means that all states below this branch were already explored and
14133  * their final liveness marks are already propagated.
14134  * Hence when the verifier completes the search of state list in is_state_visited()
14135  * we can call this clean_live_states() function to mark all liveness states
14136  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14137  * will not be used.
14138  * This function also clears the registers and stack for states that !READ
14139  * to simplify state merging.
14140  *
14141  * Important note here that walking the same branch instruction in the callee
14142  * doesn't meant that the states are DONE. The verifier has to compare
14143  * the callsites
14144  */
14145 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14146 			      struct bpf_verifier_state *cur)
14147 {
14148 	struct bpf_verifier_state_list *sl;
14149 	int i;
14150 
14151 	sl = *explored_state(env, insn);
14152 	while (sl) {
14153 		if (sl->state.branches)
14154 			goto next;
14155 		if (sl->state.insn_idx != insn ||
14156 		    sl->state.curframe != cur->curframe)
14157 			goto next;
14158 		for (i = 0; i <= cur->curframe; i++)
14159 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14160 				goto next;
14161 		clean_verifier_state(env, &sl->state);
14162 next:
14163 		sl = sl->next;
14164 	}
14165 }
14166 
14167 static bool regs_exact(const struct bpf_reg_state *rold,
14168 		       const struct bpf_reg_state *rcur,
14169 		       struct bpf_id_pair *idmap)
14170 {
14171 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
14172 	       check_ids(rold->id, rcur->id, idmap) &&
14173 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14174 }
14175 
14176 /* Returns true if (rold safe implies rcur safe) */
14177 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14178 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14179 {
14180 	if (!(rold->live & REG_LIVE_READ))
14181 		/* explored state didn't use this */
14182 		return true;
14183 	if (rold->type == NOT_INIT)
14184 		/* explored state can't have used this */
14185 		return true;
14186 	if (rcur->type == NOT_INIT)
14187 		return false;
14188 
14189 	/* Enforce that register types have to match exactly, including their
14190 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14191 	 * rule.
14192 	 *
14193 	 * One can make a point that using a pointer register as unbounded
14194 	 * SCALAR would be technically acceptable, but this could lead to
14195 	 * pointer leaks because scalars are allowed to leak while pointers
14196 	 * are not. We could make this safe in special cases if root is
14197 	 * calling us, but it's probably not worth the hassle.
14198 	 *
14199 	 * Also, register types that are *not* MAYBE_NULL could technically be
14200 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14201 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14202 	 * to the same map).
14203 	 * However, if the old MAYBE_NULL register then got NULL checked,
14204 	 * doing so could have affected others with the same id, and we can't
14205 	 * check for that because we lost the id when we converted to
14206 	 * a non-MAYBE_NULL variant.
14207 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
14208 	 * non-MAYBE_NULL registers as well.
14209 	 */
14210 	if (rold->type != rcur->type)
14211 		return false;
14212 
14213 	switch (base_type(rold->type)) {
14214 	case SCALAR_VALUE:
14215 		if (regs_exact(rold, rcur, idmap))
14216 			return true;
14217 		if (env->explore_alu_limits)
14218 			return false;
14219 		if (!rold->precise)
14220 			return true;
14221 		/* new val must satisfy old val knowledge */
14222 		return range_within(rold, rcur) &&
14223 		       tnum_in(rold->var_off, rcur->var_off);
14224 	case PTR_TO_MAP_KEY:
14225 	case PTR_TO_MAP_VALUE:
14226 	case PTR_TO_MEM:
14227 	case PTR_TO_BUF:
14228 	case PTR_TO_TP_BUFFER:
14229 		/* If the new min/max/var_off satisfy the old ones and
14230 		 * everything else matches, we are OK.
14231 		 */
14232 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
14233 		       range_within(rold, rcur) &&
14234 		       tnum_in(rold->var_off, rcur->var_off) &&
14235 		       check_ids(rold->id, rcur->id, idmap) &&
14236 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14237 	case PTR_TO_PACKET_META:
14238 	case PTR_TO_PACKET:
14239 		/* We must have at least as much range as the old ptr
14240 		 * did, so that any accesses which were safe before are
14241 		 * still safe.  This is true even if old range < old off,
14242 		 * since someone could have accessed through (ptr - k), or
14243 		 * even done ptr -= k in a register, to get a safe access.
14244 		 */
14245 		if (rold->range > rcur->range)
14246 			return false;
14247 		/* If the offsets don't match, we can't trust our alignment;
14248 		 * nor can we be sure that we won't fall out of range.
14249 		 */
14250 		if (rold->off != rcur->off)
14251 			return false;
14252 		/* id relations must be preserved */
14253 		if (!check_ids(rold->id, rcur->id, idmap))
14254 			return false;
14255 		/* new val must satisfy old val knowledge */
14256 		return range_within(rold, rcur) &&
14257 		       tnum_in(rold->var_off, rcur->var_off);
14258 	case PTR_TO_STACK:
14259 		/* two stack pointers are equal only if they're pointing to
14260 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
14261 		 */
14262 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
14263 	default:
14264 		return regs_exact(rold, rcur, idmap);
14265 	}
14266 }
14267 
14268 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14269 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
14270 {
14271 	int i, spi;
14272 
14273 	/* walk slots of the explored stack and ignore any additional
14274 	 * slots in the current stack, since explored(safe) state
14275 	 * didn't use them
14276 	 */
14277 	for (i = 0; i < old->allocated_stack; i++) {
14278 		spi = i / BPF_REG_SIZE;
14279 
14280 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14281 			i += BPF_REG_SIZE - 1;
14282 			/* explored state didn't use this */
14283 			continue;
14284 		}
14285 
14286 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14287 			continue;
14288 
14289 		if (env->allow_uninit_stack &&
14290 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14291 			continue;
14292 
14293 		/* explored stack has more populated slots than current stack
14294 		 * and these slots were used
14295 		 */
14296 		if (i >= cur->allocated_stack)
14297 			return false;
14298 
14299 		/* if old state was safe with misc data in the stack
14300 		 * it will be safe with zero-initialized stack.
14301 		 * The opposite is not true
14302 		 */
14303 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14304 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14305 			continue;
14306 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14307 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14308 			/* Ex: old explored (safe) state has STACK_SPILL in
14309 			 * this stack slot, but current has STACK_MISC ->
14310 			 * this verifier states are not equivalent,
14311 			 * return false to continue verification of this path
14312 			 */
14313 			return false;
14314 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
14315 			continue;
14316 		/* Both old and cur are having same slot_type */
14317 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14318 		case STACK_SPILL:
14319 			/* when explored and current stack slot are both storing
14320 			 * spilled registers, check that stored pointers types
14321 			 * are the same as well.
14322 			 * Ex: explored safe path could have stored
14323 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14324 			 * but current path has stored:
14325 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14326 			 * such verifier states are not equivalent.
14327 			 * return false to continue verification of this path
14328 			 */
14329 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
14330 				     &cur->stack[spi].spilled_ptr, idmap))
14331 				return false;
14332 			break;
14333 		case STACK_DYNPTR:
14334 		{
14335 			const struct bpf_reg_state *old_reg, *cur_reg;
14336 
14337 			old_reg = &old->stack[spi].spilled_ptr;
14338 			cur_reg = &cur->stack[spi].spilled_ptr;
14339 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14340 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14341 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14342 				return false;
14343 			break;
14344 		}
14345 		case STACK_MISC:
14346 		case STACK_ZERO:
14347 		case STACK_INVALID:
14348 			continue;
14349 		/* Ensure that new unhandled slot types return false by default */
14350 		default:
14351 			return false;
14352 		}
14353 	}
14354 	return true;
14355 }
14356 
14357 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14358 		    struct bpf_id_pair *idmap)
14359 {
14360 	int i;
14361 
14362 	if (old->acquired_refs != cur->acquired_refs)
14363 		return false;
14364 
14365 	for (i = 0; i < old->acquired_refs; i++) {
14366 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14367 			return false;
14368 	}
14369 
14370 	return true;
14371 }
14372 
14373 /* compare two verifier states
14374  *
14375  * all states stored in state_list are known to be valid, since
14376  * verifier reached 'bpf_exit' instruction through them
14377  *
14378  * this function is called when verifier exploring different branches of
14379  * execution popped from the state stack. If it sees an old state that has
14380  * more strict register state and more strict stack state then this execution
14381  * branch doesn't need to be explored further, since verifier already
14382  * concluded that more strict state leads to valid finish.
14383  *
14384  * Therefore two states are equivalent if register state is more conservative
14385  * and explored stack state is more conservative than the current one.
14386  * Example:
14387  *       explored                   current
14388  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14389  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14390  *
14391  * In other words if current stack state (one being explored) has more
14392  * valid slots than old one that already passed validation, it means
14393  * the verifier can stop exploring and conclude that current state is valid too
14394  *
14395  * Similarly with registers. If explored state has register type as invalid
14396  * whereas register type in current state is meaningful, it means that
14397  * the current state will reach 'bpf_exit' instruction safely
14398  */
14399 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14400 			      struct bpf_func_state *cur)
14401 {
14402 	int i;
14403 
14404 	for (i = 0; i < MAX_BPF_REG; i++)
14405 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
14406 			     env->idmap_scratch))
14407 			return false;
14408 
14409 	if (!stacksafe(env, old, cur, env->idmap_scratch))
14410 		return false;
14411 
14412 	if (!refsafe(old, cur, env->idmap_scratch))
14413 		return false;
14414 
14415 	return true;
14416 }
14417 
14418 static bool states_equal(struct bpf_verifier_env *env,
14419 			 struct bpf_verifier_state *old,
14420 			 struct bpf_verifier_state *cur)
14421 {
14422 	int i;
14423 
14424 	if (old->curframe != cur->curframe)
14425 		return false;
14426 
14427 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14428 
14429 	/* Verification state from speculative execution simulation
14430 	 * must never prune a non-speculative execution one.
14431 	 */
14432 	if (old->speculative && !cur->speculative)
14433 		return false;
14434 
14435 	if (old->active_lock.ptr != cur->active_lock.ptr)
14436 		return false;
14437 
14438 	/* Old and cur active_lock's have to be either both present
14439 	 * or both absent.
14440 	 */
14441 	if (!!old->active_lock.id != !!cur->active_lock.id)
14442 		return false;
14443 
14444 	if (old->active_lock.id &&
14445 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14446 		return false;
14447 
14448 	if (old->active_rcu_lock != cur->active_rcu_lock)
14449 		return false;
14450 
14451 	/* for states to be equal callsites have to be the same
14452 	 * and all frame states need to be equivalent
14453 	 */
14454 	for (i = 0; i <= old->curframe; i++) {
14455 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
14456 			return false;
14457 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
14458 			return false;
14459 	}
14460 	return true;
14461 }
14462 
14463 /* Return 0 if no propagation happened. Return negative error code if error
14464  * happened. Otherwise, return the propagated bit.
14465  */
14466 static int propagate_liveness_reg(struct bpf_verifier_env *env,
14467 				  struct bpf_reg_state *reg,
14468 				  struct bpf_reg_state *parent_reg)
14469 {
14470 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
14471 	u8 flag = reg->live & REG_LIVE_READ;
14472 	int err;
14473 
14474 	/* When comes here, read flags of PARENT_REG or REG could be any of
14475 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
14476 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
14477 	 */
14478 	if (parent_flag == REG_LIVE_READ64 ||
14479 	    /* Or if there is no read flag from REG. */
14480 	    !flag ||
14481 	    /* Or if the read flag from REG is the same as PARENT_REG. */
14482 	    parent_flag == flag)
14483 		return 0;
14484 
14485 	err = mark_reg_read(env, reg, parent_reg, flag);
14486 	if (err)
14487 		return err;
14488 
14489 	return flag;
14490 }
14491 
14492 /* A write screens off any subsequent reads; but write marks come from the
14493  * straight-line code between a state and its parent.  When we arrive at an
14494  * equivalent state (jump target or such) we didn't arrive by the straight-line
14495  * code, so read marks in the state must propagate to the parent regardless
14496  * of the state's write marks. That's what 'parent == state->parent' comparison
14497  * in mark_reg_read() is for.
14498  */
14499 static int propagate_liveness(struct bpf_verifier_env *env,
14500 			      const struct bpf_verifier_state *vstate,
14501 			      struct bpf_verifier_state *vparent)
14502 {
14503 	struct bpf_reg_state *state_reg, *parent_reg;
14504 	struct bpf_func_state *state, *parent;
14505 	int i, frame, err = 0;
14506 
14507 	if (vparent->curframe != vstate->curframe) {
14508 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
14509 		     vparent->curframe, vstate->curframe);
14510 		return -EFAULT;
14511 	}
14512 	/* Propagate read liveness of registers... */
14513 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
14514 	for (frame = 0; frame <= vstate->curframe; frame++) {
14515 		parent = vparent->frame[frame];
14516 		state = vstate->frame[frame];
14517 		parent_reg = parent->regs;
14518 		state_reg = state->regs;
14519 		/* We don't need to worry about FP liveness, it's read-only */
14520 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
14521 			err = propagate_liveness_reg(env, &state_reg[i],
14522 						     &parent_reg[i]);
14523 			if (err < 0)
14524 				return err;
14525 			if (err == REG_LIVE_READ64)
14526 				mark_insn_zext(env, &parent_reg[i]);
14527 		}
14528 
14529 		/* Propagate stack slots. */
14530 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
14531 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
14532 			parent_reg = &parent->stack[i].spilled_ptr;
14533 			state_reg = &state->stack[i].spilled_ptr;
14534 			err = propagate_liveness_reg(env, state_reg,
14535 						     parent_reg);
14536 			if (err < 0)
14537 				return err;
14538 		}
14539 	}
14540 	return 0;
14541 }
14542 
14543 /* find precise scalars in the previous equivalent state and
14544  * propagate them into the current state
14545  */
14546 static int propagate_precision(struct bpf_verifier_env *env,
14547 			       const struct bpf_verifier_state *old)
14548 {
14549 	struct bpf_reg_state *state_reg;
14550 	struct bpf_func_state *state;
14551 	int i, err = 0, fr;
14552 
14553 	for (fr = old->curframe; fr >= 0; fr--) {
14554 		state = old->frame[fr];
14555 		state_reg = state->regs;
14556 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
14557 			if (state_reg->type != SCALAR_VALUE ||
14558 			    !state_reg->precise)
14559 				continue;
14560 			if (env->log.level & BPF_LOG_LEVEL2)
14561 				verbose(env, "frame %d: propagating r%d\n", i, fr);
14562 			err = mark_chain_precision_frame(env, fr, i);
14563 			if (err < 0)
14564 				return err;
14565 		}
14566 
14567 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
14568 			if (!is_spilled_reg(&state->stack[i]))
14569 				continue;
14570 			state_reg = &state->stack[i].spilled_ptr;
14571 			if (state_reg->type != SCALAR_VALUE ||
14572 			    !state_reg->precise)
14573 				continue;
14574 			if (env->log.level & BPF_LOG_LEVEL2)
14575 				verbose(env, "frame %d: propagating fp%d\n",
14576 					(-i - 1) * BPF_REG_SIZE, fr);
14577 			err = mark_chain_precision_stack_frame(env, fr, i);
14578 			if (err < 0)
14579 				return err;
14580 		}
14581 	}
14582 	return 0;
14583 }
14584 
14585 static bool states_maybe_looping(struct bpf_verifier_state *old,
14586 				 struct bpf_verifier_state *cur)
14587 {
14588 	struct bpf_func_state *fold, *fcur;
14589 	int i, fr = cur->curframe;
14590 
14591 	if (old->curframe != fr)
14592 		return false;
14593 
14594 	fold = old->frame[fr];
14595 	fcur = cur->frame[fr];
14596 	for (i = 0; i < MAX_BPF_REG; i++)
14597 		if (memcmp(&fold->regs[i], &fcur->regs[i],
14598 			   offsetof(struct bpf_reg_state, parent)))
14599 			return false;
14600 	return true;
14601 }
14602 
14603 
14604 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
14605 {
14606 	struct bpf_verifier_state_list *new_sl;
14607 	struct bpf_verifier_state_list *sl, **pprev;
14608 	struct bpf_verifier_state *cur = env->cur_state, *new;
14609 	int i, j, err, states_cnt = 0;
14610 	bool add_new_state = env->test_state_freq ? true : false;
14611 
14612 	/* bpf progs typically have pruning point every 4 instructions
14613 	 * http://vger.kernel.org/bpfconf2019.html#session-1
14614 	 * Do not add new state for future pruning if the verifier hasn't seen
14615 	 * at least 2 jumps and at least 8 instructions.
14616 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
14617 	 * In tests that amounts to up to 50% reduction into total verifier
14618 	 * memory consumption and 20% verifier time speedup.
14619 	 */
14620 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
14621 	    env->insn_processed - env->prev_insn_processed >= 8)
14622 		add_new_state = true;
14623 
14624 	pprev = explored_state(env, insn_idx);
14625 	sl = *pprev;
14626 
14627 	clean_live_states(env, insn_idx, cur);
14628 
14629 	while (sl) {
14630 		states_cnt++;
14631 		if (sl->state.insn_idx != insn_idx)
14632 			goto next;
14633 
14634 		if (sl->state.branches) {
14635 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
14636 
14637 			if (frame->in_async_callback_fn &&
14638 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
14639 				/* Different async_entry_cnt means that the verifier is
14640 				 * processing another entry into async callback.
14641 				 * Seeing the same state is not an indication of infinite
14642 				 * loop or infinite recursion.
14643 				 * But finding the same state doesn't mean that it's safe
14644 				 * to stop processing the current state. The previous state
14645 				 * hasn't yet reached bpf_exit, since state.branches > 0.
14646 				 * Checking in_async_callback_fn alone is not enough either.
14647 				 * Since the verifier still needs to catch infinite loops
14648 				 * inside async callbacks.
14649 				 */
14650 			} else if (states_maybe_looping(&sl->state, cur) &&
14651 				   states_equal(env, &sl->state, cur)) {
14652 				verbose_linfo(env, insn_idx, "; ");
14653 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
14654 				return -EINVAL;
14655 			}
14656 			/* if the verifier is processing a loop, avoid adding new state
14657 			 * too often, since different loop iterations have distinct
14658 			 * states and may not help future pruning.
14659 			 * This threshold shouldn't be too low to make sure that
14660 			 * a loop with large bound will be rejected quickly.
14661 			 * The most abusive loop will be:
14662 			 * r1 += 1
14663 			 * if r1 < 1000000 goto pc-2
14664 			 * 1M insn_procssed limit / 100 == 10k peak states.
14665 			 * This threshold shouldn't be too high either, since states
14666 			 * at the end of the loop are likely to be useful in pruning.
14667 			 */
14668 			if (!env->test_state_freq &&
14669 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
14670 			    env->insn_processed - env->prev_insn_processed < 100)
14671 				add_new_state = false;
14672 			goto miss;
14673 		}
14674 		if (states_equal(env, &sl->state, cur)) {
14675 			sl->hit_cnt++;
14676 			/* reached equivalent register/stack state,
14677 			 * prune the search.
14678 			 * Registers read by the continuation are read by us.
14679 			 * If we have any write marks in env->cur_state, they
14680 			 * will prevent corresponding reads in the continuation
14681 			 * from reaching our parent (an explored_state).  Our
14682 			 * own state will get the read marks recorded, but
14683 			 * they'll be immediately forgotten as we're pruning
14684 			 * this state and will pop a new one.
14685 			 */
14686 			err = propagate_liveness(env, &sl->state, cur);
14687 
14688 			/* if previous state reached the exit with precision and
14689 			 * current state is equivalent to it (except precsion marks)
14690 			 * the precision needs to be propagated back in
14691 			 * the current state.
14692 			 */
14693 			err = err ? : push_jmp_history(env, cur);
14694 			err = err ? : propagate_precision(env, &sl->state);
14695 			if (err)
14696 				return err;
14697 			return 1;
14698 		}
14699 miss:
14700 		/* when new state is not going to be added do not increase miss count.
14701 		 * Otherwise several loop iterations will remove the state
14702 		 * recorded earlier. The goal of these heuristics is to have
14703 		 * states from some iterations of the loop (some in the beginning
14704 		 * and some at the end) to help pruning.
14705 		 */
14706 		if (add_new_state)
14707 			sl->miss_cnt++;
14708 		/* heuristic to determine whether this state is beneficial
14709 		 * to keep checking from state equivalence point of view.
14710 		 * Higher numbers increase max_states_per_insn and verification time,
14711 		 * but do not meaningfully decrease insn_processed.
14712 		 */
14713 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
14714 			/* the state is unlikely to be useful. Remove it to
14715 			 * speed up verification
14716 			 */
14717 			*pprev = sl->next;
14718 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
14719 				u32 br = sl->state.branches;
14720 
14721 				WARN_ONCE(br,
14722 					  "BUG live_done but branches_to_explore %d\n",
14723 					  br);
14724 				free_verifier_state(&sl->state, false);
14725 				kfree(sl);
14726 				env->peak_states--;
14727 			} else {
14728 				/* cannot free this state, since parentage chain may
14729 				 * walk it later. Add it for free_list instead to
14730 				 * be freed at the end of verification
14731 				 */
14732 				sl->next = env->free_list;
14733 				env->free_list = sl;
14734 			}
14735 			sl = *pprev;
14736 			continue;
14737 		}
14738 next:
14739 		pprev = &sl->next;
14740 		sl = *pprev;
14741 	}
14742 
14743 	if (env->max_states_per_insn < states_cnt)
14744 		env->max_states_per_insn = states_cnt;
14745 
14746 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
14747 		return 0;
14748 
14749 	if (!add_new_state)
14750 		return 0;
14751 
14752 	/* There were no equivalent states, remember the current one.
14753 	 * Technically the current state is not proven to be safe yet,
14754 	 * but it will either reach outer most bpf_exit (which means it's safe)
14755 	 * or it will be rejected. When there are no loops the verifier won't be
14756 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
14757 	 * again on the way to bpf_exit.
14758 	 * When looping the sl->state.branches will be > 0 and this state
14759 	 * will not be considered for equivalence until branches == 0.
14760 	 */
14761 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
14762 	if (!new_sl)
14763 		return -ENOMEM;
14764 	env->total_states++;
14765 	env->peak_states++;
14766 	env->prev_jmps_processed = env->jmps_processed;
14767 	env->prev_insn_processed = env->insn_processed;
14768 
14769 	/* forget precise markings we inherited, see __mark_chain_precision */
14770 	if (env->bpf_capable)
14771 		mark_all_scalars_imprecise(env, cur);
14772 
14773 	/* add new state to the head of linked list */
14774 	new = &new_sl->state;
14775 	err = copy_verifier_state(new, cur);
14776 	if (err) {
14777 		free_verifier_state(new, false);
14778 		kfree(new_sl);
14779 		return err;
14780 	}
14781 	new->insn_idx = insn_idx;
14782 	WARN_ONCE(new->branches != 1,
14783 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14784 
14785 	cur->parent = new;
14786 	cur->first_insn_idx = insn_idx;
14787 	clear_jmp_history(cur);
14788 	new_sl->next = *explored_state(env, insn_idx);
14789 	*explored_state(env, insn_idx) = new_sl;
14790 	/* connect new state to parentage chain. Current frame needs all
14791 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
14792 	 * to the stack implicitly by JITs) so in callers' frames connect just
14793 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14794 	 * the state of the call instruction (with WRITTEN set), and r0 comes
14795 	 * from callee with its full parentage chain, anyway.
14796 	 */
14797 	/* clear write marks in current state: the writes we did are not writes
14798 	 * our child did, so they don't screen off its reads from us.
14799 	 * (There are no read marks in current state, because reads always mark
14800 	 * their parent and current state never has children yet.  Only
14801 	 * explored_states can get read marks.)
14802 	 */
14803 	for (j = 0; j <= cur->curframe; j++) {
14804 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14805 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14806 		for (i = 0; i < BPF_REG_FP; i++)
14807 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14808 	}
14809 
14810 	/* all stack frames are accessible from callee, clear them all */
14811 	for (j = 0; j <= cur->curframe; j++) {
14812 		struct bpf_func_state *frame = cur->frame[j];
14813 		struct bpf_func_state *newframe = new->frame[j];
14814 
14815 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14816 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14817 			frame->stack[i].spilled_ptr.parent =
14818 						&newframe->stack[i].spilled_ptr;
14819 		}
14820 	}
14821 	return 0;
14822 }
14823 
14824 /* Return true if it's OK to have the same insn return a different type. */
14825 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14826 {
14827 	switch (base_type(type)) {
14828 	case PTR_TO_CTX:
14829 	case PTR_TO_SOCKET:
14830 	case PTR_TO_SOCK_COMMON:
14831 	case PTR_TO_TCP_SOCK:
14832 	case PTR_TO_XDP_SOCK:
14833 	case PTR_TO_BTF_ID:
14834 		return false;
14835 	default:
14836 		return true;
14837 	}
14838 }
14839 
14840 /* If an instruction was previously used with particular pointer types, then we
14841  * need to be careful to avoid cases such as the below, where it may be ok
14842  * for one branch accessing the pointer, but not ok for the other branch:
14843  *
14844  * R1 = sock_ptr
14845  * goto X;
14846  * ...
14847  * R1 = some_other_valid_ptr;
14848  * goto X;
14849  * ...
14850  * R2 = *(u32 *)(R1 + 0);
14851  */
14852 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14853 {
14854 	return src != prev && (!reg_type_mismatch_ok(src) ||
14855 			       !reg_type_mismatch_ok(prev));
14856 }
14857 
14858 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
14859 			     bool allow_trust_missmatch)
14860 {
14861 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14862 
14863 	if (*prev_type == NOT_INIT) {
14864 		/* Saw a valid insn
14865 		 * dst_reg = *(u32 *)(src_reg + off)
14866 		 * save type to validate intersecting paths
14867 		 */
14868 		*prev_type = type;
14869 	} else if (reg_type_mismatch(type, *prev_type)) {
14870 		/* Abuser program is trying to use the same insn
14871 		 * dst_reg = *(u32*) (src_reg + off)
14872 		 * with different pointer types:
14873 		 * src_reg == ctx in one branch and
14874 		 * src_reg == stack|map in some other branch.
14875 		 * Reject it.
14876 		 */
14877 		if (allow_trust_missmatch &&
14878 		    base_type(type) == PTR_TO_BTF_ID &&
14879 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
14880 			/*
14881 			 * Have to support a use case when one path through
14882 			 * the program yields TRUSTED pointer while another
14883 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
14884 			 * BPF_PROBE_MEM.
14885 			 */
14886 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
14887 		} else {
14888 			verbose(env, "same insn cannot be used with different pointers\n");
14889 			return -EINVAL;
14890 		}
14891 	}
14892 
14893 	return 0;
14894 }
14895 
14896 static int do_check(struct bpf_verifier_env *env)
14897 {
14898 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14899 	struct bpf_verifier_state *state = env->cur_state;
14900 	struct bpf_insn *insns = env->prog->insnsi;
14901 	struct bpf_reg_state *regs;
14902 	int insn_cnt = env->prog->len;
14903 	bool do_print_state = false;
14904 	int prev_insn_idx = -1;
14905 
14906 	for (;;) {
14907 		struct bpf_insn *insn;
14908 		u8 class;
14909 		int err;
14910 
14911 		env->prev_insn_idx = prev_insn_idx;
14912 		if (env->insn_idx >= insn_cnt) {
14913 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
14914 				env->insn_idx, insn_cnt);
14915 			return -EFAULT;
14916 		}
14917 
14918 		insn = &insns[env->insn_idx];
14919 		class = BPF_CLASS(insn->code);
14920 
14921 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14922 			verbose(env,
14923 				"BPF program is too large. Processed %d insn\n",
14924 				env->insn_processed);
14925 			return -E2BIG;
14926 		}
14927 
14928 		state->last_insn_idx = env->prev_insn_idx;
14929 
14930 		if (is_prune_point(env, env->insn_idx)) {
14931 			err = is_state_visited(env, env->insn_idx);
14932 			if (err < 0)
14933 				return err;
14934 			if (err == 1) {
14935 				/* found equivalent state, can prune the search */
14936 				if (env->log.level & BPF_LOG_LEVEL) {
14937 					if (do_print_state)
14938 						verbose(env, "\nfrom %d to %d%s: safe\n",
14939 							env->prev_insn_idx, env->insn_idx,
14940 							env->cur_state->speculative ?
14941 							" (speculative execution)" : "");
14942 					else
14943 						verbose(env, "%d: safe\n", env->insn_idx);
14944 				}
14945 				goto process_bpf_exit;
14946 			}
14947 		}
14948 
14949 		if (is_jmp_point(env, env->insn_idx)) {
14950 			err = push_jmp_history(env, state);
14951 			if (err)
14952 				return err;
14953 		}
14954 
14955 		if (signal_pending(current))
14956 			return -EAGAIN;
14957 
14958 		if (need_resched())
14959 			cond_resched();
14960 
14961 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14962 			verbose(env, "\nfrom %d to %d%s:",
14963 				env->prev_insn_idx, env->insn_idx,
14964 				env->cur_state->speculative ?
14965 				" (speculative execution)" : "");
14966 			print_verifier_state(env, state->frame[state->curframe], true);
14967 			do_print_state = false;
14968 		}
14969 
14970 		if (env->log.level & BPF_LOG_LEVEL) {
14971 			const struct bpf_insn_cbs cbs = {
14972 				.cb_call	= disasm_kfunc_name,
14973 				.cb_print	= verbose,
14974 				.private_data	= env,
14975 			};
14976 
14977 			if (verifier_state_scratched(env))
14978 				print_insn_state(env, state->frame[state->curframe]);
14979 
14980 			verbose_linfo(env, env->insn_idx, "; ");
14981 			env->prev_log_len = env->log.len_used;
14982 			verbose(env, "%d: ", env->insn_idx);
14983 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14984 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14985 			env->prev_log_len = env->log.len_used;
14986 		}
14987 
14988 		if (bpf_prog_is_offloaded(env->prog->aux)) {
14989 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14990 							   env->prev_insn_idx);
14991 			if (err)
14992 				return err;
14993 		}
14994 
14995 		regs = cur_regs(env);
14996 		sanitize_mark_insn_seen(env);
14997 		prev_insn_idx = env->insn_idx;
14998 
14999 		if (class == BPF_ALU || class == BPF_ALU64) {
15000 			err = check_alu_op(env, insn);
15001 			if (err)
15002 				return err;
15003 
15004 		} else if (class == BPF_LDX) {
15005 			enum bpf_reg_type src_reg_type;
15006 
15007 			/* check for reserved fields is already done */
15008 
15009 			/* check src operand */
15010 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15011 			if (err)
15012 				return err;
15013 
15014 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15015 			if (err)
15016 				return err;
15017 
15018 			src_reg_type = regs[insn->src_reg].type;
15019 
15020 			/* check that memory (src_reg + off) is readable,
15021 			 * the state of dst_reg will be updated by this func
15022 			 */
15023 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
15024 					       insn->off, BPF_SIZE(insn->code),
15025 					       BPF_READ, insn->dst_reg, false);
15026 			if (err)
15027 				return err;
15028 
15029 			err = save_aux_ptr_type(env, src_reg_type, true);
15030 			if (err)
15031 				return err;
15032 		} else if (class == BPF_STX) {
15033 			enum bpf_reg_type dst_reg_type;
15034 
15035 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15036 				err = check_atomic(env, env->insn_idx, insn);
15037 				if (err)
15038 					return err;
15039 				env->insn_idx++;
15040 				continue;
15041 			}
15042 
15043 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15044 				verbose(env, "BPF_STX uses reserved fields\n");
15045 				return -EINVAL;
15046 			}
15047 
15048 			/* check src1 operand */
15049 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15050 			if (err)
15051 				return err;
15052 			/* check src2 operand */
15053 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15054 			if (err)
15055 				return err;
15056 
15057 			dst_reg_type = regs[insn->dst_reg].type;
15058 
15059 			/* check that memory (dst_reg + off) is writeable */
15060 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15061 					       insn->off, BPF_SIZE(insn->code),
15062 					       BPF_WRITE, insn->src_reg, false);
15063 			if (err)
15064 				return err;
15065 
15066 			err = save_aux_ptr_type(env, dst_reg_type, false);
15067 			if (err)
15068 				return err;
15069 		} else if (class == BPF_ST) {
15070 			enum bpf_reg_type dst_reg_type;
15071 
15072 			if (BPF_MODE(insn->code) != BPF_MEM ||
15073 			    insn->src_reg != BPF_REG_0) {
15074 				verbose(env, "BPF_ST uses reserved fields\n");
15075 				return -EINVAL;
15076 			}
15077 			/* check src operand */
15078 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15079 			if (err)
15080 				return err;
15081 
15082 			dst_reg_type = regs[insn->dst_reg].type;
15083 
15084 			/* check that memory (dst_reg + off) is writeable */
15085 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15086 					       insn->off, BPF_SIZE(insn->code),
15087 					       BPF_WRITE, -1, false);
15088 			if (err)
15089 				return err;
15090 
15091 			err = save_aux_ptr_type(env, dst_reg_type, false);
15092 			if (err)
15093 				return err;
15094 		} else if (class == BPF_JMP || class == BPF_JMP32) {
15095 			u8 opcode = BPF_OP(insn->code);
15096 
15097 			env->jmps_processed++;
15098 			if (opcode == BPF_CALL) {
15099 				if (BPF_SRC(insn->code) != BPF_K ||
15100 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15101 				     && insn->off != 0) ||
15102 				    (insn->src_reg != BPF_REG_0 &&
15103 				     insn->src_reg != BPF_PSEUDO_CALL &&
15104 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
15105 				    insn->dst_reg != BPF_REG_0 ||
15106 				    class == BPF_JMP32) {
15107 					verbose(env, "BPF_CALL uses reserved fields\n");
15108 					return -EINVAL;
15109 				}
15110 
15111 				if (env->cur_state->active_lock.ptr) {
15112 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15113 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
15114 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
15115 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
15116 						verbose(env, "function calls are not allowed while holding a lock\n");
15117 						return -EINVAL;
15118 					}
15119 				}
15120 				if (insn->src_reg == BPF_PSEUDO_CALL)
15121 					err = check_func_call(env, insn, &env->insn_idx);
15122 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
15123 					err = check_kfunc_call(env, insn, &env->insn_idx);
15124 				else
15125 					err = check_helper_call(env, insn, &env->insn_idx);
15126 				if (err)
15127 					return err;
15128 
15129 				mark_reg_scratched(env, BPF_REG_0);
15130 			} else if (opcode == BPF_JA) {
15131 				if (BPF_SRC(insn->code) != BPF_K ||
15132 				    insn->imm != 0 ||
15133 				    insn->src_reg != BPF_REG_0 ||
15134 				    insn->dst_reg != BPF_REG_0 ||
15135 				    class == BPF_JMP32) {
15136 					verbose(env, "BPF_JA uses reserved fields\n");
15137 					return -EINVAL;
15138 				}
15139 
15140 				env->insn_idx += insn->off + 1;
15141 				continue;
15142 
15143 			} else if (opcode == BPF_EXIT) {
15144 				if (BPF_SRC(insn->code) != BPF_K ||
15145 				    insn->imm != 0 ||
15146 				    insn->src_reg != BPF_REG_0 ||
15147 				    insn->dst_reg != BPF_REG_0 ||
15148 				    class == BPF_JMP32) {
15149 					verbose(env, "BPF_EXIT uses reserved fields\n");
15150 					return -EINVAL;
15151 				}
15152 
15153 				if (env->cur_state->active_lock.ptr &&
15154 				    !in_rbtree_lock_required_cb(env)) {
15155 					verbose(env, "bpf_spin_unlock is missing\n");
15156 					return -EINVAL;
15157 				}
15158 
15159 				if (env->cur_state->active_rcu_lock) {
15160 					verbose(env, "bpf_rcu_read_unlock is missing\n");
15161 					return -EINVAL;
15162 				}
15163 
15164 				/* We must do check_reference_leak here before
15165 				 * prepare_func_exit to handle the case when
15166 				 * state->curframe > 0, it may be a callback
15167 				 * function, for which reference_state must
15168 				 * match caller reference state when it exits.
15169 				 */
15170 				err = check_reference_leak(env);
15171 				if (err)
15172 					return err;
15173 
15174 				if (state->curframe) {
15175 					/* exit from nested function */
15176 					err = prepare_func_exit(env, &env->insn_idx);
15177 					if (err)
15178 						return err;
15179 					do_print_state = true;
15180 					continue;
15181 				}
15182 
15183 				err = check_return_code(env);
15184 				if (err)
15185 					return err;
15186 process_bpf_exit:
15187 				mark_verifier_state_scratched(env);
15188 				update_branch_counts(env, env->cur_state);
15189 				err = pop_stack(env, &prev_insn_idx,
15190 						&env->insn_idx, pop_log);
15191 				if (err < 0) {
15192 					if (err != -ENOENT)
15193 						return err;
15194 					break;
15195 				} else {
15196 					do_print_state = true;
15197 					continue;
15198 				}
15199 			} else {
15200 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
15201 				if (err)
15202 					return err;
15203 			}
15204 		} else if (class == BPF_LD) {
15205 			u8 mode = BPF_MODE(insn->code);
15206 
15207 			if (mode == BPF_ABS || mode == BPF_IND) {
15208 				err = check_ld_abs(env, insn);
15209 				if (err)
15210 					return err;
15211 
15212 			} else if (mode == BPF_IMM) {
15213 				err = check_ld_imm(env, insn);
15214 				if (err)
15215 					return err;
15216 
15217 				env->insn_idx++;
15218 				sanitize_mark_insn_seen(env);
15219 			} else {
15220 				verbose(env, "invalid BPF_LD mode\n");
15221 				return -EINVAL;
15222 			}
15223 		} else {
15224 			verbose(env, "unknown insn class %d\n", class);
15225 			return -EINVAL;
15226 		}
15227 
15228 		env->insn_idx++;
15229 	}
15230 
15231 	return 0;
15232 }
15233 
15234 static int find_btf_percpu_datasec(struct btf *btf)
15235 {
15236 	const struct btf_type *t;
15237 	const char *tname;
15238 	int i, n;
15239 
15240 	/*
15241 	 * Both vmlinux and module each have their own ".data..percpu"
15242 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15243 	 * types to look at only module's own BTF types.
15244 	 */
15245 	n = btf_nr_types(btf);
15246 	if (btf_is_module(btf))
15247 		i = btf_nr_types(btf_vmlinux);
15248 	else
15249 		i = 1;
15250 
15251 	for(; i < n; i++) {
15252 		t = btf_type_by_id(btf, i);
15253 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15254 			continue;
15255 
15256 		tname = btf_name_by_offset(btf, t->name_off);
15257 		if (!strcmp(tname, ".data..percpu"))
15258 			return i;
15259 	}
15260 
15261 	return -ENOENT;
15262 }
15263 
15264 /* replace pseudo btf_id with kernel symbol address */
15265 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15266 			       struct bpf_insn *insn,
15267 			       struct bpf_insn_aux_data *aux)
15268 {
15269 	const struct btf_var_secinfo *vsi;
15270 	const struct btf_type *datasec;
15271 	struct btf_mod_pair *btf_mod;
15272 	const struct btf_type *t;
15273 	const char *sym_name;
15274 	bool percpu = false;
15275 	u32 type, id = insn->imm;
15276 	struct btf *btf;
15277 	s32 datasec_id;
15278 	u64 addr;
15279 	int i, btf_fd, err;
15280 
15281 	btf_fd = insn[1].imm;
15282 	if (btf_fd) {
15283 		btf = btf_get_by_fd(btf_fd);
15284 		if (IS_ERR(btf)) {
15285 			verbose(env, "invalid module BTF object FD specified.\n");
15286 			return -EINVAL;
15287 		}
15288 	} else {
15289 		if (!btf_vmlinux) {
15290 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15291 			return -EINVAL;
15292 		}
15293 		btf = btf_vmlinux;
15294 		btf_get(btf);
15295 	}
15296 
15297 	t = btf_type_by_id(btf, id);
15298 	if (!t) {
15299 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
15300 		err = -ENOENT;
15301 		goto err_put;
15302 	}
15303 
15304 	if (!btf_type_is_var(t)) {
15305 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
15306 		err = -EINVAL;
15307 		goto err_put;
15308 	}
15309 
15310 	sym_name = btf_name_by_offset(btf, t->name_off);
15311 	addr = kallsyms_lookup_name(sym_name);
15312 	if (!addr) {
15313 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15314 			sym_name);
15315 		err = -ENOENT;
15316 		goto err_put;
15317 	}
15318 
15319 	datasec_id = find_btf_percpu_datasec(btf);
15320 	if (datasec_id > 0) {
15321 		datasec = btf_type_by_id(btf, datasec_id);
15322 		for_each_vsi(i, datasec, vsi) {
15323 			if (vsi->type == id) {
15324 				percpu = true;
15325 				break;
15326 			}
15327 		}
15328 	}
15329 
15330 	insn[0].imm = (u32)addr;
15331 	insn[1].imm = addr >> 32;
15332 
15333 	type = t->type;
15334 	t = btf_type_skip_modifiers(btf, type, NULL);
15335 	if (percpu) {
15336 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
15337 		aux->btf_var.btf = btf;
15338 		aux->btf_var.btf_id = type;
15339 	} else if (!btf_type_is_struct(t)) {
15340 		const struct btf_type *ret;
15341 		const char *tname;
15342 		u32 tsize;
15343 
15344 		/* resolve the type size of ksym. */
15345 		ret = btf_resolve_size(btf, t, &tsize);
15346 		if (IS_ERR(ret)) {
15347 			tname = btf_name_by_offset(btf, t->name_off);
15348 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
15349 				tname, PTR_ERR(ret));
15350 			err = -EINVAL;
15351 			goto err_put;
15352 		}
15353 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15354 		aux->btf_var.mem_size = tsize;
15355 	} else {
15356 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
15357 		aux->btf_var.btf = btf;
15358 		aux->btf_var.btf_id = type;
15359 	}
15360 
15361 	/* check whether we recorded this BTF (and maybe module) already */
15362 	for (i = 0; i < env->used_btf_cnt; i++) {
15363 		if (env->used_btfs[i].btf == btf) {
15364 			btf_put(btf);
15365 			return 0;
15366 		}
15367 	}
15368 
15369 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
15370 		err = -E2BIG;
15371 		goto err_put;
15372 	}
15373 
15374 	btf_mod = &env->used_btfs[env->used_btf_cnt];
15375 	btf_mod->btf = btf;
15376 	btf_mod->module = NULL;
15377 
15378 	/* if we reference variables from kernel module, bump its refcount */
15379 	if (btf_is_module(btf)) {
15380 		btf_mod->module = btf_try_get_module(btf);
15381 		if (!btf_mod->module) {
15382 			err = -ENXIO;
15383 			goto err_put;
15384 		}
15385 	}
15386 
15387 	env->used_btf_cnt++;
15388 
15389 	return 0;
15390 err_put:
15391 	btf_put(btf);
15392 	return err;
15393 }
15394 
15395 static bool is_tracing_prog_type(enum bpf_prog_type type)
15396 {
15397 	switch (type) {
15398 	case BPF_PROG_TYPE_KPROBE:
15399 	case BPF_PROG_TYPE_TRACEPOINT:
15400 	case BPF_PROG_TYPE_PERF_EVENT:
15401 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15402 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
15403 		return true;
15404 	default:
15405 		return false;
15406 	}
15407 }
15408 
15409 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
15410 					struct bpf_map *map,
15411 					struct bpf_prog *prog)
15412 
15413 {
15414 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15415 
15416 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
15417 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
15418 		if (is_tracing_prog_type(prog_type)) {
15419 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
15420 			return -EINVAL;
15421 		}
15422 	}
15423 
15424 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
15425 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
15426 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
15427 			return -EINVAL;
15428 		}
15429 
15430 		if (is_tracing_prog_type(prog_type)) {
15431 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
15432 			return -EINVAL;
15433 		}
15434 
15435 		if (prog->aux->sleepable) {
15436 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
15437 			return -EINVAL;
15438 		}
15439 	}
15440 
15441 	if (btf_record_has_field(map->record, BPF_TIMER)) {
15442 		if (is_tracing_prog_type(prog_type)) {
15443 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
15444 			return -EINVAL;
15445 		}
15446 	}
15447 
15448 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
15449 	    !bpf_offload_prog_map_match(prog, map)) {
15450 		verbose(env, "offload device mismatch between prog and map\n");
15451 		return -EINVAL;
15452 	}
15453 
15454 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
15455 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
15456 		return -EINVAL;
15457 	}
15458 
15459 	if (prog->aux->sleepable)
15460 		switch (map->map_type) {
15461 		case BPF_MAP_TYPE_HASH:
15462 		case BPF_MAP_TYPE_LRU_HASH:
15463 		case BPF_MAP_TYPE_ARRAY:
15464 		case BPF_MAP_TYPE_PERCPU_HASH:
15465 		case BPF_MAP_TYPE_PERCPU_ARRAY:
15466 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
15467 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
15468 		case BPF_MAP_TYPE_HASH_OF_MAPS:
15469 		case BPF_MAP_TYPE_RINGBUF:
15470 		case BPF_MAP_TYPE_USER_RINGBUF:
15471 		case BPF_MAP_TYPE_INODE_STORAGE:
15472 		case BPF_MAP_TYPE_SK_STORAGE:
15473 		case BPF_MAP_TYPE_TASK_STORAGE:
15474 		case BPF_MAP_TYPE_CGRP_STORAGE:
15475 			break;
15476 		default:
15477 			verbose(env,
15478 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
15479 			return -EINVAL;
15480 		}
15481 
15482 	return 0;
15483 }
15484 
15485 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
15486 {
15487 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
15488 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
15489 }
15490 
15491 /* find and rewrite pseudo imm in ld_imm64 instructions:
15492  *
15493  * 1. if it accesses map FD, replace it with actual map pointer.
15494  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
15495  *
15496  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
15497  */
15498 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
15499 {
15500 	struct bpf_insn *insn = env->prog->insnsi;
15501 	int insn_cnt = env->prog->len;
15502 	int i, j, err;
15503 
15504 	err = bpf_prog_calc_tag(env->prog);
15505 	if (err)
15506 		return err;
15507 
15508 	for (i = 0; i < insn_cnt; i++, insn++) {
15509 		if (BPF_CLASS(insn->code) == BPF_LDX &&
15510 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
15511 			verbose(env, "BPF_LDX uses reserved fields\n");
15512 			return -EINVAL;
15513 		}
15514 
15515 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
15516 			struct bpf_insn_aux_data *aux;
15517 			struct bpf_map *map;
15518 			struct fd f;
15519 			u64 addr;
15520 			u32 fd;
15521 
15522 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
15523 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
15524 			    insn[1].off != 0) {
15525 				verbose(env, "invalid bpf_ld_imm64 insn\n");
15526 				return -EINVAL;
15527 			}
15528 
15529 			if (insn[0].src_reg == 0)
15530 				/* valid generic load 64-bit imm */
15531 				goto next_insn;
15532 
15533 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
15534 				aux = &env->insn_aux_data[i];
15535 				err = check_pseudo_btf_id(env, insn, aux);
15536 				if (err)
15537 					return err;
15538 				goto next_insn;
15539 			}
15540 
15541 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
15542 				aux = &env->insn_aux_data[i];
15543 				aux->ptr_type = PTR_TO_FUNC;
15544 				goto next_insn;
15545 			}
15546 
15547 			/* In final convert_pseudo_ld_imm64() step, this is
15548 			 * converted into regular 64-bit imm load insn.
15549 			 */
15550 			switch (insn[0].src_reg) {
15551 			case BPF_PSEUDO_MAP_VALUE:
15552 			case BPF_PSEUDO_MAP_IDX_VALUE:
15553 				break;
15554 			case BPF_PSEUDO_MAP_FD:
15555 			case BPF_PSEUDO_MAP_IDX:
15556 				if (insn[1].imm == 0)
15557 					break;
15558 				fallthrough;
15559 			default:
15560 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
15561 				return -EINVAL;
15562 			}
15563 
15564 			switch (insn[0].src_reg) {
15565 			case BPF_PSEUDO_MAP_IDX_VALUE:
15566 			case BPF_PSEUDO_MAP_IDX:
15567 				if (bpfptr_is_null(env->fd_array)) {
15568 					verbose(env, "fd_idx without fd_array is invalid\n");
15569 					return -EPROTO;
15570 				}
15571 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
15572 							    insn[0].imm * sizeof(fd),
15573 							    sizeof(fd)))
15574 					return -EFAULT;
15575 				break;
15576 			default:
15577 				fd = insn[0].imm;
15578 				break;
15579 			}
15580 
15581 			f = fdget(fd);
15582 			map = __bpf_map_get(f);
15583 			if (IS_ERR(map)) {
15584 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
15585 					insn[0].imm);
15586 				return PTR_ERR(map);
15587 			}
15588 
15589 			err = check_map_prog_compatibility(env, map, env->prog);
15590 			if (err) {
15591 				fdput(f);
15592 				return err;
15593 			}
15594 
15595 			aux = &env->insn_aux_data[i];
15596 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
15597 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
15598 				addr = (unsigned long)map;
15599 			} else {
15600 				u32 off = insn[1].imm;
15601 
15602 				if (off >= BPF_MAX_VAR_OFF) {
15603 					verbose(env, "direct value offset of %u is not allowed\n", off);
15604 					fdput(f);
15605 					return -EINVAL;
15606 				}
15607 
15608 				if (!map->ops->map_direct_value_addr) {
15609 					verbose(env, "no direct value access support for this map type\n");
15610 					fdput(f);
15611 					return -EINVAL;
15612 				}
15613 
15614 				err = map->ops->map_direct_value_addr(map, &addr, off);
15615 				if (err) {
15616 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
15617 						map->value_size, off);
15618 					fdput(f);
15619 					return err;
15620 				}
15621 
15622 				aux->map_off = off;
15623 				addr += off;
15624 			}
15625 
15626 			insn[0].imm = (u32)addr;
15627 			insn[1].imm = addr >> 32;
15628 
15629 			/* check whether we recorded this map already */
15630 			for (j = 0; j < env->used_map_cnt; j++) {
15631 				if (env->used_maps[j] == map) {
15632 					aux->map_index = j;
15633 					fdput(f);
15634 					goto next_insn;
15635 				}
15636 			}
15637 
15638 			if (env->used_map_cnt >= MAX_USED_MAPS) {
15639 				fdput(f);
15640 				return -E2BIG;
15641 			}
15642 
15643 			/* hold the map. If the program is rejected by verifier,
15644 			 * the map will be released by release_maps() or it
15645 			 * will be used by the valid program until it's unloaded
15646 			 * and all maps are released in free_used_maps()
15647 			 */
15648 			bpf_map_inc(map);
15649 
15650 			aux->map_index = env->used_map_cnt;
15651 			env->used_maps[env->used_map_cnt++] = map;
15652 
15653 			if (bpf_map_is_cgroup_storage(map) &&
15654 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
15655 				verbose(env, "only one cgroup storage of each type is allowed\n");
15656 				fdput(f);
15657 				return -EBUSY;
15658 			}
15659 
15660 			fdput(f);
15661 next_insn:
15662 			insn++;
15663 			i++;
15664 			continue;
15665 		}
15666 
15667 		/* Basic sanity check before we invest more work here. */
15668 		if (!bpf_opcode_in_insntable(insn->code)) {
15669 			verbose(env, "unknown opcode %02x\n", insn->code);
15670 			return -EINVAL;
15671 		}
15672 	}
15673 
15674 	/* now all pseudo BPF_LD_IMM64 instructions load valid
15675 	 * 'struct bpf_map *' into a register instead of user map_fd.
15676 	 * These pointers will be used later by verifier to validate map access.
15677 	 */
15678 	return 0;
15679 }
15680 
15681 /* drop refcnt of maps used by the rejected program */
15682 static void release_maps(struct bpf_verifier_env *env)
15683 {
15684 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
15685 			     env->used_map_cnt);
15686 }
15687 
15688 /* drop refcnt of maps used by the rejected program */
15689 static void release_btfs(struct bpf_verifier_env *env)
15690 {
15691 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
15692 			     env->used_btf_cnt);
15693 }
15694 
15695 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
15696 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
15697 {
15698 	struct bpf_insn *insn = env->prog->insnsi;
15699 	int insn_cnt = env->prog->len;
15700 	int i;
15701 
15702 	for (i = 0; i < insn_cnt; i++, insn++) {
15703 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
15704 			continue;
15705 		if (insn->src_reg == BPF_PSEUDO_FUNC)
15706 			continue;
15707 		insn->src_reg = 0;
15708 	}
15709 }
15710 
15711 /* single env->prog->insni[off] instruction was replaced with the range
15712  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
15713  * [0, off) and [off, end) to new locations, so the patched range stays zero
15714  */
15715 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
15716 				 struct bpf_insn_aux_data *new_data,
15717 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
15718 {
15719 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
15720 	struct bpf_insn *insn = new_prog->insnsi;
15721 	u32 old_seen = old_data[off].seen;
15722 	u32 prog_len;
15723 	int i;
15724 
15725 	/* aux info at OFF always needs adjustment, no matter fast path
15726 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
15727 	 * original insn at old prog.
15728 	 */
15729 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
15730 
15731 	if (cnt == 1)
15732 		return;
15733 	prog_len = new_prog->len;
15734 
15735 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
15736 	memcpy(new_data + off + cnt - 1, old_data + off,
15737 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
15738 	for (i = off; i < off + cnt - 1; i++) {
15739 		/* Expand insni[off]'s seen count to the patched range. */
15740 		new_data[i].seen = old_seen;
15741 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
15742 	}
15743 	env->insn_aux_data = new_data;
15744 	vfree(old_data);
15745 }
15746 
15747 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
15748 {
15749 	int i;
15750 
15751 	if (len == 1)
15752 		return;
15753 	/* NOTE: fake 'exit' subprog should be updated as well. */
15754 	for (i = 0; i <= env->subprog_cnt; i++) {
15755 		if (env->subprog_info[i].start <= off)
15756 			continue;
15757 		env->subprog_info[i].start += len - 1;
15758 	}
15759 }
15760 
15761 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
15762 {
15763 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
15764 	int i, sz = prog->aux->size_poke_tab;
15765 	struct bpf_jit_poke_descriptor *desc;
15766 
15767 	for (i = 0; i < sz; i++) {
15768 		desc = &tab[i];
15769 		if (desc->insn_idx <= off)
15770 			continue;
15771 		desc->insn_idx += len - 1;
15772 	}
15773 }
15774 
15775 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
15776 					    const struct bpf_insn *patch, u32 len)
15777 {
15778 	struct bpf_prog *new_prog;
15779 	struct bpf_insn_aux_data *new_data = NULL;
15780 
15781 	if (len > 1) {
15782 		new_data = vzalloc(array_size(env->prog->len + len - 1,
15783 					      sizeof(struct bpf_insn_aux_data)));
15784 		if (!new_data)
15785 			return NULL;
15786 	}
15787 
15788 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
15789 	if (IS_ERR(new_prog)) {
15790 		if (PTR_ERR(new_prog) == -ERANGE)
15791 			verbose(env,
15792 				"insn %d cannot be patched due to 16-bit range\n",
15793 				env->insn_aux_data[off].orig_idx);
15794 		vfree(new_data);
15795 		return NULL;
15796 	}
15797 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
15798 	adjust_subprog_starts(env, off, len);
15799 	adjust_poke_descs(new_prog, off, len);
15800 	return new_prog;
15801 }
15802 
15803 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15804 					      u32 off, u32 cnt)
15805 {
15806 	int i, j;
15807 
15808 	/* find first prog starting at or after off (first to remove) */
15809 	for (i = 0; i < env->subprog_cnt; i++)
15810 		if (env->subprog_info[i].start >= off)
15811 			break;
15812 	/* find first prog starting at or after off + cnt (first to stay) */
15813 	for (j = i; j < env->subprog_cnt; j++)
15814 		if (env->subprog_info[j].start >= off + cnt)
15815 			break;
15816 	/* if j doesn't start exactly at off + cnt, we are just removing
15817 	 * the front of previous prog
15818 	 */
15819 	if (env->subprog_info[j].start != off + cnt)
15820 		j--;
15821 
15822 	if (j > i) {
15823 		struct bpf_prog_aux *aux = env->prog->aux;
15824 		int move;
15825 
15826 		/* move fake 'exit' subprog as well */
15827 		move = env->subprog_cnt + 1 - j;
15828 
15829 		memmove(env->subprog_info + i,
15830 			env->subprog_info + j,
15831 			sizeof(*env->subprog_info) * move);
15832 		env->subprog_cnt -= j - i;
15833 
15834 		/* remove func_info */
15835 		if (aux->func_info) {
15836 			move = aux->func_info_cnt - j;
15837 
15838 			memmove(aux->func_info + i,
15839 				aux->func_info + j,
15840 				sizeof(*aux->func_info) * move);
15841 			aux->func_info_cnt -= j - i;
15842 			/* func_info->insn_off is set after all code rewrites,
15843 			 * in adjust_btf_func() - no need to adjust
15844 			 */
15845 		}
15846 	} else {
15847 		/* convert i from "first prog to remove" to "first to adjust" */
15848 		if (env->subprog_info[i].start == off)
15849 			i++;
15850 	}
15851 
15852 	/* update fake 'exit' subprog as well */
15853 	for (; i <= env->subprog_cnt; i++)
15854 		env->subprog_info[i].start -= cnt;
15855 
15856 	return 0;
15857 }
15858 
15859 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15860 				      u32 cnt)
15861 {
15862 	struct bpf_prog *prog = env->prog;
15863 	u32 i, l_off, l_cnt, nr_linfo;
15864 	struct bpf_line_info *linfo;
15865 
15866 	nr_linfo = prog->aux->nr_linfo;
15867 	if (!nr_linfo)
15868 		return 0;
15869 
15870 	linfo = prog->aux->linfo;
15871 
15872 	/* find first line info to remove, count lines to be removed */
15873 	for (i = 0; i < nr_linfo; i++)
15874 		if (linfo[i].insn_off >= off)
15875 			break;
15876 
15877 	l_off = i;
15878 	l_cnt = 0;
15879 	for (; i < nr_linfo; i++)
15880 		if (linfo[i].insn_off < off + cnt)
15881 			l_cnt++;
15882 		else
15883 			break;
15884 
15885 	/* First live insn doesn't match first live linfo, it needs to "inherit"
15886 	 * last removed linfo.  prog is already modified, so prog->len == off
15887 	 * means no live instructions after (tail of the program was removed).
15888 	 */
15889 	if (prog->len != off && l_cnt &&
15890 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15891 		l_cnt--;
15892 		linfo[--i].insn_off = off + cnt;
15893 	}
15894 
15895 	/* remove the line info which refer to the removed instructions */
15896 	if (l_cnt) {
15897 		memmove(linfo + l_off, linfo + i,
15898 			sizeof(*linfo) * (nr_linfo - i));
15899 
15900 		prog->aux->nr_linfo -= l_cnt;
15901 		nr_linfo = prog->aux->nr_linfo;
15902 	}
15903 
15904 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
15905 	for (i = l_off; i < nr_linfo; i++)
15906 		linfo[i].insn_off -= cnt;
15907 
15908 	/* fix up all subprogs (incl. 'exit') which start >= off */
15909 	for (i = 0; i <= env->subprog_cnt; i++)
15910 		if (env->subprog_info[i].linfo_idx > l_off) {
15911 			/* program may have started in the removed region but
15912 			 * may not be fully removed
15913 			 */
15914 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15915 				env->subprog_info[i].linfo_idx -= l_cnt;
15916 			else
15917 				env->subprog_info[i].linfo_idx = l_off;
15918 		}
15919 
15920 	return 0;
15921 }
15922 
15923 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15924 {
15925 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15926 	unsigned int orig_prog_len = env->prog->len;
15927 	int err;
15928 
15929 	if (bpf_prog_is_offloaded(env->prog->aux))
15930 		bpf_prog_offload_remove_insns(env, off, cnt);
15931 
15932 	err = bpf_remove_insns(env->prog, off, cnt);
15933 	if (err)
15934 		return err;
15935 
15936 	err = adjust_subprog_starts_after_remove(env, off, cnt);
15937 	if (err)
15938 		return err;
15939 
15940 	err = bpf_adj_linfo_after_remove(env, off, cnt);
15941 	if (err)
15942 		return err;
15943 
15944 	memmove(aux_data + off,	aux_data + off + cnt,
15945 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
15946 
15947 	return 0;
15948 }
15949 
15950 /* The verifier does more data flow analysis than llvm and will not
15951  * explore branches that are dead at run time. Malicious programs can
15952  * have dead code too. Therefore replace all dead at-run-time code
15953  * with 'ja -1'.
15954  *
15955  * Just nops are not optimal, e.g. if they would sit at the end of the
15956  * program and through another bug we would manage to jump there, then
15957  * we'd execute beyond program memory otherwise. Returning exception
15958  * code also wouldn't work since we can have subprogs where the dead
15959  * code could be located.
15960  */
15961 static void sanitize_dead_code(struct bpf_verifier_env *env)
15962 {
15963 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15964 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15965 	struct bpf_insn *insn = env->prog->insnsi;
15966 	const int insn_cnt = env->prog->len;
15967 	int i;
15968 
15969 	for (i = 0; i < insn_cnt; i++) {
15970 		if (aux_data[i].seen)
15971 			continue;
15972 		memcpy(insn + i, &trap, sizeof(trap));
15973 		aux_data[i].zext_dst = false;
15974 	}
15975 }
15976 
15977 static bool insn_is_cond_jump(u8 code)
15978 {
15979 	u8 op;
15980 
15981 	if (BPF_CLASS(code) == BPF_JMP32)
15982 		return true;
15983 
15984 	if (BPF_CLASS(code) != BPF_JMP)
15985 		return false;
15986 
15987 	op = BPF_OP(code);
15988 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15989 }
15990 
15991 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15992 {
15993 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15994 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15995 	struct bpf_insn *insn = env->prog->insnsi;
15996 	const int insn_cnt = env->prog->len;
15997 	int i;
15998 
15999 	for (i = 0; i < insn_cnt; i++, insn++) {
16000 		if (!insn_is_cond_jump(insn->code))
16001 			continue;
16002 
16003 		if (!aux_data[i + 1].seen)
16004 			ja.off = insn->off;
16005 		else if (!aux_data[i + 1 + insn->off].seen)
16006 			ja.off = 0;
16007 		else
16008 			continue;
16009 
16010 		if (bpf_prog_is_offloaded(env->prog->aux))
16011 			bpf_prog_offload_replace_insn(env, i, &ja);
16012 
16013 		memcpy(insn, &ja, sizeof(ja));
16014 	}
16015 }
16016 
16017 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16018 {
16019 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16020 	int insn_cnt = env->prog->len;
16021 	int i, err;
16022 
16023 	for (i = 0; i < insn_cnt; i++) {
16024 		int j;
16025 
16026 		j = 0;
16027 		while (i + j < insn_cnt && !aux_data[i + j].seen)
16028 			j++;
16029 		if (!j)
16030 			continue;
16031 
16032 		err = verifier_remove_insns(env, i, j);
16033 		if (err)
16034 			return err;
16035 		insn_cnt = env->prog->len;
16036 	}
16037 
16038 	return 0;
16039 }
16040 
16041 static int opt_remove_nops(struct bpf_verifier_env *env)
16042 {
16043 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16044 	struct bpf_insn *insn = env->prog->insnsi;
16045 	int insn_cnt = env->prog->len;
16046 	int i, err;
16047 
16048 	for (i = 0; i < insn_cnt; i++) {
16049 		if (memcmp(&insn[i], &ja, sizeof(ja)))
16050 			continue;
16051 
16052 		err = verifier_remove_insns(env, i, 1);
16053 		if (err)
16054 			return err;
16055 		insn_cnt--;
16056 		i--;
16057 	}
16058 
16059 	return 0;
16060 }
16061 
16062 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16063 					 const union bpf_attr *attr)
16064 {
16065 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
16066 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
16067 	int i, patch_len, delta = 0, len = env->prog->len;
16068 	struct bpf_insn *insns = env->prog->insnsi;
16069 	struct bpf_prog *new_prog;
16070 	bool rnd_hi32;
16071 
16072 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
16073 	zext_patch[1] = BPF_ZEXT_REG(0);
16074 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16075 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16076 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
16077 	for (i = 0; i < len; i++) {
16078 		int adj_idx = i + delta;
16079 		struct bpf_insn insn;
16080 		int load_reg;
16081 
16082 		insn = insns[adj_idx];
16083 		load_reg = insn_def_regno(&insn);
16084 		if (!aux[adj_idx].zext_dst) {
16085 			u8 code, class;
16086 			u32 imm_rnd;
16087 
16088 			if (!rnd_hi32)
16089 				continue;
16090 
16091 			code = insn.code;
16092 			class = BPF_CLASS(code);
16093 			if (load_reg == -1)
16094 				continue;
16095 
16096 			/* NOTE: arg "reg" (the fourth one) is only used for
16097 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
16098 			 *       here.
16099 			 */
16100 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
16101 				if (class == BPF_LD &&
16102 				    BPF_MODE(code) == BPF_IMM)
16103 					i++;
16104 				continue;
16105 			}
16106 
16107 			/* ctx load could be transformed into wider load. */
16108 			if (class == BPF_LDX &&
16109 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
16110 				continue;
16111 
16112 			imm_rnd = get_random_u32();
16113 			rnd_hi32_patch[0] = insn;
16114 			rnd_hi32_patch[1].imm = imm_rnd;
16115 			rnd_hi32_patch[3].dst_reg = load_reg;
16116 			patch = rnd_hi32_patch;
16117 			patch_len = 4;
16118 			goto apply_patch_buffer;
16119 		}
16120 
16121 		/* Add in an zero-extend instruction if a) the JIT has requested
16122 		 * it or b) it's a CMPXCHG.
16123 		 *
16124 		 * The latter is because: BPF_CMPXCHG always loads a value into
16125 		 * R0, therefore always zero-extends. However some archs'
16126 		 * equivalent instruction only does this load when the
16127 		 * comparison is successful. This detail of CMPXCHG is
16128 		 * orthogonal to the general zero-extension behaviour of the
16129 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
16130 		 */
16131 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
16132 			continue;
16133 
16134 		/* Zero-extension is done by the caller. */
16135 		if (bpf_pseudo_kfunc_call(&insn))
16136 			continue;
16137 
16138 		if (WARN_ON(load_reg == -1)) {
16139 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16140 			return -EFAULT;
16141 		}
16142 
16143 		zext_patch[0] = insn;
16144 		zext_patch[1].dst_reg = load_reg;
16145 		zext_patch[1].src_reg = load_reg;
16146 		patch = zext_patch;
16147 		patch_len = 2;
16148 apply_patch_buffer:
16149 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
16150 		if (!new_prog)
16151 			return -ENOMEM;
16152 		env->prog = new_prog;
16153 		insns = new_prog->insnsi;
16154 		aux = env->insn_aux_data;
16155 		delta += patch_len - 1;
16156 	}
16157 
16158 	return 0;
16159 }
16160 
16161 /* convert load instructions that access fields of a context type into a
16162  * sequence of instructions that access fields of the underlying structure:
16163  *     struct __sk_buff    -> struct sk_buff
16164  *     struct bpf_sock_ops -> struct sock
16165  */
16166 static int convert_ctx_accesses(struct bpf_verifier_env *env)
16167 {
16168 	const struct bpf_verifier_ops *ops = env->ops;
16169 	int i, cnt, size, ctx_field_size, delta = 0;
16170 	const int insn_cnt = env->prog->len;
16171 	struct bpf_insn insn_buf[16], *insn;
16172 	u32 target_size, size_default, off;
16173 	struct bpf_prog *new_prog;
16174 	enum bpf_access_type type;
16175 	bool is_narrower_load;
16176 
16177 	if (ops->gen_prologue || env->seen_direct_write) {
16178 		if (!ops->gen_prologue) {
16179 			verbose(env, "bpf verifier is misconfigured\n");
16180 			return -EINVAL;
16181 		}
16182 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16183 					env->prog);
16184 		if (cnt >= ARRAY_SIZE(insn_buf)) {
16185 			verbose(env, "bpf verifier is misconfigured\n");
16186 			return -EINVAL;
16187 		} else if (cnt) {
16188 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
16189 			if (!new_prog)
16190 				return -ENOMEM;
16191 
16192 			env->prog = new_prog;
16193 			delta += cnt - 1;
16194 		}
16195 	}
16196 
16197 	if (bpf_prog_is_offloaded(env->prog->aux))
16198 		return 0;
16199 
16200 	insn = env->prog->insnsi + delta;
16201 
16202 	for (i = 0; i < insn_cnt; i++, insn++) {
16203 		bpf_convert_ctx_access_t convert_ctx_access;
16204 
16205 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16206 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16207 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
16208 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
16209 			type = BPF_READ;
16210 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16211 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16212 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16213 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16214 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16215 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16216 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16217 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
16218 			type = BPF_WRITE;
16219 		} else {
16220 			continue;
16221 		}
16222 
16223 		if (type == BPF_WRITE &&
16224 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
16225 			struct bpf_insn patch[] = {
16226 				*insn,
16227 				BPF_ST_NOSPEC(),
16228 			};
16229 
16230 			cnt = ARRAY_SIZE(patch);
16231 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16232 			if (!new_prog)
16233 				return -ENOMEM;
16234 
16235 			delta    += cnt - 1;
16236 			env->prog = new_prog;
16237 			insn      = new_prog->insnsi + i + delta;
16238 			continue;
16239 		}
16240 
16241 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
16242 		case PTR_TO_CTX:
16243 			if (!ops->convert_ctx_access)
16244 				continue;
16245 			convert_ctx_access = ops->convert_ctx_access;
16246 			break;
16247 		case PTR_TO_SOCKET:
16248 		case PTR_TO_SOCK_COMMON:
16249 			convert_ctx_access = bpf_sock_convert_ctx_access;
16250 			break;
16251 		case PTR_TO_TCP_SOCK:
16252 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16253 			break;
16254 		case PTR_TO_XDP_SOCK:
16255 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16256 			break;
16257 		case PTR_TO_BTF_ID:
16258 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
16259 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16260 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16261 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
16262 		 * any faults for loads into such types. BPF_WRITE is disallowed
16263 		 * for this case.
16264 		 */
16265 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
16266 			if (type == BPF_READ) {
16267 				insn->code = BPF_LDX | BPF_PROBE_MEM |
16268 					BPF_SIZE((insn)->code);
16269 				env->prog->aux->num_exentries++;
16270 			}
16271 			continue;
16272 		default:
16273 			continue;
16274 		}
16275 
16276 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
16277 		size = BPF_LDST_BYTES(insn);
16278 
16279 		/* If the read access is a narrower load of the field,
16280 		 * convert to a 4/8-byte load, to minimum program type specific
16281 		 * convert_ctx_access changes. If conversion is successful,
16282 		 * we will apply proper mask to the result.
16283 		 */
16284 		is_narrower_load = size < ctx_field_size;
16285 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16286 		off = insn->off;
16287 		if (is_narrower_load) {
16288 			u8 size_code;
16289 
16290 			if (type == BPF_WRITE) {
16291 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
16292 				return -EINVAL;
16293 			}
16294 
16295 			size_code = BPF_H;
16296 			if (ctx_field_size == 4)
16297 				size_code = BPF_W;
16298 			else if (ctx_field_size == 8)
16299 				size_code = BPF_DW;
16300 
16301 			insn->off = off & ~(size_default - 1);
16302 			insn->code = BPF_LDX | BPF_MEM | size_code;
16303 		}
16304 
16305 		target_size = 0;
16306 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16307 					 &target_size);
16308 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16309 		    (ctx_field_size && !target_size)) {
16310 			verbose(env, "bpf verifier is misconfigured\n");
16311 			return -EINVAL;
16312 		}
16313 
16314 		if (is_narrower_load && size < target_size) {
16315 			u8 shift = bpf_ctx_narrow_access_offset(
16316 				off, size, size_default) * 8;
16317 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16318 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
16319 				return -EINVAL;
16320 			}
16321 			if (ctx_field_size <= 4) {
16322 				if (shift)
16323 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
16324 									insn->dst_reg,
16325 									shift);
16326 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
16327 								(1 << size * 8) - 1);
16328 			} else {
16329 				if (shift)
16330 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
16331 									insn->dst_reg,
16332 									shift);
16333 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
16334 								(1ULL << size * 8) - 1);
16335 			}
16336 		}
16337 
16338 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16339 		if (!new_prog)
16340 			return -ENOMEM;
16341 
16342 		delta += cnt - 1;
16343 
16344 		/* keep walking new program and skip insns we just inserted */
16345 		env->prog = new_prog;
16346 		insn      = new_prog->insnsi + i + delta;
16347 	}
16348 
16349 	return 0;
16350 }
16351 
16352 static int jit_subprogs(struct bpf_verifier_env *env)
16353 {
16354 	struct bpf_prog *prog = env->prog, **func, *tmp;
16355 	int i, j, subprog_start, subprog_end = 0, len, subprog;
16356 	struct bpf_map *map_ptr;
16357 	struct bpf_insn *insn;
16358 	void *old_bpf_func;
16359 	int err, num_exentries;
16360 
16361 	if (env->subprog_cnt <= 1)
16362 		return 0;
16363 
16364 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16365 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
16366 			continue;
16367 
16368 		/* Upon error here we cannot fall back to interpreter but
16369 		 * need a hard reject of the program. Thus -EFAULT is
16370 		 * propagated in any case.
16371 		 */
16372 		subprog = find_subprog(env, i + insn->imm + 1);
16373 		if (subprog < 0) {
16374 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
16375 				  i + insn->imm + 1);
16376 			return -EFAULT;
16377 		}
16378 		/* temporarily remember subprog id inside insn instead of
16379 		 * aux_data, since next loop will split up all insns into funcs
16380 		 */
16381 		insn->off = subprog;
16382 		/* remember original imm in case JIT fails and fallback
16383 		 * to interpreter will be needed
16384 		 */
16385 		env->insn_aux_data[i].call_imm = insn->imm;
16386 		/* point imm to __bpf_call_base+1 from JITs point of view */
16387 		insn->imm = 1;
16388 		if (bpf_pseudo_func(insn))
16389 			/* jit (e.g. x86_64) may emit fewer instructions
16390 			 * if it learns a u32 imm is the same as a u64 imm.
16391 			 * Force a non zero here.
16392 			 */
16393 			insn[1].imm = 1;
16394 	}
16395 
16396 	err = bpf_prog_alloc_jited_linfo(prog);
16397 	if (err)
16398 		goto out_undo_insn;
16399 
16400 	err = -ENOMEM;
16401 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
16402 	if (!func)
16403 		goto out_undo_insn;
16404 
16405 	for (i = 0; i < env->subprog_cnt; i++) {
16406 		subprog_start = subprog_end;
16407 		subprog_end = env->subprog_info[i + 1].start;
16408 
16409 		len = subprog_end - subprog_start;
16410 		/* bpf_prog_run() doesn't call subprogs directly,
16411 		 * hence main prog stats include the runtime of subprogs.
16412 		 * subprogs don't have IDs and not reachable via prog_get_next_id
16413 		 * func[i]->stats will never be accessed and stays NULL
16414 		 */
16415 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
16416 		if (!func[i])
16417 			goto out_free;
16418 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
16419 		       len * sizeof(struct bpf_insn));
16420 		func[i]->type = prog->type;
16421 		func[i]->len = len;
16422 		if (bpf_prog_calc_tag(func[i]))
16423 			goto out_free;
16424 		func[i]->is_func = 1;
16425 		func[i]->aux->func_idx = i;
16426 		/* Below members will be freed only at prog->aux */
16427 		func[i]->aux->btf = prog->aux->btf;
16428 		func[i]->aux->func_info = prog->aux->func_info;
16429 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
16430 		func[i]->aux->poke_tab = prog->aux->poke_tab;
16431 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
16432 
16433 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
16434 			struct bpf_jit_poke_descriptor *poke;
16435 
16436 			poke = &prog->aux->poke_tab[j];
16437 			if (poke->insn_idx < subprog_end &&
16438 			    poke->insn_idx >= subprog_start)
16439 				poke->aux = func[i]->aux;
16440 		}
16441 
16442 		func[i]->aux->name[0] = 'F';
16443 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
16444 		func[i]->jit_requested = 1;
16445 		func[i]->blinding_requested = prog->blinding_requested;
16446 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
16447 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
16448 		func[i]->aux->linfo = prog->aux->linfo;
16449 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
16450 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
16451 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
16452 		num_exentries = 0;
16453 		insn = func[i]->insnsi;
16454 		for (j = 0; j < func[i]->len; j++, insn++) {
16455 			if (BPF_CLASS(insn->code) == BPF_LDX &&
16456 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
16457 				num_exentries++;
16458 		}
16459 		func[i]->aux->num_exentries = num_exentries;
16460 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
16461 		func[i] = bpf_int_jit_compile(func[i]);
16462 		if (!func[i]->jited) {
16463 			err = -ENOTSUPP;
16464 			goto out_free;
16465 		}
16466 		cond_resched();
16467 	}
16468 
16469 	/* at this point all bpf functions were successfully JITed
16470 	 * now populate all bpf_calls with correct addresses and
16471 	 * run last pass of JIT
16472 	 */
16473 	for (i = 0; i < env->subprog_cnt; i++) {
16474 		insn = func[i]->insnsi;
16475 		for (j = 0; j < func[i]->len; j++, insn++) {
16476 			if (bpf_pseudo_func(insn)) {
16477 				subprog = insn->off;
16478 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
16479 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
16480 				continue;
16481 			}
16482 			if (!bpf_pseudo_call(insn))
16483 				continue;
16484 			subprog = insn->off;
16485 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
16486 		}
16487 
16488 		/* we use the aux data to keep a list of the start addresses
16489 		 * of the JITed images for each function in the program
16490 		 *
16491 		 * for some architectures, such as powerpc64, the imm field
16492 		 * might not be large enough to hold the offset of the start
16493 		 * address of the callee's JITed image from __bpf_call_base
16494 		 *
16495 		 * in such cases, we can lookup the start address of a callee
16496 		 * by using its subprog id, available from the off field of
16497 		 * the call instruction, as an index for this list
16498 		 */
16499 		func[i]->aux->func = func;
16500 		func[i]->aux->func_cnt = env->subprog_cnt;
16501 	}
16502 	for (i = 0; i < env->subprog_cnt; i++) {
16503 		old_bpf_func = func[i]->bpf_func;
16504 		tmp = bpf_int_jit_compile(func[i]);
16505 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
16506 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
16507 			err = -ENOTSUPP;
16508 			goto out_free;
16509 		}
16510 		cond_resched();
16511 	}
16512 
16513 	/* finally lock prog and jit images for all functions and
16514 	 * populate kallsysm
16515 	 */
16516 	for (i = 0; i < env->subprog_cnt; i++) {
16517 		bpf_prog_lock_ro(func[i]);
16518 		bpf_prog_kallsyms_add(func[i]);
16519 	}
16520 
16521 	/* Last step: make now unused interpreter insns from main
16522 	 * prog consistent for later dump requests, so they can
16523 	 * later look the same as if they were interpreted only.
16524 	 */
16525 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16526 		if (bpf_pseudo_func(insn)) {
16527 			insn[0].imm = env->insn_aux_data[i].call_imm;
16528 			insn[1].imm = insn->off;
16529 			insn->off = 0;
16530 			continue;
16531 		}
16532 		if (!bpf_pseudo_call(insn))
16533 			continue;
16534 		insn->off = env->insn_aux_data[i].call_imm;
16535 		subprog = find_subprog(env, i + insn->off + 1);
16536 		insn->imm = subprog;
16537 	}
16538 
16539 	prog->jited = 1;
16540 	prog->bpf_func = func[0]->bpf_func;
16541 	prog->jited_len = func[0]->jited_len;
16542 	prog->aux->func = func;
16543 	prog->aux->func_cnt = env->subprog_cnt;
16544 	bpf_prog_jit_attempt_done(prog);
16545 	return 0;
16546 out_free:
16547 	/* We failed JIT'ing, so at this point we need to unregister poke
16548 	 * descriptors from subprogs, so that kernel is not attempting to
16549 	 * patch it anymore as we're freeing the subprog JIT memory.
16550 	 */
16551 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16552 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16553 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
16554 	}
16555 	/* At this point we're guaranteed that poke descriptors are not
16556 	 * live anymore. We can just unlink its descriptor table as it's
16557 	 * released with the main prog.
16558 	 */
16559 	for (i = 0; i < env->subprog_cnt; i++) {
16560 		if (!func[i])
16561 			continue;
16562 		func[i]->aux->poke_tab = NULL;
16563 		bpf_jit_free(func[i]);
16564 	}
16565 	kfree(func);
16566 out_undo_insn:
16567 	/* cleanup main prog to be interpreted */
16568 	prog->jit_requested = 0;
16569 	prog->blinding_requested = 0;
16570 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16571 		if (!bpf_pseudo_call(insn))
16572 			continue;
16573 		insn->off = 0;
16574 		insn->imm = env->insn_aux_data[i].call_imm;
16575 	}
16576 	bpf_prog_jit_attempt_done(prog);
16577 	return err;
16578 }
16579 
16580 static int fixup_call_args(struct bpf_verifier_env *env)
16581 {
16582 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16583 	struct bpf_prog *prog = env->prog;
16584 	struct bpf_insn *insn = prog->insnsi;
16585 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
16586 	int i, depth;
16587 #endif
16588 	int err = 0;
16589 
16590 	if (env->prog->jit_requested &&
16591 	    !bpf_prog_is_offloaded(env->prog->aux)) {
16592 		err = jit_subprogs(env);
16593 		if (err == 0)
16594 			return 0;
16595 		if (err == -EFAULT)
16596 			return err;
16597 	}
16598 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16599 	if (has_kfunc_call) {
16600 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
16601 		return -EINVAL;
16602 	}
16603 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
16604 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
16605 		 * have to be rejected, since interpreter doesn't support them yet.
16606 		 */
16607 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
16608 		return -EINVAL;
16609 	}
16610 	for (i = 0; i < prog->len; i++, insn++) {
16611 		if (bpf_pseudo_func(insn)) {
16612 			/* When JIT fails the progs with callback calls
16613 			 * have to be rejected, since interpreter doesn't support them yet.
16614 			 */
16615 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
16616 			return -EINVAL;
16617 		}
16618 
16619 		if (!bpf_pseudo_call(insn))
16620 			continue;
16621 		depth = get_callee_stack_depth(env, insn, i);
16622 		if (depth < 0)
16623 			return depth;
16624 		bpf_patch_call_args(insn, depth);
16625 	}
16626 	err = 0;
16627 #endif
16628 	return err;
16629 }
16630 
16631 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
16632 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
16633 {
16634 	const struct bpf_kfunc_desc *desc;
16635 	void *xdp_kfunc;
16636 
16637 	if (!insn->imm) {
16638 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
16639 		return -EINVAL;
16640 	}
16641 
16642 	*cnt = 0;
16643 
16644 	if (bpf_dev_bound_kfunc_id(insn->imm)) {
16645 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
16646 		if (xdp_kfunc) {
16647 			insn->imm = BPF_CALL_IMM(xdp_kfunc);
16648 			return 0;
16649 		}
16650 
16651 		/* fallback to default kfunc when not supported by netdev */
16652 	}
16653 
16654 	/* insn->imm has the btf func_id. Replace it with
16655 	 * an address (relative to __bpf_call_base).
16656 	 */
16657 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
16658 	if (!desc) {
16659 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
16660 			insn->imm);
16661 		return -EFAULT;
16662 	}
16663 
16664 	insn->imm = desc->imm;
16665 	if (insn->off)
16666 		return 0;
16667 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
16668 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16669 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16670 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
16671 
16672 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
16673 		insn_buf[1] = addr[0];
16674 		insn_buf[2] = addr[1];
16675 		insn_buf[3] = *insn;
16676 		*cnt = 4;
16677 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
16678 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16679 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16680 
16681 		insn_buf[0] = addr[0];
16682 		insn_buf[1] = addr[1];
16683 		insn_buf[2] = *insn;
16684 		*cnt = 3;
16685 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16686 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
16687 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
16688 		*cnt = 1;
16689 	} else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
16690 		bool seen_direct_write = env->seen_direct_write;
16691 		bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
16692 
16693 		if (is_rdonly)
16694 			insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
16695 
16696 		/* restore env->seen_direct_write to its original value, since
16697 		 * may_access_direct_pkt_data mutates it
16698 		 */
16699 		env->seen_direct_write = seen_direct_write;
16700 	}
16701 	return 0;
16702 }
16703 
16704 /* Do various post-verification rewrites in a single program pass.
16705  * These rewrites simplify JIT and interpreter implementations.
16706  */
16707 static int do_misc_fixups(struct bpf_verifier_env *env)
16708 {
16709 	struct bpf_prog *prog = env->prog;
16710 	enum bpf_attach_type eatype = prog->expected_attach_type;
16711 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
16712 	struct bpf_insn *insn = prog->insnsi;
16713 	const struct bpf_func_proto *fn;
16714 	const int insn_cnt = prog->len;
16715 	const struct bpf_map_ops *ops;
16716 	struct bpf_insn_aux_data *aux;
16717 	struct bpf_insn insn_buf[16];
16718 	struct bpf_prog *new_prog;
16719 	struct bpf_map *map_ptr;
16720 	int i, ret, cnt, delta = 0;
16721 
16722 	for (i = 0; i < insn_cnt; i++, insn++) {
16723 		/* Make divide-by-zero exceptions impossible. */
16724 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
16725 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
16726 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
16727 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
16728 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
16729 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
16730 			struct bpf_insn *patchlet;
16731 			struct bpf_insn chk_and_div[] = {
16732 				/* [R,W]x div 0 -> 0 */
16733 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16734 					     BPF_JNE | BPF_K, insn->src_reg,
16735 					     0, 2, 0),
16736 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
16737 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16738 				*insn,
16739 			};
16740 			struct bpf_insn chk_and_mod[] = {
16741 				/* [R,W]x mod 0 -> [R,W]x */
16742 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16743 					     BPF_JEQ | BPF_K, insn->src_reg,
16744 					     0, 1 + (is64 ? 0 : 1), 0),
16745 				*insn,
16746 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16747 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
16748 			};
16749 
16750 			patchlet = isdiv ? chk_and_div : chk_and_mod;
16751 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
16752 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
16753 
16754 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
16755 			if (!new_prog)
16756 				return -ENOMEM;
16757 
16758 			delta    += cnt - 1;
16759 			env->prog = prog = new_prog;
16760 			insn      = new_prog->insnsi + i + delta;
16761 			continue;
16762 		}
16763 
16764 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
16765 		if (BPF_CLASS(insn->code) == BPF_LD &&
16766 		    (BPF_MODE(insn->code) == BPF_ABS ||
16767 		     BPF_MODE(insn->code) == BPF_IND)) {
16768 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
16769 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16770 				verbose(env, "bpf verifier is misconfigured\n");
16771 				return -EINVAL;
16772 			}
16773 
16774 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16775 			if (!new_prog)
16776 				return -ENOMEM;
16777 
16778 			delta    += cnt - 1;
16779 			env->prog = prog = new_prog;
16780 			insn      = new_prog->insnsi + i + delta;
16781 			continue;
16782 		}
16783 
16784 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
16785 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
16786 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
16787 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
16788 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
16789 			struct bpf_insn *patch = &insn_buf[0];
16790 			bool issrc, isneg, isimm;
16791 			u32 off_reg;
16792 
16793 			aux = &env->insn_aux_data[i + delta];
16794 			if (!aux->alu_state ||
16795 			    aux->alu_state == BPF_ALU_NON_POINTER)
16796 				continue;
16797 
16798 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16799 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16800 				BPF_ALU_SANITIZE_SRC;
16801 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16802 
16803 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
16804 			if (isimm) {
16805 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16806 			} else {
16807 				if (isneg)
16808 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16809 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16810 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16811 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16812 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16813 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16814 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16815 			}
16816 			if (!issrc)
16817 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16818 			insn->src_reg = BPF_REG_AX;
16819 			if (isneg)
16820 				insn->code = insn->code == code_add ?
16821 					     code_sub : code_add;
16822 			*patch++ = *insn;
16823 			if (issrc && isneg && !isimm)
16824 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16825 			cnt = patch - insn_buf;
16826 
16827 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16828 			if (!new_prog)
16829 				return -ENOMEM;
16830 
16831 			delta    += cnt - 1;
16832 			env->prog = prog = new_prog;
16833 			insn      = new_prog->insnsi + i + delta;
16834 			continue;
16835 		}
16836 
16837 		if (insn->code != (BPF_JMP | BPF_CALL))
16838 			continue;
16839 		if (insn->src_reg == BPF_PSEUDO_CALL)
16840 			continue;
16841 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16842 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16843 			if (ret)
16844 				return ret;
16845 			if (cnt == 0)
16846 				continue;
16847 
16848 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16849 			if (!new_prog)
16850 				return -ENOMEM;
16851 
16852 			delta	 += cnt - 1;
16853 			env->prog = prog = new_prog;
16854 			insn	  = new_prog->insnsi + i + delta;
16855 			continue;
16856 		}
16857 
16858 		if (insn->imm == BPF_FUNC_get_route_realm)
16859 			prog->dst_needed = 1;
16860 		if (insn->imm == BPF_FUNC_get_prandom_u32)
16861 			bpf_user_rnd_init_once();
16862 		if (insn->imm == BPF_FUNC_override_return)
16863 			prog->kprobe_override = 1;
16864 		if (insn->imm == BPF_FUNC_tail_call) {
16865 			/* If we tail call into other programs, we
16866 			 * cannot make any assumptions since they can
16867 			 * be replaced dynamically during runtime in
16868 			 * the program array.
16869 			 */
16870 			prog->cb_access = 1;
16871 			if (!allow_tail_call_in_subprogs(env))
16872 				prog->aux->stack_depth = MAX_BPF_STACK;
16873 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16874 
16875 			/* mark bpf_tail_call as different opcode to avoid
16876 			 * conditional branch in the interpreter for every normal
16877 			 * call and to prevent accidental JITing by JIT compiler
16878 			 * that doesn't support bpf_tail_call yet
16879 			 */
16880 			insn->imm = 0;
16881 			insn->code = BPF_JMP | BPF_TAIL_CALL;
16882 
16883 			aux = &env->insn_aux_data[i + delta];
16884 			if (env->bpf_capable && !prog->blinding_requested &&
16885 			    prog->jit_requested &&
16886 			    !bpf_map_key_poisoned(aux) &&
16887 			    !bpf_map_ptr_poisoned(aux) &&
16888 			    !bpf_map_ptr_unpriv(aux)) {
16889 				struct bpf_jit_poke_descriptor desc = {
16890 					.reason = BPF_POKE_REASON_TAIL_CALL,
16891 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16892 					.tail_call.key = bpf_map_key_immediate(aux),
16893 					.insn_idx = i + delta,
16894 				};
16895 
16896 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
16897 				if (ret < 0) {
16898 					verbose(env, "adding tail call poke descriptor failed\n");
16899 					return ret;
16900 				}
16901 
16902 				insn->imm = ret + 1;
16903 				continue;
16904 			}
16905 
16906 			if (!bpf_map_ptr_unpriv(aux))
16907 				continue;
16908 
16909 			/* instead of changing every JIT dealing with tail_call
16910 			 * emit two extra insns:
16911 			 * if (index >= max_entries) goto out;
16912 			 * index &= array->index_mask;
16913 			 * to avoid out-of-bounds cpu speculation
16914 			 */
16915 			if (bpf_map_ptr_poisoned(aux)) {
16916 				verbose(env, "tail_call abusing map_ptr\n");
16917 				return -EINVAL;
16918 			}
16919 
16920 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16921 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16922 						  map_ptr->max_entries, 2);
16923 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16924 						    container_of(map_ptr,
16925 								 struct bpf_array,
16926 								 map)->index_mask);
16927 			insn_buf[2] = *insn;
16928 			cnt = 3;
16929 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16930 			if (!new_prog)
16931 				return -ENOMEM;
16932 
16933 			delta    += cnt - 1;
16934 			env->prog = prog = new_prog;
16935 			insn      = new_prog->insnsi + i + delta;
16936 			continue;
16937 		}
16938 
16939 		if (insn->imm == BPF_FUNC_timer_set_callback) {
16940 			/* The verifier will process callback_fn as many times as necessary
16941 			 * with different maps and the register states prepared by
16942 			 * set_timer_callback_state will be accurate.
16943 			 *
16944 			 * The following use case is valid:
16945 			 *   map1 is shared by prog1, prog2, prog3.
16946 			 *   prog1 calls bpf_timer_init for some map1 elements
16947 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
16948 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
16949 			 *   prog3 calls bpf_timer_start for some map1 elements.
16950 			 *     Those that were not both bpf_timer_init-ed and
16951 			 *     bpf_timer_set_callback-ed will return -EINVAL.
16952 			 */
16953 			struct bpf_insn ld_addrs[2] = {
16954 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16955 			};
16956 
16957 			insn_buf[0] = ld_addrs[0];
16958 			insn_buf[1] = ld_addrs[1];
16959 			insn_buf[2] = *insn;
16960 			cnt = 3;
16961 
16962 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16963 			if (!new_prog)
16964 				return -ENOMEM;
16965 
16966 			delta    += cnt - 1;
16967 			env->prog = prog = new_prog;
16968 			insn      = new_prog->insnsi + i + delta;
16969 			goto patch_call_imm;
16970 		}
16971 
16972 		if (is_storage_get_function(insn->imm)) {
16973 			if (!env->prog->aux->sleepable ||
16974 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
16975 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16976 			else
16977 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16978 			insn_buf[1] = *insn;
16979 			cnt = 2;
16980 
16981 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16982 			if (!new_prog)
16983 				return -ENOMEM;
16984 
16985 			delta += cnt - 1;
16986 			env->prog = prog = new_prog;
16987 			insn = new_prog->insnsi + i + delta;
16988 			goto patch_call_imm;
16989 		}
16990 
16991 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16992 		 * and other inlining handlers are currently limited to 64 bit
16993 		 * only.
16994 		 */
16995 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
16996 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
16997 		     insn->imm == BPF_FUNC_map_update_elem ||
16998 		     insn->imm == BPF_FUNC_map_delete_elem ||
16999 		     insn->imm == BPF_FUNC_map_push_elem   ||
17000 		     insn->imm == BPF_FUNC_map_pop_elem    ||
17001 		     insn->imm == BPF_FUNC_map_peek_elem   ||
17002 		     insn->imm == BPF_FUNC_redirect_map    ||
17003 		     insn->imm == BPF_FUNC_for_each_map_elem ||
17004 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
17005 			aux = &env->insn_aux_data[i + delta];
17006 			if (bpf_map_ptr_poisoned(aux))
17007 				goto patch_call_imm;
17008 
17009 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17010 			ops = map_ptr->ops;
17011 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
17012 			    ops->map_gen_lookup) {
17013 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
17014 				if (cnt == -EOPNOTSUPP)
17015 					goto patch_map_ops_generic;
17016 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17017 					verbose(env, "bpf verifier is misconfigured\n");
17018 					return -EINVAL;
17019 				}
17020 
17021 				new_prog = bpf_patch_insn_data(env, i + delta,
17022 							       insn_buf, cnt);
17023 				if (!new_prog)
17024 					return -ENOMEM;
17025 
17026 				delta    += cnt - 1;
17027 				env->prog = prog = new_prog;
17028 				insn      = new_prog->insnsi + i + delta;
17029 				continue;
17030 			}
17031 
17032 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17033 				     (void *(*)(struct bpf_map *map, void *key))NULL));
17034 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
17035 				     (int (*)(struct bpf_map *map, void *key))NULL));
17036 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
17037 				     (int (*)(struct bpf_map *map, void *key, void *value,
17038 					      u64 flags))NULL));
17039 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
17040 				     (int (*)(struct bpf_map *map, void *value,
17041 					      u64 flags))NULL));
17042 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
17043 				     (int (*)(struct bpf_map *map, void *value))NULL));
17044 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
17045 				     (int (*)(struct bpf_map *map, void *value))NULL));
17046 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
17047 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
17048 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
17049 				     (int (*)(struct bpf_map *map,
17050 					      bpf_callback_t callback_fn,
17051 					      void *callback_ctx,
17052 					      u64 flags))NULL));
17053 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17054 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
17055 
17056 patch_map_ops_generic:
17057 			switch (insn->imm) {
17058 			case BPF_FUNC_map_lookup_elem:
17059 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
17060 				continue;
17061 			case BPF_FUNC_map_update_elem:
17062 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
17063 				continue;
17064 			case BPF_FUNC_map_delete_elem:
17065 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
17066 				continue;
17067 			case BPF_FUNC_map_push_elem:
17068 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
17069 				continue;
17070 			case BPF_FUNC_map_pop_elem:
17071 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
17072 				continue;
17073 			case BPF_FUNC_map_peek_elem:
17074 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
17075 				continue;
17076 			case BPF_FUNC_redirect_map:
17077 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
17078 				continue;
17079 			case BPF_FUNC_for_each_map_elem:
17080 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
17081 				continue;
17082 			case BPF_FUNC_map_lookup_percpu_elem:
17083 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17084 				continue;
17085 			}
17086 
17087 			goto patch_call_imm;
17088 		}
17089 
17090 		/* Implement bpf_jiffies64 inline. */
17091 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
17092 		    insn->imm == BPF_FUNC_jiffies64) {
17093 			struct bpf_insn ld_jiffies_addr[2] = {
17094 				BPF_LD_IMM64(BPF_REG_0,
17095 					     (unsigned long)&jiffies),
17096 			};
17097 
17098 			insn_buf[0] = ld_jiffies_addr[0];
17099 			insn_buf[1] = ld_jiffies_addr[1];
17100 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17101 						  BPF_REG_0, 0);
17102 			cnt = 3;
17103 
17104 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17105 						       cnt);
17106 			if (!new_prog)
17107 				return -ENOMEM;
17108 
17109 			delta    += cnt - 1;
17110 			env->prog = prog = new_prog;
17111 			insn      = new_prog->insnsi + i + delta;
17112 			continue;
17113 		}
17114 
17115 		/* Implement bpf_get_func_arg inline. */
17116 		if (prog_type == BPF_PROG_TYPE_TRACING &&
17117 		    insn->imm == BPF_FUNC_get_func_arg) {
17118 			/* Load nr_args from ctx - 8 */
17119 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17120 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17121 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17122 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17123 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17124 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17125 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17126 			insn_buf[7] = BPF_JMP_A(1);
17127 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17128 			cnt = 9;
17129 
17130 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17131 			if (!new_prog)
17132 				return -ENOMEM;
17133 
17134 			delta    += cnt - 1;
17135 			env->prog = prog = new_prog;
17136 			insn      = new_prog->insnsi + i + delta;
17137 			continue;
17138 		}
17139 
17140 		/* Implement bpf_get_func_ret inline. */
17141 		if (prog_type == BPF_PROG_TYPE_TRACING &&
17142 		    insn->imm == BPF_FUNC_get_func_ret) {
17143 			if (eatype == BPF_TRACE_FEXIT ||
17144 			    eatype == BPF_MODIFY_RETURN) {
17145 				/* Load nr_args from ctx - 8 */
17146 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17147 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17148 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17149 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17150 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17151 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17152 				cnt = 6;
17153 			} else {
17154 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17155 				cnt = 1;
17156 			}
17157 
17158 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17159 			if (!new_prog)
17160 				return -ENOMEM;
17161 
17162 			delta    += cnt - 1;
17163 			env->prog = prog = new_prog;
17164 			insn      = new_prog->insnsi + i + delta;
17165 			continue;
17166 		}
17167 
17168 		/* Implement get_func_arg_cnt inline. */
17169 		if (prog_type == BPF_PROG_TYPE_TRACING &&
17170 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
17171 			/* Load nr_args from ctx - 8 */
17172 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17173 
17174 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17175 			if (!new_prog)
17176 				return -ENOMEM;
17177 
17178 			env->prog = prog = new_prog;
17179 			insn      = new_prog->insnsi + i + delta;
17180 			continue;
17181 		}
17182 
17183 		/* Implement bpf_get_func_ip inline. */
17184 		if (prog_type == BPF_PROG_TYPE_TRACING &&
17185 		    insn->imm == BPF_FUNC_get_func_ip) {
17186 			/* Load IP address from ctx - 16 */
17187 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
17188 
17189 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17190 			if (!new_prog)
17191 				return -ENOMEM;
17192 
17193 			env->prog = prog = new_prog;
17194 			insn      = new_prog->insnsi + i + delta;
17195 			continue;
17196 		}
17197 
17198 patch_call_imm:
17199 		fn = env->ops->get_func_proto(insn->imm, env->prog);
17200 		/* all functions that have prototype and verifier allowed
17201 		 * programs to call them, must be real in-kernel functions
17202 		 */
17203 		if (!fn->func) {
17204 			verbose(env,
17205 				"kernel subsystem misconfigured func %s#%d\n",
17206 				func_id_name(insn->imm), insn->imm);
17207 			return -EFAULT;
17208 		}
17209 		insn->imm = fn->func - __bpf_call_base;
17210 	}
17211 
17212 	/* Since poke tab is now finalized, publish aux to tracker. */
17213 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
17214 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
17215 		if (!map_ptr->ops->map_poke_track ||
17216 		    !map_ptr->ops->map_poke_untrack ||
17217 		    !map_ptr->ops->map_poke_run) {
17218 			verbose(env, "bpf verifier is misconfigured\n");
17219 			return -EINVAL;
17220 		}
17221 
17222 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17223 		if (ret < 0) {
17224 			verbose(env, "tracking tail call prog failed\n");
17225 			return ret;
17226 		}
17227 	}
17228 
17229 	sort_kfunc_descs_by_imm(env->prog);
17230 
17231 	return 0;
17232 }
17233 
17234 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17235 					int position,
17236 					s32 stack_base,
17237 					u32 callback_subprogno,
17238 					u32 *cnt)
17239 {
17240 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17241 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17242 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17243 	int reg_loop_max = BPF_REG_6;
17244 	int reg_loop_cnt = BPF_REG_7;
17245 	int reg_loop_ctx = BPF_REG_8;
17246 
17247 	struct bpf_prog *new_prog;
17248 	u32 callback_start;
17249 	u32 call_insn_offset;
17250 	s32 callback_offset;
17251 
17252 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
17253 	 * be careful to modify this code in sync.
17254 	 */
17255 	struct bpf_insn insn_buf[] = {
17256 		/* Return error and jump to the end of the patch if
17257 		 * expected number of iterations is too big.
17258 		 */
17259 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17260 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17261 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17262 		/* spill R6, R7, R8 to use these as loop vars */
17263 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17264 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17265 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17266 		/* initialize loop vars */
17267 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17268 		BPF_MOV32_IMM(reg_loop_cnt, 0),
17269 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17270 		/* loop header,
17271 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
17272 		 */
17273 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17274 		/* callback call,
17275 		 * correct callback offset would be set after patching
17276 		 */
17277 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17278 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17279 		BPF_CALL_REL(0),
17280 		/* increment loop counter */
17281 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17282 		/* jump to loop header if callback returned 0 */
17283 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17284 		/* return value of bpf_loop,
17285 		 * set R0 to the number of iterations
17286 		 */
17287 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17288 		/* restore original values of R6, R7, R8 */
17289 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17290 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17291 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17292 	};
17293 
17294 	*cnt = ARRAY_SIZE(insn_buf);
17295 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17296 	if (!new_prog)
17297 		return new_prog;
17298 
17299 	/* callback start is known only after patching */
17300 	callback_start = env->subprog_info[callback_subprogno].start;
17301 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17302 	call_insn_offset = position + 12;
17303 	callback_offset = callback_start - call_insn_offset - 1;
17304 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
17305 
17306 	return new_prog;
17307 }
17308 
17309 static bool is_bpf_loop_call(struct bpf_insn *insn)
17310 {
17311 	return insn->code == (BPF_JMP | BPF_CALL) &&
17312 		insn->src_reg == 0 &&
17313 		insn->imm == BPF_FUNC_loop;
17314 }
17315 
17316 /* For all sub-programs in the program (including main) check
17317  * insn_aux_data to see if there are bpf_loop calls that require
17318  * inlining. If such calls are found the calls are replaced with a
17319  * sequence of instructions produced by `inline_bpf_loop` function and
17320  * subprog stack_depth is increased by the size of 3 registers.
17321  * This stack space is used to spill values of the R6, R7, R8.  These
17322  * registers are used to store the loop bound, counter and context
17323  * variables.
17324  */
17325 static int optimize_bpf_loop(struct bpf_verifier_env *env)
17326 {
17327 	struct bpf_subprog_info *subprogs = env->subprog_info;
17328 	int i, cur_subprog = 0, cnt, delta = 0;
17329 	struct bpf_insn *insn = env->prog->insnsi;
17330 	int insn_cnt = env->prog->len;
17331 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
17332 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
17333 	u16 stack_depth_extra = 0;
17334 
17335 	for (i = 0; i < insn_cnt; i++, insn++) {
17336 		struct bpf_loop_inline_state *inline_state =
17337 			&env->insn_aux_data[i + delta].loop_inline_state;
17338 
17339 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
17340 			struct bpf_prog *new_prog;
17341 
17342 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
17343 			new_prog = inline_bpf_loop(env,
17344 						   i + delta,
17345 						   -(stack_depth + stack_depth_extra),
17346 						   inline_state->callback_subprogno,
17347 						   &cnt);
17348 			if (!new_prog)
17349 				return -ENOMEM;
17350 
17351 			delta     += cnt - 1;
17352 			env->prog  = new_prog;
17353 			insn       = new_prog->insnsi + i + delta;
17354 		}
17355 
17356 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
17357 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
17358 			cur_subprog++;
17359 			stack_depth = subprogs[cur_subprog].stack_depth;
17360 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
17361 			stack_depth_extra = 0;
17362 		}
17363 	}
17364 
17365 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17366 
17367 	return 0;
17368 }
17369 
17370 static void free_states(struct bpf_verifier_env *env)
17371 {
17372 	struct bpf_verifier_state_list *sl, *sln;
17373 	int i;
17374 
17375 	sl = env->free_list;
17376 	while (sl) {
17377 		sln = sl->next;
17378 		free_verifier_state(&sl->state, false);
17379 		kfree(sl);
17380 		sl = sln;
17381 	}
17382 	env->free_list = NULL;
17383 
17384 	if (!env->explored_states)
17385 		return;
17386 
17387 	for (i = 0; i < state_htab_size(env); i++) {
17388 		sl = env->explored_states[i];
17389 
17390 		while (sl) {
17391 			sln = sl->next;
17392 			free_verifier_state(&sl->state, false);
17393 			kfree(sl);
17394 			sl = sln;
17395 		}
17396 		env->explored_states[i] = NULL;
17397 	}
17398 }
17399 
17400 static int do_check_common(struct bpf_verifier_env *env, int subprog)
17401 {
17402 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17403 	struct bpf_verifier_state *state;
17404 	struct bpf_reg_state *regs;
17405 	int ret, i;
17406 
17407 	env->prev_linfo = NULL;
17408 	env->pass_cnt++;
17409 
17410 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
17411 	if (!state)
17412 		return -ENOMEM;
17413 	state->curframe = 0;
17414 	state->speculative = false;
17415 	state->branches = 1;
17416 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
17417 	if (!state->frame[0]) {
17418 		kfree(state);
17419 		return -ENOMEM;
17420 	}
17421 	env->cur_state = state;
17422 	init_func_state(env, state->frame[0],
17423 			BPF_MAIN_FUNC /* callsite */,
17424 			0 /* frameno */,
17425 			subprog);
17426 	state->first_insn_idx = env->subprog_info[subprog].start;
17427 	state->last_insn_idx = -1;
17428 
17429 	regs = state->frame[state->curframe]->regs;
17430 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
17431 		ret = btf_prepare_func_args(env, subprog, regs);
17432 		if (ret)
17433 			goto out;
17434 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
17435 			if (regs[i].type == PTR_TO_CTX)
17436 				mark_reg_known_zero(env, regs, i);
17437 			else if (regs[i].type == SCALAR_VALUE)
17438 				mark_reg_unknown(env, regs, i);
17439 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
17440 				const u32 mem_size = regs[i].mem_size;
17441 
17442 				mark_reg_known_zero(env, regs, i);
17443 				regs[i].mem_size = mem_size;
17444 				regs[i].id = ++env->id_gen;
17445 			}
17446 		}
17447 	} else {
17448 		/* 1st arg to a function */
17449 		regs[BPF_REG_1].type = PTR_TO_CTX;
17450 		mark_reg_known_zero(env, regs, BPF_REG_1);
17451 		ret = btf_check_subprog_arg_match(env, subprog, regs);
17452 		if (ret == -EFAULT)
17453 			/* unlikely verifier bug. abort.
17454 			 * ret == 0 and ret < 0 are sadly acceptable for
17455 			 * main() function due to backward compatibility.
17456 			 * Like socket filter program may be written as:
17457 			 * int bpf_prog(struct pt_regs *ctx)
17458 			 * and never dereference that ctx in the program.
17459 			 * 'struct pt_regs' is a type mismatch for socket
17460 			 * filter that should be using 'struct __sk_buff'.
17461 			 */
17462 			goto out;
17463 	}
17464 
17465 	ret = do_check(env);
17466 out:
17467 	/* check for NULL is necessary, since cur_state can be freed inside
17468 	 * do_check() under memory pressure.
17469 	 */
17470 	if (env->cur_state) {
17471 		free_verifier_state(env->cur_state, true);
17472 		env->cur_state = NULL;
17473 	}
17474 	while (!pop_stack(env, NULL, NULL, false));
17475 	if (!ret && pop_log)
17476 		bpf_vlog_reset(&env->log, 0);
17477 	free_states(env);
17478 	return ret;
17479 }
17480 
17481 /* Verify all global functions in a BPF program one by one based on their BTF.
17482  * All global functions must pass verification. Otherwise the whole program is rejected.
17483  * Consider:
17484  * int bar(int);
17485  * int foo(int f)
17486  * {
17487  *    return bar(f);
17488  * }
17489  * int bar(int b)
17490  * {
17491  *    ...
17492  * }
17493  * foo() will be verified first for R1=any_scalar_value. During verification it
17494  * will be assumed that bar() already verified successfully and call to bar()
17495  * from foo() will be checked for type match only. Later bar() will be verified
17496  * independently to check that it's safe for R1=any_scalar_value.
17497  */
17498 static int do_check_subprogs(struct bpf_verifier_env *env)
17499 {
17500 	struct bpf_prog_aux *aux = env->prog->aux;
17501 	int i, ret;
17502 
17503 	if (!aux->func_info)
17504 		return 0;
17505 
17506 	for (i = 1; i < env->subprog_cnt; i++) {
17507 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
17508 			continue;
17509 		env->insn_idx = env->subprog_info[i].start;
17510 		WARN_ON_ONCE(env->insn_idx == 0);
17511 		ret = do_check_common(env, i);
17512 		if (ret) {
17513 			return ret;
17514 		} else if (env->log.level & BPF_LOG_LEVEL) {
17515 			verbose(env,
17516 				"Func#%d is safe for any args that match its prototype\n",
17517 				i);
17518 		}
17519 	}
17520 	return 0;
17521 }
17522 
17523 static int do_check_main(struct bpf_verifier_env *env)
17524 {
17525 	int ret;
17526 
17527 	env->insn_idx = 0;
17528 	ret = do_check_common(env, 0);
17529 	if (!ret)
17530 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17531 	return ret;
17532 }
17533 
17534 
17535 static void print_verification_stats(struct bpf_verifier_env *env)
17536 {
17537 	int i;
17538 
17539 	if (env->log.level & BPF_LOG_STATS) {
17540 		verbose(env, "verification time %lld usec\n",
17541 			div_u64(env->verification_time, 1000));
17542 		verbose(env, "stack depth ");
17543 		for (i = 0; i < env->subprog_cnt; i++) {
17544 			u32 depth = env->subprog_info[i].stack_depth;
17545 
17546 			verbose(env, "%d", depth);
17547 			if (i + 1 < env->subprog_cnt)
17548 				verbose(env, "+");
17549 		}
17550 		verbose(env, "\n");
17551 	}
17552 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
17553 		"total_states %d peak_states %d mark_read %d\n",
17554 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
17555 		env->max_states_per_insn, env->total_states,
17556 		env->peak_states, env->longest_mark_read_walk);
17557 }
17558 
17559 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
17560 {
17561 	const struct btf_type *t, *func_proto;
17562 	const struct bpf_struct_ops *st_ops;
17563 	const struct btf_member *member;
17564 	struct bpf_prog *prog = env->prog;
17565 	u32 btf_id, member_idx;
17566 	const char *mname;
17567 
17568 	if (!prog->gpl_compatible) {
17569 		verbose(env, "struct ops programs must have a GPL compatible license\n");
17570 		return -EINVAL;
17571 	}
17572 
17573 	btf_id = prog->aux->attach_btf_id;
17574 	st_ops = bpf_struct_ops_find(btf_id);
17575 	if (!st_ops) {
17576 		verbose(env, "attach_btf_id %u is not a supported struct\n",
17577 			btf_id);
17578 		return -ENOTSUPP;
17579 	}
17580 
17581 	t = st_ops->type;
17582 	member_idx = prog->expected_attach_type;
17583 	if (member_idx >= btf_type_vlen(t)) {
17584 		verbose(env, "attach to invalid member idx %u of struct %s\n",
17585 			member_idx, st_ops->name);
17586 		return -EINVAL;
17587 	}
17588 
17589 	member = &btf_type_member(t)[member_idx];
17590 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
17591 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
17592 					       NULL);
17593 	if (!func_proto) {
17594 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
17595 			mname, member_idx, st_ops->name);
17596 		return -EINVAL;
17597 	}
17598 
17599 	if (st_ops->check_member) {
17600 		int err = st_ops->check_member(t, member, prog);
17601 
17602 		if (err) {
17603 			verbose(env, "attach to unsupported member %s of struct %s\n",
17604 				mname, st_ops->name);
17605 			return err;
17606 		}
17607 	}
17608 
17609 	prog->aux->attach_func_proto = func_proto;
17610 	prog->aux->attach_func_name = mname;
17611 	env->ops = st_ops->verifier_ops;
17612 
17613 	return 0;
17614 }
17615 #define SECURITY_PREFIX "security_"
17616 
17617 static int check_attach_modify_return(unsigned long addr, const char *func_name)
17618 {
17619 	if (within_error_injection_list(addr) ||
17620 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
17621 		return 0;
17622 
17623 	return -EINVAL;
17624 }
17625 
17626 /* list of non-sleepable functions that are otherwise on
17627  * ALLOW_ERROR_INJECTION list
17628  */
17629 BTF_SET_START(btf_non_sleepable_error_inject)
17630 /* Three functions below can be called from sleepable and non-sleepable context.
17631  * Assume non-sleepable from bpf safety point of view.
17632  */
17633 BTF_ID(func, __filemap_add_folio)
17634 BTF_ID(func, should_fail_alloc_page)
17635 BTF_ID(func, should_failslab)
17636 BTF_SET_END(btf_non_sleepable_error_inject)
17637 
17638 static int check_non_sleepable_error_inject(u32 btf_id)
17639 {
17640 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
17641 }
17642 
17643 int bpf_check_attach_target(struct bpf_verifier_log *log,
17644 			    const struct bpf_prog *prog,
17645 			    const struct bpf_prog *tgt_prog,
17646 			    u32 btf_id,
17647 			    struct bpf_attach_target_info *tgt_info)
17648 {
17649 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
17650 	const char prefix[] = "btf_trace_";
17651 	int ret = 0, subprog = -1, i;
17652 	const struct btf_type *t;
17653 	bool conservative = true;
17654 	const char *tname;
17655 	struct btf *btf;
17656 	long addr = 0;
17657 
17658 	if (!btf_id) {
17659 		bpf_log(log, "Tracing programs must provide btf_id\n");
17660 		return -EINVAL;
17661 	}
17662 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
17663 	if (!btf) {
17664 		bpf_log(log,
17665 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
17666 		return -EINVAL;
17667 	}
17668 	t = btf_type_by_id(btf, btf_id);
17669 	if (!t) {
17670 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
17671 		return -EINVAL;
17672 	}
17673 	tname = btf_name_by_offset(btf, t->name_off);
17674 	if (!tname) {
17675 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
17676 		return -EINVAL;
17677 	}
17678 	if (tgt_prog) {
17679 		struct bpf_prog_aux *aux = tgt_prog->aux;
17680 
17681 		if (bpf_prog_is_dev_bound(prog->aux) &&
17682 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
17683 			bpf_log(log, "Target program bound device mismatch");
17684 			return -EINVAL;
17685 		}
17686 
17687 		for (i = 0; i < aux->func_info_cnt; i++)
17688 			if (aux->func_info[i].type_id == btf_id) {
17689 				subprog = i;
17690 				break;
17691 			}
17692 		if (subprog == -1) {
17693 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
17694 			return -EINVAL;
17695 		}
17696 		conservative = aux->func_info_aux[subprog].unreliable;
17697 		if (prog_extension) {
17698 			if (conservative) {
17699 				bpf_log(log,
17700 					"Cannot replace static functions\n");
17701 				return -EINVAL;
17702 			}
17703 			if (!prog->jit_requested) {
17704 				bpf_log(log,
17705 					"Extension programs should be JITed\n");
17706 				return -EINVAL;
17707 			}
17708 		}
17709 		if (!tgt_prog->jited) {
17710 			bpf_log(log, "Can attach to only JITed progs\n");
17711 			return -EINVAL;
17712 		}
17713 		if (tgt_prog->type == prog->type) {
17714 			/* Cannot fentry/fexit another fentry/fexit program.
17715 			 * Cannot attach program extension to another extension.
17716 			 * It's ok to attach fentry/fexit to extension program.
17717 			 */
17718 			bpf_log(log, "Cannot recursively attach\n");
17719 			return -EINVAL;
17720 		}
17721 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
17722 		    prog_extension &&
17723 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
17724 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
17725 			/* Program extensions can extend all program types
17726 			 * except fentry/fexit. The reason is the following.
17727 			 * The fentry/fexit programs are used for performance
17728 			 * analysis, stats and can be attached to any program
17729 			 * type except themselves. When extension program is
17730 			 * replacing XDP function it is necessary to allow
17731 			 * performance analysis of all functions. Both original
17732 			 * XDP program and its program extension. Hence
17733 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
17734 			 * allowed. If extending of fentry/fexit was allowed it
17735 			 * would be possible to create long call chain
17736 			 * fentry->extension->fentry->extension beyond
17737 			 * reasonable stack size. Hence extending fentry is not
17738 			 * allowed.
17739 			 */
17740 			bpf_log(log, "Cannot extend fentry/fexit\n");
17741 			return -EINVAL;
17742 		}
17743 	} else {
17744 		if (prog_extension) {
17745 			bpf_log(log, "Cannot replace kernel functions\n");
17746 			return -EINVAL;
17747 		}
17748 	}
17749 
17750 	switch (prog->expected_attach_type) {
17751 	case BPF_TRACE_RAW_TP:
17752 		if (tgt_prog) {
17753 			bpf_log(log,
17754 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
17755 			return -EINVAL;
17756 		}
17757 		if (!btf_type_is_typedef(t)) {
17758 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
17759 				btf_id);
17760 			return -EINVAL;
17761 		}
17762 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
17763 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
17764 				btf_id, tname);
17765 			return -EINVAL;
17766 		}
17767 		tname += sizeof(prefix) - 1;
17768 		t = btf_type_by_id(btf, t->type);
17769 		if (!btf_type_is_ptr(t))
17770 			/* should never happen in valid vmlinux build */
17771 			return -EINVAL;
17772 		t = btf_type_by_id(btf, t->type);
17773 		if (!btf_type_is_func_proto(t))
17774 			/* should never happen in valid vmlinux build */
17775 			return -EINVAL;
17776 
17777 		break;
17778 	case BPF_TRACE_ITER:
17779 		if (!btf_type_is_func(t)) {
17780 			bpf_log(log, "attach_btf_id %u is not a function\n",
17781 				btf_id);
17782 			return -EINVAL;
17783 		}
17784 		t = btf_type_by_id(btf, t->type);
17785 		if (!btf_type_is_func_proto(t))
17786 			return -EINVAL;
17787 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17788 		if (ret)
17789 			return ret;
17790 		break;
17791 	default:
17792 		if (!prog_extension)
17793 			return -EINVAL;
17794 		fallthrough;
17795 	case BPF_MODIFY_RETURN:
17796 	case BPF_LSM_MAC:
17797 	case BPF_LSM_CGROUP:
17798 	case BPF_TRACE_FENTRY:
17799 	case BPF_TRACE_FEXIT:
17800 		if (!btf_type_is_func(t)) {
17801 			bpf_log(log, "attach_btf_id %u is not a function\n",
17802 				btf_id);
17803 			return -EINVAL;
17804 		}
17805 		if (prog_extension &&
17806 		    btf_check_type_match(log, prog, btf, t))
17807 			return -EINVAL;
17808 		t = btf_type_by_id(btf, t->type);
17809 		if (!btf_type_is_func_proto(t))
17810 			return -EINVAL;
17811 
17812 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17813 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17814 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17815 			return -EINVAL;
17816 
17817 		if (tgt_prog && conservative)
17818 			t = NULL;
17819 
17820 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17821 		if (ret < 0)
17822 			return ret;
17823 
17824 		if (tgt_prog) {
17825 			if (subprog == 0)
17826 				addr = (long) tgt_prog->bpf_func;
17827 			else
17828 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17829 		} else {
17830 			addr = kallsyms_lookup_name(tname);
17831 			if (!addr) {
17832 				bpf_log(log,
17833 					"The address of function %s cannot be found\n",
17834 					tname);
17835 				return -ENOENT;
17836 			}
17837 		}
17838 
17839 		if (prog->aux->sleepable) {
17840 			ret = -EINVAL;
17841 			switch (prog->type) {
17842 			case BPF_PROG_TYPE_TRACING:
17843 
17844 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
17845 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17846 				 */
17847 				if (!check_non_sleepable_error_inject(btf_id) &&
17848 				    within_error_injection_list(addr))
17849 					ret = 0;
17850 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
17851 				 * in the fmodret id set with the KF_SLEEPABLE flag.
17852 				 */
17853 				else {
17854 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17855 
17856 					if (flags && (*flags & KF_SLEEPABLE))
17857 						ret = 0;
17858 				}
17859 				break;
17860 			case BPF_PROG_TYPE_LSM:
17861 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
17862 				 * Only some of them are sleepable.
17863 				 */
17864 				if (bpf_lsm_is_sleepable_hook(btf_id))
17865 					ret = 0;
17866 				break;
17867 			default:
17868 				break;
17869 			}
17870 			if (ret) {
17871 				bpf_log(log, "%s is not sleepable\n", tname);
17872 				return ret;
17873 			}
17874 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17875 			if (tgt_prog) {
17876 				bpf_log(log, "can't modify return codes of BPF programs\n");
17877 				return -EINVAL;
17878 			}
17879 			ret = -EINVAL;
17880 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
17881 			    !check_attach_modify_return(addr, tname))
17882 				ret = 0;
17883 			if (ret) {
17884 				bpf_log(log, "%s() is not modifiable\n", tname);
17885 				return ret;
17886 			}
17887 		}
17888 
17889 		break;
17890 	}
17891 	tgt_info->tgt_addr = addr;
17892 	tgt_info->tgt_name = tname;
17893 	tgt_info->tgt_type = t;
17894 	return 0;
17895 }
17896 
17897 BTF_SET_START(btf_id_deny)
17898 BTF_ID_UNUSED
17899 #ifdef CONFIG_SMP
17900 BTF_ID(func, migrate_disable)
17901 BTF_ID(func, migrate_enable)
17902 #endif
17903 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17904 BTF_ID(func, rcu_read_unlock_strict)
17905 #endif
17906 BTF_SET_END(btf_id_deny)
17907 
17908 static bool can_be_sleepable(struct bpf_prog *prog)
17909 {
17910 	if (prog->type == BPF_PROG_TYPE_TRACING) {
17911 		switch (prog->expected_attach_type) {
17912 		case BPF_TRACE_FENTRY:
17913 		case BPF_TRACE_FEXIT:
17914 		case BPF_MODIFY_RETURN:
17915 		case BPF_TRACE_ITER:
17916 			return true;
17917 		default:
17918 			return false;
17919 		}
17920 	}
17921 	return prog->type == BPF_PROG_TYPE_LSM ||
17922 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17923 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17924 }
17925 
17926 static int check_attach_btf_id(struct bpf_verifier_env *env)
17927 {
17928 	struct bpf_prog *prog = env->prog;
17929 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17930 	struct bpf_attach_target_info tgt_info = {};
17931 	u32 btf_id = prog->aux->attach_btf_id;
17932 	struct bpf_trampoline *tr;
17933 	int ret;
17934 	u64 key;
17935 
17936 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17937 		if (prog->aux->sleepable)
17938 			/* attach_btf_id checked to be zero already */
17939 			return 0;
17940 		verbose(env, "Syscall programs can only be sleepable\n");
17941 		return -EINVAL;
17942 	}
17943 
17944 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17945 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17946 		return -EINVAL;
17947 	}
17948 
17949 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17950 		return check_struct_ops_btf_id(env);
17951 
17952 	if (prog->type != BPF_PROG_TYPE_TRACING &&
17953 	    prog->type != BPF_PROG_TYPE_LSM &&
17954 	    prog->type != BPF_PROG_TYPE_EXT)
17955 		return 0;
17956 
17957 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17958 	if (ret)
17959 		return ret;
17960 
17961 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17962 		/* to make freplace equivalent to their targets, they need to
17963 		 * inherit env->ops and expected_attach_type for the rest of the
17964 		 * verification
17965 		 */
17966 		env->ops = bpf_verifier_ops[tgt_prog->type];
17967 		prog->expected_attach_type = tgt_prog->expected_attach_type;
17968 	}
17969 
17970 	/* store info about the attachment target that will be used later */
17971 	prog->aux->attach_func_proto = tgt_info.tgt_type;
17972 	prog->aux->attach_func_name = tgt_info.tgt_name;
17973 
17974 	if (tgt_prog) {
17975 		prog->aux->saved_dst_prog_type = tgt_prog->type;
17976 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17977 	}
17978 
17979 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17980 		prog->aux->attach_btf_trace = true;
17981 		return 0;
17982 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17983 		if (!bpf_iter_prog_supported(prog))
17984 			return -EINVAL;
17985 		return 0;
17986 	}
17987 
17988 	if (prog->type == BPF_PROG_TYPE_LSM) {
17989 		ret = bpf_lsm_verify_prog(&env->log, prog);
17990 		if (ret < 0)
17991 			return ret;
17992 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
17993 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
17994 		return -EINVAL;
17995 	}
17996 
17997 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17998 	tr = bpf_trampoline_get(key, &tgt_info);
17999 	if (!tr)
18000 		return -ENOMEM;
18001 
18002 	prog->aux->dst_trampoline = tr;
18003 	return 0;
18004 }
18005 
18006 struct btf *bpf_get_btf_vmlinux(void)
18007 {
18008 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
18009 		mutex_lock(&bpf_verifier_lock);
18010 		if (!btf_vmlinux)
18011 			btf_vmlinux = btf_parse_vmlinux();
18012 		mutex_unlock(&bpf_verifier_lock);
18013 	}
18014 	return btf_vmlinux;
18015 }
18016 
18017 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
18018 {
18019 	u64 start_time = ktime_get_ns();
18020 	struct bpf_verifier_env *env;
18021 	struct bpf_verifier_log *log;
18022 	int i, len, ret = -EINVAL;
18023 	bool is_priv;
18024 
18025 	/* no program is valid */
18026 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18027 		return -EINVAL;
18028 
18029 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
18030 	 * allocate/free it every time bpf_check() is called
18031 	 */
18032 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
18033 	if (!env)
18034 		return -ENOMEM;
18035 	log = &env->log;
18036 
18037 	len = (*prog)->len;
18038 	env->insn_aux_data =
18039 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
18040 	ret = -ENOMEM;
18041 	if (!env->insn_aux_data)
18042 		goto err_free_env;
18043 	for (i = 0; i < len; i++)
18044 		env->insn_aux_data[i].orig_idx = i;
18045 	env->prog = *prog;
18046 	env->ops = bpf_verifier_ops[env->prog->type];
18047 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
18048 	is_priv = bpf_capable();
18049 
18050 	bpf_get_btf_vmlinux();
18051 
18052 	/* grab the mutex to protect few globals used by verifier */
18053 	if (!is_priv)
18054 		mutex_lock(&bpf_verifier_lock);
18055 
18056 	if (attr->log_level || attr->log_buf || attr->log_size) {
18057 		/* user requested verbose verifier output
18058 		 * and supplied buffer to store the verification trace
18059 		 */
18060 		log->level = attr->log_level;
18061 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
18062 		log->len_total = attr->log_size;
18063 
18064 		/* log attributes have to be sane */
18065 		if (!bpf_verifier_log_attr_valid(log)) {
18066 			ret = -EINVAL;
18067 			goto err_unlock;
18068 		}
18069 	}
18070 
18071 	mark_verifier_state_clean(env);
18072 
18073 	if (IS_ERR(btf_vmlinux)) {
18074 		/* Either gcc or pahole or kernel are broken. */
18075 		verbose(env, "in-kernel BTF is malformed\n");
18076 		ret = PTR_ERR(btf_vmlinux);
18077 		goto skip_full_check;
18078 	}
18079 
18080 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18081 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
18082 		env->strict_alignment = true;
18083 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18084 		env->strict_alignment = false;
18085 
18086 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
18087 	env->allow_uninit_stack = bpf_allow_uninit_stack();
18088 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
18089 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
18090 	env->bpf_capable = bpf_capable();
18091 
18092 	if (is_priv)
18093 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18094 
18095 	env->explored_states = kvcalloc(state_htab_size(env),
18096 				       sizeof(struct bpf_verifier_state_list *),
18097 				       GFP_USER);
18098 	ret = -ENOMEM;
18099 	if (!env->explored_states)
18100 		goto skip_full_check;
18101 
18102 	ret = add_subprog_and_kfunc(env);
18103 	if (ret < 0)
18104 		goto skip_full_check;
18105 
18106 	ret = check_subprogs(env);
18107 	if (ret < 0)
18108 		goto skip_full_check;
18109 
18110 	ret = check_btf_info(env, attr, uattr);
18111 	if (ret < 0)
18112 		goto skip_full_check;
18113 
18114 	ret = check_attach_btf_id(env);
18115 	if (ret)
18116 		goto skip_full_check;
18117 
18118 	ret = resolve_pseudo_ldimm64(env);
18119 	if (ret < 0)
18120 		goto skip_full_check;
18121 
18122 	if (bpf_prog_is_offloaded(env->prog->aux)) {
18123 		ret = bpf_prog_offload_verifier_prep(env->prog);
18124 		if (ret)
18125 			goto skip_full_check;
18126 	}
18127 
18128 	ret = check_cfg(env);
18129 	if (ret < 0)
18130 		goto skip_full_check;
18131 
18132 	ret = do_check_subprogs(env);
18133 	ret = ret ?: do_check_main(env);
18134 
18135 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
18136 		ret = bpf_prog_offload_finalize(env);
18137 
18138 skip_full_check:
18139 	kvfree(env->explored_states);
18140 
18141 	if (ret == 0)
18142 		ret = check_max_stack_depth(env);
18143 
18144 	/* instruction rewrites happen after this point */
18145 	if (ret == 0)
18146 		ret = optimize_bpf_loop(env);
18147 
18148 	if (is_priv) {
18149 		if (ret == 0)
18150 			opt_hard_wire_dead_code_branches(env);
18151 		if (ret == 0)
18152 			ret = opt_remove_dead_code(env);
18153 		if (ret == 0)
18154 			ret = opt_remove_nops(env);
18155 	} else {
18156 		if (ret == 0)
18157 			sanitize_dead_code(env);
18158 	}
18159 
18160 	if (ret == 0)
18161 		/* program is valid, convert *(u32*)(ctx + off) accesses */
18162 		ret = convert_ctx_accesses(env);
18163 
18164 	if (ret == 0)
18165 		ret = do_misc_fixups(env);
18166 
18167 	/* do 32-bit optimization after insn patching has done so those patched
18168 	 * insns could be handled correctly.
18169 	 */
18170 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
18171 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18172 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18173 								     : false;
18174 	}
18175 
18176 	if (ret == 0)
18177 		ret = fixup_call_args(env);
18178 
18179 	env->verification_time = ktime_get_ns() - start_time;
18180 	print_verification_stats(env);
18181 	env->prog->aux->verified_insns = env->insn_processed;
18182 
18183 	if (log->level && bpf_verifier_log_full(log))
18184 		ret = -ENOSPC;
18185 	if (log->level && !log->ubuf) {
18186 		ret = -EFAULT;
18187 		goto err_release_maps;
18188 	}
18189 
18190 	if (ret)
18191 		goto err_release_maps;
18192 
18193 	if (env->used_map_cnt) {
18194 		/* if program passed verifier, update used_maps in bpf_prog_info */
18195 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18196 							  sizeof(env->used_maps[0]),
18197 							  GFP_KERNEL);
18198 
18199 		if (!env->prog->aux->used_maps) {
18200 			ret = -ENOMEM;
18201 			goto err_release_maps;
18202 		}
18203 
18204 		memcpy(env->prog->aux->used_maps, env->used_maps,
18205 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
18206 		env->prog->aux->used_map_cnt = env->used_map_cnt;
18207 	}
18208 	if (env->used_btf_cnt) {
18209 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
18210 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18211 							  sizeof(env->used_btfs[0]),
18212 							  GFP_KERNEL);
18213 		if (!env->prog->aux->used_btfs) {
18214 			ret = -ENOMEM;
18215 			goto err_release_maps;
18216 		}
18217 
18218 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
18219 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18220 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18221 	}
18222 	if (env->used_map_cnt || env->used_btf_cnt) {
18223 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
18224 		 * bpf_ld_imm64 instructions
18225 		 */
18226 		convert_pseudo_ld_imm64(env);
18227 	}
18228 
18229 	adjust_btf_func(env);
18230 
18231 err_release_maps:
18232 	if (!env->prog->aux->used_maps)
18233 		/* if we didn't copy map pointers into bpf_prog_info, release
18234 		 * them now. Otherwise free_used_maps() will release them.
18235 		 */
18236 		release_maps(env);
18237 	if (!env->prog->aux->used_btfs)
18238 		release_btfs(env);
18239 
18240 	/* extension progs temporarily inherit the attach_type of their targets
18241 	   for verification purposes, so set it back to zero before returning
18242 	 */
18243 	if (env->prog->type == BPF_PROG_TYPE_EXT)
18244 		env->prog->expected_attach_type = 0;
18245 
18246 	*prog = env->prog;
18247 err_unlock:
18248 	if (!is_priv)
18249 		mutex_unlock(&bpf_verifier_lock);
18250 	vfree(env->insn_aux_data);
18251 err_free_env:
18252 	kfree(env);
18253 	return ret;
18254 }
18255