xref: /linux/kernel/bpf/verifier.c (revision e0c1b49f5b674cca7b10549c53b3791d0bbc90a8)
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 prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6136 {
6137 	struct bpf_verifier_state *state = env->cur_state;
6138 	struct bpf_func_state *caller, *callee;
6139 	struct bpf_reg_state *r0;
6140 	int err;
6141 
6142 	callee = state->frame[state->curframe];
6143 	r0 = &callee->regs[BPF_REG_0];
6144 	if (r0->type == PTR_TO_STACK) {
6145 		/* technically it's ok to return caller's stack pointer
6146 		 * (or caller's caller's pointer) back to the caller,
6147 		 * since these pointers are valid. Only current stack
6148 		 * pointer will be invalid as soon as function exits,
6149 		 * but let's be conservative
6150 		 */
6151 		verbose(env, "cannot return stack pointer to the caller\n");
6152 		return -EINVAL;
6153 	}
6154 
6155 	state->curframe--;
6156 	caller = state->frame[state->curframe];
6157 	if (callee->in_callback_fn) {
6158 		/* enforce R0 return value range [0, 1]. */
6159 		struct tnum range = tnum_range(0, 1);
6160 
6161 		if (r0->type != SCALAR_VALUE) {
6162 			verbose(env, "R0 not a scalar value\n");
6163 			return -EACCES;
6164 		}
6165 		if (!tnum_in(range, r0->var_off)) {
6166 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6167 			return -EINVAL;
6168 		}
6169 	} else {
6170 		/* return to the caller whatever r0 had in the callee */
6171 		caller->regs[BPF_REG_0] = *r0;
6172 	}
6173 
6174 	/* Transfer references to the caller */
6175 	err = copy_reference_state(caller, callee);
6176 	if (err)
6177 		return err;
6178 
6179 	*insn_idx = callee->callsite + 1;
6180 	if (env->log.level & BPF_LOG_LEVEL) {
6181 		verbose(env, "returning from callee:\n");
6182 		print_verifier_state(env, callee);
6183 		verbose(env, "to caller at %d:\n", *insn_idx);
6184 		print_verifier_state(env, caller);
6185 	}
6186 	/* clear everything in the callee */
6187 	free_func_state(callee);
6188 	state->frame[state->curframe + 1] = NULL;
6189 	return 0;
6190 }
6191 
6192 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6193 				   int func_id,
6194 				   struct bpf_call_arg_meta *meta)
6195 {
6196 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6197 
6198 	if (ret_type != RET_INTEGER ||
6199 	    (func_id != BPF_FUNC_get_stack &&
6200 	     func_id != BPF_FUNC_get_task_stack &&
6201 	     func_id != BPF_FUNC_probe_read_str &&
6202 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6203 	     func_id != BPF_FUNC_probe_read_user_str))
6204 		return;
6205 
6206 	ret_reg->smax_value = meta->msize_max_value;
6207 	ret_reg->s32_max_value = meta->msize_max_value;
6208 	ret_reg->smin_value = -MAX_ERRNO;
6209 	ret_reg->s32_min_value = -MAX_ERRNO;
6210 	__reg_deduce_bounds(ret_reg);
6211 	__reg_bound_offset(ret_reg);
6212 	__update_reg_bounds(ret_reg);
6213 }
6214 
6215 static int
6216 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6217 		int func_id, int insn_idx)
6218 {
6219 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6220 	struct bpf_map *map = meta->map_ptr;
6221 
6222 	if (func_id != BPF_FUNC_tail_call &&
6223 	    func_id != BPF_FUNC_map_lookup_elem &&
6224 	    func_id != BPF_FUNC_map_update_elem &&
6225 	    func_id != BPF_FUNC_map_delete_elem &&
6226 	    func_id != BPF_FUNC_map_push_elem &&
6227 	    func_id != BPF_FUNC_map_pop_elem &&
6228 	    func_id != BPF_FUNC_map_peek_elem &&
6229 	    func_id != BPF_FUNC_for_each_map_elem &&
6230 	    func_id != BPF_FUNC_redirect_map)
6231 		return 0;
6232 
6233 	if (map == NULL) {
6234 		verbose(env, "kernel subsystem misconfigured verifier\n");
6235 		return -EINVAL;
6236 	}
6237 
6238 	/* In case of read-only, some additional restrictions
6239 	 * need to be applied in order to prevent altering the
6240 	 * state of the map from program side.
6241 	 */
6242 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6243 	    (func_id == BPF_FUNC_map_delete_elem ||
6244 	     func_id == BPF_FUNC_map_update_elem ||
6245 	     func_id == BPF_FUNC_map_push_elem ||
6246 	     func_id == BPF_FUNC_map_pop_elem)) {
6247 		verbose(env, "write into map forbidden\n");
6248 		return -EACCES;
6249 	}
6250 
6251 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6252 		bpf_map_ptr_store(aux, meta->map_ptr,
6253 				  !meta->map_ptr->bypass_spec_v1);
6254 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6255 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6256 				  !meta->map_ptr->bypass_spec_v1);
6257 	return 0;
6258 }
6259 
6260 static int
6261 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6262 		int func_id, int insn_idx)
6263 {
6264 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6265 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6266 	struct bpf_map *map = meta->map_ptr;
6267 	struct tnum range;
6268 	u64 val;
6269 	int err;
6270 
6271 	if (func_id != BPF_FUNC_tail_call)
6272 		return 0;
6273 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6274 		verbose(env, "kernel subsystem misconfigured verifier\n");
6275 		return -EINVAL;
6276 	}
6277 
6278 	range = tnum_range(0, map->max_entries - 1);
6279 	reg = &regs[BPF_REG_3];
6280 
6281 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6282 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6283 		return 0;
6284 	}
6285 
6286 	err = mark_chain_precision(env, BPF_REG_3);
6287 	if (err)
6288 		return err;
6289 
6290 	val = reg->var_off.value;
6291 	if (bpf_map_key_unseen(aux))
6292 		bpf_map_key_store(aux, val);
6293 	else if (!bpf_map_key_poisoned(aux) &&
6294 		  bpf_map_key_immediate(aux) != val)
6295 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6296 	return 0;
6297 }
6298 
6299 static int check_reference_leak(struct bpf_verifier_env *env)
6300 {
6301 	struct bpf_func_state *state = cur_func(env);
6302 	int i;
6303 
6304 	for (i = 0; i < state->acquired_refs; i++) {
6305 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6306 			state->refs[i].id, state->refs[i].insn_idx);
6307 	}
6308 	return state->acquired_refs ? -EINVAL : 0;
6309 }
6310 
6311 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6312 				   struct bpf_reg_state *regs)
6313 {
6314 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6315 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6316 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6317 	int err, fmt_map_off, num_args;
6318 	u64 fmt_addr;
6319 	char *fmt;
6320 
6321 	/* data must be an array of u64 */
6322 	if (data_len_reg->var_off.value % 8)
6323 		return -EINVAL;
6324 	num_args = data_len_reg->var_off.value / 8;
6325 
6326 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6327 	 * and map_direct_value_addr is set.
6328 	 */
6329 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6330 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6331 						  fmt_map_off);
6332 	if (err) {
6333 		verbose(env, "verifier bug\n");
6334 		return -EFAULT;
6335 	}
6336 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6337 
6338 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6339 	 * can focus on validating the format specifiers.
6340 	 */
6341 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6342 	if (err < 0)
6343 		verbose(env, "Invalid format string\n");
6344 
6345 	return err;
6346 }
6347 
6348 static int check_get_func_ip(struct bpf_verifier_env *env)
6349 {
6350 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6351 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6352 	int func_id = BPF_FUNC_get_func_ip;
6353 
6354 	if (type == BPF_PROG_TYPE_TRACING) {
6355 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6356 		    eatype != BPF_MODIFY_RETURN) {
6357 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6358 				func_id_name(func_id), func_id);
6359 			return -ENOTSUPP;
6360 		}
6361 		return 0;
6362 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6363 		return 0;
6364 	}
6365 
6366 	verbose(env, "func %s#%d not supported for program type %d\n",
6367 		func_id_name(func_id), func_id, type);
6368 	return -ENOTSUPP;
6369 }
6370 
6371 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6372 			     int *insn_idx_p)
6373 {
6374 	const struct bpf_func_proto *fn = NULL;
6375 	struct bpf_reg_state *regs;
6376 	struct bpf_call_arg_meta meta;
6377 	int insn_idx = *insn_idx_p;
6378 	bool changes_data;
6379 	int i, err, func_id;
6380 
6381 	/* find function prototype */
6382 	func_id = insn->imm;
6383 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6384 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6385 			func_id);
6386 		return -EINVAL;
6387 	}
6388 
6389 	if (env->ops->get_func_proto)
6390 		fn = env->ops->get_func_proto(func_id, env->prog);
6391 	if (!fn) {
6392 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6393 			func_id);
6394 		return -EINVAL;
6395 	}
6396 
6397 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6398 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6399 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6400 		return -EINVAL;
6401 	}
6402 
6403 	if (fn->allowed && !fn->allowed(env->prog)) {
6404 		verbose(env, "helper call is not allowed in probe\n");
6405 		return -EINVAL;
6406 	}
6407 
6408 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6409 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6410 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6411 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6412 			func_id_name(func_id), func_id);
6413 		return -EINVAL;
6414 	}
6415 
6416 	memset(&meta, 0, sizeof(meta));
6417 	meta.pkt_access = fn->pkt_access;
6418 
6419 	err = check_func_proto(fn, func_id);
6420 	if (err) {
6421 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6422 			func_id_name(func_id), func_id);
6423 		return err;
6424 	}
6425 
6426 	meta.func_id = func_id;
6427 	/* check args */
6428 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6429 		err = check_func_arg(env, i, &meta, fn);
6430 		if (err)
6431 			return err;
6432 	}
6433 
6434 	err = record_func_map(env, &meta, func_id, insn_idx);
6435 	if (err)
6436 		return err;
6437 
6438 	err = record_func_key(env, &meta, func_id, insn_idx);
6439 	if (err)
6440 		return err;
6441 
6442 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6443 	 * is inferred from register state.
6444 	 */
6445 	for (i = 0; i < meta.access_size; i++) {
6446 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6447 				       BPF_WRITE, -1, false);
6448 		if (err)
6449 			return err;
6450 	}
6451 
6452 	if (func_id == BPF_FUNC_tail_call) {
6453 		err = check_reference_leak(env);
6454 		if (err) {
6455 			verbose(env, "tail_call would lead to reference leak\n");
6456 			return err;
6457 		}
6458 	} else if (is_release_function(func_id)) {
6459 		err = release_reference(env, meta.ref_obj_id);
6460 		if (err) {
6461 			verbose(env, "func %s#%d reference has not been acquired before\n",
6462 				func_id_name(func_id), func_id);
6463 			return err;
6464 		}
6465 	}
6466 
6467 	regs = cur_regs(env);
6468 
6469 	/* check that flags argument in get_local_storage(map, flags) is 0,
6470 	 * this is required because get_local_storage() can't return an error.
6471 	 */
6472 	if (func_id == BPF_FUNC_get_local_storage &&
6473 	    !register_is_null(&regs[BPF_REG_2])) {
6474 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6475 		return -EINVAL;
6476 	}
6477 
6478 	if (func_id == BPF_FUNC_for_each_map_elem) {
6479 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6480 					set_map_elem_callback_state);
6481 		if (err < 0)
6482 			return -EINVAL;
6483 	}
6484 
6485 	if (func_id == BPF_FUNC_timer_set_callback) {
6486 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6487 					set_timer_callback_state);
6488 		if (err < 0)
6489 			return -EINVAL;
6490 	}
6491 
6492 	if (func_id == BPF_FUNC_snprintf) {
6493 		err = check_bpf_snprintf_call(env, regs);
6494 		if (err < 0)
6495 			return err;
6496 	}
6497 
6498 	/* reset caller saved regs */
6499 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6500 		mark_reg_not_init(env, regs, caller_saved[i]);
6501 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6502 	}
6503 
6504 	/* helper call returns 64-bit value. */
6505 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6506 
6507 	/* update return register (already marked as written above) */
6508 	if (fn->ret_type == RET_INTEGER) {
6509 		/* sets type to SCALAR_VALUE */
6510 		mark_reg_unknown(env, regs, BPF_REG_0);
6511 	} else if (fn->ret_type == RET_VOID) {
6512 		regs[BPF_REG_0].type = NOT_INIT;
6513 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6514 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6515 		/* There is no offset yet applied, variable or fixed */
6516 		mark_reg_known_zero(env, regs, BPF_REG_0);
6517 		/* remember map_ptr, so that check_map_access()
6518 		 * can check 'value_size' boundary of memory access
6519 		 * to map element returned from bpf_map_lookup_elem()
6520 		 */
6521 		if (meta.map_ptr == NULL) {
6522 			verbose(env,
6523 				"kernel subsystem misconfigured verifier\n");
6524 			return -EINVAL;
6525 		}
6526 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6527 		regs[BPF_REG_0].map_uid = meta.map_uid;
6528 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6529 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6530 			if (map_value_has_spin_lock(meta.map_ptr))
6531 				regs[BPF_REG_0].id = ++env->id_gen;
6532 		} else {
6533 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6534 		}
6535 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6536 		mark_reg_known_zero(env, regs, BPF_REG_0);
6537 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6538 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6539 		mark_reg_known_zero(env, regs, BPF_REG_0);
6540 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6541 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6542 		mark_reg_known_zero(env, regs, BPF_REG_0);
6543 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6544 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6545 		mark_reg_known_zero(env, regs, BPF_REG_0);
6546 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6547 		regs[BPF_REG_0].mem_size = meta.mem_size;
6548 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6549 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6550 		const struct btf_type *t;
6551 
6552 		mark_reg_known_zero(env, regs, BPF_REG_0);
6553 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6554 		if (!btf_type_is_struct(t)) {
6555 			u32 tsize;
6556 			const struct btf_type *ret;
6557 			const char *tname;
6558 
6559 			/* resolve the type size of ksym. */
6560 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6561 			if (IS_ERR(ret)) {
6562 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6563 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6564 					tname, PTR_ERR(ret));
6565 				return -EINVAL;
6566 			}
6567 			regs[BPF_REG_0].type =
6568 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6569 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6570 			regs[BPF_REG_0].mem_size = tsize;
6571 		} else {
6572 			regs[BPF_REG_0].type =
6573 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6574 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6575 			regs[BPF_REG_0].btf = meta.ret_btf;
6576 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6577 		}
6578 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6579 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
6580 		int ret_btf_id;
6581 
6582 		mark_reg_known_zero(env, regs, BPF_REG_0);
6583 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6584 						     PTR_TO_BTF_ID :
6585 						     PTR_TO_BTF_ID_OR_NULL;
6586 		ret_btf_id = *fn->ret_btf_id;
6587 		if (ret_btf_id == 0) {
6588 			verbose(env, "invalid return type %d of func %s#%d\n",
6589 				fn->ret_type, func_id_name(func_id), func_id);
6590 			return -EINVAL;
6591 		}
6592 		/* current BPF helper definitions are only coming from
6593 		 * built-in code with type IDs from  vmlinux BTF
6594 		 */
6595 		regs[BPF_REG_0].btf = btf_vmlinux;
6596 		regs[BPF_REG_0].btf_id = ret_btf_id;
6597 	} else {
6598 		verbose(env, "unknown return type %d of func %s#%d\n",
6599 			fn->ret_type, func_id_name(func_id), func_id);
6600 		return -EINVAL;
6601 	}
6602 
6603 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
6604 		regs[BPF_REG_0].id = ++env->id_gen;
6605 
6606 	if (is_ptr_cast_function(func_id)) {
6607 		/* For release_reference() */
6608 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6609 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6610 		int id = acquire_reference_state(env, insn_idx);
6611 
6612 		if (id < 0)
6613 			return id;
6614 		/* For mark_ptr_or_null_reg() */
6615 		regs[BPF_REG_0].id = id;
6616 		/* For release_reference() */
6617 		regs[BPF_REG_0].ref_obj_id = id;
6618 	}
6619 
6620 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6621 
6622 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6623 	if (err)
6624 		return err;
6625 
6626 	if ((func_id == BPF_FUNC_get_stack ||
6627 	     func_id == BPF_FUNC_get_task_stack) &&
6628 	    !env->prog->has_callchain_buf) {
6629 		const char *err_str;
6630 
6631 #ifdef CONFIG_PERF_EVENTS
6632 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6633 		err_str = "cannot get callchain buffer for func %s#%d\n";
6634 #else
6635 		err = -ENOTSUPP;
6636 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6637 #endif
6638 		if (err) {
6639 			verbose(env, err_str, func_id_name(func_id), func_id);
6640 			return err;
6641 		}
6642 
6643 		env->prog->has_callchain_buf = true;
6644 	}
6645 
6646 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6647 		env->prog->call_get_stack = true;
6648 
6649 	if (func_id == BPF_FUNC_get_func_ip) {
6650 		if (check_get_func_ip(env))
6651 			return -ENOTSUPP;
6652 		env->prog->call_get_func_ip = true;
6653 	}
6654 
6655 	if (changes_data)
6656 		clear_all_pkt_pointers(env);
6657 	return 0;
6658 }
6659 
6660 /* mark_btf_func_reg_size() is used when the reg size is determined by
6661  * the BTF func_proto's return value size and argument.
6662  */
6663 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6664 				   size_t reg_size)
6665 {
6666 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6667 
6668 	if (regno == BPF_REG_0) {
6669 		/* Function return value */
6670 		reg->live |= REG_LIVE_WRITTEN;
6671 		reg->subreg_def = reg_size == sizeof(u64) ?
6672 			DEF_NOT_SUBREG : env->insn_idx + 1;
6673 	} else {
6674 		/* Function argument */
6675 		if (reg_size == sizeof(u64)) {
6676 			mark_insn_zext(env, reg);
6677 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6678 		} else {
6679 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6680 		}
6681 	}
6682 }
6683 
6684 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6685 {
6686 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6687 	struct bpf_reg_state *regs = cur_regs(env);
6688 	const char *func_name, *ptr_type_name;
6689 	u32 i, nargs, func_id, ptr_type_id;
6690 	struct module *btf_mod = NULL;
6691 	const struct btf_param *args;
6692 	struct btf *desc_btf;
6693 	int err;
6694 
6695 	/* skip for now, but return error when we find this in fixup_kfunc_call */
6696 	if (!insn->imm)
6697 		return 0;
6698 
6699 	desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod);
6700 	if (IS_ERR(desc_btf))
6701 		return PTR_ERR(desc_btf);
6702 
6703 	func_id = insn->imm;
6704 	func = btf_type_by_id(desc_btf, func_id);
6705 	func_name = btf_name_by_offset(desc_btf, func->name_off);
6706 	func_proto = btf_type_by_id(desc_btf, func->type);
6707 
6708 	if (!env->ops->check_kfunc_call ||
6709 	    !env->ops->check_kfunc_call(func_id, btf_mod)) {
6710 		verbose(env, "calling kernel function %s is not allowed\n",
6711 			func_name);
6712 		return -EACCES;
6713 	}
6714 
6715 	/* Check the arguments */
6716 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
6717 	if (err)
6718 		return err;
6719 
6720 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6721 		mark_reg_not_init(env, regs, caller_saved[i]);
6722 
6723 	/* Check return type */
6724 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
6725 	if (btf_type_is_scalar(t)) {
6726 		mark_reg_unknown(env, regs, BPF_REG_0);
6727 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6728 	} else if (btf_type_is_ptr(t)) {
6729 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
6730 						   &ptr_type_id);
6731 		if (!btf_type_is_struct(ptr_type)) {
6732 			ptr_type_name = btf_name_by_offset(desc_btf,
6733 							   ptr_type->name_off);
6734 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6735 				func_name, btf_type_str(ptr_type),
6736 				ptr_type_name);
6737 			return -EINVAL;
6738 		}
6739 		mark_reg_known_zero(env, regs, BPF_REG_0);
6740 		regs[BPF_REG_0].btf = desc_btf;
6741 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6742 		regs[BPF_REG_0].btf_id = ptr_type_id;
6743 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6744 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6745 
6746 	nargs = btf_type_vlen(func_proto);
6747 	args = (const struct btf_param *)(func_proto + 1);
6748 	for (i = 0; i < nargs; i++) {
6749 		u32 regno = i + 1;
6750 
6751 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
6752 		if (btf_type_is_ptr(t))
6753 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6754 		else
6755 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6756 			mark_btf_func_reg_size(env, regno, t->size);
6757 	}
6758 
6759 	return 0;
6760 }
6761 
6762 static bool signed_add_overflows(s64 a, s64 b)
6763 {
6764 	/* Do the add in u64, where overflow is well-defined */
6765 	s64 res = (s64)((u64)a + (u64)b);
6766 
6767 	if (b < 0)
6768 		return res > a;
6769 	return res < a;
6770 }
6771 
6772 static bool signed_add32_overflows(s32 a, s32 b)
6773 {
6774 	/* Do the add in u32, where overflow is well-defined */
6775 	s32 res = (s32)((u32)a + (u32)b);
6776 
6777 	if (b < 0)
6778 		return res > a;
6779 	return res < a;
6780 }
6781 
6782 static bool signed_sub_overflows(s64 a, s64 b)
6783 {
6784 	/* Do the sub in u64, where overflow is well-defined */
6785 	s64 res = (s64)((u64)a - (u64)b);
6786 
6787 	if (b < 0)
6788 		return res < a;
6789 	return res > a;
6790 }
6791 
6792 static bool signed_sub32_overflows(s32 a, s32 b)
6793 {
6794 	/* Do the sub in u32, where overflow is well-defined */
6795 	s32 res = (s32)((u32)a - (u32)b);
6796 
6797 	if (b < 0)
6798 		return res < a;
6799 	return res > a;
6800 }
6801 
6802 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6803 				  const struct bpf_reg_state *reg,
6804 				  enum bpf_reg_type type)
6805 {
6806 	bool known = tnum_is_const(reg->var_off);
6807 	s64 val = reg->var_off.value;
6808 	s64 smin = reg->smin_value;
6809 
6810 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6811 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6812 			reg_type_str[type], val);
6813 		return false;
6814 	}
6815 
6816 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6817 		verbose(env, "%s pointer offset %d is not allowed\n",
6818 			reg_type_str[type], reg->off);
6819 		return false;
6820 	}
6821 
6822 	if (smin == S64_MIN) {
6823 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6824 			reg_type_str[type]);
6825 		return false;
6826 	}
6827 
6828 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6829 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6830 			smin, reg_type_str[type]);
6831 		return false;
6832 	}
6833 
6834 	return true;
6835 }
6836 
6837 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6838 {
6839 	return &env->insn_aux_data[env->insn_idx];
6840 }
6841 
6842 enum {
6843 	REASON_BOUNDS	= -1,
6844 	REASON_TYPE	= -2,
6845 	REASON_PATHS	= -3,
6846 	REASON_LIMIT	= -4,
6847 	REASON_STACK	= -5,
6848 };
6849 
6850 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6851 			      u32 *alu_limit, bool mask_to_left)
6852 {
6853 	u32 max = 0, ptr_limit = 0;
6854 
6855 	switch (ptr_reg->type) {
6856 	case PTR_TO_STACK:
6857 		/* Offset 0 is out-of-bounds, but acceptable start for the
6858 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6859 		 * offset where we would need to deal with min/max bounds is
6860 		 * currently prohibited for unprivileged.
6861 		 */
6862 		max = MAX_BPF_STACK + mask_to_left;
6863 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6864 		break;
6865 	case PTR_TO_MAP_VALUE:
6866 		max = ptr_reg->map_ptr->value_size;
6867 		ptr_limit = (mask_to_left ?
6868 			     ptr_reg->smin_value :
6869 			     ptr_reg->umax_value) + ptr_reg->off;
6870 		break;
6871 	default:
6872 		return REASON_TYPE;
6873 	}
6874 
6875 	if (ptr_limit >= max)
6876 		return REASON_LIMIT;
6877 	*alu_limit = ptr_limit;
6878 	return 0;
6879 }
6880 
6881 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6882 				    const struct bpf_insn *insn)
6883 {
6884 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6885 }
6886 
6887 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6888 				       u32 alu_state, u32 alu_limit)
6889 {
6890 	/* If we arrived here from different branches with different
6891 	 * state or limits to sanitize, then this won't work.
6892 	 */
6893 	if (aux->alu_state &&
6894 	    (aux->alu_state != alu_state ||
6895 	     aux->alu_limit != alu_limit))
6896 		return REASON_PATHS;
6897 
6898 	/* Corresponding fixup done in do_misc_fixups(). */
6899 	aux->alu_state = alu_state;
6900 	aux->alu_limit = alu_limit;
6901 	return 0;
6902 }
6903 
6904 static int sanitize_val_alu(struct bpf_verifier_env *env,
6905 			    struct bpf_insn *insn)
6906 {
6907 	struct bpf_insn_aux_data *aux = cur_aux(env);
6908 
6909 	if (can_skip_alu_sanitation(env, insn))
6910 		return 0;
6911 
6912 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6913 }
6914 
6915 static bool sanitize_needed(u8 opcode)
6916 {
6917 	return opcode == BPF_ADD || opcode == BPF_SUB;
6918 }
6919 
6920 struct bpf_sanitize_info {
6921 	struct bpf_insn_aux_data aux;
6922 	bool mask_to_left;
6923 };
6924 
6925 static struct bpf_verifier_state *
6926 sanitize_speculative_path(struct bpf_verifier_env *env,
6927 			  const struct bpf_insn *insn,
6928 			  u32 next_idx, u32 curr_idx)
6929 {
6930 	struct bpf_verifier_state *branch;
6931 	struct bpf_reg_state *regs;
6932 
6933 	branch = push_stack(env, next_idx, curr_idx, true);
6934 	if (branch && insn) {
6935 		regs = branch->frame[branch->curframe]->regs;
6936 		if (BPF_SRC(insn->code) == BPF_K) {
6937 			mark_reg_unknown(env, regs, insn->dst_reg);
6938 		} else if (BPF_SRC(insn->code) == BPF_X) {
6939 			mark_reg_unknown(env, regs, insn->dst_reg);
6940 			mark_reg_unknown(env, regs, insn->src_reg);
6941 		}
6942 	}
6943 	return branch;
6944 }
6945 
6946 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6947 			    struct bpf_insn *insn,
6948 			    const struct bpf_reg_state *ptr_reg,
6949 			    const struct bpf_reg_state *off_reg,
6950 			    struct bpf_reg_state *dst_reg,
6951 			    struct bpf_sanitize_info *info,
6952 			    const bool commit_window)
6953 {
6954 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6955 	struct bpf_verifier_state *vstate = env->cur_state;
6956 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6957 	bool off_is_neg = off_reg->smin_value < 0;
6958 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6959 	u8 opcode = BPF_OP(insn->code);
6960 	u32 alu_state, alu_limit;
6961 	struct bpf_reg_state tmp;
6962 	bool ret;
6963 	int err;
6964 
6965 	if (can_skip_alu_sanitation(env, insn))
6966 		return 0;
6967 
6968 	/* We already marked aux for masking from non-speculative
6969 	 * paths, thus we got here in the first place. We only care
6970 	 * to explore bad access from here.
6971 	 */
6972 	if (vstate->speculative)
6973 		goto do_sim;
6974 
6975 	if (!commit_window) {
6976 		if (!tnum_is_const(off_reg->var_off) &&
6977 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6978 			return REASON_BOUNDS;
6979 
6980 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6981 				     (opcode == BPF_SUB && !off_is_neg);
6982 	}
6983 
6984 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6985 	if (err < 0)
6986 		return err;
6987 
6988 	if (commit_window) {
6989 		/* In commit phase we narrow the masking window based on
6990 		 * the observed pointer move after the simulated operation.
6991 		 */
6992 		alu_state = info->aux.alu_state;
6993 		alu_limit = abs(info->aux.alu_limit - alu_limit);
6994 	} else {
6995 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6996 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6997 		alu_state |= ptr_is_dst_reg ?
6998 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6999 
7000 		/* Limit pruning on unknown scalars to enable deep search for
7001 		 * potential masking differences from other program paths.
7002 		 */
7003 		if (!off_is_imm)
7004 			env->explore_alu_limits = true;
7005 	}
7006 
7007 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7008 	if (err < 0)
7009 		return err;
7010 do_sim:
7011 	/* If we're in commit phase, we're done here given we already
7012 	 * pushed the truncated dst_reg into the speculative verification
7013 	 * stack.
7014 	 *
7015 	 * Also, when register is a known constant, we rewrite register-based
7016 	 * operation to immediate-based, and thus do not need masking (and as
7017 	 * a consequence, do not need to simulate the zero-truncation either).
7018 	 */
7019 	if (commit_window || off_is_imm)
7020 		return 0;
7021 
7022 	/* Simulate and find potential out-of-bounds access under
7023 	 * speculative execution from truncation as a result of
7024 	 * masking when off was not within expected range. If off
7025 	 * sits in dst, then we temporarily need to move ptr there
7026 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7027 	 * for cases where we use K-based arithmetic in one direction
7028 	 * and truncated reg-based in the other in order to explore
7029 	 * bad access.
7030 	 */
7031 	if (!ptr_is_dst_reg) {
7032 		tmp = *dst_reg;
7033 		*dst_reg = *ptr_reg;
7034 	}
7035 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7036 					env->insn_idx);
7037 	if (!ptr_is_dst_reg && ret)
7038 		*dst_reg = tmp;
7039 	return !ret ? REASON_STACK : 0;
7040 }
7041 
7042 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7043 {
7044 	struct bpf_verifier_state *vstate = env->cur_state;
7045 
7046 	/* If we simulate paths under speculation, we don't update the
7047 	 * insn as 'seen' such that when we verify unreachable paths in
7048 	 * the non-speculative domain, sanitize_dead_code() can still
7049 	 * rewrite/sanitize them.
7050 	 */
7051 	if (!vstate->speculative)
7052 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7053 }
7054 
7055 static int sanitize_err(struct bpf_verifier_env *env,
7056 			const struct bpf_insn *insn, int reason,
7057 			const struct bpf_reg_state *off_reg,
7058 			const struct bpf_reg_state *dst_reg)
7059 {
7060 	static const char *err = "pointer arithmetic with it prohibited for !root";
7061 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7062 	u32 dst = insn->dst_reg, src = insn->src_reg;
7063 
7064 	switch (reason) {
7065 	case REASON_BOUNDS:
7066 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7067 			off_reg == dst_reg ? dst : src, err);
7068 		break;
7069 	case REASON_TYPE:
7070 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7071 			off_reg == dst_reg ? src : dst, err);
7072 		break;
7073 	case REASON_PATHS:
7074 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7075 			dst, op, err);
7076 		break;
7077 	case REASON_LIMIT:
7078 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7079 			dst, op, err);
7080 		break;
7081 	case REASON_STACK:
7082 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7083 			dst, err);
7084 		break;
7085 	default:
7086 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7087 			reason);
7088 		break;
7089 	}
7090 
7091 	return -EACCES;
7092 }
7093 
7094 /* check that stack access falls within stack limits and that 'reg' doesn't
7095  * have a variable offset.
7096  *
7097  * Variable offset is prohibited for unprivileged mode for simplicity since it
7098  * requires corresponding support in Spectre masking for stack ALU.  See also
7099  * retrieve_ptr_limit().
7100  *
7101  *
7102  * 'off' includes 'reg->off'.
7103  */
7104 static int check_stack_access_for_ptr_arithmetic(
7105 				struct bpf_verifier_env *env,
7106 				int regno,
7107 				const struct bpf_reg_state *reg,
7108 				int off)
7109 {
7110 	if (!tnum_is_const(reg->var_off)) {
7111 		char tn_buf[48];
7112 
7113 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7114 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7115 			regno, tn_buf, off);
7116 		return -EACCES;
7117 	}
7118 
7119 	if (off >= 0 || off < -MAX_BPF_STACK) {
7120 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7121 			"prohibited for !root; off=%d\n", regno, off);
7122 		return -EACCES;
7123 	}
7124 
7125 	return 0;
7126 }
7127 
7128 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7129 				 const struct bpf_insn *insn,
7130 				 const struct bpf_reg_state *dst_reg)
7131 {
7132 	u32 dst = insn->dst_reg;
7133 
7134 	/* For unprivileged we require that resulting offset must be in bounds
7135 	 * in order to be able to sanitize access later on.
7136 	 */
7137 	if (env->bypass_spec_v1)
7138 		return 0;
7139 
7140 	switch (dst_reg->type) {
7141 	case PTR_TO_STACK:
7142 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7143 					dst_reg->off + dst_reg->var_off.value))
7144 			return -EACCES;
7145 		break;
7146 	case PTR_TO_MAP_VALUE:
7147 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7148 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7149 				"prohibited for !root\n", dst);
7150 			return -EACCES;
7151 		}
7152 		break;
7153 	default:
7154 		break;
7155 	}
7156 
7157 	return 0;
7158 }
7159 
7160 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7161  * Caller should also handle BPF_MOV case separately.
7162  * If we return -EACCES, caller may want to try again treating pointer as a
7163  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7164  */
7165 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7166 				   struct bpf_insn *insn,
7167 				   const struct bpf_reg_state *ptr_reg,
7168 				   const struct bpf_reg_state *off_reg)
7169 {
7170 	struct bpf_verifier_state *vstate = env->cur_state;
7171 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7172 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7173 	bool known = tnum_is_const(off_reg->var_off);
7174 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7175 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7176 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7177 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7178 	struct bpf_sanitize_info info = {};
7179 	u8 opcode = BPF_OP(insn->code);
7180 	u32 dst = insn->dst_reg;
7181 	int ret;
7182 
7183 	dst_reg = &regs[dst];
7184 
7185 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7186 	    smin_val > smax_val || umin_val > umax_val) {
7187 		/* Taint dst register if offset had invalid bounds derived from
7188 		 * e.g. dead branches.
7189 		 */
7190 		__mark_reg_unknown(env, dst_reg);
7191 		return 0;
7192 	}
7193 
7194 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7195 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7196 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7197 			__mark_reg_unknown(env, dst_reg);
7198 			return 0;
7199 		}
7200 
7201 		verbose(env,
7202 			"R%d 32-bit pointer arithmetic prohibited\n",
7203 			dst);
7204 		return -EACCES;
7205 	}
7206 
7207 	switch (ptr_reg->type) {
7208 	case PTR_TO_MAP_VALUE_OR_NULL:
7209 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7210 			dst, reg_type_str[ptr_reg->type]);
7211 		return -EACCES;
7212 	case CONST_PTR_TO_MAP:
7213 		/* smin_val represents the known value */
7214 		if (known && smin_val == 0 && opcode == BPF_ADD)
7215 			break;
7216 		fallthrough;
7217 	case PTR_TO_PACKET_END:
7218 	case PTR_TO_SOCKET:
7219 	case PTR_TO_SOCKET_OR_NULL:
7220 	case PTR_TO_SOCK_COMMON:
7221 	case PTR_TO_SOCK_COMMON_OR_NULL:
7222 	case PTR_TO_TCP_SOCK:
7223 	case PTR_TO_TCP_SOCK_OR_NULL:
7224 	case PTR_TO_XDP_SOCK:
7225 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7226 			dst, reg_type_str[ptr_reg->type]);
7227 		return -EACCES;
7228 	default:
7229 		break;
7230 	}
7231 
7232 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7233 	 * The id may be overwritten later if we create a new variable offset.
7234 	 */
7235 	dst_reg->type = ptr_reg->type;
7236 	dst_reg->id = ptr_reg->id;
7237 
7238 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7239 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7240 		return -EINVAL;
7241 
7242 	/* pointer types do not carry 32-bit bounds at the moment. */
7243 	__mark_reg32_unbounded(dst_reg);
7244 
7245 	if (sanitize_needed(opcode)) {
7246 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7247 				       &info, false);
7248 		if (ret < 0)
7249 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7250 	}
7251 
7252 	switch (opcode) {
7253 	case BPF_ADD:
7254 		/* We can take a fixed offset as long as it doesn't overflow
7255 		 * the s32 'off' field
7256 		 */
7257 		if (known && (ptr_reg->off + smin_val ==
7258 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7259 			/* pointer += K.  Accumulate it into fixed offset */
7260 			dst_reg->smin_value = smin_ptr;
7261 			dst_reg->smax_value = smax_ptr;
7262 			dst_reg->umin_value = umin_ptr;
7263 			dst_reg->umax_value = umax_ptr;
7264 			dst_reg->var_off = ptr_reg->var_off;
7265 			dst_reg->off = ptr_reg->off + smin_val;
7266 			dst_reg->raw = ptr_reg->raw;
7267 			break;
7268 		}
7269 		/* A new variable offset is created.  Note that off_reg->off
7270 		 * == 0, since it's a scalar.
7271 		 * dst_reg gets the pointer type and since some positive
7272 		 * integer value was added to the pointer, give it a new 'id'
7273 		 * if it's a PTR_TO_PACKET.
7274 		 * this creates a new 'base' pointer, off_reg (variable) gets
7275 		 * added into the variable offset, and we copy the fixed offset
7276 		 * from ptr_reg.
7277 		 */
7278 		if (signed_add_overflows(smin_ptr, smin_val) ||
7279 		    signed_add_overflows(smax_ptr, smax_val)) {
7280 			dst_reg->smin_value = S64_MIN;
7281 			dst_reg->smax_value = S64_MAX;
7282 		} else {
7283 			dst_reg->smin_value = smin_ptr + smin_val;
7284 			dst_reg->smax_value = smax_ptr + smax_val;
7285 		}
7286 		if (umin_ptr + umin_val < umin_ptr ||
7287 		    umax_ptr + umax_val < umax_ptr) {
7288 			dst_reg->umin_value = 0;
7289 			dst_reg->umax_value = U64_MAX;
7290 		} else {
7291 			dst_reg->umin_value = umin_ptr + umin_val;
7292 			dst_reg->umax_value = umax_ptr + umax_val;
7293 		}
7294 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7295 		dst_reg->off = ptr_reg->off;
7296 		dst_reg->raw = ptr_reg->raw;
7297 		if (reg_is_pkt_pointer(ptr_reg)) {
7298 			dst_reg->id = ++env->id_gen;
7299 			/* something was added to pkt_ptr, set range to zero */
7300 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7301 		}
7302 		break;
7303 	case BPF_SUB:
7304 		if (dst_reg == off_reg) {
7305 			/* scalar -= pointer.  Creates an unknown scalar */
7306 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7307 				dst);
7308 			return -EACCES;
7309 		}
7310 		/* We don't allow subtraction from FP, because (according to
7311 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7312 		 * be able to deal with it.
7313 		 */
7314 		if (ptr_reg->type == PTR_TO_STACK) {
7315 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7316 				dst);
7317 			return -EACCES;
7318 		}
7319 		if (known && (ptr_reg->off - smin_val ==
7320 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7321 			/* pointer -= K.  Subtract it from fixed offset */
7322 			dst_reg->smin_value = smin_ptr;
7323 			dst_reg->smax_value = smax_ptr;
7324 			dst_reg->umin_value = umin_ptr;
7325 			dst_reg->umax_value = umax_ptr;
7326 			dst_reg->var_off = ptr_reg->var_off;
7327 			dst_reg->id = ptr_reg->id;
7328 			dst_reg->off = ptr_reg->off - smin_val;
7329 			dst_reg->raw = ptr_reg->raw;
7330 			break;
7331 		}
7332 		/* A new variable offset is created.  If the subtrahend is known
7333 		 * nonnegative, then any reg->range we had before is still good.
7334 		 */
7335 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7336 		    signed_sub_overflows(smax_ptr, smin_val)) {
7337 			/* Overflow possible, we know nothing */
7338 			dst_reg->smin_value = S64_MIN;
7339 			dst_reg->smax_value = S64_MAX;
7340 		} else {
7341 			dst_reg->smin_value = smin_ptr - smax_val;
7342 			dst_reg->smax_value = smax_ptr - smin_val;
7343 		}
7344 		if (umin_ptr < umax_val) {
7345 			/* Overflow possible, we know nothing */
7346 			dst_reg->umin_value = 0;
7347 			dst_reg->umax_value = U64_MAX;
7348 		} else {
7349 			/* Cannot overflow (as long as bounds are consistent) */
7350 			dst_reg->umin_value = umin_ptr - umax_val;
7351 			dst_reg->umax_value = umax_ptr - umin_val;
7352 		}
7353 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7354 		dst_reg->off = ptr_reg->off;
7355 		dst_reg->raw = ptr_reg->raw;
7356 		if (reg_is_pkt_pointer(ptr_reg)) {
7357 			dst_reg->id = ++env->id_gen;
7358 			/* something was added to pkt_ptr, set range to zero */
7359 			if (smin_val < 0)
7360 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7361 		}
7362 		break;
7363 	case BPF_AND:
7364 	case BPF_OR:
7365 	case BPF_XOR:
7366 		/* bitwise ops on pointers are troublesome, prohibit. */
7367 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7368 			dst, bpf_alu_string[opcode >> 4]);
7369 		return -EACCES;
7370 	default:
7371 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7372 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7373 			dst, bpf_alu_string[opcode >> 4]);
7374 		return -EACCES;
7375 	}
7376 
7377 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7378 		return -EINVAL;
7379 
7380 	__update_reg_bounds(dst_reg);
7381 	__reg_deduce_bounds(dst_reg);
7382 	__reg_bound_offset(dst_reg);
7383 
7384 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7385 		return -EACCES;
7386 	if (sanitize_needed(opcode)) {
7387 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7388 				       &info, true);
7389 		if (ret < 0)
7390 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7391 	}
7392 
7393 	return 0;
7394 }
7395 
7396 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7397 				 struct bpf_reg_state *src_reg)
7398 {
7399 	s32 smin_val = src_reg->s32_min_value;
7400 	s32 smax_val = src_reg->s32_max_value;
7401 	u32 umin_val = src_reg->u32_min_value;
7402 	u32 umax_val = src_reg->u32_max_value;
7403 
7404 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7405 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7406 		dst_reg->s32_min_value = S32_MIN;
7407 		dst_reg->s32_max_value = S32_MAX;
7408 	} else {
7409 		dst_reg->s32_min_value += smin_val;
7410 		dst_reg->s32_max_value += smax_val;
7411 	}
7412 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7413 	    dst_reg->u32_max_value + umax_val < umax_val) {
7414 		dst_reg->u32_min_value = 0;
7415 		dst_reg->u32_max_value = U32_MAX;
7416 	} else {
7417 		dst_reg->u32_min_value += umin_val;
7418 		dst_reg->u32_max_value += umax_val;
7419 	}
7420 }
7421 
7422 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7423 			       struct bpf_reg_state *src_reg)
7424 {
7425 	s64 smin_val = src_reg->smin_value;
7426 	s64 smax_val = src_reg->smax_value;
7427 	u64 umin_val = src_reg->umin_value;
7428 	u64 umax_val = src_reg->umax_value;
7429 
7430 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7431 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7432 		dst_reg->smin_value = S64_MIN;
7433 		dst_reg->smax_value = S64_MAX;
7434 	} else {
7435 		dst_reg->smin_value += smin_val;
7436 		dst_reg->smax_value += smax_val;
7437 	}
7438 	if (dst_reg->umin_value + umin_val < umin_val ||
7439 	    dst_reg->umax_value + umax_val < umax_val) {
7440 		dst_reg->umin_value = 0;
7441 		dst_reg->umax_value = U64_MAX;
7442 	} else {
7443 		dst_reg->umin_value += umin_val;
7444 		dst_reg->umax_value += umax_val;
7445 	}
7446 }
7447 
7448 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7449 				 struct bpf_reg_state *src_reg)
7450 {
7451 	s32 smin_val = src_reg->s32_min_value;
7452 	s32 smax_val = src_reg->s32_max_value;
7453 	u32 umin_val = src_reg->u32_min_value;
7454 	u32 umax_val = src_reg->u32_max_value;
7455 
7456 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7457 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7458 		/* Overflow possible, we know nothing */
7459 		dst_reg->s32_min_value = S32_MIN;
7460 		dst_reg->s32_max_value = S32_MAX;
7461 	} else {
7462 		dst_reg->s32_min_value -= smax_val;
7463 		dst_reg->s32_max_value -= smin_val;
7464 	}
7465 	if (dst_reg->u32_min_value < umax_val) {
7466 		/* Overflow possible, we know nothing */
7467 		dst_reg->u32_min_value = 0;
7468 		dst_reg->u32_max_value = U32_MAX;
7469 	} else {
7470 		/* Cannot overflow (as long as bounds are consistent) */
7471 		dst_reg->u32_min_value -= umax_val;
7472 		dst_reg->u32_max_value -= umin_val;
7473 	}
7474 }
7475 
7476 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7477 			       struct bpf_reg_state *src_reg)
7478 {
7479 	s64 smin_val = src_reg->smin_value;
7480 	s64 smax_val = src_reg->smax_value;
7481 	u64 umin_val = src_reg->umin_value;
7482 	u64 umax_val = src_reg->umax_value;
7483 
7484 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7485 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7486 		/* Overflow possible, we know nothing */
7487 		dst_reg->smin_value = S64_MIN;
7488 		dst_reg->smax_value = S64_MAX;
7489 	} else {
7490 		dst_reg->smin_value -= smax_val;
7491 		dst_reg->smax_value -= smin_val;
7492 	}
7493 	if (dst_reg->umin_value < umax_val) {
7494 		/* Overflow possible, we know nothing */
7495 		dst_reg->umin_value = 0;
7496 		dst_reg->umax_value = U64_MAX;
7497 	} else {
7498 		/* Cannot overflow (as long as bounds are consistent) */
7499 		dst_reg->umin_value -= umax_val;
7500 		dst_reg->umax_value -= umin_val;
7501 	}
7502 }
7503 
7504 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7505 				 struct bpf_reg_state *src_reg)
7506 {
7507 	s32 smin_val = src_reg->s32_min_value;
7508 	u32 umin_val = src_reg->u32_min_value;
7509 	u32 umax_val = src_reg->u32_max_value;
7510 
7511 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7512 		/* Ain't nobody got time to multiply that sign */
7513 		__mark_reg32_unbounded(dst_reg);
7514 		return;
7515 	}
7516 	/* Both values are positive, so we can work with unsigned and
7517 	 * copy the result to signed (unless it exceeds S32_MAX).
7518 	 */
7519 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7520 		/* Potential overflow, we know nothing */
7521 		__mark_reg32_unbounded(dst_reg);
7522 		return;
7523 	}
7524 	dst_reg->u32_min_value *= umin_val;
7525 	dst_reg->u32_max_value *= umax_val;
7526 	if (dst_reg->u32_max_value > S32_MAX) {
7527 		/* Overflow possible, we know nothing */
7528 		dst_reg->s32_min_value = S32_MIN;
7529 		dst_reg->s32_max_value = S32_MAX;
7530 	} else {
7531 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7532 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7533 	}
7534 }
7535 
7536 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7537 			       struct bpf_reg_state *src_reg)
7538 {
7539 	s64 smin_val = src_reg->smin_value;
7540 	u64 umin_val = src_reg->umin_value;
7541 	u64 umax_val = src_reg->umax_value;
7542 
7543 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7544 		/* Ain't nobody got time to multiply that sign */
7545 		__mark_reg64_unbounded(dst_reg);
7546 		return;
7547 	}
7548 	/* Both values are positive, so we can work with unsigned and
7549 	 * copy the result to signed (unless it exceeds S64_MAX).
7550 	 */
7551 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7552 		/* Potential overflow, we know nothing */
7553 		__mark_reg64_unbounded(dst_reg);
7554 		return;
7555 	}
7556 	dst_reg->umin_value *= umin_val;
7557 	dst_reg->umax_value *= umax_val;
7558 	if (dst_reg->umax_value > S64_MAX) {
7559 		/* Overflow possible, we know nothing */
7560 		dst_reg->smin_value = S64_MIN;
7561 		dst_reg->smax_value = S64_MAX;
7562 	} else {
7563 		dst_reg->smin_value = dst_reg->umin_value;
7564 		dst_reg->smax_value = dst_reg->umax_value;
7565 	}
7566 }
7567 
7568 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7569 				 struct bpf_reg_state *src_reg)
7570 {
7571 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7572 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7573 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7574 	s32 smin_val = src_reg->s32_min_value;
7575 	u32 umax_val = src_reg->u32_max_value;
7576 
7577 	if (src_known && dst_known) {
7578 		__mark_reg32_known(dst_reg, var32_off.value);
7579 		return;
7580 	}
7581 
7582 	/* We get our minimum from the var_off, since that's inherently
7583 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7584 	 */
7585 	dst_reg->u32_min_value = var32_off.value;
7586 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7587 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7588 		/* Lose signed bounds when ANDing negative numbers,
7589 		 * ain't nobody got time for that.
7590 		 */
7591 		dst_reg->s32_min_value = S32_MIN;
7592 		dst_reg->s32_max_value = S32_MAX;
7593 	} else {
7594 		/* ANDing two positives gives a positive, so safe to
7595 		 * cast result into s64.
7596 		 */
7597 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7598 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7599 	}
7600 }
7601 
7602 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7603 			       struct bpf_reg_state *src_reg)
7604 {
7605 	bool src_known = tnum_is_const(src_reg->var_off);
7606 	bool dst_known = tnum_is_const(dst_reg->var_off);
7607 	s64 smin_val = src_reg->smin_value;
7608 	u64 umax_val = src_reg->umax_value;
7609 
7610 	if (src_known && dst_known) {
7611 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7612 		return;
7613 	}
7614 
7615 	/* We get our minimum from the var_off, since that's inherently
7616 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7617 	 */
7618 	dst_reg->umin_value = dst_reg->var_off.value;
7619 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7620 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7621 		/* Lose signed bounds when ANDing negative numbers,
7622 		 * ain't nobody got time for that.
7623 		 */
7624 		dst_reg->smin_value = S64_MIN;
7625 		dst_reg->smax_value = S64_MAX;
7626 	} else {
7627 		/* ANDing two positives gives a positive, so safe to
7628 		 * cast result into s64.
7629 		 */
7630 		dst_reg->smin_value = dst_reg->umin_value;
7631 		dst_reg->smax_value = dst_reg->umax_value;
7632 	}
7633 	/* We may learn something more from the var_off */
7634 	__update_reg_bounds(dst_reg);
7635 }
7636 
7637 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7638 				struct bpf_reg_state *src_reg)
7639 {
7640 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7641 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7642 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7643 	s32 smin_val = src_reg->s32_min_value;
7644 	u32 umin_val = src_reg->u32_min_value;
7645 
7646 	if (src_known && dst_known) {
7647 		__mark_reg32_known(dst_reg, var32_off.value);
7648 		return;
7649 	}
7650 
7651 	/* We get our maximum from the var_off, and our minimum is the
7652 	 * maximum of the operands' minima
7653 	 */
7654 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7655 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7656 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7657 		/* Lose signed bounds when ORing negative numbers,
7658 		 * ain't nobody got time for that.
7659 		 */
7660 		dst_reg->s32_min_value = S32_MIN;
7661 		dst_reg->s32_max_value = S32_MAX;
7662 	} else {
7663 		/* ORing two positives gives a positive, so safe to
7664 		 * cast result into s64.
7665 		 */
7666 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7667 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7668 	}
7669 }
7670 
7671 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7672 			      struct bpf_reg_state *src_reg)
7673 {
7674 	bool src_known = tnum_is_const(src_reg->var_off);
7675 	bool dst_known = tnum_is_const(dst_reg->var_off);
7676 	s64 smin_val = src_reg->smin_value;
7677 	u64 umin_val = src_reg->umin_value;
7678 
7679 	if (src_known && dst_known) {
7680 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7681 		return;
7682 	}
7683 
7684 	/* We get our maximum from the var_off, and our minimum is the
7685 	 * maximum of the operands' minima
7686 	 */
7687 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7688 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7689 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7690 		/* Lose signed bounds when ORing negative numbers,
7691 		 * ain't nobody got time for that.
7692 		 */
7693 		dst_reg->smin_value = S64_MIN;
7694 		dst_reg->smax_value = S64_MAX;
7695 	} else {
7696 		/* ORing two positives gives a positive, so safe to
7697 		 * cast result into s64.
7698 		 */
7699 		dst_reg->smin_value = dst_reg->umin_value;
7700 		dst_reg->smax_value = dst_reg->umax_value;
7701 	}
7702 	/* We may learn something more from the var_off */
7703 	__update_reg_bounds(dst_reg);
7704 }
7705 
7706 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7707 				 struct bpf_reg_state *src_reg)
7708 {
7709 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7710 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7711 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7712 	s32 smin_val = src_reg->s32_min_value;
7713 
7714 	if (src_known && dst_known) {
7715 		__mark_reg32_known(dst_reg, var32_off.value);
7716 		return;
7717 	}
7718 
7719 	/* We get both minimum and maximum from the var32_off. */
7720 	dst_reg->u32_min_value = var32_off.value;
7721 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7722 
7723 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7724 		/* XORing two positive sign numbers gives a positive,
7725 		 * so safe to cast u32 result into s32.
7726 		 */
7727 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7728 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7729 	} else {
7730 		dst_reg->s32_min_value = S32_MIN;
7731 		dst_reg->s32_max_value = S32_MAX;
7732 	}
7733 }
7734 
7735 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7736 			       struct bpf_reg_state *src_reg)
7737 {
7738 	bool src_known = tnum_is_const(src_reg->var_off);
7739 	bool dst_known = tnum_is_const(dst_reg->var_off);
7740 	s64 smin_val = src_reg->smin_value;
7741 
7742 	if (src_known && dst_known) {
7743 		/* dst_reg->var_off.value has been updated earlier */
7744 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7745 		return;
7746 	}
7747 
7748 	/* We get both minimum and maximum from the var_off. */
7749 	dst_reg->umin_value = dst_reg->var_off.value;
7750 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7751 
7752 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7753 		/* XORing two positive sign numbers gives a positive,
7754 		 * so safe to cast u64 result into s64.
7755 		 */
7756 		dst_reg->smin_value = dst_reg->umin_value;
7757 		dst_reg->smax_value = dst_reg->umax_value;
7758 	} else {
7759 		dst_reg->smin_value = S64_MIN;
7760 		dst_reg->smax_value = S64_MAX;
7761 	}
7762 
7763 	__update_reg_bounds(dst_reg);
7764 }
7765 
7766 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7767 				   u64 umin_val, u64 umax_val)
7768 {
7769 	/* We lose all sign bit information (except what we can pick
7770 	 * up from var_off)
7771 	 */
7772 	dst_reg->s32_min_value = S32_MIN;
7773 	dst_reg->s32_max_value = S32_MAX;
7774 	/* If we might shift our top bit out, then we know nothing */
7775 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7776 		dst_reg->u32_min_value = 0;
7777 		dst_reg->u32_max_value = U32_MAX;
7778 	} else {
7779 		dst_reg->u32_min_value <<= umin_val;
7780 		dst_reg->u32_max_value <<= umax_val;
7781 	}
7782 }
7783 
7784 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7785 				 struct bpf_reg_state *src_reg)
7786 {
7787 	u32 umax_val = src_reg->u32_max_value;
7788 	u32 umin_val = src_reg->u32_min_value;
7789 	/* u32 alu operation will zext upper bits */
7790 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7791 
7792 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7793 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7794 	/* Not required but being careful mark reg64 bounds as unknown so
7795 	 * that we are forced to pick them up from tnum and zext later and
7796 	 * if some path skips this step we are still safe.
7797 	 */
7798 	__mark_reg64_unbounded(dst_reg);
7799 	__update_reg32_bounds(dst_reg);
7800 }
7801 
7802 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7803 				   u64 umin_val, u64 umax_val)
7804 {
7805 	/* Special case <<32 because it is a common compiler pattern to sign
7806 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7807 	 * positive we know this shift will also be positive so we can track
7808 	 * bounds correctly. Otherwise we lose all sign bit information except
7809 	 * what we can pick up from var_off. Perhaps we can generalize this
7810 	 * later to shifts of any length.
7811 	 */
7812 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7813 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7814 	else
7815 		dst_reg->smax_value = S64_MAX;
7816 
7817 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7818 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7819 	else
7820 		dst_reg->smin_value = S64_MIN;
7821 
7822 	/* If we might shift our top bit out, then we know nothing */
7823 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7824 		dst_reg->umin_value = 0;
7825 		dst_reg->umax_value = U64_MAX;
7826 	} else {
7827 		dst_reg->umin_value <<= umin_val;
7828 		dst_reg->umax_value <<= umax_val;
7829 	}
7830 }
7831 
7832 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7833 			       struct bpf_reg_state *src_reg)
7834 {
7835 	u64 umax_val = src_reg->umax_value;
7836 	u64 umin_val = src_reg->umin_value;
7837 
7838 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7839 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7840 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7841 
7842 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7843 	/* We may learn something more from the var_off */
7844 	__update_reg_bounds(dst_reg);
7845 }
7846 
7847 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7848 				 struct bpf_reg_state *src_reg)
7849 {
7850 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7851 	u32 umax_val = src_reg->u32_max_value;
7852 	u32 umin_val = src_reg->u32_min_value;
7853 
7854 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7855 	 * be negative, then either:
7856 	 * 1) src_reg might be zero, so the sign bit of the result is
7857 	 *    unknown, so we lose our signed bounds
7858 	 * 2) it's known negative, thus the unsigned bounds capture the
7859 	 *    signed bounds
7860 	 * 3) the signed bounds cross zero, so they tell us nothing
7861 	 *    about the result
7862 	 * If the value in dst_reg is known nonnegative, then again the
7863 	 * unsigned bounds capture the signed bounds.
7864 	 * Thus, in all cases it suffices to blow away our signed bounds
7865 	 * and rely on inferring new ones from the unsigned bounds and
7866 	 * var_off of the result.
7867 	 */
7868 	dst_reg->s32_min_value = S32_MIN;
7869 	dst_reg->s32_max_value = S32_MAX;
7870 
7871 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7872 	dst_reg->u32_min_value >>= umax_val;
7873 	dst_reg->u32_max_value >>= umin_val;
7874 
7875 	__mark_reg64_unbounded(dst_reg);
7876 	__update_reg32_bounds(dst_reg);
7877 }
7878 
7879 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7880 			       struct bpf_reg_state *src_reg)
7881 {
7882 	u64 umax_val = src_reg->umax_value;
7883 	u64 umin_val = src_reg->umin_value;
7884 
7885 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7886 	 * be negative, then either:
7887 	 * 1) src_reg might be zero, so the sign bit of the result is
7888 	 *    unknown, so we lose our signed bounds
7889 	 * 2) it's known negative, thus the unsigned bounds capture the
7890 	 *    signed bounds
7891 	 * 3) the signed bounds cross zero, so they tell us nothing
7892 	 *    about the result
7893 	 * If the value in dst_reg is known nonnegative, then again the
7894 	 * unsigned bounds capture the signed bounds.
7895 	 * Thus, in all cases it suffices to blow away our signed bounds
7896 	 * and rely on inferring new ones from the unsigned bounds and
7897 	 * var_off of the result.
7898 	 */
7899 	dst_reg->smin_value = S64_MIN;
7900 	dst_reg->smax_value = S64_MAX;
7901 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7902 	dst_reg->umin_value >>= umax_val;
7903 	dst_reg->umax_value >>= umin_val;
7904 
7905 	/* Its not easy to operate on alu32 bounds here because it depends
7906 	 * on bits being shifted in. Take easy way out and mark unbounded
7907 	 * so we can recalculate later from tnum.
7908 	 */
7909 	__mark_reg32_unbounded(dst_reg);
7910 	__update_reg_bounds(dst_reg);
7911 }
7912 
7913 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7914 				  struct bpf_reg_state *src_reg)
7915 {
7916 	u64 umin_val = src_reg->u32_min_value;
7917 
7918 	/* Upon reaching here, src_known is true and
7919 	 * umax_val is equal to umin_val.
7920 	 */
7921 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7922 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7923 
7924 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7925 
7926 	/* blow away the dst_reg umin_value/umax_value and rely on
7927 	 * dst_reg var_off to refine the result.
7928 	 */
7929 	dst_reg->u32_min_value = 0;
7930 	dst_reg->u32_max_value = U32_MAX;
7931 
7932 	__mark_reg64_unbounded(dst_reg);
7933 	__update_reg32_bounds(dst_reg);
7934 }
7935 
7936 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7937 				struct bpf_reg_state *src_reg)
7938 {
7939 	u64 umin_val = src_reg->umin_value;
7940 
7941 	/* Upon reaching here, src_known is true and umax_val is equal
7942 	 * to umin_val.
7943 	 */
7944 	dst_reg->smin_value >>= umin_val;
7945 	dst_reg->smax_value >>= umin_val;
7946 
7947 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7948 
7949 	/* blow away the dst_reg umin_value/umax_value and rely on
7950 	 * dst_reg var_off to refine the result.
7951 	 */
7952 	dst_reg->umin_value = 0;
7953 	dst_reg->umax_value = U64_MAX;
7954 
7955 	/* Its not easy to operate on alu32 bounds here because it depends
7956 	 * on bits being shifted in from upper 32-bits. Take easy way out
7957 	 * and mark unbounded so we can recalculate later from tnum.
7958 	 */
7959 	__mark_reg32_unbounded(dst_reg);
7960 	__update_reg_bounds(dst_reg);
7961 }
7962 
7963 /* WARNING: This function does calculations on 64-bit values, but the actual
7964  * execution may occur on 32-bit values. Therefore, things like bitshifts
7965  * need extra checks in the 32-bit case.
7966  */
7967 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7968 				      struct bpf_insn *insn,
7969 				      struct bpf_reg_state *dst_reg,
7970 				      struct bpf_reg_state src_reg)
7971 {
7972 	struct bpf_reg_state *regs = cur_regs(env);
7973 	u8 opcode = BPF_OP(insn->code);
7974 	bool src_known;
7975 	s64 smin_val, smax_val;
7976 	u64 umin_val, umax_val;
7977 	s32 s32_min_val, s32_max_val;
7978 	u32 u32_min_val, u32_max_val;
7979 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7980 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7981 	int ret;
7982 
7983 	smin_val = src_reg.smin_value;
7984 	smax_val = src_reg.smax_value;
7985 	umin_val = src_reg.umin_value;
7986 	umax_val = src_reg.umax_value;
7987 
7988 	s32_min_val = src_reg.s32_min_value;
7989 	s32_max_val = src_reg.s32_max_value;
7990 	u32_min_val = src_reg.u32_min_value;
7991 	u32_max_val = src_reg.u32_max_value;
7992 
7993 	if (alu32) {
7994 		src_known = tnum_subreg_is_const(src_reg.var_off);
7995 		if ((src_known &&
7996 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7997 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7998 			/* Taint dst register if offset had invalid bounds
7999 			 * derived from e.g. dead branches.
8000 			 */
8001 			__mark_reg_unknown(env, dst_reg);
8002 			return 0;
8003 		}
8004 	} else {
8005 		src_known = tnum_is_const(src_reg.var_off);
8006 		if ((src_known &&
8007 		     (smin_val != smax_val || umin_val != umax_val)) ||
8008 		    smin_val > smax_val || umin_val > umax_val) {
8009 			/* Taint dst register if offset had invalid bounds
8010 			 * derived from e.g. dead branches.
8011 			 */
8012 			__mark_reg_unknown(env, dst_reg);
8013 			return 0;
8014 		}
8015 	}
8016 
8017 	if (!src_known &&
8018 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8019 		__mark_reg_unknown(env, dst_reg);
8020 		return 0;
8021 	}
8022 
8023 	if (sanitize_needed(opcode)) {
8024 		ret = sanitize_val_alu(env, insn);
8025 		if (ret < 0)
8026 			return sanitize_err(env, insn, ret, NULL, NULL);
8027 	}
8028 
8029 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8030 	 * There are two classes of instructions: The first class we track both
8031 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8032 	 * greatest amount of precision when alu operations are mixed with jmp32
8033 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8034 	 * and BPF_OR. This is possible because these ops have fairly easy to
8035 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8036 	 * See alu32 verifier tests for examples. The second class of
8037 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8038 	 * with regards to tracking sign/unsigned bounds because the bits may
8039 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8040 	 * the reg unbounded in the subreg bound space and use the resulting
8041 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8042 	 */
8043 	switch (opcode) {
8044 	case BPF_ADD:
8045 		scalar32_min_max_add(dst_reg, &src_reg);
8046 		scalar_min_max_add(dst_reg, &src_reg);
8047 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8048 		break;
8049 	case BPF_SUB:
8050 		scalar32_min_max_sub(dst_reg, &src_reg);
8051 		scalar_min_max_sub(dst_reg, &src_reg);
8052 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8053 		break;
8054 	case BPF_MUL:
8055 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8056 		scalar32_min_max_mul(dst_reg, &src_reg);
8057 		scalar_min_max_mul(dst_reg, &src_reg);
8058 		break;
8059 	case BPF_AND:
8060 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8061 		scalar32_min_max_and(dst_reg, &src_reg);
8062 		scalar_min_max_and(dst_reg, &src_reg);
8063 		break;
8064 	case BPF_OR:
8065 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8066 		scalar32_min_max_or(dst_reg, &src_reg);
8067 		scalar_min_max_or(dst_reg, &src_reg);
8068 		break;
8069 	case BPF_XOR:
8070 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8071 		scalar32_min_max_xor(dst_reg, &src_reg);
8072 		scalar_min_max_xor(dst_reg, &src_reg);
8073 		break;
8074 	case BPF_LSH:
8075 		if (umax_val >= insn_bitness) {
8076 			/* Shifts greater than 31 or 63 are undefined.
8077 			 * This includes shifts by a negative number.
8078 			 */
8079 			mark_reg_unknown(env, regs, insn->dst_reg);
8080 			break;
8081 		}
8082 		if (alu32)
8083 			scalar32_min_max_lsh(dst_reg, &src_reg);
8084 		else
8085 			scalar_min_max_lsh(dst_reg, &src_reg);
8086 		break;
8087 	case BPF_RSH:
8088 		if (umax_val >= insn_bitness) {
8089 			/* Shifts greater than 31 or 63 are undefined.
8090 			 * This includes shifts by a negative number.
8091 			 */
8092 			mark_reg_unknown(env, regs, insn->dst_reg);
8093 			break;
8094 		}
8095 		if (alu32)
8096 			scalar32_min_max_rsh(dst_reg, &src_reg);
8097 		else
8098 			scalar_min_max_rsh(dst_reg, &src_reg);
8099 		break;
8100 	case BPF_ARSH:
8101 		if (umax_val >= insn_bitness) {
8102 			/* Shifts greater than 31 or 63 are undefined.
8103 			 * This includes shifts by a negative number.
8104 			 */
8105 			mark_reg_unknown(env, regs, insn->dst_reg);
8106 			break;
8107 		}
8108 		if (alu32)
8109 			scalar32_min_max_arsh(dst_reg, &src_reg);
8110 		else
8111 			scalar_min_max_arsh(dst_reg, &src_reg);
8112 		break;
8113 	default:
8114 		mark_reg_unknown(env, regs, insn->dst_reg);
8115 		break;
8116 	}
8117 
8118 	/* ALU32 ops are zero extended into 64bit register */
8119 	if (alu32)
8120 		zext_32_to_64(dst_reg);
8121 
8122 	__update_reg_bounds(dst_reg);
8123 	__reg_deduce_bounds(dst_reg);
8124 	__reg_bound_offset(dst_reg);
8125 	return 0;
8126 }
8127 
8128 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8129  * and var_off.
8130  */
8131 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8132 				   struct bpf_insn *insn)
8133 {
8134 	struct bpf_verifier_state *vstate = env->cur_state;
8135 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8136 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8137 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8138 	u8 opcode = BPF_OP(insn->code);
8139 	int err;
8140 
8141 	dst_reg = &regs[insn->dst_reg];
8142 	src_reg = NULL;
8143 	if (dst_reg->type != SCALAR_VALUE)
8144 		ptr_reg = dst_reg;
8145 	else
8146 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8147 		 * incorrectly propagated into other registers by find_equal_scalars()
8148 		 */
8149 		dst_reg->id = 0;
8150 	if (BPF_SRC(insn->code) == BPF_X) {
8151 		src_reg = &regs[insn->src_reg];
8152 		if (src_reg->type != SCALAR_VALUE) {
8153 			if (dst_reg->type != SCALAR_VALUE) {
8154 				/* Combining two pointers by any ALU op yields
8155 				 * an arbitrary scalar. Disallow all math except
8156 				 * pointer subtraction
8157 				 */
8158 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8159 					mark_reg_unknown(env, regs, insn->dst_reg);
8160 					return 0;
8161 				}
8162 				verbose(env, "R%d pointer %s pointer prohibited\n",
8163 					insn->dst_reg,
8164 					bpf_alu_string[opcode >> 4]);
8165 				return -EACCES;
8166 			} else {
8167 				/* scalar += pointer
8168 				 * This is legal, but we have to reverse our
8169 				 * src/dest handling in computing the range
8170 				 */
8171 				err = mark_chain_precision(env, insn->dst_reg);
8172 				if (err)
8173 					return err;
8174 				return adjust_ptr_min_max_vals(env, insn,
8175 							       src_reg, dst_reg);
8176 			}
8177 		} else if (ptr_reg) {
8178 			/* pointer += scalar */
8179 			err = mark_chain_precision(env, insn->src_reg);
8180 			if (err)
8181 				return err;
8182 			return adjust_ptr_min_max_vals(env, insn,
8183 						       dst_reg, src_reg);
8184 		}
8185 	} else {
8186 		/* Pretend the src is a reg with a known value, since we only
8187 		 * need to be able to read from this state.
8188 		 */
8189 		off_reg.type = SCALAR_VALUE;
8190 		__mark_reg_known(&off_reg, insn->imm);
8191 		src_reg = &off_reg;
8192 		if (ptr_reg) /* pointer += K */
8193 			return adjust_ptr_min_max_vals(env, insn,
8194 						       ptr_reg, src_reg);
8195 	}
8196 
8197 	/* Got here implies adding two SCALAR_VALUEs */
8198 	if (WARN_ON_ONCE(ptr_reg)) {
8199 		print_verifier_state(env, state);
8200 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8201 		return -EINVAL;
8202 	}
8203 	if (WARN_ON(!src_reg)) {
8204 		print_verifier_state(env, state);
8205 		verbose(env, "verifier internal error: no src_reg\n");
8206 		return -EINVAL;
8207 	}
8208 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8209 }
8210 
8211 /* check validity of 32-bit and 64-bit arithmetic operations */
8212 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8213 {
8214 	struct bpf_reg_state *regs = cur_regs(env);
8215 	u8 opcode = BPF_OP(insn->code);
8216 	int err;
8217 
8218 	if (opcode == BPF_END || opcode == BPF_NEG) {
8219 		if (opcode == BPF_NEG) {
8220 			if (BPF_SRC(insn->code) != 0 ||
8221 			    insn->src_reg != BPF_REG_0 ||
8222 			    insn->off != 0 || insn->imm != 0) {
8223 				verbose(env, "BPF_NEG uses reserved fields\n");
8224 				return -EINVAL;
8225 			}
8226 		} else {
8227 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8228 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8229 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8230 				verbose(env, "BPF_END uses reserved fields\n");
8231 				return -EINVAL;
8232 			}
8233 		}
8234 
8235 		/* check src operand */
8236 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8237 		if (err)
8238 			return err;
8239 
8240 		if (is_pointer_value(env, insn->dst_reg)) {
8241 			verbose(env, "R%d pointer arithmetic prohibited\n",
8242 				insn->dst_reg);
8243 			return -EACCES;
8244 		}
8245 
8246 		/* check dest operand */
8247 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8248 		if (err)
8249 			return err;
8250 
8251 	} else if (opcode == BPF_MOV) {
8252 
8253 		if (BPF_SRC(insn->code) == BPF_X) {
8254 			if (insn->imm != 0 || insn->off != 0) {
8255 				verbose(env, "BPF_MOV uses reserved fields\n");
8256 				return -EINVAL;
8257 			}
8258 
8259 			/* check src operand */
8260 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8261 			if (err)
8262 				return err;
8263 		} else {
8264 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8265 				verbose(env, "BPF_MOV uses reserved fields\n");
8266 				return -EINVAL;
8267 			}
8268 		}
8269 
8270 		/* check dest operand, mark as required later */
8271 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8272 		if (err)
8273 			return err;
8274 
8275 		if (BPF_SRC(insn->code) == BPF_X) {
8276 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8277 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8278 
8279 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8280 				/* case: R1 = R2
8281 				 * copy register state to dest reg
8282 				 */
8283 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8284 					/* Assign src and dst registers the same ID
8285 					 * that will be used by find_equal_scalars()
8286 					 * to propagate min/max range.
8287 					 */
8288 					src_reg->id = ++env->id_gen;
8289 				*dst_reg = *src_reg;
8290 				dst_reg->live |= REG_LIVE_WRITTEN;
8291 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8292 			} else {
8293 				/* R1 = (u32) R2 */
8294 				if (is_pointer_value(env, insn->src_reg)) {
8295 					verbose(env,
8296 						"R%d partial copy of pointer\n",
8297 						insn->src_reg);
8298 					return -EACCES;
8299 				} else if (src_reg->type == SCALAR_VALUE) {
8300 					*dst_reg = *src_reg;
8301 					/* Make sure ID is cleared otherwise
8302 					 * dst_reg min/max could be incorrectly
8303 					 * propagated into src_reg by find_equal_scalars()
8304 					 */
8305 					dst_reg->id = 0;
8306 					dst_reg->live |= REG_LIVE_WRITTEN;
8307 					dst_reg->subreg_def = env->insn_idx + 1;
8308 				} else {
8309 					mark_reg_unknown(env, regs,
8310 							 insn->dst_reg);
8311 				}
8312 				zext_32_to_64(dst_reg);
8313 			}
8314 		} else {
8315 			/* case: R = imm
8316 			 * remember the value we stored into this reg
8317 			 */
8318 			/* clear any state __mark_reg_known doesn't set */
8319 			mark_reg_unknown(env, regs, insn->dst_reg);
8320 			regs[insn->dst_reg].type = SCALAR_VALUE;
8321 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8322 				__mark_reg_known(regs + insn->dst_reg,
8323 						 insn->imm);
8324 			} else {
8325 				__mark_reg_known(regs + insn->dst_reg,
8326 						 (u32)insn->imm);
8327 			}
8328 		}
8329 
8330 	} else if (opcode > BPF_END) {
8331 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8332 		return -EINVAL;
8333 
8334 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8335 
8336 		if (BPF_SRC(insn->code) == BPF_X) {
8337 			if (insn->imm != 0 || insn->off != 0) {
8338 				verbose(env, "BPF_ALU uses reserved fields\n");
8339 				return -EINVAL;
8340 			}
8341 			/* check src1 operand */
8342 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8343 			if (err)
8344 				return err;
8345 		} else {
8346 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8347 				verbose(env, "BPF_ALU uses reserved fields\n");
8348 				return -EINVAL;
8349 			}
8350 		}
8351 
8352 		/* check src2 operand */
8353 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8354 		if (err)
8355 			return err;
8356 
8357 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8358 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8359 			verbose(env, "div by zero\n");
8360 			return -EINVAL;
8361 		}
8362 
8363 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8364 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8365 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8366 
8367 			if (insn->imm < 0 || insn->imm >= size) {
8368 				verbose(env, "invalid shift %d\n", insn->imm);
8369 				return -EINVAL;
8370 			}
8371 		}
8372 
8373 		/* check dest operand */
8374 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8375 		if (err)
8376 			return err;
8377 
8378 		return adjust_reg_min_max_vals(env, insn);
8379 	}
8380 
8381 	return 0;
8382 }
8383 
8384 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8385 				     struct bpf_reg_state *dst_reg,
8386 				     enum bpf_reg_type type, int new_range)
8387 {
8388 	struct bpf_reg_state *reg;
8389 	int i;
8390 
8391 	for (i = 0; i < MAX_BPF_REG; i++) {
8392 		reg = &state->regs[i];
8393 		if (reg->type == type && reg->id == dst_reg->id)
8394 			/* keep the maximum range already checked */
8395 			reg->range = max(reg->range, new_range);
8396 	}
8397 
8398 	bpf_for_each_spilled_reg(i, state, reg) {
8399 		if (!reg)
8400 			continue;
8401 		if (reg->type == type && reg->id == dst_reg->id)
8402 			reg->range = max(reg->range, new_range);
8403 	}
8404 }
8405 
8406 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8407 				   struct bpf_reg_state *dst_reg,
8408 				   enum bpf_reg_type type,
8409 				   bool range_right_open)
8410 {
8411 	int new_range, i;
8412 
8413 	if (dst_reg->off < 0 ||
8414 	    (dst_reg->off == 0 && range_right_open))
8415 		/* This doesn't give us any range */
8416 		return;
8417 
8418 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8419 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8420 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8421 		 * than pkt_end, but that's because it's also less than pkt.
8422 		 */
8423 		return;
8424 
8425 	new_range = dst_reg->off;
8426 	if (range_right_open)
8427 		new_range--;
8428 
8429 	/* Examples for register markings:
8430 	 *
8431 	 * pkt_data in dst register:
8432 	 *
8433 	 *   r2 = r3;
8434 	 *   r2 += 8;
8435 	 *   if (r2 > pkt_end) goto <handle exception>
8436 	 *   <access okay>
8437 	 *
8438 	 *   r2 = r3;
8439 	 *   r2 += 8;
8440 	 *   if (r2 < pkt_end) goto <access okay>
8441 	 *   <handle exception>
8442 	 *
8443 	 *   Where:
8444 	 *     r2 == dst_reg, pkt_end == src_reg
8445 	 *     r2=pkt(id=n,off=8,r=0)
8446 	 *     r3=pkt(id=n,off=0,r=0)
8447 	 *
8448 	 * pkt_data in src register:
8449 	 *
8450 	 *   r2 = r3;
8451 	 *   r2 += 8;
8452 	 *   if (pkt_end >= r2) goto <access okay>
8453 	 *   <handle exception>
8454 	 *
8455 	 *   r2 = r3;
8456 	 *   r2 += 8;
8457 	 *   if (pkt_end <= r2) goto <handle exception>
8458 	 *   <access okay>
8459 	 *
8460 	 *   Where:
8461 	 *     pkt_end == dst_reg, r2 == src_reg
8462 	 *     r2=pkt(id=n,off=8,r=0)
8463 	 *     r3=pkt(id=n,off=0,r=0)
8464 	 *
8465 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8466 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8467 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8468 	 * the check.
8469 	 */
8470 
8471 	/* If our ids match, then we must have the same max_value.  And we
8472 	 * don't care about the other reg's fixed offset, since if it's too big
8473 	 * the range won't allow anything.
8474 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8475 	 */
8476 	for (i = 0; i <= vstate->curframe; i++)
8477 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8478 					 new_range);
8479 }
8480 
8481 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8482 {
8483 	struct tnum subreg = tnum_subreg(reg->var_off);
8484 	s32 sval = (s32)val;
8485 
8486 	switch (opcode) {
8487 	case BPF_JEQ:
8488 		if (tnum_is_const(subreg))
8489 			return !!tnum_equals_const(subreg, val);
8490 		break;
8491 	case BPF_JNE:
8492 		if (tnum_is_const(subreg))
8493 			return !tnum_equals_const(subreg, val);
8494 		break;
8495 	case BPF_JSET:
8496 		if ((~subreg.mask & subreg.value) & val)
8497 			return 1;
8498 		if (!((subreg.mask | subreg.value) & val))
8499 			return 0;
8500 		break;
8501 	case BPF_JGT:
8502 		if (reg->u32_min_value > val)
8503 			return 1;
8504 		else if (reg->u32_max_value <= val)
8505 			return 0;
8506 		break;
8507 	case BPF_JSGT:
8508 		if (reg->s32_min_value > sval)
8509 			return 1;
8510 		else if (reg->s32_max_value <= sval)
8511 			return 0;
8512 		break;
8513 	case BPF_JLT:
8514 		if (reg->u32_max_value < val)
8515 			return 1;
8516 		else if (reg->u32_min_value >= val)
8517 			return 0;
8518 		break;
8519 	case BPF_JSLT:
8520 		if (reg->s32_max_value < sval)
8521 			return 1;
8522 		else if (reg->s32_min_value >= sval)
8523 			return 0;
8524 		break;
8525 	case BPF_JGE:
8526 		if (reg->u32_min_value >= val)
8527 			return 1;
8528 		else if (reg->u32_max_value < val)
8529 			return 0;
8530 		break;
8531 	case BPF_JSGE:
8532 		if (reg->s32_min_value >= sval)
8533 			return 1;
8534 		else if (reg->s32_max_value < sval)
8535 			return 0;
8536 		break;
8537 	case BPF_JLE:
8538 		if (reg->u32_max_value <= val)
8539 			return 1;
8540 		else if (reg->u32_min_value > val)
8541 			return 0;
8542 		break;
8543 	case BPF_JSLE:
8544 		if (reg->s32_max_value <= sval)
8545 			return 1;
8546 		else if (reg->s32_min_value > sval)
8547 			return 0;
8548 		break;
8549 	}
8550 
8551 	return -1;
8552 }
8553 
8554 
8555 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8556 {
8557 	s64 sval = (s64)val;
8558 
8559 	switch (opcode) {
8560 	case BPF_JEQ:
8561 		if (tnum_is_const(reg->var_off))
8562 			return !!tnum_equals_const(reg->var_off, val);
8563 		break;
8564 	case BPF_JNE:
8565 		if (tnum_is_const(reg->var_off))
8566 			return !tnum_equals_const(reg->var_off, val);
8567 		break;
8568 	case BPF_JSET:
8569 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8570 			return 1;
8571 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8572 			return 0;
8573 		break;
8574 	case BPF_JGT:
8575 		if (reg->umin_value > val)
8576 			return 1;
8577 		else if (reg->umax_value <= val)
8578 			return 0;
8579 		break;
8580 	case BPF_JSGT:
8581 		if (reg->smin_value > sval)
8582 			return 1;
8583 		else if (reg->smax_value <= sval)
8584 			return 0;
8585 		break;
8586 	case BPF_JLT:
8587 		if (reg->umax_value < val)
8588 			return 1;
8589 		else if (reg->umin_value >= val)
8590 			return 0;
8591 		break;
8592 	case BPF_JSLT:
8593 		if (reg->smax_value < sval)
8594 			return 1;
8595 		else if (reg->smin_value >= sval)
8596 			return 0;
8597 		break;
8598 	case BPF_JGE:
8599 		if (reg->umin_value >= val)
8600 			return 1;
8601 		else if (reg->umax_value < val)
8602 			return 0;
8603 		break;
8604 	case BPF_JSGE:
8605 		if (reg->smin_value >= sval)
8606 			return 1;
8607 		else if (reg->smax_value < sval)
8608 			return 0;
8609 		break;
8610 	case BPF_JLE:
8611 		if (reg->umax_value <= val)
8612 			return 1;
8613 		else if (reg->umin_value > val)
8614 			return 0;
8615 		break;
8616 	case BPF_JSLE:
8617 		if (reg->smax_value <= sval)
8618 			return 1;
8619 		else if (reg->smin_value > sval)
8620 			return 0;
8621 		break;
8622 	}
8623 
8624 	return -1;
8625 }
8626 
8627 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8628  * and return:
8629  *  1 - branch will be taken and "goto target" will be executed
8630  *  0 - branch will not be taken and fall-through to next insn
8631  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8632  *      range [0,10]
8633  */
8634 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8635 			   bool is_jmp32)
8636 {
8637 	if (__is_pointer_value(false, reg)) {
8638 		if (!reg_type_not_null(reg->type))
8639 			return -1;
8640 
8641 		/* If pointer is valid tests against zero will fail so we can
8642 		 * use this to direct branch taken.
8643 		 */
8644 		if (val != 0)
8645 			return -1;
8646 
8647 		switch (opcode) {
8648 		case BPF_JEQ:
8649 			return 0;
8650 		case BPF_JNE:
8651 			return 1;
8652 		default:
8653 			return -1;
8654 		}
8655 	}
8656 
8657 	if (is_jmp32)
8658 		return is_branch32_taken(reg, val, opcode);
8659 	return is_branch64_taken(reg, val, opcode);
8660 }
8661 
8662 static int flip_opcode(u32 opcode)
8663 {
8664 	/* How can we transform "a <op> b" into "b <op> a"? */
8665 	static const u8 opcode_flip[16] = {
8666 		/* these stay the same */
8667 		[BPF_JEQ  >> 4] = BPF_JEQ,
8668 		[BPF_JNE  >> 4] = BPF_JNE,
8669 		[BPF_JSET >> 4] = BPF_JSET,
8670 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8671 		[BPF_JGE  >> 4] = BPF_JLE,
8672 		[BPF_JGT  >> 4] = BPF_JLT,
8673 		[BPF_JLE  >> 4] = BPF_JGE,
8674 		[BPF_JLT  >> 4] = BPF_JGT,
8675 		[BPF_JSGE >> 4] = BPF_JSLE,
8676 		[BPF_JSGT >> 4] = BPF_JSLT,
8677 		[BPF_JSLE >> 4] = BPF_JSGE,
8678 		[BPF_JSLT >> 4] = BPF_JSGT
8679 	};
8680 	return opcode_flip[opcode >> 4];
8681 }
8682 
8683 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8684 				   struct bpf_reg_state *src_reg,
8685 				   u8 opcode)
8686 {
8687 	struct bpf_reg_state *pkt;
8688 
8689 	if (src_reg->type == PTR_TO_PACKET_END) {
8690 		pkt = dst_reg;
8691 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8692 		pkt = src_reg;
8693 		opcode = flip_opcode(opcode);
8694 	} else {
8695 		return -1;
8696 	}
8697 
8698 	if (pkt->range >= 0)
8699 		return -1;
8700 
8701 	switch (opcode) {
8702 	case BPF_JLE:
8703 		/* pkt <= pkt_end */
8704 		fallthrough;
8705 	case BPF_JGT:
8706 		/* pkt > pkt_end */
8707 		if (pkt->range == BEYOND_PKT_END)
8708 			/* pkt has at last one extra byte beyond pkt_end */
8709 			return opcode == BPF_JGT;
8710 		break;
8711 	case BPF_JLT:
8712 		/* pkt < pkt_end */
8713 		fallthrough;
8714 	case BPF_JGE:
8715 		/* pkt >= pkt_end */
8716 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8717 			return opcode == BPF_JGE;
8718 		break;
8719 	}
8720 	return -1;
8721 }
8722 
8723 /* Adjusts the register min/max values in the case that the dst_reg is the
8724  * variable register that we are working on, and src_reg is a constant or we're
8725  * simply doing a BPF_K check.
8726  * In JEQ/JNE cases we also adjust the var_off values.
8727  */
8728 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8729 			    struct bpf_reg_state *false_reg,
8730 			    u64 val, u32 val32,
8731 			    u8 opcode, bool is_jmp32)
8732 {
8733 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8734 	struct tnum false_64off = false_reg->var_off;
8735 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8736 	struct tnum true_64off = true_reg->var_off;
8737 	s64 sval = (s64)val;
8738 	s32 sval32 = (s32)val32;
8739 
8740 	/* If the dst_reg is a pointer, we can't learn anything about its
8741 	 * variable offset from the compare (unless src_reg were a pointer into
8742 	 * the same object, but we don't bother with that.
8743 	 * Since false_reg and true_reg have the same type by construction, we
8744 	 * only need to check one of them for pointerness.
8745 	 */
8746 	if (__is_pointer_value(false, false_reg))
8747 		return;
8748 
8749 	switch (opcode) {
8750 	case BPF_JEQ:
8751 	case BPF_JNE:
8752 	{
8753 		struct bpf_reg_state *reg =
8754 			opcode == BPF_JEQ ? true_reg : false_reg;
8755 
8756 		/* JEQ/JNE comparison doesn't change the register equivalence.
8757 		 * r1 = r2;
8758 		 * if (r1 == 42) goto label;
8759 		 * ...
8760 		 * label: // here both r1 and r2 are known to be 42.
8761 		 *
8762 		 * Hence when marking register as known preserve it's ID.
8763 		 */
8764 		if (is_jmp32)
8765 			__mark_reg32_known(reg, val32);
8766 		else
8767 			___mark_reg_known(reg, val);
8768 		break;
8769 	}
8770 	case BPF_JSET:
8771 		if (is_jmp32) {
8772 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8773 			if (is_power_of_2(val32))
8774 				true_32off = tnum_or(true_32off,
8775 						     tnum_const(val32));
8776 		} else {
8777 			false_64off = tnum_and(false_64off, tnum_const(~val));
8778 			if (is_power_of_2(val))
8779 				true_64off = tnum_or(true_64off,
8780 						     tnum_const(val));
8781 		}
8782 		break;
8783 	case BPF_JGE:
8784 	case BPF_JGT:
8785 	{
8786 		if (is_jmp32) {
8787 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8788 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8789 
8790 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8791 						       false_umax);
8792 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8793 						      true_umin);
8794 		} else {
8795 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8796 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8797 
8798 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8799 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8800 		}
8801 		break;
8802 	}
8803 	case BPF_JSGE:
8804 	case BPF_JSGT:
8805 	{
8806 		if (is_jmp32) {
8807 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8808 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8809 
8810 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8811 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8812 		} else {
8813 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8814 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8815 
8816 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8817 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8818 		}
8819 		break;
8820 	}
8821 	case BPF_JLE:
8822 	case BPF_JLT:
8823 	{
8824 		if (is_jmp32) {
8825 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8826 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8827 
8828 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8829 						       false_umin);
8830 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8831 						      true_umax);
8832 		} else {
8833 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8834 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8835 
8836 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8837 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8838 		}
8839 		break;
8840 	}
8841 	case BPF_JSLE:
8842 	case BPF_JSLT:
8843 	{
8844 		if (is_jmp32) {
8845 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8846 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8847 
8848 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8849 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8850 		} else {
8851 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8852 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8853 
8854 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8855 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8856 		}
8857 		break;
8858 	}
8859 	default:
8860 		return;
8861 	}
8862 
8863 	if (is_jmp32) {
8864 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8865 					     tnum_subreg(false_32off));
8866 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8867 					    tnum_subreg(true_32off));
8868 		__reg_combine_32_into_64(false_reg);
8869 		__reg_combine_32_into_64(true_reg);
8870 	} else {
8871 		false_reg->var_off = false_64off;
8872 		true_reg->var_off = true_64off;
8873 		__reg_combine_64_into_32(false_reg);
8874 		__reg_combine_64_into_32(true_reg);
8875 	}
8876 }
8877 
8878 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8879  * the variable reg.
8880  */
8881 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8882 				struct bpf_reg_state *false_reg,
8883 				u64 val, u32 val32,
8884 				u8 opcode, bool is_jmp32)
8885 {
8886 	opcode = flip_opcode(opcode);
8887 	/* This uses zero as "not present in table"; luckily the zero opcode,
8888 	 * BPF_JA, can't get here.
8889 	 */
8890 	if (opcode)
8891 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8892 }
8893 
8894 /* Regs are known to be equal, so intersect their min/max/var_off */
8895 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8896 				  struct bpf_reg_state *dst_reg)
8897 {
8898 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8899 							dst_reg->umin_value);
8900 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8901 							dst_reg->umax_value);
8902 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8903 							dst_reg->smin_value);
8904 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8905 							dst_reg->smax_value);
8906 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8907 							     dst_reg->var_off);
8908 	/* We might have learned new bounds from the var_off. */
8909 	__update_reg_bounds(src_reg);
8910 	__update_reg_bounds(dst_reg);
8911 	/* We might have learned something about the sign bit. */
8912 	__reg_deduce_bounds(src_reg);
8913 	__reg_deduce_bounds(dst_reg);
8914 	/* We might have learned some bits from the bounds. */
8915 	__reg_bound_offset(src_reg);
8916 	__reg_bound_offset(dst_reg);
8917 	/* Intersecting with the old var_off might have improved our bounds
8918 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8919 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
8920 	 */
8921 	__update_reg_bounds(src_reg);
8922 	__update_reg_bounds(dst_reg);
8923 }
8924 
8925 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8926 				struct bpf_reg_state *true_dst,
8927 				struct bpf_reg_state *false_src,
8928 				struct bpf_reg_state *false_dst,
8929 				u8 opcode)
8930 {
8931 	switch (opcode) {
8932 	case BPF_JEQ:
8933 		__reg_combine_min_max(true_src, true_dst);
8934 		break;
8935 	case BPF_JNE:
8936 		__reg_combine_min_max(false_src, false_dst);
8937 		break;
8938 	}
8939 }
8940 
8941 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8942 				 struct bpf_reg_state *reg, u32 id,
8943 				 bool is_null)
8944 {
8945 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
8946 	    !WARN_ON_ONCE(!reg->id)) {
8947 		/* Old offset (both fixed and variable parts) should
8948 		 * have been known-zero, because we don't allow pointer
8949 		 * arithmetic on pointers that might be NULL.
8950 		 */
8951 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8952 				 !tnum_equals_const(reg->var_off, 0) ||
8953 				 reg->off)) {
8954 			__mark_reg_known_zero(reg);
8955 			reg->off = 0;
8956 		}
8957 		if (is_null) {
8958 			reg->type = SCALAR_VALUE;
8959 			/* We don't need id and ref_obj_id from this point
8960 			 * onwards anymore, thus we should better reset it,
8961 			 * so that state pruning has chances to take effect.
8962 			 */
8963 			reg->id = 0;
8964 			reg->ref_obj_id = 0;
8965 
8966 			return;
8967 		}
8968 
8969 		mark_ptr_not_null_reg(reg);
8970 
8971 		if (!reg_may_point_to_spin_lock(reg)) {
8972 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8973 			 * in release_reg_references().
8974 			 *
8975 			 * reg->id is still used by spin_lock ptr. Other
8976 			 * than spin_lock ptr type, reg->id can be reset.
8977 			 */
8978 			reg->id = 0;
8979 		}
8980 	}
8981 }
8982 
8983 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8984 				    bool is_null)
8985 {
8986 	struct bpf_reg_state *reg;
8987 	int i;
8988 
8989 	for (i = 0; i < MAX_BPF_REG; i++)
8990 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8991 
8992 	bpf_for_each_spilled_reg(i, state, reg) {
8993 		if (!reg)
8994 			continue;
8995 		mark_ptr_or_null_reg(state, reg, id, is_null);
8996 	}
8997 }
8998 
8999 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9000  * be folded together at some point.
9001  */
9002 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9003 				  bool is_null)
9004 {
9005 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9006 	struct bpf_reg_state *regs = state->regs;
9007 	u32 ref_obj_id = regs[regno].ref_obj_id;
9008 	u32 id = regs[regno].id;
9009 	int i;
9010 
9011 	if (ref_obj_id && ref_obj_id == id && is_null)
9012 		/* regs[regno] is in the " == NULL" branch.
9013 		 * No one could have freed the reference state before
9014 		 * doing the NULL check.
9015 		 */
9016 		WARN_ON_ONCE(release_reference_state(state, id));
9017 
9018 	for (i = 0; i <= vstate->curframe; i++)
9019 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9020 }
9021 
9022 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9023 				   struct bpf_reg_state *dst_reg,
9024 				   struct bpf_reg_state *src_reg,
9025 				   struct bpf_verifier_state *this_branch,
9026 				   struct bpf_verifier_state *other_branch)
9027 {
9028 	if (BPF_SRC(insn->code) != BPF_X)
9029 		return false;
9030 
9031 	/* Pointers are always 64-bit. */
9032 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9033 		return false;
9034 
9035 	switch (BPF_OP(insn->code)) {
9036 	case BPF_JGT:
9037 		if ((dst_reg->type == PTR_TO_PACKET &&
9038 		     src_reg->type == PTR_TO_PACKET_END) ||
9039 		    (dst_reg->type == PTR_TO_PACKET_META &&
9040 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9041 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9042 			find_good_pkt_pointers(this_branch, dst_reg,
9043 					       dst_reg->type, false);
9044 			mark_pkt_end(other_branch, insn->dst_reg, true);
9045 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9046 			    src_reg->type == PTR_TO_PACKET) ||
9047 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9048 			    src_reg->type == PTR_TO_PACKET_META)) {
9049 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9050 			find_good_pkt_pointers(other_branch, src_reg,
9051 					       src_reg->type, true);
9052 			mark_pkt_end(this_branch, insn->src_reg, false);
9053 		} else {
9054 			return false;
9055 		}
9056 		break;
9057 	case BPF_JLT:
9058 		if ((dst_reg->type == PTR_TO_PACKET &&
9059 		     src_reg->type == PTR_TO_PACKET_END) ||
9060 		    (dst_reg->type == PTR_TO_PACKET_META &&
9061 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9062 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9063 			find_good_pkt_pointers(other_branch, dst_reg,
9064 					       dst_reg->type, true);
9065 			mark_pkt_end(this_branch, insn->dst_reg, false);
9066 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9067 			    src_reg->type == PTR_TO_PACKET) ||
9068 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9069 			    src_reg->type == PTR_TO_PACKET_META)) {
9070 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9071 			find_good_pkt_pointers(this_branch, src_reg,
9072 					       src_reg->type, false);
9073 			mark_pkt_end(other_branch, insn->src_reg, true);
9074 		} else {
9075 			return false;
9076 		}
9077 		break;
9078 	case BPF_JGE:
9079 		if ((dst_reg->type == PTR_TO_PACKET &&
9080 		     src_reg->type == PTR_TO_PACKET_END) ||
9081 		    (dst_reg->type == PTR_TO_PACKET_META &&
9082 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9083 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9084 			find_good_pkt_pointers(this_branch, dst_reg,
9085 					       dst_reg->type, true);
9086 			mark_pkt_end(other_branch, insn->dst_reg, false);
9087 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9088 			    src_reg->type == PTR_TO_PACKET) ||
9089 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9090 			    src_reg->type == PTR_TO_PACKET_META)) {
9091 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9092 			find_good_pkt_pointers(other_branch, src_reg,
9093 					       src_reg->type, false);
9094 			mark_pkt_end(this_branch, insn->src_reg, true);
9095 		} else {
9096 			return false;
9097 		}
9098 		break;
9099 	case BPF_JLE:
9100 		if ((dst_reg->type == PTR_TO_PACKET &&
9101 		     src_reg->type == PTR_TO_PACKET_END) ||
9102 		    (dst_reg->type == PTR_TO_PACKET_META &&
9103 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9104 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9105 			find_good_pkt_pointers(other_branch, dst_reg,
9106 					       dst_reg->type, false);
9107 			mark_pkt_end(this_branch, insn->dst_reg, true);
9108 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9109 			    src_reg->type == PTR_TO_PACKET) ||
9110 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9111 			    src_reg->type == PTR_TO_PACKET_META)) {
9112 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9113 			find_good_pkt_pointers(this_branch, src_reg,
9114 					       src_reg->type, true);
9115 			mark_pkt_end(other_branch, insn->src_reg, false);
9116 		} else {
9117 			return false;
9118 		}
9119 		break;
9120 	default:
9121 		return false;
9122 	}
9123 
9124 	return true;
9125 }
9126 
9127 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9128 			       struct bpf_reg_state *known_reg)
9129 {
9130 	struct bpf_func_state *state;
9131 	struct bpf_reg_state *reg;
9132 	int i, j;
9133 
9134 	for (i = 0; i <= vstate->curframe; i++) {
9135 		state = vstate->frame[i];
9136 		for (j = 0; j < MAX_BPF_REG; j++) {
9137 			reg = &state->regs[j];
9138 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9139 				*reg = *known_reg;
9140 		}
9141 
9142 		bpf_for_each_spilled_reg(j, state, reg) {
9143 			if (!reg)
9144 				continue;
9145 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9146 				*reg = *known_reg;
9147 		}
9148 	}
9149 }
9150 
9151 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9152 			     struct bpf_insn *insn, int *insn_idx)
9153 {
9154 	struct bpf_verifier_state *this_branch = env->cur_state;
9155 	struct bpf_verifier_state *other_branch;
9156 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9157 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9158 	u8 opcode = BPF_OP(insn->code);
9159 	bool is_jmp32;
9160 	int pred = -1;
9161 	int err;
9162 
9163 	/* Only conditional jumps are expected to reach here. */
9164 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9165 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9166 		return -EINVAL;
9167 	}
9168 
9169 	if (BPF_SRC(insn->code) == BPF_X) {
9170 		if (insn->imm != 0) {
9171 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9172 			return -EINVAL;
9173 		}
9174 
9175 		/* check src1 operand */
9176 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9177 		if (err)
9178 			return err;
9179 
9180 		if (is_pointer_value(env, insn->src_reg)) {
9181 			verbose(env, "R%d pointer comparison prohibited\n",
9182 				insn->src_reg);
9183 			return -EACCES;
9184 		}
9185 		src_reg = &regs[insn->src_reg];
9186 	} else {
9187 		if (insn->src_reg != BPF_REG_0) {
9188 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9189 			return -EINVAL;
9190 		}
9191 	}
9192 
9193 	/* check src2 operand */
9194 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9195 	if (err)
9196 		return err;
9197 
9198 	dst_reg = &regs[insn->dst_reg];
9199 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9200 
9201 	if (BPF_SRC(insn->code) == BPF_K) {
9202 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9203 	} else if (src_reg->type == SCALAR_VALUE &&
9204 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9205 		pred = is_branch_taken(dst_reg,
9206 				       tnum_subreg(src_reg->var_off).value,
9207 				       opcode,
9208 				       is_jmp32);
9209 	} else if (src_reg->type == SCALAR_VALUE &&
9210 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9211 		pred = is_branch_taken(dst_reg,
9212 				       src_reg->var_off.value,
9213 				       opcode,
9214 				       is_jmp32);
9215 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9216 		   reg_is_pkt_pointer_any(src_reg) &&
9217 		   !is_jmp32) {
9218 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9219 	}
9220 
9221 	if (pred >= 0) {
9222 		/* If we get here with a dst_reg pointer type it is because
9223 		 * above is_branch_taken() special cased the 0 comparison.
9224 		 */
9225 		if (!__is_pointer_value(false, dst_reg))
9226 			err = mark_chain_precision(env, insn->dst_reg);
9227 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9228 		    !__is_pointer_value(false, src_reg))
9229 			err = mark_chain_precision(env, insn->src_reg);
9230 		if (err)
9231 			return err;
9232 	}
9233 
9234 	if (pred == 1) {
9235 		/* Only follow the goto, ignore fall-through. If needed, push
9236 		 * the fall-through branch for simulation under speculative
9237 		 * execution.
9238 		 */
9239 		if (!env->bypass_spec_v1 &&
9240 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9241 					       *insn_idx))
9242 			return -EFAULT;
9243 		*insn_idx += insn->off;
9244 		return 0;
9245 	} else if (pred == 0) {
9246 		/* Only follow the fall-through branch, since that's where the
9247 		 * program will go. If needed, push the goto branch for
9248 		 * simulation under speculative execution.
9249 		 */
9250 		if (!env->bypass_spec_v1 &&
9251 		    !sanitize_speculative_path(env, insn,
9252 					       *insn_idx + insn->off + 1,
9253 					       *insn_idx))
9254 			return -EFAULT;
9255 		return 0;
9256 	}
9257 
9258 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9259 				  false);
9260 	if (!other_branch)
9261 		return -EFAULT;
9262 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9263 
9264 	/* detect if we are comparing against a constant value so we can adjust
9265 	 * our min/max values for our dst register.
9266 	 * this is only legit if both are scalars (or pointers to the same
9267 	 * object, I suppose, but we don't support that right now), because
9268 	 * otherwise the different base pointers mean the offsets aren't
9269 	 * comparable.
9270 	 */
9271 	if (BPF_SRC(insn->code) == BPF_X) {
9272 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9273 
9274 		if (dst_reg->type == SCALAR_VALUE &&
9275 		    src_reg->type == SCALAR_VALUE) {
9276 			if (tnum_is_const(src_reg->var_off) ||
9277 			    (is_jmp32 &&
9278 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9279 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9280 						dst_reg,
9281 						src_reg->var_off.value,
9282 						tnum_subreg(src_reg->var_off).value,
9283 						opcode, is_jmp32);
9284 			else if (tnum_is_const(dst_reg->var_off) ||
9285 				 (is_jmp32 &&
9286 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9287 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9288 						    src_reg,
9289 						    dst_reg->var_off.value,
9290 						    tnum_subreg(dst_reg->var_off).value,
9291 						    opcode, is_jmp32);
9292 			else if (!is_jmp32 &&
9293 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9294 				/* Comparing for equality, we can combine knowledge */
9295 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9296 						    &other_branch_regs[insn->dst_reg],
9297 						    src_reg, dst_reg, opcode);
9298 			if (src_reg->id &&
9299 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9300 				find_equal_scalars(this_branch, src_reg);
9301 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9302 			}
9303 
9304 		}
9305 	} else if (dst_reg->type == SCALAR_VALUE) {
9306 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9307 					dst_reg, insn->imm, (u32)insn->imm,
9308 					opcode, is_jmp32);
9309 	}
9310 
9311 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9312 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9313 		find_equal_scalars(this_branch, dst_reg);
9314 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9315 	}
9316 
9317 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9318 	 * NOTE: these optimizations below are related with pointer comparison
9319 	 *       which will never be JMP32.
9320 	 */
9321 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9322 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9323 	    reg_type_may_be_null(dst_reg->type)) {
9324 		/* Mark all identical registers in each branch as either
9325 		 * safe or unknown depending R == 0 or R != 0 conditional.
9326 		 */
9327 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9328 				      opcode == BPF_JNE);
9329 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9330 				      opcode == BPF_JEQ);
9331 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9332 					   this_branch, other_branch) &&
9333 		   is_pointer_value(env, insn->dst_reg)) {
9334 		verbose(env, "R%d pointer comparison prohibited\n",
9335 			insn->dst_reg);
9336 		return -EACCES;
9337 	}
9338 	if (env->log.level & BPF_LOG_LEVEL)
9339 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9340 	return 0;
9341 }
9342 
9343 /* verify BPF_LD_IMM64 instruction */
9344 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9345 {
9346 	struct bpf_insn_aux_data *aux = cur_aux(env);
9347 	struct bpf_reg_state *regs = cur_regs(env);
9348 	struct bpf_reg_state *dst_reg;
9349 	struct bpf_map *map;
9350 	int err;
9351 
9352 	if (BPF_SIZE(insn->code) != BPF_DW) {
9353 		verbose(env, "invalid BPF_LD_IMM insn\n");
9354 		return -EINVAL;
9355 	}
9356 	if (insn->off != 0) {
9357 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9358 		return -EINVAL;
9359 	}
9360 
9361 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9362 	if (err)
9363 		return err;
9364 
9365 	dst_reg = &regs[insn->dst_reg];
9366 	if (insn->src_reg == 0) {
9367 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9368 
9369 		dst_reg->type = SCALAR_VALUE;
9370 		__mark_reg_known(&regs[insn->dst_reg], imm);
9371 		return 0;
9372 	}
9373 
9374 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9375 		mark_reg_known_zero(env, regs, insn->dst_reg);
9376 
9377 		dst_reg->type = aux->btf_var.reg_type;
9378 		switch (dst_reg->type) {
9379 		case PTR_TO_MEM:
9380 			dst_reg->mem_size = aux->btf_var.mem_size;
9381 			break;
9382 		case PTR_TO_BTF_ID:
9383 		case PTR_TO_PERCPU_BTF_ID:
9384 			dst_reg->btf = aux->btf_var.btf;
9385 			dst_reg->btf_id = aux->btf_var.btf_id;
9386 			break;
9387 		default:
9388 			verbose(env, "bpf verifier is misconfigured\n");
9389 			return -EFAULT;
9390 		}
9391 		return 0;
9392 	}
9393 
9394 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9395 		struct bpf_prog_aux *aux = env->prog->aux;
9396 		u32 subprogno = insn[1].imm;
9397 
9398 		if (!aux->func_info) {
9399 			verbose(env, "missing btf func_info\n");
9400 			return -EINVAL;
9401 		}
9402 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9403 			verbose(env, "callback function not static\n");
9404 			return -EINVAL;
9405 		}
9406 
9407 		dst_reg->type = PTR_TO_FUNC;
9408 		dst_reg->subprogno = subprogno;
9409 		return 0;
9410 	}
9411 
9412 	map = env->used_maps[aux->map_index];
9413 	mark_reg_known_zero(env, regs, insn->dst_reg);
9414 	dst_reg->map_ptr = map;
9415 
9416 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9417 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9418 		dst_reg->type = PTR_TO_MAP_VALUE;
9419 		dst_reg->off = aux->map_off;
9420 		if (map_value_has_spin_lock(map))
9421 			dst_reg->id = ++env->id_gen;
9422 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9423 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9424 		dst_reg->type = CONST_PTR_TO_MAP;
9425 	} else {
9426 		verbose(env, "bpf verifier is misconfigured\n");
9427 		return -EINVAL;
9428 	}
9429 
9430 	return 0;
9431 }
9432 
9433 static bool may_access_skb(enum bpf_prog_type type)
9434 {
9435 	switch (type) {
9436 	case BPF_PROG_TYPE_SOCKET_FILTER:
9437 	case BPF_PROG_TYPE_SCHED_CLS:
9438 	case BPF_PROG_TYPE_SCHED_ACT:
9439 		return true;
9440 	default:
9441 		return false;
9442 	}
9443 }
9444 
9445 /* verify safety of LD_ABS|LD_IND instructions:
9446  * - they can only appear in the programs where ctx == skb
9447  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9448  *   preserve R6-R9, and store return value into R0
9449  *
9450  * Implicit input:
9451  *   ctx == skb == R6 == CTX
9452  *
9453  * Explicit input:
9454  *   SRC == any register
9455  *   IMM == 32-bit immediate
9456  *
9457  * Output:
9458  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9459  */
9460 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9461 {
9462 	struct bpf_reg_state *regs = cur_regs(env);
9463 	static const int ctx_reg = BPF_REG_6;
9464 	u8 mode = BPF_MODE(insn->code);
9465 	int i, err;
9466 
9467 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9468 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9469 		return -EINVAL;
9470 	}
9471 
9472 	if (!env->ops->gen_ld_abs) {
9473 		verbose(env, "bpf verifier is misconfigured\n");
9474 		return -EINVAL;
9475 	}
9476 
9477 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9478 	    BPF_SIZE(insn->code) == BPF_DW ||
9479 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9480 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9481 		return -EINVAL;
9482 	}
9483 
9484 	/* check whether implicit source operand (register R6) is readable */
9485 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9486 	if (err)
9487 		return err;
9488 
9489 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9490 	 * gen_ld_abs() may terminate the program at runtime, leading to
9491 	 * reference leak.
9492 	 */
9493 	err = check_reference_leak(env);
9494 	if (err) {
9495 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9496 		return err;
9497 	}
9498 
9499 	if (env->cur_state->active_spin_lock) {
9500 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9501 		return -EINVAL;
9502 	}
9503 
9504 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9505 		verbose(env,
9506 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9507 		return -EINVAL;
9508 	}
9509 
9510 	if (mode == BPF_IND) {
9511 		/* check explicit source operand */
9512 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9513 		if (err)
9514 			return err;
9515 	}
9516 
9517 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9518 	if (err < 0)
9519 		return err;
9520 
9521 	/* reset caller saved regs to unreadable */
9522 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9523 		mark_reg_not_init(env, regs, caller_saved[i]);
9524 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9525 	}
9526 
9527 	/* mark destination R0 register as readable, since it contains
9528 	 * the value fetched from the packet.
9529 	 * Already marked as written above.
9530 	 */
9531 	mark_reg_unknown(env, regs, BPF_REG_0);
9532 	/* ld_abs load up to 32-bit skb data. */
9533 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9534 	return 0;
9535 }
9536 
9537 static int check_return_code(struct bpf_verifier_env *env)
9538 {
9539 	struct tnum enforce_attach_type_range = tnum_unknown;
9540 	const struct bpf_prog *prog = env->prog;
9541 	struct bpf_reg_state *reg;
9542 	struct tnum range = tnum_range(0, 1);
9543 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9544 	int err;
9545 	struct bpf_func_state *frame = env->cur_state->frame[0];
9546 	const bool is_subprog = frame->subprogno;
9547 
9548 	/* LSM and struct_ops func-ptr's return type could be "void" */
9549 	if (!is_subprog &&
9550 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9551 	     prog_type == BPF_PROG_TYPE_LSM) &&
9552 	    !prog->aux->attach_func_proto->type)
9553 		return 0;
9554 
9555 	/* eBPF calling convention is such that R0 is used
9556 	 * to return the value from eBPF program.
9557 	 * Make sure that it's readable at this time
9558 	 * of bpf_exit, which means that program wrote
9559 	 * something into it earlier
9560 	 */
9561 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9562 	if (err)
9563 		return err;
9564 
9565 	if (is_pointer_value(env, BPF_REG_0)) {
9566 		verbose(env, "R0 leaks addr as return value\n");
9567 		return -EACCES;
9568 	}
9569 
9570 	reg = cur_regs(env) + BPF_REG_0;
9571 
9572 	if (frame->in_async_callback_fn) {
9573 		/* enforce return zero from async callbacks like timer */
9574 		if (reg->type != SCALAR_VALUE) {
9575 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9576 				reg_type_str[reg->type]);
9577 			return -EINVAL;
9578 		}
9579 
9580 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9581 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9582 			return -EINVAL;
9583 		}
9584 		return 0;
9585 	}
9586 
9587 	if (is_subprog) {
9588 		if (reg->type != SCALAR_VALUE) {
9589 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9590 				reg_type_str[reg->type]);
9591 			return -EINVAL;
9592 		}
9593 		return 0;
9594 	}
9595 
9596 	switch (prog_type) {
9597 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9598 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9599 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9600 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9601 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9602 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9603 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9604 			range = tnum_range(1, 1);
9605 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9606 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9607 			range = tnum_range(0, 3);
9608 		break;
9609 	case BPF_PROG_TYPE_CGROUP_SKB:
9610 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9611 			range = tnum_range(0, 3);
9612 			enforce_attach_type_range = tnum_range(2, 3);
9613 		}
9614 		break;
9615 	case BPF_PROG_TYPE_CGROUP_SOCK:
9616 	case BPF_PROG_TYPE_SOCK_OPS:
9617 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9618 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9619 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9620 		break;
9621 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9622 		if (!env->prog->aux->attach_btf_id)
9623 			return 0;
9624 		range = tnum_const(0);
9625 		break;
9626 	case BPF_PROG_TYPE_TRACING:
9627 		switch (env->prog->expected_attach_type) {
9628 		case BPF_TRACE_FENTRY:
9629 		case BPF_TRACE_FEXIT:
9630 			range = tnum_const(0);
9631 			break;
9632 		case BPF_TRACE_RAW_TP:
9633 		case BPF_MODIFY_RETURN:
9634 			return 0;
9635 		case BPF_TRACE_ITER:
9636 			break;
9637 		default:
9638 			return -ENOTSUPP;
9639 		}
9640 		break;
9641 	case BPF_PROG_TYPE_SK_LOOKUP:
9642 		range = tnum_range(SK_DROP, SK_PASS);
9643 		break;
9644 	case BPF_PROG_TYPE_EXT:
9645 		/* freplace program can return anything as its return value
9646 		 * depends on the to-be-replaced kernel func or bpf program.
9647 		 */
9648 	default:
9649 		return 0;
9650 	}
9651 
9652 	if (reg->type != SCALAR_VALUE) {
9653 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9654 			reg_type_str[reg->type]);
9655 		return -EINVAL;
9656 	}
9657 
9658 	if (!tnum_in(range, reg->var_off)) {
9659 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9660 		return -EINVAL;
9661 	}
9662 
9663 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9664 	    tnum_in(enforce_attach_type_range, reg->var_off))
9665 		env->prog->enforce_expected_attach_type = 1;
9666 	return 0;
9667 }
9668 
9669 /* non-recursive DFS pseudo code
9670  * 1  procedure DFS-iterative(G,v):
9671  * 2      label v as discovered
9672  * 3      let S be a stack
9673  * 4      S.push(v)
9674  * 5      while S is not empty
9675  * 6            t <- S.pop()
9676  * 7            if t is what we're looking for:
9677  * 8                return t
9678  * 9            for all edges e in G.adjacentEdges(t) do
9679  * 10               if edge e is already labelled
9680  * 11                   continue with the next edge
9681  * 12               w <- G.adjacentVertex(t,e)
9682  * 13               if vertex w is not discovered and not explored
9683  * 14                   label e as tree-edge
9684  * 15                   label w as discovered
9685  * 16                   S.push(w)
9686  * 17                   continue at 5
9687  * 18               else if vertex w is discovered
9688  * 19                   label e as back-edge
9689  * 20               else
9690  * 21                   // vertex w is explored
9691  * 22                   label e as forward- or cross-edge
9692  * 23           label t as explored
9693  * 24           S.pop()
9694  *
9695  * convention:
9696  * 0x10 - discovered
9697  * 0x11 - discovered and fall-through edge labelled
9698  * 0x12 - discovered and fall-through and branch edges labelled
9699  * 0x20 - explored
9700  */
9701 
9702 enum {
9703 	DISCOVERED = 0x10,
9704 	EXPLORED = 0x20,
9705 	FALLTHROUGH = 1,
9706 	BRANCH = 2,
9707 };
9708 
9709 static u32 state_htab_size(struct bpf_verifier_env *env)
9710 {
9711 	return env->prog->len;
9712 }
9713 
9714 static struct bpf_verifier_state_list **explored_state(
9715 					struct bpf_verifier_env *env,
9716 					int idx)
9717 {
9718 	struct bpf_verifier_state *cur = env->cur_state;
9719 	struct bpf_func_state *state = cur->frame[cur->curframe];
9720 
9721 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9722 }
9723 
9724 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9725 {
9726 	env->insn_aux_data[idx].prune_point = true;
9727 }
9728 
9729 enum {
9730 	DONE_EXPLORING = 0,
9731 	KEEP_EXPLORING = 1,
9732 };
9733 
9734 /* t, w, e - match pseudo-code above:
9735  * t - index of current instruction
9736  * w - next instruction
9737  * e - edge
9738  */
9739 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9740 		     bool loop_ok)
9741 {
9742 	int *insn_stack = env->cfg.insn_stack;
9743 	int *insn_state = env->cfg.insn_state;
9744 
9745 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9746 		return DONE_EXPLORING;
9747 
9748 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9749 		return DONE_EXPLORING;
9750 
9751 	if (w < 0 || w >= env->prog->len) {
9752 		verbose_linfo(env, t, "%d: ", t);
9753 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9754 		return -EINVAL;
9755 	}
9756 
9757 	if (e == BRANCH)
9758 		/* mark branch target for state pruning */
9759 		init_explored_state(env, w);
9760 
9761 	if (insn_state[w] == 0) {
9762 		/* tree-edge */
9763 		insn_state[t] = DISCOVERED | e;
9764 		insn_state[w] = DISCOVERED;
9765 		if (env->cfg.cur_stack >= env->prog->len)
9766 			return -E2BIG;
9767 		insn_stack[env->cfg.cur_stack++] = w;
9768 		return KEEP_EXPLORING;
9769 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9770 		if (loop_ok && env->bpf_capable)
9771 			return DONE_EXPLORING;
9772 		verbose_linfo(env, t, "%d: ", t);
9773 		verbose_linfo(env, w, "%d: ", w);
9774 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9775 		return -EINVAL;
9776 	} else if (insn_state[w] == EXPLORED) {
9777 		/* forward- or cross-edge */
9778 		insn_state[t] = DISCOVERED | e;
9779 	} else {
9780 		verbose(env, "insn state internal bug\n");
9781 		return -EFAULT;
9782 	}
9783 	return DONE_EXPLORING;
9784 }
9785 
9786 static int visit_func_call_insn(int t, int insn_cnt,
9787 				struct bpf_insn *insns,
9788 				struct bpf_verifier_env *env,
9789 				bool visit_callee)
9790 {
9791 	int ret;
9792 
9793 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9794 	if (ret)
9795 		return ret;
9796 
9797 	if (t + 1 < insn_cnt)
9798 		init_explored_state(env, t + 1);
9799 	if (visit_callee) {
9800 		init_explored_state(env, t);
9801 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9802 				/* It's ok to allow recursion from CFG point of
9803 				 * view. __check_func_call() will do the actual
9804 				 * check.
9805 				 */
9806 				bpf_pseudo_func(insns + t));
9807 	}
9808 	return ret;
9809 }
9810 
9811 /* Visits the instruction at index t and returns one of the following:
9812  *  < 0 - an error occurred
9813  *  DONE_EXPLORING - the instruction was fully explored
9814  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9815  */
9816 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9817 {
9818 	struct bpf_insn *insns = env->prog->insnsi;
9819 	int ret;
9820 
9821 	if (bpf_pseudo_func(insns + t))
9822 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9823 
9824 	/* All non-branch instructions have a single fall-through edge. */
9825 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9826 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9827 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9828 
9829 	switch (BPF_OP(insns[t].code)) {
9830 	case BPF_EXIT:
9831 		return DONE_EXPLORING;
9832 
9833 	case BPF_CALL:
9834 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9835 			/* Mark this call insn to trigger is_state_visited() check
9836 			 * before call itself is processed by __check_func_call().
9837 			 * Otherwise new async state will be pushed for further
9838 			 * exploration.
9839 			 */
9840 			init_explored_state(env, t);
9841 		return visit_func_call_insn(t, insn_cnt, insns, env,
9842 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9843 
9844 	case BPF_JA:
9845 		if (BPF_SRC(insns[t].code) != BPF_K)
9846 			return -EINVAL;
9847 
9848 		/* unconditional jump with single edge */
9849 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9850 				true);
9851 		if (ret)
9852 			return ret;
9853 
9854 		/* unconditional jmp is not a good pruning point,
9855 		 * but it's marked, since backtracking needs
9856 		 * to record jmp history in is_state_visited().
9857 		 */
9858 		init_explored_state(env, t + insns[t].off + 1);
9859 		/* tell verifier to check for equivalent states
9860 		 * after every call and jump
9861 		 */
9862 		if (t + 1 < insn_cnt)
9863 			init_explored_state(env, t + 1);
9864 
9865 		return ret;
9866 
9867 	default:
9868 		/* conditional jump with two edges */
9869 		init_explored_state(env, t);
9870 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9871 		if (ret)
9872 			return ret;
9873 
9874 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9875 	}
9876 }
9877 
9878 /* non-recursive depth-first-search to detect loops in BPF program
9879  * loop == back-edge in directed graph
9880  */
9881 static int check_cfg(struct bpf_verifier_env *env)
9882 {
9883 	int insn_cnt = env->prog->len;
9884 	int *insn_stack, *insn_state;
9885 	int ret = 0;
9886 	int i;
9887 
9888 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9889 	if (!insn_state)
9890 		return -ENOMEM;
9891 
9892 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9893 	if (!insn_stack) {
9894 		kvfree(insn_state);
9895 		return -ENOMEM;
9896 	}
9897 
9898 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9899 	insn_stack[0] = 0; /* 0 is the first instruction */
9900 	env->cfg.cur_stack = 1;
9901 
9902 	while (env->cfg.cur_stack > 0) {
9903 		int t = insn_stack[env->cfg.cur_stack - 1];
9904 
9905 		ret = visit_insn(t, insn_cnt, env);
9906 		switch (ret) {
9907 		case DONE_EXPLORING:
9908 			insn_state[t] = EXPLORED;
9909 			env->cfg.cur_stack--;
9910 			break;
9911 		case KEEP_EXPLORING:
9912 			break;
9913 		default:
9914 			if (ret > 0) {
9915 				verbose(env, "visit_insn internal bug\n");
9916 				ret = -EFAULT;
9917 			}
9918 			goto err_free;
9919 		}
9920 	}
9921 
9922 	if (env->cfg.cur_stack < 0) {
9923 		verbose(env, "pop stack internal bug\n");
9924 		ret = -EFAULT;
9925 		goto err_free;
9926 	}
9927 
9928 	for (i = 0; i < insn_cnt; i++) {
9929 		if (insn_state[i] != EXPLORED) {
9930 			verbose(env, "unreachable insn %d\n", i);
9931 			ret = -EINVAL;
9932 			goto err_free;
9933 		}
9934 	}
9935 	ret = 0; /* cfg looks good */
9936 
9937 err_free:
9938 	kvfree(insn_state);
9939 	kvfree(insn_stack);
9940 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9941 	return ret;
9942 }
9943 
9944 static int check_abnormal_return(struct bpf_verifier_env *env)
9945 {
9946 	int i;
9947 
9948 	for (i = 1; i < env->subprog_cnt; i++) {
9949 		if (env->subprog_info[i].has_ld_abs) {
9950 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9951 			return -EINVAL;
9952 		}
9953 		if (env->subprog_info[i].has_tail_call) {
9954 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9955 			return -EINVAL;
9956 		}
9957 	}
9958 	return 0;
9959 }
9960 
9961 /* The minimum supported BTF func info size */
9962 #define MIN_BPF_FUNCINFO_SIZE	8
9963 #define MAX_FUNCINFO_REC_SIZE	252
9964 
9965 static int check_btf_func(struct bpf_verifier_env *env,
9966 			  const union bpf_attr *attr,
9967 			  bpfptr_t uattr)
9968 {
9969 	const struct btf_type *type, *func_proto, *ret_type;
9970 	u32 i, nfuncs, urec_size, min_size;
9971 	u32 krec_size = sizeof(struct bpf_func_info);
9972 	struct bpf_func_info *krecord;
9973 	struct bpf_func_info_aux *info_aux = NULL;
9974 	struct bpf_prog *prog;
9975 	const struct btf *btf;
9976 	bpfptr_t urecord;
9977 	u32 prev_offset = 0;
9978 	bool scalar_return;
9979 	int ret = -ENOMEM;
9980 
9981 	nfuncs = attr->func_info_cnt;
9982 	if (!nfuncs) {
9983 		if (check_abnormal_return(env))
9984 			return -EINVAL;
9985 		return 0;
9986 	}
9987 
9988 	if (nfuncs != env->subprog_cnt) {
9989 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9990 		return -EINVAL;
9991 	}
9992 
9993 	urec_size = attr->func_info_rec_size;
9994 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9995 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
9996 	    urec_size % sizeof(u32)) {
9997 		verbose(env, "invalid func info rec size %u\n", urec_size);
9998 		return -EINVAL;
9999 	}
10000 
10001 	prog = env->prog;
10002 	btf = prog->aux->btf;
10003 
10004 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10005 	min_size = min_t(u32, krec_size, urec_size);
10006 
10007 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10008 	if (!krecord)
10009 		return -ENOMEM;
10010 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10011 	if (!info_aux)
10012 		goto err_free;
10013 
10014 	for (i = 0; i < nfuncs; i++) {
10015 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10016 		if (ret) {
10017 			if (ret == -E2BIG) {
10018 				verbose(env, "nonzero tailing record in func info");
10019 				/* set the size kernel expects so loader can zero
10020 				 * out the rest of the record.
10021 				 */
10022 				if (copy_to_bpfptr_offset(uattr,
10023 							  offsetof(union bpf_attr, func_info_rec_size),
10024 							  &min_size, sizeof(min_size)))
10025 					ret = -EFAULT;
10026 			}
10027 			goto err_free;
10028 		}
10029 
10030 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10031 			ret = -EFAULT;
10032 			goto err_free;
10033 		}
10034 
10035 		/* check insn_off */
10036 		ret = -EINVAL;
10037 		if (i == 0) {
10038 			if (krecord[i].insn_off) {
10039 				verbose(env,
10040 					"nonzero insn_off %u for the first func info record",
10041 					krecord[i].insn_off);
10042 				goto err_free;
10043 			}
10044 		} else if (krecord[i].insn_off <= prev_offset) {
10045 			verbose(env,
10046 				"same or smaller insn offset (%u) than previous func info record (%u)",
10047 				krecord[i].insn_off, prev_offset);
10048 			goto err_free;
10049 		}
10050 
10051 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10052 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10053 			goto err_free;
10054 		}
10055 
10056 		/* check type_id */
10057 		type = btf_type_by_id(btf, krecord[i].type_id);
10058 		if (!type || !btf_type_is_func(type)) {
10059 			verbose(env, "invalid type id %d in func info",
10060 				krecord[i].type_id);
10061 			goto err_free;
10062 		}
10063 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10064 
10065 		func_proto = btf_type_by_id(btf, type->type);
10066 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10067 			/* btf_func_check() already verified it during BTF load */
10068 			goto err_free;
10069 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10070 		scalar_return =
10071 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10072 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10073 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10074 			goto err_free;
10075 		}
10076 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10077 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10078 			goto err_free;
10079 		}
10080 
10081 		prev_offset = krecord[i].insn_off;
10082 		bpfptr_add(&urecord, urec_size);
10083 	}
10084 
10085 	prog->aux->func_info = krecord;
10086 	prog->aux->func_info_cnt = nfuncs;
10087 	prog->aux->func_info_aux = info_aux;
10088 	return 0;
10089 
10090 err_free:
10091 	kvfree(krecord);
10092 	kfree(info_aux);
10093 	return ret;
10094 }
10095 
10096 static void adjust_btf_func(struct bpf_verifier_env *env)
10097 {
10098 	struct bpf_prog_aux *aux = env->prog->aux;
10099 	int i;
10100 
10101 	if (!aux->func_info)
10102 		return;
10103 
10104 	for (i = 0; i < env->subprog_cnt; i++)
10105 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10106 }
10107 
10108 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
10109 		sizeof(((struct bpf_line_info *)(0))->line_col))
10110 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10111 
10112 static int check_btf_line(struct bpf_verifier_env *env,
10113 			  const union bpf_attr *attr,
10114 			  bpfptr_t uattr)
10115 {
10116 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10117 	struct bpf_subprog_info *sub;
10118 	struct bpf_line_info *linfo;
10119 	struct bpf_prog *prog;
10120 	const struct btf *btf;
10121 	bpfptr_t ulinfo;
10122 	int err;
10123 
10124 	nr_linfo = attr->line_info_cnt;
10125 	if (!nr_linfo)
10126 		return 0;
10127 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10128 		return -EINVAL;
10129 
10130 	rec_size = attr->line_info_rec_size;
10131 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10132 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10133 	    rec_size & (sizeof(u32) - 1))
10134 		return -EINVAL;
10135 
10136 	/* Need to zero it in case the userspace may
10137 	 * pass in a smaller bpf_line_info object.
10138 	 */
10139 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10140 			 GFP_KERNEL | __GFP_NOWARN);
10141 	if (!linfo)
10142 		return -ENOMEM;
10143 
10144 	prog = env->prog;
10145 	btf = prog->aux->btf;
10146 
10147 	s = 0;
10148 	sub = env->subprog_info;
10149 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10150 	expected_size = sizeof(struct bpf_line_info);
10151 	ncopy = min_t(u32, expected_size, rec_size);
10152 	for (i = 0; i < nr_linfo; i++) {
10153 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10154 		if (err) {
10155 			if (err == -E2BIG) {
10156 				verbose(env, "nonzero tailing record in line_info");
10157 				if (copy_to_bpfptr_offset(uattr,
10158 							  offsetof(union bpf_attr, line_info_rec_size),
10159 							  &expected_size, sizeof(expected_size)))
10160 					err = -EFAULT;
10161 			}
10162 			goto err_free;
10163 		}
10164 
10165 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10166 			err = -EFAULT;
10167 			goto err_free;
10168 		}
10169 
10170 		/*
10171 		 * Check insn_off to ensure
10172 		 * 1) strictly increasing AND
10173 		 * 2) bounded by prog->len
10174 		 *
10175 		 * The linfo[0].insn_off == 0 check logically falls into
10176 		 * the later "missing bpf_line_info for func..." case
10177 		 * because the first linfo[0].insn_off must be the
10178 		 * first sub also and the first sub must have
10179 		 * subprog_info[0].start == 0.
10180 		 */
10181 		if ((i && linfo[i].insn_off <= prev_offset) ||
10182 		    linfo[i].insn_off >= prog->len) {
10183 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10184 				i, linfo[i].insn_off, prev_offset,
10185 				prog->len);
10186 			err = -EINVAL;
10187 			goto err_free;
10188 		}
10189 
10190 		if (!prog->insnsi[linfo[i].insn_off].code) {
10191 			verbose(env,
10192 				"Invalid insn code at line_info[%u].insn_off\n",
10193 				i);
10194 			err = -EINVAL;
10195 			goto err_free;
10196 		}
10197 
10198 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10199 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10200 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10201 			err = -EINVAL;
10202 			goto err_free;
10203 		}
10204 
10205 		if (s != env->subprog_cnt) {
10206 			if (linfo[i].insn_off == sub[s].start) {
10207 				sub[s].linfo_idx = i;
10208 				s++;
10209 			} else if (sub[s].start < linfo[i].insn_off) {
10210 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10211 				err = -EINVAL;
10212 				goto err_free;
10213 			}
10214 		}
10215 
10216 		prev_offset = linfo[i].insn_off;
10217 		bpfptr_add(&ulinfo, rec_size);
10218 	}
10219 
10220 	if (s != env->subprog_cnt) {
10221 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10222 			env->subprog_cnt - s, s);
10223 		err = -EINVAL;
10224 		goto err_free;
10225 	}
10226 
10227 	prog->aux->linfo = linfo;
10228 	prog->aux->nr_linfo = nr_linfo;
10229 
10230 	return 0;
10231 
10232 err_free:
10233 	kvfree(linfo);
10234 	return err;
10235 }
10236 
10237 static int check_btf_info(struct bpf_verifier_env *env,
10238 			  const union bpf_attr *attr,
10239 			  bpfptr_t uattr)
10240 {
10241 	struct btf *btf;
10242 	int err;
10243 
10244 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10245 		if (check_abnormal_return(env))
10246 			return -EINVAL;
10247 		return 0;
10248 	}
10249 
10250 	btf = btf_get_by_fd(attr->prog_btf_fd);
10251 	if (IS_ERR(btf))
10252 		return PTR_ERR(btf);
10253 	if (btf_is_kernel(btf)) {
10254 		btf_put(btf);
10255 		return -EACCES;
10256 	}
10257 	env->prog->aux->btf = btf;
10258 
10259 	err = check_btf_func(env, attr, uattr);
10260 	if (err)
10261 		return err;
10262 
10263 	err = check_btf_line(env, attr, uattr);
10264 	if (err)
10265 		return err;
10266 
10267 	return 0;
10268 }
10269 
10270 /* check %cur's range satisfies %old's */
10271 static bool range_within(struct bpf_reg_state *old,
10272 			 struct bpf_reg_state *cur)
10273 {
10274 	return old->umin_value <= cur->umin_value &&
10275 	       old->umax_value >= cur->umax_value &&
10276 	       old->smin_value <= cur->smin_value &&
10277 	       old->smax_value >= cur->smax_value &&
10278 	       old->u32_min_value <= cur->u32_min_value &&
10279 	       old->u32_max_value >= cur->u32_max_value &&
10280 	       old->s32_min_value <= cur->s32_min_value &&
10281 	       old->s32_max_value >= cur->s32_max_value;
10282 }
10283 
10284 /* If in the old state two registers had the same id, then they need to have
10285  * the same id in the new state as well.  But that id could be different from
10286  * the old state, so we need to track the mapping from old to new ids.
10287  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10288  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10289  * regs with a different old id could still have new id 9, we don't care about
10290  * that.
10291  * So we look through our idmap to see if this old id has been seen before.  If
10292  * so, we require the new id to match; otherwise, we add the id pair to the map.
10293  */
10294 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10295 {
10296 	unsigned int i;
10297 
10298 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10299 		if (!idmap[i].old) {
10300 			/* Reached an empty slot; haven't seen this id before */
10301 			idmap[i].old = old_id;
10302 			idmap[i].cur = cur_id;
10303 			return true;
10304 		}
10305 		if (idmap[i].old == old_id)
10306 			return idmap[i].cur == cur_id;
10307 	}
10308 	/* We ran out of idmap slots, which should be impossible */
10309 	WARN_ON_ONCE(1);
10310 	return false;
10311 }
10312 
10313 static void clean_func_state(struct bpf_verifier_env *env,
10314 			     struct bpf_func_state *st)
10315 {
10316 	enum bpf_reg_liveness live;
10317 	int i, j;
10318 
10319 	for (i = 0; i < BPF_REG_FP; i++) {
10320 		live = st->regs[i].live;
10321 		/* liveness must not touch this register anymore */
10322 		st->regs[i].live |= REG_LIVE_DONE;
10323 		if (!(live & REG_LIVE_READ))
10324 			/* since the register is unused, clear its state
10325 			 * to make further comparison simpler
10326 			 */
10327 			__mark_reg_not_init(env, &st->regs[i]);
10328 	}
10329 
10330 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10331 		live = st->stack[i].spilled_ptr.live;
10332 		/* liveness must not touch this stack slot anymore */
10333 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10334 		if (!(live & REG_LIVE_READ)) {
10335 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10336 			for (j = 0; j < BPF_REG_SIZE; j++)
10337 				st->stack[i].slot_type[j] = STACK_INVALID;
10338 		}
10339 	}
10340 }
10341 
10342 static void clean_verifier_state(struct bpf_verifier_env *env,
10343 				 struct bpf_verifier_state *st)
10344 {
10345 	int i;
10346 
10347 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10348 		/* all regs in this state in all frames were already marked */
10349 		return;
10350 
10351 	for (i = 0; i <= st->curframe; i++)
10352 		clean_func_state(env, st->frame[i]);
10353 }
10354 
10355 /* the parentage chains form a tree.
10356  * the verifier states are added to state lists at given insn and
10357  * pushed into state stack for future exploration.
10358  * when the verifier reaches bpf_exit insn some of the verifer states
10359  * stored in the state lists have their final liveness state already,
10360  * but a lot of states will get revised from liveness point of view when
10361  * the verifier explores other branches.
10362  * Example:
10363  * 1: r0 = 1
10364  * 2: if r1 == 100 goto pc+1
10365  * 3: r0 = 2
10366  * 4: exit
10367  * when the verifier reaches exit insn the register r0 in the state list of
10368  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10369  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10370  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10371  *
10372  * Since the verifier pushes the branch states as it sees them while exploring
10373  * the program the condition of walking the branch instruction for the second
10374  * time means that all states below this branch were already explored and
10375  * their final liveness marks are already propagated.
10376  * Hence when the verifier completes the search of state list in is_state_visited()
10377  * we can call this clean_live_states() function to mark all liveness states
10378  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10379  * will not be used.
10380  * This function also clears the registers and stack for states that !READ
10381  * to simplify state merging.
10382  *
10383  * Important note here that walking the same branch instruction in the callee
10384  * doesn't meant that the states are DONE. The verifier has to compare
10385  * the callsites
10386  */
10387 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10388 			      struct bpf_verifier_state *cur)
10389 {
10390 	struct bpf_verifier_state_list *sl;
10391 	int i;
10392 
10393 	sl = *explored_state(env, insn);
10394 	while (sl) {
10395 		if (sl->state.branches)
10396 			goto next;
10397 		if (sl->state.insn_idx != insn ||
10398 		    sl->state.curframe != cur->curframe)
10399 			goto next;
10400 		for (i = 0; i <= cur->curframe; i++)
10401 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10402 				goto next;
10403 		clean_verifier_state(env, &sl->state);
10404 next:
10405 		sl = sl->next;
10406 	}
10407 }
10408 
10409 /* Returns true if (rold safe implies rcur safe) */
10410 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10411 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10412 {
10413 	bool equal;
10414 
10415 	if (!(rold->live & REG_LIVE_READ))
10416 		/* explored state didn't use this */
10417 		return true;
10418 
10419 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10420 
10421 	if (rold->type == PTR_TO_STACK)
10422 		/* two stack pointers are equal only if they're pointing to
10423 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10424 		 */
10425 		return equal && rold->frameno == rcur->frameno;
10426 
10427 	if (equal)
10428 		return true;
10429 
10430 	if (rold->type == NOT_INIT)
10431 		/* explored state can't have used this */
10432 		return true;
10433 	if (rcur->type == NOT_INIT)
10434 		return false;
10435 	switch (rold->type) {
10436 	case SCALAR_VALUE:
10437 		if (env->explore_alu_limits)
10438 			return false;
10439 		if (rcur->type == SCALAR_VALUE) {
10440 			if (!rold->precise && !rcur->precise)
10441 				return true;
10442 			/* new val must satisfy old val knowledge */
10443 			return range_within(rold, rcur) &&
10444 			       tnum_in(rold->var_off, rcur->var_off);
10445 		} else {
10446 			/* We're trying to use a pointer in place of a scalar.
10447 			 * Even if the scalar was unbounded, this could lead to
10448 			 * pointer leaks because scalars are allowed to leak
10449 			 * while pointers are not. We could make this safe in
10450 			 * special cases if root is calling us, but it's
10451 			 * probably not worth the hassle.
10452 			 */
10453 			return false;
10454 		}
10455 	case PTR_TO_MAP_KEY:
10456 	case PTR_TO_MAP_VALUE:
10457 		/* If the new min/max/var_off satisfy the old ones and
10458 		 * everything else matches, we are OK.
10459 		 * 'id' is not compared, since it's only used for maps with
10460 		 * bpf_spin_lock inside map element and in such cases if
10461 		 * the rest of the prog is valid for one map element then
10462 		 * it's valid for all map elements regardless of the key
10463 		 * used in bpf_map_lookup()
10464 		 */
10465 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10466 		       range_within(rold, rcur) &&
10467 		       tnum_in(rold->var_off, rcur->var_off);
10468 	case PTR_TO_MAP_VALUE_OR_NULL:
10469 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10470 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10471 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10472 		 * checked, doing so could have affected others with the same
10473 		 * id, and we can't check for that because we lost the id when
10474 		 * we converted to a PTR_TO_MAP_VALUE.
10475 		 */
10476 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10477 			return false;
10478 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10479 			return false;
10480 		/* Check our ids match any regs they're supposed to */
10481 		return check_ids(rold->id, rcur->id, idmap);
10482 	case PTR_TO_PACKET_META:
10483 	case PTR_TO_PACKET:
10484 		if (rcur->type != rold->type)
10485 			return false;
10486 		/* We must have at least as much range as the old ptr
10487 		 * did, so that any accesses which were safe before are
10488 		 * still safe.  This is true even if old range < old off,
10489 		 * since someone could have accessed through (ptr - k), or
10490 		 * even done ptr -= k in a register, to get a safe access.
10491 		 */
10492 		if (rold->range > rcur->range)
10493 			return false;
10494 		/* If the offsets don't match, we can't trust our alignment;
10495 		 * nor can we be sure that we won't fall out of range.
10496 		 */
10497 		if (rold->off != rcur->off)
10498 			return false;
10499 		/* id relations must be preserved */
10500 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10501 			return false;
10502 		/* new val must satisfy old val knowledge */
10503 		return range_within(rold, rcur) &&
10504 		       tnum_in(rold->var_off, rcur->var_off);
10505 	case PTR_TO_CTX:
10506 	case CONST_PTR_TO_MAP:
10507 	case PTR_TO_PACKET_END:
10508 	case PTR_TO_FLOW_KEYS:
10509 	case PTR_TO_SOCKET:
10510 	case PTR_TO_SOCKET_OR_NULL:
10511 	case PTR_TO_SOCK_COMMON:
10512 	case PTR_TO_SOCK_COMMON_OR_NULL:
10513 	case PTR_TO_TCP_SOCK:
10514 	case PTR_TO_TCP_SOCK_OR_NULL:
10515 	case PTR_TO_XDP_SOCK:
10516 		/* Only valid matches are exact, which memcmp() above
10517 		 * would have accepted
10518 		 */
10519 	default:
10520 		/* Don't know what's going on, just say it's not safe */
10521 		return false;
10522 	}
10523 
10524 	/* Shouldn't get here; if we do, say it's not safe */
10525 	WARN_ON_ONCE(1);
10526 	return false;
10527 }
10528 
10529 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10530 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10531 {
10532 	int i, spi;
10533 
10534 	/* walk slots of the explored stack and ignore any additional
10535 	 * slots in the current stack, since explored(safe) state
10536 	 * didn't use them
10537 	 */
10538 	for (i = 0; i < old->allocated_stack; i++) {
10539 		spi = i / BPF_REG_SIZE;
10540 
10541 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10542 			i += BPF_REG_SIZE - 1;
10543 			/* explored state didn't use this */
10544 			continue;
10545 		}
10546 
10547 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10548 			continue;
10549 
10550 		/* explored stack has more populated slots than current stack
10551 		 * and these slots were used
10552 		 */
10553 		if (i >= cur->allocated_stack)
10554 			return false;
10555 
10556 		/* if old state was safe with misc data in the stack
10557 		 * it will be safe with zero-initialized stack.
10558 		 * The opposite is not true
10559 		 */
10560 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10561 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10562 			continue;
10563 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10564 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10565 			/* Ex: old explored (safe) state has STACK_SPILL in
10566 			 * this stack slot, but current has STACK_MISC ->
10567 			 * this verifier states are not equivalent,
10568 			 * return false to continue verification of this path
10569 			 */
10570 			return false;
10571 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10572 			continue;
10573 		if (!is_spilled_reg(&old->stack[spi]))
10574 			continue;
10575 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10576 			     &cur->stack[spi].spilled_ptr, idmap))
10577 			/* when explored and current stack slot are both storing
10578 			 * spilled registers, check that stored pointers types
10579 			 * are the same as well.
10580 			 * Ex: explored safe path could have stored
10581 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10582 			 * but current path has stored:
10583 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10584 			 * such verifier states are not equivalent.
10585 			 * return false to continue verification of this path
10586 			 */
10587 			return false;
10588 	}
10589 	return true;
10590 }
10591 
10592 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10593 {
10594 	if (old->acquired_refs != cur->acquired_refs)
10595 		return false;
10596 	return !memcmp(old->refs, cur->refs,
10597 		       sizeof(*old->refs) * old->acquired_refs);
10598 }
10599 
10600 /* compare two verifier states
10601  *
10602  * all states stored in state_list are known to be valid, since
10603  * verifier reached 'bpf_exit' instruction through them
10604  *
10605  * this function is called when verifier exploring different branches of
10606  * execution popped from the state stack. If it sees an old state that has
10607  * more strict register state and more strict stack state then this execution
10608  * branch doesn't need to be explored further, since verifier already
10609  * concluded that more strict state leads to valid finish.
10610  *
10611  * Therefore two states are equivalent if register state is more conservative
10612  * and explored stack state is more conservative than the current one.
10613  * Example:
10614  *       explored                   current
10615  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10616  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10617  *
10618  * In other words if current stack state (one being explored) has more
10619  * valid slots than old one that already passed validation, it means
10620  * the verifier can stop exploring and conclude that current state is valid too
10621  *
10622  * Similarly with registers. If explored state has register type as invalid
10623  * whereas register type in current state is meaningful, it means that
10624  * the current state will reach 'bpf_exit' instruction safely
10625  */
10626 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10627 			      struct bpf_func_state *cur)
10628 {
10629 	int i;
10630 
10631 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10632 	for (i = 0; i < MAX_BPF_REG; i++)
10633 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10634 			     env->idmap_scratch))
10635 			return false;
10636 
10637 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10638 		return false;
10639 
10640 	if (!refsafe(old, cur))
10641 		return false;
10642 
10643 	return true;
10644 }
10645 
10646 static bool states_equal(struct bpf_verifier_env *env,
10647 			 struct bpf_verifier_state *old,
10648 			 struct bpf_verifier_state *cur)
10649 {
10650 	int i;
10651 
10652 	if (old->curframe != cur->curframe)
10653 		return false;
10654 
10655 	/* Verification state from speculative execution simulation
10656 	 * must never prune a non-speculative execution one.
10657 	 */
10658 	if (old->speculative && !cur->speculative)
10659 		return false;
10660 
10661 	if (old->active_spin_lock != cur->active_spin_lock)
10662 		return false;
10663 
10664 	/* for states to be equal callsites have to be the same
10665 	 * and all frame states need to be equivalent
10666 	 */
10667 	for (i = 0; i <= old->curframe; i++) {
10668 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10669 			return false;
10670 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10671 			return false;
10672 	}
10673 	return true;
10674 }
10675 
10676 /* Return 0 if no propagation happened. Return negative error code if error
10677  * happened. Otherwise, return the propagated bit.
10678  */
10679 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10680 				  struct bpf_reg_state *reg,
10681 				  struct bpf_reg_state *parent_reg)
10682 {
10683 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10684 	u8 flag = reg->live & REG_LIVE_READ;
10685 	int err;
10686 
10687 	/* When comes here, read flags of PARENT_REG or REG could be any of
10688 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10689 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10690 	 */
10691 	if (parent_flag == REG_LIVE_READ64 ||
10692 	    /* Or if there is no read flag from REG. */
10693 	    !flag ||
10694 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10695 	    parent_flag == flag)
10696 		return 0;
10697 
10698 	err = mark_reg_read(env, reg, parent_reg, flag);
10699 	if (err)
10700 		return err;
10701 
10702 	return flag;
10703 }
10704 
10705 /* A write screens off any subsequent reads; but write marks come from the
10706  * straight-line code between a state and its parent.  When we arrive at an
10707  * equivalent state (jump target or such) we didn't arrive by the straight-line
10708  * code, so read marks in the state must propagate to the parent regardless
10709  * of the state's write marks. That's what 'parent == state->parent' comparison
10710  * in mark_reg_read() is for.
10711  */
10712 static int propagate_liveness(struct bpf_verifier_env *env,
10713 			      const struct bpf_verifier_state *vstate,
10714 			      struct bpf_verifier_state *vparent)
10715 {
10716 	struct bpf_reg_state *state_reg, *parent_reg;
10717 	struct bpf_func_state *state, *parent;
10718 	int i, frame, err = 0;
10719 
10720 	if (vparent->curframe != vstate->curframe) {
10721 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10722 		     vparent->curframe, vstate->curframe);
10723 		return -EFAULT;
10724 	}
10725 	/* Propagate read liveness of registers... */
10726 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10727 	for (frame = 0; frame <= vstate->curframe; frame++) {
10728 		parent = vparent->frame[frame];
10729 		state = vstate->frame[frame];
10730 		parent_reg = parent->regs;
10731 		state_reg = state->regs;
10732 		/* We don't need to worry about FP liveness, it's read-only */
10733 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10734 			err = propagate_liveness_reg(env, &state_reg[i],
10735 						     &parent_reg[i]);
10736 			if (err < 0)
10737 				return err;
10738 			if (err == REG_LIVE_READ64)
10739 				mark_insn_zext(env, &parent_reg[i]);
10740 		}
10741 
10742 		/* Propagate stack slots. */
10743 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10744 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10745 			parent_reg = &parent->stack[i].spilled_ptr;
10746 			state_reg = &state->stack[i].spilled_ptr;
10747 			err = propagate_liveness_reg(env, state_reg,
10748 						     parent_reg);
10749 			if (err < 0)
10750 				return err;
10751 		}
10752 	}
10753 	return 0;
10754 }
10755 
10756 /* find precise scalars in the previous equivalent state and
10757  * propagate them into the current state
10758  */
10759 static int propagate_precision(struct bpf_verifier_env *env,
10760 			       const struct bpf_verifier_state *old)
10761 {
10762 	struct bpf_reg_state *state_reg;
10763 	struct bpf_func_state *state;
10764 	int i, err = 0;
10765 
10766 	state = old->frame[old->curframe];
10767 	state_reg = state->regs;
10768 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10769 		if (state_reg->type != SCALAR_VALUE ||
10770 		    !state_reg->precise)
10771 			continue;
10772 		if (env->log.level & BPF_LOG_LEVEL2)
10773 			verbose(env, "propagating r%d\n", i);
10774 		err = mark_chain_precision(env, i);
10775 		if (err < 0)
10776 			return err;
10777 	}
10778 
10779 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10780 		if (!is_spilled_reg(&state->stack[i]))
10781 			continue;
10782 		state_reg = &state->stack[i].spilled_ptr;
10783 		if (state_reg->type != SCALAR_VALUE ||
10784 		    !state_reg->precise)
10785 			continue;
10786 		if (env->log.level & BPF_LOG_LEVEL2)
10787 			verbose(env, "propagating fp%d\n",
10788 				(-i - 1) * BPF_REG_SIZE);
10789 		err = mark_chain_precision_stack(env, i);
10790 		if (err < 0)
10791 			return err;
10792 	}
10793 	return 0;
10794 }
10795 
10796 static bool states_maybe_looping(struct bpf_verifier_state *old,
10797 				 struct bpf_verifier_state *cur)
10798 {
10799 	struct bpf_func_state *fold, *fcur;
10800 	int i, fr = cur->curframe;
10801 
10802 	if (old->curframe != fr)
10803 		return false;
10804 
10805 	fold = old->frame[fr];
10806 	fcur = cur->frame[fr];
10807 	for (i = 0; i < MAX_BPF_REG; i++)
10808 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10809 			   offsetof(struct bpf_reg_state, parent)))
10810 			return false;
10811 	return true;
10812 }
10813 
10814 
10815 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10816 {
10817 	struct bpf_verifier_state_list *new_sl;
10818 	struct bpf_verifier_state_list *sl, **pprev;
10819 	struct bpf_verifier_state *cur = env->cur_state, *new;
10820 	int i, j, err, states_cnt = 0;
10821 	bool add_new_state = env->test_state_freq ? true : false;
10822 
10823 	cur->last_insn_idx = env->prev_insn_idx;
10824 	if (!env->insn_aux_data[insn_idx].prune_point)
10825 		/* this 'insn_idx' instruction wasn't marked, so we will not
10826 		 * be doing state search here
10827 		 */
10828 		return 0;
10829 
10830 	/* bpf progs typically have pruning point every 4 instructions
10831 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10832 	 * Do not add new state for future pruning if the verifier hasn't seen
10833 	 * at least 2 jumps and at least 8 instructions.
10834 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10835 	 * In tests that amounts to up to 50% reduction into total verifier
10836 	 * memory consumption and 20% verifier time speedup.
10837 	 */
10838 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10839 	    env->insn_processed - env->prev_insn_processed >= 8)
10840 		add_new_state = true;
10841 
10842 	pprev = explored_state(env, insn_idx);
10843 	sl = *pprev;
10844 
10845 	clean_live_states(env, insn_idx, cur);
10846 
10847 	while (sl) {
10848 		states_cnt++;
10849 		if (sl->state.insn_idx != insn_idx)
10850 			goto next;
10851 
10852 		if (sl->state.branches) {
10853 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10854 
10855 			if (frame->in_async_callback_fn &&
10856 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10857 				/* Different async_entry_cnt means that the verifier is
10858 				 * processing another entry into async callback.
10859 				 * Seeing the same state is not an indication of infinite
10860 				 * loop or infinite recursion.
10861 				 * But finding the same state doesn't mean that it's safe
10862 				 * to stop processing the current state. The previous state
10863 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10864 				 * Checking in_async_callback_fn alone is not enough either.
10865 				 * Since the verifier still needs to catch infinite loops
10866 				 * inside async callbacks.
10867 				 */
10868 			} else if (states_maybe_looping(&sl->state, cur) &&
10869 				   states_equal(env, &sl->state, cur)) {
10870 				verbose_linfo(env, insn_idx, "; ");
10871 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10872 				return -EINVAL;
10873 			}
10874 			/* if the verifier is processing a loop, avoid adding new state
10875 			 * too often, since different loop iterations have distinct
10876 			 * states and may not help future pruning.
10877 			 * This threshold shouldn't be too low to make sure that
10878 			 * a loop with large bound will be rejected quickly.
10879 			 * The most abusive loop will be:
10880 			 * r1 += 1
10881 			 * if r1 < 1000000 goto pc-2
10882 			 * 1M insn_procssed limit / 100 == 10k peak states.
10883 			 * This threshold shouldn't be too high either, since states
10884 			 * at the end of the loop are likely to be useful in pruning.
10885 			 */
10886 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10887 			    env->insn_processed - env->prev_insn_processed < 100)
10888 				add_new_state = false;
10889 			goto miss;
10890 		}
10891 		if (states_equal(env, &sl->state, cur)) {
10892 			sl->hit_cnt++;
10893 			/* reached equivalent register/stack state,
10894 			 * prune the search.
10895 			 * Registers read by the continuation are read by us.
10896 			 * If we have any write marks in env->cur_state, they
10897 			 * will prevent corresponding reads in the continuation
10898 			 * from reaching our parent (an explored_state).  Our
10899 			 * own state will get the read marks recorded, but
10900 			 * they'll be immediately forgotten as we're pruning
10901 			 * this state and will pop a new one.
10902 			 */
10903 			err = propagate_liveness(env, &sl->state, cur);
10904 
10905 			/* if previous state reached the exit with precision and
10906 			 * current state is equivalent to it (except precsion marks)
10907 			 * the precision needs to be propagated back in
10908 			 * the current state.
10909 			 */
10910 			err = err ? : push_jmp_history(env, cur);
10911 			err = err ? : propagate_precision(env, &sl->state);
10912 			if (err)
10913 				return err;
10914 			return 1;
10915 		}
10916 miss:
10917 		/* when new state is not going to be added do not increase miss count.
10918 		 * Otherwise several loop iterations will remove the state
10919 		 * recorded earlier. The goal of these heuristics is to have
10920 		 * states from some iterations of the loop (some in the beginning
10921 		 * and some at the end) to help pruning.
10922 		 */
10923 		if (add_new_state)
10924 			sl->miss_cnt++;
10925 		/* heuristic to determine whether this state is beneficial
10926 		 * to keep checking from state equivalence point of view.
10927 		 * Higher numbers increase max_states_per_insn and verification time,
10928 		 * but do not meaningfully decrease insn_processed.
10929 		 */
10930 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10931 			/* the state is unlikely to be useful. Remove it to
10932 			 * speed up verification
10933 			 */
10934 			*pprev = sl->next;
10935 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10936 				u32 br = sl->state.branches;
10937 
10938 				WARN_ONCE(br,
10939 					  "BUG live_done but branches_to_explore %d\n",
10940 					  br);
10941 				free_verifier_state(&sl->state, false);
10942 				kfree(sl);
10943 				env->peak_states--;
10944 			} else {
10945 				/* cannot free this state, since parentage chain may
10946 				 * walk it later. Add it for free_list instead to
10947 				 * be freed at the end of verification
10948 				 */
10949 				sl->next = env->free_list;
10950 				env->free_list = sl;
10951 			}
10952 			sl = *pprev;
10953 			continue;
10954 		}
10955 next:
10956 		pprev = &sl->next;
10957 		sl = *pprev;
10958 	}
10959 
10960 	if (env->max_states_per_insn < states_cnt)
10961 		env->max_states_per_insn = states_cnt;
10962 
10963 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10964 		return push_jmp_history(env, cur);
10965 
10966 	if (!add_new_state)
10967 		return push_jmp_history(env, cur);
10968 
10969 	/* There were no equivalent states, remember the current one.
10970 	 * Technically the current state is not proven to be safe yet,
10971 	 * but it will either reach outer most bpf_exit (which means it's safe)
10972 	 * or it will be rejected. When there are no loops the verifier won't be
10973 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10974 	 * again on the way to bpf_exit.
10975 	 * When looping the sl->state.branches will be > 0 and this state
10976 	 * will not be considered for equivalence until branches == 0.
10977 	 */
10978 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10979 	if (!new_sl)
10980 		return -ENOMEM;
10981 	env->total_states++;
10982 	env->peak_states++;
10983 	env->prev_jmps_processed = env->jmps_processed;
10984 	env->prev_insn_processed = env->insn_processed;
10985 
10986 	/* add new state to the head of linked list */
10987 	new = &new_sl->state;
10988 	err = copy_verifier_state(new, cur);
10989 	if (err) {
10990 		free_verifier_state(new, false);
10991 		kfree(new_sl);
10992 		return err;
10993 	}
10994 	new->insn_idx = insn_idx;
10995 	WARN_ONCE(new->branches != 1,
10996 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10997 
10998 	cur->parent = new;
10999 	cur->first_insn_idx = insn_idx;
11000 	clear_jmp_history(cur);
11001 	new_sl->next = *explored_state(env, insn_idx);
11002 	*explored_state(env, insn_idx) = new_sl;
11003 	/* connect new state to parentage chain. Current frame needs all
11004 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
11005 	 * to the stack implicitly by JITs) so in callers' frames connect just
11006 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11007 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11008 	 * from callee with its full parentage chain, anyway.
11009 	 */
11010 	/* clear write marks in current state: the writes we did are not writes
11011 	 * our child did, so they don't screen off its reads from us.
11012 	 * (There are no read marks in current state, because reads always mark
11013 	 * their parent and current state never has children yet.  Only
11014 	 * explored_states can get read marks.)
11015 	 */
11016 	for (j = 0; j <= cur->curframe; j++) {
11017 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11018 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11019 		for (i = 0; i < BPF_REG_FP; i++)
11020 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11021 	}
11022 
11023 	/* all stack frames are accessible from callee, clear them all */
11024 	for (j = 0; j <= cur->curframe; j++) {
11025 		struct bpf_func_state *frame = cur->frame[j];
11026 		struct bpf_func_state *newframe = new->frame[j];
11027 
11028 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11029 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11030 			frame->stack[i].spilled_ptr.parent =
11031 						&newframe->stack[i].spilled_ptr;
11032 		}
11033 	}
11034 	return 0;
11035 }
11036 
11037 /* Return true if it's OK to have the same insn return a different type. */
11038 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11039 {
11040 	switch (type) {
11041 	case PTR_TO_CTX:
11042 	case PTR_TO_SOCKET:
11043 	case PTR_TO_SOCKET_OR_NULL:
11044 	case PTR_TO_SOCK_COMMON:
11045 	case PTR_TO_SOCK_COMMON_OR_NULL:
11046 	case PTR_TO_TCP_SOCK:
11047 	case PTR_TO_TCP_SOCK_OR_NULL:
11048 	case PTR_TO_XDP_SOCK:
11049 	case PTR_TO_BTF_ID:
11050 	case PTR_TO_BTF_ID_OR_NULL:
11051 		return false;
11052 	default:
11053 		return true;
11054 	}
11055 }
11056 
11057 /* If an instruction was previously used with particular pointer types, then we
11058  * need to be careful to avoid cases such as the below, where it may be ok
11059  * for one branch accessing the pointer, but not ok for the other branch:
11060  *
11061  * R1 = sock_ptr
11062  * goto X;
11063  * ...
11064  * R1 = some_other_valid_ptr;
11065  * goto X;
11066  * ...
11067  * R2 = *(u32 *)(R1 + 0);
11068  */
11069 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11070 {
11071 	return src != prev && (!reg_type_mismatch_ok(src) ||
11072 			       !reg_type_mismatch_ok(prev));
11073 }
11074 
11075 static int do_check(struct bpf_verifier_env *env)
11076 {
11077 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11078 	struct bpf_verifier_state *state = env->cur_state;
11079 	struct bpf_insn *insns = env->prog->insnsi;
11080 	struct bpf_reg_state *regs;
11081 	int insn_cnt = env->prog->len;
11082 	bool do_print_state = false;
11083 	int prev_insn_idx = -1;
11084 
11085 	for (;;) {
11086 		struct bpf_insn *insn;
11087 		u8 class;
11088 		int err;
11089 
11090 		env->prev_insn_idx = prev_insn_idx;
11091 		if (env->insn_idx >= insn_cnt) {
11092 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11093 				env->insn_idx, insn_cnt);
11094 			return -EFAULT;
11095 		}
11096 
11097 		insn = &insns[env->insn_idx];
11098 		class = BPF_CLASS(insn->code);
11099 
11100 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11101 			verbose(env,
11102 				"BPF program is too large. Processed %d insn\n",
11103 				env->insn_processed);
11104 			return -E2BIG;
11105 		}
11106 
11107 		err = is_state_visited(env, env->insn_idx);
11108 		if (err < 0)
11109 			return err;
11110 		if (err == 1) {
11111 			/* found equivalent state, can prune the search */
11112 			if (env->log.level & BPF_LOG_LEVEL) {
11113 				if (do_print_state)
11114 					verbose(env, "\nfrom %d to %d%s: safe\n",
11115 						env->prev_insn_idx, env->insn_idx,
11116 						env->cur_state->speculative ?
11117 						" (speculative execution)" : "");
11118 				else
11119 					verbose(env, "%d: safe\n", env->insn_idx);
11120 			}
11121 			goto process_bpf_exit;
11122 		}
11123 
11124 		if (signal_pending(current))
11125 			return -EAGAIN;
11126 
11127 		if (need_resched())
11128 			cond_resched();
11129 
11130 		if (env->log.level & BPF_LOG_LEVEL2 ||
11131 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
11132 			if (env->log.level & BPF_LOG_LEVEL2)
11133 				verbose(env, "%d:", env->insn_idx);
11134 			else
11135 				verbose(env, "\nfrom %d to %d%s:",
11136 					env->prev_insn_idx, env->insn_idx,
11137 					env->cur_state->speculative ?
11138 					" (speculative execution)" : "");
11139 			print_verifier_state(env, state->frame[state->curframe]);
11140 			do_print_state = false;
11141 		}
11142 
11143 		if (env->log.level & BPF_LOG_LEVEL) {
11144 			const struct bpf_insn_cbs cbs = {
11145 				.cb_call	= disasm_kfunc_name,
11146 				.cb_print	= verbose,
11147 				.private_data	= env,
11148 			};
11149 
11150 			verbose_linfo(env, env->insn_idx, "; ");
11151 			verbose(env, "%d: ", env->insn_idx);
11152 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11153 		}
11154 
11155 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11156 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11157 							   env->prev_insn_idx);
11158 			if (err)
11159 				return err;
11160 		}
11161 
11162 		regs = cur_regs(env);
11163 		sanitize_mark_insn_seen(env);
11164 		prev_insn_idx = env->insn_idx;
11165 
11166 		if (class == BPF_ALU || class == BPF_ALU64) {
11167 			err = check_alu_op(env, insn);
11168 			if (err)
11169 				return err;
11170 
11171 		} else if (class == BPF_LDX) {
11172 			enum bpf_reg_type *prev_src_type, src_reg_type;
11173 
11174 			/* check for reserved fields is already done */
11175 
11176 			/* check src operand */
11177 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11178 			if (err)
11179 				return err;
11180 
11181 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11182 			if (err)
11183 				return err;
11184 
11185 			src_reg_type = regs[insn->src_reg].type;
11186 
11187 			/* check that memory (src_reg + off) is readable,
11188 			 * the state of dst_reg will be updated by this func
11189 			 */
11190 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11191 					       insn->off, BPF_SIZE(insn->code),
11192 					       BPF_READ, insn->dst_reg, false);
11193 			if (err)
11194 				return err;
11195 
11196 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11197 
11198 			if (*prev_src_type == NOT_INIT) {
11199 				/* saw a valid insn
11200 				 * dst_reg = *(u32 *)(src_reg + off)
11201 				 * save type to validate intersecting paths
11202 				 */
11203 				*prev_src_type = src_reg_type;
11204 
11205 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11206 				/* ABuser program is trying to use the same insn
11207 				 * dst_reg = *(u32*) (src_reg + off)
11208 				 * with different pointer types:
11209 				 * src_reg == ctx in one branch and
11210 				 * src_reg == stack|map in some other branch.
11211 				 * Reject it.
11212 				 */
11213 				verbose(env, "same insn cannot be used with different pointers\n");
11214 				return -EINVAL;
11215 			}
11216 
11217 		} else if (class == BPF_STX) {
11218 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11219 
11220 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11221 				err = check_atomic(env, env->insn_idx, insn);
11222 				if (err)
11223 					return err;
11224 				env->insn_idx++;
11225 				continue;
11226 			}
11227 
11228 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11229 				verbose(env, "BPF_STX uses reserved fields\n");
11230 				return -EINVAL;
11231 			}
11232 
11233 			/* check src1 operand */
11234 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11235 			if (err)
11236 				return err;
11237 			/* check src2 operand */
11238 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11239 			if (err)
11240 				return err;
11241 
11242 			dst_reg_type = regs[insn->dst_reg].type;
11243 
11244 			/* check that memory (dst_reg + off) is writeable */
11245 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11246 					       insn->off, BPF_SIZE(insn->code),
11247 					       BPF_WRITE, insn->src_reg, false);
11248 			if (err)
11249 				return err;
11250 
11251 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11252 
11253 			if (*prev_dst_type == NOT_INIT) {
11254 				*prev_dst_type = dst_reg_type;
11255 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11256 				verbose(env, "same insn cannot be used with different pointers\n");
11257 				return -EINVAL;
11258 			}
11259 
11260 		} else if (class == BPF_ST) {
11261 			if (BPF_MODE(insn->code) != BPF_MEM ||
11262 			    insn->src_reg != BPF_REG_0) {
11263 				verbose(env, "BPF_ST uses reserved fields\n");
11264 				return -EINVAL;
11265 			}
11266 			/* check src operand */
11267 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11268 			if (err)
11269 				return err;
11270 
11271 			if (is_ctx_reg(env, insn->dst_reg)) {
11272 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11273 					insn->dst_reg,
11274 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
11275 				return -EACCES;
11276 			}
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, -1, false);
11282 			if (err)
11283 				return err;
11284 
11285 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11286 			u8 opcode = BPF_OP(insn->code);
11287 
11288 			env->jmps_processed++;
11289 			if (opcode == BPF_CALL) {
11290 				if (BPF_SRC(insn->code) != BPF_K ||
11291 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11292 				     && insn->off != 0) ||
11293 				    (insn->src_reg != BPF_REG_0 &&
11294 				     insn->src_reg != BPF_PSEUDO_CALL &&
11295 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11296 				    insn->dst_reg != BPF_REG_0 ||
11297 				    class == BPF_JMP32) {
11298 					verbose(env, "BPF_CALL uses reserved fields\n");
11299 					return -EINVAL;
11300 				}
11301 
11302 				if (env->cur_state->active_spin_lock &&
11303 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11304 				     insn->imm != BPF_FUNC_spin_unlock)) {
11305 					verbose(env, "function calls are not allowed while holding a lock\n");
11306 					return -EINVAL;
11307 				}
11308 				if (insn->src_reg == BPF_PSEUDO_CALL)
11309 					err = check_func_call(env, insn, &env->insn_idx);
11310 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11311 					err = check_kfunc_call(env, insn);
11312 				else
11313 					err = check_helper_call(env, insn, &env->insn_idx);
11314 				if (err)
11315 					return err;
11316 			} else if (opcode == BPF_JA) {
11317 				if (BPF_SRC(insn->code) != BPF_K ||
11318 				    insn->imm != 0 ||
11319 				    insn->src_reg != BPF_REG_0 ||
11320 				    insn->dst_reg != BPF_REG_0 ||
11321 				    class == BPF_JMP32) {
11322 					verbose(env, "BPF_JA uses reserved fields\n");
11323 					return -EINVAL;
11324 				}
11325 
11326 				env->insn_idx += insn->off + 1;
11327 				continue;
11328 
11329 			} else if (opcode == BPF_EXIT) {
11330 				if (BPF_SRC(insn->code) != BPF_K ||
11331 				    insn->imm != 0 ||
11332 				    insn->src_reg != BPF_REG_0 ||
11333 				    insn->dst_reg != BPF_REG_0 ||
11334 				    class == BPF_JMP32) {
11335 					verbose(env, "BPF_EXIT uses reserved fields\n");
11336 					return -EINVAL;
11337 				}
11338 
11339 				if (env->cur_state->active_spin_lock) {
11340 					verbose(env, "bpf_spin_unlock is missing\n");
11341 					return -EINVAL;
11342 				}
11343 
11344 				if (state->curframe) {
11345 					/* exit from nested function */
11346 					err = prepare_func_exit(env, &env->insn_idx);
11347 					if (err)
11348 						return err;
11349 					do_print_state = true;
11350 					continue;
11351 				}
11352 
11353 				err = check_reference_leak(env);
11354 				if (err)
11355 					return err;
11356 
11357 				err = check_return_code(env);
11358 				if (err)
11359 					return err;
11360 process_bpf_exit:
11361 				update_branch_counts(env, env->cur_state);
11362 				err = pop_stack(env, &prev_insn_idx,
11363 						&env->insn_idx, pop_log);
11364 				if (err < 0) {
11365 					if (err != -ENOENT)
11366 						return err;
11367 					break;
11368 				} else {
11369 					do_print_state = true;
11370 					continue;
11371 				}
11372 			} else {
11373 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11374 				if (err)
11375 					return err;
11376 			}
11377 		} else if (class == BPF_LD) {
11378 			u8 mode = BPF_MODE(insn->code);
11379 
11380 			if (mode == BPF_ABS || mode == BPF_IND) {
11381 				err = check_ld_abs(env, insn);
11382 				if (err)
11383 					return err;
11384 
11385 			} else if (mode == BPF_IMM) {
11386 				err = check_ld_imm(env, insn);
11387 				if (err)
11388 					return err;
11389 
11390 				env->insn_idx++;
11391 				sanitize_mark_insn_seen(env);
11392 			} else {
11393 				verbose(env, "invalid BPF_LD mode\n");
11394 				return -EINVAL;
11395 			}
11396 		} else {
11397 			verbose(env, "unknown insn class %d\n", class);
11398 			return -EINVAL;
11399 		}
11400 
11401 		env->insn_idx++;
11402 	}
11403 
11404 	return 0;
11405 }
11406 
11407 static int find_btf_percpu_datasec(struct btf *btf)
11408 {
11409 	const struct btf_type *t;
11410 	const char *tname;
11411 	int i, n;
11412 
11413 	/*
11414 	 * Both vmlinux and module each have their own ".data..percpu"
11415 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11416 	 * types to look at only module's own BTF types.
11417 	 */
11418 	n = btf_nr_types(btf);
11419 	if (btf_is_module(btf))
11420 		i = btf_nr_types(btf_vmlinux);
11421 	else
11422 		i = 1;
11423 
11424 	for(; i < n; i++) {
11425 		t = btf_type_by_id(btf, i);
11426 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11427 			continue;
11428 
11429 		tname = btf_name_by_offset(btf, t->name_off);
11430 		if (!strcmp(tname, ".data..percpu"))
11431 			return i;
11432 	}
11433 
11434 	return -ENOENT;
11435 }
11436 
11437 /* replace pseudo btf_id with kernel symbol address */
11438 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11439 			       struct bpf_insn *insn,
11440 			       struct bpf_insn_aux_data *aux)
11441 {
11442 	const struct btf_var_secinfo *vsi;
11443 	const struct btf_type *datasec;
11444 	struct btf_mod_pair *btf_mod;
11445 	const struct btf_type *t;
11446 	const char *sym_name;
11447 	bool percpu = false;
11448 	u32 type, id = insn->imm;
11449 	struct btf *btf;
11450 	s32 datasec_id;
11451 	u64 addr;
11452 	int i, btf_fd, err;
11453 
11454 	btf_fd = insn[1].imm;
11455 	if (btf_fd) {
11456 		btf = btf_get_by_fd(btf_fd);
11457 		if (IS_ERR(btf)) {
11458 			verbose(env, "invalid module BTF object FD specified.\n");
11459 			return -EINVAL;
11460 		}
11461 	} else {
11462 		if (!btf_vmlinux) {
11463 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11464 			return -EINVAL;
11465 		}
11466 		btf = btf_vmlinux;
11467 		btf_get(btf);
11468 	}
11469 
11470 	t = btf_type_by_id(btf, id);
11471 	if (!t) {
11472 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11473 		err = -ENOENT;
11474 		goto err_put;
11475 	}
11476 
11477 	if (!btf_type_is_var(t)) {
11478 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11479 		err = -EINVAL;
11480 		goto err_put;
11481 	}
11482 
11483 	sym_name = btf_name_by_offset(btf, t->name_off);
11484 	addr = kallsyms_lookup_name(sym_name);
11485 	if (!addr) {
11486 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11487 			sym_name);
11488 		err = -ENOENT;
11489 		goto err_put;
11490 	}
11491 
11492 	datasec_id = find_btf_percpu_datasec(btf);
11493 	if (datasec_id > 0) {
11494 		datasec = btf_type_by_id(btf, datasec_id);
11495 		for_each_vsi(i, datasec, vsi) {
11496 			if (vsi->type == id) {
11497 				percpu = true;
11498 				break;
11499 			}
11500 		}
11501 	}
11502 
11503 	insn[0].imm = (u32)addr;
11504 	insn[1].imm = addr >> 32;
11505 
11506 	type = t->type;
11507 	t = btf_type_skip_modifiers(btf, type, NULL);
11508 	if (percpu) {
11509 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11510 		aux->btf_var.btf = btf;
11511 		aux->btf_var.btf_id = type;
11512 	} else if (!btf_type_is_struct(t)) {
11513 		const struct btf_type *ret;
11514 		const char *tname;
11515 		u32 tsize;
11516 
11517 		/* resolve the type size of ksym. */
11518 		ret = btf_resolve_size(btf, t, &tsize);
11519 		if (IS_ERR(ret)) {
11520 			tname = btf_name_by_offset(btf, t->name_off);
11521 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11522 				tname, PTR_ERR(ret));
11523 			err = -EINVAL;
11524 			goto err_put;
11525 		}
11526 		aux->btf_var.reg_type = PTR_TO_MEM;
11527 		aux->btf_var.mem_size = tsize;
11528 	} else {
11529 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11530 		aux->btf_var.btf = btf;
11531 		aux->btf_var.btf_id = type;
11532 	}
11533 
11534 	/* check whether we recorded this BTF (and maybe module) already */
11535 	for (i = 0; i < env->used_btf_cnt; i++) {
11536 		if (env->used_btfs[i].btf == btf) {
11537 			btf_put(btf);
11538 			return 0;
11539 		}
11540 	}
11541 
11542 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11543 		err = -E2BIG;
11544 		goto err_put;
11545 	}
11546 
11547 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11548 	btf_mod->btf = btf;
11549 	btf_mod->module = NULL;
11550 
11551 	/* if we reference variables from kernel module, bump its refcount */
11552 	if (btf_is_module(btf)) {
11553 		btf_mod->module = btf_try_get_module(btf);
11554 		if (!btf_mod->module) {
11555 			err = -ENXIO;
11556 			goto err_put;
11557 		}
11558 	}
11559 
11560 	env->used_btf_cnt++;
11561 
11562 	return 0;
11563 err_put:
11564 	btf_put(btf);
11565 	return err;
11566 }
11567 
11568 static int check_map_prealloc(struct bpf_map *map)
11569 {
11570 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11571 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11572 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11573 		!(map->map_flags & BPF_F_NO_PREALLOC);
11574 }
11575 
11576 static bool is_tracing_prog_type(enum bpf_prog_type type)
11577 {
11578 	switch (type) {
11579 	case BPF_PROG_TYPE_KPROBE:
11580 	case BPF_PROG_TYPE_TRACEPOINT:
11581 	case BPF_PROG_TYPE_PERF_EVENT:
11582 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11583 		return true;
11584 	default:
11585 		return false;
11586 	}
11587 }
11588 
11589 static bool is_preallocated_map(struct bpf_map *map)
11590 {
11591 	if (!check_map_prealloc(map))
11592 		return false;
11593 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11594 		return false;
11595 	return true;
11596 }
11597 
11598 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11599 					struct bpf_map *map,
11600 					struct bpf_prog *prog)
11601 
11602 {
11603 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11604 	/*
11605 	 * Validate that trace type programs use preallocated hash maps.
11606 	 *
11607 	 * For programs attached to PERF events this is mandatory as the
11608 	 * perf NMI can hit any arbitrary code sequence.
11609 	 *
11610 	 * All other trace types using preallocated hash maps are unsafe as
11611 	 * well because tracepoint or kprobes can be inside locked regions
11612 	 * of the memory allocator or at a place where a recursion into the
11613 	 * memory allocator would see inconsistent state.
11614 	 *
11615 	 * On RT enabled kernels run-time allocation of all trace type
11616 	 * programs is strictly prohibited due to lock type constraints. On
11617 	 * !RT kernels it is allowed for backwards compatibility reasons for
11618 	 * now, but warnings are emitted so developers are made aware of
11619 	 * the unsafety and can fix their programs before this is enforced.
11620 	 */
11621 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11622 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11623 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11624 			return -EINVAL;
11625 		}
11626 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11627 			verbose(env, "trace type programs can only use preallocated hash map\n");
11628 			return -EINVAL;
11629 		}
11630 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11631 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11632 	}
11633 
11634 	if (map_value_has_spin_lock(map)) {
11635 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11636 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11637 			return -EINVAL;
11638 		}
11639 
11640 		if (is_tracing_prog_type(prog_type)) {
11641 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11642 			return -EINVAL;
11643 		}
11644 
11645 		if (prog->aux->sleepable) {
11646 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11647 			return -EINVAL;
11648 		}
11649 	}
11650 
11651 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11652 	    !bpf_offload_prog_map_match(prog, map)) {
11653 		verbose(env, "offload device mismatch between prog and map\n");
11654 		return -EINVAL;
11655 	}
11656 
11657 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11658 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11659 		return -EINVAL;
11660 	}
11661 
11662 	if (prog->aux->sleepable)
11663 		switch (map->map_type) {
11664 		case BPF_MAP_TYPE_HASH:
11665 		case BPF_MAP_TYPE_LRU_HASH:
11666 		case BPF_MAP_TYPE_ARRAY:
11667 		case BPF_MAP_TYPE_PERCPU_HASH:
11668 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11669 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11670 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11671 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11672 			if (!is_preallocated_map(map)) {
11673 				verbose(env,
11674 					"Sleepable programs can only use preallocated maps\n");
11675 				return -EINVAL;
11676 			}
11677 			break;
11678 		case BPF_MAP_TYPE_RINGBUF:
11679 			break;
11680 		default:
11681 			verbose(env,
11682 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11683 			return -EINVAL;
11684 		}
11685 
11686 	return 0;
11687 }
11688 
11689 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11690 {
11691 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11692 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11693 }
11694 
11695 /* find and rewrite pseudo imm in ld_imm64 instructions:
11696  *
11697  * 1. if it accesses map FD, replace it with actual map pointer.
11698  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11699  *
11700  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11701  */
11702 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11703 {
11704 	struct bpf_insn *insn = env->prog->insnsi;
11705 	int insn_cnt = env->prog->len;
11706 	int i, j, err;
11707 
11708 	err = bpf_prog_calc_tag(env->prog);
11709 	if (err)
11710 		return err;
11711 
11712 	for (i = 0; i < insn_cnt; i++, insn++) {
11713 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11714 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11715 			verbose(env, "BPF_LDX uses reserved fields\n");
11716 			return -EINVAL;
11717 		}
11718 
11719 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11720 			struct bpf_insn_aux_data *aux;
11721 			struct bpf_map *map;
11722 			struct fd f;
11723 			u64 addr;
11724 			u32 fd;
11725 
11726 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11727 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11728 			    insn[1].off != 0) {
11729 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11730 				return -EINVAL;
11731 			}
11732 
11733 			if (insn[0].src_reg == 0)
11734 				/* valid generic load 64-bit imm */
11735 				goto next_insn;
11736 
11737 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11738 				aux = &env->insn_aux_data[i];
11739 				err = check_pseudo_btf_id(env, insn, aux);
11740 				if (err)
11741 					return err;
11742 				goto next_insn;
11743 			}
11744 
11745 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11746 				aux = &env->insn_aux_data[i];
11747 				aux->ptr_type = PTR_TO_FUNC;
11748 				goto next_insn;
11749 			}
11750 
11751 			/* In final convert_pseudo_ld_imm64() step, this is
11752 			 * converted into regular 64-bit imm load insn.
11753 			 */
11754 			switch (insn[0].src_reg) {
11755 			case BPF_PSEUDO_MAP_VALUE:
11756 			case BPF_PSEUDO_MAP_IDX_VALUE:
11757 				break;
11758 			case BPF_PSEUDO_MAP_FD:
11759 			case BPF_PSEUDO_MAP_IDX:
11760 				if (insn[1].imm == 0)
11761 					break;
11762 				fallthrough;
11763 			default:
11764 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11765 				return -EINVAL;
11766 			}
11767 
11768 			switch (insn[0].src_reg) {
11769 			case BPF_PSEUDO_MAP_IDX_VALUE:
11770 			case BPF_PSEUDO_MAP_IDX:
11771 				if (bpfptr_is_null(env->fd_array)) {
11772 					verbose(env, "fd_idx without fd_array is invalid\n");
11773 					return -EPROTO;
11774 				}
11775 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11776 							    insn[0].imm * sizeof(fd),
11777 							    sizeof(fd)))
11778 					return -EFAULT;
11779 				break;
11780 			default:
11781 				fd = insn[0].imm;
11782 				break;
11783 			}
11784 
11785 			f = fdget(fd);
11786 			map = __bpf_map_get(f);
11787 			if (IS_ERR(map)) {
11788 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11789 					insn[0].imm);
11790 				return PTR_ERR(map);
11791 			}
11792 
11793 			err = check_map_prog_compatibility(env, map, env->prog);
11794 			if (err) {
11795 				fdput(f);
11796 				return err;
11797 			}
11798 
11799 			aux = &env->insn_aux_data[i];
11800 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11801 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11802 				addr = (unsigned long)map;
11803 			} else {
11804 				u32 off = insn[1].imm;
11805 
11806 				if (off >= BPF_MAX_VAR_OFF) {
11807 					verbose(env, "direct value offset of %u is not allowed\n", off);
11808 					fdput(f);
11809 					return -EINVAL;
11810 				}
11811 
11812 				if (!map->ops->map_direct_value_addr) {
11813 					verbose(env, "no direct value access support for this map type\n");
11814 					fdput(f);
11815 					return -EINVAL;
11816 				}
11817 
11818 				err = map->ops->map_direct_value_addr(map, &addr, off);
11819 				if (err) {
11820 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11821 						map->value_size, off);
11822 					fdput(f);
11823 					return err;
11824 				}
11825 
11826 				aux->map_off = off;
11827 				addr += off;
11828 			}
11829 
11830 			insn[0].imm = (u32)addr;
11831 			insn[1].imm = addr >> 32;
11832 
11833 			/* check whether we recorded this map already */
11834 			for (j = 0; j < env->used_map_cnt; j++) {
11835 				if (env->used_maps[j] == map) {
11836 					aux->map_index = j;
11837 					fdput(f);
11838 					goto next_insn;
11839 				}
11840 			}
11841 
11842 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11843 				fdput(f);
11844 				return -E2BIG;
11845 			}
11846 
11847 			/* hold the map. If the program is rejected by verifier,
11848 			 * the map will be released by release_maps() or it
11849 			 * will be used by the valid program until it's unloaded
11850 			 * and all maps are released in free_used_maps()
11851 			 */
11852 			bpf_map_inc(map);
11853 
11854 			aux->map_index = env->used_map_cnt;
11855 			env->used_maps[env->used_map_cnt++] = map;
11856 
11857 			if (bpf_map_is_cgroup_storage(map) &&
11858 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11859 				verbose(env, "only one cgroup storage of each type is allowed\n");
11860 				fdput(f);
11861 				return -EBUSY;
11862 			}
11863 
11864 			fdput(f);
11865 next_insn:
11866 			insn++;
11867 			i++;
11868 			continue;
11869 		}
11870 
11871 		/* Basic sanity check before we invest more work here. */
11872 		if (!bpf_opcode_in_insntable(insn->code)) {
11873 			verbose(env, "unknown opcode %02x\n", insn->code);
11874 			return -EINVAL;
11875 		}
11876 	}
11877 
11878 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11879 	 * 'struct bpf_map *' into a register instead of user map_fd.
11880 	 * These pointers will be used later by verifier to validate map access.
11881 	 */
11882 	return 0;
11883 }
11884 
11885 /* drop refcnt of maps used by the rejected program */
11886 static void release_maps(struct bpf_verifier_env *env)
11887 {
11888 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11889 			     env->used_map_cnt);
11890 }
11891 
11892 /* drop refcnt of maps used by the rejected program */
11893 static void release_btfs(struct bpf_verifier_env *env)
11894 {
11895 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11896 			     env->used_btf_cnt);
11897 }
11898 
11899 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11900 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11901 {
11902 	struct bpf_insn *insn = env->prog->insnsi;
11903 	int insn_cnt = env->prog->len;
11904 	int i;
11905 
11906 	for (i = 0; i < insn_cnt; i++, insn++) {
11907 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11908 			continue;
11909 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11910 			continue;
11911 		insn->src_reg = 0;
11912 	}
11913 }
11914 
11915 /* single env->prog->insni[off] instruction was replaced with the range
11916  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11917  * [0, off) and [off, end) to new locations, so the patched range stays zero
11918  */
11919 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11920 				 struct bpf_insn_aux_data *new_data,
11921 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11922 {
11923 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11924 	struct bpf_insn *insn = new_prog->insnsi;
11925 	u32 old_seen = old_data[off].seen;
11926 	u32 prog_len;
11927 	int i;
11928 
11929 	/* aux info at OFF always needs adjustment, no matter fast path
11930 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11931 	 * original insn at old prog.
11932 	 */
11933 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11934 
11935 	if (cnt == 1)
11936 		return;
11937 	prog_len = new_prog->len;
11938 
11939 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11940 	memcpy(new_data + off + cnt - 1, old_data + off,
11941 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11942 	for (i = off; i < off + cnt - 1; i++) {
11943 		/* Expand insni[off]'s seen count to the patched range. */
11944 		new_data[i].seen = old_seen;
11945 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11946 	}
11947 	env->insn_aux_data = new_data;
11948 	vfree(old_data);
11949 }
11950 
11951 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11952 {
11953 	int i;
11954 
11955 	if (len == 1)
11956 		return;
11957 	/* NOTE: fake 'exit' subprog should be updated as well. */
11958 	for (i = 0; i <= env->subprog_cnt; i++) {
11959 		if (env->subprog_info[i].start <= off)
11960 			continue;
11961 		env->subprog_info[i].start += len - 1;
11962 	}
11963 }
11964 
11965 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11966 {
11967 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11968 	int i, sz = prog->aux->size_poke_tab;
11969 	struct bpf_jit_poke_descriptor *desc;
11970 
11971 	for (i = 0; i < sz; i++) {
11972 		desc = &tab[i];
11973 		if (desc->insn_idx <= off)
11974 			continue;
11975 		desc->insn_idx += len - 1;
11976 	}
11977 }
11978 
11979 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11980 					    const struct bpf_insn *patch, u32 len)
11981 {
11982 	struct bpf_prog *new_prog;
11983 	struct bpf_insn_aux_data *new_data = NULL;
11984 
11985 	if (len > 1) {
11986 		new_data = vzalloc(array_size(env->prog->len + len - 1,
11987 					      sizeof(struct bpf_insn_aux_data)));
11988 		if (!new_data)
11989 			return NULL;
11990 	}
11991 
11992 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11993 	if (IS_ERR(new_prog)) {
11994 		if (PTR_ERR(new_prog) == -ERANGE)
11995 			verbose(env,
11996 				"insn %d cannot be patched due to 16-bit range\n",
11997 				env->insn_aux_data[off].orig_idx);
11998 		vfree(new_data);
11999 		return NULL;
12000 	}
12001 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12002 	adjust_subprog_starts(env, off, len);
12003 	adjust_poke_descs(new_prog, off, len);
12004 	return new_prog;
12005 }
12006 
12007 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12008 					      u32 off, u32 cnt)
12009 {
12010 	int i, j;
12011 
12012 	/* find first prog starting at or after off (first to remove) */
12013 	for (i = 0; i < env->subprog_cnt; i++)
12014 		if (env->subprog_info[i].start >= off)
12015 			break;
12016 	/* find first prog starting at or after off + cnt (first to stay) */
12017 	for (j = i; j < env->subprog_cnt; j++)
12018 		if (env->subprog_info[j].start >= off + cnt)
12019 			break;
12020 	/* if j doesn't start exactly at off + cnt, we are just removing
12021 	 * the front of previous prog
12022 	 */
12023 	if (env->subprog_info[j].start != off + cnt)
12024 		j--;
12025 
12026 	if (j > i) {
12027 		struct bpf_prog_aux *aux = env->prog->aux;
12028 		int move;
12029 
12030 		/* move fake 'exit' subprog as well */
12031 		move = env->subprog_cnt + 1 - j;
12032 
12033 		memmove(env->subprog_info + i,
12034 			env->subprog_info + j,
12035 			sizeof(*env->subprog_info) * move);
12036 		env->subprog_cnt -= j - i;
12037 
12038 		/* remove func_info */
12039 		if (aux->func_info) {
12040 			move = aux->func_info_cnt - j;
12041 
12042 			memmove(aux->func_info + i,
12043 				aux->func_info + j,
12044 				sizeof(*aux->func_info) * move);
12045 			aux->func_info_cnt -= j - i;
12046 			/* func_info->insn_off is set after all code rewrites,
12047 			 * in adjust_btf_func() - no need to adjust
12048 			 */
12049 		}
12050 	} else {
12051 		/* convert i from "first prog to remove" to "first to adjust" */
12052 		if (env->subprog_info[i].start == off)
12053 			i++;
12054 	}
12055 
12056 	/* update fake 'exit' subprog as well */
12057 	for (; i <= env->subprog_cnt; i++)
12058 		env->subprog_info[i].start -= cnt;
12059 
12060 	return 0;
12061 }
12062 
12063 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12064 				      u32 cnt)
12065 {
12066 	struct bpf_prog *prog = env->prog;
12067 	u32 i, l_off, l_cnt, nr_linfo;
12068 	struct bpf_line_info *linfo;
12069 
12070 	nr_linfo = prog->aux->nr_linfo;
12071 	if (!nr_linfo)
12072 		return 0;
12073 
12074 	linfo = prog->aux->linfo;
12075 
12076 	/* find first line info to remove, count lines to be removed */
12077 	for (i = 0; i < nr_linfo; i++)
12078 		if (linfo[i].insn_off >= off)
12079 			break;
12080 
12081 	l_off = i;
12082 	l_cnt = 0;
12083 	for (; i < nr_linfo; i++)
12084 		if (linfo[i].insn_off < off + cnt)
12085 			l_cnt++;
12086 		else
12087 			break;
12088 
12089 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12090 	 * last removed linfo.  prog is already modified, so prog->len == off
12091 	 * means no live instructions after (tail of the program was removed).
12092 	 */
12093 	if (prog->len != off && l_cnt &&
12094 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12095 		l_cnt--;
12096 		linfo[--i].insn_off = off + cnt;
12097 	}
12098 
12099 	/* remove the line info which refer to the removed instructions */
12100 	if (l_cnt) {
12101 		memmove(linfo + l_off, linfo + i,
12102 			sizeof(*linfo) * (nr_linfo - i));
12103 
12104 		prog->aux->nr_linfo -= l_cnt;
12105 		nr_linfo = prog->aux->nr_linfo;
12106 	}
12107 
12108 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12109 	for (i = l_off; i < nr_linfo; i++)
12110 		linfo[i].insn_off -= cnt;
12111 
12112 	/* fix up all subprogs (incl. 'exit') which start >= off */
12113 	for (i = 0; i <= env->subprog_cnt; i++)
12114 		if (env->subprog_info[i].linfo_idx > l_off) {
12115 			/* program may have started in the removed region but
12116 			 * may not be fully removed
12117 			 */
12118 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12119 				env->subprog_info[i].linfo_idx -= l_cnt;
12120 			else
12121 				env->subprog_info[i].linfo_idx = l_off;
12122 		}
12123 
12124 	return 0;
12125 }
12126 
12127 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12128 {
12129 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12130 	unsigned int orig_prog_len = env->prog->len;
12131 	int err;
12132 
12133 	if (bpf_prog_is_dev_bound(env->prog->aux))
12134 		bpf_prog_offload_remove_insns(env, off, cnt);
12135 
12136 	err = bpf_remove_insns(env->prog, off, cnt);
12137 	if (err)
12138 		return err;
12139 
12140 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12141 	if (err)
12142 		return err;
12143 
12144 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12145 	if (err)
12146 		return err;
12147 
12148 	memmove(aux_data + off,	aux_data + off + cnt,
12149 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12150 
12151 	return 0;
12152 }
12153 
12154 /* The verifier does more data flow analysis than llvm and will not
12155  * explore branches that are dead at run time. Malicious programs can
12156  * have dead code too. Therefore replace all dead at-run-time code
12157  * with 'ja -1'.
12158  *
12159  * Just nops are not optimal, e.g. if they would sit at the end of the
12160  * program and through another bug we would manage to jump there, then
12161  * we'd execute beyond program memory otherwise. Returning exception
12162  * code also wouldn't work since we can have subprogs where the dead
12163  * code could be located.
12164  */
12165 static void sanitize_dead_code(struct bpf_verifier_env *env)
12166 {
12167 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12168 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12169 	struct bpf_insn *insn = env->prog->insnsi;
12170 	const int insn_cnt = env->prog->len;
12171 	int i;
12172 
12173 	for (i = 0; i < insn_cnt; i++) {
12174 		if (aux_data[i].seen)
12175 			continue;
12176 		memcpy(insn + i, &trap, sizeof(trap));
12177 		aux_data[i].zext_dst = false;
12178 	}
12179 }
12180 
12181 static bool insn_is_cond_jump(u8 code)
12182 {
12183 	u8 op;
12184 
12185 	if (BPF_CLASS(code) == BPF_JMP32)
12186 		return true;
12187 
12188 	if (BPF_CLASS(code) != BPF_JMP)
12189 		return false;
12190 
12191 	op = BPF_OP(code);
12192 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12193 }
12194 
12195 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12196 {
12197 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12198 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12199 	struct bpf_insn *insn = env->prog->insnsi;
12200 	const int insn_cnt = env->prog->len;
12201 	int i;
12202 
12203 	for (i = 0; i < insn_cnt; i++, insn++) {
12204 		if (!insn_is_cond_jump(insn->code))
12205 			continue;
12206 
12207 		if (!aux_data[i + 1].seen)
12208 			ja.off = insn->off;
12209 		else if (!aux_data[i + 1 + insn->off].seen)
12210 			ja.off = 0;
12211 		else
12212 			continue;
12213 
12214 		if (bpf_prog_is_dev_bound(env->prog->aux))
12215 			bpf_prog_offload_replace_insn(env, i, &ja);
12216 
12217 		memcpy(insn, &ja, sizeof(ja));
12218 	}
12219 }
12220 
12221 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12222 {
12223 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12224 	int insn_cnt = env->prog->len;
12225 	int i, err;
12226 
12227 	for (i = 0; i < insn_cnt; i++) {
12228 		int j;
12229 
12230 		j = 0;
12231 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12232 			j++;
12233 		if (!j)
12234 			continue;
12235 
12236 		err = verifier_remove_insns(env, i, j);
12237 		if (err)
12238 			return err;
12239 		insn_cnt = env->prog->len;
12240 	}
12241 
12242 	return 0;
12243 }
12244 
12245 static int opt_remove_nops(struct bpf_verifier_env *env)
12246 {
12247 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12248 	struct bpf_insn *insn = env->prog->insnsi;
12249 	int insn_cnt = env->prog->len;
12250 	int i, err;
12251 
12252 	for (i = 0; i < insn_cnt; i++) {
12253 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12254 			continue;
12255 
12256 		err = verifier_remove_insns(env, i, 1);
12257 		if (err)
12258 			return err;
12259 		insn_cnt--;
12260 		i--;
12261 	}
12262 
12263 	return 0;
12264 }
12265 
12266 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12267 					 const union bpf_attr *attr)
12268 {
12269 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12270 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12271 	int i, patch_len, delta = 0, len = env->prog->len;
12272 	struct bpf_insn *insns = env->prog->insnsi;
12273 	struct bpf_prog *new_prog;
12274 	bool rnd_hi32;
12275 
12276 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12277 	zext_patch[1] = BPF_ZEXT_REG(0);
12278 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12279 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12280 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12281 	for (i = 0; i < len; i++) {
12282 		int adj_idx = i + delta;
12283 		struct bpf_insn insn;
12284 		int load_reg;
12285 
12286 		insn = insns[adj_idx];
12287 		load_reg = insn_def_regno(&insn);
12288 		if (!aux[adj_idx].zext_dst) {
12289 			u8 code, class;
12290 			u32 imm_rnd;
12291 
12292 			if (!rnd_hi32)
12293 				continue;
12294 
12295 			code = insn.code;
12296 			class = BPF_CLASS(code);
12297 			if (load_reg == -1)
12298 				continue;
12299 
12300 			/* NOTE: arg "reg" (the fourth one) is only used for
12301 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12302 			 *       here.
12303 			 */
12304 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12305 				if (class == BPF_LD &&
12306 				    BPF_MODE(code) == BPF_IMM)
12307 					i++;
12308 				continue;
12309 			}
12310 
12311 			/* ctx load could be transformed into wider load. */
12312 			if (class == BPF_LDX &&
12313 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12314 				continue;
12315 
12316 			imm_rnd = get_random_int();
12317 			rnd_hi32_patch[0] = insn;
12318 			rnd_hi32_patch[1].imm = imm_rnd;
12319 			rnd_hi32_patch[3].dst_reg = load_reg;
12320 			patch = rnd_hi32_patch;
12321 			patch_len = 4;
12322 			goto apply_patch_buffer;
12323 		}
12324 
12325 		/* Add in an zero-extend instruction if a) the JIT has requested
12326 		 * it or b) it's a CMPXCHG.
12327 		 *
12328 		 * The latter is because: BPF_CMPXCHG always loads a value into
12329 		 * R0, therefore always zero-extends. However some archs'
12330 		 * equivalent instruction only does this load when the
12331 		 * comparison is successful. This detail of CMPXCHG is
12332 		 * orthogonal to the general zero-extension behaviour of the
12333 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12334 		 */
12335 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12336 			continue;
12337 
12338 		if (WARN_ON(load_reg == -1)) {
12339 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12340 			return -EFAULT;
12341 		}
12342 
12343 		zext_patch[0] = insn;
12344 		zext_patch[1].dst_reg = load_reg;
12345 		zext_patch[1].src_reg = load_reg;
12346 		patch = zext_patch;
12347 		patch_len = 2;
12348 apply_patch_buffer:
12349 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12350 		if (!new_prog)
12351 			return -ENOMEM;
12352 		env->prog = new_prog;
12353 		insns = new_prog->insnsi;
12354 		aux = env->insn_aux_data;
12355 		delta += patch_len - 1;
12356 	}
12357 
12358 	return 0;
12359 }
12360 
12361 /* convert load instructions that access fields of a context type into a
12362  * sequence of instructions that access fields of the underlying structure:
12363  *     struct __sk_buff    -> struct sk_buff
12364  *     struct bpf_sock_ops -> struct sock
12365  */
12366 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12367 {
12368 	const struct bpf_verifier_ops *ops = env->ops;
12369 	int i, cnt, size, ctx_field_size, delta = 0;
12370 	const int insn_cnt = env->prog->len;
12371 	struct bpf_insn insn_buf[16], *insn;
12372 	u32 target_size, size_default, off;
12373 	struct bpf_prog *new_prog;
12374 	enum bpf_access_type type;
12375 	bool is_narrower_load;
12376 
12377 	if (ops->gen_prologue || env->seen_direct_write) {
12378 		if (!ops->gen_prologue) {
12379 			verbose(env, "bpf verifier is misconfigured\n");
12380 			return -EINVAL;
12381 		}
12382 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12383 					env->prog);
12384 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12385 			verbose(env, "bpf verifier is misconfigured\n");
12386 			return -EINVAL;
12387 		} else if (cnt) {
12388 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12389 			if (!new_prog)
12390 				return -ENOMEM;
12391 
12392 			env->prog = new_prog;
12393 			delta += cnt - 1;
12394 		}
12395 	}
12396 
12397 	if (bpf_prog_is_dev_bound(env->prog->aux))
12398 		return 0;
12399 
12400 	insn = env->prog->insnsi + delta;
12401 
12402 	for (i = 0; i < insn_cnt; i++, insn++) {
12403 		bpf_convert_ctx_access_t convert_ctx_access;
12404 		bool ctx_access;
12405 
12406 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12407 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12408 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12409 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12410 			type = BPF_READ;
12411 			ctx_access = true;
12412 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12413 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12414 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12415 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12416 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12417 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12418 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12419 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12420 			type = BPF_WRITE;
12421 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12422 		} else {
12423 			continue;
12424 		}
12425 
12426 		if (type == BPF_WRITE &&
12427 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12428 			struct bpf_insn patch[] = {
12429 				*insn,
12430 				BPF_ST_NOSPEC(),
12431 			};
12432 
12433 			cnt = ARRAY_SIZE(patch);
12434 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12435 			if (!new_prog)
12436 				return -ENOMEM;
12437 
12438 			delta    += cnt - 1;
12439 			env->prog = new_prog;
12440 			insn      = new_prog->insnsi + i + delta;
12441 			continue;
12442 		}
12443 
12444 		if (!ctx_access)
12445 			continue;
12446 
12447 		switch (env->insn_aux_data[i + delta].ptr_type) {
12448 		case PTR_TO_CTX:
12449 			if (!ops->convert_ctx_access)
12450 				continue;
12451 			convert_ctx_access = ops->convert_ctx_access;
12452 			break;
12453 		case PTR_TO_SOCKET:
12454 		case PTR_TO_SOCK_COMMON:
12455 			convert_ctx_access = bpf_sock_convert_ctx_access;
12456 			break;
12457 		case PTR_TO_TCP_SOCK:
12458 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12459 			break;
12460 		case PTR_TO_XDP_SOCK:
12461 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12462 			break;
12463 		case PTR_TO_BTF_ID:
12464 			if (type == BPF_READ) {
12465 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12466 					BPF_SIZE((insn)->code);
12467 				env->prog->aux->num_exentries++;
12468 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12469 				verbose(env, "Writes through BTF pointers are not allowed\n");
12470 				return -EINVAL;
12471 			}
12472 			continue;
12473 		default:
12474 			continue;
12475 		}
12476 
12477 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12478 		size = BPF_LDST_BYTES(insn);
12479 
12480 		/* If the read access is a narrower load of the field,
12481 		 * convert to a 4/8-byte load, to minimum program type specific
12482 		 * convert_ctx_access changes. If conversion is successful,
12483 		 * we will apply proper mask to the result.
12484 		 */
12485 		is_narrower_load = size < ctx_field_size;
12486 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12487 		off = insn->off;
12488 		if (is_narrower_load) {
12489 			u8 size_code;
12490 
12491 			if (type == BPF_WRITE) {
12492 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12493 				return -EINVAL;
12494 			}
12495 
12496 			size_code = BPF_H;
12497 			if (ctx_field_size == 4)
12498 				size_code = BPF_W;
12499 			else if (ctx_field_size == 8)
12500 				size_code = BPF_DW;
12501 
12502 			insn->off = off & ~(size_default - 1);
12503 			insn->code = BPF_LDX | BPF_MEM | size_code;
12504 		}
12505 
12506 		target_size = 0;
12507 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12508 					 &target_size);
12509 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12510 		    (ctx_field_size && !target_size)) {
12511 			verbose(env, "bpf verifier is misconfigured\n");
12512 			return -EINVAL;
12513 		}
12514 
12515 		if (is_narrower_load && size < target_size) {
12516 			u8 shift = bpf_ctx_narrow_access_offset(
12517 				off, size, size_default) * 8;
12518 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12519 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12520 				return -EINVAL;
12521 			}
12522 			if (ctx_field_size <= 4) {
12523 				if (shift)
12524 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12525 									insn->dst_reg,
12526 									shift);
12527 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12528 								(1 << size * 8) - 1);
12529 			} else {
12530 				if (shift)
12531 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12532 									insn->dst_reg,
12533 									shift);
12534 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12535 								(1ULL << size * 8) - 1);
12536 			}
12537 		}
12538 
12539 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12540 		if (!new_prog)
12541 			return -ENOMEM;
12542 
12543 		delta += cnt - 1;
12544 
12545 		/* keep walking new program and skip insns we just inserted */
12546 		env->prog = new_prog;
12547 		insn      = new_prog->insnsi + i + delta;
12548 	}
12549 
12550 	return 0;
12551 }
12552 
12553 static int jit_subprogs(struct bpf_verifier_env *env)
12554 {
12555 	struct bpf_prog *prog = env->prog, **func, *tmp;
12556 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12557 	struct bpf_map *map_ptr;
12558 	struct bpf_insn *insn;
12559 	void *old_bpf_func;
12560 	int err, num_exentries;
12561 
12562 	if (env->subprog_cnt <= 1)
12563 		return 0;
12564 
12565 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12566 		if (bpf_pseudo_func(insn)) {
12567 			env->insn_aux_data[i].call_imm = insn->imm;
12568 			/* subprog is encoded in insn[1].imm */
12569 			continue;
12570 		}
12571 
12572 		if (!bpf_pseudo_call(insn))
12573 			continue;
12574 		/* Upon error here we cannot fall back to interpreter but
12575 		 * need a hard reject of the program. Thus -EFAULT is
12576 		 * propagated in any case.
12577 		 */
12578 		subprog = find_subprog(env, i + insn->imm + 1);
12579 		if (subprog < 0) {
12580 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12581 				  i + insn->imm + 1);
12582 			return -EFAULT;
12583 		}
12584 		/* temporarily remember subprog id inside insn instead of
12585 		 * aux_data, since next loop will split up all insns into funcs
12586 		 */
12587 		insn->off = subprog;
12588 		/* remember original imm in case JIT fails and fallback
12589 		 * to interpreter will be needed
12590 		 */
12591 		env->insn_aux_data[i].call_imm = insn->imm;
12592 		/* point imm to __bpf_call_base+1 from JITs point of view */
12593 		insn->imm = 1;
12594 	}
12595 
12596 	err = bpf_prog_alloc_jited_linfo(prog);
12597 	if (err)
12598 		goto out_undo_insn;
12599 
12600 	err = -ENOMEM;
12601 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12602 	if (!func)
12603 		goto out_undo_insn;
12604 
12605 	for (i = 0; i < env->subprog_cnt; i++) {
12606 		subprog_start = subprog_end;
12607 		subprog_end = env->subprog_info[i + 1].start;
12608 
12609 		len = subprog_end - subprog_start;
12610 		/* bpf_prog_run() doesn't call subprogs directly,
12611 		 * hence main prog stats include the runtime of subprogs.
12612 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12613 		 * func[i]->stats will never be accessed and stays NULL
12614 		 */
12615 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12616 		if (!func[i])
12617 			goto out_free;
12618 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12619 		       len * sizeof(struct bpf_insn));
12620 		func[i]->type = prog->type;
12621 		func[i]->len = len;
12622 		if (bpf_prog_calc_tag(func[i]))
12623 			goto out_free;
12624 		func[i]->is_func = 1;
12625 		func[i]->aux->func_idx = i;
12626 		/* Below members will be freed only at prog->aux */
12627 		func[i]->aux->btf = prog->aux->btf;
12628 		func[i]->aux->func_info = prog->aux->func_info;
12629 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12630 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12631 
12632 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12633 			struct bpf_jit_poke_descriptor *poke;
12634 
12635 			poke = &prog->aux->poke_tab[j];
12636 			if (poke->insn_idx < subprog_end &&
12637 			    poke->insn_idx >= subprog_start)
12638 				poke->aux = func[i]->aux;
12639 		}
12640 
12641 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
12642 		 * Long term would need debug info to populate names
12643 		 */
12644 		func[i]->aux->name[0] = 'F';
12645 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12646 		func[i]->jit_requested = 1;
12647 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12648 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
12649 		func[i]->aux->linfo = prog->aux->linfo;
12650 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12651 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12652 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12653 		num_exentries = 0;
12654 		insn = func[i]->insnsi;
12655 		for (j = 0; j < func[i]->len; j++, insn++) {
12656 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12657 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12658 				num_exentries++;
12659 		}
12660 		func[i]->aux->num_exentries = num_exentries;
12661 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12662 		func[i] = bpf_int_jit_compile(func[i]);
12663 		if (!func[i]->jited) {
12664 			err = -ENOTSUPP;
12665 			goto out_free;
12666 		}
12667 		cond_resched();
12668 	}
12669 
12670 	/* at this point all bpf functions were successfully JITed
12671 	 * now populate all bpf_calls with correct addresses and
12672 	 * run last pass of JIT
12673 	 */
12674 	for (i = 0; i < env->subprog_cnt; i++) {
12675 		insn = func[i]->insnsi;
12676 		for (j = 0; j < func[i]->len; j++, insn++) {
12677 			if (bpf_pseudo_func(insn)) {
12678 				subprog = insn[1].imm;
12679 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12680 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12681 				continue;
12682 			}
12683 			if (!bpf_pseudo_call(insn))
12684 				continue;
12685 			subprog = insn->off;
12686 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
12687 		}
12688 
12689 		/* we use the aux data to keep a list of the start addresses
12690 		 * of the JITed images for each function in the program
12691 		 *
12692 		 * for some architectures, such as powerpc64, the imm field
12693 		 * might not be large enough to hold the offset of the start
12694 		 * address of the callee's JITed image from __bpf_call_base
12695 		 *
12696 		 * in such cases, we can lookup the start address of a callee
12697 		 * by using its subprog id, available from the off field of
12698 		 * the call instruction, as an index for this list
12699 		 */
12700 		func[i]->aux->func = func;
12701 		func[i]->aux->func_cnt = env->subprog_cnt;
12702 	}
12703 	for (i = 0; i < env->subprog_cnt; i++) {
12704 		old_bpf_func = func[i]->bpf_func;
12705 		tmp = bpf_int_jit_compile(func[i]);
12706 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12707 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12708 			err = -ENOTSUPP;
12709 			goto out_free;
12710 		}
12711 		cond_resched();
12712 	}
12713 
12714 	/* finally lock prog and jit images for all functions and
12715 	 * populate kallsysm
12716 	 */
12717 	for (i = 0; i < env->subprog_cnt; i++) {
12718 		bpf_prog_lock_ro(func[i]);
12719 		bpf_prog_kallsyms_add(func[i]);
12720 	}
12721 
12722 	/* Last step: make now unused interpreter insns from main
12723 	 * prog consistent for later dump requests, so they can
12724 	 * later look the same as if they were interpreted only.
12725 	 */
12726 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12727 		if (bpf_pseudo_func(insn)) {
12728 			insn[0].imm = env->insn_aux_data[i].call_imm;
12729 			insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12730 			continue;
12731 		}
12732 		if (!bpf_pseudo_call(insn))
12733 			continue;
12734 		insn->off = env->insn_aux_data[i].call_imm;
12735 		subprog = find_subprog(env, i + insn->off + 1);
12736 		insn->imm = subprog;
12737 	}
12738 
12739 	prog->jited = 1;
12740 	prog->bpf_func = func[0]->bpf_func;
12741 	prog->aux->func = func;
12742 	prog->aux->func_cnt = env->subprog_cnt;
12743 	bpf_prog_jit_attempt_done(prog);
12744 	return 0;
12745 out_free:
12746 	/* We failed JIT'ing, so at this point we need to unregister poke
12747 	 * descriptors from subprogs, so that kernel is not attempting to
12748 	 * patch it anymore as we're freeing the subprog JIT memory.
12749 	 */
12750 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12751 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12752 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12753 	}
12754 	/* At this point we're guaranteed that poke descriptors are not
12755 	 * live anymore. We can just unlink its descriptor table as it's
12756 	 * released with the main prog.
12757 	 */
12758 	for (i = 0; i < env->subprog_cnt; i++) {
12759 		if (!func[i])
12760 			continue;
12761 		func[i]->aux->poke_tab = NULL;
12762 		bpf_jit_free(func[i]);
12763 	}
12764 	kfree(func);
12765 out_undo_insn:
12766 	/* cleanup main prog to be interpreted */
12767 	prog->jit_requested = 0;
12768 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12769 		if (!bpf_pseudo_call(insn))
12770 			continue;
12771 		insn->off = 0;
12772 		insn->imm = env->insn_aux_data[i].call_imm;
12773 	}
12774 	bpf_prog_jit_attempt_done(prog);
12775 	return err;
12776 }
12777 
12778 static int fixup_call_args(struct bpf_verifier_env *env)
12779 {
12780 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12781 	struct bpf_prog *prog = env->prog;
12782 	struct bpf_insn *insn = prog->insnsi;
12783 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12784 	int i, depth;
12785 #endif
12786 	int err = 0;
12787 
12788 	if (env->prog->jit_requested &&
12789 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12790 		err = jit_subprogs(env);
12791 		if (err == 0)
12792 			return 0;
12793 		if (err == -EFAULT)
12794 			return err;
12795 	}
12796 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12797 	if (has_kfunc_call) {
12798 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12799 		return -EINVAL;
12800 	}
12801 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12802 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12803 		 * have to be rejected, since interpreter doesn't support them yet.
12804 		 */
12805 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12806 		return -EINVAL;
12807 	}
12808 	for (i = 0; i < prog->len; i++, insn++) {
12809 		if (bpf_pseudo_func(insn)) {
12810 			/* When JIT fails the progs with callback calls
12811 			 * have to be rejected, since interpreter doesn't support them yet.
12812 			 */
12813 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12814 			return -EINVAL;
12815 		}
12816 
12817 		if (!bpf_pseudo_call(insn))
12818 			continue;
12819 		depth = get_callee_stack_depth(env, insn, i);
12820 		if (depth < 0)
12821 			return depth;
12822 		bpf_patch_call_args(insn, depth);
12823 	}
12824 	err = 0;
12825 #endif
12826 	return err;
12827 }
12828 
12829 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12830 			    struct bpf_insn *insn)
12831 {
12832 	const struct bpf_kfunc_desc *desc;
12833 
12834 	if (!insn->imm) {
12835 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
12836 		return -EINVAL;
12837 	}
12838 
12839 	/* insn->imm has the btf func_id. Replace it with
12840 	 * an address (relative to __bpf_base_call).
12841 	 */
12842 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
12843 	if (!desc) {
12844 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12845 			insn->imm);
12846 		return -EFAULT;
12847 	}
12848 
12849 	insn->imm = desc->imm;
12850 
12851 	return 0;
12852 }
12853 
12854 /* Do various post-verification rewrites in a single program pass.
12855  * These rewrites simplify JIT and interpreter implementations.
12856  */
12857 static int do_misc_fixups(struct bpf_verifier_env *env)
12858 {
12859 	struct bpf_prog *prog = env->prog;
12860 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12861 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12862 	struct bpf_insn *insn = prog->insnsi;
12863 	const struct bpf_func_proto *fn;
12864 	const int insn_cnt = prog->len;
12865 	const struct bpf_map_ops *ops;
12866 	struct bpf_insn_aux_data *aux;
12867 	struct bpf_insn insn_buf[16];
12868 	struct bpf_prog *new_prog;
12869 	struct bpf_map *map_ptr;
12870 	int i, ret, cnt, delta = 0;
12871 
12872 	for (i = 0; i < insn_cnt; i++, insn++) {
12873 		/* Make divide-by-zero exceptions impossible. */
12874 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12875 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12876 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12877 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12878 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12879 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12880 			struct bpf_insn *patchlet;
12881 			struct bpf_insn chk_and_div[] = {
12882 				/* [R,W]x div 0 -> 0 */
12883 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12884 					     BPF_JNE | BPF_K, insn->src_reg,
12885 					     0, 2, 0),
12886 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12887 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12888 				*insn,
12889 			};
12890 			struct bpf_insn chk_and_mod[] = {
12891 				/* [R,W]x mod 0 -> [R,W]x */
12892 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12893 					     BPF_JEQ | BPF_K, insn->src_reg,
12894 					     0, 1 + (is64 ? 0 : 1), 0),
12895 				*insn,
12896 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12897 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12898 			};
12899 
12900 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12901 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12902 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12903 
12904 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12905 			if (!new_prog)
12906 				return -ENOMEM;
12907 
12908 			delta    += cnt - 1;
12909 			env->prog = prog = new_prog;
12910 			insn      = new_prog->insnsi + i + delta;
12911 			continue;
12912 		}
12913 
12914 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12915 		if (BPF_CLASS(insn->code) == BPF_LD &&
12916 		    (BPF_MODE(insn->code) == BPF_ABS ||
12917 		     BPF_MODE(insn->code) == BPF_IND)) {
12918 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12919 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12920 				verbose(env, "bpf verifier is misconfigured\n");
12921 				return -EINVAL;
12922 			}
12923 
12924 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12925 			if (!new_prog)
12926 				return -ENOMEM;
12927 
12928 			delta    += cnt - 1;
12929 			env->prog = prog = new_prog;
12930 			insn      = new_prog->insnsi + i + delta;
12931 			continue;
12932 		}
12933 
12934 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12935 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12936 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12937 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12938 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12939 			struct bpf_insn *patch = &insn_buf[0];
12940 			bool issrc, isneg, isimm;
12941 			u32 off_reg;
12942 
12943 			aux = &env->insn_aux_data[i + delta];
12944 			if (!aux->alu_state ||
12945 			    aux->alu_state == BPF_ALU_NON_POINTER)
12946 				continue;
12947 
12948 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12949 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12950 				BPF_ALU_SANITIZE_SRC;
12951 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12952 
12953 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12954 			if (isimm) {
12955 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12956 			} else {
12957 				if (isneg)
12958 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12959 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12960 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12961 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12962 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12963 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12964 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12965 			}
12966 			if (!issrc)
12967 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12968 			insn->src_reg = BPF_REG_AX;
12969 			if (isneg)
12970 				insn->code = insn->code == code_add ?
12971 					     code_sub : code_add;
12972 			*patch++ = *insn;
12973 			if (issrc && isneg && !isimm)
12974 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12975 			cnt = patch - insn_buf;
12976 
12977 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12978 			if (!new_prog)
12979 				return -ENOMEM;
12980 
12981 			delta    += cnt - 1;
12982 			env->prog = prog = new_prog;
12983 			insn      = new_prog->insnsi + i + delta;
12984 			continue;
12985 		}
12986 
12987 		if (insn->code != (BPF_JMP | BPF_CALL))
12988 			continue;
12989 		if (insn->src_reg == BPF_PSEUDO_CALL)
12990 			continue;
12991 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12992 			ret = fixup_kfunc_call(env, insn);
12993 			if (ret)
12994 				return ret;
12995 			continue;
12996 		}
12997 
12998 		if (insn->imm == BPF_FUNC_get_route_realm)
12999 			prog->dst_needed = 1;
13000 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13001 			bpf_user_rnd_init_once();
13002 		if (insn->imm == BPF_FUNC_override_return)
13003 			prog->kprobe_override = 1;
13004 		if (insn->imm == BPF_FUNC_tail_call) {
13005 			/* If we tail call into other programs, we
13006 			 * cannot make any assumptions since they can
13007 			 * be replaced dynamically during runtime in
13008 			 * the program array.
13009 			 */
13010 			prog->cb_access = 1;
13011 			if (!allow_tail_call_in_subprogs(env))
13012 				prog->aux->stack_depth = MAX_BPF_STACK;
13013 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13014 
13015 			/* mark bpf_tail_call as different opcode to avoid
13016 			 * conditional branch in the interpreter for every normal
13017 			 * call and to prevent accidental JITing by JIT compiler
13018 			 * that doesn't support bpf_tail_call yet
13019 			 */
13020 			insn->imm = 0;
13021 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13022 
13023 			aux = &env->insn_aux_data[i + delta];
13024 			if (env->bpf_capable && !expect_blinding &&
13025 			    prog->jit_requested &&
13026 			    !bpf_map_key_poisoned(aux) &&
13027 			    !bpf_map_ptr_poisoned(aux) &&
13028 			    !bpf_map_ptr_unpriv(aux)) {
13029 				struct bpf_jit_poke_descriptor desc = {
13030 					.reason = BPF_POKE_REASON_TAIL_CALL,
13031 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13032 					.tail_call.key = bpf_map_key_immediate(aux),
13033 					.insn_idx = i + delta,
13034 				};
13035 
13036 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13037 				if (ret < 0) {
13038 					verbose(env, "adding tail call poke descriptor failed\n");
13039 					return ret;
13040 				}
13041 
13042 				insn->imm = ret + 1;
13043 				continue;
13044 			}
13045 
13046 			if (!bpf_map_ptr_unpriv(aux))
13047 				continue;
13048 
13049 			/* instead of changing every JIT dealing with tail_call
13050 			 * emit two extra insns:
13051 			 * if (index >= max_entries) goto out;
13052 			 * index &= array->index_mask;
13053 			 * to avoid out-of-bounds cpu speculation
13054 			 */
13055 			if (bpf_map_ptr_poisoned(aux)) {
13056 				verbose(env, "tail_call abusing map_ptr\n");
13057 				return -EINVAL;
13058 			}
13059 
13060 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13061 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13062 						  map_ptr->max_entries, 2);
13063 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13064 						    container_of(map_ptr,
13065 								 struct bpf_array,
13066 								 map)->index_mask);
13067 			insn_buf[2] = *insn;
13068 			cnt = 3;
13069 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13070 			if (!new_prog)
13071 				return -ENOMEM;
13072 
13073 			delta    += cnt - 1;
13074 			env->prog = prog = new_prog;
13075 			insn      = new_prog->insnsi + i + delta;
13076 			continue;
13077 		}
13078 
13079 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13080 			/* The verifier will process callback_fn as many times as necessary
13081 			 * with different maps and the register states prepared by
13082 			 * set_timer_callback_state will be accurate.
13083 			 *
13084 			 * The following use case is valid:
13085 			 *   map1 is shared by prog1, prog2, prog3.
13086 			 *   prog1 calls bpf_timer_init for some map1 elements
13087 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13088 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13089 			 *   prog3 calls bpf_timer_start for some map1 elements.
13090 			 *     Those that were not both bpf_timer_init-ed and
13091 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13092 			 */
13093 			struct bpf_insn ld_addrs[2] = {
13094 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13095 			};
13096 
13097 			insn_buf[0] = ld_addrs[0];
13098 			insn_buf[1] = ld_addrs[1];
13099 			insn_buf[2] = *insn;
13100 			cnt = 3;
13101 
13102 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13103 			if (!new_prog)
13104 				return -ENOMEM;
13105 
13106 			delta    += cnt - 1;
13107 			env->prog = prog = new_prog;
13108 			insn      = new_prog->insnsi + i + delta;
13109 			goto patch_call_imm;
13110 		}
13111 
13112 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13113 		 * and other inlining handlers are currently limited to 64 bit
13114 		 * only.
13115 		 */
13116 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13117 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13118 		     insn->imm == BPF_FUNC_map_update_elem ||
13119 		     insn->imm == BPF_FUNC_map_delete_elem ||
13120 		     insn->imm == BPF_FUNC_map_push_elem   ||
13121 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13122 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13123 		     insn->imm == BPF_FUNC_redirect_map    ||
13124 		     insn->imm == BPF_FUNC_for_each_map_elem)) {
13125 			aux = &env->insn_aux_data[i + delta];
13126 			if (bpf_map_ptr_poisoned(aux))
13127 				goto patch_call_imm;
13128 
13129 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13130 			ops = map_ptr->ops;
13131 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13132 			    ops->map_gen_lookup) {
13133 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13134 				if (cnt == -EOPNOTSUPP)
13135 					goto patch_map_ops_generic;
13136 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13137 					verbose(env, "bpf verifier is misconfigured\n");
13138 					return -EINVAL;
13139 				}
13140 
13141 				new_prog = bpf_patch_insn_data(env, i + delta,
13142 							       insn_buf, cnt);
13143 				if (!new_prog)
13144 					return -ENOMEM;
13145 
13146 				delta    += cnt - 1;
13147 				env->prog = prog = new_prog;
13148 				insn      = new_prog->insnsi + i + delta;
13149 				continue;
13150 			}
13151 
13152 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13153 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13154 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13155 				     (int (*)(struct bpf_map *map, void *key))NULL));
13156 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13157 				     (int (*)(struct bpf_map *map, void *key, void *value,
13158 					      u64 flags))NULL));
13159 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13160 				     (int (*)(struct bpf_map *map, void *value,
13161 					      u64 flags))NULL));
13162 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13163 				     (int (*)(struct bpf_map *map, void *value))NULL));
13164 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13165 				     (int (*)(struct bpf_map *map, void *value))NULL));
13166 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13167 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13168 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13169 				     (int (*)(struct bpf_map *map,
13170 					      bpf_callback_t callback_fn,
13171 					      void *callback_ctx,
13172 					      u64 flags))NULL));
13173 
13174 patch_map_ops_generic:
13175 			switch (insn->imm) {
13176 			case BPF_FUNC_map_lookup_elem:
13177 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
13178 				continue;
13179 			case BPF_FUNC_map_update_elem:
13180 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13181 				continue;
13182 			case BPF_FUNC_map_delete_elem:
13183 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13184 				continue;
13185 			case BPF_FUNC_map_push_elem:
13186 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13187 				continue;
13188 			case BPF_FUNC_map_pop_elem:
13189 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13190 				continue;
13191 			case BPF_FUNC_map_peek_elem:
13192 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13193 				continue;
13194 			case BPF_FUNC_redirect_map:
13195 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
13196 				continue;
13197 			case BPF_FUNC_for_each_map_elem:
13198 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
13199 				continue;
13200 			}
13201 
13202 			goto patch_call_imm;
13203 		}
13204 
13205 		/* Implement bpf_jiffies64 inline. */
13206 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13207 		    insn->imm == BPF_FUNC_jiffies64) {
13208 			struct bpf_insn ld_jiffies_addr[2] = {
13209 				BPF_LD_IMM64(BPF_REG_0,
13210 					     (unsigned long)&jiffies),
13211 			};
13212 
13213 			insn_buf[0] = ld_jiffies_addr[0];
13214 			insn_buf[1] = ld_jiffies_addr[1];
13215 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13216 						  BPF_REG_0, 0);
13217 			cnt = 3;
13218 
13219 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13220 						       cnt);
13221 			if (!new_prog)
13222 				return -ENOMEM;
13223 
13224 			delta    += cnt - 1;
13225 			env->prog = prog = new_prog;
13226 			insn      = new_prog->insnsi + i + delta;
13227 			continue;
13228 		}
13229 
13230 		/* Implement bpf_get_func_ip inline. */
13231 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13232 		    insn->imm == BPF_FUNC_get_func_ip) {
13233 			/* Load IP address from ctx - 8 */
13234 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13235 
13236 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13237 			if (!new_prog)
13238 				return -ENOMEM;
13239 
13240 			env->prog = prog = new_prog;
13241 			insn      = new_prog->insnsi + i + delta;
13242 			continue;
13243 		}
13244 
13245 patch_call_imm:
13246 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13247 		/* all functions that have prototype and verifier allowed
13248 		 * programs to call them, must be real in-kernel functions
13249 		 */
13250 		if (!fn->func) {
13251 			verbose(env,
13252 				"kernel subsystem misconfigured func %s#%d\n",
13253 				func_id_name(insn->imm), insn->imm);
13254 			return -EFAULT;
13255 		}
13256 		insn->imm = fn->func - __bpf_call_base;
13257 	}
13258 
13259 	/* Since poke tab is now finalized, publish aux to tracker. */
13260 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13261 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13262 		if (!map_ptr->ops->map_poke_track ||
13263 		    !map_ptr->ops->map_poke_untrack ||
13264 		    !map_ptr->ops->map_poke_run) {
13265 			verbose(env, "bpf verifier is misconfigured\n");
13266 			return -EINVAL;
13267 		}
13268 
13269 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13270 		if (ret < 0) {
13271 			verbose(env, "tracking tail call prog failed\n");
13272 			return ret;
13273 		}
13274 	}
13275 
13276 	sort_kfunc_descs_by_imm(env->prog);
13277 
13278 	return 0;
13279 }
13280 
13281 static void free_states(struct bpf_verifier_env *env)
13282 {
13283 	struct bpf_verifier_state_list *sl, *sln;
13284 	int i;
13285 
13286 	sl = env->free_list;
13287 	while (sl) {
13288 		sln = sl->next;
13289 		free_verifier_state(&sl->state, false);
13290 		kfree(sl);
13291 		sl = sln;
13292 	}
13293 	env->free_list = NULL;
13294 
13295 	if (!env->explored_states)
13296 		return;
13297 
13298 	for (i = 0; i < state_htab_size(env); i++) {
13299 		sl = env->explored_states[i];
13300 
13301 		while (sl) {
13302 			sln = sl->next;
13303 			free_verifier_state(&sl->state, false);
13304 			kfree(sl);
13305 			sl = sln;
13306 		}
13307 		env->explored_states[i] = NULL;
13308 	}
13309 }
13310 
13311 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13312 {
13313 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13314 	struct bpf_verifier_state *state;
13315 	struct bpf_reg_state *regs;
13316 	int ret, i;
13317 
13318 	env->prev_linfo = NULL;
13319 	env->pass_cnt++;
13320 
13321 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13322 	if (!state)
13323 		return -ENOMEM;
13324 	state->curframe = 0;
13325 	state->speculative = false;
13326 	state->branches = 1;
13327 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13328 	if (!state->frame[0]) {
13329 		kfree(state);
13330 		return -ENOMEM;
13331 	}
13332 	env->cur_state = state;
13333 	init_func_state(env, state->frame[0],
13334 			BPF_MAIN_FUNC /* callsite */,
13335 			0 /* frameno */,
13336 			subprog);
13337 
13338 	regs = state->frame[state->curframe]->regs;
13339 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13340 		ret = btf_prepare_func_args(env, subprog, regs);
13341 		if (ret)
13342 			goto out;
13343 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13344 			if (regs[i].type == PTR_TO_CTX)
13345 				mark_reg_known_zero(env, regs, i);
13346 			else if (regs[i].type == SCALAR_VALUE)
13347 				mark_reg_unknown(env, regs, i);
13348 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13349 				const u32 mem_size = regs[i].mem_size;
13350 
13351 				mark_reg_known_zero(env, regs, i);
13352 				regs[i].mem_size = mem_size;
13353 				regs[i].id = ++env->id_gen;
13354 			}
13355 		}
13356 	} else {
13357 		/* 1st arg to a function */
13358 		regs[BPF_REG_1].type = PTR_TO_CTX;
13359 		mark_reg_known_zero(env, regs, BPF_REG_1);
13360 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13361 		if (ret == -EFAULT)
13362 			/* unlikely verifier bug. abort.
13363 			 * ret == 0 and ret < 0 are sadly acceptable for
13364 			 * main() function due to backward compatibility.
13365 			 * Like socket filter program may be written as:
13366 			 * int bpf_prog(struct pt_regs *ctx)
13367 			 * and never dereference that ctx in the program.
13368 			 * 'struct pt_regs' is a type mismatch for socket
13369 			 * filter that should be using 'struct __sk_buff'.
13370 			 */
13371 			goto out;
13372 	}
13373 
13374 	ret = do_check(env);
13375 out:
13376 	/* check for NULL is necessary, since cur_state can be freed inside
13377 	 * do_check() under memory pressure.
13378 	 */
13379 	if (env->cur_state) {
13380 		free_verifier_state(env->cur_state, true);
13381 		env->cur_state = NULL;
13382 	}
13383 	while (!pop_stack(env, NULL, NULL, false));
13384 	if (!ret && pop_log)
13385 		bpf_vlog_reset(&env->log, 0);
13386 	free_states(env);
13387 	return ret;
13388 }
13389 
13390 /* Verify all global functions in a BPF program one by one based on their BTF.
13391  * All global functions must pass verification. Otherwise the whole program is rejected.
13392  * Consider:
13393  * int bar(int);
13394  * int foo(int f)
13395  * {
13396  *    return bar(f);
13397  * }
13398  * int bar(int b)
13399  * {
13400  *    ...
13401  * }
13402  * foo() will be verified first for R1=any_scalar_value. During verification it
13403  * will be assumed that bar() already verified successfully and call to bar()
13404  * from foo() will be checked for type match only. Later bar() will be verified
13405  * independently to check that it's safe for R1=any_scalar_value.
13406  */
13407 static int do_check_subprogs(struct bpf_verifier_env *env)
13408 {
13409 	struct bpf_prog_aux *aux = env->prog->aux;
13410 	int i, ret;
13411 
13412 	if (!aux->func_info)
13413 		return 0;
13414 
13415 	for (i = 1; i < env->subprog_cnt; i++) {
13416 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13417 			continue;
13418 		env->insn_idx = env->subprog_info[i].start;
13419 		WARN_ON_ONCE(env->insn_idx == 0);
13420 		ret = do_check_common(env, i);
13421 		if (ret) {
13422 			return ret;
13423 		} else if (env->log.level & BPF_LOG_LEVEL) {
13424 			verbose(env,
13425 				"Func#%d is safe for any args that match its prototype\n",
13426 				i);
13427 		}
13428 	}
13429 	return 0;
13430 }
13431 
13432 static int do_check_main(struct bpf_verifier_env *env)
13433 {
13434 	int ret;
13435 
13436 	env->insn_idx = 0;
13437 	ret = do_check_common(env, 0);
13438 	if (!ret)
13439 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13440 	return ret;
13441 }
13442 
13443 
13444 static void print_verification_stats(struct bpf_verifier_env *env)
13445 {
13446 	int i;
13447 
13448 	if (env->log.level & BPF_LOG_STATS) {
13449 		verbose(env, "verification time %lld usec\n",
13450 			div_u64(env->verification_time, 1000));
13451 		verbose(env, "stack depth ");
13452 		for (i = 0; i < env->subprog_cnt; i++) {
13453 			u32 depth = env->subprog_info[i].stack_depth;
13454 
13455 			verbose(env, "%d", depth);
13456 			if (i + 1 < env->subprog_cnt)
13457 				verbose(env, "+");
13458 		}
13459 		verbose(env, "\n");
13460 	}
13461 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13462 		"total_states %d peak_states %d mark_read %d\n",
13463 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13464 		env->max_states_per_insn, env->total_states,
13465 		env->peak_states, env->longest_mark_read_walk);
13466 }
13467 
13468 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13469 {
13470 	const struct btf_type *t, *func_proto;
13471 	const struct bpf_struct_ops *st_ops;
13472 	const struct btf_member *member;
13473 	struct bpf_prog *prog = env->prog;
13474 	u32 btf_id, member_idx;
13475 	const char *mname;
13476 
13477 	if (!prog->gpl_compatible) {
13478 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13479 		return -EINVAL;
13480 	}
13481 
13482 	btf_id = prog->aux->attach_btf_id;
13483 	st_ops = bpf_struct_ops_find(btf_id);
13484 	if (!st_ops) {
13485 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13486 			btf_id);
13487 		return -ENOTSUPP;
13488 	}
13489 
13490 	t = st_ops->type;
13491 	member_idx = prog->expected_attach_type;
13492 	if (member_idx >= btf_type_vlen(t)) {
13493 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13494 			member_idx, st_ops->name);
13495 		return -EINVAL;
13496 	}
13497 
13498 	member = &btf_type_member(t)[member_idx];
13499 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13500 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13501 					       NULL);
13502 	if (!func_proto) {
13503 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13504 			mname, member_idx, st_ops->name);
13505 		return -EINVAL;
13506 	}
13507 
13508 	if (st_ops->check_member) {
13509 		int err = st_ops->check_member(t, member);
13510 
13511 		if (err) {
13512 			verbose(env, "attach to unsupported member %s of struct %s\n",
13513 				mname, st_ops->name);
13514 			return err;
13515 		}
13516 	}
13517 
13518 	prog->aux->attach_func_proto = func_proto;
13519 	prog->aux->attach_func_name = mname;
13520 	env->ops = st_ops->verifier_ops;
13521 
13522 	return 0;
13523 }
13524 #define SECURITY_PREFIX "security_"
13525 
13526 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13527 {
13528 	if (within_error_injection_list(addr) ||
13529 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13530 		return 0;
13531 
13532 	return -EINVAL;
13533 }
13534 
13535 /* list of non-sleepable functions that are otherwise on
13536  * ALLOW_ERROR_INJECTION list
13537  */
13538 BTF_SET_START(btf_non_sleepable_error_inject)
13539 /* Three functions below can be called from sleepable and non-sleepable context.
13540  * Assume non-sleepable from bpf safety point of view.
13541  */
13542 BTF_ID(func, __filemap_add_folio)
13543 BTF_ID(func, should_fail_alloc_page)
13544 BTF_ID(func, should_failslab)
13545 BTF_SET_END(btf_non_sleepable_error_inject)
13546 
13547 static int check_non_sleepable_error_inject(u32 btf_id)
13548 {
13549 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13550 }
13551 
13552 int bpf_check_attach_target(struct bpf_verifier_log *log,
13553 			    const struct bpf_prog *prog,
13554 			    const struct bpf_prog *tgt_prog,
13555 			    u32 btf_id,
13556 			    struct bpf_attach_target_info *tgt_info)
13557 {
13558 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13559 	const char prefix[] = "btf_trace_";
13560 	int ret = 0, subprog = -1, i;
13561 	const struct btf_type *t;
13562 	bool conservative = true;
13563 	const char *tname;
13564 	struct btf *btf;
13565 	long addr = 0;
13566 
13567 	if (!btf_id) {
13568 		bpf_log(log, "Tracing programs must provide btf_id\n");
13569 		return -EINVAL;
13570 	}
13571 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13572 	if (!btf) {
13573 		bpf_log(log,
13574 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13575 		return -EINVAL;
13576 	}
13577 	t = btf_type_by_id(btf, btf_id);
13578 	if (!t) {
13579 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13580 		return -EINVAL;
13581 	}
13582 	tname = btf_name_by_offset(btf, t->name_off);
13583 	if (!tname) {
13584 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13585 		return -EINVAL;
13586 	}
13587 	if (tgt_prog) {
13588 		struct bpf_prog_aux *aux = tgt_prog->aux;
13589 
13590 		for (i = 0; i < aux->func_info_cnt; i++)
13591 			if (aux->func_info[i].type_id == btf_id) {
13592 				subprog = i;
13593 				break;
13594 			}
13595 		if (subprog == -1) {
13596 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13597 			return -EINVAL;
13598 		}
13599 		conservative = aux->func_info_aux[subprog].unreliable;
13600 		if (prog_extension) {
13601 			if (conservative) {
13602 				bpf_log(log,
13603 					"Cannot replace static functions\n");
13604 				return -EINVAL;
13605 			}
13606 			if (!prog->jit_requested) {
13607 				bpf_log(log,
13608 					"Extension programs should be JITed\n");
13609 				return -EINVAL;
13610 			}
13611 		}
13612 		if (!tgt_prog->jited) {
13613 			bpf_log(log, "Can attach to only JITed progs\n");
13614 			return -EINVAL;
13615 		}
13616 		if (tgt_prog->type == prog->type) {
13617 			/* Cannot fentry/fexit another fentry/fexit program.
13618 			 * Cannot attach program extension to another extension.
13619 			 * It's ok to attach fentry/fexit to extension program.
13620 			 */
13621 			bpf_log(log, "Cannot recursively attach\n");
13622 			return -EINVAL;
13623 		}
13624 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13625 		    prog_extension &&
13626 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13627 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13628 			/* Program extensions can extend all program types
13629 			 * except fentry/fexit. The reason is the following.
13630 			 * The fentry/fexit programs are used for performance
13631 			 * analysis, stats and can be attached to any program
13632 			 * type except themselves. When extension program is
13633 			 * replacing XDP function it is necessary to allow
13634 			 * performance analysis of all functions. Both original
13635 			 * XDP program and its program extension. Hence
13636 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13637 			 * allowed. If extending of fentry/fexit was allowed it
13638 			 * would be possible to create long call chain
13639 			 * fentry->extension->fentry->extension beyond
13640 			 * reasonable stack size. Hence extending fentry is not
13641 			 * allowed.
13642 			 */
13643 			bpf_log(log, "Cannot extend fentry/fexit\n");
13644 			return -EINVAL;
13645 		}
13646 	} else {
13647 		if (prog_extension) {
13648 			bpf_log(log, "Cannot replace kernel functions\n");
13649 			return -EINVAL;
13650 		}
13651 	}
13652 
13653 	switch (prog->expected_attach_type) {
13654 	case BPF_TRACE_RAW_TP:
13655 		if (tgt_prog) {
13656 			bpf_log(log,
13657 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13658 			return -EINVAL;
13659 		}
13660 		if (!btf_type_is_typedef(t)) {
13661 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13662 				btf_id);
13663 			return -EINVAL;
13664 		}
13665 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13666 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13667 				btf_id, tname);
13668 			return -EINVAL;
13669 		}
13670 		tname += sizeof(prefix) - 1;
13671 		t = btf_type_by_id(btf, t->type);
13672 		if (!btf_type_is_ptr(t))
13673 			/* should never happen in valid vmlinux build */
13674 			return -EINVAL;
13675 		t = btf_type_by_id(btf, t->type);
13676 		if (!btf_type_is_func_proto(t))
13677 			/* should never happen in valid vmlinux build */
13678 			return -EINVAL;
13679 
13680 		break;
13681 	case BPF_TRACE_ITER:
13682 		if (!btf_type_is_func(t)) {
13683 			bpf_log(log, "attach_btf_id %u is not a function\n",
13684 				btf_id);
13685 			return -EINVAL;
13686 		}
13687 		t = btf_type_by_id(btf, t->type);
13688 		if (!btf_type_is_func_proto(t))
13689 			return -EINVAL;
13690 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13691 		if (ret)
13692 			return ret;
13693 		break;
13694 	default:
13695 		if (!prog_extension)
13696 			return -EINVAL;
13697 		fallthrough;
13698 	case BPF_MODIFY_RETURN:
13699 	case BPF_LSM_MAC:
13700 	case BPF_TRACE_FENTRY:
13701 	case BPF_TRACE_FEXIT:
13702 		if (!btf_type_is_func(t)) {
13703 			bpf_log(log, "attach_btf_id %u is not a function\n",
13704 				btf_id);
13705 			return -EINVAL;
13706 		}
13707 		if (prog_extension &&
13708 		    btf_check_type_match(log, prog, btf, t))
13709 			return -EINVAL;
13710 		t = btf_type_by_id(btf, t->type);
13711 		if (!btf_type_is_func_proto(t))
13712 			return -EINVAL;
13713 
13714 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13715 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13716 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13717 			return -EINVAL;
13718 
13719 		if (tgt_prog && conservative)
13720 			t = NULL;
13721 
13722 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13723 		if (ret < 0)
13724 			return ret;
13725 
13726 		if (tgt_prog) {
13727 			if (subprog == 0)
13728 				addr = (long) tgt_prog->bpf_func;
13729 			else
13730 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13731 		} else {
13732 			addr = kallsyms_lookup_name(tname);
13733 			if (!addr) {
13734 				bpf_log(log,
13735 					"The address of function %s cannot be found\n",
13736 					tname);
13737 				return -ENOENT;
13738 			}
13739 		}
13740 
13741 		if (prog->aux->sleepable) {
13742 			ret = -EINVAL;
13743 			switch (prog->type) {
13744 			case BPF_PROG_TYPE_TRACING:
13745 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13746 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13747 				 */
13748 				if (!check_non_sleepable_error_inject(btf_id) &&
13749 				    within_error_injection_list(addr))
13750 					ret = 0;
13751 				break;
13752 			case BPF_PROG_TYPE_LSM:
13753 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13754 				 * Only some of them are sleepable.
13755 				 */
13756 				if (bpf_lsm_is_sleepable_hook(btf_id))
13757 					ret = 0;
13758 				break;
13759 			default:
13760 				break;
13761 			}
13762 			if (ret) {
13763 				bpf_log(log, "%s is not sleepable\n", tname);
13764 				return ret;
13765 			}
13766 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13767 			if (tgt_prog) {
13768 				bpf_log(log, "can't modify return codes of BPF programs\n");
13769 				return -EINVAL;
13770 			}
13771 			ret = check_attach_modify_return(addr, tname);
13772 			if (ret) {
13773 				bpf_log(log, "%s() is not modifiable\n", tname);
13774 				return ret;
13775 			}
13776 		}
13777 
13778 		break;
13779 	}
13780 	tgt_info->tgt_addr = addr;
13781 	tgt_info->tgt_name = tname;
13782 	tgt_info->tgt_type = t;
13783 	return 0;
13784 }
13785 
13786 BTF_SET_START(btf_id_deny)
13787 BTF_ID_UNUSED
13788 #ifdef CONFIG_SMP
13789 BTF_ID(func, migrate_disable)
13790 BTF_ID(func, migrate_enable)
13791 #endif
13792 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13793 BTF_ID(func, rcu_read_unlock_strict)
13794 #endif
13795 BTF_SET_END(btf_id_deny)
13796 
13797 static int check_attach_btf_id(struct bpf_verifier_env *env)
13798 {
13799 	struct bpf_prog *prog = env->prog;
13800 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13801 	struct bpf_attach_target_info tgt_info = {};
13802 	u32 btf_id = prog->aux->attach_btf_id;
13803 	struct bpf_trampoline *tr;
13804 	int ret;
13805 	u64 key;
13806 
13807 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13808 		if (prog->aux->sleepable)
13809 			/* attach_btf_id checked to be zero already */
13810 			return 0;
13811 		verbose(env, "Syscall programs can only be sleepable\n");
13812 		return -EINVAL;
13813 	}
13814 
13815 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13816 	    prog->type != BPF_PROG_TYPE_LSM) {
13817 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13818 		return -EINVAL;
13819 	}
13820 
13821 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13822 		return check_struct_ops_btf_id(env);
13823 
13824 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13825 	    prog->type != BPF_PROG_TYPE_LSM &&
13826 	    prog->type != BPF_PROG_TYPE_EXT)
13827 		return 0;
13828 
13829 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13830 	if (ret)
13831 		return ret;
13832 
13833 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13834 		/* to make freplace equivalent to their targets, they need to
13835 		 * inherit env->ops and expected_attach_type for the rest of the
13836 		 * verification
13837 		 */
13838 		env->ops = bpf_verifier_ops[tgt_prog->type];
13839 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13840 	}
13841 
13842 	/* store info about the attachment target that will be used later */
13843 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13844 	prog->aux->attach_func_name = tgt_info.tgt_name;
13845 
13846 	if (tgt_prog) {
13847 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13848 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13849 	}
13850 
13851 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13852 		prog->aux->attach_btf_trace = true;
13853 		return 0;
13854 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13855 		if (!bpf_iter_prog_supported(prog))
13856 			return -EINVAL;
13857 		return 0;
13858 	}
13859 
13860 	if (prog->type == BPF_PROG_TYPE_LSM) {
13861 		ret = bpf_lsm_verify_prog(&env->log, prog);
13862 		if (ret < 0)
13863 			return ret;
13864 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13865 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13866 		return -EINVAL;
13867 	}
13868 
13869 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13870 	tr = bpf_trampoline_get(key, &tgt_info);
13871 	if (!tr)
13872 		return -ENOMEM;
13873 
13874 	prog->aux->dst_trampoline = tr;
13875 	return 0;
13876 }
13877 
13878 struct btf *bpf_get_btf_vmlinux(void)
13879 {
13880 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13881 		mutex_lock(&bpf_verifier_lock);
13882 		if (!btf_vmlinux)
13883 			btf_vmlinux = btf_parse_vmlinux();
13884 		mutex_unlock(&bpf_verifier_lock);
13885 	}
13886 	return btf_vmlinux;
13887 }
13888 
13889 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13890 {
13891 	u64 start_time = ktime_get_ns();
13892 	struct bpf_verifier_env *env;
13893 	struct bpf_verifier_log *log;
13894 	int i, len, ret = -EINVAL;
13895 	bool is_priv;
13896 
13897 	/* no program is valid */
13898 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13899 		return -EINVAL;
13900 
13901 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13902 	 * allocate/free it every time bpf_check() is called
13903 	 */
13904 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13905 	if (!env)
13906 		return -ENOMEM;
13907 	log = &env->log;
13908 
13909 	len = (*prog)->len;
13910 	env->insn_aux_data =
13911 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13912 	ret = -ENOMEM;
13913 	if (!env->insn_aux_data)
13914 		goto err_free_env;
13915 	for (i = 0; i < len; i++)
13916 		env->insn_aux_data[i].orig_idx = i;
13917 	env->prog = *prog;
13918 	env->ops = bpf_verifier_ops[env->prog->type];
13919 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13920 	is_priv = bpf_capable();
13921 
13922 	bpf_get_btf_vmlinux();
13923 
13924 	/* grab the mutex to protect few globals used by verifier */
13925 	if (!is_priv)
13926 		mutex_lock(&bpf_verifier_lock);
13927 
13928 	if (attr->log_level || attr->log_buf || attr->log_size) {
13929 		/* user requested verbose verifier output
13930 		 * and supplied buffer to store the verification trace
13931 		 */
13932 		log->level = attr->log_level;
13933 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13934 		log->len_total = attr->log_size;
13935 
13936 		ret = -EINVAL;
13937 		/* log attributes have to be sane */
13938 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13939 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13940 			goto err_unlock;
13941 	}
13942 
13943 	if (IS_ERR(btf_vmlinux)) {
13944 		/* Either gcc or pahole or kernel are broken. */
13945 		verbose(env, "in-kernel BTF is malformed\n");
13946 		ret = PTR_ERR(btf_vmlinux);
13947 		goto skip_full_check;
13948 	}
13949 
13950 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13951 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13952 		env->strict_alignment = true;
13953 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13954 		env->strict_alignment = false;
13955 
13956 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13957 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13958 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13959 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13960 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13961 	env->bpf_capable = bpf_capable();
13962 
13963 	if (is_priv)
13964 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13965 
13966 	env->explored_states = kvcalloc(state_htab_size(env),
13967 				       sizeof(struct bpf_verifier_state_list *),
13968 				       GFP_USER);
13969 	ret = -ENOMEM;
13970 	if (!env->explored_states)
13971 		goto skip_full_check;
13972 
13973 	ret = add_subprog_and_kfunc(env);
13974 	if (ret < 0)
13975 		goto skip_full_check;
13976 
13977 	ret = check_subprogs(env);
13978 	if (ret < 0)
13979 		goto skip_full_check;
13980 
13981 	ret = check_btf_info(env, attr, uattr);
13982 	if (ret < 0)
13983 		goto skip_full_check;
13984 
13985 	ret = check_attach_btf_id(env);
13986 	if (ret)
13987 		goto skip_full_check;
13988 
13989 	ret = resolve_pseudo_ldimm64(env);
13990 	if (ret < 0)
13991 		goto skip_full_check;
13992 
13993 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
13994 		ret = bpf_prog_offload_verifier_prep(env->prog);
13995 		if (ret)
13996 			goto skip_full_check;
13997 	}
13998 
13999 	ret = check_cfg(env);
14000 	if (ret < 0)
14001 		goto skip_full_check;
14002 
14003 	ret = do_check_subprogs(env);
14004 	ret = ret ?: do_check_main(env);
14005 
14006 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14007 		ret = bpf_prog_offload_finalize(env);
14008 
14009 skip_full_check:
14010 	kvfree(env->explored_states);
14011 
14012 	if (ret == 0)
14013 		ret = check_max_stack_depth(env);
14014 
14015 	/* instruction rewrites happen after this point */
14016 	if (is_priv) {
14017 		if (ret == 0)
14018 			opt_hard_wire_dead_code_branches(env);
14019 		if (ret == 0)
14020 			ret = opt_remove_dead_code(env);
14021 		if (ret == 0)
14022 			ret = opt_remove_nops(env);
14023 	} else {
14024 		if (ret == 0)
14025 			sanitize_dead_code(env);
14026 	}
14027 
14028 	if (ret == 0)
14029 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14030 		ret = convert_ctx_accesses(env);
14031 
14032 	if (ret == 0)
14033 		ret = do_misc_fixups(env);
14034 
14035 	/* do 32-bit optimization after insn patching has done so those patched
14036 	 * insns could be handled correctly.
14037 	 */
14038 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14039 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14040 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14041 								     : false;
14042 	}
14043 
14044 	if (ret == 0)
14045 		ret = fixup_call_args(env);
14046 
14047 	env->verification_time = ktime_get_ns() - start_time;
14048 	print_verification_stats(env);
14049 	env->prog->aux->verified_insns = env->insn_processed;
14050 
14051 	if (log->level && bpf_verifier_log_full(log))
14052 		ret = -ENOSPC;
14053 	if (log->level && !log->ubuf) {
14054 		ret = -EFAULT;
14055 		goto err_release_maps;
14056 	}
14057 
14058 	if (ret)
14059 		goto err_release_maps;
14060 
14061 	if (env->used_map_cnt) {
14062 		/* if program passed verifier, update used_maps in bpf_prog_info */
14063 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14064 							  sizeof(env->used_maps[0]),
14065 							  GFP_KERNEL);
14066 
14067 		if (!env->prog->aux->used_maps) {
14068 			ret = -ENOMEM;
14069 			goto err_release_maps;
14070 		}
14071 
14072 		memcpy(env->prog->aux->used_maps, env->used_maps,
14073 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14074 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14075 	}
14076 	if (env->used_btf_cnt) {
14077 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14078 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14079 							  sizeof(env->used_btfs[0]),
14080 							  GFP_KERNEL);
14081 		if (!env->prog->aux->used_btfs) {
14082 			ret = -ENOMEM;
14083 			goto err_release_maps;
14084 		}
14085 
14086 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14087 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14088 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14089 	}
14090 	if (env->used_map_cnt || env->used_btf_cnt) {
14091 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14092 		 * bpf_ld_imm64 instructions
14093 		 */
14094 		convert_pseudo_ld_imm64(env);
14095 	}
14096 
14097 	adjust_btf_func(env);
14098 
14099 err_release_maps:
14100 	if (!env->prog->aux->used_maps)
14101 		/* if we didn't copy map pointers into bpf_prog_info, release
14102 		 * them now. Otherwise free_used_maps() will release them.
14103 		 */
14104 		release_maps(env);
14105 	if (!env->prog->aux->used_btfs)
14106 		release_btfs(env);
14107 
14108 	/* extension progs temporarily inherit the attach_type of their targets
14109 	   for verification purposes, so set it back to zero before returning
14110 	 */
14111 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14112 		env->prog->expected_attach_type = 0;
14113 
14114 	*prog = env->prog;
14115 err_unlock:
14116 	if (!is_priv)
14117 		mutex_unlock(&bpf_verifier_lock);
14118 	vfree(env->insn_aux_data);
14119 err_free_env:
14120 	kfree(env);
14121 	return ret;
14122 }
14123