xref: /linux/kernel/bpf/verifier.c (revision eb63cfcd2ee8ec3805f6881f43341f589c3d2278)
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/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25 
26 #include "disasm.h"
27 
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 	[_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38 
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all paths through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns either pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163 
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 	/* verifer state is 'st'
167 	 * before processing instruction 'insn_idx'
168 	 * and after processing instruction 'prev_insn_idx'
169 	 */
170 	struct bpf_verifier_state st;
171 	int insn_idx;
172 	int prev_insn_idx;
173 	struct bpf_verifier_stack_elem *next;
174 	/* length of verifier log at the time this state was pushed on stack */
175 	u32 log_pos;
176 };
177 
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
179 #define BPF_COMPLEXITY_LIMIT_STATES	64
180 
181 #define BPF_MAP_KEY_POISON	(1ULL << 63)
182 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
183 
184 #define BPF_MAP_PTR_UNPRIV	1UL
185 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
186 					  POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193 
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198 
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 			      const struct bpf_map *map, bool unpriv)
201 {
202 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 	unpriv |= bpf_map_ptr_unpriv(aux);
204 	aux->map_ptr_state = (unsigned long)map |
205 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207 
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212 
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217 
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222 
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225 	bool poisoned = bpf_map_key_poisoned(aux);
226 
227 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230 
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233 	return insn->code == (BPF_JMP | BPF_CALL) &&
234 	       insn->src_reg == BPF_PSEUDO_CALL;
235 }
236 
237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238 {
239 	return insn->code == (BPF_JMP | BPF_CALL) &&
240 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241 }
242 
243 static bool bpf_pseudo_func(const struct bpf_insn *insn)
244 {
245 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246 	       insn->src_reg == BPF_PSEUDO_FUNC;
247 }
248 
249 struct bpf_call_arg_meta {
250 	struct bpf_map *map_ptr;
251 	bool raw_mode;
252 	bool pkt_access;
253 	int regno;
254 	int access_size;
255 	int mem_size;
256 	u64 msize_max_value;
257 	int ref_obj_id;
258 	int map_uid;
259 	int func_id;
260 	struct btf *btf;
261 	u32 btf_id;
262 	struct btf *ret_btf;
263 	u32 ret_btf_id;
264 	u32 subprogno;
265 };
266 
267 struct btf *btf_vmlinux;
268 
269 static DEFINE_MUTEX(bpf_verifier_lock);
270 
271 static const struct bpf_line_info *
272 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
273 {
274 	const struct bpf_line_info *linfo;
275 	const struct bpf_prog *prog;
276 	u32 i, nr_linfo;
277 
278 	prog = env->prog;
279 	nr_linfo = prog->aux->nr_linfo;
280 
281 	if (!nr_linfo || insn_off >= prog->len)
282 		return NULL;
283 
284 	linfo = prog->aux->linfo;
285 	for (i = 1; i < nr_linfo; i++)
286 		if (insn_off < linfo[i].insn_off)
287 			break;
288 
289 	return &linfo[i - 1];
290 }
291 
292 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
293 		       va_list args)
294 {
295 	unsigned int n;
296 
297 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
298 
299 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
300 		  "verifier log line truncated - local buffer too short\n");
301 
302 	n = min(log->len_total - log->len_used - 1, n);
303 	log->kbuf[n] = '\0';
304 
305 	if (log->level == BPF_LOG_KERNEL) {
306 		pr_err("BPF:%s\n", log->kbuf);
307 		return;
308 	}
309 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
310 		log->len_used += n;
311 	else
312 		log->ubuf = NULL;
313 }
314 
315 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
316 {
317 	char zero = 0;
318 
319 	if (!bpf_verifier_log_needed(log))
320 		return;
321 
322 	log->len_used = new_pos;
323 	if (put_user(zero, log->ubuf + new_pos))
324 		log->ubuf = NULL;
325 }
326 
327 /* log_level controls verbosity level of eBPF verifier.
328  * bpf_verifier_log_write() is used to dump the verification trace to the log,
329  * so the user can figure out what's wrong with the program
330  */
331 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
332 					   const char *fmt, ...)
333 {
334 	va_list args;
335 
336 	if (!bpf_verifier_log_needed(&env->log))
337 		return;
338 
339 	va_start(args, fmt);
340 	bpf_verifier_vlog(&env->log, fmt, args);
341 	va_end(args);
342 }
343 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
344 
345 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
346 {
347 	struct bpf_verifier_env *env = private_data;
348 	va_list args;
349 
350 	if (!bpf_verifier_log_needed(&env->log))
351 		return;
352 
353 	va_start(args, fmt);
354 	bpf_verifier_vlog(&env->log, fmt, args);
355 	va_end(args);
356 }
357 
358 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
359 			    const char *fmt, ...)
360 {
361 	va_list args;
362 
363 	if (!bpf_verifier_log_needed(log))
364 		return;
365 
366 	va_start(args, fmt);
367 	bpf_verifier_vlog(log, fmt, args);
368 	va_end(args);
369 }
370 
371 static const char *ltrim(const char *s)
372 {
373 	while (isspace(*s))
374 		s++;
375 
376 	return s;
377 }
378 
379 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
380 					 u32 insn_off,
381 					 const char *prefix_fmt, ...)
382 {
383 	const struct bpf_line_info *linfo;
384 
385 	if (!bpf_verifier_log_needed(&env->log))
386 		return;
387 
388 	linfo = find_linfo(env, insn_off);
389 	if (!linfo || linfo == env->prev_linfo)
390 		return;
391 
392 	if (prefix_fmt) {
393 		va_list args;
394 
395 		va_start(args, prefix_fmt);
396 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
397 		va_end(args);
398 	}
399 
400 	verbose(env, "%s\n",
401 		ltrim(btf_name_by_offset(env->prog->aux->btf,
402 					 linfo->line_off)));
403 
404 	env->prev_linfo = linfo;
405 }
406 
407 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
408 				   struct bpf_reg_state *reg,
409 				   struct tnum *range, const char *ctx,
410 				   const char *reg_name)
411 {
412 	char tn_buf[48];
413 
414 	verbose(env, "At %s the register %s ", ctx, reg_name);
415 	if (!tnum_is_unknown(reg->var_off)) {
416 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
417 		verbose(env, "has value %s", tn_buf);
418 	} else {
419 		verbose(env, "has unknown scalar value");
420 	}
421 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
422 	verbose(env, " should have been in %s\n", tn_buf);
423 }
424 
425 static bool type_is_pkt_pointer(enum bpf_reg_type type)
426 {
427 	return type == PTR_TO_PACKET ||
428 	       type == PTR_TO_PACKET_META;
429 }
430 
431 static bool type_is_sk_pointer(enum bpf_reg_type type)
432 {
433 	return type == PTR_TO_SOCKET ||
434 		type == PTR_TO_SOCK_COMMON ||
435 		type == PTR_TO_TCP_SOCK ||
436 		type == PTR_TO_XDP_SOCK;
437 }
438 
439 static bool reg_type_not_null(enum bpf_reg_type type)
440 {
441 	return type == PTR_TO_SOCKET ||
442 		type == PTR_TO_TCP_SOCK ||
443 		type == PTR_TO_MAP_VALUE ||
444 		type == PTR_TO_MAP_KEY ||
445 		type == PTR_TO_SOCK_COMMON;
446 }
447 
448 static bool reg_type_may_be_null(enum bpf_reg_type type)
449 {
450 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
451 	       type == PTR_TO_SOCKET_OR_NULL ||
452 	       type == PTR_TO_SOCK_COMMON_OR_NULL ||
453 	       type == PTR_TO_TCP_SOCK_OR_NULL ||
454 	       type == PTR_TO_BTF_ID_OR_NULL ||
455 	       type == PTR_TO_MEM_OR_NULL ||
456 	       type == PTR_TO_RDONLY_BUF_OR_NULL ||
457 	       type == PTR_TO_RDWR_BUF_OR_NULL;
458 }
459 
460 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
461 {
462 	return reg->type == PTR_TO_MAP_VALUE &&
463 		map_value_has_spin_lock(reg->map_ptr);
464 }
465 
466 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
467 {
468 	return type == PTR_TO_SOCKET ||
469 		type == PTR_TO_SOCKET_OR_NULL ||
470 		type == PTR_TO_TCP_SOCK ||
471 		type == PTR_TO_TCP_SOCK_OR_NULL ||
472 		type == PTR_TO_MEM ||
473 		type == PTR_TO_MEM_OR_NULL;
474 }
475 
476 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
477 {
478 	return type == ARG_PTR_TO_SOCK_COMMON;
479 }
480 
481 static bool arg_type_may_be_null(enum bpf_arg_type type)
482 {
483 	return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
484 	       type == ARG_PTR_TO_MEM_OR_NULL ||
485 	       type == ARG_PTR_TO_CTX_OR_NULL ||
486 	       type == ARG_PTR_TO_SOCKET_OR_NULL ||
487 	       type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
488 	       type == ARG_PTR_TO_STACK_OR_NULL;
489 }
490 
491 /* Determine whether the function releases some resources allocated by another
492  * function call. The first reference type argument will be assumed to be
493  * released by release_reference().
494  */
495 static bool is_release_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_sk_release ||
498 	       func_id == BPF_FUNC_ringbuf_submit ||
499 	       func_id == BPF_FUNC_ringbuf_discard;
500 }
501 
502 static bool may_be_acquire_function(enum bpf_func_id func_id)
503 {
504 	return func_id == BPF_FUNC_sk_lookup_tcp ||
505 		func_id == BPF_FUNC_sk_lookup_udp ||
506 		func_id == BPF_FUNC_skc_lookup_tcp ||
507 		func_id == BPF_FUNC_map_lookup_elem ||
508 	        func_id == BPF_FUNC_ringbuf_reserve;
509 }
510 
511 static bool is_acquire_function(enum bpf_func_id func_id,
512 				const struct bpf_map *map)
513 {
514 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
515 
516 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
517 	    func_id == BPF_FUNC_sk_lookup_udp ||
518 	    func_id == BPF_FUNC_skc_lookup_tcp ||
519 	    func_id == BPF_FUNC_ringbuf_reserve)
520 		return true;
521 
522 	if (func_id == BPF_FUNC_map_lookup_elem &&
523 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
524 	     map_type == BPF_MAP_TYPE_SOCKHASH))
525 		return true;
526 
527 	return false;
528 }
529 
530 static bool is_ptr_cast_function(enum bpf_func_id func_id)
531 {
532 	return func_id == BPF_FUNC_tcp_sock ||
533 		func_id == BPF_FUNC_sk_fullsock ||
534 		func_id == BPF_FUNC_skc_to_tcp_sock ||
535 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
536 		func_id == BPF_FUNC_skc_to_udp6_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
538 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
539 }
540 
541 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
542 {
543 	return BPF_CLASS(insn->code) == BPF_STX &&
544 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
545 	       insn->imm == BPF_CMPXCHG;
546 }
547 
548 /* string representation of 'enum bpf_reg_type' */
549 static const char * const reg_type_str[] = {
550 	[NOT_INIT]		= "?",
551 	[SCALAR_VALUE]		= "inv",
552 	[PTR_TO_CTX]		= "ctx",
553 	[CONST_PTR_TO_MAP]	= "map_ptr",
554 	[PTR_TO_MAP_VALUE]	= "map_value",
555 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
556 	[PTR_TO_STACK]		= "fp",
557 	[PTR_TO_PACKET]		= "pkt",
558 	[PTR_TO_PACKET_META]	= "pkt_meta",
559 	[PTR_TO_PACKET_END]	= "pkt_end",
560 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
561 	[PTR_TO_SOCKET]		= "sock",
562 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
563 	[PTR_TO_SOCK_COMMON]	= "sock_common",
564 	[PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
565 	[PTR_TO_TCP_SOCK]	= "tcp_sock",
566 	[PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
567 	[PTR_TO_TP_BUFFER]	= "tp_buffer",
568 	[PTR_TO_XDP_SOCK]	= "xdp_sock",
569 	[PTR_TO_BTF_ID]		= "ptr_",
570 	[PTR_TO_BTF_ID_OR_NULL]	= "ptr_or_null_",
571 	[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
572 	[PTR_TO_MEM]		= "mem",
573 	[PTR_TO_MEM_OR_NULL]	= "mem_or_null",
574 	[PTR_TO_RDONLY_BUF]	= "rdonly_buf",
575 	[PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
576 	[PTR_TO_RDWR_BUF]	= "rdwr_buf",
577 	[PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
578 	[PTR_TO_FUNC]		= "func",
579 	[PTR_TO_MAP_KEY]	= "map_key",
580 };
581 
582 static char slot_type_char[] = {
583 	[STACK_INVALID]	= '?',
584 	[STACK_SPILL]	= 'r',
585 	[STACK_MISC]	= 'm',
586 	[STACK_ZERO]	= '0',
587 };
588 
589 static void print_liveness(struct bpf_verifier_env *env,
590 			   enum bpf_reg_liveness live)
591 {
592 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
593 	    verbose(env, "_");
594 	if (live & REG_LIVE_READ)
595 		verbose(env, "r");
596 	if (live & REG_LIVE_WRITTEN)
597 		verbose(env, "w");
598 	if (live & REG_LIVE_DONE)
599 		verbose(env, "D");
600 }
601 
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
610 static const char *kernel_type_name(const struct btf* btf, u32 id)
611 {
612 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
613 }
614 
615 /* The reg state of a pointer or a bounded scalar was saved when
616  * it was spilled to the stack.
617  */
618 static bool is_spilled_reg(const struct bpf_stack_state *stack)
619 {
620 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
621 }
622 
623 static void scrub_spilled_slot(u8 *stype)
624 {
625 	if (*stype != STACK_INVALID)
626 		*stype = STACK_MISC;
627 }
628 
629 static void print_verifier_state(struct bpf_verifier_env *env,
630 				 const struct bpf_func_state *state)
631 {
632 	const struct bpf_reg_state *reg;
633 	enum bpf_reg_type t;
634 	int i;
635 
636 	if (state->frameno)
637 		verbose(env, " frame%d:", state->frameno);
638 	for (i = 0; i < MAX_BPF_REG; i++) {
639 		reg = &state->regs[i];
640 		t = reg->type;
641 		if (t == NOT_INIT)
642 			continue;
643 		verbose(env, " R%d", i);
644 		print_liveness(env, reg->live);
645 		verbose(env, "=%s", reg_type_str[t]);
646 		if (t == SCALAR_VALUE && reg->precise)
647 			verbose(env, "P");
648 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
649 		    tnum_is_const(reg->var_off)) {
650 			/* reg->off should be 0 for SCALAR_VALUE */
651 			verbose(env, "%lld", reg->var_off.value + reg->off);
652 		} else {
653 			if (t == PTR_TO_BTF_ID ||
654 			    t == PTR_TO_BTF_ID_OR_NULL ||
655 			    t == PTR_TO_PERCPU_BTF_ID)
656 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
657 			verbose(env, "(id=%d", reg->id);
658 			if (reg_type_may_be_refcounted_or_null(t))
659 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
660 			if (t != SCALAR_VALUE)
661 				verbose(env, ",off=%d", reg->off);
662 			if (type_is_pkt_pointer(t))
663 				verbose(env, ",r=%d", reg->range);
664 			else if (t == CONST_PTR_TO_MAP ||
665 				 t == PTR_TO_MAP_KEY ||
666 				 t == PTR_TO_MAP_VALUE ||
667 				 t == PTR_TO_MAP_VALUE_OR_NULL)
668 				verbose(env, ",ks=%d,vs=%d",
669 					reg->map_ptr->key_size,
670 					reg->map_ptr->value_size);
671 			if (tnum_is_const(reg->var_off)) {
672 				/* Typically an immediate SCALAR_VALUE, but
673 				 * could be a pointer whose offset is too big
674 				 * for reg->off
675 				 */
676 				verbose(env, ",imm=%llx", reg->var_off.value);
677 			} else {
678 				if (reg->smin_value != reg->umin_value &&
679 				    reg->smin_value != S64_MIN)
680 					verbose(env, ",smin_value=%lld",
681 						(long long)reg->smin_value);
682 				if (reg->smax_value != reg->umax_value &&
683 				    reg->smax_value != S64_MAX)
684 					verbose(env, ",smax_value=%lld",
685 						(long long)reg->smax_value);
686 				if (reg->umin_value != 0)
687 					verbose(env, ",umin_value=%llu",
688 						(unsigned long long)reg->umin_value);
689 				if (reg->umax_value != U64_MAX)
690 					verbose(env, ",umax_value=%llu",
691 						(unsigned long long)reg->umax_value);
692 				if (!tnum_is_unknown(reg->var_off)) {
693 					char tn_buf[48];
694 
695 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
696 					verbose(env, ",var_off=%s", tn_buf);
697 				}
698 				if (reg->s32_min_value != reg->smin_value &&
699 				    reg->s32_min_value != S32_MIN)
700 					verbose(env, ",s32_min_value=%d",
701 						(int)(reg->s32_min_value));
702 				if (reg->s32_max_value != reg->smax_value &&
703 				    reg->s32_max_value != S32_MAX)
704 					verbose(env, ",s32_max_value=%d",
705 						(int)(reg->s32_max_value));
706 				if (reg->u32_min_value != reg->umin_value &&
707 				    reg->u32_min_value != U32_MIN)
708 					verbose(env, ",u32_min_value=%d",
709 						(int)(reg->u32_min_value));
710 				if (reg->u32_max_value != reg->umax_value &&
711 				    reg->u32_max_value != U32_MAX)
712 					verbose(env, ",u32_max_value=%d",
713 						(int)(reg->u32_max_value));
714 			}
715 			verbose(env, ")");
716 		}
717 	}
718 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
719 		char types_buf[BPF_REG_SIZE + 1];
720 		bool valid = false;
721 		int j;
722 
723 		for (j = 0; j < BPF_REG_SIZE; j++) {
724 			if (state->stack[i].slot_type[j] != STACK_INVALID)
725 				valid = true;
726 			types_buf[j] = slot_type_char[
727 					state->stack[i].slot_type[j]];
728 		}
729 		types_buf[BPF_REG_SIZE] = 0;
730 		if (!valid)
731 			continue;
732 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
733 		print_liveness(env, state->stack[i].spilled_ptr.live);
734 		if (is_spilled_reg(&state->stack[i])) {
735 			reg = &state->stack[i].spilled_ptr;
736 			t = reg->type;
737 			verbose(env, "=%s", reg_type_str[t]);
738 			if (t == SCALAR_VALUE && reg->precise)
739 				verbose(env, "P");
740 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
741 				verbose(env, "%lld", reg->var_off.value + reg->off);
742 		} else {
743 			verbose(env, "=%s", types_buf);
744 		}
745 	}
746 	if (state->acquired_refs && state->refs[0].id) {
747 		verbose(env, " refs=%d", state->refs[0].id);
748 		for (i = 1; i < state->acquired_refs; i++)
749 			if (state->refs[i].id)
750 				verbose(env, ",%d", state->refs[i].id);
751 	}
752 	if (state->in_callback_fn)
753 		verbose(env, " cb");
754 	if (state->in_async_callback_fn)
755 		verbose(env, " async_cb");
756 	verbose(env, "\n");
757 }
758 
759 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
760  * small to hold src. This is different from krealloc since we don't want to preserve
761  * the contents of dst.
762  *
763  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
764  * not be allocated.
765  */
766 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
767 {
768 	size_t bytes;
769 
770 	if (ZERO_OR_NULL_PTR(src))
771 		goto out;
772 
773 	if (unlikely(check_mul_overflow(n, size, &bytes)))
774 		return NULL;
775 
776 	if (ksize(dst) < bytes) {
777 		kfree(dst);
778 		dst = kmalloc_track_caller(bytes, flags);
779 		if (!dst)
780 			return NULL;
781 	}
782 
783 	memcpy(dst, src, bytes);
784 out:
785 	return dst ? dst : ZERO_SIZE_PTR;
786 }
787 
788 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
789  * small to hold new_n items. new items are zeroed out if the array grows.
790  *
791  * Contrary to krealloc_array, does not free arr if new_n is zero.
792  */
793 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
794 {
795 	if (!new_n || old_n == new_n)
796 		goto out;
797 
798 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
799 	if (!arr)
800 		return NULL;
801 
802 	if (new_n > old_n)
803 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
804 
805 out:
806 	return arr ? arr : ZERO_SIZE_PTR;
807 }
808 
809 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
810 {
811 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
812 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
813 	if (!dst->refs)
814 		return -ENOMEM;
815 
816 	dst->acquired_refs = src->acquired_refs;
817 	return 0;
818 }
819 
820 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
821 {
822 	size_t n = src->allocated_stack / BPF_REG_SIZE;
823 
824 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
825 				GFP_KERNEL);
826 	if (!dst->stack)
827 		return -ENOMEM;
828 
829 	dst->allocated_stack = src->allocated_stack;
830 	return 0;
831 }
832 
833 static int resize_reference_state(struct bpf_func_state *state, size_t n)
834 {
835 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
836 				    sizeof(struct bpf_reference_state));
837 	if (!state->refs)
838 		return -ENOMEM;
839 
840 	state->acquired_refs = n;
841 	return 0;
842 }
843 
844 static int grow_stack_state(struct bpf_func_state *state, int size)
845 {
846 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
847 
848 	if (old_n >= n)
849 		return 0;
850 
851 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
852 	if (!state->stack)
853 		return -ENOMEM;
854 
855 	state->allocated_stack = size;
856 	return 0;
857 }
858 
859 /* Acquire a pointer id from the env and update the state->refs to include
860  * this new pointer reference.
861  * On success, returns a valid pointer id to associate with the register
862  * On failure, returns a negative errno.
863  */
864 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
865 {
866 	struct bpf_func_state *state = cur_func(env);
867 	int new_ofs = state->acquired_refs;
868 	int id, err;
869 
870 	err = resize_reference_state(state, state->acquired_refs + 1);
871 	if (err)
872 		return err;
873 	id = ++env->id_gen;
874 	state->refs[new_ofs].id = id;
875 	state->refs[new_ofs].insn_idx = insn_idx;
876 
877 	return id;
878 }
879 
880 /* release function corresponding to acquire_reference_state(). Idempotent. */
881 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
882 {
883 	int i, last_idx;
884 
885 	last_idx = state->acquired_refs - 1;
886 	for (i = 0; i < state->acquired_refs; i++) {
887 		if (state->refs[i].id == ptr_id) {
888 			if (last_idx && i != last_idx)
889 				memcpy(&state->refs[i], &state->refs[last_idx],
890 				       sizeof(*state->refs));
891 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
892 			state->acquired_refs--;
893 			return 0;
894 		}
895 	}
896 	return -EINVAL;
897 }
898 
899 static void free_func_state(struct bpf_func_state *state)
900 {
901 	if (!state)
902 		return;
903 	kfree(state->refs);
904 	kfree(state->stack);
905 	kfree(state);
906 }
907 
908 static void clear_jmp_history(struct bpf_verifier_state *state)
909 {
910 	kfree(state->jmp_history);
911 	state->jmp_history = NULL;
912 	state->jmp_history_cnt = 0;
913 }
914 
915 static void free_verifier_state(struct bpf_verifier_state *state,
916 				bool free_self)
917 {
918 	int i;
919 
920 	for (i = 0; i <= state->curframe; i++) {
921 		free_func_state(state->frame[i]);
922 		state->frame[i] = NULL;
923 	}
924 	clear_jmp_history(state);
925 	if (free_self)
926 		kfree(state);
927 }
928 
929 /* copy verifier state from src to dst growing dst stack space
930  * when necessary to accommodate larger src stack
931  */
932 static int copy_func_state(struct bpf_func_state *dst,
933 			   const struct bpf_func_state *src)
934 {
935 	int err;
936 
937 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
938 	err = copy_reference_state(dst, src);
939 	if (err)
940 		return err;
941 	return copy_stack_state(dst, src);
942 }
943 
944 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
945 			       const struct bpf_verifier_state *src)
946 {
947 	struct bpf_func_state *dst;
948 	int i, err;
949 
950 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
951 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
952 					    GFP_USER);
953 	if (!dst_state->jmp_history)
954 		return -ENOMEM;
955 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
956 
957 	/* if dst has more stack frames then src frame, free them */
958 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
959 		free_func_state(dst_state->frame[i]);
960 		dst_state->frame[i] = NULL;
961 	}
962 	dst_state->speculative = src->speculative;
963 	dst_state->curframe = src->curframe;
964 	dst_state->active_spin_lock = src->active_spin_lock;
965 	dst_state->branches = src->branches;
966 	dst_state->parent = src->parent;
967 	dst_state->first_insn_idx = src->first_insn_idx;
968 	dst_state->last_insn_idx = src->last_insn_idx;
969 	for (i = 0; i <= src->curframe; i++) {
970 		dst = dst_state->frame[i];
971 		if (!dst) {
972 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
973 			if (!dst)
974 				return -ENOMEM;
975 			dst_state->frame[i] = dst;
976 		}
977 		err = copy_func_state(dst, src->frame[i]);
978 		if (err)
979 			return err;
980 	}
981 	return 0;
982 }
983 
984 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
985 {
986 	while (st) {
987 		u32 br = --st->branches;
988 
989 		/* WARN_ON(br > 1) technically makes sense here,
990 		 * but see comment in push_stack(), hence:
991 		 */
992 		WARN_ONCE((int)br < 0,
993 			  "BUG update_branch_counts:branches_to_explore=%d\n",
994 			  br);
995 		if (br)
996 			break;
997 		st = st->parent;
998 	}
999 }
1000 
1001 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1002 		     int *insn_idx, bool pop_log)
1003 {
1004 	struct bpf_verifier_state *cur = env->cur_state;
1005 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1006 	int err;
1007 
1008 	if (env->head == NULL)
1009 		return -ENOENT;
1010 
1011 	if (cur) {
1012 		err = copy_verifier_state(cur, &head->st);
1013 		if (err)
1014 			return err;
1015 	}
1016 	if (pop_log)
1017 		bpf_vlog_reset(&env->log, head->log_pos);
1018 	if (insn_idx)
1019 		*insn_idx = head->insn_idx;
1020 	if (prev_insn_idx)
1021 		*prev_insn_idx = head->prev_insn_idx;
1022 	elem = head->next;
1023 	free_verifier_state(&head->st, false);
1024 	kfree(head);
1025 	env->head = elem;
1026 	env->stack_size--;
1027 	return 0;
1028 }
1029 
1030 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1031 					     int insn_idx, int prev_insn_idx,
1032 					     bool speculative)
1033 {
1034 	struct bpf_verifier_state *cur = env->cur_state;
1035 	struct bpf_verifier_stack_elem *elem;
1036 	int err;
1037 
1038 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1039 	if (!elem)
1040 		goto err;
1041 
1042 	elem->insn_idx = insn_idx;
1043 	elem->prev_insn_idx = prev_insn_idx;
1044 	elem->next = env->head;
1045 	elem->log_pos = env->log.len_used;
1046 	env->head = elem;
1047 	env->stack_size++;
1048 	err = copy_verifier_state(&elem->st, cur);
1049 	if (err)
1050 		goto err;
1051 	elem->st.speculative |= speculative;
1052 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1053 		verbose(env, "The sequence of %d jumps is too complex.\n",
1054 			env->stack_size);
1055 		goto err;
1056 	}
1057 	if (elem->st.parent) {
1058 		++elem->st.parent->branches;
1059 		/* WARN_ON(branches > 2) technically makes sense here,
1060 		 * but
1061 		 * 1. speculative states will bump 'branches' for non-branch
1062 		 * instructions
1063 		 * 2. is_state_visited() heuristics may decide not to create
1064 		 * a new state for a sequence of branches and all such current
1065 		 * and cloned states will be pointing to a single parent state
1066 		 * which might have large 'branches' count.
1067 		 */
1068 	}
1069 	return &elem->st;
1070 err:
1071 	free_verifier_state(env->cur_state, true);
1072 	env->cur_state = NULL;
1073 	/* pop all elements and return */
1074 	while (!pop_stack(env, NULL, NULL, false));
1075 	return NULL;
1076 }
1077 
1078 #define CALLER_SAVED_REGS 6
1079 static const int caller_saved[CALLER_SAVED_REGS] = {
1080 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1081 };
1082 
1083 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1084 				struct bpf_reg_state *reg);
1085 
1086 /* This helper doesn't clear reg->id */
1087 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1088 {
1089 	reg->var_off = tnum_const(imm);
1090 	reg->smin_value = (s64)imm;
1091 	reg->smax_value = (s64)imm;
1092 	reg->umin_value = imm;
1093 	reg->umax_value = imm;
1094 
1095 	reg->s32_min_value = (s32)imm;
1096 	reg->s32_max_value = (s32)imm;
1097 	reg->u32_min_value = (u32)imm;
1098 	reg->u32_max_value = (u32)imm;
1099 }
1100 
1101 /* Mark the unknown part of a register (variable offset or scalar value) as
1102  * known to have the value @imm.
1103  */
1104 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1105 {
1106 	/* Clear id, off, and union(map_ptr, range) */
1107 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1108 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1109 	___mark_reg_known(reg, imm);
1110 }
1111 
1112 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1113 {
1114 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1115 	reg->s32_min_value = (s32)imm;
1116 	reg->s32_max_value = (s32)imm;
1117 	reg->u32_min_value = (u32)imm;
1118 	reg->u32_max_value = (u32)imm;
1119 }
1120 
1121 /* Mark the 'variable offset' part of a register as zero.  This should be
1122  * used only on registers holding a pointer type.
1123  */
1124 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1125 {
1126 	__mark_reg_known(reg, 0);
1127 }
1128 
1129 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1130 {
1131 	__mark_reg_known(reg, 0);
1132 	reg->type = SCALAR_VALUE;
1133 }
1134 
1135 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1136 				struct bpf_reg_state *regs, u32 regno)
1137 {
1138 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1139 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1140 		/* Something bad happened, let's kill all regs */
1141 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1142 			__mark_reg_not_init(env, regs + regno);
1143 		return;
1144 	}
1145 	__mark_reg_known_zero(regs + regno);
1146 }
1147 
1148 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1149 {
1150 	switch (reg->type) {
1151 	case PTR_TO_MAP_VALUE_OR_NULL: {
1152 		const struct bpf_map *map = reg->map_ptr;
1153 
1154 		if (map->inner_map_meta) {
1155 			reg->type = CONST_PTR_TO_MAP;
1156 			reg->map_ptr = map->inner_map_meta;
1157 			/* transfer reg's id which is unique for every map_lookup_elem
1158 			 * as UID of the inner map.
1159 			 */
1160 			reg->map_uid = reg->id;
1161 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1162 			reg->type = PTR_TO_XDP_SOCK;
1163 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1164 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1165 			reg->type = PTR_TO_SOCKET;
1166 		} else {
1167 			reg->type = PTR_TO_MAP_VALUE;
1168 		}
1169 		break;
1170 	}
1171 	case PTR_TO_SOCKET_OR_NULL:
1172 		reg->type = PTR_TO_SOCKET;
1173 		break;
1174 	case PTR_TO_SOCK_COMMON_OR_NULL:
1175 		reg->type = PTR_TO_SOCK_COMMON;
1176 		break;
1177 	case PTR_TO_TCP_SOCK_OR_NULL:
1178 		reg->type = PTR_TO_TCP_SOCK;
1179 		break;
1180 	case PTR_TO_BTF_ID_OR_NULL:
1181 		reg->type = PTR_TO_BTF_ID;
1182 		break;
1183 	case PTR_TO_MEM_OR_NULL:
1184 		reg->type = PTR_TO_MEM;
1185 		break;
1186 	case PTR_TO_RDONLY_BUF_OR_NULL:
1187 		reg->type = PTR_TO_RDONLY_BUF;
1188 		break;
1189 	case PTR_TO_RDWR_BUF_OR_NULL:
1190 		reg->type = PTR_TO_RDWR_BUF;
1191 		break;
1192 	default:
1193 		WARN_ONCE(1, "unknown nullable register type");
1194 	}
1195 }
1196 
1197 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1198 {
1199 	return type_is_pkt_pointer(reg->type);
1200 }
1201 
1202 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1203 {
1204 	return reg_is_pkt_pointer(reg) ||
1205 	       reg->type == PTR_TO_PACKET_END;
1206 }
1207 
1208 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1209 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1210 				    enum bpf_reg_type which)
1211 {
1212 	/* The register can already have a range from prior markings.
1213 	 * This is fine as long as it hasn't been advanced from its
1214 	 * origin.
1215 	 */
1216 	return reg->type == which &&
1217 	       reg->id == 0 &&
1218 	       reg->off == 0 &&
1219 	       tnum_equals_const(reg->var_off, 0);
1220 }
1221 
1222 /* Reset the min/max bounds of a register */
1223 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1224 {
1225 	reg->smin_value = S64_MIN;
1226 	reg->smax_value = S64_MAX;
1227 	reg->umin_value = 0;
1228 	reg->umax_value = U64_MAX;
1229 
1230 	reg->s32_min_value = S32_MIN;
1231 	reg->s32_max_value = S32_MAX;
1232 	reg->u32_min_value = 0;
1233 	reg->u32_max_value = U32_MAX;
1234 }
1235 
1236 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1237 {
1238 	reg->smin_value = S64_MIN;
1239 	reg->smax_value = S64_MAX;
1240 	reg->umin_value = 0;
1241 	reg->umax_value = U64_MAX;
1242 }
1243 
1244 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1245 {
1246 	reg->s32_min_value = S32_MIN;
1247 	reg->s32_max_value = S32_MAX;
1248 	reg->u32_min_value = 0;
1249 	reg->u32_max_value = U32_MAX;
1250 }
1251 
1252 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1253 {
1254 	struct tnum var32_off = tnum_subreg(reg->var_off);
1255 
1256 	/* min signed is max(sign bit) | min(other bits) */
1257 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1258 			var32_off.value | (var32_off.mask & S32_MIN));
1259 	/* max signed is min(sign bit) | max(other bits) */
1260 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1261 			var32_off.value | (var32_off.mask & S32_MAX));
1262 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1263 	reg->u32_max_value = min(reg->u32_max_value,
1264 				 (u32)(var32_off.value | var32_off.mask));
1265 }
1266 
1267 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1268 {
1269 	/* min signed is max(sign bit) | min(other bits) */
1270 	reg->smin_value = max_t(s64, reg->smin_value,
1271 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1272 	/* max signed is min(sign bit) | max(other bits) */
1273 	reg->smax_value = min_t(s64, reg->smax_value,
1274 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1275 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1276 	reg->umax_value = min(reg->umax_value,
1277 			      reg->var_off.value | reg->var_off.mask);
1278 }
1279 
1280 static void __update_reg_bounds(struct bpf_reg_state *reg)
1281 {
1282 	__update_reg32_bounds(reg);
1283 	__update_reg64_bounds(reg);
1284 }
1285 
1286 /* Uses signed min/max values to inform unsigned, and vice-versa */
1287 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1288 {
1289 	/* Learn sign from signed bounds.
1290 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1291 	 * are the same, so combine.  This works even in the negative case, e.g.
1292 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1293 	 */
1294 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1295 		reg->s32_min_value = reg->u32_min_value =
1296 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1297 		reg->s32_max_value = reg->u32_max_value =
1298 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1299 		return;
1300 	}
1301 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1302 	 * boundary, so we must be careful.
1303 	 */
1304 	if ((s32)reg->u32_max_value >= 0) {
1305 		/* Positive.  We can't learn anything from the smin, but smax
1306 		 * is positive, hence safe.
1307 		 */
1308 		reg->s32_min_value = reg->u32_min_value;
1309 		reg->s32_max_value = reg->u32_max_value =
1310 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1311 	} else if ((s32)reg->u32_min_value < 0) {
1312 		/* Negative.  We can't learn anything from the smax, but smin
1313 		 * is negative, hence safe.
1314 		 */
1315 		reg->s32_min_value = reg->u32_min_value =
1316 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1317 		reg->s32_max_value = reg->u32_max_value;
1318 	}
1319 }
1320 
1321 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1322 {
1323 	/* Learn sign from signed bounds.
1324 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1325 	 * are the same, so combine.  This works even in the negative case, e.g.
1326 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1327 	 */
1328 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1329 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1330 							  reg->umin_value);
1331 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1332 							  reg->umax_value);
1333 		return;
1334 	}
1335 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1336 	 * boundary, so we must be careful.
1337 	 */
1338 	if ((s64)reg->umax_value >= 0) {
1339 		/* Positive.  We can't learn anything from the smin, but smax
1340 		 * is positive, hence safe.
1341 		 */
1342 		reg->smin_value = reg->umin_value;
1343 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1344 							  reg->umax_value);
1345 	} else if ((s64)reg->umin_value < 0) {
1346 		/* Negative.  We can't learn anything from the smax, but smin
1347 		 * is negative, hence safe.
1348 		 */
1349 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1350 							  reg->umin_value);
1351 		reg->smax_value = reg->umax_value;
1352 	}
1353 }
1354 
1355 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1356 {
1357 	__reg32_deduce_bounds(reg);
1358 	__reg64_deduce_bounds(reg);
1359 }
1360 
1361 /* Attempts to improve var_off based on unsigned min/max information */
1362 static void __reg_bound_offset(struct bpf_reg_state *reg)
1363 {
1364 	struct tnum var64_off = tnum_intersect(reg->var_off,
1365 					       tnum_range(reg->umin_value,
1366 							  reg->umax_value));
1367 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1368 						tnum_range(reg->u32_min_value,
1369 							   reg->u32_max_value));
1370 
1371 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1372 }
1373 
1374 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1375 {
1376 	reg->umin_value = reg->u32_min_value;
1377 	reg->umax_value = reg->u32_max_value;
1378 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds
1379 	 * but must be positive otherwise set to worse case bounds
1380 	 * and refine later from tnum.
1381 	 */
1382 	if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1383 		reg->smax_value = reg->s32_max_value;
1384 	else
1385 		reg->smax_value = U32_MAX;
1386 	if (reg->s32_min_value >= 0)
1387 		reg->smin_value = reg->s32_min_value;
1388 	else
1389 		reg->smin_value = 0;
1390 }
1391 
1392 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1393 {
1394 	/* special case when 64-bit register has upper 32-bit register
1395 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1396 	 * allowing us to use 32-bit bounds directly,
1397 	 */
1398 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1399 		__reg_assign_32_into_64(reg);
1400 	} else {
1401 		/* Otherwise the best we can do is push lower 32bit known and
1402 		 * unknown bits into register (var_off set from jmp logic)
1403 		 * then learn as much as possible from the 64-bit tnum
1404 		 * known and unknown bits. The previous smin/smax bounds are
1405 		 * invalid here because of jmp32 compare so mark them unknown
1406 		 * so they do not impact tnum bounds calculation.
1407 		 */
1408 		__mark_reg64_unbounded(reg);
1409 		__update_reg_bounds(reg);
1410 	}
1411 
1412 	/* Intersecting with the old var_off might have improved our bounds
1413 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1414 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1415 	 */
1416 	__reg_deduce_bounds(reg);
1417 	__reg_bound_offset(reg);
1418 	__update_reg_bounds(reg);
1419 }
1420 
1421 static bool __reg64_bound_s32(s64 a)
1422 {
1423 	return a > S32_MIN && a < S32_MAX;
1424 }
1425 
1426 static bool __reg64_bound_u32(u64 a)
1427 {
1428 	return a > U32_MIN && a < U32_MAX;
1429 }
1430 
1431 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1432 {
1433 	__mark_reg32_unbounded(reg);
1434 
1435 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1436 		reg->s32_min_value = (s32)reg->smin_value;
1437 		reg->s32_max_value = (s32)reg->smax_value;
1438 	}
1439 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1440 		reg->u32_min_value = (u32)reg->umin_value;
1441 		reg->u32_max_value = (u32)reg->umax_value;
1442 	}
1443 
1444 	/* Intersecting with the old var_off might have improved our bounds
1445 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1446 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1447 	 */
1448 	__reg_deduce_bounds(reg);
1449 	__reg_bound_offset(reg);
1450 	__update_reg_bounds(reg);
1451 }
1452 
1453 /* Mark a register as having a completely unknown (scalar) value. */
1454 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1455 			       struct bpf_reg_state *reg)
1456 {
1457 	/*
1458 	 * Clear type, id, off, and union(map_ptr, range) and
1459 	 * padding between 'type' and union
1460 	 */
1461 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1462 	reg->type = SCALAR_VALUE;
1463 	reg->var_off = tnum_unknown;
1464 	reg->frameno = 0;
1465 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1466 	__mark_reg_unbounded(reg);
1467 }
1468 
1469 static void mark_reg_unknown(struct bpf_verifier_env *env,
1470 			     struct bpf_reg_state *regs, u32 regno)
1471 {
1472 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1473 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1474 		/* Something bad happened, let's kill all regs except FP */
1475 		for (regno = 0; regno < BPF_REG_FP; regno++)
1476 			__mark_reg_not_init(env, regs + regno);
1477 		return;
1478 	}
1479 	__mark_reg_unknown(env, regs + regno);
1480 }
1481 
1482 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1483 				struct bpf_reg_state *reg)
1484 {
1485 	__mark_reg_unknown(env, reg);
1486 	reg->type = NOT_INIT;
1487 }
1488 
1489 static void mark_reg_not_init(struct bpf_verifier_env *env,
1490 			      struct bpf_reg_state *regs, u32 regno)
1491 {
1492 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1493 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1494 		/* Something bad happened, let's kill all regs except FP */
1495 		for (regno = 0; regno < BPF_REG_FP; regno++)
1496 			__mark_reg_not_init(env, regs + regno);
1497 		return;
1498 	}
1499 	__mark_reg_not_init(env, regs + regno);
1500 }
1501 
1502 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1503 			    struct bpf_reg_state *regs, u32 regno,
1504 			    enum bpf_reg_type reg_type,
1505 			    struct btf *btf, u32 btf_id)
1506 {
1507 	if (reg_type == SCALAR_VALUE) {
1508 		mark_reg_unknown(env, regs, regno);
1509 		return;
1510 	}
1511 	mark_reg_known_zero(env, regs, regno);
1512 	regs[regno].type = PTR_TO_BTF_ID;
1513 	regs[regno].btf = btf;
1514 	regs[regno].btf_id = btf_id;
1515 }
1516 
1517 #define DEF_NOT_SUBREG	(0)
1518 static void init_reg_state(struct bpf_verifier_env *env,
1519 			   struct bpf_func_state *state)
1520 {
1521 	struct bpf_reg_state *regs = state->regs;
1522 	int i;
1523 
1524 	for (i = 0; i < MAX_BPF_REG; i++) {
1525 		mark_reg_not_init(env, regs, i);
1526 		regs[i].live = REG_LIVE_NONE;
1527 		regs[i].parent = NULL;
1528 		regs[i].subreg_def = DEF_NOT_SUBREG;
1529 	}
1530 
1531 	/* frame pointer */
1532 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1533 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1534 	regs[BPF_REG_FP].frameno = state->frameno;
1535 }
1536 
1537 #define BPF_MAIN_FUNC (-1)
1538 static void init_func_state(struct bpf_verifier_env *env,
1539 			    struct bpf_func_state *state,
1540 			    int callsite, int frameno, int subprogno)
1541 {
1542 	state->callsite = callsite;
1543 	state->frameno = frameno;
1544 	state->subprogno = subprogno;
1545 	init_reg_state(env, state);
1546 }
1547 
1548 /* Similar to push_stack(), but for async callbacks */
1549 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1550 						int insn_idx, int prev_insn_idx,
1551 						int subprog)
1552 {
1553 	struct bpf_verifier_stack_elem *elem;
1554 	struct bpf_func_state *frame;
1555 
1556 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1557 	if (!elem)
1558 		goto err;
1559 
1560 	elem->insn_idx = insn_idx;
1561 	elem->prev_insn_idx = prev_insn_idx;
1562 	elem->next = env->head;
1563 	elem->log_pos = env->log.len_used;
1564 	env->head = elem;
1565 	env->stack_size++;
1566 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1567 		verbose(env,
1568 			"The sequence of %d jumps is too complex for async cb.\n",
1569 			env->stack_size);
1570 		goto err;
1571 	}
1572 	/* Unlike push_stack() do not copy_verifier_state().
1573 	 * The caller state doesn't matter.
1574 	 * This is async callback. It starts in a fresh stack.
1575 	 * Initialize it similar to do_check_common().
1576 	 */
1577 	elem->st.branches = 1;
1578 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1579 	if (!frame)
1580 		goto err;
1581 	init_func_state(env, frame,
1582 			BPF_MAIN_FUNC /* callsite */,
1583 			0 /* frameno within this callchain */,
1584 			subprog /* subprog number within this prog */);
1585 	elem->st.frame[0] = frame;
1586 	return &elem->st;
1587 err:
1588 	free_verifier_state(env->cur_state, true);
1589 	env->cur_state = NULL;
1590 	/* pop all elements and return */
1591 	while (!pop_stack(env, NULL, NULL, false));
1592 	return NULL;
1593 }
1594 
1595 
1596 enum reg_arg_type {
1597 	SRC_OP,		/* register is used as source operand */
1598 	DST_OP,		/* register is used as destination operand */
1599 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1600 };
1601 
1602 static int cmp_subprogs(const void *a, const void *b)
1603 {
1604 	return ((struct bpf_subprog_info *)a)->start -
1605 	       ((struct bpf_subprog_info *)b)->start;
1606 }
1607 
1608 static int find_subprog(struct bpf_verifier_env *env, int off)
1609 {
1610 	struct bpf_subprog_info *p;
1611 
1612 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1613 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1614 	if (!p)
1615 		return -ENOENT;
1616 	return p - env->subprog_info;
1617 
1618 }
1619 
1620 static int add_subprog(struct bpf_verifier_env *env, int off)
1621 {
1622 	int insn_cnt = env->prog->len;
1623 	int ret;
1624 
1625 	if (off >= insn_cnt || off < 0) {
1626 		verbose(env, "call to invalid destination\n");
1627 		return -EINVAL;
1628 	}
1629 	ret = find_subprog(env, off);
1630 	if (ret >= 0)
1631 		return ret;
1632 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1633 		verbose(env, "too many subprograms\n");
1634 		return -E2BIG;
1635 	}
1636 	/* determine subprog starts. The end is one before the next starts */
1637 	env->subprog_info[env->subprog_cnt++].start = off;
1638 	sort(env->subprog_info, env->subprog_cnt,
1639 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1640 	return env->subprog_cnt - 1;
1641 }
1642 
1643 #define MAX_KFUNC_DESCS 256
1644 #define MAX_KFUNC_BTFS	256
1645 
1646 struct bpf_kfunc_desc {
1647 	struct btf_func_model func_model;
1648 	u32 func_id;
1649 	s32 imm;
1650 	u16 offset;
1651 };
1652 
1653 struct bpf_kfunc_btf {
1654 	struct btf *btf;
1655 	struct module *module;
1656 	u16 offset;
1657 };
1658 
1659 struct bpf_kfunc_desc_tab {
1660 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1661 	u32 nr_descs;
1662 };
1663 
1664 struct bpf_kfunc_btf_tab {
1665 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1666 	u32 nr_descs;
1667 };
1668 
1669 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1670 {
1671 	const struct bpf_kfunc_desc *d0 = a;
1672 	const struct bpf_kfunc_desc *d1 = b;
1673 
1674 	/* func_id is not greater than BTF_MAX_TYPE */
1675 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1676 }
1677 
1678 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1679 {
1680 	const struct bpf_kfunc_btf *d0 = a;
1681 	const struct bpf_kfunc_btf *d1 = b;
1682 
1683 	return d0->offset - d1->offset;
1684 }
1685 
1686 static const struct bpf_kfunc_desc *
1687 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1688 {
1689 	struct bpf_kfunc_desc desc = {
1690 		.func_id = func_id,
1691 		.offset = offset,
1692 	};
1693 	struct bpf_kfunc_desc_tab *tab;
1694 
1695 	tab = prog->aux->kfunc_tab;
1696 	return bsearch(&desc, tab->descs, tab->nr_descs,
1697 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1698 }
1699 
1700 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1701 					 s16 offset, struct module **btf_modp)
1702 {
1703 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1704 	struct bpf_kfunc_btf_tab *tab;
1705 	struct bpf_kfunc_btf *b;
1706 	struct module *mod;
1707 	struct btf *btf;
1708 	int btf_fd;
1709 
1710 	tab = env->prog->aux->kfunc_btf_tab;
1711 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1712 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1713 	if (!b) {
1714 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1715 			verbose(env, "too many different module BTFs\n");
1716 			return ERR_PTR(-E2BIG);
1717 		}
1718 
1719 		if (bpfptr_is_null(env->fd_array)) {
1720 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1721 			return ERR_PTR(-EPROTO);
1722 		}
1723 
1724 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1725 					    offset * sizeof(btf_fd),
1726 					    sizeof(btf_fd)))
1727 			return ERR_PTR(-EFAULT);
1728 
1729 		btf = btf_get_by_fd(btf_fd);
1730 		if (IS_ERR(btf))
1731 			return btf;
1732 
1733 		if (!btf_is_module(btf)) {
1734 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1735 			btf_put(btf);
1736 			return ERR_PTR(-EINVAL);
1737 		}
1738 
1739 		mod = btf_try_get_module(btf);
1740 		if (!mod) {
1741 			btf_put(btf);
1742 			return ERR_PTR(-ENXIO);
1743 		}
1744 
1745 		b = &tab->descs[tab->nr_descs++];
1746 		b->btf = btf;
1747 		b->module = mod;
1748 		b->offset = offset;
1749 
1750 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1751 		     kfunc_btf_cmp_by_off, NULL);
1752 	}
1753 	if (btf_modp)
1754 		*btf_modp = b->module;
1755 	return b->btf;
1756 }
1757 
1758 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1759 {
1760 	if (!tab)
1761 		return;
1762 
1763 	while (tab->nr_descs--) {
1764 		module_put(tab->descs[tab->nr_descs].module);
1765 		btf_put(tab->descs[tab->nr_descs].btf);
1766 	}
1767 	kfree(tab);
1768 }
1769 
1770 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
1771 				       u32 func_id, s16 offset,
1772 				       struct module **btf_modp)
1773 {
1774 	struct btf *kfunc_btf;
1775 
1776 	if (offset) {
1777 		if (offset < 0) {
1778 			/* In the future, this can be allowed to increase limit
1779 			 * of fd index into fd_array, interpreted as u16.
1780 			 */
1781 			verbose(env, "negative offset disallowed for kernel module function call\n");
1782 			return ERR_PTR(-EINVAL);
1783 		}
1784 
1785 		kfunc_btf = __find_kfunc_desc_btf(env, offset, btf_modp);
1786 		if (IS_ERR_OR_NULL(kfunc_btf)) {
1787 			verbose(env, "cannot find module BTF for func_id %u\n", func_id);
1788 			return kfunc_btf ?: ERR_PTR(-ENOENT);
1789 		}
1790 		return kfunc_btf;
1791 	}
1792 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
1793 }
1794 
1795 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1796 {
1797 	const struct btf_type *func, *func_proto;
1798 	struct bpf_kfunc_btf_tab *btf_tab;
1799 	struct bpf_kfunc_desc_tab *tab;
1800 	struct bpf_prog_aux *prog_aux;
1801 	struct bpf_kfunc_desc *desc;
1802 	const char *func_name;
1803 	struct btf *desc_btf;
1804 	unsigned long addr;
1805 	int err;
1806 
1807 	prog_aux = env->prog->aux;
1808 	tab = prog_aux->kfunc_tab;
1809 	btf_tab = prog_aux->kfunc_btf_tab;
1810 	if (!tab) {
1811 		if (!btf_vmlinux) {
1812 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1813 			return -ENOTSUPP;
1814 		}
1815 
1816 		if (!env->prog->jit_requested) {
1817 			verbose(env, "JIT is required for calling kernel function\n");
1818 			return -ENOTSUPP;
1819 		}
1820 
1821 		if (!bpf_jit_supports_kfunc_call()) {
1822 			verbose(env, "JIT does not support calling kernel function\n");
1823 			return -ENOTSUPP;
1824 		}
1825 
1826 		if (!env->prog->gpl_compatible) {
1827 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1828 			return -EINVAL;
1829 		}
1830 
1831 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1832 		if (!tab)
1833 			return -ENOMEM;
1834 		prog_aux->kfunc_tab = tab;
1835 	}
1836 
1837 	/* func_id == 0 is always invalid, but instead of returning an error, be
1838 	 * conservative and wait until the code elimination pass before returning
1839 	 * error, so that invalid calls that get pruned out can be in BPF programs
1840 	 * loaded from userspace.  It is also required that offset be untouched
1841 	 * for such calls.
1842 	 */
1843 	if (!func_id && !offset)
1844 		return 0;
1845 
1846 	if (!btf_tab && offset) {
1847 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1848 		if (!btf_tab)
1849 			return -ENOMEM;
1850 		prog_aux->kfunc_btf_tab = btf_tab;
1851 	}
1852 
1853 	desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL);
1854 	if (IS_ERR(desc_btf)) {
1855 		verbose(env, "failed to find BTF for kernel function\n");
1856 		return PTR_ERR(desc_btf);
1857 	}
1858 
1859 	if (find_kfunc_desc(env->prog, func_id, offset))
1860 		return 0;
1861 
1862 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1863 		verbose(env, "too many different kernel function calls\n");
1864 		return -E2BIG;
1865 	}
1866 
1867 	func = btf_type_by_id(desc_btf, func_id);
1868 	if (!func || !btf_type_is_func(func)) {
1869 		verbose(env, "kernel btf_id %u is not a function\n",
1870 			func_id);
1871 		return -EINVAL;
1872 	}
1873 	func_proto = btf_type_by_id(desc_btf, func->type);
1874 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1875 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1876 			func_id);
1877 		return -EINVAL;
1878 	}
1879 
1880 	func_name = btf_name_by_offset(desc_btf, func->name_off);
1881 	addr = kallsyms_lookup_name(func_name);
1882 	if (!addr) {
1883 		verbose(env, "cannot find address for kernel function %s\n",
1884 			func_name);
1885 		return -EINVAL;
1886 	}
1887 
1888 	desc = &tab->descs[tab->nr_descs++];
1889 	desc->func_id = func_id;
1890 	desc->imm = BPF_CALL_IMM(addr);
1891 	desc->offset = offset;
1892 	err = btf_distill_func_proto(&env->log, desc_btf,
1893 				     func_proto, func_name,
1894 				     &desc->func_model);
1895 	if (!err)
1896 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1897 		     kfunc_desc_cmp_by_id_off, NULL);
1898 	return err;
1899 }
1900 
1901 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1902 {
1903 	const struct bpf_kfunc_desc *d0 = a;
1904 	const struct bpf_kfunc_desc *d1 = b;
1905 
1906 	if (d0->imm > d1->imm)
1907 		return 1;
1908 	else if (d0->imm < d1->imm)
1909 		return -1;
1910 	return 0;
1911 }
1912 
1913 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1914 {
1915 	struct bpf_kfunc_desc_tab *tab;
1916 
1917 	tab = prog->aux->kfunc_tab;
1918 	if (!tab)
1919 		return;
1920 
1921 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1922 	     kfunc_desc_cmp_by_imm, NULL);
1923 }
1924 
1925 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1926 {
1927 	return !!prog->aux->kfunc_tab;
1928 }
1929 
1930 const struct btf_func_model *
1931 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1932 			 const struct bpf_insn *insn)
1933 {
1934 	const struct bpf_kfunc_desc desc = {
1935 		.imm = insn->imm,
1936 	};
1937 	const struct bpf_kfunc_desc *res;
1938 	struct bpf_kfunc_desc_tab *tab;
1939 
1940 	tab = prog->aux->kfunc_tab;
1941 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1942 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1943 
1944 	return res ? &res->func_model : NULL;
1945 }
1946 
1947 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1948 {
1949 	struct bpf_subprog_info *subprog = env->subprog_info;
1950 	struct bpf_insn *insn = env->prog->insnsi;
1951 	int i, ret, insn_cnt = env->prog->len;
1952 
1953 	/* Add entry function. */
1954 	ret = add_subprog(env, 0);
1955 	if (ret)
1956 		return ret;
1957 
1958 	for (i = 0; i < insn_cnt; i++, insn++) {
1959 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1960 		    !bpf_pseudo_kfunc_call(insn))
1961 			continue;
1962 
1963 		if (!env->bpf_capable) {
1964 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1965 			return -EPERM;
1966 		}
1967 
1968 		if (bpf_pseudo_func(insn)) {
1969 			ret = add_subprog(env, i + insn->imm + 1);
1970 			if (ret >= 0)
1971 				/* remember subprog */
1972 				insn[1].imm = ret;
1973 		} else if (bpf_pseudo_call(insn)) {
1974 			ret = add_subprog(env, i + insn->imm + 1);
1975 		} else {
1976 			ret = add_kfunc_call(env, insn->imm, insn->off);
1977 		}
1978 
1979 		if (ret < 0)
1980 			return ret;
1981 	}
1982 
1983 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1984 	 * logic. 'subprog_cnt' should not be increased.
1985 	 */
1986 	subprog[env->subprog_cnt].start = insn_cnt;
1987 
1988 	if (env->log.level & BPF_LOG_LEVEL2)
1989 		for (i = 0; i < env->subprog_cnt; i++)
1990 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1991 
1992 	return 0;
1993 }
1994 
1995 static int check_subprogs(struct bpf_verifier_env *env)
1996 {
1997 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1998 	struct bpf_subprog_info *subprog = env->subprog_info;
1999 	struct bpf_insn *insn = env->prog->insnsi;
2000 	int insn_cnt = env->prog->len;
2001 
2002 	/* now check that all jumps are within the same subprog */
2003 	subprog_start = subprog[cur_subprog].start;
2004 	subprog_end = subprog[cur_subprog + 1].start;
2005 	for (i = 0; i < insn_cnt; i++) {
2006 		u8 code = insn[i].code;
2007 
2008 		if (code == (BPF_JMP | BPF_CALL) &&
2009 		    insn[i].imm == BPF_FUNC_tail_call &&
2010 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2011 			subprog[cur_subprog].has_tail_call = true;
2012 		if (BPF_CLASS(code) == BPF_LD &&
2013 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2014 			subprog[cur_subprog].has_ld_abs = true;
2015 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2016 			goto next;
2017 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2018 			goto next;
2019 		off = i + insn[i].off + 1;
2020 		if (off < subprog_start || off >= subprog_end) {
2021 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2022 			return -EINVAL;
2023 		}
2024 next:
2025 		if (i == subprog_end - 1) {
2026 			/* to avoid fall-through from one subprog into another
2027 			 * the last insn of the subprog should be either exit
2028 			 * or unconditional jump back
2029 			 */
2030 			if (code != (BPF_JMP | BPF_EXIT) &&
2031 			    code != (BPF_JMP | BPF_JA)) {
2032 				verbose(env, "last insn is not an exit or jmp\n");
2033 				return -EINVAL;
2034 			}
2035 			subprog_start = subprog_end;
2036 			cur_subprog++;
2037 			if (cur_subprog < env->subprog_cnt)
2038 				subprog_end = subprog[cur_subprog + 1].start;
2039 		}
2040 	}
2041 	return 0;
2042 }
2043 
2044 /* Parentage chain of this register (or stack slot) should take care of all
2045  * issues like callee-saved registers, stack slot allocation time, etc.
2046  */
2047 static int mark_reg_read(struct bpf_verifier_env *env,
2048 			 const struct bpf_reg_state *state,
2049 			 struct bpf_reg_state *parent, u8 flag)
2050 {
2051 	bool writes = parent == state->parent; /* Observe write marks */
2052 	int cnt = 0;
2053 
2054 	while (parent) {
2055 		/* if read wasn't screened by an earlier write ... */
2056 		if (writes && state->live & REG_LIVE_WRITTEN)
2057 			break;
2058 		if (parent->live & REG_LIVE_DONE) {
2059 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2060 				reg_type_str[parent->type],
2061 				parent->var_off.value, parent->off);
2062 			return -EFAULT;
2063 		}
2064 		/* The first condition is more likely to be true than the
2065 		 * second, checked it first.
2066 		 */
2067 		if ((parent->live & REG_LIVE_READ) == flag ||
2068 		    parent->live & REG_LIVE_READ64)
2069 			/* The parentage chain never changes and
2070 			 * this parent was already marked as LIVE_READ.
2071 			 * There is no need to keep walking the chain again and
2072 			 * keep re-marking all parents as LIVE_READ.
2073 			 * This case happens when the same register is read
2074 			 * multiple times without writes into it in-between.
2075 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2076 			 * then no need to set the weak REG_LIVE_READ32.
2077 			 */
2078 			break;
2079 		/* ... then we depend on parent's value */
2080 		parent->live |= flag;
2081 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2082 		if (flag == REG_LIVE_READ64)
2083 			parent->live &= ~REG_LIVE_READ32;
2084 		state = parent;
2085 		parent = state->parent;
2086 		writes = true;
2087 		cnt++;
2088 	}
2089 
2090 	if (env->longest_mark_read_walk < cnt)
2091 		env->longest_mark_read_walk = cnt;
2092 	return 0;
2093 }
2094 
2095 /* This function is supposed to be used by the following 32-bit optimization
2096  * code only. It returns TRUE if the source or destination register operates
2097  * on 64-bit, otherwise return FALSE.
2098  */
2099 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2100 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2101 {
2102 	u8 code, class, op;
2103 
2104 	code = insn->code;
2105 	class = BPF_CLASS(code);
2106 	op = BPF_OP(code);
2107 	if (class == BPF_JMP) {
2108 		/* BPF_EXIT for "main" will reach here. Return TRUE
2109 		 * conservatively.
2110 		 */
2111 		if (op == BPF_EXIT)
2112 			return true;
2113 		if (op == BPF_CALL) {
2114 			/* BPF to BPF call will reach here because of marking
2115 			 * caller saved clobber with DST_OP_NO_MARK for which we
2116 			 * don't care the register def because they are anyway
2117 			 * marked as NOT_INIT already.
2118 			 */
2119 			if (insn->src_reg == BPF_PSEUDO_CALL)
2120 				return false;
2121 			/* Helper call will reach here because of arg type
2122 			 * check, conservatively return TRUE.
2123 			 */
2124 			if (t == SRC_OP)
2125 				return true;
2126 
2127 			return false;
2128 		}
2129 	}
2130 
2131 	if (class == BPF_ALU64 || class == BPF_JMP ||
2132 	    /* BPF_END always use BPF_ALU class. */
2133 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2134 		return true;
2135 
2136 	if (class == BPF_ALU || class == BPF_JMP32)
2137 		return false;
2138 
2139 	if (class == BPF_LDX) {
2140 		if (t != SRC_OP)
2141 			return BPF_SIZE(code) == BPF_DW;
2142 		/* LDX source must be ptr. */
2143 		return true;
2144 	}
2145 
2146 	if (class == BPF_STX) {
2147 		/* BPF_STX (including atomic variants) has multiple source
2148 		 * operands, one of which is a ptr. Check whether the caller is
2149 		 * asking about it.
2150 		 */
2151 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2152 			return true;
2153 		return BPF_SIZE(code) == BPF_DW;
2154 	}
2155 
2156 	if (class == BPF_LD) {
2157 		u8 mode = BPF_MODE(code);
2158 
2159 		/* LD_IMM64 */
2160 		if (mode == BPF_IMM)
2161 			return true;
2162 
2163 		/* Both LD_IND and LD_ABS return 32-bit data. */
2164 		if (t != SRC_OP)
2165 			return  false;
2166 
2167 		/* Implicit ctx ptr. */
2168 		if (regno == BPF_REG_6)
2169 			return true;
2170 
2171 		/* Explicit source could be any width. */
2172 		return true;
2173 	}
2174 
2175 	if (class == BPF_ST)
2176 		/* The only source register for BPF_ST is a ptr. */
2177 		return true;
2178 
2179 	/* Conservatively return true at default. */
2180 	return true;
2181 }
2182 
2183 /* Return the regno defined by the insn, or -1. */
2184 static int insn_def_regno(const struct bpf_insn *insn)
2185 {
2186 	switch (BPF_CLASS(insn->code)) {
2187 	case BPF_JMP:
2188 	case BPF_JMP32:
2189 	case BPF_ST:
2190 		return -1;
2191 	case BPF_STX:
2192 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2193 		    (insn->imm & BPF_FETCH)) {
2194 			if (insn->imm == BPF_CMPXCHG)
2195 				return BPF_REG_0;
2196 			else
2197 				return insn->src_reg;
2198 		} else {
2199 			return -1;
2200 		}
2201 	default:
2202 		return insn->dst_reg;
2203 	}
2204 }
2205 
2206 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2207 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2208 {
2209 	int dst_reg = insn_def_regno(insn);
2210 
2211 	if (dst_reg == -1)
2212 		return false;
2213 
2214 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2215 }
2216 
2217 static void mark_insn_zext(struct bpf_verifier_env *env,
2218 			   struct bpf_reg_state *reg)
2219 {
2220 	s32 def_idx = reg->subreg_def;
2221 
2222 	if (def_idx == DEF_NOT_SUBREG)
2223 		return;
2224 
2225 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2226 	/* The dst will be zero extended, so won't be sub-register anymore. */
2227 	reg->subreg_def = DEF_NOT_SUBREG;
2228 }
2229 
2230 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2231 			 enum reg_arg_type t)
2232 {
2233 	struct bpf_verifier_state *vstate = env->cur_state;
2234 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2235 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2236 	struct bpf_reg_state *reg, *regs = state->regs;
2237 	bool rw64;
2238 
2239 	if (regno >= MAX_BPF_REG) {
2240 		verbose(env, "R%d is invalid\n", regno);
2241 		return -EINVAL;
2242 	}
2243 
2244 	reg = &regs[regno];
2245 	rw64 = is_reg64(env, insn, regno, reg, t);
2246 	if (t == SRC_OP) {
2247 		/* check whether register used as source operand can be read */
2248 		if (reg->type == NOT_INIT) {
2249 			verbose(env, "R%d !read_ok\n", regno);
2250 			return -EACCES;
2251 		}
2252 		/* We don't need to worry about FP liveness because it's read-only */
2253 		if (regno == BPF_REG_FP)
2254 			return 0;
2255 
2256 		if (rw64)
2257 			mark_insn_zext(env, reg);
2258 
2259 		return mark_reg_read(env, reg, reg->parent,
2260 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2261 	} else {
2262 		/* check whether register used as dest operand can be written to */
2263 		if (regno == BPF_REG_FP) {
2264 			verbose(env, "frame pointer is read only\n");
2265 			return -EACCES;
2266 		}
2267 		reg->live |= REG_LIVE_WRITTEN;
2268 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2269 		if (t == DST_OP)
2270 			mark_reg_unknown(env, regs, regno);
2271 	}
2272 	return 0;
2273 }
2274 
2275 /* for any branch, call, exit record the history of jmps in the given state */
2276 static int push_jmp_history(struct bpf_verifier_env *env,
2277 			    struct bpf_verifier_state *cur)
2278 {
2279 	u32 cnt = cur->jmp_history_cnt;
2280 	struct bpf_idx_pair *p;
2281 
2282 	cnt++;
2283 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2284 	if (!p)
2285 		return -ENOMEM;
2286 	p[cnt - 1].idx = env->insn_idx;
2287 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2288 	cur->jmp_history = p;
2289 	cur->jmp_history_cnt = cnt;
2290 	return 0;
2291 }
2292 
2293 /* Backtrack one insn at a time. If idx is not at the top of recorded
2294  * history then previous instruction came from straight line execution.
2295  */
2296 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2297 			     u32 *history)
2298 {
2299 	u32 cnt = *history;
2300 
2301 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2302 		i = st->jmp_history[cnt - 1].prev_idx;
2303 		(*history)--;
2304 	} else {
2305 		i--;
2306 	}
2307 	return i;
2308 }
2309 
2310 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2311 {
2312 	const struct btf_type *func;
2313 	struct btf *desc_btf;
2314 
2315 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2316 		return NULL;
2317 
2318 	desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL);
2319 	if (IS_ERR(desc_btf))
2320 		return "<error>";
2321 
2322 	func = btf_type_by_id(desc_btf, insn->imm);
2323 	return btf_name_by_offset(desc_btf, func->name_off);
2324 }
2325 
2326 /* For given verifier state backtrack_insn() is called from the last insn to
2327  * the first insn. Its purpose is to compute a bitmask of registers and
2328  * stack slots that needs precision in the parent verifier state.
2329  */
2330 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2331 			  u32 *reg_mask, u64 *stack_mask)
2332 {
2333 	const struct bpf_insn_cbs cbs = {
2334 		.cb_call	= disasm_kfunc_name,
2335 		.cb_print	= verbose,
2336 		.private_data	= env,
2337 	};
2338 	struct bpf_insn *insn = env->prog->insnsi + idx;
2339 	u8 class = BPF_CLASS(insn->code);
2340 	u8 opcode = BPF_OP(insn->code);
2341 	u8 mode = BPF_MODE(insn->code);
2342 	u32 dreg = 1u << insn->dst_reg;
2343 	u32 sreg = 1u << insn->src_reg;
2344 	u32 spi;
2345 
2346 	if (insn->code == 0)
2347 		return 0;
2348 	if (env->log.level & BPF_LOG_LEVEL) {
2349 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2350 		verbose(env, "%d: ", idx);
2351 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2352 	}
2353 
2354 	if (class == BPF_ALU || class == BPF_ALU64) {
2355 		if (!(*reg_mask & dreg))
2356 			return 0;
2357 		if (opcode == BPF_MOV) {
2358 			if (BPF_SRC(insn->code) == BPF_X) {
2359 				/* dreg = sreg
2360 				 * dreg needs precision after this insn
2361 				 * sreg needs precision before this insn
2362 				 */
2363 				*reg_mask &= ~dreg;
2364 				*reg_mask |= sreg;
2365 			} else {
2366 				/* dreg = K
2367 				 * dreg needs precision after this insn.
2368 				 * Corresponding register is already marked
2369 				 * as precise=true in this verifier state.
2370 				 * No further markings in parent are necessary
2371 				 */
2372 				*reg_mask &= ~dreg;
2373 			}
2374 		} else {
2375 			if (BPF_SRC(insn->code) == BPF_X) {
2376 				/* dreg += sreg
2377 				 * both dreg and sreg need precision
2378 				 * before this insn
2379 				 */
2380 				*reg_mask |= sreg;
2381 			} /* else dreg += K
2382 			   * dreg still needs precision before this insn
2383 			   */
2384 		}
2385 	} else if (class == BPF_LDX) {
2386 		if (!(*reg_mask & dreg))
2387 			return 0;
2388 		*reg_mask &= ~dreg;
2389 
2390 		/* scalars can only be spilled into stack w/o losing precision.
2391 		 * Load from any other memory can be zero extended.
2392 		 * The desire to keep that precision is already indicated
2393 		 * by 'precise' mark in corresponding register of this state.
2394 		 * No further tracking necessary.
2395 		 */
2396 		if (insn->src_reg != BPF_REG_FP)
2397 			return 0;
2398 		if (BPF_SIZE(insn->code) != BPF_DW)
2399 			return 0;
2400 
2401 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2402 		 * that [fp - off] slot contains scalar that needs to be
2403 		 * tracked with precision
2404 		 */
2405 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2406 		if (spi >= 64) {
2407 			verbose(env, "BUG spi %d\n", spi);
2408 			WARN_ONCE(1, "verifier backtracking bug");
2409 			return -EFAULT;
2410 		}
2411 		*stack_mask |= 1ull << spi;
2412 	} else if (class == BPF_STX || class == BPF_ST) {
2413 		if (*reg_mask & dreg)
2414 			/* stx & st shouldn't be using _scalar_ dst_reg
2415 			 * to access memory. It means backtracking
2416 			 * encountered a case of pointer subtraction.
2417 			 */
2418 			return -ENOTSUPP;
2419 		/* scalars can only be spilled into stack */
2420 		if (insn->dst_reg != BPF_REG_FP)
2421 			return 0;
2422 		if (BPF_SIZE(insn->code) != BPF_DW)
2423 			return 0;
2424 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2425 		if (spi >= 64) {
2426 			verbose(env, "BUG spi %d\n", spi);
2427 			WARN_ONCE(1, "verifier backtracking bug");
2428 			return -EFAULT;
2429 		}
2430 		if (!(*stack_mask & (1ull << spi)))
2431 			return 0;
2432 		*stack_mask &= ~(1ull << spi);
2433 		if (class == BPF_STX)
2434 			*reg_mask |= sreg;
2435 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2436 		if (opcode == BPF_CALL) {
2437 			if (insn->src_reg == BPF_PSEUDO_CALL)
2438 				return -ENOTSUPP;
2439 			/* regular helper call sets R0 */
2440 			*reg_mask &= ~1;
2441 			if (*reg_mask & 0x3f) {
2442 				/* if backtracing was looking for registers R1-R5
2443 				 * they should have been found already.
2444 				 */
2445 				verbose(env, "BUG regs %x\n", *reg_mask);
2446 				WARN_ONCE(1, "verifier backtracking bug");
2447 				return -EFAULT;
2448 			}
2449 		} else if (opcode == BPF_EXIT) {
2450 			return -ENOTSUPP;
2451 		}
2452 	} else if (class == BPF_LD) {
2453 		if (!(*reg_mask & dreg))
2454 			return 0;
2455 		*reg_mask &= ~dreg;
2456 		/* It's ld_imm64 or ld_abs or ld_ind.
2457 		 * For ld_imm64 no further tracking of precision
2458 		 * into parent is necessary
2459 		 */
2460 		if (mode == BPF_IND || mode == BPF_ABS)
2461 			/* to be analyzed */
2462 			return -ENOTSUPP;
2463 	}
2464 	return 0;
2465 }
2466 
2467 /* the scalar precision tracking algorithm:
2468  * . at the start all registers have precise=false.
2469  * . scalar ranges are tracked as normal through alu and jmp insns.
2470  * . once precise value of the scalar register is used in:
2471  *   .  ptr + scalar alu
2472  *   . if (scalar cond K|scalar)
2473  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2474  *   backtrack through the verifier states and mark all registers and
2475  *   stack slots with spilled constants that these scalar regisers
2476  *   should be precise.
2477  * . during state pruning two registers (or spilled stack slots)
2478  *   are equivalent if both are not precise.
2479  *
2480  * Note the verifier cannot simply walk register parentage chain,
2481  * since many different registers and stack slots could have been
2482  * used to compute single precise scalar.
2483  *
2484  * The approach of starting with precise=true for all registers and then
2485  * backtrack to mark a register as not precise when the verifier detects
2486  * that program doesn't care about specific value (e.g., when helper
2487  * takes register as ARG_ANYTHING parameter) is not safe.
2488  *
2489  * It's ok to walk single parentage chain of the verifier states.
2490  * It's possible that this backtracking will go all the way till 1st insn.
2491  * All other branches will be explored for needing precision later.
2492  *
2493  * The backtracking needs to deal with cases like:
2494  *   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)
2495  * r9 -= r8
2496  * r5 = r9
2497  * if r5 > 0x79f goto pc+7
2498  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2499  * r5 += 1
2500  * ...
2501  * call bpf_perf_event_output#25
2502  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2503  *
2504  * and this case:
2505  * r6 = 1
2506  * call foo // uses callee's r6 inside to compute r0
2507  * r0 += r6
2508  * if r0 == 0 goto
2509  *
2510  * to track above reg_mask/stack_mask needs to be independent for each frame.
2511  *
2512  * Also if parent's curframe > frame where backtracking started,
2513  * the verifier need to mark registers in both frames, otherwise callees
2514  * may incorrectly prune callers. This is similar to
2515  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2516  *
2517  * For now backtracking falls back into conservative marking.
2518  */
2519 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2520 				     struct bpf_verifier_state *st)
2521 {
2522 	struct bpf_func_state *func;
2523 	struct bpf_reg_state *reg;
2524 	int i, j;
2525 
2526 	/* big hammer: mark all scalars precise in this path.
2527 	 * pop_stack may still get !precise scalars.
2528 	 */
2529 	for (; st; st = st->parent)
2530 		for (i = 0; i <= st->curframe; i++) {
2531 			func = st->frame[i];
2532 			for (j = 0; j < BPF_REG_FP; j++) {
2533 				reg = &func->regs[j];
2534 				if (reg->type != SCALAR_VALUE)
2535 					continue;
2536 				reg->precise = true;
2537 			}
2538 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2539 				if (!is_spilled_reg(&func->stack[j]))
2540 					continue;
2541 				reg = &func->stack[j].spilled_ptr;
2542 				if (reg->type != SCALAR_VALUE)
2543 					continue;
2544 				reg->precise = true;
2545 			}
2546 		}
2547 }
2548 
2549 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2550 				  int spi)
2551 {
2552 	struct bpf_verifier_state *st = env->cur_state;
2553 	int first_idx = st->first_insn_idx;
2554 	int last_idx = env->insn_idx;
2555 	struct bpf_func_state *func;
2556 	struct bpf_reg_state *reg;
2557 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2558 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2559 	bool skip_first = true;
2560 	bool new_marks = false;
2561 	int i, err;
2562 
2563 	if (!env->bpf_capable)
2564 		return 0;
2565 
2566 	func = st->frame[st->curframe];
2567 	if (regno >= 0) {
2568 		reg = &func->regs[regno];
2569 		if (reg->type != SCALAR_VALUE) {
2570 			WARN_ONCE(1, "backtracing misuse");
2571 			return -EFAULT;
2572 		}
2573 		if (!reg->precise)
2574 			new_marks = true;
2575 		else
2576 			reg_mask = 0;
2577 		reg->precise = true;
2578 	}
2579 
2580 	while (spi >= 0) {
2581 		if (!is_spilled_reg(&func->stack[spi])) {
2582 			stack_mask = 0;
2583 			break;
2584 		}
2585 		reg = &func->stack[spi].spilled_ptr;
2586 		if (reg->type != SCALAR_VALUE) {
2587 			stack_mask = 0;
2588 			break;
2589 		}
2590 		if (!reg->precise)
2591 			new_marks = true;
2592 		else
2593 			stack_mask = 0;
2594 		reg->precise = true;
2595 		break;
2596 	}
2597 
2598 	if (!new_marks)
2599 		return 0;
2600 	if (!reg_mask && !stack_mask)
2601 		return 0;
2602 	for (;;) {
2603 		DECLARE_BITMAP(mask, 64);
2604 		u32 history = st->jmp_history_cnt;
2605 
2606 		if (env->log.level & BPF_LOG_LEVEL)
2607 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2608 		for (i = last_idx;;) {
2609 			if (skip_first) {
2610 				err = 0;
2611 				skip_first = false;
2612 			} else {
2613 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2614 			}
2615 			if (err == -ENOTSUPP) {
2616 				mark_all_scalars_precise(env, st);
2617 				return 0;
2618 			} else if (err) {
2619 				return err;
2620 			}
2621 			if (!reg_mask && !stack_mask)
2622 				/* Found assignment(s) into tracked register in this state.
2623 				 * Since this state is already marked, just return.
2624 				 * Nothing to be tracked further in the parent state.
2625 				 */
2626 				return 0;
2627 			if (i == first_idx)
2628 				break;
2629 			i = get_prev_insn_idx(st, i, &history);
2630 			if (i >= env->prog->len) {
2631 				/* This can happen if backtracking reached insn 0
2632 				 * and there are still reg_mask or stack_mask
2633 				 * to backtrack.
2634 				 * It means the backtracking missed the spot where
2635 				 * particular register was initialized with a constant.
2636 				 */
2637 				verbose(env, "BUG backtracking idx %d\n", i);
2638 				WARN_ONCE(1, "verifier backtracking bug");
2639 				return -EFAULT;
2640 			}
2641 		}
2642 		st = st->parent;
2643 		if (!st)
2644 			break;
2645 
2646 		new_marks = false;
2647 		func = st->frame[st->curframe];
2648 		bitmap_from_u64(mask, reg_mask);
2649 		for_each_set_bit(i, mask, 32) {
2650 			reg = &func->regs[i];
2651 			if (reg->type != SCALAR_VALUE) {
2652 				reg_mask &= ~(1u << i);
2653 				continue;
2654 			}
2655 			if (!reg->precise)
2656 				new_marks = true;
2657 			reg->precise = true;
2658 		}
2659 
2660 		bitmap_from_u64(mask, stack_mask);
2661 		for_each_set_bit(i, mask, 64) {
2662 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2663 				/* the sequence of instructions:
2664 				 * 2: (bf) r3 = r10
2665 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2666 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2667 				 * doesn't contain jmps. It's backtracked
2668 				 * as a single block.
2669 				 * During backtracking insn 3 is not recognized as
2670 				 * stack access, so at the end of backtracking
2671 				 * stack slot fp-8 is still marked in stack_mask.
2672 				 * However the parent state may not have accessed
2673 				 * fp-8 and it's "unallocated" stack space.
2674 				 * In such case fallback to conservative.
2675 				 */
2676 				mark_all_scalars_precise(env, st);
2677 				return 0;
2678 			}
2679 
2680 			if (!is_spilled_reg(&func->stack[i])) {
2681 				stack_mask &= ~(1ull << i);
2682 				continue;
2683 			}
2684 			reg = &func->stack[i].spilled_ptr;
2685 			if (reg->type != SCALAR_VALUE) {
2686 				stack_mask &= ~(1ull << i);
2687 				continue;
2688 			}
2689 			if (!reg->precise)
2690 				new_marks = true;
2691 			reg->precise = true;
2692 		}
2693 		if (env->log.level & BPF_LOG_LEVEL) {
2694 			print_verifier_state(env, func);
2695 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2696 				new_marks ? "didn't have" : "already had",
2697 				reg_mask, stack_mask);
2698 		}
2699 
2700 		if (!reg_mask && !stack_mask)
2701 			break;
2702 		if (!new_marks)
2703 			break;
2704 
2705 		last_idx = st->last_insn_idx;
2706 		first_idx = st->first_insn_idx;
2707 	}
2708 	return 0;
2709 }
2710 
2711 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2712 {
2713 	return __mark_chain_precision(env, regno, -1);
2714 }
2715 
2716 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2717 {
2718 	return __mark_chain_precision(env, -1, spi);
2719 }
2720 
2721 static bool is_spillable_regtype(enum bpf_reg_type type)
2722 {
2723 	switch (type) {
2724 	case PTR_TO_MAP_VALUE:
2725 	case PTR_TO_MAP_VALUE_OR_NULL:
2726 	case PTR_TO_STACK:
2727 	case PTR_TO_CTX:
2728 	case PTR_TO_PACKET:
2729 	case PTR_TO_PACKET_META:
2730 	case PTR_TO_PACKET_END:
2731 	case PTR_TO_FLOW_KEYS:
2732 	case CONST_PTR_TO_MAP:
2733 	case PTR_TO_SOCKET:
2734 	case PTR_TO_SOCKET_OR_NULL:
2735 	case PTR_TO_SOCK_COMMON:
2736 	case PTR_TO_SOCK_COMMON_OR_NULL:
2737 	case PTR_TO_TCP_SOCK:
2738 	case PTR_TO_TCP_SOCK_OR_NULL:
2739 	case PTR_TO_XDP_SOCK:
2740 	case PTR_TO_BTF_ID:
2741 	case PTR_TO_BTF_ID_OR_NULL:
2742 	case PTR_TO_RDONLY_BUF:
2743 	case PTR_TO_RDONLY_BUF_OR_NULL:
2744 	case PTR_TO_RDWR_BUF:
2745 	case PTR_TO_RDWR_BUF_OR_NULL:
2746 	case PTR_TO_PERCPU_BTF_ID:
2747 	case PTR_TO_MEM:
2748 	case PTR_TO_MEM_OR_NULL:
2749 	case PTR_TO_FUNC:
2750 	case PTR_TO_MAP_KEY:
2751 		return true;
2752 	default:
2753 		return false;
2754 	}
2755 }
2756 
2757 /* Does this register contain a constant zero? */
2758 static bool register_is_null(struct bpf_reg_state *reg)
2759 {
2760 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2761 }
2762 
2763 static bool register_is_const(struct bpf_reg_state *reg)
2764 {
2765 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2766 }
2767 
2768 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2769 {
2770 	return tnum_is_unknown(reg->var_off) &&
2771 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2772 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2773 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2774 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2775 }
2776 
2777 static bool register_is_bounded(struct bpf_reg_state *reg)
2778 {
2779 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2780 }
2781 
2782 static bool __is_pointer_value(bool allow_ptr_leaks,
2783 			       const struct bpf_reg_state *reg)
2784 {
2785 	if (allow_ptr_leaks)
2786 		return false;
2787 
2788 	return reg->type != SCALAR_VALUE;
2789 }
2790 
2791 static void save_register_state(struct bpf_func_state *state,
2792 				int spi, struct bpf_reg_state *reg,
2793 				int size)
2794 {
2795 	int i;
2796 
2797 	state->stack[spi].spilled_ptr = *reg;
2798 	if (size == BPF_REG_SIZE)
2799 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2800 
2801 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2802 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2803 
2804 	/* size < 8 bytes spill */
2805 	for (; i; i--)
2806 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2807 }
2808 
2809 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2810  * stack boundary and alignment are checked in check_mem_access()
2811  */
2812 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2813 				       /* stack frame we're writing to */
2814 				       struct bpf_func_state *state,
2815 				       int off, int size, int value_regno,
2816 				       int insn_idx)
2817 {
2818 	struct bpf_func_state *cur; /* state of the current function */
2819 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2820 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2821 	struct bpf_reg_state *reg = NULL;
2822 
2823 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2824 	if (err)
2825 		return err;
2826 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2827 	 * so it's aligned access and [off, off + size) are within stack limits
2828 	 */
2829 	if (!env->allow_ptr_leaks &&
2830 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2831 	    size != BPF_REG_SIZE) {
2832 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2833 		return -EACCES;
2834 	}
2835 
2836 	cur = env->cur_state->frame[env->cur_state->curframe];
2837 	if (value_regno >= 0)
2838 		reg = &cur->regs[value_regno];
2839 	if (!env->bypass_spec_v4) {
2840 		bool sanitize = reg && is_spillable_regtype(reg->type);
2841 
2842 		for (i = 0; i < size; i++) {
2843 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2844 				sanitize = true;
2845 				break;
2846 			}
2847 		}
2848 
2849 		if (sanitize)
2850 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2851 	}
2852 
2853 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2854 	    !register_is_null(reg) && env->bpf_capable) {
2855 		if (dst_reg != BPF_REG_FP) {
2856 			/* The backtracking logic can only recognize explicit
2857 			 * stack slot address like [fp - 8]. Other spill of
2858 			 * scalar via different register has to be conservative.
2859 			 * Backtrack from here and mark all registers as precise
2860 			 * that contributed into 'reg' being a constant.
2861 			 */
2862 			err = mark_chain_precision(env, value_regno);
2863 			if (err)
2864 				return err;
2865 		}
2866 		save_register_state(state, spi, reg, size);
2867 	} else if (reg && is_spillable_regtype(reg->type)) {
2868 		/* register containing pointer is being spilled into stack */
2869 		if (size != BPF_REG_SIZE) {
2870 			verbose_linfo(env, insn_idx, "; ");
2871 			verbose(env, "invalid size of register spill\n");
2872 			return -EACCES;
2873 		}
2874 		if (state != cur && reg->type == PTR_TO_STACK) {
2875 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2876 			return -EINVAL;
2877 		}
2878 		save_register_state(state, spi, reg, size);
2879 	} else {
2880 		u8 type = STACK_MISC;
2881 
2882 		/* regular write of data into stack destroys any spilled ptr */
2883 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2884 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2885 		if (is_spilled_reg(&state->stack[spi]))
2886 			for (i = 0; i < BPF_REG_SIZE; i++)
2887 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2888 
2889 		/* only mark the slot as written if all 8 bytes were written
2890 		 * otherwise read propagation may incorrectly stop too soon
2891 		 * when stack slots are partially written.
2892 		 * This heuristic means that read propagation will be
2893 		 * conservative, since it will add reg_live_read marks
2894 		 * to stack slots all the way to first state when programs
2895 		 * writes+reads less than 8 bytes
2896 		 */
2897 		if (size == BPF_REG_SIZE)
2898 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2899 
2900 		/* when we zero initialize stack slots mark them as such */
2901 		if (reg && register_is_null(reg)) {
2902 			/* backtracking doesn't work for STACK_ZERO yet. */
2903 			err = mark_chain_precision(env, value_regno);
2904 			if (err)
2905 				return err;
2906 			type = STACK_ZERO;
2907 		}
2908 
2909 		/* Mark slots affected by this stack write. */
2910 		for (i = 0; i < size; i++)
2911 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2912 				type;
2913 	}
2914 	return 0;
2915 }
2916 
2917 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2918  * known to contain a variable offset.
2919  * This function checks whether the write is permitted and conservatively
2920  * tracks the effects of the write, considering that each stack slot in the
2921  * dynamic range is potentially written to.
2922  *
2923  * 'off' includes 'regno->off'.
2924  * 'value_regno' can be -1, meaning that an unknown value is being written to
2925  * the stack.
2926  *
2927  * Spilled pointers in range are not marked as written because we don't know
2928  * what's going to be actually written. This means that read propagation for
2929  * future reads cannot be terminated by this write.
2930  *
2931  * For privileged programs, uninitialized stack slots are considered
2932  * initialized by this write (even though we don't know exactly what offsets
2933  * are going to be written to). The idea is that we don't want the verifier to
2934  * reject future reads that access slots written to through variable offsets.
2935  */
2936 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2937 				     /* func where register points to */
2938 				     struct bpf_func_state *state,
2939 				     int ptr_regno, int off, int size,
2940 				     int value_regno, int insn_idx)
2941 {
2942 	struct bpf_func_state *cur; /* state of the current function */
2943 	int min_off, max_off;
2944 	int i, err;
2945 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2946 	bool writing_zero = false;
2947 	/* set if the fact that we're writing a zero is used to let any
2948 	 * stack slots remain STACK_ZERO
2949 	 */
2950 	bool zero_used = false;
2951 
2952 	cur = env->cur_state->frame[env->cur_state->curframe];
2953 	ptr_reg = &cur->regs[ptr_regno];
2954 	min_off = ptr_reg->smin_value + off;
2955 	max_off = ptr_reg->smax_value + off + size;
2956 	if (value_regno >= 0)
2957 		value_reg = &cur->regs[value_regno];
2958 	if (value_reg && register_is_null(value_reg))
2959 		writing_zero = true;
2960 
2961 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2962 	if (err)
2963 		return err;
2964 
2965 
2966 	/* Variable offset writes destroy any spilled pointers in range. */
2967 	for (i = min_off; i < max_off; i++) {
2968 		u8 new_type, *stype;
2969 		int slot, spi;
2970 
2971 		slot = -i - 1;
2972 		spi = slot / BPF_REG_SIZE;
2973 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2974 
2975 		if (!env->allow_ptr_leaks
2976 				&& *stype != NOT_INIT
2977 				&& *stype != SCALAR_VALUE) {
2978 			/* Reject the write if there's are spilled pointers in
2979 			 * range. If we didn't reject here, the ptr status
2980 			 * would be erased below (even though not all slots are
2981 			 * actually overwritten), possibly opening the door to
2982 			 * leaks.
2983 			 */
2984 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2985 				insn_idx, i);
2986 			return -EINVAL;
2987 		}
2988 
2989 		/* Erase all spilled pointers. */
2990 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2991 
2992 		/* Update the slot type. */
2993 		new_type = STACK_MISC;
2994 		if (writing_zero && *stype == STACK_ZERO) {
2995 			new_type = STACK_ZERO;
2996 			zero_used = true;
2997 		}
2998 		/* If the slot is STACK_INVALID, we check whether it's OK to
2999 		 * pretend that it will be initialized by this write. The slot
3000 		 * might not actually be written to, and so if we mark it as
3001 		 * initialized future reads might leak uninitialized memory.
3002 		 * For privileged programs, we will accept such reads to slots
3003 		 * that may or may not be written because, if we're reject
3004 		 * them, the error would be too confusing.
3005 		 */
3006 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3007 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3008 					insn_idx, i);
3009 			return -EINVAL;
3010 		}
3011 		*stype = new_type;
3012 	}
3013 	if (zero_used) {
3014 		/* backtracking doesn't work for STACK_ZERO yet. */
3015 		err = mark_chain_precision(env, value_regno);
3016 		if (err)
3017 			return err;
3018 	}
3019 	return 0;
3020 }
3021 
3022 /* When register 'dst_regno' is assigned some values from stack[min_off,
3023  * max_off), we set the register's type according to the types of the
3024  * respective stack slots. If all the stack values are known to be zeros, then
3025  * so is the destination reg. Otherwise, the register is considered to be
3026  * SCALAR. This function does not deal with register filling; the caller must
3027  * ensure that all spilled registers in the stack range have been marked as
3028  * read.
3029  */
3030 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3031 				/* func where src register points to */
3032 				struct bpf_func_state *ptr_state,
3033 				int min_off, int max_off, int dst_regno)
3034 {
3035 	struct bpf_verifier_state *vstate = env->cur_state;
3036 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3037 	int i, slot, spi;
3038 	u8 *stype;
3039 	int zeros = 0;
3040 
3041 	for (i = min_off; i < max_off; i++) {
3042 		slot = -i - 1;
3043 		spi = slot / BPF_REG_SIZE;
3044 		stype = ptr_state->stack[spi].slot_type;
3045 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3046 			break;
3047 		zeros++;
3048 	}
3049 	if (zeros == max_off - min_off) {
3050 		/* any access_size read into register is zero extended,
3051 		 * so the whole register == const_zero
3052 		 */
3053 		__mark_reg_const_zero(&state->regs[dst_regno]);
3054 		/* backtracking doesn't support STACK_ZERO yet,
3055 		 * so mark it precise here, so that later
3056 		 * backtracking can stop here.
3057 		 * Backtracking may not need this if this register
3058 		 * doesn't participate in pointer adjustment.
3059 		 * Forward propagation of precise flag is not
3060 		 * necessary either. This mark is only to stop
3061 		 * backtracking. Any register that contributed
3062 		 * to const 0 was marked precise before spill.
3063 		 */
3064 		state->regs[dst_regno].precise = true;
3065 	} else {
3066 		/* have read misc data from the stack */
3067 		mark_reg_unknown(env, state->regs, dst_regno);
3068 	}
3069 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3070 }
3071 
3072 /* Read the stack at 'off' and put the results into the register indicated by
3073  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3074  * spilled reg.
3075  *
3076  * 'dst_regno' can be -1, meaning that the read value is not going to a
3077  * register.
3078  *
3079  * The access is assumed to be within the current stack bounds.
3080  */
3081 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3082 				      /* func where src register points to */
3083 				      struct bpf_func_state *reg_state,
3084 				      int off, int size, int dst_regno)
3085 {
3086 	struct bpf_verifier_state *vstate = env->cur_state;
3087 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3088 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3089 	struct bpf_reg_state *reg;
3090 	u8 *stype, type;
3091 
3092 	stype = reg_state->stack[spi].slot_type;
3093 	reg = &reg_state->stack[spi].spilled_ptr;
3094 
3095 	if (is_spilled_reg(&reg_state->stack[spi])) {
3096 		if (size != BPF_REG_SIZE) {
3097 			u8 scalar_size = 0;
3098 
3099 			if (reg->type != SCALAR_VALUE) {
3100 				verbose_linfo(env, env->insn_idx, "; ");
3101 				verbose(env, "invalid size of register fill\n");
3102 				return -EACCES;
3103 			}
3104 
3105 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3106 			if (dst_regno < 0)
3107 				return 0;
3108 
3109 			for (i = BPF_REG_SIZE; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3110 				scalar_size++;
3111 
3112 			if (!(off % BPF_REG_SIZE) && size == scalar_size) {
3113 				/* The earlier check_reg_arg() has decided the
3114 				 * subreg_def for this insn.  Save it first.
3115 				 */
3116 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3117 
3118 				state->regs[dst_regno] = *reg;
3119 				state->regs[dst_regno].subreg_def = subreg_def;
3120 			} else {
3121 				for (i = 0; i < size; i++) {
3122 					type = stype[(slot - i) % BPF_REG_SIZE];
3123 					if (type == STACK_SPILL)
3124 						continue;
3125 					if (type == STACK_MISC)
3126 						continue;
3127 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3128 						off, i, size);
3129 					return -EACCES;
3130 				}
3131 				mark_reg_unknown(env, state->regs, dst_regno);
3132 			}
3133 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3134 			return 0;
3135 		}
3136 		for (i = 1; i < BPF_REG_SIZE; i++) {
3137 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
3138 				verbose(env, "corrupted spill memory\n");
3139 				return -EACCES;
3140 			}
3141 		}
3142 
3143 		if (dst_regno >= 0) {
3144 			/* restore register state from stack */
3145 			state->regs[dst_regno] = *reg;
3146 			/* mark reg as written since spilled pointer state likely
3147 			 * has its liveness marks cleared by is_state_visited()
3148 			 * which resets stack/reg liveness for state transitions
3149 			 */
3150 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3151 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3152 			/* If dst_regno==-1, the caller is asking us whether
3153 			 * it is acceptable to use this value as a SCALAR_VALUE
3154 			 * (e.g. for XADD).
3155 			 * We must not allow unprivileged callers to do that
3156 			 * with spilled pointers.
3157 			 */
3158 			verbose(env, "leaking pointer from stack off %d\n",
3159 				off);
3160 			return -EACCES;
3161 		}
3162 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3163 	} else {
3164 		for (i = 0; i < size; i++) {
3165 			type = stype[(slot - i) % BPF_REG_SIZE];
3166 			if (type == STACK_MISC)
3167 				continue;
3168 			if (type == STACK_ZERO)
3169 				continue;
3170 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3171 				off, i, size);
3172 			return -EACCES;
3173 		}
3174 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3175 		if (dst_regno >= 0)
3176 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3177 	}
3178 	return 0;
3179 }
3180 
3181 enum stack_access_src {
3182 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3183 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3184 };
3185 
3186 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3187 					 int regno, int off, int access_size,
3188 					 bool zero_size_allowed,
3189 					 enum stack_access_src type,
3190 					 struct bpf_call_arg_meta *meta);
3191 
3192 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3193 {
3194 	return cur_regs(env) + regno;
3195 }
3196 
3197 /* Read the stack at 'ptr_regno + off' and put the result into the register
3198  * 'dst_regno'.
3199  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3200  * but not its variable offset.
3201  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3202  *
3203  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3204  * filling registers (i.e. reads of spilled register cannot be detected when
3205  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3206  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3207  * offset; for a fixed offset check_stack_read_fixed_off should be used
3208  * instead.
3209  */
3210 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3211 				    int ptr_regno, int off, int size, int dst_regno)
3212 {
3213 	/* The state of the source register. */
3214 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3215 	struct bpf_func_state *ptr_state = func(env, reg);
3216 	int err;
3217 	int min_off, max_off;
3218 
3219 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3220 	 */
3221 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3222 					    false, ACCESS_DIRECT, NULL);
3223 	if (err)
3224 		return err;
3225 
3226 	min_off = reg->smin_value + off;
3227 	max_off = reg->smax_value + off;
3228 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3229 	return 0;
3230 }
3231 
3232 /* check_stack_read dispatches to check_stack_read_fixed_off or
3233  * check_stack_read_var_off.
3234  *
3235  * The caller must ensure that the offset falls within the allocated stack
3236  * bounds.
3237  *
3238  * 'dst_regno' is a register which will receive the value from the stack. It
3239  * can be -1, meaning that the read value is not going to a register.
3240  */
3241 static int check_stack_read(struct bpf_verifier_env *env,
3242 			    int ptr_regno, int off, int size,
3243 			    int dst_regno)
3244 {
3245 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3246 	struct bpf_func_state *state = func(env, reg);
3247 	int err;
3248 	/* Some accesses are only permitted with a static offset. */
3249 	bool var_off = !tnum_is_const(reg->var_off);
3250 
3251 	/* The offset is required to be static when reads don't go to a
3252 	 * register, in order to not leak pointers (see
3253 	 * check_stack_read_fixed_off).
3254 	 */
3255 	if (dst_regno < 0 && var_off) {
3256 		char tn_buf[48];
3257 
3258 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3259 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3260 			tn_buf, off, size);
3261 		return -EACCES;
3262 	}
3263 	/* Variable offset is prohibited for unprivileged mode for simplicity
3264 	 * since it requires corresponding support in Spectre masking for stack
3265 	 * ALU. See also retrieve_ptr_limit().
3266 	 */
3267 	if (!env->bypass_spec_v1 && var_off) {
3268 		char tn_buf[48];
3269 
3270 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3271 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3272 				ptr_regno, tn_buf);
3273 		return -EACCES;
3274 	}
3275 
3276 	if (!var_off) {
3277 		off += reg->var_off.value;
3278 		err = check_stack_read_fixed_off(env, state, off, size,
3279 						 dst_regno);
3280 	} else {
3281 		/* Variable offset stack reads need more conservative handling
3282 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3283 		 * branch.
3284 		 */
3285 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3286 					       dst_regno);
3287 	}
3288 	return err;
3289 }
3290 
3291 
3292 /* check_stack_write dispatches to check_stack_write_fixed_off or
3293  * check_stack_write_var_off.
3294  *
3295  * 'ptr_regno' is the register used as a pointer into the stack.
3296  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3297  * 'value_regno' is the register whose value we're writing to the stack. It can
3298  * be -1, meaning that we're not writing from a register.
3299  *
3300  * The caller must ensure that the offset falls within the maximum stack size.
3301  */
3302 static int check_stack_write(struct bpf_verifier_env *env,
3303 			     int ptr_regno, int off, int size,
3304 			     int value_regno, int insn_idx)
3305 {
3306 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3307 	struct bpf_func_state *state = func(env, reg);
3308 	int err;
3309 
3310 	if (tnum_is_const(reg->var_off)) {
3311 		off += reg->var_off.value;
3312 		err = check_stack_write_fixed_off(env, state, off, size,
3313 						  value_regno, insn_idx);
3314 	} else {
3315 		/* Variable offset stack reads need more conservative handling
3316 		 * than fixed offset ones.
3317 		 */
3318 		err = check_stack_write_var_off(env, state,
3319 						ptr_regno, off, size,
3320 						value_regno, insn_idx);
3321 	}
3322 	return err;
3323 }
3324 
3325 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3326 				 int off, int size, enum bpf_access_type type)
3327 {
3328 	struct bpf_reg_state *regs = cur_regs(env);
3329 	struct bpf_map *map = regs[regno].map_ptr;
3330 	u32 cap = bpf_map_flags_to_cap(map);
3331 
3332 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3333 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3334 			map->value_size, off, size);
3335 		return -EACCES;
3336 	}
3337 
3338 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3339 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3340 			map->value_size, off, size);
3341 		return -EACCES;
3342 	}
3343 
3344 	return 0;
3345 }
3346 
3347 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3348 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3349 			      int off, int size, u32 mem_size,
3350 			      bool zero_size_allowed)
3351 {
3352 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3353 	struct bpf_reg_state *reg;
3354 
3355 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3356 		return 0;
3357 
3358 	reg = &cur_regs(env)[regno];
3359 	switch (reg->type) {
3360 	case PTR_TO_MAP_KEY:
3361 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3362 			mem_size, off, size);
3363 		break;
3364 	case PTR_TO_MAP_VALUE:
3365 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3366 			mem_size, off, size);
3367 		break;
3368 	case PTR_TO_PACKET:
3369 	case PTR_TO_PACKET_META:
3370 	case PTR_TO_PACKET_END:
3371 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3372 			off, size, regno, reg->id, off, mem_size);
3373 		break;
3374 	case PTR_TO_MEM:
3375 	default:
3376 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3377 			mem_size, off, size);
3378 	}
3379 
3380 	return -EACCES;
3381 }
3382 
3383 /* check read/write into a memory region with possible variable offset */
3384 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3385 				   int off, int size, u32 mem_size,
3386 				   bool zero_size_allowed)
3387 {
3388 	struct bpf_verifier_state *vstate = env->cur_state;
3389 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3390 	struct bpf_reg_state *reg = &state->regs[regno];
3391 	int err;
3392 
3393 	/* We may have adjusted the register pointing to memory region, so we
3394 	 * need to try adding each of min_value and max_value to off
3395 	 * to make sure our theoretical access will be safe.
3396 	 */
3397 	if (env->log.level & BPF_LOG_LEVEL)
3398 		print_verifier_state(env, state);
3399 
3400 	/* The minimum value is only important with signed
3401 	 * comparisons where we can't assume the floor of a
3402 	 * value is 0.  If we are using signed variables for our
3403 	 * index'es we need to make sure that whatever we use
3404 	 * will have a set floor within our range.
3405 	 */
3406 	if (reg->smin_value < 0 &&
3407 	    (reg->smin_value == S64_MIN ||
3408 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3409 	      reg->smin_value + off < 0)) {
3410 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3411 			regno);
3412 		return -EACCES;
3413 	}
3414 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3415 				 mem_size, zero_size_allowed);
3416 	if (err) {
3417 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3418 			regno);
3419 		return err;
3420 	}
3421 
3422 	/* If we haven't set a max value then we need to bail since we can't be
3423 	 * sure we won't do bad things.
3424 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3425 	 */
3426 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3427 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3428 			regno);
3429 		return -EACCES;
3430 	}
3431 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3432 				 mem_size, zero_size_allowed);
3433 	if (err) {
3434 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3435 			regno);
3436 		return err;
3437 	}
3438 
3439 	return 0;
3440 }
3441 
3442 /* check read/write into a map element with possible variable offset */
3443 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3444 			    int off, int size, bool zero_size_allowed)
3445 {
3446 	struct bpf_verifier_state *vstate = env->cur_state;
3447 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3448 	struct bpf_reg_state *reg = &state->regs[regno];
3449 	struct bpf_map *map = reg->map_ptr;
3450 	int err;
3451 
3452 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3453 				      zero_size_allowed);
3454 	if (err)
3455 		return err;
3456 
3457 	if (map_value_has_spin_lock(map)) {
3458 		u32 lock = map->spin_lock_off;
3459 
3460 		/* if any part of struct bpf_spin_lock can be touched by
3461 		 * load/store reject this program.
3462 		 * To check that [x1, x2) overlaps with [y1, y2)
3463 		 * it is sufficient to check x1 < y2 && y1 < x2.
3464 		 */
3465 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3466 		     lock < reg->umax_value + off + size) {
3467 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3468 			return -EACCES;
3469 		}
3470 	}
3471 	if (map_value_has_timer(map)) {
3472 		u32 t = map->timer_off;
3473 
3474 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3475 		     t < reg->umax_value + off + size) {
3476 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3477 			return -EACCES;
3478 		}
3479 	}
3480 	return err;
3481 }
3482 
3483 #define MAX_PACKET_OFF 0xffff
3484 
3485 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3486 {
3487 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3488 }
3489 
3490 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3491 				       const struct bpf_call_arg_meta *meta,
3492 				       enum bpf_access_type t)
3493 {
3494 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3495 
3496 	switch (prog_type) {
3497 	/* Program types only with direct read access go here! */
3498 	case BPF_PROG_TYPE_LWT_IN:
3499 	case BPF_PROG_TYPE_LWT_OUT:
3500 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3501 	case BPF_PROG_TYPE_SK_REUSEPORT:
3502 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3503 	case BPF_PROG_TYPE_CGROUP_SKB:
3504 		if (t == BPF_WRITE)
3505 			return false;
3506 		fallthrough;
3507 
3508 	/* Program types with direct read + write access go here! */
3509 	case BPF_PROG_TYPE_SCHED_CLS:
3510 	case BPF_PROG_TYPE_SCHED_ACT:
3511 	case BPF_PROG_TYPE_XDP:
3512 	case BPF_PROG_TYPE_LWT_XMIT:
3513 	case BPF_PROG_TYPE_SK_SKB:
3514 	case BPF_PROG_TYPE_SK_MSG:
3515 		if (meta)
3516 			return meta->pkt_access;
3517 
3518 		env->seen_direct_write = true;
3519 		return true;
3520 
3521 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3522 		if (t == BPF_WRITE)
3523 			env->seen_direct_write = true;
3524 
3525 		return true;
3526 
3527 	default:
3528 		return false;
3529 	}
3530 }
3531 
3532 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3533 			       int size, bool zero_size_allowed)
3534 {
3535 	struct bpf_reg_state *regs = cur_regs(env);
3536 	struct bpf_reg_state *reg = &regs[regno];
3537 	int err;
3538 
3539 	/* We may have added a variable offset to the packet pointer; but any
3540 	 * reg->range we have comes after that.  We are only checking the fixed
3541 	 * offset.
3542 	 */
3543 
3544 	/* We don't allow negative numbers, because we aren't tracking enough
3545 	 * detail to prove they're safe.
3546 	 */
3547 	if (reg->smin_value < 0) {
3548 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3549 			regno);
3550 		return -EACCES;
3551 	}
3552 
3553 	err = reg->range < 0 ? -EINVAL :
3554 	      __check_mem_access(env, regno, off, size, reg->range,
3555 				 zero_size_allowed);
3556 	if (err) {
3557 		verbose(env, "R%d offset is outside of the packet\n", regno);
3558 		return err;
3559 	}
3560 
3561 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3562 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3563 	 * otherwise find_good_pkt_pointers would have refused to set range info
3564 	 * that __check_mem_access would have rejected this pkt access.
3565 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3566 	 */
3567 	env->prog->aux->max_pkt_offset =
3568 		max_t(u32, env->prog->aux->max_pkt_offset,
3569 		      off + reg->umax_value + size - 1);
3570 
3571 	return err;
3572 }
3573 
3574 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3575 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3576 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3577 			    struct btf **btf, u32 *btf_id)
3578 {
3579 	struct bpf_insn_access_aux info = {
3580 		.reg_type = *reg_type,
3581 		.log = &env->log,
3582 	};
3583 
3584 	if (env->ops->is_valid_access &&
3585 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3586 		/* A non zero info.ctx_field_size indicates that this field is a
3587 		 * candidate for later verifier transformation to load the whole
3588 		 * field and then apply a mask when accessed with a narrower
3589 		 * access than actual ctx access size. A zero info.ctx_field_size
3590 		 * will only allow for whole field access and rejects any other
3591 		 * type of narrower access.
3592 		 */
3593 		*reg_type = info.reg_type;
3594 
3595 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3596 			*btf = info.btf;
3597 			*btf_id = info.btf_id;
3598 		} else {
3599 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3600 		}
3601 		/* remember the offset of last byte accessed in ctx */
3602 		if (env->prog->aux->max_ctx_offset < off + size)
3603 			env->prog->aux->max_ctx_offset = off + size;
3604 		return 0;
3605 	}
3606 
3607 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3608 	return -EACCES;
3609 }
3610 
3611 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3612 				  int size)
3613 {
3614 	if (size < 0 || off < 0 ||
3615 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3616 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3617 			off, size);
3618 		return -EACCES;
3619 	}
3620 	return 0;
3621 }
3622 
3623 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3624 			     u32 regno, int off, int size,
3625 			     enum bpf_access_type t)
3626 {
3627 	struct bpf_reg_state *regs = cur_regs(env);
3628 	struct bpf_reg_state *reg = &regs[regno];
3629 	struct bpf_insn_access_aux info = {};
3630 	bool valid;
3631 
3632 	if (reg->smin_value < 0) {
3633 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3634 			regno);
3635 		return -EACCES;
3636 	}
3637 
3638 	switch (reg->type) {
3639 	case PTR_TO_SOCK_COMMON:
3640 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3641 		break;
3642 	case PTR_TO_SOCKET:
3643 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3644 		break;
3645 	case PTR_TO_TCP_SOCK:
3646 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3647 		break;
3648 	case PTR_TO_XDP_SOCK:
3649 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3650 		break;
3651 	default:
3652 		valid = false;
3653 	}
3654 
3655 
3656 	if (valid) {
3657 		env->insn_aux_data[insn_idx].ctx_field_size =
3658 			info.ctx_field_size;
3659 		return 0;
3660 	}
3661 
3662 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3663 		regno, reg_type_str[reg->type], off, size);
3664 
3665 	return -EACCES;
3666 }
3667 
3668 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3669 {
3670 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3671 }
3672 
3673 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3674 {
3675 	const struct bpf_reg_state *reg = reg_state(env, regno);
3676 
3677 	return reg->type == PTR_TO_CTX;
3678 }
3679 
3680 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3681 {
3682 	const struct bpf_reg_state *reg = reg_state(env, regno);
3683 
3684 	return type_is_sk_pointer(reg->type);
3685 }
3686 
3687 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3688 {
3689 	const struct bpf_reg_state *reg = reg_state(env, regno);
3690 
3691 	return type_is_pkt_pointer(reg->type);
3692 }
3693 
3694 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3695 {
3696 	const struct bpf_reg_state *reg = reg_state(env, regno);
3697 
3698 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3699 	return reg->type == PTR_TO_FLOW_KEYS;
3700 }
3701 
3702 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3703 				   const struct bpf_reg_state *reg,
3704 				   int off, int size, bool strict)
3705 {
3706 	struct tnum reg_off;
3707 	int ip_align;
3708 
3709 	/* Byte size accesses are always allowed. */
3710 	if (!strict || size == 1)
3711 		return 0;
3712 
3713 	/* For platforms that do not have a Kconfig enabling
3714 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3715 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3716 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3717 	 * to this code only in strict mode where we want to emulate
3718 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3719 	 * unconditional IP align value of '2'.
3720 	 */
3721 	ip_align = 2;
3722 
3723 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3724 	if (!tnum_is_aligned(reg_off, size)) {
3725 		char tn_buf[48];
3726 
3727 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3728 		verbose(env,
3729 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3730 			ip_align, tn_buf, reg->off, off, size);
3731 		return -EACCES;
3732 	}
3733 
3734 	return 0;
3735 }
3736 
3737 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3738 				       const struct bpf_reg_state *reg,
3739 				       const char *pointer_desc,
3740 				       int off, int size, bool strict)
3741 {
3742 	struct tnum reg_off;
3743 
3744 	/* Byte size accesses are always allowed. */
3745 	if (!strict || size == 1)
3746 		return 0;
3747 
3748 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3749 	if (!tnum_is_aligned(reg_off, size)) {
3750 		char tn_buf[48];
3751 
3752 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3753 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3754 			pointer_desc, tn_buf, reg->off, off, size);
3755 		return -EACCES;
3756 	}
3757 
3758 	return 0;
3759 }
3760 
3761 static int check_ptr_alignment(struct bpf_verifier_env *env,
3762 			       const struct bpf_reg_state *reg, int off,
3763 			       int size, bool strict_alignment_once)
3764 {
3765 	bool strict = env->strict_alignment || strict_alignment_once;
3766 	const char *pointer_desc = "";
3767 
3768 	switch (reg->type) {
3769 	case PTR_TO_PACKET:
3770 	case PTR_TO_PACKET_META:
3771 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3772 		 * right in front, treat it the very same way.
3773 		 */
3774 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3775 	case PTR_TO_FLOW_KEYS:
3776 		pointer_desc = "flow keys ";
3777 		break;
3778 	case PTR_TO_MAP_KEY:
3779 		pointer_desc = "key ";
3780 		break;
3781 	case PTR_TO_MAP_VALUE:
3782 		pointer_desc = "value ";
3783 		break;
3784 	case PTR_TO_CTX:
3785 		pointer_desc = "context ";
3786 		break;
3787 	case PTR_TO_STACK:
3788 		pointer_desc = "stack ";
3789 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3790 		 * and check_stack_read_fixed_off() relies on stack accesses being
3791 		 * aligned.
3792 		 */
3793 		strict = true;
3794 		break;
3795 	case PTR_TO_SOCKET:
3796 		pointer_desc = "sock ";
3797 		break;
3798 	case PTR_TO_SOCK_COMMON:
3799 		pointer_desc = "sock_common ";
3800 		break;
3801 	case PTR_TO_TCP_SOCK:
3802 		pointer_desc = "tcp_sock ";
3803 		break;
3804 	case PTR_TO_XDP_SOCK:
3805 		pointer_desc = "xdp_sock ";
3806 		break;
3807 	default:
3808 		break;
3809 	}
3810 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3811 					   strict);
3812 }
3813 
3814 static int update_stack_depth(struct bpf_verifier_env *env,
3815 			      const struct bpf_func_state *func,
3816 			      int off)
3817 {
3818 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3819 
3820 	if (stack >= -off)
3821 		return 0;
3822 
3823 	/* update known max for given subprogram */
3824 	env->subprog_info[func->subprogno].stack_depth = -off;
3825 	return 0;
3826 }
3827 
3828 /* starting from main bpf function walk all instructions of the function
3829  * and recursively walk all callees that given function can call.
3830  * Ignore jump and exit insns.
3831  * Since recursion is prevented by check_cfg() this algorithm
3832  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3833  */
3834 static int check_max_stack_depth(struct bpf_verifier_env *env)
3835 {
3836 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3837 	struct bpf_subprog_info *subprog = env->subprog_info;
3838 	struct bpf_insn *insn = env->prog->insnsi;
3839 	bool tail_call_reachable = false;
3840 	int ret_insn[MAX_CALL_FRAMES];
3841 	int ret_prog[MAX_CALL_FRAMES];
3842 	int j;
3843 
3844 process_func:
3845 	/* protect against potential stack overflow that might happen when
3846 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3847 	 * depth for such case down to 256 so that the worst case scenario
3848 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3849 	 * 8k).
3850 	 *
3851 	 * To get the idea what might happen, see an example:
3852 	 * func1 -> sub rsp, 128
3853 	 *  subfunc1 -> sub rsp, 256
3854 	 *  tailcall1 -> add rsp, 256
3855 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3856 	 *   subfunc2 -> sub rsp, 64
3857 	 *   subfunc22 -> sub rsp, 128
3858 	 *   tailcall2 -> add rsp, 128
3859 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3860 	 *
3861 	 * tailcall will unwind the current stack frame but it will not get rid
3862 	 * of caller's stack as shown on the example above.
3863 	 */
3864 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3865 		verbose(env,
3866 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3867 			depth);
3868 		return -EACCES;
3869 	}
3870 	/* round up to 32-bytes, since this is granularity
3871 	 * of interpreter stack size
3872 	 */
3873 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3874 	if (depth > MAX_BPF_STACK) {
3875 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3876 			frame + 1, depth);
3877 		return -EACCES;
3878 	}
3879 continue_func:
3880 	subprog_end = subprog[idx + 1].start;
3881 	for (; i < subprog_end; i++) {
3882 		int next_insn;
3883 
3884 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3885 			continue;
3886 		/* remember insn and function to return to */
3887 		ret_insn[frame] = i + 1;
3888 		ret_prog[frame] = idx;
3889 
3890 		/* find the callee */
3891 		next_insn = i + insn[i].imm + 1;
3892 		idx = find_subprog(env, next_insn);
3893 		if (idx < 0) {
3894 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3895 				  next_insn);
3896 			return -EFAULT;
3897 		}
3898 		if (subprog[idx].is_async_cb) {
3899 			if (subprog[idx].has_tail_call) {
3900 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3901 				return -EFAULT;
3902 			}
3903 			 /* async callbacks don't increase bpf prog stack size */
3904 			continue;
3905 		}
3906 		i = next_insn;
3907 
3908 		if (subprog[idx].has_tail_call)
3909 			tail_call_reachable = true;
3910 
3911 		frame++;
3912 		if (frame >= MAX_CALL_FRAMES) {
3913 			verbose(env, "the call stack of %d frames is too deep !\n",
3914 				frame);
3915 			return -E2BIG;
3916 		}
3917 		goto process_func;
3918 	}
3919 	/* if tail call got detected across bpf2bpf calls then mark each of the
3920 	 * currently present subprog frames as tail call reachable subprogs;
3921 	 * this info will be utilized by JIT so that we will be preserving the
3922 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3923 	 */
3924 	if (tail_call_reachable)
3925 		for (j = 0; j < frame; j++)
3926 			subprog[ret_prog[j]].tail_call_reachable = true;
3927 	if (subprog[0].tail_call_reachable)
3928 		env->prog->aux->tail_call_reachable = true;
3929 
3930 	/* end of for() loop means the last insn of the 'subprog'
3931 	 * was reached. Doesn't matter whether it was JA or EXIT
3932 	 */
3933 	if (frame == 0)
3934 		return 0;
3935 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3936 	frame--;
3937 	i = ret_insn[frame];
3938 	idx = ret_prog[frame];
3939 	goto continue_func;
3940 }
3941 
3942 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3943 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3944 				  const struct bpf_insn *insn, int idx)
3945 {
3946 	int start = idx + insn->imm + 1, subprog;
3947 
3948 	subprog = find_subprog(env, start);
3949 	if (subprog < 0) {
3950 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3951 			  start);
3952 		return -EFAULT;
3953 	}
3954 	return env->subprog_info[subprog].stack_depth;
3955 }
3956 #endif
3957 
3958 int check_ctx_reg(struct bpf_verifier_env *env,
3959 		  const struct bpf_reg_state *reg, int regno)
3960 {
3961 	/* Access to ctx or passing it to a helper is only allowed in
3962 	 * its original, unmodified form.
3963 	 */
3964 
3965 	if (reg->off) {
3966 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3967 			regno, reg->off);
3968 		return -EACCES;
3969 	}
3970 
3971 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3972 		char tn_buf[48];
3973 
3974 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3975 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3976 		return -EACCES;
3977 	}
3978 
3979 	return 0;
3980 }
3981 
3982 static int __check_buffer_access(struct bpf_verifier_env *env,
3983 				 const char *buf_info,
3984 				 const struct bpf_reg_state *reg,
3985 				 int regno, int off, int size)
3986 {
3987 	if (off < 0) {
3988 		verbose(env,
3989 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3990 			regno, buf_info, off, size);
3991 		return -EACCES;
3992 	}
3993 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3994 		char tn_buf[48];
3995 
3996 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3997 		verbose(env,
3998 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3999 			regno, off, tn_buf);
4000 		return -EACCES;
4001 	}
4002 
4003 	return 0;
4004 }
4005 
4006 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4007 				  const struct bpf_reg_state *reg,
4008 				  int regno, int off, int size)
4009 {
4010 	int err;
4011 
4012 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4013 	if (err)
4014 		return err;
4015 
4016 	if (off + size > env->prog->aux->max_tp_access)
4017 		env->prog->aux->max_tp_access = off + size;
4018 
4019 	return 0;
4020 }
4021 
4022 static int check_buffer_access(struct bpf_verifier_env *env,
4023 			       const struct bpf_reg_state *reg,
4024 			       int regno, int off, int size,
4025 			       bool zero_size_allowed,
4026 			       const char *buf_info,
4027 			       u32 *max_access)
4028 {
4029 	int err;
4030 
4031 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4032 	if (err)
4033 		return err;
4034 
4035 	if (off + size > *max_access)
4036 		*max_access = off + size;
4037 
4038 	return 0;
4039 }
4040 
4041 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4042 static void zext_32_to_64(struct bpf_reg_state *reg)
4043 {
4044 	reg->var_off = tnum_subreg(reg->var_off);
4045 	__reg_assign_32_into_64(reg);
4046 }
4047 
4048 /* truncate register to smaller size (in bytes)
4049  * must be called with size < BPF_REG_SIZE
4050  */
4051 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4052 {
4053 	u64 mask;
4054 
4055 	/* clear high bits in bit representation */
4056 	reg->var_off = tnum_cast(reg->var_off, size);
4057 
4058 	/* fix arithmetic bounds */
4059 	mask = ((u64)1 << (size * 8)) - 1;
4060 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4061 		reg->umin_value &= mask;
4062 		reg->umax_value &= mask;
4063 	} else {
4064 		reg->umin_value = 0;
4065 		reg->umax_value = mask;
4066 	}
4067 	reg->smin_value = reg->umin_value;
4068 	reg->smax_value = reg->umax_value;
4069 
4070 	/* If size is smaller than 32bit register the 32bit register
4071 	 * values are also truncated so we push 64-bit bounds into
4072 	 * 32-bit bounds. Above were truncated < 32-bits already.
4073 	 */
4074 	if (size >= 4)
4075 		return;
4076 	__reg_combine_64_into_32(reg);
4077 }
4078 
4079 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4080 {
4081 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
4082 }
4083 
4084 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4085 {
4086 	void *ptr;
4087 	u64 addr;
4088 	int err;
4089 
4090 	err = map->ops->map_direct_value_addr(map, &addr, off);
4091 	if (err)
4092 		return err;
4093 	ptr = (void *)(long)addr + off;
4094 
4095 	switch (size) {
4096 	case sizeof(u8):
4097 		*val = (u64)*(u8 *)ptr;
4098 		break;
4099 	case sizeof(u16):
4100 		*val = (u64)*(u16 *)ptr;
4101 		break;
4102 	case sizeof(u32):
4103 		*val = (u64)*(u32 *)ptr;
4104 		break;
4105 	case sizeof(u64):
4106 		*val = *(u64 *)ptr;
4107 		break;
4108 	default:
4109 		return -EINVAL;
4110 	}
4111 	return 0;
4112 }
4113 
4114 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4115 				   struct bpf_reg_state *regs,
4116 				   int regno, int off, int size,
4117 				   enum bpf_access_type atype,
4118 				   int value_regno)
4119 {
4120 	struct bpf_reg_state *reg = regs + regno;
4121 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4122 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4123 	u32 btf_id;
4124 	int ret;
4125 
4126 	if (off < 0) {
4127 		verbose(env,
4128 			"R%d is ptr_%s invalid negative access: off=%d\n",
4129 			regno, tname, off);
4130 		return -EACCES;
4131 	}
4132 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4133 		char tn_buf[48];
4134 
4135 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4136 		verbose(env,
4137 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4138 			regno, tname, off, tn_buf);
4139 		return -EACCES;
4140 	}
4141 
4142 	if (env->ops->btf_struct_access) {
4143 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4144 						  off, size, atype, &btf_id);
4145 	} else {
4146 		if (atype != BPF_READ) {
4147 			verbose(env, "only read is supported\n");
4148 			return -EACCES;
4149 		}
4150 
4151 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4152 					atype, &btf_id);
4153 	}
4154 
4155 	if (ret < 0)
4156 		return ret;
4157 
4158 	if (atype == BPF_READ && value_regno >= 0)
4159 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4160 
4161 	return 0;
4162 }
4163 
4164 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4165 				   struct bpf_reg_state *regs,
4166 				   int regno, int off, int size,
4167 				   enum bpf_access_type atype,
4168 				   int value_regno)
4169 {
4170 	struct bpf_reg_state *reg = regs + regno;
4171 	struct bpf_map *map = reg->map_ptr;
4172 	const struct btf_type *t;
4173 	const char *tname;
4174 	u32 btf_id;
4175 	int ret;
4176 
4177 	if (!btf_vmlinux) {
4178 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4179 		return -ENOTSUPP;
4180 	}
4181 
4182 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4183 		verbose(env, "map_ptr access not supported for map type %d\n",
4184 			map->map_type);
4185 		return -ENOTSUPP;
4186 	}
4187 
4188 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4189 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4190 
4191 	if (!env->allow_ptr_to_map_access) {
4192 		verbose(env,
4193 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4194 			tname);
4195 		return -EPERM;
4196 	}
4197 
4198 	if (off < 0) {
4199 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4200 			regno, tname, off);
4201 		return -EACCES;
4202 	}
4203 
4204 	if (atype != BPF_READ) {
4205 		verbose(env, "only read from %s is supported\n", tname);
4206 		return -EACCES;
4207 	}
4208 
4209 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4210 	if (ret < 0)
4211 		return ret;
4212 
4213 	if (value_regno >= 0)
4214 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4215 
4216 	return 0;
4217 }
4218 
4219 /* Check that the stack access at the given offset is within bounds. The
4220  * maximum valid offset is -1.
4221  *
4222  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4223  * -state->allocated_stack for reads.
4224  */
4225 static int check_stack_slot_within_bounds(int off,
4226 					  struct bpf_func_state *state,
4227 					  enum bpf_access_type t)
4228 {
4229 	int min_valid_off;
4230 
4231 	if (t == BPF_WRITE)
4232 		min_valid_off = -MAX_BPF_STACK;
4233 	else
4234 		min_valid_off = -state->allocated_stack;
4235 
4236 	if (off < min_valid_off || off > -1)
4237 		return -EACCES;
4238 	return 0;
4239 }
4240 
4241 /* Check that the stack access at 'regno + off' falls within the maximum stack
4242  * bounds.
4243  *
4244  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4245  */
4246 static int check_stack_access_within_bounds(
4247 		struct bpf_verifier_env *env,
4248 		int regno, int off, int access_size,
4249 		enum stack_access_src src, enum bpf_access_type type)
4250 {
4251 	struct bpf_reg_state *regs = cur_regs(env);
4252 	struct bpf_reg_state *reg = regs + regno;
4253 	struct bpf_func_state *state = func(env, reg);
4254 	int min_off, max_off;
4255 	int err;
4256 	char *err_extra;
4257 
4258 	if (src == ACCESS_HELPER)
4259 		/* We don't know if helpers are reading or writing (or both). */
4260 		err_extra = " indirect access to";
4261 	else if (type == BPF_READ)
4262 		err_extra = " read from";
4263 	else
4264 		err_extra = " write to";
4265 
4266 	if (tnum_is_const(reg->var_off)) {
4267 		min_off = reg->var_off.value + off;
4268 		if (access_size > 0)
4269 			max_off = min_off + access_size - 1;
4270 		else
4271 			max_off = min_off;
4272 	} else {
4273 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4274 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4275 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4276 				err_extra, regno);
4277 			return -EACCES;
4278 		}
4279 		min_off = reg->smin_value + off;
4280 		if (access_size > 0)
4281 			max_off = reg->smax_value + off + access_size - 1;
4282 		else
4283 			max_off = min_off;
4284 	}
4285 
4286 	err = check_stack_slot_within_bounds(min_off, state, type);
4287 	if (!err)
4288 		err = check_stack_slot_within_bounds(max_off, state, type);
4289 
4290 	if (err) {
4291 		if (tnum_is_const(reg->var_off)) {
4292 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4293 				err_extra, regno, off, access_size);
4294 		} else {
4295 			char tn_buf[48];
4296 
4297 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4298 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4299 				err_extra, regno, tn_buf, access_size);
4300 		}
4301 	}
4302 	return err;
4303 }
4304 
4305 /* check whether memory at (regno + off) is accessible for t = (read | write)
4306  * if t==write, value_regno is a register which value is stored into memory
4307  * if t==read, value_regno is a register which will receive the value from memory
4308  * if t==write && value_regno==-1, some unknown value is stored into memory
4309  * if t==read && value_regno==-1, don't care what we read from memory
4310  */
4311 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4312 			    int off, int bpf_size, enum bpf_access_type t,
4313 			    int value_regno, bool strict_alignment_once)
4314 {
4315 	struct bpf_reg_state *regs = cur_regs(env);
4316 	struct bpf_reg_state *reg = regs + regno;
4317 	struct bpf_func_state *state;
4318 	int size, err = 0;
4319 
4320 	size = bpf_size_to_bytes(bpf_size);
4321 	if (size < 0)
4322 		return size;
4323 
4324 	/* alignment checks will add in reg->off themselves */
4325 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4326 	if (err)
4327 		return err;
4328 
4329 	/* for access checks, reg->off is just part of off */
4330 	off += reg->off;
4331 
4332 	if (reg->type == PTR_TO_MAP_KEY) {
4333 		if (t == BPF_WRITE) {
4334 			verbose(env, "write to change key R%d not allowed\n", regno);
4335 			return -EACCES;
4336 		}
4337 
4338 		err = check_mem_region_access(env, regno, off, size,
4339 					      reg->map_ptr->key_size, false);
4340 		if (err)
4341 			return err;
4342 		if (value_regno >= 0)
4343 			mark_reg_unknown(env, regs, value_regno);
4344 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4345 		if (t == BPF_WRITE && value_regno >= 0 &&
4346 		    is_pointer_value(env, value_regno)) {
4347 			verbose(env, "R%d leaks addr into map\n", value_regno);
4348 			return -EACCES;
4349 		}
4350 		err = check_map_access_type(env, regno, off, size, t);
4351 		if (err)
4352 			return err;
4353 		err = check_map_access(env, regno, off, size, false);
4354 		if (!err && t == BPF_READ && value_regno >= 0) {
4355 			struct bpf_map *map = reg->map_ptr;
4356 
4357 			/* if map is read-only, track its contents as scalars */
4358 			if (tnum_is_const(reg->var_off) &&
4359 			    bpf_map_is_rdonly(map) &&
4360 			    map->ops->map_direct_value_addr) {
4361 				int map_off = off + reg->var_off.value;
4362 				u64 val = 0;
4363 
4364 				err = bpf_map_direct_read(map, map_off, size,
4365 							  &val);
4366 				if (err)
4367 					return err;
4368 
4369 				regs[value_regno].type = SCALAR_VALUE;
4370 				__mark_reg_known(&regs[value_regno], val);
4371 			} else {
4372 				mark_reg_unknown(env, regs, value_regno);
4373 			}
4374 		}
4375 	} else if (reg->type == PTR_TO_MEM) {
4376 		if (t == BPF_WRITE && value_regno >= 0 &&
4377 		    is_pointer_value(env, value_regno)) {
4378 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4379 			return -EACCES;
4380 		}
4381 		err = check_mem_region_access(env, regno, off, size,
4382 					      reg->mem_size, false);
4383 		if (!err && t == BPF_READ && value_regno >= 0)
4384 			mark_reg_unknown(env, regs, value_regno);
4385 	} else if (reg->type == PTR_TO_CTX) {
4386 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4387 		struct btf *btf = NULL;
4388 		u32 btf_id = 0;
4389 
4390 		if (t == BPF_WRITE && value_regno >= 0 &&
4391 		    is_pointer_value(env, value_regno)) {
4392 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4393 			return -EACCES;
4394 		}
4395 
4396 		err = check_ctx_reg(env, reg, regno);
4397 		if (err < 0)
4398 			return err;
4399 
4400 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4401 		if (err)
4402 			verbose_linfo(env, insn_idx, "; ");
4403 		if (!err && t == BPF_READ && value_regno >= 0) {
4404 			/* ctx access returns either a scalar, or a
4405 			 * PTR_TO_PACKET[_META,_END]. In the latter
4406 			 * case, we know the offset is zero.
4407 			 */
4408 			if (reg_type == SCALAR_VALUE) {
4409 				mark_reg_unknown(env, regs, value_regno);
4410 			} else {
4411 				mark_reg_known_zero(env, regs,
4412 						    value_regno);
4413 				if (reg_type_may_be_null(reg_type))
4414 					regs[value_regno].id = ++env->id_gen;
4415 				/* A load of ctx field could have different
4416 				 * actual load size with the one encoded in the
4417 				 * insn. When the dst is PTR, it is for sure not
4418 				 * a sub-register.
4419 				 */
4420 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4421 				if (reg_type == PTR_TO_BTF_ID ||
4422 				    reg_type == PTR_TO_BTF_ID_OR_NULL) {
4423 					regs[value_regno].btf = btf;
4424 					regs[value_regno].btf_id = btf_id;
4425 				}
4426 			}
4427 			regs[value_regno].type = reg_type;
4428 		}
4429 
4430 	} else if (reg->type == PTR_TO_STACK) {
4431 		/* Basic bounds checks. */
4432 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4433 		if (err)
4434 			return err;
4435 
4436 		state = func(env, reg);
4437 		err = update_stack_depth(env, state, off);
4438 		if (err)
4439 			return err;
4440 
4441 		if (t == BPF_READ)
4442 			err = check_stack_read(env, regno, off, size,
4443 					       value_regno);
4444 		else
4445 			err = check_stack_write(env, regno, off, size,
4446 						value_regno, insn_idx);
4447 	} else if (reg_is_pkt_pointer(reg)) {
4448 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4449 			verbose(env, "cannot write into packet\n");
4450 			return -EACCES;
4451 		}
4452 		if (t == BPF_WRITE && value_regno >= 0 &&
4453 		    is_pointer_value(env, value_regno)) {
4454 			verbose(env, "R%d leaks addr into packet\n",
4455 				value_regno);
4456 			return -EACCES;
4457 		}
4458 		err = check_packet_access(env, regno, off, size, false);
4459 		if (!err && t == BPF_READ && value_regno >= 0)
4460 			mark_reg_unknown(env, regs, value_regno);
4461 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4462 		if (t == BPF_WRITE && value_regno >= 0 &&
4463 		    is_pointer_value(env, value_regno)) {
4464 			verbose(env, "R%d leaks addr into flow keys\n",
4465 				value_regno);
4466 			return -EACCES;
4467 		}
4468 
4469 		err = check_flow_keys_access(env, off, size);
4470 		if (!err && t == BPF_READ && value_regno >= 0)
4471 			mark_reg_unknown(env, regs, value_regno);
4472 	} else if (type_is_sk_pointer(reg->type)) {
4473 		if (t == BPF_WRITE) {
4474 			verbose(env, "R%d cannot write into %s\n",
4475 				regno, reg_type_str[reg->type]);
4476 			return -EACCES;
4477 		}
4478 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4479 		if (!err && value_regno >= 0)
4480 			mark_reg_unknown(env, regs, value_regno);
4481 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4482 		err = check_tp_buffer_access(env, reg, regno, off, size);
4483 		if (!err && t == BPF_READ && value_regno >= 0)
4484 			mark_reg_unknown(env, regs, value_regno);
4485 	} else if (reg->type == PTR_TO_BTF_ID) {
4486 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4487 					      value_regno);
4488 	} else if (reg->type == CONST_PTR_TO_MAP) {
4489 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4490 					      value_regno);
4491 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
4492 		if (t == BPF_WRITE) {
4493 			verbose(env, "R%d cannot write into %s\n",
4494 				regno, reg_type_str[reg->type]);
4495 			return -EACCES;
4496 		}
4497 		err = check_buffer_access(env, reg, regno, off, size, false,
4498 					  "rdonly",
4499 					  &env->prog->aux->max_rdonly_access);
4500 		if (!err && value_regno >= 0)
4501 			mark_reg_unknown(env, regs, value_regno);
4502 	} else if (reg->type == PTR_TO_RDWR_BUF) {
4503 		err = check_buffer_access(env, reg, regno, off, size, false,
4504 					  "rdwr",
4505 					  &env->prog->aux->max_rdwr_access);
4506 		if (!err && t == BPF_READ && value_regno >= 0)
4507 			mark_reg_unknown(env, regs, value_regno);
4508 	} else {
4509 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4510 			reg_type_str[reg->type]);
4511 		return -EACCES;
4512 	}
4513 
4514 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4515 	    regs[value_regno].type == SCALAR_VALUE) {
4516 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4517 		coerce_reg_to_size(&regs[value_regno], size);
4518 	}
4519 	return err;
4520 }
4521 
4522 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4523 {
4524 	int load_reg;
4525 	int err;
4526 
4527 	switch (insn->imm) {
4528 	case BPF_ADD:
4529 	case BPF_ADD | BPF_FETCH:
4530 	case BPF_AND:
4531 	case BPF_AND | BPF_FETCH:
4532 	case BPF_OR:
4533 	case BPF_OR | BPF_FETCH:
4534 	case BPF_XOR:
4535 	case BPF_XOR | BPF_FETCH:
4536 	case BPF_XCHG:
4537 	case BPF_CMPXCHG:
4538 		break;
4539 	default:
4540 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4541 		return -EINVAL;
4542 	}
4543 
4544 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4545 		verbose(env, "invalid atomic operand size\n");
4546 		return -EINVAL;
4547 	}
4548 
4549 	/* check src1 operand */
4550 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4551 	if (err)
4552 		return err;
4553 
4554 	/* check src2 operand */
4555 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4556 	if (err)
4557 		return err;
4558 
4559 	if (insn->imm == BPF_CMPXCHG) {
4560 		/* Check comparison of R0 with memory location */
4561 		err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4562 		if (err)
4563 			return err;
4564 	}
4565 
4566 	if (is_pointer_value(env, insn->src_reg)) {
4567 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4568 		return -EACCES;
4569 	}
4570 
4571 	if (is_ctx_reg(env, insn->dst_reg) ||
4572 	    is_pkt_reg(env, insn->dst_reg) ||
4573 	    is_flow_key_reg(env, insn->dst_reg) ||
4574 	    is_sk_reg(env, insn->dst_reg)) {
4575 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4576 			insn->dst_reg,
4577 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
4578 		return -EACCES;
4579 	}
4580 
4581 	if (insn->imm & BPF_FETCH) {
4582 		if (insn->imm == BPF_CMPXCHG)
4583 			load_reg = BPF_REG_0;
4584 		else
4585 			load_reg = insn->src_reg;
4586 
4587 		/* check and record load of old value */
4588 		err = check_reg_arg(env, load_reg, DST_OP);
4589 		if (err)
4590 			return err;
4591 	} else {
4592 		/* This instruction accesses a memory location but doesn't
4593 		 * actually load it into a register.
4594 		 */
4595 		load_reg = -1;
4596 	}
4597 
4598 	/* check whether we can read the memory */
4599 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4600 			       BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4601 	if (err)
4602 		return err;
4603 
4604 	/* check whether we can write into the same memory */
4605 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4606 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4607 	if (err)
4608 		return err;
4609 
4610 	return 0;
4611 }
4612 
4613 /* When register 'regno' is used to read the stack (either directly or through
4614  * a helper function) make sure that it's within stack boundary and, depending
4615  * on the access type, that all elements of the stack are initialized.
4616  *
4617  * 'off' includes 'regno->off', but not its dynamic part (if any).
4618  *
4619  * All registers that have been spilled on the stack in the slots within the
4620  * read offsets are marked as read.
4621  */
4622 static int check_stack_range_initialized(
4623 		struct bpf_verifier_env *env, int regno, int off,
4624 		int access_size, bool zero_size_allowed,
4625 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4626 {
4627 	struct bpf_reg_state *reg = reg_state(env, regno);
4628 	struct bpf_func_state *state = func(env, reg);
4629 	int err, min_off, max_off, i, j, slot, spi;
4630 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4631 	enum bpf_access_type bounds_check_type;
4632 	/* Some accesses can write anything into the stack, others are
4633 	 * read-only.
4634 	 */
4635 	bool clobber = false;
4636 
4637 	if (access_size == 0 && !zero_size_allowed) {
4638 		verbose(env, "invalid zero-sized read\n");
4639 		return -EACCES;
4640 	}
4641 
4642 	if (type == ACCESS_HELPER) {
4643 		/* The bounds checks for writes are more permissive than for
4644 		 * reads. However, if raw_mode is not set, we'll do extra
4645 		 * checks below.
4646 		 */
4647 		bounds_check_type = BPF_WRITE;
4648 		clobber = true;
4649 	} else {
4650 		bounds_check_type = BPF_READ;
4651 	}
4652 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4653 					       type, bounds_check_type);
4654 	if (err)
4655 		return err;
4656 
4657 
4658 	if (tnum_is_const(reg->var_off)) {
4659 		min_off = max_off = reg->var_off.value + off;
4660 	} else {
4661 		/* Variable offset is prohibited for unprivileged mode for
4662 		 * simplicity since it requires corresponding support in
4663 		 * Spectre masking for stack ALU.
4664 		 * See also retrieve_ptr_limit().
4665 		 */
4666 		if (!env->bypass_spec_v1) {
4667 			char tn_buf[48];
4668 
4669 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4670 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4671 				regno, err_extra, tn_buf);
4672 			return -EACCES;
4673 		}
4674 		/* Only initialized buffer on stack is allowed to be accessed
4675 		 * with variable offset. With uninitialized buffer it's hard to
4676 		 * guarantee that whole memory is marked as initialized on
4677 		 * helper return since specific bounds are unknown what may
4678 		 * cause uninitialized stack leaking.
4679 		 */
4680 		if (meta && meta->raw_mode)
4681 			meta = NULL;
4682 
4683 		min_off = reg->smin_value + off;
4684 		max_off = reg->smax_value + off;
4685 	}
4686 
4687 	if (meta && meta->raw_mode) {
4688 		meta->access_size = access_size;
4689 		meta->regno = regno;
4690 		return 0;
4691 	}
4692 
4693 	for (i = min_off; i < max_off + access_size; i++) {
4694 		u8 *stype;
4695 
4696 		slot = -i - 1;
4697 		spi = slot / BPF_REG_SIZE;
4698 		if (state->allocated_stack <= slot)
4699 			goto err;
4700 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4701 		if (*stype == STACK_MISC)
4702 			goto mark;
4703 		if (*stype == STACK_ZERO) {
4704 			if (clobber) {
4705 				/* helper can write anything into the stack */
4706 				*stype = STACK_MISC;
4707 			}
4708 			goto mark;
4709 		}
4710 
4711 		if (is_spilled_reg(&state->stack[spi]) &&
4712 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4713 			goto mark;
4714 
4715 		if (is_spilled_reg(&state->stack[spi]) &&
4716 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4717 		     env->allow_ptr_leaks)) {
4718 			if (clobber) {
4719 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4720 				for (j = 0; j < BPF_REG_SIZE; j++)
4721 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4722 			}
4723 			goto mark;
4724 		}
4725 
4726 err:
4727 		if (tnum_is_const(reg->var_off)) {
4728 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4729 				err_extra, regno, min_off, i - min_off, access_size);
4730 		} else {
4731 			char tn_buf[48];
4732 
4733 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4734 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4735 				err_extra, regno, tn_buf, i - min_off, access_size);
4736 		}
4737 		return -EACCES;
4738 mark:
4739 		/* reading any byte out of 8-byte 'spill_slot' will cause
4740 		 * the whole slot to be marked as 'read'
4741 		 */
4742 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4743 			      state->stack[spi].spilled_ptr.parent,
4744 			      REG_LIVE_READ64);
4745 	}
4746 	return update_stack_depth(env, state, min_off);
4747 }
4748 
4749 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4750 				   int access_size, bool zero_size_allowed,
4751 				   struct bpf_call_arg_meta *meta)
4752 {
4753 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4754 
4755 	switch (reg->type) {
4756 	case PTR_TO_PACKET:
4757 	case PTR_TO_PACKET_META:
4758 		return check_packet_access(env, regno, reg->off, access_size,
4759 					   zero_size_allowed);
4760 	case PTR_TO_MAP_KEY:
4761 		return check_mem_region_access(env, regno, reg->off, access_size,
4762 					       reg->map_ptr->key_size, false);
4763 	case PTR_TO_MAP_VALUE:
4764 		if (check_map_access_type(env, regno, reg->off, access_size,
4765 					  meta && meta->raw_mode ? BPF_WRITE :
4766 					  BPF_READ))
4767 			return -EACCES;
4768 		return check_map_access(env, regno, reg->off, access_size,
4769 					zero_size_allowed);
4770 	case PTR_TO_MEM:
4771 		return check_mem_region_access(env, regno, reg->off,
4772 					       access_size, reg->mem_size,
4773 					       zero_size_allowed);
4774 	case PTR_TO_RDONLY_BUF:
4775 		if (meta && meta->raw_mode)
4776 			return -EACCES;
4777 		return check_buffer_access(env, reg, regno, reg->off,
4778 					   access_size, zero_size_allowed,
4779 					   "rdonly",
4780 					   &env->prog->aux->max_rdonly_access);
4781 	case PTR_TO_RDWR_BUF:
4782 		return check_buffer_access(env, reg, regno, reg->off,
4783 					   access_size, zero_size_allowed,
4784 					   "rdwr",
4785 					   &env->prog->aux->max_rdwr_access);
4786 	case PTR_TO_STACK:
4787 		return check_stack_range_initialized(
4788 				env,
4789 				regno, reg->off, access_size,
4790 				zero_size_allowed, ACCESS_HELPER, meta);
4791 	default: /* scalar_value or invalid ptr */
4792 		/* Allow zero-byte read from NULL, regardless of pointer type */
4793 		if (zero_size_allowed && access_size == 0 &&
4794 		    register_is_null(reg))
4795 			return 0;
4796 
4797 		verbose(env, "R%d type=%s expected=%s\n", regno,
4798 			reg_type_str[reg->type],
4799 			reg_type_str[PTR_TO_STACK]);
4800 		return -EACCES;
4801 	}
4802 }
4803 
4804 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4805 		   u32 regno, u32 mem_size)
4806 {
4807 	if (register_is_null(reg))
4808 		return 0;
4809 
4810 	if (reg_type_may_be_null(reg->type)) {
4811 		/* Assuming that the register contains a value check if the memory
4812 		 * access is safe. Temporarily save and restore the register's state as
4813 		 * the conversion shouldn't be visible to a caller.
4814 		 */
4815 		const struct bpf_reg_state saved_reg = *reg;
4816 		int rv;
4817 
4818 		mark_ptr_not_null_reg(reg);
4819 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4820 		*reg = saved_reg;
4821 		return rv;
4822 	}
4823 
4824 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4825 }
4826 
4827 /* Implementation details:
4828  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4829  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4830  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4831  * value_or_null->value transition, since the verifier only cares about
4832  * the range of access to valid map value pointer and doesn't care about actual
4833  * address of the map element.
4834  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4835  * reg->id > 0 after value_or_null->value transition. By doing so
4836  * two bpf_map_lookups will be considered two different pointers that
4837  * point to different bpf_spin_locks.
4838  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4839  * dead-locks.
4840  * Since only one bpf_spin_lock is allowed the checks are simpler than
4841  * reg_is_refcounted() logic. The verifier needs to remember only
4842  * one spin_lock instead of array of acquired_refs.
4843  * cur_state->active_spin_lock remembers which map value element got locked
4844  * and clears it after bpf_spin_unlock.
4845  */
4846 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4847 			     bool is_lock)
4848 {
4849 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4850 	struct bpf_verifier_state *cur = env->cur_state;
4851 	bool is_const = tnum_is_const(reg->var_off);
4852 	struct bpf_map *map = reg->map_ptr;
4853 	u64 val = reg->var_off.value;
4854 
4855 	if (!is_const) {
4856 		verbose(env,
4857 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4858 			regno);
4859 		return -EINVAL;
4860 	}
4861 	if (!map->btf) {
4862 		verbose(env,
4863 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4864 			map->name);
4865 		return -EINVAL;
4866 	}
4867 	if (!map_value_has_spin_lock(map)) {
4868 		if (map->spin_lock_off == -E2BIG)
4869 			verbose(env,
4870 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4871 				map->name);
4872 		else if (map->spin_lock_off == -ENOENT)
4873 			verbose(env,
4874 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4875 				map->name);
4876 		else
4877 			verbose(env,
4878 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4879 				map->name);
4880 		return -EINVAL;
4881 	}
4882 	if (map->spin_lock_off != val + reg->off) {
4883 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4884 			val + reg->off);
4885 		return -EINVAL;
4886 	}
4887 	if (is_lock) {
4888 		if (cur->active_spin_lock) {
4889 			verbose(env,
4890 				"Locking two bpf_spin_locks are not allowed\n");
4891 			return -EINVAL;
4892 		}
4893 		cur->active_spin_lock = reg->id;
4894 	} else {
4895 		if (!cur->active_spin_lock) {
4896 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4897 			return -EINVAL;
4898 		}
4899 		if (cur->active_spin_lock != reg->id) {
4900 			verbose(env, "bpf_spin_unlock of different lock\n");
4901 			return -EINVAL;
4902 		}
4903 		cur->active_spin_lock = 0;
4904 	}
4905 	return 0;
4906 }
4907 
4908 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4909 			      struct bpf_call_arg_meta *meta)
4910 {
4911 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4912 	bool is_const = tnum_is_const(reg->var_off);
4913 	struct bpf_map *map = reg->map_ptr;
4914 	u64 val = reg->var_off.value;
4915 
4916 	if (!is_const) {
4917 		verbose(env,
4918 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4919 			regno);
4920 		return -EINVAL;
4921 	}
4922 	if (!map->btf) {
4923 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4924 			map->name);
4925 		return -EINVAL;
4926 	}
4927 	if (!map_value_has_timer(map)) {
4928 		if (map->timer_off == -E2BIG)
4929 			verbose(env,
4930 				"map '%s' has more than one 'struct bpf_timer'\n",
4931 				map->name);
4932 		else if (map->timer_off == -ENOENT)
4933 			verbose(env,
4934 				"map '%s' doesn't have 'struct bpf_timer'\n",
4935 				map->name);
4936 		else
4937 			verbose(env,
4938 				"map '%s' is not a struct type or bpf_timer is mangled\n",
4939 				map->name);
4940 		return -EINVAL;
4941 	}
4942 	if (map->timer_off != val + reg->off) {
4943 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4944 			val + reg->off, map->timer_off);
4945 		return -EINVAL;
4946 	}
4947 	if (meta->map_ptr) {
4948 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4949 		return -EFAULT;
4950 	}
4951 	meta->map_uid = reg->map_uid;
4952 	meta->map_ptr = map;
4953 	return 0;
4954 }
4955 
4956 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4957 {
4958 	return type == ARG_PTR_TO_MEM ||
4959 	       type == ARG_PTR_TO_MEM_OR_NULL ||
4960 	       type == ARG_PTR_TO_UNINIT_MEM;
4961 }
4962 
4963 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4964 {
4965 	return type == ARG_CONST_SIZE ||
4966 	       type == ARG_CONST_SIZE_OR_ZERO;
4967 }
4968 
4969 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4970 {
4971 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4972 }
4973 
4974 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4975 {
4976 	return type == ARG_PTR_TO_INT ||
4977 	       type == ARG_PTR_TO_LONG;
4978 }
4979 
4980 static int int_ptr_type_to_size(enum bpf_arg_type type)
4981 {
4982 	if (type == ARG_PTR_TO_INT)
4983 		return sizeof(u32);
4984 	else if (type == ARG_PTR_TO_LONG)
4985 		return sizeof(u64);
4986 
4987 	return -EINVAL;
4988 }
4989 
4990 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4991 				 const struct bpf_call_arg_meta *meta,
4992 				 enum bpf_arg_type *arg_type)
4993 {
4994 	if (!meta->map_ptr) {
4995 		/* kernel subsystem misconfigured verifier */
4996 		verbose(env, "invalid map_ptr to access map->type\n");
4997 		return -EACCES;
4998 	}
4999 
5000 	switch (meta->map_ptr->map_type) {
5001 	case BPF_MAP_TYPE_SOCKMAP:
5002 	case BPF_MAP_TYPE_SOCKHASH:
5003 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5004 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5005 		} else {
5006 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5007 			return -EINVAL;
5008 		}
5009 		break;
5010 
5011 	default:
5012 		break;
5013 	}
5014 	return 0;
5015 }
5016 
5017 struct bpf_reg_types {
5018 	const enum bpf_reg_type types[10];
5019 	u32 *btf_id;
5020 };
5021 
5022 static const struct bpf_reg_types map_key_value_types = {
5023 	.types = {
5024 		PTR_TO_STACK,
5025 		PTR_TO_PACKET,
5026 		PTR_TO_PACKET_META,
5027 		PTR_TO_MAP_KEY,
5028 		PTR_TO_MAP_VALUE,
5029 	},
5030 };
5031 
5032 static const struct bpf_reg_types sock_types = {
5033 	.types = {
5034 		PTR_TO_SOCK_COMMON,
5035 		PTR_TO_SOCKET,
5036 		PTR_TO_TCP_SOCK,
5037 		PTR_TO_XDP_SOCK,
5038 	},
5039 };
5040 
5041 #ifdef CONFIG_NET
5042 static const struct bpf_reg_types btf_id_sock_common_types = {
5043 	.types = {
5044 		PTR_TO_SOCK_COMMON,
5045 		PTR_TO_SOCKET,
5046 		PTR_TO_TCP_SOCK,
5047 		PTR_TO_XDP_SOCK,
5048 		PTR_TO_BTF_ID,
5049 	},
5050 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5051 };
5052 #endif
5053 
5054 static const struct bpf_reg_types mem_types = {
5055 	.types = {
5056 		PTR_TO_STACK,
5057 		PTR_TO_PACKET,
5058 		PTR_TO_PACKET_META,
5059 		PTR_TO_MAP_KEY,
5060 		PTR_TO_MAP_VALUE,
5061 		PTR_TO_MEM,
5062 		PTR_TO_RDONLY_BUF,
5063 		PTR_TO_RDWR_BUF,
5064 	},
5065 };
5066 
5067 static const struct bpf_reg_types int_ptr_types = {
5068 	.types = {
5069 		PTR_TO_STACK,
5070 		PTR_TO_PACKET,
5071 		PTR_TO_PACKET_META,
5072 		PTR_TO_MAP_KEY,
5073 		PTR_TO_MAP_VALUE,
5074 	},
5075 };
5076 
5077 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5078 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5079 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5080 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
5081 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5082 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5083 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5084 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
5085 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5086 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5087 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5088 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5089 
5090 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5091 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5092 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5093 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
5094 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
5095 	[ARG_CONST_SIZE]		= &scalar_types,
5096 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5097 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5098 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5099 	[ARG_PTR_TO_CTX]		= &context_types,
5100 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
5101 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5102 #ifdef CONFIG_NET
5103 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5104 #endif
5105 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5106 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
5107 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5108 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5109 	[ARG_PTR_TO_MEM]		= &mem_types,
5110 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
5111 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
5112 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5113 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
5114 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5115 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5116 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5117 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5118 	[ARG_PTR_TO_STACK_OR_NULL]	= &stack_ptr_types,
5119 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5120 	[ARG_PTR_TO_TIMER]		= &timer_types,
5121 };
5122 
5123 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5124 			  enum bpf_arg_type arg_type,
5125 			  const u32 *arg_btf_id)
5126 {
5127 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5128 	enum bpf_reg_type expected, type = reg->type;
5129 	const struct bpf_reg_types *compatible;
5130 	int i, j;
5131 
5132 	compatible = compatible_reg_types[arg_type];
5133 	if (!compatible) {
5134 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5135 		return -EFAULT;
5136 	}
5137 
5138 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5139 		expected = compatible->types[i];
5140 		if (expected == NOT_INIT)
5141 			break;
5142 
5143 		if (type == expected)
5144 			goto found;
5145 	}
5146 
5147 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
5148 	for (j = 0; j + 1 < i; j++)
5149 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
5150 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
5151 	return -EACCES;
5152 
5153 found:
5154 	if (type == PTR_TO_BTF_ID) {
5155 		if (!arg_btf_id) {
5156 			if (!compatible->btf_id) {
5157 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5158 				return -EFAULT;
5159 			}
5160 			arg_btf_id = compatible->btf_id;
5161 		}
5162 
5163 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5164 					  btf_vmlinux, *arg_btf_id)) {
5165 			verbose(env, "R%d is of type %s but %s is expected\n",
5166 				regno, kernel_type_name(reg->btf, reg->btf_id),
5167 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5168 			return -EACCES;
5169 		}
5170 
5171 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5172 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5173 				regno);
5174 			return -EACCES;
5175 		}
5176 	}
5177 
5178 	return 0;
5179 }
5180 
5181 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5182 			  struct bpf_call_arg_meta *meta,
5183 			  const struct bpf_func_proto *fn)
5184 {
5185 	u32 regno = BPF_REG_1 + arg;
5186 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5187 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5188 	enum bpf_reg_type type = reg->type;
5189 	int err = 0;
5190 
5191 	if (arg_type == ARG_DONTCARE)
5192 		return 0;
5193 
5194 	err = check_reg_arg(env, regno, SRC_OP);
5195 	if (err)
5196 		return err;
5197 
5198 	if (arg_type == ARG_ANYTHING) {
5199 		if (is_pointer_value(env, regno)) {
5200 			verbose(env, "R%d leaks addr into helper function\n",
5201 				regno);
5202 			return -EACCES;
5203 		}
5204 		return 0;
5205 	}
5206 
5207 	if (type_is_pkt_pointer(type) &&
5208 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5209 		verbose(env, "helper access to the packet is not allowed\n");
5210 		return -EACCES;
5211 	}
5212 
5213 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5214 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5215 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5216 		err = resolve_map_arg_type(env, meta, &arg_type);
5217 		if (err)
5218 			return err;
5219 	}
5220 
5221 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5222 		/* A NULL register has a SCALAR_VALUE type, so skip
5223 		 * type checking.
5224 		 */
5225 		goto skip_type_check;
5226 
5227 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5228 	if (err)
5229 		return err;
5230 
5231 	if (type == PTR_TO_CTX) {
5232 		err = check_ctx_reg(env, reg, regno);
5233 		if (err < 0)
5234 			return err;
5235 	}
5236 
5237 skip_type_check:
5238 	if (reg->ref_obj_id) {
5239 		if (meta->ref_obj_id) {
5240 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5241 				regno, reg->ref_obj_id,
5242 				meta->ref_obj_id);
5243 			return -EFAULT;
5244 		}
5245 		meta->ref_obj_id = reg->ref_obj_id;
5246 	}
5247 
5248 	if (arg_type == ARG_CONST_MAP_PTR) {
5249 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5250 		if (meta->map_ptr) {
5251 			/* Use map_uid (which is unique id of inner map) to reject:
5252 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5253 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5254 			 * if (inner_map1 && inner_map2) {
5255 			 *     timer = bpf_map_lookup_elem(inner_map1);
5256 			 *     if (timer)
5257 			 *         // mismatch would have been allowed
5258 			 *         bpf_timer_init(timer, inner_map2);
5259 			 * }
5260 			 *
5261 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5262 			 */
5263 			if (meta->map_ptr != reg->map_ptr ||
5264 			    meta->map_uid != reg->map_uid) {
5265 				verbose(env,
5266 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5267 					meta->map_uid, reg->map_uid);
5268 				return -EINVAL;
5269 			}
5270 		}
5271 		meta->map_ptr = reg->map_ptr;
5272 		meta->map_uid = reg->map_uid;
5273 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5274 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5275 		 * check that [key, key + map->key_size) are within
5276 		 * stack limits and initialized
5277 		 */
5278 		if (!meta->map_ptr) {
5279 			/* in function declaration map_ptr must come before
5280 			 * map_key, so that it's verified and known before
5281 			 * we have to check map_key here. Otherwise it means
5282 			 * that kernel subsystem misconfigured verifier
5283 			 */
5284 			verbose(env, "invalid map_ptr to access map->key\n");
5285 			return -EACCES;
5286 		}
5287 		err = check_helper_mem_access(env, regno,
5288 					      meta->map_ptr->key_size, false,
5289 					      NULL);
5290 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5291 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5292 		    !register_is_null(reg)) ||
5293 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5294 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5295 		 * check [value, value + map->value_size) validity
5296 		 */
5297 		if (!meta->map_ptr) {
5298 			/* kernel subsystem misconfigured verifier */
5299 			verbose(env, "invalid map_ptr to access map->value\n");
5300 			return -EACCES;
5301 		}
5302 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5303 		err = check_helper_mem_access(env, regno,
5304 					      meta->map_ptr->value_size, false,
5305 					      meta);
5306 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5307 		if (!reg->btf_id) {
5308 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5309 			return -EACCES;
5310 		}
5311 		meta->ret_btf = reg->btf;
5312 		meta->ret_btf_id = reg->btf_id;
5313 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5314 		if (meta->func_id == BPF_FUNC_spin_lock) {
5315 			if (process_spin_lock(env, regno, true))
5316 				return -EACCES;
5317 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5318 			if (process_spin_lock(env, regno, false))
5319 				return -EACCES;
5320 		} else {
5321 			verbose(env, "verifier internal error\n");
5322 			return -EFAULT;
5323 		}
5324 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5325 		if (process_timer_func(env, regno, meta))
5326 			return -EACCES;
5327 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5328 		meta->subprogno = reg->subprogno;
5329 	} else if (arg_type_is_mem_ptr(arg_type)) {
5330 		/* The access to this pointer is only checked when we hit the
5331 		 * next is_mem_size argument below.
5332 		 */
5333 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5334 	} else if (arg_type_is_mem_size(arg_type)) {
5335 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5336 
5337 		/* This is used to refine r0 return value bounds for helpers
5338 		 * that enforce this value as an upper bound on return values.
5339 		 * See do_refine_retval_range() for helpers that can refine
5340 		 * the return value. C type of helper is u32 so we pull register
5341 		 * bound from umax_value however, if negative verifier errors
5342 		 * out. Only upper bounds can be learned because retval is an
5343 		 * int type and negative retvals are allowed.
5344 		 */
5345 		meta->msize_max_value = reg->umax_value;
5346 
5347 		/* The register is SCALAR_VALUE; the access check
5348 		 * happens using its boundaries.
5349 		 */
5350 		if (!tnum_is_const(reg->var_off))
5351 			/* For unprivileged variable accesses, disable raw
5352 			 * mode so that the program is required to
5353 			 * initialize all the memory that the helper could
5354 			 * just partially fill up.
5355 			 */
5356 			meta = NULL;
5357 
5358 		if (reg->smin_value < 0) {
5359 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5360 				regno);
5361 			return -EACCES;
5362 		}
5363 
5364 		if (reg->umin_value == 0) {
5365 			err = check_helper_mem_access(env, regno - 1, 0,
5366 						      zero_size_allowed,
5367 						      meta);
5368 			if (err)
5369 				return err;
5370 		}
5371 
5372 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5373 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5374 				regno);
5375 			return -EACCES;
5376 		}
5377 		err = check_helper_mem_access(env, regno - 1,
5378 					      reg->umax_value,
5379 					      zero_size_allowed, meta);
5380 		if (!err)
5381 			err = mark_chain_precision(env, regno);
5382 	} else if (arg_type_is_alloc_size(arg_type)) {
5383 		if (!tnum_is_const(reg->var_off)) {
5384 			verbose(env, "R%d is not a known constant'\n",
5385 				regno);
5386 			return -EACCES;
5387 		}
5388 		meta->mem_size = reg->var_off.value;
5389 	} else if (arg_type_is_int_ptr(arg_type)) {
5390 		int size = int_ptr_type_to_size(arg_type);
5391 
5392 		err = check_helper_mem_access(env, regno, size, false, meta);
5393 		if (err)
5394 			return err;
5395 		err = check_ptr_alignment(env, reg, 0, size, true);
5396 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5397 		struct bpf_map *map = reg->map_ptr;
5398 		int map_off;
5399 		u64 map_addr;
5400 		char *str_ptr;
5401 
5402 		if (!bpf_map_is_rdonly(map)) {
5403 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5404 			return -EACCES;
5405 		}
5406 
5407 		if (!tnum_is_const(reg->var_off)) {
5408 			verbose(env, "R%d is not a constant address'\n", regno);
5409 			return -EACCES;
5410 		}
5411 
5412 		if (!map->ops->map_direct_value_addr) {
5413 			verbose(env, "no direct value access support for this map type\n");
5414 			return -EACCES;
5415 		}
5416 
5417 		err = check_map_access(env, regno, reg->off,
5418 				       map->value_size - reg->off, false);
5419 		if (err)
5420 			return err;
5421 
5422 		map_off = reg->off + reg->var_off.value;
5423 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5424 		if (err) {
5425 			verbose(env, "direct value access on string failed\n");
5426 			return err;
5427 		}
5428 
5429 		str_ptr = (char *)(long)(map_addr);
5430 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5431 			verbose(env, "string is not zero-terminated\n");
5432 			return -EINVAL;
5433 		}
5434 	}
5435 
5436 	return err;
5437 }
5438 
5439 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5440 {
5441 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5442 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5443 
5444 	if (func_id != BPF_FUNC_map_update_elem)
5445 		return false;
5446 
5447 	/* It's not possible to get access to a locked struct sock in these
5448 	 * contexts, so updating is safe.
5449 	 */
5450 	switch (type) {
5451 	case BPF_PROG_TYPE_TRACING:
5452 		if (eatype == BPF_TRACE_ITER)
5453 			return true;
5454 		break;
5455 	case BPF_PROG_TYPE_SOCKET_FILTER:
5456 	case BPF_PROG_TYPE_SCHED_CLS:
5457 	case BPF_PROG_TYPE_SCHED_ACT:
5458 	case BPF_PROG_TYPE_XDP:
5459 	case BPF_PROG_TYPE_SK_REUSEPORT:
5460 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5461 	case BPF_PROG_TYPE_SK_LOOKUP:
5462 		return true;
5463 	default:
5464 		break;
5465 	}
5466 
5467 	verbose(env, "cannot update sockmap in this context\n");
5468 	return false;
5469 }
5470 
5471 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5472 {
5473 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5474 }
5475 
5476 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5477 					struct bpf_map *map, int func_id)
5478 {
5479 	if (!map)
5480 		return 0;
5481 
5482 	/* We need a two way check, first is from map perspective ... */
5483 	switch (map->map_type) {
5484 	case BPF_MAP_TYPE_PROG_ARRAY:
5485 		if (func_id != BPF_FUNC_tail_call)
5486 			goto error;
5487 		break;
5488 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5489 		if (func_id != BPF_FUNC_perf_event_read &&
5490 		    func_id != BPF_FUNC_perf_event_output &&
5491 		    func_id != BPF_FUNC_skb_output &&
5492 		    func_id != BPF_FUNC_perf_event_read_value &&
5493 		    func_id != BPF_FUNC_xdp_output)
5494 			goto error;
5495 		break;
5496 	case BPF_MAP_TYPE_RINGBUF:
5497 		if (func_id != BPF_FUNC_ringbuf_output &&
5498 		    func_id != BPF_FUNC_ringbuf_reserve &&
5499 		    func_id != BPF_FUNC_ringbuf_query)
5500 			goto error;
5501 		break;
5502 	case BPF_MAP_TYPE_STACK_TRACE:
5503 		if (func_id != BPF_FUNC_get_stackid)
5504 			goto error;
5505 		break;
5506 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5507 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5508 		    func_id != BPF_FUNC_current_task_under_cgroup)
5509 			goto error;
5510 		break;
5511 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5512 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5513 		if (func_id != BPF_FUNC_get_local_storage)
5514 			goto error;
5515 		break;
5516 	case BPF_MAP_TYPE_DEVMAP:
5517 	case BPF_MAP_TYPE_DEVMAP_HASH:
5518 		if (func_id != BPF_FUNC_redirect_map &&
5519 		    func_id != BPF_FUNC_map_lookup_elem)
5520 			goto error;
5521 		break;
5522 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5523 	 * appear.
5524 	 */
5525 	case BPF_MAP_TYPE_CPUMAP:
5526 		if (func_id != BPF_FUNC_redirect_map)
5527 			goto error;
5528 		break;
5529 	case BPF_MAP_TYPE_XSKMAP:
5530 		if (func_id != BPF_FUNC_redirect_map &&
5531 		    func_id != BPF_FUNC_map_lookup_elem)
5532 			goto error;
5533 		break;
5534 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5535 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5536 		if (func_id != BPF_FUNC_map_lookup_elem)
5537 			goto error;
5538 		break;
5539 	case BPF_MAP_TYPE_SOCKMAP:
5540 		if (func_id != BPF_FUNC_sk_redirect_map &&
5541 		    func_id != BPF_FUNC_sock_map_update &&
5542 		    func_id != BPF_FUNC_map_delete_elem &&
5543 		    func_id != BPF_FUNC_msg_redirect_map &&
5544 		    func_id != BPF_FUNC_sk_select_reuseport &&
5545 		    func_id != BPF_FUNC_map_lookup_elem &&
5546 		    !may_update_sockmap(env, func_id))
5547 			goto error;
5548 		break;
5549 	case BPF_MAP_TYPE_SOCKHASH:
5550 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5551 		    func_id != BPF_FUNC_sock_hash_update &&
5552 		    func_id != BPF_FUNC_map_delete_elem &&
5553 		    func_id != BPF_FUNC_msg_redirect_hash &&
5554 		    func_id != BPF_FUNC_sk_select_reuseport &&
5555 		    func_id != BPF_FUNC_map_lookup_elem &&
5556 		    !may_update_sockmap(env, func_id))
5557 			goto error;
5558 		break;
5559 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5560 		if (func_id != BPF_FUNC_sk_select_reuseport)
5561 			goto error;
5562 		break;
5563 	case BPF_MAP_TYPE_QUEUE:
5564 	case BPF_MAP_TYPE_STACK:
5565 		if (func_id != BPF_FUNC_map_peek_elem &&
5566 		    func_id != BPF_FUNC_map_pop_elem &&
5567 		    func_id != BPF_FUNC_map_push_elem)
5568 			goto error;
5569 		break;
5570 	case BPF_MAP_TYPE_SK_STORAGE:
5571 		if (func_id != BPF_FUNC_sk_storage_get &&
5572 		    func_id != BPF_FUNC_sk_storage_delete)
5573 			goto error;
5574 		break;
5575 	case BPF_MAP_TYPE_INODE_STORAGE:
5576 		if (func_id != BPF_FUNC_inode_storage_get &&
5577 		    func_id != BPF_FUNC_inode_storage_delete)
5578 			goto error;
5579 		break;
5580 	case BPF_MAP_TYPE_TASK_STORAGE:
5581 		if (func_id != BPF_FUNC_task_storage_get &&
5582 		    func_id != BPF_FUNC_task_storage_delete)
5583 			goto error;
5584 		break;
5585 	default:
5586 		break;
5587 	}
5588 
5589 	/* ... and second from the function itself. */
5590 	switch (func_id) {
5591 	case BPF_FUNC_tail_call:
5592 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5593 			goto error;
5594 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5595 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5596 			return -EINVAL;
5597 		}
5598 		break;
5599 	case BPF_FUNC_perf_event_read:
5600 	case BPF_FUNC_perf_event_output:
5601 	case BPF_FUNC_perf_event_read_value:
5602 	case BPF_FUNC_skb_output:
5603 	case BPF_FUNC_xdp_output:
5604 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5605 			goto error;
5606 		break;
5607 	case BPF_FUNC_ringbuf_output:
5608 	case BPF_FUNC_ringbuf_reserve:
5609 	case BPF_FUNC_ringbuf_query:
5610 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5611 			goto error;
5612 		break;
5613 	case BPF_FUNC_get_stackid:
5614 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5615 			goto error;
5616 		break;
5617 	case BPF_FUNC_current_task_under_cgroup:
5618 	case BPF_FUNC_skb_under_cgroup:
5619 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5620 			goto error;
5621 		break;
5622 	case BPF_FUNC_redirect_map:
5623 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5624 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5625 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5626 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5627 			goto error;
5628 		break;
5629 	case BPF_FUNC_sk_redirect_map:
5630 	case BPF_FUNC_msg_redirect_map:
5631 	case BPF_FUNC_sock_map_update:
5632 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5633 			goto error;
5634 		break;
5635 	case BPF_FUNC_sk_redirect_hash:
5636 	case BPF_FUNC_msg_redirect_hash:
5637 	case BPF_FUNC_sock_hash_update:
5638 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5639 			goto error;
5640 		break;
5641 	case BPF_FUNC_get_local_storage:
5642 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5643 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5644 			goto error;
5645 		break;
5646 	case BPF_FUNC_sk_select_reuseport:
5647 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5648 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5649 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5650 			goto error;
5651 		break;
5652 	case BPF_FUNC_map_peek_elem:
5653 	case BPF_FUNC_map_pop_elem:
5654 	case BPF_FUNC_map_push_elem:
5655 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5656 		    map->map_type != BPF_MAP_TYPE_STACK)
5657 			goto error;
5658 		break;
5659 	case BPF_FUNC_sk_storage_get:
5660 	case BPF_FUNC_sk_storage_delete:
5661 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5662 			goto error;
5663 		break;
5664 	case BPF_FUNC_inode_storage_get:
5665 	case BPF_FUNC_inode_storage_delete:
5666 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5667 			goto error;
5668 		break;
5669 	case BPF_FUNC_task_storage_get:
5670 	case BPF_FUNC_task_storage_delete:
5671 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5672 			goto error;
5673 		break;
5674 	default:
5675 		break;
5676 	}
5677 
5678 	return 0;
5679 error:
5680 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5681 		map->map_type, func_id_name(func_id), func_id);
5682 	return -EINVAL;
5683 }
5684 
5685 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5686 {
5687 	int count = 0;
5688 
5689 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5690 		count++;
5691 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5692 		count++;
5693 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5694 		count++;
5695 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5696 		count++;
5697 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5698 		count++;
5699 
5700 	/* We only support one arg being in raw mode at the moment,
5701 	 * which is sufficient for the helper functions we have
5702 	 * right now.
5703 	 */
5704 	return count <= 1;
5705 }
5706 
5707 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5708 				    enum bpf_arg_type arg_next)
5709 {
5710 	return (arg_type_is_mem_ptr(arg_curr) &&
5711 	        !arg_type_is_mem_size(arg_next)) ||
5712 	       (!arg_type_is_mem_ptr(arg_curr) &&
5713 		arg_type_is_mem_size(arg_next));
5714 }
5715 
5716 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5717 {
5718 	/* bpf_xxx(..., buf, len) call will access 'len'
5719 	 * bytes from memory 'buf'. Both arg types need
5720 	 * to be paired, so make sure there's no buggy
5721 	 * helper function specification.
5722 	 */
5723 	if (arg_type_is_mem_size(fn->arg1_type) ||
5724 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5725 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5726 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5727 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5728 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5729 		return false;
5730 
5731 	return true;
5732 }
5733 
5734 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5735 {
5736 	int count = 0;
5737 
5738 	if (arg_type_may_be_refcounted(fn->arg1_type))
5739 		count++;
5740 	if (arg_type_may_be_refcounted(fn->arg2_type))
5741 		count++;
5742 	if (arg_type_may_be_refcounted(fn->arg3_type))
5743 		count++;
5744 	if (arg_type_may_be_refcounted(fn->arg4_type))
5745 		count++;
5746 	if (arg_type_may_be_refcounted(fn->arg5_type))
5747 		count++;
5748 
5749 	/* A reference acquiring function cannot acquire
5750 	 * another refcounted ptr.
5751 	 */
5752 	if (may_be_acquire_function(func_id) && count)
5753 		return false;
5754 
5755 	/* We only support one arg being unreferenced at the moment,
5756 	 * which is sufficient for the helper functions we have right now.
5757 	 */
5758 	return count <= 1;
5759 }
5760 
5761 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5762 {
5763 	int i;
5764 
5765 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5766 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5767 			return false;
5768 
5769 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5770 			return false;
5771 	}
5772 
5773 	return true;
5774 }
5775 
5776 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5777 {
5778 	return check_raw_mode_ok(fn) &&
5779 	       check_arg_pair_ok(fn) &&
5780 	       check_btf_id_ok(fn) &&
5781 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5782 }
5783 
5784 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5785  * are now invalid, so turn them into unknown SCALAR_VALUE.
5786  */
5787 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5788 				     struct bpf_func_state *state)
5789 {
5790 	struct bpf_reg_state *regs = state->regs, *reg;
5791 	int i;
5792 
5793 	for (i = 0; i < MAX_BPF_REG; i++)
5794 		if (reg_is_pkt_pointer_any(&regs[i]))
5795 			mark_reg_unknown(env, regs, i);
5796 
5797 	bpf_for_each_spilled_reg(i, state, reg) {
5798 		if (!reg)
5799 			continue;
5800 		if (reg_is_pkt_pointer_any(reg))
5801 			__mark_reg_unknown(env, reg);
5802 	}
5803 }
5804 
5805 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5806 {
5807 	struct bpf_verifier_state *vstate = env->cur_state;
5808 	int i;
5809 
5810 	for (i = 0; i <= vstate->curframe; i++)
5811 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5812 }
5813 
5814 enum {
5815 	AT_PKT_END = -1,
5816 	BEYOND_PKT_END = -2,
5817 };
5818 
5819 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5820 {
5821 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5822 	struct bpf_reg_state *reg = &state->regs[regn];
5823 
5824 	if (reg->type != PTR_TO_PACKET)
5825 		/* PTR_TO_PACKET_META is not supported yet */
5826 		return;
5827 
5828 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5829 	 * How far beyond pkt_end it goes is unknown.
5830 	 * if (!range_open) it's the case of pkt >= pkt_end
5831 	 * if (range_open) it's the case of pkt > pkt_end
5832 	 * hence this pointer is at least 1 byte bigger than pkt_end
5833 	 */
5834 	if (range_open)
5835 		reg->range = BEYOND_PKT_END;
5836 	else
5837 		reg->range = AT_PKT_END;
5838 }
5839 
5840 static void release_reg_references(struct bpf_verifier_env *env,
5841 				   struct bpf_func_state *state,
5842 				   int ref_obj_id)
5843 {
5844 	struct bpf_reg_state *regs = state->regs, *reg;
5845 	int i;
5846 
5847 	for (i = 0; i < MAX_BPF_REG; i++)
5848 		if (regs[i].ref_obj_id == ref_obj_id)
5849 			mark_reg_unknown(env, regs, i);
5850 
5851 	bpf_for_each_spilled_reg(i, state, reg) {
5852 		if (!reg)
5853 			continue;
5854 		if (reg->ref_obj_id == ref_obj_id)
5855 			__mark_reg_unknown(env, reg);
5856 	}
5857 }
5858 
5859 /* The pointer with the specified id has released its reference to kernel
5860  * resources. Identify all copies of the same pointer and clear the reference.
5861  */
5862 static int release_reference(struct bpf_verifier_env *env,
5863 			     int ref_obj_id)
5864 {
5865 	struct bpf_verifier_state *vstate = env->cur_state;
5866 	int err;
5867 	int i;
5868 
5869 	err = release_reference_state(cur_func(env), ref_obj_id);
5870 	if (err)
5871 		return err;
5872 
5873 	for (i = 0; i <= vstate->curframe; i++)
5874 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5875 
5876 	return 0;
5877 }
5878 
5879 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5880 				    struct bpf_reg_state *regs)
5881 {
5882 	int i;
5883 
5884 	/* after the call registers r0 - r5 were scratched */
5885 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5886 		mark_reg_not_init(env, regs, caller_saved[i]);
5887 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5888 	}
5889 }
5890 
5891 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5892 				   struct bpf_func_state *caller,
5893 				   struct bpf_func_state *callee,
5894 				   int insn_idx);
5895 
5896 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5897 			     int *insn_idx, int subprog,
5898 			     set_callee_state_fn set_callee_state_cb)
5899 {
5900 	struct bpf_verifier_state *state = env->cur_state;
5901 	struct bpf_func_info_aux *func_info_aux;
5902 	struct bpf_func_state *caller, *callee;
5903 	int err;
5904 	bool is_global = false;
5905 
5906 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5907 		verbose(env, "the call stack of %d frames is too deep\n",
5908 			state->curframe + 2);
5909 		return -E2BIG;
5910 	}
5911 
5912 	caller = state->frame[state->curframe];
5913 	if (state->frame[state->curframe + 1]) {
5914 		verbose(env, "verifier bug. Frame %d already allocated\n",
5915 			state->curframe + 1);
5916 		return -EFAULT;
5917 	}
5918 
5919 	func_info_aux = env->prog->aux->func_info_aux;
5920 	if (func_info_aux)
5921 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5922 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5923 	if (err == -EFAULT)
5924 		return err;
5925 	if (is_global) {
5926 		if (err) {
5927 			verbose(env, "Caller passes invalid args into func#%d\n",
5928 				subprog);
5929 			return err;
5930 		} else {
5931 			if (env->log.level & BPF_LOG_LEVEL)
5932 				verbose(env,
5933 					"Func#%d is global and valid. Skipping.\n",
5934 					subprog);
5935 			clear_caller_saved_regs(env, caller->regs);
5936 
5937 			/* All global functions return a 64-bit SCALAR_VALUE */
5938 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5939 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5940 
5941 			/* continue with next insn after call */
5942 			return 0;
5943 		}
5944 	}
5945 
5946 	if (insn->code == (BPF_JMP | BPF_CALL) &&
5947 	    insn->imm == BPF_FUNC_timer_set_callback) {
5948 		struct bpf_verifier_state *async_cb;
5949 
5950 		/* there is no real recursion here. timer callbacks are async */
5951 		env->subprog_info[subprog].is_async_cb = true;
5952 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5953 					 *insn_idx, subprog);
5954 		if (!async_cb)
5955 			return -EFAULT;
5956 		callee = async_cb->frame[0];
5957 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
5958 
5959 		/* Convert bpf_timer_set_callback() args into timer callback args */
5960 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
5961 		if (err)
5962 			return err;
5963 
5964 		clear_caller_saved_regs(env, caller->regs);
5965 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
5966 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5967 		/* continue with next insn after call */
5968 		return 0;
5969 	}
5970 
5971 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5972 	if (!callee)
5973 		return -ENOMEM;
5974 	state->frame[state->curframe + 1] = callee;
5975 
5976 	/* callee cannot access r0, r6 - r9 for reading and has to write
5977 	 * into its own stack before reading from it.
5978 	 * callee can read/write into caller's stack
5979 	 */
5980 	init_func_state(env, callee,
5981 			/* remember the callsite, it will be used by bpf_exit */
5982 			*insn_idx /* callsite */,
5983 			state->curframe + 1 /* frameno within this callchain */,
5984 			subprog /* subprog number within this prog */);
5985 
5986 	/* Transfer references to the callee */
5987 	err = copy_reference_state(callee, caller);
5988 	if (err)
5989 		return err;
5990 
5991 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
5992 	if (err)
5993 		return err;
5994 
5995 	clear_caller_saved_regs(env, caller->regs);
5996 
5997 	/* only increment it after check_reg_arg() finished */
5998 	state->curframe++;
5999 
6000 	/* and go analyze first insn of the callee */
6001 	*insn_idx = env->subprog_info[subprog].start - 1;
6002 
6003 	if (env->log.level & BPF_LOG_LEVEL) {
6004 		verbose(env, "caller:\n");
6005 		print_verifier_state(env, caller);
6006 		verbose(env, "callee:\n");
6007 		print_verifier_state(env, callee);
6008 	}
6009 	return 0;
6010 }
6011 
6012 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6013 				   struct bpf_func_state *caller,
6014 				   struct bpf_func_state *callee)
6015 {
6016 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6017 	 *      void *callback_ctx, u64 flags);
6018 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6019 	 *      void *callback_ctx);
6020 	 */
6021 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6022 
6023 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6024 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6025 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6026 
6027 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6028 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6029 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6030 
6031 	/* pointer to stack or null */
6032 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6033 
6034 	/* unused */
6035 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6036 	return 0;
6037 }
6038 
6039 static int set_callee_state(struct bpf_verifier_env *env,
6040 			    struct bpf_func_state *caller,
6041 			    struct bpf_func_state *callee, int insn_idx)
6042 {
6043 	int i;
6044 
6045 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6046 	 * pointers, which connects us up to the liveness chain
6047 	 */
6048 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6049 		callee->regs[i] = caller->regs[i];
6050 	return 0;
6051 }
6052 
6053 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6054 			   int *insn_idx)
6055 {
6056 	int subprog, target_insn;
6057 
6058 	target_insn = *insn_idx + insn->imm + 1;
6059 	subprog = find_subprog(env, target_insn);
6060 	if (subprog < 0) {
6061 		verbose(env, "verifier bug. No program starts at insn %d\n",
6062 			target_insn);
6063 		return -EFAULT;
6064 	}
6065 
6066 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6067 }
6068 
6069 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6070 				       struct bpf_func_state *caller,
6071 				       struct bpf_func_state *callee,
6072 				       int insn_idx)
6073 {
6074 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6075 	struct bpf_map *map;
6076 	int err;
6077 
6078 	if (bpf_map_ptr_poisoned(insn_aux)) {
6079 		verbose(env, "tail_call abusing map_ptr\n");
6080 		return -EINVAL;
6081 	}
6082 
6083 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6084 	if (!map->ops->map_set_for_each_callback_args ||
6085 	    !map->ops->map_for_each_callback) {
6086 		verbose(env, "callback function not allowed for map\n");
6087 		return -ENOTSUPP;
6088 	}
6089 
6090 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6091 	if (err)
6092 		return err;
6093 
6094 	callee->in_callback_fn = true;
6095 	return 0;
6096 }
6097 
6098 static int set_timer_callback_state(struct bpf_verifier_env *env,
6099 				    struct bpf_func_state *caller,
6100 				    struct bpf_func_state *callee,
6101 				    int insn_idx)
6102 {
6103 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6104 
6105 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6106 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6107 	 */
6108 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6109 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6110 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6111 
6112 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6113 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6114 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6115 
6116 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6117 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6118 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6119 
6120 	/* unused */
6121 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6122 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6123 	callee->in_async_callback_fn = true;
6124 	return 0;
6125 }
6126 
6127 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6128 {
6129 	struct bpf_verifier_state *state = env->cur_state;
6130 	struct bpf_func_state *caller, *callee;
6131 	struct bpf_reg_state *r0;
6132 	int err;
6133 
6134 	callee = state->frame[state->curframe];
6135 	r0 = &callee->regs[BPF_REG_0];
6136 	if (r0->type == PTR_TO_STACK) {
6137 		/* technically it's ok to return caller's stack pointer
6138 		 * (or caller's caller's pointer) back to the caller,
6139 		 * since these pointers are valid. Only current stack
6140 		 * pointer will be invalid as soon as function exits,
6141 		 * but let's be conservative
6142 		 */
6143 		verbose(env, "cannot return stack pointer to the caller\n");
6144 		return -EINVAL;
6145 	}
6146 
6147 	state->curframe--;
6148 	caller = state->frame[state->curframe];
6149 	if (callee->in_callback_fn) {
6150 		/* enforce R0 return value range [0, 1]. */
6151 		struct tnum range = tnum_range(0, 1);
6152 
6153 		if (r0->type != SCALAR_VALUE) {
6154 			verbose(env, "R0 not a scalar value\n");
6155 			return -EACCES;
6156 		}
6157 		if (!tnum_in(range, r0->var_off)) {
6158 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6159 			return -EINVAL;
6160 		}
6161 	} else {
6162 		/* return to the caller whatever r0 had in the callee */
6163 		caller->regs[BPF_REG_0] = *r0;
6164 	}
6165 
6166 	/* Transfer references to the caller */
6167 	err = copy_reference_state(caller, callee);
6168 	if (err)
6169 		return err;
6170 
6171 	*insn_idx = callee->callsite + 1;
6172 	if (env->log.level & BPF_LOG_LEVEL) {
6173 		verbose(env, "returning from callee:\n");
6174 		print_verifier_state(env, callee);
6175 		verbose(env, "to caller at %d:\n", *insn_idx);
6176 		print_verifier_state(env, caller);
6177 	}
6178 	/* clear everything in the callee */
6179 	free_func_state(callee);
6180 	state->frame[state->curframe + 1] = NULL;
6181 	return 0;
6182 }
6183 
6184 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6185 				   int func_id,
6186 				   struct bpf_call_arg_meta *meta)
6187 {
6188 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6189 
6190 	if (ret_type != RET_INTEGER ||
6191 	    (func_id != BPF_FUNC_get_stack &&
6192 	     func_id != BPF_FUNC_get_task_stack &&
6193 	     func_id != BPF_FUNC_probe_read_str &&
6194 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6195 	     func_id != BPF_FUNC_probe_read_user_str))
6196 		return;
6197 
6198 	ret_reg->smax_value = meta->msize_max_value;
6199 	ret_reg->s32_max_value = meta->msize_max_value;
6200 	ret_reg->smin_value = -MAX_ERRNO;
6201 	ret_reg->s32_min_value = -MAX_ERRNO;
6202 	__reg_deduce_bounds(ret_reg);
6203 	__reg_bound_offset(ret_reg);
6204 	__update_reg_bounds(ret_reg);
6205 }
6206 
6207 static int
6208 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6209 		int func_id, int insn_idx)
6210 {
6211 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6212 	struct bpf_map *map = meta->map_ptr;
6213 
6214 	if (func_id != BPF_FUNC_tail_call &&
6215 	    func_id != BPF_FUNC_map_lookup_elem &&
6216 	    func_id != BPF_FUNC_map_update_elem &&
6217 	    func_id != BPF_FUNC_map_delete_elem &&
6218 	    func_id != BPF_FUNC_map_push_elem &&
6219 	    func_id != BPF_FUNC_map_pop_elem &&
6220 	    func_id != BPF_FUNC_map_peek_elem &&
6221 	    func_id != BPF_FUNC_for_each_map_elem &&
6222 	    func_id != BPF_FUNC_redirect_map)
6223 		return 0;
6224 
6225 	if (map == NULL) {
6226 		verbose(env, "kernel subsystem misconfigured verifier\n");
6227 		return -EINVAL;
6228 	}
6229 
6230 	/* In case of read-only, some additional restrictions
6231 	 * need to be applied in order to prevent altering the
6232 	 * state of the map from program side.
6233 	 */
6234 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6235 	    (func_id == BPF_FUNC_map_delete_elem ||
6236 	     func_id == BPF_FUNC_map_update_elem ||
6237 	     func_id == BPF_FUNC_map_push_elem ||
6238 	     func_id == BPF_FUNC_map_pop_elem)) {
6239 		verbose(env, "write into map forbidden\n");
6240 		return -EACCES;
6241 	}
6242 
6243 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6244 		bpf_map_ptr_store(aux, meta->map_ptr,
6245 				  !meta->map_ptr->bypass_spec_v1);
6246 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6247 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6248 				  !meta->map_ptr->bypass_spec_v1);
6249 	return 0;
6250 }
6251 
6252 static int
6253 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6254 		int func_id, int insn_idx)
6255 {
6256 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6257 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6258 	struct bpf_map *map = meta->map_ptr;
6259 	struct tnum range;
6260 	u64 val;
6261 	int err;
6262 
6263 	if (func_id != BPF_FUNC_tail_call)
6264 		return 0;
6265 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6266 		verbose(env, "kernel subsystem misconfigured verifier\n");
6267 		return -EINVAL;
6268 	}
6269 
6270 	range = tnum_range(0, map->max_entries - 1);
6271 	reg = &regs[BPF_REG_3];
6272 
6273 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6274 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6275 		return 0;
6276 	}
6277 
6278 	err = mark_chain_precision(env, BPF_REG_3);
6279 	if (err)
6280 		return err;
6281 
6282 	val = reg->var_off.value;
6283 	if (bpf_map_key_unseen(aux))
6284 		bpf_map_key_store(aux, val);
6285 	else if (!bpf_map_key_poisoned(aux) &&
6286 		  bpf_map_key_immediate(aux) != val)
6287 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6288 	return 0;
6289 }
6290 
6291 static int check_reference_leak(struct bpf_verifier_env *env)
6292 {
6293 	struct bpf_func_state *state = cur_func(env);
6294 	int i;
6295 
6296 	for (i = 0; i < state->acquired_refs; i++) {
6297 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6298 			state->refs[i].id, state->refs[i].insn_idx);
6299 	}
6300 	return state->acquired_refs ? -EINVAL : 0;
6301 }
6302 
6303 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6304 				   struct bpf_reg_state *regs)
6305 {
6306 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6307 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6308 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6309 	int err, fmt_map_off, num_args;
6310 	u64 fmt_addr;
6311 	char *fmt;
6312 
6313 	/* data must be an array of u64 */
6314 	if (data_len_reg->var_off.value % 8)
6315 		return -EINVAL;
6316 	num_args = data_len_reg->var_off.value / 8;
6317 
6318 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6319 	 * and map_direct_value_addr is set.
6320 	 */
6321 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6322 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6323 						  fmt_map_off);
6324 	if (err) {
6325 		verbose(env, "verifier bug\n");
6326 		return -EFAULT;
6327 	}
6328 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6329 
6330 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6331 	 * can focus on validating the format specifiers.
6332 	 */
6333 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6334 	if (err < 0)
6335 		verbose(env, "Invalid format string\n");
6336 
6337 	return err;
6338 }
6339 
6340 static int check_get_func_ip(struct bpf_verifier_env *env)
6341 {
6342 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6343 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6344 	int func_id = BPF_FUNC_get_func_ip;
6345 
6346 	if (type == BPF_PROG_TYPE_TRACING) {
6347 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6348 		    eatype != BPF_MODIFY_RETURN) {
6349 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6350 				func_id_name(func_id), func_id);
6351 			return -ENOTSUPP;
6352 		}
6353 		return 0;
6354 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6355 		return 0;
6356 	}
6357 
6358 	verbose(env, "func %s#%d not supported for program type %d\n",
6359 		func_id_name(func_id), func_id, type);
6360 	return -ENOTSUPP;
6361 }
6362 
6363 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6364 			     int *insn_idx_p)
6365 {
6366 	const struct bpf_func_proto *fn = NULL;
6367 	struct bpf_reg_state *regs;
6368 	struct bpf_call_arg_meta meta;
6369 	int insn_idx = *insn_idx_p;
6370 	bool changes_data;
6371 	int i, err, func_id;
6372 
6373 	/* find function prototype */
6374 	func_id = insn->imm;
6375 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6376 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6377 			func_id);
6378 		return -EINVAL;
6379 	}
6380 
6381 	if (env->ops->get_func_proto)
6382 		fn = env->ops->get_func_proto(func_id, env->prog);
6383 	if (!fn) {
6384 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6385 			func_id);
6386 		return -EINVAL;
6387 	}
6388 
6389 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6390 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6391 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6392 		return -EINVAL;
6393 	}
6394 
6395 	if (fn->allowed && !fn->allowed(env->prog)) {
6396 		verbose(env, "helper call is not allowed in probe\n");
6397 		return -EINVAL;
6398 	}
6399 
6400 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6401 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6402 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6403 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6404 			func_id_name(func_id), func_id);
6405 		return -EINVAL;
6406 	}
6407 
6408 	memset(&meta, 0, sizeof(meta));
6409 	meta.pkt_access = fn->pkt_access;
6410 
6411 	err = check_func_proto(fn, func_id);
6412 	if (err) {
6413 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6414 			func_id_name(func_id), func_id);
6415 		return err;
6416 	}
6417 
6418 	meta.func_id = func_id;
6419 	/* check args */
6420 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6421 		err = check_func_arg(env, i, &meta, fn);
6422 		if (err)
6423 			return err;
6424 	}
6425 
6426 	err = record_func_map(env, &meta, func_id, insn_idx);
6427 	if (err)
6428 		return err;
6429 
6430 	err = record_func_key(env, &meta, func_id, insn_idx);
6431 	if (err)
6432 		return err;
6433 
6434 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6435 	 * is inferred from register state.
6436 	 */
6437 	for (i = 0; i < meta.access_size; i++) {
6438 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6439 				       BPF_WRITE, -1, false);
6440 		if (err)
6441 			return err;
6442 	}
6443 
6444 	if (func_id == BPF_FUNC_tail_call) {
6445 		err = check_reference_leak(env);
6446 		if (err) {
6447 			verbose(env, "tail_call would lead to reference leak\n");
6448 			return err;
6449 		}
6450 	} else if (is_release_function(func_id)) {
6451 		err = release_reference(env, meta.ref_obj_id);
6452 		if (err) {
6453 			verbose(env, "func %s#%d reference has not been acquired before\n",
6454 				func_id_name(func_id), func_id);
6455 			return err;
6456 		}
6457 	}
6458 
6459 	regs = cur_regs(env);
6460 
6461 	/* check that flags argument in get_local_storage(map, flags) is 0,
6462 	 * this is required because get_local_storage() can't return an error.
6463 	 */
6464 	if (func_id == BPF_FUNC_get_local_storage &&
6465 	    !register_is_null(&regs[BPF_REG_2])) {
6466 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6467 		return -EINVAL;
6468 	}
6469 
6470 	if (func_id == BPF_FUNC_for_each_map_elem) {
6471 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6472 					set_map_elem_callback_state);
6473 		if (err < 0)
6474 			return -EINVAL;
6475 	}
6476 
6477 	if (func_id == BPF_FUNC_timer_set_callback) {
6478 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6479 					set_timer_callback_state);
6480 		if (err < 0)
6481 			return -EINVAL;
6482 	}
6483 
6484 	if (func_id == BPF_FUNC_snprintf) {
6485 		err = check_bpf_snprintf_call(env, regs);
6486 		if (err < 0)
6487 			return err;
6488 	}
6489 
6490 	/* reset caller saved regs */
6491 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6492 		mark_reg_not_init(env, regs, caller_saved[i]);
6493 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6494 	}
6495 
6496 	/* helper call returns 64-bit value. */
6497 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6498 
6499 	/* update return register (already marked as written above) */
6500 	if (fn->ret_type == RET_INTEGER) {
6501 		/* sets type to SCALAR_VALUE */
6502 		mark_reg_unknown(env, regs, BPF_REG_0);
6503 	} else if (fn->ret_type == RET_VOID) {
6504 		regs[BPF_REG_0].type = NOT_INIT;
6505 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6506 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6507 		/* There is no offset yet applied, variable or fixed */
6508 		mark_reg_known_zero(env, regs, BPF_REG_0);
6509 		/* remember map_ptr, so that check_map_access()
6510 		 * can check 'value_size' boundary of memory access
6511 		 * to map element returned from bpf_map_lookup_elem()
6512 		 */
6513 		if (meta.map_ptr == NULL) {
6514 			verbose(env,
6515 				"kernel subsystem misconfigured verifier\n");
6516 			return -EINVAL;
6517 		}
6518 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6519 		regs[BPF_REG_0].map_uid = meta.map_uid;
6520 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6521 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6522 			if (map_value_has_spin_lock(meta.map_ptr))
6523 				regs[BPF_REG_0].id = ++env->id_gen;
6524 		} else {
6525 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6526 		}
6527 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6528 		mark_reg_known_zero(env, regs, BPF_REG_0);
6529 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6530 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6531 		mark_reg_known_zero(env, regs, BPF_REG_0);
6532 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6533 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6534 		mark_reg_known_zero(env, regs, BPF_REG_0);
6535 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6536 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6537 		mark_reg_known_zero(env, regs, BPF_REG_0);
6538 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6539 		regs[BPF_REG_0].mem_size = meta.mem_size;
6540 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6541 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6542 		const struct btf_type *t;
6543 
6544 		mark_reg_known_zero(env, regs, BPF_REG_0);
6545 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6546 		if (!btf_type_is_struct(t)) {
6547 			u32 tsize;
6548 			const struct btf_type *ret;
6549 			const char *tname;
6550 
6551 			/* resolve the type size of ksym. */
6552 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6553 			if (IS_ERR(ret)) {
6554 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6555 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6556 					tname, PTR_ERR(ret));
6557 				return -EINVAL;
6558 			}
6559 			regs[BPF_REG_0].type =
6560 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6561 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6562 			regs[BPF_REG_0].mem_size = tsize;
6563 		} else {
6564 			regs[BPF_REG_0].type =
6565 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6566 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6567 			regs[BPF_REG_0].btf = meta.ret_btf;
6568 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6569 		}
6570 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6571 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
6572 		int ret_btf_id;
6573 
6574 		mark_reg_known_zero(env, regs, BPF_REG_0);
6575 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6576 						     PTR_TO_BTF_ID :
6577 						     PTR_TO_BTF_ID_OR_NULL;
6578 		ret_btf_id = *fn->ret_btf_id;
6579 		if (ret_btf_id == 0) {
6580 			verbose(env, "invalid return type %d of func %s#%d\n",
6581 				fn->ret_type, func_id_name(func_id), func_id);
6582 			return -EINVAL;
6583 		}
6584 		/* current BPF helper definitions are only coming from
6585 		 * built-in code with type IDs from  vmlinux BTF
6586 		 */
6587 		regs[BPF_REG_0].btf = btf_vmlinux;
6588 		regs[BPF_REG_0].btf_id = ret_btf_id;
6589 	} else {
6590 		verbose(env, "unknown return type %d of func %s#%d\n",
6591 			fn->ret_type, func_id_name(func_id), func_id);
6592 		return -EINVAL;
6593 	}
6594 
6595 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
6596 		regs[BPF_REG_0].id = ++env->id_gen;
6597 
6598 	if (is_ptr_cast_function(func_id)) {
6599 		/* For release_reference() */
6600 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6601 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6602 		int id = acquire_reference_state(env, insn_idx);
6603 
6604 		if (id < 0)
6605 			return id;
6606 		/* For mark_ptr_or_null_reg() */
6607 		regs[BPF_REG_0].id = id;
6608 		/* For release_reference() */
6609 		regs[BPF_REG_0].ref_obj_id = id;
6610 	}
6611 
6612 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6613 
6614 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6615 	if (err)
6616 		return err;
6617 
6618 	if ((func_id == BPF_FUNC_get_stack ||
6619 	     func_id == BPF_FUNC_get_task_stack) &&
6620 	    !env->prog->has_callchain_buf) {
6621 		const char *err_str;
6622 
6623 #ifdef CONFIG_PERF_EVENTS
6624 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6625 		err_str = "cannot get callchain buffer for func %s#%d\n";
6626 #else
6627 		err = -ENOTSUPP;
6628 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6629 #endif
6630 		if (err) {
6631 			verbose(env, err_str, func_id_name(func_id), func_id);
6632 			return err;
6633 		}
6634 
6635 		env->prog->has_callchain_buf = true;
6636 	}
6637 
6638 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6639 		env->prog->call_get_stack = true;
6640 
6641 	if (func_id == BPF_FUNC_get_func_ip) {
6642 		if (check_get_func_ip(env))
6643 			return -ENOTSUPP;
6644 		env->prog->call_get_func_ip = true;
6645 	}
6646 
6647 	if (changes_data)
6648 		clear_all_pkt_pointers(env);
6649 	return 0;
6650 }
6651 
6652 /* mark_btf_func_reg_size() is used when the reg size is determined by
6653  * the BTF func_proto's return value size and argument.
6654  */
6655 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6656 				   size_t reg_size)
6657 {
6658 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6659 
6660 	if (regno == BPF_REG_0) {
6661 		/* Function return value */
6662 		reg->live |= REG_LIVE_WRITTEN;
6663 		reg->subreg_def = reg_size == sizeof(u64) ?
6664 			DEF_NOT_SUBREG : env->insn_idx + 1;
6665 	} else {
6666 		/* Function argument */
6667 		if (reg_size == sizeof(u64)) {
6668 			mark_insn_zext(env, reg);
6669 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6670 		} else {
6671 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6672 		}
6673 	}
6674 }
6675 
6676 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6677 {
6678 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6679 	struct bpf_reg_state *regs = cur_regs(env);
6680 	const char *func_name, *ptr_type_name;
6681 	u32 i, nargs, func_id, ptr_type_id;
6682 	struct module *btf_mod = NULL;
6683 	const struct btf_param *args;
6684 	struct btf *desc_btf;
6685 	int err;
6686 
6687 	/* skip for now, but return error when we find this in fixup_kfunc_call */
6688 	if (!insn->imm)
6689 		return 0;
6690 
6691 	desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod);
6692 	if (IS_ERR(desc_btf))
6693 		return PTR_ERR(desc_btf);
6694 
6695 	func_id = insn->imm;
6696 	func = btf_type_by_id(desc_btf, func_id);
6697 	func_name = btf_name_by_offset(desc_btf, func->name_off);
6698 	func_proto = btf_type_by_id(desc_btf, func->type);
6699 
6700 	if (!env->ops->check_kfunc_call ||
6701 	    !env->ops->check_kfunc_call(func_id, btf_mod)) {
6702 		verbose(env, "calling kernel function %s is not allowed\n",
6703 			func_name);
6704 		return -EACCES;
6705 	}
6706 
6707 	/* Check the arguments */
6708 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
6709 	if (err)
6710 		return err;
6711 
6712 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6713 		mark_reg_not_init(env, regs, caller_saved[i]);
6714 
6715 	/* Check return type */
6716 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
6717 	if (btf_type_is_scalar(t)) {
6718 		mark_reg_unknown(env, regs, BPF_REG_0);
6719 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6720 	} else if (btf_type_is_ptr(t)) {
6721 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
6722 						   &ptr_type_id);
6723 		if (!btf_type_is_struct(ptr_type)) {
6724 			ptr_type_name = btf_name_by_offset(desc_btf,
6725 							   ptr_type->name_off);
6726 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6727 				func_name, btf_type_str(ptr_type),
6728 				ptr_type_name);
6729 			return -EINVAL;
6730 		}
6731 		mark_reg_known_zero(env, regs, BPF_REG_0);
6732 		regs[BPF_REG_0].btf = desc_btf;
6733 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6734 		regs[BPF_REG_0].btf_id = ptr_type_id;
6735 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6736 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6737 
6738 	nargs = btf_type_vlen(func_proto);
6739 	args = (const struct btf_param *)(func_proto + 1);
6740 	for (i = 0; i < nargs; i++) {
6741 		u32 regno = i + 1;
6742 
6743 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
6744 		if (btf_type_is_ptr(t))
6745 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6746 		else
6747 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6748 			mark_btf_func_reg_size(env, regno, t->size);
6749 	}
6750 
6751 	return 0;
6752 }
6753 
6754 static bool signed_add_overflows(s64 a, s64 b)
6755 {
6756 	/* Do the add in u64, where overflow is well-defined */
6757 	s64 res = (s64)((u64)a + (u64)b);
6758 
6759 	if (b < 0)
6760 		return res > a;
6761 	return res < a;
6762 }
6763 
6764 static bool signed_add32_overflows(s32 a, s32 b)
6765 {
6766 	/* Do the add in u32, where overflow is well-defined */
6767 	s32 res = (s32)((u32)a + (u32)b);
6768 
6769 	if (b < 0)
6770 		return res > a;
6771 	return res < a;
6772 }
6773 
6774 static bool signed_sub_overflows(s64 a, s64 b)
6775 {
6776 	/* Do the sub in u64, where overflow is well-defined */
6777 	s64 res = (s64)((u64)a - (u64)b);
6778 
6779 	if (b < 0)
6780 		return res < a;
6781 	return res > a;
6782 }
6783 
6784 static bool signed_sub32_overflows(s32 a, s32 b)
6785 {
6786 	/* Do the sub in u32, where overflow is well-defined */
6787 	s32 res = (s32)((u32)a - (u32)b);
6788 
6789 	if (b < 0)
6790 		return res < a;
6791 	return res > a;
6792 }
6793 
6794 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6795 				  const struct bpf_reg_state *reg,
6796 				  enum bpf_reg_type type)
6797 {
6798 	bool known = tnum_is_const(reg->var_off);
6799 	s64 val = reg->var_off.value;
6800 	s64 smin = reg->smin_value;
6801 
6802 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6803 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6804 			reg_type_str[type], val);
6805 		return false;
6806 	}
6807 
6808 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6809 		verbose(env, "%s pointer offset %d is not allowed\n",
6810 			reg_type_str[type], reg->off);
6811 		return false;
6812 	}
6813 
6814 	if (smin == S64_MIN) {
6815 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6816 			reg_type_str[type]);
6817 		return false;
6818 	}
6819 
6820 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6821 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6822 			smin, reg_type_str[type]);
6823 		return false;
6824 	}
6825 
6826 	return true;
6827 }
6828 
6829 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6830 {
6831 	return &env->insn_aux_data[env->insn_idx];
6832 }
6833 
6834 enum {
6835 	REASON_BOUNDS	= -1,
6836 	REASON_TYPE	= -2,
6837 	REASON_PATHS	= -3,
6838 	REASON_LIMIT	= -4,
6839 	REASON_STACK	= -5,
6840 };
6841 
6842 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6843 			      u32 *alu_limit, bool mask_to_left)
6844 {
6845 	u32 max = 0, ptr_limit = 0;
6846 
6847 	switch (ptr_reg->type) {
6848 	case PTR_TO_STACK:
6849 		/* Offset 0 is out-of-bounds, but acceptable start for the
6850 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6851 		 * offset where we would need to deal with min/max bounds is
6852 		 * currently prohibited for unprivileged.
6853 		 */
6854 		max = MAX_BPF_STACK + mask_to_left;
6855 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6856 		break;
6857 	case PTR_TO_MAP_VALUE:
6858 		max = ptr_reg->map_ptr->value_size;
6859 		ptr_limit = (mask_to_left ?
6860 			     ptr_reg->smin_value :
6861 			     ptr_reg->umax_value) + ptr_reg->off;
6862 		break;
6863 	default:
6864 		return REASON_TYPE;
6865 	}
6866 
6867 	if (ptr_limit >= max)
6868 		return REASON_LIMIT;
6869 	*alu_limit = ptr_limit;
6870 	return 0;
6871 }
6872 
6873 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6874 				    const struct bpf_insn *insn)
6875 {
6876 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6877 }
6878 
6879 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6880 				       u32 alu_state, u32 alu_limit)
6881 {
6882 	/* If we arrived here from different branches with different
6883 	 * state or limits to sanitize, then this won't work.
6884 	 */
6885 	if (aux->alu_state &&
6886 	    (aux->alu_state != alu_state ||
6887 	     aux->alu_limit != alu_limit))
6888 		return REASON_PATHS;
6889 
6890 	/* Corresponding fixup done in do_misc_fixups(). */
6891 	aux->alu_state = alu_state;
6892 	aux->alu_limit = alu_limit;
6893 	return 0;
6894 }
6895 
6896 static int sanitize_val_alu(struct bpf_verifier_env *env,
6897 			    struct bpf_insn *insn)
6898 {
6899 	struct bpf_insn_aux_data *aux = cur_aux(env);
6900 
6901 	if (can_skip_alu_sanitation(env, insn))
6902 		return 0;
6903 
6904 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6905 }
6906 
6907 static bool sanitize_needed(u8 opcode)
6908 {
6909 	return opcode == BPF_ADD || opcode == BPF_SUB;
6910 }
6911 
6912 struct bpf_sanitize_info {
6913 	struct bpf_insn_aux_data aux;
6914 	bool mask_to_left;
6915 };
6916 
6917 static struct bpf_verifier_state *
6918 sanitize_speculative_path(struct bpf_verifier_env *env,
6919 			  const struct bpf_insn *insn,
6920 			  u32 next_idx, u32 curr_idx)
6921 {
6922 	struct bpf_verifier_state *branch;
6923 	struct bpf_reg_state *regs;
6924 
6925 	branch = push_stack(env, next_idx, curr_idx, true);
6926 	if (branch && insn) {
6927 		regs = branch->frame[branch->curframe]->regs;
6928 		if (BPF_SRC(insn->code) == BPF_K) {
6929 			mark_reg_unknown(env, regs, insn->dst_reg);
6930 		} else if (BPF_SRC(insn->code) == BPF_X) {
6931 			mark_reg_unknown(env, regs, insn->dst_reg);
6932 			mark_reg_unknown(env, regs, insn->src_reg);
6933 		}
6934 	}
6935 	return branch;
6936 }
6937 
6938 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6939 			    struct bpf_insn *insn,
6940 			    const struct bpf_reg_state *ptr_reg,
6941 			    const struct bpf_reg_state *off_reg,
6942 			    struct bpf_reg_state *dst_reg,
6943 			    struct bpf_sanitize_info *info,
6944 			    const bool commit_window)
6945 {
6946 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6947 	struct bpf_verifier_state *vstate = env->cur_state;
6948 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6949 	bool off_is_neg = off_reg->smin_value < 0;
6950 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6951 	u8 opcode = BPF_OP(insn->code);
6952 	u32 alu_state, alu_limit;
6953 	struct bpf_reg_state tmp;
6954 	bool ret;
6955 	int err;
6956 
6957 	if (can_skip_alu_sanitation(env, insn))
6958 		return 0;
6959 
6960 	/* We already marked aux for masking from non-speculative
6961 	 * paths, thus we got here in the first place. We only care
6962 	 * to explore bad access from here.
6963 	 */
6964 	if (vstate->speculative)
6965 		goto do_sim;
6966 
6967 	if (!commit_window) {
6968 		if (!tnum_is_const(off_reg->var_off) &&
6969 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6970 			return REASON_BOUNDS;
6971 
6972 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6973 				     (opcode == BPF_SUB && !off_is_neg);
6974 	}
6975 
6976 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6977 	if (err < 0)
6978 		return err;
6979 
6980 	if (commit_window) {
6981 		/* In commit phase we narrow the masking window based on
6982 		 * the observed pointer move after the simulated operation.
6983 		 */
6984 		alu_state = info->aux.alu_state;
6985 		alu_limit = abs(info->aux.alu_limit - alu_limit);
6986 	} else {
6987 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6988 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6989 		alu_state |= ptr_is_dst_reg ?
6990 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6991 
6992 		/* Limit pruning on unknown scalars to enable deep search for
6993 		 * potential masking differences from other program paths.
6994 		 */
6995 		if (!off_is_imm)
6996 			env->explore_alu_limits = true;
6997 	}
6998 
6999 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7000 	if (err < 0)
7001 		return err;
7002 do_sim:
7003 	/* If we're in commit phase, we're done here given we already
7004 	 * pushed the truncated dst_reg into the speculative verification
7005 	 * stack.
7006 	 *
7007 	 * Also, when register is a known constant, we rewrite register-based
7008 	 * operation to immediate-based, and thus do not need masking (and as
7009 	 * a consequence, do not need to simulate the zero-truncation either).
7010 	 */
7011 	if (commit_window || off_is_imm)
7012 		return 0;
7013 
7014 	/* Simulate and find potential out-of-bounds access under
7015 	 * speculative execution from truncation as a result of
7016 	 * masking when off was not within expected range. If off
7017 	 * sits in dst, then we temporarily need to move ptr there
7018 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7019 	 * for cases where we use K-based arithmetic in one direction
7020 	 * and truncated reg-based in the other in order to explore
7021 	 * bad access.
7022 	 */
7023 	if (!ptr_is_dst_reg) {
7024 		tmp = *dst_reg;
7025 		*dst_reg = *ptr_reg;
7026 	}
7027 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7028 					env->insn_idx);
7029 	if (!ptr_is_dst_reg && ret)
7030 		*dst_reg = tmp;
7031 	return !ret ? REASON_STACK : 0;
7032 }
7033 
7034 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7035 {
7036 	struct bpf_verifier_state *vstate = env->cur_state;
7037 
7038 	/* If we simulate paths under speculation, we don't update the
7039 	 * insn as 'seen' such that when we verify unreachable paths in
7040 	 * the non-speculative domain, sanitize_dead_code() can still
7041 	 * rewrite/sanitize them.
7042 	 */
7043 	if (!vstate->speculative)
7044 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7045 }
7046 
7047 static int sanitize_err(struct bpf_verifier_env *env,
7048 			const struct bpf_insn *insn, int reason,
7049 			const struct bpf_reg_state *off_reg,
7050 			const struct bpf_reg_state *dst_reg)
7051 {
7052 	static const char *err = "pointer arithmetic with it prohibited for !root";
7053 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7054 	u32 dst = insn->dst_reg, src = insn->src_reg;
7055 
7056 	switch (reason) {
7057 	case REASON_BOUNDS:
7058 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7059 			off_reg == dst_reg ? dst : src, err);
7060 		break;
7061 	case REASON_TYPE:
7062 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7063 			off_reg == dst_reg ? src : dst, err);
7064 		break;
7065 	case REASON_PATHS:
7066 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7067 			dst, op, err);
7068 		break;
7069 	case REASON_LIMIT:
7070 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7071 			dst, op, err);
7072 		break;
7073 	case REASON_STACK:
7074 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7075 			dst, err);
7076 		break;
7077 	default:
7078 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7079 			reason);
7080 		break;
7081 	}
7082 
7083 	return -EACCES;
7084 }
7085 
7086 /* check that stack access falls within stack limits and that 'reg' doesn't
7087  * have a variable offset.
7088  *
7089  * Variable offset is prohibited for unprivileged mode for simplicity since it
7090  * requires corresponding support in Spectre masking for stack ALU.  See also
7091  * retrieve_ptr_limit().
7092  *
7093  *
7094  * 'off' includes 'reg->off'.
7095  */
7096 static int check_stack_access_for_ptr_arithmetic(
7097 				struct bpf_verifier_env *env,
7098 				int regno,
7099 				const struct bpf_reg_state *reg,
7100 				int off)
7101 {
7102 	if (!tnum_is_const(reg->var_off)) {
7103 		char tn_buf[48];
7104 
7105 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7106 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7107 			regno, tn_buf, off);
7108 		return -EACCES;
7109 	}
7110 
7111 	if (off >= 0 || off < -MAX_BPF_STACK) {
7112 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7113 			"prohibited for !root; off=%d\n", regno, off);
7114 		return -EACCES;
7115 	}
7116 
7117 	return 0;
7118 }
7119 
7120 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7121 				 const struct bpf_insn *insn,
7122 				 const struct bpf_reg_state *dst_reg)
7123 {
7124 	u32 dst = insn->dst_reg;
7125 
7126 	/* For unprivileged we require that resulting offset must be in bounds
7127 	 * in order to be able to sanitize access later on.
7128 	 */
7129 	if (env->bypass_spec_v1)
7130 		return 0;
7131 
7132 	switch (dst_reg->type) {
7133 	case PTR_TO_STACK:
7134 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7135 					dst_reg->off + dst_reg->var_off.value))
7136 			return -EACCES;
7137 		break;
7138 	case PTR_TO_MAP_VALUE:
7139 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7140 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7141 				"prohibited for !root\n", dst);
7142 			return -EACCES;
7143 		}
7144 		break;
7145 	default:
7146 		break;
7147 	}
7148 
7149 	return 0;
7150 }
7151 
7152 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7153  * Caller should also handle BPF_MOV case separately.
7154  * If we return -EACCES, caller may want to try again treating pointer as a
7155  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7156  */
7157 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7158 				   struct bpf_insn *insn,
7159 				   const struct bpf_reg_state *ptr_reg,
7160 				   const struct bpf_reg_state *off_reg)
7161 {
7162 	struct bpf_verifier_state *vstate = env->cur_state;
7163 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7164 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7165 	bool known = tnum_is_const(off_reg->var_off);
7166 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7167 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7168 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7169 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7170 	struct bpf_sanitize_info info = {};
7171 	u8 opcode = BPF_OP(insn->code);
7172 	u32 dst = insn->dst_reg;
7173 	int ret;
7174 
7175 	dst_reg = &regs[dst];
7176 
7177 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7178 	    smin_val > smax_val || umin_val > umax_val) {
7179 		/* Taint dst register if offset had invalid bounds derived from
7180 		 * e.g. dead branches.
7181 		 */
7182 		__mark_reg_unknown(env, dst_reg);
7183 		return 0;
7184 	}
7185 
7186 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7187 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7188 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7189 			__mark_reg_unknown(env, dst_reg);
7190 			return 0;
7191 		}
7192 
7193 		verbose(env,
7194 			"R%d 32-bit pointer arithmetic prohibited\n",
7195 			dst);
7196 		return -EACCES;
7197 	}
7198 
7199 	switch (ptr_reg->type) {
7200 	case PTR_TO_MAP_VALUE_OR_NULL:
7201 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7202 			dst, reg_type_str[ptr_reg->type]);
7203 		return -EACCES;
7204 	case CONST_PTR_TO_MAP:
7205 		/* smin_val represents the known value */
7206 		if (known && smin_val == 0 && opcode == BPF_ADD)
7207 			break;
7208 		fallthrough;
7209 	case PTR_TO_PACKET_END:
7210 	case PTR_TO_SOCKET:
7211 	case PTR_TO_SOCKET_OR_NULL:
7212 	case PTR_TO_SOCK_COMMON:
7213 	case PTR_TO_SOCK_COMMON_OR_NULL:
7214 	case PTR_TO_TCP_SOCK:
7215 	case PTR_TO_TCP_SOCK_OR_NULL:
7216 	case PTR_TO_XDP_SOCK:
7217 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7218 			dst, reg_type_str[ptr_reg->type]);
7219 		return -EACCES;
7220 	default:
7221 		break;
7222 	}
7223 
7224 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7225 	 * The id may be overwritten later if we create a new variable offset.
7226 	 */
7227 	dst_reg->type = ptr_reg->type;
7228 	dst_reg->id = ptr_reg->id;
7229 
7230 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7231 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7232 		return -EINVAL;
7233 
7234 	/* pointer types do not carry 32-bit bounds at the moment. */
7235 	__mark_reg32_unbounded(dst_reg);
7236 
7237 	if (sanitize_needed(opcode)) {
7238 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7239 				       &info, false);
7240 		if (ret < 0)
7241 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7242 	}
7243 
7244 	switch (opcode) {
7245 	case BPF_ADD:
7246 		/* We can take a fixed offset as long as it doesn't overflow
7247 		 * the s32 'off' field
7248 		 */
7249 		if (known && (ptr_reg->off + smin_val ==
7250 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7251 			/* pointer += K.  Accumulate it into fixed offset */
7252 			dst_reg->smin_value = smin_ptr;
7253 			dst_reg->smax_value = smax_ptr;
7254 			dst_reg->umin_value = umin_ptr;
7255 			dst_reg->umax_value = umax_ptr;
7256 			dst_reg->var_off = ptr_reg->var_off;
7257 			dst_reg->off = ptr_reg->off + smin_val;
7258 			dst_reg->raw = ptr_reg->raw;
7259 			break;
7260 		}
7261 		/* A new variable offset is created.  Note that off_reg->off
7262 		 * == 0, since it's a scalar.
7263 		 * dst_reg gets the pointer type and since some positive
7264 		 * integer value was added to the pointer, give it a new 'id'
7265 		 * if it's a PTR_TO_PACKET.
7266 		 * this creates a new 'base' pointer, off_reg (variable) gets
7267 		 * added into the variable offset, and we copy the fixed offset
7268 		 * from ptr_reg.
7269 		 */
7270 		if (signed_add_overflows(smin_ptr, smin_val) ||
7271 		    signed_add_overflows(smax_ptr, smax_val)) {
7272 			dst_reg->smin_value = S64_MIN;
7273 			dst_reg->smax_value = S64_MAX;
7274 		} else {
7275 			dst_reg->smin_value = smin_ptr + smin_val;
7276 			dst_reg->smax_value = smax_ptr + smax_val;
7277 		}
7278 		if (umin_ptr + umin_val < umin_ptr ||
7279 		    umax_ptr + umax_val < umax_ptr) {
7280 			dst_reg->umin_value = 0;
7281 			dst_reg->umax_value = U64_MAX;
7282 		} else {
7283 			dst_reg->umin_value = umin_ptr + umin_val;
7284 			dst_reg->umax_value = umax_ptr + umax_val;
7285 		}
7286 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7287 		dst_reg->off = ptr_reg->off;
7288 		dst_reg->raw = ptr_reg->raw;
7289 		if (reg_is_pkt_pointer(ptr_reg)) {
7290 			dst_reg->id = ++env->id_gen;
7291 			/* something was added to pkt_ptr, set range to zero */
7292 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7293 		}
7294 		break;
7295 	case BPF_SUB:
7296 		if (dst_reg == off_reg) {
7297 			/* scalar -= pointer.  Creates an unknown scalar */
7298 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7299 				dst);
7300 			return -EACCES;
7301 		}
7302 		/* We don't allow subtraction from FP, because (according to
7303 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7304 		 * be able to deal with it.
7305 		 */
7306 		if (ptr_reg->type == PTR_TO_STACK) {
7307 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7308 				dst);
7309 			return -EACCES;
7310 		}
7311 		if (known && (ptr_reg->off - smin_val ==
7312 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7313 			/* pointer -= K.  Subtract it from fixed offset */
7314 			dst_reg->smin_value = smin_ptr;
7315 			dst_reg->smax_value = smax_ptr;
7316 			dst_reg->umin_value = umin_ptr;
7317 			dst_reg->umax_value = umax_ptr;
7318 			dst_reg->var_off = ptr_reg->var_off;
7319 			dst_reg->id = ptr_reg->id;
7320 			dst_reg->off = ptr_reg->off - smin_val;
7321 			dst_reg->raw = ptr_reg->raw;
7322 			break;
7323 		}
7324 		/* A new variable offset is created.  If the subtrahend is known
7325 		 * nonnegative, then any reg->range we had before is still good.
7326 		 */
7327 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7328 		    signed_sub_overflows(smax_ptr, smin_val)) {
7329 			/* Overflow possible, we know nothing */
7330 			dst_reg->smin_value = S64_MIN;
7331 			dst_reg->smax_value = S64_MAX;
7332 		} else {
7333 			dst_reg->smin_value = smin_ptr - smax_val;
7334 			dst_reg->smax_value = smax_ptr - smin_val;
7335 		}
7336 		if (umin_ptr < umax_val) {
7337 			/* Overflow possible, we know nothing */
7338 			dst_reg->umin_value = 0;
7339 			dst_reg->umax_value = U64_MAX;
7340 		} else {
7341 			/* Cannot overflow (as long as bounds are consistent) */
7342 			dst_reg->umin_value = umin_ptr - umax_val;
7343 			dst_reg->umax_value = umax_ptr - umin_val;
7344 		}
7345 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7346 		dst_reg->off = ptr_reg->off;
7347 		dst_reg->raw = ptr_reg->raw;
7348 		if (reg_is_pkt_pointer(ptr_reg)) {
7349 			dst_reg->id = ++env->id_gen;
7350 			/* something was added to pkt_ptr, set range to zero */
7351 			if (smin_val < 0)
7352 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7353 		}
7354 		break;
7355 	case BPF_AND:
7356 	case BPF_OR:
7357 	case BPF_XOR:
7358 		/* bitwise ops on pointers are troublesome, prohibit. */
7359 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7360 			dst, bpf_alu_string[opcode >> 4]);
7361 		return -EACCES;
7362 	default:
7363 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7364 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7365 			dst, bpf_alu_string[opcode >> 4]);
7366 		return -EACCES;
7367 	}
7368 
7369 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7370 		return -EINVAL;
7371 
7372 	__update_reg_bounds(dst_reg);
7373 	__reg_deduce_bounds(dst_reg);
7374 	__reg_bound_offset(dst_reg);
7375 
7376 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7377 		return -EACCES;
7378 	if (sanitize_needed(opcode)) {
7379 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7380 				       &info, true);
7381 		if (ret < 0)
7382 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7383 	}
7384 
7385 	return 0;
7386 }
7387 
7388 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7389 				 struct bpf_reg_state *src_reg)
7390 {
7391 	s32 smin_val = src_reg->s32_min_value;
7392 	s32 smax_val = src_reg->s32_max_value;
7393 	u32 umin_val = src_reg->u32_min_value;
7394 	u32 umax_val = src_reg->u32_max_value;
7395 
7396 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7397 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7398 		dst_reg->s32_min_value = S32_MIN;
7399 		dst_reg->s32_max_value = S32_MAX;
7400 	} else {
7401 		dst_reg->s32_min_value += smin_val;
7402 		dst_reg->s32_max_value += smax_val;
7403 	}
7404 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7405 	    dst_reg->u32_max_value + umax_val < umax_val) {
7406 		dst_reg->u32_min_value = 0;
7407 		dst_reg->u32_max_value = U32_MAX;
7408 	} else {
7409 		dst_reg->u32_min_value += umin_val;
7410 		dst_reg->u32_max_value += umax_val;
7411 	}
7412 }
7413 
7414 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7415 			       struct bpf_reg_state *src_reg)
7416 {
7417 	s64 smin_val = src_reg->smin_value;
7418 	s64 smax_val = src_reg->smax_value;
7419 	u64 umin_val = src_reg->umin_value;
7420 	u64 umax_val = src_reg->umax_value;
7421 
7422 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7423 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7424 		dst_reg->smin_value = S64_MIN;
7425 		dst_reg->smax_value = S64_MAX;
7426 	} else {
7427 		dst_reg->smin_value += smin_val;
7428 		dst_reg->smax_value += smax_val;
7429 	}
7430 	if (dst_reg->umin_value + umin_val < umin_val ||
7431 	    dst_reg->umax_value + umax_val < umax_val) {
7432 		dst_reg->umin_value = 0;
7433 		dst_reg->umax_value = U64_MAX;
7434 	} else {
7435 		dst_reg->umin_value += umin_val;
7436 		dst_reg->umax_value += umax_val;
7437 	}
7438 }
7439 
7440 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7441 				 struct bpf_reg_state *src_reg)
7442 {
7443 	s32 smin_val = src_reg->s32_min_value;
7444 	s32 smax_val = src_reg->s32_max_value;
7445 	u32 umin_val = src_reg->u32_min_value;
7446 	u32 umax_val = src_reg->u32_max_value;
7447 
7448 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7449 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7450 		/* Overflow possible, we know nothing */
7451 		dst_reg->s32_min_value = S32_MIN;
7452 		dst_reg->s32_max_value = S32_MAX;
7453 	} else {
7454 		dst_reg->s32_min_value -= smax_val;
7455 		dst_reg->s32_max_value -= smin_val;
7456 	}
7457 	if (dst_reg->u32_min_value < umax_val) {
7458 		/* Overflow possible, we know nothing */
7459 		dst_reg->u32_min_value = 0;
7460 		dst_reg->u32_max_value = U32_MAX;
7461 	} else {
7462 		/* Cannot overflow (as long as bounds are consistent) */
7463 		dst_reg->u32_min_value -= umax_val;
7464 		dst_reg->u32_max_value -= umin_val;
7465 	}
7466 }
7467 
7468 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7469 			       struct bpf_reg_state *src_reg)
7470 {
7471 	s64 smin_val = src_reg->smin_value;
7472 	s64 smax_val = src_reg->smax_value;
7473 	u64 umin_val = src_reg->umin_value;
7474 	u64 umax_val = src_reg->umax_value;
7475 
7476 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7477 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7478 		/* Overflow possible, we know nothing */
7479 		dst_reg->smin_value = S64_MIN;
7480 		dst_reg->smax_value = S64_MAX;
7481 	} else {
7482 		dst_reg->smin_value -= smax_val;
7483 		dst_reg->smax_value -= smin_val;
7484 	}
7485 	if (dst_reg->umin_value < umax_val) {
7486 		/* Overflow possible, we know nothing */
7487 		dst_reg->umin_value = 0;
7488 		dst_reg->umax_value = U64_MAX;
7489 	} else {
7490 		/* Cannot overflow (as long as bounds are consistent) */
7491 		dst_reg->umin_value -= umax_val;
7492 		dst_reg->umax_value -= umin_val;
7493 	}
7494 }
7495 
7496 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7497 				 struct bpf_reg_state *src_reg)
7498 {
7499 	s32 smin_val = src_reg->s32_min_value;
7500 	u32 umin_val = src_reg->u32_min_value;
7501 	u32 umax_val = src_reg->u32_max_value;
7502 
7503 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7504 		/* Ain't nobody got time to multiply that sign */
7505 		__mark_reg32_unbounded(dst_reg);
7506 		return;
7507 	}
7508 	/* Both values are positive, so we can work with unsigned and
7509 	 * copy the result to signed (unless it exceeds S32_MAX).
7510 	 */
7511 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7512 		/* Potential overflow, we know nothing */
7513 		__mark_reg32_unbounded(dst_reg);
7514 		return;
7515 	}
7516 	dst_reg->u32_min_value *= umin_val;
7517 	dst_reg->u32_max_value *= umax_val;
7518 	if (dst_reg->u32_max_value > S32_MAX) {
7519 		/* Overflow possible, we know nothing */
7520 		dst_reg->s32_min_value = S32_MIN;
7521 		dst_reg->s32_max_value = S32_MAX;
7522 	} else {
7523 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7524 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7525 	}
7526 }
7527 
7528 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7529 			       struct bpf_reg_state *src_reg)
7530 {
7531 	s64 smin_val = src_reg->smin_value;
7532 	u64 umin_val = src_reg->umin_value;
7533 	u64 umax_val = src_reg->umax_value;
7534 
7535 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7536 		/* Ain't nobody got time to multiply that sign */
7537 		__mark_reg64_unbounded(dst_reg);
7538 		return;
7539 	}
7540 	/* Both values are positive, so we can work with unsigned and
7541 	 * copy the result to signed (unless it exceeds S64_MAX).
7542 	 */
7543 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7544 		/* Potential overflow, we know nothing */
7545 		__mark_reg64_unbounded(dst_reg);
7546 		return;
7547 	}
7548 	dst_reg->umin_value *= umin_val;
7549 	dst_reg->umax_value *= umax_val;
7550 	if (dst_reg->umax_value > S64_MAX) {
7551 		/* Overflow possible, we know nothing */
7552 		dst_reg->smin_value = S64_MIN;
7553 		dst_reg->smax_value = S64_MAX;
7554 	} else {
7555 		dst_reg->smin_value = dst_reg->umin_value;
7556 		dst_reg->smax_value = dst_reg->umax_value;
7557 	}
7558 }
7559 
7560 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7561 				 struct bpf_reg_state *src_reg)
7562 {
7563 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7564 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7565 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7566 	s32 smin_val = src_reg->s32_min_value;
7567 	u32 umax_val = src_reg->u32_max_value;
7568 
7569 	if (src_known && dst_known) {
7570 		__mark_reg32_known(dst_reg, var32_off.value);
7571 		return;
7572 	}
7573 
7574 	/* We get our minimum from the var_off, since that's inherently
7575 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7576 	 */
7577 	dst_reg->u32_min_value = var32_off.value;
7578 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7579 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7580 		/* Lose signed bounds when ANDing negative numbers,
7581 		 * ain't nobody got time for that.
7582 		 */
7583 		dst_reg->s32_min_value = S32_MIN;
7584 		dst_reg->s32_max_value = S32_MAX;
7585 	} else {
7586 		/* ANDing two positives gives a positive, so safe to
7587 		 * cast result into s64.
7588 		 */
7589 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7590 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7591 	}
7592 }
7593 
7594 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7595 			       struct bpf_reg_state *src_reg)
7596 {
7597 	bool src_known = tnum_is_const(src_reg->var_off);
7598 	bool dst_known = tnum_is_const(dst_reg->var_off);
7599 	s64 smin_val = src_reg->smin_value;
7600 	u64 umax_val = src_reg->umax_value;
7601 
7602 	if (src_known && dst_known) {
7603 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7604 		return;
7605 	}
7606 
7607 	/* We get our minimum from the var_off, since that's inherently
7608 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7609 	 */
7610 	dst_reg->umin_value = dst_reg->var_off.value;
7611 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7612 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7613 		/* Lose signed bounds when ANDing negative numbers,
7614 		 * ain't nobody got time for that.
7615 		 */
7616 		dst_reg->smin_value = S64_MIN;
7617 		dst_reg->smax_value = S64_MAX;
7618 	} else {
7619 		/* ANDing two positives gives a positive, so safe to
7620 		 * cast result into s64.
7621 		 */
7622 		dst_reg->smin_value = dst_reg->umin_value;
7623 		dst_reg->smax_value = dst_reg->umax_value;
7624 	}
7625 	/* We may learn something more from the var_off */
7626 	__update_reg_bounds(dst_reg);
7627 }
7628 
7629 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7630 				struct bpf_reg_state *src_reg)
7631 {
7632 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7633 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7634 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7635 	s32 smin_val = src_reg->s32_min_value;
7636 	u32 umin_val = src_reg->u32_min_value;
7637 
7638 	if (src_known && dst_known) {
7639 		__mark_reg32_known(dst_reg, var32_off.value);
7640 		return;
7641 	}
7642 
7643 	/* We get our maximum from the var_off, and our minimum is the
7644 	 * maximum of the operands' minima
7645 	 */
7646 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7647 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7648 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7649 		/* Lose signed bounds when ORing negative numbers,
7650 		 * ain't nobody got time for that.
7651 		 */
7652 		dst_reg->s32_min_value = S32_MIN;
7653 		dst_reg->s32_max_value = S32_MAX;
7654 	} else {
7655 		/* ORing two positives gives a positive, so safe to
7656 		 * cast result into s64.
7657 		 */
7658 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7659 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7660 	}
7661 }
7662 
7663 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7664 			      struct bpf_reg_state *src_reg)
7665 {
7666 	bool src_known = tnum_is_const(src_reg->var_off);
7667 	bool dst_known = tnum_is_const(dst_reg->var_off);
7668 	s64 smin_val = src_reg->smin_value;
7669 	u64 umin_val = src_reg->umin_value;
7670 
7671 	if (src_known && dst_known) {
7672 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7673 		return;
7674 	}
7675 
7676 	/* We get our maximum from the var_off, and our minimum is the
7677 	 * maximum of the operands' minima
7678 	 */
7679 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7680 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7681 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7682 		/* Lose signed bounds when ORing negative numbers,
7683 		 * ain't nobody got time for that.
7684 		 */
7685 		dst_reg->smin_value = S64_MIN;
7686 		dst_reg->smax_value = S64_MAX;
7687 	} else {
7688 		/* ORing two positives gives a positive, so safe to
7689 		 * cast result into s64.
7690 		 */
7691 		dst_reg->smin_value = dst_reg->umin_value;
7692 		dst_reg->smax_value = dst_reg->umax_value;
7693 	}
7694 	/* We may learn something more from the var_off */
7695 	__update_reg_bounds(dst_reg);
7696 }
7697 
7698 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7699 				 struct bpf_reg_state *src_reg)
7700 {
7701 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7702 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7703 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7704 	s32 smin_val = src_reg->s32_min_value;
7705 
7706 	if (src_known && dst_known) {
7707 		__mark_reg32_known(dst_reg, var32_off.value);
7708 		return;
7709 	}
7710 
7711 	/* We get both minimum and maximum from the var32_off. */
7712 	dst_reg->u32_min_value = var32_off.value;
7713 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7714 
7715 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7716 		/* XORing two positive sign numbers gives a positive,
7717 		 * so safe to cast u32 result into s32.
7718 		 */
7719 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7720 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7721 	} else {
7722 		dst_reg->s32_min_value = S32_MIN;
7723 		dst_reg->s32_max_value = S32_MAX;
7724 	}
7725 }
7726 
7727 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7728 			       struct bpf_reg_state *src_reg)
7729 {
7730 	bool src_known = tnum_is_const(src_reg->var_off);
7731 	bool dst_known = tnum_is_const(dst_reg->var_off);
7732 	s64 smin_val = src_reg->smin_value;
7733 
7734 	if (src_known && dst_known) {
7735 		/* dst_reg->var_off.value has been updated earlier */
7736 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7737 		return;
7738 	}
7739 
7740 	/* We get both minimum and maximum from the var_off. */
7741 	dst_reg->umin_value = dst_reg->var_off.value;
7742 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7743 
7744 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7745 		/* XORing two positive sign numbers gives a positive,
7746 		 * so safe to cast u64 result into s64.
7747 		 */
7748 		dst_reg->smin_value = dst_reg->umin_value;
7749 		dst_reg->smax_value = dst_reg->umax_value;
7750 	} else {
7751 		dst_reg->smin_value = S64_MIN;
7752 		dst_reg->smax_value = S64_MAX;
7753 	}
7754 
7755 	__update_reg_bounds(dst_reg);
7756 }
7757 
7758 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7759 				   u64 umin_val, u64 umax_val)
7760 {
7761 	/* We lose all sign bit information (except what we can pick
7762 	 * up from var_off)
7763 	 */
7764 	dst_reg->s32_min_value = S32_MIN;
7765 	dst_reg->s32_max_value = S32_MAX;
7766 	/* If we might shift our top bit out, then we know nothing */
7767 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7768 		dst_reg->u32_min_value = 0;
7769 		dst_reg->u32_max_value = U32_MAX;
7770 	} else {
7771 		dst_reg->u32_min_value <<= umin_val;
7772 		dst_reg->u32_max_value <<= umax_val;
7773 	}
7774 }
7775 
7776 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7777 				 struct bpf_reg_state *src_reg)
7778 {
7779 	u32 umax_val = src_reg->u32_max_value;
7780 	u32 umin_val = src_reg->u32_min_value;
7781 	/* u32 alu operation will zext upper bits */
7782 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7783 
7784 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7785 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7786 	/* Not required but being careful mark reg64 bounds as unknown so
7787 	 * that we are forced to pick them up from tnum and zext later and
7788 	 * if some path skips this step we are still safe.
7789 	 */
7790 	__mark_reg64_unbounded(dst_reg);
7791 	__update_reg32_bounds(dst_reg);
7792 }
7793 
7794 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7795 				   u64 umin_val, u64 umax_val)
7796 {
7797 	/* Special case <<32 because it is a common compiler pattern to sign
7798 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7799 	 * positive we know this shift will also be positive so we can track
7800 	 * bounds correctly. Otherwise we lose all sign bit information except
7801 	 * what we can pick up from var_off. Perhaps we can generalize this
7802 	 * later to shifts of any length.
7803 	 */
7804 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7805 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7806 	else
7807 		dst_reg->smax_value = S64_MAX;
7808 
7809 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7810 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7811 	else
7812 		dst_reg->smin_value = S64_MIN;
7813 
7814 	/* If we might shift our top bit out, then we know nothing */
7815 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7816 		dst_reg->umin_value = 0;
7817 		dst_reg->umax_value = U64_MAX;
7818 	} else {
7819 		dst_reg->umin_value <<= umin_val;
7820 		dst_reg->umax_value <<= umax_val;
7821 	}
7822 }
7823 
7824 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7825 			       struct bpf_reg_state *src_reg)
7826 {
7827 	u64 umax_val = src_reg->umax_value;
7828 	u64 umin_val = src_reg->umin_value;
7829 
7830 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7831 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7832 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7833 
7834 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7835 	/* We may learn something more from the var_off */
7836 	__update_reg_bounds(dst_reg);
7837 }
7838 
7839 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7840 				 struct bpf_reg_state *src_reg)
7841 {
7842 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7843 	u32 umax_val = src_reg->u32_max_value;
7844 	u32 umin_val = src_reg->u32_min_value;
7845 
7846 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7847 	 * be negative, then either:
7848 	 * 1) src_reg might be zero, so the sign bit of the result is
7849 	 *    unknown, so we lose our signed bounds
7850 	 * 2) it's known negative, thus the unsigned bounds capture the
7851 	 *    signed bounds
7852 	 * 3) the signed bounds cross zero, so they tell us nothing
7853 	 *    about the result
7854 	 * If the value in dst_reg is known nonnegative, then again the
7855 	 * unsigned bounds capture the signed bounds.
7856 	 * Thus, in all cases it suffices to blow away our signed bounds
7857 	 * and rely on inferring new ones from the unsigned bounds and
7858 	 * var_off of the result.
7859 	 */
7860 	dst_reg->s32_min_value = S32_MIN;
7861 	dst_reg->s32_max_value = S32_MAX;
7862 
7863 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7864 	dst_reg->u32_min_value >>= umax_val;
7865 	dst_reg->u32_max_value >>= umin_val;
7866 
7867 	__mark_reg64_unbounded(dst_reg);
7868 	__update_reg32_bounds(dst_reg);
7869 }
7870 
7871 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7872 			       struct bpf_reg_state *src_reg)
7873 {
7874 	u64 umax_val = src_reg->umax_value;
7875 	u64 umin_val = src_reg->umin_value;
7876 
7877 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7878 	 * be negative, then either:
7879 	 * 1) src_reg might be zero, so the sign bit of the result is
7880 	 *    unknown, so we lose our signed bounds
7881 	 * 2) it's known negative, thus the unsigned bounds capture the
7882 	 *    signed bounds
7883 	 * 3) the signed bounds cross zero, so they tell us nothing
7884 	 *    about the result
7885 	 * If the value in dst_reg is known nonnegative, then again the
7886 	 * unsigned bounds capture the signed bounds.
7887 	 * Thus, in all cases it suffices to blow away our signed bounds
7888 	 * and rely on inferring new ones from the unsigned bounds and
7889 	 * var_off of the result.
7890 	 */
7891 	dst_reg->smin_value = S64_MIN;
7892 	dst_reg->smax_value = S64_MAX;
7893 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7894 	dst_reg->umin_value >>= umax_val;
7895 	dst_reg->umax_value >>= umin_val;
7896 
7897 	/* Its not easy to operate on alu32 bounds here because it depends
7898 	 * on bits being shifted in. Take easy way out and mark unbounded
7899 	 * so we can recalculate later from tnum.
7900 	 */
7901 	__mark_reg32_unbounded(dst_reg);
7902 	__update_reg_bounds(dst_reg);
7903 }
7904 
7905 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7906 				  struct bpf_reg_state *src_reg)
7907 {
7908 	u64 umin_val = src_reg->u32_min_value;
7909 
7910 	/* Upon reaching here, src_known is true and
7911 	 * umax_val is equal to umin_val.
7912 	 */
7913 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7914 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7915 
7916 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7917 
7918 	/* blow away the dst_reg umin_value/umax_value and rely on
7919 	 * dst_reg var_off to refine the result.
7920 	 */
7921 	dst_reg->u32_min_value = 0;
7922 	dst_reg->u32_max_value = U32_MAX;
7923 
7924 	__mark_reg64_unbounded(dst_reg);
7925 	__update_reg32_bounds(dst_reg);
7926 }
7927 
7928 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7929 				struct bpf_reg_state *src_reg)
7930 {
7931 	u64 umin_val = src_reg->umin_value;
7932 
7933 	/* Upon reaching here, src_known is true and umax_val is equal
7934 	 * to umin_val.
7935 	 */
7936 	dst_reg->smin_value >>= umin_val;
7937 	dst_reg->smax_value >>= umin_val;
7938 
7939 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7940 
7941 	/* blow away the dst_reg umin_value/umax_value and rely on
7942 	 * dst_reg var_off to refine the result.
7943 	 */
7944 	dst_reg->umin_value = 0;
7945 	dst_reg->umax_value = U64_MAX;
7946 
7947 	/* Its not easy to operate on alu32 bounds here because it depends
7948 	 * on bits being shifted in from upper 32-bits. Take easy way out
7949 	 * and mark unbounded so we can recalculate later from tnum.
7950 	 */
7951 	__mark_reg32_unbounded(dst_reg);
7952 	__update_reg_bounds(dst_reg);
7953 }
7954 
7955 /* WARNING: This function does calculations on 64-bit values, but the actual
7956  * execution may occur on 32-bit values. Therefore, things like bitshifts
7957  * need extra checks in the 32-bit case.
7958  */
7959 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7960 				      struct bpf_insn *insn,
7961 				      struct bpf_reg_state *dst_reg,
7962 				      struct bpf_reg_state src_reg)
7963 {
7964 	struct bpf_reg_state *regs = cur_regs(env);
7965 	u8 opcode = BPF_OP(insn->code);
7966 	bool src_known;
7967 	s64 smin_val, smax_val;
7968 	u64 umin_val, umax_val;
7969 	s32 s32_min_val, s32_max_val;
7970 	u32 u32_min_val, u32_max_val;
7971 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7972 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7973 	int ret;
7974 
7975 	smin_val = src_reg.smin_value;
7976 	smax_val = src_reg.smax_value;
7977 	umin_val = src_reg.umin_value;
7978 	umax_val = src_reg.umax_value;
7979 
7980 	s32_min_val = src_reg.s32_min_value;
7981 	s32_max_val = src_reg.s32_max_value;
7982 	u32_min_val = src_reg.u32_min_value;
7983 	u32_max_val = src_reg.u32_max_value;
7984 
7985 	if (alu32) {
7986 		src_known = tnum_subreg_is_const(src_reg.var_off);
7987 		if ((src_known &&
7988 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7989 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7990 			/* Taint dst register if offset had invalid bounds
7991 			 * derived from e.g. dead branches.
7992 			 */
7993 			__mark_reg_unknown(env, dst_reg);
7994 			return 0;
7995 		}
7996 	} else {
7997 		src_known = tnum_is_const(src_reg.var_off);
7998 		if ((src_known &&
7999 		     (smin_val != smax_val || umin_val != umax_val)) ||
8000 		    smin_val > smax_val || umin_val > umax_val) {
8001 			/* Taint dst register if offset had invalid bounds
8002 			 * derived from e.g. dead branches.
8003 			 */
8004 			__mark_reg_unknown(env, dst_reg);
8005 			return 0;
8006 		}
8007 	}
8008 
8009 	if (!src_known &&
8010 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8011 		__mark_reg_unknown(env, dst_reg);
8012 		return 0;
8013 	}
8014 
8015 	if (sanitize_needed(opcode)) {
8016 		ret = sanitize_val_alu(env, insn);
8017 		if (ret < 0)
8018 			return sanitize_err(env, insn, ret, NULL, NULL);
8019 	}
8020 
8021 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8022 	 * There are two classes of instructions: The first class we track both
8023 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8024 	 * greatest amount of precision when alu operations are mixed with jmp32
8025 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8026 	 * and BPF_OR. This is possible because these ops have fairly easy to
8027 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8028 	 * See alu32 verifier tests for examples. The second class of
8029 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8030 	 * with regards to tracking sign/unsigned bounds because the bits may
8031 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8032 	 * the reg unbounded in the subreg bound space and use the resulting
8033 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8034 	 */
8035 	switch (opcode) {
8036 	case BPF_ADD:
8037 		scalar32_min_max_add(dst_reg, &src_reg);
8038 		scalar_min_max_add(dst_reg, &src_reg);
8039 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8040 		break;
8041 	case BPF_SUB:
8042 		scalar32_min_max_sub(dst_reg, &src_reg);
8043 		scalar_min_max_sub(dst_reg, &src_reg);
8044 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8045 		break;
8046 	case BPF_MUL:
8047 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8048 		scalar32_min_max_mul(dst_reg, &src_reg);
8049 		scalar_min_max_mul(dst_reg, &src_reg);
8050 		break;
8051 	case BPF_AND:
8052 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8053 		scalar32_min_max_and(dst_reg, &src_reg);
8054 		scalar_min_max_and(dst_reg, &src_reg);
8055 		break;
8056 	case BPF_OR:
8057 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8058 		scalar32_min_max_or(dst_reg, &src_reg);
8059 		scalar_min_max_or(dst_reg, &src_reg);
8060 		break;
8061 	case BPF_XOR:
8062 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8063 		scalar32_min_max_xor(dst_reg, &src_reg);
8064 		scalar_min_max_xor(dst_reg, &src_reg);
8065 		break;
8066 	case BPF_LSH:
8067 		if (umax_val >= insn_bitness) {
8068 			/* Shifts greater than 31 or 63 are undefined.
8069 			 * This includes shifts by a negative number.
8070 			 */
8071 			mark_reg_unknown(env, regs, insn->dst_reg);
8072 			break;
8073 		}
8074 		if (alu32)
8075 			scalar32_min_max_lsh(dst_reg, &src_reg);
8076 		else
8077 			scalar_min_max_lsh(dst_reg, &src_reg);
8078 		break;
8079 	case BPF_RSH:
8080 		if (umax_val >= insn_bitness) {
8081 			/* Shifts greater than 31 or 63 are undefined.
8082 			 * This includes shifts by a negative number.
8083 			 */
8084 			mark_reg_unknown(env, regs, insn->dst_reg);
8085 			break;
8086 		}
8087 		if (alu32)
8088 			scalar32_min_max_rsh(dst_reg, &src_reg);
8089 		else
8090 			scalar_min_max_rsh(dst_reg, &src_reg);
8091 		break;
8092 	case BPF_ARSH:
8093 		if (umax_val >= insn_bitness) {
8094 			/* Shifts greater than 31 or 63 are undefined.
8095 			 * This includes shifts by a negative number.
8096 			 */
8097 			mark_reg_unknown(env, regs, insn->dst_reg);
8098 			break;
8099 		}
8100 		if (alu32)
8101 			scalar32_min_max_arsh(dst_reg, &src_reg);
8102 		else
8103 			scalar_min_max_arsh(dst_reg, &src_reg);
8104 		break;
8105 	default:
8106 		mark_reg_unknown(env, regs, insn->dst_reg);
8107 		break;
8108 	}
8109 
8110 	/* ALU32 ops are zero extended into 64bit register */
8111 	if (alu32)
8112 		zext_32_to_64(dst_reg);
8113 
8114 	__update_reg_bounds(dst_reg);
8115 	__reg_deduce_bounds(dst_reg);
8116 	__reg_bound_offset(dst_reg);
8117 	return 0;
8118 }
8119 
8120 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8121  * and var_off.
8122  */
8123 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8124 				   struct bpf_insn *insn)
8125 {
8126 	struct bpf_verifier_state *vstate = env->cur_state;
8127 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8128 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8129 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8130 	u8 opcode = BPF_OP(insn->code);
8131 	int err;
8132 
8133 	dst_reg = &regs[insn->dst_reg];
8134 	src_reg = NULL;
8135 	if (dst_reg->type != SCALAR_VALUE)
8136 		ptr_reg = dst_reg;
8137 	else
8138 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8139 		 * incorrectly propagated into other registers by find_equal_scalars()
8140 		 */
8141 		dst_reg->id = 0;
8142 	if (BPF_SRC(insn->code) == BPF_X) {
8143 		src_reg = &regs[insn->src_reg];
8144 		if (src_reg->type != SCALAR_VALUE) {
8145 			if (dst_reg->type != SCALAR_VALUE) {
8146 				/* Combining two pointers by any ALU op yields
8147 				 * an arbitrary scalar. Disallow all math except
8148 				 * pointer subtraction
8149 				 */
8150 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8151 					mark_reg_unknown(env, regs, insn->dst_reg);
8152 					return 0;
8153 				}
8154 				verbose(env, "R%d pointer %s pointer prohibited\n",
8155 					insn->dst_reg,
8156 					bpf_alu_string[opcode >> 4]);
8157 				return -EACCES;
8158 			} else {
8159 				/* scalar += pointer
8160 				 * This is legal, but we have to reverse our
8161 				 * src/dest handling in computing the range
8162 				 */
8163 				err = mark_chain_precision(env, insn->dst_reg);
8164 				if (err)
8165 					return err;
8166 				return adjust_ptr_min_max_vals(env, insn,
8167 							       src_reg, dst_reg);
8168 			}
8169 		} else if (ptr_reg) {
8170 			/* pointer += scalar */
8171 			err = mark_chain_precision(env, insn->src_reg);
8172 			if (err)
8173 				return err;
8174 			return adjust_ptr_min_max_vals(env, insn,
8175 						       dst_reg, src_reg);
8176 		}
8177 	} else {
8178 		/* Pretend the src is a reg with a known value, since we only
8179 		 * need to be able to read from this state.
8180 		 */
8181 		off_reg.type = SCALAR_VALUE;
8182 		__mark_reg_known(&off_reg, insn->imm);
8183 		src_reg = &off_reg;
8184 		if (ptr_reg) /* pointer += K */
8185 			return adjust_ptr_min_max_vals(env, insn,
8186 						       ptr_reg, src_reg);
8187 	}
8188 
8189 	/* Got here implies adding two SCALAR_VALUEs */
8190 	if (WARN_ON_ONCE(ptr_reg)) {
8191 		print_verifier_state(env, state);
8192 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8193 		return -EINVAL;
8194 	}
8195 	if (WARN_ON(!src_reg)) {
8196 		print_verifier_state(env, state);
8197 		verbose(env, "verifier internal error: no src_reg\n");
8198 		return -EINVAL;
8199 	}
8200 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8201 }
8202 
8203 /* check validity of 32-bit and 64-bit arithmetic operations */
8204 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8205 {
8206 	struct bpf_reg_state *regs = cur_regs(env);
8207 	u8 opcode = BPF_OP(insn->code);
8208 	int err;
8209 
8210 	if (opcode == BPF_END || opcode == BPF_NEG) {
8211 		if (opcode == BPF_NEG) {
8212 			if (BPF_SRC(insn->code) != 0 ||
8213 			    insn->src_reg != BPF_REG_0 ||
8214 			    insn->off != 0 || insn->imm != 0) {
8215 				verbose(env, "BPF_NEG uses reserved fields\n");
8216 				return -EINVAL;
8217 			}
8218 		} else {
8219 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8220 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8221 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8222 				verbose(env, "BPF_END uses reserved fields\n");
8223 				return -EINVAL;
8224 			}
8225 		}
8226 
8227 		/* check src operand */
8228 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8229 		if (err)
8230 			return err;
8231 
8232 		if (is_pointer_value(env, insn->dst_reg)) {
8233 			verbose(env, "R%d pointer arithmetic prohibited\n",
8234 				insn->dst_reg);
8235 			return -EACCES;
8236 		}
8237 
8238 		/* check dest operand */
8239 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8240 		if (err)
8241 			return err;
8242 
8243 	} else if (opcode == BPF_MOV) {
8244 
8245 		if (BPF_SRC(insn->code) == BPF_X) {
8246 			if (insn->imm != 0 || insn->off != 0) {
8247 				verbose(env, "BPF_MOV uses reserved fields\n");
8248 				return -EINVAL;
8249 			}
8250 
8251 			/* check src operand */
8252 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8253 			if (err)
8254 				return err;
8255 		} else {
8256 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8257 				verbose(env, "BPF_MOV uses reserved fields\n");
8258 				return -EINVAL;
8259 			}
8260 		}
8261 
8262 		/* check dest operand, mark as required later */
8263 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8264 		if (err)
8265 			return err;
8266 
8267 		if (BPF_SRC(insn->code) == BPF_X) {
8268 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8269 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8270 
8271 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8272 				/* case: R1 = R2
8273 				 * copy register state to dest reg
8274 				 */
8275 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8276 					/* Assign src and dst registers the same ID
8277 					 * that will be used by find_equal_scalars()
8278 					 * to propagate min/max range.
8279 					 */
8280 					src_reg->id = ++env->id_gen;
8281 				*dst_reg = *src_reg;
8282 				dst_reg->live |= REG_LIVE_WRITTEN;
8283 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8284 			} else {
8285 				/* R1 = (u32) R2 */
8286 				if (is_pointer_value(env, insn->src_reg)) {
8287 					verbose(env,
8288 						"R%d partial copy of pointer\n",
8289 						insn->src_reg);
8290 					return -EACCES;
8291 				} else if (src_reg->type == SCALAR_VALUE) {
8292 					*dst_reg = *src_reg;
8293 					/* Make sure ID is cleared otherwise
8294 					 * dst_reg min/max could be incorrectly
8295 					 * propagated into src_reg by find_equal_scalars()
8296 					 */
8297 					dst_reg->id = 0;
8298 					dst_reg->live |= REG_LIVE_WRITTEN;
8299 					dst_reg->subreg_def = env->insn_idx + 1;
8300 				} else {
8301 					mark_reg_unknown(env, regs,
8302 							 insn->dst_reg);
8303 				}
8304 				zext_32_to_64(dst_reg);
8305 			}
8306 		} else {
8307 			/* case: R = imm
8308 			 * remember the value we stored into this reg
8309 			 */
8310 			/* clear any state __mark_reg_known doesn't set */
8311 			mark_reg_unknown(env, regs, insn->dst_reg);
8312 			regs[insn->dst_reg].type = SCALAR_VALUE;
8313 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8314 				__mark_reg_known(regs + insn->dst_reg,
8315 						 insn->imm);
8316 			} else {
8317 				__mark_reg_known(regs + insn->dst_reg,
8318 						 (u32)insn->imm);
8319 			}
8320 		}
8321 
8322 	} else if (opcode > BPF_END) {
8323 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8324 		return -EINVAL;
8325 
8326 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8327 
8328 		if (BPF_SRC(insn->code) == BPF_X) {
8329 			if (insn->imm != 0 || insn->off != 0) {
8330 				verbose(env, "BPF_ALU uses reserved fields\n");
8331 				return -EINVAL;
8332 			}
8333 			/* check src1 operand */
8334 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8335 			if (err)
8336 				return err;
8337 		} else {
8338 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8339 				verbose(env, "BPF_ALU uses reserved fields\n");
8340 				return -EINVAL;
8341 			}
8342 		}
8343 
8344 		/* check src2 operand */
8345 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8346 		if (err)
8347 			return err;
8348 
8349 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8350 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8351 			verbose(env, "div by zero\n");
8352 			return -EINVAL;
8353 		}
8354 
8355 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8356 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8357 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8358 
8359 			if (insn->imm < 0 || insn->imm >= size) {
8360 				verbose(env, "invalid shift %d\n", insn->imm);
8361 				return -EINVAL;
8362 			}
8363 		}
8364 
8365 		/* check dest operand */
8366 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8367 		if (err)
8368 			return err;
8369 
8370 		return adjust_reg_min_max_vals(env, insn);
8371 	}
8372 
8373 	return 0;
8374 }
8375 
8376 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8377 				     struct bpf_reg_state *dst_reg,
8378 				     enum bpf_reg_type type, int new_range)
8379 {
8380 	struct bpf_reg_state *reg;
8381 	int i;
8382 
8383 	for (i = 0; i < MAX_BPF_REG; i++) {
8384 		reg = &state->regs[i];
8385 		if (reg->type == type && reg->id == dst_reg->id)
8386 			/* keep the maximum range already checked */
8387 			reg->range = max(reg->range, new_range);
8388 	}
8389 
8390 	bpf_for_each_spilled_reg(i, state, reg) {
8391 		if (!reg)
8392 			continue;
8393 		if (reg->type == type && reg->id == dst_reg->id)
8394 			reg->range = max(reg->range, new_range);
8395 	}
8396 }
8397 
8398 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8399 				   struct bpf_reg_state *dst_reg,
8400 				   enum bpf_reg_type type,
8401 				   bool range_right_open)
8402 {
8403 	int new_range, i;
8404 
8405 	if (dst_reg->off < 0 ||
8406 	    (dst_reg->off == 0 && range_right_open))
8407 		/* This doesn't give us any range */
8408 		return;
8409 
8410 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8411 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8412 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8413 		 * than pkt_end, but that's because it's also less than pkt.
8414 		 */
8415 		return;
8416 
8417 	new_range = dst_reg->off;
8418 	if (range_right_open)
8419 		new_range--;
8420 
8421 	/* Examples for register markings:
8422 	 *
8423 	 * pkt_data in dst register:
8424 	 *
8425 	 *   r2 = r3;
8426 	 *   r2 += 8;
8427 	 *   if (r2 > pkt_end) goto <handle exception>
8428 	 *   <access okay>
8429 	 *
8430 	 *   r2 = r3;
8431 	 *   r2 += 8;
8432 	 *   if (r2 < pkt_end) goto <access okay>
8433 	 *   <handle exception>
8434 	 *
8435 	 *   Where:
8436 	 *     r2 == dst_reg, pkt_end == src_reg
8437 	 *     r2=pkt(id=n,off=8,r=0)
8438 	 *     r3=pkt(id=n,off=0,r=0)
8439 	 *
8440 	 * pkt_data in src register:
8441 	 *
8442 	 *   r2 = r3;
8443 	 *   r2 += 8;
8444 	 *   if (pkt_end >= r2) goto <access okay>
8445 	 *   <handle exception>
8446 	 *
8447 	 *   r2 = r3;
8448 	 *   r2 += 8;
8449 	 *   if (pkt_end <= r2) goto <handle exception>
8450 	 *   <access okay>
8451 	 *
8452 	 *   Where:
8453 	 *     pkt_end == dst_reg, r2 == src_reg
8454 	 *     r2=pkt(id=n,off=8,r=0)
8455 	 *     r3=pkt(id=n,off=0,r=0)
8456 	 *
8457 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8458 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8459 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8460 	 * the check.
8461 	 */
8462 
8463 	/* If our ids match, then we must have the same max_value.  And we
8464 	 * don't care about the other reg's fixed offset, since if it's too big
8465 	 * the range won't allow anything.
8466 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8467 	 */
8468 	for (i = 0; i <= vstate->curframe; i++)
8469 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8470 					 new_range);
8471 }
8472 
8473 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8474 {
8475 	struct tnum subreg = tnum_subreg(reg->var_off);
8476 	s32 sval = (s32)val;
8477 
8478 	switch (opcode) {
8479 	case BPF_JEQ:
8480 		if (tnum_is_const(subreg))
8481 			return !!tnum_equals_const(subreg, val);
8482 		break;
8483 	case BPF_JNE:
8484 		if (tnum_is_const(subreg))
8485 			return !tnum_equals_const(subreg, val);
8486 		break;
8487 	case BPF_JSET:
8488 		if ((~subreg.mask & subreg.value) & val)
8489 			return 1;
8490 		if (!((subreg.mask | subreg.value) & val))
8491 			return 0;
8492 		break;
8493 	case BPF_JGT:
8494 		if (reg->u32_min_value > val)
8495 			return 1;
8496 		else if (reg->u32_max_value <= val)
8497 			return 0;
8498 		break;
8499 	case BPF_JSGT:
8500 		if (reg->s32_min_value > sval)
8501 			return 1;
8502 		else if (reg->s32_max_value <= sval)
8503 			return 0;
8504 		break;
8505 	case BPF_JLT:
8506 		if (reg->u32_max_value < val)
8507 			return 1;
8508 		else if (reg->u32_min_value >= val)
8509 			return 0;
8510 		break;
8511 	case BPF_JSLT:
8512 		if (reg->s32_max_value < sval)
8513 			return 1;
8514 		else if (reg->s32_min_value >= sval)
8515 			return 0;
8516 		break;
8517 	case BPF_JGE:
8518 		if (reg->u32_min_value >= val)
8519 			return 1;
8520 		else if (reg->u32_max_value < val)
8521 			return 0;
8522 		break;
8523 	case BPF_JSGE:
8524 		if (reg->s32_min_value >= sval)
8525 			return 1;
8526 		else if (reg->s32_max_value < sval)
8527 			return 0;
8528 		break;
8529 	case BPF_JLE:
8530 		if (reg->u32_max_value <= val)
8531 			return 1;
8532 		else if (reg->u32_min_value > val)
8533 			return 0;
8534 		break;
8535 	case BPF_JSLE:
8536 		if (reg->s32_max_value <= sval)
8537 			return 1;
8538 		else if (reg->s32_min_value > sval)
8539 			return 0;
8540 		break;
8541 	}
8542 
8543 	return -1;
8544 }
8545 
8546 
8547 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8548 {
8549 	s64 sval = (s64)val;
8550 
8551 	switch (opcode) {
8552 	case BPF_JEQ:
8553 		if (tnum_is_const(reg->var_off))
8554 			return !!tnum_equals_const(reg->var_off, val);
8555 		break;
8556 	case BPF_JNE:
8557 		if (tnum_is_const(reg->var_off))
8558 			return !tnum_equals_const(reg->var_off, val);
8559 		break;
8560 	case BPF_JSET:
8561 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8562 			return 1;
8563 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8564 			return 0;
8565 		break;
8566 	case BPF_JGT:
8567 		if (reg->umin_value > val)
8568 			return 1;
8569 		else if (reg->umax_value <= val)
8570 			return 0;
8571 		break;
8572 	case BPF_JSGT:
8573 		if (reg->smin_value > sval)
8574 			return 1;
8575 		else if (reg->smax_value <= sval)
8576 			return 0;
8577 		break;
8578 	case BPF_JLT:
8579 		if (reg->umax_value < val)
8580 			return 1;
8581 		else if (reg->umin_value >= val)
8582 			return 0;
8583 		break;
8584 	case BPF_JSLT:
8585 		if (reg->smax_value < sval)
8586 			return 1;
8587 		else if (reg->smin_value >= sval)
8588 			return 0;
8589 		break;
8590 	case BPF_JGE:
8591 		if (reg->umin_value >= val)
8592 			return 1;
8593 		else if (reg->umax_value < val)
8594 			return 0;
8595 		break;
8596 	case BPF_JSGE:
8597 		if (reg->smin_value >= sval)
8598 			return 1;
8599 		else if (reg->smax_value < sval)
8600 			return 0;
8601 		break;
8602 	case BPF_JLE:
8603 		if (reg->umax_value <= val)
8604 			return 1;
8605 		else if (reg->umin_value > val)
8606 			return 0;
8607 		break;
8608 	case BPF_JSLE:
8609 		if (reg->smax_value <= sval)
8610 			return 1;
8611 		else if (reg->smin_value > sval)
8612 			return 0;
8613 		break;
8614 	}
8615 
8616 	return -1;
8617 }
8618 
8619 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8620  * and return:
8621  *  1 - branch will be taken and "goto target" will be executed
8622  *  0 - branch will not be taken and fall-through to next insn
8623  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8624  *      range [0,10]
8625  */
8626 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8627 			   bool is_jmp32)
8628 {
8629 	if (__is_pointer_value(false, reg)) {
8630 		if (!reg_type_not_null(reg->type))
8631 			return -1;
8632 
8633 		/* If pointer is valid tests against zero will fail so we can
8634 		 * use this to direct branch taken.
8635 		 */
8636 		if (val != 0)
8637 			return -1;
8638 
8639 		switch (opcode) {
8640 		case BPF_JEQ:
8641 			return 0;
8642 		case BPF_JNE:
8643 			return 1;
8644 		default:
8645 			return -1;
8646 		}
8647 	}
8648 
8649 	if (is_jmp32)
8650 		return is_branch32_taken(reg, val, opcode);
8651 	return is_branch64_taken(reg, val, opcode);
8652 }
8653 
8654 static int flip_opcode(u32 opcode)
8655 {
8656 	/* How can we transform "a <op> b" into "b <op> a"? */
8657 	static const u8 opcode_flip[16] = {
8658 		/* these stay the same */
8659 		[BPF_JEQ  >> 4] = BPF_JEQ,
8660 		[BPF_JNE  >> 4] = BPF_JNE,
8661 		[BPF_JSET >> 4] = BPF_JSET,
8662 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8663 		[BPF_JGE  >> 4] = BPF_JLE,
8664 		[BPF_JGT  >> 4] = BPF_JLT,
8665 		[BPF_JLE  >> 4] = BPF_JGE,
8666 		[BPF_JLT  >> 4] = BPF_JGT,
8667 		[BPF_JSGE >> 4] = BPF_JSLE,
8668 		[BPF_JSGT >> 4] = BPF_JSLT,
8669 		[BPF_JSLE >> 4] = BPF_JSGE,
8670 		[BPF_JSLT >> 4] = BPF_JSGT
8671 	};
8672 	return opcode_flip[opcode >> 4];
8673 }
8674 
8675 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8676 				   struct bpf_reg_state *src_reg,
8677 				   u8 opcode)
8678 {
8679 	struct bpf_reg_state *pkt;
8680 
8681 	if (src_reg->type == PTR_TO_PACKET_END) {
8682 		pkt = dst_reg;
8683 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8684 		pkt = src_reg;
8685 		opcode = flip_opcode(opcode);
8686 	} else {
8687 		return -1;
8688 	}
8689 
8690 	if (pkt->range >= 0)
8691 		return -1;
8692 
8693 	switch (opcode) {
8694 	case BPF_JLE:
8695 		/* pkt <= pkt_end */
8696 		fallthrough;
8697 	case BPF_JGT:
8698 		/* pkt > pkt_end */
8699 		if (pkt->range == BEYOND_PKT_END)
8700 			/* pkt has at last one extra byte beyond pkt_end */
8701 			return opcode == BPF_JGT;
8702 		break;
8703 	case BPF_JLT:
8704 		/* pkt < pkt_end */
8705 		fallthrough;
8706 	case BPF_JGE:
8707 		/* pkt >= pkt_end */
8708 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8709 			return opcode == BPF_JGE;
8710 		break;
8711 	}
8712 	return -1;
8713 }
8714 
8715 /* Adjusts the register min/max values in the case that the dst_reg is the
8716  * variable register that we are working on, and src_reg is a constant or we're
8717  * simply doing a BPF_K check.
8718  * In JEQ/JNE cases we also adjust the var_off values.
8719  */
8720 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8721 			    struct bpf_reg_state *false_reg,
8722 			    u64 val, u32 val32,
8723 			    u8 opcode, bool is_jmp32)
8724 {
8725 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8726 	struct tnum false_64off = false_reg->var_off;
8727 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8728 	struct tnum true_64off = true_reg->var_off;
8729 	s64 sval = (s64)val;
8730 	s32 sval32 = (s32)val32;
8731 
8732 	/* If the dst_reg is a pointer, we can't learn anything about its
8733 	 * variable offset from the compare (unless src_reg were a pointer into
8734 	 * the same object, but we don't bother with that.
8735 	 * Since false_reg and true_reg have the same type by construction, we
8736 	 * only need to check one of them for pointerness.
8737 	 */
8738 	if (__is_pointer_value(false, false_reg))
8739 		return;
8740 
8741 	switch (opcode) {
8742 	case BPF_JEQ:
8743 	case BPF_JNE:
8744 	{
8745 		struct bpf_reg_state *reg =
8746 			opcode == BPF_JEQ ? true_reg : false_reg;
8747 
8748 		/* JEQ/JNE comparison doesn't change the register equivalence.
8749 		 * r1 = r2;
8750 		 * if (r1 == 42) goto label;
8751 		 * ...
8752 		 * label: // here both r1 and r2 are known to be 42.
8753 		 *
8754 		 * Hence when marking register as known preserve it's ID.
8755 		 */
8756 		if (is_jmp32)
8757 			__mark_reg32_known(reg, val32);
8758 		else
8759 			___mark_reg_known(reg, val);
8760 		break;
8761 	}
8762 	case BPF_JSET:
8763 		if (is_jmp32) {
8764 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8765 			if (is_power_of_2(val32))
8766 				true_32off = tnum_or(true_32off,
8767 						     tnum_const(val32));
8768 		} else {
8769 			false_64off = tnum_and(false_64off, tnum_const(~val));
8770 			if (is_power_of_2(val))
8771 				true_64off = tnum_or(true_64off,
8772 						     tnum_const(val));
8773 		}
8774 		break;
8775 	case BPF_JGE:
8776 	case BPF_JGT:
8777 	{
8778 		if (is_jmp32) {
8779 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8780 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8781 
8782 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8783 						       false_umax);
8784 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8785 						      true_umin);
8786 		} else {
8787 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8788 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8789 
8790 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8791 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8792 		}
8793 		break;
8794 	}
8795 	case BPF_JSGE:
8796 	case BPF_JSGT:
8797 	{
8798 		if (is_jmp32) {
8799 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8800 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8801 
8802 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8803 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8804 		} else {
8805 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8806 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8807 
8808 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8809 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8810 		}
8811 		break;
8812 	}
8813 	case BPF_JLE:
8814 	case BPF_JLT:
8815 	{
8816 		if (is_jmp32) {
8817 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8818 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8819 
8820 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8821 						       false_umin);
8822 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8823 						      true_umax);
8824 		} else {
8825 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8826 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8827 
8828 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8829 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8830 		}
8831 		break;
8832 	}
8833 	case BPF_JSLE:
8834 	case BPF_JSLT:
8835 	{
8836 		if (is_jmp32) {
8837 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8838 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8839 
8840 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8841 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8842 		} else {
8843 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8844 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8845 
8846 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8847 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8848 		}
8849 		break;
8850 	}
8851 	default:
8852 		return;
8853 	}
8854 
8855 	if (is_jmp32) {
8856 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8857 					     tnum_subreg(false_32off));
8858 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8859 					    tnum_subreg(true_32off));
8860 		__reg_combine_32_into_64(false_reg);
8861 		__reg_combine_32_into_64(true_reg);
8862 	} else {
8863 		false_reg->var_off = false_64off;
8864 		true_reg->var_off = true_64off;
8865 		__reg_combine_64_into_32(false_reg);
8866 		__reg_combine_64_into_32(true_reg);
8867 	}
8868 }
8869 
8870 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8871  * the variable reg.
8872  */
8873 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8874 				struct bpf_reg_state *false_reg,
8875 				u64 val, u32 val32,
8876 				u8 opcode, bool is_jmp32)
8877 {
8878 	opcode = flip_opcode(opcode);
8879 	/* This uses zero as "not present in table"; luckily the zero opcode,
8880 	 * BPF_JA, can't get here.
8881 	 */
8882 	if (opcode)
8883 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8884 }
8885 
8886 /* Regs are known to be equal, so intersect their min/max/var_off */
8887 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8888 				  struct bpf_reg_state *dst_reg)
8889 {
8890 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8891 							dst_reg->umin_value);
8892 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8893 							dst_reg->umax_value);
8894 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8895 							dst_reg->smin_value);
8896 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8897 							dst_reg->smax_value);
8898 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8899 							     dst_reg->var_off);
8900 	/* We might have learned new bounds from the var_off. */
8901 	__update_reg_bounds(src_reg);
8902 	__update_reg_bounds(dst_reg);
8903 	/* We might have learned something about the sign bit. */
8904 	__reg_deduce_bounds(src_reg);
8905 	__reg_deduce_bounds(dst_reg);
8906 	/* We might have learned some bits from the bounds. */
8907 	__reg_bound_offset(src_reg);
8908 	__reg_bound_offset(dst_reg);
8909 	/* Intersecting with the old var_off might have improved our bounds
8910 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8911 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
8912 	 */
8913 	__update_reg_bounds(src_reg);
8914 	__update_reg_bounds(dst_reg);
8915 }
8916 
8917 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8918 				struct bpf_reg_state *true_dst,
8919 				struct bpf_reg_state *false_src,
8920 				struct bpf_reg_state *false_dst,
8921 				u8 opcode)
8922 {
8923 	switch (opcode) {
8924 	case BPF_JEQ:
8925 		__reg_combine_min_max(true_src, true_dst);
8926 		break;
8927 	case BPF_JNE:
8928 		__reg_combine_min_max(false_src, false_dst);
8929 		break;
8930 	}
8931 }
8932 
8933 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8934 				 struct bpf_reg_state *reg, u32 id,
8935 				 bool is_null)
8936 {
8937 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
8938 	    !WARN_ON_ONCE(!reg->id)) {
8939 		/* Old offset (both fixed and variable parts) should
8940 		 * have been known-zero, because we don't allow pointer
8941 		 * arithmetic on pointers that might be NULL.
8942 		 */
8943 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8944 				 !tnum_equals_const(reg->var_off, 0) ||
8945 				 reg->off)) {
8946 			__mark_reg_known_zero(reg);
8947 			reg->off = 0;
8948 		}
8949 		if (is_null) {
8950 			reg->type = SCALAR_VALUE;
8951 			/* We don't need id and ref_obj_id from this point
8952 			 * onwards anymore, thus we should better reset it,
8953 			 * so that state pruning has chances to take effect.
8954 			 */
8955 			reg->id = 0;
8956 			reg->ref_obj_id = 0;
8957 
8958 			return;
8959 		}
8960 
8961 		mark_ptr_not_null_reg(reg);
8962 
8963 		if (!reg_may_point_to_spin_lock(reg)) {
8964 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8965 			 * in release_reg_references().
8966 			 *
8967 			 * reg->id is still used by spin_lock ptr. Other
8968 			 * than spin_lock ptr type, reg->id can be reset.
8969 			 */
8970 			reg->id = 0;
8971 		}
8972 	}
8973 }
8974 
8975 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8976 				    bool is_null)
8977 {
8978 	struct bpf_reg_state *reg;
8979 	int i;
8980 
8981 	for (i = 0; i < MAX_BPF_REG; i++)
8982 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8983 
8984 	bpf_for_each_spilled_reg(i, state, reg) {
8985 		if (!reg)
8986 			continue;
8987 		mark_ptr_or_null_reg(state, reg, id, is_null);
8988 	}
8989 }
8990 
8991 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8992  * be folded together at some point.
8993  */
8994 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8995 				  bool is_null)
8996 {
8997 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8998 	struct bpf_reg_state *regs = state->regs;
8999 	u32 ref_obj_id = regs[regno].ref_obj_id;
9000 	u32 id = regs[regno].id;
9001 	int i;
9002 
9003 	if (ref_obj_id && ref_obj_id == id && is_null)
9004 		/* regs[regno] is in the " == NULL" branch.
9005 		 * No one could have freed the reference state before
9006 		 * doing the NULL check.
9007 		 */
9008 		WARN_ON_ONCE(release_reference_state(state, id));
9009 
9010 	for (i = 0; i <= vstate->curframe; i++)
9011 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9012 }
9013 
9014 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9015 				   struct bpf_reg_state *dst_reg,
9016 				   struct bpf_reg_state *src_reg,
9017 				   struct bpf_verifier_state *this_branch,
9018 				   struct bpf_verifier_state *other_branch)
9019 {
9020 	if (BPF_SRC(insn->code) != BPF_X)
9021 		return false;
9022 
9023 	/* Pointers are always 64-bit. */
9024 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9025 		return false;
9026 
9027 	switch (BPF_OP(insn->code)) {
9028 	case BPF_JGT:
9029 		if ((dst_reg->type == PTR_TO_PACKET &&
9030 		     src_reg->type == PTR_TO_PACKET_END) ||
9031 		    (dst_reg->type == PTR_TO_PACKET_META &&
9032 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9033 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9034 			find_good_pkt_pointers(this_branch, dst_reg,
9035 					       dst_reg->type, false);
9036 			mark_pkt_end(other_branch, insn->dst_reg, true);
9037 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9038 			    src_reg->type == PTR_TO_PACKET) ||
9039 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9040 			    src_reg->type == PTR_TO_PACKET_META)) {
9041 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9042 			find_good_pkt_pointers(other_branch, src_reg,
9043 					       src_reg->type, true);
9044 			mark_pkt_end(this_branch, insn->src_reg, false);
9045 		} else {
9046 			return false;
9047 		}
9048 		break;
9049 	case BPF_JLT:
9050 		if ((dst_reg->type == PTR_TO_PACKET &&
9051 		     src_reg->type == PTR_TO_PACKET_END) ||
9052 		    (dst_reg->type == PTR_TO_PACKET_META &&
9053 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9054 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9055 			find_good_pkt_pointers(other_branch, dst_reg,
9056 					       dst_reg->type, true);
9057 			mark_pkt_end(this_branch, insn->dst_reg, false);
9058 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9059 			    src_reg->type == PTR_TO_PACKET) ||
9060 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9061 			    src_reg->type == PTR_TO_PACKET_META)) {
9062 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9063 			find_good_pkt_pointers(this_branch, src_reg,
9064 					       src_reg->type, false);
9065 			mark_pkt_end(other_branch, insn->src_reg, true);
9066 		} else {
9067 			return false;
9068 		}
9069 		break;
9070 	case BPF_JGE:
9071 		if ((dst_reg->type == PTR_TO_PACKET &&
9072 		     src_reg->type == PTR_TO_PACKET_END) ||
9073 		    (dst_reg->type == PTR_TO_PACKET_META &&
9074 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9075 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9076 			find_good_pkt_pointers(this_branch, dst_reg,
9077 					       dst_reg->type, true);
9078 			mark_pkt_end(other_branch, insn->dst_reg, false);
9079 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9080 			    src_reg->type == PTR_TO_PACKET) ||
9081 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9082 			    src_reg->type == PTR_TO_PACKET_META)) {
9083 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9084 			find_good_pkt_pointers(other_branch, src_reg,
9085 					       src_reg->type, false);
9086 			mark_pkt_end(this_branch, insn->src_reg, true);
9087 		} else {
9088 			return false;
9089 		}
9090 		break;
9091 	case BPF_JLE:
9092 		if ((dst_reg->type == PTR_TO_PACKET &&
9093 		     src_reg->type == PTR_TO_PACKET_END) ||
9094 		    (dst_reg->type == PTR_TO_PACKET_META &&
9095 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9096 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9097 			find_good_pkt_pointers(other_branch, dst_reg,
9098 					       dst_reg->type, false);
9099 			mark_pkt_end(this_branch, insn->dst_reg, true);
9100 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9101 			    src_reg->type == PTR_TO_PACKET) ||
9102 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9103 			    src_reg->type == PTR_TO_PACKET_META)) {
9104 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9105 			find_good_pkt_pointers(this_branch, src_reg,
9106 					       src_reg->type, true);
9107 			mark_pkt_end(other_branch, insn->src_reg, false);
9108 		} else {
9109 			return false;
9110 		}
9111 		break;
9112 	default:
9113 		return false;
9114 	}
9115 
9116 	return true;
9117 }
9118 
9119 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9120 			       struct bpf_reg_state *known_reg)
9121 {
9122 	struct bpf_func_state *state;
9123 	struct bpf_reg_state *reg;
9124 	int i, j;
9125 
9126 	for (i = 0; i <= vstate->curframe; i++) {
9127 		state = vstate->frame[i];
9128 		for (j = 0; j < MAX_BPF_REG; j++) {
9129 			reg = &state->regs[j];
9130 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9131 				*reg = *known_reg;
9132 		}
9133 
9134 		bpf_for_each_spilled_reg(j, state, reg) {
9135 			if (!reg)
9136 				continue;
9137 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9138 				*reg = *known_reg;
9139 		}
9140 	}
9141 }
9142 
9143 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9144 			     struct bpf_insn *insn, int *insn_idx)
9145 {
9146 	struct bpf_verifier_state *this_branch = env->cur_state;
9147 	struct bpf_verifier_state *other_branch;
9148 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9149 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9150 	u8 opcode = BPF_OP(insn->code);
9151 	bool is_jmp32;
9152 	int pred = -1;
9153 	int err;
9154 
9155 	/* Only conditional jumps are expected to reach here. */
9156 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9157 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9158 		return -EINVAL;
9159 	}
9160 
9161 	if (BPF_SRC(insn->code) == BPF_X) {
9162 		if (insn->imm != 0) {
9163 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9164 			return -EINVAL;
9165 		}
9166 
9167 		/* check src1 operand */
9168 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9169 		if (err)
9170 			return err;
9171 
9172 		if (is_pointer_value(env, insn->src_reg)) {
9173 			verbose(env, "R%d pointer comparison prohibited\n",
9174 				insn->src_reg);
9175 			return -EACCES;
9176 		}
9177 		src_reg = &regs[insn->src_reg];
9178 	} else {
9179 		if (insn->src_reg != BPF_REG_0) {
9180 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9181 			return -EINVAL;
9182 		}
9183 	}
9184 
9185 	/* check src2 operand */
9186 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9187 	if (err)
9188 		return err;
9189 
9190 	dst_reg = &regs[insn->dst_reg];
9191 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9192 
9193 	if (BPF_SRC(insn->code) == BPF_K) {
9194 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9195 	} else if (src_reg->type == SCALAR_VALUE &&
9196 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9197 		pred = is_branch_taken(dst_reg,
9198 				       tnum_subreg(src_reg->var_off).value,
9199 				       opcode,
9200 				       is_jmp32);
9201 	} else if (src_reg->type == SCALAR_VALUE &&
9202 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9203 		pred = is_branch_taken(dst_reg,
9204 				       src_reg->var_off.value,
9205 				       opcode,
9206 				       is_jmp32);
9207 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9208 		   reg_is_pkt_pointer_any(src_reg) &&
9209 		   !is_jmp32) {
9210 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9211 	}
9212 
9213 	if (pred >= 0) {
9214 		/* If we get here with a dst_reg pointer type it is because
9215 		 * above is_branch_taken() special cased the 0 comparison.
9216 		 */
9217 		if (!__is_pointer_value(false, dst_reg))
9218 			err = mark_chain_precision(env, insn->dst_reg);
9219 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9220 		    !__is_pointer_value(false, src_reg))
9221 			err = mark_chain_precision(env, insn->src_reg);
9222 		if (err)
9223 			return err;
9224 	}
9225 
9226 	if (pred == 1) {
9227 		/* Only follow the goto, ignore fall-through. If needed, push
9228 		 * the fall-through branch for simulation under speculative
9229 		 * execution.
9230 		 */
9231 		if (!env->bypass_spec_v1 &&
9232 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9233 					       *insn_idx))
9234 			return -EFAULT;
9235 		*insn_idx += insn->off;
9236 		return 0;
9237 	} else if (pred == 0) {
9238 		/* Only follow the fall-through branch, since that's where the
9239 		 * program will go. If needed, push the goto branch for
9240 		 * simulation under speculative execution.
9241 		 */
9242 		if (!env->bypass_spec_v1 &&
9243 		    !sanitize_speculative_path(env, insn,
9244 					       *insn_idx + insn->off + 1,
9245 					       *insn_idx))
9246 			return -EFAULT;
9247 		return 0;
9248 	}
9249 
9250 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9251 				  false);
9252 	if (!other_branch)
9253 		return -EFAULT;
9254 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9255 
9256 	/* detect if we are comparing against a constant value so we can adjust
9257 	 * our min/max values for our dst register.
9258 	 * this is only legit if both are scalars (or pointers to the same
9259 	 * object, I suppose, but we don't support that right now), because
9260 	 * otherwise the different base pointers mean the offsets aren't
9261 	 * comparable.
9262 	 */
9263 	if (BPF_SRC(insn->code) == BPF_X) {
9264 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9265 
9266 		if (dst_reg->type == SCALAR_VALUE &&
9267 		    src_reg->type == SCALAR_VALUE) {
9268 			if (tnum_is_const(src_reg->var_off) ||
9269 			    (is_jmp32 &&
9270 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9271 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9272 						dst_reg,
9273 						src_reg->var_off.value,
9274 						tnum_subreg(src_reg->var_off).value,
9275 						opcode, is_jmp32);
9276 			else if (tnum_is_const(dst_reg->var_off) ||
9277 				 (is_jmp32 &&
9278 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9279 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9280 						    src_reg,
9281 						    dst_reg->var_off.value,
9282 						    tnum_subreg(dst_reg->var_off).value,
9283 						    opcode, is_jmp32);
9284 			else if (!is_jmp32 &&
9285 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9286 				/* Comparing for equality, we can combine knowledge */
9287 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9288 						    &other_branch_regs[insn->dst_reg],
9289 						    src_reg, dst_reg, opcode);
9290 			if (src_reg->id &&
9291 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9292 				find_equal_scalars(this_branch, src_reg);
9293 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9294 			}
9295 
9296 		}
9297 	} else if (dst_reg->type == SCALAR_VALUE) {
9298 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9299 					dst_reg, insn->imm, (u32)insn->imm,
9300 					opcode, is_jmp32);
9301 	}
9302 
9303 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9304 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9305 		find_equal_scalars(this_branch, dst_reg);
9306 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9307 	}
9308 
9309 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9310 	 * NOTE: these optimizations below are related with pointer comparison
9311 	 *       which will never be JMP32.
9312 	 */
9313 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9314 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9315 	    reg_type_may_be_null(dst_reg->type)) {
9316 		/* Mark all identical registers in each branch as either
9317 		 * safe or unknown depending R == 0 or R != 0 conditional.
9318 		 */
9319 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9320 				      opcode == BPF_JNE);
9321 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9322 				      opcode == BPF_JEQ);
9323 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9324 					   this_branch, other_branch) &&
9325 		   is_pointer_value(env, insn->dst_reg)) {
9326 		verbose(env, "R%d pointer comparison prohibited\n",
9327 			insn->dst_reg);
9328 		return -EACCES;
9329 	}
9330 	if (env->log.level & BPF_LOG_LEVEL)
9331 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9332 	return 0;
9333 }
9334 
9335 /* verify BPF_LD_IMM64 instruction */
9336 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9337 {
9338 	struct bpf_insn_aux_data *aux = cur_aux(env);
9339 	struct bpf_reg_state *regs = cur_regs(env);
9340 	struct bpf_reg_state *dst_reg;
9341 	struct bpf_map *map;
9342 	int err;
9343 
9344 	if (BPF_SIZE(insn->code) != BPF_DW) {
9345 		verbose(env, "invalid BPF_LD_IMM insn\n");
9346 		return -EINVAL;
9347 	}
9348 	if (insn->off != 0) {
9349 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9350 		return -EINVAL;
9351 	}
9352 
9353 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9354 	if (err)
9355 		return err;
9356 
9357 	dst_reg = &regs[insn->dst_reg];
9358 	if (insn->src_reg == 0) {
9359 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9360 
9361 		dst_reg->type = SCALAR_VALUE;
9362 		__mark_reg_known(&regs[insn->dst_reg], imm);
9363 		return 0;
9364 	}
9365 
9366 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9367 		mark_reg_known_zero(env, regs, insn->dst_reg);
9368 
9369 		dst_reg->type = aux->btf_var.reg_type;
9370 		switch (dst_reg->type) {
9371 		case PTR_TO_MEM:
9372 			dst_reg->mem_size = aux->btf_var.mem_size;
9373 			break;
9374 		case PTR_TO_BTF_ID:
9375 		case PTR_TO_PERCPU_BTF_ID:
9376 			dst_reg->btf = aux->btf_var.btf;
9377 			dst_reg->btf_id = aux->btf_var.btf_id;
9378 			break;
9379 		default:
9380 			verbose(env, "bpf verifier is misconfigured\n");
9381 			return -EFAULT;
9382 		}
9383 		return 0;
9384 	}
9385 
9386 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9387 		struct bpf_prog_aux *aux = env->prog->aux;
9388 		u32 subprogno = insn[1].imm;
9389 
9390 		if (!aux->func_info) {
9391 			verbose(env, "missing btf func_info\n");
9392 			return -EINVAL;
9393 		}
9394 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9395 			verbose(env, "callback function not static\n");
9396 			return -EINVAL;
9397 		}
9398 
9399 		dst_reg->type = PTR_TO_FUNC;
9400 		dst_reg->subprogno = subprogno;
9401 		return 0;
9402 	}
9403 
9404 	map = env->used_maps[aux->map_index];
9405 	mark_reg_known_zero(env, regs, insn->dst_reg);
9406 	dst_reg->map_ptr = map;
9407 
9408 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9409 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9410 		dst_reg->type = PTR_TO_MAP_VALUE;
9411 		dst_reg->off = aux->map_off;
9412 		if (map_value_has_spin_lock(map))
9413 			dst_reg->id = ++env->id_gen;
9414 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9415 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9416 		dst_reg->type = CONST_PTR_TO_MAP;
9417 	} else {
9418 		verbose(env, "bpf verifier is misconfigured\n");
9419 		return -EINVAL;
9420 	}
9421 
9422 	return 0;
9423 }
9424 
9425 static bool may_access_skb(enum bpf_prog_type type)
9426 {
9427 	switch (type) {
9428 	case BPF_PROG_TYPE_SOCKET_FILTER:
9429 	case BPF_PROG_TYPE_SCHED_CLS:
9430 	case BPF_PROG_TYPE_SCHED_ACT:
9431 		return true;
9432 	default:
9433 		return false;
9434 	}
9435 }
9436 
9437 /* verify safety of LD_ABS|LD_IND instructions:
9438  * - they can only appear in the programs where ctx == skb
9439  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9440  *   preserve R6-R9, and store return value into R0
9441  *
9442  * Implicit input:
9443  *   ctx == skb == R6 == CTX
9444  *
9445  * Explicit input:
9446  *   SRC == any register
9447  *   IMM == 32-bit immediate
9448  *
9449  * Output:
9450  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9451  */
9452 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9453 {
9454 	struct bpf_reg_state *regs = cur_regs(env);
9455 	static const int ctx_reg = BPF_REG_6;
9456 	u8 mode = BPF_MODE(insn->code);
9457 	int i, err;
9458 
9459 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9460 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9461 		return -EINVAL;
9462 	}
9463 
9464 	if (!env->ops->gen_ld_abs) {
9465 		verbose(env, "bpf verifier is misconfigured\n");
9466 		return -EINVAL;
9467 	}
9468 
9469 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9470 	    BPF_SIZE(insn->code) == BPF_DW ||
9471 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9472 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9473 		return -EINVAL;
9474 	}
9475 
9476 	/* check whether implicit source operand (register R6) is readable */
9477 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9478 	if (err)
9479 		return err;
9480 
9481 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9482 	 * gen_ld_abs() may terminate the program at runtime, leading to
9483 	 * reference leak.
9484 	 */
9485 	err = check_reference_leak(env);
9486 	if (err) {
9487 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9488 		return err;
9489 	}
9490 
9491 	if (env->cur_state->active_spin_lock) {
9492 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9493 		return -EINVAL;
9494 	}
9495 
9496 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9497 		verbose(env,
9498 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9499 		return -EINVAL;
9500 	}
9501 
9502 	if (mode == BPF_IND) {
9503 		/* check explicit source operand */
9504 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9505 		if (err)
9506 			return err;
9507 	}
9508 
9509 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9510 	if (err < 0)
9511 		return err;
9512 
9513 	/* reset caller saved regs to unreadable */
9514 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9515 		mark_reg_not_init(env, regs, caller_saved[i]);
9516 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9517 	}
9518 
9519 	/* mark destination R0 register as readable, since it contains
9520 	 * the value fetched from the packet.
9521 	 * Already marked as written above.
9522 	 */
9523 	mark_reg_unknown(env, regs, BPF_REG_0);
9524 	/* ld_abs load up to 32-bit skb data. */
9525 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9526 	return 0;
9527 }
9528 
9529 static int check_return_code(struct bpf_verifier_env *env)
9530 {
9531 	struct tnum enforce_attach_type_range = tnum_unknown;
9532 	const struct bpf_prog *prog = env->prog;
9533 	struct bpf_reg_state *reg;
9534 	struct tnum range = tnum_range(0, 1);
9535 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9536 	int err;
9537 	struct bpf_func_state *frame = env->cur_state->frame[0];
9538 	const bool is_subprog = frame->subprogno;
9539 
9540 	/* LSM and struct_ops func-ptr's return type could be "void" */
9541 	if (!is_subprog &&
9542 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9543 	     prog_type == BPF_PROG_TYPE_LSM) &&
9544 	    !prog->aux->attach_func_proto->type)
9545 		return 0;
9546 
9547 	/* eBPF calling convention is such that R0 is used
9548 	 * to return the value from eBPF program.
9549 	 * Make sure that it's readable at this time
9550 	 * of bpf_exit, which means that program wrote
9551 	 * something into it earlier
9552 	 */
9553 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9554 	if (err)
9555 		return err;
9556 
9557 	if (is_pointer_value(env, BPF_REG_0)) {
9558 		verbose(env, "R0 leaks addr as return value\n");
9559 		return -EACCES;
9560 	}
9561 
9562 	reg = cur_regs(env) + BPF_REG_0;
9563 
9564 	if (frame->in_async_callback_fn) {
9565 		/* enforce return zero from async callbacks like timer */
9566 		if (reg->type != SCALAR_VALUE) {
9567 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9568 				reg_type_str[reg->type]);
9569 			return -EINVAL;
9570 		}
9571 
9572 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9573 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9574 			return -EINVAL;
9575 		}
9576 		return 0;
9577 	}
9578 
9579 	if (is_subprog) {
9580 		if (reg->type != SCALAR_VALUE) {
9581 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9582 				reg_type_str[reg->type]);
9583 			return -EINVAL;
9584 		}
9585 		return 0;
9586 	}
9587 
9588 	switch (prog_type) {
9589 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9590 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9591 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9592 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9593 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9594 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9595 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9596 			range = tnum_range(1, 1);
9597 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9598 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9599 			range = tnum_range(0, 3);
9600 		break;
9601 	case BPF_PROG_TYPE_CGROUP_SKB:
9602 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9603 			range = tnum_range(0, 3);
9604 			enforce_attach_type_range = tnum_range(2, 3);
9605 		}
9606 		break;
9607 	case BPF_PROG_TYPE_CGROUP_SOCK:
9608 	case BPF_PROG_TYPE_SOCK_OPS:
9609 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9610 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9611 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9612 		break;
9613 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9614 		if (!env->prog->aux->attach_btf_id)
9615 			return 0;
9616 		range = tnum_const(0);
9617 		break;
9618 	case BPF_PROG_TYPE_TRACING:
9619 		switch (env->prog->expected_attach_type) {
9620 		case BPF_TRACE_FENTRY:
9621 		case BPF_TRACE_FEXIT:
9622 			range = tnum_const(0);
9623 			break;
9624 		case BPF_TRACE_RAW_TP:
9625 		case BPF_MODIFY_RETURN:
9626 			return 0;
9627 		case BPF_TRACE_ITER:
9628 			break;
9629 		default:
9630 			return -ENOTSUPP;
9631 		}
9632 		break;
9633 	case BPF_PROG_TYPE_SK_LOOKUP:
9634 		range = tnum_range(SK_DROP, SK_PASS);
9635 		break;
9636 	case BPF_PROG_TYPE_EXT:
9637 		/* freplace program can return anything as its return value
9638 		 * depends on the to-be-replaced kernel func or bpf program.
9639 		 */
9640 	default:
9641 		return 0;
9642 	}
9643 
9644 	if (reg->type != SCALAR_VALUE) {
9645 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9646 			reg_type_str[reg->type]);
9647 		return -EINVAL;
9648 	}
9649 
9650 	if (!tnum_in(range, reg->var_off)) {
9651 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9652 		return -EINVAL;
9653 	}
9654 
9655 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9656 	    tnum_in(enforce_attach_type_range, reg->var_off))
9657 		env->prog->enforce_expected_attach_type = 1;
9658 	return 0;
9659 }
9660 
9661 /* non-recursive DFS pseudo code
9662  * 1  procedure DFS-iterative(G,v):
9663  * 2      label v as discovered
9664  * 3      let S be a stack
9665  * 4      S.push(v)
9666  * 5      while S is not empty
9667  * 6            t <- S.pop()
9668  * 7            if t is what we're looking for:
9669  * 8                return t
9670  * 9            for all edges e in G.adjacentEdges(t) do
9671  * 10               if edge e is already labelled
9672  * 11                   continue with the next edge
9673  * 12               w <- G.adjacentVertex(t,e)
9674  * 13               if vertex w is not discovered and not explored
9675  * 14                   label e as tree-edge
9676  * 15                   label w as discovered
9677  * 16                   S.push(w)
9678  * 17                   continue at 5
9679  * 18               else if vertex w is discovered
9680  * 19                   label e as back-edge
9681  * 20               else
9682  * 21                   // vertex w is explored
9683  * 22                   label e as forward- or cross-edge
9684  * 23           label t as explored
9685  * 24           S.pop()
9686  *
9687  * convention:
9688  * 0x10 - discovered
9689  * 0x11 - discovered and fall-through edge labelled
9690  * 0x12 - discovered and fall-through and branch edges labelled
9691  * 0x20 - explored
9692  */
9693 
9694 enum {
9695 	DISCOVERED = 0x10,
9696 	EXPLORED = 0x20,
9697 	FALLTHROUGH = 1,
9698 	BRANCH = 2,
9699 };
9700 
9701 static u32 state_htab_size(struct bpf_verifier_env *env)
9702 {
9703 	return env->prog->len;
9704 }
9705 
9706 static struct bpf_verifier_state_list **explored_state(
9707 					struct bpf_verifier_env *env,
9708 					int idx)
9709 {
9710 	struct bpf_verifier_state *cur = env->cur_state;
9711 	struct bpf_func_state *state = cur->frame[cur->curframe];
9712 
9713 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9714 }
9715 
9716 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9717 {
9718 	env->insn_aux_data[idx].prune_point = true;
9719 }
9720 
9721 enum {
9722 	DONE_EXPLORING = 0,
9723 	KEEP_EXPLORING = 1,
9724 };
9725 
9726 /* t, w, e - match pseudo-code above:
9727  * t - index of current instruction
9728  * w - next instruction
9729  * e - edge
9730  */
9731 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9732 		     bool loop_ok)
9733 {
9734 	int *insn_stack = env->cfg.insn_stack;
9735 	int *insn_state = env->cfg.insn_state;
9736 
9737 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9738 		return DONE_EXPLORING;
9739 
9740 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9741 		return DONE_EXPLORING;
9742 
9743 	if (w < 0 || w >= env->prog->len) {
9744 		verbose_linfo(env, t, "%d: ", t);
9745 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9746 		return -EINVAL;
9747 	}
9748 
9749 	if (e == BRANCH)
9750 		/* mark branch target for state pruning */
9751 		init_explored_state(env, w);
9752 
9753 	if (insn_state[w] == 0) {
9754 		/* tree-edge */
9755 		insn_state[t] = DISCOVERED | e;
9756 		insn_state[w] = DISCOVERED;
9757 		if (env->cfg.cur_stack >= env->prog->len)
9758 			return -E2BIG;
9759 		insn_stack[env->cfg.cur_stack++] = w;
9760 		return KEEP_EXPLORING;
9761 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9762 		if (loop_ok && env->bpf_capable)
9763 			return DONE_EXPLORING;
9764 		verbose_linfo(env, t, "%d: ", t);
9765 		verbose_linfo(env, w, "%d: ", w);
9766 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9767 		return -EINVAL;
9768 	} else if (insn_state[w] == EXPLORED) {
9769 		/* forward- or cross-edge */
9770 		insn_state[t] = DISCOVERED | e;
9771 	} else {
9772 		verbose(env, "insn state internal bug\n");
9773 		return -EFAULT;
9774 	}
9775 	return DONE_EXPLORING;
9776 }
9777 
9778 static int visit_func_call_insn(int t, int insn_cnt,
9779 				struct bpf_insn *insns,
9780 				struct bpf_verifier_env *env,
9781 				bool visit_callee)
9782 {
9783 	int ret;
9784 
9785 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9786 	if (ret)
9787 		return ret;
9788 
9789 	if (t + 1 < insn_cnt)
9790 		init_explored_state(env, t + 1);
9791 	if (visit_callee) {
9792 		init_explored_state(env, t);
9793 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9794 				/* It's ok to allow recursion from CFG point of
9795 				 * view. __check_func_call() will do the actual
9796 				 * check.
9797 				 */
9798 				bpf_pseudo_func(insns + t));
9799 	}
9800 	return ret;
9801 }
9802 
9803 /* Visits the instruction at index t and returns one of the following:
9804  *  < 0 - an error occurred
9805  *  DONE_EXPLORING - the instruction was fully explored
9806  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9807  */
9808 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9809 {
9810 	struct bpf_insn *insns = env->prog->insnsi;
9811 	int ret;
9812 
9813 	if (bpf_pseudo_func(insns + t))
9814 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9815 
9816 	/* All non-branch instructions have a single fall-through edge. */
9817 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9818 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9819 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9820 
9821 	switch (BPF_OP(insns[t].code)) {
9822 	case BPF_EXIT:
9823 		return DONE_EXPLORING;
9824 
9825 	case BPF_CALL:
9826 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9827 			/* Mark this call insn to trigger is_state_visited() check
9828 			 * before call itself is processed by __check_func_call().
9829 			 * Otherwise new async state will be pushed for further
9830 			 * exploration.
9831 			 */
9832 			init_explored_state(env, t);
9833 		return visit_func_call_insn(t, insn_cnt, insns, env,
9834 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9835 
9836 	case BPF_JA:
9837 		if (BPF_SRC(insns[t].code) != BPF_K)
9838 			return -EINVAL;
9839 
9840 		/* unconditional jump with single edge */
9841 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9842 				true);
9843 		if (ret)
9844 			return ret;
9845 
9846 		/* unconditional jmp is not a good pruning point,
9847 		 * but it's marked, since backtracking needs
9848 		 * to record jmp history in is_state_visited().
9849 		 */
9850 		init_explored_state(env, t + insns[t].off + 1);
9851 		/* tell verifier to check for equivalent states
9852 		 * after every call and jump
9853 		 */
9854 		if (t + 1 < insn_cnt)
9855 			init_explored_state(env, t + 1);
9856 
9857 		return ret;
9858 
9859 	default:
9860 		/* conditional jump with two edges */
9861 		init_explored_state(env, t);
9862 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9863 		if (ret)
9864 			return ret;
9865 
9866 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9867 	}
9868 }
9869 
9870 /* non-recursive depth-first-search to detect loops in BPF program
9871  * loop == back-edge in directed graph
9872  */
9873 static int check_cfg(struct bpf_verifier_env *env)
9874 {
9875 	int insn_cnt = env->prog->len;
9876 	int *insn_stack, *insn_state;
9877 	int ret = 0;
9878 	int i;
9879 
9880 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9881 	if (!insn_state)
9882 		return -ENOMEM;
9883 
9884 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9885 	if (!insn_stack) {
9886 		kvfree(insn_state);
9887 		return -ENOMEM;
9888 	}
9889 
9890 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9891 	insn_stack[0] = 0; /* 0 is the first instruction */
9892 	env->cfg.cur_stack = 1;
9893 
9894 	while (env->cfg.cur_stack > 0) {
9895 		int t = insn_stack[env->cfg.cur_stack - 1];
9896 
9897 		ret = visit_insn(t, insn_cnt, env);
9898 		switch (ret) {
9899 		case DONE_EXPLORING:
9900 			insn_state[t] = EXPLORED;
9901 			env->cfg.cur_stack--;
9902 			break;
9903 		case KEEP_EXPLORING:
9904 			break;
9905 		default:
9906 			if (ret > 0) {
9907 				verbose(env, "visit_insn internal bug\n");
9908 				ret = -EFAULT;
9909 			}
9910 			goto err_free;
9911 		}
9912 	}
9913 
9914 	if (env->cfg.cur_stack < 0) {
9915 		verbose(env, "pop stack internal bug\n");
9916 		ret = -EFAULT;
9917 		goto err_free;
9918 	}
9919 
9920 	for (i = 0; i < insn_cnt; i++) {
9921 		if (insn_state[i] != EXPLORED) {
9922 			verbose(env, "unreachable insn %d\n", i);
9923 			ret = -EINVAL;
9924 			goto err_free;
9925 		}
9926 	}
9927 	ret = 0; /* cfg looks good */
9928 
9929 err_free:
9930 	kvfree(insn_state);
9931 	kvfree(insn_stack);
9932 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9933 	return ret;
9934 }
9935 
9936 static int check_abnormal_return(struct bpf_verifier_env *env)
9937 {
9938 	int i;
9939 
9940 	for (i = 1; i < env->subprog_cnt; i++) {
9941 		if (env->subprog_info[i].has_ld_abs) {
9942 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9943 			return -EINVAL;
9944 		}
9945 		if (env->subprog_info[i].has_tail_call) {
9946 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9947 			return -EINVAL;
9948 		}
9949 	}
9950 	return 0;
9951 }
9952 
9953 /* The minimum supported BTF func info size */
9954 #define MIN_BPF_FUNCINFO_SIZE	8
9955 #define MAX_FUNCINFO_REC_SIZE	252
9956 
9957 static int check_btf_func(struct bpf_verifier_env *env,
9958 			  const union bpf_attr *attr,
9959 			  bpfptr_t uattr)
9960 {
9961 	const struct btf_type *type, *func_proto, *ret_type;
9962 	u32 i, nfuncs, urec_size, min_size;
9963 	u32 krec_size = sizeof(struct bpf_func_info);
9964 	struct bpf_func_info *krecord;
9965 	struct bpf_func_info_aux *info_aux = NULL;
9966 	struct bpf_prog *prog;
9967 	const struct btf *btf;
9968 	bpfptr_t urecord;
9969 	u32 prev_offset = 0;
9970 	bool scalar_return;
9971 	int ret = -ENOMEM;
9972 
9973 	nfuncs = attr->func_info_cnt;
9974 	if (!nfuncs) {
9975 		if (check_abnormal_return(env))
9976 			return -EINVAL;
9977 		return 0;
9978 	}
9979 
9980 	if (nfuncs != env->subprog_cnt) {
9981 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9982 		return -EINVAL;
9983 	}
9984 
9985 	urec_size = attr->func_info_rec_size;
9986 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9987 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
9988 	    urec_size % sizeof(u32)) {
9989 		verbose(env, "invalid func info rec size %u\n", urec_size);
9990 		return -EINVAL;
9991 	}
9992 
9993 	prog = env->prog;
9994 	btf = prog->aux->btf;
9995 
9996 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9997 	min_size = min_t(u32, krec_size, urec_size);
9998 
9999 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10000 	if (!krecord)
10001 		return -ENOMEM;
10002 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10003 	if (!info_aux)
10004 		goto err_free;
10005 
10006 	for (i = 0; i < nfuncs; i++) {
10007 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10008 		if (ret) {
10009 			if (ret == -E2BIG) {
10010 				verbose(env, "nonzero tailing record in func info");
10011 				/* set the size kernel expects so loader can zero
10012 				 * out the rest of the record.
10013 				 */
10014 				if (copy_to_bpfptr_offset(uattr,
10015 							  offsetof(union bpf_attr, func_info_rec_size),
10016 							  &min_size, sizeof(min_size)))
10017 					ret = -EFAULT;
10018 			}
10019 			goto err_free;
10020 		}
10021 
10022 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10023 			ret = -EFAULT;
10024 			goto err_free;
10025 		}
10026 
10027 		/* check insn_off */
10028 		ret = -EINVAL;
10029 		if (i == 0) {
10030 			if (krecord[i].insn_off) {
10031 				verbose(env,
10032 					"nonzero insn_off %u for the first func info record",
10033 					krecord[i].insn_off);
10034 				goto err_free;
10035 			}
10036 		} else if (krecord[i].insn_off <= prev_offset) {
10037 			verbose(env,
10038 				"same or smaller insn offset (%u) than previous func info record (%u)",
10039 				krecord[i].insn_off, prev_offset);
10040 			goto err_free;
10041 		}
10042 
10043 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10044 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10045 			goto err_free;
10046 		}
10047 
10048 		/* check type_id */
10049 		type = btf_type_by_id(btf, krecord[i].type_id);
10050 		if (!type || !btf_type_is_func(type)) {
10051 			verbose(env, "invalid type id %d in func info",
10052 				krecord[i].type_id);
10053 			goto err_free;
10054 		}
10055 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10056 
10057 		func_proto = btf_type_by_id(btf, type->type);
10058 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10059 			/* btf_func_check() already verified it during BTF load */
10060 			goto err_free;
10061 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10062 		scalar_return =
10063 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10064 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10065 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10066 			goto err_free;
10067 		}
10068 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10069 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10070 			goto err_free;
10071 		}
10072 
10073 		prev_offset = krecord[i].insn_off;
10074 		bpfptr_add(&urecord, urec_size);
10075 	}
10076 
10077 	prog->aux->func_info = krecord;
10078 	prog->aux->func_info_cnt = nfuncs;
10079 	prog->aux->func_info_aux = info_aux;
10080 	return 0;
10081 
10082 err_free:
10083 	kvfree(krecord);
10084 	kfree(info_aux);
10085 	return ret;
10086 }
10087 
10088 static void adjust_btf_func(struct bpf_verifier_env *env)
10089 {
10090 	struct bpf_prog_aux *aux = env->prog->aux;
10091 	int i;
10092 
10093 	if (!aux->func_info)
10094 		return;
10095 
10096 	for (i = 0; i < env->subprog_cnt; i++)
10097 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10098 }
10099 
10100 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
10101 		sizeof(((struct bpf_line_info *)(0))->line_col))
10102 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10103 
10104 static int check_btf_line(struct bpf_verifier_env *env,
10105 			  const union bpf_attr *attr,
10106 			  bpfptr_t uattr)
10107 {
10108 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10109 	struct bpf_subprog_info *sub;
10110 	struct bpf_line_info *linfo;
10111 	struct bpf_prog *prog;
10112 	const struct btf *btf;
10113 	bpfptr_t ulinfo;
10114 	int err;
10115 
10116 	nr_linfo = attr->line_info_cnt;
10117 	if (!nr_linfo)
10118 		return 0;
10119 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10120 		return -EINVAL;
10121 
10122 	rec_size = attr->line_info_rec_size;
10123 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10124 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10125 	    rec_size & (sizeof(u32) - 1))
10126 		return -EINVAL;
10127 
10128 	/* Need to zero it in case the userspace may
10129 	 * pass in a smaller bpf_line_info object.
10130 	 */
10131 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10132 			 GFP_KERNEL | __GFP_NOWARN);
10133 	if (!linfo)
10134 		return -ENOMEM;
10135 
10136 	prog = env->prog;
10137 	btf = prog->aux->btf;
10138 
10139 	s = 0;
10140 	sub = env->subprog_info;
10141 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10142 	expected_size = sizeof(struct bpf_line_info);
10143 	ncopy = min_t(u32, expected_size, rec_size);
10144 	for (i = 0; i < nr_linfo; i++) {
10145 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10146 		if (err) {
10147 			if (err == -E2BIG) {
10148 				verbose(env, "nonzero tailing record in line_info");
10149 				if (copy_to_bpfptr_offset(uattr,
10150 							  offsetof(union bpf_attr, line_info_rec_size),
10151 							  &expected_size, sizeof(expected_size)))
10152 					err = -EFAULT;
10153 			}
10154 			goto err_free;
10155 		}
10156 
10157 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10158 			err = -EFAULT;
10159 			goto err_free;
10160 		}
10161 
10162 		/*
10163 		 * Check insn_off to ensure
10164 		 * 1) strictly increasing AND
10165 		 * 2) bounded by prog->len
10166 		 *
10167 		 * The linfo[0].insn_off == 0 check logically falls into
10168 		 * the later "missing bpf_line_info for func..." case
10169 		 * because the first linfo[0].insn_off must be the
10170 		 * first sub also and the first sub must have
10171 		 * subprog_info[0].start == 0.
10172 		 */
10173 		if ((i && linfo[i].insn_off <= prev_offset) ||
10174 		    linfo[i].insn_off >= prog->len) {
10175 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10176 				i, linfo[i].insn_off, prev_offset,
10177 				prog->len);
10178 			err = -EINVAL;
10179 			goto err_free;
10180 		}
10181 
10182 		if (!prog->insnsi[linfo[i].insn_off].code) {
10183 			verbose(env,
10184 				"Invalid insn code at line_info[%u].insn_off\n",
10185 				i);
10186 			err = -EINVAL;
10187 			goto err_free;
10188 		}
10189 
10190 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10191 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10192 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10193 			err = -EINVAL;
10194 			goto err_free;
10195 		}
10196 
10197 		if (s != env->subprog_cnt) {
10198 			if (linfo[i].insn_off == sub[s].start) {
10199 				sub[s].linfo_idx = i;
10200 				s++;
10201 			} else if (sub[s].start < linfo[i].insn_off) {
10202 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10203 				err = -EINVAL;
10204 				goto err_free;
10205 			}
10206 		}
10207 
10208 		prev_offset = linfo[i].insn_off;
10209 		bpfptr_add(&ulinfo, rec_size);
10210 	}
10211 
10212 	if (s != env->subprog_cnt) {
10213 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10214 			env->subprog_cnt - s, s);
10215 		err = -EINVAL;
10216 		goto err_free;
10217 	}
10218 
10219 	prog->aux->linfo = linfo;
10220 	prog->aux->nr_linfo = nr_linfo;
10221 
10222 	return 0;
10223 
10224 err_free:
10225 	kvfree(linfo);
10226 	return err;
10227 }
10228 
10229 static int check_btf_info(struct bpf_verifier_env *env,
10230 			  const union bpf_attr *attr,
10231 			  bpfptr_t uattr)
10232 {
10233 	struct btf *btf;
10234 	int err;
10235 
10236 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10237 		if (check_abnormal_return(env))
10238 			return -EINVAL;
10239 		return 0;
10240 	}
10241 
10242 	btf = btf_get_by_fd(attr->prog_btf_fd);
10243 	if (IS_ERR(btf))
10244 		return PTR_ERR(btf);
10245 	if (btf_is_kernel(btf)) {
10246 		btf_put(btf);
10247 		return -EACCES;
10248 	}
10249 	env->prog->aux->btf = btf;
10250 
10251 	err = check_btf_func(env, attr, uattr);
10252 	if (err)
10253 		return err;
10254 
10255 	err = check_btf_line(env, attr, uattr);
10256 	if (err)
10257 		return err;
10258 
10259 	return 0;
10260 }
10261 
10262 /* check %cur's range satisfies %old's */
10263 static bool range_within(struct bpf_reg_state *old,
10264 			 struct bpf_reg_state *cur)
10265 {
10266 	return old->umin_value <= cur->umin_value &&
10267 	       old->umax_value >= cur->umax_value &&
10268 	       old->smin_value <= cur->smin_value &&
10269 	       old->smax_value >= cur->smax_value &&
10270 	       old->u32_min_value <= cur->u32_min_value &&
10271 	       old->u32_max_value >= cur->u32_max_value &&
10272 	       old->s32_min_value <= cur->s32_min_value &&
10273 	       old->s32_max_value >= cur->s32_max_value;
10274 }
10275 
10276 /* If in the old state two registers had the same id, then they need to have
10277  * the same id in the new state as well.  But that id could be different from
10278  * the old state, so we need to track the mapping from old to new ids.
10279  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10280  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10281  * regs with a different old id could still have new id 9, we don't care about
10282  * that.
10283  * So we look through our idmap to see if this old id has been seen before.  If
10284  * so, we require the new id to match; otherwise, we add the id pair to the map.
10285  */
10286 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10287 {
10288 	unsigned int i;
10289 
10290 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10291 		if (!idmap[i].old) {
10292 			/* Reached an empty slot; haven't seen this id before */
10293 			idmap[i].old = old_id;
10294 			idmap[i].cur = cur_id;
10295 			return true;
10296 		}
10297 		if (idmap[i].old == old_id)
10298 			return idmap[i].cur == cur_id;
10299 	}
10300 	/* We ran out of idmap slots, which should be impossible */
10301 	WARN_ON_ONCE(1);
10302 	return false;
10303 }
10304 
10305 static void clean_func_state(struct bpf_verifier_env *env,
10306 			     struct bpf_func_state *st)
10307 {
10308 	enum bpf_reg_liveness live;
10309 	int i, j;
10310 
10311 	for (i = 0; i < BPF_REG_FP; i++) {
10312 		live = st->regs[i].live;
10313 		/* liveness must not touch this register anymore */
10314 		st->regs[i].live |= REG_LIVE_DONE;
10315 		if (!(live & REG_LIVE_READ))
10316 			/* since the register is unused, clear its state
10317 			 * to make further comparison simpler
10318 			 */
10319 			__mark_reg_not_init(env, &st->regs[i]);
10320 	}
10321 
10322 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10323 		live = st->stack[i].spilled_ptr.live;
10324 		/* liveness must not touch this stack slot anymore */
10325 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10326 		if (!(live & REG_LIVE_READ)) {
10327 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10328 			for (j = 0; j < BPF_REG_SIZE; j++)
10329 				st->stack[i].slot_type[j] = STACK_INVALID;
10330 		}
10331 	}
10332 }
10333 
10334 static void clean_verifier_state(struct bpf_verifier_env *env,
10335 				 struct bpf_verifier_state *st)
10336 {
10337 	int i;
10338 
10339 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10340 		/* all regs in this state in all frames were already marked */
10341 		return;
10342 
10343 	for (i = 0; i <= st->curframe; i++)
10344 		clean_func_state(env, st->frame[i]);
10345 }
10346 
10347 /* the parentage chains form a tree.
10348  * the verifier states are added to state lists at given insn and
10349  * pushed into state stack for future exploration.
10350  * when the verifier reaches bpf_exit insn some of the verifer states
10351  * stored in the state lists have their final liveness state already,
10352  * but a lot of states will get revised from liveness point of view when
10353  * the verifier explores other branches.
10354  * Example:
10355  * 1: r0 = 1
10356  * 2: if r1 == 100 goto pc+1
10357  * 3: r0 = 2
10358  * 4: exit
10359  * when the verifier reaches exit insn the register r0 in the state list of
10360  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10361  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10362  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10363  *
10364  * Since the verifier pushes the branch states as it sees them while exploring
10365  * the program the condition of walking the branch instruction for the second
10366  * time means that all states below this branch were already explored and
10367  * their final liveness marks are already propagated.
10368  * Hence when the verifier completes the search of state list in is_state_visited()
10369  * we can call this clean_live_states() function to mark all liveness states
10370  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10371  * will not be used.
10372  * This function also clears the registers and stack for states that !READ
10373  * to simplify state merging.
10374  *
10375  * Important note here that walking the same branch instruction in the callee
10376  * doesn't meant that the states are DONE. The verifier has to compare
10377  * the callsites
10378  */
10379 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10380 			      struct bpf_verifier_state *cur)
10381 {
10382 	struct bpf_verifier_state_list *sl;
10383 	int i;
10384 
10385 	sl = *explored_state(env, insn);
10386 	while (sl) {
10387 		if (sl->state.branches)
10388 			goto next;
10389 		if (sl->state.insn_idx != insn ||
10390 		    sl->state.curframe != cur->curframe)
10391 			goto next;
10392 		for (i = 0; i <= cur->curframe; i++)
10393 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10394 				goto next;
10395 		clean_verifier_state(env, &sl->state);
10396 next:
10397 		sl = sl->next;
10398 	}
10399 }
10400 
10401 /* Returns true if (rold safe implies rcur safe) */
10402 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10403 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10404 {
10405 	bool equal;
10406 
10407 	if (!(rold->live & REG_LIVE_READ))
10408 		/* explored state didn't use this */
10409 		return true;
10410 
10411 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10412 
10413 	if (rold->type == PTR_TO_STACK)
10414 		/* two stack pointers are equal only if they're pointing to
10415 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10416 		 */
10417 		return equal && rold->frameno == rcur->frameno;
10418 
10419 	if (equal)
10420 		return true;
10421 
10422 	if (rold->type == NOT_INIT)
10423 		/* explored state can't have used this */
10424 		return true;
10425 	if (rcur->type == NOT_INIT)
10426 		return false;
10427 	switch (rold->type) {
10428 	case SCALAR_VALUE:
10429 		if (env->explore_alu_limits)
10430 			return false;
10431 		if (rcur->type == SCALAR_VALUE) {
10432 			if (!rold->precise && !rcur->precise)
10433 				return true;
10434 			/* new val must satisfy old val knowledge */
10435 			return range_within(rold, rcur) &&
10436 			       tnum_in(rold->var_off, rcur->var_off);
10437 		} else {
10438 			/* We're trying to use a pointer in place of a scalar.
10439 			 * Even if the scalar was unbounded, this could lead to
10440 			 * pointer leaks because scalars are allowed to leak
10441 			 * while pointers are not. We could make this safe in
10442 			 * special cases if root is calling us, but it's
10443 			 * probably not worth the hassle.
10444 			 */
10445 			return false;
10446 		}
10447 	case PTR_TO_MAP_KEY:
10448 	case PTR_TO_MAP_VALUE:
10449 		/* If the new min/max/var_off satisfy the old ones and
10450 		 * everything else matches, we are OK.
10451 		 * 'id' is not compared, since it's only used for maps with
10452 		 * bpf_spin_lock inside map element and in such cases if
10453 		 * the rest of the prog is valid for one map element then
10454 		 * it's valid for all map elements regardless of the key
10455 		 * used in bpf_map_lookup()
10456 		 */
10457 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10458 		       range_within(rold, rcur) &&
10459 		       tnum_in(rold->var_off, rcur->var_off);
10460 	case PTR_TO_MAP_VALUE_OR_NULL:
10461 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10462 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10463 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10464 		 * checked, doing so could have affected others with the same
10465 		 * id, and we can't check for that because we lost the id when
10466 		 * we converted to a PTR_TO_MAP_VALUE.
10467 		 */
10468 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10469 			return false;
10470 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10471 			return false;
10472 		/* Check our ids match any regs they're supposed to */
10473 		return check_ids(rold->id, rcur->id, idmap);
10474 	case PTR_TO_PACKET_META:
10475 	case PTR_TO_PACKET:
10476 		if (rcur->type != rold->type)
10477 			return false;
10478 		/* We must have at least as much range as the old ptr
10479 		 * did, so that any accesses which were safe before are
10480 		 * still safe.  This is true even if old range < old off,
10481 		 * since someone could have accessed through (ptr - k), or
10482 		 * even done ptr -= k in a register, to get a safe access.
10483 		 */
10484 		if (rold->range > rcur->range)
10485 			return false;
10486 		/* If the offsets don't match, we can't trust our alignment;
10487 		 * nor can we be sure that we won't fall out of range.
10488 		 */
10489 		if (rold->off != rcur->off)
10490 			return false;
10491 		/* id relations must be preserved */
10492 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10493 			return false;
10494 		/* new val must satisfy old val knowledge */
10495 		return range_within(rold, rcur) &&
10496 		       tnum_in(rold->var_off, rcur->var_off);
10497 	case PTR_TO_CTX:
10498 	case CONST_PTR_TO_MAP:
10499 	case PTR_TO_PACKET_END:
10500 	case PTR_TO_FLOW_KEYS:
10501 	case PTR_TO_SOCKET:
10502 	case PTR_TO_SOCKET_OR_NULL:
10503 	case PTR_TO_SOCK_COMMON:
10504 	case PTR_TO_SOCK_COMMON_OR_NULL:
10505 	case PTR_TO_TCP_SOCK:
10506 	case PTR_TO_TCP_SOCK_OR_NULL:
10507 	case PTR_TO_XDP_SOCK:
10508 		/* Only valid matches are exact, which memcmp() above
10509 		 * would have accepted
10510 		 */
10511 	default:
10512 		/* Don't know what's going on, just say it's not safe */
10513 		return false;
10514 	}
10515 
10516 	/* Shouldn't get here; if we do, say it's not safe */
10517 	WARN_ON_ONCE(1);
10518 	return false;
10519 }
10520 
10521 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10522 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10523 {
10524 	int i, spi;
10525 
10526 	/* walk slots of the explored stack and ignore any additional
10527 	 * slots in the current stack, since explored(safe) state
10528 	 * didn't use them
10529 	 */
10530 	for (i = 0; i < old->allocated_stack; i++) {
10531 		spi = i / BPF_REG_SIZE;
10532 
10533 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10534 			i += BPF_REG_SIZE - 1;
10535 			/* explored state didn't use this */
10536 			continue;
10537 		}
10538 
10539 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10540 			continue;
10541 
10542 		/* explored stack has more populated slots than current stack
10543 		 * and these slots were used
10544 		 */
10545 		if (i >= cur->allocated_stack)
10546 			return false;
10547 
10548 		/* if old state was safe with misc data in the stack
10549 		 * it will be safe with zero-initialized stack.
10550 		 * The opposite is not true
10551 		 */
10552 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10553 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10554 			continue;
10555 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10556 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10557 			/* Ex: old explored (safe) state has STACK_SPILL in
10558 			 * this stack slot, but current has STACK_MISC ->
10559 			 * this verifier states are not equivalent,
10560 			 * return false to continue verification of this path
10561 			 */
10562 			return false;
10563 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10564 			continue;
10565 		if (!is_spilled_reg(&old->stack[spi]))
10566 			continue;
10567 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10568 			     &cur->stack[spi].spilled_ptr, idmap))
10569 			/* when explored and current stack slot are both storing
10570 			 * spilled registers, check that stored pointers types
10571 			 * are the same as well.
10572 			 * Ex: explored safe path could have stored
10573 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10574 			 * but current path has stored:
10575 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10576 			 * such verifier states are not equivalent.
10577 			 * return false to continue verification of this path
10578 			 */
10579 			return false;
10580 	}
10581 	return true;
10582 }
10583 
10584 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10585 {
10586 	if (old->acquired_refs != cur->acquired_refs)
10587 		return false;
10588 	return !memcmp(old->refs, cur->refs,
10589 		       sizeof(*old->refs) * old->acquired_refs);
10590 }
10591 
10592 /* compare two verifier states
10593  *
10594  * all states stored in state_list are known to be valid, since
10595  * verifier reached 'bpf_exit' instruction through them
10596  *
10597  * this function is called when verifier exploring different branches of
10598  * execution popped from the state stack. If it sees an old state that has
10599  * more strict register state and more strict stack state then this execution
10600  * branch doesn't need to be explored further, since verifier already
10601  * concluded that more strict state leads to valid finish.
10602  *
10603  * Therefore two states are equivalent if register state is more conservative
10604  * and explored stack state is more conservative than the current one.
10605  * Example:
10606  *       explored                   current
10607  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10608  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10609  *
10610  * In other words if current stack state (one being explored) has more
10611  * valid slots than old one that already passed validation, it means
10612  * the verifier can stop exploring and conclude that current state is valid too
10613  *
10614  * Similarly with registers. If explored state has register type as invalid
10615  * whereas register type in current state is meaningful, it means that
10616  * the current state will reach 'bpf_exit' instruction safely
10617  */
10618 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10619 			      struct bpf_func_state *cur)
10620 {
10621 	int i;
10622 
10623 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10624 	for (i = 0; i < MAX_BPF_REG; i++)
10625 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10626 			     env->idmap_scratch))
10627 			return false;
10628 
10629 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10630 		return false;
10631 
10632 	if (!refsafe(old, cur))
10633 		return false;
10634 
10635 	return true;
10636 }
10637 
10638 static bool states_equal(struct bpf_verifier_env *env,
10639 			 struct bpf_verifier_state *old,
10640 			 struct bpf_verifier_state *cur)
10641 {
10642 	int i;
10643 
10644 	if (old->curframe != cur->curframe)
10645 		return false;
10646 
10647 	/* Verification state from speculative execution simulation
10648 	 * must never prune a non-speculative execution one.
10649 	 */
10650 	if (old->speculative && !cur->speculative)
10651 		return false;
10652 
10653 	if (old->active_spin_lock != cur->active_spin_lock)
10654 		return false;
10655 
10656 	/* for states to be equal callsites have to be the same
10657 	 * and all frame states need to be equivalent
10658 	 */
10659 	for (i = 0; i <= old->curframe; i++) {
10660 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10661 			return false;
10662 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10663 			return false;
10664 	}
10665 	return true;
10666 }
10667 
10668 /* Return 0 if no propagation happened. Return negative error code if error
10669  * happened. Otherwise, return the propagated bit.
10670  */
10671 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10672 				  struct bpf_reg_state *reg,
10673 				  struct bpf_reg_state *parent_reg)
10674 {
10675 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10676 	u8 flag = reg->live & REG_LIVE_READ;
10677 	int err;
10678 
10679 	/* When comes here, read flags of PARENT_REG or REG could be any of
10680 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10681 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10682 	 */
10683 	if (parent_flag == REG_LIVE_READ64 ||
10684 	    /* Or if there is no read flag from REG. */
10685 	    !flag ||
10686 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10687 	    parent_flag == flag)
10688 		return 0;
10689 
10690 	err = mark_reg_read(env, reg, parent_reg, flag);
10691 	if (err)
10692 		return err;
10693 
10694 	return flag;
10695 }
10696 
10697 /* A write screens off any subsequent reads; but write marks come from the
10698  * straight-line code between a state and its parent.  When we arrive at an
10699  * equivalent state (jump target or such) we didn't arrive by the straight-line
10700  * code, so read marks in the state must propagate to the parent regardless
10701  * of the state's write marks. That's what 'parent == state->parent' comparison
10702  * in mark_reg_read() is for.
10703  */
10704 static int propagate_liveness(struct bpf_verifier_env *env,
10705 			      const struct bpf_verifier_state *vstate,
10706 			      struct bpf_verifier_state *vparent)
10707 {
10708 	struct bpf_reg_state *state_reg, *parent_reg;
10709 	struct bpf_func_state *state, *parent;
10710 	int i, frame, err = 0;
10711 
10712 	if (vparent->curframe != vstate->curframe) {
10713 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10714 		     vparent->curframe, vstate->curframe);
10715 		return -EFAULT;
10716 	}
10717 	/* Propagate read liveness of registers... */
10718 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10719 	for (frame = 0; frame <= vstate->curframe; frame++) {
10720 		parent = vparent->frame[frame];
10721 		state = vstate->frame[frame];
10722 		parent_reg = parent->regs;
10723 		state_reg = state->regs;
10724 		/* We don't need to worry about FP liveness, it's read-only */
10725 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10726 			err = propagate_liveness_reg(env, &state_reg[i],
10727 						     &parent_reg[i]);
10728 			if (err < 0)
10729 				return err;
10730 			if (err == REG_LIVE_READ64)
10731 				mark_insn_zext(env, &parent_reg[i]);
10732 		}
10733 
10734 		/* Propagate stack slots. */
10735 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10736 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10737 			parent_reg = &parent->stack[i].spilled_ptr;
10738 			state_reg = &state->stack[i].spilled_ptr;
10739 			err = propagate_liveness_reg(env, state_reg,
10740 						     parent_reg);
10741 			if (err < 0)
10742 				return err;
10743 		}
10744 	}
10745 	return 0;
10746 }
10747 
10748 /* find precise scalars in the previous equivalent state and
10749  * propagate them into the current state
10750  */
10751 static int propagate_precision(struct bpf_verifier_env *env,
10752 			       const struct bpf_verifier_state *old)
10753 {
10754 	struct bpf_reg_state *state_reg;
10755 	struct bpf_func_state *state;
10756 	int i, err = 0;
10757 
10758 	state = old->frame[old->curframe];
10759 	state_reg = state->regs;
10760 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10761 		if (state_reg->type != SCALAR_VALUE ||
10762 		    !state_reg->precise)
10763 			continue;
10764 		if (env->log.level & BPF_LOG_LEVEL2)
10765 			verbose(env, "propagating r%d\n", i);
10766 		err = mark_chain_precision(env, i);
10767 		if (err < 0)
10768 			return err;
10769 	}
10770 
10771 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10772 		if (!is_spilled_reg(&state->stack[i]))
10773 			continue;
10774 		state_reg = &state->stack[i].spilled_ptr;
10775 		if (state_reg->type != SCALAR_VALUE ||
10776 		    !state_reg->precise)
10777 			continue;
10778 		if (env->log.level & BPF_LOG_LEVEL2)
10779 			verbose(env, "propagating fp%d\n",
10780 				(-i - 1) * BPF_REG_SIZE);
10781 		err = mark_chain_precision_stack(env, i);
10782 		if (err < 0)
10783 			return err;
10784 	}
10785 	return 0;
10786 }
10787 
10788 static bool states_maybe_looping(struct bpf_verifier_state *old,
10789 				 struct bpf_verifier_state *cur)
10790 {
10791 	struct bpf_func_state *fold, *fcur;
10792 	int i, fr = cur->curframe;
10793 
10794 	if (old->curframe != fr)
10795 		return false;
10796 
10797 	fold = old->frame[fr];
10798 	fcur = cur->frame[fr];
10799 	for (i = 0; i < MAX_BPF_REG; i++)
10800 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10801 			   offsetof(struct bpf_reg_state, parent)))
10802 			return false;
10803 	return true;
10804 }
10805 
10806 
10807 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10808 {
10809 	struct bpf_verifier_state_list *new_sl;
10810 	struct bpf_verifier_state_list *sl, **pprev;
10811 	struct bpf_verifier_state *cur = env->cur_state, *new;
10812 	int i, j, err, states_cnt = 0;
10813 	bool add_new_state = env->test_state_freq ? true : false;
10814 
10815 	cur->last_insn_idx = env->prev_insn_idx;
10816 	if (!env->insn_aux_data[insn_idx].prune_point)
10817 		/* this 'insn_idx' instruction wasn't marked, so we will not
10818 		 * be doing state search here
10819 		 */
10820 		return 0;
10821 
10822 	/* bpf progs typically have pruning point every 4 instructions
10823 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10824 	 * Do not add new state for future pruning if the verifier hasn't seen
10825 	 * at least 2 jumps and at least 8 instructions.
10826 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10827 	 * In tests that amounts to up to 50% reduction into total verifier
10828 	 * memory consumption and 20% verifier time speedup.
10829 	 */
10830 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10831 	    env->insn_processed - env->prev_insn_processed >= 8)
10832 		add_new_state = true;
10833 
10834 	pprev = explored_state(env, insn_idx);
10835 	sl = *pprev;
10836 
10837 	clean_live_states(env, insn_idx, cur);
10838 
10839 	while (sl) {
10840 		states_cnt++;
10841 		if (sl->state.insn_idx != insn_idx)
10842 			goto next;
10843 
10844 		if (sl->state.branches) {
10845 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10846 
10847 			if (frame->in_async_callback_fn &&
10848 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10849 				/* Different async_entry_cnt means that the verifier is
10850 				 * processing another entry into async callback.
10851 				 * Seeing the same state is not an indication of infinite
10852 				 * loop or infinite recursion.
10853 				 * But finding the same state doesn't mean that it's safe
10854 				 * to stop processing the current state. The previous state
10855 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10856 				 * Checking in_async_callback_fn alone is not enough either.
10857 				 * Since the verifier still needs to catch infinite loops
10858 				 * inside async callbacks.
10859 				 */
10860 			} else if (states_maybe_looping(&sl->state, cur) &&
10861 				   states_equal(env, &sl->state, cur)) {
10862 				verbose_linfo(env, insn_idx, "; ");
10863 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10864 				return -EINVAL;
10865 			}
10866 			/* if the verifier is processing a loop, avoid adding new state
10867 			 * too often, since different loop iterations have distinct
10868 			 * states and may not help future pruning.
10869 			 * This threshold shouldn't be too low to make sure that
10870 			 * a loop with large bound will be rejected quickly.
10871 			 * The most abusive loop will be:
10872 			 * r1 += 1
10873 			 * if r1 < 1000000 goto pc-2
10874 			 * 1M insn_procssed limit / 100 == 10k peak states.
10875 			 * This threshold shouldn't be too high either, since states
10876 			 * at the end of the loop are likely to be useful in pruning.
10877 			 */
10878 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10879 			    env->insn_processed - env->prev_insn_processed < 100)
10880 				add_new_state = false;
10881 			goto miss;
10882 		}
10883 		if (states_equal(env, &sl->state, cur)) {
10884 			sl->hit_cnt++;
10885 			/* reached equivalent register/stack state,
10886 			 * prune the search.
10887 			 * Registers read by the continuation are read by us.
10888 			 * If we have any write marks in env->cur_state, they
10889 			 * will prevent corresponding reads in the continuation
10890 			 * from reaching our parent (an explored_state).  Our
10891 			 * own state will get the read marks recorded, but
10892 			 * they'll be immediately forgotten as we're pruning
10893 			 * this state and will pop a new one.
10894 			 */
10895 			err = propagate_liveness(env, &sl->state, cur);
10896 
10897 			/* if previous state reached the exit with precision and
10898 			 * current state is equivalent to it (except precsion marks)
10899 			 * the precision needs to be propagated back in
10900 			 * the current state.
10901 			 */
10902 			err = err ? : push_jmp_history(env, cur);
10903 			err = err ? : propagate_precision(env, &sl->state);
10904 			if (err)
10905 				return err;
10906 			return 1;
10907 		}
10908 miss:
10909 		/* when new state is not going to be added do not increase miss count.
10910 		 * Otherwise several loop iterations will remove the state
10911 		 * recorded earlier. The goal of these heuristics is to have
10912 		 * states from some iterations of the loop (some in the beginning
10913 		 * and some at the end) to help pruning.
10914 		 */
10915 		if (add_new_state)
10916 			sl->miss_cnt++;
10917 		/* heuristic to determine whether this state is beneficial
10918 		 * to keep checking from state equivalence point of view.
10919 		 * Higher numbers increase max_states_per_insn and verification time,
10920 		 * but do not meaningfully decrease insn_processed.
10921 		 */
10922 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10923 			/* the state is unlikely to be useful. Remove it to
10924 			 * speed up verification
10925 			 */
10926 			*pprev = sl->next;
10927 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10928 				u32 br = sl->state.branches;
10929 
10930 				WARN_ONCE(br,
10931 					  "BUG live_done but branches_to_explore %d\n",
10932 					  br);
10933 				free_verifier_state(&sl->state, false);
10934 				kfree(sl);
10935 				env->peak_states--;
10936 			} else {
10937 				/* cannot free this state, since parentage chain may
10938 				 * walk it later. Add it for free_list instead to
10939 				 * be freed at the end of verification
10940 				 */
10941 				sl->next = env->free_list;
10942 				env->free_list = sl;
10943 			}
10944 			sl = *pprev;
10945 			continue;
10946 		}
10947 next:
10948 		pprev = &sl->next;
10949 		sl = *pprev;
10950 	}
10951 
10952 	if (env->max_states_per_insn < states_cnt)
10953 		env->max_states_per_insn = states_cnt;
10954 
10955 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10956 		return push_jmp_history(env, cur);
10957 
10958 	if (!add_new_state)
10959 		return push_jmp_history(env, cur);
10960 
10961 	/* There were no equivalent states, remember the current one.
10962 	 * Technically the current state is not proven to be safe yet,
10963 	 * but it will either reach outer most bpf_exit (which means it's safe)
10964 	 * or it will be rejected. When there are no loops the verifier won't be
10965 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10966 	 * again on the way to bpf_exit.
10967 	 * When looping the sl->state.branches will be > 0 and this state
10968 	 * will not be considered for equivalence until branches == 0.
10969 	 */
10970 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10971 	if (!new_sl)
10972 		return -ENOMEM;
10973 	env->total_states++;
10974 	env->peak_states++;
10975 	env->prev_jmps_processed = env->jmps_processed;
10976 	env->prev_insn_processed = env->insn_processed;
10977 
10978 	/* add new state to the head of linked list */
10979 	new = &new_sl->state;
10980 	err = copy_verifier_state(new, cur);
10981 	if (err) {
10982 		free_verifier_state(new, false);
10983 		kfree(new_sl);
10984 		return err;
10985 	}
10986 	new->insn_idx = insn_idx;
10987 	WARN_ONCE(new->branches != 1,
10988 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10989 
10990 	cur->parent = new;
10991 	cur->first_insn_idx = insn_idx;
10992 	clear_jmp_history(cur);
10993 	new_sl->next = *explored_state(env, insn_idx);
10994 	*explored_state(env, insn_idx) = new_sl;
10995 	/* connect new state to parentage chain. Current frame needs all
10996 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
10997 	 * to the stack implicitly by JITs) so in callers' frames connect just
10998 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10999 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11000 	 * from callee with its full parentage chain, anyway.
11001 	 */
11002 	/* clear write marks in current state: the writes we did are not writes
11003 	 * our child did, so they don't screen off its reads from us.
11004 	 * (There are no read marks in current state, because reads always mark
11005 	 * their parent and current state never has children yet.  Only
11006 	 * explored_states can get read marks.)
11007 	 */
11008 	for (j = 0; j <= cur->curframe; j++) {
11009 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11010 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11011 		for (i = 0; i < BPF_REG_FP; i++)
11012 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11013 	}
11014 
11015 	/* all stack frames are accessible from callee, clear them all */
11016 	for (j = 0; j <= cur->curframe; j++) {
11017 		struct bpf_func_state *frame = cur->frame[j];
11018 		struct bpf_func_state *newframe = new->frame[j];
11019 
11020 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11021 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11022 			frame->stack[i].spilled_ptr.parent =
11023 						&newframe->stack[i].spilled_ptr;
11024 		}
11025 	}
11026 	return 0;
11027 }
11028 
11029 /* Return true if it's OK to have the same insn return a different type. */
11030 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11031 {
11032 	switch (type) {
11033 	case PTR_TO_CTX:
11034 	case PTR_TO_SOCKET:
11035 	case PTR_TO_SOCKET_OR_NULL:
11036 	case PTR_TO_SOCK_COMMON:
11037 	case PTR_TO_SOCK_COMMON_OR_NULL:
11038 	case PTR_TO_TCP_SOCK:
11039 	case PTR_TO_TCP_SOCK_OR_NULL:
11040 	case PTR_TO_XDP_SOCK:
11041 	case PTR_TO_BTF_ID:
11042 	case PTR_TO_BTF_ID_OR_NULL:
11043 		return false;
11044 	default:
11045 		return true;
11046 	}
11047 }
11048 
11049 /* If an instruction was previously used with particular pointer types, then we
11050  * need to be careful to avoid cases such as the below, where it may be ok
11051  * for one branch accessing the pointer, but not ok for the other branch:
11052  *
11053  * R1 = sock_ptr
11054  * goto X;
11055  * ...
11056  * R1 = some_other_valid_ptr;
11057  * goto X;
11058  * ...
11059  * R2 = *(u32 *)(R1 + 0);
11060  */
11061 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11062 {
11063 	return src != prev && (!reg_type_mismatch_ok(src) ||
11064 			       !reg_type_mismatch_ok(prev));
11065 }
11066 
11067 static int do_check(struct bpf_verifier_env *env)
11068 {
11069 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11070 	struct bpf_verifier_state *state = env->cur_state;
11071 	struct bpf_insn *insns = env->prog->insnsi;
11072 	struct bpf_reg_state *regs;
11073 	int insn_cnt = env->prog->len;
11074 	bool do_print_state = false;
11075 	int prev_insn_idx = -1;
11076 
11077 	for (;;) {
11078 		struct bpf_insn *insn;
11079 		u8 class;
11080 		int err;
11081 
11082 		env->prev_insn_idx = prev_insn_idx;
11083 		if (env->insn_idx >= insn_cnt) {
11084 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11085 				env->insn_idx, insn_cnt);
11086 			return -EFAULT;
11087 		}
11088 
11089 		insn = &insns[env->insn_idx];
11090 		class = BPF_CLASS(insn->code);
11091 
11092 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11093 			verbose(env,
11094 				"BPF program is too large. Processed %d insn\n",
11095 				env->insn_processed);
11096 			return -E2BIG;
11097 		}
11098 
11099 		err = is_state_visited(env, env->insn_idx);
11100 		if (err < 0)
11101 			return err;
11102 		if (err == 1) {
11103 			/* found equivalent state, can prune the search */
11104 			if (env->log.level & BPF_LOG_LEVEL) {
11105 				if (do_print_state)
11106 					verbose(env, "\nfrom %d to %d%s: safe\n",
11107 						env->prev_insn_idx, env->insn_idx,
11108 						env->cur_state->speculative ?
11109 						" (speculative execution)" : "");
11110 				else
11111 					verbose(env, "%d: safe\n", env->insn_idx);
11112 			}
11113 			goto process_bpf_exit;
11114 		}
11115 
11116 		if (signal_pending(current))
11117 			return -EAGAIN;
11118 
11119 		if (need_resched())
11120 			cond_resched();
11121 
11122 		if (env->log.level & BPF_LOG_LEVEL2 ||
11123 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
11124 			if (env->log.level & BPF_LOG_LEVEL2)
11125 				verbose(env, "%d:", env->insn_idx);
11126 			else
11127 				verbose(env, "\nfrom %d to %d%s:",
11128 					env->prev_insn_idx, env->insn_idx,
11129 					env->cur_state->speculative ?
11130 					" (speculative execution)" : "");
11131 			print_verifier_state(env, state->frame[state->curframe]);
11132 			do_print_state = false;
11133 		}
11134 
11135 		if (env->log.level & BPF_LOG_LEVEL) {
11136 			const struct bpf_insn_cbs cbs = {
11137 				.cb_call	= disasm_kfunc_name,
11138 				.cb_print	= verbose,
11139 				.private_data	= env,
11140 			};
11141 
11142 			verbose_linfo(env, env->insn_idx, "; ");
11143 			verbose(env, "%d: ", env->insn_idx);
11144 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11145 		}
11146 
11147 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11148 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11149 							   env->prev_insn_idx);
11150 			if (err)
11151 				return err;
11152 		}
11153 
11154 		regs = cur_regs(env);
11155 		sanitize_mark_insn_seen(env);
11156 		prev_insn_idx = env->insn_idx;
11157 
11158 		if (class == BPF_ALU || class == BPF_ALU64) {
11159 			err = check_alu_op(env, insn);
11160 			if (err)
11161 				return err;
11162 
11163 		} else if (class == BPF_LDX) {
11164 			enum bpf_reg_type *prev_src_type, src_reg_type;
11165 
11166 			/* check for reserved fields is already done */
11167 
11168 			/* check src operand */
11169 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11170 			if (err)
11171 				return err;
11172 
11173 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11174 			if (err)
11175 				return err;
11176 
11177 			src_reg_type = regs[insn->src_reg].type;
11178 
11179 			/* check that memory (src_reg + off) is readable,
11180 			 * the state of dst_reg will be updated by this func
11181 			 */
11182 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11183 					       insn->off, BPF_SIZE(insn->code),
11184 					       BPF_READ, insn->dst_reg, false);
11185 			if (err)
11186 				return err;
11187 
11188 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11189 
11190 			if (*prev_src_type == NOT_INIT) {
11191 				/* saw a valid insn
11192 				 * dst_reg = *(u32 *)(src_reg + off)
11193 				 * save type to validate intersecting paths
11194 				 */
11195 				*prev_src_type = src_reg_type;
11196 
11197 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11198 				/* ABuser program is trying to use the same insn
11199 				 * dst_reg = *(u32*) (src_reg + off)
11200 				 * with different pointer types:
11201 				 * src_reg == ctx in one branch and
11202 				 * src_reg == stack|map in some other branch.
11203 				 * Reject it.
11204 				 */
11205 				verbose(env, "same insn cannot be used with different pointers\n");
11206 				return -EINVAL;
11207 			}
11208 
11209 		} else if (class == BPF_STX) {
11210 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11211 
11212 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11213 				err = check_atomic(env, env->insn_idx, insn);
11214 				if (err)
11215 					return err;
11216 				env->insn_idx++;
11217 				continue;
11218 			}
11219 
11220 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11221 				verbose(env, "BPF_STX uses reserved fields\n");
11222 				return -EINVAL;
11223 			}
11224 
11225 			/* check src1 operand */
11226 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11227 			if (err)
11228 				return err;
11229 			/* check src2 operand */
11230 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11231 			if (err)
11232 				return err;
11233 
11234 			dst_reg_type = regs[insn->dst_reg].type;
11235 
11236 			/* check that memory (dst_reg + off) is writeable */
11237 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11238 					       insn->off, BPF_SIZE(insn->code),
11239 					       BPF_WRITE, insn->src_reg, false);
11240 			if (err)
11241 				return err;
11242 
11243 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11244 
11245 			if (*prev_dst_type == NOT_INIT) {
11246 				*prev_dst_type = dst_reg_type;
11247 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11248 				verbose(env, "same insn cannot be used with different pointers\n");
11249 				return -EINVAL;
11250 			}
11251 
11252 		} else if (class == BPF_ST) {
11253 			if (BPF_MODE(insn->code) != BPF_MEM ||
11254 			    insn->src_reg != BPF_REG_0) {
11255 				verbose(env, "BPF_ST uses reserved fields\n");
11256 				return -EINVAL;
11257 			}
11258 			/* check src operand */
11259 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11260 			if (err)
11261 				return err;
11262 
11263 			if (is_ctx_reg(env, insn->dst_reg)) {
11264 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11265 					insn->dst_reg,
11266 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
11267 				return -EACCES;
11268 			}
11269 
11270 			/* check that memory (dst_reg + off) is writeable */
11271 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11272 					       insn->off, BPF_SIZE(insn->code),
11273 					       BPF_WRITE, -1, false);
11274 			if (err)
11275 				return err;
11276 
11277 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11278 			u8 opcode = BPF_OP(insn->code);
11279 
11280 			env->jmps_processed++;
11281 			if (opcode == BPF_CALL) {
11282 				if (BPF_SRC(insn->code) != BPF_K ||
11283 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11284 				     && insn->off != 0) ||
11285 				    (insn->src_reg != BPF_REG_0 &&
11286 				     insn->src_reg != BPF_PSEUDO_CALL &&
11287 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11288 				    insn->dst_reg != BPF_REG_0 ||
11289 				    class == BPF_JMP32) {
11290 					verbose(env, "BPF_CALL uses reserved fields\n");
11291 					return -EINVAL;
11292 				}
11293 
11294 				if (env->cur_state->active_spin_lock &&
11295 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11296 				     insn->imm != BPF_FUNC_spin_unlock)) {
11297 					verbose(env, "function calls are not allowed while holding a lock\n");
11298 					return -EINVAL;
11299 				}
11300 				if (insn->src_reg == BPF_PSEUDO_CALL)
11301 					err = check_func_call(env, insn, &env->insn_idx);
11302 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11303 					err = check_kfunc_call(env, insn);
11304 				else
11305 					err = check_helper_call(env, insn, &env->insn_idx);
11306 				if (err)
11307 					return err;
11308 			} else if (opcode == BPF_JA) {
11309 				if (BPF_SRC(insn->code) != BPF_K ||
11310 				    insn->imm != 0 ||
11311 				    insn->src_reg != BPF_REG_0 ||
11312 				    insn->dst_reg != BPF_REG_0 ||
11313 				    class == BPF_JMP32) {
11314 					verbose(env, "BPF_JA uses reserved fields\n");
11315 					return -EINVAL;
11316 				}
11317 
11318 				env->insn_idx += insn->off + 1;
11319 				continue;
11320 
11321 			} else if (opcode == BPF_EXIT) {
11322 				if (BPF_SRC(insn->code) != BPF_K ||
11323 				    insn->imm != 0 ||
11324 				    insn->src_reg != BPF_REG_0 ||
11325 				    insn->dst_reg != BPF_REG_0 ||
11326 				    class == BPF_JMP32) {
11327 					verbose(env, "BPF_EXIT uses reserved fields\n");
11328 					return -EINVAL;
11329 				}
11330 
11331 				if (env->cur_state->active_spin_lock) {
11332 					verbose(env, "bpf_spin_unlock is missing\n");
11333 					return -EINVAL;
11334 				}
11335 
11336 				if (state->curframe) {
11337 					/* exit from nested function */
11338 					err = prepare_func_exit(env, &env->insn_idx);
11339 					if (err)
11340 						return err;
11341 					do_print_state = true;
11342 					continue;
11343 				}
11344 
11345 				err = check_reference_leak(env);
11346 				if (err)
11347 					return err;
11348 
11349 				err = check_return_code(env);
11350 				if (err)
11351 					return err;
11352 process_bpf_exit:
11353 				update_branch_counts(env, env->cur_state);
11354 				err = pop_stack(env, &prev_insn_idx,
11355 						&env->insn_idx, pop_log);
11356 				if (err < 0) {
11357 					if (err != -ENOENT)
11358 						return err;
11359 					break;
11360 				} else {
11361 					do_print_state = true;
11362 					continue;
11363 				}
11364 			} else {
11365 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11366 				if (err)
11367 					return err;
11368 			}
11369 		} else if (class == BPF_LD) {
11370 			u8 mode = BPF_MODE(insn->code);
11371 
11372 			if (mode == BPF_ABS || mode == BPF_IND) {
11373 				err = check_ld_abs(env, insn);
11374 				if (err)
11375 					return err;
11376 
11377 			} else if (mode == BPF_IMM) {
11378 				err = check_ld_imm(env, insn);
11379 				if (err)
11380 					return err;
11381 
11382 				env->insn_idx++;
11383 				sanitize_mark_insn_seen(env);
11384 			} else {
11385 				verbose(env, "invalid BPF_LD mode\n");
11386 				return -EINVAL;
11387 			}
11388 		} else {
11389 			verbose(env, "unknown insn class %d\n", class);
11390 			return -EINVAL;
11391 		}
11392 
11393 		env->insn_idx++;
11394 	}
11395 
11396 	return 0;
11397 }
11398 
11399 static int find_btf_percpu_datasec(struct btf *btf)
11400 {
11401 	const struct btf_type *t;
11402 	const char *tname;
11403 	int i, n;
11404 
11405 	/*
11406 	 * Both vmlinux and module each have their own ".data..percpu"
11407 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11408 	 * types to look at only module's own BTF types.
11409 	 */
11410 	n = btf_nr_types(btf);
11411 	if (btf_is_module(btf))
11412 		i = btf_nr_types(btf_vmlinux);
11413 	else
11414 		i = 1;
11415 
11416 	for(; i < n; i++) {
11417 		t = btf_type_by_id(btf, i);
11418 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11419 			continue;
11420 
11421 		tname = btf_name_by_offset(btf, t->name_off);
11422 		if (!strcmp(tname, ".data..percpu"))
11423 			return i;
11424 	}
11425 
11426 	return -ENOENT;
11427 }
11428 
11429 /* replace pseudo btf_id with kernel symbol address */
11430 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11431 			       struct bpf_insn *insn,
11432 			       struct bpf_insn_aux_data *aux)
11433 {
11434 	const struct btf_var_secinfo *vsi;
11435 	const struct btf_type *datasec;
11436 	struct btf_mod_pair *btf_mod;
11437 	const struct btf_type *t;
11438 	const char *sym_name;
11439 	bool percpu = false;
11440 	u32 type, id = insn->imm;
11441 	struct btf *btf;
11442 	s32 datasec_id;
11443 	u64 addr;
11444 	int i, btf_fd, err;
11445 
11446 	btf_fd = insn[1].imm;
11447 	if (btf_fd) {
11448 		btf = btf_get_by_fd(btf_fd);
11449 		if (IS_ERR(btf)) {
11450 			verbose(env, "invalid module BTF object FD specified.\n");
11451 			return -EINVAL;
11452 		}
11453 	} else {
11454 		if (!btf_vmlinux) {
11455 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11456 			return -EINVAL;
11457 		}
11458 		btf = btf_vmlinux;
11459 		btf_get(btf);
11460 	}
11461 
11462 	t = btf_type_by_id(btf, id);
11463 	if (!t) {
11464 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11465 		err = -ENOENT;
11466 		goto err_put;
11467 	}
11468 
11469 	if (!btf_type_is_var(t)) {
11470 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11471 		err = -EINVAL;
11472 		goto err_put;
11473 	}
11474 
11475 	sym_name = btf_name_by_offset(btf, t->name_off);
11476 	addr = kallsyms_lookup_name(sym_name);
11477 	if (!addr) {
11478 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11479 			sym_name);
11480 		err = -ENOENT;
11481 		goto err_put;
11482 	}
11483 
11484 	datasec_id = find_btf_percpu_datasec(btf);
11485 	if (datasec_id > 0) {
11486 		datasec = btf_type_by_id(btf, datasec_id);
11487 		for_each_vsi(i, datasec, vsi) {
11488 			if (vsi->type == id) {
11489 				percpu = true;
11490 				break;
11491 			}
11492 		}
11493 	}
11494 
11495 	insn[0].imm = (u32)addr;
11496 	insn[1].imm = addr >> 32;
11497 
11498 	type = t->type;
11499 	t = btf_type_skip_modifiers(btf, type, NULL);
11500 	if (percpu) {
11501 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11502 		aux->btf_var.btf = btf;
11503 		aux->btf_var.btf_id = type;
11504 	} else if (!btf_type_is_struct(t)) {
11505 		const struct btf_type *ret;
11506 		const char *tname;
11507 		u32 tsize;
11508 
11509 		/* resolve the type size of ksym. */
11510 		ret = btf_resolve_size(btf, t, &tsize);
11511 		if (IS_ERR(ret)) {
11512 			tname = btf_name_by_offset(btf, t->name_off);
11513 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11514 				tname, PTR_ERR(ret));
11515 			err = -EINVAL;
11516 			goto err_put;
11517 		}
11518 		aux->btf_var.reg_type = PTR_TO_MEM;
11519 		aux->btf_var.mem_size = tsize;
11520 	} else {
11521 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11522 		aux->btf_var.btf = btf;
11523 		aux->btf_var.btf_id = type;
11524 	}
11525 
11526 	/* check whether we recorded this BTF (and maybe module) already */
11527 	for (i = 0; i < env->used_btf_cnt; i++) {
11528 		if (env->used_btfs[i].btf == btf) {
11529 			btf_put(btf);
11530 			return 0;
11531 		}
11532 	}
11533 
11534 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11535 		err = -E2BIG;
11536 		goto err_put;
11537 	}
11538 
11539 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11540 	btf_mod->btf = btf;
11541 	btf_mod->module = NULL;
11542 
11543 	/* if we reference variables from kernel module, bump its refcount */
11544 	if (btf_is_module(btf)) {
11545 		btf_mod->module = btf_try_get_module(btf);
11546 		if (!btf_mod->module) {
11547 			err = -ENXIO;
11548 			goto err_put;
11549 		}
11550 	}
11551 
11552 	env->used_btf_cnt++;
11553 
11554 	return 0;
11555 err_put:
11556 	btf_put(btf);
11557 	return err;
11558 }
11559 
11560 static int check_map_prealloc(struct bpf_map *map)
11561 {
11562 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11563 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11564 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11565 		!(map->map_flags & BPF_F_NO_PREALLOC);
11566 }
11567 
11568 static bool is_tracing_prog_type(enum bpf_prog_type type)
11569 {
11570 	switch (type) {
11571 	case BPF_PROG_TYPE_KPROBE:
11572 	case BPF_PROG_TYPE_TRACEPOINT:
11573 	case BPF_PROG_TYPE_PERF_EVENT:
11574 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11575 		return true;
11576 	default:
11577 		return false;
11578 	}
11579 }
11580 
11581 static bool is_preallocated_map(struct bpf_map *map)
11582 {
11583 	if (!check_map_prealloc(map))
11584 		return false;
11585 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11586 		return false;
11587 	return true;
11588 }
11589 
11590 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11591 					struct bpf_map *map,
11592 					struct bpf_prog *prog)
11593 
11594 {
11595 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11596 	/*
11597 	 * Validate that trace type programs use preallocated hash maps.
11598 	 *
11599 	 * For programs attached to PERF events this is mandatory as the
11600 	 * perf NMI can hit any arbitrary code sequence.
11601 	 *
11602 	 * All other trace types using preallocated hash maps are unsafe as
11603 	 * well because tracepoint or kprobes can be inside locked regions
11604 	 * of the memory allocator or at a place where a recursion into the
11605 	 * memory allocator would see inconsistent state.
11606 	 *
11607 	 * On RT enabled kernels run-time allocation of all trace type
11608 	 * programs is strictly prohibited due to lock type constraints. On
11609 	 * !RT kernels it is allowed for backwards compatibility reasons for
11610 	 * now, but warnings are emitted so developers are made aware of
11611 	 * the unsafety and can fix their programs before this is enforced.
11612 	 */
11613 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11614 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11615 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11616 			return -EINVAL;
11617 		}
11618 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11619 			verbose(env, "trace type programs can only use preallocated hash map\n");
11620 			return -EINVAL;
11621 		}
11622 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11623 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11624 	}
11625 
11626 	if (map_value_has_spin_lock(map)) {
11627 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11628 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11629 			return -EINVAL;
11630 		}
11631 
11632 		if (is_tracing_prog_type(prog_type)) {
11633 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11634 			return -EINVAL;
11635 		}
11636 
11637 		if (prog->aux->sleepable) {
11638 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11639 			return -EINVAL;
11640 		}
11641 	}
11642 
11643 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11644 	    !bpf_offload_prog_map_match(prog, map)) {
11645 		verbose(env, "offload device mismatch between prog and map\n");
11646 		return -EINVAL;
11647 	}
11648 
11649 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11650 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11651 		return -EINVAL;
11652 	}
11653 
11654 	if (prog->aux->sleepable)
11655 		switch (map->map_type) {
11656 		case BPF_MAP_TYPE_HASH:
11657 		case BPF_MAP_TYPE_LRU_HASH:
11658 		case BPF_MAP_TYPE_ARRAY:
11659 		case BPF_MAP_TYPE_PERCPU_HASH:
11660 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11661 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11662 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11663 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11664 			if (!is_preallocated_map(map)) {
11665 				verbose(env,
11666 					"Sleepable programs can only use preallocated maps\n");
11667 				return -EINVAL;
11668 			}
11669 			break;
11670 		case BPF_MAP_TYPE_RINGBUF:
11671 			break;
11672 		default:
11673 			verbose(env,
11674 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11675 			return -EINVAL;
11676 		}
11677 
11678 	return 0;
11679 }
11680 
11681 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11682 {
11683 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11684 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11685 }
11686 
11687 /* find and rewrite pseudo imm in ld_imm64 instructions:
11688  *
11689  * 1. if it accesses map FD, replace it with actual map pointer.
11690  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11691  *
11692  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11693  */
11694 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11695 {
11696 	struct bpf_insn *insn = env->prog->insnsi;
11697 	int insn_cnt = env->prog->len;
11698 	int i, j, err;
11699 
11700 	err = bpf_prog_calc_tag(env->prog);
11701 	if (err)
11702 		return err;
11703 
11704 	for (i = 0; i < insn_cnt; i++, insn++) {
11705 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11706 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11707 			verbose(env, "BPF_LDX uses reserved fields\n");
11708 			return -EINVAL;
11709 		}
11710 
11711 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11712 			struct bpf_insn_aux_data *aux;
11713 			struct bpf_map *map;
11714 			struct fd f;
11715 			u64 addr;
11716 			u32 fd;
11717 
11718 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11719 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11720 			    insn[1].off != 0) {
11721 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11722 				return -EINVAL;
11723 			}
11724 
11725 			if (insn[0].src_reg == 0)
11726 				/* valid generic load 64-bit imm */
11727 				goto next_insn;
11728 
11729 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11730 				aux = &env->insn_aux_data[i];
11731 				err = check_pseudo_btf_id(env, insn, aux);
11732 				if (err)
11733 					return err;
11734 				goto next_insn;
11735 			}
11736 
11737 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11738 				aux = &env->insn_aux_data[i];
11739 				aux->ptr_type = PTR_TO_FUNC;
11740 				goto next_insn;
11741 			}
11742 
11743 			/* In final convert_pseudo_ld_imm64() step, this is
11744 			 * converted into regular 64-bit imm load insn.
11745 			 */
11746 			switch (insn[0].src_reg) {
11747 			case BPF_PSEUDO_MAP_VALUE:
11748 			case BPF_PSEUDO_MAP_IDX_VALUE:
11749 				break;
11750 			case BPF_PSEUDO_MAP_FD:
11751 			case BPF_PSEUDO_MAP_IDX:
11752 				if (insn[1].imm == 0)
11753 					break;
11754 				fallthrough;
11755 			default:
11756 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11757 				return -EINVAL;
11758 			}
11759 
11760 			switch (insn[0].src_reg) {
11761 			case BPF_PSEUDO_MAP_IDX_VALUE:
11762 			case BPF_PSEUDO_MAP_IDX:
11763 				if (bpfptr_is_null(env->fd_array)) {
11764 					verbose(env, "fd_idx without fd_array is invalid\n");
11765 					return -EPROTO;
11766 				}
11767 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11768 							    insn[0].imm * sizeof(fd),
11769 							    sizeof(fd)))
11770 					return -EFAULT;
11771 				break;
11772 			default:
11773 				fd = insn[0].imm;
11774 				break;
11775 			}
11776 
11777 			f = fdget(fd);
11778 			map = __bpf_map_get(f);
11779 			if (IS_ERR(map)) {
11780 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11781 					insn[0].imm);
11782 				return PTR_ERR(map);
11783 			}
11784 
11785 			err = check_map_prog_compatibility(env, map, env->prog);
11786 			if (err) {
11787 				fdput(f);
11788 				return err;
11789 			}
11790 
11791 			aux = &env->insn_aux_data[i];
11792 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11793 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11794 				addr = (unsigned long)map;
11795 			} else {
11796 				u32 off = insn[1].imm;
11797 
11798 				if (off >= BPF_MAX_VAR_OFF) {
11799 					verbose(env, "direct value offset of %u is not allowed\n", off);
11800 					fdput(f);
11801 					return -EINVAL;
11802 				}
11803 
11804 				if (!map->ops->map_direct_value_addr) {
11805 					verbose(env, "no direct value access support for this map type\n");
11806 					fdput(f);
11807 					return -EINVAL;
11808 				}
11809 
11810 				err = map->ops->map_direct_value_addr(map, &addr, off);
11811 				if (err) {
11812 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11813 						map->value_size, off);
11814 					fdput(f);
11815 					return err;
11816 				}
11817 
11818 				aux->map_off = off;
11819 				addr += off;
11820 			}
11821 
11822 			insn[0].imm = (u32)addr;
11823 			insn[1].imm = addr >> 32;
11824 
11825 			/* check whether we recorded this map already */
11826 			for (j = 0; j < env->used_map_cnt; j++) {
11827 				if (env->used_maps[j] == map) {
11828 					aux->map_index = j;
11829 					fdput(f);
11830 					goto next_insn;
11831 				}
11832 			}
11833 
11834 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11835 				fdput(f);
11836 				return -E2BIG;
11837 			}
11838 
11839 			/* hold the map. If the program is rejected by verifier,
11840 			 * the map will be released by release_maps() or it
11841 			 * will be used by the valid program until it's unloaded
11842 			 * and all maps are released in free_used_maps()
11843 			 */
11844 			bpf_map_inc(map);
11845 
11846 			aux->map_index = env->used_map_cnt;
11847 			env->used_maps[env->used_map_cnt++] = map;
11848 
11849 			if (bpf_map_is_cgroup_storage(map) &&
11850 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11851 				verbose(env, "only one cgroup storage of each type is allowed\n");
11852 				fdput(f);
11853 				return -EBUSY;
11854 			}
11855 
11856 			fdput(f);
11857 next_insn:
11858 			insn++;
11859 			i++;
11860 			continue;
11861 		}
11862 
11863 		/* Basic sanity check before we invest more work here. */
11864 		if (!bpf_opcode_in_insntable(insn->code)) {
11865 			verbose(env, "unknown opcode %02x\n", insn->code);
11866 			return -EINVAL;
11867 		}
11868 	}
11869 
11870 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11871 	 * 'struct bpf_map *' into a register instead of user map_fd.
11872 	 * These pointers will be used later by verifier to validate map access.
11873 	 */
11874 	return 0;
11875 }
11876 
11877 /* drop refcnt of maps used by the rejected program */
11878 static void release_maps(struct bpf_verifier_env *env)
11879 {
11880 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11881 			     env->used_map_cnt);
11882 }
11883 
11884 /* drop refcnt of maps used by the rejected program */
11885 static void release_btfs(struct bpf_verifier_env *env)
11886 {
11887 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11888 			     env->used_btf_cnt);
11889 }
11890 
11891 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11892 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11893 {
11894 	struct bpf_insn *insn = env->prog->insnsi;
11895 	int insn_cnt = env->prog->len;
11896 	int i;
11897 
11898 	for (i = 0; i < insn_cnt; i++, insn++) {
11899 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11900 			continue;
11901 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11902 			continue;
11903 		insn->src_reg = 0;
11904 	}
11905 }
11906 
11907 /* single env->prog->insni[off] instruction was replaced with the range
11908  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11909  * [0, off) and [off, end) to new locations, so the patched range stays zero
11910  */
11911 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11912 				 struct bpf_insn_aux_data *new_data,
11913 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11914 {
11915 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11916 	struct bpf_insn *insn = new_prog->insnsi;
11917 	u32 old_seen = old_data[off].seen;
11918 	u32 prog_len;
11919 	int i;
11920 
11921 	/* aux info at OFF always needs adjustment, no matter fast path
11922 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11923 	 * original insn at old prog.
11924 	 */
11925 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11926 
11927 	if (cnt == 1)
11928 		return;
11929 	prog_len = new_prog->len;
11930 
11931 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11932 	memcpy(new_data + off + cnt - 1, old_data + off,
11933 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11934 	for (i = off; i < off + cnt - 1; i++) {
11935 		/* Expand insni[off]'s seen count to the patched range. */
11936 		new_data[i].seen = old_seen;
11937 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11938 	}
11939 	env->insn_aux_data = new_data;
11940 	vfree(old_data);
11941 }
11942 
11943 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11944 {
11945 	int i;
11946 
11947 	if (len == 1)
11948 		return;
11949 	/* NOTE: fake 'exit' subprog should be updated as well. */
11950 	for (i = 0; i <= env->subprog_cnt; i++) {
11951 		if (env->subprog_info[i].start <= off)
11952 			continue;
11953 		env->subprog_info[i].start += len - 1;
11954 	}
11955 }
11956 
11957 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11958 {
11959 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11960 	int i, sz = prog->aux->size_poke_tab;
11961 	struct bpf_jit_poke_descriptor *desc;
11962 
11963 	for (i = 0; i < sz; i++) {
11964 		desc = &tab[i];
11965 		if (desc->insn_idx <= off)
11966 			continue;
11967 		desc->insn_idx += len - 1;
11968 	}
11969 }
11970 
11971 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11972 					    const struct bpf_insn *patch, u32 len)
11973 {
11974 	struct bpf_prog *new_prog;
11975 	struct bpf_insn_aux_data *new_data = NULL;
11976 
11977 	if (len > 1) {
11978 		new_data = vzalloc(array_size(env->prog->len + len - 1,
11979 					      sizeof(struct bpf_insn_aux_data)));
11980 		if (!new_data)
11981 			return NULL;
11982 	}
11983 
11984 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11985 	if (IS_ERR(new_prog)) {
11986 		if (PTR_ERR(new_prog) == -ERANGE)
11987 			verbose(env,
11988 				"insn %d cannot be patched due to 16-bit range\n",
11989 				env->insn_aux_data[off].orig_idx);
11990 		vfree(new_data);
11991 		return NULL;
11992 	}
11993 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
11994 	adjust_subprog_starts(env, off, len);
11995 	adjust_poke_descs(new_prog, off, len);
11996 	return new_prog;
11997 }
11998 
11999 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12000 					      u32 off, u32 cnt)
12001 {
12002 	int i, j;
12003 
12004 	/* find first prog starting at or after off (first to remove) */
12005 	for (i = 0; i < env->subprog_cnt; i++)
12006 		if (env->subprog_info[i].start >= off)
12007 			break;
12008 	/* find first prog starting at or after off + cnt (first to stay) */
12009 	for (j = i; j < env->subprog_cnt; j++)
12010 		if (env->subprog_info[j].start >= off + cnt)
12011 			break;
12012 	/* if j doesn't start exactly at off + cnt, we are just removing
12013 	 * the front of previous prog
12014 	 */
12015 	if (env->subprog_info[j].start != off + cnt)
12016 		j--;
12017 
12018 	if (j > i) {
12019 		struct bpf_prog_aux *aux = env->prog->aux;
12020 		int move;
12021 
12022 		/* move fake 'exit' subprog as well */
12023 		move = env->subprog_cnt + 1 - j;
12024 
12025 		memmove(env->subprog_info + i,
12026 			env->subprog_info + j,
12027 			sizeof(*env->subprog_info) * move);
12028 		env->subprog_cnt -= j - i;
12029 
12030 		/* remove func_info */
12031 		if (aux->func_info) {
12032 			move = aux->func_info_cnt - j;
12033 
12034 			memmove(aux->func_info + i,
12035 				aux->func_info + j,
12036 				sizeof(*aux->func_info) * move);
12037 			aux->func_info_cnt -= j - i;
12038 			/* func_info->insn_off is set after all code rewrites,
12039 			 * in adjust_btf_func() - no need to adjust
12040 			 */
12041 		}
12042 	} else {
12043 		/* convert i from "first prog to remove" to "first to adjust" */
12044 		if (env->subprog_info[i].start == off)
12045 			i++;
12046 	}
12047 
12048 	/* update fake 'exit' subprog as well */
12049 	for (; i <= env->subprog_cnt; i++)
12050 		env->subprog_info[i].start -= cnt;
12051 
12052 	return 0;
12053 }
12054 
12055 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12056 				      u32 cnt)
12057 {
12058 	struct bpf_prog *prog = env->prog;
12059 	u32 i, l_off, l_cnt, nr_linfo;
12060 	struct bpf_line_info *linfo;
12061 
12062 	nr_linfo = prog->aux->nr_linfo;
12063 	if (!nr_linfo)
12064 		return 0;
12065 
12066 	linfo = prog->aux->linfo;
12067 
12068 	/* find first line info to remove, count lines to be removed */
12069 	for (i = 0; i < nr_linfo; i++)
12070 		if (linfo[i].insn_off >= off)
12071 			break;
12072 
12073 	l_off = i;
12074 	l_cnt = 0;
12075 	for (; i < nr_linfo; i++)
12076 		if (linfo[i].insn_off < off + cnt)
12077 			l_cnt++;
12078 		else
12079 			break;
12080 
12081 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12082 	 * last removed linfo.  prog is already modified, so prog->len == off
12083 	 * means no live instructions after (tail of the program was removed).
12084 	 */
12085 	if (prog->len != off && l_cnt &&
12086 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12087 		l_cnt--;
12088 		linfo[--i].insn_off = off + cnt;
12089 	}
12090 
12091 	/* remove the line info which refer to the removed instructions */
12092 	if (l_cnt) {
12093 		memmove(linfo + l_off, linfo + i,
12094 			sizeof(*linfo) * (nr_linfo - i));
12095 
12096 		prog->aux->nr_linfo -= l_cnt;
12097 		nr_linfo = prog->aux->nr_linfo;
12098 	}
12099 
12100 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12101 	for (i = l_off; i < nr_linfo; i++)
12102 		linfo[i].insn_off -= cnt;
12103 
12104 	/* fix up all subprogs (incl. 'exit') which start >= off */
12105 	for (i = 0; i <= env->subprog_cnt; i++)
12106 		if (env->subprog_info[i].linfo_idx > l_off) {
12107 			/* program may have started in the removed region but
12108 			 * may not be fully removed
12109 			 */
12110 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12111 				env->subprog_info[i].linfo_idx -= l_cnt;
12112 			else
12113 				env->subprog_info[i].linfo_idx = l_off;
12114 		}
12115 
12116 	return 0;
12117 }
12118 
12119 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12120 {
12121 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12122 	unsigned int orig_prog_len = env->prog->len;
12123 	int err;
12124 
12125 	if (bpf_prog_is_dev_bound(env->prog->aux))
12126 		bpf_prog_offload_remove_insns(env, off, cnt);
12127 
12128 	err = bpf_remove_insns(env->prog, off, cnt);
12129 	if (err)
12130 		return err;
12131 
12132 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12133 	if (err)
12134 		return err;
12135 
12136 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12137 	if (err)
12138 		return err;
12139 
12140 	memmove(aux_data + off,	aux_data + off + cnt,
12141 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12142 
12143 	return 0;
12144 }
12145 
12146 /* The verifier does more data flow analysis than llvm and will not
12147  * explore branches that are dead at run time. Malicious programs can
12148  * have dead code too. Therefore replace all dead at-run-time code
12149  * with 'ja -1'.
12150  *
12151  * Just nops are not optimal, e.g. if they would sit at the end of the
12152  * program and through another bug we would manage to jump there, then
12153  * we'd execute beyond program memory otherwise. Returning exception
12154  * code also wouldn't work since we can have subprogs where the dead
12155  * code could be located.
12156  */
12157 static void sanitize_dead_code(struct bpf_verifier_env *env)
12158 {
12159 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12160 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12161 	struct bpf_insn *insn = env->prog->insnsi;
12162 	const int insn_cnt = env->prog->len;
12163 	int i;
12164 
12165 	for (i = 0; i < insn_cnt; i++) {
12166 		if (aux_data[i].seen)
12167 			continue;
12168 		memcpy(insn + i, &trap, sizeof(trap));
12169 		aux_data[i].zext_dst = false;
12170 	}
12171 }
12172 
12173 static bool insn_is_cond_jump(u8 code)
12174 {
12175 	u8 op;
12176 
12177 	if (BPF_CLASS(code) == BPF_JMP32)
12178 		return true;
12179 
12180 	if (BPF_CLASS(code) != BPF_JMP)
12181 		return false;
12182 
12183 	op = BPF_OP(code);
12184 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12185 }
12186 
12187 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12188 {
12189 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12190 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12191 	struct bpf_insn *insn = env->prog->insnsi;
12192 	const int insn_cnt = env->prog->len;
12193 	int i;
12194 
12195 	for (i = 0; i < insn_cnt; i++, insn++) {
12196 		if (!insn_is_cond_jump(insn->code))
12197 			continue;
12198 
12199 		if (!aux_data[i + 1].seen)
12200 			ja.off = insn->off;
12201 		else if (!aux_data[i + 1 + insn->off].seen)
12202 			ja.off = 0;
12203 		else
12204 			continue;
12205 
12206 		if (bpf_prog_is_dev_bound(env->prog->aux))
12207 			bpf_prog_offload_replace_insn(env, i, &ja);
12208 
12209 		memcpy(insn, &ja, sizeof(ja));
12210 	}
12211 }
12212 
12213 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12214 {
12215 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12216 	int insn_cnt = env->prog->len;
12217 	int i, err;
12218 
12219 	for (i = 0; i < insn_cnt; i++) {
12220 		int j;
12221 
12222 		j = 0;
12223 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12224 			j++;
12225 		if (!j)
12226 			continue;
12227 
12228 		err = verifier_remove_insns(env, i, j);
12229 		if (err)
12230 			return err;
12231 		insn_cnt = env->prog->len;
12232 	}
12233 
12234 	return 0;
12235 }
12236 
12237 static int opt_remove_nops(struct bpf_verifier_env *env)
12238 {
12239 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12240 	struct bpf_insn *insn = env->prog->insnsi;
12241 	int insn_cnt = env->prog->len;
12242 	int i, err;
12243 
12244 	for (i = 0; i < insn_cnt; i++) {
12245 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12246 			continue;
12247 
12248 		err = verifier_remove_insns(env, i, 1);
12249 		if (err)
12250 			return err;
12251 		insn_cnt--;
12252 		i--;
12253 	}
12254 
12255 	return 0;
12256 }
12257 
12258 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12259 					 const union bpf_attr *attr)
12260 {
12261 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12262 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12263 	int i, patch_len, delta = 0, len = env->prog->len;
12264 	struct bpf_insn *insns = env->prog->insnsi;
12265 	struct bpf_prog *new_prog;
12266 	bool rnd_hi32;
12267 
12268 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12269 	zext_patch[1] = BPF_ZEXT_REG(0);
12270 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12271 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12272 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12273 	for (i = 0; i < len; i++) {
12274 		int adj_idx = i + delta;
12275 		struct bpf_insn insn;
12276 		int load_reg;
12277 
12278 		insn = insns[adj_idx];
12279 		load_reg = insn_def_regno(&insn);
12280 		if (!aux[adj_idx].zext_dst) {
12281 			u8 code, class;
12282 			u32 imm_rnd;
12283 
12284 			if (!rnd_hi32)
12285 				continue;
12286 
12287 			code = insn.code;
12288 			class = BPF_CLASS(code);
12289 			if (load_reg == -1)
12290 				continue;
12291 
12292 			/* NOTE: arg "reg" (the fourth one) is only used for
12293 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12294 			 *       here.
12295 			 */
12296 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12297 				if (class == BPF_LD &&
12298 				    BPF_MODE(code) == BPF_IMM)
12299 					i++;
12300 				continue;
12301 			}
12302 
12303 			/* ctx load could be transformed into wider load. */
12304 			if (class == BPF_LDX &&
12305 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12306 				continue;
12307 
12308 			imm_rnd = get_random_int();
12309 			rnd_hi32_patch[0] = insn;
12310 			rnd_hi32_patch[1].imm = imm_rnd;
12311 			rnd_hi32_patch[3].dst_reg = load_reg;
12312 			patch = rnd_hi32_patch;
12313 			patch_len = 4;
12314 			goto apply_patch_buffer;
12315 		}
12316 
12317 		/* Add in an zero-extend instruction if a) the JIT has requested
12318 		 * it or b) it's a CMPXCHG.
12319 		 *
12320 		 * The latter is because: BPF_CMPXCHG always loads a value into
12321 		 * R0, therefore always zero-extends. However some archs'
12322 		 * equivalent instruction only does this load when the
12323 		 * comparison is successful. This detail of CMPXCHG is
12324 		 * orthogonal to the general zero-extension behaviour of the
12325 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12326 		 */
12327 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12328 			continue;
12329 
12330 		if (WARN_ON(load_reg == -1)) {
12331 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12332 			return -EFAULT;
12333 		}
12334 
12335 		zext_patch[0] = insn;
12336 		zext_patch[1].dst_reg = load_reg;
12337 		zext_patch[1].src_reg = load_reg;
12338 		patch = zext_patch;
12339 		patch_len = 2;
12340 apply_patch_buffer:
12341 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12342 		if (!new_prog)
12343 			return -ENOMEM;
12344 		env->prog = new_prog;
12345 		insns = new_prog->insnsi;
12346 		aux = env->insn_aux_data;
12347 		delta += patch_len - 1;
12348 	}
12349 
12350 	return 0;
12351 }
12352 
12353 /* convert load instructions that access fields of a context type into a
12354  * sequence of instructions that access fields of the underlying structure:
12355  *     struct __sk_buff    -> struct sk_buff
12356  *     struct bpf_sock_ops -> struct sock
12357  */
12358 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12359 {
12360 	const struct bpf_verifier_ops *ops = env->ops;
12361 	int i, cnt, size, ctx_field_size, delta = 0;
12362 	const int insn_cnt = env->prog->len;
12363 	struct bpf_insn insn_buf[16], *insn;
12364 	u32 target_size, size_default, off;
12365 	struct bpf_prog *new_prog;
12366 	enum bpf_access_type type;
12367 	bool is_narrower_load;
12368 
12369 	if (ops->gen_prologue || env->seen_direct_write) {
12370 		if (!ops->gen_prologue) {
12371 			verbose(env, "bpf verifier is misconfigured\n");
12372 			return -EINVAL;
12373 		}
12374 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12375 					env->prog);
12376 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12377 			verbose(env, "bpf verifier is misconfigured\n");
12378 			return -EINVAL;
12379 		} else if (cnt) {
12380 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12381 			if (!new_prog)
12382 				return -ENOMEM;
12383 
12384 			env->prog = new_prog;
12385 			delta += cnt - 1;
12386 		}
12387 	}
12388 
12389 	if (bpf_prog_is_dev_bound(env->prog->aux))
12390 		return 0;
12391 
12392 	insn = env->prog->insnsi + delta;
12393 
12394 	for (i = 0; i < insn_cnt; i++, insn++) {
12395 		bpf_convert_ctx_access_t convert_ctx_access;
12396 		bool ctx_access;
12397 
12398 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12399 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12400 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12401 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12402 			type = BPF_READ;
12403 			ctx_access = true;
12404 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12405 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12406 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12407 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12408 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12409 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12410 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12411 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12412 			type = BPF_WRITE;
12413 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12414 		} else {
12415 			continue;
12416 		}
12417 
12418 		if (type == BPF_WRITE &&
12419 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12420 			struct bpf_insn patch[] = {
12421 				*insn,
12422 				BPF_ST_NOSPEC(),
12423 			};
12424 
12425 			cnt = ARRAY_SIZE(patch);
12426 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12427 			if (!new_prog)
12428 				return -ENOMEM;
12429 
12430 			delta    += cnt - 1;
12431 			env->prog = new_prog;
12432 			insn      = new_prog->insnsi + i + delta;
12433 			continue;
12434 		}
12435 
12436 		if (!ctx_access)
12437 			continue;
12438 
12439 		switch (env->insn_aux_data[i + delta].ptr_type) {
12440 		case PTR_TO_CTX:
12441 			if (!ops->convert_ctx_access)
12442 				continue;
12443 			convert_ctx_access = ops->convert_ctx_access;
12444 			break;
12445 		case PTR_TO_SOCKET:
12446 		case PTR_TO_SOCK_COMMON:
12447 			convert_ctx_access = bpf_sock_convert_ctx_access;
12448 			break;
12449 		case PTR_TO_TCP_SOCK:
12450 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12451 			break;
12452 		case PTR_TO_XDP_SOCK:
12453 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12454 			break;
12455 		case PTR_TO_BTF_ID:
12456 			if (type == BPF_READ) {
12457 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12458 					BPF_SIZE((insn)->code);
12459 				env->prog->aux->num_exentries++;
12460 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12461 				verbose(env, "Writes through BTF pointers are not allowed\n");
12462 				return -EINVAL;
12463 			}
12464 			continue;
12465 		default:
12466 			continue;
12467 		}
12468 
12469 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12470 		size = BPF_LDST_BYTES(insn);
12471 
12472 		/* If the read access is a narrower load of the field,
12473 		 * convert to a 4/8-byte load, to minimum program type specific
12474 		 * convert_ctx_access changes. If conversion is successful,
12475 		 * we will apply proper mask to the result.
12476 		 */
12477 		is_narrower_load = size < ctx_field_size;
12478 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12479 		off = insn->off;
12480 		if (is_narrower_load) {
12481 			u8 size_code;
12482 
12483 			if (type == BPF_WRITE) {
12484 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12485 				return -EINVAL;
12486 			}
12487 
12488 			size_code = BPF_H;
12489 			if (ctx_field_size == 4)
12490 				size_code = BPF_W;
12491 			else if (ctx_field_size == 8)
12492 				size_code = BPF_DW;
12493 
12494 			insn->off = off & ~(size_default - 1);
12495 			insn->code = BPF_LDX | BPF_MEM | size_code;
12496 		}
12497 
12498 		target_size = 0;
12499 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12500 					 &target_size);
12501 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12502 		    (ctx_field_size && !target_size)) {
12503 			verbose(env, "bpf verifier is misconfigured\n");
12504 			return -EINVAL;
12505 		}
12506 
12507 		if (is_narrower_load && size < target_size) {
12508 			u8 shift = bpf_ctx_narrow_access_offset(
12509 				off, size, size_default) * 8;
12510 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12511 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12512 				return -EINVAL;
12513 			}
12514 			if (ctx_field_size <= 4) {
12515 				if (shift)
12516 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12517 									insn->dst_reg,
12518 									shift);
12519 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12520 								(1 << size * 8) - 1);
12521 			} else {
12522 				if (shift)
12523 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12524 									insn->dst_reg,
12525 									shift);
12526 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12527 								(1ULL << size * 8) - 1);
12528 			}
12529 		}
12530 
12531 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12532 		if (!new_prog)
12533 			return -ENOMEM;
12534 
12535 		delta += cnt - 1;
12536 
12537 		/* keep walking new program and skip insns we just inserted */
12538 		env->prog = new_prog;
12539 		insn      = new_prog->insnsi + i + delta;
12540 	}
12541 
12542 	return 0;
12543 }
12544 
12545 static int jit_subprogs(struct bpf_verifier_env *env)
12546 {
12547 	struct bpf_prog *prog = env->prog, **func, *tmp;
12548 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12549 	struct bpf_map *map_ptr;
12550 	struct bpf_insn *insn;
12551 	void *old_bpf_func;
12552 	int err, num_exentries;
12553 
12554 	if (env->subprog_cnt <= 1)
12555 		return 0;
12556 
12557 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12558 		if (bpf_pseudo_func(insn)) {
12559 			env->insn_aux_data[i].call_imm = insn->imm;
12560 			/* subprog is encoded in insn[1].imm */
12561 			continue;
12562 		}
12563 
12564 		if (!bpf_pseudo_call(insn))
12565 			continue;
12566 		/* Upon error here we cannot fall back to interpreter but
12567 		 * need a hard reject of the program. Thus -EFAULT is
12568 		 * propagated in any case.
12569 		 */
12570 		subprog = find_subprog(env, i + insn->imm + 1);
12571 		if (subprog < 0) {
12572 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12573 				  i + insn->imm + 1);
12574 			return -EFAULT;
12575 		}
12576 		/* temporarily remember subprog id inside insn instead of
12577 		 * aux_data, since next loop will split up all insns into funcs
12578 		 */
12579 		insn->off = subprog;
12580 		/* remember original imm in case JIT fails and fallback
12581 		 * to interpreter will be needed
12582 		 */
12583 		env->insn_aux_data[i].call_imm = insn->imm;
12584 		/* point imm to __bpf_call_base+1 from JITs point of view */
12585 		insn->imm = 1;
12586 	}
12587 
12588 	err = bpf_prog_alloc_jited_linfo(prog);
12589 	if (err)
12590 		goto out_undo_insn;
12591 
12592 	err = -ENOMEM;
12593 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12594 	if (!func)
12595 		goto out_undo_insn;
12596 
12597 	for (i = 0; i < env->subprog_cnt; i++) {
12598 		subprog_start = subprog_end;
12599 		subprog_end = env->subprog_info[i + 1].start;
12600 
12601 		len = subprog_end - subprog_start;
12602 		/* bpf_prog_run() doesn't call subprogs directly,
12603 		 * hence main prog stats include the runtime of subprogs.
12604 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12605 		 * func[i]->stats will never be accessed and stays NULL
12606 		 */
12607 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12608 		if (!func[i])
12609 			goto out_free;
12610 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12611 		       len * sizeof(struct bpf_insn));
12612 		func[i]->type = prog->type;
12613 		func[i]->len = len;
12614 		if (bpf_prog_calc_tag(func[i]))
12615 			goto out_free;
12616 		func[i]->is_func = 1;
12617 		func[i]->aux->func_idx = i;
12618 		/* Below members will be freed only at prog->aux */
12619 		func[i]->aux->btf = prog->aux->btf;
12620 		func[i]->aux->func_info = prog->aux->func_info;
12621 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12622 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12623 
12624 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12625 			struct bpf_jit_poke_descriptor *poke;
12626 
12627 			poke = &prog->aux->poke_tab[j];
12628 			if (poke->insn_idx < subprog_end &&
12629 			    poke->insn_idx >= subprog_start)
12630 				poke->aux = func[i]->aux;
12631 		}
12632 
12633 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
12634 		 * Long term would need debug info to populate names
12635 		 */
12636 		func[i]->aux->name[0] = 'F';
12637 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12638 		func[i]->jit_requested = 1;
12639 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12640 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
12641 		func[i]->aux->linfo = prog->aux->linfo;
12642 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12643 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12644 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12645 		num_exentries = 0;
12646 		insn = func[i]->insnsi;
12647 		for (j = 0; j < func[i]->len; j++, insn++) {
12648 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12649 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12650 				num_exentries++;
12651 		}
12652 		func[i]->aux->num_exentries = num_exentries;
12653 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12654 		func[i] = bpf_int_jit_compile(func[i]);
12655 		if (!func[i]->jited) {
12656 			err = -ENOTSUPP;
12657 			goto out_free;
12658 		}
12659 		cond_resched();
12660 	}
12661 
12662 	/* at this point all bpf functions were successfully JITed
12663 	 * now populate all bpf_calls with correct addresses and
12664 	 * run last pass of JIT
12665 	 */
12666 	for (i = 0; i < env->subprog_cnt; i++) {
12667 		insn = func[i]->insnsi;
12668 		for (j = 0; j < func[i]->len; j++, insn++) {
12669 			if (bpf_pseudo_func(insn)) {
12670 				subprog = insn[1].imm;
12671 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12672 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12673 				continue;
12674 			}
12675 			if (!bpf_pseudo_call(insn))
12676 				continue;
12677 			subprog = insn->off;
12678 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
12679 		}
12680 
12681 		/* we use the aux data to keep a list of the start addresses
12682 		 * of the JITed images for each function in the program
12683 		 *
12684 		 * for some architectures, such as powerpc64, the imm field
12685 		 * might not be large enough to hold the offset of the start
12686 		 * address of the callee's JITed image from __bpf_call_base
12687 		 *
12688 		 * in such cases, we can lookup the start address of a callee
12689 		 * by using its subprog id, available from the off field of
12690 		 * the call instruction, as an index for this list
12691 		 */
12692 		func[i]->aux->func = func;
12693 		func[i]->aux->func_cnt = env->subprog_cnt;
12694 	}
12695 	for (i = 0; i < env->subprog_cnt; i++) {
12696 		old_bpf_func = func[i]->bpf_func;
12697 		tmp = bpf_int_jit_compile(func[i]);
12698 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12699 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12700 			err = -ENOTSUPP;
12701 			goto out_free;
12702 		}
12703 		cond_resched();
12704 	}
12705 
12706 	/* finally lock prog and jit images for all functions and
12707 	 * populate kallsysm
12708 	 */
12709 	for (i = 0; i < env->subprog_cnt; i++) {
12710 		bpf_prog_lock_ro(func[i]);
12711 		bpf_prog_kallsyms_add(func[i]);
12712 	}
12713 
12714 	/* Last step: make now unused interpreter insns from main
12715 	 * prog consistent for later dump requests, so they can
12716 	 * later look the same as if they were interpreted only.
12717 	 */
12718 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12719 		if (bpf_pseudo_func(insn)) {
12720 			insn[0].imm = env->insn_aux_data[i].call_imm;
12721 			insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12722 			continue;
12723 		}
12724 		if (!bpf_pseudo_call(insn))
12725 			continue;
12726 		insn->off = env->insn_aux_data[i].call_imm;
12727 		subprog = find_subprog(env, i + insn->off + 1);
12728 		insn->imm = subprog;
12729 	}
12730 
12731 	prog->jited = 1;
12732 	prog->bpf_func = func[0]->bpf_func;
12733 	prog->aux->func = func;
12734 	prog->aux->func_cnt = env->subprog_cnt;
12735 	bpf_prog_jit_attempt_done(prog);
12736 	return 0;
12737 out_free:
12738 	/* We failed JIT'ing, so at this point we need to unregister poke
12739 	 * descriptors from subprogs, so that kernel is not attempting to
12740 	 * patch it anymore as we're freeing the subprog JIT memory.
12741 	 */
12742 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12743 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12744 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12745 	}
12746 	/* At this point we're guaranteed that poke descriptors are not
12747 	 * live anymore. We can just unlink its descriptor table as it's
12748 	 * released with the main prog.
12749 	 */
12750 	for (i = 0; i < env->subprog_cnt; i++) {
12751 		if (!func[i])
12752 			continue;
12753 		func[i]->aux->poke_tab = NULL;
12754 		bpf_jit_free(func[i]);
12755 	}
12756 	kfree(func);
12757 out_undo_insn:
12758 	/* cleanup main prog to be interpreted */
12759 	prog->jit_requested = 0;
12760 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12761 		if (!bpf_pseudo_call(insn))
12762 			continue;
12763 		insn->off = 0;
12764 		insn->imm = env->insn_aux_data[i].call_imm;
12765 	}
12766 	bpf_prog_jit_attempt_done(prog);
12767 	return err;
12768 }
12769 
12770 static int fixup_call_args(struct bpf_verifier_env *env)
12771 {
12772 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12773 	struct bpf_prog *prog = env->prog;
12774 	struct bpf_insn *insn = prog->insnsi;
12775 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12776 	int i, depth;
12777 #endif
12778 	int err = 0;
12779 
12780 	if (env->prog->jit_requested &&
12781 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12782 		err = jit_subprogs(env);
12783 		if (err == 0)
12784 			return 0;
12785 		if (err == -EFAULT)
12786 			return err;
12787 	}
12788 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12789 	if (has_kfunc_call) {
12790 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12791 		return -EINVAL;
12792 	}
12793 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12794 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12795 		 * have to be rejected, since interpreter doesn't support them yet.
12796 		 */
12797 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12798 		return -EINVAL;
12799 	}
12800 	for (i = 0; i < prog->len; i++, insn++) {
12801 		if (bpf_pseudo_func(insn)) {
12802 			/* When JIT fails the progs with callback calls
12803 			 * have to be rejected, since interpreter doesn't support them yet.
12804 			 */
12805 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12806 			return -EINVAL;
12807 		}
12808 
12809 		if (!bpf_pseudo_call(insn))
12810 			continue;
12811 		depth = get_callee_stack_depth(env, insn, i);
12812 		if (depth < 0)
12813 			return depth;
12814 		bpf_patch_call_args(insn, depth);
12815 	}
12816 	err = 0;
12817 #endif
12818 	return err;
12819 }
12820 
12821 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12822 			    struct bpf_insn *insn)
12823 {
12824 	const struct bpf_kfunc_desc *desc;
12825 
12826 	if (!insn->imm) {
12827 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
12828 		return -EINVAL;
12829 	}
12830 
12831 	/* insn->imm has the btf func_id. Replace it with
12832 	 * an address (relative to __bpf_base_call).
12833 	 */
12834 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
12835 	if (!desc) {
12836 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12837 			insn->imm);
12838 		return -EFAULT;
12839 	}
12840 
12841 	insn->imm = desc->imm;
12842 
12843 	return 0;
12844 }
12845 
12846 /* Do various post-verification rewrites in a single program pass.
12847  * These rewrites simplify JIT and interpreter implementations.
12848  */
12849 static int do_misc_fixups(struct bpf_verifier_env *env)
12850 {
12851 	struct bpf_prog *prog = env->prog;
12852 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12853 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12854 	struct bpf_insn *insn = prog->insnsi;
12855 	const struct bpf_func_proto *fn;
12856 	const int insn_cnt = prog->len;
12857 	const struct bpf_map_ops *ops;
12858 	struct bpf_insn_aux_data *aux;
12859 	struct bpf_insn insn_buf[16];
12860 	struct bpf_prog *new_prog;
12861 	struct bpf_map *map_ptr;
12862 	int i, ret, cnt, delta = 0;
12863 
12864 	for (i = 0; i < insn_cnt; i++, insn++) {
12865 		/* Make divide-by-zero exceptions impossible. */
12866 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12867 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12868 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12869 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12870 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12871 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12872 			struct bpf_insn *patchlet;
12873 			struct bpf_insn chk_and_div[] = {
12874 				/* [R,W]x div 0 -> 0 */
12875 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12876 					     BPF_JNE | BPF_K, insn->src_reg,
12877 					     0, 2, 0),
12878 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12879 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12880 				*insn,
12881 			};
12882 			struct bpf_insn chk_and_mod[] = {
12883 				/* [R,W]x mod 0 -> [R,W]x */
12884 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12885 					     BPF_JEQ | BPF_K, insn->src_reg,
12886 					     0, 1 + (is64 ? 0 : 1), 0),
12887 				*insn,
12888 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12889 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12890 			};
12891 
12892 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12893 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12894 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12895 
12896 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12897 			if (!new_prog)
12898 				return -ENOMEM;
12899 
12900 			delta    += cnt - 1;
12901 			env->prog = prog = new_prog;
12902 			insn      = new_prog->insnsi + i + delta;
12903 			continue;
12904 		}
12905 
12906 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12907 		if (BPF_CLASS(insn->code) == BPF_LD &&
12908 		    (BPF_MODE(insn->code) == BPF_ABS ||
12909 		     BPF_MODE(insn->code) == BPF_IND)) {
12910 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12911 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12912 				verbose(env, "bpf verifier is misconfigured\n");
12913 				return -EINVAL;
12914 			}
12915 
12916 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12917 			if (!new_prog)
12918 				return -ENOMEM;
12919 
12920 			delta    += cnt - 1;
12921 			env->prog = prog = new_prog;
12922 			insn      = new_prog->insnsi + i + delta;
12923 			continue;
12924 		}
12925 
12926 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12927 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12928 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12929 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12930 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12931 			struct bpf_insn *patch = &insn_buf[0];
12932 			bool issrc, isneg, isimm;
12933 			u32 off_reg;
12934 
12935 			aux = &env->insn_aux_data[i + delta];
12936 			if (!aux->alu_state ||
12937 			    aux->alu_state == BPF_ALU_NON_POINTER)
12938 				continue;
12939 
12940 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12941 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12942 				BPF_ALU_SANITIZE_SRC;
12943 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12944 
12945 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12946 			if (isimm) {
12947 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12948 			} else {
12949 				if (isneg)
12950 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12951 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12952 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12953 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12954 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12955 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12956 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12957 			}
12958 			if (!issrc)
12959 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12960 			insn->src_reg = BPF_REG_AX;
12961 			if (isneg)
12962 				insn->code = insn->code == code_add ?
12963 					     code_sub : code_add;
12964 			*patch++ = *insn;
12965 			if (issrc && isneg && !isimm)
12966 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12967 			cnt = patch - insn_buf;
12968 
12969 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12970 			if (!new_prog)
12971 				return -ENOMEM;
12972 
12973 			delta    += cnt - 1;
12974 			env->prog = prog = new_prog;
12975 			insn      = new_prog->insnsi + i + delta;
12976 			continue;
12977 		}
12978 
12979 		if (insn->code != (BPF_JMP | BPF_CALL))
12980 			continue;
12981 		if (insn->src_reg == BPF_PSEUDO_CALL)
12982 			continue;
12983 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12984 			ret = fixup_kfunc_call(env, insn);
12985 			if (ret)
12986 				return ret;
12987 			continue;
12988 		}
12989 
12990 		if (insn->imm == BPF_FUNC_get_route_realm)
12991 			prog->dst_needed = 1;
12992 		if (insn->imm == BPF_FUNC_get_prandom_u32)
12993 			bpf_user_rnd_init_once();
12994 		if (insn->imm == BPF_FUNC_override_return)
12995 			prog->kprobe_override = 1;
12996 		if (insn->imm == BPF_FUNC_tail_call) {
12997 			/* If we tail call into other programs, we
12998 			 * cannot make any assumptions since they can
12999 			 * be replaced dynamically during runtime in
13000 			 * the program array.
13001 			 */
13002 			prog->cb_access = 1;
13003 			if (!allow_tail_call_in_subprogs(env))
13004 				prog->aux->stack_depth = MAX_BPF_STACK;
13005 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13006 
13007 			/* mark bpf_tail_call as different opcode to avoid
13008 			 * conditional branch in the interpreter for every normal
13009 			 * call and to prevent accidental JITing by JIT compiler
13010 			 * that doesn't support bpf_tail_call yet
13011 			 */
13012 			insn->imm = 0;
13013 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13014 
13015 			aux = &env->insn_aux_data[i + delta];
13016 			if (env->bpf_capable && !expect_blinding &&
13017 			    prog->jit_requested &&
13018 			    !bpf_map_key_poisoned(aux) &&
13019 			    !bpf_map_ptr_poisoned(aux) &&
13020 			    !bpf_map_ptr_unpriv(aux)) {
13021 				struct bpf_jit_poke_descriptor desc = {
13022 					.reason = BPF_POKE_REASON_TAIL_CALL,
13023 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13024 					.tail_call.key = bpf_map_key_immediate(aux),
13025 					.insn_idx = i + delta,
13026 				};
13027 
13028 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13029 				if (ret < 0) {
13030 					verbose(env, "adding tail call poke descriptor failed\n");
13031 					return ret;
13032 				}
13033 
13034 				insn->imm = ret + 1;
13035 				continue;
13036 			}
13037 
13038 			if (!bpf_map_ptr_unpriv(aux))
13039 				continue;
13040 
13041 			/* instead of changing every JIT dealing with tail_call
13042 			 * emit two extra insns:
13043 			 * if (index >= max_entries) goto out;
13044 			 * index &= array->index_mask;
13045 			 * to avoid out-of-bounds cpu speculation
13046 			 */
13047 			if (bpf_map_ptr_poisoned(aux)) {
13048 				verbose(env, "tail_call abusing map_ptr\n");
13049 				return -EINVAL;
13050 			}
13051 
13052 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13053 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13054 						  map_ptr->max_entries, 2);
13055 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13056 						    container_of(map_ptr,
13057 								 struct bpf_array,
13058 								 map)->index_mask);
13059 			insn_buf[2] = *insn;
13060 			cnt = 3;
13061 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13062 			if (!new_prog)
13063 				return -ENOMEM;
13064 
13065 			delta    += cnt - 1;
13066 			env->prog = prog = new_prog;
13067 			insn      = new_prog->insnsi + i + delta;
13068 			continue;
13069 		}
13070 
13071 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13072 			/* The verifier will process callback_fn as many times as necessary
13073 			 * with different maps and the register states prepared by
13074 			 * set_timer_callback_state will be accurate.
13075 			 *
13076 			 * The following use case is valid:
13077 			 *   map1 is shared by prog1, prog2, prog3.
13078 			 *   prog1 calls bpf_timer_init for some map1 elements
13079 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13080 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13081 			 *   prog3 calls bpf_timer_start for some map1 elements.
13082 			 *     Those that were not both bpf_timer_init-ed and
13083 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13084 			 */
13085 			struct bpf_insn ld_addrs[2] = {
13086 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13087 			};
13088 
13089 			insn_buf[0] = ld_addrs[0];
13090 			insn_buf[1] = ld_addrs[1];
13091 			insn_buf[2] = *insn;
13092 			cnt = 3;
13093 
13094 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13095 			if (!new_prog)
13096 				return -ENOMEM;
13097 
13098 			delta    += cnt - 1;
13099 			env->prog = prog = new_prog;
13100 			insn      = new_prog->insnsi + i + delta;
13101 			goto patch_call_imm;
13102 		}
13103 
13104 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13105 		 * and other inlining handlers are currently limited to 64 bit
13106 		 * only.
13107 		 */
13108 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13109 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13110 		     insn->imm == BPF_FUNC_map_update_elem ||
13111 		     insn->imm == BPF_FUNC_map_delete_elem ||
13112 		     insn->imm == BPF_FUNC_map_push_elem   ||
13113 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13114 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13115 		     insn->imm == BPF_FUNC_redirect_map    ||
13116 		     insn->imm == BPF_FUNC_for_each_map_elem)) {
13117 			aux = &env->insn_aux_data[i + delta];
13118 			if (bpf_map_ptr_poisoned(aux))
13119 				goto patch_call_imm;
13120 
13121 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13122 			ops = map_ptr->ops;
13123 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13124 			    ops->map_gen_lookup) {
13125 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13126 				if (cnt == -EOPNOTSUPP)
13127 					goto patch_map_ops_generic;
13128 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13129 					verbose(env, "bpf verifier is misconfigured\n");
13130 					return -EINVAL;
13131 				}
13132 
13133 				new_prog = bpf_patch_insn_data(env, i + delta,
13134 							       insn_buf, cnt);
13135 				if (!new_prog)
13136 					return -ENOMEM;
13137 
13138 				delta    += cnt - 1;
13139 				env->prog = prog = new_prog;
13140 				insn      = new_prog->insnsi + i + delta;
13141 				continue;
13142 			}
13143 
13144 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13145 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13146 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13147 				     (int (*)(struct bpf_map *map, void *key))NULL));
13148 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13149 				     (int (*)(struct bpf_map *map, void *key, void *value,
13150 					      u64 flags))NULL));
13151 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13152 				     (int (*)(struct bpf_map *map, void *value,
13153 					      u64 flags))NULL));
13154 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13155 				     (int (*)(struct bpf_map *map, void *value))NULL));
13156 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13157 				     (int (*)(struct bpf_map *map, void *value))NULL));
13158 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13159 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13160 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13161 				     (int (*)(struct bpf_map *map,
13162 					      bpf_callback_t callback_fn,
13163 					      void *callback_ctx,
13164 					      u64 flags))NULL));
13165 
13166 patch_map_ops_generic:
13167 			switch (insn->imm) {
13168 			case BPF_FUNC_map_lookup_elem:
13169 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
13170 				continue;
13171 			case BPF_FUNC_map_update_elem:
13172 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13173 				continue;
13174 			case BPF_FUNC_map_delete_elem:
13175 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13176 				continue;
13177 			case BPF_FUNC_map_push_elem:
13178 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13179 				continue;
13180 			case BPF_FUNC_map_pop_elem:
13181 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13182 				continue;
13183 			case BPF_FUNC_map_peek_elem:
13184 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13185 				continue;
13186 			case BPF_FUNC_redirect_map:
13187 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
13188 				continue;
13189 			case BPF_FUNC_for_each_map_elem:
13190 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
13191 				continue;
13192 			}
13193 
13194 			goto patch_call_imm;
13195 		}
13196 
13197 		/* Implement bpf_jiffies64 inline. */
13198 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13199 		    insn->imm == BPF_FUNC_jiffies64) {
13200 			struct bpf_insn ld_jiffies_addr[2] = {
13201 				BPF_LD_IMM64(BPF_REG_0,
13202 					     (unsigned long)&jiffies),
13203 			};
13204 
13205 			insn_buf[0] = ld_jiffies_addr[0];
13206 			insn_buf[1] = ld_jiffies_addr[1];
13207 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13208 						  BPF_REG_0, 0);
13209 			cnt = 3;
13210 
13211 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13212 						       cnt);
13213 			if (!new_prog)
13214 				return -ENOMEM;
13215 
13216 			delta    += cnt - 1;
13217 			env->prog = prog = new_prog;
13218 			insn      = new_prog->insnsi + i + delta;
13219 			continue;
13220 		}
13221 
13222 		/* Implement bpf_get_func_ip inline. */
13223 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13224 		    insn->imm == BPF_FUNC_get_func_ip) {
13225 			/* Load IP address from ctx - 8 */
13226 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13227 
13228 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13229 			if (!new_prog)
13230 				return -ENOMEM;
13231 
13232 			env->prog = prog = new_prog;
13233 			insn      = new_prog->insnsi + i + delta;
13234 			continue;
13235 		}
13236 
13237 patch_call_imm:
13238 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13239 		/* all functions that have prototype and verifier allowed
13240 		 * programs to call them, must be real in-kernel functions
13241 		 */
13242 		if (!fn->func) {
13243 			verbose(env,
13244 				"kernel subsystem misconfigured func %s#%d\n",
13245 				func_id_name(insn->imm), insn->imm);
13246 			return -EFAULT;
13247 		}
13248 		insn->imm = fn->func - __bpf_call_base;
13249 	}
13250 
13251 	/* Since poke tab is now finalized, publish aux to tracker. */
13252 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13253 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13254 		if (!map_ptr->ops->map_poke_track ||
13255 		    !map_ptr->ops->map_poke_untrack ||
13256 		    !map_ptr->ops->map_poke_run) {
13257 			verbose(env, "bpf verifier is misconfigured\n");
13258 			return -EINVAL;
13259 		}
13260 
13261 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13262 		if (ret < 0) {
13263 			verbose(env, "tracking tail call prog failed\n");
13264 			return ret;
13265 		}
13266 	}
13267 
13268 	sort_kfunc_descs_by_imm(env->prog);
13269 
13270 	return 0;
13271 }
13272 
13273 static void free_states(struct bpf_verifier_env *env)
13274 {
13275 	struct bpf_verifier_state_list *sl, *sln;
13276 	int i;
13277 
13278 	sl = env->free_list;
13279 	while (sl) {
13280 		sln = sl->next;
13281 		free_verifier_state(&sl->state, false);
13282 		kfree(sl);
13283 		sl = sln;
13284 	}
13285 	env->free_list = NULL;
13286 
13287 	if (!env->explored_states)
13288 		return;
13289 
13290 	for (i = 0; i < state_htab_size(env); i++) {
13291 		sl = env->explored_states[i];
13292 
13293 		while (sl) {
13294 			sln = sl->next;
13295 			free_verifier_state(&sl->state, false);
13296 			kfree(sl);
13297 			sl = sln;
13298 		}
13299 		env->explored_states[i] = NULL;
13300 	}
13301 }
13302 
13303 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13304 {
13305 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13306 	struct bpf_verifier_state *state;
13307 	struct bpf_reg_state *regs;
13308 	int ret, i;
13309 
13310 	env->prev_linfo = NULL;
13311 	env->pass_cnt++;
13312 
13313 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13314 	if (!state)
13315 		return -ENOMEM;
13316 	state->curframe = 0;
13317 	state->speculative = false;
13318 	state->branches = 1;
13319 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13320 	if (!state->frame[0]) {
13321 		kfree(state);
13322 		return -ENOMEM;
13323 	}
13324 	env->cur_state = state;
13325 	init_func_state(env, state->frame[0],
13326 			BPF_MAIN_FUNC /* callsite */,
13327 			0 /* frameno */,
13328 			subprog);
13329 
13330 	regs = state->frame[state->curframe]->regs;
13331 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13332 		ret = btf_prepare_func_args(env, subprog, regs);
13333 		if (ret)
13334 			goto out;
13335 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13336 			if (regs[i].type == PTR_TO_CTX)
13337 				mark_reg_known_zero(env, regs, i);
13338 			else if (regs[i].type == SCALAR_VALUE)
13339 				mark_reg_unknown(env, regs, i);
13340 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13341 				const u32 mem_size = regs[i].mem_size;
13342 
13343 				mark_reg_known_zero(env, regs, i);
13344 				regs[i].mem_size = mem_size;
13345 				regs[i].id = ++env->id_gen;
13346 			}
13347 		}
13348 	} else {
13349 		/* 1st arg to a function */
13350 		regs[BPF_REG_1].type = PTR_TO_CTX;
13351 		mark_reg_known_zero(env, regs, BPF_REG_1);
13352 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13353 		if (ret == -EFAULT)
13354 			/* unlikely verifier bug. abort.
13355 			 * ret == 0 and ret < 0 are sadly acceptable for
13356 			 * main() function due to backward compatibility.
13357 			 * Like socket filter program may be written as:
13358 			 * int bpf_prog(struct pt_regs *ctx)
13359 			 * and never dereference that ctx in the program.
13360 			 * 'struct pt_regs' is a type mismatch for socket
13361 			 * filter that should be using 'struct __sk_buff'.
13362 			 */
13363 			goto out;
13364 	}
13365 
13366 	ret = do_check(env);
13367 out:
13368 	/* check for NULL is necessary, since cur_state can be freed inside
13369 	 * do_check() under memory pressure.
13370 	 */
13371 	if (env->cur_state) {
13372 		free_verifier_state(env->cur_state, true);
13373 		env->cur_state = NULL;
13374 	}
13375 	while (!pop_stack(env, NULL, NULL, false));
13376 	if (!ret && pop_log)
13377 		bpf_vlog_reset(&env->log, 0);
13378 	free_states(env);
13379 	return ret;
13380 }
13381 
13382 /* Verify all global functions in a BPF program one by one based on their BTF.
13383  * All global functions must pass verification. Otherwise the whole program is rejected.
13384  * Consider:
13385  * int bar(int);
13386  * int foo(int f)
13387  * {
13388  *    return bar(f);
13389  * }
13390  * int bar(int b)
13391  * {
13392  *    ...
13393  * }
13394  * foo() will be verified first for R1=any_scalar_value. During verification it
13395  * will be assumed that bar() already verified successfully and call to bar()
13396  * from foo() will be checked for type match only. Later bar() will be verified
13397  * independently to check that it's safe for R1=any_scalar_value.
13398  */
13399 static int do_check_subprogs(struct bpf_verifier_env *env)
13400 {
13401 	struct bpf_prog_aux *aux = env->prog->aux;
13402 	int i, ret;
13403 
13404 	if (!aux->func_info)
13405 		return 0;
13406 
13407 	for (i = 1; i < env->subprog_cnt; i++) {
13408 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13409 			continue;
13410 		env->insn_idx = env->subprog_info[i].start;
13411 		WARN_ON_ONCE(env->insn_idx == 0);
13412 		ret = do_check_common(env, i);
13413 		if (ret) {
13414 			return ret;
13415 		} else if (env->log.level & BPF_LOG_LEVEL) {
13416 			verbose(env,
13417 				"Func#%d is safe for any args that match its prototype\n",
13418 				i);
13419 		}
13420 	}
13421 	return 0;
13422 }
13423 
13424 static int do_check_main(struct bpf_verifier_env *env)
13425 {
13426 	int ret;
13427 
13428 	env->insn_idx = 0;
13429 	ret = do_check_common(env, 0);
13430 	if (!ret)
13431 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13432 	return ret;
13433 }
13434 
13435 
13436 static void print_verification_stats(struct bpf_verifier_env *env)
13437 {
13438 	int i;
13439 
13440 	if (env->log.level & BPF_LOG_STATS) {
13441 		verbose(env, "verification time %lld usec\n",
13442 			div_u64(env->verification_time, 1000));
13443 		verbose(env, "stack depth ");
13444 		for (i = 0; i < env->subprog_cnt; i++) {
13445 			u32 depth = env->subprog_info[i].stack_depth;
13446 
13447 			verbose(env, "%d", depth);
13448 			if (i + 1 < env->subprog_cnt)
13449 				verbose(env, "+");
13450 		}
13451 		verbose(env, "\n");
13452 	}
13453 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13454 		"total_states %d peak_states %d mark_read %d\n",
13455 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13456 		env->max_states_per_insn, env->total_states,
13457 		env->peak_states, env->longest_mark_read_walk);
13458 }
13459 
13460 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13461 {
13462 	const struct btf_type *t, *func_proto;
13463 	const struct bpf_struct_ops *st_ops;
13464 	const struct btf_member *member;
13465 	struct bpf_prog *prog = env->prog;
13466 	u32 btf_id, member_idx;
13467 	const char *mname;
13468 
13469 	if (!prog->gpl_compatible) {
13470 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13471 		return -EINVAL;
13472 	}
13473 
13474 	btf_id = prog->aux->attach_btf_id;
13475 	st_ops = bpf_struct_ops_find(btf_id);
13476 	if (!st_ops) {
13477 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13478 			btf_id);
13479 		return -ENOTSUPP;
13480 	}
13481 
13482 	t = st_ops->type;
13483 	member_idx = prog->expected_attach_type;
13484 	if (member_idx >= btf_type_vlen(t)) {
13485 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13486 			member_idx, st_ops->name);
13487 		return -EINVAL;
13488 	}
13489 
13490 	member = &btf_type_member(t)[member_idx];
13491 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13492 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13493 					       NULL);
13494 	if (!func_proto) {
13495 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13496 			mname, member_idx, st_ops->name);
13497 		return -EINVAL;
13498 	}
13499 
13500 	if (st_ops->check_member) {
13501 		int err = st_ops->check_member(t, member);
13502 
13503 		if (err) {
13504 			verbose(env, "attach to unsupported member %s of struct %s\n",
13505 				mname, st_ops->name);
13506 			return err;
13507 		}
13508 	}
13509 
13510 	prog->aux->attach_func_proto = func_proto;
13511 	prog->aux->attach_func_name = mname;
13512 	env->ops = st_ops->verifier_ops;
13513 
13514 	return 0;
13515 }
13516 #define SECURITY_PREFIX "security_"
13517 
13518 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13519 {
13520 	if (within_error_injection_list(addr) ||
13521 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13522 		return 0;
13523 
13524 	return -EINVAL;
13525 }
13526 
13527 /* list of non-sleepable functions that are otherwise on
13528  * ALLOW_ERROR_INJECTION list
13529  */
13530 BTF_SET_START(btf_non_sleepable_error_inject)
13531 /* Three functions below can be called from sleepable and non-sleepable context.
13532  * Assume non-sleepable from bpf safety point of view.
13533  */
13534 BTF_ID(func, __add_to_page_cache_locked)
13535 BTF_ID(func, should_fail_alloc_page)
13536 BTF_ID(func, should_failslab)
13537 BTF_SET_END(btf_non_sleepable_error_inject)
13538 
13539 static int check_non_sleepable_error_inject(u32 btf_id)
13540 {
13541 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13542 }
13543 
13544 int bpf_check_attach_target(struct bpf_verifier_log *log,
13545 			    const struct bpf_prog *prog,
13546 			    const struct bpf_prog *tgt_prog,
13547 			    u32 btf_id,
13548 			    struct bpf_attach_target_info *tgt_info)
13549 {
13550 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13551 	const char prefix[] = "btf_trace_";
13552 	int ret = 0, subprog = -1, i;
13553 	const struct btf_type *t;
13554 	bool conservative = true;
13555 	const char *tname;
13556 	struct btf *btf;
13557 	long addr = 0;
13558 
13559 	if (!btf_id) {
13560 		bpf_log(log, "Tracing programs must provide btf_id\n");
13561 		return -EINVAL;
13562 	}
13563 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13564 	if (!btf) {
13565 		bpf_log(log,
13566 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13567 		return -EINVAL;
13568 	}
13569 	t = btf_type_by_id(btf, btf_id);
13570 	if (!t) {
13571 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13572 		return -EINVAL;
13573 	}
13574 	tname = btf_name_by_offset(btf, t->name_off);
13575 	if (!tname) {
13576 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13577 		return -EINVAL;
13578 	}
13579 	if (tgt_prog) {
13580 		struct bpf_prog_aux *aux = tgt_prog->aux;
13581 
13582 		for (i = 0; i < aux->func_info_cnt; i++)
13583 			if (aux->func_info[i].type_id == btf_id) {
13584 				subprog = i;
13585 				break;
13586 			}
13587 		if (subprog == -1) {
13588 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13589 			return -EINVAL;
13590 		}
13591 		conservative = aux->func_info_aux[subprog].unreliable;
13592 		if (prog_extension) {
13593 			if (conservative) {
13594 				bpf_log(log,
13595 					"Cannot replace static functions\n");
13596 				return -EINVAL;
13597 			}
13598 			if (!prog->jit_requested) {
13599 				bpf_log(log,
13600 					"Extension programs should be JITed\n");
13601 				return -EINVAL;
13602 			}
13603 		}
13604 		if (!tgt_prog->jited) {
13605 			bpf_log(log, "Can attach to only JITed progs\n");
13606 			return -EINVAL;
13607 		}
13608 		if (tgt_prog->type == prog->type) {
13609 			/* Cannot fentry/fexit another fentry/fexit program.
13610 			 * Cannot attach program extension to another extension.
13611 			 * It's ok to attach fentry/fexit to extension program.
13612 			 */
13613 			bpf_log(log, "Cannot recursively attach\n");
13614 			return -EINVAL;
13615 		}
13616 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13617 		    prog_extension &&
13618 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13619 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13620 			/* Program extensions can extend all program types
13621 			 * except fentry/fexit. The reason is the following.
13622 			 * The fentry/fexit programs are used for performance
13623 			 * analysis, stats and can be attached to any program
13624 			 * type except themselves. When extension program is
13625 			 * replacing XDP function it is necessary to allow
13626 			 * performance analysis of all functions. Both original
13627 			 * XDP program and its program extension. Hence
13628 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13629 			 * allowed. If extending of fentry/fexit was allowed it
13630 			 * would be possible to create long call chain
13631 			 * fentry->extension->fentry->extension beyond
13632 			 * reasonable stack size. Hence extending fentry is not
13633 			 * allowed.
13634 			 */
13635 			bpf_log(log, "Cannot extend fentry/fexit\n");
13636 			return -EINVAL;
13637 		}
13638 	} else {
13639 		if (prog_extension) {
13640 			bpf_log(log, "Cannot replace kernel functions\n");
13641 			return -EINVAL;
13642 		}
13643 	}
13644 
13645 	switch (prog->expected_attach_type) {
13646 	case BPF_TRACE_RAW_TP:
13647 		if (tgt_prog) {
13648 			bpf_log(log,
13649 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13650 			return -EINVAL;
13651 		}
13652 		if (!btf_type_is_typedef(t)) {
13653 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13654 				btf_id);
13655 			return -EINVAL;
13656 		}
13657 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13658 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13659 				btf_id, tname);
13660 			return -EINVAL;
13661 		}
13662 		tname += sizeof(prefix) - 1;
13663 		t = btf_type_by_id(btf, t->type);
13664 		if (!btf_type_is_ptr(t))
13665 			/* should never happen in valid vmlinux build */
13666 			return -EINVAL;
13667 		t = btf_type_by_id(btf, t->type);
13668 		if (!btf_type_is_func_proto(t))
13669 			/* should never happen in valid vmlinux build */
13670 			return -EINVAL;
13671 
13672 		break;
13673 	case BPF_TRACE_ITER:
13674 		if (!btf_type_is_func(t)) {
13675 			bpf_log(log, "attach_btf_id %u is not a function\n",
13676 				btf_id);
13677 			return -EINVAL;
13678 		}
13679 		t = btf_type_by_id(btf, t->type);
13680 		if (!btf_type_is_func_proto(t))
13681 			return -EINVAL;
13682 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13683 		if (ret)
13684 			return ret;
13685 		break;
13686 	default:
13687 		if (!prog_extension)
13688 			return -EINVAL;
13689 		fallthrough;
13690 	case BPF_MODIFY_RETURN:
13691 	case BPF_LSM_MAC:
13692 	case BPF_TRACE_FENTRY:
13693 	case BPF_TRACE_FEXIT:
13694 		if (!btf_type_is_func(t)) {
13695 			bpf_log(log, "attach_btf_id %u is not a function\n",
13696 				btf_id);
13697 			return -EINVAL;
13698 		}
13699 		if (prog_extension &&
13700 		    btf_check_type_match(log, prog, btf, t))
13701 			return -EINVAL;
13702 		t = btf_type_by_id(btf, t->type);
13703 		if (!btf_type_is_func_proto(t))
13704 			return -EINVAL;
13705 
13706 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13707 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13708 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13709 			return -EINVAL;
13710 
13711 		if (tgt_prog && conservative)
13712 			t = NULL;
13713 
13714 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13715 		if (ret < 0)
13716 			return ret;
13717 
13718 		if (tgt_prog) {
13719 			if (subprog == 0)
13720 				addr = (long) tgt_prog->bpf_func;
13721 			else
13722 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13723 		} else {
13724 			addr = kallsyms_lookup_name(tname);
13725 			if (!addr) {
13726 				bpf_log(log,
13727 					"The address of function %s cannot be found\n",
13728 					tname);
13729 				return -ENOENT;
13730 			}
13731 		}
13732 
13733 		if (prog->aux->sleepable) {
13734 			ret = -EINVAL;
13735 			switch (prog->type) {
13736 			case BPF_PROG_TYPE_TRACING:
13737 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13738 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13739 				 */
13740 				if (!check_non_sleepable_error_inject(btf_id) &&
13741 				    within_error_injection_list(addr))
13742 					ret = 0;
13743 				break;
13744 			case BPF_PROG_TYPE_LSM:
13745 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13746 				 * Only some of them are sleepable.
13747 				 */
13748 				if (bpf_lsm_is_sleepable_hook(btf_id))
13749 					ret = 0;
13750 				break;
13751 			default:
13752 				break;
13753 			}
13754 			if (ret) {
13755 				bpf_log(log, "%s is not sleepable\n", tname);
13756 				return ret;
13757 			}
13758 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13759 			if (tgt_prog) {
13760 				bpf_log(log, "can't modify return codes of BPF programs\n");
13761 				return -EINVAL;
13762 			}
13763 			ret = check_attach_modify_return(addr, tname);
13764 			if (ret) {
13765 				bpf_log(log, "%s() is not modifiable\n", tname);
13766 				return ret;
13767 			}
13768 		}
13769 
13770 		break;
13771 	}
13772 	tgt_info->tgt_addr = addr;
13773 	tgt_info->tgt_name = tname;
13774 	tgt_info->tgt_type = t;
13775 	return 0;
13776 }
13777 
13778 BTF_SET_START(btf_id_deny)
13779 BTF_ID_UNUSED
13780 #ifdef CONFIG_SMP
13781 BTF_ID(func, migrate_disable)
13782 BTF_ID(func, migrate_enable)
13783 #endif
13784 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13785 BTF_ID(func, rcu_read_unlock_strict)
13786 #endif
13787 BTF_SET_END(btf_id_deny)
13788 
13789 static int check_attach_btf_id(struct bpf_verifier_env *env)
13790 {
13791 	struct bpf_prog *prog = env->prog;
13792 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13793 	struct bpf_attach_target_info tgt_info = {};
13794 	u32 btf_id = prog->aux->attach_btf_id;
13795 	struct bpf_trampoline *tr;
13796 	int ret;
13797 	u64 key;
13798 
13799 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13800 		if (prog->aux->sleepable)
13801 			/* attach_btf_id checked to be zero already */
13802 			return 0;
13803 		verbose(env, "Syscall programs can only be sleepable\n");
13804 		return -EINVAL;
13805 	}
13806 
13807 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13808 	    prog->type != BPF_PROG_TYPE_LSM) {
13809 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13810 		return -EINVAL;
13811 	}
13812 
13813 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13814 		return check_struct_ops_btf_id(env);
13815 
13816 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13817 	    prog->type != BPF_PROG_TYPE_LSM &&
13818 	    prog->type != BPF_PROG_TYPE_EXT)
13819 		return 0;
13820 
13821 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13822 	if (ret)
13823 		return ret;
13824 
13825 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13826 		/* to make freplace equivalent to their targets, they need to
13827 		 * inherit env->ops and expected_attach_type for the rest of the
13828 		 * verification
13829 		 */
13830 		env->ops = bpf_verifier_ops[tgt_prog->type];
13831 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13832 	}
13833 
13834 	/* store info about the attachment target that will be used later */
13835 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13836 	prog->aux->attach_func_name = tgt_info.tgt_name;
13837 
13838 	if (tgt_prog) {
13839 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13840 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13841 	}
13842 
13843 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13844 		prog->aux->attach_btf_trace = true;
13845 		return 0;
13846 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13847 		if (!bpf_iter_prog_supported(prog))
13848 			return -EINVAL;
13849 		return 0;
13850 	}
13851 
13852 	if (prog->type == BPF_PROG_TYPE_LSM) {
13853 		ret = bpf_lsm_verify_prog(&env->log, prog);
13854 		if (ret < 0)
13855 			return ret;
13856 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13857 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13858 		return -EINVAL;
13859 	}
13860 
13861 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13862 	tr = bpf_trampoline_get(key, &tgt_info);
13863 	if (!tr)
13864 		return -ENOMEM;
13865 
13866 	prog->aux->dst_trampoline = tr;
13867 	return 0;
13868 }
13869 
13870 struct btf *bpf_get_btf_vmlinux(void)
13871 {
13872 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13873 		mutex_lock(&bpf_verifier_lock);
13874 		if (!btf_vmlinux)
13875 			btf_vmlinux = btf_parse_vmlinux();
13876 		mutex_unlock(&bpf_verifier_lock);
13877 	}
13878 	return btf_vmlinux;
13879 }
13880 
13881 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13882 {
13883 	u64 start_time = ktime_get_ns();
13884 	struct bpf_verifier_env *env;
13885 	struct bpf_verifier_log *log;
13886 	int i, len, ret = -EINVAL;
13887 	bool is_priv;
13888 
13889 	/* no program is valid */
13890 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13891 		return -EINVAL;
13892 
13893 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13894 	 * allocate/free it every time bpf_check() is called
13895 	 */
13896 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13897 	if (!env)
13898 		return -ENOMEM;
13899 	log = &env->log;
13900 
13901 	len = (*prog)->len;
13902 	env->insn_aux_data =
13903 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13904 	ret = -ENOMEM;
13905 	if (!env->insn_aux_data)
13906 		goto err_free_env;
13907 	for (i = 0; i < len; i++)
13908 		env->insn_aux_data[i].orig_idx = i;
13909 	env->prog = *prog;
13910 	env->ops = bpf_verifier_ops[env->prog->type];
13911 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13912 	is_priv = bpf_capable();
13913 
13914 	bpf_get_btf_vmlinux();
13915 
13916 	/* grab the mutex to protect few globals used by verifier */
13917 	if (!is_priv)
13918 		mutex_lock(&bpf_verifier_lock);
13919 
13920 	if (attr->log_level || attr->log_buf || attr->log_size) {
13921 		/* user requested verbose verifier output
13922 		 * and supplied buffer to store the verification trace
13923 		 */
13924 		log->level = attr->log_level;
13925 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13926 		log->len_total = attr->log_size;
13927 
13928 		ret = -EINVAL;
13929 		/* log attributes have to be sane */
13930 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13931 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13932 			goto err_unlock;
13933 	}
13934 
13935 	if (IS_ERR(btf_vmlinux)) {
13936 		/* Either gcc or pahole or kernel are broken. */
13937 		verbose(env, "in-kernel BTF is malformed\n");
13938 		ret = PTR_ERR(btf_vmlinux);
13939 		goto skip_full_check;
13940 	}
13941 
13942 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13943 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13944 		env->strict_alignment = true;
13945 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13946 		env->strict_alignment = false;
13947 
13948 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13949 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13950 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13951 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13952 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13953 	env->bpf_capable = bpf_capable();
13954 
13955 	if (is_priv)
13956 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13957 
13958 	env->explored_states = kvcalloc(state_htab_size(env),
13959 				       sizeof(struct bpf_verifier_state_list *),
13960 				       GFP_USER);
13961 	ret = -ENOMEM;
13962 	if (!env->explored_states)
13963 		goto skip_full_check;
13964 
13965 	ret = add_subprog_and_kfunc(env);
13966 	if (ret < 0)
13967 		goto skip_full_check;
13968 
13969 	ret = check_subprogs(env);
13970 	if (ret < 0)
13971 		goto skip_full_check;
13972 
13973 	ret = check_btf_info(env, attr, uattr);
13974 	if (ret < 0)
13975 		goto skip_full_check;
13976 
13977 	ret = check_attach_btf_id(env);
13978 	if (ret)
13979 		goto skip_full_check;
13980 
13981 	ret = resolve_pseudo_ldimm64(env);
13982 	if (ret < 0)
13983 		goto skip_full_check;
13984 
13985 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
13986 		ret = bpf_prog_offload_verifier_prep(env->prog);
13987 		if (ret)
13988 			goto skip_full_check;
13989 	}
13990 
13991 	ret = check_cfg(env);
13992 	if (ret < 0)
13993 		goto skip_full_check;
13994 
13995 	ret = do_check_subprogs(env);
13996 	ret = ret ?: do_check_main(env);
13997 
13998 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13999 		ret = bpf_prog_offload_finalize(env);
14000 
14001 skip_full_check:
14002 	kvfree(env->explored_states);
14003 
14004 	if (ret == 0)
14005 		ret = check_max_stack_depth(env);
14006 
14007 	/* instruction rewrites happen after this point */
14008 	if (is_priv) {
14009 		if (ret == 0)
14010 			opt_hard_wire_dead_code_branches(env);
14011 		if (ret == 0)
14012 			ret = opt_remove_dead_code(env);
14013 		if (ret == 0)
14014 			ret = opt_remove_nops(env);
14015 	} else {
14016 		if (ret == 0)
14017 			sanitize_dead_code(env);
14018 	}
14019 
14020 	if (ret == 0)
14021 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14022 		ret = convert_ctx_accesses(env);
14023 
14024 	if (ret == 0)
14025 		ret = do_misc_fixups(env);
14026 
14027 	/* do 32-bit optimization after insn patching has done so those patched
14028 	 * insns could be handled correctly.
14029 	 */
14030 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14031 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14032 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14033 								     : false;
14034 	}
14035 
14036 	if (ret == 0)
14037 		ret = fixup_call_args(env);
14038 
14039 	env->verification_time = ktime_get_ns() - start_time;
14040 	print_verification_stats(env);
14041 
14042 	if (log->level && bpf_verifier_log_full(log))
14043 		ret = -ENOSPC;
14044 	if (log->level && !log->ubuf) {
14045 		ret = -EFAULT;
14046 		goto err_release_maps;
14047 	}
14048 
14049 	if (ret)
14050 		goto err_release_maps;
14051 
14052 	if (env->used_map_cnt) {
14053 		/* if program passed verifier, update used_maps in bpf_prog_info */
14054 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14055 							  sizeof(env->used_maps[0]),
14056 							  GFP_KERNEL);
14057 
14058 		if (!env->prog->aux->used_maps) {
14059 			ret = -ENOMEM;
14060 			goto err_release_maps;
14061 		}
14062 
14063 		memcpy(env->prog->aux->used_maps, env->used_maps,
14064 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14065 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14066 	}
14067 	if (env->used_btf_cnt) {
14068 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14069 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14070 							  sizeof(env->used_btfs[0]),
14071 							  GFP_KERNEL);
14072 		if (!env->prog->aux->used_btfs) {
14073 			ret = -ENOMEM;
14074 			goto err_release_maps;
14075 		}
14076 
14077 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14078 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14079 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14080 	}
14081 	if (env->used_map_cnt || env->used_btf_cnt) {
14082 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14083 		 * bpf_ld_imm64 instructions
14084 		 */
14085 		convert_pseudo_ld_imm64(env);
14086 	}
14087 
14088 	adjust_btf_func(env);
14089 
14090 err_release_maps:
14091 	if (!env->prog->aux->used_maps)
14092 		/* if we didn't copy map pointers into bpf_prog_info, release
14093 		 * them now. Otherwise free_used_maps() will release them.
14094 		 */
14095 		release_maps(env);
14096 	if (!env->prog->aux->used_btfs)
14097 		release_btfs(env);
14098 
14099 	/* extension progs temporarily inherit the attach_type of their targets
14100 	   for verification purposes, so set it back to zero before returning
14101 	 */
14102 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14103 		env->prog->expected_attach_type = 0;
14104 
14105 	*prog = env->prog;
14106 err_unlock:
14107 	if (!is_priv)
14108 		mutex_unlock(&bpf_verifier_lock);
14109 	vfree(env->insn_aux_data);
14110 err_free_env:
14111 	kfree(env);
14112 	return ret;
14113 }
14114