xref: /linux/kernel/bpf/verifier.c (revision 49545357bf7e134a4012d4652c2df5f78f4485af)
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 static void print_verifier_state(struct bpf_verifier_env *env,
616 				 const struct bpf_func_state *state)
617 {
618 	const struct bpf_reg_state *reg;
619 	enum bpf_reg_type t;
620 	int i;
621 
622 	if (state->frameno)
623 		verbose(env, " frame%d:", state->frameno);
624 	for (i = 0; i < MAX_BPF_REG; i++) {
625 		reg = &state->regs[i];
626 		t = reg->type;
627 		if (t == NOT_INIT)
628 			continue;
629 		verbose(env, " R%d", i);
630 		print_liveness(env, reg->live);
631 		verbose(env, "=%s", reg_type_str[t]);
632 		if (t == SCALAR_VALUE && reg->precise)
633 			verbose(env, "P");
634 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
635 		    tnum_is_const(reg->var_off)) {
636 			/* reg->off should be 0 for SCALAR_VALUE */
637 			verbose(env, "%lld", reg->var_off.value + reg->off);
638 		} else {
639 			if (t == PTR_TO_BTF_ID ||
640 			    t == PTR_TO_BTF_ID_OR_NULL ||
641 			    t == PTR_TO_PERCPU_BTF_ID)
642 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
643 			verbose(env, "(id=%d", reg->id);
644 			if (reg_type_may_be_refcounted_or_null(t))
645 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
646 			if (t != SCALAR_VALUE)
647 				verbose(env, ",off=%d", reg->off);
648 			if (type_is_pkt_pointer(t))
649 				verbose(env, ",r=%d", reg->range);
650 			else if (t == CONST_PTR_TO_MAP ||
651 				 t == PTR_TO_MAP_KEY ||
652 				 t == PTR_TO_MAP_VALUE ||
653 				 t == PTR_TO_MAP_VALUE_OR_NULL)
654 				verbose(env, ",ks=%d,vs=%d",
655 					reg->map_ptr->key_size,
656 					reg->map_ptr->value_size);
657 			if (tnum_is_const(reg->var_off)) {
658 				/* Typically an immediate SCALAR_VALUE, but
659 				 * could be a pointer whose offset is too big
660 				 * for reg->off
661 				 */
662 				verbose(env, ",imm=%llx", reg->var_off.value);
663 			} else {
664 				if (reg->smin_value != reg->umin_value &&
665 				    reg->smin_value != S64_MIN)
666 					verbose(env, ",smin_value=%lld",
667 						(long long)reg->smin_value);
668 				if (reg->smax_value != reg->umax_value &&
669 				    reg->smax_value != S64_MAX)
670 					verbose(env, ",smax_value=%lld",
671 						(long long)reg->smax_value);
672 				if (reg->umin_value != 0)
673 					verbose(env, ",umin_value=%llu",
674 						(unsigned long long)reg->umin_value);
675 				if (reg->umax_value != U64_MAX)
676 					verbose(env, ",umax_value=%llu",
677 						(unsigned long long)reg->umax_value);
678 				if (!tnum_is_unknown(reg->var_off)) {
679 					char tn_buf[48];
680 
681 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
682 					verbose(env, ",var_off=%s", tn_buf);
683 				}
684 				if (reg->s32_min_value != reg->smin_value &&
685 				    reg->s32_min_value != S32_MIN)
686 					verbose(env, ",s32_min_value=%d",
687 						(int)(reg->s32_min_value));
688 				if (reg->s32_max_value != reg->smax_value &&
689 				    reg->s32_max_value != S32_MAX)
690 					verbose(env, ",s32_max_value=%d",
691 						(int)(reg->s32_max_value));
692 				if (reg->u32_min_value != reg->umin_value &&
693 				    reg->u32_min_value != U32_MIN)
694 					verbose(env, ",u32_min_value=%d",
695 						(int)(reg->u32_min_value));
696 				if (reg->u32_max_value != reg->umax_value &&
697 				    reg->u32_max_value != U32_MAX)
698 					verbose(env, ",u32_max_value=%d",
699 						(int)(reg->u32_max_value));
700 			}
701 			verbose(env, ")");
702 		}
703 	}
704 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
705 		char types_buf[BPF_REG_SIZE + 1];
706 		bool valid = false;
707 		int j;
708 
709 		for (j = 0; j < BPF_REG_SIZE; j++) {
710 			if (state->stack[i].slot_type[j] != STACK_INVALID)
711 				valid = true;
712 			types_buf[j] = slot_type_char[
713 					state->stack[i].slot_type[j]];
714 		}
715 		types_buf[BPF_REG_SIZE] = 0;
716 		if (!valid)
717 			continue;
718 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
719 		print_liveness(env, state->stack[i].spilled_ptr.live);
720 		if (state->stack[i].slot_type[0] == STACK_SPILL) {
721 			reg = &state->stack[i].spilled_ptr;
722 			t = reg->type;
723 			verbose(env, "=%s", reg_type_str[t]);
724 			if (t == SCALAR_VALUE && reg->precise)
725 				verbose(env, "P");
726 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
727 				verbose(env, "%lld", reg->var_off.value + reg->off);
728 		} else {
729 			verbose(env, "=%s", types_buf);
730 		}
731 	}
732 	if (state->acquired_refs && state->refs[0].id) {
733 		verbose(env, " refs=%d", state->refs[0].id);
734 		for (i = 1; i < state->acquired_refs; i++)
735 			if (state->refs[i].id)
736 				verbose(env, ",%d", state->refs[i].id);
737 	}
738 	if (state->in_callback_fn)
739 		verbose(env, " cb");
740 	if (state->in_async_callback_fn)
741 		verbose(env, " async_cb");
742 	verbose(env, "\n");
743 }
744 
745 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
746  * small to hold src. This is different from krealloc since we don't want to preserve
747  * the contents of dst.
748  *
749  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
750  * not be allocated.
751  */
752 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
753 {
754 	size_t bytes;
755 
756 	if (ZERO_OR_NULL_PTR(src))
757 		goto out;
758 
759 	if (unlikely(check_mul_overflow(n, size, &bytes)))
760 		return NULL;
761 
762 	if (ksize(dst) < bytes) {
763 		kfree(dst);
764 		dst = kmalloc_track_caller(bytes, flags);
765 		if (!dst)
766 			return NULL;
767 	}
768 
769 	memcpy(dst, src, bytes);
770 out:
771 	return dst ? dst : ZERO_SIZE_PTR;
772 }
773 
774 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
775  * small to hold new_n items. new items are zeroed out if the array grows.
776  *
777  * Contrary to krealloc_array, does not free arr if new_n is zero.
778  */
779 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
780 {
781 	if (!new_n || old_n == new_n)
782 		goto out;
783 
784 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
785 	if (!arr)
786 		return NULL;
787 
788 	if (new_n > old_n)
789 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
790 
791 out:
792 	return arr ? arr : ZERO_SIZE_PTR;
793 }
794 
795 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
796 {
797 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
798 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
799 	if (!dst->refs)
800 		return -ENOMEM;
801 
802 	dst->acquired_refs = src->acquired_refs;
803 	return 0;
804 }
805 
806 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
807 {
808 	size_t n = src->allocated_stack / BPF_REG_SIZE;
809 
810 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
811 				GFP_KERNEL);
812 	if (!dst->stack)
813 		return -ENOMEM;
814 
815 	dst->allocated_stack = src->allocated_stack;
816 	return 0;
817 }
818 
819 static int resize_reference_state(struct bpf_func_state *state, size_t n)
820 {
821 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
822 				    sizeof(struct bpf_reference_state));
823 	if (!state->refs)
824 		return -ENOMEM;
825 
826 	state->acquired_refs = n;
827 	return 0;
828 }
829 
830 static int grow_stack_state(struct bpf_func_state *state, int size)
831 {
832 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
833 
834 	if (old_n >= n)
835 		return 0;
836 
837 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
838 	if (!state->stack)
839 		return -ENOMEM;
840 
841 	state->allocated_stack = size;
842 	return 0;
843 }
844 
845 /* Acquire a pointer id from the env and update the state->refs to include
846  * this new pointer reference.
847  * On success, returns a valid pointer id to associate with the register
848  * On failure, returns a negative errno.
849  */
850 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
851 {
852 	struct bpf_func_state *state = cur_func(env);
853 	int new_ofs = state->acquired_refs;
854 	int id, err;
855 
856 	err = resize_reference_state(state, state->acquired_refs + 1);
857 	if (err)
858 		return err;
859 	id = ++env->id_gen;
860 	state->refs[new_ofs].id = id;
861 	state->refs[new_ofs].insn_idx = insn_idx;
862 
863 	return id;
864 }
865 
866 /* release function corresponding to acquire_reference_state(). Idempotent. */
867 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
868 {
869 	int i, last_idx;
870 
871 	last_idx = state->acquired_refs - 1;
872 	for (i = 0; i < state->acquired_refs; i++) {
873 		if (state->refs[i].id == ptr_id) {
874 			if (last_idx && i != last_idx)
875 				memcpy(&state->refs[i], &state->refs[last_idx],
876 				       sizeof(*state->refs));
877 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
878 			state->acquired_refs--;
879 			return 0;
880 		}
881 	}
882 	return -EINVAL;
883 }
884 
885 static void free_func_state(struct bpf_func_state *state)
886 {
887 	if (!state)
888 		return;
889 	kfree(state->refs);
890 	kfree(state->stack);
891 	kfree(state);
892 }
893 
894 static void clear_jmp_history(struct bpf_verifier_state *state)
895 {
896 	kfree(state->jmp_history);
897 	state->jmp_history = NULL;
898 	state->jmp_history_cnt = 0;
899 }
900 
901 static void free_verifier_state(struct bpf_verifier_state *state,
902 				bool free_self)
903 {
904 	int i;
905 
906 	for (i = 0; i <= state->curframe; i++) {
907 		free_func_state(state->frame[i]);
908 		state->frame[i] = NULL;
909 	}
910 	clear_jmp_history(state);
911 	if (free_self)
912 		kfree(state);
913 }
914 
915 /* copy verifier state from src to dst growing dst stack space
916  * when necessary to accommodate larger src stack
917  */
918 static int copy_func_state(struct bpf_func_state *dst,
919 			   const struct bpf_func_state *src)
920 {
921 	int err;
922 
923 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
924 	err = copy_reference_state(dst, src);
925 	if (err)
926 		return err;
927 	return copy_stack_state(dst, src);
928 }
929 
930 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
931 			       const struct bpf_verifier_state *src)
932 {
933 	struct bpf_func_state *dst;
934 	int i, err;
935 
936 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
937 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
938 					    GFP_USER);
939 	if (!dst_state->jmp_history)
940 		return -ENOMEM;
941 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
942 
943 	/* if dst has more stack frames then src frame, free them */
944 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
945 		free_func_state(dst_state->frame[i]);
946 		dst_state->frame[i] = NULL;
947 	}
948 	dst_state->speculative = src->speculative;
949 	dst_state->curframe = src->curframe;
950 	dst_state->active_spin_lock = src->active_spin_lock;
951 	dst_state->branches = src->branches;
952 	dst_state->parent = src->parent;
953 	dst_state->first_insn_idx = src->first_insn_idx;
954 	dst_state->last_insn_idx = src->last_insn_idx;
955 	for (i = 0; i <= src->curframe; i++) {
956 		dst = dst_state->frame[i];
957 		if (!dst) {
958 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
959 			if (!dst)
960 				return -ENOMEM;
961 			dst_state->frame[i] = dst;
962 		}
963 		err = copy_func_state(dst, src->frame[i]);
964 		if (err)
965 			return err;
966 	}
967 	return 0;
968 }
969 
970 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
971 {
972 	while (st) {
973 		u32 br = --st->branches;
974 
975 		/* WARN_ON(br > 1) technically makes sense here,
976 		 * but see comment in push_stack(), hence:
977 		 */
978 		WARN_ONCE((int)br < 0,
979 			  "BUG update_branch_counts:branches_to_explore=%d\n",
980 			  br);
981 		if (br)
982 			break;
983 		st = st->parent;
984 	}
985 }
986 
987 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
988 		     int *insn_idx, bool pop_log)
989 {
990 	struct bpf_verifier_state *cur = env->cur_state;
991 	struct bpf_verifier_stack_elem *elem, *head = env->head;
992 	int err;
993 
994 	if (env->head == NULL)
995 		return -ENOENT;
996 
997 	if (cur) {
998 		err = copy_verifier_state(cur, &head->st);
999 		if (err)
1000 			return err;
1001 	}
1002 	if (pop_log)
1003 		bpf_vlog_reset(&env->log, head->log_pos);
1004 	if (insn_idx)
1005 		*insn_idx = head->insn_idx;
1006 	if (prev_insn_idx)
1007 		*prev_insn_idx = head->prev_insn_idx;
1008 	elem = head->next;
1009 	free_verifier_state(&head->st, false);
1010 	kfree(head);
1011 	env->head = elem;
1012 	env->stack_size--;
1013 	return 0;
1014 }
1015 
1016 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1017 					     int insn_idx, int prev_insn_idx,
1018 					     bool speculative)
1019 {
1020 	struct bpf_verifier_state *cur = env->cur_state;
1021 	struct bpf_verifier_stack_elem *elem;
1022 	int err;
1023 
1024 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1025 	if (!elem)
1026 		goto err;
1027 
1028 	elem->insn_idx = insn_idx;
1029 	elem->prev_insn_idx = prev_insn_idx;
1030 	elem->next = env->head;
1031 	elem->log_pos = env->log.len_used;
1032 	env->head = elem;
1033 	env->stack_size++;
1034 	err = copy_verifier_state(&elem->st, cur);
1035 	if (err)
1036 		goto err;
1037 	elem->st.speculative |= speculative;
1038 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1039 		verbose(env, "The sequence of %d jumps is too complex.\n",
1040 			env->stack_size);
1041 		goto err;
1042 	}
1043 	if (elem->st.parent) {
1044 		++elem->st.parent->branches;
1045 		/* WARN_ON(branches > 2) technically makes sense here,
1046 		 * but
1047 		 * 1. speculative states will bump 'branches' for non-branch
1048 		 * instructions
1049 		 * 2. is_state_visited() heuristics may decide not to create
1050 		 * a new state for a sequence of branches and all such current
1051 		 * and cloned states will be pointing to a single parent state
1052 		 * which might have large 'branches' count.
1053 		 */
1054 	}
1055 	return &elem->st;
1056 err:
1057 	free_verifier_state(env->cur_state, true);
1058 	env->cur_state = NULL;
1059 	/* pop all elements and return */
1060 	while (!pop_stack(env, NULL, NULL, false));
1061 	return NULL;
1062 }
1063 
1064 #define CALLER_SAVED_REGS 6
1065 static const int caller_saved[CALLER_SAVED_REGS] = {
1066 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1067 };
1068 
1069 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1070 				struct bpf_reg_state *reg);
1071 
1072 /* This helper doesn't clear reg->id */
1073 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1074 {
1075 	reg->var_off = tnum_const(imm);
1076 	reg->smin_value = (s64)imm;
1077 	reg->smax_value = (s64)imm;
1078 	reg->umin_value = imm;
1079 	reg->umax_value = imm;
1080 
1081 	reg->s32_min_value = (s32)imm;
1082 	reg->s32_max_value = (s32)imm;
1083 	reg->u32_min_value = (u32)imm;
1084 	reg->u32_max_value = (u32)imm;
1085 }
1086 
1087 /* Mark the unknown part of a register (variable offset or scalar value) as
1088  * known to have the value @imm.
1089  */
1090 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1091 {
1092 	/* Clear id, off, and union(map_ptr, range) */
1093 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1094 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1095 	___mark_reg_known(reg, imm);
1096 }
1097 
1098 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1099 {
1100 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1101 	reg->s32_min_value = (s32)imm;
1102 	reg->s32_max_value = (s32)imm;
1103 	reg->u32_min_value = (u32)imm;
1104 	reg->u32_max_value = (u32)imm;
1105 }
1106 
1107 /* Mark the 'variable offset' part of a register as zero.  This should be
1108  * used only on registers holding a pointer type.
1109  */
1110 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1111 {
1112 	__mark_reg_known(reg, 0);
1113 }
1114 
1115 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1116 {
1117 	__mark_reg_known(reg, 0);
1118 	reg->type = SCALAR_VALUE;
1119 }
1120 
1121 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1122 				struct bpf_reg_state *regs, u32 regno)
1123 {
1124 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1125 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1126 		/* Something bad happened, let's kill all regs */
1127 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1128 			__mark_reg_not_init(env, regs + regno);
1129 		return;
1130 	}
1131 	__mark_reg_known_zero(regs + regno);
1132 }
1133 
1134 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1135 {
1136 	switch (reg->type) {
1137 	case PTR_TO_MAP_VALUE_OR_NULL: {
1138 		const struct bpf_map *map = reg->map_ptr;
1139 
1140 		if (map->inner_map_meta) {
1141 			reg->type = CONST_PTR_TO_MAP;
1142 			reg->map_ptr = map->inner_map_meta;
1143 			/* transfer reg's id which is unique for every map_lookup_elem
1144 			 * as UID of the inner map.
1145 			 */
1146 			reg->map_uid = reg->id;
1147 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1148 			reg->type = PTR_TO_XDP_SOCK;
1149 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1150 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1151 			reg->type = PTR_TO_SOCKET;
1152 		} else {
1153 			reg->type = PTR_TO_MAP_VALUE;
1154 		}
1155 		break;
1156 	}
1157 	case PTR_TO_SOCKET_OR_NULL:
1158 		reg->type = PTR_TO_SOCKET;
1159 		break;
1160 	case PTR_TO_SOCK_COMMON_OR_NULL:
1161 		reg->type = PTR_TO_SOCK_COMMON;
1162 		break;
1163 	case PTR_TO_TCP_SOCK_OR_NULL:
1164 		reg->type = PTR_TO_TCP_SOCK;
1165 		break;
1166 	case PTR_TO_BTF_ID_OR_NULL:
1167 		reg->type = PTR_TO_BTF_ID;
1168 		break;
1169 	case PTR_TO_MEM_OR_NULL:
1170 		reg->type = PTR_TO_MEM;
1171 		break;
1172 	case PTR_TO_RDONLY_BUF_OR_NULL:
1173 		reg->type = PTR_TO_RDONLY_BUF;
1174 		break;
1175 	case PTR_TO_RDWR_BUF_OR_NULL:
1176 		reg->type = PTR_TO_RDWR_BUF;
1177 		break;
1178 	default:
1179 		WARN_ONCE(1, "unknown nullable register type");
1180 	}
1181 }
1182 
1183 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1184 {
1185 	return type_is_pkt_pointer(reg->type);
1186 }
1187 
1188 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1189 {
1190 	return reg_is_pkt_pointer(reg) ||
1191 	       reg->type == PTR_TO_PACKET_END;
1192 }
1193 
1194 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1195 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1196 				    enum bpf_reg_type which)
1197 {
1198 	/* The register can already have a range from prior markings.
1199 	 * This is fine as long as it hasn't been advanced from its
1200 	 * origin.
1201 	 */
1202 	return reg->type == which &&
1203 	       reg->id == 0 &&
1204 	       reg->off == 0 &&
1205 	       tnum_equals_const(reg->var_off, 0);
1206 }
1207 
1208 /* Reset the min/max bounds of a register */
1209 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1210 {
1211 	reg->smin_value = S64_MIN;
1212 	reg->smax_value = S64_MAX;
1213 	reg->umin_value = 0;
1214 	reg->umax_value = U64_MAX;
1215 
1216 	reg->s32_min_value = S32_MIN;
1217 	reg->s32_max_value = S32_MAX;
1218 	reg->u32_min_value = 0;
1219 	reg->u32_max_value = U32_MAX;
1220 }
1221 
1222 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1223 {
1224 	reg->smin_value = S64_MIN;
1225 	reg->smax_value = S64_MAX;
1226 	reg->umin_value = 0;
1227 	reg->umax_value = U64_MAX;
1228 }
1229 
1230 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1231 {
1232 	reg->s32_min_value = S32_MIN;
1233 	reg->s32_max_value = S32_MAX;
1234 	reg->u32_min_value = 0;
1235 	reg->u32_max_value = U32_MAX;
1236 }
1237 
1238 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1239 {
1240 	struct tnum var32_off = tnum_subreg(reg->var_off);
1241 
1242 	/* min signed is max(sign bit) | min(other bits) */
1243 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1244 			var32_off.value | (var32_off.mask & S32_MIN));
1245 	/* max signed is min(sign bit) | max(other bits) */
1246 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1247 			var32_off.value | (var32_off.mask & S32_MAX));
1248 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1249 	reg->u32_max_value = min(reg->u32_max_value,
1250 				 (u32)(var32_off.value | var32_off.mask));
1251 }
1252 
1253 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1254 {
1255 	/* min signed is max(sign bit) | min(other bits) */
1256 	reg->smin_value = max_t(s64, reg->smin_value,
1257 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1258 	/* max signed is min(sign bit) | max(other bits) */
1259 	reg->smax_value = min_t(s64, reg->smax_value,
1260 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1261 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1262 	reg->umax_value = min(reg->umax_value,
1263 			      reg->var_off.value | reg->var_off.mask);
1264 }
1265 
1266 static void __update_reg_bounds(struct bpf_reg_state *reg)
1267 {
1268 	__update_reg32_bounds(reg);
1269 	__update_reg64_bounds(reg);
1270 }
1271 
1272 /* Uses signed min/max values to inform unsigned, and vice-versa */
1273 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1274 {
1275 	/* Learn sign from signed bounds.
1276 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1277 	 * are the same, so combine.  This works even in the negative case, e.g.
1278 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1279 	 */
1280 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1281 		reg->s32_min_value = reg->u32_min_value =
1282 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1283 		reg->s32_max_value = reg->u32_max_value =
1284 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1285 		return;
1286 	}
1287 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1288 	 * boundary, so we must be careful.
1289 	 */
1290 	if ((s32)reg->u32_max_value >= 0) {
1291 		/* Positive.  We can't learn anything from the smin, but smax
1292 		 * is positive, hence safe.
1293 		 */
1294 		reg->s32_min_value = reg->u32_min_value;
1295 		reg->s32_max_value = reg->u32_max_value =
1296 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1297 	} else if ((s32)reg->u32_min_value < 0) {
1298 		/* Negative.  We can't learn anything from the smax, but smin
1299 		 * is negative, hence safe.
1300 		 */
1301 		reg->s32_min_value = reg->u32_min_value =
1302 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1303 		reg->s32_max_value = reg->u32_max_value;
1304 	}
1305 }
1306 
1307 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1308 {
1309 	/* Learn sign from signed bounds.
1310 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1311 	 * are the same, so combine.  This works even in the negative case, e.g.
1312 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1313 	 */
1314 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1315 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1316 							  reg->umin_value);
1317 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1318 							  reg->umax_value);
1319 		return;
1320 	}
1321 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1322 	 * boundary, so we must be careful.
1323 	 */
1324 	if ((s64)reg->umax_value >= 0) {
1325 		/* Positive.  We can't learn anything from the smin, but smax
1326 		 * is positive, hence safe.
1327 		 */
1328 		reg->smin_value = reg->umin_value;
1329 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1330 							  reg->umax_value);
1331 	} else if ((s64)reg->umin_value < 0) {
1332 		/* Negative.  We can't learn anything from the smax, but smin
1333 		 * is negative, hence safe.
1334 		 */
1335 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1336 							  reg->umin_value);
1337 		reg->smax_value = reg->umax_value;
1338 	}
1339 }
1340 
1341 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1342 {
1343 	__reg32_deduce_bounds(reg);
1344 	__reg64_deduce_bounds(reg);
1345 }
1346 
1347 /* Attempts to improve var_off based on unsigned min/max information */
1348 static void __reg_bound_offset(struct bpf_reg_state *reg)
1349 {
1350 	struct tnum var64_off = tnum_intersect(reg->var_off,
1351 					       tnum_range(reg->umin_value,
1352 							  reg->umax_value));
1353 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1354 						tnum_range(reg->u32_min_value,
1355 							   reg->u32_max_value));
1356 
1357 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1358 }
1359 
1360 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1361 {
1362 	reg->umin_value = reg->u32_min_value;
1363 	reg->umax_value = reg->u32_max_value;
1364 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds
1365 	 * but must be positive otherwise set to worse case bounds
1366 	 * and refine later from tnum.
1367 	 */
1368 	if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1369 		reg->smax_value = reg->s32_max_value;
1370 	else
1371 		reg->smax_value = U32_MAX;
1372 	if (reg->s32_min_value >= 0)
1373 		reg->smin_value = reg->s32_min_value;
1374 	else
1375 		reg->smin_value = 0;
1376 }
1377 
1378 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1379 {
1380 	/* special case when 64-bit register has upper 32-bit register
1381 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1382 	 * allowing us to use 32-bit bounds directly,
1383 	 */
1384 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1385 		__reg_assign_32_into_64(reg);
1386 	} else {
1387 		/* Otherwise the best we can do is push lower 32bit known and
1388 		 * unknown bits into register (var_off set from jmp logic)
1389 		 * then learn as much as possible from the 64-bit tnum
1390 		 * known and unknown bits. The previous smin/smax bounds are
1391 		 * invalid here because of jmp32 compare so mark them unknown
1392 		 * so they do not impact tnum bounds calculation.
1393 		 */
1394 		__mark_reg64_unbounded(reg);
1395 		__update_reg_bounds(reg);
1396 	}
1397 
1398 	/* Intersecting with the old var_off might have improved our bounds
1399 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1400 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1401 	 */
1402 	__reg_deduce_bounds(reg);
1403 	__reg_bound_offset(reg);
1404 	__update_reg_bounds(reg);
1405 }
1406 
1407 static bool __reg64_bound_s32(s64 a)
1408 {
1409 	return a > S32_MIN && a < S32_MAX;
1410 }
1411 
1412 static bool __reg64_bound_u32(u64 a)
1413 {
1414 	return a > U32_MIN && a < U32_MAX;
1415 }
1416 
1417 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1418 {
1419 	__mark_reg32_unbounded(reg);
1420 
1421 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1422 		reg->s32_min_value = (s32)reg->smin_value;
1423 		reg->s32_max_value = (s32)reg->smax_value;
1424 	}
1425 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1426 		reg->u32_min_value = (u32)reg->umin_value;
1427 		reg->u32_max_value = (u32)reg->umax_value;
1428 	}
1429 
1430 	/* Intersecting with the old var_off might have improved our bounds
1431 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1432 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1433 	 */
1434 	__reg_deduce_bounds(reg);
1435 	__reg_bound_offset(reg);
1436 	__update_reg_bounds(reg);
1437 }
1438 
1439 /* Mark a register as having a completely unknown (scalar) value. */
1440 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1441 			       struct bpf_reg_state *reg)
1442 {
1443 	/*
1444 	 * Clear type, id, off, and union(map_ptr, range) and
1445 	 * padding between 'type' and union
1446 	 */
1447 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1448 	reg->type = SCALAR_VALUE;
1449 	reg->var_off = tnum_unknown;
1450 	reg->frameno = 0;
1451 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1452 	__mark_reg_unbounded(reg);
1453 }
1454 
1455 static void mark_reg_unknown(struct bpf_verifier_env *env,
1456 			     struct bpf_reg_state *regs, u32 regno)
1457 {
1458 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1459 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1460 		/* Something bad happened, let's kill all regs except FP */
1461 		for (regno = 0; regno < BPF_REG_FP; regno++)
1462 			__mark_reg_not_init(env, regs + regno);
1463 		return;
1464 	}
1465 	__mark_reg_unknown(env, regs + regno);
1466 }
1467 
1468 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1469 				struct bpf_reg_state *reg)
1470 {
1471 	__mark_reg_unknown(env, reg);
1472 	reg->type = NOT_INIT;
1473 }
1474 
1475 static void mark_reg_not_init(struct bpf_verifier_env *env,
1476 			      struct bpf_reg_state *regs, u32 regno)
1477 {
1478 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1479 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1480 		/* Something bad happened, let's kill all regs except FP */
1481 		for (regno = 0; regno < BPF_REG_FP; regno++)
1482 			__mark_reg_not_init(env, regs + regno);
1483 		return;
1484 	}
1485 	__mark_reg_not_init(env, regs + regno);
1486 }
1487 
1488 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1489 			    struct bpf_reg_state *regs, u32 regno,
1490 			    enum bpf_reg_type reg_type,
1491 			    struct btf *btf, u32 btf_id)
1492 {
1493 	if (reg_type == SCALAR_VALUE) {
1494 		mark_reg_unknown(env, regs, regno);
1495 		return;
1496 	}
1497 	mark_reg_known_zero(env, regs, regno);
1498 	regs[regno].type = PTR_TO_BTF_ID;
1499 	regs[regno].btf = btf;
1500 	regs[regno].btf_id = btf_id;
1501 }
1502 
1503 #define DEF_NOT_SUBREG	(0)
1504 static void init_reg_state(struct bpf_verifier_env *env,
1505 			   struct bpf_func_state *state)
1506 {
1507 	struct bpf_reg_state *regs = state->regs;
1508 	int i;
1509 
1510 	for (i = 0; i < MAX_BPF_REG; i++) {
1511 		mark_reg_not_init(env, regs, i);
1512 		regs[i].live = REG_LIVE_NONE;
1513 		regs[i].parent = NULL;
1514 		regs[i].subreg_def = DEF_NOT_SUBREG;
1515 	}
1516 
1517 	/* frame pointer */
1518 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1519 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1520 	regs[BPF_REG_FP].frameno = state->frameno;
1521 }
1522 
1523 #define BPF_MAIN_FUNC (-1)
1524 static void init_func_state(struct bpf_verifier_env *env,
1525 			    struct bpf_func_state *state,
1526 			    int callsite, int frameno, int subprogno)
1527 {
1528 	state->callsite = callsite;
1529 	state->frameno = frameno;
1530 	state->subprogno = subprogno;
1531 	init_reg_state(env, state);
1532 }
1533 
1534 /* Similar to push_stack(), but for async callbacks */
1535 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1536 						int insn_idx, int prev_insn_idx,
1537 						int subprog)
1538 {
1539 	struct bpf_verifier_stack_elem *elem;
1540 	struct bpf_func_state *frame;
1541 
1542 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1543 	if (!elem)
1544 		goto err;
1545 
1546 	elem->insn_idx = insn_idx;
1547 	elem->prev_insn_idx = prev_insn_idx;
1548 	elem->next = env->head;
1549 	elem->log_pos = env->log.len_used;
1550 	env->head = elem;
1551 	env->stack_size++;
1552 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1553 		verbose(env,
1554 			"The sequence of %d jumps is too complex for async cb.\n",
1555 			env->stack_size);
1556 		goto err;
1557 	}
1558 	/* Unlike push_stack() do not copy_verifier_state().
1559 	 * The caller state doesn't matter.
1560 	 * This is async callback. It starts in a fresh stack.
1561 	 * Initialize it similar to do_check_common().
1562 	 */
1563 	elem->st.branches = 1;
1564 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1565 	if (!frame)
1566 		goto err;
1567 	init_func_state(env, frame,
1568 			BPF_MAIN_FUNC /* callsite */,
1569 			0 /* frameno within this callchain */,
1570 			subprog /* subprog number within this prog */);
1571 	elem->st.frame[0] = frame;
1572 	return &elem->st;
1573 err:
1574 	free_verifier_state(env->cur_state, true);
1575 	env->cur_state = NULL;
1576 	/* pop all elements and return */
1577 	while (!pop_stack(env, NULL, NULL, false));
1578 	return NULL;
1579 }
1580 
1581 
1582 enum reg_arg_type {
1583 	SRC_OP,		/* register is used as source operand */
1584 	DST_OP,		/* register is used as destination operand */
1585 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1586 };
1587 
1588 static int cmp_subprogs(const void *a, const void *b)
1589 {
1590 	return ((struct bpf_subprog_info *)a)->start -
1591 	       ((struct bpf_subprog_info *)b)->start;
1592 }
1593 
1594 static int find_subprog(struct bpf_verifier_env *env, int off)
1595 {
1596 	struct bpf_subprog_info *p;
1597 
1598 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1599 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1600 	if (!p)
1601 		return -ENOENT;
1602 	return p - env->subprog_info;
1603 
1604 }
1605 
1606 static int add_subprog(struct bpf_verifier_env *env, int off)
1607 {
1608 	int insn_cnt = env->prog->len;
1609 	int ret;
1610 
1611 	if (off >= insn_cnt || off < 0) {
1612 		verbose(env, "call to invalid destination\n");
1613 		return -EINVAL;
1614 	}
1615 	ret = find_subprog(env, off);
1616 	if (ret >= 0)
1617 		return ret;
1618 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1619 		verbose(env, "too many subprograms\n");
1620 		return -E2BIG;
1621 	}
1622 	/* determine subprog starts. The end is one before the next starts */
1623 	env->subprog_info[env->subprog_cnt++].start = off;
1624 	sort(env->subprog_info, env->subprog_cnt,
1625 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1626 	return env->subprog_cnt - 1;
1627 }
1628 
1629 struct bpf_kfunc_desc {
1630 	struct btf_func_model func_model;
1631 	u32 func_id;
1632 	s32 imm;
1633 };
1634 
1635 #define MAX_KFUNC_DESCS 256
1636 struct bpf_kfunc_desc_tab {
1637 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1638 	u32 nr_descs;
1639 };
1640 
1641 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1642 {
1643 	const struct bpf_kfunc_desc *d0 = a;
1644 	const struct bpf_kfunc_desc *d1 = b;
1645 
1646 	/* func_id is not greater than BTF_MAX_TYPE */
1647 	return d0->func_id - d1->func_id;
1648 }
1649 
1650 static const struct bpf_kfunc_desc *
1651 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1652 {
1653 	struct bpf_kfunc_desc desc = {
1654 		.func_id = func_id,
1655 	};
1656 	struct bpf_kfunc_desc_tab *tab;
1657 
1658 	tab = prog->aux->kfunc_tab;
1659 	return bsearch(&desc, tab->descs, tab->nr_descs,
1660 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1661 }
1662 
1663 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1664 {
1665 	const struct btf_type *func, *func_proto;
1666 	struct bpf_kfunc_desc_tab *tab;
1667 	struct bpf_prog_aux *prog_aux;
1668 	struct bpf_kfunc_desc *desc;
1669 	const char *func_name;
1670 	unsigned long addr;
1671 	int err;
1672 
1673 	prog_aux = env->prog->aux;
1674 	tab = prog_aux->kfunc_tab;
1675 	if (!tab) {
1676 		if (!btf_vmlinux) {
1677 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1678 			return -ENOTSUPP;
1679 		}
1680 
1681 		if (!env->prog->jit_requested) {
1682 			verbose(env, "JIT is required for calling kernel function\n");
1683 			return -ENOTSUPP;
1684 		}
1685 
1686 		if (!bpf_jit_supports_kfunc_call()) {
1687 			verbose(env, "JIT does not support calling kernel function\n");
1688 			return -ENOTSUPP;
1689 		}
1690 
1691 		if (!env->prog->gpl_compatible) {
1692 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1693 			return -EINVAL;
1694 		}
1695 
1696 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1697 		if (!tab)
1698 			return -ENOMEM;
1699 		prog_aux->kfunc_tab = tab;
1700 	}
1701 
1702 	if (find_kfunc_desc(env->prog, func_id))
1703 		return 0;
1704 
1705 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1706 		verbose(env, "too many different kernel function calls\n");
1707 		return -E2BIG;
1708 	}
1709 
1710 	func = btf_type_by_id(btf_vmlinux, func_id);
1711 	if (!func || !btf_type_is_func(func)) {
1712 		verbose(env, "kernel btf_id %u is not a function\n",
1713 			func_id);
1714 		return -EINVAL;
1715 	}
1716 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
1717 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1718 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1719 			func_id);
1720 		return -EINVAL;
1721 	}
1722 
1723 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1724 	addr = kallsyms_lookup_name(func_name);
1725 	if (!addr) {
1726 		verbose(env, "cannot find address for kernel function %s\n",
1727 			func_name);
1728 		return -EINVAL;
1729 	}
1730 
1731 	desc = &tab->descs[tab->nr_descs++];
1732 	desc->func_id = func_id;
1733 	desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1734 	err = btf_distill_func_proto(&env->log, btf_vmlinux,
1735 				     func_proto, func_name,
1736 				     &desc->func_model);
1737 	if (!err)
1738 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1739 		     kfunc_desc_cmp_by_id, NULL);
1740 	return err;
1741 }
1742 
1743 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1744 {
1745 	const struct bpf_kfunc_desc *d0 = a;
1746 	const struct bpf_kfunc_desc *d1 = b;
1747 
1748 	if (d0->imm > d1->imm)
1749 		return 1;
1750 	else if (d0->imm < d1->imm)
1751 		return -1;
1752 	return 0;
1753 }
1754 
1755 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1756 {
1757 	struct bpf_kfunc_desc_tab *tab;
1758 
1759 	tab = prog->aux->kfunc_tab;
1760 	if (!tab)
1761 		return;
1762 
1763 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1764 	     kfunc_desc_cmp_by_imm, NULL);
1765 }
1766 
1767 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1768 {
1769 	return !!prog->aux->kfunc_tab;
1770 }
1771 
1772 const struct btf_func_model *
1773 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1774 			 const struct bpf_insn *insn)
1775 {
1776 	const struct bpf_kfunc_desc desc = {
1777 		.imm = insn->imm,
1778 	};
1779 	const struct bpf_kfunc_desc *res;
1780 	struct bpf_kfunc_desc_tab *tab;
1781 
1782 	tab = prog->aux->kfunc_tab;
1783 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1784 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1785 
1786 	return res ? &res->func_model : NULL;
1787 }
1788 
1789 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1790 {
1791 	struct bpf_subprog_info *subprog = env->subprog_info;
1792 	struct bpf_insn *insn = env->prog->insnsi;
1793 	int i, ret, insn_cnt = env->prog->len;
1794 
1795 	/* Add entry function. */
1796 	ret = add_subprog(env, 0);
1797 	if (ret)
1798 		return ret;
1799 
1800 	for (i = 0; i < insn_cnt; i++, insn++) {
1801 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1802 		    !bpf_pseudo_kfunc_call(insn))
1803 			continue;
1804 
1805 		if (!env->bpf_capable) {
1806 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1807 			return -EPERM;
1808 		}
1809 
1810 		if (bpf_pseudo_func(insn)) {
1811 			ret = add_subprog(env, i + insn->imm + 1);
1812 			if (ret >= 0)
1813 				/* remember subprog */
1814 				insn[1].imm = ret;
1815 		} else if (bpf_pseudo_call(insn)) {
1816 			ret = add_subprog(env, i + insn->imm + 1);
1817 		} else {
1818 			ret = add_kfunc_call(env, insn->imm);
1819 		}
1820 
1821 		if (ret < 0)
1822 			return ret;
1823 	}
1824 
1825 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1826 	 * logic. 'subprog_cnt' should not be increased.
1827 	 */
1828 	subprog[env->subprog_cnt].start = insn_cnt;
1829 
1830 	if (env->log.level & BPF_LOG_LEVEL2)
1831 		for (i = 0; i < env->subprog_cnt; i++)
1832 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1833 
1834 	return 0;
1835 }
1836 
1837 static int check_subprogs(struct bpf_verifier_env *env)
1838 {
1839 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1840 	struct bpf_subprog_info *subprog = env->subprog_info;
1841 	struct bpf_insn *insn = env->prog->insnsi;
1842 	int insn_cnt = env->prog->len;
1843 
1844 	/* now check that all jumps are within the same subprog */
1845 	subprog_start = subprog[cur_subprog].start;
1846 	subprog_end = subprog[cur_subprog + 1].start;
1847 	for (i = 0; i < insn_cnt; i++) {
1848 		u8 code = insn[i].code;
1849 
1850 		if (code == (BPF_JMP | BPF_CALL) &&
1851 		    insn[i].imm == BPF_FUNC_tail_call &&
1852 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1853 			subprog[cur_subprog].has_tail_call = true;
1854 		if (BPF_CLASS(code) == BPF_LD &&
1855 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1856 			subprog[cur_subprog].has_ld_abs = true;
1857 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1858 			goto next;
1859 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1860 			goto next;
1861 		off = i + insn[i].off + 1;
1862 		if (off < subprog_start || off >= subprog_end) {
1863 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1864 			return -EINVAL;
1865 		}
1866 next:
1867 		if (i == subprog_end - 1) {
1868 			/* to avoid fall-through from one subprog into another
1869 			 * the last insn of the subprog should be either exit
1870 			 * or unconditional jump back
1871 			 */
1872 			if (code != (BPF_JMP | BPF_EXIT) &&
1873 			    code != (BPF_JMP | BPF_JA)) {
1874 				verbose(env, "last insn is not an exit or jmp\n");
1875 				return -EINVAL;
1876 			}
1877 			subprog_start = subprog_end;
1878 			cur_subprog++;
1879 			if (cur_subprog < env->subprog_cnt)
1880 				subprog_end = subprog[cur_subprog + 1].start;
1881 		}
1882 	}
1883 	return 0;
1884 }
1885 
1886 /* Parentage chain of this register (or stack slot) should take care of all
1887  * issues like callee-saved registers, stack slot allocation time, etc.
1888  */
1889 static int mark_reg_read(struct bpf_verifier_env *env,
1890 			 const struct bpf_reg_state *state,
1891 			 struct bpf_reg_state *parent, u8 flag)
1892 {
1893 	bool writes = parent == state->parent; /* Observe write marks */
1894 	int cnt = 0;
1895 
1896 	while (parent) {
1897 		/* if read wasn't screened by an earlier write ... */
1898 		if (writes && state->live & REG_LIVE_WRITTEN)
1899 			break;
1900 		if (parent->live & REG_LIVE_DONE) {
1901 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1902 				reg_type_str[parent->type],
1903 				parent->var_off.value, parent->off);
1904 			return -EFAULT;
1905 		}
1906 		/* The first condition is more likely to be true than the
1907 		 * second, checked it first.
1908 		 */
1909 		if ((parent->live & REG_LIVE_READ) == flag ||
1910 		    parent->live & REG_LIVE_READ64)
1911 			/* The parentage chain never changes and
1912 			 * this parent was already marked as LIVE_READ.
1913 			 * There is no need to keep walking the chain again and
1914 			 * keep re-marking all parents as LIVE_READ.
1915 			 * This case happens when the same register is read
1916 			 * multiple times without writes into it in-between.
1917 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1918 			 * then no need to set the weak REG_LIVE_READ32.
1919 			 */
1920 			break;
1921 		/* ... then we depend on parent's value */
1922 		parent->live |= flag;
1923 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1924 		if (flag == REG_LIVE_READ64)
1925 			parent->live &= ~REG_LIVE_READ32;
1926 		state = parent;
1927 		parent = state->parent;
1928 		writes = true;
1929 		cnt++;
1930 	}
1931 
1932 	if (env->longest_mark_read_walk < cnt)
1933 		env->longest_mark_read_walk = cnt;
1934 	return 0;
1935 }
1936 
1937 /* This function is supposed to be used by the following 32-bit optimization
1938  * code only. It returns TRUE if the source or destination register operates
1939  * on 64-bit, otherwise return FALSE.
1940  */
1941 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1942 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1943 {
1944 	u8 code, class, op;
1945 
1946 	code = insn->code;
1947 	class = BPF_CLASS(code);
1948 	op = BPF_OP(code);
1949 	if (class == BPF_JMP) {
1950 		/* BPF_EXIT for "main" will reach here. Return TRUE
1951 		 * conservatively.
1952 		 */
1953 		if (op == BPF_EXIT)
1954 			return true;
1955 		if (op == BPF_CALL) {
1956 			/* BPF to BPF call will reach here because of marking
1957 			 * caller saved clobber with DST_OP_NO_MARK for which we
1958 			 * don't care the register def because they are anyway
1959 			 * marked as NOT_INIT already.
1960 			 */
1961 			if (insn->src_reg == BPF_PSEUDO_CALL)
1962 				return false;
1963 			/* Helper call will reach here because of arg type
1964 			 * check, conservatively return TRUE.
1965 			 */
1966 			if (t == SRC_OP)
1967 				return true;
1968 
1969 			return false;
1970 		}
1971 	}
1972 
1973 	if (class == BPF_ALU64 || class == BPF_JMP ||
1974 	    /* BPF_END always use BPF_ALU class. */
1975 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1976 		return true;
1977 
1978 	if (class == BPF_ALU || class == BPF_JMP32)
1979 		return false;
1980 
1981 	if (class == BPF_LDX) {
1982 		if (t != SRC_OP)
1983 			return BPF_SIZE(code) == BPF_DW;
1984 		/* LDX source must be ptr. */
1985 		return true;
1986 	}
1987 
1988 	if (class == BPF_STX) {
1989 		/* BPF_STX (including atomic variants) has multiple source
1990 		 * operands, one of which is a ptr. Check whether the caller is
1991 		 * asking about it.
1992 		 */
1993 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
1994 			return true;
1995 		return BPF_SIZE(code) == BPF_DW;
1996 	}
1997 
1998 	if (class == BPF_LD) {
1999 		u8 mode = BPF_MODE(code);
2000 
2001 		/* LD_IMM64 */
2002 		if (mode == BPF_IMM)
2003 			return true;
2004 
2005 		/* Both LD_IND and LD_ABS return 32-bit data. */
2006 		if (t != SRC_OP)
2007 			return  false;
2008 
2009 		/* Implicit ctx ptr. */
2010 		if (regno == BPF_REG_6)
2011 			return true;
2012 
2013 		/* Explicit source could be any width. */
2014 		return true;
2015 	}
2016 
2017 	if (class == BPF_ST)
2018 		/* The only source register for BPF_ST is a ptr. */
2019 		return true;
2020 
2021 	/* Conservatively return true at default. */
2022 	return true;
2023 }
2024 
2025 /* Return the regno defined by the insn, or -1. */
2026 static int insn_def_regno(const struct bpf_insn *insn)
2027 {
2028 	switch (BPF_CLASS(insn->code)) {
2029 	case BPF_JMP:
2030 	case BPF_JMP32:
2031 	case BPF_ST:
2032 		return -1;
2033 	case BPF_STX:
2034 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2035 		    (insn->imm & BPF_FETCH)) {
2036 			if (insn->imm == BPF_CMPXCHG)
2037 				return BPF_REG_0;
2038 			else
2039 				return insn->src_reg;
2040 		} else {
2041 			return -1;
2042 		}
2043 	default:
2044 		return insn->dst_reg;
2045 	}
2046 }
2047 
2048 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2049 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2050 {
2051 	int dst_reg = insn_def_regno(insn);
2052 
2053 	if (dst_reg == -1)
2054 		return false;
2055 
2056 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2057 }
2058 
2059 static void mark_insn_zext(struct bpf_verifier_env *env,
2060 			   struct bpf_reg_state *reg)
2061 {
2062 	s32 def_idx = reg->subreg_def;
2063 
2064 	if (def_idx == DEF_NOT_SUBREG)
2065 		return;
2066 
2067 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2068 	/* The dst will be zero extended, so won't be sub-register anymore. */
2069 	reg->subreg_def = DEF_NOT_SUBREG;
2070 }
2071 
2072 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2073 			 enum reg_arg_type t)
2074 {
2075 	struct bpf_verifier_state *vstate = env->cur_state;
2076 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2077 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2078 	struct bpf_reg_state *reg, *regs = state->regs;
2079 	bool rw64;
2080 
2081 	if (regno >= MAX_BPF_REG) {
2082 		verbose(env, "R%d is invalid\n", regno);
2083 		return -EINVAL;
2084 	}
2085 
2086 	reg = &regs[regno];
2087 	rw64 = is_reg64(env, insn, regno, reg, t);
2088 	if (t == SRC_OP) {
2089 		/* check whether register used as source operand can be read */
2090 		if (reg->type == NOT_INIT) {
2091 			verbose(env, "R%d !read_ok\n", regno);
2092 			return -EACCES;
2093 		}
2094 		/* We don't need to worry about FP liveness because it's read-only */
2095 		if (regno == BPF_REG_FP)
2096 			return 0;
2097 
2098 		if (rw64)
2099 			mark_insn_zext(env, reg);
2100 
2101 		return mark_reg_read(env, reg, reg->parent,
2102 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2103 	} else {
2104 		/* check whether register used as dest operand can be written to */
2105 		if (regno == BPF_REG_FP) {
2106 			verbose(env, "frame pointer is read only\n");
2107 			return -EACCES;
2108 		}
2109 		reg->live |= REG_LIVE_WRITTEN;
2110 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2111 		if (t == DST_OP)
2112 			mark_reg_unknown(env, regs, regno);
2113 	}
2114 	return 0;
2115 }
2116 
2117 /* for any branch, call, exit record the history of jmps in the given state */
2118 static int push_jmp_history(struct bpf_verifier_env *env,
2119 			    struct bpf_verifier_state *cur)
2120 {
2121 	u32 cnt = cur->jmp_history_cnt;
2122 	struct bpf_idx_pair *p;
2123 
2124 	cnt++;
2125 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2126 	if (!p)
2127 		return -ENOMEM;
2128 	p[cnt - 1].idx = env->insn_idx;
2129 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2130 	cur->jmp_history = p;
2131 	cur->jmp_history_cnt = cnt;
2132 	return 0;
2133 }
2134 
2135 /* Backtrack one insn at a time. If idx is not at the top of recorded
2136  * history then previous instruction came from straight line execution.
2137  */
2138 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2139 			     u32 *history)
2140 {
2141 	u32 cnt = *history;
2142 
2143 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2144 		i = st->jmp_history[cnt - 1].prev_idx;
2145 		(*history)--;
2146 	} else {
2147 		i--;
2148 	}
2149 	return i;
2150 }
2151 
2152 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2153 {
2154 	const struct btf_type *func;
2155 
2156 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2157 		return NULL;
2158 
2159 	func = btf_type_by_id(btf_vmlinux, insn->imm);
2160 	return btf_name_by_offset(btf_vmlinux, func->name_off);
2161 }
2162 
2163 /* For given verifier state backtrack_insn() is called from the last insn to
2164  * the first insn. Its purpose is to compute a bitmask of registers and
2165  * stack slots that needs precision in the parent verifier state.
2166  */
2167 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2168 			  u32 *reg_mask, u64 *stack_mask)
2169 {
2170 	const struct bpf_insn_cbs cbs = {
2171 		.cb_call	= disasm_kfunc_name,
2172 		.cb_print	= verbose,
2173 		.private_data	= env,
2174 	};
2175 	struct bpf_insn *insn = env->prog->insnsi + idx;
2176 	u8 class = BPF_CLASS(insn->code);
2177 	u8 opcode = BPF_OP(insn->code);
2178 	u8 mode = BPF_MODE(insn->code);
2179 	u32 dreg = 1u << insn->dst_reg;
2180 	u32 sreg = 1u << insn->src_reg;
2181 	u32 spi;
2182 
2183 	if (insn->code == 0)
2184 		return 0;
2185 	if (env->log.level & BPF_LOG_LEVEL) {
2186 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2187 		verbose(env, "%d: ", idx);
2188 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2189 	}
2190 
2191 	if (class == BPF_ALU || class == BPF_ALU64) {
2192 		if (!(*reg_mask & dreg))
2193 			return 0;
2194 		if (opcode == BPF_MOV) {
2195 			if (BPF_SRC(insn->code) == BPF_X) {
2196 				/* dreg = sreg
2197 				 * dreg needs precision after this insn
2198 				 * sreg needs precision before this insn
2199 				 */
2200 				*reg_mask &= ~dreg;
2201 				*reg_mask |= sreg;
2202 			} else {
2203 				/* dreg = K
2204 				 * dreg needs precision after this insn.
2205 				 * Corresponding register is already marked
2206 				 * as precise=true in this verifier state.
2207 				 * No further markings in parent are necessary
2208 				 */
2209 				*reg_mask &= ~dreg;
2210 			}
2211 		} else {
2212 			if (BPF_SRC(insn->code) == BPF_X) {
2213 				/* dreg += sreg
2214 				 * both dreg and sreg need precision
2215 				 * before this insn
2216 				 */
2217 				*reg_mask |= sreg;
2218 			} /* else dreg += K
2219 			   * dreg still needs precision before this insn
2220 			   */
2221 		}
2222 	} else if (class == BPF_LDX) {
2223 		if (!(*reg_mask & dreg))
2224 			return 0;
2225 		*reg_mask &= ~dreg;
2226 
2227 		/* scalars can only be spilled into stack w/o losing precision.
2228 		 * Load from any other memory can be zero extended.
2229 		 * The desire to keep that precision is already indicated
2230 		 * by 'precise' mark in corresponding register of this state.
2231 		 * No further tracking necessary.
2232 		 */
2233 		if (insn->src_reg != BPF_REG_FP)
2234 			return 0;
2235 		if (BPF_SIZE(insn->code) != BPF_DW)
2236 			return 0;
2237 
2238 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2239 		 * that [fp - off] slot contains scalar that needs to be
2240 		 * tracked with precision
2241 		 */
2242 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2243 		if (spi >= 64) {
2244 			verbose(env, "BUG spi %d\n", spi);
2245 			WARN_ONCE(1, "verifier backtracking bug");
2246 			return -EFAULT;
2247 		}
2248 		*stack_mask |= 1ull << spi;
2249 	} else if (class == BPF_STX || class == BPF_ST) {
2250 		if (*reg_mask & dreg)
2251 			/* stx & st shouldn't be using _scalar_ dst_reg
2252 			 * to access memory. It means backtracking
2253 			 * encountered a case of pointer subtraction.
2254 			 */
2255 			return -ENOTSUPP;
2256 		/* scalars can only be spilled into stack */
2257 		if (insn->dst_reg != BPF_REG_FP)
2258 			return 0;
2259 		if (BPF_SIZE(insn->code) != BPF_DW)
2260 			return 0;
2261 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2262 		if (spi >= 64) {
2263 			verbose(env, "BUG spi %d\n", spi);
2264 			WARN_ONCE(1, "verifier backtracking bug");
2265 			return -EFAULT;
2266 		}
2267 		if (!(*stack_mask & (1ull << spi)))
2268 			return 0;
2269 		*stack_mask &= ~(1ull << spi);
2270 		if (class == BPF_STX)
2271 			*reg_mask |= sreg;
2272 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2273 		if (opcode == BPF_CALL) {
2274 			if (insn->src_reg == BPF_PSEUDO_CALL)
2275 				return -ENOTSUPP;
2276 			/* regular helper call sets R0 */
2277 			*reg_mask &= ~1;
2278 			if (*reg_mask & 0x3f) {
2279 				/* if backtracing was looking for registers R1-R5
2280 				 * they should have been found already.
2281 				 */
2282 				verbose(env, "BUG regs %x\n", *reg_mask);
2283 				WARN_ONCE(1, "verifier backtracking bug");
2284 				return -EFAULT;
2285 			}
2286 		} else if (opcode == BPF_EXIT) {
2287 			return -ENOTSUPP;
2288 		}
2289 	} else if (class == BPF_LD) {
2290 		if (!(*reg_mask & dreg))
2291 			return 0;
2292 		*reg_mask &= ~dreg;
2293 		/* It's ld_imm64 or ld_abs or ld_ind.
2294 		 * For ld_imm64 no further tracking of precision
2295 		 * into parent is necessary
2296 		 */
2297 		if (mode == BPF_IND || mode == BPF_ABS)
2298 			/* to be analyzed */
2299 			return -ENOTSUPP;
2300 	}
2301 	return 0;
2302 }
2303 
2304 /* the scalar precision tracking algorithm:
2305  * . at the start all registers have precise=false.
2306  * . scalar ranges are tracked as normal through alu and jmp insns.
2307  * . once precise value of the scalar register is used in:
2308  *   .  ptr + scalar alu
2309  *   . if (scalar cond K|scalar)
2310  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2311  *   backtrack through the verifier states and mark all registers and
2312  *   stack slots with spilled constants that these scalar regisers
2313  *   should be precise.
2314  * . during state pruning two registers (or spilled stack slots)
2315  *   are equivalent if both are not precise.
2316  *
2317  * Note the verifier cannot simply walk register parentage chain,
2318  * since many different registers and stack slots could have been
2319  * used to compute single precise scalar.
2320  *
2321  * The approach of starting with precise=true for all registers and then
2322  * backtrack to mark a register as not precise when the verifier detects
2323  * that program doesn't care about specific value (e.g., when helper
2324  * takes register as ARG_ANYTHING parameter) is not safe.
2325  *
2326  * It's ok to walk single parentage chain of the verifier states.
2327  * It's possible that this backtracking will go all the way till 1st insn.
2328  * All other branches will be explored for needing precision later.
2329  *
2330  * The backtracking needs to deal with cases like:
2331  *   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)
2332  * r9 -= r8
2333  * r5 = r9
2334  * if r5 > 0x79f goto pc+7
2335  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2336  * r5 += 1
2337  * ...
2338  * call bpf_perf_event_output#25
2339  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2340  *
2341  * and this case:
2342  * r6 = 1
2343  * call foo // uses callee's r6 inside to compute r0
2344  * r0 += r6
2345  * if r0 == 0 goto
2346  *
2347  * to track above reg_mask/stack_mask needs to be independent for each frame.
2348  *
2349  * Also if parent's curframe > frame where backtracking started,
2350  * the verifier need to mark registers in both frames, otherwise callees
2351  * may incorrectly prune callers. This is similar to
2352  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2353  *
2354  * For now backtracking falls back into conservative marking.
2355  */
2356 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2357 				     struct bpf_verifier_state *st)
2358 {
2359 	struct bpf_func_state *func;
2360 	struct bpf_reg_state *reg;
2361 	int i, j;
2362 
2363 	/* big hammer: mark all scalars precise in this path.
2364 	 * pop_stack may still get !precise scalars.
2365 	 */
2366 	for (; st; st = st->parent)
2367 		for (i = 0; i <= st->curframe; i++) {
2368 			func = st->frame[i];
2369 			for (j = 0; j < BPF_REG_FP; j++) {
2370 				reg = &func->regs[j];
2371 				if (reg->type != SCALAR_VALUE)
2372 					continue;
2373 				reg->precise = true;
2374 			}
2375 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2376 				if (func->stack[j].slot_type[0] != STACK_SPILL)
2377 					continue;
2378 				reg = &func->stack[j].spilled_ptr;
2379 				if (reg->type != SCALAR_VALUE)
2380 					continue;
2381 				reg->precise = true;
2382 			}
2383 		}
2384 }
2385 
2386 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2387 				  int spi)
2388 {
2389 	struct bpf_verifier_state *st = env->cur_state;
2390 	int first_idx = st->first_insn_idx;
2391 	int last_idx = env->insn_idx;
2392 	struct bpf_func_state *func;
2393 	struct bpf_reg_state *reg;
2394 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2395 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2396 	bool skip_first = true;
2397 	bool new_marks = false;
2398 	int i, err;
2399 
2400 	if (!env->bpf_capable)
2401 		return 0;
2402 
2403 	func = st->frame[st->curframe];
2404 	if (regno >= 0) {
2405 		reg = &func->regs[regno];
2406 		if (reg->type != SCALAR_VALUE) {
2407 			WARN_ONCE(1, "backtracing misuse");
2408 			return -EFAULT;
2409 		}
2410 		if (!reg->precise)
2411 			new_marks = true;
2412 		else
2413 			reg_mask = 0;
2414 		reg->precise = true;
2415 	}
2416 
2417 	while (spi >= 0) {
2418 		if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2419 			stack_mask = 0;
2420 			break;
2421 		}
2422 		reg = &func->stack[spi].spilled_ptr;
2423 		if (reg->type != SCALAR_VALUE) {
2424 			stack_mask = 0;
2425 			break;
2426 		}
2427 		if (!reg->precise)
2428 			new_marks = true;
2429 		else
2430 			stack_mask = 0;
2431 		reg->precise = true;
2432 		break;
2433 	}
2434 
2435 	if (!new_marks)
2436 		return 0;
2437 	if (!reg_mask && !stack_mask)
2438 		return 0;
2439 	for (;;) {
2440 		DECLARE_BITMAP(mask, 64);
2441 		u32 history = st->jmp_history_cnt;
2442 
2443 		if (env->log.level & BPF_LOG_LEVEL)
2444 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2445 		for (i = last_idx;;) {
2446 			if (skip_first) {
2447 				err = 0;
2448 				skip_first = false;
2449 			} else {
2450 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2451 			}
2452 			if (err == -ENOTSUPP) {
2453 				mark_all_scalars_precise(env, st);
2454 				return 0;
2455 			} else if (err) {
2456 				return err;
2457 			}
2458 			if (!reg_mask && !stack_mask)
2459 				/* Found assignment(s) into tracked register in this state.
2460 				 * Since this state is already marked, just return.
2461 				 * Nothing to be tracked further in the parent state.
2462 				 */
2463 				return 0;
2464 			if (i == first_idx)
2465 				break;
2466 			i = get_prev_insn_idx(st, i, &history);
2467 			if (i >= env->prog->len) {
2468 				/* This can happen if backtracking reached insn 0
2469 				 * and there are still reg_mask or stack_mask
2470 				 * to backtrack.
2471 				 * It means the backtracking missed the spot where
2472 				 * particular register was initialized with a constant.
2473 				 */
2474 				verbose(env, "BUG backtracking idx %d\n", i);
2475 				WARN_ONCE(1, "verifier backtracking bug");
2476 				return -EFAULT;
2477 			}
2478 		}
2479 		st = st->parent;
2480 		if (!st)
2481 			break;
2482 
2483 		new_marks = false;
2484 		func = st->frame[st->curframe];
2485 		bitmap_from_u64(mask, reg_mask);
2486 		for_each_set_bit(i, mask, 32) {
2487 			reg = &func->regs[i];
2488 			if (reg->type != SCALAR_VALUE) {
2489 				reg_mask &= ~(1u << i);
2490 				continue;
2491 			}
2492 			if (!reg->precise)
2493 				new_marks = true;
2494 			reg->precise = true;
2495 		}
2496 
2497 		bitmap_from_u64(mask, stack_mask);
2498 		for_each_set_bit(i, mask, 64) {
2499 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2500 				/* the sequence of instructions:
2501 				 * 2: (bf) r3 = r10
2502 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2503 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2504 				 * doesn't contain jmps. It's backtracked
2505 				 * as a single block.
2506 				 * During backtracking insn 3 is not recognized as
2507 				 * stack access, so at the end of backtracking
2508 				 * stack slot fp-8 is still marked in stack_mask.
2509 				 * However the parent state may not have accessed
2510 				 * fp-8 and it's "unallocated" stack space.
2511 				 * In such case fallback to conservative.
2512 				 */
2513 				mark_all_scalars_precise(env, st);
2514 				return 0;
2515 			}
2516 
2517 			if (func->stack[i].slot_type[0] != STACK_SPILL) {
2518 				stack_mask &= ~(1ull << i);
2519 				continue;
2520 			}
2521 			reg = &func->stack[i].spilled_ptr;
2522 			if (reg->type != SCALAR_VALUE) {
2523 				stack_mask &= ~(1ull << i);
2524 				continue;
2525 			}
2526 			if (!reg->precise)
2527 				new_marks = true;
2528 			reg->precise = true;
2529 		}
2530 		if (env->log.level & BPF_LOG_LEVEL) {
2531 			print_verifier_state(env, func);
2532 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2533 				new_marks ? "didn't have" : "already had",
2534 				reg_mask, stack_mask);
2535 		}
2536 
2537 		if (!reg_mask && !stack_mask)
2538 			break;
2539 		if (!new_marks)
2540 			break;
2541 
2542 		last_idx = st->last_insn_idx;
2543 		first_idx = st->first_insn_idx;
2544 	}
2545 	return 0;
2546 }
2547 
2548 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2549 {
2550 	return __mark_chain_precision(env, regno, -1);
2551 }
2552 
2553 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2554 {
2555 	return __mark_chain_precision(env, -1, spi);
2556 }
2557 
2558 static bool is_spillable_regtype(enum bpf_reg_type type)
2559 {
2560 	switch (type) {
2561 	case PTR_TO_MAP_VALUE:
2562 	case PTR_TO_MAP_VALUE_OR_NULL:
2563 	case PTR_TO_STACK:
2564 	case PTR_TO_CTX:
2565 	case PTR_TO_PACKET:
2566 	case PTR_TO_PACKET_META:
2567 	case PTR_TO_PACKET_END:
2568 	case PTR_TO_FLOW_KEYS:
2569 	case CONST_PTR_TO_MAP:
2570 	case PTR_TO_SOCKET:
2571 	case PTR_TO_SOCKET_OR_NULL:
2572 	case PTR_TO_SOCK_COMMON:
2573 	case PTR_TO_SOCK_COMMON_OR_NULL:
2574 	case PTR_TO_TCP_SOCK:
2575 	case PTR_TO_TCP_SOCK_OR_NULL:
2576 	case PTR_TO_XDP_SOCK:
2577 	case PTR_TO_BTF_ID:
2578 	case PTR_TO_BTF_ID_OR_NULL:
2579 	case PTR_TO_RDONLY_BUF:
2580 	case PTR_TO_RDONLY_BUF_OR_NULL:
2581 	case PTR_TO_RDWR_BUF:
2582 	case PTR_TO_RDWR_BUF_OR_NULL:
2583 	case PTR_TO_PERCPU_BTF_ID:
2584 	case PTR_TO_MEM:
2585 	case PTR_TO_MEM_OR_NULL:
2586 	case PTR_TO_FUNC:
2587 	case PTR_TO_MAP_KEY:
2588 		return true;
2589 	default:
2590 		return false;
2591 	}
2592 }
2593 
2594 /* Does this register contain a constant zero? */
2595 static bool register_is_null(struct bpf_reg_state *reg)
2596 {
2597 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2598 }
2599 
2600 static bool register_is_const(struct bpf_reg_state *reg)
2601 {
2602 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2603 }
2604 
2605 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2606 {
2607 	return tnum_is_unknown(reg->var_off) &&
2608 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2609 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2610 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2611 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2612 }
2613 
2614 static bool register_is_bounded(struct bpf_reg_state *reg)
2615 {
2616 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2617 }
2618 
2619 static bool __is_pointer_value(bool allow_ptr_leaks,
2620 			       const struct bpf_reg_state *reg)
2621 {
2622 	if (allow_ptr_leaks)
2623 		return false;
2624 
2625 	return reg->type != SCALAR_VALUE;
2626 }
2627 
2628 static void save_register_state(struct bpf_func_state *state,
2629 				int spi, struct bpf_reg_state *reg)
2630 {
2631 	int i;
2632 
2633 	state->stack[spi].spilled_ptr = *reg;
2634 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2635 
2636 	for (i = 0; i < BPF_REG_SIZE; i++)
2637 		state->stack[spi].slot_type[i] = STACK_SPILL;
2638 }
2639 
2640 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2641  * stack boundary and alignment are checked in check_mem_access()
2642  */
2643 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2644 				       /* stack frame we're writing to */
2645 				       struct bpf_func_state *state,
2646 				       int off, int size, int value_regno,
2647 				       int insn_idx)
2648 {
2649 	struct bpf_func_state *cur; /* state of the current function */
2650 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2651 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2652 	struct bpf_reg_state *reg = NULL;
2653 
2654 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2655 	if (err)
2656 		return err;
2657 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2658 	 * so it's aligned access and [off, off + size) are within stack limits
2659 	 */
2660 	if (!env->allow_ptr_leaks &&
2661 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2662 	    size != BPF_REG_SIZE) {
2663 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2664 		return -EACCES;
2665 	}
2666 
2667 	cur = env->cur_state->frame[env->cur_state->curframe];
2668 	if (value_regno >= 0)
2669 		reg = &cur->regs[value_regno];
2670 
2671 	if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2672 	    !register_is_null(reg) && env->bpf_capable) {
2673 		if (dst_reg != BPF_REG_FP) {
2674 			/* The backtracking logic can only recognize explicit
2675 			 * stack slot address like [fp - 8]. Other spill of
2676 			 * scalar via different register has to be conservative.
2677 			 * Backtrack from here and mark all registers as precise
2678 			 * that contributed into 'reg' being a constant.
2679 			 */
2680 			err = mark_chain_precision(env, value_regno);
2681 			if (err)
2682 				return err;
2683 		}
2684 		save_register_state(state, spi, reg);
2685 	} else if (reg && is_spillable_regtype(reg->type)) {
2686 		/* register containing pointer is being spilled into stack */
2687 		if (size != BPF_REG_SIZE) {
2688 			verbose_linfo(env, insn_idx, "; ");
2689 			verbose(env, "invalid size of register spill\n");
2690 			return -EACCES;
2691 		}
2692 
2693 		if (state != cur && reg->type == PTR_TO_STACK) {
2694 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2695 			return -EINVAL;
2696 		}
2697 
2698 		if (!env->bypass_spec_v4) {
2699 			bool sanitize = false;
2700 
2701 			if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2702 			    register_is_const(&state->stack[spi].spilled_ptr))
2703 				sanitize = true;
2704 			for (i = 0; i < BPF_REG_SIZE; i++)
2705 				if (state->stack[spi].slot_type[i] == STACK_MISC) {
2706 					sanitize = true;
2707 					break;
2708 				}
2709 			if (sanitize) {
2710 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2711 				int soff = (-spi - 1) * BPF_REG_SIZE;
2712 
2713 				/* detected reuse of integer stack slot with a pointer
2714 				 * which means either llvm is reusing stack slot or
2715 				 * an attacker is trying to exploit CVE-2018-3639
2716 				 * (speculative store bypass)
2717 				 * Have to sanitize that slot with preemptive
2718 				 * store of zero.
2719 				 */
2720 				if (*poff && *poff != soff) {
2721 					/* disallow programs where single insn stores
2722 					 * into two different stack slots, since verifier
2723 					 * cannot sanitize them
2724 					 */
2725 					verbose(env,
2726 						"insn %d cannot access two stack slots fp%d and fp%d",
2727 						insn_idx, *poff, soff);
2728 					return -EINVAL;
2729 				}
2730 				*poff = soff;
2731 			}
2732 		}
2733 		save_register_state(state, spi, reg);
2734 	} else {
2735 		u8 type = STACK_MISC;
2736 
2737 		/* regular write of data into stack destroys any spilled ptr */
2738 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2739 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2740 		if (state->stack[spi].slot_type[0] == STACK_SPILL)
2741 			for (i = 0; i < BPF_REG_SIZE; i++)
2742 				state->stack[spi].slot_type[i] = STACK_MISC;
2743 
2744 		/* only mark the slot as written if all 8 bytes were written
2745 		 * otherwise read propagation may incorrectly stop too soon
2746 		 * when stack slots are partially written.
2747 		 * This heuristic means that read propagation will be
2748 		 * conservative, since it will add reg_live_read marks
2749 		 * to stack slots all the way to first state when programs
2750 		 * writes+reads less than 8 bytes
2751 		 */
2752 		if (size == BPF_REG_SIZE)
2753 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2754 
2755 		/* when we zero initialize stack slots mark them as such */
2756 		if (reg && register_is_null(reg)) {
2757 			/* backtracking doesn't work for STACK_ZERO yet. */
2758 			err = mark_chain_precision(env, value_regno);
2759 			if (err)
2760 				return err;
2761 			type = STACK_ZERO;
2762 		}
2763 
2764 		/* Mark slots affected by this stack write. */
2765 		for (i = 0; i < size; i++)
2766 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2767 				type;
2768 	}
2769 	return 0;
2770 }
2771 
2772 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2773  * known to contain a variable offset.
2774  * This function checks whether the write is permitted and conservatively
2775  * tracks the effects of the write, considering that each stack slot in the
2776  * dynamic range is potentially written to.
2777  *
2778  * 'off' includes 'regno->off'.
2779  * 'value_regno' can be -1, meaning that an unknown value is being written to
2780  * the stack.
2781  *
2782  * Spilled pointers in range are not marked as written because we don't know
2783  * what's going to be actually written. This means that read propagation for
2784  * future reads cannot be terminated by this write.
2785  *
2786  * For privileged programs, uninitialized stack slots are considered
2787  * initialized by this write (even though we don't know exactly what offsets
2788  * are going to be written to). The idea is that we don't want the verifier to
2789  * reject future reads that access slots written to through variable offsets.
2790  */
2791 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2792 				     /* func where register points to */
2793 				     struct bpf_func_state *state,
2794 				     int ptr_regno, int off, int size,
2795 				     int value_regno, int insn_idx)
2796 {
2797 	struct bpf_func_state *cur; /* state of the current function */
2798 	int min_off, max_off;
2799 	int i, err;
2800 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2801 	bool writing_zero = false;
2802 	/* set if the fact that we're writing a zero is used to let any
2803 	 * stack slots remain STACK_ZERO
2804 	 */
2805 	bool zero_used = false;
2806 
2807 	cur = env->cur_state->frame[env->cur_state->curframe];
2808 	ptr_reg = &cur->regs[ptr_regno];
2809 	min_off = ptr_reg->smin_value + off;
2810 	max_off = ptr_reg->smax_value + off + size;
2811 	if (value_regno >= 0)
2812 		value_reg = &cur->regs[value_regno];
2813 	if (value_reg && register_is_null(value_reg))
2814 		writing_zero = true;
2815 
2816 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2817 	if (err)
2818 		return err;
2819 
2820 
2821 	/* Variable offset writes destroy any spilled pointers in range. */
2822 	for (i = min_off; i < max_off; i++) {
2823 		u8 new_type, *stype;
2824 		int slot, spi;
2825 
2826 		slot = -i - 1;
2827 		spi = slot / BPF_REG_SIZE;
2828 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2829 
2830 		if (!env->allow_ptr_leaks
2831 				&& *stype != NOT_INIT
2832 				&& *stype != SCALAR_VALUE) {
2833 			/* Reject the write if there's are spilled pointers in
2834 			 * range. If we didn't reject here, the ptr status
2835 			 * would be erased below (even though not all slots are
2836 			 * actually overwritten), possibly opening the door to
2837 			 * leaks.
2838 			 */
2839 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2840 				insn_idx, i);
2841 			return -EINVAL;
2842 		}
2843 
2844 		/* Erase all spilled pointers. */
2845 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2846 
2847 		/* Update the slot type. */
2848 		new_type = STACK_MISC;
2849 		if (writing_zero && *stype == STACK_ZERO) {
2850 			new_type = STACK_ZERO;
2851 			zero_used = true;
2852 		}
2853 		/* If the slot is STACK_INVALID, we check whether it's OK to
2854 		 * pretend that it will be initialized by this write. The slot
2855 		 * might not actually be written to, and so if we mark it as
2856 		 * initialized future reads might leak uninitialized memory.
2857 		 * For privileged programs, we will accept such reads to slots
2858 		 * that may or may not be written because, if we're reject
2859 		 * them, the error would be too confusing.
2860 		 */
2861 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2862 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2863 					insn_idx, i);
2864 			return -EINVAL;
2865 		}
2866 		*stype = new_type;
2867 	}
2868 	if (zero_used) {
2869 		/* backtracking doesn't work for STACK_ZERO yet. */
2870 		err = mark_chain_precision(env, value_regno);
2871 		if (err)
2872 			return err;
2873 	}
2874 	return 0;
2875 }
2876 
2877 /* When register 'dst_regno' is assigned some values from stack[min_off,
2878  * max_off), we set the register's type according to the types of the
2879  * respective stack slots. If all the stack values are known to be zeros, then
2880  * so is the destination reg. Otherwise, the register is considered to be
2881  * SCALAR. This function does not deal with register filling; the caller must
2882  * ensure that all spilled registers in the stack range have been marked as
2883  * read.
2884  */
2885 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2886 				/* func where src register points to */
2887 				struct bpf_func_state *ptr_state,
2888 				int min_off, int max_off, int dst_regno)
2889 {
2890 	struct bpf_verifier_state *vstate = env->cur_state;
2891 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2892 	int i, slot, spi;
2893 	u8 *stype;
2894 	int zeros = 0;
2895 
2896 	for (i = min_off; i < max_off; i++) {
2897 		slot = -i - 1;
2898 		spi = slot / BPF_REG_SIZE;
2899 		stype = ptr_state->stack[spi].slot_type;
2900 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2901 			break;
2902 		zeros++;
2903 	}
2904 	if (zeros == max_off - min_off) {
2905 		/* any access_size read into register is zero extended,
2906 		 * so the whole register == const_zero
2907 		 */
2908 		__mark_reg_const_zero(&state->regs[dst_regno]);
2909 		/* backtracking doesn't support STACK_ZERO yet,
2910 		 * so mark it precise here, so that later
2911 		 * backtracking can stop here.
2912 		 * Backtracking may not need this if this register
2913 		 * doesn't participate in pointer adjustment.
2914 		 * Forward propagation of precise flag is not
2915 		 * necessary either. This mark is only to stop
2916 		 * backtracking. Any register that contributed
2917 		 * to const 0 was marked precise before spill.
2918 		 */
2919 		state->regs[dst_regno].precise = true;
2920 	} else {
2921 		/* have read misc data from the stack */
2922 		mark_reg_unknown(env, state->regs, dst_regno);
2923 	}
2924 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2925 }
2926 
2927 /* Read the stack at 'off' and put the results into the register indicated by
2928  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2929  * spilled reg.
2930  *
2931  * 'dst_regno' can be -1, meaning that the read value is not going to a
2932  * register.
2933  *
2934  * The access is assumed to be within the current stack bounds.
2935  */
2936 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2937 				      /* func where src register points to */
2938 				      struct bpf_func_state *reg_state,
2939 				      int off, int size, int dst_regno)
2940 {
2941 	struct bpf_verifier_state *vstate = env->cur_state;
2942 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2943 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2944 	struct bpf_reg_state *reg;
2945 	u8 *stype;
2946 
2947 	stype = reg_state->stack[spi].slot_type;
2948 	reg = &reg_state->stack[spi].spilled_ptr;
2949 
2950 	if (stype[0] == STACK_SPILL) {
2951 		if (size != BPF_REG_SIZE) {
2952 			if (reg->type != SCALAR_VALUE) {
2953 				verbose_linfo(env, env->insn_idx, "; ");
2954 				verbose(env, "invalid size of register fill\n");
2955 				return -EACCES;
2956 			}
2957 			if (dst_regno >= 0) {
2958 				mark_reg_unknown(env, state->regs, dst_regno);
2959 				state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2960 			}
2961 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2962 			return 0;
2963 		}
2964 		for (i = 1; i < BPF_REG_SIZE; i++) {
2965 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2966 				verbose(env, "corrupted spill memory\n");
2967 				return -EACCES;
2968 			}
2969 		}
2970 
2971 		if (dst_regno >= 0) {
2972 			/* restore register state from stack */
2973 			state->regs[dst_regno] = *reg;
2974 			/* mark reg as written since spilled pointer state likely
2975 			 * has its liveness marks cleared by is_state_visited()
2976 			 * which resets stack/reg liveness for state transitions
2977 			 */
2978 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2979 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2980 			/* If dst_regno==-1, the caller is asking us whether
2981 			 * it is acceptable to use this value as a SCALAR_VALUE
2982 			 * (e.g. for XADD).
2983 			 * We must not allow unprivileged callers to do that
2984 			 * with spilled pointers.
2985 			 */
2986 			verbose(env, "leaking pointer from stack off %d\n",
2987 				off);
2988 			return -EACCES;
2989 		}
2990 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2991 	} else {
2992 		u8 type;
2993 
2994 		for (i = 0; i < size; i++) {
2995 			type = stype[(slot - i) % BPF_REG_SIZE];
2996 			if (type == STACK_MISC)
2997 				continue;
2998 			if (type == STACK_ZERO)
2999 				continue;
3000 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3001 				off, i, size);
3002 			return -EACCES;
3003 		}
3004 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3005 		if (dst_regno >= 0)
3006 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3007 	}
3008 	return 0;
3009 }
3010 
3011 enum stack_access_src {
3012 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3013 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3014 };
3015 
3016 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3017 					 int regno, int off, int access_size,
3018 					 bool zero_size_allowed,
3019 					 enum stack_access_src type,
3020 					 struct bpf_call_arg_meta *meta);
3021 
3022 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3023 {
3024 	return cur_regs(env) + regno;
3025 }
3026 
3027 /* Read the stack at 'ptr_regno + off' and put the result into the register
3028  * 'dst_regno'.
3029  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3030  * but not its variable offset.
3031  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3032  *
3033  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3034  * filling registers (i.e. reads of spilled register cannot be detected when
3035  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3036  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3037  * offset; for a fixed offset check_stack_read_fixed_off should be used
3038  * instead.
3039  */
3040 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3041 				    int ptr_regno, int off, int size, int dst_regno)
3042 {
3043 	/* The state of the source register. */
3044 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3045 	struct bpf_func_state *ptr_state = func(env, reg);
3046 	int err;
3047 	int min_off, max_off;
3048 
3049 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3050 	 */
3051 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3052 					    false, ACCESS_DIRECT, NULL);
3053 	if (err)
3054 		return err;
3055 
3056 	min_off = reg->smin_value + off;
3057 	max_off = reg->smax_value + off;
3058 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3059 	return 0;
3060 }
3061 
3062 /* check_stack_read dispatches to check_stack_read_fixed_off or
3063  * check_stack_read_var_off.
3064  *
3065  * The caller must ensure that the offset falls within the allocated stack
3066  * bounds.
3067  *
3068  * 'dst_regno' is a register which will receive the value from the stack. It
3069  * can be -1, meaning that the read value is not going to a register.
3070  */
3071 static int check_stack_read(struct bpf_verifier_env *env,
3072 			    int ptr_regno, int off, int size,
3073 			    int dst_regno)
3074 {
3075 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3076 	struct bpf_func_state *state = func(env, reg);
3077 	int err;
3078 	/* Some accesses are only permitted with a static offset. */
3079 	bool var_off = !tnum_is_const(reg->var_off);
3080 
3081 	/* The offset is required to be static when reads don't go to a
3082 	 * register, in order to not leak pointers (see
3083 	 * check_stack_read_fixed_off).
3084 	 */
3085 	if (dst_regno < 0 && var_off) {
3086 		char tn_buf[48];
3087 
3088 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3089 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3090 			tn_buf, off, size);
3091 		return -EACCES;
3092 	}
3093 	/* Variable offset is prohibited for unprivileged mode for simplicity
3094 	 * since it requires corresponding support in Spectre masking for stack
3095 	 * ALU. See also retrieve_ptr_limit().
3096 	 */
3097 	if (!env->bypass_spec_v1 && var_off) {
3098 		char tn_buf[48];
3099 
3100 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3101 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3102 				ptr_regno, tn_buf);
3103 		return -EACCES;
3104 	}
3105 
3106 	if (!var_off) {
3107 		off += reg->var_off.value;
3108 		err = check_stack_read_fixed_off(env, state, off, size,
3109 						 dst_regno);
3110 	} else {
3111 		/* Variable offset stack reads need more conservative handling
3112 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3113 		 * branch.
3114 		 */
3115 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3116 					       dst_regno);
3117 	}
3118 	return err;
3119 }
3120 
3121 
3122 /* check_stack_write dispatches to check_stack_write_fixed_off or
3123  * check_stack_write_var_off.
3124  *
3125  * 'ptr_regno' is the register used as a pointer into the stack.
3126  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3127  * 'value_regno' is the register whose value we're writing to the stack. It can
3128  * be -1, meaning that we're not writing from a register.
3129  *
3130  * The caller must ensure that the offset falls within the maximum stack size.
3131  */
3132 static int check_stack_write(struct bpf_verifier_env *env,
3133 			     int ptr_regno, int off, int size,
3134 			     int value_regno, int insn_idx)
3135 {
3136 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3137 	struct bpf_func_state *state = func(env, reg);
3138 	int err;
3139 
3140 	if (tnum_is_const(reg->var_off)) {
3141 		off += reg->var_off.value;
3142 		err = check_stack_write_fixed_off(env, state, off, size,
3143 						  value_regno, insn_idx);
3144 	} else {
3145 		/* Variable offset stack reads need more conservative handling
3146 		 * than fixed offset ones.
3147 		 */
3148 		err = check_stack_write_var_off(env, state,
3149 						ptr_regno, off, size,
3150 						value_regno, insn_idx);
3151 	}
3152 	return err;
3153 }
3154 
3155 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3156 				 int off, int size, enum bpf_access_type type)
3157 {
3158 	struct bpf_reg_state *regs = cur_regs(env);
3159 	struct bpf_map *map = regs[regno].map_ptr;
3160 	u32 cap = bpf_map_flags_to_cap(map);
3161 
3162 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3163 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3164 			map->value_size, off, size);
3165 		return -EACCES;
3166 	}
3167 
3168 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3169 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3170 			map->value_size, off, size);
3171 		return -EACCES;
3172 	}
3173 
3174 	return 0;
3175 }
3176 
3177 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3178 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3179 			      int off, int size, u32 mem_size,
3180 			      bool zero_size_allowed)
3181 {
3182 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3183 	struct bpf_reg_state *reg;
3184 
3185 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3186 		return 0;
3187 
3188 	reg = &cur_regs(env)[regno];
3189 	switch (reg->type) {
3190 	case PTR_TO_MAP_KEY:
3191 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3192 			mem_size, off, size);
3193 		break;
3194 	case PTR_TO_MAP_VALUE:
3195 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3196 			mem_size, off, size);
3197 		break;
3198 	case PTR_TO_PACKET:
3199 	case PTR_TO_PACKET_META:
3200 	case PTR_TO_PACKET_END:
3201 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3202 			off, size, regno, reg->id, off, mem_size);
3203 		break;
3204 	case PTR_TO_MEM:
3205 	default:
3206 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3207 			mem_size, off, size);
3208 	}
3209 
3210 	return -EACCES;
3211 }
3212 
3213 /* check read/write into a memory region with possible variable offset */
3214 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3215 				   int off, int size, u32 mem_size,
3216 				   bool zero_size_allowed)
3217 {
3218 	struct bpf_verifier_state *vstate = env->cur_state;
3219 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3220 	struct bpf_reg_state *reg = &state->regs[regno];
3221 	int err;
3222 
3223 	/* We may have adjusted the register pointing to memory region, so we
3224 	 * need to try adding each of min_value and max_value to off
3225 	 * to make sure our theoretical access will be safe.
3226 	 */
3227 	if (env->log.level & BPF_LOG_LEVEL)
3228 		print_verifier_state(env, state);
3229 
3230 	/* The minimum value is only important with signed
3231 	 * comparisons where we can't assume the floor of a
3232 	 * value is 0.  If we are using signed variables for our
3233 	 * index'es we need to make sure that whatever we use
3234 	 * will have a set floor within our range.
3235 	 */
3236 	if (reg->smin_value < 0 &&
3237 	    (reg->smin_value == S64_MIN ||
3238 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3239 	      reg->smin_value + off < 0)) {
3240 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3241 			regno);
3242 		return -EACCES;
3243 	}
3244 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3245 				 mem_size, zero_size_allowed);
3246 	if (err) {
3247 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3248 			regno);
3249 		return err;
3250 	}
3251 
3252 	/* If we haven't set a max value then we need to bail since we can't be
3253 	 * sure we won't do bad things.
3254 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3255 	 */
3256 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3257 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3258 			regno);
3259 		return -EACCES;
3260 	}
3261 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3262 				 mem_size, zero_size_allowed);
3263 	if (err) {
3264 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3265 			regno);
3266 		return err;
3267 	}
3268 
3269 	return 0;
3270 }
3271 
3272 /* check read/write into a map element with possible variable offset */
3273 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3274 			    int off, int size, bool zero_size_allowed)
3275 {
3276 	struct bpf_verifier_state *vstate = env->cur_state;
3277 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3278 	struct bpf_reg_state *reg = &state->regs[regno];
3279 	struct bpf_map *map = reg->map_ptr;
3280 	int err;
3281 
3282 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3283 				      zero_size_allowed);
3284 	if (err)
3285 		return err;
3286 
3287 	if (map_value_has_spin_lock(map)) {
3288 		u32 lock = map->spin_lock_off;
3289 
3290 		/* if any part of struct bpf_spin_lock can be touched by
3291 		 * load/store reject this program.
3292 		 * To check that [x1, x2) overlaps with [y1, y2)
3293 		 * it is sufficient to check x1 < y2 && y1 < x2.
3294 		 */
3295 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3296 		     lock < reg->umax_value + off + size) {
3297 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3298 			return -EACCES;
3299 		}
3300 	}
3301 	if (map_value_has_timer(map)) {
3302 		u32 t = map->timer_off;
3303 
3304 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3305 		     t < reg->umax_value + off + size) {
3306 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3307 			return -EACCES;
3308 		}
3309 	}
3310 	return err;
3311 }
3312 
3313 #define MAX_PACKET_OFF 0xffff
3314 
3315 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3316 {
3317 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3318 }
3319 
3320 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3321 				       const struct bpf_call_arg_meta *meta,
3322 				       enum bpf_access_type t)
3323 {
3324 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3325 
3326 	switch (prog_type) {
3327 	/* Program types only with direct read access go here! */
3328 	case BPF_PROG_TYPE_LWT_IN:
3329 	case BPF_PROG_TYPE_LWT_OUT:
3330 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3331 	case BPF_PROG_TYPE_SK_REUSEPORT:
3332 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3333 	case BPF_PROG_TYPE_CGROUP_SKB:
3334 		if (t == BPF_WRITE)
3335 			return false;
3336 		fallthrough;
3337 
3338 	/* Program types with direct read + write access go here! */
3339 	case BPF_PROG_TYPE_SCHED_CLS:
3340 	case BPF_PROG_TYPE_SCHED_ACT:
3341 	case BPF_PROG_TYPE_XDP:
3342 	case BPF_PROG_TYPE_LWT_XMIT:
3343 	case BPF_PROG_TYPE_SK_SKB:
3344 	case BPF_PROG_TYPE_SK_MSG:
3345 		if (meta)
3346 			return meta->pkt_access;
3347 
3348 		env->seen_direct_write = true;
3349 		return true;
3350 
3351 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3352 		if (t == BPF_WRITE)
3353 			env->seen_direct_write = true;
3354 
3355 		return true;
3356 
3357 	default:
3358 		return false;
3359 	}
3360 }
3361 
3362 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3363 			       int size, bool zero_size_allowed)
3364 {
3365 	struct bpf_reg_state *regs = cur_regs(env);
3366 	struct bpf_reg_state *reg = &regs[regno];
3367 	int err;
3368 
3369 	/* We may have added a variable offset to the packet pointer; but any
3370 	 * reg->range we have comes after that.  We are only checking the fixed
3371 	 * offset.
3372 	 */
3373 
3374 	/* We don't allow negative numbers, because we aren't tracking enough
3375 	 * detail to prove they're safe.
3376 	 */
3377 	if (reg->smin_value < 0) {
3378 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3379 			regno);
3380 		return -EACCES;
3381 	}
3382 
3383 	err = reg->range < 0 ? -EINVAL :
3384 	      __check_mem_access(env, regno, off, size, reg->range,
3385 				 zero_size_allowed);
3386 	if (err) {
3387 		verbose(env, "R%d offset is outside of the packet\n", regno);
3388 		return err;
3389 	}
3390 
3391 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3392 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3393 	 * otherwise find_good_pkt_pointers would have refused to set range info
3394 	 * that __check_mem_access would have rejected this pkt access.
3395 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3396 	 */
3397 	env->prog->aux->max_pkt_offset =
3398 		max_t(u32, env->prog->aux->max_pkt_offset,
3399 		      off + reg->umax_value + size - 1);
3400 
3401 	return err;
3402 }
3403 
3404 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3405 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3406 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3407 			    struct btf **btf, u32 *btf_id)
3408 {
3409 	struct bpf_insn_access_aux info = {
3410 		.reg_type = *reg_type,
3411 		.log = &env->log,
3412 	};
3413 
3414 	if (env->ops->is_valid_access &&
3415 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3416 		/* A non zero info.ctx_field_size indicates that this field is a
3417 		 * candidate for later verifier transformation to load the whole
3418 		 * field and then apply a mask when accessed with a narrower
3419 		 * access than actual ctx access size. A zero info.ctx_field_size
3420 		 * will only allow for whole field access and rejects any other
3421 		 * type of narrower access.
3422 		 */
3423 		*reg_type = info.reg_type;
3424 
3425 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3426 			*btf = info.btf;
3427 			*btf_id = info.btf_id;
3428 		} else {
3429 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3430 		}
3431 		/* remember the offset of last byte accessed in ctx */
3432 		if (env->prog->aux->max_ctx_offset < off + size)
3433 			env->prog->aux->max_ctx_offset = off + size;
3434 		return 0;
3435 	}
3436 
3437 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3438 	return -EACCES;
3439 }
3440 
3441 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3442 				  int size)
3443 {
3444 	if (size < 0 || off < 0 ||
3445 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3446 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3447 			off, size);
3448 		return -EACCES;
3449 	}
3450 	return 0;
3451 }
3452 
3453 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3454 			     u32 regno, int off, int size,
3455 			     enum bpf_access_type t)
3456 {
3457 	struct bpf_reg_state *regs = cur_regs(env);
3458 	struct bpf_reg_state *reg = &regs[regno];
3459 	struct bpf_insn_access_aux info = {};
3460 	bool valid;
3461 
3462 	if (reg->smin_value < 0) {
3463 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3464 			regno);
3465 		return -EACCES;
3466 	}
3467 
3468 	switch (reg->type) {
3469 	case PTR_TO_SOCK_COMMON:
3470 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3471 		break;
3472 	case PTR_TO_SOCKET:
3473 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3474 		break;
3475 	case PTR_TO_TCP_SOCK:
3476 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3477 		break;
3478 	case PTR_TO_XDP_SOCK:
3479 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3480 		break;
3481 	default:
3482 		valid = false;
3483 	}
3484 
3485 
3486 	if (valid) {
3487 		env->insn_aux_data[insn_idx].ctx_field_size =
3488 			info.ctx_field_size;
3489 		return 0;
3490 	}
3491 
3492 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3493 		regno, reg_type_str[reg->type], off, size);
3494 
3495 	return -EACCES;
3496 }
3497 
3498 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3499 {
3500 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3501 }
3502 
3503 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3504 {
3505 	const struct bpf_reg_state *reg = reg_state(env, regno);
3506 
3507 	return reg->type == PTR_TO_CTX;
3508 }
3509 
3510 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3511 {
3512 	const struct bpf_reg_state *reg = reg_state(env, regno);
3513 
3514 	return type_is_sk_pointer(reg->type);
3515 }
3516 
3517 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3518 {
3519 	const struct bpf_reg_state *reg = reg_state(env, regno);
3520 
3521 	return type_is_pkt_pointer(reg->type);
3522 }
3523 
3524 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3525 {
3526 	const struct bpf_reg_state *reg = reg_state(env, regno);
3527 
3528 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3529 	return reg->type == PTR_TO_FLOW_KEYS;
3530 }
3531 
3532 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3533 				   const struct bpf_reg_state *reg,
3534 				   int off, int size, bool strict)
3535 {
3536 	struct tnum reg_off;
3537 	int ip_align;
3538 
3539 	/* Byte size accesses are always allowed. */
3540 	if (!strict || size == 1)
3541 		return 0;
3542 
3543 	/* For platforms that do not have a Kconfig enabling
3544 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3545 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3546 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3547 	 * to this code only in strict mode where we want to emulate
3548 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3549 	 * unconditional IP align value of '2'.
3550 	 */
3551 	ip_align = 2;
3552 
3553 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3554 	if (!tnum_is_aligned(reg_off, size)) {
3555 		char tn_buf[48];
3556 
3557 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3558 		verbose(env,
3559 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3560 			ip_align, tn_buf, reg->off, off, size);
3561 		return -EACCES;
3562 	}
3563 
3564 	return 0;
3565 }
3566 
3567 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3568 				       const struct bpf_reg_state *reg,
3569 				       const char *pointer_desc,
3570 				       int off, int size, bool strict)
3571 {
3572 	struct tnum reg_off;
3573 
3574 	/* Byte size accesses are always allowed. */
3575 	if (!strict || size == 1)
3576 		return 0;
3577 
3578 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3579 	if (!tnum_is_aligned(reg_off, size)) {
3580 		char tn_buf[48];
3581 
3582 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3583 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3584 			pointer_desc, tn_buf, reg->off, off, size);
3585 		return -EACCES;
3586 	}
3587 
3588 	return 0;
3589 }
3590 
3591 static int check_ptr_alignment(struct bpf_verifier_env *env,
3592 			       const struct bpf_reg_state *reg, int off,
3593 			       int size, bool strict_alignment_once)
3594 {
3595 	bool strict = env->strict_alignment || strict_alignment_once;
3596 	const char *pointer_desc = "";
3597 
3598 	switch (reg->type) {
3599 	case PTR_TO_PACKET:
3600 	case PTR_TO_PACKET_META:
3601 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3602 		 * right in front, treat it the very same way.
3603 		 */
3604 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3605 	case PTR_TO_FLOW_KEYS:
3606 		pointer_desc = "flow keys ";
3607 		break;
3608 	case PTR_TO_MAP_KEY:
3609 		pointer_desc = "key ";
3610 		break;
3611 	case PTR_TO_MAP_VALUE:
3612 		pointer_desc = "value ";
3613 		break;
3614 	case PTR_TO_CTX:
3615 		pointer_desc = "context ";
3616 		break;
3617 	case PTR_TO_STACK:
3618 		pointer_desc = "stack ";
3619 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3620 		 * and check_stack_read_fixed_off() relies on stack accesses being
3621 		 * aligned.
3622 		 */
3623 		strict = true;
3624 		break;
3625 	case PTR_TO_SOCKET:
3626 		pointer_desc = "sock ";
3627 		break;
3628 	case PTR_TO_SOCK_COMMON:
3629 		pointer_desc = "sock_common ";
3630 		break;
3631 	case PTR_TO_TCP_SOCK:
3632 		pointer_desc = "tcp_sock ";
3633 		break;
3634 	case PTR_TO_XDP_SOCK:
3635 		pointer_desc = "xdp_sock ";
3636 		break;
3637 	default:
3638 		break;
3639 	}
3640 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3641 					   strict);
3642 }
3643 
3644 static int update_stack_depth(struct bpf_verifier_env *env,
3645 			      const struct bpf_func_state *func,
3646 			      int off)
3647 {
3648 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3649 
3650 	if (stack >= -off)
3651 		return 0;
3652 
3653 	/* update known max for given subprogram */
3654 	env->subprog_info[func->subprogno].stack_depth = -off;
3655 	return 0;
3656 }
3657 
3658 /* starting from main bpf function walk all instructions of the function
3659  * and recursively walk all callees that given function can call.
3660  * Ignore jump and exit insns.
3661  * Since recursion is prevented by check_cfg() this algorithm
3662  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3663  */
3664 static int check_max_stack_depth(struct bpf_verifier_env *env)
3665 {
3666 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3667 	struct bpf_subprog_info *subprog = env->subprog_info;
3668 	struct bpf_insn *insn = env->prog->insnsi;
3669 	bool tail_call_reachable = false;
3670 	int ret_insn[MAX_CALL_FRAMES];
3671 	int ret_prog[MAX_CALL_FRAMES];
3672 	int j;
3673 
3674 process_func:
3675 	/* protect against potential stack overflow that might happen when
3676 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3677 	 * depth for such case down to 256 so that the worst case scenario
3678 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3679 	 * 8k).
3680 	 *
3681 	 * To get the idea what might happen, see an example:
3682 	 * func1 -> sub rsp, 128
3683 	 *  subfunc1 -> sub rsp, 256
3684 	 *  tailcall1 -> add rsp, 256
3685 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3686 	 *   subfunc2 -> sub rsp, 64
3687 	 *   subfunc22 -> sub rsp, 128
3688 	 *   tailcall2 -> add rsp, 128
3689 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3690 	 *
3691 	 * tailcall will unwind the current stack frame but it will not get rid
3692 	 * of caller's stack as shown on the example above.
3693 	 */
3694 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3695 		verbose(env,
3696 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3697 			depth);
3698 		return -EACCES;
3699 	}
3700 	/* round up to 32-bytes, since this is granularity
3701 	 * of interpreter stack size
3702 	 */
3703 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3704 	if (depth > MAX_BPF_STACK) {
3705 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3706 			frame + 1, depth);
3707 		return -EACCES;
3708 	}
3709 continue_func:
3710 	subprog_end = subprog[idx + 1].start;
3711 	for (; i < subprog_end; i++) {
3712 		int next_insn;
3713 
3714 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3715 			continue;
3716 		/* remember insn and function to return to */
3717 		ret_insn[frame] = i + 1;
3718 		ret_prog[frame] = idx;
3719 
3720 		/* find the callee */
3721 		next_insn = i + insn[i].imm + 1;
3722 		idx = find_subprog(env, next_insn);
3723 		if (idx < 0) {
3724 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3725 				  next_insn);
3726 			return -EFAULT;
3727 		}
3728 		if (subprog[idx].is_async_cb) {
3729 			if (subprog[idx].has_tail_call) {
3730 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3731 				return -EFAULT;
3732 			}
3733 			 /* async callbacks don't increase bpf prog stack size */
3734 			continue;
3735 		}
3736 		i = next_insn;
3737 
3738 		if (subprog[idx].has_tail_call)
3739 			tail_call_reachable = true;
3740 
3741 		frame++;
3742 		if (frame >= MAX_CALL_FRAMES) {
3743 			verbose(env, "the call stack of %d frames is too deep !\n",
3744 				frame);
3745 			return -E2BIG;
3746 		}
3747 		goto process_func;
3748 	}
3749 	/* if tail call got detected across bpf2bpf calls then mark each of the
3750 	 * currently present subprog frames as tail call reachable subprogs;
3751 	 * this info will be utilized by JIT so that we will be preserving the
3752 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3753 	 */
3754 	if (tail_call_reachable)
3755 		for (j = 0; j < frame; j++)
3756 			subprog[ret_prog[j]].tail_call_reachable = true;
3757 	if (subprog[0].tail_call_reachable)
3758 		env->prog->aux->tail_call_reachable = true;
3759 
3760 	/* end of for() loop means the last insn of the 'subprog'
3761 	 * was reached. Doesn't matter whether it was JA or EXIT
3762 	 */
3763 	if (frame == 0)
3764 		return 0;
3765 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3766 	frame--;
3767 	i = ret_insn[frame];
3768 	idx = ret_prog[frame];
3769 	goto continue_func;
3770 }
3771 
3772 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3773 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3774 				  const struct bpf_insn *insn, int idx)
3775 {
3776 	int start = idx + insn->imm + 1, subprog;
3777 
3778 	subprog = find_subprog(env, start);
3779 	if (subprog < 0) {
3780 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3781 			  start);
3782 		return -EFAULT;
3783 	}
3784 	return env->subprog_info[subprog].stack_depth;
3785 }
3786 #endif
3787 
3788 int check_ctx_reg(struct bpf_verifier_env *env,
3789 		  const struct bpf_reg_state *reg, int regno)
3790 {
3791 	/* Access to ctx or passing it to a helper is only allowed in
3792 	 * its original, unmodified form.
3793 	 */
3794 
3795 	if (reg->off) {
3796 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3797 			regno, reg->off);
3798 		return -EACCES;
3799 	}
3800 
3801 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3802 		char tn_buf[48];
3803 
3804 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3805 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3806 		return -EACCES;
3807 	}
3808 
3809 	return 0;
3810 }
3811 
3812 static int __check_buffer_access(struct bpf_verifier_env *env,
3813 				 const char *buf_info,
3814 				 const struct bpf_reg_state *reg,
3815 				 int regno, int off, int size)
3816 {
3817 	if (off < 0) {
3818 		verbose(env,
3819 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3820 			regno, buf_info, off, size);
3821 		return -EACCES;
3822 	}
3823 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3824 		char tn_buf[48];
3825 
3826 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3827 		verbose(env,
3828 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3829 			regno, off, tn_buf);
3830 		return -EACCES;
3831 	}
3832 
3833 	return 0;
3834 }
3835 
3836 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3837 				  const struct bpf_reg_state *reg,
3838 				  int regno, int off, int size)
3839 {
3840 	int err;
3841 
3842 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3843 	if (err)
3844 		return err;
3845 
3846 	if (off + size > env->prog->aux->max_tp_access)
3847 		env->prog->aux->max_tp_access = off + size;
3848 
3849 	return 0;
3850 }
3851 
3852 static int check_buffer_access(struct bpf_verifier_env *env,
3853 			       const struct bpf_reg_state *reg,
3854 			       int regno, int off, int size,
3855 			       bool zero_size_allowed,
3856 			       const char *buf_info,
3857 			       u32 *max_access)
3858 {
3859 	int err;
3860 
3861 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3862 	if (err)
3863 		return err;
3864 
3865 	if (off + size > *max_access)
3866 		*max_access = off + size;
3867 
3868 	return 0;
3869 }
3870 
3871 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3872 static void zext_32_to_64(struct bpf_reg_state *reg)
3873 {
3874 	reg->var_off = tnum_subreg(reg->var_off);
3875 	__reg_assign_32_into_64(reg);
3876 }
3877 
3878 /* truncate register to smaller size (in bytes)
3879  * must be called with size < BPF_REG_SIZE
3880  */
3881 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3882 {
3883 	u64 mask;
3884 
3885 	/* clear high bits in bit representation */
3886 	reg->var_off = tnum_cast(reg->var_off, size);
3887 
3888 	/* fix arithmetic bounds */
3889 	mask = ((u64)1 << (size * 8)) - 1;
3890 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3891 		reg->umin_value &= mask;
3892 		reg->umax_value &= mask;
3893 	} else {
3894 		reg->umin_value = 0;
3895 		reg->umax_value = mask;
3896 	}
3897 	reg->smin_value = reg->umin_value;
3898 	reg->smax_value = reg->umax_value;
3899 
3900 	/* If size is smaller than 32bit register the 32bit register
3901 	 * values are also truncated so we push 64-bit bounds into
3902 	 * 32-bit bounds. Above were truncated < 32-bits already.
3903 	 */
3904 	if (size >= 4)
3905 		return;
3906 	__reg_combine_64_into_32(reg);
3907 }
3908 
3909 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3910 {
3911 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3912 }
3913 
3914 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3915 {
3916 	void *ptr;
3917 	u64 addr;
3918 	int err;
3919 
3920 	err = map->ops->map_direct_value_addr(map, &addr, off);
3921 	if (err)
3922 		return err;
3923 	ptr = (void *)(long)addr + off;
3924 
3925 	switch (size) {
3926 	case sizeof(u8):
3927 		*val = (u64)*(u8 *)ptr;
3928 		break;
3929 	case sizeof(u16):
3930 		*val = (u64)*(u16 *)ptr;
3931 		break;
3932 	case sizeof(u32):
3933 		*val = (u64)*(u32 *)ptr;
3934 		break;
3935 	case sizeof(u64):
3936 		*val = *(u64 *)ptr;
3937 		break;
3938 	default:
3939 		return -EINVAL;
3940 	}
3941 	return 0;
3942 }
3943 
3944 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3945 				   struct bpf_reg_state *regs,
3946 				   int regno, int off, int size,
3947 				   enum bpf_access_type atype,
3948 				   int value_regno)
3949 {
3950 	struct bpf_reg_state *reg = regs + regno;
3951 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3952 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3953 	u32 btf_id;
3954 	int ret;
3955 
3956 	if (off < 0) {
3957 		verbose(env,
3958 			"R%d is ptr_%s invalid negative access: off=%d\n",
3959 			regno, tname, off);
3960 		return -EACCES;
3961 	}
3962 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3963 		char tn_buf[48];
3964 
3965 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3966 		verbose(env,
3967 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3968 			regno, tname, off, tn_buf);
3969 		return -EACCES;
3970 	}
3971 
3972 	if (env->ops->btf_struct_access) {
3973 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3974 						  off, size, atype, &btf_id);
3975 	} else {
3976 		if (atype != BPF_READ) {
3977 			verbose(env, "only read is supported\n");
3978 			return -EACCES;
3979 		}
3980 
3981 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3982 					atype, &btf_id);
3983 	}
3984 
3985 	if (ret < 0)
3986 		return ret;
3987 
3988 	if (atype == BPF_READ && value_regno >= 0)
3989 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3990 
3991 	return 0;
3992 }
3993 
3994 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3995 				   struct bpf_reg_state *regs,
3996 				   int regno, int off, int size,
3997 				   enum bpf_access_type atype,
3998 				   int value_regno)
3999 {
4000 	struct bpf_reg_state *reg = regs + regno;
4001 	struct bpf_map *map = reg->map_ptr;
4002 	const struct btf_type *t;
4003 	const char *tname;
4004 	u32 btf_id;
4005 	int ret;
4006 
4007 	if (!btf_vmlinux) {
4008 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4009 		return -ENOTSUPP;
4010 	}
4011 
4012 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4013 		verbose(env, "map_ptr access not supported for map type %d\n",
4014 			map->map_type);
4015 		return -ENOTSUPP;
4016 	}
4017 
4018 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4019 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4020 
4021 	if (!env->allow_ptr_to_map_access) {
4022 		verbose(env,
4023 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4024 			tname);
4025 		return -EPERM;
4026 	}
4027 
4028 	if (off < 0) {
4029 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4030 			regno, tname, off);
4031 		return -EACCES;
4032 	}
4033 
4034 	if (atype != BPF_READ) {
4035 		verbose(env, "only read from %s is supported\n", tname);
4036 		return -EACCES;
4037 	}
4038 
4039 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4040 	if (ret < 0)
4041 		return ret;
4042 
4043 	if (value_regno >= 0)
4044 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4045 
4046 	return 0;
4047 }
4048 
4049 /* Check that the stack access at the given offset is within bounds. The
4050  * maximum valid offset is -1.
4051  *
4052  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4053  * -state->allocated_stack for reads.
4054  */
4055 static int check_stack_slot_within_bounds(int off,
4056 					  struct bpf_func_state *state,
4057 					  enum bpf_access_type t)
4058 {
4059 	int min_valid_off;
4060 
4061 	if (t == BPF_WRITE)
4062 		min_valid_off = -MAX_BPF_STACK;
4063 	else
4064 		min_valid_off = -state->allocated_stack;
4065 
4066 	if (off < min_valid_off || off > -1)
4067 		return -EACCES;
4068 	return 0;
4069 }
4070 
4071 /* Check that the stack access at 'regno + off' falls within the maximum stack
4072  * bounds.
4073  *
4074  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4075  */
4076 static int check_stack_access_within_bounds(
4077 		struct bpf_verifier_env *env,
4078 		int regno, int off, int access_size,
4079 		enum stack_access_src src, enum bpf_access_type type)
4080 {
4081 	struct bpf_reg_state *regs = cur_regs(env);
4082 	struct bpf_reg_state *reg = regs + regno;
4083 	struct bpf_func_state *state = func(env, reg);
4084 	int min_off, max_off;
4085 	int err;
4086 	char *err_extra;
4087 
4088 	if (src == ACCESS_HELPER)
4089 		/* We don't know if helpers are reading or writing (or both). */
4090 		err_extra = " indirect access to";
4091 	else if (type == BPF_READ)
4092 		err_extra = " read from";
4093 	else
4094 		err_extra = " write to";
4095 
4096 	if (tnum_is_const(reg->var_off)) {
4097 		min_off = reg->var_off.value + off;
4098 		if (access_size > 0)
4099 			max_off = min_off + access_size - 1;
4100 		else
4101 			max_off = min_off;
4102 	} else {
4103 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4104 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4105 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4106 				err_extra, regno);
4107 			return -EACCES;
4108 		}
4109 		min_off = reg->smin_value + off;
4110 		if (access_size > 0)
4111 			max_off = reg->smax_value + off + access_size - 1;
4112 		else
4113 			max_off = min_off;
4114 	}
4115 
4116 	err = check_stack_slot_within_bounds(min_off, state, type);
4117 	if (!err)
4118 		err = check_stack_slot_within_bounds(max_off, state, type);
4119 
4120 	if (err) {
4121 		if (tnum_is_const(reg->var_off)) {
4122 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4123 				err_extra, regno, off, access_size);
4124 		} else {
4125 			char tn_buf[48];
4126 
4127 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4128 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4129 				err_extra, regno, tn_buf, access_size);
4130 		}
4131 	}
4132 	return err;
4133 }
4134 
4135 /* check whether memory at (regno + off) is accessible for t = (read | write)
4136  * if t==write, value_regno is a register which value is stored into memory
4137  * if t==read, value_regno is a register which will receive the value from memory
4138  * if t==write && value_regno==-1, some unknown value is stored into memory
4139  * if t==read && value_regno==-1, don't care what we read from memory
4140  */
4141 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4142 			    int off, int bpf_size, enum bpf_access_type t,
4143 			    int value_regno, bool strict_alignment_once)
4144 {
4145 	struct bpf_reg_state *regs = cur_regs(env);
4146 	struct bpf_reg_state *reg = regs + regno;
4147 	struct bpf_func_state *state;
4148 	int size, err = 0;
4149 
4150 	size = bpf_size_to_bytes(bpf_size);
4151 	if (size < 0)
4152 		return size;
4153 
4154 	/* alignment checks will add in reg->off themselves */
4155 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4156 	if (err)
4157 		return err;
4158 
4159 	/* for access checks, reg->off is just part of off */
4160 	off += reg->off;
4161 
4162 	if (reg->type == PTR_TO_MAP_KEY) {
4163 		if (t == BPF_WRITE) {
4164 			verbose(env, "write to change key R%d not allowed\n", regno);
4165 			return -EACCES;
4166 		}
4167 
4168 		err = check_mem_region_access(env, regno, off, size,
4169 					      reg->map_ptr->key_size, false);
4170 		if (err)
4171 			return err;
4172 		if (value_regno >= 0)
4173 			mark_reg_unknown(env, regs, value_regno);
4174 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4175 		if (t == BPF_WRITE && value_regno >= 0 &&
4176 		    is_pointer_value(env, value_regno)) {
4177 			verbose(env, "R%d leaks addr into map\n", value_regno);
4178 			return -EACCES;
4179 		}
4180 		err = check_map_access_type(env, regno, off, size, t);
4181 		if (err)
4182 			return err;
4183 		err = check_map_access(env, regno, off, size, false);
4184 		if (!err && t == BPF_READ && value_regno >= 0) {
4185 			struct bpf_map *map = reg->map_ptr;
4186 
4187 			/* if map is read-only, track its contents as scalars */
4188 			if (tnum_is_const(reg->var_off) &&
4189 			    bpf_map_is_rdonly(map) &&
4190 			    map->ops->map_direct_value_addr) {
4191 				int map_off = off + reg->var_off.value;
4192 				u64 val = 0;
4193 
4194 				err = bpf_map_direct_read(map, map_off, size,
4195 							  &val);
4196 				if (err)
4197 					return err;
4198 
4199 				regs[value_regno].type = SCALAR_VALUE;
4200 				__mark_reg_known(&regs[value_regno], val);
4201 			} else {
4202 				mark_reg_unknown(env, regs, value_regno);
4203 			}
4204 		}
4205 	} else if (reg->type == PTR_TO_MEM) {
4206 		if (t == BPF_WRITE && value_regno >= 0 &&
4207 		    is_pointer_value(env, value_regno)) {
4208 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4209 			return -EACCES;
4210 		}
4211 		err = check_mem_region_access(env, regno, off, size,
4212 					      reg->mem_size, false);
4213 		if (!err && t == BPF_READ && value_regno >= 0)
4214 			mark_reg_unknown(env, regs, value_regno);
4215 	} else if (reg->type == PTR_TO_CTX) {
4216 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4217 		struct btf *btf = NULL;
4218 		u32 btf_id = 0;
4219 
4220 		if (t == BPF_WRITE && value_regno >= 0 &&
4221 		    is_pointer_value(env, value_regno)) {
4222 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4223 			return -EACCES;
4224 		}
4225 
4226 		err = check_ctx_reg(env, reg, regno);
4227 		if (err < 0)
4228 			return err;
4229 
4230 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4231 		if (err)
4232 			verbose_linfo(env, insn_idx, "; ");
4233 		if (!err && t == BPF_READ && value_regno >= 0) {
4234 			/* ctx access returns either a scalar, or a
4235 			 * PTR_TO_PACKET[_META,_END]. In the latter
4236 			 * case, we know the offset is zero.
4237 			 */
4238 			if (reg_type == SCALAR_VALUE) {
4239 				mark_reg_unknown(env, regs, value_regno);
4240 			} else {
4241 				mark_reg_known_zero(env, regs,
4242 						    value_regno);
4243 				if (reg_type_may_be_null(reg_type))
4244 					regs[value_regno].id = ++env->id_gen;
4245 				/* A load of ctx field could have different
4246 				 * actual load size with the one encoded in the
4247 				 * insn. When the dst is PTR, it is for sure not
4248 				 * a sub-register.
4249 				 */
4250 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4251 				if (reg_type == PTR_TO_BTF_ID ||
4252 				    reg_type == PTR_TO_BTF_ID_OR_NULL) {
4253 					regs[value_regno].btf = btf;
4254 					regs[value_regno].btf_id = btf_id;
4255 				}
4256 			}
4257 			regs[value_regno].type = reg_type;
4258 		}
4259 
4260 	} else if (reg->type == PTR_TO_STACK) {
4261 		/* Basic bounds checks. */
4262 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4263 		if (err)
4264 			return err;
4265 
4266 		state = func(env, reg);
4267 		err = update_stack_depth(env, state, off);
4268 		if (err)
4269 			return err;
4270 
4271 		if (t == BPF_READ)
4272 			err = check_stack_read(env, regno, off, size,
4273 					       value_regno);
4274 		else
4275 			err = check_stack_write(env, regno, off, size,
4276 						value_regno, insn_idx);
4277 	} else if (reg_is_pkt_pointer(reg)) {
4278 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4279 			verbose(env, "cannot write into packet\n");
4280 			return -EACCES;
4281 		}
4282 		if (t == BPF_WRITE && value_regno >= 0 &&
4283 		    is_pointer_value(env, value_regno)) {
4284 			verbose(env, "R%d leaks addr into packet\n",
4285 				value_regno);
4286 			return -EACCES;
4287 		}
4288 		err = check_packet_access(env, regno, off, size, false);
4289 		if (!err && t == BPF_READ && value_regno >= 0)
4290 			mark_reg_unknown(env, regs, value_regno);
4291 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4292 		if (t == BPF_WRITE && value_regno >= 0 &&
4293 		    is_pointer_value(env, value_regno)) {
4294 			verbose(env, "R%d leaks addr into flow keys\n",
4295 				value_regno);
4296 			return -EACCES;
4297 		}
4298 
4299 		err = check_flow_keys_access(env, off, size);
4300 		if (!err && t == BPF_READ && value_regno >= 0)
4301 			mark_reg_unknown(env, regs, value_regno);
4302 	} else if (type_is_sk_pointer(reg->type)) {
4303 		if (t == BPF_WRITE) {
4304 			verbose(env, "R%d cannot write into %s\n",
4305 				regno, reg_type_str[reg->type]);
4306 			return -EACCES;
4307 		}
4308 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4309 		if (!err && value_regno >= 0)
4310 			mark_reg_unknown(env, regs, value_regno);
4311 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4312 		err = check_tp_buffer_access(env, reg, regno, off, size);
4313 		if (!err && t == BPF_READ && value_regno >= 0)
4314 			mark_reg_unknown(env, regs, value_regno);
4315 	} else if (reg->type == PTR_TO_BTF_ID) {
4316 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4317 					      value_regno);
4318 	} else if (reg->type == CONST_PTR_TO_MAP) {
4319 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4320 					      value_regno);
4321 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
4322 		if (t == BPF_WRITE) {
4323 			verbose(env, "R%d cannot write into %s\n",
4324 				regno, reg_type_str[reg->type]);
4325 			return -EACCES;
4326 		}
4327 		err = check_buffer_access(env, reg, regno, off, size, false,
4328 					  "rdonly",
4329 					  &env->prog->aux->max_rdonly_access);
4330 		if (!err && value_regno >= 0)
4331 			mark_reg_unknown(env, regs, value_regno);
4332 	} else if (reg->type == PTR_TO_RDWR_BUF) {
4333 		err = check_buffer_access(env, reg, regno, off, size, false,
4334 					  "rdwr",
4335 					  &env->prog->aux->max_rdwr_access);
4336 		if (!err && t == BPF_READ && value_regno >= 0)
4337 			mark_reg_unknown(env, regs, value_regno);
4338 	} else {
4339 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4340 			reg_type_str[reg->type]);
4341 		return -EACCES;
4342 	}
4343 
4344 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4345 	    regs[value_regno].type == SCALAR_VALUE) {
4346 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4347 		coerce_reg_to_size(&regs[value_regno], size);
4348 	}
4349 	return err;
4350 }
4351 
4352 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4353 {
4354 	int load_reg;
4355 	int err;
4356 
4357 	switch (insn->imm) {
4358 	case BPF_ADD:
4359 	case BPF_ADD | BPF_FETCH:
4360 	case BPF_AND:
4361 	case BPF_AND | BPF_FETCH:
4362 	case BPF_OR:
4363 	case BPF_OR | BPF_FETCH:
4364 	case BPF_XOR:
4365 	case BPF_XOR | BPF_FETCH:
4366 	case BPF_XCHG:
4367 	case BPF_CMPXCHG:
4368 		break;
4369 	default:
4370 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4371 		return -EINVAL;
4372 	}
4373 
4374 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4375 		verbose(env, "invalid atomic operand size\n");
4376 		return -EINVAL;
4377 	}
4378 
4379 	/* check src1 operand */
4380 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4381 	if (err)
4382 		return err;
4383 
4384 	/* check src2 operand */
4385 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4386 	if (err)
4387 		return err;
4388 
4389 	if (insn->imm == BPF_CMPXCHG) {
4390 		/* Check comparison of R0 with memory location */
4391 		err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4392 		if (err)
4393 			return err;
4394 	}
4395 
4396 	if (is_pointer_value(env, insn->src_reg)) {
4397 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4398 		return -EACCES;
4399 	}
4400 
4401 	if (is_ctx_reg(env, insn->dst_reg) ||
4402 	    is_pkt_reg(env, insn->dst_reg) ||
4403 	    is_flow_key_reg(env, insn->dst_reg) ||
4404 	    is_sk_reg(env, insn->dst_reg)) {
4405 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4406 			insn->dst_reg,
4407 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
4408 		return -EACCES;
4409 	}
4410 
4411 	if (insn->imm & BPF_FETCH) {
4412 		if (insn->imm == BPF_CMPXCHG)
4413 			load_reg = BPF_REG_0;
4414 		else
4415 			load_reg = insn->src_reg;
4416 
4417 		/* check and record load of old value */
4418 		err = check_reg_arg(env, load_reg, DST_OP);
4419 		if (err)
4420 			return err;
4421 	} else {
4422 		/* This instruction accesses a memory location but doesn't
4423 		 * actually load it into a register.
4424 		 */
4425 		load_reg = -1;
4426 	}
4427 
4428 	/* check whether we can read the memory */
4429 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4430 			       BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4431 	if (err)
4432 		return err;
4433 
4434 	/* check whether we can write into the same memory */
4435 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4436 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4437 	if (err)
4438 		return err;
4439 
4440 	return 0;
4441 }
4442 
4443 /* When register 'regno' is used to read the stack (either directly or through
4444  * a helper function) make sure that it's within stack boundary and, depending
4445  * on the access type, that all elements of the stack are initialized.
4446  *
4447  * 'off' includes 'regno->off', but not its dynamic part (if any).
4448  *
4449  * All registers that have been spilled on the stack in the slots within the
4450  * read offsets are marked as read.
4451  */
4452 static int check_stack_range_initialized(
4453 		struct bpf_verifier_env *env, int regno, int off,
4454 		int access_size, bool zero_size_allowed,
4455 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4456 {
4457 	struct bpf_reg_state *reg = reg_state(env, regno);
4458 	struct bpf_func_state *state = func(env, reg);
4459 	int err, min_off, max_off, i, j, slot, spi;
4460 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4461 	enum bpf_access_type bounds_check_type;
4462 	/* Some accesses can write anything into the stack, others are
4463 	 * read-only.
4464 	 */
4465 	bool clobber = false;
4466 
4467 	if (access_size == 0 && !zero_size_allowed) {
4468 		verbose(env, "invalid zero-sized read\n");
4469 		return -EACCES;
4470 	}
4471 
4472 	if (type == ACCESS_HELPER) {
4473 		/* The bounds checks for writes are more permissive than for
4474 		 * reads. However, if raw_mode is not set, we'll do extra
4475 		 * checks below.
4476 		 */
4477 		bounds_check_type = BPF_WRITE;
4478 		clobber = true;
4479 	} else {
4480 		bounds_check_type = BPF_READ;
4481 	}
4482 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4483 					       type, bounds_check_type);
4484 	if (err)
4485 		return err;
4486 
4487 
4488 	if (tnum_is_const(reg->var_off)) {
4489 		min_off = max_off = reg->var_off.value + off;
4490 	} else {
4491 		/* Variable offset is prohibited for unprivileged mode for
4492 		 * simplicity since it requires corresponding support in
4493 		 * Spectre masking for stack ALU.
4494 		 * See also retrieve_ptr_limit().
4495 		 */
4496 		if (!env->bypass_spec_v1) {
4497 			char tn_buf[48];
4498 
4499 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4500 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4501 				regno, err_extra, tn_buf);
4502 			return -EACCES;
4503 		}
4504 		/* Only initialized buffer on stack is allowed to be accessed
4505 		 * with variable offset. With uninitialized buffer it's hard to
4506 		 * guarantee that whole memory is marked as initialized on
4507 		 * helper return since specific bounds are unknown what may
4508 		 * cause uninitialized stack leaking.
4509 		 */
4510 		if (meta && meta->raw_mode)
4511 			meta = NULL;
4512 
4513 		min_off = reg->smin_value + off;
4514 		max_off = reg->smax_value + off;
4515 	}
4516 
4517 	if (meta && meta->raw_mode) {
4518 		meta->access_size = access_size;
4519 		meta->regno = regno;
4520 		return 0;
4521 	}
4522 
4523 	for (i = min_off; i < max_off + access_size; i++) {
4524 		u8 *stype;
4525 
4526 		slot = -i - 1;
4527 		spi = slot / BPF_REG_SIZE;
4528 		if (state->allocated_stack <= slot)
4529 			goto err;
4530 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4531 		if (*stype == STACK_MISC)
4532 			goto mark;
4533 		if (*stype == STACK_ZERO) {
4534 			if (clobber) {
4535 				/* helper can write anything into the stack */
4536 				*stype = STACK_MISC;
4537 			}
4538 			goto mark;
4539 		}
4540 
4541 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4542 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4543 			goto mark;
4544 
4545 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4546 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4547 		     env->allow_ptr_leaks)) {
4548 			if (clobber) {
4549 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4550 				for (j = 0; j < BPF_REG_SIZE; j++)
4551 					state->stack[spi].slot_type[j] = STACK_MISC;
4552 			}
4553 			goto mark;
4554 		}
4555 
4556 err:
4557 		if (tnum_is_const(reg->var_off)) {
4558 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4559 				err_extra, regno, min_off, i - min_off, access_size);
4560 		} else {
4561 			char tn_buf[48];
4562 
4563 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4564 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4565 				err_extra, regno, tn_buf, i - min_off, access_size);
4566 		}
4567 		return -EACCES;
4568 mark:
4569 		/* reading any byte out of 8-byte 'spill_slot' will cause
4570 		 * the whole slot to be marked as 'read'
4571 		 */
4572 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4573 			      state->stack[spi].spilled_ptr.parent,
4574 			      REG_LIVE_READ64);
4575 	}
4576 	return update_stack_depth(env, state, min_off);
4577 }
4578 
4579 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4580 				   int access_size, bool zero_size_allowed,
4581 				   struct bpf_call_arg_meta *meta)
4582 {
4583 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4584 
4585 	switch (reg->type) {
4586 	case PTR_TO_PACKET:
4587 	case PTR_TO_PACKET_META:
4588 		return check_packet_access(env, regno, reg->off, access_size,
4589 					   zero_size_allowed);
4590 	case PTR_TO_MAP_KEY:
4591 		return check_mem_region_access(env, regno, reg->off, access_size,
4592 					       reg->map_ptr->key_size, false);
4593 	case PTR_TO_MAP_VALUE:
4594 		if (check_map_access_type(env, regno, reg->off, access_size,
4595 					  meta && meta->raw_mode ? BPF_WRITE :
4596 					  BPF_READ))
4597 			return -EACCES;
4598 		return check_map_access(env, regno, reg->off, access_size,
4599 					zero_size_allowed);
4600 	case PTR_TO_MEM:
4601 		return check_mem_region_access(env, regno, reg->off,
4602 					       access_size, reg->mem_size,
4603 					       zero_size_allowed);
4604 	case PTR_TO_RDONLY_BUF:
4605 		if (meta && meta->raw_mode)
4606 			return -EACCES;
4607 		return check_buffer_access(env, reg, regno, reg->off,
4608 					   access_size, zero_size_allowed,
4609 					   "rdonly",
4610 					   &env->prog->aux->max_rdonly_access);
4611 	case PTR_TO_RDWR_BUF:
4612 		return check_buffer_access(env, reg, regno, reg->off,
4613 					   access_size, zero_size_allowed,
4614 					   "rdwr",
4615 					   &env->prog->aux->max_rdwr_access);
4616 	case PTR_TO_STACK:
4617 		return check_stack_range_initialized(
4618 				env,
4619 				regno, reg->off, access_size,
4620 				zero_size_allowed, ACCESS_HELPER, meta);
4621 	default: /* scalar_value or invalid ptr */
4622 		/* Allow zero-byte read from NULL, regardless of pointer type */
4623 		if (zero_size_allowed && access_size == 0 &&
4624 		    register_is_null(reg))
4625 			return 0;
4626 
4627 		verbose(env, "R%d type=%s expected=%s\n", regno,
4628 			reg_type_str[reg->type],
4629 			reg_type_str[PTR_TO_STACK]);
4630 		return -EACCES;
4631 	}
4632 }
4633 
4634 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4635 		   u32 regno, u32 mem_size)
4636 {
4637 	if (register_is_null(reg))
4638 		return 0;
4639 
4640 	if (reg_type_may_be_null(reg->type)) {
4641 		/* Assuming that the register contains a value check if the memory
4642 		 * access is safe. Temporarily save and restore the register's state as
4643 		 * the conversion shouldn't be visible to a caller.
4644 		 */
4645 		const struct bpf_reg_state saved_reg = *reg;
4646 		int rv;
4647 
4648 		mark_ptr_not_null_reg(reg);
4649 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4650 		*reg = saved_reg;
4651 		return rv;
4652 	}
4653 
4654 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4655 }
4656 
4657 /* Implementation details:
4658  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4659  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4660  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4661  * value_or_null->value transition, since the verifier only cares about
4662  * the range of access to valid map value pointer and doesn't care about actual
4663  * address of the map element.
4664  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4665  * reg->id > 0 after value_or_null->value transition. By doing so
4666  * two bpf_map_lookups will be considered two different pointers that
4667  * point to different bpf_spin_locks.
4668  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4669  * dead-locks.
4670  * Since only one bpf_spin_lock is allowed the checks are simpler than
4671  * reg_is_refcounted() logic. The verifier needs to remember only
4672  * one spin_lock instead of array of acquired_refs.
4673  * cur_state->active_spin_lock remembers which map value element got locked
4674  * and clears it after bpf_spin_unlock.
4675  */
4676 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4677 			     bool is_lock)
4678 {
4679 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4680 	struct bpf_verifier_state *cur = env->cur_state;
4681 	bool is_const = tnum_is_const(reg->var_off);
4682 	struct bpf_map *map = reg->map_ptr;
4683 	u64 val = reg->var_off.value;
4684 
4685 	if (!is_const) {
4686 		verbose(env,
4687 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4688 			regno);
4689 		return -EINVAL;
4690 	}
4691 	if (!map->btf) {
4692 		verbose(env,
4693 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4694 			map->name);
4695 		return -EINVAL;
4696 	}
4697 	if (!map_value_has_spin_lock(map)) {
4698 		if (map->spin_lock_off == -E2BIG)
4699 			verbose(env,
4700 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4701 				map->name);
4702 		else if (map->spin_lock_off == -ENOENT)
4703 			verbose(env,
4704 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4705 				map->name);
4706 		else
4707 			verbose(env,
4708 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4709 				map->name);
4710 		return -EINVAL;
4711 	}
4712 	if (map->spin_lock_off != val + reg->off) {
4713 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4714 			val + reg->off);
4715 		return -EINVAL;
4716 	}
4717 	if (is_lock) {
4718 		if (cur->active_spin_lock) {
4719 			verbose(env,
4720 				"Locking two bpf_spin_locks are not allowed\n");
4721 			return -EINVAL;
4722 		}
4723 		cur->active_spin_lock = reg->id;
4724 	} else {
4725 		if (!cur->active_spin_lock) {
4726 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4727 			return -EINVAL;
4728 		}
4729 		if (cur->active_spin_lock != reg->id) {
4730 			verbose(env, "bpf_spin_unlock of different lock\n");
4731 			return -EINVAL;
4732 		}
4733 		cur->active_spin_lock = 0;
4734 	}
4735 	return 0;
4736 }
4737 
4738 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4739 			      struct bpf_call_arg_meta *meta)
4740 {
4741 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4742 	bool is_const = tnum_is_const(reg->var_off);
4743 	struct bpf_map *map = reg->map_ptr;
4744 	u64 val = reg->var_off.value;
4745 
4746 	if (!is_const) {
4747 		verbose(env,
4748 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4749 			regno);
4750 		return -EINVAL;
4751 	}
4752 	if (!map->btf) {
4753 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4754 			map->name);
4755 		return -EINVAL;
4756 	}
4757 	if (!map_value_has_timer(map)) {
4758 		if (map->timer_off == -E2BIG)
4759 			verbose(env,
4760 				"map '%s' has more than one 'struct bpf_timer'\n",
4761 				map->name);
4762 		else if (map->timer_off == -ENOENT)
4763 			verbose(env,
4764 				"map '%s' doesn't have 'struct bpf_timer'\n",
4765 				map->name);
4766 		else
4767 			verbose(env,
4768 				"map '%s' is not a struct type or bpf_timer is mangled\n",
4769 				map->name);
4770 		return -EINVAL;
4771 	}
4772 	if (map->timer_off != val + reg->off) {
4773 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4774 			val + reg->off, map->timer_off);
4775 		return -EINVAL;
4776 	}
4777 	if (meta->map_ptr) {
4778 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4779 		return -EFAULT;
4780 	}
4781 	meta->map_uid = reg->map_uid;
4782 	meta->map_ptr = map;
4783 	return 0;
4784 }
4785 
4786 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4787 {
4788 	return type == ARG_PTR_TO_MEM ||
4789 	       type == ARG_PTR_TO_MEM_OR_NULL ||
4790 	       type == ARG_PTR_TO_UNINIT_MEM;
4791 }
4792 
4793 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4794 {
4795 	return type == ARG_CONST_SIZE ||
4796 	       type == ARG_CONST_SIZE_OR_ZERO;
4797 }
4798 
4799 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4800 {
4801 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4802 }
4803 
4804 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4805 {
4806 	return type == ARG_PTR_TO_INT ||
4807 	       type == ARG_PTR_TO_LONG;
4808 }
4809 
4810 static int int_ptr_type_to_size(enum bpf_arg_type type)
4811 {
4812 	if (type == ARG_PTR_TO_INT)
4813 		return sizeof(u32);
4814 	else if (type == ARG_PTR_TO_LONG)
4815 		return sizeof(u64);
4816 
4817 	return -EINVAL;
4818 }
4819 
4820 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4821 				 const struct bpf_call_arg_meta *meta,
4822 				 enum bpf_arg_type *arg_type)
4823 {
4824 	if (!meta->map_ptr) {
4825 		/* kernel subsystem misconfigured verifier */
4826 		verbose(env, "invalid map_ptr to access map->type\n");
4827 		return -EACCES;
4828 	}
4829 
4830 	switch (meta->map_ptr->map_type) {
4831 	case BPF_MAP_TYPE_SOCKMAP:
4832 	case BPF_MAP_TYPE_SOCKHASH:
4833 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4834 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4835 		} else {
4836 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4837 			return -EINVAL;
4838 		}
4839 		break;
4840 
4841 	default:
4842 		break;
4843 	}
4844 	return 0;
4845 }
4846 
4847 struct bpf_reg_types {
4848 	const enum bpf_reg_type types[10];
4849 	u32 *btf_id;
4850 };
4851 
4852 static const struct bpf_reg_types map_key_value_types = {
4853 	.types = {
4854 		PTR_TO_STACK,
4855 		PTR_TO_PACKET,
4856 		PTR_TO_PACKET_META,
4857 		PTR_TO_MAP_KEY,
4858 		PTR_TO_MAP_VALUE,
4859 	},
4860 };
4861 
4862 static const struct bpf_reg_types sock_types = {
4863 	.types = {
4864 		PTR_TO_SOCK_COMMON,
4865 		PTR_TO_SOCKET,
4866 		PTR_TO_TCP_SOCK,
4867 		PTR_TO_XDP_SOCK,
4868 	},
4869 };
4870 
4871 #ifdef CONFIG_NET
4872 static const struct bpf_reg_types btf_id_sock_common_types = {
4873 	.types = {
4874 		PTR_TO_SOCK_COMMON,
4875 		PTR_TO_SOCKET,
4876 		PTR_TO_TCP_SOCK,
4877 		PTR_TO_XDP_SOCK,
4878 		PTR_TO_BTF_ID,
4879 	},
4880 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4881 };
4882 #endif
4883 
4884 static const struct bpf_reg_types mem_types = {
4885 	.types = {
4886 		PTR_TO_STACK,
4887 		PTR_TO_PACKET,
4888 		PTR_TO_PACKET_META,
4889 		PTR_TO_MAP_KEY,
4890 		PTR_TO_MAP_VALUE,
4891 		PTR_TO_MEM,
4892 		PTR_TO_RDONLY_BUF,
4893 		PTR_TO_RDWR_BUF,
4894 	},
4895 };
4896 
4897 static const struct bpf_reg_types int_ptr_types = {
4898 	.types = {
4899 		PTR_TO_STACK,
4900 		PTR_TO_PACKET,
4901 		PTR_TO_PACKET_META,
4902 		PTR_TO_MAP_KEY,
4903 		PTR_TO_MAP_VALUE,
4904 	},
4905 };
4906 
4907 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4908 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4909 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4910 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4911 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4912 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4913 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4914 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4915 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4916 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4917 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4918 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
4919 
4920 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4921 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4922 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4923 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4924 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
4925 	[ARG_CONST_SIZE]		= &scalar_types,
4926 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4927 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4928 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4929 	[ARG_PTR_TO_CTX]		= &context_types,
4930 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
4931 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4932 #ifdef CONFIG_NET
4933 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4934 #endif
4935 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4936 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
4937 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4938 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4939 	[ARG_PTR_TO_MEM]		= &mem_types,
4940 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
4941 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4942 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4943 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
4944 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4945 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4946 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4947 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
4948 	[ARG_PTR_TO_STACK_OR_NULL]	= &stack_ptr_types,
4949 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
4950 	[ARG_PTR_TO_TIMER]		= &timer_types,
4951 };
4952 
4953 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4954 			  enum bpf_arg_type arg_type,
4955 			  const u32 *arg_btf_id)
4956 {
4957 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4958 	enum bpf_reg_type expected, type = reg->type;
4959 	const struct bpf_reg_types *compatible;
4960 	int i, j;
4961 
4962 	compatible = compatible_reg_types[arg_type];
4963 	if (!compatible) {
4964 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4965 		return -EFAULT;
4966 	}
4967 
4968 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4969 		expected = compatible->types[i];
4970 		if (expected == NOT_INIT)
4971 			break;
4972 
4973 		if (type == expected)
4974 			goto found;
4975 	}
4976 
4977 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4978 	for (j = 0; j + 1 < i; j++)
4979 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4980 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4981 	return -EACCES;
4982 
4983 found:
4984 	if (type == PTR_TO_BTF_ID) {
4985 		if (!arg_btf_id) {
4986 			if (!compatible->btf_id) {
4987 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4988 				return -EFAULT;
4989 			}
4990 			arg_btf_id = compatible->btf_id;
4991 		}
4992 
4993 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4994 					  btf_vmlinux, *arg_btf_id)) {
4995 			verbose(env, "R%d is of type %s but %s is expected\n",
4996 				regno, kernel_type_name(reg->btf, reg->btf_id),
4997 				kernel_type_name(btf_vmlinux, *arg_btf_id));
4998 			return -EACCES;
4999 		}
5000 
5001 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5002 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5003 				regno);
5004 			return -EACCES;
5005 		}
5006 	}
5007 
5008 	return 0;
5009 }
5010 
5011 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5012 			  struct bpf_call_arg_meta *meta,
5013 			  const struct bpf_func_proto *fn)
5014 {
5015 	u32 regno = BPF_REG_1 + arg;
5016 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5017 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5018 	enum bpf_reg_type type = reg->type;
5019 	int err = 0;
5020 
5021 	if (arg_type == ARG_DONTCARE)
5022 		return 0;
5023 
5024 	err = check_reg_arg(env, regno, SRC_OP);
5025 	if (err)
5026 		return err;
5027 
5028 	if (arg_type == ARG_ANYTHING) {
5029 		if (is_pointer_value(env, regno)) {
5030 			verbose(env, "R%d leaks addr into helper function\n",
5031 				regno);
5032 			return -EACCES;
5033 		}
5034 		return 0;
5035 	}
5036 
5037 	if (type_is_pkt_pointer(type) &&
5038 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5039 		verbose(env, "helper access to the packet is not allowed\n");
5040 		return -EACCES;
5041 	}
5042 
5043 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5044 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5045 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5046 		err = resolve_map_arg_type(env, meta, &arg_type);
5047 		if (err)
5048 			return err;
5049 	}
5050 
5051 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5052 		/* A NULL register has a SCALAR_VALUE type, so skip
5053 		 * type checking.
5054 		 */
5055 		goto skip_type_check;
5056 
5057 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5058 	if (err)
5059 		return err;
5060 
5061 	if (type == PTR_TO_CTX) {
5062 		err = check_ctx_reg(env, reg, regno);
5063 		if (err < 0)
5064 			return err;
5065 	}
5066 
5067 skip_type_check:
5068 	if (reg->ref_obj_id) {
5069 		if (meta->ref_obj_id) {
5070 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5071 				regno, reg->ref_obj_id,
5072 				meta->ref_obj_id);
5073 			return -EFAULT;
5074 		}
5075 		meta->ref_obj_id = reg->ref_obj_id;
5076 	}
5077 
5078 	if (arg_type == ARG_CONST_MAP_PTR) {
5079 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5080 		if (meta->map_ptr) {
5081 			/* Use map_uid (which is unique id of inner map) to reject:
5082 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5083 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5084 			 * if (inner_map1 && inner_map2) {
5085 			 *     timer = bpf_map_lookup_elem(inner_map1);
5086 			 *     if (timer)
5087 			 *         // mismatch would have been allowed
5088 			 *         bpf_timer_init(timer, inner_map2);
5089 			 * }
5090 			 *
5091 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5092 			 */
5093 			if (meta->map_ptr != reg->map_ptr ||
5094 			    meta->map_uid != reg->map_uid) {
5095 				verbose(env,
5096 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5097 					meta->map_uid, reg->map_uid);
5098 				return -EINVAL;
5099 			}
5100 		}
5101 		meta->map_ptr = reg->map_ptr;
5102 		meta->map_uid = reg->map_uid;
5103 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5104 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5105 		 * check that [key, key + map->key_size) are within
5106 		 * stack limits and initialized
5107 		 */
5108 		if (!meta->map_ptr) {
5109 			/* in function declaration map_ptr must come before
5110 			 * map_key, so that it's verified and known before
5111 			 * we have to check map_key here. Otherwise it means
5112 			 * that kernel subsystem misconfigured verifier
5113 			 */
5114 			verbose(env, "invalid map_ptr to access map->key\n");
5115 			return -EACCES;
5116 		}
5117 		err = check_helper_mem_access(env, regno,
5118 					      meta->map_ptr->key_size, false,
5119 					      NULL);
5120 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5121 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5122 		    !register_is_null(reg)) ||
5123 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5124 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5125 		 * check [value, value + map->value_size) validity
5126 		 */
5127 		if (!meta->map_ptr) {
5128 			/* kernel subsystem misconfigured verifier */
5129 			verbose(env, "invalid map_ptr to access map->value\n");
5130 			return -EACCES;
5131 		}
5132 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5133 		err = check_helper_mem_access(env, regno,
5134 					      meta->map_ptr->value_size, false,
5135 					      meta);
5136 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5137 		if (!reg->btf_id) {
5138 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5139 			return -EACCES;
5140 		}
5141 		meta->ret_btf = reg->btf;
5142 		meta->ret_btf_id = reg->btf_id;
5143 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5144 		if (meta->func_id == BPF_FUNC_spin_lock) {
5145 			if (process_spin_lock(env, regno, true))
5146 				return -EACCES;
5147 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5148 			if (process_spin_lock(env, regno, false))
5149 				return -EACCES;
5150 		} else {
5151 			verbose(env, "verifier internal error\n");
5152 			return -EFAULT;
5153 		}
5154 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5155 		if (process_timer_func(env, regno, meta))
5156 			return -EACCES;
5157 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5158 		meta->subprogno = reg->subprogno;
5159 	} else if (arg_type_is_mem_ptr(arg_type)) {
5160 		/* The access to this pointer is only checked when we hit the
5161 		 * next is_mem_size argument below.
5162 		 */
5163 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5164 	} else if (arg_type_is_mem_size(arg_type)) {
5165 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5166 
5167 		/* This is used to refine r0 return value bounds for helpers
5168 		 * that enforce this value as an upper bound on return values.
5169 		 * See do_refine_retval_range() for helpers that can refine
5170 		 * the return value. C type of helper is u32 so we pull register
5171 		 * bound from umax_value however, if negative verifier errors
5172 		 * out. Only upper bounds can be learned because retval is an
5173 		 * int type and negative retvals are allowed.
5174 		 */
5175 		meta->msize_max_value = reg->umax_value;
5176 
5177 		/* The register is SCALAR_VALUE; the access check
5178 		 * happens using its boundaries.
5179 		 */
5180 		if (!tnum_is_const(reg->var_off))
5181 			/* For unprivileged variable accesses, disable raw
5182 			 * mode so that the program is required to
5183 			 * initialize all the memory that the helper could
5184 			 * just partially fill up.
5185 			 */
5186 			meta = NULL;
5187 
5188 		if (reg->smin_value < 0) {
5189 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5190 				regno);
5191 			return -EACCES;
5192 		}
5193 
5194 		if (reg->umin_value == 0) {
5195 			err = check_helper_mem_access(env, regno - 1, 0,
5196 						      zero_size_allowed,
5197 						      meta);
5198 			if (err)
5199 				return err;
5200 		}
5201 
5202 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5203 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5204 				regno);
5205 			return -EACCES;
5206 		}
5207 		err = check_helper_mem_access(env, regno - 1,
5208 					      reg->umax_value,
5209 					      zero_size_allowed, meta);
5210 		if (!err)
5211 			err = mark_chain_precision(env, regno);
5212 	} else if (arg_type_is_alloc_size(arg_type)) {
5213 		if (!tnum_is_const(reg->var_off)) {
5214 			verbose(env, "R%d is not a known constant'\n",
5215 				regno);
5216 			return -EACCES;
5217 		}
5218 		meta->mem_size = reg->var_off.value;
5219 	} else if (arg_type_is_int_ptr(arg_type)) {
5220 		int size = int_ptr_type_to_size(arg_type);
5221 
5222 		err = check_helper_mem_access(env, regno, size, false, meta);
5223 		if (err)
5224 			return err;
5225 		err = check_ptr_alignment(env, reg, 0, size, true);
5226 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5227 		struct bpf_map *map = reg->map_ptr;
5228 		int map_off;
5229 		u64 map_addr;
5230 		char *str_ptr;
5231 
5232 		if (!bpf_map_is_rdonly(map)) {
5233 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5234 			return -EACCES;
5235 		}
5236 
5237 		if (!tnum_is_const(reg->var_off)) {
5238 			verbose(env, "R%d is not a constant address'\n", regno);
5239 			return -EACCES;
5240 		}
5241 
5242 		if (!map->ops->map_direct_value_addr) {
5243 			verbose(env, "no direct value access support for this map type\n");
5244 			return -EACCES;
5245 		}
5246 
5247 		err = check_map_access(env, regno, reg->off,
5248 				       map->value_size - reg->off, false);
5249 		if (err)
5250 			return err;
5251 
5252 		map_off = reg->off + reg->var_off.value;
5253 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5254 		if (err) {
5255 			verbose(env, "direct value access on string failed\n");
5256 			return err;
5257 		}
5258 
5259 		str_ptr = (char *)(long)(map_addr);
5260 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5261 			verbose(env, "string is not zero-terminated\n");
5262 			return -EINVAL;
5263 		}
5264 	}
5265 
5266 	return err;
5267 }
5268 
5269 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5270 {
5271 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5272 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5273 
5274 	if (func_id != BPF_FUNC_map_update_elem)
5275 		return false;
5276 
5277 	/* It's not possible to get access to a locked struct sock in these
5278 	 * contexts, so updating is safe.
5279 	 */
5280 	switch (type) {
5281 	case BPF_PROG_TYPE_TRACING:
5282 		if (eatype == BPF_TRACE_ITER)
5283 			return true;
5284 		break;
5285 	case BPF_PROG_TYPE_SOCKET_FILTER:
5286 	case BPF_PROG_TYPE_SCHED_CLS:
5287 	case BPF_PROG_TYPE_SCHED_ACT:
5288 	case BPF_PROG_TYPE_XDP:
5289 	case BPF_PROG_TYPE_SK_REUSEPORT:
5290 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5291 	case BPF_PROG_TYPE_SK_LOOKUP:
5292 		return true;
5293 	default:
5294 		break;
5295 	}
5296 
5297 	verbose(env, "cannot update sockmap in this context\n");
5298 	return false;
5299 }
5300 
5301 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5302 {
5303 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5304 }
5305 
5306 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5307 					struct bpf_map *map, int func_id)
5308 {
5309 	if (!map)
5310 		return 0;
5311 
5312 	/* We need a two way check, first is from map perspective ... */
5313 	switch (map->map_type) {
5314 	case BPF_MAP_TYPE_PROG_ARRAY:
5315 		if (func_id != BPF_FUNC_tail_call)
5316 			goto error;
5317 		break;
5318 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5319 		if (func_id != BPF_FUNC_perf_event_read &&
5320 		    func_id != BPF_FUNC_perf_event_output &&
5321 		    func_id != BPF_FUNC_skb_output &&
5322 		    func_id != BPF_FUNC_perf_event_read_value &&
5323 		    func_id != BPF_FUNC_xdp_output)
5324 			goto error;
5325 		break;
5326 	case BPF_MAP_TYPE_RINGBUF:
5327 		if (func_id != BPF_FUNC_ringbuf_output &&
5328 		    func_id != BPF_FUNC_ringbuf_reserve &&
5329 		    func_id != BPF_FUNC_ringbuf_submit &&
5330 		    func_id != BPF_FUNC_ringbuf_discard &&
5331 		    func_id != BPF_FUNC_ringbuf_query)
5332 			goto error;
5333 		break;
5334 	case BPF_MAP_TYPE_STACK_TRACE:
5335 		if (func_id != BPF_FUNC_get_stackid)
5336 			goto error;
5337 		break;
5338 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5339 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5340 		    func_id != BPF_FUNC_current_task_under_cgroup)
5341 			goto error;
5342 		break;
5343 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5344 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5345 		if (func_id != BPF_FUNC_get_local_storage)
5346 			goto error;
5347 		break;
5348 	case BPF_MAP_TYPE_DEVMAP:
5349 	case BPF_MAP_TYPE_DEVMAP_HASH:
5350 		if (func_id != BPF_FUNC_redirect_map &&
5351 		    func_id != BPF_FUNC_map_lookup_elem)
5352 			goto error;
5353 		break;
5354 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5355 	 * appear.
5356 	 */
5357 	case BPF_MAP_TYPE_CPUMAP:
5358 		if (func_id != BPF_FUNC_redirect_map)
5359 			goto error;
5360 		break;
5361 	case BPF_MAP_TYPE_XSKMAP:
5362 		if (func_id != BPF_FUNC_redirect_map &&
5363 		    func_id != BPF_FUNC_map_lookup_elem)
5364 			goto error;
5365 		break;
5366 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5367 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5368 		if (func_id != BPF_FUNC_map_lookup_elem)
5369 			goto error;
5370 		break;
5371 	case BPF_MAP_TYPE_SOCKMAP:
5372 		if (func_id != BPF_FUNC_sk_redirect_map &&
5373 		    func_id != BPF_FUNC_sock_map_update &&
5374 		    func_id != BPF_FUNC_map_delete_elem &&
5375 		    func_id != BPF_FUNC_msg_redirect_map &&
5376 		    func_id != BPF_FUNC_sk_select_reuseport &&
5377 		    func_id != BPF_FUNC_map_lookup_elem &&
5378 		    !may_update_sockmap(env, func_id))
5379 			goto error;
5380 		break;
5381 	case BPF_MAP_TYPE_SOCKHASH:
5382 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5383 		    func_id != BPF_FUNC_sock_hash_update &&
5384 		    func_id != BPF_FUNC_map_delete_elem &&
5385 		    func_id != BPF_FUNC_msg_redirect_hash &&
5386 		    func_id != BPF_FUNC_sk_select_reuseport &&
5387 		    func_id != BPF_FUNC_map_lookup_elem &&
5388 		    !may_update_sockmap(env, func_id))
5389 			goto error;
5390 		break;
5391 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5392 		if (func_id != BPF_FUNC_sk_select_reuseport)
5393 			goto error;
5394 		break;
5395 	case BPF_MAP_TYPE_QUEUE:
5396 	case BPF_MAP_TYPE_STACK:
5397 		if (func_id != BPF_FUNC_map_peek_elem &&
5398 		    func_id != BPF_FUNC_map_pop_elem &&
5399 		    func_id != BPF_FUNC_map_push_elem)
5400 			goto error;
5401 		break;
5402 	case BPF_MAP_TYPE_SK_STORAGE:
5403 		if (func_id != BPF_FUNC_sk_storage_get &&
5404 		    func_id != BPF_FUNC_sk_storage_delete)
5405 			goto error;
5406 		break;
5407 	case BPF_MAP_TYPE_INODE_STORAGE:
5408 		if (func_id != BPF_FUNC_inode_storage_get &&
5409 		    func_id != BPF_FUNC_inode_storage_delete)
5410 			goto error;
5411 		break;
5412 	case BPF_MAP_TYPE_TASK_STORAGE:
5413 		if (func_id != BPF_FUNC_task_storage_get &&
5414 		    func_id != BPF_FUNC_task_storage_delete)
5415 			goto error;
5416 		break;
5417 	default:
5418 		break;
5419 	}
5420 
5421 	/* ... and second from the function itself. */
5422 	switch (func_id) {
5423 	case BPF_FUNC_tail_call:
5424 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5425 			goto error;
5426 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5427 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5428 			return -EINVAL;
5429 		}
5430 		break;
5431 	case BPF_FUNC_perf_event_read:
5432 	case BPF_FUNC_perf_event_output:
5433 	case BPF_FUNC_perf_event_read_value:
5434 	case BPF_FUNC_skb_output:
5435 	case BPF_FUNC_xdp_output:
5436 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5437 			goto error;
5438 		break;
5439 	case BPF_FUNC_get_stackid:
5440 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5441 			goto error;
5442 		break;
5443 	case BPF_FUNC_current_task_under_cgroup:
5444 	case BPF_FUNC_skb_under_cgroup:
5445 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5446 			goto error;
5447 		break;
5448 	case BPF_FUNC_redirect_map:
5449 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5450 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5451 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5452 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5453 			goto error;
5454 		break;
5455 	case BPF_FUNC_sk_redirect_map:
5456 	case BPF_FUNC_msg_redirect_map:
5457 	case BPF_FUNC_sock_map_update:
5458 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5459 			goto error;
5460 		break;
5461 	case BPF_FUNC_sk_redirect_hash:
5462 	case BPF_FUNC_msg_redirect_hash:
5463 	case BPF_FUNC_sock_hash_update:
5464 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5465 			goto error;
5466 		break;
5467 	case BPF_FUNC_get_local_storage:
5468 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5469 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5470 			goto error;
5471 		break;
5472 	case BPF_FUNC_sk_select_reuseport:
5473 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5474 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5475 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5476 			goto error;
5477 		break;
5478 	case BPF_FUNC_map_peek_elem:
5479 	case BPF_FUNC_map_pop_elem:
5480 	case BPF_FUNC_map_push_elem:
5481 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5482 		    map->map_type != BPF_MAP_TYPE_STACK)
5483 			goto error;
5484 		break;
5485 	case BPF_FUNC_sk_storage_get:
5486 	case BPF_FUNC_sk_storage_delete:
5487 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5488 			goto error;
5489 		break;
5490 	case BPF_FUNC_inode_storage_get:
5491 	case BPF_FUNC_inode_storage_delete:
5492 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5493 			goto error;
5494 		break;
5495 	case BPF_FUNC_task_storage_get:
5496 	case BPF_FUNC_task_storage_delete:
5497 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5498 			goto error;
5499 		break;
5500 	default:
5501 		break;
5502 	}
5503 
5504 	return 0;
5505 error:
5506 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5507 		map->map_type, func_id_name(func_id), func_id);
5508 	return -EINVAL;
5509 }
5510 
5511 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5512 {
5513 	int count = 0;
5514 
5515 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5516 		count++;
5517 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5518 		count++;
5519 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5520 		count++;
5521 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5522 		count++;
5523 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5524 		count++;
5525 
5526 	/* We only support one arg being in raw mode at the moment,
5527 	 * which is sufficient for the helper functions we have
5528 	 * right now.
5529 	 */
5530 	return count <= 1;
5531 }
5532 
5533 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5534 				    enum bpf_arg_type arg_next)
5535 {
5536 	return (arg_type_is_mem_ptr(arg_curr) &&
5537 	        !arg_type_is_mem_size(arg_next)) ||
5538 	       (!arg_type_is_mem_ptr(arg_curr) &&
5539 		arg_type_is_mem_size(arg_next));
5540 }
5541 
5542 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5543 {
5544 	/* bpf_xxx(..., buf, len) call will access 'len'
5545 	 * bytes from memory 'buf'. Both arg types need
5546 	 * to be paired, so make sure there's no buggy
5547 	 * helper function specification.
5548 	 */
5549 	if (arg_type_is_mem_size(fn->arg1_type) ||
5550 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5551 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5552 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5553 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5554 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5555 		return false;
5556 
5557 	return true;
5558 }
5559 
5560 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5561 {
5562 	int count = 0;
5563 
5564 	if (arg_type_may_be_refcounted(fn->arg1_type))
5565 		count++;
5566 	if (arg_type_may_be_refcounted(fn->arg2_type))
5567 		count++;
5568 	if (arg_type_may_be_refcounted(fn->arg3_type))
5569 		count++;
5570 	if (arg_type_may_be_refcounted(fn->arg4_type))
5571 		count++;
5572 	if (arg_type_may_be_refcounted(fn->arg5_type))
5573 		count++;
5574 
5575 	/* A reference acquiring function cannot acquire
5576 	 * another refcounted ptr.
5577 	 */
5578 	if (may_be_acquire_function(func_id) && count)
5579 		return false;
5580 
5581 	/* We only support one arg being unreferenced at the moment,
5582 	 * which is sufficient for the helper functions we have right now.
5583 	 */
5584 	return count <= 1;
5585 }
5586 
5587 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5588 {
5589 	int i;
5590 
5591 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5592 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5593 			return false;
5594 
5595 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5596 			return false;
5597 	}
5598 
5599 	return true;
5600 }
5601 
5602 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5603 {
5604 	return check_raw_mode_ok(fn) &&
5605 	       check_arg_pair_ok(fn) &&
5606 	       check_btf_id_ok(fn) &&
5607 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5608 }
5609 
5610 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5611  * are now invalid, so turn them into unknown SCALAR_VALUE.
5612  */
5613 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5614 				     struct bpf_func_state *state)
5615 {
5616 	struct bpf_reg_state *regs = state->regs, *reg;
5617 	int i;
5618 
5619 	for (i = 0; i < MAX_BPF_REG; i++)
5620 		if (reg_is_pkt_pointer_any(&regs[i]))
5621 			mark_reg_unknown(env, regs, i);
5622 
5623 	bpf_for_each_spilled_reg(i, state, reg) {
5624 		if (!reg)
5625 			continue;
5626 		if (reg_is_pkt_pointer_any(reg))
5627 			__mark_reg_unknown(env, reg);
5628 	}
5629 }
5630 
5631 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5632 {
5633 	struct bpf_verifier_state *vstate = env->cur_state;
5634 	int i;
5635 
5636 	for (i = 0; i <= vstate->curframe; i++)
5637 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5638 }
5639 
5640 enum {
5641 	AT_PKT_END = -1,
5642 	BEYOND_PKT_END = -2,
5643 };
5644 
5645 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5646 {
5647 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5648 	struct bpf_reg_state *reg = &state->regs[regn];
5649 
5650 	if (reg->type != PTR_TO_PACKET)
5651 		/* PTR_TO_PACKET_META is not supported yet */
5652 		return;
5653 
5654 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5655 	 * How far beyond pkt_end it goes is unknown.
5656 	 * if (!range_open) it's the case of pkt >= pkt_end
5657 	 * if (range_open) it's the case of pkt > pkt_end
5658 	 * hence this pointer is at least 1 byte bigger than pkt_end
5659 	 */
5660 	if (range_open)
5661 		reg->range = BEYOND_PKT_END;
5662 	else
5663 		reg->range = AT_PKT_END;
5664 }
5665 
5666 static void release_reg_references(struct bpf_verifier_env *env,
5667 				   struct bpf_func_state *state,
5668 				   int ref_obj_id)
5669 {
5670 	struct bpf_reg_state *regs = state->regs, *reg;
5671 	int i;
5672 
5673 	for (i = 0; i < MAX_BPF_REG; i++)
5674 		if (regs[i].ref_obj_id == ref_obj_id)
5675 			mark_reg_unknown(env, regs, i);
5676 
5677 	bpf_for_each_spilled_reg(i, state, reg) {
5678 		if (!reg)
5679 			continue;
5680 		if (reg->ref_obj_id == ref_obj_id)
5681 			__mark_reg_unknown(env, reg);
5682 	}
5683 }
5684 
5685 /* The pointer with the specified id has released its reference to kernel
5686  * resources. Identify all copies of the same pointer and clear the reference.
5687  */
5688 static int release_reference(struct bpf_verifier_env *env,
5689 			     int ref_obj_id)
5690 {
5691 	struct bpf_verifier_state *vstate = env->cur_state;
5692 	int err;
5693 	int i;
5694 
5695 	err = release_reference_state(cur_func(env), ref_obj_id);
5696 	if (err)
5697 		return err;
5698 
5699 	for (i = 0; i <= vstate->curframe; i++)
5700 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5701 
5702 	return 0;
5703 }
5704 
5705 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5706 				    struct bpf_reg_state *regs)
5707 {
5708 	int i;
5709 
5710 	/* after the call registers r0 - r5 were scratched */
5711 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5712 		mark_reg_not_init(env, regs, caller_saved[i]);
5713 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5714 	}
5715 }
5716 
5717 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5718 				   struct bpf_func_state *caller,
5719 				   struct bpf_func_state *callee,
5720 				   int insn_idx);
5721 
5722 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5723 			     int *insn_idx, int subprog,
5724 			     set_callee_state_fn set_callee_state_cb)
5725 {
5726 	struct bpf_verifier_state *state = env->cur_state;
5727 	struct bpf_func_info_aux *func_info_aux;
5728 	struct bpf_func_state *caller, *callee;
5729 	int err;
5730 	bool is_global = false;
5731 
5732 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5733 		verbose(env, "the call stack of %d frames is too deep\n",
5734 			state->curframe + 2);
5735 		return -E2BIG;
5736 	}
5737 
5738 	caller = state->frame[state->curframe];
5739 	if (state->frame[state->curframe + 1]) {
5740 		verbose(env, "verifier bug. Frame %d already allocated\n",
5741 			state->curframe + 1);
5742 		return -EFAULT;
5743 	}
5744 
5745 	func_info_aux = env->prog->aux->func_info_aux;
5746 	if (func_info_aux)
5747 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5748 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5749 	if (err == -EFAULT)
5750 		return err;
5751 	if (is_global) {
5752 		if (err) {
5753 			verbose(env, "Caller passes invalid args into func#%d\n",
5754 				subprog);
5755 			return err;
5756 		} else {
5757 			if (env->log.level & BPF_LOG_LEVEL)
5758 				verbose(env,
5759 					"Func#%d is global and valid. Skipping.\n",
5760 					subprog);
5761 			clear_caller_saved_regs(env, caller->regs);
5762 
5763 			/* All global functions return a 64-bit SCALAR_VALUE */
5764 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5765 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5766 
5767 			/* continue with next insn after call */
5768 			return 0;
5769 		}
5770 	}
5771 
5772 	if (insn->code == (BPF_JMP | BPF_CALL) &&
5773 	    insn->imm == BPF_FUNC_timer_set_callback) {
5774 		struct bpf_verifier_state *async_cb;
5775 
5776 		/* there is no real recursion here. timer callbacks are async */
5777 		env->subprog_info[subprog].is_async_cb = true;
5778 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5779 					 *insn_idx, subprog);
5780 		if (!async_cb)
5781 			return -EFAULT;
5782 		callee = async_cb->frame[0];
5783 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
5784 
5785 		/* Convert bpf_timer_set_callback() args into timer callback args */
5786 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
5787 		if (err)
5788 			return err;
5789 
5790 		clear_caller_saved_regs(env, caller->regs);
5791 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
5792 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5793 		/* continue with next insn after call */
5794 		return 0;
5795 	}
5796 
5797 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5798 	if (!callee)
5799 		return -ENOMEM;
5800 	state->frame[state->curframe + 1] = callee;
5801 
5802 	/* callee cannot access r0, r6 - r9 for reading and has to write
5803 	 * into its own stack before reading from it.
5804 	 * callee can read/write into caller's stack
5805 	 */
5806 	init_func_state(env, callee,
5807 			/* remember the callsite, it will be used by bpf_exit */
5808 			*insn_idx /* callsite */,
5809 			state->curframe + 1 /* frameno within this callchain */,
5810 			subprog /* subprog number within this prog */);
5811 
5812 	/* Transfer references to the callee */
5813 	err = copy_reference_state(callee, caller);
5814 	if (err)
5815 		return err;
5816 
5817 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
5818 	if (err)
5819 		return err;
5820 
5821 	clear_caller_saved_regs(env, caller->regs);
5822 
5823 	/* only increment it after check_reg_arg() finished */
5824 	state->curframe++;
5825 
5826 	/* and go analyze first insn of the callee */
5827 	*insn_idx = env->subprog_info[subprog].start - 1;
5828 
5829 	if (env->log.level & BPF_LOG_LEVEL) {
5830 		verbose(env, "caller:\n");
5831 		print_verifier_state(env, caller);
5832 		verbose(env, "callee:\n");
5833 		print_verifier_state(env, callee);
5834 	}
5835 	return 0;
5836 }
5837 
5838 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5839 				   struct bpf_func_state *caller,
5840 				   struct bpf_func_state *callee)
5841 {
5842 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5843 	 *      void *callback_ctx, u64 flags);
5844 	 * callback_fn(struct bpf_map *map, void *key, void *value,
5845 	 *      void *callback_ctx);
5846 	 */
5847 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5848 
5849 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5850 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5851 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5852 
5853 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5854 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5855 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5856 
5857 	/* pointer to stack or null */
5858 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5859 
5860 	/* unused */
5861 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5862 	return 0;
5863 }
5864 
5865 static int set_callee_state(struct bpf_verifier_env *env,
5866 			    struct bpf_func_state *caller,
5867 			    struct bpf_func_state *callee, int insn_idx)
5868 {
5869 	int i;
5870 
5871 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5872 	 * pointers, which connects us up to the liveness chain
5873 	 */
5874 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5875 		callee->regs[i] = caller->regs[i];
5876 	return 0;
5877 }
5878 
5879 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5880 			   int *insn_idx)
5881 {
5882 	int subprog, target_insn;
5883 
5884 	target_insn = *insn_idx + insn->imm + 1;
5885 	subprog = find_subprog(env, target_insn);
5886 	if (subprog < 0) {
5887 		verbose(env, "verifier bug. No program starts at insn %d\n",
5888 			target_insn);
5889 		return -EFAULT;
5890 	}
5891 
5892 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5893 }
5894 
5895 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5896 				       struct bpf_func_state *caller,
5897 				       struct bpf_func_state *callee,
5898 				       int insn_idx)
5899 {
5900 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5901 	struct bpf_map *map;
5902 	int err;
5903 
5904 	if (bpf_map_ptr_poisoned(insn_aux)) {
5905 		verbose(env, "tail_call abusing map_ptr\n");
5906 		return -EINVAL;
5907 	}
5908 
5909 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5910 	if (!map->ops->map_set_for_each_callback_args ||
5911 	    !map->ops->map_for_each_callback) {
5912 		verbose(env, "callback function not allowed for map\n");
5913 		return -ENOTSUPP;
5914 	}
5915 
5916 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5917 	if (err)
5918 		return err;
5919 
5920 	callee->in_callback_fn = true;
5921 	return 0;
5922 }
5923 
5924 static int set_timer_callback_state(struct bpf_verifier_env *env,
5925 				    struct bpf_func_state *caller,
5926 				    struct bpf_func_state *callee,
5927 				    int insn_idx)
5928 {
5929 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
5930 
5931 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
5932 	 * callback_fn(struct bpf_map *map, void *key, void *value);
5933 	 */
5934 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
5935 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
5936 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
5937 
5938 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5939 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5940 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
5941 
5942 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5943 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5944 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
5945 
5946 	/* unused */
5947 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
5948 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5949 	callee->in_async_callback_fn = true;
5950 	return 0;
5951 }
5952 
5953 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5954 {
5955 	struct bpf_verifier_state *state = env->cur_state;
5956 	struct bpf_func_state *caller, *callee;
5957 	struct bpf_reg_state *r0;
5958 	int err;
5959 
5960 	callee = state->frame[state->curframe];
5961 	r0 = &callee->regs[BPF_REG_0];
5962 	if (r0->type == PTR_TO_STACK) {
5963 		/* technically it's ok to return caller's stack pointer
5964 		 * (or caller's caller's pointer) back to the caller,
5965 		 * since these pointers are valid. Only current stack
5966 		 * pointer will be invalid as soon as function exits,
5967 		 * but let's be conservative
5968 		 */
5969 		verbose(env, "cannot return stack pointer to the caller\n");
5970 		return -EINVAL;
5971 	}
5972 
5973 	state->curframe--;
5974 	caller = state->frame[state->curframe];
5975 	if (callee->in_callback_fn) {
5976 		/* enforce R0 return value range [0, 1]. */
5977 		struct tnum range = tnum_range(0, 1);
5978 
5979 		if (r0->type != SCALAR_VALUE) {
5980 			verbose(env, "R0 not a scalar value\n");
5981 			return -EACCES;
5982 		}
5983 		if (!tnum_in(range, r0->var_off)) {
5984 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5985 			return -EINVAL;
5986 		}
5987 	} else {
5988 		/* return to the caller whatever r0 had in the callee */
5989 		caller->regs[BPF_REG_0] = *r0;
5990 	}
5991 
5992 	/* Transfer references to the caller */
5993 	err = copy_reference_state(caller, callee);
5994 	if (err)
5995 		return err;
5996 
5997 	*insn_idx = callee->callsite + 1;
5998 	if (env->log.level & BPF_LOG_LEVEL) {
5999 		verbose(env, "returning from callee:\n");
6000 		print_verifier_state(env, callee);
6001 		verbose(env, "to caller at %d:\n", *insn_idx);
6002 		print_verifier_state(env, caller);
6003 	}
6004 	/* clear everything in the callee */
6005 	free_func_state(callee);
6006 	state->frame[state->curframe + 1] = NULL;
6007 	return 0;
6008 }
6009 
6010 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6011 				   int func_id,
6012 				   struct bpf_call_arg_meta *meta)
6013 {
6014 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6015 
6016 	if (ret_type != RET_INTEGER ||
6017 	    (func_id != BPF_FUNC_get_stack &&
6018 	     func_id != BPF_FUNC_get_task_stack &&
6019 	     func_id != BPF_FUNC_probe_read_str &&
6020 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6021 	     func_id != BPF_FUNC_probe_read_user_str))
6022 		return;
6023 
6024 	ret_reg->smax_value = meta->msize_max_value;
6025 	ret_reg->s32_max_value = meta->msize_max_value;
6026 	ret_reg->smin_value = -MAX_ERRNO;
6027 	ret_reg->s32_min_value = -MAX_ERRNO;
6028 	__reg_deduce_bounds(ret_reg);
6029 	__reg_bound_offset(ret_reg);
6030 	__update_reg_bounds(ret_reg);
6031 }
6032 
6033 static int
6034 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6035 		int func_id, int insn_idx)
6036 {
6037 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6038 	struct bpf_map *map = meta->map_ptr;
6039 
6040 	if (func_id != BPF_FUNC_tail_call &&
6041 	    func_id != BPF_FUNC_map_lookup_elem &&
6042 	    func_id != BPF_FUNC_map_update_elem &&
6043 	    func_id != BPF_FUNC_map_delete_elem &&
6044 	    func_id != BPF_FUNC_map_push_elem &&
6045 	    func_id != BPF_FUNC_map_pop_elem &&
6046 	    func_id != BPF_FUNC_map_peek_elem &&
6047 	    func_id != BPF_FUNC_for_each_map_elem &&
6048 	    func_id != BPF_FUNC_redirect_map)
6049 		return 0;
6050 
6051 	if (map == NULL) {
6052 		verbose(env, "kernel subsystem misconfigured verifier\n");
6053 		return -EINVAL;
6054 	}
6055 
6056 	/* In case of read-only, some additional restrictions
6057 	 * need to be applied in order to prevent altering the
6058 	 * state of the map from program side.
6059 	 */
6060 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6061 	    (func_id == BPF_FUNC_map_delete_elem ||
6062 	     func_id == BPF_FUNC_map_update_elem ||
6063 	     func_id == BPF_FUNC_map_push_elem ||
6064 	     func_id == BPF_FUNC_map_pop_elem)) {
6065 		verbose(env, "write into map forbidden\n");
6066 		return -EACCES;
6067 	}
6068 
6069 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6070 		bpf_map_ptr_store(aux, meta->map_ptr,
6071 				  !meta->map_ptr->bypass_spec_v1);
6072 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6073 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6074 				  !meta->map_ptr->bypass_spec_v1);
6075 	return 0;
6076 }
6077 
6078 static int
6079 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6080 		int func_id, int insn_idx)
6081 {
6082 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6083 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6084 	struct bpf_map *map = meta->map_ptr;
6085 	struct tnum range;
6086 	u64 val;
6087 	int err;
6088 
6089 	if (func_id != BPF_FUNC_tail_call)
6090 		return 0;
6091 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6092 		verbose(env, "kernel subsystem misconfigured verifier\n");
6093 		return -EINVAL;
6094 	}
6095 
6096 	range = tnum_range(0, map->max_entries - 1);
6097 	reg = &regs[BPF_REG_3];
6098 
6099 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6100 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6101 		return 0;
6102 	}
6103 
6104 	err = mark_chain_precision(env, BPF_REG_3);
6105 	if (err)
6106 		return err;
6107 
6108 	val = reg->var_off.value;
6109 	if (bpf_map_key_unseen(aux))
6110 		bpf_map_key_store(aux, val);
6111 	else if (!bpf_map_key_poisoned(aux) &&
6112 		  bpf_map_key_immediate(aux) != val)
6113 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6114 	return 0;
6115 }
6116 
6117 static int check_reference_leak(struct bpf_verifier_env *env)
6118 {
6119 	struct bpf_func_state *state = cur_func(env);
6120 	int i;
6121 
6122 	for (i = 0; i < state->acquired_refs; i++) {
6123 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6124 			state->refs[i].id, state->refs[i].insn_idx);
6125 	}
6126 	return state->acquired_refs ? -EINVAL : 0;
6127 }
6128 
6129 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6130 				   struct bpf_reg_state *regs)
6131 {
6132 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6133 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6134 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6135 	int err, fmt_map_off, num_args;
6136 	u64 fmt_addr;
6137 	char *fmt;
6138 
6139 	/* data must be an array of u64 */
6140 	if (data_len_reg->var_off.value % 8)
6141 		return -EINVAL;
6142 	num_args = data_len_reg->var_off.value / 8;
6143 
6144 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6145 	 * and map_direct_value_addr is set.
6146 	 */
6147 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6148 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6149 						  fmt_map_off);
6150 	if (err) {
6151 		verbose(env, "verifier bug\n");
6152 		return -EFAULT;
6153 	}
6154 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6155 
6156 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6157 	 * can focus on validating the format specifiers.
6158 	 */
6159 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6160 	if (err < 0)
6161 		verbose(env, "Invalid format string\n");
6162 
6163 	return err;
6164 }
6165 
6166 static int check_get_func_ip(struct bpf_verifier_env *env)
6167 {
6168 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6169 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6170 	int func_id = BPF_FUNC_get_func_ip;
6171 
6172 	if (type == BPF_PROG_TYPE_TRACING) {
6173 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6174 		    eatype != BPF_MODIFY_RETURN) {
6175 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6176 				func_id_name(func_id), func_id);
6177 			return -ENOTSUPP;
6178 		}
6179 		return 0;
6180 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6181 		return 0;
6182 	}
6183 
6184 	verbose(env, "func %s#%d not supported for program type %d\n",
6185 		func_id_name(func_id), func_id, type);
6186 	return -ENOTSUPP;
6187 }
6188 
6189 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6190 			     int *insn_idx_p)
6191 {
6192 	const struct bpf_func_proto *fn = NULL;
6193 	struct bpf_reg_state *regs;
6194 	struct bpf_call_arg_meta meta;
6195 	int insn_idx = *insn_idx_p;
6196 	bool changes_data;
6197 	int i, err, func_id;
6198 
6199 	/* find function prototype */
6200 	func_id = insn->imm;
6201 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6202 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6203 			func_id);
6204 		return -EINVAL;
6205 	}
6206 
6207 	if (env->ops->get_func_proto)
6208 		fn = env->ops->get_func_proto(func_id, env->prog);
6209 	if (!fn) {
6210 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6211 			func_id);
6212 		return -EINVAL;
6213 	}
6214 
6215 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6216 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6217 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6218 		return -EINVAL;
6219 	}
6220 
6221 	if (fn->allowed && !fn->allowed(env->prog)) {
6222 		verbose(env, "helper call is not allowed in probe\n");
6223 		return -EINVAL;
6224 	}
6225 
6226 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6227 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6228 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6229 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6230 			func_id_name(func_id), func_id);
6231 		return -EINVAL;
6232 	}
6233 
6234 	memset(&meta, 0, sizeof(meta));
6235 	meta.pkt_access = fn->pkt_access;
6236 
6237 	err = check_func_proto(fn, func_id);
6238 	if (err) {
6239 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6240 			func_id_name(func_id), func_id);
6241 		return err;
6242 	}
6243 
6244 	meta.func_id = func_id;
6245 	/* check args */
6246 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6247 		err = check_func_arg(env, i, &meta, fn);
6248 		if (err)
6249 			return err;
6250 	}
6251 
6252 	err = record_func_map(env, &meta, func_id, insn_idx);
6253 	if (err)
6254 		return err;
6255 
6256 	err = record_func_key(env, &meta, func_id, insn_idx);
6257 	if (err)
6258 		return err;
6259 
6260 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6261 	 * is inferred from register state.
6262 	 */
6263 	for (i = 0; i < meta.access_size; i++) {
6264 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6265 				       BPF_WRITE, -1, false);
6266 		if (err)
6267 			return err;
6268 	}
6269 
6270 	if (func_id == BPF_FUNC_tail_call) {
6271 		err = check_reference_leak(env);
6272 		if (err) {
6273 			verbose(env, "tail_call would lead to reference leak\n");
6274 			return err;
6275 		}
6276 	} else if (is_release_function(func_id)) {
6277 		err = release_reference(env, meta.ref_obj_id);
6278 		if (err) {
6279 			verbose(env, "func %s#%d reference has not been acquired before\n",
6280 				func_id_name(func_id), func_id);
6281 			return err;
6282 		}
6283 	}
6284 
6285 	regs = cur_regs(env);
6286 
6287 	/* check that flags argument in get_local_storage(map, flags) is 0,
6288 	 * this is required because get_local_storage() can't return an error.
6289 	 */
6290 	if (func_id == BPF_FUNC_get_local_storage &&
6291 	    !register_is_null(&regs[BPF_REG_2])) {
6292 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6293 		return -EINVAL;
6294 	}
6295 
6296 	if (func_id == BPF_FUNC_for_each_map_elem) {
6297 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6298 					set_map_elem_callback_state);
6299 		if (err < 0)
6300 			return -EINVAL;
6301 	}
6302 
6303 	if (func_id == BPF_FUNC_timer_set_callback) {
6304 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6305 					set_timer_callback_state);
6306 		if (err < 0)
6307 			return -EINVAL;
6308 	}
6309 
6310 	if (func_id == BPF_FUNC_snprintf) {
6311 		err = check_bpf_snprintf_call(env, regs);
6312 		if (err < 0)
6313 			return err;
6314 	}
6315 
6316 	/* reset caller saved regs */
6317 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6318 		mark_reg_not_init(env, regs, caller_saved[i]);
6319 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6320 	}
6321 
6322 	/* helper call returns 64-bit value. */
6323 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6324 
6325 	/* update return register (already marked as written above) */
6326 	if (fn->ret_type == RET_INTEGER) {
6327 		/* sets type to SCALAR_VALUE */
6328 		mark_reg_unknown(env, regs, BPF_REG_0);
6329 	} else if (fn->ret_type == RET_VOID) {
6330 		regs[BPF_REG_0].type = NOT_INIT;
6331 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6332 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6333 		/* There is no offset yet applied, variable or fixed */
6334 		mark_reg_known_zero(env, regs, BPF_REG_0);
6335 		/* remember map_ptr, so that check_map_access()
6336 		 * can check 'value_size' boundary of memory access
6337 		 * to map element returned from bpf_map_lookup_elem()
6338 		 */
6339 		if (meta.map_ptr == NULL) {
6340 			verbose(env,
6341 				"kernel subsystem misconfigured verifier\n");
6342 			return -EINVAL;
6343 		}
6344 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6345 		regs[BPF_REG_0].map_uid = meta.map_uid;
6346 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6347 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6348 			if (map_value_has_spin_lock(meta.map_ptr))
6349 				regs[BPF_REG_0].id = ++env->id_gen;
6350 		} else {
6351 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6352 		}
6353 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6354 		mark_reg_known_zero(env, regs, BPF_REG_0);
6355 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6356 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6357 		mark_reg_known_zero(env, regs, BPF_REG_0);
6358 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6359 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6360 		mark_reg_known_zero(env, regs, BPF_REG_0);
6361 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6362 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6363 		mark_reg_known_zero(env, regs, BPF_REG_0);
6364 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6365 		regs[BPF_REG_0].mem_size = meta.mem_size;
6366 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6367 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6368 		const struct btf_type *t;
6369 
6370 		mark_reg_known_zero(env, regs, BPF_REG_0);
6371 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6372 		if (!btf_type_is_struct(t)) {
6373 			u32 tsize;
6374 			const struct btf_type *ret;
6375 			const char *tname;
6376 
6377 			/* resolve the type size of ksym. */
6378 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6379 			if (IS_ERR(ret)) {
6380 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6381 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6382 					tname, PTR_ERR(ret));
6383 				return -EINVAL;
6384 			}
6385 			regs[BPF_REG_0].type =
6386 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6387 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6388 			regs[BPF_REG_0].mem_size = tsize;
6389 		} else {
6390 			regs[BPF_REG_0].type =
6391 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6392 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6393 			regs[BPF_REG_0].btf = meta.ret_btf;
6394 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6395 		}
6396 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6397 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
6398 		int ret_btf_id;
6399 
6400 		mark_reg_known_zero(env, regs, BPF_REG_0);
6401 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6402 						     PTR_TO_BTF_ID :
6403 						     PTR_TO_BTF_ID_OR_NULL;
6404 		ret_btf_id = *fn->ret_btf_id;
6405 		if (ret_btf_id == 0) {
6406 			verbose(env, "invalid return type %d of func %s#%d\n",
6407 				fn->ret_type, func_id_name(func_id), func_id);
6408 			return -EINVAL;
6409 		}
6410 		/* current BPF helper definitions are only coming from
6411 		 * built-in code with type IDs from  vmlinux BTF
6412 		 */
6413 		regs[BPF_REG_0].btf = btf_vmlinux;
6414 		regs[BPF_REG_0].btf_id = ret_btf_id;
6415 	} else {
6416 		verbose(env, "unknown return type %d of func %s#%d\n",
6417 			fn->ret_type, func_id_name(func_id), func_id);
6418 		return -EINVAL;
6419 	}
6420 
6421 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
6422 		regs[BPF_REG_0].id = ++env->id_gen;
6423 
6424 	if (is_ptr_cast_function(func_id)) {
6425 		/* For release_reference() */
6426 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6427 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6428 		int id = acquire_reference_state(env, insn_idx);
6429 
6430 		if (id < 0)
6431 			return id;
6432 		/* For mark_ptr_or_null_reg() */
6433 		regs[BPF_REG_0].id = id;
6434 		/* For release_reference() */
6435 		regs[BPF_REG_0].ref_obj_id = id;
6436 	}
6437 
6438 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6439 
6440 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6441 	if (err)
6442 		return err;
6443 
6444 	if ((func_id == BPF_FUNC_get_stack ||
6445 	     func_id == BPF_FUNC_get_task_stack) &&
6446 	    !env->prog->has_callchain_buf) {
6447 		const char *err_str;
6448 
6449 #ifdef CONFIG_PERF_EVENTS
6450 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6451 		err_str = "cannot get callchain buffer for func %s#%d\n";
6452 #else
6453 		err = -ENOTSUPP;
6454 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6455 #endif
6456 		if (err) {
6457 			verbose(env, err_str, func_id_name(func_id), func_id);
6458 			return err;
6459 		}
6460 
6461 		env->prog->has_callchain_buf = true;
6462 	}
6463 
6464 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6465 		env->prog->call_get_stack = true;
6466 
6467 	if (func_id == BPF_FUNC_get_func_ip) {
6468 		if (check_get_func_ip(env))
6469 			return -ENOTSUPP;
6470 		env->prog->call_get_func_ip = true;
6471 	}
6472 
6473 	if (changes_data)
6474 		clear_all_pkt_pointers(env);
6475 	return 0;
6476 }
6477 
6478 /* mark_btf_func_reg_size() is used when the reg size is determined by
6479  * the BTF func_proto's return value size and argument.
6480  */
6481 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6482 				   size_t reg_size)
6483 {
6484 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6485 
6486 	if (regno == BPF_REG_0) {
6487 		/* Function return value */
6488 		reg->live |= REG_LIVE_WRITTEN;
6489 		reg->subreg_def = reg_size == sizeof(u64) ?
6490 			DEF_NOT_SUBREG : env->insn_idx + 1;
6491 	} else {
6492 		/* Function argument */
6493 		if (reg_size == sizeof(u64)) {
6494 			mark_insn_zext(env, reg);
6495 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6496 		} else {
6497 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6498 		}
6499 	}
6500 }
6501 
6502 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6503 {
6504 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6505 	struct bpf_reg_state *regs = cur_regs(env);
6506 	const char *func_name, *ptr_type_name;
6507 	u32 i, nargs, func_id, ptr_type_id;
6508 	const struct btf_param *args;
6509 	int err;
6510 
6511 	func_id = insn->imm;
6512 	func = btf_type_by_id(btf_vmlinux, func_id);
6513 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6514 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
6515 
6516 	if (!env->ops->check_kfunc_call ||
6517 	    !env->ops->check_kfunc_call(func_id)) {
6518 		verbose(env, "calling kernel function %s is not allowed\n",
6519 			func_name);
6520 		return -EACCES;
6521 	}
6522 
6523 	/* Check the arguments */
6524 	err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6525 	if (err)
6526 		return err;
6527 
6528 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6529 		mark_reg_not_init(env, regs, caller_saved[i]);
6530 
6531 	/* Check return type */
6532 	t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6533 	if (btf_type_is_scalar(t)) {
6534 		mark_reg_unknown(env, regs, BPF_REG_0);
6535 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6536 	} else if (btf_type_is_ptr(t)) {
6537 		ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6538 						   &ptr_type_id);
6539 		if (!btf_type_is_struct(ptr_type)) {
6540 			ptr_type_name = btf_name_by_offset(btf_vmlinux,
6541 							   ptr_type->name_off);
6542 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6543 				func_name, btf_type_str(ptr_type),
6544 				ptr_type_name);
6545 			return -EINVAL;
6546 		}
6547 		mark_reg_known_zero(env, regs, BPF_REG_0);
6548 		regs[BPF_REG_0].btf = btf_vmlinux;
6549 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6550 		regs[BPF_REG_0].btf_id = ptr_type_id;
6551 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6552 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6553 
6554 	nargs = btf_type_vlen(func_proto);
6555 	args = (const struct btf_param *)(func_proto + 1);
6556 	for (i = 0; i < nargs; i++) {
6557 		u32 regno = i + 1;
6558 
6559 		t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6560 		if (btf_type_is_ptr(t))
6561 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6562 		else
6563 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6564 			mark_btf_func_reg_size(env, regno, t->size);
6565 	}
6566 
6567 	return 0;
6568 }
6569 
6570 static bool signed_add_overflows(s64 a, s64 b)
6571 {
6572 	/* Do the add in u64, where overflow is well-defined */
6573 	s64 res = (s64)((u64)a + (u64)b);
6574 
6575 	if (b < 0)
6576 		return res > a;
6577 	return res < a;
6578 }
6579 
6580 static bool signed_add32_overflows(s32 a, s32 b)
6581 {
6582 	/* Do the add in u32, where overflow is well-defined */
6583 	s32 res = (s32)((u32)a + (u32)b);
6584 
6585 	if (b < 0)
6586 		return res > a;
6587 	return res < a;
6588 }
6589 
6590 static bool signed_sub_overflows(s64 a, s64 b)
6591 {
6592 	/* Do the sub in u64, where overflow is well-defined */
6593 	s64 res = (s64)((u64)a - (u64)b);
6594 
6595 	if (b < 0)
6596 		return res < a;
6597 	return res > a;
6598 }
6599 
6600 static bool signed_sub32_overflows(s32 a, s32 b)
6601 {
6602 	/* Do the sub in u32, where overflow is well-defined */
6603 	s32 res = (s32)((u32)a - (u32)b);
6604 
6605 	if (b < 0)
6606 		return res < a;
6607 	return res > a;
6608 }
6609 
6610 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6611 				  const struct bpf_reg_state *reg,
6612 				  enum bpf_reg_type type)
6613 {
6614 	bool known = tnum_is_const(reg->var_off);
6615 	s64 val = reg->var_off.value;
6616 	s64 smin = reg->smin_value;
6617 
6618 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6619 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6620 			reg_type_str[type], val);
6621 		return false;
6622 	}
6623 
6624 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6625 		verbose(env, "%s pointer offset %d is not allowed\n",
6626 			reg_type_str[type], reg->off);
6627 		return false;
6628 	}
6629 
6630 	if (smin == S64_MIN) {
6631 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6632 			reg_type_str[type]);
6633 		return false;
6634 	}
6635 
6636 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6637 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6638 			smin, reg_type_str[type]);
6639 		return false;
6640 	}
6641 
6642 	return true;
6643 }
6644 
6645 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6646 {
6647 	return &env->insn_aux_data[env->insn_idx];
6648 }
6649 
6650 enum {
6651 	REASON_BOUNDS	= -1,
6652 	REASON_TYPE	= -2,
6653 	REASON_PATHS	= -3,
6654 	REASON_LIMIT	= -4,
6655 	REASON_STACK	= -5,
6656 };
6657 
6658 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6659 			      u32 *alu_limit, bool mask_to_left)
6660 {
6661 	u32 max = 0, ptr_limit = 0;
6662 
6663 	switch (ptr_reg->type) {
6664 	case PTR_TO_STACK:
6665 		/* Offset 0 is out-of-bounds, but acceptable start for the
6666 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6667 		 * offset where we would need to deal with min/max bounds is
6668 		 * currently prohibited for unprivileged.
6669 		 */
6670 		max = MAX_BPF_STACK + mask_to_left;
6671 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6672 		break;
6673 	case PTR_TO_MAP_VALUE:
6674 		max = ptr_reg->map_ptr->value_size;
6675 		ptr_limit = (mask_to_left ?
6676 			     ptr_reg->smin_value :
6677 			     ptr_reg->umax_value) + ptr_reg->off;
6678 		break;
6679 	default:
6680 		return REASON_TYPE;
6681 	}
6682 
6683 	if (ptr_limit >= max)
6684 		return REASON_LIMIT;
6685 	*alu_limit = ptr_limit;
6686 	return 0;
6687 }
6688 
6689 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6690 				    const struct bpf_insn *insn)
6691 {
6692 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6693 }
6694 
6695 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6696 				       u32 alu_state, u32 alu_limit)
6697 {
6698 	/* If we arrived here from different branches with different
6699 	 * state or limits to sanitize, then this won't work.
6700 	 */
6701 	if (aux->alu_state &&
6702 	    (aux->alu_state != alu_state ||
6703 	     aux->alu_limit != alu_limit))
6704 		return REASON_PATHS;
6705 
6706 	/* Corresponding fixup done in do_misc_fixups(). */
6707 	aux->alu_state = alu_state;
6708 	aux->alu_limit = alu_limit;
6709 	return 0;
6710 }
6711 
6712 static int sanitize_val_alu(struct bpf_verifier_env *env,
6713 			    struct bpf_insn *insn)
6714 {
6715 	struct bpf_insn_aux_data *aux = cur_aux(env);
6716 
6717 	if (can_skip_alu_sanitation(env, insn))
6718 		return 0;
6719 
6720 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6721 }
6722 
6723 static bool sanitize_needed(u8 opcode)
6724 {
6725 	return opcode == BPF_ADD || opcode == BPF_SUB;
6726 }
6727 
6728 struct bpf_sanitize_info {
6729 	struct bpf_insn_aux_data aux;
6730 	bool mask_to_left;
6731 };
6732 
6733 static struct bpf_verifier_state *
6734 sanitize_speculative_path(struct bpf_verifier_env *env,
6735 			  const struct bpf_insn *insn,
6736 			  u32 next_idx, u32 curr_idx)
6737 {
6738 	struct bpf_verifier_state *branch;
6739 	struct bpf_reg_state *regs;
6740 
6741 	branch = push_stack(env, next_idx, curr_idx, true);
6742 	if (branch && insn) {
6743 		regs = branch->frame[branch->curframe]->regs;
6744 		if (BPF_SRC(insn->code) == BPF_K) {
6745 			mark_reg_unknown(env, regs, insn->dst_reg);
6746 		} else if (BPF_SRC(insn->code) == BPF_X) {
6747 			mark_reg_unknown(env, regs, insn->dst_reg);
6748 			mark_reg_unknown(env, regs, insn->src_reg);
6749 		}
6750 	}
6751 	return branch;
6752 }
6753 
6754 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6755 			    struct bpf_insn *insn,
6756 			    const struct bpf_reg_state *ptr_reg,
6757 			    const struct bpf_reg_state *off_reg,
6758 			    struct bpf_reg_state *dst_reg,
6759 			    struct bpf_sanitize_info *info,
6760 			    const bool commit_window)
6761 {
6762 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6763 	struct bpf_verifier_state *vstate = env->cur_state;
6764 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6765 	bool off_is_neg = off_reg->smin_value < 0;
6766 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6767 	u8 opcode = BPF_OP(insn->code);
6768 	u32 alu_state, alu_limit;
6769 	struct bpf_reg_state tmp;
6770 	bool ret;
6771 	int err;
6772 
6773 	if (can_skip_alu_sanitation(env, insn))
6774 		return 0;
6775 
6776 	/* We already marked aux for masking from non-speculative
6777 	 * paths, thus we got here in the first place. We only care
6778 	 * to explore bad access from here.
6779 	 */
6780 	if (vstate->speculative)
6781 		goto do_sim;
6782 
6783 	if (!commit_window) {
6784 		if (!tnum_is_const(off_reg->var_off) &&
6785 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6786 			return REASON_BOUNDS;
6787 
6788 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6789 				     (opcode == BPF_SUB && !off_is_neg);
6790 	}
6791 
6792 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6793 	if (err < 0)
6794 		return err;
6795 
6796 	if (commit_window) {
6797 		/* In commit phase we narrow the masking window based on
6798 		 * the observed pointer move after the simulated operation.
6799 		 */
6800 		alu_state = info->aux.alu_state;
6801 		alu_limit = abs(info->aux.alu_limit - alu_limit);
6802 	} else {
6803 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6804 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6805 		alu_state |= ptr_is_dst_reg ?
6806 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6807 	}
6808 
6809 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6810 	if (err < 0)
6811 		return err;
6812 do_sim:
6813 	/* If we're in commit phase, we're done here given we already
6814 	 * pushed the truncated dst_reg into the speculative verification
6815 	 * stack.
6816 	 *
6817 	 * Also, when register is a known constant, we rewrite register-based
6818 	 * operation to immediate-based, and thus do not need masking (and as
6819 	 * a consequence, do not need to simulate the zero-truncation either).
6820 	 */
6821 	if (commit_window || off_is_imm)
6822 		return 0;
6823 
6824 	/* Simulate and find potential out-of-bounds access under
6825 	 * speculative execution from truncation as a result of
6826 	 * masking when off was not within expected range. If off
6827 	 * sits in dst, then we temporarily need to move ptr there
6828 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6829 	 * for cases where we use K-based arithmetic in one direction
6830 	 * and truncated reg-based in the other in order to explore
6831 	 * bad access.
6832 	 */
6833 	if (!ptr_is_dst_reg) {
6834 		tmp = *dst_reg;
6835 		*dst_reg = *ptr_reg;
6836 	}
6837 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6838 					env->insn_idx);
6839 	if (!ptr_is_dst_reg && ret)
6840 		*dst_reg = tmp;
6841 	return !ret ? REASON_STACK : 0;
6842 }
6843 
6844 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6845 {
6846 	struct bpf_verifier_state *vstate = env->cur_state;
6847 
6848 	/* If we simulate paths under speculation, we don't update the
6849 	 * insn as 'seen' such that when we verify unreachable paths in
6850 	 * the non-speculative domain, sanitize_dead_code() can still
6851 	 * rewrite/sanitize them.
6852 	 */
6853 	if (!vstate->speculative)
6854 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6855 }
6856 
6857 static int sanitize_err(struct bpf_verifier_env *env,
6858 			const struct bpf_insn *insn, int reason,
6859 			const struct bpf_reg_state *off_reg,
6860 			const struct bpf_reg_state *dst_reg)
6861 {
6862 	static const char *err = "pointer arithmetic with it prohibited for !root";
6863 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6864 	u32 dst = insn->dst_reg, src = insn->src_reg;
6865 
6866 	switch (reason) {
6867 	case REASON_BOUNDS:
6868 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6869 			off_reg == dst_reg ? dst : src, err);
6870 		break;
6871 	case REASON_TYPE:
6872 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6873 			off_reg == dst_reg ? src : dst, err);
6874 		break;
6875 	case REASON_PATHS:
6876 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6877 			dst, op, err);
6878 		break;
6879 	case REASON_LIMIT:
6880 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6881 			dst, op, err);
6882 		break;
6883 	case REASON_STACK:
6884 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6885 			dst, err);
6886 		break;
6887 	default:
6888 		verbose(env, "verifier internal error: unknown reason (%d)\n",
6889 			reason);
6890 		break;
6891 	}
6892 
6893 	return -EACCES;
6894 }
6895 
6896 /* check that stack access falls within stack limits and that 'reg' doesn't
6897  * have a variable offset.
6898  *
6899  * Variable offset is prohibited for unprivileged mode for simplicity since it
6900  * requires corresponding support in Spectre masking for stack ALU.  See also
6901  * retrieve_ptr_limit().
6902  *
6903  *
6904  * 'off' includes 'reg->off'.
6905  */
6906 static int check_stack_access_for_ptr_arithmetic(
6907 				struct bpf_verifier_env *env,
6908 				int regno,
6909 				const struct bpf_reg_state *reg,
6910 				int off)
6911 {
6912 	if (!tnum_is_const(reg->var_off)) {
6913 		char tn_buf[48];
6914 
6915 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6916 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6917 			regno, tn_buf, off);
6918 		return -EACCES;
6919 	}
6920 
6921 	if (off >= 0 || off < -MAX_BPF_STACK) {
6922 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6923 			"prohibited for !root; off=%d\n", regno, off);
6924 		return -EACCES;
6925 	}
6926 
6927 	return 0;
6928 }
6929 
6930 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6931 				 const struct bpf_insn *insn,
6932 				 const struct bpf_reg_state *dst_reg)
6933 {
6934 	u32 dst = insn->dst_reg;
6935 
6936 	/* For unprivileged we require that resulting offset must be in bounds
6937 	 * in order to be able to sanitize access later on.
6938 	 */
6939 	if (env->bypass_spec_v1)
6940 		return 0;
6941 
6942 	switch (dst_reg->type) {
6943 	case PTR_TO_STACK:
6944 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6945 					dst_reg->off + dst_reg->var_off.value))
6946 			return -EACCES;
6947 		break;
6948 	case PTR_TO_MAP_VALUE:
6949 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6950 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6951 				"prohibited for !root\n", dst);
6952 			return -EACCES;
6953 		}
6954 		break;
6955 	default:
6956 		break;
6957 	}
6958 
6959 	return 0;
6960 }
6961 
6962 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6963  * Caller should also handle BPF_MOV case separately.
6964  * If we return -EACCES, caller may want to try again treating pointer as a
6965  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6966  */
6967 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6968 				   struct bpf_insn *insn,
6969 				   const struct bpf_reg_state *ptr_reg,
6970 				   const struct bpf_reg_state *off_reg)
6971 {
6972 	struct bpf_verifier_state *vstate = env->cur_state;
6973 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6974 	struct bpf_reg_state *regs = state->regs, *dst_reg;
6975 	bool known = tnum_is_const(off_reg->var_off);
6976 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6977 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6978 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6979 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6980 	struct bpf_sanitize_info info = {};
6981 	u8 opcode = BPF_OP(insn->code);
6982 	u32 dst = insn->dst_reg;
6983 	int ret;
6984 
6985 	dst_reg = &regs[dst];
6986 
6987 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6988 	    smin_val > smax_val || umin_val > umax_val) {
6989 		/* Taint dst register if offset had invalid bounds derived from
6990 		 * e.g. dead branches.
6991 		 */
6992 		__mark_reg_unknown(env, dst_reg);
6993 		return 0;
6994 	}
6995 
6996 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6997 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6998 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6999 			__mark_reg_unknown(env, dst_reg);
7000 			return 0;
7001 		}
7002 
7003 		verbose(env,
7004 			"R%d 32-bit pointer arithmetic prohibited\n",
7005 			dst);
7006 		return -EACCES;
7007 	}
7008 
7009 	switch (ptr_reg->type) {
7010 	case PTR_TO_MAP_VALUE_OR_NULL:
7011 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7012 			dst, reg_type_str[ptr_reg->type]);
7013 		return -EACCES;
7014 	case CONST_PTR_TO_MAP:
7015 		/* smin_val represents the known value */
7016 		if (known && smin_val == 0 && opcode == BPF_ADD)
7017 			break;
7018 		fallthrough;
7019 	case PTR_TO_PACKET_END:
7020 	case PTR_TO_SOCKET:
7021 	case PTR_TO_SOCKET_OR_NULL:
7022 	case PTR_TO_SOCK_COMMON:
7023 	case PTR_TO_SOCK_COMMON_OR_NULL:
7024 	case PTR_TO_TCP_SOCK:
7025 	case PTR_TO_TCP_SOCK_OR_NULL:
7026 	case PTR_TO_XDP_SOCK:
7027 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7028 			dst, reg_type_str[ptr_reg->type]);
7029 		return -EACCES;
7030 	default:
7031 		break;
7032 	}
7033 
7034 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7035 	 * The id may be overwritten later if we create a new variable offset.
7036 	 */
7037 	dst_reg->type = ptr_reg->type;
7038 	dst_reg->id = ptr_reg->id;
7039 
7040 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7041 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7042 		return -EINVAL;
7043 
7044 	/* pointer types do not carry 32-bit bounds at the moment. */
7045 	__mark_reg32_unbounded(dst_reg);
7046 
7047 	if (sanitize_needed(opcode)) {
7048 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7049 				       &info, false);
7050 		if (ret < 0)
7051 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7052 	}
7053 
7054 	switch (opcode) {
7055 	case BPF_ADD:
7056 		/* We can take a fixed offset as long as it doesn't overflow
7057 		 * the s32 'off' field
7058 		 */
7059 		if (known && (ptr_reg->off + smin_val ==
7060 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7061 			/* pointer += K.  Accumulate it into fixed offset */
7062 			dst_reg->smin_value = smin_ptr;
7063 			dst_reg->smax_value = smax_ptr;
7064 			dst_reg->umin_value = umin_ptr;
7065 			dst_reg->umax_value = umax_ptr;
7066 			dst_reg->var_off = ptr_reg->var_off;
7067 			dst_reg->off = ptr_reg->off + smin_val;
7068 			dst_reg->raw = ptr_reg->raw;
7069 			break;
7070 		}
7071 		/* A new variable offset is created.  Note that off_reg->off
7072 		 * == 0, since it's a scalar.
7073 		 * dst_reg gets the pointer type and since some positive
7074 		 * integer value was added to the pointer, give it a new 'id'
7075 		 * if it's a PTR_TO_PACKET.
7076 		 * this creates a new 'base' pointer, off_reg (variable) gets
7077 		 * added into the variable offset, and we copy the fixed offset
7078 		 * from ptr_reg.
7079 		 */
7080 		if (signed_add_overflows(smin_ptr, smin_val) ||
7081 		    signed_add_overflows(smax_ptr, smax_val)) {
7082 			dst_reg->smin_value = S64_MIN;
7083 			dst_reg->smax_value = S64_MAX;
7084 		} else {
7085 			dst_reg->smin_value = smin_ptr + smin_val;
7086 			dst_reg->smax_value = smax_ptr + smax_val;
7087 		}
7088 		if (umin_ptr + umin_val < umin_ptr ||
7089 		    umax_ptr + umax_val < umax_ptr) {
7090 			dst_reg->umin_value = 0;
7091 			dst_reg->umax_value = U64_MAX;
7092 		} else {
7093 			dst_reg->umin_value = umin_ptr + umin_val;
7094 			dst_reg->umax_value = umax_ptr + umax_val;
7095 		}
7096 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7097 		dst_reg->off = ptr_reg->off;
7098 		dst_reg->raw = ptr_reg->raw;
7099 		if (reg_is_pkt_pointer(ptr_reg)) {
7100 			dst_reg->id = ++env->id_gen;
7101 			/* something was added to pkt_ptr, set range to zero */
7102 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7103 		}
7104 		break;
7105 	case BPF_SUB:
7106 		if (dst_reg == off_reg) {
7107 			/* scalar -= pointer.  Creates an unknown scalar */
7108 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7109 				dst);
7110 			return -EACCES;
7111 		}
7112 		/* We don't allow subtraction from FP, because (according to
7113 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7114 		 * be able to deal with it.
7115 		 */
7116 		if (ptr_reg->type == PTR_TO_STACK) {
7117 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7118 				dst);
7119 			return -EACCES;
7120 		}
7121 		if (known && (ptr_reg->off - smin_val ==
7122 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7123 			/* pointer -= K.  Subtract it from fixed offset */
7124 			dst_reg->smin_value = smin_ptr;
7125 			dst_reg->smax_value = smax_ptr;
7126 			dst_reg->umin_value = umin_ptr;
7127 			dst_reg->umax_value = umax_ptr;
7128 			dst_reg->var_off = ptr_reg->var_off;
7129 			dst_reg->id = ptr_reg->id;
7130 			dst_reg->off = ptr_reg->off - smin_val;
7131 			dst_reg->raw = ptr_reg->raw;
7132 			break;
7133 		}
7134 		/* A new variable offset is created.  If the subtrahend is known
7135 		 * nonnegative, then any reg->range we had before is still good.
7136 		 */
7137 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7138 		    signed_sub_overflows(smax_ptr, smin_val)) {
7139 			/* Overflow possible, we know nothing */
7140 			dst_reg->smin_value = S64_MIN;
7141 			dst_reg->smax_value = S64_MAX;
7142 		} else {
7143 			dst_reg->smin_value = smin_ptr - smax_val;
7144 			dst_reg->smax_value = smax_ptr - smin_val;
7145 		}
7146 		if (umin_ptr < umax_val) {
7147 			/* Overflow possible, we know nothing */
7148 			dst_reg->umin_value = 0;
7149 			dst_reg->umax_value = U64_MAX;
7150 		} else {
7151 			/* Cannot overflow (as long as bounds are consistent) */
7152 			dst_reg->umin_value = umin_ptr - umax_val;
7153 			dst_reg->umax_value = umax_ptr - umin_val;
7154 		}
7155 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7156 		dst_reg->off = ptr_reg->off;
7157 		dst_reg->raw = ptr_reg->raw;
7158 		if (reg_is_pkt_pointer(ptr_reg)) {
7159 			dst_reg->id = ++env->id_gen;
7160 			/* something was added to pkt_ptr, set range to zero */
7161 			if (smin_val < 0)
7162 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7163 		}
7164 		break;
7165 	case BPF_AND:
7166 	case BPF_OR:
7167 	case BPF_XOR:
7168 		/* bitwise ops on pointers are troublesome, prohibit. */
7169 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7170 			dst, bpf_alu_string[opcode >> 4]);
7171 		return -EACCES;
7172 	default:
7173 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7174 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7175 			dst, bpf_alu_string[opcode >> 4]);
7176 		return -EACCES;
7177 	}
7178 
7179 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7180 		return -EINVAL;
7181 
7182 	__update_reg_bounds(dst_reg);
7183 	__reg_deduce_bounds(dst_reg);
7184 	__reg_bound_offset(dst_reg);
7185 
7186 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7187 		return -EACCES;
7188 	if (sanitize_needed(opcode)) {
7189 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7190 				       &info, true);
7191 		if (ret < 0)
7192 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7193 	}
7194 
7195 	return 0;
7196 }
7197 
7198 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7199 				 struct bpf_reg_state *src_reg)
7200 {
7201 	s32 smin_val = src_reg->s32_min_value;
7202 	s32 smax_val = src_reg->s32_max_value;
7203 	u32 umin_val = src_reg->u32_min_value;
7204 	u32 umax_val = src_reg->u32_max_value;
7205 
7206 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7207 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7208 		dst_reg->s32_min_value = S32_MIN;
7209 		dst_reg->s32_max_value = S32_MAX;
7210 	} else {
7211 		dst_reg->s32_min_value += smin_val;
7212 		dst_reg->s32_max_value += smax_val;
7213 	}
7214 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7215 	    dst_reg->u32_max_value + umax_val < umax_val) {
7216 		dst_reg->u32_min_value = 0;
7217 		dst_reg->u32_max_value = U32_MAX;
7218 	} else {
7219 		dst_reg->u32_min_value += umin_val;
7220 		dst_reg->u32_max_value += umax_val;
7221 	}
7222 }
7223 
7224 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7225 			       struct bpf_reg_state *src_reg)
7226 {
7227 	s64 smin_val = src_reg->smin_value;
7228 	s64 smax_val = src_reg->smax_value;
7229 	u64 umin_val = src_reg->umin_value;
7230 	u64 umax_val = src_reg->umax_value;
7231 
7232 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7233 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7234 		dst_reg->smin_value = S64_MIN;
7235 		dst_reg->smax_value = S64_MAX;
7236 	} else {
7237 		dst_reg->smin_value += smin_val;
7238 		dst_reg->smax_value += smax_val;
7239 	}
7240 	if (dst_reg->umin_value + umin_val < umin_val ||
7241 	    dst_reg->umax_value + umax_val < umax_val) {
7242 		dst_reg->umin_value = 0;
7243 		dst_reg->umax_value = U64_MAX;
7244 	} else {
7245 		dst_reg->umin_value += umin_val;
7246 		dst_reg->umax_value += umax_val;
7247 	}
7248 }
7249 
7250 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7251 				 struct bpf_reg_state *src_reg)
7252 {
7253 	s32 smin_val = src_reg->s32_min_value;
7254 	s32 smax_val = src_reg->s32_max_value;
7255 	u32 umin_val = src_reg->u32_min_value;
7256 	u32 umax_val = src_reg->u32_max_value;
7257 
7258 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7259 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7260 		/* Overflow possible, we know nothing */
7261 		dst_reg->s32_min_value = S32_MIN;
7262 		dst_reg->s32_max_value = S32_MAX;
7263 	} else {
7264 		dst_reg->s32_min_value -= smax_val;
7265 		dst_reg->s32_max_value -= smin_val;
7266 	}
7267 	if (dst_reg->u32_min_value < umax_val) {
7268 		/* Overflow possible, we know nothing */
7269 		dst_reg->u32_min_value = 0;
7270 		dst_reg->u32_max_value = U32_MAX;
7271 	} else {
7272 		/* Cannot overflow (as long as bounds are consistent) */
7273 		dst_reg->u32_min_value -= umax_val;
7274 		dst_reg->u32_max_value -= umin_val;
7275 	}
7276 }
7277 
7278 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7279 			       struct bpf_reg_state *src_reg)
7280 {
7281 	s64 smin_val = src_reg->smin_value;
7282 	s64 smax_val = src_reg->smax_value;
7283 	u64 umin_val = src_reg->umin_value;
7284 	u64 umax_val = src_reg->umax_value;
7285 
7286 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7287 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7288 		/* Overflow possible, we know nothing */
7289 		dst_reg->smin_value = S64_MIN;
7290 		dst_reg->smax_value = S64_MAX;
7291 	} else {
7292 		dst_reg->smin_value -= smax_val;
7293 		dst_reg->smax_value -= smin_val;
7294 	}
7295 	if (dst_reg->umin_value < umax_val) {
7296 		/* Overflow possible, we know nothing */
7297 		dst_reg->umin_value = 0;
7298 		dst_reg->umax_value = U64_MAX;
7299 	} else {
7300 		/* Cannot overflow (as long as bounds are consistent) */
7301 		dst_reg->umin_value -= umax_val;
7302 		dst_reg->umax_value -= umin_val;
7303 	}
7304 }
7305 
7306 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7307 				 struct bpf_reg_state *src_reg)
7308 {
7309 	s32 smin_val = src_reg->s32_min_value;
7310 	u32 umin_val = src_reg->u32_min_value;
7311 	u32 umax_val = src_reg->u32_max_value;
7312 
7313 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7314 		/* Ain't nobody got time to multiply that sign */
7315 		__mark_reg32_unbounded(dst_reg);
7316 		return;
7317 	}
7318 	/* Both values are positive, so we can work with unsigned and
7319 	 * copy the result to signed (unless it exceeds S32_MAX).
7320 	 */
7321 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7322 		/* Potential overflow, we know nothing */
7323 		__mark_reg32_unbounded(dst_reg);
7324 		return;
7325 	}
7326 	dst_reg->u32_min_value *= umin_val;
7327 	dst_reg->u32_max_value *= umax_val;
7328 	if (dst_reg->u32_max_value > S32_MAX) {
7329 		/* Overflow possible, we know nothing */
7330 		dst_reg->s32_min_value = S32_MIN;
7331 		dst_reg->s32_max_value = S32_MAX;
7332 	} else {
7333 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7334 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7335 	}
7336 }
7337 
7338 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7339 			       struct bpf_reg_state *src_reg)
7340 {
7341 	s64 smin_val = src_reg->smin_value;
7342 	u64 umin_val = src_reg->umin_value;
7343 	u64 umax_val = src_reg->umax_value;
7344 
7345 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7346 		/* Ain't nobody got time to multiply that sign */
7347 		__mark_reg64_unbounded(dst_reg);
7348 		return;
7349 	}
7350 	/* Both values are positive, so we can work with unsigned and
7351 	 * copy the result to signed (unless it exceeds S64_MAX).
7352 	 */
7353 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7354 		/* Potential overflow, we know nothing */
7355 		__mark_reg64_unbounded(dst_reg);
7356 		return;
7357 	}
7358 	dst_reg->umin_value *= umin_val;
7359 	dst_reg->umax_value *= umax_val;
7360 	if (dst_reg->umax_value > S64_MAX) {
7361 		/* Overflow possible, we know nothing */
7362 		dst_reg->smin_value = S64_MIN;
7363 		dst_reg->smax_value = S64_MAX;
7364 	} else {
7365 		dst_reg->smin_value = dst_reg->umin_value;
7366 		dst_reg->smax_value = dst_reg->umax_value;
7367 	}
7368 }
7369 
7370 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7371 				 struct bpf_reg_state *src_reg)
7372 {
7373 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7374 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7375 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7376 	s32 smin_val = src_reg->s32_min_value;
7377 	u32 umax_val = src_reg->u32_max_value;
7378 
7379 	if (src_known && dst_known) {
7380 		__mark_reg32_known(dst_reg, var32_off.value);
7381 		return;
7382 	}
7383 
7384 	/* We get our minimum from the var_off, since that's inherently
7385 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7386 	 */
7387 	dst_reg->u32_min_value = var32_off.value;
7388 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7389 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7390 		/* Lose signed bounds when ANDing negative numbers,
7391 		 * ain't nobody got time for that.
7392 		 */
7393 		dst_reg->s32_min_value = S32_MIN;
7394 		dst_reg->s32_max_value = S32_MAX;
7395 	} else {
7396 		/* ANDing two positives gives a positive, so safe to
7397 		 * cast result into s64.
7398 		 */
7399 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7400 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7401 	}
7402 }
7403 
7404 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7405 			       struct bpf_reg_state *src_reg)
7406 {
7407 	bool src_known = tnum_is_const(src_reg->var_off);
7408 	bool dst_known = tnum_is_const(dst_reg->var_off);
7409 	s64 smin_val = src_reg->smin_value;
7410 	u64 umax_val = src_reg->umax_value;
7411 
7412 	if (src_known && dst_known) {
7413 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7414 		return;
7415 	}
7416 
7417 	/* We get our minimum from the var_off, since that's inherently
7418 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7419 	 */
7420 	dst_reg->umin_value = dst_reg->var_off.value;
7421 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7422 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7423 		/* Lose signed bounds when ANDing negative numbers,
7424 		 * ain't nobody got time for that.
7425 		 */
7426 		dst_reg->smin_value = S64_MIN;
7427 		dst_reg->smax_value = S64_MAX;
7428 	} else {
7429 		/* ANDing two positives gives a positive, so safe to
7430 		 * cast result into s64.
7431 		 */
7432 		dst_reg->smin_value = dst_reg->umin_value;
7433 		dst_reg->smax_value = dst_reg->umax_value;
7434 	}
7435 	/* We may learn something more from the var_off */
7436 	__update_reg_bounds(dst_reg);
7437 }
7438 
7439 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7440 				struct bpf_reg_state *src_reg)
7441 {
7442 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7443 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7444 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7445 	s32 smin_val = src_reg->s32_min_value;
7446 	u32 umin_val = src_reg->u32_min_value;
7447 
7448 	if (src_known && dst_known) {
7449 		__mark_reg32_known(dst_reg, var32_off.value);
7450 		return;
7451 	}
7452 
7453 	/* We get our maximum from the var_off, and our minimum is the
7454 	 * maximum of the operands' minima
7455 	 */
7456 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7457 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7458 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7459 		/* Lose signed bounds when ORing negative numbers,
7460 		 * ain't nobody got time for that.
7461 		 */
7462 		dst_reg->s32_min_value = S32_MIN;
7463 		dst_reg->s32_max_value = S32_MAX;
7464 	} else {
7465 		/* ORing two positives gives a positive, so safe to
7466 		 * cast result into s64.
7467 		 */
7468 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7469 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7470 	}
7471 }
7472 
7473 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7474 			      struct bpf_reg_state *src_reg)
7475 {
7476 	bool src_known = tnum_is_const(src_reg->var_off);
7477 	bool dst_known = tnum_is_const(dst_reg->var_off);
7478 	s64 smin_val = src_reg->smin_value;
7479 	u64 umin_val = src_reg->umin_value;
7480 
7481 	if (src_known && dst_known) {
7482 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7483 		return;
7484 	}
7485 
7486 	/* We get our maximum from the var_off, and our minimum is the
7487 	 * maximum of the operands' minima
7488 	 */
7489 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7490 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7491 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7492 		/* Lose signed bounds when ORing negative numbers,
7493 		 * ain't nobody got time for that.
7494 		 */
7495 		dst_reg->smin_value = S64_MIN;
7496 		dst_reg->smax_value = S64_MAX;
7497 	} else {
7498 		/* ORing two positives gives a positive, so safe to
7499 		 * cast result into s64.
7500 		 */
7501 		dst_reg->smin_value = dst_reg->umin_value;
7502 		dst_reg->smax_value = dst_reg->umax_value;
7503 	}
7504 	/* We may learn something more from the var_off */
7505 	__update_reg_bounds(dst_reg);
7506 }
7507 
7508 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7509 				 struct bpf_reg_state *src_reg)
7510 {
7511 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7512 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7513 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7514 	s32 smin_val = src_reg->s32_min_value;
7515 
7516 	if (src_known && dst_known) {
7517 		__mark_reg32_known(dst_reg, var32_off.value);
7518 		return;
7519 	}
7520 
7521 	/* We get both minimum and maximum from the var32_off. */
7522 	dst_reg->u32_min_value = var32_off.value;
7523 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7524 
7525 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7526 		/* XORing two positive sign numbers gives a positive,
7527 		 * so safe to cast u32 result into s32.
7528 		 */
7529 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7530 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7531 	} else {
7532 		dst_reg->s32_min_value = S32_MIN;
7533 		dst_reg->s32_max_value = S32_MAX;
7534 	}
7535 }
7536 
7537 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7538 			       struct bpf_reg_state *src_reg)
7539 {
7540 	bool src_known = tnum_is_const(src_reg->var_off);
7541 	bool dst_known = tnum_is_const(dst_reg->var_off);
7542 	s64 smin_val = src_reg->smin_value;
7543 
7544 	if (src_known && dst_known) {
7545 		/* dst_reg->var_off.value has been updated earlier */
7546 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7547 		return;
7548 	}
7549 
7550 	/* We get both minimum and maximum from the var_off. */
7551 	dst_reg->umin_value = dst_reg->var_off.value;
7552 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7553 
7554 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7555 		/* XORing two positive sign numbers gives a positive,
7556 		 * so safe to cast u64 result into s64.
7557 		 */
7558 		dst_reg->smin_value = dst_reg->umin_value;
7559 		dst_reg->smax_value = dst_reg->umax_value;
7560 	} else {
7561 		dst_reg->smin_value = S64_MIN;
7562 		dst_reg->smax_value = S64_MAX;
7563 	}
7564 
7565 	__update_reg_bounds(dst_reg);
7566 }
7567 
7568 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7569 				   u64 umin_val, u64 umax_val)
7570 {
7571 	/* We lose all sign bit information (except what we can pick
7572 	 * up from var_off)
7573 	 */
7574 	dst_reg->s32_min_value = S32_MIN;
7575 	dst_reg->s32_max_value = S32_MAX;
7576 	/* If we might shift our top bit out, then we know nothing */
7577 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7578 		dst_reg->u32_min_value = 0;
7579 		dst_reg->u32_max_value = U32_MAX;
7580 	} else {
7581 		dst_reg->u32_min_value <<= umin_val;
7582 		dst_reg->u32_max_value <<= umax_val;
7583 	}
7584 }
7585 
7586 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7587 				 struct bpf_reg_state *src_reg)
7588 {
7589 	u32 umax_val = src_reg->u32_max_value;
7590 	u32 umin_val = src_reg->u32_min_value;
7591 	/* u32 alu operation will zext upper bits */
7592 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7593 
7594 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7595 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7596 	/* Not required but being careful mark reg64 bounds as unknown so
7597 	 * that we are forced to pick them up from tnum and zext later and
7598 	 * if some path skips this step we are still safe.
7599 	 */
7600 	__mark_reg64_unbounded(dst_reg);
7601 	__update_reg32_bounds(dst_reg);
7602 }
7603 
7604 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7605 				   u64 umin_val, u64 umax_val)
7606 {
7607 	/* Special case <<32 because it is a common compiler pattern to sign
7608 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7609 	 * positive we know this shift will also be positive so we can track
7610 	 * bounds correctly. Otherwise we lose all sign bit information except
7611 	 * what we can pick up from var_off. Perhaps we can generalize this
7612 	 * later to shifts of any length.
7613 	 */
7614 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7615 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7616 	else
7617 		dst_reg->smax_value = S64_MAX;
7618 
7619 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7620 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7621 	else
7622 		dst_reg->smin_value = S64_MIN;
7623 
7624 	/* If we might shift our top bit out, then we know nothing */
7625 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7626 		dst_reg->umin_value = 0;
7627 		dst_reg->umax_value = U64_MAX;
7628 	} else {
7629 		dst_reg->umin_value <<= umin_val;
7630 		dst_reg->umax_value <<= umax_val;
7631 	}
7632 }
7633 
7634 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7635 			       struct bpf_reg_state *src_reg)
7636 {
7637 	u64 umax_val = src_reg->umax_value;
7638 	u64 umin_val = src_reg->umin_value;
7639 
7640 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7641 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7642 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7643 
7644 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7645 	/* We may learn something more from the var_off */
7646 	__update_reg_bounds(dst_reg);
7647 }
7648 
7649 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7650 				 struct bpf_reg_state *src_reg)
7651 {
7652 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7653 	u32 umax_val = src_reg->u32_max_value;
7654 	u32 umin_val = src_reg->u32_min_value;
7655 
7656 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7657 	 * be negative, then either:
7658 	 * 1) src_reg might be zero, so the sign bit of the result is
7659 	 *    unknown, so we lose our signed bounds
7660 	 * 2) it's known negative, thus the unsigned bounds capture the
7661 	 *    signed bounds
7662 	 * 3) the signed bounds cross zero, so they tell us nothing
7663 	 *    about the result
7664 	 * If the value in dst_reg is known nonnegative, then again the
7665 	 * unsigned bounds capture the signed bounds.
7666 	 * Thus, in all cases it suffices to blow away our signed bounds
7667 	 * and rely on inferring new ones from the unsigned bounds and
7668 	 * var_off of the result.
7669 	 */
7670 	dst_reg->s32_min_value = S32_MIN;
7671 	dst_reg->s32_max_value = S32_MAX;
7672 
7673 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7674 	dst_reg->u32_min_value >>= umax_val;
7675 	dst_reg->u32_max_value >>= umin_val;
7676 
7677 	__mark_reg64_unbounded(dst_reg);
7678 	__update_reg32_bounds(dst_reg);
7679 }
7680 
7681 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7682 			       struct bpf_reg_state *src_reg)
7683 {
7684 	u64 umax_val = src_reg->umax_value;
7685 	u64 umin_val = src_reg->umin_value;
7686 
7687 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7688 	 * be negative, then either:
7689 	 * 1) src_reg might be zero, so the sign bit of the result is
7690 	 *    unknown, so we lose our signed bounds
7691 	 * 2) it's known negative, thus the unsigned bounds capture the
7692 	 *    signed bounds
7693 	 * 3) the signed bounds cross zero, so they tell us nothing
7694 	 *    about the result
7695 	 * If the value in dst_reg is known nonnegative, then again the
7696 	 * unsigned bounds capture the signed bounds.
7697 	 * Thus, in all cases it suffices to blow away our signed bounds
7698 	 * and rely on inferring new ones from the unsigned bounds and
7699 	 * var_off of the result.
7700 	 */
7701 	dst_reg->smin_value = S64_MIN;
7702 	dst_reg->smax_value = S64_MAX;
7703 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7704 	dst_reg->umin_value >>= umax_val;
7705 	dst_reg->umax_value >>= umin_val;
7706 
7707 	/* Its not easy to operate on alu32 bounds here because it depends
7708 	 * on bits being shifted in. Take easy way out and mark unbounded
7709 	 * so we can recalculate later from tnum.
7710 	 */
7711 	__mark_reg32_unbounded(dst_reg);
7712 	__update_reg_bounds(dst_reg);
7713 }
7714 
7715 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7716 				  struct bpf_reg_state *src_reg)
7717 {
7718 	u64 umin_val = src_reg->u32_min_value;
7719 
7720 	/* Upon reaching here, src_known is true and
7721 	 * umax_val is equal to umin_val.
7722 	 */
7723 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7724 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7725 
7726 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7727 
7728 	/* blow away the dst_reg umin_value/umax_value and rely on
7729 	 * dst_reg var_off to refine the result.
7730 	 */
7731 	dst_reg->u32_min_value = 0;
7732 	dst_reg->u32_max_value = U32_MAX;
7733 
7734 	__mark_reg64_unbounded(dst_reg);
7735 	__update_reg32_bounds(dst_reg);
7736 }
7737 
7738 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7739 				struct bpf_reg_state *src_reg)
7740 {
7741 	u64 umin_val = src_reg->umin_value;
7742 
7743 	/* Upon reaching here, src_known is true and umax_val is equal
7744 	 * to umin_val.
7745 	 */
7746 	dst_reg->smin_value >>= umin_val;
7747 	dst_reg->smax_value >>= umin_val;
7748 
7749 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7750 
7751 	/* blow away the dst_reg umin_value/umax_value and rely on
7752 	 * dst_reg var_off to refine the result.
7753 	 */
7754 	dst_reg->umin_value = 0;
7755 	dst_reg->umax_value = U64_MAX;
7756 
7757 	/* Its not easy to operate on alu32 bounds here because it depends
7758 	 * on bits being shifted in from upper 32-bits. Take easy way out
7759 	 * and mark unbounded so we can recalculate later from tnum.
7760 	 */
7761 	__mark_reg32_unbounded(dst_reg);
7762 	__update_reg_bounds(dst_reg);
7763 }
7764 
7765 /* WARNING: This function does calculations on 64-bit values, but the actual
7766  * execution may occur on 32-bit values. Therefore, things like bitshifts
7767  * need extra checks in the 32-bit case.
7768  */
7769 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7770 				      struct bpf_insn *insn,
7771 				      struct bpf_reg_state *dst_reg,
7772 				      struct bpf_reg_state src_reg)
7773 {
7774 	struct bpf_reg_state *regs = cur_regs(env);
7775 	u8 opcode = BPF_OP(insn->code);
7776 	bool src_known;
7777 	s64 smin_val, smax_val;
7778 	u64 umin_val, umax_val;
7779 	s32 s32_min_val, s32_max_val;
7780 	u32 u32_min_val, u32_max_val;
7781 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7782 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7783 	int ret;
7784 
7785 	smin_val = src_reg.smin_value;
7786 	smax_val = src_reg.smax_value;
7787 	umin_val = src_reg.umin_value;
7788 	umax_val = src_reg.umax_value;
7789 
7790 	s32_min_val = src_reg.s32_min_value;
7791 	s32_max_val = src_reg.s32_max_value;
7792 	u32_min_val = src_reg.u32_min_value;
7793 	u32_max_val = src_reg.u32_max_value;
7794 
7795 	if (alu32) {
7796 		src_known = tnum_subreg_is_const(src_reg.var_off);
7797 		if ((src_known &&
7798 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7799 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7800 			/* Taint dst register if offset had invalid bounds
7801 			 * derived from e.g. dead branches.
7802 			 */
7803 			__mark_reg_unknown(env, dst_reg);
7804 			return 0;
7805 		}
7806 	} else {
7807 		src_known = tnum_is_const(src_reg.var_off);
7808 		if ((src_known &&
7809 		     (smin_val != smax_val || umin_val != umax_val)) ||
7810 		    smin_val > smax_val || umin_val > umax_val) {
7811 			/* Taint dst register if offset had invalid bounds
7812 			 * derived from e.g. dead branches.
7813 			 */
7814 			__mark_reg_unknown(env, dst_reg);
7815 			return 0;
7816 		}
7817 	}
7818 
7819 	if (!src_known &&
7820 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7821 		__mark_reg_unknown(env, dst_reg);
7822 		return 0;
7823 	}
7824 
7825 	if (sanitize_needed(opcode)) {
7826 		ret = sanitize_val_alu(env, insn);
7827 		if (ret < 0)
7828 			return sanitize_err(env, insn, ret, NULL, NULL);
7829 	}
7830 
7831 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7832 	 * There are two classes of instructions: The first class we track both
7833 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
7834 	 * greatest amount of precision when alu operations are mixed with jmp32
7835 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7836 	 * and BPF_OR. This is possible because these ops have fairly easy to
7837 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7838 	 * See alu32 verifier tests for examples. The second class of
7839 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7840 	 * with regards to tracking sign/unsigned bounds because the bits may
7841 	 * cross subreg boundaries in the alu64 case. When this happens we mark
7842 	 * the reg unbounded in the subreg bound space and use the resulting
7843 	 * tnum to calculate an approximation of the sign/unsigned bounds.
7844 	 */
7845 	switch (opcode) {
7846 	case BPF_ADD:
7847 		scalar32_min_max_add(dst_reg, &src_reg);
7848 		scalar_min_max_add(dst_reg, &src_reg);
7849 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7850 		break;
7851 	case BPF_SUB:
7852 		scalar32_min_max_sub(dst_reg, &src_reg);
7853 		scalar_min_max_sub(dst_reg, &src_reg);
7854 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7855 		break;
7856 	case BPF_MUL:
7857 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7858 		scalar32_min_max_mul(dst_reg, &src_reg);
7859 		scalar_min_max_mul(dst_reg, &src_reg);
7860 		break;
7861 	case BPF_AND:
7862 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7863 		scalar32_min_max_and(dst_reg, &src_reg);
7864 		scalar_min_max_and(dst_reg, &src_reg);
7865 		break;
7866 	case BPF_OR:
7867 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7868 		scalar32_min_max_or(dst_reg, &src_reg);
7869 		scalar_min_max_or(dst_reg, &src_reg);
7870 		break;
7871 	case BPF_XOR:
7872 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7873 		scalar32_min_max_xor(dst_reg, &src_reg);
7874 		scalar_min_max_xor(dst_reg, &src_reg);
7875 		break;
7876 	case BPF_LSH:
7877 		if (umax_val >= insn_bitness) {
7878 			/* Shifts greater than 31 or 63 are undefined.
7879 			 * This includes shifts by a negative number.
7880 			 */
7881 			mark_reg_unknown(env, regs, insn->dst_reg);
7882 			break;
7883 		}
7884 		if (alu32)
7885 			scalar32_min_max_lsh(dst_reg, &src_reg);
7886 		else
7887 			scalar_min_max_lsh(dst_reg, &src_reg);
7888 		break;
7889 	case BPF_RSH:
7890 		if (umax_val >= insn_bitness) {
7891 			/* Shifts greater than 31 or 63 are undefined.
7892 			 * This includes shifts by a negative number.
7893 			 */
7894 			mark_reg_unknown(env, regs, insn->dst_reg);
7895 			break;
7896 		}
7897 		if (alu32)
7898 			scalar32_min_max_rsh(dst_reg, &src_reg);
7899 		else
7900 			scalar_min_max_rsh(dst_reg, &src_reg);
7901 		break;
7902 	case BPF_ARSH:
7903 		if (umax_val >= insn_bitness) {
7904 			/* Shifts greater than 31 or 63 are undefined.
7905 			 * This includes shifts by a negative number.
7906 			 */
7907 			mark_reg_unknown(env, regs, insn->dst_reg);
7908 			break;
7909 		}
7910 		if (alu32)
7911 			scalar32_min_max_arsh(dst_reg, &src_reg);
7912 		else
7913 			scalar_min_max_arsh(dst_reg, &src_reg);
7914 		break;
7915 	default:
7916 		mark_reg_unknown(env, regs, insn->dst_reg);
7917 		break;
7918 	}
7919 
7920 	/* ALU32 ops are zero extended into 64bit register */
7921 	if (alu32)
7922 		zext_32_to_64(dst_reg);
7923 
7924 	__update_reg_bounds(dst_reg);
7925 	__reg_deduce_bounds(dst_reg);
7926 	__reg_bound_offset(dst_reg);
7927 	return 0;
7928 }
7929 
7930 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7931  * and var_off.
7932  */
7933 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7934 				   struct bpf_insn *insn)
7935 {
7936 	struct bpf_verifier_state *vstate = env->cur_state;
7937 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7938 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7939 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7940 	u8 opcode = BPF_OP(insn->code);
7941 	int err;
7942 
7943 	dst_reg = &regs[insn->dst_reg];
7944 	src_reg = NULL;
7945 	if (dst_reg->type != SCALAR_VALUE)
7946 		ptr_reg = dst_reg;
7947 	else
7948 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7949 		 * incorrectly propagated into other registers by find_equal_scalars()
7950 		 */
7951 		dst_reg->id = 0;
7952 	if (BPF_SRC(insn->code) == BPF_X) {
7953 		src_reg = &regs[insn->src_reg];
7954 		if (src_reg->type != SCALAR_VALUE) {
7955 			if (dst_reg->type != SCALAR_VALUE) {
7956 				/* Combining two pointers by any ALU op yields
7957 				 * an arbitrary scalar. Disallow all math except
7958 				 * pointer subtraction
7959 				 */
7960 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7961 					mark_reg_unknown(env, regs, insn->dst_reg);
7962 					return 0;
7963 				}
7964 				verbose(env, "R%d pointer %s pointer prohibited\n",
7965 					insn->dst_reg,
7966 					bpf_alu_string[opcode >> 4]);
7967 				return -EACCES;
7968 			} else {
7969 				/* scalar += pointer
7970 				 * This is legal, but we have to reverse our
7971 				 * src/dest handling in computing the range
7972 				 */
7973 				err = mark_chain_precision(env, insn->dst_reg);
7974 				if (err)
7975 					return err;
7976 				return adjust_ptr_min_max_vals(env, insn,
7977 							       src_reg, dst_reg);
7978 			}
7979 		} else if (ptr_reg) {
7980 			/* pointer += scalar */
7981 			err = mark_chain_precision(env, insn->src_reg);
7982 			if (err)
7983 				return err;
7984 			return adjust_ptr_min_max_vals(env, insn,
7985 						       dst_reg, src_reg);
7986 		}
7987 	} else {
7988 		/* Pretend the src is a reg with a known value, since we only
7989 		 * need to be able to read from this state.
7990 		 */
7991 		off_reg.type = SCALAR_VALUE;
7992 		__mark_reg_known(&off_reg, insn->imm);
7993 		src_reg = &off_reg;
7994 		if (ptr_reg) /* pointer += K */
7995 			return adjust_ptr_min_max_vals(env, insn,
7996 						       ptr_reg, src_reg);
7997 	}
7998 
7999 	/* Got here implies adding two SCALAR_VALUEs */
8000 	if (WARN_ON_ONCE(ptr_reg)) {
8001 		print_verifier_state(env, state);
8002 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8003 		return -EINVAL;
8004 	}
8005 	if (WARN_ON(!src_reg)) {
8006 		print_verifier_state(env, state);
8007 		verbose(env, "verifier internal error: no src_reg\n");
8008 		return -EINVAL;
8009 	}
8010 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8011 }
8012 
8013 /* check validity of 32-bit and 64-bit arithmetic operations */
8014 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8015 {
8016 	struct bpf_reg_state *regs = cur_regs(env);
8017 	u8 opcode = BPF_OP(insn->code);
8018 	int err;
8019 
8020 	if (opcode == BPF_END || opcode == BPF_NEG) {
8021 		if (opcode == BPF_NEG) {
8022 			if (BPF_SRC(insn->code) != 0 ||
8023 			    insn->src_reg != BPF_REG_0 ||
8024 			    insn->off != 0 || insn->imm != 0) {
8025 				verbose(env, "BPF_NEG uses reserved fields\n");
8026 				return -EINVAL;
8027 			}
8028 		} else {
8029 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8030 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8031 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8032 				verbose(env, "BPF_END uses reserved fields\n");
8033 				return -EINVAL;
8034 			}
8035 		}
8036 
8037 		/* check src operand */
8038 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8039 		if (err)
8040 			return err;
8041 
8042 		if (is_pointer_value(env, insn->dst_reg)) {
8043 			verbose(env, "R%d pointer arithmetic prohibited\n",
8044 				insn->dst_reg);
8045 			return -EACCES;
8046 		}
8047 
8048 		/* check dest operand */
8049 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8050 		if (err)
8051 			return err;
8052 
8053 	} else if (opcode == BPF_MOV) {
8054 
8055 		if (BPF_SRC(insn->code) == BPF_X) {
8056 			if (insn->imm != 0 || insn->off != 0) {
8057 				verbose(env, "BPF_MOV uses reserved fields\n");
8058 				return -EINVAL;
8059 			}
8060 
8061 			/* check src operand */
8062 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8063 			if (err)
8064 				return err;
8065 		} else {
8066 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8067 				verbose(env, "BPF_MOV uses reserved fields\n");
8068 				return -EINVAL;
8069 			}
8070 		}
8071 
8072 		/* check dest operand, mark as required later */
8073 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8074 		if (err)
8075 			return err;
8076 
8077 		if (BPF_SRC(insn->code) == BPF_X) {
8078 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8079 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8080 
8081 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8082 				/* case: R1 = R2
8083 				 * copy register state to dest reg
8084 				 */
8085 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8086 					/* Assign src and dst registers the same ID
8087 					 * that will be used by find_equal_scalars()
8088 					 * to propagate min/max range.
8089 					 */
8090 					src_reg->id = ++env->id_gen;
8091 				*dst_reg = *src_reg;
8092 				dst_reg->live |= REG_LIVE_WRITTEN;
8093 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8094 			} else {
8095 				/* R1 = (u32) R2 */
8096 				if (is_pointer_value(env, insn->src_reg)) {
8097 					verbose(env,
8098 						"R%d partial copy of pointer\n",
8099 						insn->src_reg);
8100 					return -EACCES;
8101 				} else if (src_reg->type == SCALAR_VALUE) {
8102 					*dst_reg = *src_reg;
8103 					/* Make sure ID is cleared otherwise
8104 					 * dst_reg min/max could be incorrectly
8105 					 * propagated into src_reg by find_equal_scalars()
8106 					 */
8107 					dst_reg->id = 0;
8108 					dst_reg->live |= REG_LIVE_WRITTEN;
8109 					dst_reg->subreg_def = env->insn_idx + 1;
8110 				} else {
8111 					mark_reg_unknown(env, regs,
8112 							 insn->dst_reg);
8113 				}
8114 				zext_32_to_64(dst_reg);
8115 			}
8116 		} else {
8117 			/* case: R = imm
8118 			 * remember the value we stored into this reg
8119 			 */
8120 			/* clear any state __mark_reg_known doesn't set */
8121 			mark_reg_unknown(env, regs, insn->dst_reg);
8122 			regs[insn->dst_reg].type = SCALAR_VALUE;
8123 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8124 				__mark_reg_known(regs + insn->dst_reg,
8125 						 insn->imm);
8126 			} else {
8127 				__mark_reg_known(regs + insn->dst_reg,
8128 						 (u32)insn->imm);
8129 			}
8130 		}
8131 
8132 	} else if (opcode > BPF_END) {
8133 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8134 		return -EINVAL;
8135 
8136 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8137 
8138 		if (BPF_SRC(insn->code) == BPF_X) {
8139 			if (insn->imm != 0 || insn->off != 0) {
8140 				verbose(env, "BPF_ALU uses reserved fields\n");
8141 				return -EINVAL;
8142 			}
8143 			/* check src1 operand */
8144 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8145 			if (err)
8146 				return err;
8147 		} else {
8148 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8149 				verbose(env, "BPF_ALU uses reserved fields\n");
8150 				return -EINVAL;
8151 			}
8152 		}
8153 
8154 		/* check src2 operand */
8155 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8156 		if (err)
8157 			return err;
8158 
8159 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8160 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8161 			verbose(env, "div by zero\n");
8162 			return -EINVAL;
8163 		}
8164 
8165 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8166 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8167 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8168 
8169 			if (insn->imm < 0 || insn->imm >= size) {
8170 				verbose(env, "invalid shift %d\n", insn->imm);
8171 				return -EINVAL;
8172 			}
8173 		}
8174 
8175 		/* check dest operand */
8176 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8177 		if (err)
8178 			return err;
8179 
8180 		return adjust_reg_min_max_vals(env, insn);
8181 	}
8182 
8183 	return 0;
8184 }
8185 
8186 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8187 				     struct bpf_reg_state *dst_reg,
8188 				     enum bpf_reg_type type, int new_range)
8189 {
8190 	struct bpf_reg_state *reg;
8191 	int i;
8192 
8193 	for (i = 0; i < MAX_BPF_REG; i++) {
8194 		reg = &state->regs[i];
8195 		if (reg->type == type && reg->id == dst_reg->id)
8196 			/* keep the maximum range already checked */
8197 			reg->range = max(reg->range, new_range);
8198 	}
8199 
8200 	bpf_for_each_spilled_reg(i, state, reg) {
8201 		if (!reg)
8202 			continue;
8203 		if (reg->type == type && reg->id == dst_reg->id)
8204 			reg->range = max(reg->range, new_range);
8205 	}
8206 }
8207 
8208 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8209 				   struct bpf_reg_state *dst_reg,
8210 				   enum bpf_reg_type type,
8211 				   bool range_right_open)
8212 {
8213 	int new_range, i;
8214 
8215 	if (dst_reg->off < 0 ||
8216 	    (dst_reg->off == 0 && range_right_open))
8217 		/* This doesn't give us any range */
8218 		return;
8219 
8220 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8221 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8222 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8223 		 * than pkt_end, but that's because it's also less than pkt.
8224 		 */
8225 		return;
8226 
8227 	new_range = dst_reg->off;
8228 	if (range_right_open)
8229 		new_range--;
8230 
8231 	/* Examples for register markings:
8232 	 *
8233 	 * pkt_data in dst register:
8234 	 *
8235 	 *   r2 = r3;
8236 	 *   r2 += 8;
8237 	 *   if (r2 > pkt_end) goto <handle exception>
8238 	 *   <access okay>
8239 	 *
8240 	 *   r2 = r3;
8241 	 *   r2 += 8;
8242 	 *   if (r2 < pkt_end) goto <access okay>
8243 	 *   <handle exception>
8244 	 *
8245 	 *   Where:
8246 	 *     r2 == dst_reg, pkt_end == src_reg
8247 	 *     r2=pkt(id=n,off=8,r=0)
8248 	 *     r3=pkt(id=n,off=0,r=0)
8249 	 *
8250 	 * pkt_data in src register:
8251 	 *
8252 	 *   r2 = r3;
8253 	 *   r2 += 8;
8254 	 *   if (pkt_end >= r2) goto <access okay>
8255 	 *   <handle exception>
8256 	 *
8257 	 *   r2 = r3;
8258 	 *   r2 += 8;
8259 	 *   if (pkt_end <= r2) goto <handle exception>
8260 	 *   <access okay>
8261 	 *
8262 	 *   Where:
8263 	 *     pkt_end == dst_reg, r2 == src_reg
8264 	 *     r2=pkt(id=n,off=8,r=0)
8265 	 *     r3=pkt(id=n,off=0,r=0)
8266 	 *
8267 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8268 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8269 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8270 	 * the check.
8271 	 */
8272 
8273 	/* If our ids match, then we must have the same max_value.  And we
8274 	 * don't care about the other reg's fixed offset, since if it's too big
8275 	 * the range won't allow anything.
8276 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8277 	 */
8278 	for (i = 0; i <= vstate->curframe; i++)
8279 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8280 					 new_range);
8281 }
8282 
8283 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8284 {
8285 	struct tnum subreg = tnum_subreg(reg->var_off);
8286 	s32 sval = (s32)val;
8287 
8288 	switch (opcode) {
8289 	case BPF_JEQ:
8290 		if (tnum_is_const(subreg))
8291 			return !!tnum_equals_const(subreg, val);
8292 		break;
8293 	case BPF_JNE:
8294 		if (tnum_is_const(subreg))
8295 			return !tnum_equals_const(subreg, val);
8296 		break;
8297 	case BPF_JSET:
8298 		if ((~subreg.mask & subreg.value) & val)
8299 			return 1;
8300 		if (!((subreg.mask | subreg.value) & val))
8301 			return 0;
8302 		break;
8303 	case BPF_JGT:
8304 		if (reg->u32_min_value > val)
8305 			return 1;
8306 		else if (reg->u32_max_value <= val)
8307 			return 0;
8308 		break;
8309 	case BPF_JSGT:
8310 		if (reg->s32_min_value > sval)
8311 			return 1;
8312 		else if (reg->s32_max_value <= sval)
8313 			return 0;
8314 		break;
8315 	case BPF_JLT:
8316 		if (reg->u32_max_value < val)
8317 			return 1;
8318 		else if (reg->u32_min_value >= val)
8319 			return 0;
8320 		break;
8321 	case BPF_JSLT:
8322 		if (reg->s32_max_value < sval)
8323 			return 1;
8324 		else if (reg->s32_min_value >= sval)
8325 			return 0;
8326 		break;
8327 	case BPF_JGE:
8328 		if (reg->u32_min_value >= val)
8329 			return 1;
8330 		else if (reg->u32_max_value < val)
8331 			return 0;
8332 		break;
8333 	case BPF_JSGE:
8334 		if (reg->s32_min_value >= sval)
8335 			return 1;
8336 		else if (reg->s32_max_value < sval)
8337 			return 0;
8338 		break;
8339 	case BPF_JLE:
8340 		if (reg->u32_max_value <= val)
8341 			return 1;
8342 		else if (reg->u32_min_value > val)
8343 			return 0;
8344 		break;
8345 	case BPF_JSLE:
8346 		if (reg->s32_max_value <= sval)
8347 			return 1;
8348 		else if (reg->s32_min_value > sval)
8349 			return 0;
8350 		break;
8351 	}
8352 
8353 	return -1;
8354 }
8355 
8356 
8357 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8358 {
8359 	s64 sval = (s64)val;
8360 
8361 	switch (opcode) {
8362 	case BPF_JEQ:
8363 		if (tnum_is_const(reg->var_off))
8364 			return !!tnum_equals_const(reg->var_off, val);
8365 		break;
8366 	case BPF_JNE:
8367 		if (tnum_is_const(reg->var_off))
8368 			return !tnum_equals_const(reg->var_off, val);
8369 		break;
8370 	case BPF_JSET:
8371 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8372 			return 1;
8373 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8374 			return 0;
8375 		break;
8376 	case BPF_JGT:
8377 		if (reg->umin_value > val)
8378 			return 1;
8379 		else if (reg->umax_value <= val)
8380 			return 0;
8381 		break;
8382 	case BPF_JSGT:
8383 		if (reg->smin_value > sval)
8384 			return 1;
8385 		else if (reg->smax_value <= sval)
8386 			return 0;
8387 		break;
8388 	case BPF_JLT:
8389 		if (reg->umax_value < val)
8390 			return 1;
8391 		else if (reg->umin_value >= val)
8392 			return 0;
8393 		break;
8394 	case BPF_JSLT:
8395 		if (reg->smax_value < sval)
8396 			return 1;
8397 		else if (reg->smin_value >= sval)
8398 			return 0;
8399 		break;
8400 	case BPF_JGE:
8401 		if (reg->umin_value >= val)
8402 			return 1;
8403 		else if (reg->umax_value < val)
8404 			return 0;
8405 		break;
8406 	case BPF_JSGE:
8407 		if (reg->smin_value >= sval)
8408 			return 1;
8409 		else if (reg->smax_value < sval)
8410 			return 0;
8411 		break;
8412 	case BPF_JLE:
8413 		if (reg->umax_value <= val)
8414 			return 1;
8415 		else if (reg->umin_value > val)
8416 			return 0;
8417 		break;
8418 	case BPF_JSLE:
8419 		if (reg->smax_value <= sval)
8420 			return 1;
8421 		else if (reg->smin_value > sval)
8422 			return 0;
8423 		break;
8424 	}
8425 
8426 	return -1;
8427 }
8428 
8429 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8430  * and return:
8431  *  1 - branch will be taken and "goto target" will be executed
8432  *  0 - branch will not be taken and fall-through to next insn
8433  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8434  *      range [0,10]
8435  */
8436 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8437 			   bool is_jmp32)
8438 {
8439 	if (__is_pointer_value(false, reg)) {
8440 		if (!reg_type_not_null(reg->type))
8441 			return -1;
8442 
8443 		/* If pointer is valid tests against zero will fail so we can
8444 		 * use this to direct branch taken.
8445 		 */
8446 		if (val != 0)
8447 			return -1;
8448 
8449 		switch (opcode) {
8450 		case BPF_JEQ:
8451 			return 0;
8452 		case BPF_JNE:
8453 			return 1;
8454 		default:
8455 			return -1;
8456 		}
8457 	}
8458 
8459 	if (is_jmp32)
8460 		return is_branch32_taken(reg, val, opcode);
8461 	return is_branch64_taken(reg, val, opcode);
8462 }
8463 
8464 static int flip_opcode(u32 opcode)
8465 {
8466 	/* How can we transform "a <op> b" into "b <op> a"? */
8467 	static const u8 opcode_flip[16] = {
8468 		/* these stay the same */
8469 		[BPF_JEQ  >> 4] = BPF_JEQ,
8470 		[BPF_JNE  >> 4] = BPF_JNE,
8471 		[BPF_JSET >> 4] = BPF_JSET,
8472 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8473 		[BPF_JGE  >> 4] = BPF_JLE,
8474 		[BPF_JGT  >> 4] = BPF_JLT,
8475 		[BPF_JLE  >> 4] = BPF_JGE,
8476 		[BPF_JLT  >> 4] = BPF_JGT,
8477 		[BPF_JSGE >> 4] = BPF_JSLE,
8478 		[BPF_JSGT >> 4] = BPF_JSLT,
8479 		[BPF_JSLE >> 4] = BPF_JSGE,
8480 		[BPF_JSLT >> 4] = BPF_JSGT
8481 	};
8482 	return opcode_flip[opcode >> 4];
8483 }
8484 
8485 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8486 				   struct bpf_reg_state *src_reg,
8487 				   u8 opcode)
8488 {
8489 	struct bpf_reg_state *pkt;
8490 
8491 	if (src_reg->type == PTR_TO_PACKET_END) {
8492 		pkt = dst_reg;
8493 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8494 		pkt = src_reg;
8495 		opcode = flip_opcode(opcode);
8496 	} else {
8497 		return -1;
8498 	}
8499 
8500 	if (pkt->range >= 0)
8501 		return -1;
8502 
8503 	switch (opcode) {
8504 	case BPF_JLE:
8505 		/* pkt <= pkt_end */
8506 		fallthrough;
8507 	case BPF_JGT:
8508 		/* pkt > pkt_end */
8509 		if (pkt->range == BEYOND_PKT_END)
8510 			/* pkt has at last one extra byte beyond pkt_end */
8511 			return opcode == BPF_JGT;
8512 		break;
8513 	case BPF_JLT:
8514 		/* pkt < pkt_end */
8515 		fallthrough;
8516 	case BPF_JGE:
8517 		/* pkt >= pkt_end */
8518 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8519 			return opcode == BPF_JGE;
8520 		break;
8521 	}
8522 	return -1;
8523 }
8524 
8525 /* Adjusts the register min/max values in the case that the dst_reg is the
8526  * variable register that we are working on, and src_reg is a constant or we're
8527  * simply doing a BPF_K check.
8528  * In JEQ/JNE cases we also adjust the var_off values.
8529  */
8530 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8531 			    struct bpf_reg_state *false_reg,
8532 			    u64 val, u32 val32,
8533 			    u8 opcode, bool is_jmp32)
8534 {
8535 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8536 	struct tnum false_64off = false_reg->var_off;
8537 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8538 	struct tnum true_64off = true_reg->var_off;
8539 	s64 sval = (s64)val;
8540 	s32 sval32 = (s32)val32;
8541 
8542 	/* If the dst_reg is a pointer, we can't learn anything about its
8543 	 * variable offset from the compare (unless src_reg were a pointer into
8544 	 * the same object, but we don't bother with that.
8545 	 * Since false_reg and true_reg have the same type by construction, we
8546 	 * only need to check one of them for pointerness.
8547 	 */
8548 	if (__is_pointer_value(false, false_reg))
8549 		return;
8550 
8551 	switch (opcode) {
8552 	case BPF_JEQ:
8553 	case BPF_JNE:
8554 	{
8555 		struct bpf_reg_state *reg =
8556 			opcode == BPF_JEQ ? true_reg : false_reg;
8557 
8558 		/* JEQ/JNE comparison doesn't change the register equivalence.
8559 		 * r1 = r2;
8560 		 * if (r1 == 42) goto label;
8561 		 * ...
8562 		 * label: // here both r1 and r2 are known to be 42.
8563 		 *
8564 		 * Hence when marking register as known preserve it's ID.
8565 		 */
8566 		if (is_jmp32)
8567 			__mark_reg32_known(reg, val32);
8568 		else
8569 			___mark_reg_known(reg, val);
8570 		break;
8571 	}
8572 	case BPF_JSET:
8573 		if (is_jmp32) {
8574 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8575 			if (is_power_of_2(val32))
8576 				true_32off = tnum_or(true_32off,
8577 						     tnum_const(val32));
8578 		} else {
8579 			false_64off = tnum_and(false_64off, tnum_const(~val));
8580 			if (is_power_of_2(val))
8581 				true_64off = tnum_or(true_64off,
8582 						     tnum_const(val));
8583 		}
8584 		break;
8585 	case BPF_JGE:
8586 	case BPF_JGT:
8587 	{
8588 		if (is_jmp32) {
8589 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8590 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8591 
8592 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8593 						       false_umax);
8594 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8595 						      true_umin);
8596 		} else {
8597 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8598 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8599 
8600 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8601 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8602 		}
8603 		break;
8604 	}
8605 	case BPF_JSGE:
8606 	case BPF_JSGT:
8607 	{
8608 		if (is_jmp32) {
8609 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8610 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8611 
8612 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8613 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8614 		} else {
8615 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8616 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8617 
8618 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8619 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8620 		}
8621 		break;
8622 	}
8623 	case BPF_JLE:
8624 	case BPF_JLT:
8625 	{
8626 		if (is_jmp32) {
8627 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8628 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8629 
8630 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8631 						       false_umin);
8632 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8633 						      true_umax);
8634 		} else {
8635 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8636 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8637 
8638 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8639 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8640 		}
8641 		break;
8642 	}
8643 	case BPF_JSLE:
8644 	case BPF_JSLT:
8645 	{
8646 		if (is_jmp32) {
8647 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8648 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8649 
8650 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8651 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8652 		} else {
8653 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8654 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8655 
8656 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8657 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8658 		}
8659 		break;
8660 	}
8661 	default:
8662 		return;
8663 	}
8664 
8665 	if (is_jmp32) {
8666 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8667 					     tnum_subreg(false_32off));
8668 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8669 					    tnum_subreg(true_32off));
8670 		__reg_combine_32_into_64(false_reg);
8671 		__reg_combine_32_into_64(true_reg);
8672 	} else {
8673 		false_reg->var_off = false_64off;
8674 		true_reg->var_off = true_64off;
8675 		__reg_combine_64_into_32(false_reg);
8676 		__reg_combine_64_into_32(true_reg);
8677 	}
8678 }
8679 
8680 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8681  * the variable reg.
8682  */
8683 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8684 				struct bpf_reg_state *false_reg,
8685 				u64 val, u32 val32,
8686 				u8 opcode, bool is_jmp32)
8687 {
8688 	opcode = flip_opcode(opcode);
8689 	/* This uses zero as "not present in table"; luckily the zero opcode,
8690 	 * BPF_JA, can't get here.
8691 	 */
8692 	if (opcode)
8693 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8694 }
8695 
8696 /* Regs are known to be equal, so intersect their min/max/var_off */
8697 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8698 				  struct bpf_reg_state *dst_reg)
8699 {
8700 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8701 							dst_reg->umin_value);
8702 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8703 							dst_reg->umax_value);
8704 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8705 							dst_reg->smin_value);
8706 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8707 							dst_reg->smax_value);
8708 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8709 							     dst_reg->var_off);
8710 	/* We might have learned new bounds from the var_off. */
8711 	__update_reg_bounds(src_reg);
8712 	__update_reg_bounds(dst_reg);
8713 	/* We might have learned something about the sign bit. */
8714 	__reg_deduce_bounds(src_reg);
8715 	__reg_deduce_bounds(dst_reg);
8716 	/* We might have learned some bits from the bounds. */
8717 	__reg_bound_offset(src_reg);
8718 	__reg_bound_offset(dst_reg);
8719 	/* Intersecting with the old var_off might have improved our bounds
8720 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8721 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
8722 	 */
8723 	__update_reg_bounds(src_reg);
8724 	__update_reg_bounds(dst_reg);
8725 }
8726 
8727 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8728 				struct bpf_reg_state *true_dst,
8729 				struct bpf_reg_state *false_src,
8730 				struct bpf_reg_state *false_dst,
8731 				u8 opcode)
8732 {
8733 	switch (opcode) {
8734 	case BPF_JEQ:
8735 		__reg_combine_min_max(true_src, true_dst);
8736 		break;
8737 	case BPF_JNE:
8738 		__reg_combine_min_max(false_src, false_dst);
8739 		break;
8740 	}
8741 }
8742 
8743 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8744 				 struct bpf_reg_state *reg, u32 id,
8745 				 bool is_null)
8746 {
8747 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
8748 	    !WARN_ON_ONCE(!reg->id)) {
8749 		/* Old offset (both fixed and variable parts) should
8750 		 * have been known-zero, because we don't allow pointer
8751 		 * arithmetic on pointers that might be NULL.
8752 		 */
8753 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8754 				 !tnum_equals_const(reg->var_off, 0) ||
8755 				 reg->off)) {
8756 			__mark_reg_known_zero(reg);
8757 			reg->off = 0;
8758 		}
8759 		if (is_null) {
8760 			reg->type = SCALAR_VALUE;
8761 			/* We don't need id and ref_obj_id from this point
8762 			 * onwards anymore, thus we should better reset it,
8763 			 * so that state pruning has chances to take effect.
8764 			 */
8765 			reg->id = 0;
8766 			reg->ref_obj_id = 0;
8767 
8768 			return;
8769 		}
8770 
8771 		mark_ptr_not_null_reg(reg);
8772 
8773 		if (!reg_may_point_to_spin_lock(reg)) {
8774 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8775 			 * in release_reg_references().
8776 			 *
8777 			 * reg->id is still used by spin_lock ptr. Other
8778 			 * than spin_lock ptr type, reg->id can be reset.
8779 			 */
8780 			reg->id = 0;
8781 		}
8782 	}
8783 }
8784 
8785 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8786 				    bool is_null)
8787 {
8788 	struct bpf_reg_state *reg;
8789 	int i;
8790 
8791 	for (i = 0; i < MAX_BPF_REG; i++)
8792 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8793 
8794 	bpf_for_each_spilled_reg(i, state, reg) {
8795 		if (!reg)
8796 			continue;
8797 		mark_ptr_or_null_reg(state, reg, id, is_null);
8798 	}
8799 }
8800 
8801 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8802  * be folded together at some point.
8803  */
8804 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8805 				  bool is_null)
8806 {
8807 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8808 	struct bpf_reg_state *regs = state->regs;
8809 	u32 ref_obj_id = regs[regno].ref_obj_id;
8810 	u32 id = regs[regno].id;
8811 	int i;
8812 
8813 	if (ref_obj_id && ref_obj_id == id && is_null)
8814 		/* regs[regno] is in the " == NULL" branch.
8815 		 * No one could have freed the reference state before
8816 		 * doing the NULL check.
8817 		 */
8818 		WARN_ON_ONCE(release_reference_state(state, id));
8819 
8820 	for (i = 0; i <= vstate->curframe; i++)
8821 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8822 }
8823 
8824 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8825 				   struct bpf_reg_state *dst_reg,
8826 				   struct bpf_reg_state *src_reg,
8827 				   struct bpf_verifier_state *this_branch,
8828 				   struct bpf_verifier_state *other_branch)
8829 {
8830 	if (BPF_SRC(insn->code) != BPF_X)
8831 		return false;
8832 
8833 	/* Pointers are always 64-bit. */
8834 	if (BPF_CLASS(insn->code) == BPF_JMP32)
8835 		return false;
8836 
8837 	switch (BPF_OP(insn->code)) {
8838 	case BPF_JGT:
8839 		if ((dst_reg->type == PTR_TO_PACKET &&
8840 		     src_reg->type == PTR_TO_PACKET_END) ||
8841 		    (dst_reg->type == PTR_TO_PACKET_META &&
8842 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8843 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8844 			find_good_pkt_pointers(this_branch, dst_reg,
8845 					       dst_reg->type, false);
8846 			mark_pkt_end(other_branch, insn->dst_reg, true);
8847 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8848 			    src_reg->type == PTR_TO_PACKET) ||
8849 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8850 			    src_reg->type == PTR_TO_PACKET_META)) {
8851 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
8852 			find_good_pkt_pointers(other_branch, src_reg,
8853 					       src_reg->type, true);
8854 			mark_pkt_end(this_branch, insn->src_reg, false);
8855 		} else {
8856 			return false;
8857 		}
8858 		break;
8859 	case BPF_JLT:
8860 		if ((dst_reg->type == PTR_TO_PACKET &&
8861 		     src_reg->type == PTR_TO_PACKET_END) ||
8862 		    (dst_reg->type == PTR_TO_PACKET_META &&
8863 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8864 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8865 			find_good_pkt_pointers(other_branch, dst_reg,
8866 					       dst_reg->type, true);
8867 			mark_pkt_end(this_branch, insn->dst_reg, false);
8868 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8869 			    src_reg->type == PTR_TO_PACKET) ||
8870 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8871 			    src_reg->type == PTR_TO_PACKET_META)) {
8872 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
8873 			find_good_pkt_pointers(this_branch, src_reg,
8874 					       src_reg->type, false);
8875 			mark_pkt_end(other_branch, insn->src_reg, true);
8876 		} else {
8877 			return false;
8878 		}
8879 		break;
8880 	case BPF_JGE:
8881 		if ((dst_reg->type == PTR_TO_PACKET &&
8882 		     src_reg->type == PTR_TO_PACKET_END) ||
8883 		    (dst_reg->type == PTR_TO_PACKET_META &&
8884 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8885 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8886 			find_good_pkt_pointers(this_branch, dst_reg,
8887 					       dst_reg->type, true);
8888 			mark_pkt_end(other_branch, insn->dst_reg, false);
8889 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8890 			    src_reg->type == PTR_TO_PACKET) ||
8891 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8892 			    src_reg->type == PTR_TO_PACKET_META)) {
8893 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8894 			find_good_pkt_pointers(other_branch, src_reg,
8895 					       src_reg->type, false);
8896 			mark_pkt_end(this_branch, insn->src_reg, true);
8897 		} else {
8898 			return false;
8899 		}
8900 		break;
8901 	case BPF_JLE:
8902 		if ((dst_reg->type == PTR_TO_PACKET &&
8903 		     src_reg->type == PTR_TO_PACKET_END) ||
8904 		    (dst_reg->type == PTR_TO_PACKET_META &&
8905 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8906 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8907 			find_good_pkt_pointers(other_branch, dst_reg,
8908 					       dst_reg->type, false);
8909 			mark_pkt_end(this_branch, insn->dst_reg, true);
8910 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8911 			    src_reg->type == PTR_TO_PACKET) ||
8912 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8913 			    src_reg->type == PTR_TO_PACKET_META)) {
8914 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8915 			find_good_pkt_pointers(this_branch, src_reg,
8916 					       src_reg->type, true);
8917 			mark_pkt_end(other_branch, insn->src_reg, false);
8918 		} else {
8919 			return false;
8920 		}
8921 		break;
8922 	default:
8923 		return false;
8924 	}
8925 
8926 	return true;
8927 }
8928 
8929 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8930 			       struct bpf_reg_state *known_reg)
8931 {
8932 	struct bpf_func_state *state;
8933 	struct bpf_reg_state *reg;
8934 	int i, j;
8935 
8936 	for (i = 0; i <= vstate->curframe; i++) {
8937 		state = vstate->frame[i];
8938 		for (j = 0; j < MAX_BPF_REG; j++) {
8939 			reg = &state->regs[j];
8940 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8941 				*reg = *known_reg;
8942 		}
8943 
8944 		bpf_for_each_spilled_reg(j, state, reg) {
8945 			if (!reg)
8946 				continue;
8947 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8948 				*reg = *known_reg;
8949 		}
8950 	}
8951 }
8952 
8953 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8954 			     struct bpf_insn *insn, int *insn_idx)
8955 {
8956 	struct bpf_verifier_state *this_branch = env->cur_state;
8957 	struct bpf_verifier_state *other_branch;
8958 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8959 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8960 	u8 opcode = BPF_OP(insn->code);
8961 	bool is_jmp32;
8962 	int pred = -1;
8963 	int err;
8964 
8965 	/* Only conditional jumps are expected to reach here. */
8966 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8967 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8968 		return -EINVAL;
8969 	}
8970 
8971 	if (BPF_SRC(insn->code) == BPF_X) {
8972 		if (insn->imm != 0) {
8973 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8974 			return -EINVAL;
8975 		}
8976 
8977 		/* check src1 operand */
8978 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8979 		if (err)
8980 			return err;
8981 
8982 		if (is_pointer_value(env, insn->src_reg)) {
8983 			verbose(env, "R%d pointer comparison prohibited\n",
8984 				insn->src_reg);
8985 			return -EACCES;
8986 		}
8987 		src_reg = &regs[insn->src_reg];
8988 	} else {
8989 		if (insn->src_reg != BPF_REG_0) {
8990 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8991 			return -EINVAL;
8992 		}
8993 	}
8994 
8995 	/* check src2 operand */
8996 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8997 	if (err)
8998 		return err;
8999 
9000 	dst_reg = &regs[insn->dst_reg];
9001 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9002 
9003 	if (BPF_SRC(insn->code) == BPF_K) {
9004 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9005 	} else if (src_reg->type == SCALAR_VALUE &&
9006 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9007 		pred = is_branch_taken(dst_reg,
9008 				       tnum_subreg(src_reg->var_off).value,
9009 				       opcode,
9010 				       is_jmp32);
9011 	} else if (src_reg->type == SCALAR_VALUE &&
9012 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9013 		pred = is_branch_taken(dst_reg,
9014 				       src_reg->var_off.value,
9015 				       opcode,
9016 				       is_jmp32);
9017 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9018 		   reg_is_pkt_pointer_any(src_reg) &&
9019 		   !is_jmp32) {
9020 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9021 	}
9022 
9023 	if (pred >= 0) {
9024 		/* If we get here with a dst_reg pointer type it is because
9025 		 * above is_branch_taken() special cased the 0 comparison.
9026 		 */
9027 		if (!__is_pointer_value(false, dst_reg))
9028 			err = mark_chain_precision(env, insn->dst_reg);
9029 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9030 		    !__is_pointer_value(false, src_reg))
9031 			err = mark_chain_precision(env, insn->src_reg);
9032 		if (err)
9033 			return err;
9034 	}
9035 
9036 	if (pred == 1) {
9037 		/* Only follow the goto, ignore fall-through. If needed, push
9038 		 * the fall-through branch for simulation under speculative
9039 		 * execution.
9040 		 */
9041 		if (!env->bypass_spec_v1 &&
9042 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9043 					       *insn_idx))
9044 			return -EFAULT;
9045 		*insn_idx += insn->off;
9046 		return 0;
9047 	} else if (pred == 0) {
9048 		/* Only follow the fall-through branch, since that's where the
9049 		 * program will go. If needed, push the goto branch for
9050 		 * simulation under speculative execution.
9051 		 */
9052 		if (!env->bypass_spec_v1 &&
9053 		    !sanitize_speculative_path(env, insn,
9054 					       *insn_idx + insn->off + 1,
9055 					       *insn_idx))
9056 			return -EFAULT;
9057 		return 0;
9058 	}
9059 
9060 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9061 				  false);
9062 	if (!other_branch)
9063 		return -EFAULT;
9064 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9065 
9066 	/* detect if we are comparing against a constant value so we can adjust
9067 	 * our min/max values for our dst register.
9068 	 * this is only legit if both are scalars (or pointers to the same
9069 	 * object, I suppose, but we don't support that right now), because
9070 	 * otherwise the different base pointers mean the offsets aren't
9071 	 * comparable.
9072 	 */
9073 	if (BPF_SRC(insn->code) == BPF_X) {
9074 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9075 
9076 		if (dst_reg->type == SCALAR_VALUE &&
9077 		    src_reg->type == SCALAR_VALUE) {
9078 			if (tnum_is_const(src_reg->var_off) ||
9079 			    (is_jmp32 &&
9080 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9081 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9082 						dst_reg,
9083 						src_reg->var_off.value,
9084 						tnum_subreg(src_reg->var_off).value,
9085 						opcode, is_jmp32);
9086 			else if (tnum_is_const(dst_reg->var_off) ||
9087 				 (is_jmp32 &&
9088 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9089 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9090 						    src_reg,
9091 						    dst_reg->var_off.value,
9092 						    tnum_subreg(dst_reg->var_off).value,
9093 						    opcode, is_jmp32);
9094 			else if (!is_jmp32 &&
9095 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9096 				/* Comparing for equality, we can combine knowledge */
9097 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9098 						    &other_branch_regs[insn->dst_reg],
9099 						    src_reg, dst_reg, opcode);
9100 			if (src_reg->id &&
9101 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9102 				find_equal_scalars(this_branch, src_reg);
9103 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9104 			}
9105 
9106 		}
9107 	} else if (dst_reg->type == SCALAR_VALUE) {
9108 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9109 					dst_reg, insn->imm, (u32)insn->imm,
9110 					opcode, is_jmp32);
9111 	}
9112 
9113 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9114 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9115 		find_equal_scalars(this_branch, dst_reg);
9116 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9117 	}
9118 
9119 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9120 	 * NOTE: these optimizations below are related with pointer comparison
9121 	 *       which will never be JMP32.
9122 	 */
9123 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9124 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9125 	    reg_type_may_be_null(dst_reg->type)) {
9126 		/* Mark all identical registers in each branch as either
9127 		 * safe or unknown depending R == 0 or R != 0 conditional.
9128 		 */
9129 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9130 				      opcode == BPF_JNE);
9131 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9132 				      opcode == BPF_JEQ);
9133 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9134 					   this_branch, other_branch) &&
9135 		   is_pointer_value(env, insn->dst_reg)) {
9136 		verbose(env, "R%d pointer comparison prohibited\n",
9137 			insn->dst_reg);
9138 		return -EACCES;
9139 	}
9140 	if (env->log.level & BPF_LOG_LEVEL)
9141 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9142 	return 0;
9143 }
9144 
9145 /* verify BPF_LD_IMM64 instruction */
9146 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9147 {
9148 	struct bpf_insn_aux_data *aux = cur_aux(env);
9149 	struct bpf_reg_state *regs = cur_regs(env);
9150 	struct bpf_reg_state *dst_reg;
9151 	struct bpf_map *map;
9152 	int err;
9153 
9154 	if (BPF_SIZE(insn->code) != BPF_DW) {
9155 		verbose(env, "invalid BPF_LD_IMM insn\n");
9156 		return -EINVAL;
9157 	}
9158 	if (insn->off != 0) {
9159 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9160 		return -EINVAL;
9161 	}
9162 
9163 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9164 	if (err)
9165 		return err;
9166 
9167 	dst_reg = &regs[insn->dst_reg];
9168 	if (insn->src_reg == 0) {
9169 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9170 
9171 		dst_reg->type = SCALAR_VALUE;
9172 		__mark_reg_known(&regs[insn->dst_reg], imm);
9173 		return 0;
9174 	}
9175 
9176 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9177 		mark_reg_known_zero(env, regs, insn->dst_reg);
9178 
9179 		dst_reg->type = aux->btf_var.reg_type;
9180 		switch (dst_reg->type) {
9181 		case PTR_TO_MEM:
9182 			dst_reg->mem_size = aux->btf_var.mem_size;
9183 			break;
9184 		case PTR_TO_BTF_ID:
9185 		case PTR_TO_PERCPU_BTF_ID:
9186 			dst_reg->btf = aux->btf_var.btf;
9187 			dst_reg->btf_id = aux->btf_var.btf_id;
9188 			break;
9189 		default:
9190 			verbose(env, "bpf verifier is misconfigured\n");
9191 			return -EFAULT;
9192 		}
9193 		return 0;
9194 	}
9195 
9196 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9197 		struct bpf_prog_aux *aux = env->prog->aux;
9198 		u32 subprogno = insn[1].imm;
9199 
9200 		if (!aux->func_info) {
9201 			verbose(env, "missing btf func_info\n");
9202 			return -EINVAL;
9203 		}
9204 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9205 			verbose(env, "callback function not static\n");
9206 			return -EINVAL;
9207 		}
9208 
9209 		dst_reg->type = PTR_TO_FUNC;
9210 		dst_reg->subprogno = subprogno;
9211 		return 0;
9212 	}
9213 
9214 	map = env->used_maps[aux->map_index];
9215 	mark_reg_known_zero(env, regs, insn->dst_reg);
9216 	dst_reg->map_ptr = map;
9217 
9218 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9219 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9220 		dst_reg->type = PTR_TO_MAP_VALUE;
9221 		dst_reg->off = aux->map_off;
9222 		if (map_value_has_spin_lock(map))
9223 			dst_reg->id = ++env->id_gen;
9224 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9225 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9226 		dst_reg->type = CONST_PTR_TO_MAP;
9227 	} else {
9228 		verbose(env, "bpf verifier is misconfigured\n");
9229 		return -EINVAL;
9230 	}
9231 
9232 	return 0;
9233 }
9234 
9235 static bool may_access_skb(enum bpf_prog_type type)
9236 {
9237 	switch (type) {
9238 	case BPF_PROG_TYPE_SOCKET_FILTER:
9239 	case BPF_PROG_TYPE_SCHED_CLS:
9240 	case BPF_PROG_TYPE_SCHED_ACT:
9241 		return true;
9242 	default:
9243 		return false;
9244 	}
9245 }
9246 
9247 /* verify safety of LD_ABS|LD_IND instructions:
9248  * - they can only appear in the programs where ctx == skb
9249  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9250  *   preserve R6-R9, and store return value into R0
9251  *
9252  * Implicit input:
9253  *   ctx == skb == R6 == CTX
9254  *
9255  * Explicit input:
9256  *   SRC == any register
9257  *   IMM == 32-bit immediate
9258  *
9259  * Output:
9260  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9261  */
9262 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9263 {
9264 	struct bpf_reg_state *regs = cur_regs(env);
9265 	static const int ctx_reg = BPF_REG_6;
9266 	u8 mode = BPF_MODE(insn->code);
9267 	int i, err;
9268 
9269 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9270 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9271 		return -EINVAL;
9272 	}
9273 
9274 	if (!env->ops->gen_ld_abs) {
9275 		verbose(env, "bpf verifier is misconfigured\n");
9276 		return -EINVAL;
9277 	}
9278 
9279 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9280 	    BPF_SIZE(insn->code) == BPF_DW ||
9281 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9282 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9283 		return -EINVAL;
9284 	}
9285 
9286 	/* check whether implicit source operand (register R6) is readable */
9287 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9288 	if (err)
9289 		return err;
9290 
9291 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9292 	 * gen_ld_abs() may terminate the program at runtime, leading to
9293 	 * reference leak.
9294 	 */
9295 	err = check_reference_leak(env);
9296 	if (err) {
9297 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9298 		return err;
9299 	}
9300 
9301 	if (env->cur_state->active_spin_lock) {
9302 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9303 		return -EINVAL;
9304 	}
9305 
9306 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9307 		verbose(env,
9308 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9309 		return -EINVAL;
9310 	}
9311 
9312 	if (mode == BPF_IND) {
9313 		/* check explicit source operand */
9314 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9315 		if (err)
9316 			return err;
9317 	}
9318 
9319 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9320 	if (err < 0)
9321 		return err;
9322 
9323 	/* reset caller saved regs to unreadable */
9324 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9325 		mark_reg_not_init(env, regs, caller_saved[i]);
9326 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9327 	}
9328 
9329 	/* mark destination R0 register as readable, since it contains
9330 	 * the value fetched from the packet.
9331 	 * Already marked as written above.
9332 	 */
9333 	mark_reg_unknown(env, regs, BPF_REG_0);
9334 	/* ld_abs load up to 32-bit skb data. */
9335 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9336 	return 0;
9337 }
9338 
9339 static int check_return_code(struct bpf_verifier_env *env)
9340 {
9341 	struct tnum enforce_attach_type_range = tnum_unknown;
9342 	const struct bpf_prog *prog = env->prog;
9343 	struct bpf_reg_state *reg;
9344 	struct tnum range = tnum_range(0, 1);
9345 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9346 	int err;
9347 	struct bpf_func_state *frame = env->cur_state->frame[0];
9348 	const bool is_subprog = frame->subprogno;
9349 
9350 	/* LSM and struct_ops func-ptr's return type could be "void" */
9351 	if (!is_subprog &&
9352 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9353 	     prog_type == BPF_PROG_TYPE_LSM) &&
9354 	    !prog->aux->attach_func_proto->type)
9355 		return 0;
9356 
9357 	/* eBPF calling convention is such that R0 is used
9358 	 * to return the value from eBPF program.
9359 	 * Make sure that it's readable at this time
9360 	 * of bpf_exit, which means that program wrote
9361 	 * something into it earlier
9362 	 */
9363 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9364 	if (err)
9365 		return err;
9366 
9367 	if (is_pointer_value(env, BPF_REG_0)) {
9368 		verbose(env, "R0 leaks addr as return value\n");
9369 		return -EACCES;
9370 	}
9371 
9372 	reg = cur_regs(env) + BPF_REG_0;
9373 
9374 	if (frame->in_async_callback_fn) {
9375 		/* enforce return zero from async callbacks like timer */
9376 		if (reg->type != SCALAR_VALUE) {
9377 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9378 				reg_type_str[reg->type]);
9379 			return -EINVAL;
9380 		}
9381 
9382 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9383 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9384 			return -EINVAL;
9385 		}
9386 		return 0;
9387 	}
9388 
9389 	if (is_subprog) {
9390 		if (reg->type != SCALAR_VALUE) {
9391 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9392 				reg_type_str[reg->type]);
9393 			return -EINVAL;
9394 		}
9395 		return 0;
9396 	}
9397 
9398 	switch (prog_type) {
9399 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9400 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9401 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9402 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9403 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9404 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9405 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9406 			range = tnum_range(1, 1);
9407 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9408 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9409 			range = tnum_range(0, 3);
9410 		break;
9411 	case BPF_PROG_TYPE_CGROUP_SKB:
9412 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9413 			range = tnum_range(0, 3);
9414 			enforce_attach_type_range = tnum_range(2, 3);
9415 		}
9416 		break;
9417 	case BPF_PROG_TYPE_CGROUP_SOCK:
9418 	case BPF_PROG_TYPE_SOCK_OPS:
9419 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9420 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9421 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9422 		break;
9423 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9424 		if (!env->prog->aux->attach_btf_id)
9425 			return 0;
9426 		range = tnum_const(0);
9427 		break;
9428 	case BPF_PROG_TYPE_TRACING:
9429 		switch (env->prog->expected_attach_type) {
9430 		case BPF_TRACE_FENTRY:
9431 		case BPF_TRACE_FEXIT:
9432 			range = tnum_const(0);
9433 			break;
9434 		case BPF_TRACE_RAW_TP:
9435 		case BPF_MODIFY_RETURN:
9436 			return 0;
9437 		case BPF_TRACE_ITER:
9438 			break;
9439 		default:
9440 			return -ENOTSUPP;
9441 		}
9442 		break;
9443 	case BPF_PROG_TYPE_SK_LOOKUP:
9444 		range = tnum_range(SK_DROP, SK_PASS);
9445 		break;
9446 	case BPF_PROG_TYPE_EXT:
9447 		/* freplace program can return anything as its return value
9448 		 * depends on the to-be-replaced kernel func or bpf program.
9449 		 */
9450 	default:
9451 		return 0;
9452 	}
9453 
9454 	if (reg->type != SCALAR_VALUE) {
9455 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9456 			reg_type_str[reg->type]);
9457 		return -EINVAL;
9458 	}
9459 
9460 	if (!tnum_in(range, reg->var_off)) {
9461 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9462 		return -EINVAL;
9463 	}
9464 
9465 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9466 	    tnum_in(enforce_attach_type_range, reg->var_off))
9467 		env->prog->enforce_expected_attach_type = 1;
9468 	return 0;
9469 }
9470 
9471 /* non-recursive DFS pseudo code
9472  * 1  procedure DFS-iterative(G,v):
9473  * 2      label v as discovered
9474  * 3      let S be a stack
9475  * 4      S.push(v)
9476  * 5      while S is not empty
9477  * 6            t <- S.pop()
9478  * 7            if t is what we're looking for:
9479  * 8                return t
9480  * 9            for all edges e in G.adjacentEdges(t) do
9481  * 10               if edge e is already labelled
9482  * 11                   continue with the next edge
9483  * 12               w <- G.adjacentVertex(t,e)
9484  * 13               if vertex w is not discovered and not explored
9485  * 14                   label e as tree-edge
9486  * 15                   label w as discovered
9487  * 16                   S.push(w)
9488  * 17                   continue at 5
9489  * 18               else if vertex w is discovered
9490  * 19                   label e as back-edge
9491  * 20               else
9492  * 21                   // vertex w is explored
9493  * 22                   label e as forward- or cross-edge
9494  * 23           label t as explored
9495  * 24           S.pop()
9496  *
9497  * convention:
9498  * 0x10 - discovered
9499  * 0x11 - discovered and fall-through edge labelled
9500  * 0x12 - discovered and fall-through and branch edges labelled
9501  * 0x20 - explored
9502  */
9503 
9504 enum {
9505 	DISCOVERED = 0x10,
9506 	EXPLORED = 0x20,
9507 	FALLTHROUGH = 1,
9508 	BRANCH = 2,
9509 };
9510 
9511 static u32 state_htab_size(struct bpf_verifier_env *env)
9512 {
9513 	return env->prog->len;
9514 }
9515 
9516 static struct bpf_verifier_state_list **explored_state(
9517 					struct bpf_verifier_env *env,
9518 					int idx)
9519 {
9520 	struct bpf_verifier_state *cur = env->cur_state;
9521 	struct bpf_func_state *state = cur->frame[cur->curframe];
9522 
9523 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9524 }
9525 
9526 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9527 {
9528 	env->insn_aux_data[idx].prune_point = true;
9529 }
9530 
9531 enum {
9532 	DONE_EXPLORING = 0,
9533 	KEEP_EXPLORING = 1,
9534 };
9535 
9536 /* t, w, e - match pseudo-code above:
9537  * t - index of current instruction
9538  * w - next instruction
9539  * e - edge
9540  */
9541 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9542 		     bool loop_ok)
9543 {
9544 	int *insn_stack = env->cfg.insn_stack;
9545 	int *insn_state = env->cfg.insn_state;
9546 
9547 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9548 		return DONE_EXPLORING;
9549 
9550 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9551 		return DONE_EXPLORING;
9552 
9553 	if (w < 0 || w >= env->prog->len) {
9554 		verbose_linfo(env, t, "%d: ", t);
9555 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9556 		return -EINVAL;
9557 	}
9558 
9559 	if (e == BRANCH)
9560 		/* mark branch target for state pruning */
9561 		init_explored_state(env, w);
9562 
9563 	if (insn_state[w] == 0) {
9564 		/* tree-edge */
9565 		insn_state[t] = DISCOVERED | e;
9566 		insn_state[w] = DISCOVERED;
9567 		if (env->cfg.cur_stack >= env->prog->len)
9568 			return -E2BIG;
9569 		insn_stack[env->cfg.cur_stack++] = w;
9570 		return KEEP_EXPLORING;
9571 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9572 		if (loop_ok && env->bpf_capable)
9573 			return DONE_EXPLORING;
9574 		verbose_linfo(env, t, "%d: ", t);
9575 		verbose_linfo(env, w, "%d: ", w);
9576 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9577 		return -EINVAL;
9578 	} else if (insn_state[w] == EXPLORED) {
9579 		/* forward- or cross-edge */
9580 		insn_state[t] = DISCOVERED | e;
9581 	} else {
9582 		verbose(env, "insn state internal bug\n");
9583 		return -EFAULT;
9584 	}
9585 	return DONE_EXPLORING;
9586 }
9587 
9588 static int visit_func_call_insn(int t, int insn_cnt,
9589 				struct bpf_insn *insns,
9590 				struct bpf_verifier_env *env,
9591 				bool visit_callee)
9592 {
9593 	int ret;
9594 
9595 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9596 	if (ret)
9597 		return ret;
9598 
9599 	if (t + 1 < insn_cnt)
9600 		init_explored_state(env, t + 1);
9601 	if (visit_callee) {
9602 		init_explored_state(env, t);
9603 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9604 				/* It's ok to allow recursion from CFG point of
9605 				 * view. __check_func_call() will do the actual
9606 				 * check.
9607 				 */
9608 				bpf_pseudo_func(insns + t));
9609 	}
9610 	return ret;
9611 }
9612 
9613 /* Visits the instruction at index t and returns one of the following:
9614  *  < 0 - an error occurred
9615  *  DONE_EXPLORING - the instruction was fully explored
9616  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9617  */
9618 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9619 {
9620 	struct bpf_insn *insns = env->prog->insnsi;
9621 	int ret;
9622 
9623 	if (bpf_pseudo_func(insns + t))
9624 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9625 
9626 	/* All non-branch instructions have a single fall-through edge. */
9627 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9628 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9629 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9630 
9631 	switch (BPF_OP(insns[t].code)) {
9632 	case BPF_EXIT:
9633 		return DONE_EXPLORING;
9634 
9635 	case BPF_CALL:
9636 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9637 			/* Mark this call insn to trigger is_state_visited() check
9638 			 * before call itself is processed by __check_func_call().
9639 			 * Otherwise new async state will be pushed for further
9640 			 * exploration.
9641 			 */
9642 			init_explored_state(env, t);
9643 		return visit_func_call_insn(t, insn_cnt, insns, env,
9644 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9645 
9646 	case BPF_JA:
9647 		if (BPF_SRC(insns[t].code) != BPF_K)
9648 			return -EINVAL;
9649 
9650 		/* unconditional jump with single edge */
9651 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9652 				true);
9653 		if (ret)
9654 			return ret;
9655 
9656 		/* unconditional jmp is not a good pruning point,
9657 		 * but it's marked, since backtracking needs
9658 		 * to record jmp history in is_state_visited().
9659 		 */
9660 		init_explored_state(env, t + insns[t].off + 1);
9661 		/* tell verifier to check for equivalent states
9662 		 * after every call and jump
9663 		 */
9664 		if (t + 1 < insn_cnt)
9665 			init_explored_state(env, t + 1);
9666 
9667 		return ret;
9668 
9669 	default:
9670 		/* conditional jump with two edges */
9671 		init_explored_state(env, t);
9672 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9673 		if (ret)
9674 			return ret;
9675 
9676 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9677 	}
9678 }
9679 
9680 /* non-recursive depth-first-search to detect loops in BPF program
9681  * loop == back-edge in directed graph
9682  */
9683 static int check_cfg(struct bpf_verifier_env *env)
9684 {
9685 	int insn_cnt = env->prog->len;
9686 	int *insn_stack, *insn_state;
9687 	int ret = 0;
9688 	int i;
9689 
9690 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9691 	if (!insn_state)
9692 		return -ENOMEM;
9693 
9694 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9695 	if (!insn_stack) {
9696 		kvfree(insn_state);
9697 		return -ENOMEM;
9698 	}
9699 
9700 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9701 	insn_stack[0] = 0; /* 0 is the first instruction */
9702 	env->cfg.cur_stack = 1;
9703 
9704 	while (env->cfg.cur_stack > 0) {
9705 		int t = insn_stack[env->cfg.cur_stack - 1];
9706 
9707 		ret = visit_insn(t, insn_cnt, env);
9708 		switch (ret) {
9709 		case DONE_EXPLORING:
9710 			insn_state[t] = EXPLORED;
9711 			env->cfg.cur_stack--;
9712 			break;
9713 		case KEEP_EXPLORING:
9714 			break;
9715 		default:
9716 			if (ret > 0) {
9717 				verbose(env, "visit_insn internal bug\n");
9718 				ret = -EFAULT;
9719 			}
9720 			goto err_free;
9721 		}
9722 	}
9723 
9724 	if (env->cfg.cur_stack < 0) {
9725 		verbose(env, "pop stack internal bug\n");
9726 		ret = -EFAULT;
9727 		goto err_free;
9728 	}
9729 
9730 	for (i = 0; i < insn_cnt; i++) {
9731 		if (insn_state[i] != EXPLORED) {
9732 			verbose(env, "unreachable insn %d\n", i);
9733 			ret = -EINVAL;
9734 			goto err_free;
9735 		}
9736 	}
9737 	ret = 0; /* cfg looks good */
9738 
9739 err_free:
9740 	kvfree(insn_state);
9741 	kvfree(insn_stack);
9742 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9743 	return ret;
9744 }
9745 
9746 static int check_abnormal_return(struct bpf_verifier_env *env)
9747 {
9748 	int i;
9749 
9750 	for (i = 1; i < env->subprog_cnt; i++) {
9751 		if (env->subprog_info[i].has_ld_abs) {
9752 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9753 			return -EINVAL;
9754 		}
9755 		if (env->subprog_info[i].has_tail_call) {
9756 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9757 			return -EINVAL;
9758 		}
9759 	}
9760 	return 0;
9761 }
9762 
9763 /* The minimum supported BTF func info size */
9764 #define MIN_BPF_FUNCINFO_SIZE	8
9765 #define MAX_FUNCINFO_REC_SIZE	252
9766 
9767 static int check_btf_func(struct bpf_verifier_env *env,
9768 			  const union bpf_attr *attr,
9769 			  bpfptr_t uattr)
9770 {
9771 	const struct btf_type *type, *func_proto, *ret_type;
9772 	u32 i, nfuncs, urec_size, min_size;
9773 	u32 krec_size = sizeof(struct bpf_func_info);
9774 	struct bpf_func_info *krecord;
9775 	struct bpf_func_info_aux *info_aux = NULL;
9776 	struct bpf_prog *prog;
9777 	const struct btf *btf;
9778 	bpfptr_t urecord;
9779 	u32 prev_offset = 0;
9780 	bool scalar_return;
9781 	int ret = -ENOMEM;
9782 
9783 	nfuncs = attr->func_info_cnt;
9784 	if (!nfuncs) {
9785 		if (check_abnormal_return(env))
9786 			return -EINVAL;
9787 		return 0;
9788 	}
9789 
9790 	if (nfuncs != env->subprog_cnt) {
9791 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9792 		return -EINVAL;
9793 	}
9794 
9795 	urec_size = attr->func_info_rec_size;
9796 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9797 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
9798 	    urec_size % sizeof(u32)) {
9799 		verbose(env, "invalid func info rec size %u\n", urec_size);
9800 		return -EINVAL;
9801 	}
9802 
9803 	prog = env->prog;
9804 	btf = prog->aux->btf;
9805 
9806 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9807 	min_size = min_t(u32, krec_size, urec_size);
9808 
9809 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9810 	if (!krecord)
9811 		return -ENOMEM;
9812 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9813 	if (!info_aux)
9814 		goto err_free;
9815 
9816 	for (i = 0; i < nfuncs; i++) {
9817 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9818 		if (ret) {
9819 			if (ret == -E2BIG) {
9820 				verbose(env, "nonzero tailing record in func info");
9821 				/* set the size kernel expects so loader can zero
9822 				 * out the rest of the record.
9823 				 */
9824 				if (copy_to_bpfptr_offset(uattr,
9825 							  offsetof(union bpf_attr, func_info_rec_size),
9826 							  &min_size, sizeof(min_size)))
9827 					ret = -EFAULT;
9828 			}
9829 			goto err_free;
9830 		}
9831 
9832 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
9833 			ret = -EFAULT;
9834 			goto err_free;
9835 		}
9836 
9837 		/* check insn_off */
9838 		ret = -EINVAL;
9839 		if (i == 0) {
9840 			if (krecord[i].insn_off) {
9841 				verbose(env,
9842 					"nonzero insn_off %u for the first func info record",
9843 					krecord[i].insn_off);
9844 				goto err_free;
9845 			}
9846 		} else if (krecord[i].insn_off <= prev_offset) {
9847 			verbose(env,
9848 				"same or smaller insn offset (%u) than previous func info record (%u)",
9849 				krecord[i].insn_off, prev_offset);
9850 			goto err_free;
9851 		}
9852 
9853 		if (env->subprog_info[i].start != krecord[i].insn_off) {
9854 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9855 			goto err_free;
9856 		}
9857 
9858 		/* check type_id */
9859 		type = btf_type_by_id(btf, krecord[i].type_id);
9860 		if (!type || !btf_type_is_func(type)) {
9861 			verbose(env, "invalid type id %d in func info",
9862 				krecord[i].type_id);
9863 			goto err_free;
9864 		}
9865 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9866 
9867 		func_proto = btf_type_by_id(btf, type->type);
9868 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9869 			/* btf_func_check() already verified it during BTF load */
9870 			goto err_free;
9871 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9872 		scalar_return =
9873 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9874 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9875 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9876 			goto err_free;
9877 		}
9878 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9879 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9880 			goto err_free;
9881 		}
9882 
9883 		prev_offset = krecord[i].insn_off;
9884 		bpfptr_add(&urecord, urec_size);
9885 	}
9886 
9887 	prog->aux->func_info = krecord;
9888 	prog->aux->func_info_cnt = nfuncs;
9889 	prog->aux->func_info_aux = info_aux;
9890 	return 0;
9891 
9892 err_free:
9893 	kvfree(krecord);
9894 	kfree(info_aux);
9895 	return ret;
9896 }
9897 
9898 static void adjust_btf_func(struct bpf_verifier_env *env)
9899 {
9900 	struct bpf_prog_aux *aux = env->prog->aux;
9901 	int i;
9902 
9903 	if (!aux->func_info)
9904 		return;
9905 
9906 	for (i = 0; i < env->subprog_cnt; i++)
9907 		aux->func_info[i].insn_off = env->subprog_info[i].start;
9908 }
9909 
9910 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
9911 		sizeof(((struct bpf_line_info *)(0))->line_col))
9912 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
9913 
9914 static int check_btf_line(struct bpf_verifier_env *env,
9915 			  const union bpf_attr *attr,
9916 			  bpfptr_t uattr)
9917 {
9918 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9919 	struct bpf_subprog_info *sub;
9920 	struct bpf_line_info *linfo;
9921 	struct bpf_prog *prog;
9922 	const struct btf *btf;
9923 	bpfptr_t ulinfo;
9924 	int err;
9925 
9926 	nr_linfo = attr->line_info_cnt;
9927 	if (!nr_linfo)
9928 		return 0;
9929 
9930 	rec_size = attr->line_info_rec_size;
9931 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9932 	    rec_size > MAX_LINEINFO_REC_SIZE ||
9933 	    rec_size & (sizeof(u32) - 1))
9934 		return -EINVAL;
9935 
9936 	/* Need to zero it in case the userspace may
9937 	 * pass in a smaller bpf_line_info object.
9938 	 */
9939 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9940 			 GFP_KERNEL | __GFP_NOWARN);
9941 	if (!linfo)
9942 		return -ENOMEM;
9943 
9944 	prog = env->prog;
9945 	btf = prog->aux->btf;
9946 
9947 	s = 0;
9948 	sub = env->subprog_info;
9949 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
9950 	expected_size = sizeof(struct bpf_line_info);
9951 	ncopy = min_t(u32, expected_size, rec_size);
9952 	for (i = 0; i < nr_linfo; i++) {
9953 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9954 		if (err) {
9955 			if (err == -E2BIG) {
9956 				verbose(env, "nonzero tailing record in line_info");
9957 				if (copy_to_bpfptr_offset(uattr,
9958 							  offsetof(union bpf_attr, line_info_rec_size),
9959 							  &expected_size, sizeof(expected_size)))
9960 					err = -EFAULT;
9961 			}
9962 			goto err_free;
9963 		}
9964 
9965 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
9966 			err = -EFAULT;
9967 			goto err_free;
9968 		}
9969 
9970 		/*
9971 		 * Check insn_off to ensure
9972 		 * 1) strictly increasing AND
9973 		 * 2) bounded by prog->len
9974 		 *
9975 		 * The linfo[0].insn_off == 0 check logically falls into
9976 		 * the later "missing bpf_line_info for func..." case
9977 		 * because the first linfo[0].insn_off must be the
9978 		 * first sub also and the first sub must have
9979 		 * subprog_info[0].start == 0.
9980 		 */
9981 		if ((i && linfo[i].insn_off <= prev_offset) ||
9982 		    linfo[i].insn_off >= prog->len) {
9983 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9984 				i, linfo[i].insn_off, prev_offset,
9985 				prog->len);
9986 			err = -EINVAL;
9987 			goto err_free;
9988 		}
9989 
9990 		if (!prog->insnsi[linfo[i].insn_off].code) {
9991 			verbose(env,
9992 				"Invalid insn code at line_info[%u].insn_off\n",
9993 				i);
9994 			err = -EINVAL;
9995 			goto err_free;
9996 		}
9997 
9998 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9999 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10000 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10001 			err = -EINVAL;
10002 			goto err_free;
10003 		}
10004 
10005 		if (s != env->subprog_cnt) {
10006 			if (linfo[i].insn_off == sub[s].start) {
10007 				sub[s].linfo_idx = i;
10008 				s++;
10009 			} else if (sub[s].start < linfo[i].insn_off) {
10010 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10011 				err = -EINVAL;
10012 				goto err_free;
10013 			}
10014 		}
10015 
10016 		prev_offset = linfo[i].insn_off;
10017 		bpfptr_add(&ulinfo, rec_size);
10018 	}
10019 
10020 	if (s != env->subprog_cnt) {
10021 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10022 			env->subprog_cnt - s, s);
10023 		err = -EINVAL;
10024 		goto err_free;
10025 	}
10026 
10027 	prog->aux->linfo = linfo;
10028 	prog->aux->nr_linfo = nr_linfo;
10029 
10030 	return 0;
10031 
10032 err_free:
10033 	kvfree(linfo);
10034 	return err;
10035 }
10036 
10037 static int check_btf_info(struct bpf_verifier_env *env,
10038 			  const union bpf_attr *attr,
10039 			  bpfptr_t uattr)
10040 {
10041 	struct btf *btf;
10042 	int err;
10043 
10044 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10045 		if (check_abnormal_return(env))
10046 			return -EINVAL;
10047 		return 0;
10048 	}
10049 
10050 	btf = btf_get_by_fd(attr->prog_btf_fd);
10051 	if (IS_ERR(btf))
10052 		return PTR_ERR(btf);
10053 	if (btf_is_kernel(btf)) {
10054 		btf_put(btf);
10055 		return -EACCES;
10056 	}
10057 	env->prog->aux->btf = btf;
10058 
10059 	err = check_btf_func(env, attr, uattr);
10060 	if (err)
10061 		return err;
10062 
10063 	err = check_btf_line(env, attr, uattr);
10064 	if (err)
10065 		return err;
10066 
10067 	return 0;
10068 }
10069 
10070 /* check %cur's range satisfies %old's */
10071 static bool range_within(struct bpf_reg_state *old,
10072 			 struct bpf_reg_state *cur)
10073 {
10074 	return old->umin_value <= cur->umin_value &&
10075 	       old->umax_value >= cur->umax_value &&
10076 	       old->smin_value <= cur->smin_value &&
10077 	       old->smax_value >= cur->smax_value &&
10078 	       old->u32_min_value <= cur->u32_min_value &&
10079 	       old->u32_max_value >= cur->u32_max_value &&
10080 	       old->s32_min_value <= cur->s32_min_value &&
10081 	       old->s32_max_value >= cur->s32_max_value;
10082 }
10083 
10084 /* If in the old state two registers had the same id, then they need to have
10085  * the same id in the new state as well.  But that id could be different from
10086  * the old state, so we need to track the mapping from old to new ids.
10087  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10088  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10089  * regs with a different old id could still have new id 9, we don't care about
10090  * that.
10091  * So we look through our idmap to see if this old id has been seen before.  If
10092  * so, we require the new id to match; otherwise, we add the id pair to the map.
10093  */
10094 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10095 {
10096 	unsigned int i;
10097 
10098 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10099 		if (!idmap[i].old) {
10100 			/* Reached an empty slot; haven't seen this id before */
10101 			idmap[i].old = old_id;
10102 			idmap[i].cur = cur_id;
10103 			return true;
10104 		}
10105 		if (idmap[i].old == old_id)
10106 			return idmap[i].cur == cur_id;
10107 	}
10108 	/* We ran out of idmap slots, which should be impossible */
10109 	WARN_ON_ONCE(1);
10110 	return false;
10111 }
10112 
10113 static void clean_func_state(struct bpf_verifier_env *env,
10114 			     struct bpf_func_state *st)
10115 {
10116 	enum bpf_reg_liveness live;
10117 	int i, j;
10118 
10119 	for (i = 0; i < BPF_REG_FP; i++) {
10120 		live = st->regs[i].live;
10121 		/* liveness must not touch this register anymore */
10122 		st->regs[i].live |= REG_LIVE_DONE;
10123 		if (!(live & REG_LIVE_READ))
10124 			/* since the register is unused, clear its state
10125 			 * to make further comparison simpler
10126 			 */
10127 			__mark_reg_not_init(env, &st->regs[i]);
10128 	}
10129 
10130 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10131 		live = st->stack[i].spilled_ptr.live;
10132 		/* liveness must not touch this stack slot anymore */
10133 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10134 		if (!(live & REG_LIVE_READ)) {
10135 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10136 			for (j = 0; j < BPF_REG_SIZE; j++)
10137 				st->stack[i].slot_type[j] = STACK_INVALID;
10138 		}
10139 	}
10140 }
10141 
10142 static void clean_verifier_state(struct bpf_verifier_env *env,
10143 				 struct bpf_verifier_state *st)
10144 {
10145 	int i;
10146 
10147 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10148 		/* all regs in this state in all frames were already marked */
10149 		return;
10150 
10151 	for (i = 0; i <= st->curframe; i++)
10152 		clean_func_state(env, st->frame[i]);
10153 }
10154 
10155 /* the parentage chains form a tree.
10156  * the verifier states are added to state lists at given insn and
10157  * pushed into state stack for future exploration.
10158  * when the verifier reaches bpf_exit insn some of the verifer states
10159  * stored in the state lists have their final liveness state already,
10160  * but a lot of states will get revised from liveness point of view when
10161  * the verifier explores other branches.
10162  * Example:
10163  * 1: r0 = 1
10164  * 2: if r1 == 100 goto pc+1
10165  * 3: r0 = 2
10166  * 4: exit
10167  * when the verifier reaches exit insn the register r0 in the state list of
10168  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10169  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10170  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10171  *
10172  * Since the verifier pushes the branch states as it sees them while exploring
10173  * the program the condition of walking the branch instruction for the second
10174  * time means that all states below this branch were already explored and
10175  * their final liveness marks are already propagated.
10176  * Hence when the verifier completes the search of state list in is_state_visited()
10177  * we can call this clean_live_states() function to mark all liveness states
10178  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10179  * will not be used.
10180  * This function also clears the registers and stack for states that !READ
10181  * to simplify state merging.
10182  *
10183  * Important note here that walking the same branch instruction in the callee
10184  * doesn't meant that the states are DONE. The verifier has to compare
10185  * the callsites
10186  */
10187 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10188 			      struct bpf_verifier_state *cur)
10189 {
10190 	struct bpf_verifier_state_list *sl;
10191 	int i;
10192 
10193 	sl = *explored_state(env, insn);
10194 	while (sl) {
10195 		if (sl->state.branches)
10196 			goto next;
10197 		if (sl->state.insn_idx != insn ||
10198 		    sl->state.curframe != cur->curframe)
10199 			goto next;
10200 		for (i = 0; i <= cur->curframe; i++)
10201 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10202 				goto next;
10203 		clean_verifier_state(env, &sl->state);
10204 next:
10205 		sl = sl->next;
10206 	}
10207 }
10208 
10209 /* Returns true if (rold safe implies rcur safe) */
10210 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
10211 		    struct bpf_id_pair *idmap)
10212 {
10213 	bool equal;
10214 
10215 	if (!(rold->live & REG_LIVE_READ))
10216 		/* explored state didn't use this */
10217 		return true;
10218 
10219 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10220 
10221 	if (rold->type == PTR_TO_STACK)
10222 		/* two stack pointers are equal only if they're pointing to
10223 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10224 		 */
10225 		return equal && rold->frameno == rcur->frameno;
10226 
10227 	if (equal)
10228 		return true;
10229 
10230 	if (rold->type == NOT_INIT)
10231 		/* explored state can't have used this */
10232 		return true;
10233 	if (rcur->type == NOT_INIT)
10234 		return false;
10235 	switch (rold->type) {
10236 	case SCALAR_VALUE:
10237 		if (rcur->type == SCALAR_VALUE) {
10238 			if (!rold->precise && !rcur->precise)
10239 				return true;
10240 			/* new val must satisfy old val knowledge */
10241 			return range_within(rold, rcur) &&
10242 			       tnum_in(rold->var_off, rcur->var_off);
10243 		} else {
10244 			/* We're trying to use a pointer in place of a scalar.
10245 			 * Even if the scalar was unbounded, this could lead to
10246 			 * pointer leaks because scalars are allowed to leak
10247 			 * while pointers are not. We could make this safe in
10248 			 * special cases if root is calling us, but it's
10249 			 * probably not worth the hassle.
10250 			 */
10251 			return false;
10252 		}
10253 	case PTR_TO_MAP_KEY:
10254 	case PTR_TO_MAP_VALUE:
10255 		/* If the new min/max/var_off satisfy the old ones and
10256 		 * everything else matches, we are OK.
10257 		 * 'id' is not compared, since it's only used for maps with
10258 		 * bpf_spin_lock inside map element and in such cases if
10259 		 * the rest of the prog is valid for one map element then
10260 		 * it's valid for all map elements regardless of the key
10261 		 * used in bpf_map_lookup()
10262 		 */
10263 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10264 		       range_within(rold, rcur) &&
10265 		       tnum_in(rold->var_off, rcur->var_off);
10266 	case PTR_TO_MAP_VALUE_OR_NULL:
10267 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10268 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10269 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10270 		 * checked, doing so could have affected others with the same
10271 		 * id, and we can't check for that because we lost the id when
10272 		 * we converted to a PTR_TO_MAP_VALUE.
10273 		 */
10274 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10275 			return false;
10276 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10277 			return false;
10278 		/* Check our ids match any regs they're supposed to */
10279 		return check_ids(rold->id, rcur->id, idmap);
10280 	case PTR_TO_PACKET_META:
10281 	case PTR_TO_PACKET:
10282 		if (rcur->type != rold->type)
10283 			return false;
10284 		/* We must have at least as much range as the old ptr
10285 		 * did, so that any accesses which were safe before are
10286 		 * still safe.  This is true even if old range < old off,
10287 		 * since someone could have accessed through (ptr - k), or
10288 		 * even done ptr -= k in a register, to get a safe access.
10289 		 */
10290 		if (rold->range > rcur->range)
10291 			return false;
10292 		/* If the offsets don't match, we can't trust our alignment;
10293 		 * nor can we be sure that we won't fall out of range.
10294 		 */
10295 		if (rold->off != rcur->off)
10296 			return false;
10297 		/* id relations must be preserved */
10298 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10299 			return false;
10300 		/* new val must satisfy old val knowledge */
10301 		return range_within(rold, rcur) &&
10302 		       tnum_in(rold->var_off, rcur->var_off);
10303 	case PTR_TO_CTX:
10304 	case CONST_PTR_TO_MAP:
10305 	case PTR_TO_PACKET_END:
10306 	case PTR_TO_FLOW_KEYS:
10307 	case PTR_TO_SOCKET:
10308 	case PTR_TO_SOCKET_OR_NULL:
10309 	case PTR_TO_SOCK_COMMON:
10310 	case PTR_TO_SOCK_COMMON_OR_NULL:
10311 	case PTR_TO_TCP_SOCK:
10312 	case PTR_TO_TCP_SOCK_OR_NULL:
10313 	case PTR_TO_XDP_SOCK:
10314 		/* Only valid matches are exact, which memcmp() above
10315 		 * would have accepted
10316 		 */
10317 	default:
10318 		/* Don't know what's going on, just say it's not safe */
10319 		return false;
10320 	}
10321 
10322 	/* Shouldn't get here; if we do, say it's not safe */
10323 	WARN_ON_ONCE(1);
10324 	return false;
10325 }
10326 
10327 static bool stacksafe(struct bpf_func_state *old,
10328 		      struct bpf_func_state *cur,
10329 		      struct bpf_id_pair *idmap)
10330 {
10331 	int i, spi;
10332 
10333 	/* walk slots of the explored stack and ignore any additional
10334 	 * slots in the current stack, since explored(safe) state
10335 	 * didn't use them
10336 	 */
10337 	for (i = 0; i < old->allocated_stack; i++) {
10338 		spi = i / BPF_REG_SIZE;
10339 
10340 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10341 			i += BPF_REG_SIZE - 1;
10342 			/* explored state didn't use this */
10343 			continue;
10344 		}
10345 
10346 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10347 			continue;
10348 
10349 		/* explored stack has more populated slots than current stack
10350 		 * and these slots were used
10351 		 */
10352 		if (i >= cur->allocated_stack)
10353 			return false;
10354 
10355 		/* if old state was safe with misc data in the stack
10356 		 * it will be safe with zero-initialized stack.
10357 		 * The opposite is not true
10358 		 */
10359 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10360 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10361 			continue;
10362 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10363 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10364 			/* Ex: old explored (safe) state has STACK_SPILL in
10365 			 * this stack slot, but current has STACK_MISC ->
10366 			 * this verifier states are not equivalent,
10367 			 * return false to continue verification of this path
10368 			 */
10369 			return false;
10370 		if (i % BPF_REG_SIZE)
10371 			continue;
10372 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
10373 			continue;
10374 		if (!regsafe(&old->stack[spi].spilled_ptr,
10375 			     &cur->stack[spi].spilled_ptr,
10376 			     idmap))
10377 			/* when explored and current stack slot are both storing
10378 			 * spilled registers, check that stored pointers types
10379 			 * are the same as well.
10380 			 * Ex: explored safe path could have stored
10381 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10382 			 * but current path has stored:
10383 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10384 			 * such verifier states are not equivalent.
10385 			 * return false to continue verification of this path
10386 			 */
10387 			return false;
10388 	}
10389 	return true;
10390 }
10391 
10392 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10393 {
10394 	if (old->acquired_refs != cur->acquired_refs)
10395 		return false;
10396 	return !memcmp(old->refs, cur->refs,
10397 		       sizeof(*old->refs) * old->acquired_refs);
10398 }
10399 
10400 /* compare two verifier states
10401  *
10402  * all states stored in state_list are known to be valid, since
10403  * verifier reached 'bpf_exit' instruction through them
10404  *
10405  * this function is called when verifier exploring different branches of
10406  * execution popped from the state stack. If it sees an old state that has
10407  * more strict register state and more strict stack state then this execution
10408  * branch doesn't need to be explored further, since verifier already
10409  * concluded that more strict state leads to valid finish.
10410  *
10411  * Therefore two states are equivalent if register state is more conservative
10412  * and explored stack state is more conservative than the current one.
10413  * Example:
10414  *       explored                   current
10415  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10416  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10417  *
10418  * In other words if current stack state (one being explored) has more
10419  * valid slots than old one that already passed validation, it means
10420  * the verifier can stop exploring and conclude that current state is valid too
10421  *
10422  * Similarly with registers. If explored state has register type as invalid
10423  * whereas register type in current state is meaningful, it means that
10424  * the current state will reach 'bpf_exit' instruction safely
10425  */
10426 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10427 			      struct bpf_func_state *cur)
10428 {
10429 	int i;
10430 
10431 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10432 	for (i = 0; i < MAX_BPF_REG; i++)
10433 		if (!regsafe(&old->regs[i], &cur->regs[i], env->idmap_scratch))
10434 			return false;
10435 
10436 	if (!stacksafe(old, cur, env->idmap_scratch))
10437 		return false;
10438 
10439 	if (!refsafe(old, cur))
10440 		return false;
10441 
10442 	return true;
10443 }
10444 
10445 static bool states_equal(struct bpf_verifier_env *env,
10446 			 struct bpf_verifier_state *old,
10447 			 struct bpf_verifier_state *cur)
10448 {
10449 	int i;
10450 
10451 	if (old->curframe != cur->curframe)
10452 		return false;
10453 
10454 	/* Verification state from speculative execution simulation
10455 	 * must never prune a non-speculative execution one.
10456 	 */
10457 	if (old->speculative && !cur->speculative)
10458 		return false;
10459 
10460 	if (old->active_spin_lock != cur->active_spin_lock)
10461 		return false;
10462 
10463 	/* for states to be equal callsites have to be the same
10464 	 * and all frame states need to be equivalent
10465 	 */
10466 	for (i = 0; i <= old->curframe; i++) {
10467 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10468 			return false;
10469 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10470 			return false;
10471 	}
10472 	return true;
10473 }
10474 
10475 /* Return 0 if no propagation happened. Return negative error code if error
10476  * happened. Otherwise, return the propagated bit.
10477  */
10478 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10479 				  struct bpf_reg_state *reg,
10480 				  struct bpf_reg_state *parent_reg)
10481 {
10482 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10483 	u8 flag = reg->live & REG_LIVE_READ;
10484 	int err;
10485 
10486 	/* When comes here, read flags of PARENT_REG or REG could be any of
10487 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10488 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10489 	 */
10490 	if (parent_flag == REG_LIVE_READ64 ||
10491 	    /* Or if there is no read flag from REG. */
10492 	    !flag ||
10493 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10494 	    parent_flag == flag)
10495 		return 0;
10496 
10497 	err = mark_reg_read(env, reg, parent_reg, flag);
10498 	if (err)
10499 		return err;
10500 
10501 	return flag;
10502 }
10503 
10504 /* A write screens off any subsequent reads; but write marks come from the
10505  * straight-line code between a state and its parent.  When we arrive at an
10506  * equivalent state (jump target or such) we didn't arrive by the straight-line
10507  * code, so read marks in the state must propagate to the parent regardless
10508  * of the state's write marks. That's what 'parent == state->parent' comparison
10509  * in mark_reg_read() is for.
10510  */
10511 static int propagate_liveness(struct bpf_verifier_env *env,
10512 			      const struct bpf_verifier_state *vstate,
10513 			      struct bpf_verifier_state *vparent)
10514 {
10515 	struct bpf_reg_state *state_reg, *parent_reg;
10516 	struct bpf_func_state *state, *parent;
10517 	int i, frame, err = 0;
10518 
10519 	if (vparent->curframe != vstate->curframe) {
10520 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10521 		     vparent->curframe, vstate->curframe);
10522 		return -EFAULT;
10523 	}
10524 	/* Propagate read liveness of registers... */
10525 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10526 	for (frame = 0; frame <= vstate->curframe; frame++) {
10527 		parent = vparent->frame[frame];
10528 		state = vstate->frame[frame];
10529 		parent_reg = parent->regs;
10530 		state_reg = state->regs;
10531 		/* We don't need to worry about FP liveness, it's read-only */
10532 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10533 			err = propagate_liveness_reg(env, &state_reg[i],
10534 						     &parent_reg[i]);
10535 			if (err < 0)
10536 				return err;
10537 			if (err == REG_LIVE_READ64)
10538 				mark_insn_zext(env, &parent_reg[i]);
10539 		}
10540 
10541 		/* Propagate stack slots. */
10542 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10543 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10544 			parent_reg = &parent->stack[i].spilled_ptr;
10545 			state_reg = &state->stack[i].spilled_ptr;
10546 			err = propagate_liveness_reg(env, state_reg,
10547 						     parent_reg);
10548 			if (err < 0)
10549 				return err;
10550 		}
10551 	}
10552 	return 0;
10553 }
10554 
10555 /* find precise scalars in the previous equivalent state and
10556  * propagate them into the current state
10557  */
10558 static int propagate_precision(struct bpf_verifier_env *env,
10559 			       const struct bpf_verifier_state *old)
10560 {
10561 	struct bpf_reg_state *state_reg;
10562 	struct bpf_func_state *state;
10563 	int i, err = 0;
10564 
10565 	state = old->frame[old->curframe];
10566 	state_reg = state->regs;
10567 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10568 		if (state_reg->type != SCALAR_VALUE ||
10569 		    !state_reg->precise)
10570 			continue;
10571 		if (env->log.level & BPF_LOG_LEVEL2)
10572 			verbose(env, "propagating r%d\n", i);
10573 		err = mark_chain_precision(env, i);
10574 		if (err < 0)
10575 			return err;
10576 	}
10577 
10578 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10579 		if (state->stack[i].slot_type[0] != STACK_SPILL)
10580 			continue;
10581 		state_reg = &state->stack[i].spilled_ptr;
10582 		if (state_reg->type != SCALAR_VALUE ||
10583 		    !state_reg->precise)
10584 			continue;
10585 		if (env->log.level & BPF_LOG_LEVEL2)
10586 			verbose(env, "propagating fp%d\n",
10587 				(-i - 1) * BPF_REG_SIZE);
10588 		err = mark_chain_precision_stack(env, i);
10589 		if (err < 0)
10590 			return err;
10591 	}
10592 	return 0;
10593 }
10594 
10595 static bool states_maybe_looping(struct bpf_verifier_state *old,
10596 				 struct bpf_verifier_state *cur)
10597 {
10598 	struct bpf_func_state *fold, *fcur;
10599 	int i, fr = cur->curframe;
10600 
10601 	if (old->curframe != fr)
10602 		return false;
10603 
10604 	fold = old->frame[fr];
10605 	fcur = cur->frame[fr];
10606 	for (i = 0; i < MAX_BPF_REG; i++)
10607 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10608 			   offsetof(struct bpf_reg_state, parent)))
10609 			return false;
10610 	return true;
10611 }
10612 
10613 
10614 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10615 {
10616 	struct bpf_verifier_state_list *new_sl;
10617 	struct bpf_verifier_state_list *sl, **pprev;
10618 	struct bpf_verifier_state *cur = env->cur_state, *new;
10619 	int i, j, err, states_cnt = 0;
10620 	bool add_new_state = env->test_state_freq ? true : false;
10621 
10622 	cur->last_insn_idx = env->prev_insn_idx;
10623 	if (!env->insn_aux_data[insn_idx].prune_point)
10624 		/* this 'insn_idx' instruction wasn't marked, so we will not
10625 		 * be doing state search here
10626 		 */
10627 		return 0;
10628 
10629 	/* bpf progs typically have pruning point every 4 instructions
10630 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10631 	 * Do not add new state for future pruning if the verifier hasn't seen
10632 	 * at least 2 jumps and at least 8 instructions.
10633 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10634 	 * In tests that amounts to up to 50% reduction into total verifier
10635 	 * memory consumption and 20% verifier time speedup.
10636 	 */
10637 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10638 	    env->insn_processed - env->prev_insn_processed >= 8)
10639 		add_new_state = true;
10640 
10641 	pprev = explored_state(env, insn_idx);
10642 	sl = *pprev;
10643 
10644 	clean_live_states(env, insn_idx, cur);
10645 
10646 	while (sl) {
10647 		states_cnt++;
10648 		if (sl->state.insn_idx != insn_idx)
10649 			goto next;
10650 
10651 		if (sl->state.branches) {
10652 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10653 
10654 			if (frame->in_async_callback_fn &&
10655 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10656 				/* Different async_entry_cnt means that the verifier is
10657 				 * processing another entry into async callback.
10658 				 * Seeing the same state is not an indication of infinite
10659 				 * loop or infinite recursion.
10660 				 * But finding the same state doesn't mean that it's safe
10661 				 * to stop processing the current state. The previous state
10662 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10663 				 * Checking in_async_callback_fn alone is not enough either.
10664 				 * Since the verifier still needs to catch infinite loops
10665 				 * inside async callbacks.
10666 				 */
10667 			} else if (states_maybe_looping(&sl->state, cur) &&
10668 				   states_equal(env, &sl->state, cur)) {
10669 				verbose_linfo(env, insn_idx, "; ");
10670 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10671 				return -EINVAL;
10672 			}
10673 			/* if the verifier is processing a loop, avoid adding new state
10674 			 * too often, since different loop iterations have distinct
10675 			 * states and may not help future pruning.
10676 			 * This threshold shouldn't be too low to make sure that
10677 			 * a loop with large bound will be rejected quickly.
10678 			 * The most abusive loop will be:
10679 			 * r1 += 1
10680 			 * if r1 < 1000000 goto pc-2
10681 			 * 1M insn_procssed limit / 100 == 10k peak states.
10682 			 * This threshold shouldn't be too high either, since states
10683 			 * at the end of the loop are likely to be useful in pruning.
10684 			 */
10685 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10686 			    env->insn_processed - env->prev_insn_processed < 100)
10687 				add_new_state = false;
10688 			goto miss;
10689 		}
10690 		if (states_equal(env, &sl->state, cur)) {
10691 			sl->hit_cnt++;
10692 			/* reached equivalent register/stack state,
10693 			 * prune the search.
10694 			 * Registers read by the continuation are read by us.
10695 			 * If we have any write marks in env->cur_state, they
10696 			 * will prevent corresponding reads in the continuation
10697 			 * from reaching our parent (an explored_state).  Our
10698 			 * own state will get the read marks recorded, but
10699 			 * they'll be immediately forgotten as we're pruning
10700 			 * this state and will pop a new one.
10701 			 */
10702 			err = propagate_liveness(env, &sl->state, cur);
10703 
10704 			/* if previous state reached the exit with precision and
10705 			 * current state is equivalent to it (except precsion marks)
10706 			 * the precision needs to be propagated back in
10707 			 * the current state.
10708 			 */
10709 			err = err ? : push_jmp_history(env, cur);
10710 			err = err ? : propagate_precision(env, &sl->state);
10711 			if (err)
10712 				return err;
10713 			return 1;
10714 		}
10715 miss:
10716 		/* when new state is not going to be added do not increase miss count.
10717 		 * Otherwise several loop iterations will remove the state
10718 		 * recorded earlier. The goal of these heuristics is to have
10719 		 * states from some iterations of the loop (some in the beginning
10720 		 * and some at the end) to help pruning.
10721 		 */
10722 		if (add_new_state)
10723 			sl->miss_cnt++;
10724 		/* heuristic to determine whether this state is beneficial
10725 		 * to keep checking from state equivalence point of view.
10726 		 * Higher numbers increase max_states_per_insn and verification time,
10727 		 * but do not meaningfully decrease insn_processed.
10728 		 */
10729 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10730 			/* the state is unlikely to be useful. Remove it to
10731 			 * speed up verification
10732 			 */
10733 			*pprev = sl->next;
10734 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10735 				u32 br = sl->state.branches;
10736 
10737 				WARN_ONCE(br,
10738 					  "BUG live_done but branches_to_explore %d\n",
10739 					  br);
10740 				free_verifier_state(&sl->state, false);
10741 				kfree(sl);
10742 				env->peak_states--;
10743 			} else {
10744 				/* cannot free this state, since parentage chain may
10745 				 * walk it later. Add it for free_list instead to
10746 				 * be freed at the end of verification
10747 				 */
10748 				sl->next = env->free_list;
10749 				env->free_list = sl;
10750 			}
10751 			sl = *pprev;
10752 			continue;
10753 		}
10754 next:
10755 		pprev = &sl->next;
10756 		sl = *pprev;
10757 	}
10758 
10759 	if (env->max_states_per_insn < states_cnt)
10760 		env->max_states_per_insn = states_cnt;
10761 
10762 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10763 		return push_jmp_history(env, cur);
10764 
10765 	if (!add_new_state)
10766 		return push_jmp_history(env, cur);
10767 
10768 	/* There were no equivalent states, remember the current one.
10769 	 * Technically the current state is not proven to be safe yet,
10770 	 * but it will either reach outer most bpf_exit (which means it's safe)
10771 	 * or it will be rejected. When there are no loops the verifier won't be
10772 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10773 	 * again on the way to bpf_exit.
10774 	 * When looping the sl->state.branches will be > 0 and this state
10775 	 * will not be considered for equivalence until branches == 0.
10776 	 */
10777 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10778 	if (!new_sl)
10779 		return -ENOMEM;
10780 	env->total_states++;
10781 	env->peak_states++;
10782 	env->prev_jmps_processed = env->jmps_processed;
10783 	env->prev_insn_processed = env->insn_processed;
10784 
10785 	/* add new state to the head of linked list */
10786 	new = &new_sl->state;
10787 	err = copy_verifier_state(new, cur);
10788 	if (err) {
10789 		free_verifier_state(new, false);
10790 		kfree(new_sl);
10791 		return err;
10792 	}
10793 	new->insn_idx = insn_idx;
10794 	WARN_ONCE(new->branches != 1,
10795 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10796 
10797 	cur->parent = new;
10798 	cur->first_insn_idx = insn_idx;
10799 	clear_jmp_history(cur);
10800 	new_sl->next = *explored_state(env, insn_idx);
10801 	*explored_state(env, insn_idx) = new_sl;
10802 	/* connect new state to parentage chain. Current frame needs all
10803 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
10804 	 * to the stack implicitly by JITs) so in callers' frames connect just
10805 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10806 	 * the state of the call instruction (with WRITTEN set), and r0 comes
10807 	 * from callee with its full parentage chain, anyway.
10808 	 */
10809 	/* clear write marks in current state: the writes we did are not writes
10810 	 * our child did, so they don't screen off its reads from us.
10811 	 * (There are no read marks in current state, because reads always mark
10812 	 * their parent and current state never has children yet.  Only
10813 	 * explored_states can get read marks.)
10814 	 */
10815 	for (j = 0; j <= cur->curframe; j++) {
10816 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10817 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10818 		for (i = 0; i < BPF_REG_FP; i++)
10819 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10820 	}
10821 
10822 	/* all stack frames are accessible from callee, clear them all */
10823 	for (j = 0; j <= cur->curframe; j++) {
10824 		struct bpf_func_state *frame = cur->frame[j];
10825 		struct bpf_func_state *newframe = new->frame[j];
10826 
10827 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10828 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10829 			frame->stack[i].spilled_ptr.parent =
10830 						&newframe->stack[i].spilled_ptr;
10831 		}
10832 	}
10833 	return 0;
10834 }
10835 
10836 /* Return true if it's OK to have the same insn return a different type. */
10837 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10838 {
10839 	switch (type) {
10840 	case PTR_TO_CTX:
10841 	case PTR_TO_SOCKET:
10842 	case PTR_TO_SOCKET_OR_NULL:
10843 	case PTR_TO_SOCK_COMMON:
10844 	case PTR_TO_SOCK_COMMON_OR_NULL:
10845 	case PTR_TO_TCP_SOCK:
10846 	case PTR_TO_TCP_SOCK_OR_NULL:
10847 	case PTR_TO_XDP_SOCK:
10848 	case PTR_TO_BTF_ID:
10849 	case PTR_TO_BTF_ID_OR_NULL:
10850 		return false;
10851 	default:
10852 		return true;
10853 	}
10854 }
10855 
10856 /* If an instruction was previously used with particular pointer types, then we
10857  * need to be careful to avoid cases such as the below, where it may be ok
10858  * for one branch accessing the pointer, but not ok for the other branch:
10859  *
10860  * R1 = sock_ptr
10861  * goto X;
10862  * ...
10863  * R1 = some_other_valid_ptr;
10864  * goto X;
10865  * ...
10866  * R2 = *(u32 *)(R1 + 0);
10867  */
10868 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10869 {
10870 	return src != prev && (!reg_type_mismatch_ok(src) ||
10871 			       !reg_type_mismatch_ok(prev));
10872 }
10873 
10874 static int do_check(struct bpf_verifier_env *env)
10875 {
10876 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10877 	struct bpf_verifier_state *state = env->cur_state;
10878 	struct bpf_insn *insns = env->prog->insnsi;
10879 	struct bpf_reg_state *regs;
10880 	int insn_cnt = env->prog->len;
10881 	bool do_print_state = false;
10882 	int prev_insn_idx = -1;
10883 
10884 	for (;;) {
10885 		struct bpf_insn *insn;
10886 		u8 class;
10887 		int err;
10888 
10889 		env->prev_insn_idx = prev_insn_idx;
10890 		if (env->insn_idx >= insn_cnt) {
10891 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
10892 				env->insn_idx, insn_cnt);
10893 			return -EFAULT;
10894 		}
10895 
10896 		insn = &insns[env->insn_idx];
10897 		class = BPF_CLASS(insn->code);
10898 
10899 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10900 			verbose(env,
10901 				"BPF program is too large. Processed %d insn\n",
10902 				env->insn_processed);
10903 			return -E2BIG;
10904 		}
10905 
10906 		err = is_state_visited(env, env->insn_idx);
10907 		if (err < 0)
10908 			return err;
10909 		if (err == 1) {
10910 			/* found equivalent state, can prune the search */
10911 			if (env->log.level & BPF_LOG_LEVEL) {
10912 				if (do_print_state)
10913 					verbose(env, "\nfrom %d to %d%s: safe\n",
10914 						env->prev_insn_idx, env->insn_idx,
10915 						env->cur_state->speculative ?
10916 						" (speculative execution)" : "");
10917 				else
10918 					verbose(env, "%d: safe\n", env->insn_idx);
10919 			}
10920 			goto process_bpf_exit;
10921 		}
10922 
10923 		if (signal_pending(current))
10924 			return -EAGAIN;
10925 
10926 		if (need_resched())
10927 			cond_resched();
10928 
10929 		if (env->log.level & BPF_LOG_LEVEL2 ||
10930 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10931 			if (env->log.level & BPF_LOG_LEVEL2)
10932 				verbose(env, "%d:", env->insn_idx);
10933 			else
10934 				verbose(env, "\nfrom %d to %d%s:",
10935 					env->prev_insn_idx, env->insn_idx,
10936 					env->cur_state->speculative ?
10937 					" (speculative execution)" : "");
10938 			print_verifier_state(env, state->frame[state->curframe]);
10939 			do_print_state = false;
10940 		}
10941 
10942 		if (env->log.level & BPF_LOG_LEVEL) {
10943 			const struct bpf_insn_cbs cbs = {
10944 				.cb_call	= disasm_kfunc_name,
10945 				.cb_print	= verbose,
10946 				.private_data	= env,
10947 			};
10948 
10949 			verbose_linfo(env, env->insn_idx, "; ");
10950 			verbose(env, "%d: ", env->insn_idx);
10951 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10952 		}
10953 
10954 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
10955 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10956 							   env->prev_insn_idx);
10957 			if (err)
10958 				return err;
10959 		}
10960 
10961 		regs = cur_regs(env);
10962 		sanitize_mark_insn_seen(env);
10963 		prev_insn_idx = env->insn_idx;
10964 
10965 		if (class == BPF_ALU || class == BPF_ALU64) {
10966 			err = check_alu_op(env, insn);
10967 			if (err)
10968 				return err;
10969 
10970 		} else if (class == BPF_LDX) {
10971 			enum bpf_reg_type *prev_src_type, src_reg_type;
10972 
10973 			/* check for reserved fields is already done */
10974 
10975 			/* check src operand */
10976 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10977 			if (err)
10978 				return err;
10979 
10980 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10981 			if (err)
10982 				return err;
10983 
10984 			src_reg_type = regs[insn->src_reg].type;
10985 
10986 			/* check that memory (src_reg + off) is readable,
10987 			 * the state of dst_reg will be updated by this func
10988 			 */
10989 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
10990 					       insn->off, BPF_SIZE(insn->code),
10991 					       BPF_READ, insn->dst_reg, false);
10992 			if (err)
10993 				return err;
10994 
10995 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10996 
10997 			if (*prev_src_type == NOT_INIT) {
10998 				/* saw a valid insn
10999 				 * dst_reg = *(u32 *)(src_reg + off)
11000 				 * save type to validate intersecting paths
11001 				 */
11002 				*prev_src_type = src_reg_type;
11003 
11004 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11005 				/* ABuser program is trying to use the same insn
11006 				 * dst_reg = *(u32*) (src_reg + off)
11007 				 * with different pointer types:
11008 				 * src_reg == ctx in one branch and
11009 				 * src_reg == stack|map in some other branch.
11010 				 * Reject it.
11011 				 */
11012 				verbose(env, "same insn cannot be used with different pointers\n");
11013 				return -EINVAL;
11014 			}
11015 
11016 		} else if (class == BPF_STX) {
11017 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11018 
11019 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11020 				err = check_atomic(env, env->insn_idx, insn);
11021 				if (err)
11022 					return err;
11023 				env->insn_idx++;
11024 				continue;
11025 			}
11026 
11027 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11028 				verbose(env, "BPF_STX uses reserved fields\n");
11029 				return -EINVAL;
11030 			}
11031 
11032 			/* check src1 operand */
11033 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11034 			if (err)
11035 				return err;
11036 			/* check src2 operand */
11037 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11038 			if (err)
11039 				return err;
11040 
11041 			dst_reg_type = regs[insn->dst_reg].type;
11042 
11043 			/* check that memory (dst_reg + off) is writeable */
11044 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11045 					       insn->off, BPF_SIZE(insn->code),
11046 					       BPF_WRITE, insn->src_reg, false);
11047 			if (err)
11048 				return err;
11049 
11050 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11051 
11052 			if (*prev_dst_type == NOT_INIT) {
11053 				*prev_dst_type = dst_reg_type;
11054 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11055 				verbose(env, "same insn cannot be used with different pointers\n");
11056 				return -EINVAL;
11057 			}
11058 
11059 		} else if (class == BPF_ST) {
11060 			if (BPF_MODE(insn->code) != BPF_MEM ||
11061 			    insn->src_reg != BPF_REG_0) {
11062 				verbose(env, "BPF_ST uses reserved fields\n");
11063 				return -EINVAL;
11064 			}
11065 			/* check src operand */
11066 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11067 			if (err)
11068 				return err;
11069 
11070 			if (is_ctx_reg(env, insn->dst_reg)) {
11071 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11072 					insn->dst_reg,
11073 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
11074 				return -EACCES;
11075 			}
11076 
11077 			/* check that memory (dst_reg + off) is writeable */
11078 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11079 					       insn->off, BPF_SIZE(insn->code),
11080 					       BPF_WRITE, -1, false);
11081 			if (err)
11082 				return err;
11083 
11084 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11085 			u8 opcode = BPF_OP(insn->code);
11086 
11087 			env->jmps_processed++;
11088 			if (opcode == BPF_CALL) {
11089 				if (BPF_SRC(insn->code) != BPF_K ||
11090 				    insn->off != 0 ||
11091 				    (insn->src_reg != BPF_REG_0 &&
11092 				     insn->src_reg != BPF_PSEUDO_CALL &&
11093 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11094 				    insn->dst_reg != BPF_REG_0 ||
11095 				    class == BPF_JMP32) {
11096 					verbose(env, "BPF_CALL uses reserved fields\n");
11097 					return -EINVAL;
11098 				}
11099 
11100 				if (env->cur_state->active_spin_lock &&
11101 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11102 				     insn->imm != BPF_FUNC_spin_unlock)) {
11103 					verbose(env, "function calls are not allowed while holding a lock\n");
11104 					return -EINVAL;
11105 				}
11106 				if (insn->src_reg == BPF_PSEUDO_CALL)
11107 					err = check_func_call(env, insn, &env->insn_idx);
11108 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11109 					err = check_kfunc_call(env, insn);
11110 				else
11111 					err = check_helper_call(env, insn, &env->insn_idx);
11112 				if (err)
11113 					return err;
11114 			} else if (opcode == BPF_JA) {
11115 				if (BPF_SRC(insn->code) != BPF_K ||
11116 				    insn->imm != 0 ||
11117 				    insn->src_reg != BPF_REG_0 ||
11118 				    insn->dst_reg != BPF_REG_0 ||
11119 				    class == BPF_JMP32) {
11120 					verbose(env, "BPF_JA uses reserved fields\n");
11121 					return -EINVAL;
11122 				}
11123 
11124 				env->insn_idx += insn->off + 1;
11125 				continue;
11126 
11127 			} else if (opcode == BPF_EXIT) {
11128 				if (BPF_SRC(insn->code) != BPF_K ||
11129 				    insn->imm != 0 ||
11130 				    insn->src_reg != BPF_REG_0 ||
11131 				    insn->dst_reg != BPF_REG_0 ||
11132 				    class == BPF_JMP32) {
11133 					verbose(env, "BPF_EXIT uses reserved fields\n");
11134 					return -EINVAL;
11135 				}
11136 
11137 				if (env->cur_state->active_spin_lock) {
11138 					verbose(env, "bpf_spin_unlock is missing\n");
11139 					return -EINVAL;
11140 				}
11141 
11142 				if (state->curframe) {
11143 					/* exit from nested function */
11144 					err = prepare_func_exit(env, &env->insn_idx);
11145 					if (err)
11146 						return err;
11147 					do_print_state = true;
11148 					continue;
11149 				}
11150 
11151 				err = check_reference_leak(env);
11152 				if (err)
11153 					return err;
11154 
11155 				err = check_return_code(env);
11156 				if (err)
11157 					return err;
11158 process_bpf_exit:
11159 				update_branch_counts(env, env->cur_state);
11160 				err = pop_stack(env, &prev_insn_idx,
11161 						&env->insn_idx, pop_log);
11162 				if (err < 0) {
11163 					if (err != -ENOENT)
11164 						return err;
11165 					break;
11166 				} else {
11167 					do_print_state = true;
11168 					continue;
11169 				}
11170 			} else {
11171 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11172 				if (err)
11173 					return err;
11174 			}
11175 		} else if (class == BPF_LD) {
11176 			u8 mode = BPF_MODE(insn->code);
11177 
11178 			if (mode == BPF_ABS || mode == BPF_IND) {
11179 				err = check_ld_abs(env, insn);
11180 				if (err)
11181 					return err;
11182 
11183 			} else if (mode == BPF_IMM) {
11184 				err = check_ld_imm(env, insn);
11185 				if (err)
11186 					return err;
11187 
11188 				env->insn_idx++;
11189 				sanitize_mark_insn_seen(env);
11190 			} else {
11191 				verbose(env, "invalid BPF_LD mode\n");
11192 				return -EINVAL;
11193 			}
11194 		} else {
11195 			verbose(env, "unknown insn class %d\n", class);
11196 			return -EINVAL;
11197 		}
11198 
11199 		env->insn_idx++;
11200 	}
11201 
11202 	return 0;
11203 }
11204 
11205 static int find_btf_percpu_datasec(struct btf *btf)
11206 {
11207 	const struct btf_type *t;
11208 	const char *tname;
11209 	int i, n;
11210 
11211 	/*
11212 	 * Both vmlinux and module each have their own ".data..percpu"
11213 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11214 	 * types to look at only module's own BTF types.
11215 	 */
11216 	n = btf_nr_types(btf);
11217 	if (btf_is_module(btf))
11218 		i = btf_nr_types(btf_vmlinux);
11219 	else
11220 		i = 1;
11221 
11222 	for(; i < n; i++) {
11223 		t = btf_type_by_id(btf, i);
11224 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11225 			continue;
11226 
11227 		tname = btf_name_by_offset(btf, t->name_off);
11228 		if (!strcmp(tname, ".data..percpu"))
11229 			return i;
11230 	}
11231 
11232 	return -ENOENT;
11233 }
11234 
11235 /* replace pseudo btf_id with kernel symbol address */
11236 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11237 			       struct bpf_insn *insn,
11238 			       struct bpf_insn_aux_data *aux)
11239 {
11240 	const struct btf_var_secinfo *vsi;
11241 	const struct btf_type *datasec;
11242 	struct btf_mod_pair *btf_mod;
11243 	const struct btf_type *t;
11244 	const char *sym_name;
11245 	bool percpu = false;
11246 	u32 type, id = insn->imm;
11247 	struct btf *btf;
11248 	s32 datasec_id;
11249 	u64 addr;
11250 	int i, btf_fd, err;
11251 
11252 	btf_fd = insn[1].imm;
11253 	if (btf_fd) {
11254 		btf = btf_get_by_fd(btf_fd);
11255 		if (IS_ERR(btf)) {
11256 			verbose(env, "invalid module BTF object FD specified.\n");
11257 			return -EINVAL;
11258 		}
11259 	} else {
11260 		if (!btf_vmlinux) {
11261 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11262 			return -EINVAL;
11263 		}
11264 		btf = btf_vmlinux;
11265 		btf_get(btf);
11266 	}
11267 
11268 	t = btf_type_by_id(btf, id);
11269 	if (!t) {
11270 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11271 		err = -ENOENT;
11272 		goto err_put;
11273 	}
11274 
11275 	if (!btf_type_is_var(t)) {
11276 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11277 		err = -EINVAL;
11278 		goto err_put;
11279 	}
11280 
11281 	sym_name = btf_name_by_offset(btf, t->name_off);
11282 	addr = kallsyms_lookup_name(sym_name);
11283 	if (!addr) {
11284 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11285 			sym_name);
11286 		err = -ENOENT;
11287 		goto err_put;
11288 	}
11289 
11290 	datasec_id = find_btf_percpu_datasec(btf);
11291 	if (datasec_id > 0) {
11292 		datasec = btf_type_by_id(btf, datasec_id);
11293 		for_each_vsi(i, datasec, vsi) {
11294 			if (vsi->type == id) {
11295 				percpu = true;
11296 				break;
11297 			}
11298 		}
11299 	}
11300 
11301 	insn[0].imm = (u32)addr;
11302 	insn[1].imm = addr >> 32;
11303 
11304 	type = t->type;
11305 	t = btf_type_skip_modifiers(btf, type, NULL);
11306 	if (percpu) {
11307 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11308 		aux->btf_var.btf = btf;
11309 		aux->btf_var.btf_id = type;
11310 	} else if (!btf_type_is_struct(t)) {
11311 		const struct btf_type *ret;
11312 		const char *tname;
11313 		u32 tsize;
11314 
11315 		/* resolve the type size of ksym. */
11316 		ret = btf_resolve_size(btf, t, &tsize);
11317 		if (IS_ERR(ret)) {
11318 			tname = btf_name_by_offset(btf, t->name_off);
11319 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11320 				tname, PTR_ERR(ret));
11321 			err = -EINVAL;
11322 			goto err_put;
11323 		}
11324 		aux->btf_var.reg_type = PTR_TO_MEM;
11325 		aux->btf_var.mem_size = tsize;
11326 	} else {
11327 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11328 		aux->btf_var.btf = btf;
11329 		aux->btf_var.btf_id = type;
11330 	}
11331 
11332 	/* check whether we recorded this BTF (and maybe module) already */
11333 	for (i = 0; i < env->used_btf_cnt; i++) {
11334 		if (env->used_btfs[i].btf == btf) {
11335 			btf_put(btf);
11336 			return 0;
11337 		}
11338 	}
11339 
11340 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11341 		err = -E2BIG;
11342 		goto err_put;
11343 	}
11344 
11345 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11346 	btf_mod->btf = btf;
11347 	btf_mod->module = NULL;
11348 
11349 	/* if we reference variables from kernel module, bump its refcount */
11350 	if (btf_is_module(btf)) {
11351 		btf_mod->module = btf_try_get_module(btf);
11352 		if (!btf_mod->module) {
11353 			err = -ENXIO;
11354 			goto err_put;
11355 		}
11356 	}
11357 
11358 	env->used_btf_cnt++;
11359 
11360 	return 0;
11361 err_put:
11362 	btf_put(btf);
11363 	return err;
11364 }
11365 
11366 static int check_map_prealloc(struct bpf_map *map)
11367 {
11368 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11369 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11370 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11371 		!(map->map_flags & BPF_F_NO_PREALLOC);
11372 }
11373 
11374 static bool is_tracing_prog_type(enum bpf_prog_type type)
11375 {
11376 	switch (type) {
11377 	case BPF_PROG_TYPE_KPROBE:
11378 	case BPF_PROG_TYPE_TRACEPOINT:
11379 	case BPF_PROG_TYPE_PERF_EVENT:
11380 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11381 		return true;
11382 	default:
11383 		return false;
11384 	}
11385 }
11386 
11387 static bool is_preallocated_map(struct bpf_map *map)
11388 {
11389 	if (!check_map_prealloc(map))
11390 		return false;
11391 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11392 		return false;
11393 	return true;
11394 }
11395 
11396 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11397 					struct bpf_map *map,
11398 					struct bpf_prog *prog)
11399 
11400 {
11401 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11402 	/*
11403 	 * Validate that trace type programs use preallocated hash maps.
11404 	 *
11405 	 * For programs attached to PERF events this is mandatory as the
11406 	 * perf NMI can hit any arbitrary code sequence.
11407 	 *
11408 	 * All other trace types using preallocated hash maps are unsafe as
11409 	 * well because tracepoint or kprobes can be inside locked regions
11410 	 * of the memory allocator or at a place where a recursion into the
11411 	 * memory allocator would see inconsistent state.
11412 	 *
11413 	 * On RT enabled kernels run-time allocation of all trace type
11414 	 * programs is strictly prohibited due to lock type constraints. On
11415 	 * !RT kernels it is allowed for backwards compatibility reasons for
11416 	 * now, but warnings are emitted so developers are made aware of
11417 	 * the unsafety and can fix their programs before this is enforced.
11418 	 */
11419 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11420 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11421 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11422 			return -EINVAL;
11423 		}
11424 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11425 			verbose(env, "trace type programs can only use preallocated hash map\n");
11426 			return -EINVAL;
11427 		}
11428 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11429 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11430 	}
11431 
11432 	if (map_value_has_spin_lock(map)) {
11433 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11434 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11435 			return -EINVAL;
11436 		}
11437 
11438 		if (is_tracing_prog_type(prog_type)) {
11439 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11440 			return -EINVAL;
11441 		}
11442 
11443 		if (prog->aux->sleepable) {
11444 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11445 			return -EINVAL;
11446 		}
11447 	}
11448 
11449 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11450 	    !bpf_offload_prog_map_match(prog, map)) {
11451 		verbose(env, "offload device mismatch between prog and map\n");
11452 		return -EINVAL;
11453 	}
11454 
11455 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11456 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11457 		return -EINVAL;
11458 	}
11459 
11460 	if (prog->aux->sleepable)
11461 		switch (map->map_type) {
11462 		case BPF_MAP_TYPE_HASH:
11463 		case BPF_MAP_TYPE_LRU_HASH:
11464 		case BPF_MAP_TYPE_ARRAY:
11465 		case BPF_MAP_TYPE_PERCPU_HASH:
11466 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11467 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11468 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11469 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11470 			if (!is_preallocated_map(map)) {
11471 				verbose(env,
11472 					"Sleepable programs can only use preallocated maps\n");
11473 				return -EINVAL;
11474 			}
11475 			break;
11476 		case BPF_MAP_TYPE_RINGBUF:
11477 			break;
11478 		default:
11479 			verbose(env,
11480 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11481 			return -EINVAL;
11482 		}
11483 
11484 	return 0;
11485 }
11486 
11487 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11488 {
11489 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11490 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11491 }
11492 
11493 /* find and rewrite pseudo imm in ld_imm64 instructions:
11494  *
11495  * 1. if it accesses map FD, replace it with actual map pointer.
11496  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11497  *
11498  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11499  */
11500 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11501 {
11502 	struct bpf_insn *insn = env->prog->insnsi;
11503 	int insn_cnt = env->prog->len;
11504 	int i, j, err;
11505 
11506 	err = bpf_prog_calc_tag(env->prog);
11507 	if (err)
11508 		return err;
11509 
11510 	for (i = 0; i < insn_cnt; i++, insn++) {
11511 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11512 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11513 			verbose(env, "BPF_LDX uses reserved fields\n");
11514 			return -EINVAL;
11515 		}
11516 
11517 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11518 			struct bpf_insn_aux_data *aux;
11519 			struct bpf_map *map;
11520 			struct fd f;
11521 			u64 addr;
11522 			u32 fd;
11523 
11524 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11525 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11526 			    insn[1].off != 0) {
11527 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11528 				return -EINVAL;
11529 			}
11530 
11531 			if (insn[0].src_reg == 0)
11532 				/* valid generic load 64-bit imm */
11533 				goto next_insn;
11534 
11535 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11536 				aux = &env->insn_aux_data[i];
11537 				err = check_pseudo_btf_id(env, insn, aux);
11538 				if (err)
11539 					return err;
11540 				goto next_insn;
11541 			}
11542 
11543 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11544 				aux = &env->insn_aux_data[i];
11545 				aux->ptr_type = PTR_TO_FUNC;
11546 				goto next_insn;
11547 			}
11548 
11549 			/* In final convert_pseudo_ld_imm64() step, this is
11550 			 * converted into regular 64-bit imm load insn.
11551 			 */
11552 			switch (insn[0].src_reg) {
11553 			case BPF_PSEUDO_MAP_VALUE:
11554 			case BPF_PSEUDO_MAP_IDX_VALUE:
11555 				break;
11556 			case BPF_PSEUDO_MAP_FD:
11557 			case BPF_PSEUDO_MAP_IDX:
11558 				if (insn[1].imm == 0)
11559 					break;
11560 				fallthrough;
11561 			default:
11562 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11563 				return -EINVAL;
11564 			}
11565 
11566 			switch (insn[0].src_reg) {
11567 			case BPF_PSEUDO_MAP_IDX_VALUE:
11568 			case BPF_PSEUDO_MAP_IDX:
11569 				if (bpfptr_is_null(env->fd_array)) {
11570 					verbose(env, "fd_idx without fd_array is invalid\n");
11571 					return -EPROTO;
11572 				}
11573 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11574 							    insn[0].imm * sizeof(fd),
11575 							    sizeof(fd)))
11576 					return -EFAULT;
11577 				break;
11578 			default:
11579 				fd = insn[0].imm;
11580 				break;
11581 			}
11582 
11583 			f = fdget(fd);
11584 			map = __bpf_map_get(f);
11585 			if (IS_ERR(map)) {
11586 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11587 					insn[0].imm);
11588 				return PTR_ERR(map);
11589 			}
11590 
11591 			err = check_map_prog_compatibility(env, map, env->prog);
11592 			if (err) {
11593 				fdput(f);
11594 				return err;
11595 			}
11596 
11597 			aux = &env->insn_aux_data[i];
11598 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11599 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11600 				addr = (unsigned long)map;
11601 			} else {
11602 				u32 off = insn[1].imm;
11603 
11604 				if (off >= BPF_MAX_VAR_OFF) {
11605 					verbose(env, "direct value offset of %u is not allowed\n", off);
11606 					fdput(f);
11607 					return -EINVAL;
11608 				}
11609 
11610 				if (!map->ops->map_direct_value_addr) {
11611 					verbose(env, "no direct value access support for this map type\n");
11612 					fdput(f);
11613 					return -EINVAL;
11614 				}
11615 
11616 				err = map->ops->map_direct_value_addr(map, &addr, off);
11617 				if (err) {
11618 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11619 						map->value_size, off);
11620 					fdput(f);
11621 					return err;
11622 				}
11623 
11624 				aux->map_off = off;
11625 				addr += off;
11626 			}
11627 
11628 			insn[0].imm = (u32)addr;
11629 			insn[1].imm = addr >> 32;
11630 
11631 			/* check whether we recorded this map already */
11632 			for (j = 0; j < env->used_map_cnt; j++) {
11633 				if (env->used_maps[j] == map) {
11634 					aux->map_index = j;
11635 					fdput(f);
11636 					goto next_insn;
11637 				}
11638 			}
11639 
11640 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11641 				fdput(f);
11642 				return -E2BIG;
11643 			}
11644 
11645 			/* hold the map. If the program is rejected by verifier,
11646 			 * the map will be released by release_maps() or it
11647 			 * will be used by the valid program until it's unloaded
11648 			 * and all maps are released in free_used_maps()
11649 			 */
11650 			bpf_map_inc(map);
11651 
11652 			aux->map_index = env->used_map_cnt;
11653 			env->used_maps[env->used_map_cnt++] = map;
11654 
11655 			if (bpf_map_is_cgroup_storage(map) &&
11656 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11657 				verbose(env, "only one cgroup storage of each type is allowed\n");
11658 				fdput(f);
11659 				return -EBUSY;
11660 			}
11661 
11662 			fdput(f);
11663 next_insn:
11664 			insn++;
11665 			i++;
11666 			continue;
11667 		}
11668 
11669 		/* Basic sanity check before we invest more work here. */
11670 		if (!bpf_opcode_in_insntable(insn->code)) {
11671 			verbose(env, "unknown opcode %02x\n", insn->code);
11672 			return -EINVAL;
11673 		}
11674 	}
11675 
11676 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11677 	 * 'struct bpf_map *' into a register instead of user map_fd.
11678 	 * These pointers will be used later by verifier to validate map access.
11679 	 */
11680 	return 0;
11681 }
11682 
11683 /* drop refcnt of maps used by the rejected program */
11684 static void release_maps(struct bpf_verifier_env *env)
11685 {
11686 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11687 			     env->used_map_cnt);
11688 }
11689 
11690 /* drop refcnt of maps used by the rejected program */
11691 static void release_btfs(struct bpf_verifier_env *env)
11692 {
11693 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11694 			     env->used_btf_cnt);
11695 }
11696 
11697 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11698 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11699 {
11700 	struct bpf_insn *insn = env->prog->insnsi;
11701 	int insn_cnt = env->prog->len;
11702 	int i;
11703 
11704 	for (i = 0; i < insn_cnt; i++, insn++) {
11705 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11706 			continue;
11707 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11708 			continue;
11709 		insn->src_reg = 0;
11710 	}
11711 }
11712 
11713 /* single env->prog->insni[off] instruction was replaced with the range
11714  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11715  * [0, off) and [off, end) to new locations, so the patched range stays zero
11716  */
11717 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11718 				 struct bpf_insn_aux_data *new_data,
11719 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11720 {
11721 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11722 	struct bpf_insn *insn = new_prog->insnsi;
11723 	u32 old_seen = old_data[off].seen;
11724 	u32 prog_len;
11725 	int i;
11726 
11727 	/* aux info at OFF always needs adjustment, no matter fast path
11728 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11729 	 * original insn at old prog.
11730 	 */
11731 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11732 
11733 	if (cnt == 1)
11734 		return;
11735 	prog_len = new_prog->len;
11736 
11737 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11738 	memcpy(new_data + off + cnt - 1, old_data + off,
11739 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11740 	for (i = off; i < off + cnt - 1; i++) {
11741 		/* Expand insni[off]'s seen count to the patched range. */
11742 		new_data[i].seen = old_seen;
11743 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11744 	}
11745 	env->insn_aux_data = new_data;
11746 	vfree(old_data);
11747 }
11748 
11749 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11750 {
11751 	int i;
11752 
11753 	if (len == 1)
11754 		return;
11755 	/* NOTE: fake 'exit' subprog should be updated as well. */
11756 	for (i = 0; i <= env->subprog_cnt; i++) {
11757 		if (env->subprog_info[i].start <= off)
11758 			continue;
11759 		env->subprog_info[i].start += len - 1;
11760 	}
11761 }
11762 
11763 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11764 {
11765 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11766 	int i, sz = prog->aux->size_poke_tab;
11767 	struct bpf_jit_poke_descriptor *desc;
11768 
11769 	for (i = 0; i < sz; i++) {
11770 		desc = &tab[i];
11771 		if (desc->insn_idx <= off)
11772 			continue;
11773 		desc->insn_idx += len - 1;
11774 	}
11775 }
11776 
11777 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11778 					    const struct bpf_insn *patch, u32 len)
11779 {
11780 	struct bpf_prog *new_prog;
11781 	struct bpf_insn_aux_data *new_data = NULL;
11782 
11783 	if (len > 1) {
11784 		new_data = vzalloc(array_size(env->prog->len + len - 1,
11785 					      sizeof(struct bpf_insn_aux_data)));
11786 		if (!new_data)
11787 			return NULL;
11788 	}
11789 
11790 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11791 	if (IS_ERR(new_prog)) {
11792 		if (PTR_ERR(new_prog) == -ERANGE)
11793 			verbose(env,
11794 				"insn %d cannot be patched due to 16-bit range\n",
11795 				env->insn_aux_data[off].orig_idx);
11796 		vfree(new_data);
11797 		return NULL;
11798 	}
11799 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
11800 	adjust_subprog_starts(env, off, len);
11801 	adjust_poke_descs(new_prog, off, len);
11802 	return new_prog;
11803 }
11804 
11805 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11806 					      u32 off, u32 cnt)
11807 {
11808 	int i, j;
11809 
11810 	/* find first prog starting at or after off (first to remove) */
11811 	for (i = 0; i < env->subprog_cnt; i++)
11812 		if (env->subprog_info[i].start >= off)
11813 			break;
11814 	/* find first prog starting at or after off + cnt (first to stay) */
11815 	for (j = i; j < env->subprog_cnt; j++)
11816 		if (env->subprog_info[j].start >= off + cnt)
11817 			break;
11818 	/* if j doesn't start exactly at off + cnt, we are just removing
11819 	 * the front of previous prog
11820 	 */
11821 	if (env->subprog_info[j].start != off + cnt)
11822 		j--;
11823 
11824 	if (j > i) {
11825 		struct bpf_prog_aux *aux = env->prog->aux;
11826 		int move;
11827 
11828 		/* move fake 'exit' subprog as well */
11829 		move = env->subprog_cnt + 1 - j;
11830 
11831 		memmove(env->subprog_info + i,
11832 			env->subprog_info + j,
11833 			sizeof(*env->subprog_info) * move);
11834 		env->subprog_cnt -= j - i;
11835 
11836 		/* remove func_info */
11837 		if (aux->func_info) {
11838 			move = aux->func_info_cnt - j;
11839 
11840 			memmove(aux->func_info + i,
11841 				aux->func_info + j,
11842 				sizeof(*aux->func_info) * move);
11843 			aux->func_info_cnt -= j - i;
11844 			/* func_info->insn_off is set after all code rewrites,
11845 			 * in adjust_btf_func() - no need to adjust
11846 			 */
11847 		}
11848 	} else {
11849 		/* convert i from "first prog to remove" to "first to adjust" */
11850 		if (env->subprog_info[i].start == off)
11851 			i++;
11852 	}
11853 
11854 	/* update fake 'exit' subprog as well */
11855 	for (; i <= env->subprog_cnt; i++)
11856 		env->subprog_info[i].start -= cnt;
11857 
11858 	return 0;
11859 }
11860 
11861 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11862 				      u32 cnt)
11863 {
11864 	struct bpf_prog *prog = env->prog;
11865 	u32 i, l_off, l_cnt, nr_linfo;
11866 	struct bpf_line_info *linfo;
11867 
11868 	nr_linfo = prog->aux->nr_linfo;
11869 	if (!nr_linfo)
11870 		return 0;
11871 
11872 	linfo = prog->aux->linfo;
11873 
11874 	/* find first line info to remove, count lines to be removed */
11875 	for (i = 0; i < nr_linfo; i++)
11876 		if (linfo[i].insn_off >= off)
11877 			break;
11878 
11879 	l_off = i;
11880 	l_cnt = 0;
11881 	for (; i < nr_linfo; i++)
11882 		if (linfo[i].insn_off < off + cnt)
11883 			l_cnt++;
11884 		else
11885 			break;
11886 
11887 	/* First live insn doesn't match first live linfo, it needs to "inherit"
11888 	 * last removed linfo.  prog is already modified, so prog->len == off
11889 	 * means no live instructions after (tail of the program was removed).
11890 	 */
11891 	if (prog->len != off && l_cnt &&
11892 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11893 		l_cnt--;
11894 		linfo[--i].insn_off = off + cnt;
11895 	}
11896 
11897 	/* remove the line info which refer to the removed instructions */
11898 	if (l_cnt) {
11899 		memmove(linfo + l_off, linfo + i,
11900 			sizeof(*linfo) * (nr_linfo - i));
11901 
11902 		prog->aux->nr_linfo -= l_cnt;
11903 		nr_linfo = prog->aux->nr_linfo;
11904 	}
11905 
11906 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
11907 	for (i = l_off; i < nr_linfo; i++)
11908 		linfo[i].insn_off -= cnt;
11909 
11910 	/* fix up all subprogs (incl. 'exit') which start >= off */
11911 	for (i = 0; i <= env->subprog_cnt; i++)
11912 		if (env->subprog_info[i].linfo_idx > l_off) {
11913 			/* program may have started in the removed region but
11914 			 * may not be fully removed
11915 			 */
11916 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11917 				env->subprog_info[i].linfo_idx -= l_cnt;
11918 			else
11919 				env->subprog_info[i].linfo_idx = l_off;
11920 		}
11921 
11922 	return 0;
11923 }
11924 
11925 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11926 {
11927 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11928 	unsigned int orig_prog_len = env->prog->len;
11929 	int err;
11930 
11931 	if (bpf_prog_is_dev_bound(env->prog->aux))
11932 		bpf_prog_offload_remove_insns(env, off, cnt);
11933 
11934 	err = bpf_remove_insns(env->prog, off, cnt);
11935 	if (err)
11936 		return err;
11937 
11938 	err = adjust_subprog_starts_after_remove(env, off, cnt);
11939 	if (err)
11940 		return err;
11941 
11942 	err = bpf_adj_linfo_after_remove(env, off, cnt);
11943 	if (err)
11944 		return err;
11945 
11946 	memmove(aux_data + off,	aux_data + off + cnt,
11947 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
11948 
11949 	return 0;
11950 }
11951 
11952 /* The verifier does more data flow analysis than llvm and will not
11953  * explore branches that are dead at run time. Malicious programs can
11954  * have dead code too. Therefore replace all dead at-run-time code
11955  * with 'ja -1'.
11956  *
11957  * Just nops are not optimal, e.g. if they would sit at the end of the
11958  * program and through another bug we would manage to jump there, then
11959  * we'd execute beyond program memory otherwise. Returning exception
11960  * code also wouldn't work since we can have subprogs where the dead
11961  * code could be located.
11962  */
11963 static void sanitize_dead_code(struct bpf_verifier_env *env)
11964 {
11965 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11966 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11967 	struct bpf_insn *insn = env->prog->insnsi;
11968 	const int insn_cnt = env->prog->len;
11969 	int i;
11970 
11971 	for (i = 0; i < insn_cnt; i++) {
11972 		if (aux_data[i].seen)
11973 			continue;
11974 		memcpy(insn + i, &trap, sizeof(trap));
11975 	}
11976 }
11977 
11978 static bool insn_is_cond_jump(u8 code)
11979 {
11980 	u8 op;
11981 
11982 	if (BPF_CLASS(code) == BPF_JMP32)
11983 		return true;
11984 
11985 	if (BPF_CLASS(code) != BPF_JMP)
11986 		return false;
11987 
11988 	op = BPF_OP(code);
11989 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11990 }
11991 
11992 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11993 {
11994 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11995 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11996 	struct bpf_insn *insn = env->prog->insnsi;
11997 	const int insn_cnt = env->prog->len;
11998 	int i;
11999 
12000 	for (i = 0; i < insn_cnt; i++, insn++) {
12001 		if (!insn_is_cond_jump(insn->code))
12002 			continue;
12003 
12004 		if (!aux_data[i + 1].seen)
12005 			ja.off = insn->off;
12006 		else if (!aux_data[i + 1 + insn->off].seen)
12007 			ja.off = 0;
12008 		else
12009 			continue;
12010 
12011 		if (bpf_prog_is_dev_bound(env->prog->aux))
12012 			bpf_prog_offload_replace_insn(env, i, &ja);
12013 
12014 		memcpy(insn, &ja, sizeof(ja));
12015 	}
12016 }
12017 
12018 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12019 {
12020 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12021 	int insn_cnt = env->prog->len;
12022 	int i, err;
12023 
12024 	for (i = 0; i < insn_cnt; i++) {
12025 		int j;
12026 
12027 		j = 0;
12028 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12029 			j++;
12030 		if (!j)
12031 			continue;
12032 
12033 		err = verifier_remove_insns(env, i, j);
12034 		if (err)
12035 			return err;
12036 		insn_cnt = env->prog->len;
12037 	}
12038 
12039 	return 0;
12040 }
12041 
12042 static int opt_remove_nops(struct bpf_verifier_env *env)
12043 {
12044 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12045 	struct bpf_insn *insn = env->prog->insnsi;
12046 	int insn_cnt = env->prog->len;
12047 	int i, err;
12048 
12049 	for (i = 0; i < insn_cnt; i++) {
12050 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12051 			continue;
12052 
12053 		err = verifier_remove_insns(env, i, 1);
12054 		if (err)
12055 			return err;
12056 		insn_cnt--;
12057 		i--;
12058 	}
12059 
12060 	return 0;
12061 }
12062 
12063 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12064 					 const union bpf_attr *attr)
12065 {
12066 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12067 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12068 	int i, patch_len, delta = 0, len = env->prog->len;
12069 	struct bpf_insn *insns = env->prog->insnsi;
12070 	struct bpf_prog *new_prog;
12071 	bool rnd_hi32;
12072 
12073 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12074 	zext_patch[1] = BPF_ZEXT_REG(0);
12075 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12076 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12077 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12078 	for (i = 0; i < len; i++) {
12079 		int adj_idx = i + delta;
12080 		struct bpf_insn insn;
12081 		int load_reg;
12082 
12083 		insn = insns[adj_idx];
12084 		load_reg = insn_def_regno(&insn);
12085 		if (!aux[adj_idx].zext_dst) {
12086 			u8 code, class;
12087 			u32 imm_rnd;
12088 
12089 			if (!rnd_hi32)
12090 				continue;
12091 
12092 			code = insn.code;
12093 			class = BPF_CLASS(code);
12094 			if (load_reg == -1)
12095 				continue;
12096 
12097 			/* NOTE: arg "reg" (the fourth one) is only used for
12098 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12099 			 *       here.
12100 			 */
12101 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12102 				if (class == BPF_LD &&
12103 				    BPF_MODE(code) == BPF_IMM)
12104 					i++;
12105 				continue;
12106 			}
12107 
12108 			/* ctx load could be transformed into wider load. */
12109 			if (class == BPF_LDX &&
12110 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12111 				continue;
12112 
12113 			imm_rnd = get_random_int();
12114 			rnd_hi32_patch[0] = insn;
12115 			rnd_hi32_patch[1].imm = imm_rnd;
12116 			rnd_hi32_patch[3].dst_reg = load_reg;
12117 			patch = rnd_hi32_patch;
12118 			patch_len = 4;
12119 			goto apply_patch_buffer;
12120 		}
12121 
12122 		/* Add in an zero-extend instruction if a) the JIT has requested
12123 		 * it or b) it's a CMPXCHG.
12124 		 *
12125 		 * The latter is because: BPF_CMPXCHG always loads a value into
12126 		 * R0, therefore always zero-extends. However some archs'
12127 		 * equivalent instruction only does this load when the
12128 		 * comparison is successful. This detail of CMPXCHG is
12129 		 * orthogonal to the general zero-extension behaviour of the
12130 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12131 		 */
12132 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12133 			continue;
12134 
12135 		if (WARN_ON(load_reg == -1)) {
12136 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12137 			return -EFAULT;
12138 		}
12139 
12140 		zext_patch[0] = insn;
12141 		zext_patch[1].dst_reg = load_reg;
12142 		zext_patch[1].src_reg = load_reg;
12143 		patch = zext_patch;
12144 		patch_len = 2;
12145 apply_patch_buffer:
12146 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12147 		if (!new_prog)
12148 			return -ENOMEM;
12149 		env->prog = new_prog;
12150 		insns = new_prog->insnsi;
12151 		aux = env->insn_aux_data;
12152 		delta += patch_len - 1;
12153 	}
12154 
12155 	return 0;
12156 }
12157 
12158 /* convert load instructions that access fields of a context type into a
12159  * sequence of instructions that access fields of the underlying structure:
12160  *     struct __sk_buff    -> struct sk_buff
12161  *     struct bpf_sock_ops -> struct sock
12162  */
12163 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12164 {
12165 	const struct bpf_verifier_ops *ops = env->ops;
12166 	int i, cnt, size, ctx_field_size, delta = 0;
12167 	const int insn_cnt = env->prog->len;
12168 	struct bpf_insn insn_buf[16], *insn;
12169 	u32 target_size, size_default, off;
12170 	struct bpf_prog *new_prog;
12171 	enum bpf_access_type type;
12172 	bool is_narrower_load;
12173 
12174 	if (ops->gen_prologue || env->seen_direct_write) {
12175 		if (!ops->gen_prologue) {
12176 			verbose(env, "bpf verifier is misconfigured\n");
12177 			return -EINVAL;
12178 		}
12179 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12180 					env->prog);
12181 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12182 			verbose(env, "bpf verifier is misconfigured\n");
12183 			return -EINVAL;
12184 		} else if (cnt) {
12185 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12186 			if (!new_prog)
12187 				return -ENOMEM;
12188 
12189 			env->prog = new_prog;
12190 			delta += cnt - 1;
12191 		}
12192 	}
12193 
12194 	if (bpf_prog_is_dev_bound(env->prog->aux))
12195 		return 0;
12196 
12197 	insn = env->prog->insnsi + delta;
12198 
12199 	for (i = 0; i < insn_cnt; i++, insn++) {
12200 		bpf_convert_ctx_access_t convert_ctx_access;
12201 
12202 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12203 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12204 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12205 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
12206 			type = BPF_READ;
12207 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12208 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12209 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12210 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
12211 			type = BPF_WRITE;
12212 		else
12213 			continue;
12214 
12215 		if (type == BPF_WRITE &&
12216 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
12217 			struct bpf_insn patch[] = {
12218 				/* Sanitize suspicious stack slot with zero.
12219 				 * There are no memory dependencies for this store,
12220 				 * since it's only using frame pointer and immediate
12221 				 * constant of zero
12222 				 */
12223 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
12224 					   env->insn_aux_data[i + delta].sanitize_stack_off,
12225 					   0),
12226 				/* the original STX instruction will immediately
12227 				 * overwrite the same stack slot with appropriate value
12228 				 */
12229 				*insn,
12230 			};
12231 
12232 			cnt = ARRAY_SIZE(patch);
12233 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12234 			if (!new_prog)
12235 				return -ENOMEM;
12236 
12237 			delta    += cnt - 1;
12238 			env->prog = new_prog;
12239 			insn      = new_prog->insnsi + i + delta;
12240 			continue;
12241 		}
12242 
12243 		switch (env->insn_aux_data[i + delta].ptr_type) {
12244 		case PTR_TO_CTX:
12245 			if (!ops->convert_ctx_access)
12246 				continue;
12247 			convert_ctx_access = ops->convert_ctx_access;
12248 			break;
12249 		case PTR_TO_SOCKET:
12250 		case PTR_TO_SOCK_COMMON:
12251 			convert_ctx_access = bpf_sock_convert_ctx_access;
12252 			break;
12253 		case PTR_TO_TCP_SOCK:
12254 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12255 			break;
12256 		case PTR_TO_XDP_SOCK:
12257 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12258 			break;
12259 		case PTR_TO_BTF_ID:
12260 			if (type == BPF_READ) {
12261 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12262 					BPF_SIZE((insn)->code);
12263 				env->prog->aux->num_exentries++;
12264 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12265 				verbose(env, "Writes through BTF pointers are not allowed\n");
12266 				return -EINVAL;
12267 			}
12268 			continue;
12269 		default:
12270 			continue;
12271 		}
12272 
12273 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12274 		size = BPF_LDST_BYTES(insn);
12275 
12276 		/* If the read access is a narrower load of the field,
12277 		 * convert to a 4/8-byte load, to minimum program type specific
12278 		 * convert_ctx_access changes. If conversion is successful,
12279 		 * we will apply proper mask to the result.
12280 		 */
12281 		is_narrower_load = size < ctx_field_size;
12282 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12283 		off = insn->off;
12284 		if (is_narrower_load) {
12285 			u8 size_code;
12286 
12287 			if (type == BPF_WRITE) {
12288 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12289 				return -EINVAL;
12290 			}
12291 
12292 			size_code = BPF_H;
12293 			if (ctx_field_size == 4)
12294 				size_code = BPF_W;
12295 			else if (ctx_field_size == 8)
12296 				size_code = BPF_DW;
12297 
12298 			insn->off = off & ~(size_default - 1);
12299 			insn->code = BPF_LDX | BPF_MEM | size_code;
12300 		}
12301 
12302 		target_size = 0;
12303 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12304 					 &target_size);
12305 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12306 		    (ctx_field_size && !target_size)) {
12307 			verbose(env, "bpf verifier is misconfigured\n");
12308 			return -EINVAL;
12309 		}
12310 
12311 		if (is_narrower_load && size < target_size) {
12312 			u8 shift = bpf_ctx_narrow_access_offset(
12313 				off, size, size_default) * 8;
12314 			if (ctx_field_size <= 4) {
12315 				if (shift)
12316 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12317 									insn->dst_reg,
12318 									shift);
12319 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12320 								(1 << size * 8) - 1);
12321 			} else {
12322 				if (shift)
12323 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12324 									insn->dst_reg,
12325 									shift);
12326 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12327 								(1ULL << size * 8) - 1);
12328 			}
12329 		}
12330 
12331 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12332 		if (!new_prog)
12333 			return -ENOMEM;
12334 
12335 		delta += cnt - 1;
12336 
12337 		/* keep walking new program and skip insns we just inserted */
12338 		env->prog = new_prog;
12339 		insn      = new_prog->insnsi + i + delta;
12340 	}
12341 
12342 	return 0;
12343 }
12344 
12345 static int jit_subprogs(struct bpf_verifier_env *env)
12346 {
12347 	struct bpf_prog *prog = env->prog, **func, *tmp;
12348 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12349 	struct bpf_map *map_ptr;
12350 	struct bpf_insn *insn;
12351 	void *old_bpf_func;
12352 	int err, num_exentries;
12353 
12354 	if (env->subprog_cnt <= 1)
12355 		return 0;
12356 
12357 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12358 		if (bpf_pseudo_func(insn)) {
12359 			env->insn_aux_data[i].call_imm = insn->imm;
12360 			/* subprog is encoded in insn[1].imm */
12361 			continue;
12362 		}
12363 
12364 		if (!bpf_pseudo_call(insn))
12365 			continue;
12366 		/* Upon error here we cannot fall back to interpreter but
12367 		 * need a hard reject of the program. Thus -EFAULT is
12368 		 * propagated in any case.
12369 		 */
12370 		subprog = find_subprog(env, i + insn->imm + 1);
12371 		if (subprog < 0) {
12372 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12373 				  i + insn->imm + 1);
12374 			return -EFAULT;
12375 		}
12376 		/* temporarily remember subprog id inside insn instead of
12377 		 * aux_data, since next loop will split up all insns into funcs
12378 		 */
12379 		insn->off = subprog;
12380 		/* remember original imm in case JIT fails and fallback
12381 		 * to interpreter will be needed
12382 		 */
12383 		env->insn_aux_data[i].call_imm = insn->imm;
12384 		/* point imm to __bpf_call_base+1 from JITs point of view */
12385 		insn->imm = 1;
12386 	}
12387 
12388 	err = bpf_prog_alloc_jited_linfo(prog);
12389 	if (err)
12390 		goto out_undo_insn;
12391 
12392 	err = -ENOMEM;
12393 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12394 	if (!func)
12395 		goto out_undo_insn;
12396 
12397 	for (i = 0; i < env->subprog_cnt; i++) {
12398 		subprog_start = subprog_end;
12399 		subprog_end = env->subprog_info[i + 1].start;
12400 
12401 		len = subprog_end - subprog_start;
12402 		/* BPF_PROG_RUN doesn't call subprogs directly,
12403 		 * hence main prog stats include the runtime of subprogs.
12404 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12405 		 * func[i]->stats will never be accessed and stays NULL
12406 		 */
12407 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12408 		if (!func[i])
12409 			goto out_free;
12410 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12411 		       len * sizeof(struct bpf_insn));
12412 		func[i]->type = prog->type;
12413 		func[i]->len = len;
12414 		if (bpf_prog_calc_tag(func[i]))
12415 			goto out_free;
12416 		func[i]->is_func = 1;
12417 		func[i]->aux->func_idx = i;
12418 		/* Below members will be freed only at prog->aux */
12419 		func[i]->aux->btf = prog->aux->btf;
12420 		func[i]->aux->func_info = prog->aux->func_info;
12421 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12422 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12423 
12424 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12425 			struct bpf_jit_poke_descriptor *poke;
12426 
12427 			poke = &prog->aux->poke_tab[j];
12428 			if (poke->insn_idx < subprog_end &&
12429 			    poke->insn_idx >= subprog_start)
12430 				poke->aux = func[i]->aux;
12431 		}
12432 
12433 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
12434 		 * Long term would need debug info to populate names
12435 		 */
12436 		func[i]->aux->name[0] = 'F';
12437 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12438 		func[i]->jit_requested = 1;
12439 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12440 		func[i]->aux->linfo = prog->aux->linfo;
12441 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12442 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12443 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12444 		num_exentries = 0;
12445 		insn = func[i]->insnsi;
12446 		for (j = 0; j < func[i]->len; j++, insn++) {
12447 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12448 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12449 				num_exentries++;
12450 		}
12451 		func[i]->aux->num_exentries = num_exentries;
12452 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12453 		func[i] = bpf_int_jit_compile(func[i]);
12454 		if (!func[i]->jited) {
12455 			err = -ENOTSUPP;
12456 			goto out_free;
12457 		}
12458 		cond_resched();
12459 	}
12460 
12461 	/* at this point all bpf functions were successfully JITed
12462 	 * now populate all bpf_calls with correct addresses and
12463 	 * run last pass of JIT
12464 	 */
12465 	for (i = 0; i < env->subprog_cnt; i++) {
12466 		insn = func[i]->insnsi;
12467 		for (j = 0; j < func[i]->len; j++, insn++) {
12468 			if (bpf_pseudo_func(insn)) {
12469 				subprog = insn[1].imm;
12470 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12471 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12472 				continue;
12473 			}
12474 			if (!bpf_pseudo_call(insn))
12475 				continue;
12476 			subprog = insn->off;
12477 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12478 				    __bpf_call_base;
12479 		}
12480 
12481 		/* we use the aux data to keep a list of the start addresses
12482 		 * of the JITed images for each function in the program
12483 		 *
12484 		 * for some architectures, such as powerpc64, the imm field
12485 		 * might not be large enough to hold the offset of the start
12486 		 * address of the callee's JITed image from __bpf_call_base
12487 		 *
12488 		 * in such cases, we can lookup the start address of a callee
12489 		 * by using its subprog id, available from the off field of
12490 		 * the call instruction, as an index for this list
12491 		 */
12492 		func[i]->aux->func = func;
12493 		func[i]->aux->func_cnt = env->subprog_cnt;
12494 	}
12495 	for (i = 0; i < env->subprog_cnt; i++) {
12496 		old_bpf_func = func[i]->bpf_func;
12497 		tmp = bpf_int_jit_compile(func[i]);
12498 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12499 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12500 			err = -ENOTSUPP;
12501 			goto out_free;
12502 		}
12503 		cond_resched();
12504 	}
12505 
12506 	/* finally lock prog and jit images for all functions and
12507 	 * populate kallsysm
12508 	 */
12509 	for (i = 0; i < env->subprog_cnt; i++) {
12510 		bpf_prog_lock_ro(func[i]);
12511 		bpf_prog_kallsyms_add(func[i]);
12512 	}
12513 
12514 	/* Last step: make now unused interpreter insns from main
12515 	 * prog consistent for later dump requests, so they can
12516 	 * later look the same as if they were interpreted only.
12517 	 */
12518 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12519 		if (bpf_pseudo_func(insn)) {
12520 			insn[0].imm = env->insn_aux_data[i].call_imm;
12521 			insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12522 			continue;
12523 		}
12524 		if (!bpf_pseudo_call(insn))
12525 			continue;
12526 		insn->off = env->insn_aux_data[i].call_imm;
12527 		subprog = find_subprog(env, i + insn->off + 1);
12528 		insn->imm = subprog;
12529 	}
12530 
12531 	prog->jited = 1;
12532 	prog->bpf_func = func[0]->bpf_func;
12533 	prog->aux->func = func;
12534 	prog->aux->func_cnt = env->subprog_cnt;
12535 	bpf_prog_jit_attempt_done(prog);
12536 	return 0;
12537 out_free:
12538 	/* We failed JIT'ing, so at this point we need to unregister poke
12539 	 * descriptors from subprogs, so that kernel is not attempting to
12540 	 * patch it anymore as we're freeing the subprog JIT memory.
12541 	 */
12542 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12543 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12544 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12545 	}
12546 	/* At this point we're guaranteed that poke descriptors are not
12547 	 * live anymore. We can just unlink its descriptor table as it's
12548 	 * released with the main prog.
12549 	 */
12550 	for (i = 0; i < env->subprog_cnt; i++) {
12551 		if (!func[i])
12552 			continue;
12553 		func[i]->aux->poke_tab = NULL;
12554 		bpf_jit_free(func[i]);
12555 	}
12556 	kfree(func);
12557 out_undo_insn:
12558 	/* cleanup main prog to be interpreted */
12559 	prog->jit_requested = 0;
12560 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12561 		if (!bpf_pseudo_call(insn))
12562 			continue;
12563 		insn->off = 0;
12564 		insn->imm = env->insn_aux_data[i].call_imm;
12565 	}
12566 	bpf_prog_jit_attempt_done(prog);
12567 	return err;
12568 }
12569 
12570 static int fixup_call_args(struct bpf_verifier_env *env)
12571 {
12572 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12573 	struct bpf_prog *prog = env->prog;
12574 	struct bpf_insn *insn = prog->insnsi;
12575 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12576 	int i, depth;
12577 #endif
12578 	int err = 0;
12579 
12580 	if (env->prog->jit_requested &&
12581 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12582 		err = jit_subprogs(env);
12583 		if (err == 0)
12584 			return 0;
12585 		if (err == -EFAULT)
12586 			return err;
12587 	}
12588 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12589 	if (has_kfunc_call) {
12590 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12591 		return -EINVAL;
12592 	}
12593 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12594 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12595 		 * have to be rejected, since interpreter doesn't support them yet.
12596 		 */
12597 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12598 		return -EINVAL;
12599 	}
12600 	for (i = 0; i < prog->len; i++, insn++) {
12601 		if (bpf_pseudo_func(insn)) {
12602 			/* When JIT fails the progs with callback calls
12603 			 * have to be rejected, since interpreter doesn't support them yet.
12604 			 */
12605 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12606 			return -EINVAL;
12607 		}
12608 
12609 		if (!bpf_pseudo_call(insn))
12610 			continue;
12611 		depth = get_callee_stack_depth(env, insn, i);
12612 		if (depth < 0)
12613 			return depth;
12614 		bpf_patch_call_args(insn, depth);
12615 	}
12616 	err = 0;
12617 #endif
12618 	return err;
12619 }
12620 
12621 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12622 			    struct bpf_insn *insn)
12623 {
12624 	const struct bpf_kfunc_desc *desc;
12625 
12626 	/* insn->imm has the btf func_id. Replace it with
12627 	 * an address (relative to __bpf_base_call).
12628 	 */
12629 	desc = find_kfunc_desc(env->prog, insn->imm);
12630 	if (!desc) {
12631 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12632 			insn->imm);
12633 		return -EFAULT;
12634 	}
12635 
12636 	insn->imm = desc->imm;
12637 
12638 	return 0;
12639 }
12640 
12641 /* Do various post-verification rewrites in a single program pass.
12642  * These rewrites simplify JIT and interpreter implementations.
12643  */
12644 static int do_misc_fixups(struct bpf_verifier_env *env)
12645 {
12646 	struct bpf_prog *prog = env->prog;
12647 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12648 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12649 	struct bpf_insn *insn = prog->insnsi;
12650 	const struct bpf_func_proto *fn;
12651 	const int insn_cnt = prog->len;
12652 	const struct bpf_map_ops *ops;
12653 	struct bpf_insn_aux_data *aux;
12654 	struct bpf_insn insn_buf[16];
12655 	struct bpf_prog *new_prog;
12656 	struct bpf_map *map_ptr;
12657 	int i, ret, cnt, delta = 0;
12658 
12659 	for (i = 0; i < insn_cnt; i++, insn++) {
12660 		/* Make divide-by-zero exceptions impossible. */
12661 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12662 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12663 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12664 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12665 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12666 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12667 			struct bpf_insn *patchlet;
12668 			struct bpf_insn chk_and_div[] = {
12669 				/* [R,W]x div 0 -> 0 */
12670 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12671 					     BPF_JNE | BPF_K, insn->src_reg,
12672 					     0, 2, 0),
12673 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12674 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12675 				*insn,
12676 			};
12677 			struct bpf_insn chk_and_mod[] = {
12678 				/* [R,W]x mod 0 -> [R,W]x */
12679 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12680 					     BPF_JEQ | BPF_K, insn->src_reg,
12681 					     0, 1 + (is64 ? 0 : 1), 0),
12682 				*insn,
12683 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12684 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12685 			};
12686 
12687 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12688 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12689 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12690 
12691 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12692 			if (!new_prog)
12693 				return -ENOMEM;
12694 
12695 			delta    += cnt - 1;
12696 			env->prog = prog = new_prog;
12697 			insn      = new_prog->insnsi + i + delta;
12698 			continue;
12699 		}
12700 
12701 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12702 		if (BPF_CLASS(insn->code) == BPF_LD &&
12703 		    (BPF_MODE(insn->code) == BPF_ABS ||
12704 		     BPF_MODE(insn->code) == BPF_IND)) {
12705 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12706 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12707 				verbose(env, "bpf verifier is misconfigured\n");
12708 				return -EINVAL;
12709 			}
12710 
12711 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12712 			if (!new_prog)
12713 				return -ENOMEM;
12714 
12715 			delta    += cnt - 1;
12716 			env->prog = prog = new_prog;
12717 			insn      = new_prog->insnsi + i + delta;
12718 			continue;
12719 		}
12720 
12721 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12722 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12723 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12724 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12725 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12726 			struct bpf_insn *patch = &insn_buf[0];
12727 			bool issrc, isneg, isimm;
12728 			u32 off_reg;
12729 
12730 			aux = &env->insn_aux_data[i + delta];
12731 			if (!aux->alu_state ||
12732 			    aux->alu_state == BPF_ALU_NON_POINTER)
12733 				continue;
12734 
12735 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12736 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12737 				BPF_ALU_SANITIZE_SRC;
12738 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12739 
12740 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12741 			if (isimm) {
12742 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12743 			} else {
12744 				if (isneg)
12745 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12746 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12747 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12748 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12749 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12750 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12751 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12752 			}
12753 			if (!issrc)
12754 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12755 			insn->src_reg = BPF_REG_AX;
12756 			if (isneg)
12757 				insn->code = insn->code == code_add ?
12758 					     code_sub : code_add;
12759 			*patch++ = *insn;
12760 			if (issrc && isneg && !isimm)
12761 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12762 			cnt = patch - insn_buf;
12763 
12764 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12765 			if (!new_prog)
12766 				return -ENOMEM;
12767 
12768 			delta    += cnt - 1;
12769 			env->prog = prog = new_prog;
12770 			insn      = new_prog->insnsi + i + delta;
12771 			continue;
12772 		}
12773 
12774 		if (insn->code != (BPF_JMP | BPF_CALL))
12775 			continue;
12776 		if (insn->src_reg == BPF_PSEUDO_CALL)
12777 			continue;
12778 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12779 			ret = fixup_kfunc_call(env, insn);
12780 			if (ret)
12781 				return ret;
12782 			continue;
12783 		}
12784 
12785 		if (insn->imm == BPF_FUNC_get_route_realm)
12786 			prog->dst_needed = 1;
12787 		if (insn->imm == BPF_FUNC_get_prandom_u32)
12788 			bpf_user_rnd_init_once();
12789 		if (insn->imm == BPF_FUNC_override_return)
12790 			prog->kprobe_override = 1;
12791 		if (insn->imm == BPF_FUNC_tail_call) {
12792 			/* If we tail call into other programs, we
12793 			 * cannot make any assumptions since they can
12794 			 * be replaced dynamically during runtime in
12795 			 * the program array.
12796 			 */
12797 			prog->cb_access = 1;
12798 			if (!allow_tail_call_in_subprogs(env))
12799 				prog->aux->stack_depth = MAX_BPF_STACK;
12800 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12801 
12802 			/* mark bpf_tail_call as different opcode to avoid
12803 			 * conditional branch in the interpreter for every normal
12804 			 * call and to prevent accidental JITing by JIT compiler
12805 			 * that doesn't support bpf_tail_call yet
12806 			 */
12807 			insn->imm = 0;
12808 			insn->code = BPF_JMP | BPF_TAIL_CALL;
12809 
12810 			aux = &env->insn_aux_data[i + delta];
12811 			if (env->bpf_capable && !expect_blinding &&
12812 			    prog->jit_requested &&
12813 			    !bpf_map_key_poisoned(aux) &&
12814 			    !bpf_map_ptr_poisoned(aux) &&
12815 			    !bpf_map_ptr_unpriv(aux)) {
12816 				struct bpf_jit_poke_descriptor desc = {
12817 					.reason = BPF_POKE_REASON_TAIL_CALL,
12818 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12819 					.tail_call.key = bpf_map_key_immediate(aux),
12820 					.insn_idx = i + delta,
12821 				};
12822 
12823 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
12824 				if (ret < 0) {
12825 					verbose(env, "adding tail call poke descriptor failed\n");
12826 					return ret;
12827 				}
12828 
12829 				insn->imm = ret + 1;
12830 				continue;
12831 			}
12832 
12833 			if (!bpf_map_ptr_unpriv(aux))
12834 				continue;
12835 
12836 			/* instead of changing every JIT dealing with tail_call
12837 			 * emit two extra insns:
12838 			 * if (index >= max_entries) goto out;
12839 			 * index &= array->index_mask;
12840 			 * to avoid out-of-bounds cpu speculation
12841 			 */
12842 			if (bpf_map_ptr_poisoned(aux)) {
12843 				verbose(env, "tail_call abusing map_ptr\n");
12844 				return -EINVAL;
12845 			}
12846 
12847 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12848 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12849 						  map_ptr->max_entries, 2);
12850 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12851 						    container_of(map_ptr,
12852 								 struct bpf_array,
12853 								 map)->index_mask);
12854 			insn_buf[2] = *insn;
12855 			cnt = 3;
12856 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12857 			if (!new_prog)
12858 				return -ENOMEM;
12859 
12860 			delta    += cnt - 1;
12861 			env->prog = prog = new_prog;
12862 			insn      = new_prog->insnsi + i + delta;
12863 			continue;
12864 		}
12865 
12866 		if (insn->imm == BPF_FUNC_timer_set_callback) {
12867 			/* The verifier will process callback_fn as many times as necessary
12868 			 * with different maps and the register states prepared by
12869 			 * set_timer_callback_state will be accurate.
12870 			 *
12871 			 * The following use case is valid:
12872 			 *   map1 is shared by prog1, prog2, prog3.
12873 			 *   prog1 calls bpf_timer_init for some map1 elements
12874 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
12875 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
12876 			 *   prog3 calls bpf_timer_start for some map1 elements.
12877 			 *     Those that were not both bpf_timer_init-ed and
12878 			 *     bpf_timer_set_callback-ed will return -EINVAL.
12879 			 */
12880 			struct bpf_insn ld_addrs[2] = {
12881 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
12882 			};
12883 
12884 			insn_buf[0] = ld_addrs[0];
12885 			insn_buf[1] = ld_addrs[1];
12886 			insn_buf[2] = *insn;
12887 			cnt = 3;
12888 
12889 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12890 			if (!new_prog)
12891 				return -ENOMEM;
12892 
12893 			delta    += cnt - 1;
12894 			env->prog = prog = new_prog;
12895 			insn      = new_prog->insnsi + i + delta;
12896 			goto patch_call_imm;
12897 		}
12898 
12899 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12900 		 * and other inlining handlers are currently limited to 64 bit
12901 		 * only.
12902 		 */
12903 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
12904 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
12905 		     insn->imm == BPF_FUNC_map_update_elem ||
12906 		     insn->imm == BPF_FUNC_map_delete_elem ||
12907 		     insn->imm == BPF_FUNC_map_push_elem   ||
12908 		     insn->imm == BPF_FUNC_map_pop_elem    ||
12909 		     insn->imm == BPF_FUNC_map_peek_elem   ||
12910 		     insn->imm == BPF_FUNC_redirect_map)) {
12911 			aux = &env->insn_aux_data[i + delta];
12912 			if (bpf_map_ptr_poisoned(aux))
12913 				goto patch_call_imm;
12914 
12915 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12916 			ops = map_ptr->ops;
12917 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
12918 			    ops->map_gen_lookup) {
12919 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12920 				if (cnt == -EOPNOTSUPP)
12921 					goto patch_map_ops_generic;
12922 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12923 					verbose(env, "bpf verifier is misconfigured\n");
12924 					return -EINVAL;
12925 				}
12926 
12927 				new_prog = bpf_patch_insn_data(env, i + delta,
12928 							       insn_buf, cnt);
12929 				if (!new_prog)
12930 					return -ENOMEM;
12931 
12932 				delta    += cnt - 1;
12933 				env->prog = prog = new_prog;
12934 				insn      = new_prog->insnsi + i + delta;
12935 				continue;
12936 			}
12937 
12938 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12939 				     (void *(*)(struct bpf_map *map, void *key))NULL));
12940 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12941 				     (int (*)(struct bpf_map *map, void *key))NULL));
12942 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12943 				     (int (*)(struct bpf_map *map, void *key, void *value,
12944 					      u64 flags))NULL));
12945 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12946 				     (int (*)(struct bpf_map *map, void *value,
12947 					      u64 flags))NULL));
12948 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12949 				     (int (*)(struct bpf_map *map, void *value))NULL));
12950 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12951 				     (int (*)(struct bpf_map *map, void *value))NULL));
12952 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
12953 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12954 
12955 patch_map_ops_generic:
12956 			switch (insn->imm) {
12957 			case BPF_FUNC_map_lookup_elem:
12958 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12959 					    __bpf_call_base;
12960 				continue;
12961 			case BPF_FUNC_map_update_elem:
12962 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12963 					    __bpf_call_base;
12964 				continue;
12965 			case BPF_FUNC_map_delete_elem:
12966 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12967 					    __bpf_call_base;
12968 				continue;
12969 			case BPF_FUNC_map_push_elem:
12970 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12971 					    __bpf_call_base;
12972 				continue;
12973 			case BPF_FUNC_map_pop_elem:
12974 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12975 					    __bpf_call_base;
12976 				continue;
12977 			case BPF_FUNC_map_peek_elem:
12978 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12979 					    __bpf_call_base;
12980 				continue;
12981 			case BPF_FUNC_redirect_map:
12982 				insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12983 					    __bpf_call_base;
12984 				continue;
12985 			}
12986 
12987 			goto patch_call_imm;
12988 		}
12989 
12990 		/* Implement bpf_jiffies64 inline. */
12991 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
12992 		    insn->imm == BPF_FUNC_jiffies64) {
12993 			struct bpf_insn ld_jiffies_addr[2] = {
12994 				BPF_LD_IMM64(BPF_REG_0,
12995 					     (unsigned long)&jiffies),
12996 			};
12997 
12998 			insn_buf[0] = ld_jiffies_addr[0];
12999 			insn_buf[1] = ld_jiffies_addr[1];
13000 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13001 						  BPF_REG_0, 0);
13002 			cnt = 3;
13003 
13004 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13005 						       cnt);
13006 			if (!new_prog)
13007 				return -ENOMEM;
13008 
13009 			delta    += cnt - 1;
13010 			env->prog = prog = new_prog;
13011 			insn      = new_prog->insnsi + i + delta;
13012 			continue;
13013 		}
13014 
13015 		/* Implement bpf_get_func_ip inline. */
13016 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13017 		    insn->imm == BPF_FUNC_get_func_ip) {
13018 			/* Load IP address from ctx - 8 */
13019 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13020 
13021 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13022 			if (!new_prog)
13023 				return -ENOMEM;
13024 
13025 			env->prog = prog = new_prog;
13026 			insn      = new_prog->insnsi + i + delta;
13027 			continue;
13028 		}
13029 
13030 patch_call_imm:
13031 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13032 		/* all functions that have prototype and verifier allowed
13033 		 * programs to call them, must be real in-kernel functions
13034 		 */
13035 		if (!fn->func) {
13036 			verbose(env,
13037 				"kernel subsystem misconfigured func %s#%d\n",
13038 				func_id_name(insn->imm), insn->imm);
13039 			return -EFAULT;
13040 		}
13041 		insn->imm = fn->func - __bpf_call_base;
13042 	}
13043 
13044 	/* Since poke tab is now finalized, publish aux to tracker. */
13045 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13046 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13047 		if (!map_ptr->ops->map_poke_track ||
13048 		    !map_ptr->ops->map_poke_untrack ||
13049 		    !map_ptr->ops->map_poke_run) {
13050 			verbose(env, "bpf verifier is misconfigured\n");
13051 			return -EINVAL;
13052 		}
13053 
13054 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13055 		if (ret < 0) {
13056 			verbose(env, "tracking tail call prog failed\n");
13057 			return ret;
13058 		}
13059 	}
13060 
13061 	sort_kfunc_descs_by_imm(env->prog);
13062 
13063 	return 0;
13064 }
13065 
13066 static void free_states(struct bpf_verifier_env *env)
13067 {
13068 	struct bpf_verifier_state_list *sl, *sln;
13069 	int i;
13070 
13071 	sl = env->free_list;
13072 	while (sl) {
13073 		sln = sl->next;
13074 		free_verifier_state(&sl->state, false);
13075 		kfree(sl);
13076 		sl = sln;
13077 	}
13078 	env->free_list = NULL;
13079 
13080 	if (!env->explored_states)
13081 		return;
13082 
13083 	for (i = 0; i < state_htab_size(env); i++) {
13084 		sl = env->explored_states[i];
13085 
13086 		while (sl) {
13087 			sln = sl->next;
13088 			free_verifier_state(&sl->state, false);
13089 			kfree(sl);
13090 			sl = sln;
13091 		}
13092 		env->explored_states[i] = NULL;
13093 	}
13094 }
13095 
13096 /* The verifier is using insn_aux_data[] to store temporary data during
13097  * verification and to store information for passes that run after the
13098  * verification like dead code sanitization. do_check_common() for subprogram N
13099  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
13100  * temporary data after do_check_common() finds that subprogram N cannot be
13101  * verified independently. pass_cnt counts the number of times
13102  * do_check_common() was run and insn->aux->seen tells the pass number
13103  * insn_aux_data was touched. These variables are compared to clear temporary
13104  * data from failed pass. For testing and experiments do_check_common() can be
13105  * run multiple times even when prior attempt to verify is unsuccessful.
13106  *
13107  * Note that special handling is needed on !env->bypass_spec_v1 if this is
13108  * ever called outside of error path with subsequent program rejection.
13109  */
13110 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
13111 {
13112 	struct bpf_insn *insn = env->prog->insnsi;
13113 	struct bpf_insn_aux_data *aux;
13114 	int i, class;
13115 
13116 	for (i = 0; i < env->prog->len; i++) {
13117 		class = BPF_CLASS(insn[i].code);
13118 		if (class != BPF_LDX && class != BPF_STX)
13119 			continue;
13120 		aux = &env->insn_aux_data[i];
13121 		if (aux->seen != env->pass_cnt)
13122 			continue;
13123 		memset(aux, 0, offsetof(typeof(*aux), orig_idx));
13124 	}
13125 }
13126 
13127 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13128 {
13129 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13130 	struct bpf_verifier_state *state;
13131 	struct bpf_reg_state *regs;
13132 	int ret, i;
13133 
13134 	env->prev_linfo = NULL;
13135 	env->pass_cnt++;
13136 
13137 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13138 	if (!state)
13139 		return -ENOMEM;
13140 	state->curframe = 0;
13141 	state->speculative = false;
13142 	state->branches = 1;
13143 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13144 	if (!state->frame[0]) {
13145 		kfree(state);
13146 		return -ENOMEM;
13147 	}
13148 	env->cur_state = state;
13149 	init_func_state(env, state->frame[0],
13150 			BPF_MAIN_FUNC /* callsite */,
13151 			0 /* frameno */,
13152 			subprog);
13153 
13154 	regs = state->frame[state->curframe]->regs;
13155 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13156 		ret = btf_prepare_func_args(env, subprog, regs);
13157 		if (ret)
13158 			goto out;
13159 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13160 			if (regs[i].type == PTR_TO_CTX)
13161 				mark_reg_known_zero(env, regs, i);
13162 			else if (regs[i].type == SCALAR_VALUE)
13163 				mark_reg_unknown(env, regs, i);
13164 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13165 				const u32 mem_size = regs[i].mem_size;
13166 
13167 				mark_reg_known_zero(env, regs, i);
13168 				regs[i].mem_size = mem_size;
13169 				regs[i].id = ++env->id_gen;
13170 			}
13171 		}
13172 	} else {
13173 		/* 1st arg to a function */
13174 		regs[BPF_REG_1].type = PTR_TO_CTX;
13175 		mark_reg_known_zero(env, regs, BPF_REG_1);
13176 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13177 		if (ret == -EFAULT)
13178 			/* unlikely verifier bug. abort.
13179 			 * ret == 0 and ret < 0 are sadly acceptable for
13180 			 * main() function due to backward compatibility.
13181 			 * Like socket filter program may be written as:
13182 			 * int bpf_prog(struct pt_regs *ctx)
13183 			 * and never dereference that ctx in the program.
13184 			 * 'struct pt_regs' is a type mismatch for socket
13185 			 * filter that should be using 'struct __sk_buff'.
13186 			 */
13187 			goto out;
13188 	}
13189 
13190 	ret = do_check(env);
13191 out:
13192 	/* check for NULL is necessary, since cur_state can be freed inside
13193 	 * do_check() under memory pressure.
13194 	 */
13195 	if (env->cur_state) {
13196 		free_verifier_state(env->cur_state, true);
13197 		env->cur_state = NULL;
13198 	}
13199 	while (!pop_stack(env, NULL, NULL, false));
13200 	if (!ret && pop_log)
13201 		bpf_vlog_reset(&env->log, 0);
13202 	free_states(env);
13203 	if (ret)
13204 		/* clean aux data in case subprog was rejected */
13205 		sanitize_insn_aux_data(env);
13206 	return ret;
13207 }
13208 
13209 /* Verify all global functions in a BPF program one by one based on their BTF.
13210  * All global functions must pass verification. Otherwise the whole program is rejected.
13211  * Consider:
13212  * int bar(int);
13213  * int foo(int f)
13214  * {
13215  *    return bar(f);
13216  * }
13217  * int bar(int b)
13218  * {
13219  *    ...
13220  * }
13221  * foo() will be verified first for R1=any_scalar_value. During verification it
13222  * will be assumed that bar() already verified successfully and call to bar()
13223  * from foo() will be checked for type match only. Later bar() will be verified
13224  * independently to check that it's safe for R1=any_scalar_value.
13225  */
13226 static int do_check_subprogs(struct bpf_verifier_env *env)
13227 {
13228 	struct bpf_prog_aux *aux = env->prog->aux;
13229 	int i, ret;
13230 
13231 	if (!aux->func_info)
13232 		return 0;
13233 
13234 	for (i = 1; i < env->subprog_cnt; i++) {
13235 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13236 			continue;
13237 		env->insn_idx = env->subprog_info[i].start;
13238 		WARN_ON_ONCE(env->insn_idx == 0);
13239 		ret = do_check_common(env, i);
13240 		if (ret) {
13241 			return ret;
13242 		} else if (env->log.level & BPF_LOG_LEVEL) {
13243 			verbose(env,
13244 				"Func#%d is safe for any args that match its prototype\n",
13245 				i);
13246 		}
13247 	}
13248 	return 0;
13249 }
13250 
13251 static int do_check_main(struct bpf_verifier_env *env)
13252 {
13253 	int ret;
13254 
13255 	env->insn_idx = 0;
13256 	ret = do_check_common(env, 0);
13257 	if (!ret)
13258 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13259 	return ret;
13260 }
13261 
13262 
13263 static void print_verification_stats(struct bpf_verifier_env *env)
13264 {
13265 	int i;
13266 
13267 	if (env->log.level & BPF_LOG_STATS) {
13268 		verbose(env, "verification time %lld usec\n",
13269 			div_u64(env->verification_time, 1000));
13270 		verbose(env, "stack depth ");
13271 		for (i = 0; i < env->subprog_cnt; i++) {
13272 			u32 depth = env->subprog_info[i].stack_depth;
13273 
13274 			verbose(env, "%d", depth);
13275 			if (i + 1 < env->subprog_cnt)
13276 				verbose(env, "+");
13277 		}
13278 		verbose(env, "\n");
13279 	}
13280 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13281 		"total_states %d peak_states %d mark_read %d\n",
13282 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13283 		env->max_states_per_insn, env->total_states,
13284 		env->peak_states, env->longest_mark_read_walk);
13285 }
13286 
13287 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13288 {
13289 	const struct btf_type *t, *func_proto;
13290 	const struct bpf_struct_ops *st_ops;
13291 	const struct btf_member *member;
13292 	struct bpf_prog *prog = env->prog;
13293 	u32 btf_id, member_idx;
13294 	const char *mname;
13295 
13296 	if (!prog->gpl_compatible) {
13297 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13298 		return -EINVAL;
13299 	}
13300 
13301 	btf_id = prog->aux->attach_btf_id;
13302 	st_ops = bpf_struct_ops_find(btf_id);
13303 	if (!st_ops) {
13304 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13305 			btf_id);
13306 		return -ENOTSUPP;
13307 	}
13308 
13309 	t = st_ops->type;
13310 	member_idx = prog->expected_attach_type;
13311 	if (member_idx >= btf_type_vlen(t)) {
13312 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13313 			member_idx, st_ops->name);
13314 		return -EINVAL;
13315 	}
13316 
13317 	member = &btf_type_member(t)[member_idx];
13318 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13319 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13320 					       NULL);
13321 	if (!func_proto) {
13322 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13323 			mname, member_idx, st_ops->name);
13324 		return -EINVAL;
13325 	}
13326 
13327 	if (st_ops->check_member) {
13328 		int err = st_ops->check_member(t, member);
13329 
13330 		if (err) {
13331 			verbose(env, "attach to unsupported member %s of struct %s\n",
13332 				mname, st_ops->name);
13333 			return err;
13334 		}
13335 	}
13336 
13337 	prog->aux->attach_func_proto = func_proto;
13338 	prog->aux->attach_func_name = mname;
13339 	env->ops = st_ops->verifier_ops;
13340 
13341 	return 0;
13342 }
13343 #define SECURITY_PREFIX "security_"
13344 
13345 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13346 {
13347 	if (within_error_injection_list(addr) ||
13348 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13349 		return 0;
13350 
13351 	return -EINVAL;
13352 }
13353 
13354 /* list of non-sleepable functions that are otherwise on
13355  * ALLOW_ERROR_INJECTION list
13356  */
13357 BTF_SET_START(btf_non_sleepable_error_inject)
13358 /* Three functions below can be called from sleepable and non-sleepable context.
13359  * Assume non-sleepable from bpf safety point of view.
13360  */
13361 BTF_ID(func, __add_to_page_cache_locked)
13362 BTF_ID(func, should_fail_alloc_page)
13363 BTF_ID(func, should_failslab)
13364 BTF_SET_END(btf_non_sleepable_error_inject)
13365 
13366 static int check_non_sleepable_error_inject(u32 btf_id)
13367 {
13368 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13369 }
13370 
13371 int bpf_check_attach_target(struct bpf_verifier_log *log,
13372 			    const struct bpf_prog *prog,
13373 			    const struct bpf_prog *tgt_prog,
13374 			    u32 btf_id,
13375 			    struct bpf_attach_target_info *tgt_info)
13376 {
13377 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13378 	const char prefix[] = "btf_trace_";
13379 	int ret = 0, subprog = -1, i;
13380 	const struct btf_type *t;
13381 	bool conservative = true;
13382 	const char *tname;
13383 	struct btf *btf;
13384 	long addr = 0;
13385 
13386 	if (!btf_id) {
13387 		bpf_log(log, "Tracing programs must provide btf_id\n");
13388 		return -EINVAL;
13389 	}
13390 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13391 	if (!btf) {
13392 		bpf_log(log,
13393 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13394 		return -EINVAL;
13395 	}
13396 	t = btf_type_by_id(btf, btf_id);
13397 	if (!t) {
13398 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13399 		return -EINVAL;
13400 	}
13401 	tname = btf_name_by_offset(btf, t->name_off);
13402 	if (!tname) {
13403 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13404 		return -EINVAL;
13405 	}
13406 	if (tgt_prog) {
13407 		struct bpf_prog_aux *aux = tgt_prog->aux;
13408 
13409 		for (i = 0; i < aux->func_info_cnt; i++)
13410 			if (aux->func_info[i].type_id == btf_id) {
13411 				subprog = i;
13412 				break;
13413 			}
13414 		if (subprog == -1) {
13415 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13416 			return -EINVAL;
13417 		}
13418 		conservative = aux->func_info_aux[subprog].unreliable;
13419 		if (prog_extension) {
13420 			if (conservative) {
13421 				bpf_log(log,
13422 					"Cannot replace static functions\n");
13423 				return -EINVAL;
13424 			}
13425 			if (!prog->jit_requested) {
13426 				bpf_log(log,
13427 					"Extension programs should be JITed\n");
13428 				return -EINVAL;
13429 			}
13430 		}
13431 		if (!tgt_prog->jited) {
13432 			bpf_log(log, "Can attach to only JITed progs\n");
13433 			return -EINVAL;
13434 		}
13435 		if (tgt_prog->type == prog->type) {
13436 			/* Cannot fentry/fexit another fentry/fexit program.
13437 			 * Cannot attach program extension to another extension.
13438 			 * It's ok to attach fentry/fexit to extension program.
13439 			 */
13440 			bpf_log(log, "Cannot recursively attach\n");
13441 			return -EINVAL;
13442 		}
13443 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13444 		    prog_extension &&
13445 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13446 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13447 			/* Program extensions can extend all program types
13448 			 * except fentry/fexit. The reason is the following.
13449 			 * The fentry/fexit programs are used for performance
13450 			 * analysis, stats and can be attached to any program
13451 			 * type except themselves. When extension program is
13452 			 * replacing XDP function it is necessary to allow
13453 			 * performance analysis of all functions. Both original
13454 			 * XDP program and its program extension. Hence
13455 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13456 			 * allowed. If extending of fentry/fexit was allowed it
13457 			 * would be possible to create long call chain
13458 			 * fentry->extension->fentry->extension beyond
13459 			 * reasonable stack size. Hence extending fentry is not
13460 			 * allowed.
13461 			 */
13462 			bpf_log(log, "Cannot extend fentry/fexit\n");
13463 			return -EINVAL;
13464 		}
13465 	} else {
13466 		if (prog_extension) {
13467 			bpf_log(log, "Cannot replace kernel functions\n");
13468 			return -EINVAL;
13469 		}
13470 	}
13471 
13472 	switch (prog->expected_attach_type) {
13473 	case BPF_TRACE_RAW_TP:
13474 		if (tgt_prog) {
13475 			bpf_log(log,
13476 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13477 			return -EINVAL;
13478 		}
13479 		if (!btf_type_is_typedef(t)) {
13480 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13481 				btf_id);
13482 			return -EINVAL;
13483 		}
13484 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13485 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13486 				btf_id, tname);
13487 			return -EINVAL;
13488 		}
13489 		tname += sizeof(prefix) - 1;
13490 		t = btf_type_by_id(btf, t->type);
13491 		if (!btf_type_is_ptr(t))
13492 			/* should never happen in valid vmlinux build */
13493 			return -EINVAL;
13494 		t = btf_type_by_id(btf, t->type);
13495 		if (!btf_type_is_func_proto(t))
13496 			/* should never happen in valid vmlinux build */
13497 			return -EINVAL;
13498 
13499 		break;
13500 	case BPF_TRACE_ITER:
13501 		if (!btf_type_is_func(t)) {
13502 			bpf_log(log, "attach_btf_id %u is not a function\n",
13503 				btf_id);
13504 			return -EINVAL;
13505 		}
13506 		t = btf_type_by_id(btf, t->type);
13507 		if (!btf_type_is_func_proto(t))
13508 			return -EINVAL;
13509 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13510 		if (ret)
13511 			return ret;
13512 		break;
13513 	default:
13514 		if (!prog_extension)
13515 			return -EINVAL;
13516 		fallthrough;
13517 	case BPF_MODIFY_RETURN:
13518 	case BPF_LSM_MAC:
13519 	case BPF_TRACE_FENTRY:
13520 	case BPF_TRACE_FEXIT:
13521 		if (!btf_type_is_func(t)) {
13522 			bpf_log(log, "attach_btf_id %u is not a function\n",
13523 				btf_id);
13524 			return -EINVAL;
13525 		}
13526 		if (prog_extension &&
13527 		    btf_check_type_match(log, prog, btf, t))
13528 			return -EINVAL;
13529 		t = btf_type_by_id(btf, t->type);
13530 		if (!btf_type_is_func_proto(t))
13531 			return -EINVAL;
13532 
13533 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13534 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13535 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13536 			return -EINVAL;
13537 
13538 		if (tgt_prog && conservative)
13539 			t = NULL;
13540 
13541 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13542 		if (ret < 0)
13543 			return ret;
13544 
13545 		if (tgt_prog) {
13546 			if (subprog == 0)
13547 				addr = (long) tgt_prog->bpf_func;
13548 			else
13549 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13550 		} else {
13551 			addr = kallsyms_lookup_name(tname);
13552 			if (!addr) {
13553 				bpf_log(log,
13554 					"The address of function %s cannot be found\n",
13555 					tname);
13556 				return -ENOENT;
13557 			}
13558 		}
13559 
13560 		if (prog->aux->sleepable) {
13561 			ret = -EINVAL;
13562 			switch (prog->type) {
13563 			case BPF_PROG_TYPE_TRACING:
13564 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13565 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13566 				 */
13567 				if (!check_non_sleepable_error_inject(btf_id) &&
13568 				    within_error_injection_list(addr))
13569 					ret = 0;
13570 				break;
13571 			case BPF_PROG_TYPE_LSM:
13572 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13573 				 * Only some of them are sleepable.
13574 				 */
13575 				if (bpf_lsm_is_sleepable_hook(btf_id))
13576 					ret = 0;
13577 				break;
13578 			default:
13579 				break;
13580 			}
13581 			if (ret) {
13582 				bpf_log(log, "%s is not sleepable\n", tname);
13583 				return ret;
13584 			}
13585 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13586 			if (tgt_prog) {
13587 				bpf_log(log, "can't modify return codes of BPF programs\n");
13588 				return -EINVAL;
13589 			}
13590 			ret = check_attach_modify_return(addr, tname);
13591 			if (ret) {
13592 				bpf_log(log, "%s() is not modifiable\n", tname);
13593 				return ret;
13594 			}
13595 		}
13596 
13597 		break;
13598 	}
13599 	tgt_info->tgt_addr = addr;
13600 	tgt_info->tgt_name = tname;
13601 	tgt_info->tgt_type = t;
13602 	return 0;
13603 }
13604 
13605 BTF_SET_START(btf_id_deny)
13606 BTF_ID_UNUSED
13607 #ifdef CONFIG_SMP
13608 BTF_ID(func, migrate_disable)
13609 BTF_ID(func, migrate_enable)
13610 #endif
13611 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13612 BTF_ID(func, rcu_read_unlock_strict)
13613 #endif
13614 BTF_SET_END(btf_id_deny)
13615 
13616 static int check_attach_btf_id(struct bpf_verifier_env *env)
13617 {
13618 	struct bpf_prog *prog = env->prog;
13619 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13620 	struct bpf_attach_target_info tgt_info = {};
13621 	u32 btf_id = prog->aux->attach_btf_id;
13622 	struct bpf_trampoline *tr;
13623 	int ret;
13624 	u64 key;
13625 
13626 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13627 		if (prog->aux->sleepable)
13628 			/* attach_btf_id checked to be zero already */
13629 			return 0;
13630 		verbose(env, "Syscall programs can only be sleepable\n");
13631 		return -EINVAL;
13632 	}
13633 
13634 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13635 	    prog->type != BPF_PROG_TYPE_LSM) {
13636 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13637 		return -EINVAL;
13638 	}
13639 
13640 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13641 		return check_struct_ops_btf_id(env);
13642 
13643 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13644 	    prog->type != BPF_PROG_TYPE_LSM &&
13645 	    prog->type != BPF_PROG_TYPE_EXT)
13646 		return 0;
13647 
13648 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13649 	if (ret)
13650 		return ret;
13651 
13652 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13653 		/* to make freplace equivalent to their targets, they need to
13654 		 * inherit env->ops and expected_attach_type for the rest of the
13655 		 * verification
13656 		 */
13657 		env->ops = bpf_verifier_ops[tgt_prog->type];
13658 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13659 	}
13660 
13661 	/* store info about the attachment target that will be used later */
13662 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13663 	prog->aux->attach_func_name = tgt_info.tgt_name;
13664 
13665 	if (tgt_prog) {
13666 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13667 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13668 	}
13669 
13670 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13671 		prog->aux->attach_btf_trace = true;
13672 		return 0;
13673 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13674 		if (!bpf_iter_prog_supported(prog))
13675 			return -EINVAL;
13676 		return 0;
13677 	}
13678 
13679 	if (prog->type == BPF_PROG_TYPE_LSM) {
13680 		ret = bpf_lsm_verify_prog(&env->log, prog);
13681 		if (ret < 0)
13682 			return ret;
13683 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13684 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13685 		return -EINVAL;
13686 	}
13687 
13688 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13689 	tr = bpf_trampoline_get(key, &tgt_info);
13690 	if (!tr)
13691 		return -ENOMEM;
13692 
13693 	prog->aux->dst_trampoline = tr;
13694 	return 0;
13695 }
13696 
13697 struct btf *bpf_get_btf_vmlinux(void)
13698 {
13699 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13700 		mutex_lock(&bpf_verifier_lock);
13701 		if (!btf_vmlinux)
13702 			btf_vmlinux = btf_parse_vmlinux();
13703 		mutex_unlock(&bpf_verifier_lock);
13704 	}
13705 	return btf_vmlinux;
13706 }
13707 
13708 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13709 {
13710 	u64 start_time = ktime_get_ns();
13711 	struct bpf_verifier_env *env;
13712 	struct bpf_verifier_log *log;
13713 	int i, len, ret = -EINVAL;
13714 	bool is_priv;
13715 
13716 	/* no program is valid */
13717 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13718 		return -EINVAL;
13719 
13720 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13721 	 * allocate/free it every time bpf_check() is called
13722 	 */
13723 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13724 	if (!env)
13725 		return -ENOMEM;
13726 	log = &env->log;
13727 
13728 	len = (*prog)->len;
13729 	env->insn_aux_data =
13730 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13731 	ret = -ENOMEM;
13732 	if (!env->insn_aux_data)
13733 		goto err_free_env;
13734 	for (i = 0; i < len; i++)
13735 		env->insn_aux_data[i].orig_idx = i;
13736 	env->prog = *prog;
13737 	env->ops = bpf_verifier_ops[env->prog->type];
13738 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13739 	is_priv = bpf_capable();
13740 
13741 	bpf_get_btf_vmlinux();
13742 
13743 	/* grab the mutex to protect few globals used by verifier */
13744 	if (!is_priv)
13745 		mutex_lock(&bpf_verifier_lock);
13746 
13747 	if (attr->log_level || attr->log_buf || attr->log_size) {
13748 		/* user requested verbose verifier output
13749 		 * and supplied buffer to store the verification trace
13750 		 */
13751 		log->level = attr->log_level;
13752 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13753 		log->len_total = attr->log_size;
13754 
13755 		ret = -EINVAL;
13756 		/* log attributes have to be sane */
13757 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13758 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13759 			goto err_unlock;
13760 	}
13761 
13762 	if (IS_ERR(btf_vmlinux)) {
13763 		/* Either gcc or pahole or kernel are broken. */
13764 		verbose(env, "in-kernel BTF is malformed\n");
13765 		ret = PTR_ERR(btf_vmlinux);
13766 		goto skip_full_check;
13767 	}
13768 
13769 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13770 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13771 		env->strict_alignment = true;
13772 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13773 		env->strict_alignment = false;
13774 
13775 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13776 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13777 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13778 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13779 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13780 	env->bpf_capable = bpf_capable();
13781 
13782 	if (is_priv)
13783 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13784 
13785 	env->explored_states = kvcalloc(state_htab_size(env),
13786 				       sizeof(struct bpf_verifier_state_list *),
13787 				       GFP_USER);
13788 	ret = -ENOMEM;
13789 	if (!env->explored_states)
13790 		goto skip_full_check;
13791 
13792 	ret = add_subprog_and_kfunc(env);
13793 	if (ret < 0)
13794 		goto skip_full_check;
13795 
13796 	ret = check_subprogs(env);
13797 	if (ret < 0)
13798 		goto skip_full_check;
13799 
13800 	ret = check_btf_info(env, attr, uattr);
13801 	if (ret < 0)
13802 		goto skip_full_check;
13803 
13804 	ret = check_attach_btf_id(env);
13805 	if (ret)
13806 		goto skip_full_check;
13807 
13808 	ret = resolve_pseudo_ldimm64(env);
13809 	if (ret < 0)
13810 		goto skip_full_check;
13811 
13812 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
13813 		ret = bpf_prog_offload_verifier_prep(env->prog);
13814 		if (ret)
13815 			goto skip_full_check;
13816 	}
13817 
13818 	ret = check_cfg(env);
13819 	if (ret < 0)
13820 		goto skip_full_check;
13821 
13822 	ret = do_check_subprogs(env);
13823 	ret = ret ?: do_check_main(env);
13824 
13825 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13826 		ret = bpf_prog_offload_finalize(env);
13827 
13828 skip_full_check:
13829 	kvfree(env->explored_states);
13830 
13831 	if (ret == 0)
13832 		ret = check_max_stack_depth(env);
13833 
13834 	/* instruction rewrites happen after this point */
13835 	if (is_priv) {
13836 		if (ret == 0)
13837 			opt_hard_wire_dead_code_branches(env);
13838 		if (ret == 0)
13839 			ret = opt_remove_dead_code(env);
13840 		if (ret == 0)
13841 			ret = opt_remove_nops(env);
13842 	} else {
13843 		if (ret == 0)
13844 			sanitize_dead_code(env);
13845 	}
13846 
13847 	if (ret == 0)
13848 		/* program is valid, convert *(u32*)(ctx + off) accesses */
13849 		ret = convert_ctx_accesses(env);
13850 
13851 	if (ret == 0)
13852 		ret = do_misc_fixups(env);
13853 
13854 	/* do 32-bit optimization after insn patching has done so those patched
13855 	 * insns could be handled correctly.
13856 	 */
13857 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13858 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13859 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13860 								     : false;
13861 	}
13862 
13863 	if (ret == 0)
13864 		ret = fixup_call_args(env);
13865 
13866 	env->verification_time = ktime_get_ns() - start_time;
13867 	print_verification_stats(env);
13868 
13869 	if (log->level && bpf_verifier_log_full(log))
13870 		ret = -ENOSPC;
13871 	if (log->level && !log->ubuf) {
13872 		ret = -EFAULT;
13873 		goto err_release_maps;
13874 	}
13875 
13876 	if (ret)
13877 		goto err_release_maps;
13878 
13879 	if (env->used_map_cnt) {
13880 		/* if program passed verifier, update used_maps in bpf_prog_info */
13881 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13882 							  sizeof(env->used_maps[0]),
13883 							  GFP_KERNEL);
13884 
13885 		if (!env->prog->aux->used_maps) {
13886 			ret = -ENOMEM;
13887 			goto err_release_maps;
13888 		}
13889 
13890 		memcpy(env->prog->aux->used_maps, env->used_maps,
13891 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
13892 		env->prog->aux->used_map_cnt = env->used_map_cnt;
13893 	}
13894 	if (env->used_btf_cnt) {
13895 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
13896 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13897 							  sizeof(env->used_btfs[0]),
13898 							  GFP_KERNEL);
13899 		if (!env->prog->aux->used_btfs) {
13900 			ret = -ENOMEM;
13901 			goto err_release_maps;
13902 		}
13903 
13904 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
13905 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13906 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13907 	}
13908 	if (env->used_map_cnt || env->used_btf_cnt) {
13909 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
13910 		 * bpf_ld_imm64 instructions
13911 		 */
13912 		convert_pseudo_ld_imm64(env);
13913 	}
13914 
13915 	adjust_btf_func(env);
13916 
13917 err_release_maps:
13918 	if (!env->prog->aux->used_maps)
13919 		/* if we didn't copy map pointers into bpf_prog_info, release
13920 		 * them now. Otherwise free_used_maps() will release them.
13921 		 */
13922 		release_maps(env);
13923 	if (!env->prog->aux->used_btfs)
13924 		release_btfs(env);
13925 
13926 	/* extension progs temporarily inherit the attach_type of their targets
13927 	   for verification purposes, so set it back to zero before returning
13928 	 */
13929 	if (env->prog->type == BPF_PROG_TYPE_EXT)
13930 		env->prog->expected_attach_type = 0;
13931 
13932 	*prog = env->prog;
13933 err_unlock:
13934 	if (!is_priv)
13935 		mutex_unlock(&bpf_verifier_lock);
13936 	vfree(env->insn_aux_data);
13937 err_free_env:
13938 	kfree(env);
13939 	return ret;
13940 }
13941