xref: /linux/kernel/bpf/verifier.c (revision 314f14abdeca78de6b16f97d796a9966ce4b90ae)
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 			verbose(env, "invalid module BTF fd specified\n");
1732 			return btf;
1733 		}
1734 
1735 		if (!btf_is_module(btf)) {
1736 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1737 			btf_put(btf);
1738 			return ERR_PTR(-EINVAL);
1739 		}
1740 
1741 		mod = btf_try_get_module(btf);
1742 		if (!mod) {
1743 			btf_put(btf);
1744 			return ERR_PTR(-ENXIO);
1745 		}
1746 
1747 		b = &tab->descs[tab->nr_descs++];
1748 		b->btf = btf;
1749 		b->module = mod;
1750 		b->offset = offset;
1751 
1752 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1753 		     kfunc_btf_cmp_by_off, NULL);
1754 	}
1755 	if (btf_modp)
1756 		*btf_modp = b->module;
1757 	return b->btf;
1758 }
1759 
1760 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1761 {
1762 	if (!tab)
1763 		return;
1764 
1765 	while (tab->nr_descs--) {
1766 		module_put(tab->descs[tab->nr_descs].module);
1767 		btf_put(tab->descs[tab->nr_descs].btf);
1768 	}
1769 	kfree(tab);
1770 }
1771 
1772 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
1773 				       u32 func_id, s16 offset,
1774 				       struct module **btf_modp)
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 		return __find_kfunc_desc_btf(env, offset, btf_modp);
1786 	}
1787 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
1788 }
1789 
1790 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1791 {
1792 	const struct btf_type *func, *func_proto;
1793 	struct bpf_kfunc_btf_tab *btf_tab;
1794 	struct bpf_kfunc_desc_tab *tab;
1795 	struct bpf_prog_aux *prog_aux;
1796 	struct bpf_kfunc_desc *desc;
1797 	const char *func_name;
1798 	struct btf *desc_btf;
1799 	unsigned long addr;
1800 	int err;
1801 
1802 	prog_aux = env->prog->aux;
1803 	tab = prog_aux->kfunc_tab;
1804 	btf_tab = prog_aux->kfunc_btf_tab;
1805 	if (!tab) {
1806 		if (!btf_vmlinux) {
1807 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1808 			return -ENOTSUPP;
1809 		}
1810 
1811 		if (!env->prog->jit_requested) {
1812 			verbose(env, "JIT is required for calling kernel function\n");
1813 			return -ENOTSUPP;
1814 		}
1815 
1816 		if (!bpf_jit_supports_kfunc_call()) {
1817 			verbose(env, "JIT does not support calling kernel function\n");
1818 			return -ENOTSUPP;
1819 		}
1820 
1821 		if (!env->prog->gpl_compatible) {
1822 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1823 			return -EINVAL;
1824 		}
1825 
1826 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1827 		if (!tab)
1828 			return -ENOMEM;
1829 		prog_aux->kfunc_tab = tab;
1830 	}
1831 
1832 	/* func_id == 0 is always invalid, but instead of returning an error, be
1833 	 * conservative and wait until the code elimination pass before returning
1834 	 * error, so that invalid calls that get pruned out can be in BPF programs
1835 	 * loaded from userspace.  It is also required that offset be untouched
1836 	 * for such calls.
1837 	 */
1838 	if (!func_id && !offset)
1839 		return 0;
1840 
1841 	if (!btf_tab && offset) {
1842 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1843 		if (!btf_tab)
1844 			return -ENOMEM;
1845 		prog_aux->kfunc_btf_tab = btf_tab;
1846 	}
1847 
1848 	desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL);
1849 	if (IS_ERR(desc_btf)) {
1850 		verbose(env, "failed to find BTF for kernel function\n");
1851 		return PTR_ERR(desc_btf);
1852 	}
1853 
1854 	if (find_kfunc_desc(env->prog, func_id, offset))
1855 		return 0;
1856 
1857 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1858 		verbose(env, "too many different kernel function calls\n");
1859 		return -E2BIG;
1860 	}
1861 
1862 	func = btf_type_by_id(desc_btf, func_id);
1863 	if (!func || !btf_type_is_func(func)) {
1864 		verbose(env, "kernel btf_id %u is not a function\n",
1865 			func_id);
1866 		return -EINVAL;
1867 	}
1868 	func_proto = btf_type_by_id(desc_btf, func->type);
1869 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1870 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1871 			func_id);
1872 		return -EINVAL;
1873 	}
1874 
1875 	func_name = btf_name_by_offset(desc_btf, func->name_off);
1876 	addr = kallsyms_lookup_name(func_name);
1877 	if (!addr) {
1878 		verbose(env, "cannot find address for kernel function %s\n",
1879 			func_name);
1880 		return -EINVAL;
1881 	}
1882 
1883 	desc = &tab->descs[tab->nr_descs++];
1884 	desc->func_id = func_id;
1885 	desc->imm = BPF_CALL_IMM(addr);
1886 	desc->offset = offset;
1887 	err = btf_distill_func_proto(&env->log, desc_btf,
1888 				     func_proto, func_name,
1889 				     &desc->func_model);
1890 	if (!err)
1891 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1892 		     kfunc_desc_cmp_by_id_off, NULL);
1893 	return err;
1894 }
1895 
1896 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1897 {
1898 	const struct bpf_kfunc_desc *d0 = a;
1899 	const struct bpf_kfunc_desc *d1 = b;
1900 
1901 	if (d0->imm > d1->imm)
1902 		return 1;
1903 	else if (d0->imm < d1->imm)
1904 		return -1;
1905 	return 0;
1906 }
1907 
1908 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1909 {
1910 	struct bpf_kfunc_desc_tab *tab;
1911 
1912 	tab = prog->aux->kfunc_tab;
1913 	if (!tab)
1914 		return;
1915 
1916 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1917 	     kfunc_desc_cmp_by_imm, NULL);
1918 }
1919 
1920 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1921 {
1922 	return !!prog->aux->kfunc_tab;
1923 }
1924 
1925 const struct btf_func_model *
1926 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1927 			 const struct bpf_insn *insn)
1928 {
1929 	const struct bpf_kfunc_desc desc = {
1930 		.imm = insn->imm,
1931 	};
1932 	const struct bpf_kfunc_desc *res;
1933 	struct bpf_kfunc_desc_tab *tab;
1934 
1935 	tab = prog->aux->kfunc_tab;
1936 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1937 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1938 
1939 	return res ? &res->func_model : NULL;
1940 }
1941 
1942 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1943 {
1944 	struct bpf_subprog_info *subprog = env->subprog_info;
1945 	struct bpf_insn *insn = env->prog->insnsi;
1946 	int i, ret, insn_cnt = env->prog->len;
1947 
1948 	/* Add entry function. */
1949 	ret = add_subprog(env, 0);
1950 	if (ret)
1951 		return ret;
1952 
1953 	for (i = 0; i < insn_cnt; i++, insn++) {
1954 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1955 		    !bpf_pseudo_kfunc_call(insn))
1956 			continue;
1957 
1958 		if (!env->bpf_capable) {
1959 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1960 			return -EPERM;
1961 		}
1962 
1963 		if (bpf_pseudo_func(insn)) {
1964 			ret = add_subprog(env, i + insn->imm + 1);
1965 			if (ret >= 0)
1966 				/* remember subprog */
1967 				insn[1].imm = ret;
1968 		} else if (bpf_pseudo_call(insn)) {
1969 			ret = add_subprog(env, i + insn->imm + 1);
1970 		} else {
1971 			ret = add_kfunc_call(env, insn->imm, insn->off);
1972 		}
1973 
1974 		if (ret < 0)
1975 			return ret;
1976 	}
1977 
1978 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1979 	 * logic. 'subprog_cnt' should not be increased.
1980 	 */
1981 	subprog[env->subprog_cnt].start = insn_cnt;
1982 
1983 	if (env->log.level & BPF_LOG_LEVEL2)
1984 		for (i = 0; i < env->subprog_cnt; i++)
1985 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1986 
1987 	return 0;
1988 }
1989 
1990 static int check_subprogs(struct bpf_verifier_env *env)
1991 {
1992 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1993 	struct bpf_subprog_info *subprog = env->subprog_info;
1994 	struct bpf_insn *insn = env->prog->insnsi;
1995 	int insn_cnt = env->prog->len;
1996 
1997 	/* now check that all jumps are within the same subprog */
1998 	subprog_start = subprog[cur_subprog].start;
1999 	subprog_end = subprog[cur_subprog + 1].start;
2000 	for (i = 0; i < insn_cnt; i++) {
2001 		u8 code = insn[i].code;
2002 
2003 		if (code == (BPF_JMP | BPF_CALL) &&
2004 		    insn[i].imm == BPF_FUNC_tail_call &&
2005 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2006 			subprog[cur_subprog].has_tail_call = true;
2007 		if (BPF_CLASS(code) == BPF_LD &&
2008 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2009 			subprog[cur_subprog].has_ld_abs = true;
2010 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2011 			goto next;
2012 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2013 			goto next;
2014 		off = i + insn[i].off + 1;
2015 		if (off < subprog_start || off >= subprog_end) {
2016 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2017 			return -EINVAL;
2018 		}
2019 next:
2020 		if (i == subprog_end - 1) {
2021 			/* to avoid fall-through from one subprog into another
2022 			 * the last insn of the subprog should be either exit
2023 			 * or unconditional jump back
2024 			 */
2025 			if (code != (BPF_JMP | BPF_EXIT) &&
2026 			    code != (BPF_JMP | BPF_JA)) {
2027 				verbose(env, "last insn is not an exit or jmp\n");
2028 				return -EINVAL;
2029 			}
2030 			subprog_start = subprog_end;
2031 			cur_subprog++;
2032 			if (cur_subprog < env->subprog_cnt)
2033 				subprog_end = subprog[cur_subprog + 1].start;
2034 		}
2035 	}
2036 	return 0;
2037 }
2038 
2039 /* Parentage chain of this register (or stack slot) should take care of all
2040  * issues like callee-saved registers, stack slot allocation time, etc.
2041  */
2042 static int mark_reg_read(struct bpf_verifier_env *env,
2043 			 const struct bpf_reg_state *state,
2044 			 struct bpf_reg_state *parent, u8 flag)
2045 {
2046 	bool writes = parent == state->parent; /* Observe write marks */
2047 	int cnt = 0;
2048 
2049 	while (parent) {
2050 		/* if read wasn't screened by an earlier write ... */
2051 		if (writes && state->live & REG_LIVE_WRITTEN)
2052 			break;
2053 		if (parent->live & REG_LIVE_DONE) {
2054 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2055 				reg_type_str[parent->type],
2056 				parent->var_off.value, parent->off);
2057 			return -EFAULT;
2058 		}
2059 		/* The first condition is more likely to be true than the
2060 		 * second, checked it first.
2061 		 */
2062 		if ((parent->live & REG_LIVE_READ) == flag ||
2063 		    parent->live & REG_LIVE_READ64)
2064 			/* The parentage chain never changes and
2065 			 * this parent was already marked as LIVE_READ.
2066 			 * There is no need to keep walking the chain again and
2067 			 * keep re-marking all parents as LIVE_READ.
2068 			 * This case happens when the same register is read
2069 			 * multiple times without writes into it in-between.
2070 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2071 			 * then no need to set the weak REG_LIVE_READ32.
2072 			 */
2073 			break;
2074 		/* ... then we depend on parent's value */
2075 		parent->live |= flag;
2076 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2077 		if (flag == REG_LIVE_READ64)
2078 			parent->live &= ~REG_LIVE_READ32;
2079 		state = parent;
2080 		parent = state->parent;
2081 		writes = true;
2082 		cnt++;
2083 	}
2084 
2085 	if (env->longest_mark_read_walk < cnt)
2086 		env->longest_mark_read_walk = cnt;
2087 	return 0;
2088 }
2089 
2090 /* This function is supposed to be used by the following 32-bit optimization
2091  * code only. It returns TRUE if the source or destination register operates
2092  * on 64-bit, otherwise return FALSE.
2093  */
2094 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2095 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2096 {
2097 	u8 code, class, op;
2098 
2099 	code = insn->code;
2100 	class = BPF_CLASS(code);
2101 	op = BPF_OP(code);
2102 	if (class == BPF_JMP) {
2103 		/* BPF_EXIT for "main" will reach here. Return TRUE
2104 		 * conservatively.
2105 		 */
2106 		if (op == BPF_EXIT)
2107 			return true;
2108 		if (op == BPF_CALL) {
2109 			/* BPF to BPF call will reach here because of marking
2110 			 * caller saved clobber with DST_OP_NO_MARK for which we
2111 			 * don't care the register def because they are anyway
2112 			 * marked as NOT_INIT already.
2113 			 */
2114 			if (insn->src_reg == BPF_PSEUDO_CALL)
2115 				return false;
2116 			/* Helper call will reach here because of arg type
2117 			 * check, conservatively return TRUE.
2118 			 */
2119 			if (t == SRC_OP)
2120 				return true;
2121 
2122 			return false;
2123 		}
2124 	}
2125 
2126 	if (class == BPF_ALU64 || class == BPF_JMP ||
2127 	    /* BPF_END always use BPF_ALU class. */
2128 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2129 		return true;
2130 
2131 	if (class == BPF_ALU || class == BPF_JMP32)
2132 		return false;
2133 
2134 	if (class == BPF_LDX) {
2135 		if (t != SRC_OP)
2136 			return BPF_SIZE(code) == BPF_DW;
2137 		/* LDX source must be ptr. */
2138 		return true;
2139 	}
2140 
2141 	if (class == BPF_STX) {
2142 		/* BPF_STX (including atomic variants) has multiple source
2143 		 * operands, one of which is a ptr. Check whether the caller is
2144 		 * asking about it.
2145 		 */
2146 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2147 			return true;
2148 		return BPF_SIZE(code) == BPF_DW;
2149 	}
2150 
2151 	if (class == BPF_LD) {
2152 		u8 mode = BPF_MODE(code);
2153 
2154 		/* LD_IMM64 */
2155 		if (mode == BPF_IMM)
2156 			return true;
2157 
2158 		/* Both LD_IND and LD_ABS return 32-bit data. */
2159 		if (t != SRC_OP)
2160 			return  false;
2161 
2162 		/* Implicit ctx ptr. */
2163 		if (regno == BPF_REG_6)
2164 			return true;
2165 
2166 		/* Explicit source could be any width. */
2167 		return true;
2168 	}
2169 
2170 	if (class == BPF_ST)
2171 		/* The only source register for BPF_ST is a ptr. */
2172 		return true;
2173 
2174 	/* Conservatively return true at default. */
2175 	return true;
2176 }
2177 
2178 /* Return the regno defined by the insn, or -1. */
2179 static int insn_def_regno(const struct bpf_insn *insn)
2180 {
2181 	switch (BPF_CLASS(insn->code)) {
2182 	case BPF_JMP:
2183 	case BPF_JMP32:
2184 	case BPF_ST:
2185 		return -1;
2186 	case BPF_STX:
2187 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2188 		    (insn->imm & BPF_FETCH)) {
2189 			if (insn->imm == BPF_CMPXCHG)
2190 				return BPF_REG_0;
2191 			else
2192 				return insn->src_reg;
2193 		} else {
2194 			return -1;
2195 		}
2196 	default:
2197 		return insn->dst_reg;
2198 	}
2199 }
2200 
2201 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2202 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2203 {
2204 	int dst_reg = insn_def_regno(insn);
2205 
2206 	if (dst_reg == -1)
2207 		return false;
2208 
2209 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2210 }
2211 
2212 static void mark_insn_zext(struct bpf_verifier_env *env,
2213 			   struct bpf_reg_state *reg)
2214 {
2215 	s32 def_idx = reg->subreg_def;
2216 
2217 	if (def_idx == DEF_NOT_SUBREG)
2218 		return;
2219 
2220 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2221 	/* The dst will be zero extended, so won't be sub-register anymore. */
2222 	reg->subreg_def = DEF_NOT_SUBREG;
2223 }
2224 
2225 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2226 			 enum reg_arg_type t)
2227 {
2228 	struct bpf_verifier_state *vstate = env->cur_state;
2229 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2230 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2231 	struct bpf_reg_state *reg, *regs = state->regs;
2232 	bool rw64;
2233 
2234 	if (regno >= MAX_BPF_REG) {
2235 		verbose(env, "R%d is invalid\n", regno);
2236 		return -EINVAL;
2237 	}
2238 
2239 	reg = &regs[regno];
2240 	rw64 = is_reg64(env, insn, regno, reg, t);
2241 	if (t == SRC_OP) {
2242 		/* check whether register used as source operand can be read */
2243 		if (reg->type == NOT_INIT) {
2244 			verbose(env, "R%d !read_ok\n", regno);
2245 			return -EACCES;
2246 		}
2247 		/* We don't need to worry about FP liveness because it's read-only */
2248 		if (regno == BPF_REG_FP)
2249 			return 0;
2250 
2251 		if (rw64)
2252 			mark_insn_zext(env, reg);
2253 
2254 		return mark_reg_read(env, reg, reg->parent,
2255 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2256 	} else {
2257 		/* check whether register used as dest operand can be written to */
2258 		if (regno == BPF_REG_FP) {
2259 			verbose(env, "frame pointer is read only\n");
2260 			return -EACCES;
2261 		}
2262 		reg->live |= REG_LIVE_WRITTEN;
2263 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2264 		if (t == DST_OP)
2265 			mark_reg_unknown(env, regs, regno);
2266 	}
2267 	return 0;
2268 }
2269 
2270 /* for any branch, call, exit record the history of jmps in the given state */
2271 static int push_jmp_history(struct bpf_verifier_env *env,
2272 			    struct bpf_verifier_state *cur)
2273 {
2274 	u32 cnt = cur->jmp_history_cnt;
2275 	struct bpf_idx_pair *p;
2276 
2277 	cnt++;
2278 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2279 	if (!p)
2280 		return -ENOMEM;
2281 	p[cnt - 1].idx = env->insn_idx;
2282 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2283 	cur->jmp_history = p;
2284 	cur->jmp_history_cnt = cnt;
2285 	return 0;
2286 }
2287 
2288 /* Backtrack one insn at a time. If idx is not at the top of recorded
2289  * history then previous instruction came from straight line execution.
2290  */
2291 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2292 			     u32 *history)
2293 {
2294 	u32 cnt = *history;
2295 
2296 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2297 		i = st->jmp_history[cnt - 1].prev_idx;
2298 		(*history)--;
2299 	} else {
2300 		i--;
2301 	}
2302 	return i;
2303 }
2304 
2305 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2306 {
2307 	const struct btf_type *func;
2308 	struct btf *desc_btf;
2309 
2310 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2311 		return NULL;
2312 
2313 	desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL);
2314 	if (IS_ERR(desc_btf))
2315 		return "<error>";
2316 
2317 	func = btf_type_by_id(desc_btf, insn->imm);
2318 	return btf_name_by_offset(desc_btf, func->name_off);
2319 }
2320 
2321 /* For given verifier state backtrack_insn() is called from the last insn to
2322  * the first insn. Its purpose is to compute a bitmask of registers and
2323  * stack slots that needs precision in the parent verifier state.
2324  */
2325 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2326 			  u32 *reg_mask, u64 *stack_mask)
2327 {
2328 	const struct bpf_insn_cbs cbs = {
2329 		.cb_call	= disasm_kfunc_name,
2330 		.cb_print	= verbose,
2331 		.private_data	= env,
2332 	};
2333 	struct bpf_insn *insn = env->prog->insnsi + idx;
2334 	u8 class = BPF_CLASS(insn->code);
2335 	u8 opcode = BPF_OP(insn->code);
2336 	u8 mode = BPF_MODE(insn->code);
2337 	u32 dreg = 1u << insn->dst_reg;
2338 	u32 sreg = 1u << insn->src_reg;
2339 	u32 spi;
2340 
2341 	if (insn->code == 0)
2342 		return 0;
2343 	if (env->log.level & BPF_LOG_LEVEL) {
2344 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2345 		verbose(env, "%d: ", idx);
2346 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2347 	}
2348 
2349 	if (class == BPF_ALU || class == BPF_ALU64) {
2350 		if (!(*reg_mask & dreg))
2351 			return 0;
2352 		if (opcode == BPF_MOV) {
2353 			if (BPF_SRC(insn->code) == BPF_X) {
2354 				/* dreg = sreg
2355 				 * dreg needs precision after this insn
2356 				 * sreg needs precision before this insn
2357 				 */
2358 				*reg_mask &= ~dreg;
2359 				*reg_mask |= sreg;
2360 			} else {
2361 				/* dreg = K
2362 				 * dreg needs precision after this insn.
2363 				 * Corresponding register is already marked
2364 				 * as precise=true in this verifier state.
2365 				 * No further markings in parent are necessary
2366 				 */
2367 				*reg_mask &= ~dreg;
2368 			}
2369 		} else {
2370 			if (BPF_SRC(insn->code) == BPF_X) {
2371 				/* dreg += sreg
2372 				 * both dreg and sreg need precision
2373 				 * before this insn
2374 				 */
2375 				*reg_mask |= sreg;
2376 			} /* else dreg += K
2377 			   * dreg still needs precision before this insn
2378 			   */
2379 		}
2380 	} else if (class == BPF_LDX) {
2381 		if (!(*reg_mask & dreg))
2382 			return 0;
2383 		*reg_mask &= ~dreg;
2384 
2385 		/* scalars can only be spilled into stack w/o losing precision.
2386 		 * Load from any other memory can be zero extended.
2387 		 * The desire to keep that precision is already indicated
2388 		 * by 'precise' mark in corresponding register of this state.
2389 		 * No further tracking necessary.
2390 		 */
2391 		if (insn->src_reg != BPF_REG_FP)
2392 			return 0;
2393 		if (BPF_SIZE(insn->code) != BPF_DW)
2394 			return 0;
2395 
2396 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2397 		 * that [fp - off] slot contains scalar that needs to be
2398 		 * tracked with precision
2399 		 */
2400 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2401 		if (spi >= 64) {
2402 			verbose(env, "BUG spi %d\n", spi);
2403 			WARN_ONCE(1, "verifier backtracking bug");
2404 			return -EFAULT;
2405 		}
2406 		*stack_mask |= 1ull << spi;
2407 	} else if (class == BPF_STX || class == BPF_ST) {
2408 		if (*reg_mask & dreg)
2409 			/* stx & st shouldn't be using _scalar_ dst_reg
2410 			 * to access memory. It means backtracking
2411 			 * encountered a case of pointer subtraction.
2412 			 */
2413 			return -ENOTSUPP;
2414 		/* scalars can only be spilled into stack */
2415 		if (insn->dst_reg != BPF_REG_FP)
2416 			return 0;
2417 		if (BPF_SIZE(insn->code) != BPF_DW)
2418 			return 0;
2419 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2420 		if (spi >= 64) {
2421 			verbose(env, "BUG spi %d\n", spi);
2422 			WARN_ONCE(1, "verifier backtracking bug");
2423 			return -EFAULT;
2424 		}
2425 		if (!(*stack_mask & (1ull << spi)))
2426 			return 0;
2427 		*stack_mask &= ~(1ull << spi);
2428 		if (class == BPF_STX)
2429 			*reg_mask |= sreg;
2430 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2431 		if (opcode == BPF_CALL) {
2432 			if (insn->src_reg == BPF_PSEUDO_CALL)
2433 				return -ENOTSUPP;
2434 			/* regular helper call sets R0 */
2435 			*reg_mask &= ~1;
2436 			if (*reg_mask & 0x3f) {
2437 				/* if backtracing was looking for registers R1-R5
2438 				 * they should have been found already.
2439 				 */
2440 				verbose(env, "BUG regs %x\n", *reg_mask);
2441 				WARN_ONCE(1, "verifier backtracking bug");
2442 				return -EFAULT;
2443 			}
2444 		} else if (opcode == BPF_EXIT) {
2445 			return -ENOTSUPP;
2446 		}
2447 	} else if (class == BPF_LD) {
2448 		if (!(*reg_mask & dreg))
2449 			return 0;
2450 		*reg_mask &= ~dreg;
2451 		/* It's ld_imm64 or ld_abs or ld_ind.
2452 		 * For ld_imm64 no further tracking of precision
2453 		 * into parent is necessary
2454 		 */
2455 		if (mode == BPF_IND || mode == BPF_ABS)
2456 			/* to be analyzed */
2457 			return -ENOTSUPP;
2458 	}
2459 	return 0;
2460 }
2461 
2462 /* the scalar precision tracking algorithm:
2463  * . at the start all registers have precise=false.
2464  * . scalar ranges are tracked as normal through alu and jmp insns.
2465  * . once precise value of the scalar register is used in:
2466  *   .  ptr + scalar alu
2467  *   . if (scalar cond K|scalar)
2468  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2469  *   backtrack through the verifier states and mark all registers and
2470  *   stack slots with spilled constants that these scalar regisers
2471  *   should be precise.
2472  * . during state pruning two registers (or spilled stack slots)
2473  *   are equivalent if both are not precise.
2474  *
2475  * Note the verifier cannot simply walk register parentage chain,
2476  * since many different registers and stack slots could have been
2477  * used to compute single precise scalar.
2478  *
2479  * The approach of starting with precise=true for all registers and then
2480  * backtrack to mark a register as not precise when the verifier detects
2481  * that program doesn't care about specific value (e.g., when helper
2482  * takes register as ARG_ANYTHING parameter) is not safe.
2483  *
2484  * It's ok to walk single parentage chain of the verifier states.
2485  * It's possible that this backtracking will go all the way till 1st insn.
2486  * All other branches will be explored for needing precision later.
2487  *
2488  * The backtracking needs to deal with cases like:
2489  *   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)
2490  * r9 -= r8
2491  * r5 = r9
2492  * if r5 > 0x79f goto pc+7
2493  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2494  * r5 += 1
2495  * ...
2496  * call bpf_perf_event_output#25
2497  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2498  *
2499  * and this case:
2500  * r6 = 1
2501  * call foo // uses callee's r6 inside to compute r0
2502  * r0 += r6
2503  * if r0 == 0 goto
2504  *
2505  * to track above reg_mask/stack_mask needs to be independent for each frame.
2506  *
2507  * Also if parent's curframe > frame where backtracking started,
2508  * the verifier need to mark registers in both frames, otherwise callees
2509  * may incorrectly prune callers. This is similar to
2510  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2511  *
2512  * For now backtracking falls back into conservative marking.
2513  */
2514 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2515 				     struct bpf_verifier_state *st)
2516 {
2517 	struct bpf_func_state *func;
2518 	struct bpf_reg_state *reg;
2519 	int i, j;
2520 
2521 	/* big hammer: mark all scalars precise in this path.
2522 	 * pop_stack may still get !precise scalars.
2523 	 */
2524 	for (; st; st = st->parent)
2525 		for (i = 0; i <= st->curframe; i++) {
2526 			func = st->frame[i];
2527 			for (j = 0; j < BPF_REG_FP; j++) {
2528 				reg = &func->regs[j];
2529 				if (reg->type != SCALAR_VALUE)
2530 					continue;
2531 				reg->precise = true;
2532 			}
2533 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2534 				if (!is_spilled_reg(&func->stack[j]))
2535 					continue;
2536 				reg = &func->stack[j].spilled_ptr;
2537 				if (reg->type != SCALAR_VALUE)
2538 					continue;
2539 				reg->precise = true;
2540 			}
2541 		}
2542 }
2543 
2544 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2545 				  int spi)
2546 {
2547 	struct bpf_verifier_state *st = env->cur_state;
2548 	int first_idx = st->first_insn_idx;
2549 	int last_idx = env->insn_idx;
2550 	struct bpf_func_state *func;
2551 	struct bpf_reg_state *reg;
2552 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2553 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2554 	bool skip_first = true;
2555 	bool new_marks = false;
2556 	int i, err;
2557 
2558 	if (!env->bpf_capable)
2559 		return 0;
2560 
2561 	func = st->frame[st->curframe];
2562 	if (regno >= 0) {
2563 		reg = &func->regs[regno];
2564 		if (reg->type != SCALAR_VALUE) {
2565 			WARN_ONCE(1, "backtracing misuse");
2566 			return -EFAULT;
2567 		}
2568 		if (!reg->precise)
2569 			new_marks = true;
2570 		else
2571 			reg_mask = 0;
2572 		reg->precise = true;
2573 	}
2574 
2575 	while (spi >= 0) {
2576 		if (!is_spilled_reg(&func->stack[spi])) {
2577 			stack_mask = 0;
2578 			break;
2579 		}
2580 		reg = &func->stack[spi].spilled_ptr;
2581 		if (reg->type != SCALAR_VALUE) {
2582 			stack_mask = 0;
2583 			break;
2584 		}
2585 		if (!reg->precise)
2586 			new_marks = true;
2587 		else
2588 			stack_mask = 0;
2589 		reg->precise = true;
2590 		break;
2591 	}
2592 
2593 	if (!new_marks)
2594 		return 0;
2595 	if (!reg_mask && !stack_mask)
2596 		return 0;
2597 	for (;;) {
2598 		DECLARE_BITMAP(mask, 64);
2599 		u32 history = st->jmp_history_cnt;
2600 
2601 		if (env->log.level & BPF_LOG_LEVEL)
2602 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2603 		for (i = last_idx;;) {
2604 			if (skip_first) {
2605 				err = 0;
2606 				skip_first = false;
2607 			} else {
2608 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2609 			}
2610 			if (err == -ENOTSUPP) {
2611 				mark_all_scalars_precise(env, st);
2612 				return 0;
2613 			} else if (err) {
2614 				return err;
2615 			}
2616 			if (!reg_mask && !stack_mask)
2617 				/* Found assignment(s) into tracked register in this state.
2618 				 * Since this state is already marked, just return.
2619 				 * Nothing to be tracked further in the parent state.
2620 				 */
2621 				return 0;
2622 			if (i == first_idx)
2623 				break;
2624 			i = get_prev_insn_idx(st, i, &history);
2625 			if (i >= env->prog->len) {
2626 				/* This can happen if backtracking reached insn 0
2627 				 * and there are still reg_mask or stack_mask
2628 				 * to backtrack.
2629 				 * It means the backtracking missed the spot where
2630 				 * particular register was initialized with a constant.
2631 				 */
2632 				verbose(env, "BUG backtracking idx %d\n", i);
2633 				WARN_ONCE(1, "verifier backtracking bug");
2634 				return -EFAULT;
2635 			}
2636 		}
2637 		st = st->parent;
2638 		if (!st)
2639 			break;
2640 
2641 		new_marks = false;
2642 		func = st->frame[st->curframe];
2643 		bitmap_from_u64(mask, reg_mask);
2644 		for_each_set_bit(i, mask, 32) {
2645 			reg = &func->regs[i];
2646 			if (reg->type != SCALAR_VALUE) {
2647 				reg_mask &= ~(1u << i);
2648 				continue;
2649 			}
2650 			if (!reg->precise)
2651 				new_marks = true;
2652 			reg->precise = true;
2653 		}
2654 
2655 		bitmap_from_u64(mask, stack_mask);
2656 		for_each_set_bit(i, mask, 64) {
2657 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2658 				/* the sequence of instructions:
2659 				 * 2: (bf) r3 = r10
2660 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2661 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2662 				 * doesn't contain jmps. It's backtracked
2663 				 * as a single block.
2664 				 * During backtracking insn 3 is not recognized as
2665 				 * stack access, so at the end of backtracking
2666 				 * stack slot fp-8 is still marked in stack_mask.
2667 				 * However the parent state may not have accessed
2668 				 * fp-8 and it's "unallocated" stack space.
2669 				 * In such case fallback to conservative.
2670 				 */
2671 				mark_all_scalars_precise(env, st);
2672 				return 0;
2673 			}
2674 
2675 			if (!is_spilled_reg(&func->stack[i])) {
2676 				stack_mask &= ~(1ull << i);
2677 				continue;
2678 			}
2679 			reg = &func->stack[i].spilled_ptr;
2680 			if (reg->type != SCALAR_VALUE) {
2681 				stack_mask &= ~(1ull << i);
2682 				continue;
2683 			}
2684 			if (!reg->precise)
2685 				new_marks = true;
2686 			reg->precise = true;
2687 		}
2688 		if (env->log.level & BPF_LOG_LEVEL) {
2689 			print_verifier_state(env, func);
2690 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2691 				new_marks ? "didn't have" : "already had",
2692 				reg_mask, stack_mask);
2693 		}
2694 
2695 		if (!reg_mask && !stack_mask)
2696 			break;
2697 		if (!new_marks)
2698 			break;
2699 
2700 		last_idx = st->last_insn_idx;
2701 		first_idx = st->first_insn_idx;
2702 	}
2703 	return 0;
2704 }
2705 
2706 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2707 {
2708 	return __mark_chain_precision(env, regno, -1);
2709 }
2710 
2711 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2712 {
2713 	return __mark_chain_precision(env, -1, spi);
2714 }
2715 
2716 static bool is_spillable_regtype(enum bpf_reg_type type)
2717 {
2718 	switch (type) {
2719 	case PTR_TO_MAP_VALUE:
2720 	case PTR_TO_MAP_VALUE_OR_NULL:
2721 	case PTR_TO_STACK:
2722 	case PTR_TO_CTX:
2723 	case PTR_TO_PACKET:
2724 	case PTR_TO_PACKET_META:
2725 	case PTR_TO_PACKET_END:
2726 	case PTR_TO_FLOW_KEYS:
2727 	case CONST_PTR_TO_MAP:
2728 	case PTR_TO_SOCKET:
2729 	case PTR_TO_SOCKET_OR_NULL:
2730 	case PTR_TO_SOCK_COMMON:
2731 	case PTR_TO_SOCK_COMMON_OR_NULL:
2732 	case PTR_TO_TCP_SOCK:
2733 	case PTR_TO_TCP_SOCK_OR_NULL:
2734 	case PTR_TO_XDP_SOCK:
2735 	case PTR_TO_BTF_ID:
2736 	case PTR_TO_BTF_ID_OR_NULL:
2737 	case PTR_TO_RDONLY_BUF:
2738 	case PTR_TO_RDONLY_BUF_OR_NULL:
2739 	case PTR_TO_RDWR_BUF:
2740 	case PTR_TO_RDWR_BUF_OR_NULL:
2741 	case PTR_TO_PERCPU_BTF_ID:
2742 	case PTR_TO_MEM:
2743 	case PTR_TO_MEM_OR_NULL:
2744 	case PTR_TO_FUNC:
2745 	case PTR_TO_MAP_KEY:
2746 		return true;
2747 	default:
2748 		return false;
2749 	}
2750 }
2751 
2752 /* Does this register contain a constant zero? */
2753 static bool register_is_null(struct bpf_reg_state *reg)
2754 {
2755 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2756 }
2757 
2758 static bool register_is_const(struct bpf_reg_state *reg)
2759 {
2760 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2761 }
2762 
2763 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2764 {
2765 	return tnum_is_unknown(reg->var_off) &&
2766 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2767 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2768 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2769 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2770 }
2771 
2772 static bool register_is_bounded(struct bpf_reg_state *reg)
2773 {
2774 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2775 }
2776 
2777 static bool __is_pointer_value(bool allow_ptr_leaks,
2778 			       const struct bpf_reg_state *reg)
2779 {
2780 	if (allow_ptr_leaks)
2781 		return false;
2782 
2783 	return reg->type != SCALAR_VALUE;
2784 }
2785 
2786 static void save_register_state(struct bpf_func_state *state,
2787 				int spi, struct bpf_reg_state *reg,
2788 				int size)
2789 {
2790 	int i;
2791 
2792 	state->stack[spi].spilled_ptr = *reg;
2793 	if (size == BPF_REG_SIZE)
2794 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2795 
2796 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2797 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2798 
2799 	/* size < 8 bytes spill */
2800 	for (; i; i--)
2801 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2802 }
2803 
2804 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2805  * stack boundary and alignment are checked in check_mem_access()
2806  */
2807 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2808 				       /* stack frame we're writing to */
2809 				       struct bpf_func_state *state,
2810 				       int off, int size, int value_regno,
2811 				       int insn_idx)
2812 {
2813 	struct bpf_func_state *cur; /* state of the current function */
2814 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2815 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2816 	struct bpf_reg_state *reg = NULL;
2817 
2818 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2819 	if (err)
2820 		return err;
2821 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2822 	 * so it's aligned access and [off, off + size) are within stack limits
2823 	 */
2824 	if (!env->allow_ptr_leaks &&
2825 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2826 	    size != BPF_REG_SIZE) {
2827 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2828 		return -EACCES;
2829 	}
2830 
2831 	cur = env->cur_state->frame[env->cur_state->curframe];
2832 	if (value_regno >= 0)
2833 		reg = &cur->regs[value_regno];
2834 	if (!env->bypass_spec_v4) {
2835 		bool sanitize = reg && is_spillable_regtype(reg->type);
2836 
2837 		for (i = 0; i < size; i++) {
2838 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2839 				sanitize = true;
2840 				break;
2841 			}
2842 		}
2843 
2844 		if (sanitize)
2845 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2846 	}
2847 
2848 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2849 	    !register_is_null(reg) && env->bpf_capable) {
2850 		if (dst_reg != BPF_REG_FP) {
2851 			/* The backtracking logic can only recognize explicit
2852 			 * stack slot address like [fp - 8]. Other spill of
2853 			 * scalar via different register has to be conservative.
2854 			 * Backtrack from here and mark all registers as precise
2855 			 * that contributed into 'reg' being a constant.
2856 			 */
2857 			err = mark_chain_precision(env, value_regno);
2858 			if (err)
2859 				return err;
2860 		}
2861 		save_register_state(state, spi, reg, size);
2862 	} else if (reg && is_spillable_regtype(reg->type)) {
2863 		/* register containing pointer is being spilled into stack */
2864 		if (size != BPF_REG_SIZE) {
2865 			verbose_linfo(env, insn_idx, "; ");
2866 			verbose(env, "invalid size of register spill\n");
2867 			return -EACCES;
2868 		}
2869 		if (state != cur && reg->type == PTR_TO_STACK) {
2870 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2871 			return -EINVAL;
2872 		}
2873 		save_register_state(state, spi, reg, size);
2874 	} else {
2875 		u8 type = STACK_MISC;
2876 
2877 		/* regular write of data into stack destroys any spilled ptr */
2878 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2879 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2880 		if (is_spilled_reg(&state->stack[spi]))
2881 			for (i = 0; i < BPF_REG_SIZE; i++)
2882 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2883 
2884 		/* only mark the slot as written if all 8 bytes were written
2885 		 * otherwise read propagation may incorrectly stop too soon
2886 		 * when stack slots are partially written.
2887 		 * This heuristic means that read propagation will be
2888 		 * conservative, since it will add reg_live_read marks
2889 		 * to stack slots all the way to first state when programs
2890 		 * writes+reads less than 8 bytes
2891 		 */
2892 		if (size == BPF_REG_SIZE)
2893 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2894 
2895 		/* when we zero initialize stack slots mark them as such */
2896 		if (reg && register_is_null(reg)) {
2897 			/* backtracking doesn't work for STACK_ZERO yet. */
2898 			err = mark_chain_precision(env, value_regno);
2899 			if (err)
2900 				return err;
2901 			type = STACK_ZERO;
2902 		}
2903 
2904 		/* Mark slots affected by this stack write. */
2905 		for (i = 0; i < size; i++)
2906 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2907 				type;
2908 	}
2909 	return 0;
2910 }
2911 
2912 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2913  * known to contain a variable offset.
2914  * This function checks whether the write is permitted and conservatively
2915  * tracks the effects of the write, considering that each stack slot in the
2916  * dynamic range is potentially written to.
2917  *
2918  * 'off' includes 'regno->off'.
2919  * 'value_regno' can be -1, meaning that an unknown value is being written to
2920  * the stack.
2921  *
2922  * Spilled pointers in range are not marked as written because we don't know
2923  * what's going to be actually written. This means that read propagation for
2924  * future reads cannot be terminated by this write.
2925  *
2926  * For privileged programs, uninitialized stack slots are considered
2927  * initialized by this write (even though we don't know exactly what offsets
2928  * are going to be written to). The idea is that we don't want the verifier to
2929  * reject future reads that access slots written to through variable offsets.
2930  */
2931 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2932 				     /* func where register points to */
2933 				     struct bpf_func_state *state,
2934 				     int ptr_regno, int off, int size,
2935 				     int value_regno, int insn_idx)
2936 {
2937 	struct bpf_func_state *cur; /* state of the current function */
2938 	int min_off, max_off;
2939 	int i, err;
2940 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2941 	bool writing_zero = false;
2942 	/* set if the fact that we're writing a zero is used to let any
2943 	 * stack slots remain STACK_ZERO
2944 	 */
2945 	bool zero_used = false;
2946 
2947 	cur = env->cur_state->frame[env->cur_state->curframe];
2948 	ptr_reg = &cur->regs[ptr_regno];
2949 	min_off = ptr_reg->smin_value + off;
2950 	max_off = ptr_reg->smax_value + off + size;
2951 	if (value_regno >= 0)
2952 		value_reg = &cur->regs[value_regno];
2953 	if (value_reg && register_is_null(value_reg))
2954 		writing_zero = true;
2955 
2956 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2957 	if (err)
2958 		return err;
2959 
2960 
2961 	/* Variable offset writes destroy any spilled pointers in range. */
2962 	for (i = min_off; i < max_off; i++) {
2963 		u8 new_type, *stype;
2964 		int slot, spi;
2965 
2966 		slot = -i - 1;
2967 		spi = slot / BPF_REG_SIZE;
2968 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2969 
2970 		if (!env->allow_ptr_leaks
2971 				&& *stype != NOT_INIT
2972 				&& *stype != SCALAR_VALUE) {
2973 			/* Reject the write if there's are spilled pointers in
2974 			 * range. If we didn't reject here, the ptr status
2975 			 * would be erased below (even though not all slots are
2976 			 * actually overwritten), possibly opening the door to
2977 			 * leaks.
2978 			 */
2979 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2980 				insn_idx, i);
2981 			return -EINVAL;
2982 		}
2983 
2984 		/* Erase all spilled pointers. */
2985 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2986 
2987 		/* Update the slot type. */
2988 		new_type = STACK_MISC;
2989 		if (writing_zero && *stype == STACK_ZERO) {
2990 			new_type = STACK_ZERO;
2991 			zero_used = true;
2992 		}
2993 		/* If the slot is STACK_INVALID, we check whether it's OK to
2994 		 * pretend that it will be initialized by this write. The slot
2995 		 * might not actually be written to, and so if we mark it as
2996 		 * initialized future reads might leak uninitialized memory.
2997 		 * For privileged programs, we will accept such reads to slots
2998 		 * that may or may not be written because, if we're reject
2999 		 * them, the error would be too confusing.
3000 		 */
3001 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3002 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3003 					insn_idx, i);
3004 			return -EINVAL;
3005 		}
3006 		*stype = new_type;
3007 	}
3008 	if (zero_used) {
3009 		/* backtracking doesn't work for STACK_ZERO yet. */
3010 		err = mark_chain_precision(env, value_regno);
3011 		if (err)
3012 			return err;
3013 	}
3014 	return 0;
3015 }
3016 
3017 /* When register 'dst_regno' is assigned some values from stack[min_off,
3018  * max_off), we set the register's type according to the types of the
3019  * respective stack slots. If all the stack values are known to be zeros, then
3020  * so is the destination reg. Otherwise, the register is considered to be
3021  * SCALAR. This function does not deal with register filling; the caller must
3022  * ensure that all spilled registers in the stack range have been marked as
3023  * read.
3024  */
3025 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3026 				/* func where src register points to */
3027 				struct bpf_func_state *ptr_state,
3028 				int min_off, int max_off, int dst_regno)
3029 {
3030 	struct bpf_verifier_state *vstate = env->cur_state;
3031 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3032 	int i, slot, spi;
3033 	u8 *stype;
3034 	int zeros = 0;
3035 
3036 	for (i = min_off; i < max_off; i++) {
3037 		slot = -i - 1;
3038 		spi = slot / BPF_REG_SIZE;
3039 		stype = ptr_state->stack[spi].slot_type;
3040 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3041 			break;
3042 		zeros++;
3043 	}
3044 	if (zeros == max_off - min_off) {
3045 		/* any access_size read into register is zero extended,
3046 		 * so the whole register == const_zero
3047 		 */
3048 		__mark_reg_const_zero(&state->regs[dst_regno]);
3049 		/* backtracking doesn't support STACK_ZERO yet,
3050 		 * so mark it precise here, so that later
3051 		 * backtracking can stop here.
3052 		 * Backtracking may not need this if this register
3053 		 * doesn't participate in pointer adjustment.
3054 		 * Forward propagation of precise flag is not
3055 		 * necessary either. This mark is only to stop
3056 		 * backtracking. Any register that contributed
3057 		 * to const 0 was marked precise before spill.
3058 		 */
3059 		state->regs[dst_regno].precise = true;
3060 	} else {
3061 		/* have read misc data from the stack */
3062 		mark_reg_unknown(env, state->regs, dst_regno);
3063 	}
3064 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3065 }
3066 
3067 /* Read the stack at 'off' and put the results into the register indicated by
3068  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3069  * spilled reg.
3070  *
3071  * 'dst_regno' can be -1, meaning that the read value is not going to a
3072  * register.
3073  *
3074  * The access is assumed to be within the current stack bounds.
3075  */
3076 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3077 				      /* func where src register points to */
3078 				      struct bpf_func_state *reg_state,
3079 				      int off, int size, int dst_regno)
3080 {
3081 	struct bpf_verifier_state *vstate = env->cur_state;
3082 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3083 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3084 	struct bpf_reg_state *reg;
3085 	u8 *stype, type;
3086 
3087 	stype = reg_state->stack[spi].slot_type;
3088 	reg = &reg_state->stack[spi].spilled_ptr;
3089 
3090 	if (is_spilled_reg(&reg_state->stack[spi])) {
3091 		if (size != BPF_REG_SIZE) {
3092 			u8 scalar_size = 0;
3093 
3094 			if (reg->type != SCALAR_VALUE) {
3095 				verbose_linfo(env, env->insn_idx, "; ");
3096 				verbose(env, "invalid size of register fill\n");
3097 				return -EACCES;
3098 			}
3099 
3100 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3101 			if (dst_regno < 0)
3102 				return 0;
3103 
3104 			for (i = BPF_REG_SIZE; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3105 				scalar_size++;
3106 
3107 			if (!(off % BPF_REG_SIZE) && size == scalar_size) {
3108 				/* The earlier check_reg_arg() has decided the
3109 				 * subreg_def for this insn.  Save it first.
3110 				 */
3111 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3112 
3113 				state->regs[dst_regno] = *reg;
3114 				state->regs[dst_regno].subreg_def = subreg_def;
3115 			} else {
3116 				for (i = 0; i < size; i++) {
3117 					type = stype[(slot - i) % BPF_REG_SIZE];
3118 					if (type == STACK_SPILL)
3119 						continue;
3120 					if (type == STACK_MISC)
3121 						continue;
3122 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3123 						off, i, size);
3124 					return -EACCES;
3125 				}
3126 				mark_reg_unknown(env, state->regs, dst_regno);
3127 			}
3128 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3129 			return 0;
3130 		}
3131 		for (i = 1; i < BPF_REG_SIZE; i++) {
3132 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
3133 				verbose(env, "corrupted spill memory\n");
3134 				return -EACCES;
3135 			}
3136 		}
3137 
3138 		if (dst_regno >= 0) {
3139 			/* restore register state from stack */
3140 			state->regs[dst_regno] = *reg;
3141 			/* mark reg as written since spilled pointer state likely
3142 			 * has its liveness marks cleared by is_state_visited()
3143 			 * which resets stack/reg liveness for state transitions
3144 			 */
3145 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3146 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3147 			/* If dst_regno==-1, the caller is asking us whether
3148 			 * it is acceptable to use this value as a SCALAR_VALUE
3149 			 * (e.g. for XADD).
3150 			 * We must not allow unprivileged callers to do that
3151 			 * with spilled pointers.
3152 			 */
3153 			verbose(env, "leaking pointer from stack off %d\n",
3154 				off);
3155 			return -EACCES;
3156 		}
3157 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3158 	} else {
3159 		for (i = 0; i < size; i++) {
3160 			type = stype[(slot - i) % BPF_REG_SIZE];
3161 			if (type == STACK_MISC)
3162 				continue;
3163 			if (type == STACK_ZERO)
3164 				continue;
3165 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3166 				off, i, size);
3167 			return -EACCES;
3168 		}
3169 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3170 		if (dst_regno >= 0)
3171 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3172 	}
3173 	return 0;
3174 }
3175 
3176 enum stack_access_src {
3177 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3178 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3179 };
3180 
3181 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3182 					 int regno, int off, int access_size,
3183 					 bool zero_size_allowed,
3184 					 enum stack_access_src type,
3185 					 struct bpf_call_arg_meta *meta);
3186 
3187 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3188 {
3189 	return cur_regs(env) + regno;
3190 }
3191 
3192 /* Read the stack at 'ptr_regno + off' and put the result into the register
3193  * 'dst_regno'.
3194  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3195  * but not its variable offset.
3196  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3197  *
3198  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3199  * filling registers (i.e. reads of spilled register cannot be detected when
3200  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3201  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3202  * offset; for a fixed offset check_stack_read_fixed_off should be used
3203  * instead.
3204  */
3205 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3206 				    int ptr_regno, int off, int size, int dst_regno)
3207 {
3208 	/* The state of the source register. */
3209 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3210 	struct bpf_func_state *ptr_state = func(env, reg);
3211 	int err;
3212 	int min_off, max_off;
3213 
3214 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3215 	 */
3216 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3217 					    false, ACCESS_DIRECT, NULL);
3218 	if (err)
3219 		return err;
3220 
3221 	min_off = reg->smin_value + off;
3222 	max_off = reg->smax_value + off;
3223 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3224 	return 0;
3225 }
3226 
3227 /* check_stack_read dispatches to check_stack_read_fixed_off or
3228  * check_stack_read_var_off.
3229  *
3230  * The caller must ensure that the offset falls within the allocated stack
3231  * bounds.
3232  *
3233  * 'dst_regno' is a register which will receive the value from the stack. It
3234  * can be -1, meaning that the read value is not going to a register.
3235  */
3236 static int check_stack_read(struct bpf_verifier_env *env,
3237 			    int ptr_regno, int off, int size,
3238 			    int dst_regno)
3239 {
3240 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3241 	struct bpf_func_state *state = func(env, reg);
3242 	int err;
3243 	/* Some accesses are only permitted with a static offset. */
3244 	bool var_off = !tnum_is_const(reg->var_off);
3245 
3246 	/* The offset is required to be static when reads don't go to a
3247 	 * register, in order to not leak pointers (see
3248 	 * check_stack_read_fixed_off).
3249 	 */
3250 	if (dst_regno < 0 && var_off) {
3251 		char tn_buf[48];
3252 
3253 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3254 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3255 			tn_buf, off, size);
3256 		return -EACCES;
3257 	}
3258 	/* Variable offset is prohibited for unprivileged mode for simplicity
3259 	 * since it requires corresponding support in Spectre masking for stack
3260 	 * ALU. See also retrieve_ptr_limit().
3261 	 */
3262 	if (!env->bypass_spec_v1 && var_off) {
3263 		char tn_buf[48];
3264 
3265 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3266 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3267 				ptr_regno, tn_buf);
3268 		return -EACCES;
3269 	}
3270 
3271 	if (!var_off) {
3272 		off += reg->var_off.value;
3273 		err = check_stack_read_fixed_off(env, state, off, size,
3274 						 dst_regno);
3275 	} else {
3276 		/* Variable offset stack reads need more conservative handling
3277 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3278 		 * branch.
3279 		 */
3280 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3281 					       dst_regno);
3282 	}
3283 	return err;
3284 }
3285 
3286 
3287 /* check_stack_write dispatches to check_stack_write_fixed_off or
3288  * check_stack_write_var_off.
3289  *
3290  * 'ptr_regno' is the register used as a pointer into the stack.
3291  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3292  * 'value_regno' is the register whose value we're writing to the stack. It can
3293  * be -1, meaning that we're not writing from a register.
3294  *
3295  * The caller must ensure that the offset falls within the maximum stack size.
3296  */
3297 static int check_stack_write(struct bpf_verifier_env *env,
3298 			     int ptr_regno, int off, int size,
3299 			     int value_regno, int insn_idx)
3300 {
3301 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3302 	struct bpf_func_state *state = func(env, reg);
3303 	int err;
3304 
3305 	if (tnum_is_const(reg->var_off)) {
3306 		off += reg->var_off.value;
3307 		err = check_stack_write_fixed_off(env, state, off, size,
3308 						  value_regno, insn_idx);
3309 	} else {
3310 		/* Variable offset stack reads need more conservative handling
3311 		 * than fixed offset ones.
3312 		 */
3313 		err = check_stack_write_var_off(env, state,
3314 						ptr_regno, off, size,
3315 						value_regno, insn_idx);
3316 	}
3317 	return err;
3318 }
3319 
3320 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3321 				 int off, int size, enum bpf_access_type type)
3322 {
3323 	struct bpf_reg_state *regs = cur_regs(env);
3324 	struct bpf_map *map = regs[regno].map_ptr;
3325 	u32 cap = bpf_map_flags_to_cap(map);
3326 
3327 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3328 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3329 			map->value_size, off, size);
3330 		return -EACCES;
3331 	}
3332 
3333 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3334 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3335 			map->value_size, off, size);
3336 		return -EACCES;
3337 	}
3338 
3339 	return 0;
3340 }
3341 
3342 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3343 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3344 			      int off, int size, u32 mem_size,
3345 			      bool zero_size_allowed)
3346 {
3347 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3348 	struct bpf_reg_state *reg;
3349 
3350 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3351 		return 0;
3352 
3353 	reg = &cur_regs(env)[regno];
3354 	switch (reg->type) {
3355 	case PTR_TO_MAP_KEY:
3356 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3357 			mem_size, off, size);
3358 		break;
3359 	case PTR_TO_MAP_VALUE:
3360 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3361 			mem_size, off, size);
3362 		break;
3363 	case PTR_TO_PACKET:
3364 	case PTR_TO_PACKET_META:
3365 	case PTR_TO_PACKET_END:
3366 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3367 			off, size, regno, reg->id, off, mem_size);
3368 		break;
3369 	case PTR_TO_MEM:
3370 	default:
3371 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3372 			mem_size, off, size);
3373 	}
3374 
3375 	return -EACCES;
3376 }
3377 
3378 /* check read/write into a memory region with possible variable offset */
3379 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3380 				   int off, int size, u32 mem_size,
3381 				   bool zero_size_allowed)
3382 {
3383 	struct bpf_verifier_state *vstate = env->cur_state;
3384 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3385 	struct bpf_reg_state *reg = &state->regs[regno];
3386 	int err;
3387 
3388 	/* We may have adjusted the register pointing to memory region, so we
3389 	 * need to try adding each of min_value and max_value to off
3390 	 * to make sure our theoretical access will be safe.
3391 	 */
3392 	if (env->log.level & BPF_LOG_LEVEL)
3393 		print_verifier_state(env, state);
3394 
3395 	/* The minimum value is only important with signed
3396 	 * comparisons where we can't assume the floor of a
3397 	 * value is 0.  If we are using signed variables for our
3398 	 * index'es we need to make sure that whatever we use
3399 	 * will have a set floor within our range.
3400 	 */
3401 	if (reg->smin_value < 0 &&
3402 	    (reg->smin_value == S64_MIN ||
3403 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3404 	      reg->smin_value + off < 0)) {
3405 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3406 			regno);
3407 		return -EACCES;
3408 	}
3409 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3410 				 mem_size, zero_size_allowed);
3411 	if (err) {
3412 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3413 			regno);
3414 		return err;
3415 	}
3416 
3417 	/* If we haven't set a max value then we need to bail since we can't be
3418 	 * sure we won't do bad things.
3419 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3420 	 */
3421 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3422 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3423 			regno);
3424 		return -EACCES;
3425 	}
3426 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3427 				 mem_size, zero_size_allowed);
3428 	if (err) {
3429 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3430 			regno);
3431 		return err;
3432 	}
3433 
3434 	return 0;
3435 }
3436 
3437 /* check read/write into a map element with possible variable offset */
3438 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3439 			    int off, int size, bool zero_size_allowed)
3440 {
3441 	struct bpf_verifier_state *vstate = env->cur_state;
3442 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3443 	struct bpf_reg_state *reg = &state->regs[regno];
3444 	struct bpf_map *map = reg->map_ptr;
3445 	int err;
3446 
3447 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3448 				      zero_size_allowed);
3449 	if (err)
3450 		return err;
3451 
3452 	if (map_value_has_spin_lock(map)) {
3453 		u32 lock = map->spin_lock_off;
3454 
3455 		/* if any part of struct bpf_spin_lock can be touched by
3456 		 * load/store reject this program.
3457 		 * To check that [x1, x2) overlaps with [y1, y2)
3458 		 * it is sufficient to check x1 < y2 && y1 < x2.
3459 		 */
3460 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3461 		     lock < reg->umax_value + off + size) {
3462 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3463 			return -EACCES;
3464 		}
3465 	}
3466 	if (map_value_has_timer(map)) {
3467 		u32 t = map->timer_off;
3468 
3469 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3470 		     t < reg->umax_value + off + size) {
3471 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3472 			return -EACCES;
3473 		}
3474 	}
3475 	return err;
3476 }
3477 
3478 #define MAX_PACKET_OFF 0xffff
3479 
3480 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3481 {
3482 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3483 }
3484 
3485 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3486 				       const struct bpf_call_arg_meta *meta,
3487 				       enum bpf_access_type t)
3488 {
3489 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3490 
3491 	switch (prog_type) {
3492 	/* Program types only with direct read access go here! */
3493 	case BPF_PROG_TYPE_LWT_IN:
3494 	case BPF_PROG_TYPE_LWT_OUT:
3495 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3496 	case BPF_PROG_TYPE_SK_REUSEPORT:
3497 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3498 	case BPF_PROG_TYPE_CGROUP_SKB:
3499 		if (t == BPF_WRITE)
3500 			return false;
3501 		fallthrough;
3502 
3503 	/* Program types with direct read + write access go here! */
3504 	case BPF_PROG_TYPE_SCHED_CLS:
3505 	case BPF_PROG_TYPE_SCHED_ACT:
3506 	case BPF_PROG_TYPE_XDP:
3507 	case BPF_PROG_TYPE_LWT_XMIT:
3508 	case BPF_PROG_TYPE_SK_SKB:
3509 	case BPF_PROG_TYPE_SK_MSG:
3510 		if (meta)
3511 			return meta->pkt_access;
3512 
3513 		env->seen_direct_write = true;
3514 		return true;
3515 
3516 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3517 		if (t == BPF_WRITE)
3518 			env->seen_direct_write = true;
3519 
3520 		return true;
3521 
3522 	default:
3523 		return false;
3524 	}
3525 }
3526 
3527 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3528 			       int size, bool zero_size_allowed)
3529 {
3530 	struct bpf_reg_state *regs = cur_regs(env);
3531 	struct bpf_reg_state *reg = &regs[regno];
3532 	int err;
3533 
3534 	/* We may have added a variable offset to the packet pointer; but any
3535 	 * reg->range we have comes after that.  We are only checking the fixed
3536 	 * offset.
3537 	 */
3538 
3539 	/* We don't allow negative numbers, because we aren't tracking enough
3540 	 * detail to prove they're safe.
3541 	 */
3542 	if (reg->smin_value < 0) {
3543 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3544 			regno);
3545 		return -EACCES;
3546 	}
3547 
3548 	err = reg->range < 0 ? -EINVAL :
3549 	      __check_mem_access(env, regno, off, size, reg->range,
3550 				 zero_size_allowed);
3551 	if (err) {
3552 		verbose(env, "R%d offset is outside of the packet\n", regno);
3553 		return err;
3554 	}
3555 
3556 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3557 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3558 	 * otherwise find_good_pkt_pointers would have refused to set range info
3559 	 * that __check_mem_access would have rejected this pkt access.
3560 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3561 	 */
3562 	env->prog->aux->max_pkt_offset =
3563 		max_t(u32, env->prog->aux->max_pkt_offset,
3564 		      off + reg->umax_value + size - 1);
3565 
3566 	return err;
3567 }
3568 
3569 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3570 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3571 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3572 			    struct btf **btf, u32 *btf_id)
3573 {
3574 	struct bpf_insn_access_aux info = {
3575 		.reg_type = *reg_type,
3576 		.log = &env->log,
3577 	};
3578 
3579 	if (env->ops->is_valid_access &&
3580 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3581 		/* A non zero info.ctx_field_size indicates that this field is a
3582 		 * candidate for later verifier transformation to load the whole
3583 		 * field and then apply a mask when accessed with a narrower
3584 		 * access than actual ctx access size. A zero info.ctx_field_size
3585 		 * will only allow for whole field access and rejects any other
3586 		 * type of narrower access.
3587 		 */
3588 		*reg_type = info.reg_type;
3589 
3590 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3591 			*btf = info.btf;
3592 			*btf_id = info.btf_id;
3593 		} else {
3594 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3595 		}
3596 		/* remember the offset of last byte accessed in ctx */
3597 		if (env->prog->aux->max_ctx_offset < off + size)
3598 			env->prog->aux->max_ctx_offset = off + size;
3599 		return 0;
3600 	}
3601 
3602 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3603 	return -EACCES;
3604 }
3605 
3606 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3607 				  int size)
3608 {
3609 	if (size < 0 || off < 0 ||
3610 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3611 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3612 			off, size);
3613 		return -EACCES;
3614 	}
3615 	return 0;
3616 }
3617 
3618 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3619 			     u32 regno, int off, int size,
3620 			     enum bpf_access_type t)
3621 {
3622 	struct bpf_reg_state *regs = cur_regs(env);
3623 	struct bpf_reg_state *reg = &regs[regno];
3624 	struct bpf_insn_access_aux info = {};
3625 	bool valid;
3626 
3627 	if (reg->smin_value < 0) {
3628 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3629 			regno);
3630 		return -EACCES;
3631 	}
3632 
3633 	switch (reg->type) {
3634 	case PTR_TO_SOCK_COMMON:
3635 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3636 		break;
3637 	case PTR_TO_SOCKET:
3638 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3639 		break;
3640 	case PTR_TO_TCP_SOCK:
3641 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3642 		break;
3643 	case PTR_TO_XDP_SOCK:
3644 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3645 		break;
3646 	default:
3647 		valid = false;
3648 	}
3649 
3650 
3651 	if (valid) {
3652 		env->insn_aux_data[insn_idx].ctx_field_size =
3653 			info.ctx_field_size;
3654 		return 0;
3655 	}
3656 
3657 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3658 		regno, reg_type_str[reg->type], off, size);
3659 
3660 	return -EACCES;
3661 }
3662 
3663 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3664 {
3665 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3666 }
3667 
3668 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3669 {
3670 	const struct bpf_reg_state *reg = reg_state(env, regno);
3671 
3672 	return reg->type == PTR_TO_CTX;
3673 }
3674 
3675 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3676 {
3677 	const struct bpf_reg_state *reg = reg_state(env, regno);
3678 
3679 	return type_is_sk_pointer(reg->type);
3680 }
3681 
3682 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3683 {
3684 	const struct bpf_reg_state *reg = reg_state(env, regno);
3685 
3686 	return type_is_pkt_pointer(reg->type);
3687 }
3688 
3689 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3690 {
3691 	const struct bpf_reg_state *reg = reg_state(env, regno);
3692 
3693 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3694 	return reg->type == PTR_TO_FLOW_KEYS;
3695 }
3696 
3697 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3698 				   const struct bpf_reg_state *reg,
3699 				   int off, int size, bool strict)
3700 {
3701 	struct tnum reg_off;
3702 	int ip_align;
3703 
3704 	/* Byte size accesses are always allowed. */
3705 	if (!strict || size == 1)
3706 		return 0;
3707 
3708 	/* For platforms that do not have a Kconfig enabling
3709 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3710 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3711 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3712 	 * to this code only in strict mode where we want to emulate
3713 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3714 	 * unconditional IP align value of '2'.
3715 	 */
3716 	ip_align = 2;
3717 
3718 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3719 	if (!tnum_is_aligned(reg_off, size)) {
3720 		char tn_buf[48];
3721 
3722 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3723 		verbose(env,
3724 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3725 			ip_align, tn_buf, reg->off, off, size);
3726 		return -EACCES;
3727 	}
3728 
3729 	return 0;
3730 }
3731 
3732 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3733 				       const struct bpf_reg_state *reg,
3734 				       const char *pointer_desc,
3735 				       int off, int size, bool strict)
3736 {
3737 	struct tnum reg_off;
3738 
3739 	/* Byte size accesses are always allowed. */
3740 	if (!strict || size == 1)
3741 		return 0;
3742 
3743 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3744 	if (!tnum_is_aligned(reg_off, size)) {
3745 		char tn_buf[48];
3746 
3747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3748 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3749 			pointer_desc, tn_buf, reg->off, off, size);
3750 		return -EACCES;
3751 	}
3752 
3753 	return 0;
3754 }
3755 
3756 static int check_ptr_alignment(struct bpf_verifier_env *env,
3757 			       const struct bpf_reg_state *reg, int off,
3758 			       int size, bool strict_alignment_once)
3759 {
3760 	bool strict = env->strict_alignment || strict_alignment_once;
3761 	const char *pointer_desc = "";
3762 
3763 	switch (reg->type) {
3764 	case PTR_TO_PACKET:
3765 	case PTR_TO_PACKET_META:
3766 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3767 		 * right in front, treat it the very same way.
3768 		 */
3769 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3770 	case PTR_TO_FLOW_KEYS:
3771 		pointer_desc = "flow keys ";
3772 		break;
3773 	case PTR_TO_MAP_KEY:
3774 		pointer_desc = "key ";
3775 		break;
3776 	case PTR_TO_MAP_VALUE:
3777 		pointer_desc = "value ";
3778 		break;
3779 	case PTR_TO_CTX:
3780 		pointer_desc = "context ";
3781 		break;
3782 	case PTR_TO_STACK:
3783 		pointer_desc = "stack ";
3784 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3785 		 * and check_stack_read_fixed_off() relies on stack accesses being
3786 		 * aligned.
3787 		 */
3788 		strict = true;
3789 		break;
3790 	case PTR_TO_SOCKET:
3791 		pointer_desc = "sock ";
3792 		break;
3793 	case PTR_TO_SOCK_COMMON:
3794 		pointer_desc = "sock_common ";
3795 		break;
3796 	case PTR_TO_TCP_SOCK:
3797 		pointer_desc = "tcp_sock ";
3798 		break;
3799 	case PTR_TO_XDP_SOCK:
3800 		pointer_desc = "xdp_sock ";
3801 		break;
3802 	default:
3803 		break;
3804 	}
3805 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3806 					   strict);
3807 }
3808 
3809 static int update_stack_depth(struct bpf_verifier_env *env,
3810 			      const struct bpf_func_state *func,
3811 			      int off)
3812 {
3813 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3814 
3815 	if (stack >= -off)
3816 		return 0;
3817 
3818 	/* update known max for given subprogram */
3819 	env->subprog_info[func->subprogno].stack_depth = -off;
3820 	return 0;
3821 }
3822 
3823 /* starting from main bpf function walk all instructions of the function
3824  * and recursively walk all callees that given function can call.
3825  * Ignore jump and exit insns.
3826  * Since recursion is prevented by check_cfg() this algorithm
3827  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3828  */
3829 static int check_max_stack_depth(struct bpf_verifier_env *env)
3830 {
3831 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3832 	struct bpf_subprog_info *subprog = env->subprog_info;
3833 	struct bpf_insn *insn = env->prog->insnsi;
3834 	bool tail_call_reachable = false;
3835 	int ret_insn[MAX_CALL_FRAMES];
3836 	int ret_prog[MAX_CALL_FRAMES];
3837 	int j;
3838 
3839 process_func:
3840 	/* protect against potential stack overflow that might happen when
3841 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3842 	 * depth for such case down to 256 so that the worst case scenario
3843 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3844 	 * 8k).
3845 	 *
3846 	 * To get the idea what might happen, see an example:
3847 	 * func1 -> sub rsp, 128
3848 	 *  subfunc1 -> sub rsp, 256
3849 	 *  tailcall1 -> add rsp, 256
3850 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3851 	 *   subfunc2 -> sub rsp, 64
3852 	 *   subfunc22 -> sub rsp, 128
3853 	 *   tailcall2 -> add rsp, 128
3854 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3855 	 *
3856 	 * tailcall will unwind the current stack frame but it will not get rid
3857 	 * of caller's stack as shown on the example above.
3858 	 */
3859 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3860 		verbose(env,
3861 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3862 			depth);
3863 		return -EACCES;
3864 	}
3865 	/* round up to 32-bytes, since this is granularity
3866 	 * of interpreter stack size
3867 	 */
3868 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3869 	if (depth > MAX_BPF_STACK) {
3870 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3871 			frame + 1, depth);
3872 		return -EACCES;
3873 	}
3874 continue_func:
3875 	subprog_end = subprog[idx + 1].start;
3876 	for (; i < subprog_end; i++) {
3877 		int next_insn;
3878 
3879 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3880 			continue;
3881 		/* remember insn and function to return to */
3882 		ret_insn[frame] = i + 1;
3883 		ret_prog[frame] = idx;
3884 
3885 		/* find the callee */
3886 		next_insn = i + insn[i].imm + 1;
3887 		idx = find_subprog(env, next_insn);
3888 		if (idx < 0) {
3889 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3890 				  next_insn);
3891 			return -EFAULT;
3892 		}
3893 		if (subprog[idx].is_async_cb) {
3894 			if (subprog[idx].has_tail_call) {
3895 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3896 				return -EFAULT;
3897 			}
3898 			 /* async callbacks don't increase bpf prog stack size */
3899 			continue;
3900 		}
3901 		i = next_insn;
3902 
3903 		if (subprog[idx].has_tail_call)
3904 			tail_call_reachable = true;
3905 
3906 		frame++;
3907 		if (frame >= MAX_CALL_FRAMES) {
3908 			verbose(env, "the call stack of %d frames is too deep !\n",
3909 				frame);
3910 			return -E2BIG;
3911 		}
3912 		goto process_func;
3913 	}
3914 	/* if tail call got detected across bpf2bpf calls then mark each of the
3915 	 * currently present subprog frames as tail call reachable subprogs;
3916 	 * this info will be utilized by JIT so that we will be preserving the
3917 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3918 	 */
3919 	if (tail_call_reachable)
3920 		for (j = 0; j < frame; j++)
3921 			subprog[ret_prog[j]].tail_call_reachable = true;
3922 	if (subprog[0].tail_call_reachable)
3923 		env->prog->aux->tail_call_reachable = true;
3924 
3925 	/* end of for() loop means the last insn of the 'subprog'
3926 	 * was reached. Doesn't matter whether it was JA or EXIT
3927 	 */
3928 	if (frame == 0)
3929 		return 0;
3930 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3931 	frame--;
3932 	i = ret_insn[frame];
3933 	idx = ret_prog[frame];
3934 	goto continue_func;
3935 }
3936 
3937 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3938 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3939 				  const struct bpf_insn *insn, int idx)
3940 {
3941 	int start = idx + insn->imm + 1, subprog;
3942 
3943 	subprog = find_subprog(env, start);
3944 	if (subprog < 0) {
3945 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3946 			  start);
3947 		return -EFAULT;
3948 	}
3949 	return env->subprog_info[subprog].stack_depth;
3950 }
3951 #endif
3952 
3953 int check_ctx_reg(struct bpf_verifier_env *env,
3954 		  const struct bpf_reg_state *reg, int regno)
3955 {
3956 	/* Access to ctx or passing it to a helper is only allowed in
3957 	 * its original, unmodified form.
3958 	 */
3959 
3960 	if (reg->off) {
3961 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3962 			regno, reg->off);
3963 		return -EACCES;
3964 	}
3965 
3966 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3967 		char tn_buf[48];
3968 
3969 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3970 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3971 		return -EACCES;
3972 	}
3973 
3974 	return 0;
3975 }
3976 
3977 static int __check_buffer_access(struct bpf_verifier_env *env,
3978 				 const char *buf_info,
3979 				 const struct bpf_reg_state *reg,
3980 				 int regno, int off, int size)
3981 {
3982 	if (off < 0) {
3983 		verbose(env,
3984 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3985 			regno, buf_info, off, size);
3986 		return -EACCES;
3987 	}
3988 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3989 		char tn_buf[48];
3990 
3991 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3992 		verbose(env,
3993 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3994 			regno, off, tn_buf);
3995 		return -EACCES;
3996 	}
3997 
3998 	return 0;
3999 }
4000 
4001 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4002 				  const struct bpf_reg_state *reg,
4003 				  int regno, int off, int size)
4004 {
4005 	int err;
4006 
4007 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4008 	if (err)
4009 		return err;
4010 
4011 	if (off + size > env->prog->aux->max_tp_access)
4012 		env->prog->aux->max_tp_access = off + size;
4013 
4014 	return 0;
4015 }
4016 
4017 static int check_buffer_access(struct bpf_verifier_env *env,
4018 			       const struct bpf_reg_state *reg,
4019 			       int regno, int off, int size,
4020 			       bool zero_size_allowed,
4021 			       const char *buf_info,
4022 			       u32 *max_access)
4023 {
4024 	int err;
4025 
4026 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4027 	if (err)
4028 		return err;
4029 
4030 	if (off + size > *max_access)
4031 		*max_access = off + size;
4032 
4033 	return 0;
4034 }
4035 
4036 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4037 static void zext_32_to_64(struct bpf_reg_state *reg)
4038 {
4039 	reg->var_off = tnum_subreg(reg->var_off);
4040 	__reg_assign_32_into_64(reg);
4041 }
4042 
4043 /* truncate register to smaller size (in bytes)
4044  * must be called with size < BPF_REG_SIZE
4045  */
4046 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4047 {
4048 	u64 mask;
4049 
4050 	/* clear high bits in bit representation */
4051 	reg->var_off = tnum_cast(reg->var_off, size);
4052 
4053 	/* fix arithmetic bounds */
4054 	mask = ((u64)1 << (size * 8)) - 1;
4055 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4056 		reg->umin_value &= mask;
4057 		reg->umax_value &= mask;
4058 	} else {
4059 		reg->umin_value = 0;
4060 		reg->umax_value = mask;
4061 	}
4062 	reg->smin_value = reg->umin_value;
4063 	reg->smax_value = reg->umax_value;
4064 
4065 	/* If size is smaller than 32bit register the 32bit register
4066 	 * values are also truncated so we push 64-bit bounds into
4067 	 * 32-bit bounds. Above were truncated < 32-bits already.
4068 	 */
4069 	if (size >= 4)
4070 		return;
4071 	__reg_combine_64_into_32(reg);
4072 }
4073 
4074 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4075 {
4076 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
4077 }
4078 
4079 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4080 {
4081 	void *ptr;
4082 	u64 addr;
4083 	int err;
4084 
4085 	err = map->ops->map_direct_value_addr(map, &addr, off);
4086 	if (err)
4087 		return err;
4088 	ptr = (void *)(long)addr + off;
4089 
4090 	switch (size) {
4091 	case sizeof(u8):
4092 		*val = (u64)*(u8 *)ptr;
4093 		break;
4094 	case sizeof(u16):
4095 		*val = (u64)*(u16 *)ptr;
4096 		break;
4097 	case sizeof(u32):
4098 		*val = (u64)*(u32 *)ptr;
4099 		break;
4100 	case sizeof(u64):
4101 		*val = *(u64 *)ptr;
4102 		break;
4103 	default:
4104 		return -EINVAL;
4105 	}
4106 	return 0;
4107 }
4108 
4109 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4110 				   struct bpf_reg_state *regs,
4111 				   int regno, int off, int size,
4112 				   enum bpf_access_type atype,
4113 				   int value_regno)
4114 {
4115 	struct bpf_reg_state *reg = regs + regno;
4116 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4117 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4118 	u32 btf_id;
4119 	int ret;
4120 
4121 	if (off < 0) {
4122 		verbose(env,
4123 			"R%d is ptr_%s invalid negative access: off=%d\n",
4124 			regno, tname, off);
4125 		return -EACCES;
4126 	}
4127 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4128 		char tn_buf[48];
4129 
4130 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4131 		verbose(env,
4132 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4133 			regno, tname, off, tn_buf);
4134 		return -EACCES;
4135 	}
4136 
4137 	if (env->ops->btf_struct_access) {
4138 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4139 						  off, size, atype, &btf_id);
4140 	} else {
4141 		if (atype != BPF_READ) {
4142 			verbose(env, "only read is supported\n");
4143 			return -EACCES;
4144 		}
4145 
4146 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4147 					atype, &btf_id);
4148 	}
4149 
4150 	if (ret < 0)
4151 		return ret;
4152 
4153 	if (atype == BPF_READ && value_regno >= 0)
4154 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4155 
4156 	return 0;
4157 }
4158 
4159 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4160 				   struct bpf_reg_state *regs,
4161 				   int regno, int off, int size,
4162 				   enum bpf_access_type atype,
4163 				   int value_regno)
4164 {
4165 	struct bpf_reg_state *reg = regs + regno;
4166 	struct bpf_map *map = reg->map_ptr;
4167 	const struct btf_type *t;
4168 	const char *tname;
4169 	u32 btf_id;
4170 	int ret;
4171 
4172 	if (!btf_vmlinux) {
4173 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4174 		return -ENOTSUPP;
4175 	}
4176 
4177 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4178 		verbose(env, "map_ptr access not supported for map type %d\n",
4179 			map->map_type);
4180 		return -ENOTSUPP;
4181 	}
4182 
4183 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4184 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4185 
4186 	if (!env->allow_ptr_to_map_access) {
4187 		verbose(env,
4188 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4189 			tname);
4190 		return -EPERM;
4191 	}
4192 
4193 	if (off < 0) {
4194 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4195 			regno, tname, off);
4196 		return -EACCES;
4197 	}
4198 
4199 	if (atype != BPF_READ) {
4200 		verbose(env, "only read from %s is supported\n", tname);
4201 		return -EACCES;
4202 	}
4203 
4204 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4205 	if (ret < 0)
4206 		return ret;
4207 
4208 	if (value_regno >= 0)
4209 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4210 
4211 	return 0;
4212 }
4213 
4214 /* Check that the stack access at the given offset is within bounds. The
4215  * maximum valid offset is -1.
4216  *
4217  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4218  * -state->allocated_stack for reads.
4219  */
4220 static int check_stack_slot_within_bounds(int off,
4221 					  struct bpf_func_state *state,
4222 					  enum bpf_access_type t)
4223 {
4224 	int min_valid_off;
4225 
4226 	if (t == BPF_WRITE)
4227 		min_valid_off = -MAX_BPF_STACK;
4228 	else
4229 		min_valid_off = -state->allocated_stack;
4230 
4231 	if (off < min_valid_off || off > -1)
4232 		return -EACCES;
4233 	return 0;
4234 }
4235 
4236 /* Check that the stack access at 'regno + off' falls within the maximum stack
4237  * bounds.
4238  *
4239  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4240  */
4241 static int check_stack_access_within_bounds(
4242 		struct bpf_verifier_env *env,
4243 		int regno, int off, int access_size,
4244 		enum stack_access_src src, enum bpf_access_type type)
4245 {
4246 	struct bpf_reg_state *regs = cur_regs(env);
4247 	struct bpf_reg_state *reg = regs + regno;
4248 	struct bpf_func_state *state = func(env, reg);
4249 	int min_off, max_off;
4250 	int err;
4251 	char *err_extra;
4252 
4253 	if (src == ACCESS_HELPER)
4254 		/* We don't know if helpers are reading or writing (or both). */
4255 		err_extra = " indirect access to";
4256 	else if (type == BPF_READ)
4257 		err_extra = " read from";
4258 	else
4259 		err_extra = " write to";
4260 
4261 	if (tnum_is_const(reg->var_off)) {
4262 		min_off = reg->var_off.value + off;
4263 		if (access_size > 0)
4264 			max_off = min_off + access_size - 1;
4265 		else
4266 			max_off = min_off;
4267 	} else {
4268 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4269 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4270 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4271 				err_extra, regno);
4272 			return -EACCES;
4273 		}
4274 		min_off = reg->smin_value + off;
4275 		if (access_size > 0)
4276 			max_off = reg->smax_value + off + access_size - 1;
4277 		else
4278 			max_off = min_off;
4279 	}
4280 
4281 	err = check_stack_slot_within_bounds(min_off, state, type);
4282 	if (!err)
4283 		err = check_stack_slot_within_bounds(max_off, state, type);
4284 
4285 	if (err) {
4286 		if (tnum_is_const(reg->var_off)) {
4287 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4288 				err_extra, regno, off, access_size);
4289 		} else {
4290 			char tn_buf[48];
4291 
4292 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4293 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4294 				err_extra, regno, tn_buf, access_size);
4295 		}
4296 	}
4297 	return err;
4298 }
4299 
4300 /* check whether memory at (regno + off) is accessible for t = (read | write)
4301  * if t==write, value_regno is a register which value is stored into memory
4302  * if t==read, value_regno is a register which will receive the value from memory
4303  * if t==write && value_regno==-1, some unknown value is stored into memory
4304  * if t==read && value_regno==-1, don't care what we read from memory
4305  */
4306 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4307 			    int off, int bpf_size, enum bpf_access_type t,
4308 			    int value_regno, bool strict_alignment_once)
4309 {
4310 	struct bpf_reg_state *regs = cur_regs(env);
4311 	struct bpf_reg_state *reg = regs + regno;
4312 	struct bpf_func_state *state;
4313 	int size, err = 0;
4314 
4315 	size = bpf_size_to_bytes(bpf_size);
4316 	if (size < 0)
4317 		return size;
4318 
4319 	/* alignment checks will add in reg->off themselves */
4320 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4321 	if (err)
4322 		return err;
4323 
4324 	/* for access checks, reg->off is just part of off */
4325 	off += reg->off;
4326 
4327 	if (reg->type == PTR_TO_MAP_KEY) {
4328 		if (t == BPF_WRITE) {
4329 			verbose(env, "write to change key R%d not allowed\n", regno);
4330 			return -EACCES;
4331 		}
4332 
4333 		err = check_mem_region_access(env, regno, off, size,
4334 					      reg->map_ptr->key_size, false);
4335 		if (err)
4336 			return err;
4337 		if (value_regno >= 0)
4338 			mark_reg_unknown(env, regs, value_regno);
4339 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4340 		if (t == BPF_WRITE && value_regno >= 0 &&
4341 		    is_pointer_value(env, value_regno)) {
4342 			verbose(env, "R%d leaks addr into map\n", value_regno);
4343 			return -EACCES;
4344 		}
4345 		err = check_map_access_type(env, regno, off, size, t);
4346 		if (err)
4347 			return err;
4348 		err = check_map_access(env, regno, off, size, false);
4349 		if (!err && t == BPF_READ && value_regno >= 0) {
4350 			struct bpf_map *map = reg->map_ptr;
4351 
4352 			/* if map is read-only, track its contents as scalars */
4353 			if (tnum_is_const(reg->var_off) &&
4354 			    bpf_map_is_rdonly(map) &&
4355 			    map->ops->map_direct_value_addr) {
4356 				int map_off = off + reg->var_off.value;
4357 				u64 val = 0;
4358 
4359 				err = bpf_map_direct_read(map, map_off, size,
4360 							  &val);
4361 				if (err)
4362 					return err;
4363 
4364 				regs[value_regno].type = SCALAR_VALUE;
4365 				__mark_reg_known(&regs[value_regno], val);
4366 			} else {
4367 				mark_reg_unknown(env, regs, value_regno);
4368 			}
4369 		}
4370 	} else if (reg->type == PTR_TO_MEM) {
4371 		if (t == BPF_WRITE && value_regno >= 0 &&
4372 		    is_pointer_value(env, value_regno)) {
4373 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4374 			return -EACCES;
4375 		}
4376 		err = check_mem_region_access(env, regno, off, size,
4377 					      reg->mem_size, false);
4378 		if (!err && t == BPF_READ && value_regno >= 0)
4379 			mark_reg_unknown(env, regs, value_regno);
4380 	} else if (reg->type == PTR_TO_CTX) {
4381 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4382 		struct btf *btf = NULL;
4383 		u32 btf_id = 0;
4384 
4385 		if (t == BPF_WRITE && value_regno >= 0 &&
4386 		    is_pointer_value(env, value_regno)) {
4387 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4388 			return -EACCES;
4389 		}
4390 
4391 		err = check_ctx_reg(env, reg, regno);
4392 		if (err < 0)
4393 			return err;
4394 
4395 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4396 		if (err)
4397 			verbose_linfo(env, insn_idx, "; ");
4398 		if (!err && t == BPF_READ && value_regno >= 0) {
4399 			/* ctx access returns either a scalar, or a
4400 			 * PTR_TO_PACKET[_META,_END]. In the latter
4401 			 * case, we know the offset is zero.
4402 			 */
4403 			if (reg_type == SCALAR_VALUE) {
4404 				mark_reg_unknown(env, regs, value_regno);
4405 			} else {
4406 				mark_reg_known_zero(env, regs,
4407 						    value_regno);
4408 				if (reg_type_may_be_null(reg_type))
4409 					regs[value_regno].id = ++env->id_gen;
4410 				/* A load of ctx field could have different
4411 				 * actual load size with the one encoded in the
4412 				 * insn. When the dst is PTR, it is for sure not
4413 				 * a sub-register.
4414 				 */
4415 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4416 				if (reg_type == PTR_TO_BTF_ID ||
4417 				    reg_type == PTR_TO_BTF_ID_OR_NULL) {
4418 					regs[value_regno].btf = btf;
4419 					regs[value_regno].btf_id = btf_id;
4420 				}
4421 			}
4422 			regs[value_regno].type = reg_type;
4423 		}
4424 
4425 	} else if (reg->type == PTR_TO_STACK) {
4426 		/* Basic bounds checks. */
4427 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4428 		if (err)
4429 			return err;
4430 
4431 		state = func(env, reg);
4432 		err = update_stack_depth(env, state, off);
4433 		if (err)
4434 			return err;
4435 
4436 		if (t == BPF_READ)
4437 			err = check_stack_read(env, regno, off, size,
4438 					       value_regno);
4439 		else
4440 			err = check_stack_write(env, regno, off, size,
4441 						value_regno, insn_idx);
4442 	} else if (reg_is_pkt_pointer(reg)) {
4443 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4444 			verbose(env, "cannot write into packet\n");
4445 			return -EACCES;
4446 		}
4447 		if (t == BPF_WRITE && value_regno >= 0 &&
4448 		    is_pointer_value(env, value_regno)) {
4449 			verbose(env, "R%d leaks addr into packet\n",
4450 				value_regno);
4451 			return -EACCES;
4452 		}
4453 		err = check_packet_access(env, regno, off, size, false);
4454 		if (!err && t == BPF_READ && value_regno >= 0)
4455 			mark_reg_unknown(env, regs, value_regno);
4456 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4457 		if (t == BPF_WRITE && value_regno >= 0 &&
4458 		    is_pointer_value(env, value_regno)) {
4459 			verbose(env, "R%d leaks addr into flow keys\n",
4460 				value_regno);
4461 			return -EACCES;
4462 		}
4463 
4464 		err = check_flow_keys_access(env, off, size);
4465 		if (!err && t == BPF_READ && value_regno >= 0)
4466 			mark_reg_unknown(env, regs, value_regno);
4467 	} else if (type_is_sk_pointer(reg->type)) {
4468 		if (t == BPF_WRITE) {
4469 			verbose(env, "R%d cannot write into %s\n",
4470 				regno, reg_type_str[reg->type]);
4471 			return -EACCES;
4472 		}
4473 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4474 		if (!err && value_regno >= 0)
4475 			mark_reg_unknown(env, regs, value_regno);
4476 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4477 		err = check_tp_buffer_access(env, reg, regno, off, size);
4478 		if (!err && t == BPF_READ && value_regno >= 0)
4479 			mark_reg_unknown(env, regs, value_regno);
4480 	} else if (reg->type == PTR_TO_BTF_ID) {
4481 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4482 					      value_regno);
4483 	} else if (reg->type == CONST_PTR_TO_MAP) {
4484 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4485 					      value_regno);
4486 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
4487 		if (t == BPF_WRITE) {
4488 			verbose(env, "R%d cannot write into %s\n",
4489 				regno, reg_type_str[reg->type]);
4490 			return -EACCES;
4491 		}
4492 		err = check_buffer_access(env, reg, regno, off, size, false,
4493 					  "rdonly",
4494 					  &env->prog->aux->max_rdonly_access);
4495 		if (!err && value_regno >= 0)
4496 			mark_reg_unknown(env, regs, value_regno);
4497 	} else if (reg->type == PTR_TO_RDWR_BUF) {
4498 		err = check_buffer_access(env, reg, regno, off, size, false,
4499 					  "rdwr",
4500 					  &env->prog->aux->max_rdwr_access);
4501 		if (!err && t == BPF_READ && value_regno >= 0)
4502 			mark_reg_unknown(env, regs, value_regno);
4503 	} else {
4504 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4505 			reg_type_str[reg->type]);
4506 		return -EACCES;
4507 	}
4508 
4509 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4510 	    regs[value_regno].type == SCALAR_VALUE) {
4511 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4512 		coerce_reg_to_size(&regs[value_regno], size);
4513 	}
4514 	return err;
4515 }
4516 
4517 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4518 {
4519 	int load_reg;
4520 	int err;
4521 
4522 	switch (insn->imm) {
4523 	case BPF_ADD:
4524 	case BPF_ADD | BPF_FETCH:
4525 	case BPF_AND:
4526 	case BPF_AND | BPF_FETCH:
4527 	case BPF_OR:
4528 	case BPF_OR | BPF_FETCH:
4529 	case BPF_XOR:
4530 	case BPF_XOR | BPF_FETCH:
4531 	case BPF_XCHG:
4532 	case BPF_CMPXCHG:
4533 		break;
4534 	default:
4535 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4536 		return -EINVAL;
4537 	}
4538 
4539 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4540 		verbose(env, "invalid atomic operand size\n");
4541 		return -EINVAL;
4542 	}
4543 
4544 	/* check src1 operand */
4545 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4546 	if (err)
4547 		return err;
4548 
4549 	/* check src2 operand */
4550 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4551 	if (err)
4552 		return err;
4553 
4554 	if (insn->imm == BPF_CMPXCHG) {
4555 		/* Check comparison of R0 with memory location */
4556 		err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4557 		if (err)
4558 			return err;
4559 	}
4560 
4561 	if (is_pointer_value(env, insn->src_reg)) {
4562 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4563 		return -EACCES;
4564 	}
4565 
4566 	if (is_ctx_reg(env, insn->dst_reg) ||
4567 	    is_pkt_reg(env, insn->dst_reg) ||
4568 	    is_flow_key_reg(env, insn->dst_reg) ||
4569 	    is_sk_reg(env, insn->dst_reg)) {
4570 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4571 			insn->dst_reg,
4572 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
4573 		return -EACCES;
4574 	}
4575 
4576 	if (insn->imm & BPF_FETCH) {
4577 		if (insn->imm == BPF_CMPXCHG)
4578 			load_reg = BPF_REG_0;
4579 		else
4580 			load_reg = insn->src_reg;
4581 
4582 		/* check and record load of old value */
4583 		err = check_reg_arg(env, load_reg, DST_OP);
4584 		if (err)
4585 			return err;
4586 	} else {
4587 		/* This instruction accesses a memory location but doesn't
4588 		 * actually load it into a register.
4589 		 */
4590 		load_reg = -1;
4591 	}
4592 
4593 	/* check whether we can read the memory */
4594 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4595 			       BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4596 	if (err)
4597 		return err;
4598 
4599 	/* check whether we can write into the same memory */
4600 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4601 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4602 	if (err)
4603 		return err;
4604 
4605 	return 0;
4606 }
4607 
4608 /* When register 'regno' is used to read the stack (either directly or through
4609  * a helper function) make sure that it's within stack boundary and, depending
4610  * on the access type, that all elements of the stack are initialized.
4611  *
4612  * 'off' includes 'regno->off', but not its dynamic part (if any).
4613  *
4614  * All registers that have been spilled on the stack in the slots within the
4615  * read offsets are marked as read.
4616  */
4617 static int check_stack_range_initialized(
4618 		struct bpf_verifier_env *env, int regno, int off,
4619 		int access_size, bool zero_size_allowed,
4620 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4621 {
4622 	struct bpf_reg_state *reg = reg_state(env, regno);
4623 	struct bpf_func_state *state = func(env, reg);
4624 	int err, min_off, max_off, i, j, slot, spi;
4625 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4626 	enum bpf_access_type bounds_check_type;
4627 	/* Some accesses can write anything into the stack, others are
4628 	 * read-only.
4629 	 */
4630 	bool clobber = false;
4631 
4632 	if (access_size == 0 && !zero_size_allowed) {
4633 		verbose(env, "invalid zero-sized read\n");
4634 		return -EACCES;
4635 	}
4636 
4637 	if (type == ACCESS_HELPER) {
4638 		/* The bounds checks for writes are more permissive than for
4639 		 * reads. However, if raw_mode is not set, we'll do extra
4640 		 * checks below.
4641 		 */
4642 		bounds_check_type = BPF_WRITE;
4643 		clobber = true;
4644 	} else {
4645 		bounds_check_type = BPF_READ;
4646 	}
4647 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4648 					       type, bounds_check_type);
4649 	if (err)
4650 		return err;
4651 
4652 
4653 	if (tnum_is_const(reg->var_off)) {
4654 		min_off = max_off = reg->var_off.value + off;
4655 	} else {
4656 		/* Variable offset is prohibited for unprivileged mode for
4657 		 * simplicity since it requires corresponding support in
4658 		 * Spectre masking for stack ALU.
4659 		 * See also retrieve_ptr_limit().
4660 		 */
4661 		if (!env->bypass_spec_v1) {
4662 			char tn_buf[48];
4663 
4664 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4665 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4666 				regno, err_extra, tn_buf);
4667 			return -EACCES;
4668 		}
4669 		/* Only initialized buffer on stack is allowed to be accessed
4670 		 * with variable offset. With uninitialized buffer it's hard to
4671 		 * guarantee that whole memory is marked as initialized on
4672 		 * helper return since specific bounds are unknown what may
4673 		 * cause uninitialized stack leaking.
4674 		 */
4675 		if (meta && meta->raw_mode)
4676 			meta = NULL;
4677 
4678 		min_off = reg->smin_value + off;
4679 		max_off = reg->smax_value + off;
4680 	}
4681 
4682 	if (meta && meta->raw_mode) {
4683 		meta->access_size = access_size;
4684 		meta->regno = regno;
4685 		return 0;
4686 	}
4687 
4688 	for (i = min_off; i < max_off + access_size; i++) {
4689 		u8 *stype;
4690 
4691 		slot = -i - 1;
4692 		spi = slot / BPF_REG_SIZE;
4693 		if (state->allocated_stack <= slot)
4694 			goto err;
4695 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4696 		if (*stype == STACK_MISC)
4697 			goto mark;
4698 		if (*stype == STACK_ZERO) {
4699 			if (clobber) {
4700 				/* helper can write anything into the stack */
4701 				*stype = STACK_MISC;
4702 			}
4703 			goto mark;
4704 		}
4705 
4706 		if (is_spilled_reg(&state->stack[spi]) &&
4707 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4708 			goto mark;
4709 
4710 		if (is_spilled_reg(&state->stack[spi]) &&
4711 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4712 		     env->allow_ptr_leaks)) {
4713 			if (clobber) {
4714 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4715 				for (j = 0; j < BPF_REG_SIZE; j++)
4716 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4717 			}
4718 			goto mark;
4719 		}
4720 
4721 err:
4722 		if (tnum_is_const(reg->var_off)) {
4723 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4724 				err_extra, regno, min_off, i - min_off, access_size);
4725 		} else {
4726 			char tn_buf[48];
4727 
4728 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4729 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4730 				err_extra, regno, tn_buf, i - min_off, access_size);
4731 		}
4732 		return -EACCES;
4733 mark:
4734 		/* reading any byte out of 8-byte 'spill_slot' will cause
4735 		 * the whole slot to be marked as 'read'
4736 		 */
4737 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4738 			      state->stack[spi].spilled_ptr.parent,
4739 			      REG_LIVE_READ64);
4740 	}
4741 	return update_stack_depth(env, state, min_off);
4742 }
4743 
4744 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4745 				   int access_size, bool zero_size_allowed,
4746 				   struct bpf_call_arg_meta *meta)
4747 {
4748 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4749 
4750 	switch (reg->type) {
4751 	case PTR_TO_PACKET:
4752 	case PTR_TO_PACKET_META:
4753 		return check_packet_access(env, regno, reg->off, access_size,
4754 					   zero_size_allowed);
4755 	case PTR_TO_MAP_KEY:
4756 		return check_mem_region_access(env, regno, reg->off, access_size,
4757 					       reg->map_ptr->key_size, false);
4758 	case PTR_TO_MAP_VALUE:
4759 		if (check_map_access_type(env, regno, reg->off, access_size,
4760 					  meta && meta->raw_mode ? BPF_WRITE :
4761 					  BPF_READ))
4762 			return -EACCES;
4763 		return check_map_access(env, regno, reg->off, access_size,
4764 					zero_size_allowed);
4765 	case PTR_TO_MEM:
4766 		return check_mem_region_access(env, regno, reg->off,
4767 					       access_size, reg->mem_size,
4768 					       zero_size_allowed);
4769 	case PTR_TO_RDONLY_BUF:
4770 		if (meta && meta->raw_mode)
4771 			return -EACCES;
4772 		return check_buffer_access(env, reg, regno, reg->off,
4773 					   access_size, zero_size_allowed,
4774 					   "rdonly",
4775 					   &env->prog->aux->max_rdonly_access);
4776 	case PTR_TO_RDWR_BUF:
4777 		return check_buffer_access(env, reg, regno, reg->off,
4778 					   access_size, zero_size_allowed,
4779 					   "rdwr",
4780 					   &env->prog->aux->max_rdwr_access);
4781 	case PTR_TO_STACK:
4782 		return check_stack_range_initialized(
4783 				env,
4784 				regno, reg->off, access_size,
4785 				zero_size_allowed, ACCESS_HELPER, meta);
4786 	default: /* scalar_value or invalid ptr */
4787 		/* Allow zero-byte read from NULL, regardless of pointer type */
4788 		if (zero_size_allowed && access_size == 0 &&
4789 		    register_is_null(reg))
4790 			return 0;
4791 
4792 		verbose(env, "R%d type=%s expected=%s\n", regno,
4793 			reg_type_str[reg->type],
4794 			reg_type_str[PTR_TO_STACK]);
4795 		return -EACCES;
4796 	}
4797 }
4798 
4799 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4800 		   u32 regno, u32 mem_size)
4801 {
4802 	if (register_is_null(reg))
4803 		return 0;
4804 
4805 	if (reg_type_may_be_null(reg->type)) {
4806 		/* Assuming that the register contains a value check if the memory
4807 		 * access is safe. Temporarily save and restore the register's state as
4808 		 * the conversion shouldn't be visible to a caller.
4809 		 */
4810 		const struct bpf_reg_state saved_reg = *reg;
4811 		int rv;
4812 
4813 		mark_ptr_not_null_reg(reg);
4814 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4815 		*reg = saved_reg;
4816 		return rv;
4817 	}
4818 
4819 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4820 }
4821 
4822 /* Implementation details:
4823  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4824  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4825  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4826  * value_or_null->value transition, since the verifier only cares about
4827  * the range of access to valid map value pointer and doesn't care about actual
4828  * address of the map element.
4829  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4830  * reg->id > 0 after value_or_null->value transition. By doing so
4831  * two bpf_map_lookups will be considered two different pointers that
4832  * point to different bpf_spin_locks.
4833  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4834  * dead-locks.
4835  * Since only one bpf_spin_lock is allowed the checks are simpler than
4836  * reg_is_refcounted() logic. The verifier needs to remember only
4837  * one spin_lock instead of array of acquired_refs.
4838  * cur_state->active_spin_lock remembers which map value element got locked
4839  * and clears it after bpf_spin_unlock.
4840  */
4841 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4842 			     bool is_lock)
4843 {
4844 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4845 	struct bpf_verifier_state *cur = env->cur_state;
4846 	bool is_const = tnum_is_const(reg->var_off);
4847 	struct bpf_map *map = reg->map_ptr;
4848 	u64 val = reg->var_off.value;
4849 
4850 	if (!is_const) {
4851 		verbose(env,
4852 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4853 			regno);
4854 		return -EINVAL;
4855 	}
4856 	if (!map->btf) {
4857 		verbose(env,
4858 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4859 			map->name);
4860 		return -EINVAL;
4861 	}
4862 	if (!map_value_has_spin_lock(map)) {
4863 		if (map->spin_lock_off == -E2BIG)
4864 			verbose(env,
4865 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4866 				map->name);
4867 		else if (map->spin_lock_off == -ENOENT)
4868 			verbose(env,
4869 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4870 				map->name);
4871 		else
4872 			verbose(env,
4873 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4874 				map->name);
4875 		return -EINVAL;
4876 	}
4877 	if (map->spin_lock_off != val + reg->off) {
4878 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4879 			val + reg->off);
4880 		return -EINVAL;
4881 	}
4882 	if (is_lock) {
4883 		if (cur->active_spin_lock) {
4884 			verbose(env,
4885 				"Locking two bpf_spin_locks are not allowed\n");
4886 			return -EINVAL;
4887 		}
4888 		cur->active_spin_lock = reg->id;
4889 	} else {
4890 		if (!cur->active_spin_lock) {
4891 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4892 			return -EINVAL;
4893 		}
4894 		if (cur->active_spin_lock != reg->id) {
4895 			verbose(env, "bpf_spin_unlock of different lock\n");
4896 			return -EINVAL;
4897 		}
4898 		cur->active_spin_lock = 0;
4899 	}
4900 	return 0;
4901 }
4902 
4903 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4904 			      struct bpf_call_arg_meta *meta)
4905 {
4906 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4907 	bool is_const = tnum_is_const(reg->var_off);
4908 	struct bpf_map *map = reg->map_ptr;
4909 	u64 val = reg->var_off.value;
4910 
4911 	if (!is_const) {
4912 		verbose(env,
4913 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4914 			regno);
4915 		return -EINVAL;
4916 	}
4917 	if (!map->btf) {
4918 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4919 			map->name);
4920 		return -EINVAL;
4921 	}
4922 	if (!map_value_has_timer(map)) {
4923 		if (map->timer_off == -E2BIG)
4924 			verbose(env,
4925 				"map '%s' has more than one 'struct bpf_timer'\n",
4926 				map->name);
4927 		else if (map->timer_off == -ENOENT)
4928 			verbose(env,
4929 				"map '%s' doesn't have 'struct bpf_timer'\n",
4930 				map->name);
4931 		else
4932 			verbose(env,
4933 				"map '%s' is not a struct type or bpf_timer is mangled\n",
4934 				map->name);
4935 		return -EINVAL;
4936 	}
4937 	if (map->timer_off != val + reg->off) {
4938 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4939 			val + reg->off, map->timer_off);
4940 		return -EINVAL;
4941 	}
4942 	if (meta->map_ptr) {
4943 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4944 		return -EFAULT;
4945 	}
4946 	meta->map_uid = reg->map_uid;
4947 	meta->map_ptr = map;
4948 	return 0;
4949 }
4950 
4951 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4952 {
4953 	return type == ARG_PTR_TO_MEM ||
4954 	       type == ARG_PTR_TO_MEM_OR_NULL ||
4955 	       type == ARG_PTR_TO_UNINIT_MEM;
4956 }
4957 
4958 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4959 {
4960 	return type == ARG_CONST_SIZE ||
4961 	       type == ARG_CONST_SIZE_OR_ZERO;
4962 }
4963 
4964 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4965 {
4966 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4967 }
4968 
4969 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4970 {
4971 	return type == ARG_PTR_TO_INT ||
4972 	       type == ARG_PTR_TO_LONG;
4973 }
4974 
4975 static int int_ptr_type_to_size(enum bpf_arg_type type)
4976 {
4977 	if (type == ARG_PTR_TO_INT)
4978 		return sizeof(u32);
4979 	else if (type == ARG_PTR_TO_LONG)
4980 		return sizeof(u64);
4981 
4982 	return -EINVAL;
4983 }
4984 
4985 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4986 				 const struct bpf_call_arg_meta *meta,
4987 				 enum bpf_arg_type *arg_type)
4988 {
4989 	if (!meta->map_ptr) {
4990 		/* kernel subsystem misconfigured verifier */
4991 		verbose(env, "invalid map_ptr to access map->type\n");
4992 		return -EACCES;
4993 	}
4994 
4995 	switch (meta->map_ptr->map_type) {
4996 	case BPF_MAP_TYPE_SOCKMAP:
4997 	case BPF_MAP_TYPE_SOCKHASH:
4998 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4999 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5000 		} else {
5001 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5002 			return -EINVAL;
5003 		}
5004 		break;
5005 	case BPF_MAP_TYPE_BLOOM_FILTER:
5006 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5007 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5008 		break;
5009 	default:
5010 		break;
5011 	}
5012 	return 0;
5013 }
5014 
5015 struct bpf_reg_types {
5016 	const enum bpf_reg_type types[10];
5017 	u32 *btf_id;
5018 };
5019 
5020 static const struct bpf_reg_types map_key_value_types = {
5021 	.types = {
5022 		PTR_TO_STACK,
5023 		PTR_TO_PACKET,
5024 		PTR_TO_PACKET_META,
5025 		PTR_TO_MAP_KEY,
5026 		PTR_TO_MAP_VALUE,
5027 	},
5028 };
5029 
5030 static const struct bpf_reg_types sock_types = {
5031 	.types = {
5032 		PTR_TO_SOCK_COMMON,
5033 		PTR_TO_SOCKET,
5034 		PTR_TO_TCP_SOCK,
5035 		PTR_TO_XDP_SOCK,
5036 	},
5037 };
5038 
5039 #ifdef CONFIG_NET
5040 static const struct bpf_reg_types btf_id_sock_common_types = {
5041 	.types = {
5042 		PTR_TO_SOCK_COMMON,
5043 		PTR_TO_SOCKET,
5044 		PTR_TO_TCP_SOCK,
5045 		PTR_TO_XDP_SOCK,
5046 		PTR_TO_BTF_ID,
5047 	},
5048 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5049 };
5050 #endif
5051 
5052 static const struct bpf_reg_types mem_types = {
5053 	.types = {
5054 		PTR_TO_STACK,
5055 		PTR_TO_PACKET,
5056 		PTR_TO_PACKET_META,
5057 		PTR_TO_MAP_KEY,
5058 		PTR_TO_MAP_VALUE,
5059 		PTR_TO_MEM,
5060 		PTR_TO_RDONLY_BUF,
5061 		PTR_TO_RDWR_BUF,
5062 	},
5063 };
5064 
5065 static const struct bpf_reg_types int_ptr_types = {
5066 	.types = {
5067 		PTR_TO_STACK,
5068 		PTR_TO_PACKET,
5069 		PTR_TO_PACKET_META,
5070 		PTR_TO_MAP_KEY,
5071 		PTR_TO_MAP_VALUE,
5072 	},
5073 };
5074 
5075 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5076 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5077 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5078 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
5079 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5080 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5081 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5082 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
5083 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5084 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5085 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5086 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5087 
5088 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5089 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5090 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5091 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
5092 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
5093 	[ARG_CONST_SIZE]		= &scalar_types,
5094 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5095 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5096 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5097 	[ARG_PTR_TO_CTX]		= &context_types,
5098 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
5099 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5100 #ifdef CONFIG_NET
5101 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5102 #endif
5103 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5104 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
5105 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5106 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5107 	[ARG_PTR_TO_MEM]		= &mem_types,
5108 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
5109 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
5110 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5111 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
5112 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5113 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5114 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5115 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5116 	[ARG_PTR_TO_STACK_OR_NULL]	= &stack_ptr_types,
5117 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5118 	[ARG_PTR_TO_TIMER]		= &timer_types,
5119 };
5120 
5121 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5122 			  enum bpf_arg_type arg_type,
5123 			  const u32 *arg_btf_id)
5124 {
5125 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5126 	enum bpf_reg_type expected, type = reg->type;
5127 	const struct bpf_reg_types *compatible;
5128 	int i, j;
5129 
5130 	compatible = compatible_reg_types[arg_type];
5131 	if (!compatible) {
5132 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5133 		return -EFAULT;
5134 	}
5135 
5136 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5137 		expected = compatible->types[i];
5138 		if (expected == NOT_INIT)
5139 			break;
5140 
5141 		if (type == expected)
5142 			goto found;
5143 	}
5144 
5145 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
5146 	for (j = 0; j + 1 < i; j++)
5147 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
5148 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
5149 	return -EACCES;
5150 
5151 found:
5152 	if (type == PTR_TO_BTF_ID) {
5153 		if (!arg_btf_id) {
5154 			if (!compatible->btf_id) {
5155 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5156 				return -EFAULT;
5157 			}
5158 			arg_btf_id = compatible->btf_id;
5159 		}
5160 
5161 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5162 					  btf_vmlinux, *arg_btf_id)) {
5163 			verbose(env, "R%d is of type %s but %s is expected\n",
5164 				regno, kernel_type_name(reg->btf, reg->btf_id),
5165 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5166 			return -EACCES;
5167 		}
5168 
5169 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5170 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5171 				regno);
5172 			return -EACCES;
5173 		}
5174 	}
5175 
5176 	return 0;
5177 }
5178 
5179 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5180 			  struct bpf_call_arg_meta *meta,
5181 			  const struct bpf_func_proto *fn)
5182 {
5183 	u32 regno = BPF_REG_1 + arg;
5184 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5185 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5186 	enum bpf_reg_type type = reg->type;
5187 	int err = 0;
5188 
5189 	if (arg_type == ARG_DONTCARE)
5190 		return 0;
5191 
5192 	err = check_reg_arg(env, regno, SRC_OP);
5193 	if (err)
5194 		return err;
5195 
5196 	if (arg_type == ARG_ANYTHING) {
5197 		if (is_pointer_value(env, regno)) {
5198 			verbose(env, "R%d leaks addr into helper function\n",
5199 				regno);
5200 			return -EACCES;
5201 		}
5202 		return 0;
5203 	}
5204 
5205 	if (type_is_pkt_pointer(type) &&
5206 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5207 		verbose(env, "helper access to the packet is not allowed\n");
5208 		return -EACCES;
5209 	}
5210 
5211 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5212 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5213 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5214 		err = resolve_map_arg_type(env, meta, &arg_type);
5215 		if (err)
5216 			return err;
5217 	}
5218 
5219 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5220 		/* A NULL register has a SCALAR_VALUE type, so skip
5221 		 * type checking.
5222 		 */
5223 		goto skip_type_check;
5224 
5225 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5226 	if (err)
5227 		return err;
5228 
5229 	if (type == PTR_TO_CTX) {
5230 		err = check_ctx_reg(env, reg, regno);
5231 		if (err < 0)
5232 			return err;
5233 	}
5234 
5235 skip_type_check:
5236 	if (reg->ref_obj_id) {
5237 		if (meta->ref_obj_id) {
5238 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5239 				regno, reg->ref_obj_id,
5240 				meta->ref_obj_id);
5241 			return -EFAULT;
5242 		}
5243 		meta->ref_obj_id = reg->ref_obj_id;
5244 	}
5245 
5246 	if (arg_type == ARG_CONST_MAP_PTR) {
5247 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5248 		if (meta->map_ptr) {
5249 			/* Use map_uid (which is unique id of inner map) to reject:
5250 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5251 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5252 			 * if (inner_map1 && inner_map2) {
5253 			 *     timer = bpf_map_lookup_elem(inner_map1);
5254 			 *     if (timer)
5255 			 *         // mismatch would have been allowed
5256 			 *         bpf_timer_init(timer, inner_map2);
5257 			 * }
5258 			 *
5259 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5260 			 */
5261 			if (meta->map_ptr != reg->map_ptr ||
5262 			    meta->map_uid != reg->map_uid) {
5263 				verbose(env,
5264 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5265 					meta->map_uid, reg->map_uid);
5266 				return -EINVAL;
5267 			}
5268 		}
5269 		meta->map_ptr = reg->map_ptr;
5270 		meta->map_uid = reg->map_uid;
5271 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5272 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5273 		 * check that [key, key + map->key_size) are within
5274 		 * stack limits and initialized
5275 		 */
5276 		if (!meta->map_ptr) {
5277 			/* in function declaration map_ptr must come before
5278 			 * map_key, so that it's verified and known before
5279 			 * we have to check map_key here. Otherwise it means
5280 			 * that kernel subsystem misconfigured verifier
5281 			 */
5282 			verbose(env, "invalid map_ptr to access map->key\n");
5283 			return -EACCES;
5284 		}
5285 		err = check_helper_mem_access(env, regno,
5286 					      meta->map_ptr->key_size, false,
5287 					      NULL);
5288 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5289 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5290 		    !register_is_null(reg)) ||
5291 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5292 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5293 		 * check [value, value + map->value_size) validity
5294 		 */
5295 		if (!meta->map_ptr) {
5296 			/* kernel subsystem misconfigured verifier */
5297 			verbose(env, "invalid map_ptr to access map->value\n");
5298 			return -EACCES;
5299 		}
5300 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5301 		err = check_helper_mem_access(env, regno,
5302 					      meta->map_ptr->value_size, false,
5303 					      meta);
5304 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5305 		if (!reg->btf_id) {
5306 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5307 			return -EACCES;
5308 		}
5309 		meta->ret_btf = reg->btf;
5310 		meta->ret_btf_id = reg->btf_id;
5311 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5312 		if (meta->func_id == BPF_FUNC_spin_lock) {
5313 			if (process_spin_lock(env, regno, true))
5314 				return -EACCES;
5315 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5316 			if (process_spin_lock(env, regno, false))
5317 				return -EACCES;
5318 		} else {
5319 			verbose(env, "verifier internal error\n");
5320 			return -EFAULT;
5321 		}
5322 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5323 		if (process_timer_func(env, regno, meta))
5324 			return -EACCES;
5325 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5326 		meta->subprogno = reg->subprogno;
5327 	} else if (arg_type_is_mem_ptr(arg_type)) {
5328 		/* The access to this pointer is only checked when we hit the
5329 		 * next is_mem_size argument below.
5330 		 */
5331 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5332 	} else if (arg_type_is_mem_size(arg_type)) {
5333 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5334 
5335 		/* This is used to refine r0 return value bounds for helpers
5336 		 * that enforce this value as an upper bound on return values.
5337 		 * See do_refine_retval_range() for helpers that can refine
5338 		 * the return value. C type of helper is u32 so we pull register
5339 		 * bound from umax_value however, if negative verifier errors
5340 		 * out. Only upper bounds can be learned because retval is an
5341 		 * int type and negative retvals are allowed.
5342 		 */
5343 		meta->msize_max_value = reg->umax_value;
5344 
5345 		/* The register is SCALAR_VALUE; the access check
5346 		 * happens using its boundaries.
5347 		 */
5348 		if (!tnum_is_const(reg->var_off))
5349 			/* For unprivileged variable accesses, disable raw
5350 			 * mode so that the program is required to
5351 			 * initialize all the memory that the helper could
5352 			 * just partially fill up.
5353 			 */
5354 			meta = NULL;
5355 
5356 		if (reg->smin_value < 0) {
5357 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5358 				regno);
5359 			return -EACCES;
5360 		}
5361 
5362 		if (reg->umin_value == 0) {
5363 			err = check_helper_mem_access(env, regno - 1, 0,
5364 						      zero_size_allowed,
5365 						      meta);
5366 			if (err)
5367 				return err;
5368 		}
5369 
5370 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5371 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5372 				regno);
5373 			return -EACCES;
5374 		}
5375 		err = check_helper_mem_access(env, regno - 1,
5376 					      reg->umax_value,
5377 					      zero_size_allowed, meta);
5378 		if (!err)
5379 			err = mark_chain_precision(env, regno);
5380 	} else if (arg_type_is_alloc_size(arg_type)) {
5381 		if (!tnum_is_const(reg->var_off)) {
5382 			verbose(env, "R%d is not a known constant'\n",
5383 				regno);
5384 			return -EACCES;
5385 		}
5386 		meta->mem_size = reg->var_off.value;
5387 	} else if (arg_type_is_int_ptr(arg_type)) {
5388 		int size = int_ptr_type_to_size(arg_type);
5389 
5390 		err = check_helper_mem_access(env, regno, size, false, meta);
5391 		if (err)
5392 			return err;
5393 		err = check_ptr_alignment(env, reg, 0, size, true);
5394 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5395 		struct bpf_map *map = reg->map_ptr;
5396 		int map_off;
5397 		u64 map_addr;
5398 		char *str_ptr;
5399 
5400 		if (!bpf_map_is_rdonly(map)) {
5401 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5402 			return -EACCES;
5403 		}
5404 
5405 		if (!tnum_is_const(reg->var_off)) {
5406 			verbose(env, "R%d is not a constant address'\n", regno);
5407 			return -EACCES;
5408 		}
5409 
5410 		if (!map->ops->map_direct_value_addr) {
5411 			verbose(env, "no direct value access support for this map type\n");
5412 			return -EACCES;
5413 		}
5414 
5415 		err = check_map_access(env, regno, reg->off,
5416 				       map->value_size - reg->off, false);
5417 		if (err)
5418 			return err;
5419 
5420 		map_off = reg->off + reg->var_off.value;
5421 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5422 		if (err) {
5423 			verbose(env, "direct value access on string failed\n");
5424 			return err;
5425 		}
5426 
5427 		str_ptr = (char *)(long)(map_addr);
5428 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5429 			verbose(env, "string is not zero-terminated\n");
5430 			return -EINVAL;
5431 		}
5432 	}
5433 
5434 	return err;
5435 }
5436 
5437 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5438 {
5439 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5440 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5441 
5442 	if (func_id != BPF_FUNC_map_update_elem)
5443 		return false;
5444 
5445 	/* It's not possible to get access to a locked struct sock in these
5446 	 * contexts, so updating is safe.
5447 	 */
5448 	switch (type) {
5449 	case BPF_PROG_TYPE_TRACING:
5450 		if (eatype == BPF_TRACE_ITER)
5451 			return true;
5452 		break;
5453 	case BPF_PROG_TYPE_SOCKET_FILTER:
5454 	case BPF_PROG_TYPE_SCHED_CLS:
5455 	case BPF_PROG_TYPE_SCHED_ACT:
5456 	case BPF_PROG_TYPE_XDP:
5457 	case BPF_PROG_TYPE_SK_REUSEPORT:
5458 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5459 	case BPF_PROG_TYPE_SK_LOOKUP:
5460 		return true;
5461 	default:
5462 		break;
5463 	}
5464 
5465 	verbose(env, "cannot update sockmap in this context\n");
5466 	return false;
5467 }
5468 
5469 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5470 {
5471 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5472 }
5473 
5474 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5475 					struct bpf_map *map, int func_id)
5476 {
5477 	if (!map)
5478 		return 0;
5479 
5480 	/* We need a two way check, first is from map perspective ... */
5481 	switch (map->map_type) {
5482 	case BPF_MAP_TYPE_PROG_ARRAY:
5483 		if (func_id != BPF_FUNC_tail_call)
5484 			goto error;
5485 		break;
5486 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5487 		if (func_id != BPF_FUNC_perf_event_read &&
5488 		    func_id != BPF_FUNC_perf_event_output &&
5489 		    func_id != BPF_FUNC_skb_output &&
5490 		    func_id != BPF_FUNC_perf_event_read_value &&
5491 		    func_id != BPF_FUNC_xdp_output)
5492 			goto error;
5493 		break;
5494 	case BPF_MAP_TYPE_RINGBUF:
5495 		if (func_id != BPF_FUNC_ringbuf_output &&
5496 		    func_id != BPF_FUNC_ringbuf_reserve &&
5497 		    func_id != BPF_FUNC_ringbuf_query)
5498 			goto error;
5499 		break;
5500 	case BPF_MAP_TYPE_STACK_TRACE:
5501 		if (func_id != BPF_FUNC_get_stackid)
5502 			goto error;
5503 		break;
5504 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5505 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5506 		    func_id != BPF_FUNC_current_task_under_cgroup)
5507 			goto error;
5508 		break;
5509 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5510 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5511 		if (func_id != BPF_FUNC_get_local_storage)
5512 			goto error;
5513 		break;
5514 	case BPF_MAP_TYPE_DEVMAP:
5515 	case BPF_MAP_TYPE_DEVMAP_HASH:
5516 		if (func_id != BPF_FUNC_redirect_map &&
5517 		    func_id != BPF_FUNC_map_lookup_elem)
5518 			goto error;
5519 		break;
5520 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5521 	 * appear.
5522 	 */
5523 	case BPF_MAP_TYPE_CPUMAP:
5524 		if (func_id != BPF_FUNC_redirect_map)
5525 			goto error;
5526 		break;
5527 	case BPF_MAP_TYPE_XSKMAP:
5528 		if (func_id != BPF_FUNC_redirect_map &&
5529 		    func_id != BPF_FUNC_map_lookup_elem)
5530 			goto error;
5531 		break;
5532 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5533 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5534 		if (func_id != BPF_FUNC_map_lookup_elem)
5535 			goto error;
5536 		break;
5537 	case BPF_MAP_TYPE_SOCKMAP:
5538 		if (func_id != BPF_FUNC_sk_redirect_map &&
5539 		    func_id != BPF_FUNC_sock_map_update &&
5540 		    func_id != BPF_FUNC_map_delete_elem &&
5541 		    func_id != BPF_FUNC_msg_redirect_map &&
5542 		    func_id != BPF_FUNC_sk_select_reuseport &&
5543 		    func_id != BPF_FUNC_map_lookup_elem &&
5544 		    !may_update_sockmap(env, func_id))
5545 			goto error;
5546 		break;
5547 	case BPF_MAP_TYPE_SOCKHASH:
5548 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5549 		    func_id != BPF_FUNC_sock_hash_update &&
5550 		    func_id != BPF_FUNC_map_delete_elem &&
5551 		    func_id != BPF_FUNC_msg_redirect_hash &&
5552 		    func_id != BPF_FUNC_sk_select_reuseport &&
5553 		    func_id != BPF_FUNC_map_lookup_elem &&
5554 		    !may_update_sockmap(env, func_id))
5555 			goto error;
5556 		break;
5557 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5558 		if (func_id != BPF_FUNC_sk_select_reuseport)
5559 			goto error;
5560 		break;
5561 	case BPF_MAP_TYPE_QUEUE:
5562 	case BPF_MAP_TYPE_STACK:
5563 		if (func_id != BPF_FUNC_map_peek_elem &&
5564 		    func_id != BPF_FUNC_map_pop_elem &&
5565 		    func_id != BPF_FUNC_map_push_elem)
5566 			goto error;
5567 		break;
5568 	case BPF_MAP_TYPE_SK_STORAGE:
5569 		if (func_id != BPF_FUNC_sk_storage_get &&
5570 		    func_id != BPF_FUNC_sk_storage_delete)
5571 			goto error;
5572 		break;
5573 	case BPF_MAP_TYPE_INODE_STORAGE:
5574 		if (func_id != BPF_FUNC_inode_storage_get &&
5575 		    func_id != BPF_FUNC_inode_storage_delete)
5576 			goto error;
5577 		break;
5578 	case BPF_MAP_TYPE_TASK_STORAGE:
5579 		if (func_id != BPF_FUNC_task_storage_get &&
5580 		    func_id != BPF_FUNC_task_storage_delete)
5581 			goto error;
5582 		break;
5583 	case BPF_MAP_TYPE_BLOOM_FILTER:
5584 		if (func_id != BPF_FUNC_map_peek_elem &&
5585 		    func_id != BPF_FUNC_map_push_elem)
5586 			goto error;
5587 		break;
5588 	default:
5589 		break;
5590 	}
5591 
5592 	/* ... and second from the function itself. */
5593 	switch (func_id) {
5594 	case BPF_FUNC_tail_call:
5595 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5596 			goto error;
5597 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5598 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5599 			return -EINVAL;
5600 		}
5601 		break;
5602 	case BPF_FUNC_perf_event_read:
5603 	case BPF_FUNC_perf_event_output:
5604 	case BPF_FUNC_perf_event_read_value:
5605 	case BPF_FUNC_skb_output:
5606 	case BPF_FUNC_xdp_output:
5607 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5608 			goto error;
5609 		break;
5610 	case BPF_FUNC_ringbuf_output:
5611 	case BPF_FUNC_ringbuf_reserve:
5612 	case BPF_FUNC_ringbuf_query:
5613 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5614 			goto error;
5615 		break;
5616 	case BPF_FUNC_get_stackid:
5617 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5618 			goto error;
5619 		break;
5620 	case BPF_FUNC_current_task_under_cgroup:
5621 	case BPF_FUNC_skb_under_cgroup:
5622 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5623 			goto error;
5624 		break;
5625 	case BPF_FUNC_redirect_map:
5626 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5627 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5628 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5629 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5630 			goto error;
5631 		break;
5632 	case BPF_FUNC_sk_redirect_map:
5633 	case BPF_FUNC_msg_redirect_map:
5634 	case BPF_FUNC_sock_map_update:
5635 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5636 			goto error;
5637 		break;
5638 	case BPF_FUNC_sk_redirect_hash:
5639 	case BPF_FUNC_msg_redirect_hash:
5640 	case BPF_FUNC_sock_hash_update:
5641 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5642 			goto error;
5643 		break;
5644 	case BPF_FUNC_get_local_storage:
5645 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5646 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5647 			goto error;
5648 		break;
5649 	case BPF_FUNC_sk_select_reuseport:
5650 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5651 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5652 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5653 			goto error;
5654 		break;
5655 	case BPF_FUNC_map_pop_elem:
5656 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5657 		    map->map_type != BPF_MAP_TYPE_STACK)
5658 			goto error;
5659 		break;
5660 	case BPF_FUNC_map_peek_elem:
5661 	case BPF_FUNC_map_push_elem:
5662 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5663 		    map->map_type != BPF_MAP_TYPE_STACK &&
5664 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
5665 			goto error;
5666 		break;
5667 	case BPF_FUNC_sk_storage_get:
5668 	case BPF_FUNC_sk_storage_delete:
5669 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5670 			goto error;
5671 		break;
5672 	case BPF_FUNC_inode_storage_get:
5673 	case BPF_FUNC_inode_storage_delete:
5674 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5675 			goto error;
5676 		break;
5677 	case BPF_FUNC_task_storage_get:
5678 	case BPF_FUNC_task_storage_delete:
5679 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5680 			goto error;
5681 		break;
5682 	default:
5683 		break;
5684 	}
5685 
5686 	return 0;
5687 error:
5688 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5689 		map->map_type, func_id_name(func_id), func_id);
5690 	return -EINVAL;
5691 }
5692 
5693 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5694 {
5695 	int count = 0;
5696 
5697 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5698 		count++;
5699 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5700 		count++;
5701 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5702 		count++;
5703 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5704 		count++;
5705 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5706 		count++;
5707 
5708 	/* We only support one arg being in raw mode at the moment,
5709 	 * which is sufficient for the helper functions we have
5710 	 * right now.
5711 	 */
5712 	return count <= 1;
5713 }
5714 
5715 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5716 				    enum bpf_arg_type arg_next)
5717 {
5718 	return (arg_type_is_mem_ptr(arg_curr) &&
5719 	        !arg_type_is_mem_size(arg_next)) ||
5720 	       (!arg_type_is_mem_ptr(arg_curr) &&
5721 		arg_type_is_mem_size(arg_next));
5722 }
5723 
5724 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5725 {
5726 	/* bpf_xxx(..., buf, len) call will access 'len'
5727 	 * bytes from memory 'buf'. Both arg types need
5728 	 * to be paired, so make sure there's no buggy
5729 	 * helper function specification.
5730 	 */
5731 	if (arg_type_is_mem_size(fn->arg1_type) ||
5732 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5733 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5734 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5735 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5736 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5737 		return false;
5738 
5739 	return true;
5740 }
5741 
5742 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5743 {
5744 	int count = 0;
5745 
5746 	if (arg_type_may_be_refcounted(fn->arg1_type))
5747 		count++;
5748 	if (arg_type_may_be_refcounted(fn->arg2_type))
5749 		count++;
5750 	if (arg_type_may_be_refcounted(fn->arg3_type))
5751 		count++;
5752 	if (arg_type_may_be_refcounted(fn->arg4_type))
5753 		count++;
5754 	if (arg_type_may_be_refcounted(fn->arg5_type))
5755 		count++;
5756 
5757 	/* A reference acquiring function cannot acquire
5758 	 * another refcounted ptr.
5759 	 */
5760 	if (may_be_acquire_function(func_id) && count)
5761 		return false;
5762 
5763 	/* We only support one arg being unreferenced at the moment,
5764 	 * which is sufficient for the helper functions we have right now.
5765 	 */
5766 	return count <= 1;
5767 }
5768 
5769 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5770 {
5771 	int i;
5772 
5773 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5774 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5775 			return false;
5776 
5777 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5778 			return false;
5779 	}
5780 
5781 	return true;
5782 }
5783 
5784 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5785 {
5786 	return check_raw_mode_ok(fn) &&
5787 	       check_arg_pair_ok(fn) &&
5788 	       check_btf_id_ok(fn) &&
5789 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5790 }
5791 
5792 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5793  * are now invalid, so turn them into unknown SCALAR_VALUE.
5794  */
5795 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5796 				     struct bpf_func_state *state)
5797 {
5798 	struct bpf_reg_state *regs = state->regs, *reg;
5799 	int i;
5800 
5801 	for (i = 0; i < MAX_BPF_REG; i++)
5802 		if (reg_is_pkt_pointer_any(&regs[i]))
5803 			mark_reg_unknown(env, regs, i);
5804 
5805 	bpf_for_each_spilled_reg(i, state, reg) {
5806 		if (!reg)
5807 			continue;
5808 		if (reg_is_pkt_pointer_any(reg))
5809 			__mark_reg_unknown(env, reg);
5810 	}
5811 }
5812 
5813 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5814 {
5815 	struct bpf_verifier_state *vstate = env->cur_state;
5816 	int i;
5817 
5818 	for (i = 0; i <= vstate->curframe; i++)
5819 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5820 }
5821 
5822 enum {
5823 	AT_PKT_END = -1,
5824 	BEYOND_PKT_END = -2,
5825 };
5826 
5827 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5828 {
5829 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5830 	struct bpf_reg_state *reg = &state->regs[regn];
5831 
5832 	if (reg->type != PTR_TO_PACKET)
5833 		/* PTR_TO_PACKET_META is not supported yet */
5834 		return;
5835 
5836 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5837 	 * How far beyond pkt_end it goes is unknown.
5838 	 * if (!range_open) it's the case of pkt >= pkt_end
5839 	 * if (range_open) it's the case of pkt > pkt_end
5840 	 * hence this pointer is at least 1 byte bigger than pkt_end
5841 	 */
5842 	if (range_open)
5843 		reg->range = BEYOND_PKT_END;
5844 	else
5845 		reg->range = AT_PKT_END;
5846 }
5847 
5848 static void release_reg_references(struct bpf_verifier_env *env,
5849 				   struct bpf_func_state *state,
5850 				   int ref_obj_id)
5851 {
5852 	struct bpf_reg_state *regs = state->regs, *reg;
5853 	int i;
5854 
5855 	for (i = 0; i < MAX_BPF_REG; i++)
5856 		if (regs[i].ref_obj_id == ref_obj_id)
5857 			mark_reg_unknown(env, regs, i);
5858 
5859 	bpf_for_each_spilled_reg(i, state, reg) {
5860 		if (!reg)
5861 			continue;
5862 		if (reg->ref_obj_id == ref_obj_id)
5863 			__mark_reg_unknown(env, reg);
5864 	}
5865 }
5866 
5867 /* The pointer with the specified id has released its reference to kernel
5868  * resources. Identify all copies of the same pointer and clear the reference.
5869  */
5870 static int release_reference(struct bpf_verifier_env *env,
5871 			     int ref_obj_id)
5872 {
5873 	struct bpf_verifier_state *vstate = env->cur_state;
5874 	int err;
5875 	int i;
5876 
5877 	err = release_reference_state(cur_func(env), ref_obj_id);
5878 	if (err)
5879 		return err;
5880 
5881 	for (i = 0; i <= vstate->curframe; i++)
5882 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5883 
5884 	return 0;
5885 }
5886 
5887 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5888 				    struct bpf_reg_state *regs)
5889 {
5890 	int i;
5891 
5892 	/* after the call registers r0 - r5 were scratched */
5893 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5894 		mark_reg_not_init(env, regs, caller_saved[i]);
5895 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5896 	}
5897 }
5898 
5899 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5900 				   struct bpf_func_state *caller,
5901 				   struct bpf_func_state *callee,
5902 				   int insn_idx);
5903 
5904 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5905 			     int *insn_idx, int subprog,
5906 			     set_callee_state_fn set_callee_state_cb)
5907 {
5908 	struct bpf_verifier_state *state = env->cur_state;
5909 	struct bpf_func_info_aux *func_info_aux;
5910 	struct bpf_func_state *caller, *callee;
5911 	int err;
5912 	bool is_global = false;
5913 
5914 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5915 		verbose(env, "the call stack of %d frames is too deep\n",
5916 			state->curframe + 2);
5917 		return -E2BIG;
5918 	}
5919 
5920 	caller = state->frame[state->curframe];
5921 	if (state->frame[state->curframe + 1]) {
5922 		verbose(env, "verifier bug. Frame %d already allocated\n",
5923 			state->curframe + 1);
5924 		return -EFAULT;
5925 	}
5926 
5927 	func_info_aux = env->prog->aux->func_info_aux;
5928 	if (func_info_aux)
5929 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5930 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5931 	if (err == -EFAULT)
5932 		return err;
5933 	if (is_global) {
5934 		if (err) {
5935 			verbose(env, "Caller passes invalid args into func#%d\n",
5936 				subprog);
5937 			return err;
5938 		} else {
5939 			if (env->log.level & BPF_LOG_LEVEL)
5940 				verbose(env,
5941 					"Func#%d is global and valid. Skipping.\n",
5942 					subprog);
5943 			clear_caller_saved_regs(env, caller->regs);
5944 
5945 			/* All global functions return a 64-bit SCALAR_VALUE */
5946 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5947 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5948 
5949 			/* continue with next insn after call */
5950 			return 0;
5951 		}
5952 	}
5953 
5954 	if (insn->code == (BPF_JMP | BPF_CALL) &&
5955 	    insn->imm == BPF_FUNC_timer_set_callback) {
5956 		struct bpf_verifier_state *async_cb;
5957 
5958 		/* there is no real recursion here. timer callbacks are async */
5959 		env->subprog_info[subprog].is_async_cb = true;
5960 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5961 					 *insn_idx, subprog);
5962 		if (!async_cb)
5963 			return -EFAULT;
5964 		callee = async_cb->frame[0];
5965 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
5966 
5967 		/* Convert bpf_timer_set_callback() args into timer callback args */
5968 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
5969 		if (err)
5970 			return err;
5971 
5972 		clear_caller_saved_regs(env, caller->regs);
5973 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
5974 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5975 		/* continue with next insn after call */
5976 		return 0;
5977 	}
5978 
5979 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5980 	if (!callee)
5981 		return -ENOMEM;
5982 	state->frame[state->curframe + 1] = callee;
5983 
5984 	/* callee cannot access r0, r6 - r9 for reading and has to write
5985 	 * into its own stack before reading from it.
5986 	 * callee can read/write into caller's stack
5987 	 */
5988 	init_func_state(env, callee,
5989 			/* remember the callsite, it will be used by bpf_exit */
5990 			*insn_idx /* callsite */,
5991 			state->curframe + 1 /* frameno within this callchain */,
5992 			subprog /* subprog number within this prog */);
5993 
5994 	/* Transfer references to the callee */
5995 	err = copy_reference_state(callee, caller);
5996 	if (err)
5997 		return err;
5998 
5999 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6000 	if (err)
6001 		return err;
6002 
6003 	clear_caller_saved_regs(env, caller->regs);
6004 
6005 	/* only increment it after check_reg_arg() finished */
6006 	state->curframe++;
6007 
6008 	/* and go analyze first insn of the callee */
6009 	*insn_idx = env->subprog_info[subprog].start - 1;
6010 
6011 	if (env->log.level & BPF_LOG_LEVEL) {
6012 		verbose(env, "caller:\n");
6013 		print_verifier_state(env, caller);
6014 		verbose(env, "callee:\n");
6015 		print_verifier_state(env, callee);
6016 	}
6017 	return 0;
6018 }
6019 
6020 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6021 				   struct bpf_func_state *caller,
6022 				   struct bpf_func_state *callee)
6023 {
6024 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6025 	 *      void *callback_ctx, u64 flags);
6026 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6027 	 *      void *callback_ctx);
6028 	 */
6029 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6030 
6031 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6032 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6033 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6034 
6035 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6036 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6037 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6038 
6039 	/* pointer to stack or null */
6040 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6041 
6042 	/* unused */
6043 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6044 	return 0;
6045 }
6046 
6047 static int set_callee_state(struct bpf_verifier_env *env,
6048 			    struct bpf_func_state *caller,
6049 			    struct bpf_func_state *callee, int insn_idx)
6050 {
6051 	int i;
6052 
6053 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6054 	 * pointers, which connects us up to the liveness chain
6055 	 */
6056 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6057 		callee->regs[i] = caller->regs[i];
6058 	return 0;
6059 }
6060 
6061 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6062 			   int *insn_idx)
6063 {
6064 	int subprog, target_insn;
6065 
6066 	target_insn = *insn_idx + insn->imm + 1;
6067 	subprog = find_subprog(env, target_insn);
6068 	if (subprog < 0) {
6069 		verbose(env, "verifier bug. No program starts at insn %d\n",
6070 			target_insn);
6071 		return -EFAULT;
6072 	}
6073 
6074 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6075 }
6076 
6077 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6078 				       struct bpf_func_state *caller,
6079 				       struct bpf_func_state *callee,
6080 				       int insn_idx)
6081 {
6082 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6083 	struct bpf_map *map;
6084 	int err;
6085 
6086 	if (bpf_map_ptr_poisoned(insn_aux)) {
6087 		verbose(env, "tail_call abusing map_ptr\n");
6088 		return -EINVAL;
6089 	}
6090 
6091 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6092 	if (!map->ops->map_set_for_each_callback_args ||
6093 	    !map->ops->map_for_each_callback) {
6094 		verbose(env, "callback function not allowed for map\n");
6095 		return -ENOTSUPP;
6096 	}
6097 
6098 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6099 	if (err)
6100 		return err;
6101 
6102 	callee->in_callback_fn = true;
6103 	return 0;
6104 }
6105 
6106 static int set_timer_callback_state(struct bpf_verifier_env *env,
6107 				    struct bpf_func_state *caller,
6108 				    struct bpf_func_state *callee,
6109 				    int insn_idx)
6110 {
6111 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6112 
6113 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6114 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6115 	 */
6116 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6117 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6118 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6119 
6120 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6121 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6122 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6123 
6124 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6125 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6126 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6127 
6128 	/* unused */
6129 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6130 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6131 	callee->in_async_callback_fn = true;
6132 	return 0;
6133 }
6134 
6135 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6136 				       struct bpf_func_state *caller,
6137 				       struct bpf_func_state *callee,
6138 				       int insn_idx)
6139 {
6140 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6141 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6142 	 * (callback_fn)(struct task_struct *task,
6143 	 *               struct vm_area_struct *vma, void *callback_ctx);
6144 	 */
6145 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6146 
6147 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6148 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6149 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6150 	callee->regs[BPF_REG_2].btf_id = btf_task_struct_ids[2];
6151 
6152 	/* pointer to stack or null */
6153 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6154 
6155 	/* unused */
6156 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6157 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6158 	callee->in_callback_fn = true;
6159 	return 0;
6160 }
6161 
6162 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6163 {
6164 	struct bpf_verifier_state *state = env->cur_state;
6165 	struct bpf_func_state *caller, *callee;
6166 	struct bpf_reg_state *r0;
6167 	int err;
6168 
6169 	callee = state->frame[state->curframe];
6170 	r0 = &callee->regs[BPF_REG_0];
6171 	if (r0->type == PTR_TO_STACK) {
6172 		/* technically it's ok to return caller's stack pointer
6173 		 * (or caller's caller's pointer) back to the caller,
6174 		 * since these pointers are valid. Only current stack
6175 		 * pointer will be invalid as soon as function exits,
6176 		 * but let's be conservative
6177 		 */
6178 		verbose(env, "cannot return stack pointer to the caller\n");
6179 		return -EINVAL;
6180 	}
6181 
6182 	state->curframe--;
6183 	caller = state->frame[state->curframe];
6184 	if (callee->in_callback_fn) {
6185 		/* enforce R0 return value range [0, 1]. */
6186 		struct tnum range = tnum_range(0, 1);
6187 
6188 		if (r0->type != SCALAR_VALUE) {
6189 			verbose(env, "R0 not a scalar value\n");
6190 			return -EACCES;
6191 		}
6192 		if (!tnum_in(range, r0->var_off)) {
6193 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6194 			return -EINVAL;
6195 		}
6196 	} else {
6197 		/* return to the caller whatever r0 had in the callee */
6198 		caller->regs[BPF_REG_0] = *r0;
6199 	}
6200 
6201 	/* Transfer references to the caller */
6202 	err = copy_reference_state(caller, callee);
6203 	if (err)
6204 		return err;
6205 
6206 	*insn_idx = callee->callsite + 1;
6207 	if (env->log.level & BPF_LOG_LEVEL) {
6208 		verbose(env, "returning from callee:\n");
6209 		print_verifier_state(env, callee);
6210 		verbose(env, "to caller at %d:\n", *insn_idx);
6211 		print_verifier_state(env, caller);
6212 	}
6213 	/* clear everything in the callee */
6214 	free_func_state(callee);
6215 	state->frame[state->curframe + 1] = NULL;
6216 	return 0;
6217 }
6218 
6219 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6220 				   int func_id,
6221 				   struct bpf_call_arg_meta *meta)
6222 {
6223 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6224 
6225 	if (ret_type != RET_INTEGER ||
6226 	    (func_id != BPF_FUNC_get_stack &&
6227 	     func_id != BPF_FUNC_get_task_stack &&
6228 	     func_id != BPF_FUNC_probe_read_str &&
6229 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6230 	     func_id != BPF_FUNC_probe_read_user_str))
6231 		return;
6232 
6233 	ret_reg->smax_value = meta->msize_max_value;
6234 	ret_reg->s32_max_value = meta->msize_max_value;
6235 	ret_reg->smin_value = -MAX_ERRNO;
6236 	ret_reg->s32_min_value = -MAX_ERRNO;
6237 	__reg_deduce_bounds(ret_reg);
6238 	__reg_bound_offset(ret_reg);
6239 	__update_reg_bounds(ret_reg);
6240 }
6241 
6242 static int
6243 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6244 		int func_id, int insn_idx)
6245 {
6246 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6247 	struct bpf_map *map = meta->map_ptr;
6248 
6249 	if (func_id != BPF_FUNC_tail_call &&
6250 	    func_id != BPF_FUNC_map_lookup_elem &&
6251 	    func_id != BPF_FUNC_map_update_elem &&
6252 	    func_id != BPF_FUNC_map_delete_elem &&
6253 	    func_id != BPF_FUNC_map_push_elem &&
6254 	    func_id != BPF_FUNC_map_pop_elem &&
6255 	    func_id != BPF_FUNC_map_peek_elem &&
6256 	    func_id != BPF_FUNC_for_each_map_elem &&
6257 	    func_id != BPF_FUNC_redirect_map)
6258 		return 0;
6259 
6260 	if (map == NULL) {
6261 		verbose(env, "kernel subsystem misconfigured verifier\n");
6262 		return -EINVAL;
6263 	}
6264 
6265 	/* In case of read-only, some additional restrictions
6266 	 * need to be applied in order to prevent altering the
6267 	 * state of the map from program side.
6268 	 */
6269 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6270 	    (func_id == BPF_FUNC_map_delete_elem ||
6271 	     func_id == BPF_FUNC_map_update_elem ||
6272 	     func_id == BPF_FUNC_map_push_elem ||
6273 	     func_id == BPF_FUNC_map_pop_elem)) {
6274 		verbose(env, "write into map forbidden\n");
6275 		return -EACCES;
6276 	}
6277 
6278 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6279 		bpf_map_ptr_store(aux, meta->map_ptr,
6280 				  !meta->map_ptr->bypass_spec_v1);
6281 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6282 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6283 				  !meta->map_ptr->bypass_spec_v1);
6284 	return 0;
6285 }
6286 
6287 static int
6288 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6289 		int func_id, int insn_idx)
6290 {
6291 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6292 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6293 	struct bpf_map *map = meta->map_ptr;
6294 	struct tnum range;
6295 	u64 val;
6296 	int err;
6297 
6298 	if (func_id != BPF_FUNC_tail_call)
6299 		return 0;
6300 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6301 		verbose(env, "kernel subsystem misconfigured verifier\n");
6302 		return -EINVAL;
6303 	}
6304 
6305 	range = tnum_range(0, map->max_entries - 1);
6306 	reg = &regs[BPF_REG_3];
6307 
6308 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6309 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6310 		return 0;
6311 	}
6312 
6313 	err = mark_chain_precision(env, BPF_REG_3);
6314 	if (err)
6315 		return err;
6316 
6317 	val = reg->var_off.value;
6318 	if (bpf_map_key_unseen(aux))
6319 		bpf_map_key_store(aux, val);
6320 	else if (!bpf_map_key_poisoned(aux) &&
6321 		  bpf_map_key_immediate(aux) != val)
6322 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6323 	return 0;
6324 }
6325 
6326 static int check_reference_leak(struct bpf_verifier_env *env)
6327 {
6328 	struct bpf_func_state *state = cur_func(env);
6329 	int i;
6330 
6331 	for (i = 0; i < state->acquired_refs; i++) {
6332 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6333 			state->refs[i].id, state->refs[i].insn_idx);
6334 	}
6335 	return state->acquired_refs ? -EINVAL : 0;
6336 }
6337 
6338 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6339 				   struct bpf_reg_state *regs)
6340 {
6341 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6342 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6343 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6344 	int err, fmt_map_off, num_args;
6345 	u64 fmt_addr;
6346 	char *fmt;
6347 
6348 	/* data must be an array of u64 */
6349 	if (data_len_reg->var_off.value % 8)
6350 		return -EINVAL;
6351 	num_args = data_len_reg->var_off.value / 8;
6352 
6353 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6354 	 * and map_direct_value_addr is set.
6355 	 */
6356 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6357 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6358 						  fmt_map_off);
6359 	if (err) {
6360 		verbose(env, "verifier bug\n");
6361 		return -EFAULT;
6362 	}
6363 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6364 
6365 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6366 	 * can focus on validating the format specifiers.
6367 	 */
6368 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6369 	if (err < 0)
6370 		verbose(env, "Invalid format string\n");
6371 
6372 	return err;
6373 }
6374 
6375 static int check_get_func_ip(struct bpf_verifier_env *env)
6376 {
6377 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6378 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6379 	int func_id = BPF_FUNC_get_func_ip;
6380 
6381 	if (type == BPF_PROG_TYPE_TRACING) {
6382 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6383 		    eatype != BPF_MODIFY_RETURN) {
6384 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6385 				func_id_name(func_id), func_id);
6386 			return -ENOTSUPP;
6387 		}
6388 		return 0;
6389 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6390 		return 0;
6391 	}
6392 
6393 	verbose(env, "func %s#%d not supported for program type %d\n",
6394 		func_id_name(func_id), func_id, type);
6395 	return -ENOTSUPP;
6396 }
6397 
6398 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6399 			     int *insn_idx_p)
6400 {
6401 	const struct bpf_func_proto *fn = NULL;
6402 	struct bpf_reg_state *regs;
6403 	struct bpf_call_arg_meta meta;
6404 	int insn_idx = *insn_idx_p;
6405 	bool changes_data;
6406 	int i, err, func_id;
6407 
6408 	/* find function prototype */
6409 	func_id = insn->imm;
6410 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6411 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6412 			func_id);
6413 		return -EINVAL;
6414 	}
6415 
6416 	if (env->ops->get_func_proto)
6417 		fn = env->ops->get_func_proto(func_id, env->prog);
6418 	if (!fn) {
6419 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6420 			func_id);
6421 		return -EINVAL;
6422 	}
6423 
6424 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6425 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6426 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6427 		return -EINVAL;
6428 	}
6429 
6430 	if (fn->allowed && !fn->allowed(env->prog)) {
6431 		verbose(env, "helper call is not allowed in probe\n");
6432 		return -EINVAL;
6433 	}
6434 
6435 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6436 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6437 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6438 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6439 			func_id_name(func_id), func_id);
6440 		return -EINVAL;
6441 	}
6442 
6443 	memset(&meta, 0, sizeof(meta));
6444 	meta.pkt_access = fn->pkt_access;
6445 
6446 	err = check_func_proto(fn, func_id);
6447 	if (err) {
6448 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6449 			func_id_name(func_id), func_id);
6450 		return err;
6451 	}
6452 
6453 	meta.func_id = func_id;
6454 	/* check args */
6455 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6456 		err = check_func_arg(env, i, &meta, fn);
6457 		if (err)
6458 			return err;
6459 	}
6460 
6461 	err = record_func_map(env, &meta, func_id, insn_idx);
6462 	if (err)
6463 		return err;
6464 
6465 	err = record_func_key(env, &meta, func_id, insn_idx);
6466 	if (err)
6467 		return err;
6468 
6469 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6470 	 * is inferred from register state.
6471 	 */
6472 	for (i = 0; i < meta.access_size; i++) {
6473 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6474 				       BPF_WRITE, -1, false);
6475 		if (err)
6476 			return err;
6477 	}
6478 
6479 	if (func_id == BPF_FUNC_tail_call) {
6480 		err = check_reference_leak(env);
6481 		if (err) {
6482 			verbose(env, "tail_call would lead to reference leak\n");
6483 			return err;
6484 		}
6485 	} else if (is_release_function(func_id)) {
6486 		err = release_reference(env, meta.ref_obj_id);
6487 		if (err) {
6488 			verbose(env, "func %s#%d reference has not been acquired before\n",
6489 				func_id_name(func_id), func_id);
6490 			return err;
6491 		}
6492 	}
6493 
6494 	regs = cur_regs(env);
6495 
6496 	/* check that flags argument in get_local_storage(map, flags) is 0,
6497 	 * this is required because get_local_storage() can't return an error.
6498 	 */
6499 	if (func_id == BPF_FUNC_get_local_storage &&
6500 	    !register_is_null(&regs[BPF_REG_2])) {
6501 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6502 		return -EINVAL;
6503 	}
6504 
6505 	if (func_id == BPF_FUNC_for_each_map_elem) {
6506 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6507 					set_map_elem_callback_state);
6508 		if (err < 0)
6509 			return -EINVAL;
6510 	}
6511 
6512 	if (func_id == BPF_FUNC_timer_set_callback) {
6513 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6514 					set_timer_callback_state);
6515 		if (err < 0)
6516 			return -EINVAL;
6517 	}
6518 
6519 	if (func_id == BPF_FUNC_find_vma) {
6520 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6521 					set_find_vma_callback_state);
6522 		if (err < 0)
6523 			return -EINVAL;
6524 	}
6525 
6526 	if (func_id == BPF_FUNC_snprintf) {
6527 		err = check_bpf_snprintf_call(env, regs);
6528 		if (err < 0)
6529 			return err;
6530 	}
6531 
6532 	/* reset caller saved regs */
6533 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6534 		mark_reg_not_init(env, regs, caller_saved[i]);
6535 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6536 	}
6537 
6538 	/* helper call returns 64-bit value. */
6539 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6540 
6541 	/* update return register (already marked as written above) */
6542 	if (fn->ret_type == RET_INTEGER) {
6543 		/* sets type to SCALAR_VALUE */
6544 		mark_reg_unknown(env, regs, BPF_REG_0);
6545 	} else if (fn->ret_type == RET_VOID) {
6546 		regs[BPF_REG_0].type = NOT_INIT;
6547 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6548 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6549 		/* There is no offset yet applied, variable or fixed */
6550 		mark_reg_known_zero(env, regs, BPF_REG_0);
6551 		/* remember map_ptr, so that check_map_access()
6552 		 * can check 'value_size' boundary of memory access
6553 		 * to map element returned from bpf_map_lookup_elem()
6554 		 */
6555 		if (meta.map_ptr == NULL) {
6556 			verbose(env,
6557 				"kernel subsystem misconfigured verifier\n");
6558 			return -EINVAL;
6559 		}
6560 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6561 		regs[BPF_REG_0].map_uid = meta.map_uid;
6562 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6563 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6564 			if (map_value_has_spin_lock(meta.map_ptr))
6565 				regs[BPF_REG_0].id = ++env->id_gen;
6566 		} else {
6567 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6568 		}
6569 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6570 		mark_reg_known_zero(env, regs, BPF_REG_0);
6571 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6572 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6573 		mark_reg_known_zero(env, regs, BPF_REG_0);
6574 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6575 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6576 		mark_reg_known_zero(env, regs, BPF_REG_0);
6577 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6578 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6579 		mark_reg_known_zero(env, regs, BPF_REG_0);
6580 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6581 		regs[BPF_REG_0].mem_size = meta.mem_size;
6582 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6583 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6584 		const struct btf_type *t;
6585 
6586 		mark_reg_known_zero(env, regs, BPF_REG_0);
6587 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6588 		if (!btf_type_is_struct(t)) {
6589 			u32 tsize;
6590 			const struct btf_type *ret;
6591 			const char *tname;
6592 
6593 			/* resolve the type size of ksym. */
6594 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6595 			if (IS_ERR(ret)) {
6596 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6597 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6598 					tname, PTR_ERR(ret));
6599 				return -EINVAL;
6600 			}
6601 			regs[BPF_REG_0].type =
6602 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6603 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6604 			regs[BPF_REG_0].mem_size = tsize;
6605 		} else {
6606 			regs[BPF_REG_0].type =
6607 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6608 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6609 			regs[BPF_REG_0].btf = meta.ret_btf;
6610 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6611 		}
6612 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6613 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
6614 		int ret_btf_id;
6615 
6616 		mark_reg_known_zero(env, regs, BPF_REG_0);
6617 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6618 						     PTR_TO_BTF_ID :
6619 						     PTR_TO_BTF_ID_OR_NULL;
6620 		ret_btf_id = *fn->ret_btf_id;
6621 		if (ret_btf_id == 0) {
6622 			verbose(env, "invalid return type %d of func %s#%d\n",
6623 				fn->ret_type, func_id_name(func_id), func_id);
6624 			return -EINVAL;
6625 		}
6626 		/* current BPF helper definitions are only coming from
6627 		 * built-in code with type IDs from  vmlinux BTF
6628 		 */
6629 		regs[BPF_REG_0].btf = btf_vmlinux;
6630 		regs[BPF_REG_0].btf_id = ret_btf_id;
6631 	} else {
6632 		verbose(env, "unknown return type %d of func %s#%d\n",
6633 			fn->ret_type, func_id_name(func_id), func_id);
6634 		return -EINVAL;
6635 	}
6636 
6637 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
6638 		regs[BPF_REG_0].id = ++env->id_gen;
6639 
6640 	if (is_ptr_cast_function(func_id)) {
6641 		/* For release_reference() */
6642 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6643 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6644 		int id = acquire_reference_state(env, insn_idx);
6645 
6646 		if (id < 0)
6647 			return id;
6648 		/* For mark_ptr_or_null_reg() */
6649 		regs[BPF_REG_0].id = id;
6650 		/* For release_reference() */
6651 		regs[BPF_REG_0].ref_obj_id = id;
6652 	}
6653 
6654 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6655 
6656 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6657 	if (err)
6658 		return err;
6659 
6660 	if ((func_id == BPF_FUNC_get_stack ||
6661 	     func_id == BPF_FUNC_get_task_stack) &&
6662 	    !env->prog->has_callchain_buf) {
6663 		const char *err_str;
6664 
6665 #ifdef CONFIG_PERF_EVENTS
6666 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6667 		err_str = "cannot get callchain buffer for func %s#%d\n";
6668 #else
6669 		err = -ENOTSUPP;
6670 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6671 #endif
6672 		if (err) {
6673 			verbose(env, err_str, func_id_name(func_id), func_id);
6674 			return err;
6675 		}
6676 
6677 		env->prog->has_callchain_buf = true;
6678 	}
6679 
6680 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6681 		env->prog->call_get_stack = true;
6682 
6683 	if (func_id == BPF_FUNC_get_func_ip) {
6684 		if (check_get_func_ip(env))
6685 			return -ENOTSUPP;
6686 		env->prog->call_get_func_ip = true;
6687 	}
6688 
6689 	if (changes_data)
6690 		clear_all_pkt_pointers(env);
6691 	return 0;
6692 }
6693 
6694 /* mark_btf_func_reg_size() is used when the reg size is determined by
6695  * the BTF func_proto's return value size and argument.
6696  */
6697 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6698 				   size_t reg_size)
6699 {
6700 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6701 
6702 	if (regno == BPF_REG_0) {
6703 		/* Function return value */
6704 		reg->live |= REG_LIVE_WRITTEN;
6705 		reg->subreg_def = reg_size == sizeof(u64) ?
6706 			DEF_NOT_SUBREG : env->insn_idx + 1;
6707 	} else {
6708 		/* Function argument */
6709 		if (reg_size == sizeof(u64)) {
6710 			mark_insn_zext(env, reg);
6711 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6712 		} else {
6713 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6714 		}
6715 	}
6716 }
6717 
6718 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6719 {
6720 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6721 	struct bpf_reg_state *regs = cur_regs(env);
6722 	const char *func_name, *ptr_type_name;
6723 	u32 i, nargs, func_id, ptr_type_id;
6724 	struct module *btf_mod = NULL;
6725 	const struct btf_param *args;
6726 	struct btf *desc_btf;
6727 	int err;
6728 
6729 	/* skip for now, but return error when we find this in fixup_kfunc_call */
6730 	if (!insn->imm)
6731 		return 0;
6732 
6733 	desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod);
6734 	if (IS_ERR(desc_btf))
6735 		return PTR_ERR(desc_btf);
6736 
6737 	func_id = insn->imm;
6738 	func = btf_type_by_id(desc_btf, func_id);
6739 	func_name = btf_name_by_offset(desc_btf, func->name_off);
6740 	func_proto = btf_type_by_id(desc_btf, func->type);
6741 
6742 	if (!env->ops->check_kfunc_call ||
6743 	    !env->ops->check_kfunc_call(func_id, btf_mod)) {
6744 		verbose(env, "calling kernel function %s is not allowed\n",
6745 			func_name);
6746 		return -EACCES;
6747 	}
6748 
6749 	/* Check the arguments */
6750 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
6751 	if (err)
6752 		return err;
6753 
6754 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6755 		mark_reg_not_init(env, regs, caller_saved[i]);
6756 
6757 	/* Check return type */
6758 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
6759 	if (btf_type_is_scalar(t)) {
6760 		mark_reg_unknown(env, regs, BPF_REG_0);
6761 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6762 	} else if (btf_type_is_ptr(t)) {
6763 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
6764 						   &ptr_type_id);
6765 		if (!btf_type_is_struct(ptr_type)) {
6766 			ptr_type_name = btf_name_by_offset(desc_btf,
6767 							   ptr_type->name_off);
6768 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6769 				func_name, btf_type_str(ptr_type),
6770 				ptr_type_name);
6771 			return -EINVAL;
6772 		}
6773 		mark_reg_known_zero(env, regs, BPF_REG_0);
6774 		regs[BPF_REG_0].btf = desc_btf;
6775 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6776 		regs[BPF_REG_0].btf_id = ptr_type_id;
6777 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6778 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6779 
6780 	nargs = btf_type_vlen(func_proto);
6781 	args = (const struct btf_param *)(func_proto + 1);
6782 	for (i = 0; i < nargs; i++) {
6783 		u32 regno = i + 1;
6784 
6785 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
6786 		if (btf_type_is_ptr(t))
6787 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6788 		else
6789 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6790 			mark_btf_func_reg_size(env, regno, t->size);
6791 	}
6792 
6793 	return 0;
6794 }
6795 
6796 static bool signed_add_overflows(s64 a, s64 b)
6797 {
6798 	/* Do the add in u64, where overflow is well-defined */
6799 	s64 res = (s64)((u64)a + (u64)b);
6800 
6801 	if (b < 0)
6802 		return res > a;
6803 	return res < a;
6804 }
6805 
6806 static bool signed_add32_overflows(s32 a, s32 b)
6807 {
6808 	/* Do the add in u32, where overflow is well-defined */
6809 	s32 res = (s32)((u32)a + (u32)b);
6810 
6811 	if (b < 0)
6812 		return res > a;
6813 	return res < a;
6814 }
6815 
6816 static bool signed_sub_overflows(s64 a, s64 b)
6817 {
6818 	/* Do the sub in u64, where overflow is well-defined */
6819 	s64 res = (s64)((u64)a - (u64)b);
6820 
6821 	if (b < 0)
6822 		return res < a;
6823 	return res > a;
6824 }
6825 
6826 static bool signed_sub32_overflows(s32 a, s32 b)
6827 {
6828 	/* Do the sub in u32, where overflow is well-defined */
6829 	s32 res = (s32)((u32)a - (u32)b);
6830 
6831 	if (b < 0)
6832 		return res < a;
6833 	return res > a;
6834 }
6835 
6836 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6837 				  const struct bpf_reg_state *reg,
6838 				  enum bpf_reg_type type)
6839 {
6840 	bool known = tnum_is_const(reg->var_off);
6841 	s64 val = reg->var_off.value;
6842 	s64 smin = reg->smin_value;
6843 
6844 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6845 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6846 			reg_type_str[type], val);
6847 		return false;
6848 	}
6849 
6850 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6851 		verbose(env, "%s pointer offset %d is not allowed\n",
6852 			reg_type_str[type], reg->off);
6853 		return false;
6854 	}
6855 
6856 	if (smin == S64_MIN) {
6857 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6858 			reg_type_str[type]);
6859 		return false;
6860 	}
6861 
6862 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6863 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6864 			smin, reg_type_str[type]);
6865 		return false;
6866 	}
6867 
6868 	return true;
6869 }
6870 
6871 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6872 {
6873 	return &env->insn_aux_data[env->insn_idx];
6874 }
6875 
6876 enum {
6877 	REASON_BOUNDS	= -1,
6878 	REASON_TYPE	= -2,
6879 	REASON_PATHS	= -3,
6880 	REASON_LIMIT	= -4,
6881 	REASON_STACK	= -5,
6882 };
6883 
6884 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6885 			      u32 *alu_limit, bool mask_to_left)
6886 {
6887 	u32 max = 0, ptr_limit = 0;
6888 
6889 	switch (ptr_reg->type) {
6890 	case PTR_TO_STACK:
6891 		/* Offset 0 is out-of-bounds, but acceptable start for the
6892 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6893 		 * offset where we would need to deal with min/max bounds is
6894 		 * currently prohibited for unprivileged.
6895 		 */
6896 		max = MAX_BPF_STACK + mask_to_left;
6897 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6898 		break;
6899 	case PTR_TO_MAP_VALUE:
6900 		max = ptr_reg->map_ptr->value_size;
6901 		ptr_limit = (mask_to_left ?
6902 			     ptr_reg->smin_value :
6903 			     ptr_reg->umax_value) + ptr_reg->off;
6904 		break;
6905 	default:
6906 		return REASON_TYPE;
6907 	}
6908 
6909 	if (ptr_limit >= max)
6910 		return REASON_LIMIT;
6911 	*alu_limit = ptr_limit;
6912 	return 0;
6913 }
6914 
6915 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6916 				    const struct bpf_insn *insn)
6917 {
6918 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6919 }
6920 
6921 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6922 				       u32 alu_state, u32 alu_limit)
6923 {
6924 	/* If we arrived here from different branches with different
6925 	 * state or limits to sanitize, then this won't work.
6926 	 */
6927 	if (aux->alu_state &&
6928 	    (aux->alu_state != alu_state ||
6929 	     aux->alu_limit != alu_limit))
6930 		return REASON_PATHS;
6931 
6932 	/* Corresponding fixup done in do_misc_fixups(). */
6933 	aux->alu_state = alu_state;
6934 	aux->alu_limit = alu_limit;
6935 	return 0;
6936 }
6937 
6938 static int sanitize_val_alu(struct bpf_verifier_env *env,
6939 			    struct bpf_insn *insn)
6940 {
6941 	struct bpf_insn_aux_data *aux = cur_aux(env);
6942 
6943 	if (can_skip_alu_sanitation(env, insn))
6944 		return 0;
6945 
6946 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6947 }
6948 
6949 static bool sanitize_needed(u8 opcode)
6950 {
6951 	return opcode == BPF_ADD || opcode == BPF_SUB;
6952 }
6953 
6954 struct bpf_sanitize_info {
6955 	struct bpf_insn_aux_data aux;
6956 	bool mask_to_left;
6957 };
6958 
6959 static struct bpf_verifier_state *
6960 sanitize_speculative_path(struct bpf_verifier_env *env,
6961 			  const struct bpf_insn *insn,
6962 			  u32 next_idx, u32 curr_idx)
6963 {
6964 	struct bpf_verifier_state *branch;
6965 	struct bpf_reg_state *regs;
6966 
6967 	branch = push_stack(env, next_idx, curr_idx, true);
6968 	if (branch && insn) {
6969 		regs = branch->frame[branch->curframe]->regs;
6970 		if (BPF_SRC(insn->code) == BPF_K) {
6971 			mark_reg_unknown(env, regs, insn->dst_reg);
6972 		} else if (BPF_SRC(insn->code) == BPF_X) {
6973 			mark_reg_unknown(env, regs, insn->dst_reg);
6974 			mark_reg_unknown(env, regs, insn->src_reg);
6975 		}
6976 	}
6977 	return branch;
6978 }
6979 
6980 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6981 			    struct bpf_insn *insn,
6982 			    const struct bpf_reg_state *ptr_reg,
6983 			    const struct bpf_reg_state *off_reg,
6984 			    struct bpf_reg_state *dst_reg,
6985 			    struct bpf_sanitize_info *info,
6986 			    const bool commit_window)
6987 {
6988 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6989 	struct bpf_verifier_state *vstate = env->cur_state;
6990 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6991 	bool off_is_neg = off_reg->smin_value < 0;
6992 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6993 	u8 opcode = BPF_OP(insn->code);
6994 	u32 alu_state, alu_limit;
6995 	struct bpf_reg_state tmp;
6996 	bool ret;
6997 	int err;
6998 
6999 	if (can_skip_alu_sanitation(env, insn))
7000 		return 0;
7001 
7002 	/* We already marked aux for masking from non-speculative
7003 	 * paths, thus we got here in the first place. We only care
7004 	 * to explore bad access from here.
7005 	 */
7006 	if (vstate->speculative)
7007 		goto do_sim;
7008 
7009 	if (!commit_window) {
7010 		if (!tnum_is_const(off_reg->var_off) &&
7011 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7012 			return REASON_BOUNDS;
7013 
7014 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7015 				     (opcode == BPF_SUB && !off_is_neg);
7016 	}
7017 
7018 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7019 	if (err < 0)
7020 		return err;
7021 
7022 	if (commit_window) {
7023 		/* In commit phase we narrow the masking window based on
7024 		 * the observed pointer move after the simulated operation.
7025 		 */
7026 		alu_state = info->aux.alu_state;
7027 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7028 	} else {
7029 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7030 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7031 		alu_state |= ptr_is_dst_reg ?
7032 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7033 
7034 		/* Limit pruning on unknown scalars to enable deep search for
7035 		 * potential masking differences from other program paths.
7036 		 */
7037 		if (!off_is_imm)
7038 			env->explore_alu_limits = true;
7039 	}
7040 
7041 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7042 	if (err < 0)
7043 		return err;
7044 do_sim:
7045 	/* If we're in commit phase, we're done here given we already
7046 	 * pushed the truncated dst_reg into the speculative verification
7047 	 * stack.
7048 	 *
7049 	 * Also, when register is a known constant, we rewrite register-based
7050 	 * operation to immediate-based, and thus do not need masking (and as
7051 	 * a consequence, do not need to simulate the zero-truncation either).
7052 	 */
7053 	if (commit_window || off_is_imm)
7054 		return 0;
7055 
7056 	/* Simulate and find potential out-of-bounds access under
7057 	 * speculative execution from truncation as a result of
7058 	 * masking when off was not within expected range. If off
7059 	 * sits in dst, then we temporarily need to move ptr there
7060 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7061 	 * for cases where we use K-based arithmetic in one direction
7062 	 * and truncated reg-based in the other in order to explore
7063 	 * bad access.
7064 	 */
7065 	if (!ptr_is_dst_reg) {
7066 		tmp = *dst_reg;
7067 		*dst_reg = *ptr_reg;
7068 	}
7069 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7070 					env->insn_idx);
7071 	if (!ptr_is_dst_reg && ret)
7072 		*dst_reg = tmp;
7073 	return !ret ? REASON_STACK : 0;
7074 }
7075 
7076 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7077 {
7078 	struct bpf_verifier_state *vstate = env->cur_state;
7079 
7080 	/* If we simulate paths under speculation, we don't update the
7081 	 * insn as 'seen' such that when we verify unreachable paths in
7082 	 * the non-speculative domain, sanitize_dead_code() can still
7083 	 * rewrite/sanitize them.
7084 	 */
7085 	if (!vstate->speculative)
7086 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7087 }
7088 
7089 static int sanitize_err(struct bpf_verifier_env *env,
7090 			const struct bpf_insn *insn, int reason,
7091 			const struct bpf_reg_state *off_reg,
7092 			const struct bpf_reg_state *dst_reg)
7093 {
7094 	static const char *err = "pointer arithmetic with it prohibited for !root";
7095 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7096 	u32 dst = insn->dst_reg, src = insn->src_reg;
7097 
7098 	switch (reason) {
7099 	case REASON_BOUNDS:
7100 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7101 			off_reg == dst_reg ? dst : src, err);
7102 		break;
7103 	case REASON_TYPE:
7104 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7105 			off_reg == dst_reg ? src : dst, err);
7106 		break;
7107 	case REASON_PATHS:
7108 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7109 			dst, op, err);
7110 		break;
7111 	case REASON_LIMIT:
7112 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7113 			dst, op, err);
7114 		break;
7115 	case REASON_STACK:
7116 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7117 			dst, err);
7118 		break;
7119 	default:
7120 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7121 			reason);
7122 		break;
7123 	}
7124 
7125 	return -EACCES;
7126 }
7127 
7128 /* check that stack access falls within stack limits and that 'reg' doesn't
7129  * have a variable offset.
7130  *
7131  * Variable offset is prohibited for unprivileged mode for simplicity since it
7132  * requires corresponding support in Spectre masking for stack ALU.  See also
7133  * retrieve_ptr_limit().
7134  *
7135  *
7136  * 'off' includes 'reg->off'.
7137  */
7138 static int check_stack_access_for_ptr_arithmetic(
7139 				struct bpf_verifier_env *env,
7140 				int regno,
7141 				const struct bpf_reg_state *reg,
7142 				int off)
7143 {
7144 	if (!tnum_is_const(reg->var_off)) {
7145 		char tn_buf[48];
7146 
7147 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7148 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7149 			regno, tn_buf, off);
7150 		return -EACCES;
7151 	}
7152 
7153 	if (off >= 0 || off < -MAX_BPF_STACK) {
7154 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7155 			"prohibited for !root; off=%d\n", regno, off);
7156 		return -EACCES;
7157 	}
7158 
7159 	return 0;
7160 }
7161 
7162 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7163 				 const struct bpf_insn *insn,
7164 				 const struct bpf_reg_state *dst_reg)
7165 {
7166 	u32 dst = insn->dst_reg;
7167 
7168 	/* For unprivileged we require that resulting offset must be in bounds
7169 	 * in order to be able to sanitize access later on.
7170 	 */
7171 	if (env->bypass_spec_v1)
7172 		return 0;
7173 
7174 	switch (dst_reg->type) {
7175 	case PTR_TO_STACK:
7176 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7177 					dst_reg->off + dst_reg->var_off.value))
7178 			return -EACCES;
7179 		break;
7180 	case PTR_TO_MAP_VALUE:
7181 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7182 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7183 				"prohibited for !root\n", dst);
7184 			return -EACCES;
7185 		}
7186 		break;
7187 	default:
7188 		break;
7189 	}
7190 
7191 	return 0;
7192 }
7193 
7194 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7195  * Caller should also handle BPF_MOV case separately.
7196  * If we return -EACCES, caller may want to try again treating pointer as a
7197  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7198  */
7199 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7200 				   struct bpf_insn *insn,
7201 				   const struct bpf_reg_state *ptr_reg,
7202 				   const struct bpf_reg_state *off_reg)
7203 {
7204 	struct bpf_verifier_state *vstate = env->cur_state;
7205 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7206 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7207 	bool known = tnum_is_const(off_reg->var_off);
7208 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7209 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7210 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7211 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7212 	struct bpf_sanitize_info info = {};
7213 	u8 opcode = BPF_OP(insn->code);
7214 	u32 dst = insn->dst_reg;
7215 	int ret;
7216 
7217 	dst_reg = &regs[dst];
7218 
7219 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7220 	    smin_val > smax_val || umin_val > umax_val) {
7221 		/* Taint dst register if offset had invalid bounds derived from
7222 		 * e.g. dead branches.
7223 		 */
7224 		__mark_reg_unknown(env, dst_reg);
7225 		return 0;
7226 	}
7227 
7228 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7229 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7230 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7231 			__mark_reg_unknown(env, dst_reg);
7232 			return 0;
7233 		}
7234 
7235 		verbose(env,
7236 			"R%d 32-bit pointer arithmetic prohibited\n",
7237 			dst);
7238 		return -EACCES;
7239 	}
7240 
7241 	switch (ptr_reg->type) {
7242 	case PTR_TO_MAP_VALUE_OR_NULL:
7243 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7244 			dst, reg_type_str[ptr_reg->type]);
7245 		return -EACCES;
7246 	case CONST_PTR_TO_MAP:
7247 		/* smin_val represents the known value */
7248 		if (known && smin_val == 0 && opcode == BPF_ADD)
7249 			break;
7250 		fallthrough;
7251 	case PTR_TO_PACKET_END:
7252 	case PTR_TO_SOCKET:
7253 	case PTR_TO_SOCKET_OR_NULL:
7254 	case PTR_TO_SOCK_COMMON:
7255 	case PTR_TO_SOCK_COMMON_OR_NULL:
7256 	case PTR_TO_TCP_SOCK:
7257 	case PTR_TO_TCP_SOCK_OR_NULL:
7258 	case PTR_TO_XDP_SOCK:
7259 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7260 			dst, reg_type_str[ptr_reg->type]);
7261 		return -EACCES;
7262 	default:
7263 		break;
7264 	}
7265 
7266 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7267 	 * The id may be overwritten later if we create a new variable offset.
7268 	 */
7269 	dst_reg->type = ptr_reg->type;
7270 	dst_reg->id = ptr_reg->id;
7271 
7272 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7273 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7274 		return -EINVAL;
7275 
7276 	/* pointer types do not carry 32-bit bounds at the moment. */
7277 	__mark_reg32_unbounded(dst_reg);
7278 
7279 	if (sanitize_needed(opcode)) {
7280 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7281 				       &info, false);
7282 		if (ret < 0)
7283 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7284 	}
7285 
7286 	switch (opcode) {
7287 	case BPF_ADD:
7288 		/* We can take a fixed offset as long as it doesn't overflow
7289 		 * the s32 'off' field
7290 		 */
7291 		if (known && (ptr_reg->off + smin_val ==
7292 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7293 			/* pointer += K.  Accumulate it into fixed offset */
7294 			dst_reg->smin_value = smin_ptr;
7295 			dst_reg->smax_value = smax_ptr;
7296 			dst_reg->umin_value = umin_ptr;
7297 			dst_reg->umax_value = umax_ptr;
7298 			dst_reg->var_off = ptr_reg->var_off;
7299 			dst_reg->off = ptr_reg->off + smin_val;
7300 			dst_reg->raw = ptr_reg->raw;
7301 			break;
7302 		}
7303 		/* A new variable offset is created.  Note that off_reg->off
7304 		 * == 0, since it's a scalar.
7305 		 * dst_reg gets the pointer type and since some positive
7306 		 * integer value was added to the pointer, give it a new 'id'
7307 		 * if it's a PTR_TO_PACKET.
7308 		 * this creates a new 'base' pointer, off_reg (variable) gets
7309 		 * added into the variable offset, and we copy the fixed offset
7310 		 * from ptr_reg.
7311 		 */
7312 		if (signed_add_overflows(smin_ptr, smin_val) ||
7313 		    signed_add_overflows(smax_ptr, smax_val)) {
7314 			dst_reg->smin_value = S64_MIN;
7315 			dst_reg->smax_value = S64_MAX;
7316 		} else {
7317 			dst_reg->smin_value = smin_ptr + smin_val;
7318 			dst_reg->smax_value = smax_ptr + smax_val;
7319 		}
7320 		if (umin_ptr + umin_val < umin_ptr ||
7321 		    umax_ptr + umax_val < umax_ptr) {
7322 			dst_reg->umin_value = 0;
7323 			dst_reg->umax_value = U64_MAX;
7324 		} else {
7325 			dst_reg->umin_value = umin_ptr + umin_val;
7326 			dst_reg->umax_value = umax_ptr + umax_val;
7327 		}
7328 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7329 		dst_reg->off = ptr_reg->off;
7330 		dst_reg->raw = ptr_reg->raw;
7331 		if (reg_is_pkt_pointer(ptr_reg)) {
7332 			dst_reg->id = ++env->id_gen;
7333 			/* something was added to pkt_ptr, set range to zero */
7334 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7335 		}
7336 		break;
7337 	case BPF_SUB:
7338 		if (dst_reg == off_reg) {
7339 			/* scalar -= pointer.  Creates an unknown scalar */
7340 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7341 				dst);
7342 			return -EACCES;
7343 		}
7344 		/* We don't allow subtraction from FP, because (according to
7345 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7346 		 * be able to deal with it.
7347 		 */
7348 		if (ptr_reg->type == PTR_TO_STACK) {
7349 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7350 				dst);
7351 			return -EACCES;
7352 		}
7353 		if (known && (ptr_reg->off - smin_val ==
7354 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7355 			/* pointer -= K.  Subtract it from fixed offset */
7356 			dst_reg->smin_value = smin_ptr;
7357 			dst_reg->smax_value = smax_ptr;
7358 			dst_reg->umin_value = umin_ptr;
7359 			dst_reg->umax_value = umax_ptr;
7360 			dst_reg->var_off = ptr_reg->var_off;
7361 			dst_reg->id = ptr_reg->id;
7362 			dst_reg->off = ptr_reg->off - smin_val;
7363 			dst_reg->raw = ptr_reg->raw;
7364 			break;
7365 		}
7366 		/* A new variable offset is created.  If the subtrahend is known
7367 		 * nonnegative, then any reg->range we had before is still good.
7368 		 */
7369 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7370 		    signed_sub_overflows(smax_ptr, smin_val)) {
7371 			/* Overflow possible, we know nothing */
7372 			dst_reg->smin_value = S64_MIN;
7373 			dst_reg->smax_value = S64_MAX;
7374 		} else {
7375 			dst_reg->smin_value = smin_ptr - smax_val;
7376 			dst_reg->smax_value = smax_ptr - smin_val;
7377 		}
7378 		if (umin_ptr < umax_val) {
7379 			/* Overflow possible, we know nothing */
7380 			dst_reg->umin_value = 0;
7381 			dst_reg->umax_value = U64_MAX;
7382 		} else {
7383 			/* Cannot overflow (as long as bounds are consistent) */
7384 			dst_reg->umin_value = umin_ptr - umax_val;
7385 			dst_reg->umax_value = umax_ptr - umin_val;
7386 		}
7387 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7388 		dst_reg->off = ptr_reg->off;
7389 		dst_reg->raw = ptr_reg->raw;
7390 		if (reg_is_pkt_pointer(ptr_reg)) {
7391 			dst_reg->id = ++env->id_gen;
7392 			/* something was added to pkt_ptr, set range to zero */
7393 			if (smin_val < 0)
7394 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7395 		}
7396 		break;
7397 	case BPF_AND:
7398 	case BPF_OR:
7399 	case BPF_XOR:
7400 		/* bitwise ops on pointers are troublesome, prohibit. */
7401 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7402 			dst, bpf_alu_string[opcode >> 4]);
7403 		return -EACCES;
7404 	default:
7405 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7406 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7407 			dst, bpf_alu_string[opcode >> 4]);
7408 		return -EACCES;
7409 	}
7410 
7411 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7412 		return -EINVAL;
7413 
7414 	__update_reg_bounds(dst_reg);
7415 	__reg_deduce_bounds(dst_reg);
7416 	__reg_bound_offset(dst_reg);
7417 
7418 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7419 		return -EACCES;
7420 	if (sanitize_needed(opcode)) {
7421 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7422 				       &info, true);
7423 		if (ret < 0)
7424 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7425 	}
7426 
7427 	return 0;
7428 }
7429 
7430 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7431 				 struct bpf_reg_state *src_reg)
7432 {
7433 	s32 smin_val = src_reg->s32_min_value;
7434 	s32 smax_val = src_reg->s32_max_value;
7435 	u32 umin_val = src_reg->u32_min_value;
7436 	u32 umax_val = src_reg->u32_max_value;
7437 
7438 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7439 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7440 		dst_reg->s32_min_value = S32_MIN;
7441 		dst_reg->s32_max_value = S32_MAX;
7442 	} else {
7443 		dst_reg->s32_min_value += smin_val;
7444 		dst_reg->s32_max_value += smax_val;
7445 	}
7446 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7447 	    dst_reg->u32_max_value + umax_val < umax_val) {
7448 		dst_reg->u32_min_value = 0;
7449 		dst_reg->u32_max_value = U32_MAX;
7450 	} else {
7451 		dst_reg->u32_min_value += umin_val;
7452 		dst_reg->u32_max_value += umax_val;
7453 	}
7454 }
7455 
7456 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7457 			       struct bpf_reg_state *src_reg)
7458 {
7459 	s64 smin_val = src_reg->smin_value;
7460 	s64 smax_val = src_reg->smax_value;
7461 	u64 umin_val = src_reg->umin_value;
7462 	u64 umax_val = src_reg->umax_value;
7463 
7464 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7465 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7466 		dst_reg->smin_value = S64_MIN;
7467 		dst_reg->smax_value = S64_MAX;
7468 	} else {
7469 		dst_reg->smin_value += smin_val;
7470 		dst_reg->smax_value += smax_val;
7471 	}
7472 	if (dst_reg->umin_value + umin_val < umin_val ||
7473 	    dst_reg->umax_value + umax_val < umax_val) {
7474 		dst_reg->umin_value = 0;
7475 		dst_reg->umax_value = U64_MAX;
7476 	} else {
7477 		dst_reg->umin_value += umin_val;
7478 		dst_reg->umax_value += umax_val;
7479 	}
7480 }
7481 
7482 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7483 				 struct bpf_reg_state *src_reg)
7484 {
7485 	s32 smin_val = src_reg->s32_min_value;
7486 	s32 smax_val = src_reg->s32_max_value;
7487 	u32 umin_val = src_reg->u32_min_value;
7488 	u32 umax_val = src_reg->u32_max_value;
7489 
7490 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7491 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7492 		/* Overflow possible, we know nothing */
7493 		dst_reg->s32_min_value = S32_MIN;
7494 		dst_reg->s32_max_value = S32_MAX;
7495 	} else {
7496 		dst_reg->s32_min_value -= smax_val;
7497 		dst_reg->s32_max_value -= smin_val;
7498 	}
7499 	if (dst_reg->u32_min_value < umax_val) {
7500 		/* Overflow possible, we know nothing */
7501 		dst_reg->u32_min_value = 0;
7502 		dst_reg->u32_max_value = U32_MAX;
7503 	} else {
7504 		/* Cannot overflow (as long as bounds are consistent) */
7505 		dst_reg->u32_min_value -= umax_val;
7506 		dst_reg->u32_max_value -= umin_val;
7507 	}
7508 }
7509 
7510 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7511 			       struct bpf_reg_state *src_reg)
7512 {
7513 	s64 smin_val = src_reg->smin_value;
7514 	s64 smax_val = src_reg->smax_value;
7515 	u64 umin_val = src_reg->umin_value;
7516 	u64 umax_val = src_reg->umax_value;
7517 
7518 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7519 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7520 		/* Overflow possible, we know nothing */
7521 		dst_reg->smin_value = S64_MIN;
7522 		dst_reg->smax_value = S64_MAX;
7523 	} else {
7524 		dst_reg->smin_value -= smax_val;
7525 		dst_reg->smax_value -= smin_val;
7526 	}
7527 	if (dst_reg->umin_value < umax_val) {
7528 		/* Overflow possible, we know nothing */
7529 		dst_reg->umin_value = 0;
7530 		dst_reg->umax_value = U64_MAX;
7531 	} else {
7532 		/* Cannot overflow (as long as bounds are consistent) */
7533 		dst_reg->umin_value -= umax_val;
7534 		dst_reg->umax_value -= umin_val;
7535 	}
7536 }
7537 
7538 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7539 				 struct bpf_reg_state *src_reg)
7540 {
7541 	s32 smin_val = src_reg->s32_min_value;
7542 	u32 umin_val = src_reg->u32_min_value;
7543 	u32 umax_val = src_reg->u32_max_value;
7544 
7545 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7546 		/* Ain't nobody got time to multiply that sign */
7547 		__mark_reg32_unbounded(dst_reg);
7548 		return;
7549 	}
7550 	/* Both values are positive, so we can work with unsigned and
7551 	 * copy the result to signed (unless it exceeds S32_MAX).
7552 	 */
7553 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7554 		/* Potential overflow, we know nothing */
7555 		__mark_reg32_unbounded(dst_reg);
7556 		return;
7557 	}
7558 	dst_reg->u32_min_value *= umin_val;
7559 	dst_reg->u32_max_value *= umax_val;
7560 	if (dst_reg->u32_max_value > S32_MAX) {
7561 		/* Overflow possible, we know nothing */
7562 		dst_reg->s32_min_value = S32_MIN;
7563 		dst_reg->s32_max_value = S32_MAX;
7564 	} else {
7565 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7566 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7567 	}
7568 }
7569 
7570 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7571 			       struct bpf_reg_state *src_reg)
7572 {
7573 	s64 smin_val = src_reg->smin_value;
7574 	u64 umin_val = src_reg->umin_value;
7575 	u64 umax_val = src_reg->umax_value;
7576 
7577 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7578 		/* Ain't nobody got time to multiply that sign */
7579 		__mark_reg64_unbounded(dst_reg);
7580 		return;
7581 	}
7582 	/* Both values are positive, so we can work with unsigned and
7583 	 * copy the result to signed (unless it exceeds S64_MAX).
7584 	 */
7585 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7586 		/* Potential overflow, we know nothing */
7587 		__mark_reg64_unbounded(dst_reg);
7588 		return;
7589 	}
7590 	dst_reg->umin_value *= umin_val;
7591 	dst_reg->umax_value *= umax_val;
7592 	if (dst_reg->umax_value > S64_MAX) {
7593 		/* Overflow possible, we know nothing */
7594 		dst_reg->smin_value = S64_MIN;
7595 		dst_reg->smax_value = S64_MAX;
7596 	} else {
7597 		dst_reg->smin_value = dst_reg->umin_value;
7598 		dst_reg->smax_value = dst_reg->umax_value;
7599 	}
7600 }
7601 
7602 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7603 				 struct bpf_reg_state *src_reg)
7604 {
7605 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7606 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7607 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7608 	s32 smin_val = src_reg->s32_min_value;
7609 	u32 umax_val = src_reg->u32_max_value;
7610 
7611 	if (src_known && dst_known) {
7612 		__mark_reg32_known(dst_reg, var32_off.value);
7613 		return;
7614 	}
7615 
7616 	/* We get our minimum from the var_off, since that's inherently
7617 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7618 	 */
7619 	dst_reg->u32_min_value = var32_off.value;
7620 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7621 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7622 		/* Lose signed bounds when ANDing negative numbers,
7623 		 * ain't nobody got time for that.
7624 		 */
7625 		dst_reg->s32_min_value = S32_MIN;
7626 		dst_reg->s32_max_value = S32_MAX;
7627 	} else {
7628 		/* ANDing two positives gives a positive, so safe to
7629 		 * cast result into s64.
7630 		 */
7631 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7632 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7633 	}
7634 }
7635 
7636 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7637 			       struct bpf_reg_state *src_reg)
7638 {
7639 	bool src_known = tnum_is_const(src_reg->var_off);
7640 	bool dst_known = tnum_is_const(dst_reg->var_off);
7641 	s64 smin_val = src_reg->smin_value;
7642 	u64 umax_val = src_reg->umax_value;
7643 
7644 	if (src_known && dst_known) {
7645 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7646 		return;
7647 	}
7648 
7649 	/* We get our minimum from the var_off, since that's inherently
7650 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7651 	 */
7652 	dst_reg->umin_value = dst_reg->var_off.value;
7653 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7654 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7655 		/* Lose signed bounds when ANDing negative numbers,
7656 		 * ain't nobody got time for that.
7657 		 */
7658 		dst_reg->smin_value = S64_MIN;
7659 		dst_reg->smax_value = S64_MAX;
7660 	} else {
7661 		/* ANDing two positives gives a positive, so safe to
7662 		 * cast result into s64.
7663 		 */
7664 		dst_reg->smin_value = dst_reg->umin_value;
7665 		dst_reg->smax_value = dst_reg->umax_value;
7666 	}
7667 	/* We may learn something more from the var_off */
7668 	__update_reg_bounds(dst_reg);
7669 }
7670 
7671 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7672 				struct bpf_reg_state *src_reg)
7673 {
7674 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7675 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7676 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7677 	s32 smin_val = src_reg->s32_min_value;
7678 	u32 umin_val = src_reg->u32_min_value;
7679 
7680 	if (src_known && dst_known) {
7681 		__mark_reg32_known(dst_reg, var32_off.value);
7682 		return;
7683 	}
7684 
7685 	/* We get our maximum from the var_off, and our minimum is the
7686 	 * maximum of the operands' minima
7687 	 */
7688 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7689 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7690 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7691 		/* Lose signed bounds when ORing negative numbers,
7692 		 * ain't nobody got time for that.
7693 		 */
7694 		dst_reg->s32_min_value = S32_MIN;
7695 		dst_reg->s32_max_value = S32_MAX;
7696 	} else {
7697 		/* ORing two positives gives a positive, so safe to
7698 		 * cast result into s64.
7699 		 */
7700 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7701 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7702 	}
7703 }
7704 
7705 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7706 			      struct bpf_reg_state *src_reg)
7707 {
7708 	bool src_known = tnum_is_const(src_reg->var_off);
7709 	bool dst_known = tnum_is_const(dst_reg->var_off);
7710 	s64 smin_val = src_reg->smin_value;
7711 	u64 umin_val = src_reg->umin_value;
7712 
7713 	if (src_known && dst_known) {
7714 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7715 		return;
7716 	}
7717 
7718 	/* We get our maximum from the var_off, and our minimum is the
7719 	 * maximum of the operands' minima
7720 	 */
7721 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7722 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7723 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7724 		/* Lose signed bounds when ORing negative numbers,
7725 		 * ain't nobody got time for that.
7726 		 */
7727 		dst_reg->smin_value = S64_MIN;
7728 		dst_reg->smax_value = S64_MAX;
7729 	} else {
7730 		/* ORing two positives gives a positive, so safe to
7731 		 * cast result into s64.
7732 		 */
7733 		dst_reg->smin_value = dst_reg->umin_value;
7734 		dst_reg->smax_value = dst_reg->umax_value;
7735 	}
7736 	/* We may learn something more from the var_off */
7737 	__update_reg_bounds(dst_reg);
7738 }
7739 
7740 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7741 				 struct bpf_reg_state *src_reg)
7742 {
7743 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7744 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7745 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7746 	s32 smin_val = src_reg->s32_min_value;
7747 
7748 	if (src_known && dst_known) {
7749 		__mark_reg32_known(dst_reg, var32_off.value);
7750 		return;
7751 	}
7752 
7753 	/* We get both minimum and maximum from the var32_off. */
7754 	dst_reg->u32_min_value = var32_off.value;
7755 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7756 
7757 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7758 		/* XORing two positive sign numbers gives a positive,
7759 		 * so safe to cast u32 result into s32.
7760 		 */
7761 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7762 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7763 	} else {
7764 		dst_reg->s32_min_value = S32_MIN;
7765 		dst_reg->s32_max_value = S32_MAX;
7766 	}
7767 }
7768 
7769 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7770 			       struct bpf_reg_state *src_reg)
7771 {
7772 	bool src_known = tnum_is_const(src_reg->var_off);
7773 	bool dst_known = tnum_is_const(dst_reg->var_off);
7774 	s64 smin_val = src_reg->smin_value;
7775 
7776 	if (src_known && dst_known) {
7777 		/* dst_reg->var_off.value has been updated earlier */
7778 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7779 		return;
7780 	}
7781 
7782 	/* We get both minimum and maximum from the var_off. */
7783 	dst_reg->umin_value = dst_reg->var_off.value;
7784 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7785 
7786 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7787 		/* XORing two positive sign numbers gives a positive,
7788 		 * so safe to cast u64 result into s64.
7789 		 */
7790 		dst_reg->smin_value = dst_reg->umin_value;
7791 		dst_reg->smax_value = dst_reg->umax_value;
7792 	} else {
7793 		dst_reg->smin_value = S64_MIN;
7794 		dst_reg->smax_value = S64_MAX;
7795 	}
7796 
7797 	__update_reg_bounds(dst_reg);
7798 }
7799 
7800 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7801 				   u64 umin_val, u64 umax_val)
7802 {
7803 	/* We lose all sign bit information (except what we can pick
7804 	 * up from var_off)
7805 	 */
7806 	dst_reg->s32_min_value = S32_MIN;
7807 	dst_reg->s32_max_value = S32_MAX;
7808 	/* If we might shift our top bit out, then we know nothing */
7809 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7810 		dst_reg->u32_min_value = 0;
7811 		dst_reg->u32_max_value = U32_MAX;
7812 	} else {
7813 		dst_reg->u32_min_value <<= umin_val;
7814 		dst_reg->u32_max_value <<= umax_val;
7815 	}
7816 }
7817 
7818 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7819 				 struct bpf_reg_state *src_reg)
7820 {
7821 	u32 umax_val = src_reg->u32_max_value;
7822 	u32 umin_val = src_reg->u32_min_value;
7823 	/* u32 alu operation will zext upper bits */
7824 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7825 
7826 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7827 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7828 	/* Not required but being careful mark reg64 bounds as unknown so
7829 	 * that we are forced to pick them up from tnum and zext later and
7830 	 * if some path skips this step we are still safe.
7831 	 */
7832 	__mark_reg64_unbounded(dst_reg);
7833 	__update_reg32_bounds(dst_reg);
7834 }
7835 
7836 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7837 				   u64 umin_val, u64 umax_val)
7838 {
7839 	/* Special case <<32 because it is a common compiler pattern to sign
7840 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7841 	 * positive we know this shift will also be positive so we can track
7842 	 * bounds correctly. Otherwise we lose all sign bit information except
7843 	 * what we can pick up from var_off. Perhaps we can generalize this
7844 	 * later to shifts of any length.
7845 	 */
7846 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7847 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7848 	else
7849 		dst_reg->smax_value = S64_MAX;
7850 
7851 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7852 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7853 	else
7854 		dst_reg->smin_value = S64_MIN;
7855 
7856 	/* If we might shift our top bit out, then we know nothing */
7857 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7858 		dst_reg->umin_value = 0;
7859 		dst_reg->umax_value = U64_MAX;
7860 	} else {
7861 		dst_reg->umin_value <<= umin_val;
7862 		dst_reg->umax_value <<= umax_val;
7863 	}
7864 }
7865 
7866 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7867 			       struct bpf_reg_state *src_reg)
7868 {
7869 	u64 umax_val = src_reg->umax_value;
7870 	u64 umin_val = src_reg->umin_value;
7871 
7872 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7873 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7874 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7875 
7876 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7877 	/* We may learn something more from the var_off */
7878 	__update_reg_bounds(dst_reg);
7879 }
7880 
7881 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7882 				 struct bpf_reg_state *src_reg)
7883 {
7884 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7885 	u32 umax_val = src_reg->u32_max_value;
7886 	u32 umin_val = src_reg->u32_min_value;
7887 
7888 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7889 	 * be negative, then either:
7890 	 * 1) src_reg might be zero, so the sign bit of the result is
7891 	 *    unknown, so we lose our signed bounds
7892 	 * 2) it's known negative, thus the unsigned bounds capture the
7893 	 *    signed bounds
7894 	 * 3) the signed bounds cross zero, so they tell us nothing
7895 	 *    about the result
7896 	 * If the value in dst_reg is known nonnegative, then again the
7897 	 * unsigned bounds capture the signed bounds.
7898 	 * Thus, in all cases it suffices to blow away our signed bounds
7899 	 * and rely on inferring new ones from the unsigned bounds and
7900 	 * var_off of the result.
7901 	 */
7902 	dst_reg->s32_min_value = S32_MIN;
7903 	dst_reg->s32_max_value = S32_MAX;
7904 
7905 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7906 	dst_reg->u32_min_value >>= umax_val;
7907 	dst_reg->u32_max_value >>= umin_val;
7908 
7909 	__mark_reg64_unbounded(dst_reg);
7910 	__update_reg32_bounds(dst_reg);
7911 }
7912 
7913 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7914 			       struct bpf_reg_state *src_reg)
7915 {
7916 	u64 umax_val = src_reg->umax_value;
7917 	u64 umin_val = src_reg->umin_value;
7918 
7919 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7920 	 * be negative, then either:
7921 	 * 1) src_reg might be zero, so the sign bit of the result is
7922 	 *    unknown, so we lose our signed bounds
7923 	 * 2) it's known negative, thus the unsigned bounds capture the
7924 	 *    signed bounds
7925 	 * 3) the signed bounds cross zero, so they tell us nothing
7926 	 *    about the result
7927 	 * If the value in dst_reg is known nonnegative, then again the
7928 	 * unsigned bounds capture the signed bounds.
7929 	 * Thus, in all cases it suffices to blow away our signed bounds
7930 	 * and rely on inferring new ones from the unsigned bounds and
7931 	 * var_off of the result.
7932 	 */
7933 	dst_reg->smin_value = S64_MIN;
7934 	dst_reg->smax_value = S64_MAX;
7935 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7936 	dst_reg->umin_value >>= umax_val;
7937 	dst_reg->umax_value >>= umin_val;
7938 
7939 	/* Its not easy to operate on alu32 bounds here because it depends
7940 	 * on bits being shifted in. Take easy way out and mark unbounded
7941 	 * so we can recalculate later from tnum.
7942 	 */
7943 	__mark_reg32_unbounded(dst_reg);
7944 	__update_reg_bounds(dst_reg);
7945 }
7946 
7947 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7948 				  struct bpf_reg_state *src_reg)
7949 {
7950 	u64 umin_val = src_reg->u32_min_value;
7951 
7952 	/* Upon reaching here, src_known is true and
7953 	 * umax_val is equal to umin_val.
7954 	 */
7955 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7956 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7957 
7958 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7959 
7960 	/* blow away the dst_reg umin_value/umax_value and rely on
7961 	 * dst_reg var_off to refine the result.
7962 	 */
7963 	dst_reg->u32_min_value = 0;
7964 	dst_reg->u32_max_value = U32_MAX;
7965 
7966 	__mark_reg64_unbounded(dst_reg);
7967 	__update_reg32_bounds(dst_reg);
7968 }
7969 
7970 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7971 				struct bpf_reg_state *src_reg)
7972 {
7973 	u64 umin_val = src_reg->umin_value;
7974 
7975 	/* Upon reaching here, src_known is true and umax_val is equal
7976 	 * to umin_val.
7977 	 */
7978 	dst_reg->smin_value >>= umin_val;
7979 	dst_reg->smax_value >>= umin_val;
7980 
7981 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7982 
7983 	/* blow away the dst_reg umin_value/umax_value and rely on
7984 	 * dst_reg var_off to refine the result.
7985 	 */
7986 	dst_reg->umin_value = 0;
7987 	dst_reg->umax_value = U64_MAX;
7988 
7989 	/* Its not easy to operate on alu32 bounds here because it depends
7990 	 * on bits being shifted in from upper 32-bits. Take easy way out
7991 	 * and mark unbounded so we can recalculate later from tnum.
7992 	 */
7993 	__mark_reg32_unbounded(dst_reg);
7994 	__update_reg_bounds(dst_reg);
7995 }
7996 
7997 /* WARNING: This function does calculations on 64-bit values, but the actual
7998  * execution may occur on 32-bit values. Therefore, things like bitshifts
7999  * need extra checks in the 32-bit case.
8000  */
8001 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8002 				      struct bpf_insn *insn,
8003 				      struct bpf_reg_state *dst_reg,
8004 				      struct bpf_reg_state src_reg)
8005 {
8006 	struct bpf_reg_state *regs = cur_regs(env);
8007 	u8 opcode = BPF_OP(insn->code);
8008 	bool src_known;
8009 	s64 smin_val, smax_val;
8010 	u64 umin_val, umax_val;
8011 	s32 s32_min_val, s32_max_val;
8012 	u32 u32_min_val, u32_max_val;
8013 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8014 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8015 	int ret;
8016 
8017 	smin_val = src_reg.smin_value;
8018 	smax_val = src_reg.smax_value;
8019 	umin_val = src_reg.umin_value;
8020 	umax_val = src_reg.umax_value;
8021 
8022 	s32_min_val = src_reg.s32_min_value;
8023 	s32_max_val = src_reg.s32_max_value;
8024 	u32_min_val = src_reg.u32_min_value;
8025 	u32_max_val = src_reg.u32_max_value;
8026 
8027 	if (alu32) {
8028 		src_known = tnum_subreg_is_const(src_reg.var_off);
8029 		if ((src_known &&
8030 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8031 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8032 			/* Taint dst register if offset had invalid bounds
8033 			 * derived from e.g. dead branches.
8034 			 */
8035 			__mark_reg_unknown(env, dst_reg);
8036 			return 0;
8037 		}
8038 	} else {
8039 		src_known = tnum_is_const(src_reg.var_off);
8040 		if ((src_known &&
8041 		     (smin_val != smax_val || umin_val != umax_val)) ||
8042 		    smin_val > smax_val || umin_val > umax_val) {
8043 			/* Taint dst register if offset had invalid bounds
8044 			 * derived from e.g. dead branches.
8045 			 */
8046 			__mark_reg_unknown(env, dst_reg);
8047 			return 0;
8048 		}
8049 	}
8050 
8051 	if (!src_known &&
8052 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8053 		__mark_reg_unknown(env, dst_reg);
8054 		return 0;
8055 	}
8056 
8057 	if (sanitize_needed(opcode)) {
8058 		ret = sanitize_val_alu(env, insn);
8059 		if (ret < 0)
8060 			return sanitize_err(env, insn, ret, NULL, NULL);
8061 	}
8062 
8063 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8064 	 * There are two classes of instructions: The first class we track both
8065 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8066 	 * greatest amount of precision when alu operations are mixed with jmp32
8067 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8068 	 * and BPF_OR. This is possible because these ops have fairly easy to
8069 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8070 	 * See alu32 verifier tests for examples. The second class of
8071 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8072 	 * with regards to tracking sign/unsigned bounds because the bits may
8073 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8074 	 * the reg unbounded in the subreg bound space and use the resulting
8075 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8076 	 */
8077 	switch (opcode) {
8078 	case BPF_ADD:
8079 		scalar32_min_max_add(dst_reg, &src_reg);
8080 		scalar_min_max_add(dst_reg, &src_reg);
8081 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8082 		break;
8083 	case BPF_SUB:
8084 		scalar32_min_max_sub(dst_reg, &src_reg);
8085 		scalar_min_max_sub(dst_reg, &src_reg);
8086 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8087 		break;
8088 	case BPF_MUL:
8089 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8090 		scalar32_min_max_mul(dst_reg, &src_reg);
8091 		scalar_min_max_mul(dst_reg, &src_reg);
8092 		break;
8093 	case BPF_AND:
8094 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8095 		scalar32_min_max_and(dst_reg, &src_reg);
8096 		scalar_min_max_and(dst_reg, &src_reg);
8097 		break;
8098 	case BPF_OR:
8099 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8100 		scalar32_min_max_or(dst_reg, &src_reg);
8101 		scalar_min_max_or(dst_reg, &src_reg);
8102 		break;
8103 	case BPF_XOR:
8104 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8105 		scalar32_min_max_xor(dst_reg, &src_reg);
8106 		scalar_min_max_xor(dst_reg, &src_reg);
8107 		break;
8108 	case BPF_LSH:
8109 		if (umax_val >= insn_bitness) {
8110 			/* Shifts greater than 31 or 63 are undefined.
8111 			 * This includes shifts by a negative number.
8112 			 */
8113 			mark_reg_unknown(env, regs, insn->dst_reg);
8114 			break;
8115 		}
8116 		if (alu32)
8117 			scalar32_min_max_lsh(dst_reg, &src_reg);
8118 		else
8119 			scalar_min_max_lsh(dst_reg, &src_reg);
8120 		break;
8121 	case BPF_RSH:
8122 		if (umax_val >= insn_bitness) {
8123 			/* Shifts greater than 31 or 63 are undefined.
8124 			 * This includes shifts by a negative number.
8125 			 */
8126 			mark_reg_unknown(env, regs, insn->dst_reg);
8127 			break;
8128 		}
8129 		if (alu32)
8130 			scalar32_min_max_rsh(dst_reg, &src_reg);
8131 		else
8132 			scalar_min_max_rsh(dst_reg, &src_reg);
8133 		break;
8134 	case BPF_ARSH:
8135 		if (umax_val >= insn_bitness) {
8136 			/* Shifts greater than 31 or 63 are undefined.
8137 			 * This includes shifts by a negative number.
8138 			 */
8139 			mark_reg_unknown(env, regs, insn->dst_reg);
8140 			break;
8141 		}
8142 		if (alu32)
8143 			scalar32_min_max_arsh(dst_reg, &src_reg);
8144 		else
8145 			scalar_min_max_arsh(dst_reg, &src_reg);
8146 		break;
8147 	default:
8148 		mark_reg_unknown(env, regs, insn->dst_reg);
8149 		break;
8150 	}
8151 
8152 	/* ALU32 ops are zero extended into 64bit register */
8153 	if (alu32)
8154 		zext_32_to_64(dst_reg);
8155 
8156 	__update_reg_bounds(dst_reg);
8157 	__reg_deduce_bounds(dst_reg);
8158 	__reg_bound_offset(dst_reg);
8159 	return 0;
8160 }
8161 
8162 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8163  * and var_off.
8164  */
8165 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8166 				   struct bpf_insn *insn)
8167 {
8168 	struct bpf_verifier_state *vstate = env->cur_state;
8169 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8170 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8171 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8172 	u8 opcode = BPF_OP(insn->code);
8173 	int err;
8174 
8175 	dst_reg = &regs[insn->dst_reg];
8176 	src_reg = NULL;
8177 	if (dst_reg->type != SCALAR_VALUE)
8178 		ptr_reg = dst_reg;
8179 	else
8180 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8181 		 * incorrectly propagated into other registers by find_equal_scalars()
8182 		 */
8183 		dst_reg->id = 0;
8184 	if (BPF_SRC(insn->code) == BPF_X) {
8185 		src_reg = &regs[insn->src_reg];
8186 		if (src_reg->type != SCALAR_VALUE) {
8187 			if (dst_reg->type != SCALAR_VALUE) {
8188 				/* Combining two pointers by any ALU op yields
8189 				 * an arbitrary scalar. Disallow all math except
8190 				 * pointer subtraction
8191 				 */
8192 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8193 					mark_reg_unknown(env, regs, insn->dst_reg);
8194 					return 0;
8195 				}
8196 				verbose(env, "R%d pointer %s pointer prohibited\n",
8197 					insn->dst_reg,
8198 					bpf_alu_string[opcode >> 4]);
8199 				return -EACCES;
8200 			} else {
8201 				/* scalar += pointer
8202 				 * This is legal, but we have to reverse our
8203 				 * src/dest handling in computing the range
8204 				 */
8205 				err = mark_chain_precision(env, insn->dst_reg);
8206 				if (err)
8207 					return err;
8208 				return adjust_ptr_min_max_vals(env, insn,
8209 							       src_reg, dst_reg);
8210 			}
8211 		} else if (ptr_reg) {
8212 			/* pointer += scalar */
8213 			err = mark_chain_precision(env, insn->src_reg);
8214 			if (err)
8215 				return err;
8216 			return adjust_ptr_min_max_vals(env, insn,
8217 						       dst_reg, src_reg);
8218 		}
8219 	} else {
8220 		/* Pretend the src is a reg with a known value, since we only
8221 		 * need to be able to read from this state.
8222 		 */
8223 		off_reg.type = SCALAR_VALUE;
8224 		__mark_reg_known(&off_reg, insn->imm);
8225 		src_reg = &off_reg;
8226 		if (ptr_reg) /* pointer += K */
8227 			return adjust_ptr_min_max_vals(env, insn,
8228 						       ptr_reg, src_reg);
8229 	}
8230 
8231 	/* Got here implies adding two SCALAR_VALUEs */
8232 	if (WARN_ON_ONCE(ptr_reg)) {
8233 		print_verifier_state(env, state);
8234 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8235 		return -EINVAL;
8236 	}
8237 	if (WARN_ON(!src_reg)) {
8238 		print_verifier_state(env, state);
8239 		verbose(env, "verifier internal error: no src_reg\n");
8240 		return -EINVAL;
8241 	}
8242 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8243 }
8244 
8245 /* check validity of 32-bit and 64-bit arithmetic operations */
8246 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8247 {
8248 	struct bpf_reg_state *regs = cur_regs(env);
8249 	u8 opcode = BPF_OP(insn->code);
8250 	int err;
8251 
8252 	if (opcode == BPF_END || opcode == BPF_NEG) {
8253 		if (opcode == BPF_NEG) {
8254 			if (BPF_SRC(insn->code) != 0 ||
8255 			    insn->src_reg != BPF_REG_0 ||
8256 			    insn->off != 0 || insn->imm != 0) {
8257 				verbose(env, "BPF_NEG uses reserved fields\n");
8258 				return -EINVAL;
8259 			}
8260 		} else {
8261 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8262 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8263 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8264 				verbose(env, "BPF_END uses reserved fields\n");
8265 				return -EINVAL;
8266 			}
8267 		}
8268 
8269 		/* check src operand */
8270 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8271 		if (err)
8272 			return err;
8273 
8274 		if (is_pointer_value(env, insn->dst_reg)) {
8275 			verbose(env, "R%d pointer arithmetic prohibited\n",
8276 				insn->dst_reg);
8277 			return -EACCES;
8278 		}
8279 
8280 		/* check dest operand */
8281 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8282 		if (err)
8283 			return err;
8284 
8285 	} else if (opcode == BPF_MOV) {
8286 
8287 		if (BPF_SRC(insn->code) == BPF_X) {
8288 			if (insn->imm != 0 || insn->off != 0) {
8289 				verbose(env, "BPF_MOV uses reserved fields\n");
8290 				return -EINVAL;
8291 			}
8292 
8293 			/* check src operand */
8294 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8295 			if (err)
8296 				return err;
8297 		} else {
8298 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8299 				verbose(env, "BPF_MOV uses reserved fields\n");
8300 				return -EINVAL;
8301 			}
8302 		}
8303 
8304 		/* check dest operand, mark as required later */
8305 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8306 		if (err)
8307 			return err;
8308 
8309 		if (BPF_SRC(insn->code) == BPF_X) {
8310 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8311 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8312 
8313 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8314 				/* case: R1 = R2
8315 				 * copy register state to dest reg
8316 				 */
8317 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8318 					/* Assign src and dst registers the same ID
8319 					 * that will be used by find_equal_scalars()
8320 					 * to propagate min/max range.
8321 					 */
8322 					src_reg->id = ++env->id_gen;
8323 				*dst_reg = *src_reg;
8324 				dst_reg->live |= REG_LIVE_WRITTEN;
8325 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8326 			} else {
8327 				/* R1 = (u32) R2 */
8328 				if (is_pointer_value(env, insn->src_reg)) {
8329 					verbose(env,
8330 						"R%d partial copy of pointer\n",
8331 						insn->src_reg);
8332 					return -EACCES;
8333 				} else if (src_reg->type == SCALAR_VALUE) {
8334 					*dst_reg = *src_reg;
8335 					/* Make sure ID is cleared otherwise
8336 					 * dst_reg min/max could be incorrectly
8337 					 * propagated into src_reg by find_equal_scalars()
8338 					 */
8339 					dst_reg->id = 0;
8340 					dst_reg->live |= REG_LIVE_WRITTEN;
8341 					dst_reg->subreg_def = env->insn_idx + 1;
8342 				} else {
8343 					mark_reg_unknown(env, regs,
8344 							 insn->dst_reg);
8345 				}
8346 				zext_32_to_64(dst_reg);
8347 			}
8348 		} else {
8349 			/* case: R = imm
8350 			 * remember the value we stored into this reg
8351 			 */
8352 			/* clear any state __mark_reg_known doesn't set */
8353 			mark_reg_unknown(env, regs, insn->dst_reg);
8354 			regs[insn->dst_reg].type = SCALAR_VALUE;
8355 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8356 				__mark_reg_known(regs + insn->dst_reg,
8357 						 insn->imm);
8358 			} else {
8359 				__mark_reg_known(regs + insn->dst_reg,
8360 						 (u32)insn->imm);
8361 			}
8362 		}
8363 
8364 	} else if (opcode > BPF_END) {
8365 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8366 		return -EINVAL;
8367 
8368 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8369 
8370 		if (BPF_SRC(insn->code) == BPF_X) {
8371 			if (insn->imm != 0 || insn->off != 0) {
8372 				verbose(env, "BPF_ALU uses reserved fields\n");
8373 				return -EINVAL;
8374 			}
8375 			/* check src1 operand */
8376 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8377 			if (err)
8378 				return err;
8379 		} else {
8380 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8381 				verbose(env, "BPF_ALU uses reserved fields\n");
8382 				return -EINVAL;
8383 			}
8384 		}
8385 
8386 		/* check src2 operand */
8387 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8388 		if (err)
8389 			return err;
8390 
8391 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8392 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8393 			verbose(env, "div by zero\n");
8394 			return -EINVAL;
8395 		}
8396 
8397 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8398 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8399 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8400 
8401 			if (insn->imm < 0 || insn->imm >= size) {
8402 				verbose(env, "invalid shift %d\n", insn->imm);
8403 				return -EINVAL;
8404 			}
8405 		}
8406 
8407 		/* check dest operand */
8408 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8409 		if (err)
8410 			return err;
8411 
8412 		return adjust_reg_min_max_vals(env, insn);
8413 	}
8414 
8415 	return 0;
8416 }
8417 
8418 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8419 				     struct bpf_reg_state *dst_reg,
8420 				     enum bpf_reg_type type, int new_range)
8421 {
8422 	struct bpf_reg_state *reg;
8423 	int i;
8424 
8425 	for (i = 0; i < MAX_BPF_REG; i++) {
8426 		reg = &state->regs[i];
8427 		if (reg->type == type && reg->id == dst_reg->id)
8428 			/* keep the maximum range already checked */
8429 			reg->range = max(reg->range, new_range);
8430 	}
8431 
8432 	bpf_for_each_spilled_reg(i, state, reg) {
8433 		if (!reg)
8434 			continue;
8435 		if (reg->type == type && reg->id == dst_reg->id)
8436 			reg->range = max(reg->range, new_range);
8437 	}
8438 }
8439 
8440 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8441 				   struct bpf_reg_state *dst_reg,
8442 				   enum bpf_reg_type type,
8443 				   bool range_right_open)
8444 {
8445 	int new_range, i;
8446 
8447 	if (dst_reg->off < 0 ||
8448 	    (dst_reg->off == 0 && range_right_open))
8449 		/* This doesn't give us any range */
8450 		return;
8451 
8452 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8453 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8454 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8455 		 * than pkt_end, but that's because it's also less than pkt.
8456 		 */
8457 		return;
8458 
8459 	new_range = dst_reg->off;
8460 	if (range_right_open)
8461 		new_range--;
8462 
8463 	/* Examples for register markings:
8464 	 *
8465 	 * pkt_data in dst register:
8466 	 *
8467 	 *   r2 = r3;
8468 	 *   r2 += 8;
8469 	 *   if (r2 > pkt_end) goto <handle exception>
8470 	 *   <access okay>
8471 	 *
8472 	 *   r2 = r3;
8473 	 *   r2 += 8;
8474 	 *   if (r2 < pkt_end) goto <access okay>
8475 	 *   <handle exception>
8476 	 *
8477 	 *   Where:
8478 	 *     r2 == dst_reg, pkt_end == src_reg
8479 	 *     r2=pkt(id=n,off=8,r=0)
8480 	 *     r3=pkt(id=n,off=0,r=0)
8481 	 *
8482 	 * pkt_data in src register:
8483 	 *
8484 	 *   r2 = r3;
8485 	 *   r2 += 8;
8486 	 *   if (pkt_end >= r2) goto <access okay>
8487 	 *   <handle exception>
8488 	 *
8489 	 *   r2 = r3;
8490 	 *   r2 += 8;
8491 	 *   if (pkt_end <= r2) goto <handle exception>
8492 	 *   <access okay>
8493 	 *
8494 	 *   Where:
8495 	 *     pkt_end == dst_reg, r2 == src_reg
8496 	 *     r2=pkt(id=n,off=8,r=0)
8497 	 *     r3=pkt(id=n,off=0,r=0)
8498 	 *
8499 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8500 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8501 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8502 	 * the check.
8503 	 */
8504 
8505 	/* If our ids match, then we must have the same max_value.  And we
8506 	 * don't care about the other reg's fixed offset, since if it's too big
8507 	 * the range won't allow anything.
8508 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8509 	 */
8510 	for (i = 0; i <= vstate->curframe; i++)
8511 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8512 					 new_range);
8513 }
8514 
8515 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8516 {
8517 	struct tnum subreg = tnum_subreg(reg->var_off);
8518 	s32 sval = (s32)val;
8519 
8520 	switch (opcode) {
8521 	case BPF_JEQ:
8522 		if (tnum_is_const(subreg))
8523 			return !!tnum_equals_const(subreg, val);
8524 		break;
8525 	case BPF_JNE:
8526 		if (tnum_is_const(subreg))
8527 			return !tnum_equals_const(subreg, val);
8528 		break;
8529 	case BPF_JSET:
8530 		if ((~subreg.mask & subreg.value) & val)
8531 			return 1;
8532 		if (!((subreg.mask | subreg.value) & val))
8533 			return 0;
8534 		break;
8535 	case BPF_JGT:
8536 		if (reg->u32_min_value > val)
8537 			return 1;
8538 		else if (reg->u32_max_value <= val)
8539 			return 0;
8540 		break;
8541 	case BPF_JSGT:
8542 		if (reg->s32_min_value > sval)
8543 			return 1;
8544 		else if (reg->s32_max_value <= sval)
8545 			return 0;
8546 		break;
8547 	case BPF_JLT:
8548 		if (reg->u32_max_value < val)
8549 			return 1;
8550 		else if (reg->u32_min_value >= val)
8551 			return 0;
8552 		break;
8553 	case BPF_JSLT:
8554 		if (reg->s32_max_value < sval)
8555 			return 1;
8556 		else if (reg->s32_min_value >= sval)
8557 			return 0;
8558 		break;
8559 	case BPF_JGE:
8560 		if (reg->u32_min_value >= val)
8561 			return 1;
8562 		else if (reg->u32_max_value < val)
8563 			return 0;
8564 		break;
8565 	case BPF_JSGE:
8566 		if (reg->s32_min_value >= sval)
8567 			return 1;
8568 		else if (reg->s32_max_value < sval)
8569 			return 0;
8570 		break;
8571 	case BPF_JLE:
8572 		if (reg->u32_max_value <= val)
8573 			return 1;
8574 		else if (reg->u32_min_value > val)
8575 			return 0;
8576 		break;
8577 	case BPF_JSLE:
8578 		if (reg->s32_max_value <= sval)
8579 			return 1;
8580 		else if (reg->s32_min_value > sval)
8581 			return 0;
8582 		break;
8583 	}
8584 
8585 	return -1;
8586 }
8587 
8588 
8589 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8590 {
8591 	s64 sval = (s64)val;
8592 
8593 	switch (opcode) {
8594 	case BPF_JEQ:
8595 		if (tnum_is_const(reg->var_off))
8596 			return !!tnum_equals_const(reg->var_off, val);
8597 		break;
8598 	case BPF_JNE:
8599 		if (tnum_is_const(reg->var_off))
8600 			return !tnum_equals_const(reg->var_off, val);
8601 		break;
8602 	case BPF_JSET:
8603 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8604 			return 1;
8605 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8606 			return 0;
8607 		break;
8608 	case BPF_JGT:
8609 		if (reg->umin_value > val)
8610 			return 1;
8611 		else if (reg->umax_value <= val)
8612 			return 0;
8613 		break;
8614 	case BPF_JSGT:
8615 		if (reg->smin_value > sval)
8616 			return 1;
8617 		else if (reg->smax_value <= sval)
8618 			return 0;
8619 		break;
8620 	case BPF_JLT:
8621 		if (reg->umax_value < val)
8622 			return 1;
8623 		else if (reg->umin_value >= val)
8624 			return 0;
8625 		break;
8626 	case BPF_JSLT:
8627 		if (reg->smax_value < sval)
8628 			return 1;
8629 		else if (reg->smin_value >= sval)
8630 			return 0;
8631 		break;
8632 	case BPF_JGE:
8633 		if (reg->umin_value >= val)
8634 			return 1;
8635 		else if (reg->umax_value < val)
8636 			return 0;
8637 		break;
8638 	case BPF_JSGE:
8639 		if (reg->smin_value >= sval)
8640 			return 1;
8641 		else if (reg->smax_value < sval)
8642 			return 0;
8643 		break;
8644 	case BPF_JLE:
8645 		if (reg->umax_value <= val)
8646 			return 1;
8647 		else if (reg->umin_value > val)
8648 			return 0;
8649 		break;
8650 	case BPF_JSLE:
8651 		if (reg->smax_value <= sval)
8652 			return 1;
8653 		else if (reg->smin_value > sval)
8654 			return 0;
8655 		break;
8656 	}
8657 
8658 	return -1;
8659 }
8660 
8661 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8662  * and return:
8663  *  1 - branch will be taken and "goto target" will be executed
8664  *  0 - branch will not be taken and fall-through to next insn
8665  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8666  *      range [0,10]
8667  */
8668 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8669 			   bool is_jmp32)
8670 {
8671 	if (__is_pointer_value(false, reg)) {
8672 		if (!reg_type_not_null(reg->type))
8673 			return -1;
8674 
8675 		/* If pointer is valid tests against zero will fail so we can
8676 		 * use this to direct branch taken.
8677 		 */
8678 		if (val != 0)
8679 			return -1;
8680 
8681 		switch (opcode) {
8682 		case BPF_JEQ:
8683 			return 0;
8684 		case BPF_JNE:
8685 			return 1;
8686 		default:
8687 			return -1;
8688 		}
8689 	}
8690 
8691 	if (is_jmp32)
8692 		return is_branch32_taken(reg, val, opcode);
8693 	return is_branch64_taken(reg, val, opcode);
8694 }
8695 
8696 static int flip_opcode(u32 opcode)
8697 {
8698 	/* How can we transform "a <op> b" into "b <op> a"? */
8699 	static const u8 opcode_flip[16] = {
8700 		/* these stay the same */
8701 		[BPF_JEQ  >> 4] = BPF_JEQ,
8702 		[BPF_JNE  >> 4] = BPF_JNE,
8703 		[BPF_JSET >> 4] = BPF_JSET,
8704 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8705 		[BPF_JGE  >> 4] = BPF_JLE,
8706 		[BPF_JGT  >> 4] = BPF_JLT,
8707 		[BPF_JLE  >> 4] = BPF_JGE,
8708 		[BPF_JLT  >> 4] = BPF_JGT,
8709 		[BPF_JSGE >> 4] = BPF_JSLE,
8710 		[BPF_JSGT >> 4] = BPF_JSLT,
8711 		[BPF_JSLE >> 4] = BPF_JSGE,
8712 		[BPF_JSLT >> 4] = BPF_JSGT
8713 	};
8714 	return opcode_flip[opcode >> 4];
8715 }
8716 
8717 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8718 				   struct bpf_reg_state *src_reg,
8719 				   u8 opcode)
8720 {
8721 	struct bpf_reg_state *pkt;
8722 
8723 	if (src_reg->type == PTR_TO_PACKET_END) {
8724 		pkt = dst_reg;
8725 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8726 		pkt = src_reg;
8727 		opcode = flip_opcode(opcode);
8728 	} else {
8729 		return -1;
8730 	}
8731 
8732 	if (pkt->range >= 0)
8733 		return -1;
8734 
8735 	switch (opcode) {
8736 	case BPF_JLE:
8737 		/* pkt <= pkt_end */
8738 		fallthrough;
8739 	case BPF_JGT:
8740 		/* pkt > pkt_end */
8741 		if (pkt->range == BEYOND_PKT_END)
8742 			/* pkt has at last one extra byte beyond pkt_end */
8743 			return opcode == BPF_JGT;
8744 		break;
8745 	case BPF_JLT:
8746 		/* pkt < pkt_end */
8747 		fallthrough;
8748 	case BPF_JGE:
8749 		/* pkt >= pkt_end */
8750 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8751 			return opcode == BPF_JGE;
8752 		break;
8753 	}
8754 	return -1;
8755 }
8756 
8757 /* Adjusts the register min/max values in the case that the dst_reg is the
8758  * variable register that we are working on, and src_reg is a constant or we're
8759  * simply doing a BPF_K check.
8760  * In JEQ/JNE cases we also adjust the var_off values.
8761  */
8762 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8763 			    struct bpf_reg_state *false_reg,
8764 			    u64 val, u32 val32,
8765 			    u8 opcode, bool is_jmp32)
8766 {
8767 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8768 	struct tnum false_64off = false_reg->var_off;
8769 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8770 	struct tnum true_64off = true_reg->var_off;
8771 	s64 sval = (s64)val;
8772 	s32 sval32 = (s32)val32;
8773 
8774 	/* If the dst_reg is a pointer, we can't learn anything about its
8775 	 * variable offset from the compare (unless src_reg were a pointer into
8776 	 * the same object, but we don't bother with that.
8777 	 * Since false_reg and true_reg have the same type by construction, we
8778 	 * only need to check one of them for pointerness.
8779 	 */
8780 	if (__is_pointer_value(false, false_reg))
8781 		return;
8782 
8783 	switch (opcode) {
8784 	case BPF_JEQ:
8785 	case BPF_JNE:
8786 	{
8787 		struct bpf_reg_state *reg =
8788 			opcode == BPF_JEQ ? true_reg : false_reg;
8789 
8790 		/* JEQ/JNE comparison doesn't change the register equivalence.
8791 		 * r1 = r2;
8792 		 * if (r1 == 42) goto label;
8793 		 * ...
8794 		 * label: // here both r1 and r2 are known to be 42.
8795 		 *
8796 		 * Hence when marking register as known preserve it's ID.
8797 		 */
8798 		if (is_jmp32)
8799 			__mark_reg32_known(reg, val32);
8800 		else
8801 			___mark_reg_known(reg, val);
8802 		break;
8803 	}
8804 	case BPF_JSET:
8805 		if (is_jmp32) {
8806 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8807 			if (is_power_of_2(val32))
8808 				true_32off = tnum_or(true_32off,
8809 						     tnum_const(val32));
8810 		} else {
8811 			false_64off = tnum_and(false_64off, tnum_const(~val));
8812 			if (is_power_of_2(val))
8813 				true_64off = tnum_or(true_64off,
8814 						     tnum_const(val));
8815 		}
8816 		break;
8817 	case BPF_JGE:
8818 	case BPF_JGT:
8819 	{
8820 		if (is_jmp32) {
8821 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8822 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8823 
8824 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8825 						       false_umax);
8826 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8827 						      true_umin);
8828 		} else {
8829 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8830 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8831 
8832 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8833 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8834 		}
8835 		break;
8836 	}
8837 	case BPF_JSGE:
8838 	case BPF_JSGT:
8839 	{
8840 		if (is_jmp32) {
8841 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8842 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8843 
8844 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8845 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8846 		} else {
8847 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8848 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8849 
8850 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8851 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8852 		}
8853 		break;
8854 	}
8855 	case BPF_JLE:
8856 	case BPF_JLT:
8857 	{
8858 		if (is_jmp32) {
8859 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8860 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8861 
8862 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8863 						       false_umin);
8864 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8865 						      true_umax);
8866 		} else {
8867 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8868 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8869 
8870 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8871 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8872 		}
8873 		break;
8874 	}
8875 	case BPF_JSLE:
8876 	case BPF_JSLT:
8877 	{
8878 		if (is_jmp32) {
8879 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8880 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8881 
8882 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8883 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8884 		} else {
8885 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8886 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8887 
8888 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8889 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8890 		}
8891 		break;
8892 	}
8893 	default:
8894 		return;
8895 	}
8896 
8897 	if (is_jmp32) {
8898 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8899 					     tnum_subreg(false_32off));
8900 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8901 					    tnum_subreg(true_32off));
8902 		__reg_combine_32_into_64(false_reg);
8903 		__reg_combine_32_into_64(true_reg);
8904 	} else {
8905 		false_reg->var_off = false_64off;
8906 		true_reg->var_off = true_64off;
8907 		__reg_combine_64_into_32(false_reg);
8908 		__reg_combine_64_into_32(true_reg);
8909 	}
8910 }
8911 
8912 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8913  * the variable reg.
8914  */
8915 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8916 				struct bpf_reg_state *false_reg,
8917 				u64 val, u32 val32,
8918 				u8 opcode, bool is_jmp32)
8919 {
8920 	opcode = flip_opcode(opcode);
8921 	/* This uses zero as "not present in table"; luckily the zero opcode,
8922 	 * BPF_JA, can't get here.
8923 	 */
8924 	if (opcode)
8925 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8926 }
8927 
8928 /* Regs are known to be equal, so intersect their min/max/var_off */
8929 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8930 				  struct bpf_reg_state *dst_reg)
8931 {
8932 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8933 							dst_reg->umin_value);
8934 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8935 							dst_reg->umax_value);
8936 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8937 							dst_reg->smin_value);
8938 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8939 							dst_reg->smax_value);
8940 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8941 							     dst_reg->var_off);
8942 	/* We might have learned new bounds from the var_off. */
8943 	__update_reg_bounds(src_reg);
8944 	__update_reg_bounds(dst_reg);
8945 	/* We might have learned something about the sign bit. */
8946 	__reg_deduce_bounds(src_reg);
8947 	__reg_deduce_bounds(dst_reg);
8948 	/* We might have learned some bits from the bounds. */
8949 	__reg_bound_offset(src_reg);
8950 	__reg_bound_offset(dst_reg);
8951 	/* Intersecting with the old var_off might have improved our bounds
8952 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8953 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
8954 	 */
8955 	__update_reg_bounds(src_reg);
8956 	__update_reg_bounds(dst_reg);
8957 }
8958 
8959 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8960 				struct bpf_reg_state *true_dst,
8961 				struct bpf_reg_state *false_src,
8962 				struct bpf_reg_state *false_dst,
8963 				u8 opcode)
8964 {
8965 	switch (opcode) {
8966 	case BPF_JEQ:
8967 		__reg_combine_min_max(true_src, true_dst);
8968 		break;
8969 	case BPF_JNE:
8970 		__reg_combine_min_max(false_src, false_dst);
8971 		break;
8972 	}
8973 }
8974 
8975 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8976 				 struct bpf_reg_state *reg, u32 id,
8977 				 bool is_null)
8978 {
8979 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
8980 	    !WARN_ON_ONCE(!reg->id)) {
8981 		/* Old offset (both fixed and variable parts) should
8982 		 * have been known-zero, because we don't allow pointer
8983 		 * arithmetic on pointers that might be NULL.
8984 		 */
8985 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8986 				 !tnum_equals_const(reg->var_off, 0) ||
8987 				 reg->off)) {
8988 			__mark_reg_known_zero(reg);
8989 			reg->off = 0;
8990 		}
8991 		if (is_null) {
8992 			reg->type = SCALAR_VALUE;
8993 			/* We don't need id and ref_obj_id from this point
8994 			 * onwards anymore, thus we should better reset it,
8995 			 * so that state pruning has chances to take effect.
8996 			 */
8997 			reg->id = 0;
8998 			reg->ref_obj_id = 0;
8999 
9000 			return;
9001 		}
9002 
9003 		mark_ptr_not_null_reg(reg);
9004 
9005 		if (!reg_may_point_to_spin_lock(reg)) {
9006 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9007 			 * in release_reg_references().
9008 			 *
9009 			 * reg->id is still used by spin_lock ptr. Other
9010 			 * than spin_lock ptr type, reg->id can be reset.
9011 			 */
9012 			reg->id = 0;
9013 		}
9014 	}
9015 }
9016 
9017 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9018 				    bool is_null)
9019 {
9020 	struct bpf_reg_state *reg;
9021 	int i;
9022 
9023 	for (i = 0; i < MAX_BPF_REG; i++)
9024 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9025 
9026 	bpf_for_each_spilled_reg(i, state, reg) {
9027 		if (!reg)
9028 			continue;
9029 		mark_ptr_or_null_reg(state, reg, id, is_null);
9030 	}
9031 }
9032 
9033 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9034  * be folded together at some point.
9035  */
9036 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9037 				  bool is_null)
9038 {
9039 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9040 	struct bpf_reg_state *regs = state->regs;
9041 	u32 ref_obj_id = regs[regno].ref_obj_id;
9042 	u32 id = regs[regno].id;
9043 	int i;
9044 
9045 	if (ref_obj_id && ref_obj_id == id && is_null)
9046 		/* regs[regno] is in the " == NULL" branch.
9047 		 * No one could have freed the reference state before
9048 		 * doing the NULL check.
9049 		 */
9050 		WARN_ON_ONCE(release_reference_state(state, id));
9051 
9052 	for (i = 0; i <= vstate->curframe; i++)
9053 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9054 }
9055 
9056 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9057 				   struct bpf_reg_state *dst_reg,
9058 				   struct bpf_reg_state *src_reg,
9059 				   struct bpf_verifier_state *this_branch,
9060 				   struct bpf_verifier_state *other_branch)
9061 {
9062 	if (BPF_SRC(insn->code) != BPF_X)
9063 		return false;
9064 
9065 	/* Pointers are always 64-bit. */
9066 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9067 		return false;
9068 
9069 	switch (BPF_OP(insn->code)) {
9070 	case BPF_JGT:
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, false);
9078 			mark_pkt_end(other_branch, insn->dst_reg, true);
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, true);
9086 			mark_pkt_end(this_branch, insn->src_reg, false);
9087 		} else {
9088 			return false;
9089 		}
9090 		break;
9091 	case BPF_JLT:
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, true);
9099 			mark_pkt_end(this_branch, insn->dst_reg, false);
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, false);
9107 			mark_pkt_end(other_branch, insn->src_reg, true);
9108 		} else {
9109 			return false;
9110 		}
9111 		break;
9112 	case BPF_JGE:
9113 		if ((dst_reg->type == PTR_TO_PACKET &&
9114 		     src_reg->type == PTR_TO_PACKET_END) ||
9115 		    (dst_reg->type == PTR_TO_PACKET_META &&
9116 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9117 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9118 			find_good_pkt_pointers(this_branch, dst_reg,
9119 					       dst_reg->type, true);
9120 			mark_pkt_end(other_branch, insn->dst_reg, false);
9121 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9122 			    src_reg->type == PTR_TO_PACKET) ||
9123 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9124 			    src_reg->type == PTR_TO_PACKET_META)) {
9125 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9126 			find_good_pkt_pointers(other_branch, src_reg,
9127 					       src_reg->type, false);
9128 			mark_pkt_end(this_branch, insn->src_reg, true);
9129 		} else {
9130 			return false;
9131 		}
9132 		break;
9133 	case BPF_JLE:
9134 		if ((dst_reg->type == PTR_TO_PACKET &&
9135 		     src_reg->type == PTR_TO_PACKET_END) ||
9136 		    (dst_reg->type == PTR_TO_PACKET_META &&
9137 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9138 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9139 			find_good_pkt_pointers(other_branch, dst_reg,
9140 					       dst_reg->type, false);
9141 			mark_pkt_end(this_branch, insn->dst_reg, true);
9142 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9143 			    src_reg->type == PTR_TO_PACKET) ||
9144 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9145 			    src_reg->type == PTR_TO_PACKET_META)) {
9146 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9147 			find_good_pkt_pointers(this_branch, src_reg,
9148 					       src_reg->type, true);
9149 			mark_pkt_end(other_branch, insn->src_reg, false);
9150 		} else {
9151 			return false;
9152 		}
9153 		break;
9154 	default:
9155 		return false;
9156 	}
9157 
9158 	return true;
9159 }
9160 
9161 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9162 			       struct bpf_reg_state *known_reg)
9163 {
9164 	struct bpf_func_state *state;
9165 	struct bpf_reg_state *reg;
9166 	int i, j;
9167 
9168 	for (i = 0; i <= vstate->curframe; i++) {
9169 		state = vstate->frame[i];
9170 		for (j = 0; j < MAX_BPF_REG; j++) {
9171 			reg = &state->regs[j];
9172 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9173 				*reg = *known_reg;
9174 		}
9175 
9176 		bpf_for_each_spilled_reg(j, state, reg) {
9177 			if (!reg)
9178 				continue;
9179 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9180 				*reg = *known_reg;
9181 		}
9182 	}
9183 }
9184 
9185 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9186 			     struct bpf_insn *insn, int *insn_idx)
9187 {
9188 	struct bpf_verifier_state *this_branch = env->cur_state;
9189 	struct bpf_verifier_state *other_branch;
9190 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9191 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9192 	u8 opcode = BPF_OP(insn->code);
9193 	bool is_jmp32;
9194 	int pred = -1;
9195 	int err;
9196 
9197 	/* Only conditional jumps are expected to reach here. */
9198 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9199 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9200 		return -EINVAL;
9201 	}
9202 
9203 	if (BPF_SRC(insn->code) == BPF_X) {
9204 		if (insn->imm != 0) {
9205 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9206 			return -EINVAL;
9207 		}
9208 
9209 		/* check src1 operand */
9210 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9211 		if (err)
9212 			return err;
9213 
9214 		if (is_pointer_value(env, insn->src_reg)) {
9215 			verbose(env, "R%d pointer comparison prohibited\n",
9216 				insn->src_reg);
9217 			return -EACCES;
9218 		}
9219 		src_reg = &regs[insn->src_reg];
9220 	} else {
9221 		if (insn->src_reg != BPF_REG_0) {
9222 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9223 			return -EINVAL;
9224 		}
9225 	}
9226 
9227 	/* check src2 operand */
9228 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9229 	if (err)
9230 		return err;
9231 
9232 	dst_reg = &regs[insn->dst_reg];
9233 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9234 
9235 	if (BPF_SRC(insn->code) == BPF_K) {
9236 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9237 	} else if (src_reg->type == SCALAR_VALUE &&
9238 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9239 		pred = is_branch_taken(dst_reg,
9240 				       tnum_subreg(src_reg->var_off).value,
9241 				       opcode,
9242 				       is_jmp32);
9243 	} else if (src_reg->type == SCALAR_VALUE &&
9244 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9245 		pred = is_branch_taken(dst_reg,
9246 				       src_reg->var_off.value,
9247 				       opcode,
9248 				       is_jmp32);
9249 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9250 		   reg_is_pkt_pointer_any(src_reg) &&
9251 		   !is_jmp32) {
9252 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9253 	}
9254 
9255 	if (pred >= 0) {
9256 		/* If we get here with a dst_reg pointer type it is because
9257 		 * above is_branch_taken() special cased the 0 comparison.
9258 		 */
9259 		if (!__is_pointer_value(false, dst_reg))
9260 			err = mark_chain_precision(env, insn->dst_reg);
9261 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9262 		    !__is_pointer_value(false, src_reg))
9263 			err = mark_chain_precision(env, insn->src_reg);
9264 		if (err)
9265 			return err;
9266 	}
9267 
9268 	if (pred == 1) {
9269 		/* Only follow the goto, ignore fall-through. If needed, push
9270 		 * the fall-through branch for simulation under speculative
9271 		 * execution.
9272 		 */
9273 		if (!env->bypass_spec_v1 &&
9274 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9275 					       *insn_idx))
9276 			return -EFAULT;
9277 		*insn_idx += insn->off;
9278 		return 0;
9279 	} else if (pred == 0) {
9280 		/* Only follow the fall-through branch, since that's where the
9281 		 * program will go. If needed, push the goto branch for
9282 		 * simulation under speculative execution.
9283 		 */
9284 		if (!env->bypass_spec_v1 &&
9285 		    !sanitize_speculative_path(env, insn,
9286 					       *insn_idx + insn->off + 1,
9287 					       *insn_idx))
9288 			return -EFAULT;
9289 		return 0;
9290 	}
9291 
9292 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9293 				  false);
9294 	if (!other_branch)
9295 		return -EFAULT;
9296 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9297 
9298 	/* detect if we are comparing against a constant value so we can adjust
9299 	 * our min/max values for our dst register.
9300 	 * this is only legit if both are scalars (or pointers to the same
9301 	 * object, I suppose, but we don't support that right now), because
9302 	 * otherwise the different base pointers mean the offsets aren't
9303 	 * comparable.
9304 	 */
9305 	if (BPF_SRC(insn->code) == BPF_X) {
9306 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9307 
9308 		if (dst_reg->type == SCALAR_VALUE &&
9309 		    src_reg->type == SCALAR_VALUE) {
9310 			if (tnum_is_const(src_reg->var_off) ||
9311 			    (is_jmp32 &&
9312 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9313 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9314 						dst_reg,
9315 						src_reg->var_off.value,
9316 						tnum_subreg(src_reg->var_off).value,
9317 						opcode, is_jmp32);
9318 			else if (tnum_is_const(dst_reg->var_off) ||
9319 				 (is_jmp32 &&
9320 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9321 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9322 						    src_reg,
9323 						    dst_reg->var_off.value,
9324 						    tnum_subreg(dst_reg->var_off).value,
9325 						    opcode, is_jmp32);
9326 			else if (!is_jmp32 &&
9327 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9328 				/* Comparing for equality, we can combine knowledge */
9329 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9330 						    &other_branch_regs[insn->dst_reg],
9331 						    src_reg, dst_reg, opcode);
9332 			if (src_reg->id &&
9333 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9334 				find_equal_scalars(this_branch, src_reg);
9335 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9336 			}
9337 
9338 		}
9339 	} else if (dst_reg->type == SCALAR_VALUE) {
9340 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9341 					dst_reg, insn->imm, (u32)insn->imm,
9342 					opcode, is_jmp32);
9343 	}
9344 
9345 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9346 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9347 		find_equal_scalars(this_branch, dst_reg);
9348 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9349 	}
9350 
9351 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9352 	 * NOTE: these optimizations below are related with pointer comparison
9353 	 *       which will never be JMP32.
9354 	 */
9355 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9356 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9357 	    reg_type_may_be_null(dst_reg->type)) {
9358 		/* Mark all identical registers in each branch as either
9359 		 * safe or unknown depending R == 0 or R != 0 conditional.
9360 		 */
9361 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9362 				      opcode == BPF_JNE);
9363 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9364 				      opcode == BPF_JEQ);
9365 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9366 					   this_branch, other_branch) &&
9367 		   is_pointer_value(env, insn->dst_reg)) {
9368 		verbose(env, "R%d pointer comparison prohibited\n",
9369 			insn->dst_reg);
9370 		return -EACCES;
9371 	}
9372 	if (env->log.level & BPF_LOG_LEVEL)
9373 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9374 	return 0;
9375 }
9376 
9377 /* verify BPF_LD_IMM64 instruction */
9378 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9379 {
9380 	struct bpf_insn_aux_data *aux = cur_aux(env);
9381 	struct bpf_reg_state *regs = cur_regs(env);
9382 	struct bpf_reg_state *dst_reg;
9383 	struct bpf_map *map;
9384 	int err;
9385 
9386 	if (BPF_SIZE(insn->code) != BPF_DW) {
9387 		verbose(env, "invalid BPF_LD_IMM insn\n");
9388 		return -EINVAL;
9389 	}
9390 	if (insn->off != 0) {
9391 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9392 		return -EINVAL;
9393 	}
9394 
9395 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9396 	if (err)
9397 		return err;
9398 
9399 	dst_reg = &regs[insn->dst_reg];
9400 	if (insn->src_reg == 0) {
9401 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9402 
9403 		dst_reg->type = SCALAR_VALUE;
9404 		__mark_reg_known(&regs[insn->dst_reg], imm);
9405 		return 0;
9406 	}
9407 
9408 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9409 		mark_reg_known_zero(env, regs, insn->dst_reg);
9410 
9411 		dst_reg->type = aux->btf_var.reg_type;
9412 		switch (dst_reg->type) {
9413 		case PTR_TO_MEM:
9414 			dst_reg->mem_size = aux->btf_var.mem_size;
9415 			break;
9416 		case PTR_TO_BTF_ID:
9417 		case PTR_TO_PERCPU_BTF_ID:
9418 			dst_reg->btf = aux->btf_var.btf;
9419 			dst_reg->btf_id = aux->btf_var.btf_id;
9420 			break;
9421 		default:
9422 			verbose(env, "bpf verifier is misconfigured\n");
9423 			return -EFAULT;
9424 		}
9425 		return 0;
9426 	}
9427 
9428 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9429 		struct bpf_prog_aux *aux = env->prog->aux;
9430 		u32 subprogno = insn[1].imm;
9431 
9432 		if (!aux->func_info) {
9433 			verbose(env, "missing btf func_info\n");
9434 			return -EINVAL;
9435 		}
9436 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9437 			verbose(env, "callback function not static\n");
9438 			return -EINVAL;
9439 		}
9440 
9441 		dst_reg->type = PTR_TO_FUNC;
9442 		dst_reg->subprogno = subprogno;
9443 		return 0;
9444 	}
9445 
9446 	map = env->used_maps[aux->map_index];
9447 	mark_reg_known_zero(env, regs, insn->dst_reg);
9448 	dst_reg->map_ptr = map;
9449 
9450 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9451 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9452 		dst_reg->type = PTR_TO_MAP_VALUE;
9453 		dst_reg->off = aux->map_off;
9454 		if (map_value_has_spin_lock(map))
9455 			dst_reg->id = ++env->id_gen;
9456 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9457 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9458 		dst_reg->type = CONST_PTR_TO_MAP;
9459 	} else {
9460 		verbose(env, "bpf verifier is misconfigured\n");
9461 		return -EINVAL;
9462 	}
9463 
9464 	return 0;
9465 }
9466 
9467 static bool may_access_skb(enum bpf_prog_type type)
9468 {
9469 	switch (type) {
9470 	case BPF_PROG_TYPE_SOCKET_FILTER:
9471 	case BPF_PROG_TYPE_SCHED_CLS:
9472 	case BPF_PROG_TYPE_SCHED_ACT:
9473 		return true;
9474 	default:
9475 		return false;
9476 	}
9477 }
9478 
9479 /* verify safety of LD_ABS|LD_IND instructions:
9480  * - they can only appear in the programs where ctx == skb
9481  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9482  *   preserve R6-R9, and store return value into R0
9483  *
9484  * Implicit input:
9485  *   ctx == skb == R6 == CTX
9486  *
9487  * Explicit input:
9488  *   SRC == any register
9489  *   IMM == 32-bit immediate
9490  *
9491  * Output:
9492  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9493  */
9494 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9495 {
9496 	struct bpf_reg_state *regs = cur_regs(env);
9497 	static const int ctx_reg = BPF_REG_6;
9498 	u8 mode = BPF_MODE(insn->code);
9499 	int i, err;
9500 
9501 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9502 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9503 		return -EINVAL;
9504 	}
9505 
9506 	if (!env->ops->gen_ld_abs) {
9507 		verbose(env, "bpf verifier is misconfigured\n");
9508 		return -EINVAL;
9509 	}
9510 
9511 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9512 	    BPF_SIZE(insn->code) == BPF_DW ||
9513 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9514 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9515 		return -EINVAL;
9516 	}
9517 
9518 	/* check whether implicit source operand (register R6) is readable */
9519 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9520 	if (err)
9521 		return err;
9522 
9523 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9524 	 * gen_ld_abs() may terminate the program at runtime, leading to
9525 	 * reference leak.
9526 	 */
9527 	err = check_reference_leak(env);
9528 	if (err) {
9529 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9530 		return err;
9531 	}
9532 
9533 	if (env->cur_state->active_spin_lock) {
9534 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9535 		return -EINVAL;
9536 	}
9537 
9538 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9539 		verbose(env,
9540 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9541 		return -EINVAL;
9542 	}
9543 
9544 	if (mode == BPF_IND) {
9545 		/* check explicit source operand */
9546 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9547 		if (err)
9548 			return err;
9549 	}
9550 
9551 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9552 	if (err < 0)
9553 		return err;
9554 
9555 	/* reset caller saved regs to unreadable */
9556 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9557 		mark_reg_not_init(env, regs, caller_saved[i]);
9558 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9559 	}
9560 
9561 	/* mark destination R0 register as readable, since it contains
9562 	 * the value fetched from the packet.
9563 	 * Already marked as written above.
9564 	 */
9565 	mark_reg_unknown(env, regs, BPF_REG_0);
9566 	/* ld_abs load up to 32-bit skb data. */
9567 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9568 	return 0;
9569 }
9570 
9571 static int check_return_code(struct bpf_verifier_env *env)
9572 {
9573 	struct tnum enforce_attach_type_range = tnum_unknown;
9574 	const struct bpf_prog *prog = env->prog;
9575 	struct bpf_reg_state *reg;
9576 	struct tnum range = tnum_range(0, 1);
9577 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9578 	int err;
9579 	struct bpf_func_state *frame = env->cur_state->frame[0];
9580 	const bool is_subprog = frame->subprogno;
9581 
9582 	/* LSM and struct_ops func-ptr's return type could be "void" */
9583 	if (!is_subprog &&
9584 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9585 	     prog_type == BPF_PROG_TYPE_LSM) &&
9586 	    !prog->aux->attach_func_proto->type)
9587 		return 0;
9588 
9589 	/* eBPF calling convention is such that R0 is used
9590 	 * to return the value from eBPF program.
9591 	 * Make sure that it's readable at this time
9592 	 * of bpf_exit, which means that program wrote
9593 	 * something into it earlier
9594 	 */
9595 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9596 	if (err)
9597 		return err;
9598 
9599 	if (is_pointer_value(env, BPF_REG_0)) {
9600 		verbose(env, "R0 leaks addr as return value\n");
9601 		return -EACCES;
9602 	}
9603 
9604 	reg = cur_regs(env) + BPF_REG_0;
9605 
9606 	if (frame->in_async_callback_fn) {
9607 		/* enforce return zero from async callbacks like timer */
9608 		if (reg->type != SCALAR_VALUE) {
9609 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9610 				reg_type_str[reg->type]);
9611 			return -EINVAL;
9612 		}
9613 
9614 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9615 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9616 			return -EINVAL;
9617 		}
9618 		return 0;
9619 	}
9620 
9621 	if (is_subprog) {
9622 		if (reg->type != SCALAR_VALUE) {
9623 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9624 				reg_type_str[reg->type]);
9625 			return -EINVAL;
9626 		}
9627 		return 0;
9628 	}
9629 
9630 	switch (prog_type) {
9631 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9632 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9633 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9634 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9635 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9636 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9637 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9638 			range = tnum_range(1, 1);
9639 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9640 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9641 			range = tnum_range(0, 3);
9642 		break;
9643 	case BPF_PROG_TYPE_CGROUP_SKB:
9644 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9645 			range = tnum_range(0, 3);
9646 			enforce_attach_type_range = tnum_range(2, 3);
9647 		}
9648 		break;
9649 	case BPF_PROG_TYPE_CGROUP_SOCK:
9650 	case BPF_PROG_TYPE_SOCK_OPS:
9651 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9652 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9653 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9654 		break;
9655 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9656 		if (!env->prog->aux->attach_btf_id)
9657 			return 0;
9658 		range = tnum_const(0);
9659 		break;
9660 	case BPF_PROG_TYPE_TRACING:
9661 		switch (env->prog->expected_attach_type) {
9662 		case BPF_TRACE_FENTRY:
9663 		case BPF_TRACE_FEXIT:
9664 			range = tnum_const(0);
9665 			break;
9666 		case BPF_TRACE_RAW_TP:
9667 		case BPF_MODIFY_RETURN:
9668 			return 0;
9669 		case BPF_TRACE_ITER:
9670 			break;
9671 		default:
9672 			return -ENOTSUPP;
9673 		}
9674 		break;
9675 	case BPF_PROG_TYPE_SK_LOOKUP:
9676 		range = tnum_range(SK_DROP, SK_PASS);
9677 		break;
9678 	case BPF_PROG_TYPE_EXT:
9679 		/* freplace program can return anything as its return value
9680 		 * depends on the to-be-replaced kernel func or bpf program.
9681 		 */
9682 	default:
9683 		return 0;
9684 	}
9685 
9686 	if (reg->type != SCALAR_VALUE) {
9687 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9688 			reg_type_str[reg->type]);
9689 		return -EINVAL;
9690 	}
9691 
9692 	if (!tnum_in(range, reg->var_off)) {
9693 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9694 		return -EINVAL;
9695 	}
9696 
9697 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9698 	    tnum_in(enforce_attach_type_range, reg->var_off))
9699 		env->prog->enforce_expected_attach_type = 1;
9700 	return 0;
9701 }
9702 
9703 /* non-recursive DFS pseudo code
9704  * 1  procedure DFS-iterative(G,v):
9705  * 2      label v as discovered
9706  * 3      let S be a stack
9707  * 4      S.push(v)
9708  * 5      while S is not empty
9709  * 6            t <- S.pop()
9710  * 7            if t is what we're looking for:
9711  * 8                return t
9712  * 9            for all edges e in G.adjacentEdges(t) do
9713  * 10               if edge e is already labelled
9714  * 11                   continue with the next edge
9715  * 12               w <- G.adjacentVertex(t,e)
9716  * 13               if vertex w is not discovered and not explored
9717  * 14                   label e as tree-edge
9718  * 15                   label w as discovered
9719  * 16                   S.push(w)
9720  * 17                   continue at 5
9721  * 18               else if vertex w is discovered
9722  * 19                   label e as back-edge
9723  * 20               else
9724  * 21                   // vertex w is explored
9725  * 22                   label e as forward- or cross-edge
9726  * 23           label t as explored
9727  * 24           S.pop()
9728  *
9729  * convention:
9730  * 0x10 - discovered
9731  * 0x11 - discovered and fall-through edge labelled
9732  * 0x12 - discovered and fall-through and branch edges labelled
9733  * 0x20 - explored
9734  */
9735 
9736 enum {
9737 	DISCOVERED = 0x10,
9738 	EXPLORED = 0x20,
9739 	FALLTHROUGH = 1,
9740 	BRANCH = 2,
9741 };
9742 
9743 static u32 state_htab_size(struct bpf_verifier_env *env)
9744 {
9745 	return env->prog->len;
9746 }
9747 
9748 static struct bpf_verifier_state_list **explored_state(
9749 					struct bpf_verifier_env *env,
9750 					int idx)
9751 {
9752 	struct bpf_verifier_state *cur = env->cur_state;
9753 	struct bpf_func_state *state = cur->frame[cur->curframe];
9754 
9755 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9756 }
9757 
9758 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9759 {
9760 	env->insn_aux_data[idx].prune_point = true;
9761 }
9762 
9763 enum {
9764 	DONE_EXPLORING = 0,
9765 	KEEP_EXPLORING = 1,
9766 };
9767 
9768 /* t, w, e - match pseudo-code above:
9769  * t - index of current instruction
9770  * w - next instruction
9771  * e - edge
9772  */
9773 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9774 		     bool loop_ok)
9775 {
9776 	int *insn_stack = env->cfg.insn_stack;
9777 	int *insn_state = env->cfg.insn_state;
9778 
9779 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9780 		return DONE_EXPLORING;
9781 
9782 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9783 		return DONE_EXPLORING;
9784 
9785 	if (w < 0 || w >= env->prog->len) {
9786 		verbose_linfo(env, t, "%d: ", t);
9787 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9788 		return -EINVAL;
9789 	}
9790 
9791 	if (e == BRANCH)
9792 		/* mark branch target for state pruning */
9793 		init_explored_state(env, w);
9794 
9795 	if (insn_state[w] == 0) {
9796 		/* tree-edge */
9797 		insn_state[t] = DISCOVERED | e;
9798 		insn_state[w] = DISCOVERED;
9799 		if (env->cfg.cur_stack >= env->prog->len)
9800 			return -E2BIG;
9801 		insn_stack[env->cfg.cur_stack++] = w;
9802 		return KEEP_EXPLORING;
9803 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9804 		if (loop_ok && env->bpf_capable)
9805 			return DONE_EXPLORING;
9806 		verbose_linfo(env, t, "%d: ", t);
9807 		verbose_linfo(env, w, "%d: ", w);
9808 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9809 		return -EINVAL;
9810 	} else if (insn_state[w] == EXPLORED) {
9811 		/* forward- or cross-edge */
9812 		insn_state[t] = DISCOVERED | e;
9813 	} else {
9814 		verbose(env, "insn state internal bug\n");
9815 		return -EFAULT;
9816 	}
9817 	return DONE_EXPLORING;
9818 }
9819 
9820 static int visit_func_call_insn(int t, int insn_cnt,
9821 				struct bpf_insn *insns,
9822 				struct bpf_verifier_env *env,
9823 				bool visit_callee)
9824 {
9825 	int ret;
9826 
9827 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9828 	if (ret)
9829 		return ret;
9830 
9831 	if (t + 1 < insn_cnt)
9832 		init_explored_state(env, t + 1);
9833 	if (visit_callee) {
9834 		init_explored_state(env, t);
9835 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9836 				/* It's ok to allow recursion from CFG point of
9837 				 * view. __check_func_call() will do the actual
9838 				 * check.
9839 				 */
9840 				bpf_pseudo_func(insns + t));
9841 	}
9842 	return ret;
9843 }
9844 
9845 /* Visits the instruction at index t and returns one of the following:
9846  *  < 0 - an error occurred
9847  *  DONE_EXPLORING - the instruction was fully explored
9848  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9849  */
9850 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9851 {
9852 	struct bpf_insn *insns = env->prog->insnsi;
9853 	int ret;
9854 
9855 	if (bpf_pseudo_func(insns + t))
9856 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9857 
9858 	/* All non-branch instructions have a single fall-through edge. */
9859 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9860 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9861 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9862 
9863 	switch (BPF_OP(insns[t].code)) {
9864 	case BPF_EXIT:
9865 		return DONE_EXPLORING;
9866 
9867 	case BPF_CALL:
9868 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9869 			/* Mark this call insn to trigger is_state_visited() check
9870 			 * before call itself is processed by __check_func_call().
9871 			 * Otherwise new async state will be pushed for further
9872 			 * exploration.
9873 			 */
9874 			init_explored_state(env, t);
9875 		return visit_func_call_insn(t, insn_cnt, insns, env,
9876 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9877 
9878 	case BPF_JA:
9879 		if (BPF_SRC(insns[t].code) != BPF_K)
9880 			return -EINVAL;
9881 
9882 		/* unconditional jump with single edge */
9883 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9884 				true);
9885 		if (ret)
9886 			return ret;
9887 
9888 		/* unconditional jmp is not a good pruning point,
9889 		 * but it's marked, since backtracking needs
9890 		 * to record jmp history in is_state_visited().
9891 		 */
9892 		init_explored_state(env, t + insns[t].off + 1);
9893 		/* tell verifier to check for equivalent states
9894 		 * after every call and jump
9895 		 */
9896 		if (t + 1 < insn_cnt)
9897 			init_explored_state(env, t + 1);
9898 
9899 		return ret;
9900 
9901 	default:
9902 		/* conditional jump with two edges */
9903 		init_explored_state(env, t);
9904 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9905 		if (ret)
9906 			return ret;
9907 
9908 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9909 	}
9910 }
9911 
9912 /* non-recursive depth-first-search to detect loops in BPF program
9913  * loop == back-edge in directed graph
9914  */
9915 static int check_cfg(struct bpf_verifier_env *env)
9916 {
9917 	int insn_cnt = env->prog->len;
9918 	int *insn_stack, *insn_state;
9919 	int ret = 0;
9920 	int i;
9921 
9922 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9923 	if (!insn_state)
9924 		return -ENOMEM;
9925 
9926 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9927 	if (!insn_stack) {
9928 		kvfree(insn_state);
9929 		return -ENOMEM;
9930 	}
9931 
9932 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9933 	insn_stack[0] = 0; /* 0 is the first instruction */
9934 	env->cfg.cur_stack = 1;
9935 
9936 	while (env->cfg.cur_stack > 0) {
9937 		int t = insn_stack[env->cfg.cur_stack - 1];
9938 
9939 		ret = visit_insn(t, insn_cnt, env);
9940 		switch (ret) {
9941 		case DONE_EXPLORING:
9942 			insn_state[t] = EXPLORED;
9943 			env->cfg.cur_stack--;
9944 			break;
9945 		case KEEP_EXPLORING:
9946 			break;
9947 		default:
9948 			if (ret > 0) {
9949 				verbose(env, "visit_insn internal bug\n");
9950 				ret = -EFAULT;
9951 			}
9952 			goto err_free;
9953 		}
9954 	}
9955 
9956 	if (env->cfg.cur_stack < 0) {
9957 		verbose(env, "pop stack internal bug\n");
9958 		ret = -EFAULT;
9959 		goto err_free;
9960 	}
9961 
9962 	for (i = 0; i < insn_cnt; i++) {
9963 		if (insn_state[i] != EXPLORED) {
9964 			verbose(env, "unreachable insn %d\n", i);
9965 			ret = -EINVAL;
9966 			goto err_free;
9967 		}
9968 	}
9969 	ret = 0; /* cfg looks good */
9970 
9971 err_free:
9972 	kvfree(insn_state);
9973 	kvfree(insn_stack);
9974 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9975 	return ret;
9976 }
9977 
9978 static int check_abnormal_return(struct bpf_verifier_env *env)
9979 {
9980 	int i;
9981 
9982 	for (i = 1; i < env->subprog_cnt; i++) {
9983 		if (env->subprog_info[i].has_ld_abs) {
9984 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9985 			return -EINVAL;
9986 		}
9987 		if (env->subprog_info[i].has_tail_call) {
9988 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9989 			return -EINVAL;
9990 		}
9991 	}
9992 	return 0;
9993 }
9994 
9995 /* The minimum supported BTF func info size */
9996 #define MIN_BPF_FUNCINFO_SIZE	8
9997 #define MAX_FUNCINFO_REC_SIZE	252
9998 
9999 static int check_btf_func(struct bpf_verifier_env *env,
10000 			  const union bpf_attr *attr,
10001 			  bpfptr_t uattr)
10002 {
10003 	const struct btf_type *type, *func_proto, *ret_type;
10004 	u32 i, nfuncs, urec_size, min_size;
10005 	u32 krec_size = sizeof(struct bpf_func_info);
10006 	struct bpf_func_info *krecord;
10007 	struct bpf_func_info_aux *info_aux = NULL;
10008 	struct bpf_prog *prog;
10009 	const struct btf *btf;
10010 	bpfptr_t urecord;
10011 	u32 prev_offset = 0;
10012 	bool scalar_return;
10013 	int ret = -ENOMEM;
10014 
10015 	nfuncs = attr->func_info_cnt;
10016 	if (!nfuncs) {
10017 		if (check_abnormal_return(env))
10018 			return -EINVAL;
10019 		return 0;
10020 	}
10021 
10022 	if (nfuncs != env->subprog_cnt) {
10023 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10024 		return -EINVAL;
10025 	}
10026 
10027 	urec_size = attr->func_info_rec_size;
10028 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10029 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10030 	    urec_size % sizeof(u32)) {
10031 		verbose(env, "invalid func info rec size %u\n", urec_size);
10032 		return -EINVAL;
10033 	}
10034 
10035 	prog = env->prog;
10036 	btf = prog->aux->btf;
10037 
10038 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10039 	min_size = min_t(u32, krec_size, urec_size);
10040 
10041 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10042 	if (!krecord)
10043 		return -ENOMEM;
10044 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10045 	if (!info_aux)
10046 		goto err_free;
10047 
10048 	for (i = 0; i < nfuncs; i++) {
10049 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10050 		if (ret) {
10051 			if (ret == -E2BIG) {
10052 				verbose(env, "nonzero tailing record in func info");
10053 				/* set the size kernel expects so loader can zero
10054 				 * out the rest of the record.
10055 				 */
10056 				if (copy_to_bpfptr_offset(uattr,
10057 							  offsetof(union bpf_attr, func_info_rec_size),
10058 							  &min_size, sizeof(min_size)))
10059 					ret = -EFAULT;
10060 			}
10061 			goto err_free;
10062 		}
10063 
10064 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10065 			ret = -EFAULT;
10066 			goto err_free;
10067 		}
10068 
10069 		/* check insn_off */
10070 		ret = -EINVAL;
10071 		if (i == 0) {
10072 			if (krecord[i].insn_off) {
10073 				verbose(env,
10074 					"nonzero insn_off %u for the first func info record",
10075 					krecord[i].insn_off);
10076 				goto err_free;
10077 			}
10078 		} else if (krecord[i].insn_off <= prev_offset) {
10079 			verbose(env,
10080 				"same or smaller insn offset (%u) than previous func info record (%u)",
10081 				krecord[i].insn_off, prev_offset);
10082 			goto err_free;
10083 		}
10084 
10085 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10086 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10087 			goto err_free;
10088 		}
10089 
10090 		/* check type_id */
10091 		type = btf_type_by_id(btf, krecord[i].type_id);
10092 		if (!type || !btf_type_is_func(type)) {
10093 			verbose(env, "invalid type id %d in func info",
10094 				krecord[i].type_id);
10095 			goto err_free;
10096 		}
10097 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10098 
10099 		func_proto = btf_type_by_id(btf, type->type);
10100 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10101 			/* btf_func_check() already verified it during BTF load */
10102 			goto err_free;
10103 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10104 		scalar_return =
10105 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10106 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10107 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10108 			goto err_free;
10109 		}
10110 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10111 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10112 			goto err_free;
10113 		}
10114 
10115 		prev_offset = krecord[i].insn_off;
10116 		bpfptr_add(&urecord, urec_size);
10117 	}
10118 
10119 	prog->aux->func_info = krecord;
10120 	prog->aux->func_info_cnt = nfuncs;
10121 	prog->aux->func_info_aux = info_aux;
10122 	return 0;
10123 
10124 err_free:
10125 	kvfree(krecord);
10126 	kfree(info_aux);
10127 	return ret;
10128 }
10129 
10130 static void adjust_btf_func(struct bpf_verifier_env *env)
10131 {
10132 	struct bpf_prog_aux *aux = env->prog->aux;
10133 	int i;
10134 
10135 	if (!aux->func_info)
10136 		return;
10137 
10138 	for (i = 0; i < env->subprog_cnt; i++)
10139 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10140 }
10141 
10142 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
10143 		sizeof(((struct bpf_line_info *)(0))->line_col))
10144 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10145 
10146 static int check_btf_line(struct bpf_verifier_env *env,
10147 			  const union bpf_attr *attr,
10148 			  bpfptr_t uattr)
10149 {
10150 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10151 	struct bpf_subprog_info *sub;
10152 	struct bpf_line_info *linfo;
10153 	struct bpf_prog *prog;
10154 	const struct btf *btf;
10155 	bpfptr_t ulinfo;
10156 	int err;
10157 
10158 	nr_linfo = attr->line_info_cnt;
10159 	if (!nr_linfo)
10160 		return 0;
10161 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10162 		return -EINVAL;
10163 
10164 	rec_size = attr->line_info_rec_size;
10165 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10166 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10167 	    rec_size & (sizeof(u32) - 1))
10168 		return -EINVAL;
10169 
10170 	/* Need to zero it in case the userspace may
10171 	 * pass in a smaller bpf_line_info object.
10172 	 */
10173 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10174 			 GFP_KERNEL | __GFP_NOWARN);
10175 	if (!linfo)
10176 		return -ENOMEM;
10177 
10178 	prog = env->prog;
10179 	btf = prog->aux->btf;
10180 
10181 	s = 0;
10182 	sub = env->subprog_info;
10183 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10184 	expected_size = sizeof(struct bpf_line_info);
10185 	ncopy = min_t(u32, expected_size, rec_size);
10186 	for (i = 0; i < nr_linfo; i++) {
10187 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10188 		if (err) {
10189 			if (err == -E2BIG) {
10190 				verbose(env, "nonzero tailing record in line_info");
10191 				if (copy_to_bpfptr_offset(uattr,
10192 							  offsetof(union bpf_attr, line_info_rec_size),
10193 							  &expected_size, sizeof(expected_size)))
10194 					err = -EFAULT;
10195 			}
10196 			goto err_free;
10197 		}
10198 
10199 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10200 			err = -EFAULT;
10201 			goto err_free;
10202 		}
10203 
10204 		/*
10205 		 * Check insn_off to ensure
10206 		 * 1) strictly increasing AND
10207 		 * 2) bounded by prog->len
10208 		 *
10209 		 * The linfo[0].insn_off == 0 check logically falls into
10210 		 * the later "missing bpf_line_info for func..." case
10211 		 * because the first linfo[0].insn_off must be the
10212 		 * first sub also and the first sub must have
10213 		 * subprog_info[0].start == 0.
10214 		 */
10215 		if ((i && linfo[i].insn_off <= prev_offset) ||
10216 		    linfo[i].insn_off >= prog->len) {
10217 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10218 				i, linfo[i].insn_off, prev_offset,
10219 				prog->len);
10220 			err = -EINVAL;
10221 			goto err_free;
10222 		}
10223 
10224 		if (!prog->insnsi[linfo[i].insn_off].code) {
10225 			verbose(env,
10226 				"Invalid insn code at line_info[%u].insn_off\n",
10227 				i);
10228 			err = -EINVAL;
10229 			goto err_free;
10230 		}
10231 
10232 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10233 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10234 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10235 			err = -EINVAL;
10236 			goto err_free;
10237 		}
10238 
10239 		if (s != env->subprog_cnt) {
10240 			if (linfo[i].insn_off == sub[s].start) {
10241 				sub[s].linfo_idx = i;
10242 				s++;
10243 			} else if (sub[s].start < linfo[i].insn_off) {
10244 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10245 				err = -EINVAL;
10246 				goto err_free;
10247 			}
10248 		}
10249 
10250 		prev_offset = linfo[i].insn_off;
10251 		bpfptr_add(&ulinfo, rec_size);
10252 	}
10253 
10254 	if (s != env->subprog_cnt) {
10255 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10256 			env->subprog_cnt - s, s);
10257 		err = -EINVAL;
10258 		goto err_free;
10259 	}
10260 
10261 	prog->aux->linfo = linfo;
10262 	prog->aux->nr_linfo = nr_linfo;
10263 
10264 	return 0;
10265 
10266 err_free:
10267 	kvfree(linfo);
10268 	return err;
10269 }
10270 
10271 static int check_btf_info(struct bpf_verifier_env *env,
10272 			  const union bpf_attr *attr,
10273 			  bpfptr_t uattr)
10274 {
10275 	struct btf *btf;
10276 	int err;
10277 
10278 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10279 		if (check_abnormal_return(env))
10280 			return -EINVAL;
10281 		return 0;
10282 	}
10283 
10284 	btf = btf_get_by_fd(attr->prog_btf_fd);
10285 	if (IS_ERR(btf))
10286 		return PTR_ERR(btf);
10287 	if (btf_is_kernel(btf)) {
10288 		btf_put(btf);
10289 		return -EACCES;
10290 	}
10291 	env->prog->aux->btf = btf;
10292 
10293 	err = check_btf_func(env, attr, uattr);
10294 	if (err)
10295 		return err;
10296 
10297 	err = check_btf_line(env, attr, uattr);
10298 	if (err)
10299 		return err;
10300 
10301 	return 0;
10302 }
10303 
10304 /* check %cur's range satisfies %old's */
10305 static bool range_within(struct bpf_reg_state *old,
10306 			 struct bpf_reg_state *cur)
10307 {
10308 	return old->umin_value <= cur->umin_value &&
10309 	       old->umax_value >= cur->umax_value &&
10310 	       old->smin_value <= cur->smin_value &&
10311 	       old->smax_value >= cur->smax_value &&
10312 	       old->u32_min_value <= cur->u32_min_value &&
10313 	       old->u32_max_value >= cur->u32_max_value &&
10314 	       old->s32_min_value <= cur->s32_min_value &&
10315 	       old->s32_max_value >= cur->s32_max_value;
10316 }
10317 
10318 /* If in the old state two registers had the same id, then they need to have
10319  * the same id in the new state as well.  But that id could be different from
10320  * the old state, so we need to track the mapping from old to new ids.
10321  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10322  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10323  * regs with a different old id could still have new id 9, we don't care about
10324  * that.
10325  * So we look through our idmap to see if this old id has been seen before.  If
10326  * so, we require the new id to match; otherwise, we add the id pair to the map.
10327  */
10328 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10329 {
10330 	unsigned int i;
10331 
10332 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10333 		if (!idmap[i].old) {
10334 			/* Reached an empty slot; haven't seen this id before */
10335 			idmap[i].old = old_id;
10336 			idmap[i].cur = cur_id;
10337 			return true;
10338 		}
10339 		if (idmap[i].old == old_id)
10340 			return idmap[i].cur == cur_id;
10341 	}
10342 	/* We ran out of idmap slots, which should be impossible */
10343 	WARN_ON_ONCE(1);
10344 	return false;
10345 }
10346 
10347 static void clean_func_state(struct bpf_verifier_env *env,
10348 			     struct bpf_func_state *st)
10349 {
10350 	enum bpf_reg_liveness live;
10351 	int i, j;
10352 
10353 	for (i = 0; i < BPF_REG_FP; i++) {
10354 		live = st->regs[i].live;
10355 		/* liveness must not touch this register anymore */
10356 		st->regs[i].live |= REG_LIVE_DONE;
10357 		if (!(live & REG_LIVE_READ))
10358 			/* since the register is unused, clear its state
10359 			 * to make further comparison simpler
10360 			 */
10361 			__mark_reg_not_init(env, &st->regs[i]);
10362 	}
10363 
10364 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10365 		live = st->stack[i].spilled_ptr.live;
10366 		/* liveness must not touch this stack slot anymore */
10367 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10368 		if (!(live & REG_LIVE_READ)) {
10369 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10370 			for (j = 0; j < BPF_REG_SIZE; j++)
10371 				st->stack[i].slot_type[j] = STACK_INVALID;
10372 		}
10373 	}
10374 }
10375 
10376 static void clean_verifier_state(struct bpf_verifier_env *env,
10377 				 struct bpf_verifier_state *st)
10378 {
10379 	int i;
10380 
10381 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10382 		/* all regs in this state in all frames were already marked */
10383 		return;
10384 
10385 	for (i = 0; i <= st->curframe; i++)
10386 		clean_func_state(env, st->frame[i]);
10387 }
10388 
10389 /* the parentage chains form a tree.
10390  * the verifier states are added to state lists at given insn and
10391  * pushed into state stack for future exploration.
10392  * when the verifier reaches bpf_exit insn some of the verifer states
10393  * stored in the state lists have their final liveness state already,
10394  * but a lot of states will get revised from liveness point of view when
10395  * the verifier explores other branches.
10396  * Example:
10397  * 1: r0 = 1
10398  * 2: if r1 == 100 goto pc+1
10399  * 3: r0 = 2
10400  * 4: exit
10401  * when the verifier reaches exit insn the register r0 in the state list of
10402  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10403  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10404  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10405  *
10406  * Since the verifier pushes the branch states as it sees them while exploring
10407  * the program the condition of walking the branch instruction for the second
10408  * time means that all states below this branch were already explored and
10409  * their final liveness marks are already propagated.
10410  * Hence when the verifier completes the search of state list in is_state_visited()
10411  * we can call this clean_live_states() function to mark all liveness states
10412  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10413  * will not be used.
10414  * This function also clears the registers and stack for states that !READ
10415  * to simplify state merging.
10416  *
10417  * Important note here that walking the same branch instruction in the callee
10418  * doesn't meant that the states are DONE. The verifier has to compare
10419  * the callsites
10420  */
10421 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10422 			      struct bpf_verifier_state *cur)
10423 {
10424 	struct bpf_verifier_state_list *sl;
10425 	int i;
10426 
10427 	sl = *explored_state(env, insn);
10428 	while (sl) {
10429 		if (sl->state.branches)
10430 			goto next;
10431 		if (sl->state.insn_idx != insn ||
10432 		    sl->state.curframe != cur->curframe)
10433 			goto next;
10434 		for (i = 0; i <= cur->curframe; i++)
10435 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10436 				goto next;
10437 		clean_verifier_state(env, &sl->state);
10438 next:
10439 		sl = sl->next;
10440 	}
10441 }
10442 
10443 /* Returns true if (rold safe implies rcur safe) */
10444 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10445 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10446 {
10447 	bool equal;
10448 
10449 	if (!(rold->live & REG_LIVE_READ))
10450 		/* explored state didn't use this */
10451 		return true;
10452 
10453 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10454 
10455 	if (rold->type == PTR_TO_STACK)
10456 		/* two stack pointers are equal only if they're pointing to
10457 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10458 		 */
10459 		return equal && rold->frameno == rcur->frameno;
10460 
10461 	if (equal)
10462 		return true;
10463 
10464 	if (rold->type == NOT_INIT)
10465 		/* explored state can't have used this */
10466 		return true;
10467 	if (rcur->type == NOT_INIT)
10468 		return false;
10469 	switch (rold->type) {
10470 	case SCALAR_VALUE:
10471 		if (env->explore_alu_limits)
10472 			return false;
10473 		if (rcur->type == SCALAR_VALUE) {
10474 			if (!rold->precise && !rcur->precise)
10475 				return true;
10476 			/* new val must satisfy old val knowledge */
10477 			return range_within(rold, rcur) &&
10478 			       tnum_in(rold->var_off, rcur->var_off);
10479 		} else {
10480 			/* We're trying to use a pointer in place of a scalar.
10481 			 * Even if the scalar was unbounded, this could lead to
10482 			 * pointer leaks because scalars are allowed to leak
10483 			 * while pointers are not. We could make this safe in
10484 			 * special cases if root is calling us, but it's
10485 			 * probably not worth the hassle.
10486 			 */
10487 			return false;
10488 		}
10489 	case PTR_TO_MAP_KEY:
10490 	case PTR_TO_MAP_VALUE:
10491 		/* If the new min/max/var_off satisfy the old ones and
10492 		 * everything else matches, we are OK.
10493 		 * 'id' is not compared, since it's only used for maps with
10494 		 * bpf_spin_lock inside map element and in such cases if
10495 		 * the rest of the prog is valid for one map element then
10496 		 * it's valid for all map elements regardless of the key
10497 		 * used in bpf_map_lookup()
10498 		 */
10499 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10500 		       range_within(rold, rcur) &&
10501 		       tnum_in(rold->var_off, rcur->var_off);
10502 	case PTR_TO_MAP_VALUE_OR_NULL:
10503 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10504 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10505 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10506 		 * checked, doing so could have affected others with the same
10507 		 * id, and we can't check for that because we lost the id when
10508 		 * we converted to a PTR_TO_MAP_VALUE.
10509 		 */
10510 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10511 			return false;
10512 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10513 			return false;
10514 		/* Check our ids match any regs they're supposed to */
10515 		return check_ids(rold->id, rcur->id, idmap);
10516 	case PTR_TO_PACKET_META:
10517 	case PTR_TO_PACKET:
10518 		if (rcur->type != rold->type)
10519 			return false;
10520 		/* We must have at least as much range as the old ptr
10521 		 * did, so that any accesses which were safe before are
10522 		 * still safe.  This is true even if old range < old off,
10523 		 * since someone could have accessed through (ptr - k), or
10524 		 * even done ptr -= k in a register, to get a safe access.
10525 		 */
10526 		if (rold->range > rcur->range)
10527 			return false;
10528 		/* If the offsets don't match, we can't trust our alignment;
10529 		 * nor can we be sure that we won't fall out of range.
10530 		 */
10531 		if (rold->off != rcur->off)
10532 			return false;
10533 		/* id relations must be preserved */
10534 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10535 			return false;
10536 		/* new val must satisfy old val knowledge */
10537 		return range_within(rold, rcur) &&
10538 		       tnum_in(rold->var_off, rcur->var_off);
10539 	case PTR_TO_CTX:
10540 	case CONST_PTR_TO_MAP:
10541 	case PTR_TO_PACKET_END:
10542 	case PTR_TO_FLOW_KEYS:
10543 	case PTR_TO_SOCKET:
10544 	case PTR_TO_SOCKET_OR_NULL:
10545 	case PTR_TO_SOCK_COMMON:
10546 	case PTR_TO_SOCK_COMMON_OR_NULL:
10547 	case PTR_TO_TCP_SOCK:
10548 	case PTR_TO_TCP_SOCK_OR_NULL:
10549 	case PTR_TO_XDP_SOCK:
10550 		/* Only valid matches are exact, which memcmp() above
10551 		 * would have accepted
10552 		 */
10553 	default:
10554 		/* Don't know what's going on, just say it's not safe */
10555 		return false;
10556 	}
10557 
10558 	/* Shouldn't get here; if we do, say it's not safe */
10559 	WARN_ON_ONCE(1);
10560 	return false;
10561 }
10562 
10563 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10564 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10565 {
10566 	int i, spi;
10567 
10568 	/* walk slots of the explored stack and ignore any additional
10569 	 * slots in the current stack, since explored(safe) state
10570 	 * didn't use them
10571 	 */
10572 	for (i = 0; i < old->allocated_stack; i++) {
10573 		spi = i / BPF_REG_SIZE;
10574 
10575 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10576 			i += BPF_REG_SIZE - 1;
10577 			/* explored state didn't use this */
10578 			continue;
10579 		}
10580 
10581 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10582 			continue;
10583 
10584 		/* explored stack has more populated slots than current stack
10585 		 * and these slots were used
10586 		 */
10587 		if (i >= cur->allocated_stack)
10588 			return false;
10589 
10590 		/* if old state was safe with misc data in the stack
10591 		 * it will be safe with zero-initialized stack.
10592 		 * The opposite is not true
10593 		 */
10594 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10595 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10596 			continue;
10597 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10598 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10599 			/* Ex: old explored (safe) state has STACK_SPILL in
10600 			 * this stack slot, but current has STACK_MISC ->
10601 			 * this verifier states are not equivalent,
10602 			 * return false to continue verification of this path
10603 			 */
10604 			return false;
10605 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10606 			continue;
10607 		if (!is_spilled_reg(&old->stack[spi]))
10608 			continue;
10609 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10610 			     &cur->stack[spi].spilled_ptr, idmap))
10611 			/* when explored and current stack slot are both storing
10612 			 * spilled registers, check that stored pointers types
10613 			 * are the same as well.
10614 			 * Ex: explored safe path could have stored
10615 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10616 			 * but current path has stored:
10617 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10618 			 * such verifier states are not equivalent.
10619 			 * return false to continue verification of this path
10620 			 */
10621 			return false;
10622 	}
10623 	return true;
10624 }
10625 
10626 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10627 {
10628 	if (old->acquired_refs != cur->acquired_refs)
10629 		return false;
10630 	return !memcmp(old->refs, cur->refs,
10631 		       sizeof(*old->refs) * old->acquired_refs);
10632 }
10633 
10634 /* compare two verifier states
10635  *
10636  * all states stored in state_list are known to be valid, since
10637  * verifier reached 'bpf_exit' instruction through them
10638  *
10639  * this function is called when verifier exploring different branches of
10640  * execution popped from the state stack. If it sees an old state that has
10641  * more strict register state and more strict stack state then this execution
10642  * branch doesn't need to be explored further, since verifier already
10643  * concluded that more strict state leads to valid finish.
10644  *
10645  * Therefore two states are equivalent if register state is more conservative
10646  * and explored stack state is more conservative than the current one.
10647  * Example:
10648  *       explored                   current
10649  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10650  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10651  *
10652  * In other words if current stack state (one being explored) has more
10653  * valid slots than old one that already passed validation, it means
10654  * the verifier can stop exploring and conclude that current state is valid too
10655  *
10656  * Similarly with registers. If explored state has register type as invalid
10657  * whereas register type in current state is meaningful, it means that
10658  * the current state will reach 'bpf_exit' instruction safely
10659  */
10660 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10661 			      struct bpf_func_state *cur)
10662 {
10663 	int i;
10664 
10665 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10666 	for (i = 0; i < MAX_BPF_REG; i++)
10667 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10668 			     env->idmap_scratch))
10669 			return false;
10670 
10671 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10672 		return false;
10673 
10674 	if (!refsafe(old, cur))
10675 		return false;
10676 
10677 	return true;
10678 }
10679 
10680 static bool states_equal(struct bpf_verifier_env *env,
10681 			 struct bpf_verifier_state *old,
10682 			 struct bpf_verifier_state *cur)
10683 {
10684 	int i;
10685 
10686 	if (old->curframe != cur->curframe)
10687 		return false;
10688 
10689 	/* Verification state from speculative execution simulation
10690 	 * must never prune a non-speculative execution one.
10691 	 */
10692 	if (old->speculative && !cur->speculative)
10693 		return false;
10694 
10695 	if (old->active_spin_lock != cur->active_spin_lock)
10696 		return false;
10697 
10698 	/* for states to be equal callsites have to be the same
10699 	 * and all frame states need to be equivalent
10700 	 */
10701 	for (i = 0; i <= old->curframe; i++) {
10702 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10703 			return false;
10704 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10705 			return false;
10706 	}
10707 	return true;
10708 }
10709 
10710 /* Return 0 if no propagation happened. Return negative error code if error
10711  * happened. Otherwise, return the propagated bit.
10712  */
10713 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10714 				  struct bpf_reg_state *reg,
10715 				  struct bpf_reg_state *parent_reg)
10716 {
10717 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10718 	u8 flag = reg->live & REG_LIVE_READ;
10719 	int err;
10720 
10721 	/* When comes here, read flags of PARENT_REG or REG could be any of
10722 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10723 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10724 	 */
10725 	if (parent_flag == REG_LIVE_READ64 ||
10726 	    /* Or if there is no read flag from REG. */
10727 	    !flag ||
10728 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10729 	    parent_flag == flag)
10730 		return 0;
10731 
10732 	err = mark_reg_read(env, reg, parent_reg, flag);
10733 	if (err)
10734 		return err;
10735 
10736 	return flag;
10737 }
10738 
10739 /* A write screens off any subsequent reads; but write marks come from the
10740  * straight-line code between a state and its parent.  When we arrive at an
10741  * equivalent state (jump target or such) we didn't arrive by the straight-line
10742  * code, so read marks in the state must propagate to the parent regardless
10743  * of the state's write marks. That's what 'parent == state->parent' comparison
10744  * in mark_reg_read() is for.
10745  */
10746 static int propagate_liveness(struct bpf_verifier_env *env,
10747 			      const struct bpf_verifier_state *vstate,
10748 			      struct bpf_verifier_state *vparent)
10749 {
10750 	struct bpf_reg_state *state_reg, *parent_reg;
10751 	struct bpf_func_state *state, *parent;
10752 	int i, frame, err = 0;
10753 
10754 	if (vparent->curframe != vstate->curframe) {
10755 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10756 		     vparent->curframe, vstate->curframe);
10757 		return -EFAULT;
10758 	}
10759 	/* Propagate read liveness of registers... */
10760 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10761 	for (frame = 0; frame <= vstate->curframe; frame++) {
10762 		parent = vparent->frame[frame];
10763 		state = vstate->frame[frame];
10764 		parent_reg = parent->regs;
10765 		state_reg = state->regs;
10766 		/* We don't need to worry about FP liveness, it's read-only */
10767 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10768 			err = propagate_liveness_reg(env, &state_reg[i],
10769 						     &parent_reg[i]);
10770 			if (err < 0)
10771 				return err;
10772 			if (err == REG_LIVE_READ64)
10773 				mark_insn_zext(env, &parent_reg[i]);
10774 		}
10775 
10776 		/* Propagate stack slots. */
10777 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10778 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10779 			parent_reg = &parent->stack[i].spilled_ptr;
10780 			state_reg = &state->stack[i].spilled_ptr;
10781 			err = propagate_liveness_reg(env, state_reg,
10782 						     parent_reg);
10783 			if (err < 0)
10784 				return err;
10785 		}
10786 	}
10787 	return 0;
10788 }
10789 
10790 /* find precise scalars in the previous equivalent state and
10791  * propagate them into the current state
10792  */
10793 static int propagate_precision(struct bpf_verifier_env *env,
10794 			       const struct bpf_verifier_state *old)
10795 {
10796 	struct bpf_reg_state *state_reg;
10797 	struct bpf_func_state *state;
10798 	int i, err = 0;
10799 
10800 	state = old->frame[old->curframe];
10801 	state_reg = state->regs;
10802 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10803 		if (state_reg->type != SCALAR_VALUE ||
10804 		    !state_reg->precise)
10805 			continue;
10806 		if (env->log.level & BPF_LOG_LEVEL2)
10807 			verbose(env, "propagating r%d\n", i);
10808 		err = mark_chain_precision(env, i);
10809 		if (err < 0)
10810 			return err;
10811 	}
10812 
10813 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10814 		if (!is_spilled_reg(&state->stack[i]))
10815 			continue;
10816 		state_reg = &state->stack[i].spilled_ptr;
10817 		if (state_reg->type != SCALAR_VALUE ||
10818 		    !state_reg->precise)
10819 			continue;
10820 		if (env->log.level & BPF_LOG_LEVEL2)
10821 			verbose(env, "propagating fp%d\n",
10822 				(-i - 1) * BPF_REG_SIZE);
10823 		err = mark_chain_precision_stack(env, i);
10824 		if (err < 0)
10825 			return err;
10826 	}
10827 	return 0;
10828 }
10829 
10830 static bool states_maybe_looping(struct bpf_verifier_state *old,
10831 				 struct bpf_verifier_state *cur)
10832 {
10833 	struct bpf_func_state *fold, *fcur;
10834 	int i, fr = cur->curframe;
10835 
10836 	if (old->curframe != fr)
10837 		return false;
10838 
10839 	fold = old->frame[fr];
10840 	fcur = cur->frame[fr];
10841 	for (i = 0; i < MAX_BPF_REG; i++)
10842 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10843 			   offsetof(struct bpf_reg_state, parent)))
10844 			return false;
10845 	return true;
10846 }
10847 
10848 
10849 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10850 {
10851 	struct bpf_verifier_state_list *new_sl;
10852 	struct bpf_verifier_state_list *sl, **pprev;
10853 	struct bpf_verifier_state *cur = env->cur_state, *new;
10854 	int i, j, err, states_cnt = 0;
10855 	bool add_new_state = env->test_state_freq ? true : false;
10856 
10857 	cur->last_insn_idx = env->prev_insn_idx;
10858 	if (!env->insn_aux_data[insn_idx].prune_point)
10859 		/* this 'insn_idx' instruction wasn't marked, so we will not
10860 		 * be doing state search here
10861 		 */
10862 		return 0;
10863 
10864 	/* bpf progs typically have pruning point every 4 instructions
10865 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10866 	 * Do not add new state for future pruning if the verifier hasn't seen
10867 	 * at least 2 jumps and at least 8 instructions.
10868 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10869 	 * In tests that amounts to up to 50% reduction into total verifier
10870 	 * memory consumption and 20% verifier time speedup.
10871 	 */
10872 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10873 	    env->insn_processed - env->prev_insn_processed >= 8)
10874 		add_new_state = true;
10875 
10876 	pprev = explored_state(env, insn_idx);
10877 	sl = *pprev;
10878 
10879 	clean_live_states(env, insn_idx, cur);
10880 
10881 	while (sl) {
10882 		states_cnt++;
10883 		if (sl->state.insn_idx != insn_idx)
10884 			goto next;
10885 
10886 		if (sl->state.branches) {
10887 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10888 
10889 			if (frame->in_async_callback_fn &&
10890 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10891 				/* Different async_entry_cnt means that the verifier is
10892 				 * processing another entry into async callback.
10893 				 * Seeing the same state is not an indication of infinite
10894 				 * loop or infinite recursion.
10895 				 * But finding the same state doesn't mean that it's safe
10896 				 * to stop processing the current state. The previous state
10897 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10898 				 * Checking in_async_callback_fn alone is not enough either.
10899 				 * Since the verifier still needs to catch infinite loops
10900 				 * inside async callbacks.
10901 				 */
10902 			} else if (states_maybe_looping(&sl->state, cur) &&
10903 				   states_equal(env, &sl->state, cur)) {
10904 				verbose_linfo(env, insn_idx, "; ");
10905 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10906 				return -EINVAL;
10907 			}
10908 			/* if the verifier is processing a loop, avoid adding new state
10909 			 * too often, since different loop iterations have distinct
10910 			 * states and may not help future pruning.
10911 			 * This threshold shouldn't be too low to make sure that
10912 			 * a loop with large bound will be rejected quickly.
10913 			 * The most abusive loop will be:
10914 			 * r1 += 1
10915 			 * if r1 < 1000000 goto pc-2
10916 			 * 1M insn_procssed limit / 100 == 10k peak states.
10917 			 * This threshold shouldn't be too high either, since states
10918 			 * at the end of the loop are likely to be useful in pruning.
10919 			 */
10920 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10921 			    env->insn_processed - env->prev_insn_processed < 100)
10922 				add_new_state = false;
10923 			goto miss;
10924 		}
10925 		if (states_equal(env, &sl->state, cur)) {
10926 			sl->hit_cnt++;
10927 			/* reached equivalent register/stack state,
10928 			 * prune the search.
10929 			 * Registers read by the continuation are read by us.
10930 			 * If we have any write marks in env->cur_state, they
10931 			 * will prevent corresponding reads in the continuation
10932 			 * from reaching our parent (an explored_state).  Our
10933 			 * own state will get the read marks recorded, but
10934 			 * they'll be immediately forgotten as we're pruning
10935 			 * this state and will pop a new one.
10936 			 */
10937 			err = propagate_liveness(env, &sl->state, cur);
10938 
10939 			/* if previous state reached the exit with precision and
10940 			 * current state is equivalent to it (except precsion marks)
10941 			 * the precision needs to be propagated back in
10942 			 * the current state.
10943 			 */
10944 			err = err ? : push_jmp_history(env, cur);
10945 			err = err ? : propagate_precision(env, &sl->state);
10946 			if (err)
10947 				return err;
10948 			return 1;
10949 		}
10950 miss:
10951 		/* when new state is not going to be added do not increase miss count.
10952 		 * Otherwise several loop iterations will remove the state
10953 		 * recorded earlier. The goal of these heuristics is to have
10954 		 * states from some iterations of the loop (some in the beginning
10955 		 * and some at the end) to help pruning.
10956 		 */
10957 		if (add_new_state)
10958 			sl->miss_cnt++;
10959 		/* heuristic to determine whether this state is beneficial
10960 		 * to keep checking from state equivalence point of view.
10961 		 * Higher numbers increase max_states_per_insn and verification time,
10962 		 * but do not meaningfully decrease insn_processed.
10963 		 */
10964 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10965 			/* the state is unlikely to be useful. Remove it to
10966 			 * speed up verification
10967 			 */
10968 			*pprev = sl->next;
10969 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10970 				u32 br = sl->state.branches;
10971 
10972 				WARN_ONCE(br,
10973 					  "BUG live_done but branches_to_explore %d\n",
10974 					  br);
10975 				free_verifier_state(&sl->state, false);
10976 				kfree(sl);
10977 				env->peak_states--;
10978 			} else {
10979 				/* cannot free this state, since parentage chain may
10980 				 * walk it later. Add it for free_list instead to
10981 				 * be freed at the end of verification
10982 				 */
10983 				sl->next = env->free_list;
10984 				env->free_list = sl;
10985 			}
10986 			sl = *pprev;
10987 			continue;
10988 		}
10989 next:
10990 		pprev = &sl->next;
10991 		sl = *pprev;
10992 	}
10993 
10994 	if (env->max_states_per_insn < states_cnt)
10995 		env->max_states_per_insn = states_cnt;
10996 
10997 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10998 		return push_jmp_history(env, cur);
10999 
11000 	if (!add_new_state)
11001 		return push_jmp_history(env, cur);
11002 
11003 	/* There were no equivalent states, remember the current one.
11004 	 * Technically the current state is not proven to be safe yet,
11005 	 * but it will either reach outer most bpf_exit (which means it's safe)
11006 	 * or it will be rejected. When there are no loops the verifier won't be
11007 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11008 	 * again on the way to bpf_exit.
11009 	 * When looping the sl->state.branches will be > 0 and this state
11010 	 * will not be considered for equivalence until branches == 0.
11011 	 */
11012 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11013 	if (!new_sl)
11014 		return -ENOMEM;
11015 	env->total_states++;
11016 	env->peak_states++;
11017 	env->prev_jmps_processed = env->jmps_processed;
11018 	env->prev_insn_processed = env->insn_processed;
11019 
11020 	/* add new state to the head of linked list */
11021 	new = &new_sl->state;
11022 	err = copy_verifier_state(new, cur);
11023 	if (err) {
11024 		free_verifier_state(new, false);
11025 		kfree(new_sl);
11026 		return err;
11027 	}
11028 	new->insn_idx = insn_idx;
11029 	WARN_ONCE(new->branches != 1,
11030 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11031 
11032 	cur->parent = new;
11033 	cur->first_insn_idx = insn_idx;
11034 	clear_jmp_history(cur);
11035 	new_sl->next = *explored_state(env, insn_idx);
11036 	*explored_state(env, insn_idx) = new_sl;
11037 	/* connect new state to parentage chain. Current frame needs all
11038 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
11039 	 * to the stack implicitly by JITs) so in callers' frames connect just
11040 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11041 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11042 	 * from callee with its full parentage chain, anyway.
11043 	 */
11044 	/* clear write marks in current state: the writes we did are not writes
11045 	 * our child did, so they don't screen off its reads from us.
11046 	 * (There are no read marks in current state, because reads always mark
11047 	 * their parent and current state never has children yet.  Only
11048 	 * explored_states can get read marks.)
11049 	 */
11050 	for (j = 0; j <= cur->curframe; j++) {
11051 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11052 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11053 		for (i = 0; i < BPF_REG_FP; i++)
11054 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11055 	}
11056 
11057 	/* all stack frames are accessible from callee, clear them all */
11058 	for (j = 0; j <= cur->curframe; j++) {
11059 		struct bpf_func_state *frame = cur->frame[j];
11060 		struct bpf_func_state *newframe = new->frame[j];
11061 
11062 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11063 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11064 			frame->stack[i].spilled_ptr.parent =
11065 						&newframe->stack[i].spilled_ptr;
11066 		}
11067 	}
11068 	return 0;
11069 }
11070 
11071 /* Return true if it's OK to have the same insn return a different type. */
11072 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11073 {
11074 	switch (type) {
11075 	case PTR_TO_CTX:
11076 	case PTR_TO_SOCKET:
11077 	case PTR_TO_SOCKET_OR_NULL:
11078 	case PTR_TO_SOCK_COMMON:
11079 	case PTR_TO_SOCK_COMMON_OR_NULL:
11080 	case PTR_TO_TCP_SOCK:
11081 	case PTR_TO_TCP_SOCK_OR_NULL:
11082 	case PTR_TO_XDP_SOCK:
11083 	case PTR_TO_BTF_ID:
11084 	case PTR_TO_BTF_ID_OR_NULL:
11085 		return false;
11086 	default:
11087 		return true;
11088 	}
11089 }
11090 
11091 /* If an instruction was previously used with particular pointer types, then we
11092  * need to be careful to avoid cases such as the below, where it may be ok
11093  * for one branch accessing the pointer, but not ok for the other branch:
11094  *
11095  * R1 = sock_ptr
11096  * goto X;
11097  * ...
11098  * R1 = some_other_valid_ptr;
11099  * goto X;
11100  * ...
11101  * R2 = *(u32 *)(R1 + 0);
11102  */
11103 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11104 {
11105 	return src != prev && (!reg_type_mismatch_ok(src) ||
11106 			       !reg_type_mismatch_ok(prev));
11107 }
11108 
11109 static int do_check(struct bpf_verifier_env *env)
11110 {
11111 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11112 	struct bpf_verifier_state *state = env->cur_state;
11113 	struct bpf_insn *insns = env->prog->insnsi;
11114 	struct bpf_reg_state *regs;
11115 	int insn_cnt = env->prog->len;
11116 	bool do_print_state = false;
11117 	int prev_insn_idx = -1;
11118 
11119 	for (;;) {
11120 		struct bpf_insn *insn;
11121 		u8 class;
11122 		int err;
11123 
11124 		env->prev_insn_idx = prev_insn_idx;
11125 		if (env->insn_idx >= insn_cnt) {
11126 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11127 				env->insn_idx, insn_cnt);
11128 			return -EFAULT;
11129 		}
11130 
11131 		insn = &insns[env->insn_idx];
11132 		class = BPF_CLASS(insn->code);
11133 
11134 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11135 			verbose(env,
11136 				"BPF program is too large. Processed %d insn\n",
11137 				env->insn_processed);
11138 			return -E2BIG;
11139 		}
11140 
11141 		err = is_state_visited(env, env->insn_idx);
11142 		if (err < 0)
11143 			return err;
11144 		if (err == 1) {
11145 			/* found equivalent state, can prune the search */
11146 			if (env->log.level & BPF_LOG_LEVEL) {
11147 				if (do_print_state)
11148 					verbose(env, "\nfrom %d to %d%s: safe\n",
11149 						env->prev_insn_idx, env->insn_idx,
11150 						env->cur_state->speculative ?
11151 						" (speculative execution)" : "");
11152 				else
11153 					verbose(env, "%d: safe\n", env->insn_idx);
11154 			}
11155 			goto process_bpf_exit;
11156 		}
11157 
11158 		if (signal_pending(current))
11159 			return -EAGAIN;
11160 
11161 		if (need_resched())
11162 			cond_resched();
11163 
11164 		if (env->log.level & BPF_LOG_LEVEL2 ||
11165 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
11166 			if (env->log.level & BPF_LOG_LEVEL2)
11167 				verbose(env, "%d:", env->insn_idx);
11168 			else
11169 				verbose(env, "\nfrom %d to %d%s:",
11170 					env->prev_insn_idx, env->insn_idx,
11171 					env->cur_state->speculative ?
11172 					" (speculative execution)" : "");
11173 			print_verifier_state(env, state->frame[state->curframe]);
11174 			do_print_state = false;
11175 		}
11176 
11177 		if (env->log.level & BPF_LOG_LEVEL) {
11178 			const struct bpf_insn_cbs cbs = {
11179 				.cb_call	= disasm_kfunc_name,
11180 				.cb_print	= verbose,
11181 				.private_data	= env,
11182 			};
11183 
11184 			verbose_linfo(env, env->insn_idx, "; ");
11185 			verbose(env, "%d: ", env->insn_idx);
11186 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11187 		}
11188 
11189 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11190 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11191 							   env->prev_insn_idx);
11192 			if (err)
11193 				return err;
11194 		}
11195 
11196 		regs = cur_regs(env);
11197 		sanitize_mark_insn_seen(env);
11198 		prev_insn_idx = env->insn_idx;
11199 
11200 		if (class == BPF_ALU || class == BPF_ALU64) {
11201 			err = check_alu_op(env, insn);
11202 			if (err)
11203 				return err;
11204 
11205 		} else if (class == BPF_LDX) {
11206 			enum bpf_reg_type *prev_src_type, src_reg_type;
11207 
11208 			/* check for reserved fields is already done */
11209 
11210 			/* check src operand */
11211 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11212 			if (err)
11213 				return err;
11214 
11215 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11216 			if (err)
11217 				return err;
11218 
11219 			src_reg_type = regs[insn->src_reg].type;
11220 
11221 			/* check that memory (src_reg + off) is readable,
11222 			 * the state of dst_reg will be updated by this func
11223 			 */
11224 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11225 					       insn->off, BPF_SIZE(insn->code),
11226 					       BPF_READ, insn->dst_reg, false);
11227 			if (err)
11228 				return err;
11229 
11230 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11231 
11232 			if (*prev_src_type == NOT_INIT) {
11233 				/* saw a valid insn
11234 				 * dst_reg = *(u32 *)(src_reg + off)
11235 				 * save type to validate intersecting paths
11236 				 */
11237 				*prev_src_type = src_reg_type;
11238 
11239 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11240 				/* ABuser program is trying to use the same insn
11241 				 * dst_reg = *(u32*) (src_reg + off)
11242 				 * with different pointer types:
11243 				 * src_reg == ctx in one branch and
11244 				 * src_reg == stack|map in some other branch.
11245 				 * Reject it.
11246 				 */
11247 				verbose(env, "same insn cannot be used with different pointers\n");
11248 				return -EINVAL;
11249 			}
11250 
11251 		} else if (class == BPF_STX) {
11252 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11253 
11254 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11255 				err = check_atomic(env, env->insn_idx, insn);
11256 				if (err)
11257 					return err;
11258 				env->insn_idx++;
11259 				continue;
11260 			}
11261 
11262 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11263 				verbose(env, "BPF_STX uses reserved fields\n");
11264 				return -EINVAL;
11265 			}
11266 
11267 			/* check src1 operand */
11268 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11269 			if (err)
11270 				return err;
11271 			/* check src2 operand */
11272 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11273 			if (err)
11274 				return err;
11275 
11276 			dst_reg_type = regs[insn->dst_reg].type;
11277 
11278 			/* check that memory (dst_reg + off) is writeable */
11279 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11280 					       insn->off, BPF_SIZE(insn->code),
11281 					       BPF_WRITE, insn->src_reg, false);
11282 			if (err)
11283 				return err;
11284 
11285 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11286 
11287 			if (*prev_dst_type == NOT_INIT) {
11288 				*prev_dst_type = dst_reg_type;
11289 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11290 				verbose(env, "same insn cannot be used with different pointers\n");
11291 				return -EINVAL;
11292 			}
11293 
11294 		} else if (class == BPF_ST) {
11295 			if (BPF_MODE(insn->code) != BPF_MEM ||
11296 			    insn->src_reg != BPF_REG_0) {
11297 				verbose(env, "BPF_ST uses reserved fields\n");
11298 				return -EINVAL;
11299 			}
11300 			/* check src operand */
11301 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11302 			if (err)
11303 				return err;
11304 
11305 			if (is_ctx_reg(env, insn->dst_reg)) {
11306 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11307 					insn->dst_reg,
11308 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
11309 				return -EACCES;
11310 			}
11311 
11312 			/* check that memory (dst_reg + off) is writeable */
11313 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11314 					       insn->off, BPF_SIZE(insn->code),
11315 					       BPF_WRITE, -1, false);
11316 			if (err)
11317 				return err;
11318 
11319 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11320 			u8 opcode = BPF_OP(insn->code);
11321 
11322 			env->jmps_processed++;
11323 			if (opcode == BPF_CALL) {
11324 				if (BPF_SRC(insn->code) != BPF_K ||
11325 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11326 				     && insn->off != 0) ||
11327 				    (insn->src_reg != BPF_REG_0 &&
11328 				     insn->src_reg != BPF_PSEUDO_CALL &&
11329 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11330 				    insn->dst_reg != BPF_REG_0 ||
11331 				    class == BPF_JMP32) {
11332 					verbose(env, "BPF_CALL uses reserved fields\n");
11333 					return -EINVAL;
11334 				}
11335 
11336 				if (env->cur_state->active_spin_lock &&
11337 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11338 				     insn->imm != BPF_FUNC_spin_unlock)) {
11339 					verbose(env, "function calls are not allowed while holding a lock\n");
11340 					return -EINVAL;
11341 				}
11342 				if (insn->src_reg == BPF_PSEUDO_CALL)
11343 					err = check_func_call(env, insn, &env->insn_idx);
11344 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11345 					err = check_kfunc_call(env, insn);
11346 				else
11347 					err = check_helper_call(env, insn, &env->insn_idx);
11348 				if (err)
11349 					return err;
11350 			} else if (opcode == BPF_JA) {
11351 				if (BPF_SRC(insn->code) != BPF_K ||
11352 				    insn->imm != 0 ||
11353 				    insn->src_reg != BPF_REG_0 ||
11354 				    insn->dst_reg != BPF_REG_0 ||
11355 				    class == BPF_JMP32) {
11356 					verbose(env, "BPF_JA uses reserved fields\n");
11357 					return -EINVAL;
11358 				}
11359 
11360 				env->insn_idx += insn->off + 1;
11361 				continue;
11362 
11363 			} else if (opcode == BPF_EXIT) {
11364 				if (BPF_SRC(insn->code) != BPF_K ||
11365 				    insn->imm != 0 ||
11366 				    insn->src_reg != BPF_REG_0 ||
11367 				    insn->dst_reg != BPF_REG_0 ||
11368 				    class == BPF_JMP32) {
11369 					verbose(env, "BPF_EXIT uses reserved fields\n");
11370 					return -EINVAL;
11371 				}
11372 
11373 				if (env->cur_state->active_spin_lock) {
11374 					verbose(env, "bpf_spin_unlock is missing\n");
11375 					return -EINVAL;
11376 				}
11377 
11378 				if (state->curframe) {
11379 					/* exit from nested function */
11380 					err = prepare_func_exit(env, &env->insn_idx);
11381 					if (err)
11382 						return err;
11383 					do_print_state = true;
11384 					continue;
11385 				}
11386 
11387 				err = check_reference_leak(env);
11388 				if (err)
11389 					return err;
11390 
11391 				err = check_return_code(env);
11392 				if (err)
11393 					return err;
11394 process_bpf_exit:
11395 				update_branch_counts(env, env->cur_state);
11396 				err = pop_stack(env, &prev_insn_idx,
11397 						&env->insn_idx, pop_log);
11398 				if (err < 0) {
11399 					if (err != -ENOENT)
11400 						return err;
11401 					break;
11402 				} else {
11403 					do_print_state = true;
11404 					continue;
11405 				}
11406 			} else {
11407 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11408 				if (err)
11409 					return err;
11410 			}
11411 		} else if (class == BPF_LD) {
11412 			u8 mode = BPF_MODE(insn->code);
11413 
11414 			if (mode == BPF_ABS || mode == BPF_IND) {
11415 				err = check_ld_abs(env, insn);
11416 				if (err)
11417 					return err;
11418 
11419 			} else if (mode == BPF_IMM) {
11420 				err = check_ld_imm(env, insn);
11421 				if (err)
11422 					return err;
11423 
11424 				env->insn_idx++;
11425 				sanitize_mark_insn_seen(env);
11426 			} else {
11427 				verbose(env, "invalid BPF_LD mode\n");
11428 				return -EINVAL;
11429 			}
11430 		} else {
11431 			verbose(env, "unknown insn class %d\n", class);
11432 			return -EINVAL;
11433 		}
11434 
11435 		env->insn_idx++;
11436 	}
11437 
11438 	return 0;
11439 }
11440 
11441 static int find_btf_percpu_datasec(struct btf *btf)
11442 {
11443 	const struct btf_type *t;
11444 	const char *tname;
11445 	int i, n;
11446 
11447 	/*
11448 	 * Both vmlinux and module each have their own ".data..percpu"
11449 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11450 	 * types to look at only module's own BTF types.
11451 	 */
11452 	n = btf_nr_types(btf);
11453 	if (btf_is_module(btf))
11454 		i = btf_nr_types(btf_vmlinux);
11455 	else
11456 		i = 1;
11457 
11458 	for(; i < n; i++) {
11459 		t = btf_type_by_id(btf, i);
11460 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11461 			continue;
11462 
11463 		tname = btf_name_by_offset(btf, t->name_off);
11464 		if (!strcmp(tname, ".data..percpu"))
11465 			return i;
11466 	}
11467 
11468 	return -ENOENT;
11469 }
11470 
11471 /* replace pseudo btf_id with kernel symbol address */
11472 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11473 			       struct bpf_insn *insn,
11474 			       struct bpf_insn_aux_data *aux)
11475 {
11476 	const struct btf_var_secinfo *vsi;
11477 	const struct btf_type *datasec;
11478 	struct btf_mod_pair *btf_mod;
11479 	const struct btf_type *t;
11480 	const char *sym_name;
11481 	bool percpu = false;
11482 	u32 type, id = insn->imm;
11483 	struct btf *btf;
11484 	s32 datasec_id;
11485 	u64 addr;
11486 	int i, btf_fd, err;
11487 
11488 	btf_fd = insn[1].imm;
11489 	if (btf_fd) {
11490 		btf = btf_get_by_fd(btf_fd);
11491 		if (IS_ERR(btf)) {
11492 			verbose(env, "invalid module BTF object FD specified.\n");
11493 			return -EINVAL;
11494 		}
11495 	} else {
11496 		if (!btf_vmlinux) {
11497 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11498 			return -EINVAL;
11499 		}
11500 		btf = btf_vmlinux;
11501 		btf_get(btf);
11502 	}
11503 
11504 	t = btf_type_by_id(btf, id);
11505 	if (!t) {
11506 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11507 		err = -ENOENT;
11508 		goto err_put;
11509 	}
11510 
11511 	if (!btf_type_is_var(t)) {
11512 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11513 		err = -EINVAL;
11514 		goto err_put;
11515 	}
11516 
11517 	sym_name = btf_name_by_offset(btf, t->name_off);
11518 	addr = kallsyms_lookup_name(sym_name);
11519 	if (!addr) {
11520 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11521 			sym_name);
11522 		err = -ENOENT;
11523 		goto err_put;
11524 	}
11525 
11526 	datasec_id = find_btf_percpu_datasec(btf);
11527 	if (datasec_id > 0) {
11528 		datasec = btf_type_by_id(btf, datasec_id);
11529 		for_each_vsi(i, datasec, vsi) {
11530 			if (vsi->type == id) {
11531 				percpu = true;
11532 				break;
11533 			}
11534 		}
11535 	}
11536 
11537 	insn[0].imm = (u32)addr;
11538 	insn[1].imm = addr >> 32;
11539 
11540 	type = t->type;
11541 	t = btf_type_skip_modifiers(btf, type, NULL);
11542 	if (percpu) {
11543 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11544 		aux->btf_var.btf = btf;
11545 		aux->btf_var.btf_id = type;
11546 	} else if (!btf_type_is_struct(t)) {
11547 		const struct btf_type *ret;
11548 		const char *tname;
11549 		u32 tsize;
11550 
11551 		/* resolve the type size of ksym. */
11552 		ret = btf_resolve_size(btf, t, &tsize);
11553 		if (IS_ERR(ret)) {
11554 			tname = btf_name_by_offset(btf, t->name_off);
11555 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11556 				tname, PTR_ERR(ret));
11557 			err = -EINVAL;
11558 			goto err_put;
11559 		}
11560 		aux->btf_var.reg_type = PTR_TO_MEM;
11561 		aux->btf_var.mem_size = tsize;
11562 	} else {
11563 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11564 		aux->btf_var.btf = btf;
11565 		aux->btf_var.btf_id = type;
11566 	}
11567 
11568 	/* check whether we recorded this BTF (and maybe module) already */
11569 	for (i = 0; i < env->used_btf_cnt; i++) {
11570 		if (env->used_btfs[i].btf == btf) {
11571 			btf_put(btf);
11572 			return 0;
11573 		}
11574 	}
11575 
11576 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11577 		err = -E2BIG;
11578 		goto err_put;
11579 	}
11580 
11581 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11582 	btf_mod->btf = btf;
11583 	btf_mod->module = NULL;
11584 
11585 	/* if we reference variables from kernel module, bump its refcount */
11586 	if (btf_is_module(btf)) {
11587 		btf_mod->module = btf_try_get_module(btf);
11588 		if (!btf_mod->module) {
11589 			err = -ENXIO;
11590 			goto err_put;
11591 		}
11592 	}
11593 
11594 	env->used_btf_cnt++;
11595 
11596 	return 0;
11597 err_put:
11598 	btf_put(btf);
11599 	return err;
11600 }
11601 
11602 static int check_map_prealloc(struct bpf_map *map)
11603 {
11604 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11605 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11606 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11607 		!(map->map_flags & BPF_F_NO_PREALLOC);
11608 }
11609 
11610 static bool is_tracing_prog_type(enum bpf_prog_type type)
11611 {
11612 	switch (type) {
11613 	case BPF_PROG_TYPE_KPROBE:
11614 	case BPF_PROG_TYPE_TRACEPOINT:
11615 	case BPF_PROG_TYPE_PERF_EVENT:
11616 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11617 		return true;
11618 	default:
11619 		return false;
11620 	}
11621 }
11622 
11623 static bool is_preallocated_map(struct bpf_map *map)
11624 {
11625 	if (!check_map_prealloc(map))
11626 		return false;
11627 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11628 		return false;
11629 	return true;
11630 }
11631 
11632 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11633 					struct bpf_map *map,
11634 					struct bpf_prog *prog)
11635 
11636 {
11637 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11638 	/*
11639 	 * Validate that trace type programs use preallocated hash maps.
11640 	 *
11641 	 * For programs attached to PERF events this is mandatory as the
11642 	 * perf NMI can hit any arbitrary code sequence.
11643 	 *
11644 	 * All other trace types using preallocated hash maps are unsafe as
11645 	 * well because tracepoint or kprobes can be inside locked regions
11646 	 * of the memory allocator or at a place where a recursion into the
11647 	 * memory allocator would see inconsistent state.
11648 	 *
11649 	 * On RT enabled kernels run-time allocation of all trace type
11650 	 * programs is strictly prohibited due to lock type constraints. On
11651 	 * !RT kernels it is allowed for backwards compatibility reasons for
11652 	 * now, but warnings are emitted so developers are made aware of
11653 	 * the unsafety and can fix their programs before this is enforced.
11654 	 */
11655 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11656 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11657 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11658 			return -EINVAL;
11659 		}
11660 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11661 			verbose(env, "trace type programs can only use preallocated hash map\n");
11662 			return -EINVAL;
11663 		}
11664 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11665 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11666 	}
11667 
11668 	if (map_value_has_spin_lock(map)) {
11669 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11670 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11671 			return -EINVAL;
11672 		}
11673 
11674 		if (is_tracing_prog_type(prog_type)) {
11675 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11676 			return -EINVAL;
11677 		}
11678 
11679 		if (prog->aux->sleepable) {
11680 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11681 			return -EINVAL;
11682 		}
11683 	}
11684 
11685 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11686 	    !bpf_offload_prog_map_match(prog, map)) {
11687 		verbose(env, "offload device mismatch between prog and map\n");
11688 		return -EINVAL;
11689 	}
11690 
11691 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11692 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11693 		return -EINVAL;
11694 	}
11695 
11696 	if (prog->aux->sleepable)
11697 		switch (map->map_type) {
11698 		case BPF_MAP_TYPE_HASH:
11699 		case BPF_MAP_TYPE_LRU_HASH:
11700 		case BPF_MAP_TYPE_ARRAY:
11701 		case BPF_MAP_TYPE_PERCPU_HASH:
11702 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11703 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11704 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11705 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11706 			if (!is_preallocated_map(map)) {
11707 				verbose(env,
11708 					"Sleepable programs can only use preallocated maps\n");
11709 				return -EINVAL;
11710 			}
11711 			break;
11712 		case BPF_MAP_TYPE_RINGBUF:
11713 			break;
11714 		default:
11715 			verbose(env,
11716 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11717 			return -EINVAL;
11718 		}
11719 
11720 	return 0;
11721 }
11722 
11723 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11724 {
11725 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11726 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11727 }
11728 
11729 /* find and rewrite pseudo imm in ld_imm64 instructions:
11730  *
11731  * 1. if it accesses map FD, replace it with actual map pointer.
11732  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11733  *
11734  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11735  */
11736 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11737 {
11738 	struct bpf_insn *insn = env->prog->insnsi;
11739 	int insn_cnt = env->prog->len;
11740 	int i, j, err;
11741 
11742 	err = bpf_prog_calc_tag(env->prog);
11743 	if (err)
11744 		return err;
11745 
11746 	for (i = 0; i < insn_cnt; i++, insn++) {
11747 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11748 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11749 			verbose(env, "BPF_LDX uses reserved fields\n");
11750 			return -EINVAL;
11751 		}
11752 
11753 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11754 			struct bpf_insn_aux_data *aux;
11755 			struct bpf_map *map;
11756 			struct fd f;
11757 			u64 addr;
11758 			u32 fd;
11759 
11760 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11761 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11762 			    insn[1].off != 0) {
11763 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11764 				return -EINVAL;
11765 			}
11766 
11767 			if (insn[0].src_reg == 0)
11768 				/* valid generic load 64-bit imm */
11769 				goto next_insn;
11770 
11771 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11772 				aux = &env->insn_aux_data[i];
11773 				err = check_pseudo_btf_id(env, insn, aux);
11774 				if (err)
11775 					return err;
11776 				goto next_insn;
11777 			}
11778 
11779 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11780 				aux = &env->insn_aux_data[i];
11781 				aux->ptr_type = PTR_TO_FUNC;
11782 				goto next_insn;
11783 			}
11784 
11785 			/* In final convert_pseudo_ld_imm64() step, this is
11786 			 * converted into regular 64-bit imm load insn.
11787 			 */
11788 			switch (insn[0].src_reg) {
11789 			case BPF_PSEUDO_MAP_VALUE:
11790 			case BPF_PSEUDO_MAP_IDX_VALUE:
11791 				break;
11792 			case BPF_PSEUDO_MAP_FD:
11793 			case BPF_PSEUDO_MAP_IDX:
11794 				if (insn[1].imm == 0)
11795 					break;
11796 				fallthrough;
11797 			default:
11798 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11799 				return -EINVAL;
11800 			}
11801 
11802 			switch (insn[0].src_reg) {
11803 			case BPF_PSEUDO_MAP_IDX_VALUE:
11804 			case BPF_PSEUDO_MAP_IDX:
11805 				if (bpfptr_is_null(env->fd_array)) {
11806 					verbose(env, "fd_idx without fd_array is invalid\n");
11807 					return -EPROTO;
11808 				}
11809 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11810 							    insn[0].imm * sizeof(fd),
11811 							    sizeof(fd)))
11812 					return -EFAULT;
11813 				break;
11814 			default:
11815 				fd = insn[0].imm;
11816 				break;
11817 			}
11818 
11819 			f = fdget(fd);
11820 			map = __bpf_map_get(f);
11821 			if (IS_ERR(map)) {
11822 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11823 					insn[0].imm);
11824 				return PTR_ERR(map);
11825 			}
11826 
11827 			err = check_map_prog_compatibility(env, map, env->prog);
11828 			if (err) {
11829 				fdput(f);
11830 				return err;
11831 			}
11832 
11833 			aux = &env->insn_aux_data[i];
11834 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11835 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11836 				addr = (unsigned long)map;
11837 			} else {
11838 				u32 off = insn[1].imm;
11839 
11840 				if (off >= BPF_MAX_VAR_OFF) {
11841 					verbose(env, "direct value offset of %u is not allowed\n", off);
11842 					fdput(f);
11843 					return -EINVAL;
11844 				}
11845 
11846 				if (!map->ops->map_direct_value_addr) {
11847 					verbose(env, "no direct value access support for this map type\n");
11848 					fdput(f);
11849 					return -EINVAL;
11850 				}
11851 
11852 				err = map->ops->map_direct_value_addr(map, &addr, off);
11853 				if (err) {
11854 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11855 						map->value_size, off);
11856 					fdput(f);
11857 					return err;
11858 				}
11859 
11860 				aux->map_off = off;
11861 				addr += off;
11862 			}
11863 
11864 			insn[0].imm = (u32)addr;
11865 			insn[1].imm = addr >> 32;
11866 
11867 			/* check whether we recorded this map already */
11868 			for (j = 0; j < env->used_map_cnt; j++) {
11869 				if (env->used_maps[j] == map) {
11870 					aux->map_index = j;
11871 					fdput(f);
11872 					goto next_insn;
11873 				}
11874 			}
11875 
11876 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11877 				fdput(f);
11878 				return -E2BIG;
11879 			}
11880 
11881 			/* hold the map. If the program is rejected by verifier,
11882 			 * the map will be released by release_maps() or it
11883 			 * will be used by the valid program until it's unloaded
11884 			 * and all maps are released in free_used_maps()
11885 			 */
11886 			bpf_map_inc(map);
11887 
11888 			aux->map_index = env->used_map_cnt;
11889 			env->used_maps[env->used_map_cnt++] = map;
11890 
11891 			if (bpf_map_is_cgroup_storage(map) &&
11892 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11893 				verbose(env, "only one cgroup storage of each type is allowed\n");
11894 				fdput(f);
11895 				return -EBUSY;
11896 			}
11897 
11898 			fdput(f);
11899 next_insn:
11900 			insn++;
11901 			i++;
11902 			continue;
11903 		}
11904 
11905 		/* Basic sanity check before we invest more work here. */
11906 		if (!bpf_opcode_in_insntable(insn->code)) {
11907 			verbose(env, "unknown opcode %02x\n", insn->code);
11908 			return -EINVAL;
11909 		}
11910 	}
11911 
11912 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11913 	 * 'struct bpf_map *' into a register instead of user map_fd.
11914 	 * These pointers will be used later by verifier to validate map access.
11915 	 */
11916 	return 0;
11917 }
11918 
11919 /* drop refcnt of maps used by the rejected program */
11920 static void release_maps(struct bpf_verifier_env *env)
11921 {
11922 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11923 			     env->used_map_cnt);
11924 }
11925 
11926 /* drop refcnt of maps used by the rejected program */
11927 static void release_btfs(struct bpf_verifier_env *env)
11928 {
11929 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11930 			     env->used_btf_cnt);
11931 }
11932 
11933 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11934 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11935 {
11936 	struct bpf_insn *insn = env->prog->insnsi;
11937 	int insn_cnt = env->prog->len;
11938 	int i;
11939 
11940 	for (i = 0; i < insn_cnt; i++, insn++) {
11941 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11942 			continue;
11943 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11944 			continue;
11945 		insn->src_reg = 0;
11946 	}
11947 }
11948 
11949 /* single env->prog->insni[off] instruction was replaced with the range
11950  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11951  * [0, off) and [off, end) to new locations, so the patched range stays zero
11952  */
11953 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11954 				 struct bpf_insn_aux_data *new_data,
11955 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11956 {
11957 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11958 	struct bpf_insn *insn = new_prog->insnsi;
11959 	u32 old_seen = old_data[off].seen;
11960 	u32 prog_len;
11961 	int i;
11962 
11963 	/* aux info at OFF always needs adjustment, no matter fast path
11964 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11965 	 * original insn at old prog.
11966 	 */
11967 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11968 
11969 	if (cnt == 1)
11970 		return;
11971 	prog_len = new_prog->len;
11972 
11973 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11974 	memcpy(new_data + off + cnt - 1, old_data + off,
11975 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11976 	for (i = off; i < off + cnt - 1; i++) {
11977 		/* Expand insni[off]'s seen count to the patched range. */
11978 		new_data[i].seen = old_seen;
11979 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11980 	}
11981 	env->insn_aux_data = new_data;
11982 	vfree(old_data);
11983 }
11984 
11985 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11986 {
11987 	int i;
11988 
11989 	if (len == 1)
11990 		return;
11991 	/* NOTE: fake 'exit' subprog should be updated as well. */
11992 	for (i = 0; i <= env->subprog_cnt; i++) {
11993 		if (env->subprog_info[i].start <= off)
11994 			continue;
11995 		env->subprog_info[i].start += len - 1;
11996 	}
11997 }
11998 
11999 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12000 {
12001 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12002 	int i, sz = prog->aux->size_poke_tab;
12003 	struct bpf_jit_poke_descriptor *desc;
12004 
12005 	for (i = 0; i < sz; i++) {
12006 		desc = &tab[i];
12007 		if (desc->insn_idx <= off)
12008 			continue;
12009 		desc->insn_idx += len - 1;
12010 	}
12011 }
12012 
12013 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12014 					    const struct bpf_insn *patch, u32 len)
12015 {
12016 	struct bpf_prog *new_prog;
12017 	struct bpf_insn_aux_data *new_data = NULL;
12018 
12019 	if (len > 1) {
12020 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12021 					      sizeof(struct bpf_insn_aux_data)));
12022 		if (!new_data)
12023 			return NULL;
12024 	}
12025 
12026 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12027 	if (IS_ERR(new_prog)) {
12028 		if (PTR_ERR(new_prog) == -ERANGE)
12029 			verbose(env,
12030 				"insn %d cannot be patched due to 16-bit range\n",
12031 				env->insn_aux_data[off].orig_idx);
12032 		vfree(new_data);
12033 		return NULL;
12034 	}
12035 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12036 	adjust_subprog_starts(env, off, len);
12037 	adjust_poke_descs(new_prog, off, len);
12038 	return new_prog;
12039 }
12040 
12041 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12042 					      u32 off, u32 cnt)
12043 {
12044 	int i, j;
12045 
12046 	/* find first prog starting at or after off (first to remove) */
12047 	for (i = 0; i < env->subprog_cnt; i++)
12048 		if (env->subprog_info[i].start >= off)
12049 			break;
12050 	/* find first prog starting at or after off + cnt (first to stay) */
12051 	for (j = i; j < env->subprog_cnt; j++)
12052 		if (env->subprog_info[j].start >= off + cnt)
12053 			break;
12054 	/* if j doesn't start exactly at off + cnt, we are just removing
12055 	 * the front of previous prog
12056 	 */
12057 	if (env->subprog_info[j].start != off + cnt)
12058 		j--;
12059 
12060 	if (j > i) {
12061 		struct bpf_prog_aux *aux = env->prog->aux;
12062 		int move;
12063 
12064 		/* move fake 'exit' subprog as well */
12065 		move = env->subprog_cnt + 1 - j;
12066 
12067 		memmove(env->subprog_info + i,
12068 			env->subprog_info + j,
12069 			sizeof(*env->subprog_info) * move);
12070 		env->subprog_cnt -= j - i;
12071 
12072 		/* remove func_info */
12073 		if (aux->func_info) {
12074 			move = aux->func_info_cnt - j;
12075 
12076 			memmove(aux->func_info + i,
12077 				aux->func_info + j,
12078 				sizeof(*aux->func_info) * move);
12079 			aux->func_info_cnt -= j - i;
12080 			/* func_info->insn_off is set after all code rewrites,
12081 			 * in adjust_btf_func() - no need to adjust
12082 			 */
12083 		}
12084 	} else {
12085 		/* convert i from "first prog to remove" to "first to adjust" */
12086 		if (env->subprog_info[i].start == off)
12087 			i++;
12088 	}
12089 
12090 	/* update fake 'exit' subprog as well */
12091 	for (; i <= env->subprog_cnt; i++)
12092 		env->subprog_info[i].start -= cnt;
12093 
12094 	return 0;
12095 }
12096 
12097 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12098 				      u32 cnt)
12099 {
12100 	struct bpf_prog *prog = env->prog;
12101 	u32 i, l_off, l_cnt, nr_linfo;
12102 	struct bpf_line_info *linfo;
12103 
12104 	nr_linfo = prog->aux->nr_linfo;
12105 	if (!nr_linfo)
12106 		return 0;
12107 
12108 	linfo = prog->aux->linfo;
12109 
12110 	/* find first line info to remove, count lines to be removed */
12111 	for (i = 0; i < nr_linfo; i++)
12112 		if (linfo[i].insn_off >= off)
12113 			break;
12114 
12115 	l_off = i;
12116 	l_cnt = 0;
12117 	for (; i < nr_linfo; i++)
12118 		if (linfo[i].insn_off < off + cnt)
12119 			l_cnt++;
12120 		else
12121 			break;
12122 
12123 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12124 	 * last removed linfo.  prog is already modified, so prog->len == off
12125 	 * means no live instructions after (tail of the program was removed).
12126 	 */
12127 	if (prog->len != off && l_cnt &&
12128 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12129 		l_cnt--;
12130 		linfo[--i].insn_off = off + cnt;
12131 	}
12132 
12133 	/* remove the line info which refer to the removed instructions */
12134 	if (l_cnt) {
12135 		memmove(linfo + l_off, linfo + i,
12136 			sizeof(*linfo) * (nr_linfo - i));
12137 
12138 		prog->aux->nr_linfo -= l_cnt;
12139 		nr_linfo = prog->aux->nr_linfo;
12140 	}
12141 
12142 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12143 	for (i = l_off; i < nr_linfo; i++)
12144 		linfo[i].insn_off -= cnt;
12145 
12146 	/* fix up all subprogs (incl. 'exit') which start >= off */
12147 	for (i = 0; i <= env->subprog_cnt; i++)
12148 		if (env->subprog_info[i].linfo_idx > l_off) {
12149 			/* program may have started in the removed region but
12150 			 * may not be fully removed
12151 			 */
12152 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12153 				env->subprog_info[i].linfo_idx -= l_cnt;
12154 			else
12155 				env->subprog_info[i].linfo_idx = l_off;
12156 		}
12157 
12158 	return 0;
12159 }
12160 
12161 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12162 {
12163 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12164 	unsigned int orig_prog_len = env->prog->len;
12165 	int err;
12166 
12167 	if (bpf_prog_is_dev_bound(env->prog->aux))
12168 		bpf_prog_offload_remove_insns(env, off, cnt);
12169 
12170 	err = bpf_remove_insns(env->prog, off, cnt);
12171 	if (err)
12172 		return err;
12173 
12174 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12175 	if (err)
12176 		return err;
12177 
12178 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12179 	if (err)
12180 		return err;
12181 
12182 	memmove(aux_data + off,	aux_data + off + cnt,
12183 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12184 
12185 	return 0;
12186 }
12187 
12188 /* The verifier does more data flow analysis than llvm and will not
12189  * explore branches that are dead at run time. Malicious programs can
12190  * have dead code too. Therefore replace all dead at-run-time code
12191  * with 'ja -1'.
12192  *
12193  * Just nops are not optimal, e.g. if they would sit at the end of the
12194  * program and through another bug we would manage to jump there, then
12195  * we'd execute beyond program memory otherwise. Returning exception
12196  * code also wouldn't work since we can have subprogs where the dead
12197  * code could be located.
12198  */
12199 static void sanitize_dead_code(struct bpf_verifier_env *env)
12200 {
12201 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12202 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12203 	struct bpf_insn *insn = env->prog->insnsi;
12204 	const int insn_cnt = env->prog->len;
12205 	int i;
12206 
12207 	for (i = 0; i < insn_cnt; i++) {
12208 		if (aux_data[i].seen)
12209 			continue;
12210 		memcpy(insn + i, &trap, sizeof(trap));
12211 		aux_data[i].zext_dst = false;
12212 	}
12213 }
12214 
12215 static bool insn_is_cond_jump(u8 code)
12216 {
12217 	u8 op;
12218 
12219 	if (BPF_CLASS(code) == BPF_JMP32)
12220 		return true;
12221 
12222 	if (BPF_CLASS(code) != BPF_JMP)
12223 		return false;
12224 
12225 	op = BPF_OP(code);
12226 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12227 }
12228 
12229 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12230 {
12231 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12232 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12233 	struct bpf_insn *insn = env->prog->insnsi;
12234 	const int insn_cnt = env->prog->len;
12235 	int i;
12236 
12237 	for (i = 0; i < insn_cnt; i++, insn++) {
12238 		if (!insn_is_cond_jump(insn->code))
12239 			continue;
12240 
12241 		if (!aux_data[i + 1].seen)
12242 			ja.off = insn->off;
12243 		else if (!aux_data[i + 1 + insn->off].seen)
12244 			ja.off = 0;
12245 		else
12246 			continue;
12247 
12248 		if (bpf_prog_is_dev_bound(env->prog->aux))
12249 			bpf_prog_offload_replace_insn(env, i, &ja);
12250 
12251 		memcpy(insn, &ja, sizeof(ja));
12252 	}
12253 }
12254 
12255 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12256 {
12257 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12258 	int insn_cnt = env->prog->len;
12259 	int i, err;
12260 
12261 	for (i = 0; i < insn_cnt; i++) {
12262 		int j;
12263 
12264 		j = 0;
12265 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12266 			j++;
12267 		if (!j)
12268 			continue;
12269 
12270 		err = verifier_remove_insns(env, i, j);
12271 		if (err)
12272 			return err;
12273 		insn_cnt = env->prog->len;
12274 	}
12275 
12276 	return 0;
12277 }
12278 
12279 static int opt_remove_nops(struct bpf_verifier_env *env)
12280 {
12281 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12282 	struct bpf_insn *insn = env->prog->insnsi;
12283 	int insn_cnt = env->prog->len;
12284 	int i, err;
12285 
12286 	for (i = 0; i < insn_cnt; i++) {
12287 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12288 			continue;
12289 
12290 		err = verifier_remove_insns(env, i, 1);
12291 		if (err)
12292 			return err;
12293 		insn_cnt--;
12294 		i--;
12295 	}
12296 
12297 	return 0;
12298 }
12299 
12300 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12301 					 const union bpf_attr *attr)
12302 {
12303 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12304 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12305 	int i, patch_len, delta = 0, len = env->prog->len;
12306 	struct bpf_insn *insns = env->prog->insnsi;
12307 	struct bpf_prog *new_prog;
12308 	bool rnd_hi32;
12309 
12310 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12311 	zext_patch[1] = BPF_ZEXT_REG(0);
12312 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12313 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12314 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12315 	for (i = 0; i < len; i++) {
12316 		int adj_idx = i + delta;
12317 		struct bpf_insn insn;
12318 		int load_reg;
12319 
12320 		insn = insns[adj_idx];
12321 		load_reg = insn_def_regno(&insn);
12322 		if (!aux[adj_idx].zext_dst) {
12323 			u8 code, class;
12324 			u32 imm_rnd;
12325 
12326 			if (!rnd_hi32)
12327 				continue;
12328 
12329 			code = insn.code;
12330 			class = BPF_CLASS(code);
12331 			if (load_reg == -1)
12332 				continue;
12333 
12334 			/* NOTE: arg "reg" (the fourth one) is only used for
12335 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12336 			 *       here.
12337 			 */
12338 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12339 				if (class == BPF_LD &&
12340 				    BPF_MODE(code) == BPF_IMM)
12341 					i++;
12342 				continue;
12343 			}
12344 
12345 			/* ctx load could be transformed into wider load. */
12346 			if (class == BPF_LDX &&
12347 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12348 				continue;
12349 
12350 			imm_rnd = get_random_int();
12351 			rnd_hi32_patch[0] = insn;
12352 			rnd_hi32_patch[1].imm = imm_rnd;
12353 			rnd_hi32_patch[3].dst_reg = load_reg;
12354 			patch = rnd_hi32_patch;
12355 			patch_len = 4;
12356 			goto apply_patch_buffer;
12357 		}
12358 
12359 		/* Add in an zero-extend instruction if a) the JIT has requested
12360 		 * it or b) it's a CMPXCHG.
12361 		 *
12362 		 * The latter is because: BPF_CMPXCHG always loads a value into
12363 		 * R0, therefore always zero-extends. However some archs'
12364 		 * equivalent instruction only does this load when the
12365 		 * comparison is successful. This detail of CMPXCHG is
12366 		 * orthogonal to the general zero-extension behaviour of the
12367 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12368 		 */
12369 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12370 			continue;
12371 
12372 		if (WARN_ON(load_reg == -1)) {
12373 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12374 			return -EFAULT;
12375 		}
12376 
12377 		zext_patch[0] = insn;
12378 		zext_patch[1].dst_reg = load_reg;
12379 		zext_patch[1].src_reg = load_reg;
12380 		patch = zext_patch;
12381 		patch_len = 2;
12382 apply_patch_buffer:
12383 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12384 		if (!new_prog)
12385 			return -ENOMEM;
12386 		env->prog = new_prog;
12387 		insns = new_prog->insnsi;
12388 		aux = env->insn_aux_data;
12389 		delta += patch_len - 1;
12390 	}
12391 
12392 	return 0;
12393 }
12394 
12395 /* convert load instructions that access fields of a context type into a
12396  * sequence of instructions that access fields of the underlying structure:
12397  *     struct __sk_buff    -> struct sk_buff
12398  *     struct bpf_sock_ops -> struct sock
12399  */
12400 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12401 {
12402 	const struct bpf_verifier_ops *ops = env->ops;
12403 	int i, cnt, size, ctx_field_size, delta = 0;
12404 	const int insn_cnt = env->prog->len;
12405 	struct bpf_insn insn_buf[16], *insn;
12406 	u32 target_size, size_default, off;
12407 	struct bpf_prog *new_prog;
12408 	enum bpf_access_type type;
12409 	bool is_narrower_load;
12410 
12411 	if (ops->gen_prologue || env->seen_direct_write) {
12412 		if (!ops->gen_prologue) {
12413 			verbose(env, "bpf verifier is misconfigured\n");
12414 			return -EINVAL;
12415 		}
12416 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12417 					env->prog);
12418 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12419 			verbose(env, "bpf verifier is misconfigured\n");
12420 			return -EINVAL;
12421 		} else if (cnt) {
12422 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12423 			if (!new_prog)
12424 				return -ENOMEM;
12425 
12426 			env->prog = new_prog;
12427 			delta += cnt - 1;
12428 		}
12429 	}
12430 
12431 	if (bpf_prog_is_dev_bound(env->prog->aux))
12432 		return 0;
12433 
12434 	insn = env->prog->insnsi + delta;
12435 
12436 	for (i = 0; i < insn_cnt; i++, insn++) {
12437 		bpf_convert_ctx_access_t convert_ctx_access;
12438 		bool ctx_access;
12439 
12440 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12441 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12442 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12443 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12444 			type = BPF_READ;
12445 			ctx_access = true;
12446 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12447 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12448 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12449 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12450 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12451 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12452 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12453 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12454 			type = BPF_WRITE;
12455 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12456 		} else {
12457 			continue;
12458 		}
12459 
12460 		if (type == BPF_WRITE &&
12461 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12462 			struct bpf_insn patch[] = {
12463 				*insn,
12464 				BPF_ST_NOSPEC(),
12465 			};
12466 
12467 			cnt = ARRAY_SIZE(patch);
12468 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12469 			if (!new_prog)
12470 				return -ENOMEM;
12471 
12472 			delta    += cnt - 1;
12473 			env->prog = new_prog;
12474 			insn      = new_prog->insnsi + i + delta;
12475 			continue;
12476 		}
12477 
12478 		if (!ctx_access)
12479 			continue;
12480 
12481 		switch (env->insn_aux_data[i + delta].ptr_type) {
12482 		case PTR_TO_CTX:
12483 			if (!ops->convert_ctx_access)
12484 				continue;
12485 			convert_ctx_access = ops->convert_ctx_access;
12486 			break;
12487 		case PTR_TO_SOCKET:
12488 		case PTR_TO_SOCK_COMMON:
12489 			convert_ctx_access = bpf_sock_convert_ctx_access;
12490 			break;
12491 		case PTR_TO_TCP_SOCK:
12492 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12493 			break;
12494 		case PTR_TO_XDP_SOCK:
12495 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12496 			break;
12497 		case PTR_TO_BTF_ID:
12498 			if (type == BPF_READ) {
12499 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12500 					BPF_SIZE((insn)->code);
12501 				env->prog->aux->num_exentries++;
12502 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12503 				verbose(env, "Writes through BTF pointers are not allowed\n");
12504 				return -EINVAL;
12505 			}
12506 			continue;
12507 		default:
12508 			continue;
12509 		}
12510 
12511 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12512 		size = BPF_LDST_BYTES(insn);
12513 
12514 		/* If the read access is a narrower load of the field,
12515 		 * convert to a 4/8-byte load, to minimum program type specific
12516 		 * convert_ctx_access changes. If conversion is successful,
12517 		 * we will apply proper mask to the result.
12518 		 */
12519 		is_narrower_load = size < ctx_field_size;
12520 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12521 		off = insn->off;
12522 		if (is_narrower_load) {
12523 			u8 size_code;
12524 
12525 			if (type == BPF_WRITE) {
12526 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12527 				return -EINVAL;
12528 			}
12529 
12530 			size_code = BPF_H;
12531 			if (ctx_field_size == 4)
12532 				size_code = BPF_W;
12533 			else if (ctx_field_size == 8)
12534 				size_code = BPF_DW;
12535 
12536 			insn->off = off & ~(size_default - 1);
12537 			insn->code = BPF_LDX | BPF_MEM | size_code;
12538 		}
12539 
12540 		target_size = 0;
12541 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12542 					 &target_size);
12543 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12544 		    (ctx_field_size && !target_size)) {
12545 			verbose(env, "bpf verifier is misconfigured\n");
12546 			return -EINVAL;
12547 		}
12548 
12549 		if (is_narrower_load && size < target_size) {
12550 			u8 shift = bpf_ctx_narrow_access_offset(
12551 				off, size, size_default) * 8;
12552 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12553 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12554 				return -EINVAL;
12555 			}
12556 			if (ctx_field_size <= 4) {
12557 				if (shift)
12558 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12559 									insn->dst_reg,
12560 									shift);
12561 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12562 								(1 << size * 8) - 1);
12563 			} else {
12564 				if (shift)
12565 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12566 									insn->dst_reg,
12567 									shift);
12568 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12569 								(1ULL << size * 8) - 1);
12570 			}
12571 		}
12572 
12573 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12574 		if (!new_prog)
12575 			return -ENOMEM;
12576 
12577 		delta += cnt - 1;
12578 
12579 		/* keep walking new program and skip insns we just inserted */
12580 		env->prog = new_prog;
12581 		insn      = new_prog->insnsi + i + delta;
12582 	}
12583 
12584 	return 0;
12585 }
12586 
12587 static int jit_subprogs(struct bpf_verifier_env *env)
12588 {
12589 	struct bpf_prog *prog = env->prog, **func, *tmp;
12590 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12591 	struct bpf_map *map_ptr;
12592 	struct bpf_insn *insn;
12593 	void *old_bpf_func;
12594 	int err, num_exentries;
12595 
12596 	if (env->subprog_cnt <= 1)
12597 		return 0;
12598 
12599 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12600 		if (bpf_pseudo_func(insn)) {
12601 			env->insn_aux_data[i].call_imm = insn->imm;
12602 			/* subprog is encoded in insn[1].imm */
12603 			continue;
12604 		}
12605 
12606 		if (!bpf_pseudo_call(insn))
12607 			continue;
12608 		/* Upon error here we cannot fall back to interpreter but
12609 		 * need a hard reject of the program. Thus -EFAULT is
12610 		 * propagated in any case.
12611 		 */
12612 		subprog = find_subprog(env, i + insn->imm + 1);
12613 		if (subprog < 0) {
12614 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12615 				  i + insn->imm + 1);
12616 			return -EFAULT;
12617 		}
12618 		/* temporarily remember subprog id inside insn instead of
12619 		 * aux_data, since next loop will split up all insns into funcs
12620 		 */
12621 		insn->off = subprog;
12622 		/* remember original imm in case JIT fails and fallback
12623 		 * to interpreter will be needed
12624 		 */
12625 		env->insn_aux_data[i].call_imm = insn->imm;
12626 		/* point imm to __bpf_call_base+1 from JITs point of view */
12627 		insn->imm = 1;
12628 	}
12629 
12630 	err = bpf_prog_alloc_jited_linfo(prog);
12631 	if (err)
12632 		goto out_undo_insn;
12633 
12634 	err = -ENOMEM;
12635 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12636 	if (!func)
12637 		goto out_undo_insn;
12638 
12639 	for (i = 0; i < env->subprog_cnt; i++) {
12640 		subprog_start = subprog_end;
12641 		subprog_end = env->subprog_info[i + 1].start;
12642 
12643 		len = subprog_end - subprog_start;
12644 		/* bpf_prog_run() doesn't call subprogs directly,
12645 		 * hence main prog stats include the runtime of subprogs.
12646 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12647 		 * func[i]->stats will never be accessed and stays NULL
12648 		 */
12649 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12650 		if (!func[i])
12651 			goto out_free;
12652 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12653 		       len * sizeof(struct bpf_insn));
12654 		func[i]->type = prog->type;
12655 		func[i]->len = len;
12656 		if (bpf_prog_calc_tag(func[i]))
12657 			goto out_free;
12658 		func[i]->is_func = 1;
12659 		func[i]->aux->func_idx = i;
12660 		/* Below members will be freed only at prog->aux */
12661 		func[i]->aux->btf = prog->aux->btf;
12662 		func[i]->aux->func_info = prog->aux->func_info;
12663 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12664 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12665 
12666 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12667 			struct bpf_jit_poke_descriptor *poke;
12668 
12669 			poke = &prog->aux->poke_tab[j];
12670 			if (poke->insn_idx < subprog_end &&
12671 			    poke->insn_idx >= subprog_start)
12672 				poke->aux = func[i]->aux;
12673 		}
12674 
12675 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
12676 		 * Long term would need debug info to populate names
12677 		 */
12678 		func[i]->aux->name[0] = 'F';
12679 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12680 		func[i]->jit_requested = 1;
12681 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12682 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
12683 		func[i]->aux->linfo = prog->aux->linfo;
12684 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12685 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12686 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12687 		num_exentries = 0;
12688 		insn = func[i]->insnsi;
12689 		for (j = 0; j < func[i]->len; j++, insn++) {
12690 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12691 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12692 				num_exentries++;
12693 		}
12694 		func[i]->aux->num_exentries = num_exentries;
12695 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12696 		func[i] = bpf_int_jit_compile(func[i]);
12697 		if (!func[i]->jited) {
12698 			err = -ENOTSUPP;
12699 			goto out_free;
12700 		}
12701 		cond_resched();
12702 	}
12703 
12704 	/* at this point all bpf functions were successfully JITed
12705 	 * now populate all bpf_calls with correct addresses and
12706 	 * run last pass of JIT
12707 	 */
12708 	for (i = 0; i < env->subprog_cnt; i++) {
12709 		insn = func[i]->insnsi;
12710 		for (j = 0; j < func[i]->len; j++, insn++) {
12711 			if (bpf_pseudo_func(insn)) {
12712 				subprog = insn[1].imm;
12713 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12714 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12715 				continue;
12716 			}
12717 			if (!bpf_pseudo_call(insn))
12718 				continue;
12719 			subprog = insn->off;
12720 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
12721 		}
12722 
12723 		/* we use the aux data to keep a list of the start addresses
12724 		 * of the JITed images for each function in the program
12725 		 *
12726 		 * for some architectures, such as powerpc64, the imm field
12727 		 * might not be large enough to hold the offset of the start
12728 		 * address of the callee's JITed image from __bpf_call_base
12729 		 *
12730 		 * in such cases, we can lookup the start address of a callee
12731 		 * by using its subprog id, available from the off field of
12732 		 * the call instruction, as an index for this list
12733 		 */
12734 		func[i]->aux->func = func;
12735 		func[i]->aux->func_cnt = env->subprog_cnt;
12736 	}
12737 	for (i = 0; i < env->subprog_cnt; i++) {
12738 		old_bpf_func = func[i]->bpf_func;
12739 		tmp = bpf_int_jit_compile(func[i]);
12740 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12741 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12742 			err = -ENOTSUPP;
12743 			goto out_free;
12744 		}
12745 		cond_resched();
12746 	}
12747 
12748 	/* finally lock prog and jit images for all functions and
12749 	 * populate kallsysm
12750 	 */
12751 	for (i = 0; i < env->subprog_cnt; i++) {
12752 		bpf_prog_lock_ro(func[i]);
12753 		bpf_prog_kallsyms_add(func[i]);
12754 	}
12755 
12756 	/* Last step: make now unused interpreter insns from main
12757 	 * prog consistent for later dump requests, so they can
12758 	 * later look the same as if they were interpreted only.
12759 	 */
12760 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12761 		if (bpf_pseudo_func(insn)) {
12762 			insn[0].imm = env->insn_aux_data[i].call_imm;
12763 			insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12764 			continue;
12765 		}
12766 		if (!bpf_pseudo_call(insn))
12767 			continue;
12768 		insn->off = env->insn_aux_data[i].call_imm;
12769 		subprog = find_subprog(env, i + insn->off + 1);
12770 		insn->imm = subprog;
12771 	}
12772 
12773 	prog->jited = 1;
12774 	prog->bpf_func = func[0]->bpf_func;
12775 	prog->aux->func = func;
12776 	prog->aux->func_cnt = env->subprog_cnt;
12777 	bpf_prog_jit_attempt_done(prog);
12778 	return 0;
12779 out_free:
12780 	/* We failed JIT'ing, so at this point we need to unregister poke
12781 	 * descriptors from subprogs, so that kernel is not attempting to
12782 	 * patch it anymore as we're freeing the subprog JIT memory.
12783 	 */
12784 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12785 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12786 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12787 	}
12788 	/* At this point we're guaranteed that poke descriptors are not
12789 	 * live anymore. We can just unlink its descriptor table as it's
12790 	 * released with the main prog.
12791 	 */
12792 	for (i = 0; i < env->subprog_cnt; i++) {
12793 		if (!func[i])
12794 			continue;
12795 		func[i]->aux->poke_tab = NULL;
12796 		bpf_jit_free(func[i]);
12797 	}
12798 	kfree(func);
12799 out_undo_insn:
12800 	/* cleanup main prog to be interpreted */
12801 	prog->jit_requested = 0;
12802 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12803 		if (!bpf_pseudo_call(insn))
12804 			continue;
12805 		insn->off = 0;
12806 		insn->imm = env->insn_aux_data[i].call_imm;
12807 	}
12808 	bpf_prog_jit_attempt_done(prog);
12809 	return err;
12810 }
12811 
12812 static int fixup_call_args(struct bpf_verifier_env *env)
12813 {
12814 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12815 	struct bpf_prog *prog = env->prog;
12816 	struct bpf_insn *insn = prog->insnsi;
12817 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12818 	int i, depth;
12819 #endif
12820 	int err = 0;
12821 
12822 	if (env->prog->jit_requested &&
12823 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12824 		err = jit_subprogs(env);
12825 		if (err == 0)
12826 			return 0;
12827 		if (err == -EFAULT)
12828 			return err;
12829 	}
12830 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12831 	if (has_kfunc_call) {
12832 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12833 		return -EINVAL;
12834 	}
12835 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12836 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12837 		 * have to be rejected, since interpreter doesn't support them yet.
12838 		 */
12839 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12840 		return -EINVAL;
12841 	}
12842 	for (i = 0; i < prog->len; i++, insn++) {
12843 		if (bpf_pseudo_func(insn)) {
12844 			/* When JIT fails the progs with callback calls
12845 			 * have to be rejected, since interpreter doesn't support them yet.
12846 			 */
12847 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12848 			return -EINVAL;
12849 		}
12850 
12851 		if (!bpf_pseudo_call(insn))
12852 			continue;
12853 		depth = get_callee_stack_depth(env, insn, i);
12854 		if (depth < 0)
12855 			return depth;
12856 		bpf_patch_call_args(insn, depth);
12857 	}
12858 	err = 0;
12859 #endif
12860 	return err;
12861 }
12862 
12863 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12864 			    struct bpf_insn *insn)
12865 {
12866 	const struct bpf_kfunc_desc *desc;
12867 
12868 	if (!insn->imm) {
12869 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
12870 		return -EINVAL;
12871 	}
12872 
12873 	/* insn->imm has the btf func_id. Replace it with
12874 	 * an address (relative to __bpf_base_call).
12875 	 */
12876 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
12877 	if (!desc) {
12878 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12879 			insn->imm);
12880 		return -EFAULT;
12881 	}
12882 
12883 	insn->imm = desc->imm;
12884 
12885 	return 0;
12886 }
12887 
12888 /* Do various post-verification rewrites in a single program pass.
12889  * These rewrites simplify JIT and interpreter implementations.
12890  */
12891 static int do_misc_fixups(struct bpf_verifier_env *env)
12892 {
12893 	struct bpf_prog *prog = env->prog;
12894 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12895 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12896 	struct bpf_insn *insn = prog->insnsi;
12897 	const struct bpf_func_proto *fn;
12898 	const int insn_cnt = prog->len;
12899 	const struct bpf_map_ops *ops;
12900 	struct bpf_insn_aux_data *aux;
12901 	struct bpf_insn insn_buf[16];
12902 	struct bpf_prog *new_prog;
12903 	struct bpf_map *map_ptr;
12904 	int i, ret, cnt, delta = 0;
12905 
12906 	for (i = 0; i < insn_cnt; i++, insn++) {
12907 		/* Make divide-by-zero exceptions impossible. */
12908 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12909 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12910 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12911 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12912 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12913 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12914 			struct bpf_insn *patchlet;
12915 			struct bpf_insn chk_and_div[] = {
12916 				/* [R,W]x div 0 -> 0 */
12917 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12918 					     BPF_JNE | BPF_K, insn->src_reg,
12919 					     0, 2, 0),
12920 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12921 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12922 				*insn,
12923 			};
12924 			struct bpf_insn chk_and_mod[] = {
12925 				/* [R,W]x mod 0 -> [R,W]x */
12926 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12927 					     BPF_JEQ | BPF_K, insn->src_reg,
12928 					     0, 1 + (is64 ? 0 : 1), 0),
12929 				*insn,
12930 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12931 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12932 			};
12933 
12934 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12935 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12936 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12937 
12938 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12939 			if (!new_prog)
12940 				return -ENOMEM;
12941 
12942 			delta    += cnt - 1;
12943 			env->prog = prog = new_prog;
12944 			insn      = new_prog->insnsi + i + delta;
12945 			continue;
12946 		}
12947 
12948 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12949 		if (BPF_CLASS(insn->code) == BPF_LD &&
12950 		    (BPF_MODE(insn->code) == BPF_ABS ||
12951 		     BPF_MODE(insn->code) == BPF_IND)) {
12952 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12953 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12954 				verbose(env, "bpf verifier is misconfigured\n");
12955 				return -EINVAL;
12956 			}
12957 
12958 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12959 			if (!new_prog)
12960 				return -ENOMEM;
12961 
12962 			delta    += cnt - 1;
12963 			env->prog = prog = new_prog;
12964 			insn      = new_prog->insnsi + i + delta;
12965 			continue;
12966 		}
12967 
12968 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12969 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12970 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12971 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12972 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12973 			struct bpf_insn *patch = &insn_buf[0];
12974 			bool issrc, isneg, isimm;
12975 			u32 off_reg;
12976 
12977 			aux = &env->insn_aux_data[i + delta];
12978 			if (!aux->alu_state ||
12979 			    aux->alu_state == BPF_ALU_NON_POINTER)
12980 				continue;
12981 
12982 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12983 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12984 				BPF_ALU_SANITIZE_SRC;
12985 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12986 
12987 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12988 			if (isimm) {
12989 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12990 			} else {
12991 				if (isneg)
12992 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12993 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12994 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12995 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12996 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12997 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12998 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12999 			}
13000 			if (!issrc)
13001 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13002 			insn->src_reg = BPF_REG_AX;
13003 			if (isneg)
13004 				insn->code = insn->code == code_add ?
13005 					     code_sub : code_add;
13006 			*patch++ = *insn;
13007 			if (issrc && isneg && !isimm)
13008 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13009 			cnt = patch - insn_buf;
13010 
13011 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13012 			if (!new_prog)
13013 				return -ENOMEM;
13014 
13015 			delta    += cnt - 1;
13016 			env->prog = prog = new_prog;
13017 			insn      = new_prog->insnsi + i + delta;
13018 			continue;
13019 		}
13020 
13021 		if (insn->code != (BPF_JMP | BPF_CALL))
13022 			continue;
13023 		if (insn->src_reg == BPF_PSEUDO_CALL)
13024 			continue;
13025 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13026 			ret = fixup_kfunc_call(env, insn);
13027 			if (ret)
13028 				return ret;
13029 			continue;
13030 		}
13031 
13032 		if (insn->imm == BPF_FUNC_get_route_realm)
13033 			prog->dst_needed = 1;
13034 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13035 			bpf_user_rnd_init_once();
13036 		if (insn->imm == BPF_FUNC_override_return)
13037 			prog->kprobe_override = 1;
13038 		if (insn->imm == BPF_FUNC_tail_call) {
13039 			/* If we tail call into other programs, we
13040 			 * cannot make any assumptions since they can
13041 			 * be replaced dynamically during runtime in
13042 			 * the program array.
13043 			 */
13044 			prog->cb_access = 1;
13045 			if (!allow_tail_call_in_subprogs(env))
13046 				prog->aux->stack_depth = MAX_BPF_STACK;
13047 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13048 
13049 			/* mark bpf_tail_call as different opcode to avoid
13050 			 * conditional branch in the interpreter for every normal
13051 			 * call and to prevent accidental JITing by JIT compiler
13052 			 * that doesn't support bpf_tail_call yet
13053 			 */
13054 			insn->imm = 0;
13055 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13056 
13057 			aux = &env->insn_aux_data[i + delta];
13058 			if (env->bpf_capable && !expect_blinding &&
13059 			    prog->jit_requested &&
13060 			    !bpf_map_key_poisoned(aux) &&
13061 			    !bpf_map_ptr_poisoned(aux) &&
13062 			    !bpf_map_ptr_unpriv(aux)) {
13063 				struct bpf_jit_poke_descriptor desc = {
13064 					.reason = BPF_POKE_REASON_TAIL_CALL,
13065 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13066 					.tail_call.key = bpf_map_key_immediate(aux),
13067 					.insn_idx = i + delta,
13068 				};
13069 
13070 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13071 				if (ret < 0) {
13072 					verbose(env, "adding tail call poke descriptor failed\n");
13073 					return ret;
13074 				}
13075 
13076 				insn->imm = ret + 1;
13077 				continue;
13078 			}
13079 
13080 			if (!bpf_map_ptr_unpriv(aux))
13081 				continue;
13082 
13083 			/* instead of changing every JIT dealing with tail_call
13084 			 * emit two extra insns:
13085 			 * if (index >= max_entries) goto out;
13086 			 * index &= array->index_mask;
13087 			 * to avoid out-of-bounds cpu speculation
13088 			 */
13089 			if (bpf_map_ptr_poisoned(aux)) {
13090 				verbose(env, "tail_call abusing map_ptr\n");
13091 				return -EINVAL;
13092 			}
13093 
13094 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13095 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13096 						  map_ptr->max_entries, 2);
13097 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13098 						    container_of(map_ptr,
13099 								 struct bpf_array,
13100 								 map)->index_mask);
13101 			insn_buf[2] = *insn;
13102 			cnt = 3;
13103 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13104 			if (!new_prog)
13105 				return -ENOMEM;
13106 
13107 			delta    += cnt - 1;
13108 			env->prog = prog = new_prog;
13109 			insn      = new_prog->insnsi + i + delta;
13110 			continue;
13111 		}
13112 
13113 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13114 			/* The verifier will process callback_fn as many times as necessary
13115 			 * with different maps and the register states prepared by
13116 			 * set_timer_callback_state will be accurate.
13117 			 *
13118 			 * The following use case is valid:
13119 			 *   map1 is shared by prog1, prog2, prog3.
13120 			 *   prog1 calls bpf_timer_init for some map1 elements
13121 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13122 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13123 			 *   prog3 calls bpf_timer_start for some map1 elements.
13124 			 *     Those that were not both bpf_timer_init-ed and
13125 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13126 			 */
13127 			struct bpf_insn ld_addrs[2] = {
13128 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13129 			};
13130 
13131 			insn_buf[0] = ld_addrs[0];
13132 			insn_buf[1] = ld_addrs[1];
13133 			insn_buf[2] = *insn;
13134 			cnt = 3;
13135 
13136 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13137 			if (!new_prog)
13138 				return -ENOMEM;
13139 
13140 			delta    += cnt - 1;
13141 			env->prog = prog = new_prog;
13142 			insn      = new_prog->insnsi + i + delta;
13143 			goto patch_call_imm;
13144 		}
13145 
13146 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13147 		 * and other inlining handlers are currently limited to 64 bit
13148 		 * only.
13149 		 */
13150 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13151 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13152 		     insn->imm == BPF_FUNC_map_update_elem ||
13153 		     insn->imm == BPF_FUNC_map_delete_elem ||
13154 		     insn->imm == BPF_FUNC_map_push_elem   ||
13155 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13156 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13157 		     insn->imm == BPF_FUNC_redirect_map    ||
13158 		     insn->imm == BPF_FUNC_for_each_map_elem)) {
13159 			aux = &env->insn_aux_data[i + delta];
13160 			if (bpf_map_ptr_poisoned(aux))
13161 				goto patch_call_imm;
13162 
13163 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13164 			ops = map_ptr->ops;
13165 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13166 			    ops->map_gen_lookup) {
13167 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13168 				if (cnt == -EOPNOTSUPP)
13169 					goto patch_map_ops_generic;
13170 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13171 					verbose(env, "bpf verifier is misconfigured\n");
13172 					return -EINVAL;
13173 				}
13174 
13175 				new_prog = bpf_patch_insn_data(env, i + delta,
13176 							       insn_buf, cnt);
13177 				if (!new_prog)
13178 					return -ENOMEM;
13179 
13180 				delta    += cnt - 1;
13181 				env->prog = prog = new_prog;
13182 				insn      = new_prog->insnsi + i + delta;
13183 				continue;
13184 			}
13185 
13186 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13187 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13188 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13189 				     (int (*)(struct bpf_map *map, void *key))NULL));
13190 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13191 				     (int (*)(struct bpf_map *map, void *key, void *value,
13192 					      u64 flags))NULL));
13193 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13194 				     (int (*)(struct bpf_map *map, void *value,
13195 					      u64 flags))NULL));
13196 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13197 				     (int (*)(struct bpf_map *map, void *value))NULL));
13198 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13199 				     (int (*)(struct bpf_map *map, void *value))NULL));
13200 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13201 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13202 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13203 				     (int (*)(struct bpf_map *map,
13204 					      bpf_callback_t callback_fn,
13205 					      void *callback_ctx,
13206 					      u64 flags))NULL));
13207 
13208 patch_map_ops_generic:
13209 			switch (insn->imm) {
13210 			case BPF_FUNC_map_lookup_elem:
13211 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
13212 				continue;
13213 			case BPF_FUNC_map_update_elem:
13214 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13215 				continue;
13216 			case BPF_FUNC_map_delete_elem:
13217 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13218 				continue;
13219 			case BPF_FUNC_map_push_elem:
13220 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13221 				continue;
13222 			case BPF_FUNC_map_pop_elem:
13223 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13224 				continue;
13225 			case BPF_FUNC_map_peek_elem:
13226 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13227 				continue;
13228 			case BPF_FUNC_redirect_map:
13229 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
13230 				continue;
13231 			case BPF_FUNC_for_each_map_elem:
13232 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
13233 				continue;
13234 			}
13235 
13236 			goto patch_call_imm;
13237 		}
13238 
13239 		/* Implement bpf_jiffies64 inline. */
13240 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13241 		    insn->imm == BPF_FUNC_jiffies64) {
13242 			struct bpf_insn ld_jiffies_addr[2] = {
13243 				BPF_LD_IMM64(BPF_REG_0,
13244 					     (unsigned long)&jiffies),
13245 			};
13246 
13247 			insn_buf[0] = ld_jiffies_addr[0];
13248 			insn_buf[1] = ld_jiffies_addr[1];
13249 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13250 						  BPF_REG_0, 0);
13251 			cnt = 3;
13252 
13253 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13254 						       cnt);
13255 			if (!new_prog)
13256 				return -ENOMEM;
13257 
13258 			delta    += cnt - 1;
13259 			env->prog = prog = new_prog;
13260 			insn      = new_prog->insnsi + i + delta;
13261 			continue;
13262 		}
13263 
13264 		/* Implement bpf_get_func_ip inline. */
13265 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13266 		    insn->imm == BPF_FUNC_get_func_ip) {
13267 			/* Load IP address from ctx - 8 */
13268 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13269 
13270 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13271 			if (!new_prog)
13272 				return -ENOMEM;
13273 
13274 			env->prog = prog = new_prog;
13275 			insn      = new_prog->insnsi + i + delta;
13276 			continue;
13277 		}
13278 
13279 patch_call_imm:
13280 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13281 		/* all functions that have prototype and verifier allowed
13282 		 * programs to call them, must be real in-kernel functions
13283 		 */
13284 		if (!fn->func) {
13285 			verbose(env,
13286 				"kernel subsystem misconfigured func %s#%d\n",
13287 				func_id_name(insn->imm), insn->imm);
13288 			return -EFAULT;
13289 		}
13290 		insn->imm = fn->func - __bpf_call_base;
13291 	}
13292 
13293 	/* Since poke tab is now finalized, publish aux to tracker. */
13294 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13295 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13296 		if (!map_ptr->ops->map_poke_track ||
13297 		    !map_ptr->ops->map_poke_untrack ||
13298 		    !map_ptr->ops->map_poke_run) {
13299 			verbose(env, "bpf verifier is misconfigured\n");
13300 			return -EINVAL;
13301 		}
13302 
13303 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13304 		if (ret < 0) {
13305 			verbose(env, "tracking tail call prog failed\n");
13306 			return ret;
13307 		}
13308 	}
13309 
13310 	sort_kfunc_descs_by_imm(env->prog);
13311 
13312 	return 0;
13313 }
13314 
13315 static void free_states(struct bpf_verifier_env *env)
13316 {
13317 	struct bpf_verifier_state_list *sl, *sln;
13318 	int i;
13319 
13320 	sl = env->free_list;
13321 	while (sl) {
13322 		sln = sl->next;
13323 		free_verifier_state(&sl->state, false);
13324 		kfree(sl);
13325 		sl = sln;
13326 	}
13327 	env->free_list = NULL;
13328 
13329 	if (!env->explored_states)
13330 		return;
13331 
13332 	for (i = 0; i < state_htab_size(env); i++) {
13333 		sl = env->explored_states[i];
13334 
13335 		while (sl) {
13336 			sln = sl->next;
13337 			free_verifier_state(&sl->state, false);
13338 			kfree(sl);
13339 			sl = sln;
13340 		}
13341 		env->explored_states[i] = NULL;
13342 	}
13343 }
13344 
13345 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13346 {
13347 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13348 	struct bpf_verifier_state *state;
13349 	struct bpf_reg_state *regs;
13350 	int ret, i;
13351 
13352 	env->prev_linfo = NULL;
13353 	env->pass_cnt++;
13354 
13355 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13356 	if (!state)
13357 		return -ENOMEM;
13358 	state->curframe = 0;
13359 	state->speculative = false;
13360 	state->branches = 1;
13361 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13362 	if (!state->frame[0]) {
13363 		kfree(state);
13364 		return -ENOMEM;
13365 	}
13366 	env->cur_state = state;
13367 	init_func_state(env, state->frame[0],
13368 			BPF_MAIN_FUNC /* callsite */,
13369 			0 /* frameno */,
13370 			subprog);
13371 
13372 	regs = state->frame[state->curframe]->regs;
13373 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13374 		ret = btf_prepare_func_args(env, subprog, regs);
13375 		if (ret)
13376 			goto out;
13377 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13378 			if (regs[i].type == PTR_TO_CTX)
13379 				mark_reg_known_zero(env, regs, i);
13380 			else if (regs[i].type == SCALAR_VALUE)
13381 				mark_reg_unknown(env, regs, i);
13382 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13383 				const u32 mem_size = regs[i].mem_size;
13384 
13385 				mark_reg_known_zero(env, regs, i);
13386 				regs[i].mem_size = mem_size;
13387 				regs[i].id = ++env->id_gen;
13388 			}
13389 		}
13390 	} else {
13391 		/* 1st arg to a function */
13392 		regs[BPF_REG_1].type = PTR_TO_CTX;
13393 		mark_reg_known_zero(env, regs, BPF_REG_1);
13394 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13395 		if (ret == -EFAULT)
13396 			/* unlikely verifier bug. abort.
13397 			 * ret == 0 and ret < 0 are sadly acceptable for
13398 			 * main() function due to backward compatibility.
13399 			 * Like socket filter program may be written as:
13400 			 * int bpf_prog(struct pt_regs *ctx)
13401 			 * and never dereference that ctx in the program.
13402 			 * 'struct pt_regs' is a type mismatch for socket
13403 			 * filter that should be using 'struct __sk_buff'.
13404 			 */
13405 			goto out;
13406 	}
13407 
13408 	ret = do_check(env);
13409 out:
13410 	/* check for NULL is necessary, since cur_state can be freed inside
13411 	 * do_check() under memory pressure.
13412 	 */
13413 	if (env->cur_state) {
13414 		free_verifier_state(env->cur_state, true);
13415 		env->cur_state = NULL;
13416 	}
13417 	while (!pop_stack(env, NULL, NULL, false));
13418 	if (!ret && pop_log)
13419 		bpf_vlog_reset(&env->log, 0);
13420 	free_states(env);
13421 	return ret;
13422 }
13423 
13424 /* Verify all global functions in a BPF program one by one based on their BTF.
13425  * All global functions must pass verification. Otherwise the whole program is rejected.
13426  * Consider:
13427  * int bar(int);
13428  * int foo(int f)
13429  * {
13430  *    return bar(f);
13431  * }
13432  * int bar(int b)
13433  * {
13434  *    ...
13435  * }
13436  * foo() will be verified first for R1=any_scalar_value. During verification it
13437  * will be assumed that bar() already verified successfully and call to bar()
13438  * from foo() will be checked for type match only. Later bar() will be verified
13439  * independently to check that it's safe for R1=any_scalar_value.
13440  */
13441 static int do_check_subprogs(struct bpf_verifier_env *env)
13442 {
13443 	struct bpf_prog_aux *aux = env->prog->aux;
13444 	int i, ret;
13445 
13446 	if (!aux->func_info)
13447 		return 0;
13448 
13449 	for (i = 1; i < env->subprog_cnt; i++) {
13450 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13451 			continue;
13452 		env->insn_idx = env->subprog_info[i].start;
13453 		WARN_ON_ONCE(env->insn_idx == 0);
13454 		ret = do_check_common(env, i);
13455 		if (ret) {
13456 			return ret;
13457 		} else if (env->log.level & BPF_LOG_LEVEL) {
13458 			verbose(env,
13459 				"Func#%d is safe for any args that match its prototype\n",
13460 				i);
13461 		}
13462 	}
13463 	return 0;
13464 }
13465 
13466 static int do_check_main(struct bpf_verifier_env *env)
13467 {
13468 	int ret;
13469 
13470 	env->insn_idx = 0;
13471 	ret = do_check_common(env, 0);
13472 	if (!ret)
13473 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13474 	return ret;
13475 }
13476 
13477 
13478 static void print_verification_stats(struct bpf_verifier_env *env)
13479 {
13480 	int i;
13481 
13482 	if (env->log.level & BPF_LOG_STATS) {
13483 		verbose(env, "verification time %lld usec\n",
13484 			div_u64(env->verification_time, 1000));
13485 		verbose(env, "stack depth ");
13486 		for (i = 0; i < env->subprog_cnt; i++) {
13487 			u32 depth = env->subprog_info[i].stack_depth;
13488 
13489 			verbose(env, "%d", depth);
13490 			if (i + 1 < env->subprog_cnt)
13491 				verbose(env, "+");
13492 		}
13493 		verbose(env, "\n");
13494 	}
13495 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13496 		"total_states %d peak_states %d mark_read %d\n",
13497 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13498 		env->max_states_per_insn, env->total_states,
13499 		env->peak_states, env->longest_mark_read_walk);
13500 }
13501 
13502 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13503 {
13504 	const struct btf_type *t, *func_proto;
13505 	const struct bpf_struct_ops *st_ops;
13506 	const struct btf_member *member;
13507 	struct bpf_prog *prog = env->prog;
13508 	u32 btf_id, member_idx;
13509 	const char *mname;
13510 
13511 	if (!prog->gpl_compatible) {
13512 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13513 		return -EINVAL;
13514 	}
13515 
13516 	btf_id = prog->aux->attach_btf_id;
13517 	st_ops = bpf_struct_ops_find(btf_id);
13518 	if (!st_ops) {
13519 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13520 			btf_id);
13521 		return -ENOTSUPP;
13522 	}
13523 
13524 	t = st_ops->type;
13525 	member_idx = prog->expected_attach_type;
13526 	if (member_idx >= btf_type_vlen(t)) {
13527 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13528 			member_idx, st_ops->name);
13529 		return -EINVAL;
13530 	}
13531 
13532 	member = &btf_type_member(t)[member_idx];
13533 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13534 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13535 					       NULL);
13536 	if (!func_proto) {
13537 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13538 			mname, member_idx, st_ops->name);
13539 		return -EINVAL;
13540 	}
13541 
13542 	if (st_ops->check_member) {
13543 		int err = st_ops->check_member(t, member);
13544 
13545 		if (err) {
13546 			verbose(env, "attach to unsupported member %s of struct %s\n",
13547 				mname, st_ops->name);
13548 			return err;
13549 		}
13550 	}
13551 
13552 	prog->aux->attach_func_proto = func_proto;
13553 	prog->aux->attach_func_name = mname;
13554 	env->ops = st_ops->verifier_ops;
13555 
13556 	return 0;
13557 }
13558 #define SECURITY_PREFIX "security_"
13559 
13560 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13561 {
13562 	if (within_error_injection_list(addr) ||
13563 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13564 		return 0;
13565 
13566 	return -EINVAL;
13567 }
13568 
13569 /* list of non-sleepable functions that are otherwise on
13570  * ALLOW_ERROR_INJECTION list
13571  */
13572 BTF_SET_START(btf_non_sleepable_error_inject)
13573 /* Three functions below can be called from sleepable and non-sleepable context.
13574  * Assume non-sleepable from bpf safety point of view.
13575  */
13576 BTF_ID(func, __filemap_add_folio)
13577 BTF_ID(func, should_fail_alloc_page)
13578 BTF_ID(func, should_failslab)
13579 BTF_SET_END(btf_non_sleepable_error_inject)
13580 
13581 static int check_non_sleepable_error_inject(u32 btf_id)
13582 {
13583 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13584 }
13585 
13586 int bpf_check_attach_target(struct bpf_verifier_log *log,
13587 			    const struct bpf_prog *prog,
13588 			    const struct bpf_prog *tgt_prog,
13589 			    u32 btf_id,
13590 			    struct bpf_attach_target_info *tgt_info)
13591 {
13592 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13593 	const char prefix[] = "btf_trace_";
13594 	int ret = 0, subprog = -1, i;
13595 	const struct btf_type *t;
13596 	bool conservative = true;
13597 	const char *tname;
13598 	struct btf *btf;
13599 	long addr = 0;
13600 
13601 	if (!btf_id) {
13602 		bpf_log(log, "Tracing programs must provide btf_id\n");
13603 		return -EINVAL;
13604 	}
13605 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13606 	if (!btf) {
13607 		bpf_log(log,
13608 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13609 		return -EINVAL;
13610 	}
13611 	t = btf_type_by_id(btf, btf_id);
13612 	if (!t) {
13613 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13614 		return -EINVAL;
13615 	}
13616 	tname = btf_name_by_offset(btf, t->name_off);
13617 	if (!tname) {
13618 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13619 		return -EINVAL;
13620 	}
13621 	if (tgt_prog) {
13622 		struct bpf_prog_aux *aux = tgt_prog->aux;
13623 
13624 		for (i = 0; i < aux->func_info_cnt; i++)
13625 			if (aux->func_info[i].type_id == btf_id) {
13626 				subprog = i;
13627 				break;
13628 			}
13629 		if (subprog == -1) {
13630 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13631 			return -EINVAL;
13632 		}
13633 		conservative = aux->func_info_aux[subprog].unreliable;
13634 		if (prog_extension) {
13635 			if (conservative) {
13636 				bpf_log(log,
13637 					"Cannot replace static functions\n");
13638 				return -EINVAL;
13639 			}
13640 			if (!prog->jit_requested) {
13641 				bpf_log(log,
13642 					"Extension programs should be JITed\n");
13643 				return -EINVAL;
13644 			}
13645 		}
13646 		if (!tgt_prog->jited) {
13647 			bpf_log(log, "Can attach to only JITed progs\n");
13648 			return -EINVAL;
13649 		}
13650 		if (tgt_prog->type == prog->type) {
13651 			/* Cannot fentry/fexit another fentry/fexit program.
13652 			 * Cannot attach program extension to another extension.
13653 			 * It's ok to attach fentry/fexit to extension program.
13654 			 */
13655 			bpf_log(log, "Cannot recursively attach\n");
13656 			return -EINVAL;
13657 		}
13658 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13659 		    prog_extension &&
13660 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13661 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13662 			/* Program extensions can extend all program types
13663 			 * except fentry/fexit. The reason is the following.
13664 			 * The fentry/fexit programs are used for performance
13665 			 * analysis, stats and can be attached to any program
13666 			 * type except themselves. When extension program is
13667 			 * replacing XDP function it is necessary to allow
13668 			 * performance analysis of all functions. Both original
13669 			 * XDP program and its program extension. Hence
13670 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13671 			 * allowed. If extending of fentry/fexit was allowed it
13672 			 * would be possible to create long call chain
13673 			 * fentry->extension->fentry->extension beyond
13674 			 * reasonable stack size. Hence extending fentry is not
13675 			 * allowed.
13676 			 */
13677 			bpf_log(log, "Cannot extend fentry/fexit\n");
13678 			return -EINVAL;
13679 		}
13680 	} else {
13681 		if (prog_extension) {
13682 			bpf_log(log, "Cannot replace kernel functions\n");
13683 			return -EINVAL;
13684 		}
13685 	}
13686 
13687 	switch (prog->expected_attach_type) {
13688 	case BPF_TRACE_RAW_TP:
13689 		if (tgt_prog) {
13690 			bpf_log(log,
13691 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13692 			return -EINVAL;
13693 		}
13694 		if (!btf_type_is_typedef(t)) {
13695 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13696 				btf_id);
13697 			return -EINVAL;
13698 		}
13699 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13700 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13701 				btf_id, tname);
13702 			return -EINVAL;
13703 		}
13704 		tname += sizeof(prefix) - 1;
13705 		t = btf_type_by_id(btf, t->type);
13706 		if (!btf_type_is_ptr(t))
13707 			/* should never happen in valid vmlinux build */
13708 			return -EINVAL;
13709 		t = btf_type_by_id(btf, t->type);
13710 		if (!btf_type_is_func_proto(t))
13711 			/* should never happen in valid vmlinux build */
13712 			return -EINVAL;
13713 
13714 		break;
13715 	case BPF_TRACE_ITER:
13716 		if (!btf_type_is_func(t)) {
13717 			bpf_log(log, "attach_btf_id %u is not a function\n",
13718 				btf_id);
13719 			return -EINVAL;
13720 		}
13721 		t = btf_type_by_id(btf, t->type);
13722 		if (!btf_type_is_func_proto(t))
13723 			return -EINVAL;
13724 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13725 		if (ret)
13726 			return ret;
13727 		break;
13728 	default:
13729 		if (!prog_extension)
13730 			return -EINVAL;
13731 		fallthrough;
13732 	case BPF_MODIFY_RETURN:
13733 	case BPF_LSM_MAC:
13734 	case BPF_TRACE_FENTRY:
13735 	case BPF_TRACE_FEXIT:
13736 		if (!btf_type_is_func(t)) {
13737 			bpf_log(log, "attach_btf_id %u is not a function\n",
13738 				btf_id);
13739 			return -EINVAL;
13740 		}
13741 		if (prog_extension &&
13742 		    btf_check_type_match(log, prog, btf, t))
13743 			return -EINVAL;
13744 		t = btf_type_by_id(btf, t->type);
13745 		if (!btf_type_is_func_proto(t))
13746 			return -EINVAL;
13747 
13748 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13749 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13750 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13751 			return -EINVAL;
13752 
13753 		if (tgt_prog && conservative)
13754 			t = NULL;
13755 
13756 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13757 		if (ret < 0)
13758 			return ret;
13759 
13760 		if (tgt_prog) {
13761 			if (subprog == 0)
13762 				addr = (long) tgt_prog->bpf_func;
13763 			else
13764 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13765 		} else {
13766 			addr = kallsyms_lookup_name(tname);
13767 			if (!addr) {
13768 				bpf_log(log,
13769 					"The address of function %s cannot be found\n",
13770 					tname);
13771 				return -ENOENT;
13772 			}
13773 		}
13774 
13775 		if (prog->aux->sleepable) {
13776 			ret = -EINVAL;
13777 			switch (prog->type) {
13778 			case BPF_PROG_TYPE_TRACING:
13779 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13780 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13781 				 */
13782 				if (!check_non_sleepable_error_inject(btf_id) &&
13783 				    within_error_injection_list(addr))
13784 					ret = 0;
13785 				break;
13786 			case BPF_PROG_TYPE_LSM:
13787 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13788 				 * Only some of them are sleepable.
13789 				 */
13790 				if (bpf_lsm_is_sleepable_hook(btf_id))
13791 					ret = 0;
13792 				break;
13793 			default:
13794 				break;
13795 			}
13796 			if (ret) {
13797 				bpf_log(log, "%s is not sleepable\n", tname);
13798 				return ret;
13799 			}
13800 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13801 			if (tgt_prog) {
13802 				bpf_log(log, "can't modify return codes of BPF programs\n");
13803 				return -EINVAL;
13804 			}
13805 			ret = check_attach_modify_return(addr, tname);
13806 			if (ret) {
13807 				bpf_log(log, "%s() is not modifiable\n", tname);
13808 				return ret;
13809 			}
13810 		}
13811 
13812 		break;
13813 	}
13814 	tgt_info->tgt_addr = addr;
13815 	tgt_info->tgt_name = tname;
13816 	tgt_info->tgt_type = t;
13817 	return 0;
13818 }
13819 
13820 BTF_SET_START(btf_id_deny)
13821 BTF_ID_UNUSED
13822 #ifdef CONFIG_SMP
13823 BTF_ID(func, migrate_disable)
13824 BTF_ID(func, migrate_enable)
13825 #endif
13826 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13827 BTF_ID(func, rcu_read_unlock_strict)
13828 #endif
13829 BTF_SET_END(btf_id_deny)
13830 
13831 static int check_attach_btf_id(struct bpf_verifier_env *env)
13832 {
13833 	struct bpf_prog *prog = env->prog;
13834 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13835 	struct bpf_attach_target_info tgt_info = {};
13836 	u32 btf_id = prog->aux->attach_btf_id;
13837 	struct bpf_trampoline *tr;
13838 	int ret;
13839 	u64 key;
13840 
13841 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13842 		if (prog->aux->sleepable)
13843 			/* attach_btf_id checked to be zero already */
13844 			return 0;
13845 		verbose(env, "Syscall programs can only be sleepable\n");
13846 		return -EINVAL;
13847 	}
13848 
13849 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13850 	    prog->type != BPF_PROG_TYPE_LSM) {
13851 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13852 		return -EINVAL;
13853 	}
13854 
13855 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13856 		return check_struct_ops_btf_id(env);
13857 
13858 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13859 	    prog->type != BPF_PROG_TYPE_LSM &&
13860 	    prog->type != BPF_PROG_TYPE_EXT)
13861 		return 0;
13862 
13863 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13864 	if (ret)
13865 		return ret;
13866 
13867 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13868 		/* to make freplace equivalent to their targets, they need to
13869 		 * inherit env->ops and expected_attach_type for the rest of the
13870 		 * verification
13871 		 */
13872 		env->ops = bpf_verifier_ops[tgt_prog->type];
13873 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13874 	}
13875 
13876 	/* store info about the attachment target that will be used later */
13877 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13878 	prog->aux->attach_func_name = tgt_info.tgt_name;
13879 
13880 	if (tgt_prog) {
13881 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13882 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13883 	}
13884 
13885 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13886 		prog->aux->attach_btf_trace = true;
13887 		return 0;
13888 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13889 		if (!bpf_iter_prog_supported(prog))
13890 			return -EINVAL;
13891 		return 0;
13892 	}
13893 
13894 	if (prog->type == BPF_PROG_TYPE_LSM) {
13895 		ret = bpf_lsm_verify_prog(&env->log, prog);
13896 		if (ret < 0)
13897 			return ret;
13898 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13899 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13900 		return -EINVAL;
13901 	}
13902 
13903 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13904 	tr = bpf_trampoline_get(key, &tgt_info);
13905 	if (!tr)
13906 		return -ENOMEM;
13907 
13908 	prog->aux->dst_trampoline = tr;
13909 	return 0;
13910 }
13911 
13912 struct btf *bpf_get_btf_vmlinux(void)
13913 {
13914 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13915 		mutex_lock(&bpf_verifier_lock);
13916 		if (!btf_vmlinux)
13917 			btf_vmlinux = btf_parse_vmlinux();
13918 		mutex_unlock(&bpf_verifier_lock);
13919 	}
13920 	return btf_vmlinux;
13921 }
13922 
13923 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13924 {
13925 	u64 start_time = ktime_get_ns();
13926 	struct bpf_verifier_env *env;
13927 	struct bpf_verifier_log *log;
13928 	int i, len, ret = -EINVAL;
13929 	bool is_priv;
13930 
13931 	/* no program is valid */
13932 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13933 		return -EINVAL;
13934 
13935 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13936 	 * allocate/free it every time bpf_check() is called
13937 	 */
13938 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13939 	if (!env)
13940 		return -ENOMEM;
13941 	log = &env->log;
13942 
13943 	len = (*prog)->len;
13944 	env->insn_aux_data =
13945 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13946 	ret = -ENOMEM;
13947 	if (!env->insn_aux_data)
13948 		goto err_free_env;
13949 	for (i = 0; i < len; i++)
13950 		env->insn_aux_data[i].orig_idx = i;
13951 	env->prog = *prog;
13952 	env->ops = bpf_verifier_ops[env->prog->type];
13953 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13954 	is_priv = bpf_capable();
13955 
13956 	bpf_get_btf_vmlinux();
13957 
13958 	/* grab the mutex to protect few globals used by verifier */
13959 	if (!is_priv)
13960 		mutex_lock(&bpf_verifier_lock);
13961 
13962 	if (attr->log_level || attr->log_buf || attr->log_size) {
13963 		/* user requested verbose verifier output
13964 		 * and supplied buffer to store the verification trace
13965 		 */
13966 		log->level = attr->log_level;
13967 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13968 		log->len_total = attr->log_size;
13969 
13970 		ret = -EINVAL;
13971 		/* log attributes have to be sane */
13972 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13973 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13974 			goto err_unlock;
13975 	}
13976 
13977 	if (IS_ERR(btf_vmlinux)) {
13978 		/* Either gcc or pahole or kernel are broken. */
13979 		verbose(env, "in-kernel BTF is malformed\n");
13980 		ret = PTR_ERR(btf_vmlinux);
13981 		goto skip_full_check;
13982 	}
13983 
13984 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13985 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13986 		env->strict_alignment = true;
13987 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13988 		env->strict_alignment = false;
13989 
13990 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13991 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13992 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13993 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13994 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13995 	env->bpf_capable = bpf_capable();
13996 
13997 	if (is_priv)
13998 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13999 
14000 	env->explored_states = kvcalloc(state_htab_size(env),
14001 				       sizeof(struct bpf_verifier_state_list *),
14002 				       GFP_USER);
14003 	ret = -ENOMEM;
14004 	if (!env->explored_states)
14005 		goto skip_full_check;
14006 
14007 	ret = add_subprog_and_kfunc(env);
14008 	if (ret < 0)
14009 		goto skip_full_check;
14010 
14011 	ret = check_subprogs(env);
14012 	if (ret < 0)
14013 		goto skip_full_check;
14014 
14015 	ret = check_btf_info(env, attr, uattr);
14016 	if (ret < 0)
14017 		goto skip_full_check;
14018 
14019 	ret = check_attach_btf_id(env);
14020 	if (ret)
14021 		goto skip_full_check;
14022 
14023 	ret = resolve_pseudo_ldimm64(env);
14024 	if (ret < 0)
14025 		goto skip_full_check;
14026 
14027 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
14028 		ret = bpf_prog_offload_verifier_prep(env->prog);
14029 		if (ret)
14030 			goto skip_full_check;
14031 	}
14032 
14033 	ret = check_cfg(env);
14034 	if (ret < 0)
14035 		goto skip_full_check;
14036 
14037 	ret = do_check_subprogs(env);
14038 	ret = ret ?: do_check_main(env);
14039 
14040 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14041 		ret = bpf_prog_offload_finalize(env);
14042 
14043 skip_full_check:
14044 	kvfree(env->explored_states);
14045 
14046 	if (ret == 0)
14047 		ret = check_max_stack_depth(env);
14048 
14049 	/* instruction rewrites happen after this point */
14050 	if (is_priv) {
14051 		if (ret == 0)
14052 			opt_hard_wire_dead_code_branches(env);
14053 		if (ret == 0)
14054 			ret = opt_remove_dead_code(env);
14055 		if (ret == 0)
14056 			ret = opt_remove_nops(env);
14057 	} else {
14058 		if (ret == 0)
14059 			sanitize_dead_code(env);
14060 	}
14061 
14062 	if (ret == 0)
14063 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14064 		ret = convert_ctx_accesses(env);
14065 
14066 	if (ret == 0)
14067 		ret = do_misc_fixups(env);
14068 
14069 	/* do 32-bit optimization after insn patching has done so those patched
14070 	 * insns could be handled correctly.
14071 	 */
14072 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14073 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14074 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14075 								     : false;
14076 	}
14077 
14078 	if (ret == 0)
14079 		ret = fixup_call_args(env);
14080 
14081 	env->verification_time = ktime_get_ns() - start_time;
14082 	print_verification_stats(env);
14083 	env->prog->aux->verified_insns = env->insn_processed;
14084 
14085 	if (log->level && bpf_verifier_log_full(log))
14086 		ret = -ENOSPC;
14087 	if (log->level && !log->ubuf) {
14088 		ret = -EFAULT;
14089 		goto err_release_maps;
14090 	}
14091 
14092 	if (ret)
14093 		goto err_release_maps;
14094 
14095 	if (env->used_map_cnt) {
14096 		/* if program passed verifier, update used_maps in bpf_prog_info */
14097 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14098 							  sizeof(env->used_maps[0]),
14099 							  GFP_KERNEL);
14100 
14101 		if (!env->prog->aux->used_maps) {
14102 			ret = -ENOMEM;
14103 			goto err_release_maps;
14104 		}
14105 
14106 		memcpy(env->prog->aux->used_maps, env->used_maps,
14107 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14108 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14109 	}
14110 	if (env->used_btf_cnt) {
14111 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14112 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14113 							  sizeof(env->used_btfs[0]),
14114 							  GFP_KERNEL);
14115 		if (!env->prog->aux->used_btfs) {
14116 			ret = -ENOMEM;
14117 			goto err_release_maps;
14118 		}
14119 
14120 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14121 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14122 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14123 	}
14124 	if (env->used_map_cnt || env->used_btf_cnt) {
14125 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14126 		 * bpf_ld_imm64 instructions
14127 		 */
14128 		convert_pseudo_ld_imm64(env);
14129 	}
14130 
14131 	adjust_btf_func(env);
14132 
14133 err_release_maps:
14134 	if (!env->prog->aux->used_maps)
14135 		/* if we didn't copy map pointers into bpf_prog_info, release
14136 		 * them now. Otherwise free_used_maps() will release them.
14137 		 */
14138 		release_maps(env);
14139 	if (!env->prog->aux->used_btfs)
14140 		release_btfs(env);
14141 
14142 	/* extension progs temporarily inherit the attach_type of their targets
14143 	   for verification purposes, so set it back to zero before returning
14144 	 */
14145 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14146 		env->prog->expected_attach_type = 0;
14147 
14148 	*prog = env->prog;
14149 err_unlock:
14150 	if (!is_priv)
14151 		mutex_unlock(&bpf_verifier_lock);
14152 	vfree(env->insn_aux_data);
14153 err_free_env:
14154 	kfree(env);
14155 	return ret;
14156 }
14157