xref: /linux/kernel/bpf/verifier.c (revision 83216e3988cd196183542937c9bd58b279f946af)
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 pathes 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 ether 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 func_id;
259 	struct btf *btf;
260 	u32 btf_id;
261 	struct btf *ret_btf;
262 	u32 ret_btf_id;
263 	u32 subprogno;
264 };
265 
266 struct btf *btf_vmlinux;
267 
268 static DEFINE_MUTEX(bpf_verifier_lock);
269 
270 static const struct bpf_line_info *
271 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
272 {
273 	const struct bpf_line_info *linfo;
274 	const struct bpf_prog *prog;
275 	u32 i, nr_linfo;
276 
277 	prog = env->prog;
278 	nr_linfo = prog->aux->nr_linfo;
279 
280 	if (!nr_linfo || insn_off >= prog->len)
281 		return NULL;
282 
283 	linfo = prog->aux->linfo;
284 	for (i = 1; i < nr_linfo; i++)
285 		if (insn_off < linfo[i].insn_off)
286 			break;
287 
288 	return &linfo[i - 1];
289 }
290 
291 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
292 		       va_list args)
293 {
294 	unsigned int n;
295 
296 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
297 
298 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
299 		  "verifier log line truncated - local buffer too short\n");
300 
301 	n = min(log->len_total - log->len_used - 1, n);
302 	log->kbuf[n] = '\0';
303 
304 	if (log->level == BPF_LOG_KERNEL) {
305 		pr_err("BPF:%s\n", log->kbuf);
306 		return;
307 	}
308 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
309 		log->len_used += n;
310 	else
311 		log->ubuf = NULL;
312 }
313 
314 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
315 {
316 	char zero = 0;
317 
318 	if (!bpf_verifier_log_needed(log))
319 		return;
320 
321 	log->len_used = new_pos;
322 	if (put_user(zero, log->ubuf + new_pos))
323 		log->ubuf = NULL;
324 }
325 
326 /* log_level controls verbosity level of eBPF verifier.
327  * bpf_verifier_log_write() is used to dump the verification trace to the log,
328  * so the user can figure out what's wrong with the program
329  */
330 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
331 					   const char *fmt, ...)
332 {
333 	va_list args;
334 
335 	if (!bpf_verifier_log_needed(&env->log))
336 		return;
337 
338 	va_start(args, fmt);
339 	bpf_verifier_vlog(&env->log, fmt, args);
340 	va_end(args);
341 }
342 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
343 
344 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
345 {
346 	struct bpf_verifier_env *env = private_data;
347 	va_list args;
348 
349 	if (!bpf_verifier_log_needed(&env->log))
350 		return;
351 
352 	va_start(args, fmt);
353 	bpf_verifier_vlog(&env->log, fmt, args);
354 	va_end(args);
355 }
356 
357 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
358 			    const char *fmt, ...)
359 {
360 	va_list args;
361 
362 	if (!bpf_verifier_log_needed(log))
363 		return;
364 
365 	va_start(args, fmt);
366 	bpf_verifier_vlog(log, fmt, args);
367 	va_end(args);
368 }
369 
370 static const char *ltrim(const char *s)
371 {
372 	while (isspace(*s))
373 		s++;
374 
375 	return s;
376 }
377 
378 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
379 					 u32 insn_off,
380 					 const char *prefix_fmt, ...)
381 {
382 	const struct bpf_line_info *linfo;
383 
384 	if (!bpf_verifier_log_needed(&env->log))
385 		return;
386 
387 	linfo = find_linfo(env, insn_off);
388 	if (!linfo || linfo == env->prev_linfo)
389 		return;
390 
391 	if (prefix_fmt) {
392 		va_list args;
393 
394 		va_start(args, prefix_fmt);
395 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
396 		va_end(args);
397 	}
398 
399 	verbose(env, "%s\n",
400 		ltrim(btf_name_by_offset(env->prog->aux->btf,
401 					 linfo->line_off)));
402 
403 	env->prev_linfo = linfo;
404 }
405 
406 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
407 				   struct bpf_reg_state *reg,
408 				   struct tnum *range, const char *ctx,
409 				   const char *reg_name)
410 {
411 	char tn_buf[48];
412 
413 	verbose(env, "At %s the register %s ", ctx, reg_name);
414 	if (!tnum_is_unknown(reg->var_off)) {
415 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
416 		verbose(env, "has value %s", tn_buf);
417 	} else {
418 		verbose(env, "has unknown scalar value");
419 	}
420 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
421 	verbose(env, " should have been in %s\n", tn_buf);
422 }
423 
424 static bool type_is_pkt_pointer(enum bpf_reg_type type)
425 {
426 	return type == PTR_TO_PACKET ||
427 	       type == PTR_TO_PACKET_META;
428 }
429 
430 static bool type_is_sk_pointer(enum bpf_reg_type type)
431 {
432 	return type == PTR_TO_SOCKET ||
433 		type == PTR_TO_SOCK_COMMON ||
434 		type == PTR_TO_TCP_SOCK ||
435 		type == PTR_TO_XDP_SOCK;
436 }
437 
438 static bool reg_type_not_null(enum bpf_reg_type type)
439 {
440 	return type == PTR_TO_SOCKET ||
441 		type == PTR_TO_TCP_SOCK ||
442 		type == PTR_TO_MAP_VALUE ||
443 		type == PTR_TO_MAP_KEY ||
444 		type == PTR_TO_SOCK_COMMON;
445 }
446 
447 static bool reg_type_may_be_null(enum bpf_reg_type type)
448 {
449 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
450 	       type == PTR_TO_SOCKET_OR_NULL ||
451 	       type == PTR_TO_SOCK_COMMON_OR_NULL ||
452 	       type == PTR_TO_TCP_SOCK_OR_NULL ||
453 	       type == PTR_TO_BTF_ID_OR_NULL ||
454 	       type == PTR_TO_MEM_OR_NULL ||
455 	       type == PTR_TO_RDONLY_BUF_OR_NULL ||
456 	       type == PTR_TO_RDWR_BUF_OR_NULL;
457 }
458 
459 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
460 {
461 	return reg->type == PTR_TO_MAP_VALUE &&
462 		map_value_has_spin_lock(reg->map_ptr);
463 }
464 
465 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
466 {
467 	return type == PTR_TO_SOCKET ||
468 		type == PTR_TO_SOCKET_OR_NULL ||
469 		type == PTR_TO_TCP_SOCK ||
470 		type == PTR_TO_TCP_SOCK_OR_NULL ||
471 		type == PTR_TO_MEM ||
472 		type == PTR_TO_MEM_OR_NULL;
473 }
474 
475 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
476 {
477 	return type == ARG_PTR_TO_SOCK_COMMON;
478 }
479 
480 static bool arg_type_may_be_null(enum bpf_arg_type type)
481 {
482 	return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
483 	       type == ARG_PTR_TO_MEM_OR_NULL ||
484 	       type == ARG_PTR_TO_CTX_OR_NULL ||
485 	       type == ARG_PTR_TO_SOCKET_OR_NULL ||
486 	       type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
487 	       type == ARG_PTR_TO_STACK_OR_NULL;
488 }
489 
490 /* Determine whether the function releases some resources allocated by another
491  * function call. The first reference type argument will be assumed to be
492  * released by release_reference().
493  */
494 static bool is_release_function(enum bpf_func_id func_id)
495 {
496 	return func_id == BPF_FUNC_sk_release ||
497 	       func_id == BPF_FUNC_ringbuf_submit ||
498 	       func_id == BPF_FUNC_ringbuf_discard;
499 }
500 
501 static bool may_be_acquire_function(enum bpf_func_id func_id)
502 {
503 	return func_id == BPF_FUNC_sk_lookup_tcp ||
504 		func_id == BPF_FUNC_sk_lookup_udp ||
505 		func_id == BPF_FUNC_skc_lookup_tcp ||
506 		func_id == BPF_FUNC_map_lookup_elem ||
507 	        func_id == BPF_FUNC_ringbuf_reserve;
508 }
509 
510 static bool is_acquire_function(enum bpf_func_id func_id,
511 				const struct bpf_map *map)
512 {
513 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
514 
515 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
516 	    func_id == BPF_FUNC_sk_lookup_udp ||
517 	    func_id == BPF_FUNC_skc_lookup_tcp ||
518 	    func_id == BPF_FUNC_ringbuf_reserve)
519 		return true;
520 
521 	if (func_id == BPF_FUNC_map_lookup_elem &&
522 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
523 	     map_type == BPF_MAP_TYPE_SOCKHASH))
524 		return true;
525 
526 	return false;
527 }
528 
529 static bool is_ptr_cast_function(enum bpf_func_id func_id)
530 {
531 	return func_id == BPF_FUNC_tcp_sock ||
532 		func_id == BPF_FUNC_sk_fullsock ||
533 		func_id == BPF_FUNC_skc_to_tcp_sock ||
534 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
535 		func_id == BPF_FUNC_skc_to_udp6_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
541 {
542 	return BPF_CLASS(insn->code) == BPF_STX &&
543 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
544 	       insn->imm == BPF_CMPXCHG;
545 }
546 
547 /* string representation of 'enum bpf_reg_type' */
548 static const char * const reg_type_str[] = {
549 	[NOT_INIT]		= "?",
550 	[SCALAR_VALUE]		= "inv",
551 	[PTR_TO_CTX]		= "ctx",
552 	[CONST_PTR_TO_MAP]	= "map_ptr",
553 	[PTR_TO_MAP_VALUE]	= "map_value",
554 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
555 	[PTR_TO_STACK]		= "fp",
556 	[PTR_TO_PACKET]		= "pkt",
557 	[PTR_TO_PACKET_META]	= "pkt_meta",
558 	[PTR_TO_PACKET_END]	= "pkt_end",
559 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
560 	[PTR_TO_SOCKET]		= "sock",
561 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
562 	[PTR_TO_SOCK_COMMON]	= "sock_common",
563 	[PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
564 	[PTR_TO_TCP_SOCK]	= "tcp_sock",
565 	[PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
566 	[PTR_TO_TP_BUFFER]	= "tp_buffer",
567 	[PTR_TO_XDP_SOCK]	= "xdp_sock",
568 	[PTR_TO_BTF_ID]		= "ptr_",
569 	[PTR_TO_BTF_ID_OR_NULL]	= "ptr_or_null_",
570 	[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
571 	[PTR_TO_MEM]		= "mem",
572 	[PTR_TO_MEM_OR_NULL]	= "mem_or_null",
573 	[PTR_TO_RDONLY_BUF]	= "rdonly_buf",
574 	[PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
575 	[PTR_TO_RDWR_BUF]	= "rdwr_buf",
576 	[PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
577 	[PTR_TO_FUNC]		= "func",
578 	[PTR_TO_MAP_KEY]	= "map_key",
579 };
580 
581 static char slot_type_char[] = {
582 	[STACK_INVALID]	= '?',
583 	[STACK_SPILL]	= 'r',
584 	[STACK_MISC]	= 'm',
585 	[STACK_ZERO]	= '0',
586 };
587 
588 static void print_liveness(struct bpf_verifier_env *env,
589 			   enum bpf_reg_liveness live)
590 {
591 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
592 	    verbose(env, "_");
593 	if (live & REG_LIVE_READ)
594 		verbose(env, "r");
595 	if (live & REG_LIVE_WRITTEN)
596 		verbose(env, "w");
597 	if (live & REG_LIVE_DONE)
598 		verbose(env, "D");
599 }
600 
601 static struct bpf_func_state *func(struct bpf_verifier_env *env,
602 				   const struct bpf_reg_state *reg)
603 {
604 	struct bpf_verifier_state *cur = env->cur_state;
605 
606 	return cur->frame[reg->frameno];
607 }
608 
609 static const char *kernel_type_name(const struct btf* btf, u32 id)
610 {
611 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
612 }
613 
614 static void print_verifier_state(struct bpf_verifier_env *env,
615 				 const struct bpf_func_state *state)
616 {
617 	const struct bpf_reg_state *reg;
618 	enum bpf_reg_type t;
619 	int i;
620 
621 	if (state->frameno)
622 		verbose(env, " frame%d:", state->frameno);
623 	for (i = 0; i < MAX_BPF_REG; i++) {
624 		reg = &state->regs[i];
625 		t = reg->type;
626 		if (t == NOT_INIT)
627 			continue;
628 		verbose(env, " R%d", i);
629 		print_liveness(env, reg->live);
630 		verbose(env, "=%s", reg_type_str[t]);
631 		if (t == SCALAR_VALUE && reg->precise)
632 			verbose(env, "P");
633 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
634 		    tnum_is_const(reg->var_off)) {
635 			/* reg->off should be 0 for SCALAR_VALUE */
636 			verbose(env, "%lld", reg->var_off.value + reg->off);
637 		} else {
638 			if (t == PTR_TO_BTF_ID ||
639 			    t == PTR_TO_BTF_ID_OR_NULL ||
640 			    t == PTR_TO_PERCPU_BTF_ID)
641 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
642 			verbose(env, "(id=%d", reg->id);
643 			if (reg_type_may_be_refcounted_or_null(t))
644 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
645 			if (t != SCALAR_VALUE)
646 				verbose(env, ",off=%d", reg->off);
647 			if (type_is_pkt_pointer(t))
648 				verbose(env, ",r=%d", reg->range);
649 			else if (t == CONST_PTR_TO_MAP ||
650 				 t == PTR_TO_MAP_KEY ||
651 				 t == PTR_TO_MAP_VALUE ||
652 				 t == PTR_TO_MAP_VALUE_OR_NULL)
653 				verbose(env, ",ks=%d,vs=%d",
654 					reg->map_ptr->key_size,
655 					reg->map_ptr->value_size);
656 			if (tnum_is_const(reg->var_off)) {
657 				/* Typically an immediate SCALAR_VALUE, but
658 				 * could be a pointer whose offset is too big
659 				 * for reg->off
660 				 */
661 				verbose(env, ",imm=%llx", reg->var_off.value);
662 			} else {
663 				if (reg->smin_value != reg->umin_value &&
664 				    reg->smin_value != S64_MIN)
665 					verbose(env, ",smin_value=%lld",
666 						(long long)reg->smin_value);
667 				if (reg->smax_value != reg->umax_value &&
668 				    reg->smax_value != S64_MAX)
669 					verbose(env, ",smax_value=%lld",
670 						(long long)reg->smax_value);
671 				if (reg->umin_value != 0)
672 					verbose(env, ",umin_value=%llu",
673 						(unsigned long long)reg->umin_value);
674 				if (reg->umax_value != U64_MAX)
675 					verbose(env, ",umax_value=%llu",
676 						(unsigned long long)reg->umax_value);
677 				if (!tnum_is_unknown(reg->var_off)) {
678 					char tn_buf[48];
679 
680 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
681 					verbose(env, ",var_off=%s", tn_buf);
682 				}
683 				if (reg->s32_min_value != reg->smin_value &&
684 				    reg->s32_min_value != S32_MIN)
685 					verbose(env, ",s32_min_value=%d",
686 						(int)(reg->s32_min_value));
687 				if (reg->s32_max_value != reg->smax_value &&
688 				    reg->s32_max_value != S32_MAX)
689 					verbose(env, ",s32_max_value=%d",
690 						(int)(reg->s32_max_value));
691 				if (reg->u32_min_value != reg->umin_value &&
692 				    reg->u32_min_value != U32_MIN)
693 					verbose(env, ",u32_min_value=%d",
694 						(int)(reg->u32_min_value));
695 				if (reg->u32_max_value != reg->umax_value &&
696 				    reg->u32_max_value != U32_MAX)
697 					verbose(env, ",u32_max_value=%d",
698 						(int)(reg->u32_max_value));
699 			}
700 			verbose(env, ")");
701 		}
702 	}
703 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
704 		char types_buf[BPF_REG_SIZE + 1];
705 		bool valid = false;
706 		int j;
707 
708 		for (j = 0; j < BPF_REG_SIZE; j++) {
709 			if (state->stack[i].slot_type[j] != STACK_INVALID)
710 				valid = true;
711 			types_buf[j] = slot_type_char[
712 					state->stack[i].slot_type[j]];
713 		}
714 		types_buf[BPF_REG_SIZE] = 0;
715 		if (!valid)
716 			continue;
717 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
718 		print_liveness(env, state->stack[i].spilled_ptr.live);
719 		if (state->stack[i].slot_type[0] == STACK_SPILL) {
720 			reg = &state->stack[i].spilled_ptr;
721 			t = reg->type;
722 			verbose(env, "=%s", reg_type_str[t]);
723 			if (t == SCALAR_VALUE && reg->precise)
724 				verbose(env, "P");
725 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
726 				verbose(env, "%lld", reg->var_off.value + reg->off);
727 		} else {
728 			verbose(env, "=%s", types_buf);
729 		}
730 	}
731 	if (state->acquired_refs && state->refs[0].id) {
732 		verbose(env, " refs=%d", state->refs[0].id);
733 		for (i = 1; i < state->acquired_refs; i++)
734 			if (state->refs[i].id)
735 				verbose(env, ",%d", state->refs[i].id);
736 	}
737 	verbose(env, "\n");
738 }
739 
740 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
741 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
742 			       const struct bpf_func_state *src)	\
743 {									\
744 	if (!src->FIELD)						\
745 		return 0;						\
746 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
747 		/* internal bug, make state invalid to reject the program */ \
748 		memset(dst, 0, sizeof(*dst));				\
749 		return -EFAULT;						\
750 	}								\
751 	memcpy(dst->FIELD, src->FIELD,					\
752 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
753 	return 0;							\
754 }
755 /* copy_reference_state() */
756 COPY_STATE_FN(reference, acquired_refs, refs, 1)
757 /* copy_stack_state() */
758 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
759 #undef COPY_STATE_FN
760 
761 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
762 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
763 				  bool copy_old)			\
764 {									\
765 	u32 old_size = state->COUNT;					\
766 	struct bpf_##NAME##_state *new_##FIELD;				\
767 	int slot = size / SIZE;						\
768 									\
769 	if (size <= old_size || !size) {				\
770 		if (copy_old)						\
771 			return 0;					\
772 		state->COUNT = slot * SIZE;				\
773 		if (!size && old_size) {				\
774 			kfree(state->FIELD);				\
775 			state->FIELD = NULL;				\
776 		}							\
777 		return 0;						\
778 	}								\
779 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
780 				    GFP_KERNEL);			\
781 	if (!new_##FIELD)						\
782 		return -ENOMEM;						\
783 	if (copy_old) {							\
784 		if (state->FIELD)					\
785 			memcpy(new_##FIELD, state->FIELD,		\
786 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
787 		memset(new_##FIELD + old_size / SIZE, 0,		\
788 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
789 	}								\
790 	state->COUNT = slot * SIZE;					\
791 	kfree(state->FIELD);						\
792 	state->FIELD = new_##FIELD;					\
793 	return 0;							\
794 }
795 /* realloc_reference_state() */
796 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
797 /* realloc_stack_state() */
798 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
799 #undef REALLOC_STATE_FN
800 
801 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
802  * make it consume minimal amount of memory. check_stack_write() access from
803  * the program calls into realloc_func_state() to grow the stack size.
804  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
805  * which realloc_stack_state() copies over. It points to previous
806  * bpf_verifier_state which is never reallocated.
807  */
808 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
809 			      int refs_size, bool copy_old)
810 {
811 	int err = realloc_reference_state(state, refs_size, copy_old);
812 	if (err)
813 		return err;
814 	return realloc_stack_state(state, stack_size, copy_old);
815 }
816 
817 /* Acquire a pointer id from the env and update the state->refs to include
818  * this new pointer reference.
819  * On success, returns a valid pointer id to associate with the register
820  * On failure, returns a negative errno.
821  */
822 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
823 {
824 	struct bpf_func_state *state = cur_func(env);
825 	int new_ofs = state->acquired_refs;
826 	int id, err;
827 
828 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
829 	if (err)
830 		return err;
831 	id = ++env->id_gen;
832 	state->refs[new_ofs].id = id;
833 	state->refs[new_ofs].insn_idx = insn_idx;
834 
835 	return id;
836 }
837 
838 /* release function corresponding to acquire_reference_state(). Idempotent. */
839 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
840 {
841 	int i, last_idx;
842 
843 	last_idx = state->acquired_refs - 1;
844 	for (i = 0; i < state->acquired_refs; i++) {
845 		if (state->refs[i].id == ptr_id) {
846 			if (last_idx && i != last_idx)
847 				memcpy(&state->refs[i], &state->refs[last_idx],
848 				       sizeof(*state->refs));
849 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
850 			state->acquired_refs--;
851 			return 0;
852 		}
853 	}
854 	return -EINVAL;
855 }
856 
857 static int transfer_reference_state(struct bpf_func_state *dst,
858 				    struct bpf_func_state *src)
859 {
860 	int err = realloc_reference_state(dst, src->acquired_refs, false);
861 	if (err)
862 		return err;
863 	err = copy_reference_state(dst, src);
864 	if (err)
865 		return err;
866 	return 0;
867 }
868 
869 static void free_func_state(struct bpf_func_state *state)
870 {
871 	if (!state)
872 		return;
873 	kfree(state->refs);
874 	kfree(state->stack);
875 	kfree(state);
876 }
877 
878 static void clear_jmp_history(struct bpf_verifier_state *state)
879 {
880 	kfree(state->jmp_history);
881 	state->jmp_history = NULL;
882 	state->jmp_history_cnt = 0;
883 }
884 
885 static void free_verifier_state(struct bpf_verifier_state *state,
886 				bool free_self)
887 {
888 	int i;
889 
890 	for (i = 0; i <= state->curframe; i++) {
891 		free_func_state(state->frame[i]);
892 		state->frame[i] = NULL;
893 	}
894 	clear_jmp_history(state);
895 	if (free_self)
896 		kfree(state);
897 }
898 
899 /* copy verifier state from src to dst growing dst stack space
900  * when necessary to accommodate larger src stack
901  */
902 static int copy_func_state(struct bpf_func_state *dst,
903 			   const struct bpf_func_state *src)
904 {
905 	int err;
906 
907 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
908 				 false);
909 	if (err)
910 		return err;
911 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
912 	err = copy_reference_state(dst, src);
913 	if (err)
914 		return err;
915 	return copy_stack_state(dst, src);
916 }
917 
918 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
919 			       const struct bpf_verifier_state *src)
920 {
921 	struct bpf_func_state *dst;
922 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
923 	int i, err;
924 
925 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
926 		kfree(dst_state->jmp_history);
927 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
928 		if (!dst_state->jmp_history)
929 			return -ENOMEM;
930 	}
931 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
932 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
933 
934 	/* if dst has more stack frames then src frame, free them */
935 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
936 		free_func_state(dst_state->frame[i]);
937 		dst_state->frame[i] = NULL;
938 	}
939 	dst_state->speculative = src->speculative;
940 	dst_state->curframe = src->curframe;
941 	dst_state->active_spin_lock = src->active_spin_lock;
942 	dst_state->branches = src->branches;
943 	dst_state->parent = src->parent;
944 	dst_state->first_insn_idx = src->first_insn_idx;
945 	dst_state->last_insn_idx = src->last_insn_idx;
946 	for (i = 0; i <= src->curframe; i++) {
947 		dst = dst_state->frame[i];
948 		if (!dst) {
949 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
950 			if (!dst)
951 				return -ENOMEM;
952 			dst_state->frame[i] = dst;
953 		}
954 		err = copy_func_state(dst, src->frame[i]);
955 		if (err)
956 			return err;
957 	}
958 	return 0;
959 }
960 
961 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
962 {
963 	while (st) {
964 		u32 br = --st->branches;
965 
966 		/* WARN_ON(br > 1) technically makes sense here,
967 		 * but see comment in push_stack(), hence:
968 		 */
969 		WARN_ONCE((int)br < 0,
970 			  "BUG update_branch_counts:branches_to_explore=%d\n",
971 			  br);
972 		if (br)
973 			break;
974 		st = st->parent;
975 	}
976 }
977 
978 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
979 		     int *insn_idx, bool pop_log)
980 {
981 	struct bpf_verifier_state *cur = env->cur_state;
982 	struct bpf_verifier_stack_elem *elem, *head = env->head;
983 	int err;
984 
985 	if (env->head == NULL)
986 		return -ENOENT;
987 
988 	if (cur) {
989 		err = copy_verifier_state(cur, &head->st);
990 		if (err)
991 			return err;
992 	}
993 	if (pop_log)
994 		bpf_vlog_reset(&env->log, head->log_pos);
995 	if (insn_idx)
996 		*insn_idx = head->insn_idx;
997 	if (prev_insn_idx)
998 		*prev_insn_idx = head->prev_insn_idx;
999 	elem = head->next;
1000 	free_verifier_state(&head->st, false);
1001 	kfree(head);
1002 	env->head = elem;
1003 	env->stack_size--;
1004 	return 0;
1005 }
1006 
1007 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1008 					     int insn_idx, int prev_insn_idx,
1009 					     bool speculative)
1010 {
1011 	struct bpf_verifier_state *cur = env->cur_state;
1012 	struct bpf_verifier_stack_elem *elem;
1013 	int err;
1014 
1015 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1016 	if (!elem)
1017 		goto err;
1018 
1019 	elem->insn_idx = insn_idx;
1020 	elem->prev_insn_idx = prev_insn_idx;
1021 	elem->next = env->head;
1022 	elem->log_pos = env->log.len_used;
1023 	env->head = elem;
1024 	env->stack_size++;
1025 	err = copy_verifier_state(&elem->st, cur);
1026 	if (err)
1027 		goto err;
1028 	elem->st.speculative |= speculative;
1029 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1030 		verbose(env, "The sequence of %d jumps is too complex.\n",
1031 			env->stack_size);
1032 		goto err;
1033 	}
1034 	if (elem->st.parent) {
1035 		++elem->st.parent->branches;
1036 		/* WARN_ON(branches > 2) technically makes sense here,
1037 		 * but
1038 		 * 1. speculative states will bump 'branches' for non-branch
1039 		 * instructions
1040 		 * 2. is_state_visited() heuristics may decide not to create
1041 		 * a new state for a sequence of branches and all such current
1042 		 * and cloned states will be pointing to a single parent state
1043 		 * which might have large 'branches' count.
1044 		 */
1045 	}
1046 	return &elem->st;
1047 err:
1048 	free_verifier_state(env->cur_state, true);
1049 	env->cur_state = NULL;
1050 	/* pop all elements and return */
1051 	while (!pop_stack(env, NULL, NULL, false));
1052 	return NULL;
1053 }
1054 
1055 #define CALLER_SAVED_REGS 6
1056 static const int caller_saved[CALLER_SAVED_REGS] = {
1057 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1058 };
1059 
1060 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1061 				struct bpf_reg_state *reg);
1062 
1063 /* This helper doesn't clear reg->id */
1064 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1065 {
1066 	reg->var_off = tnum_const(imm);
1067 	reg->smin_value = (s64)imm;
1068 	reg->smax_value = (s64)imm;
1069 	reg->umin_value = imm;
1070 	reg->umax_value = imm;
1071 
1072 	reg->s32_min_value = (s32)imm;
1073 	reg->s32_max_value = (s32)imm;
1074 	reg->u32_min_value = (u32)imm;
1075 	reg->u32_max_value = (u32)imm;
1076 }
1077 
1078 /* Mark the unknown part of a register (variable offset or scalar value) as
1079  * known to have the value @imm.
1080  */
1081 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1082 {
1083 	/* Clear id, off, and union(map_ptr, range) */
1084 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1085 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1086 	___mark_reg_known(reg, imm);
1087 }
1088 
1089 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1090 {
1091 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1092 	reg->s32_min_value = (s32)imm;
1093 	reg->s32_max_value = (s32)imm;
1094 	reg->u32_min_value = (u32)imm;
1095 	reg->u32_max_value = (u32)imm;
1096 }
1097 
1098 /* Mark the 'variable offset' part of a register as zero.  This should be
1099  * used only on registers holding a pointer type.
1100  */
1101 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1102 {
1103 	__mark_reg_known(reg, 0);
1104 }
1105 
1106 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1107 {
1108 	__mark_reg_known(reg, 0);
1109 	reg->type = SCALAR_VALUE;
1110 }
1111 
1112 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1113 				struct bpf_reg_state *regs, u32 regno)
1114 {
1115 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1116 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1117 		/* Something bad happened, let's kill all regs */
1118 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1119 			__mark_reg_not_init(env, regs + regno);
1120 		return;
1121 	}
1122 	__mark_reg_known_zero(regs + regno);
1123 }
1124 
1125 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1126 {
1127 	switch (reg->type) {
1128 	case PTR_TO_MAP_VALUE_OR_NULL: {
1129 		const struct bpf_map *map = reg->map_ptr;
1130 
1131 		if (map->inner_map_meta) {
1132 			reg->type = CONST_PTR_TO_MAP;
1133 			reg->map_ptr = map->inner_map_meta;
1134 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1135 			reg->type = PTR_TO_XDP_SOCK;
1136 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1137 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1138 			reg->type = PTR_TO_SOCKET;
1139 		} else {
1140 			reg->type = PTR_TO_MAP_VALUE;
1141 		}
1142 		break;
1143 	}
1144 	case PTR_TO_SOCKET_OR_NULL:
1145 		reg->type = PTR_TO_SOCKET;
1146 		break;
1147 	case PTR_TO_SOCK_COMMON_OR_NULL:
1148 		reg->type = PTR_TO_SOCK_COMMON;
1149 		break;
1150 	case PTR_TO_TCP_SOCK_OR_NULL:
1151 		reg->type = PTR_TO_TCP_SOCK;
1152 		break;
1153 	case PTR_TO_BTF_ID_OR_NULL:
1154 		reg->type = PTR_TO_BTF_ID;
1155 		break;
1156 	case PTR_TO_MEM_OR_NULL:
1157 		reg->type = PTR_TO_MEM;
1158 		break;
1159 	case PTR_TO_RDONLY_BUF_OR_NULL:
1160 		reg->type = PTR_TO_RDONLY_BUF;
1161 		break;
1162 	case PTR_TO_RDWR_BUF_OR_NULL:
1163 		reg->type = PTR_TO_RDWR_BUF;
1164 		break;
1165 	default:
1166 		WARN_ONCE(1, "unknown nullable register type");
1167 	}
1168 }
1169 
1170 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1171 {
1172 	return type_is_pkt_pointer(reg->type);
1173 }
1174 
1175 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1176 {
1177 	return reg_is_pkt_pointer(reg) ||
1178 	       reg->type == PTR_TO_PACKET_END;
1179 }
1180 
1181 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1182 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1183 				    enum bpf_reg_type which)
1184 {
1185 	/* The register can already have a range from prior markings.
1186 	 * This is fine as long as it hasn't been advanced from its
1187 	 * origin.
1188 	 */
1189 	return reg->type == which &&
1190 	       reg->id == 0 &&
1191 	       reg->off == 0 &&
1192 	       tnum_equals_const(reg->var_off, 0);
1193 }
1194 
1195 /* Reset the min/max bounds of a register */
1196 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1197 {
1198 	reg->smin_value = S64_MIN;
1199 	reg->smax_value = S64_MAX;
1200 	reg->umin_value = 0;
1201 	reg->umax_value = U64_MAX;
1202 
1203 	reg->s32_min_value = S32_MIN;
1204 	reg->s32_max_value = S32_MAX;
1205 	reg->u32_min_value = 0;
1206 	reg->u32_max_value = U32_MAX;
1207 }
1208 
1209 static void __mark_reg64_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 
1217 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1218 {
1219 	reg->s32_min_value = S32_MIN;
1220 	reg->s32_max_value = S32_MAX;
1221 	reg->u32_min_value = 0;
1222 	reg->u32_max_value = U32_MAX;
1223 }
1224 
1225 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1226 {
1227 	struct tnum var32_off = tnum_subreg(reg->var_off);
1228 
1229 	/* min signed is max(sign bit) | min(other bits) */
1230 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1231 			var32_off.value | (var32_off.mask & S32_MIN));
1232 	/* max signed is min(sign bit) | max(other bits) */
1233 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1234 			var32_off.value | (var32_off.mask & S32_MAX));
1235 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1236 	reg->u32_max_value = min(reg->u32_max_value,
1237 				 (u32)(var32_off.value | var32_off.mask));
1238 }
1239 
1240 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1241 {
1242 	/* min signed is max(sign bit) | min(other bits) */
1243 	reg->smin_value = max_t(s64, reg->smin_value,
1244 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1245 	/* max signed is min(sign bit) | max(other bits) */
1246 	reg->smax_value = min_t(s64, reg->smax_value,
1247 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1248 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1249 	reg->umax_value = min(reg->umax_value,
1250 			      reg->var_off.value | reg->var_off.mask);
1251 }
1252 
1253 static void __update_reg_bounds(struct bpf_reg_state *reg)
1254 {
1255 	__update_reg32_bounds(reg);
1256 	__update_reg64_bounds(reg);
1257 }
1258 
1259 /* Uses signed min/max values to inform unsigned, and vice-versa */
1260 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1261 {
1262 	/* Learn sign from signed bounds.
1263 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1264 	 * are the same, so combine.  This works even in the negative case, e.g.
1265 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1266 	 */
1267 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1268 		reg->s32_min_value = reg->u32_min_value =
1269 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1270 		reg->s32_max_value = reg->u32_max_value =
1271 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1272 		return;
1273 	}
1274 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1275 	 * boundary, so we must be careful.
1276 	 */
1277 	if ((s32)reg->u32_max_value >= 0) {
1278 		/* Positive.  We can't learn anything from the smin, but smax
1279 		 * is positive, hence safe.
1280 		 */
1281 		reg->s32_min_value = reg->u32_min_value;
1282 		reg->s32_max_value = reg->u32_max_value =
1283 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1284 	} else if ((s32)reg->u32_min_value < 0) {
1285 		/* Negative.  We can't learn anything from the smax, but smin
1286 		 * is negative, hence safe.
1287 		 */
1288 		reg->s32_min_value = reg->u32_min_value =
1289 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1290 		reg->s32_max_value = reg->u32_max_value;
1291 	}
1292 }
1293 
1294 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1295 {
1296 	/* Learn sign from signed bounds.
1297 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1298 	 * are the same, so combine.  This works even in the negative case, e.g.
1299 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1300 	 */
1301 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1302 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1303 							  reg->umin_value);
1304 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1305 							  reg->umax_value);
1306 		return;
1307 	}
1308 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1309 	 * boundary, so we must be careful.
1310 	 */
1311 	if ((s64)reg->umax_value >= 0) {
1312 		/* Positive.  We can't learn anything from the smin, but smax
1313 		 * is positive, hence safe.
1314 		 */
1315 		reg->smin_value = reg->umin_value;
1316 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1317 							  reg->umax_value);
1318 	} else if ((s64)reg->umin_value < 0) {
1319 		/* Negative.  We can't learn anything from the smax, but smin
1320 		 * is negative, hence safe.
1321 		 */
1322 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1323 							  reg->umin_value);
1324 		reg->smax_value = reg->umax_value;
1325 	}
1326 }
1327 
1328 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1329 {
1330 	__reg32_deduce_bounds(reg);
1331 	__reg64_deduce_bounds(reg);
1332 }
1333 
1334 /* Attempts to improve var_off based on unsigned min/max information */
1335 static void __reg_bound_offset(struct bpf_reg_state *reg)
1336 {
1337 	struct tnum var64_off = tnum_intersect(reg->var_off,
1338 					       tnum_range(reg->umin_value,
1339 							  reg->umax_value));
1340 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1341 						tnum_range(reg->u32_min_value,
1342 							   reg->u32_max_value));
1343 
1344 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1345 }
1346 
1347 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1348 {
1349 	reg->umin_value = reg->u32_min_value;
1350 	reg->umax_value = reg->u32_max_value;
1351 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds
1352 	 * but must be positive otherwise set to worse case bounds
1353 	 * and refine later from tnum.
1354 	 */
1355 	if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1356 		reg->smax_value = reg->s32_max_value;
1357 	else
1358 		reg->smax_value = U32_MAX;
1359 	if (reg->s32_min_value >= 0)
1360 		reg->smin_value = reg->s32_min_value;
1361 	else
1362 		reg->smin_value = 0;
1363 }
1364 
1365 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1366 {
1367 	/* special case when 64-bit register has upper 32-bit register
1368 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1369 	 * allowing us to use 32-bit bounds directly,
1370 	 */
1371 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1372 		__reg_assign_32_into_64(reg);
1373 	} else {
1374 		/* Otherwise the best we can do is push lower 32bit known and
1375 		 * unknown bits into register (var_off set from jmp logic)
1376 		 * then learn as much as possible from the 64-bit tnum
1377 		 * known and unknown bits. The previous smin/smax bounds are
1378 		 * invalid here because of jmp32 compare so mark them unknown
1379 		 * so they do not impact tnum bounds calculation.
1380 		 */
1381 		__mark_reg64_unbounded(reg);
1382 		__update_reg_bounds(reg);
1383 	}
1384 
1385 	/* Intersecting with the old var_off might have improved our bounds
1386 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1387 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1388 	 */
1389 	__reg_deduce_bounds(reg);
1390 	__reg_bound_offset(reg);
1391 	__update_reg_bounds(reg);
1392 }
1393 
1394 static bool __reg64_bound_s32(s64 a)
1395 {
1396 	return a > S32_MIN && a < S32_MAX;
1397 }
1398 
1399 static bool __reg64_bound_u32(u64 a)
1400 {
1401 	if (a > U32_MIN && a < U32_MAX)
1402 		return true;
1403 	return false;
1404 }
1405 
1406 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1407 {
1408 	__mark_reg32_unbounded(reg);
1409 
1410 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1411 		reg->s32_min_value = (s32)reg->smin_value;
1412 		reg->s32_max_value = (s32)reg->smax_value;
1413 	}
1414 	if (__reg64_bound_u32(reg->umin_value))
1415 		reg->u32_min_value = (u32)reg->umin_value;
1416 	if (__reg64_bound_u32(reg->umax_value))
1417 		reg->u32_max_value = (u32)reg->umax_value;
1418 
1419 	/* Intersecting with the old var_off might have improved our bounds
1420 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1421 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1422 	 */
1423 	__reg_deduce_bounds(reg);
1424 	__reg_bound_offset(reg);
1425 	__update_reg_bounds(reg);
1426 }
1427 
1428 /* Mark a register as having a completely unknown (scalar) value. */
1429 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1430 			       struct bpf_reg_state *reg)
1431 {
1432 	/*
1433 	 * Clear type, id, off, and union(map_ptr, range) and
1434 	 * padding between 'type' and union
1435 	 */
1436 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1437 	reg->type = SCALAR_VALUE;
1438 	reg->var_off = tnum_unknown;
1439 	reg->frameno = 0;
1440 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1441 	__mark_reg_unbounded(reg);
1442 }
1443 
1444 static void mark_reg_unknown(struct bpf_verifier_env *env,
1445 			     struct bpf_reg_state *regs, u32 regno)
1446 {
1447 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1448 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1449 		/* Something bad happened, let's kill all regs except FP */
1450 		for (regno = 0; regno < BPF_REG_FP; regno++)
1451 			__mark_reg_not_init(env, regs + regno);
1452 		return;
1453 	}
1454 	__mark_reg_unknown(env, regs + regno);
1455 }
1456 
1457 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1458 				struct bpf_reg_state *reg)
1459 {
1460 	__mark_reg_unknown(env, reg);
1461 	reg->type = NOT_INIT;
1462 }
1463 
1464 static void mark_reg_not_init(struct bpf_verifier_env *env,
1465 			      struct bpf_reg_state *regs, u32 regno)
1466 {
1467 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1468 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1469 		/* Something bad happened, let's kill all regs except FP */
1470 		for (regno = 0; regno < BPF_REG_FP; regno++)
1471 			__mark_reg_not_init(env, regs + regno);
1472 		return;
1473 	}
1474 	__mark_reg_not_init(env, regs + regno);
1475 }
1476 
1477 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1478 			    struct bpf_reg_state *regs, u32 regno,
1479 			    enum bpf_reg_type reg_type,
1480 			    struct btf *btf, u32 btf_id)
1481 {
1482 	if (reg_type == SCALAR_VALUE) {
1483 		mark_reg_unknown(env, regs, regno);
1484 		return;
1485 	}
1486 	mark_reg_known_zero(env, regs, regno);
1487 	regs[regno].type = PTR_TO_BTF_ID;
1488 	regs[regno].btf = btf;
1489 	regs[regno].btf_id = btf_id;
1490 }
1491 
1492 #define DEF_NOT_SUBREG	(0)
1493 static void init_reg_state(struct bpf_verifier_env *env,
1494 			   struct bpf_func_state *state)
1495 {
1496 	struct bpf_reg_state *regs = state->regs;
1497 	int i;
1498 
1499 	for (i = 0; i < MAX_BPF_REG; i++) {
1500 		mark_reg_not_init(env, regs, i);
1501 		regs[i].live = REG_LIVE_NONE;
1502 		regs[i].parent = NULL;
1503 		regs[i].subreg_def = DEF_NOT_SUBREG;
1504 	}
1505 
1506 	/* frame pointer */
1507 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1508 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1509 	regs[BPF_REG_FP].frameno = state->frameno;
1510 }
1511 
1512 #define BPF_MAIN_FUNC (-1)
1513 static void init_func_state(struct bpf_verifier_env *env,
1514 			    struct bpf_func_state *state,
1515 			    int callsite, int frameno, int subprogno)
1516 {
1517 	state->callsite = callsite;
1518 	state->frameno = frameno;
1519 	state->subprogno = subprogno;
1520 	init_reg_state(env, state);
1521 }
1522 
1523 enum reg_arg_type {
1524 	SRC_OP,		/* register is used as source operand */
1525 	DST_OP,		/* register is used as destination operand */
1526 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1527 };
1528 
1529 static int cmp_subprogs(const void *a, const void *b)
1530 {
1531 	return ((struct bpf_subprog_info *)a)->start -
1532 	       ((struct bpf_subprog_info *)b)->start;
1533 }
1534 
1535 static int find_subprog(struct bpf_verifier_env *env, int off)
1536 {
1537 	struct bpf_subprog_info *p;
1538 
1539 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1540 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1541 	if (!p)
1542 		return -ENOENT;
1543 	return p - env->subprog_info;
1544 
1545 }
1546 
1547 static int add_subprog(struct bpf_verifier_env *env, int off)
1548 {
1549 	int insn_cnt = env->prog->len;
1550 	int ret;
1551 
1552 	if (off >= insn_cnt || off < 0) {
1553 		verbose(env, "call to invalid destination\n");
1554 		return -EINVAL;
1555 	}
1556 	ret = find_subprog(env, off);
1557 	if (ret >= 0)
1558 		return ret;
1559 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1560 		verbose(env, "too many subprograms\n");
1561 		return -E2BIG;
1562 	}
1563 	/* determine subprog starts. The end is one before the next starts */
1564 	env->subprog_info[env->subprog_cnt++].start = off;
1565 	sort(env->subprog_info, env->subprog_cnt,
1566 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1567 	return env->subprog_cnt - 1;
1568 }
1569 
1570 struct bpf_kfunc_desc {
1571 	struct btf_func_model func_model;
1572 	u32 func_id;
1573 	s32 imm;
1574 };
1575 
1576 #define MAX_KFUNC_DESCS 256
1577 struct bpf_kfunc_desc_tab {
1578 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1579 	u32 nr_descs;
1580 };
1581 
1582 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1583 {
1584 	const struct bpf_kfunc_desc *d0 = a;
1585 	const struct bpf_kfunc_desc *d1 = b;
1586 
1587 	/* func_id is not greater than BTF_MAX_TYPE */
1588 	return d0->func_id - d1->func_id;
1589 }
1590 
1591 static const struct bpf_kfunc_desc *
1592 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1593 {
1594 	struct bpf_kfunc_desc desc = {
1595 		.func_id = func_id,
1596 	};
1597 	struct bpf_kfunc_desc_tab *tab;
1598 
1599 	tab = prog->aux->kfunc_tab;
1600 	return bsearch(&desc, tab->descs, tab->nr_descs,
1601 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1602 }
1603 
1604 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1605 {
1606 	const struct btf_type *func, *func_proto;
1607 	struct bpf_kfunc_desc_tab *tab;
1608 	struct bpf_prog_aux *prog_aux;
1609 	struct bpf_kfunc_desc *desc;
1610 	const char *func_name;
1611 	unsigned long addr;
1612 	int err;
1613 
1614 	prog_aux = env->prog->aux;
1615 	tab = prog_aux->kfunc_tab;
1616 	if (!tab) {
1617 		if (!btf_vmlinux) {
1618 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1619 			return -ENOTSUPP;
1620 		}
1621 
1622 		if (!env->prog->jit_requested) {
1623 			verbose(env, "JIT is required for calling kernel function\n");
1624 			return -ENOTSUPP;
1625 		}
1626 
1627 		if (!bpf_jit_supports_kfunc_call()) {
1628 			verbose(env, "JIT does not support calling kernel function\n");
1629 			return -ENOTSUPP;
1630 		}
1631 
1632 		if (!env->prog->gpl_compatible) {
1633 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1634 			return -EINVAL;
1635 		}
1636 
1637 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1638 		if (!tab)
1639 			return -ENOMEM;
1640 		prog_aux->kfunc_tab = tab;
1641 	}
1642 
1643 	if (find_kfunc_desc(env->prog, func_id))
1644 		return 0;
1645 
1646 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1647 		verbose(env, "too many different kernel function calls\n");
1648 		return -E2BIG;
1649 	}
1650 
1651 	func = btf_type_by_id(btf_vmlinux, func_id);
1652 	if (!func || !btf_type_is_func(func)) {
1653 		verbose(env, "kernel btf_id %u is not a function\n",
1654 			func_id);
1655 		return -EINVAL;
1656 	}
1657 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
1658 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1659 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1660 			func_id);
1661 		return -EINVAL;
1662 	}
1663 
1664 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1665 	addr = kallsyms_lookup_name(func_name);
1666 	if (!addr) {
1667 		verbose(env, "cannot find address for kernel function %s\n",
1668 			func_name);
1669 		return -EINVAL;
1670 	}
1671 
1672 	desc = &tab->descs[tab->nr_descs++];
1673 	desc->func_id = func_id;
1674 	desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1675 	err = btf_distill_func_proto(&env->log, btf_vmlinux,
1676 				     func_proto, func_name,
1677 				     &desc->func_model);
1678 	if (!err)
1679 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1680 		     kfunc_desc_cmp_by_id, NULL);
1681 	return err;
1682 }
1683 
1684 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1685 {
1686 	const struct bpf_kfunc_desc *d0 = a;
1687 	const struct bpf_kfunc_desc *d1 = b;
1688 
1689 	if (d0->imm > d1->imm)
1690 		return 1;
1691 	else if (d0->imm < d1->imm)
1692 		return -1;
1693 	return 0;
1694 }
1695 
1696 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1697 {
1698 	struct bpf_kfunc_desc_tab *tab;
1699 
1700 	tab = prog->aux->kfunc_tab;
1701 	if (!tab)
1702 		return;
1703 
1704 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1705 	     kfunc_desc_cmp_by_imm, NULL);
1706 }
1707 
1708 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1709 {
1710 	return !!prog->aux->kfunc_tab;
1711 }
1712 
1713 const struct btf_func_model *
1714 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1715 			 const struct bpf_insn *insn)
1716 {
1717 	const struct bpf_kfunc_desc desc = {
1718 		.imm = insn->imm,
1719 	};
1720 	const struct bpf_kfunc_desc *res;
1721 	struct bpf_kfunc_desc_tab *tab;
1722 
1723 	tab = prog->aux->kfunc_tab;
1724 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1725 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1726 
1727 	return res ? &res->func_model : NULL;
1728 }
1729 
1730 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1731 {
1732 	struct bpf_subprog_info *subprog = env->subprog_info;
1733 	struct bpf_insn *insn = env->prog->insnsi;
1734 	int i, ret, insn_cnt = env->prog->len;
1735 
1736 	/* Add entry function. */
1737 	ret = add_subprog(env, 0);
1738 	if (ret)
1739 		return ret;
1740 
1741 	for (i = 0; i < insn_cnt; i++, insn++) {
1742 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1743 		    !bpf_pseudo_kfunc_call(insn))
1744 			continue;
1745 
1746 		if (!env->bpf_capable) {
1747 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1748 			return -EPERM;
1749 		}
1750 
1751 		if (bpf_pseudo_func(insn)) {
1752 			ret = add_subprog(env, i + insn->imm + 1);
1753 			if (ret >= 0)
1754 				/* remember subprog */
1755 				insn[1].imm = ret;
1756 		} else if (bpf_pseudo_call(insn)) {
1757 			ret = add_subprog(env, i + insn->imm + 1);
1758 		} else {
1759 			ret = add_kfunc_call(env, insn->imm);
1760 		}
1761 
1762 		if (ret < 0)
1763 			return ret;
1764 	}
1765 
1766 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1767 	 * logic. 'subprog_cnt' should not be increased.
1768 	 */
1769 	subprog[env->subprog_cnt].start = insn_cnt;
1770 
1771 	if (env->log.level & BPF_LOG_LEVEL2)
1772 		for (i = 0; i < env->subprog_cnt; i++)
1773 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1774 
1775 	return 0;
1776 }
1777 
1778 static int check_subprogs(struct bpf_verifier_env *env)
1779 {
1780 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1781 	struct bpf_subprog_info *subprog = env->subprog_info;
1782 	struct bpf_insn *insn = env->prog->insnsi;
1783 	int insn_cnt = env->prog->len;
1784 
1785 	/* now check that all jumps are within the same subprog */
1786 	subprog_start = subprog[cur_subprog].start;
1787 	subprog_end = subprog[cur_subprog + 1].start;
1788 	for (i = 0; i < insn_cnt; i++) {
1789 		u8 code = insn[i].code;
1790 
1791 		if (code == (BPF_JMP | BPF_CALL) &&
1792 		    insn[i].imm == BPF_FUNC_tail_call &&
1793 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1794 			subprog[cur_subprog].has_tail_call = true;
1795 		if (BPF_CLASS(code) == BPF_LD &&
1796 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1797 			subprog[cur_subprog].has_ld_abs = true;
1798 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1799 			goto next;
1800 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1801 			goto next;
1802 		off = i + insn[i].off + 1;
1803 		if (off < subprog_start || off >= subprog_end) {
1804 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1805 			return -EINVAL;
1806 		}
1807 next:
1808 		if (i == subprog_end - 1) {
1809 			/* to avoid fall-through from one subprog into another
1810 			 * the last insn of the subprog should be either exit
1811 			 * or unconditional jump back
1812 			 */
1813 			if (code != (BPF_JMP | BPF_EXIT) &&
1814 			    code != (BPF_JMP | BPF_JA)) {
1815 				verbose(env, "last insn is not an exit or jmp\n");
1816 				return -EINVAL;
1817 			}
1818 			subprog_start = subprog_end;
1819 			cur_subprog++;
1820 			if (cur_subprog < env->subprog_cnt)
1821 				subprog_end = subprog[cur_subprog + 1].start;
1822 		}
1823 	}
1824 	return 0;
1825 }
1826 
1827 /* Parentage chain of this register (or stack slot) should take care of all
1828  * issues like callee-saved registers, stack slot allocation time, etc.
1829  */
1830 static int mark_reg_read(struct bpf_verifier_env *env,
1831 			 const struct bpf_reg_state *state,
1832 			 struct bpf_reg_state *parent, u8 flag)
1833 {
1834 	bool writes = parent == state->parent; /* Observe write marks */
1835 	int cnt = 0;
1836 
1837 	while (parent) {
1838 		/* if read wasn't screened by an earlier write ... */
1839 		if (writes && state->live & REG_LIVE_WRITTEN)
1840 			break;
1841 		if (parent->live & REG_LIVE_DONE) {
1842 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1843 				reg_type_str[parent->type],
1844 				parent->var_off.value, parent->off);
1845 			return -EFAULT;
1846 		}
1847 		/* The first condition is more likely to be true than the
1848 		 * second, checked it first.
1849 		 */
1850 		if ((parent->live & REG_LIVE_READ) == flag ||
1851 		    parent->live & REG_LIVE_READ64)
1852 			/* The parentage chain never changes and
1853 			 * this parent was already marked as LIVE_READ.
1854 			 * There is no need to keep walking the chain again and
1855 			 * keep re-marking all parents as LIVE_READ.
1856 			 * This case happens when the same register is read
1857 			 * multiple times without writes into it in-between.
1858 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1859 			 * then no need to set the weak REG_LIVE_READ32.
1860 			 */
1861 			break;
1862 		/* ... then we depend on parent's value */
1863 		parent->live |= flag;
1864 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1865 		if (flag == REG_LIVE_READ64)
1866 			parent->live &= ~REG_LIVE_READ32;
1867 		state = parent;
1868 		parent = state->parent;
1869 		writes = true;
1870 		cnt++;
1871 	}
1872 
1873 	if (env->longest_mark_read_walk < cnt)
1874 		env->longest_mark_read_walk = cnt;
1875 	return 0;
1876 }
1877 
1878 /* This function is supposed to be used by the following 32-bit optimization
1879  * code only. It returns TRUE if the source or destination register operates
1880  * on 64-bit, otherwise return FALSE.
1881  */
1882 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1883 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1884 {
1885 	u8 code, class, op;
1886 
1887 	code = insn->code;
1888 	class = BPF_CLASS(code);
1889 	op = BPF_OP(code);
1890 	if (class == BPF_JMP) {
1891 		/* BPF_EXIT for "main" will reach here. Return TRUE
1892 		 * conservatively.
1893 		 */
1894 		if (op == BPF_EXIT)
1895 			return true;
1896 		if (op == BPF_CALL) {
1897 			/* BPF to BPF call will reach here because of marking
1898 			 * caller saved clobber with DST_OP_NO_MARK for which we
1899 			 * don't care the register def because they are anyway
1900 			 * marked as NOT_INIT already.
1901 			 */
1902 			if (insn->src_reg == BPF_PSEUDO_CALL)
1903 				return false;
1904 			/* Helper call will reach here because of arg type
1905 			 * check, conservatively return TRUE.
1906 			 */
1907 			if (t == SRC_OP)
1908 				return true;
1909 
1910 			return false;
1911 		}
1912 	}
1913 
1914 	if (class == BPF_ALU64 || class == BPF_JMP ||
1915 	    /* BPF_END always use BPF_ALU class. */
1916 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1917 		return true;
1918 
1919 	if (class == BPF_ALU || class == BPF_JMP32)
1920 		return false;
1921 
1922 	if (class == BPF_LDX) {
1923 		if (t != SRC_OP)
1924 			return BPF_SIZE(code) == BPF_DW;
1925 		/* LDX source must be ptr. */
1926 		return true;
1927 	}
1928 
1929 	if (class == BPF_STX) {
1930 		/* BPF_STX (including atomic variants) has multiple source
1931 		 * operands, one of which is a ptr. Check whether the caller is
1932 		 * asking about it.
1933 		 */
1934 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
1935 			return true;
1936 		return BPF_SIZE(code) == BPF_DW;
1937 	}
1938 
1939 	if (class == BPF_LD) {
1940 		u8 mode = BPF_MODE(code);
1941 
1942 		/* LD_IMM64 */
1943 		if (mode == BPF_IMM)
1944 			return true;
1945 
1946 		/* Both LD_IND and LD_ABS return 32-bit data. */
1947 		if (t != SRC_OP)
1948 			return  false;
1949 
1950 		/* Implicit ctx ptr. */
1951 		if (regno == BPF_REG_6)
1952 			return true;
1953 
1954 		/* Explicit source could be any width. */
1955 		return true;
1956 	}
1957 
1958 	if (class == BPF_ST)
1959 		/* The only source register for BPF_ST is a ptr. */
1960 		return true;
1961 
1962 	/* Conservatively return true at default. */
1963 	return true;
1964 }
1965 
1966 /* Return the regno defined by the insn, or -1. */
1967 static int insn_def_regno(const struct bpf_insn *insn)
1968 {
1969 	switch (BPF_CLASS(insn->code)) {
1970 	case BPF_JMP:
1971 	case BPF_JMP32:
1972 	case BPF_ST:
1973 		return -1;
1974 	case BPF_STX:
1975 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1976 		    (insn->imm & BPF_FETCH)) {
1977 			if (insn->imm == BPF_CMPXCHG)
1978 				return BPF_REG_0;
1979 			else
1980 				return insn->src_reg;
1981 		} else {
1982 			return -1;
1983 		}
1984 	default:
1985 		return insn->dst_reg;
1986 	}
1987 }
1988 
1989 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1990 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1991 {
1992 	int dst_reg = insn_def_regno(insn);
1993 
1994 	if (dst_reg == -1)
1995 		return false;
1996 
1997 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
1998 }
1999 
2000 static void mark_insn_zext(struct bpf_verifier_env *env,
2001 			   struct bpf_reg_state *reg)
2002 {
2003 	s32 def_idx = reg->subreg_def;
2004 
2005 	if (def_idx == DEF_NOT_SUBREG)
2006 		return;
2007 
2008 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2009 	/* The dst will be zero extended, so won't be sub-register anymore. */
2010 	reg->subreg_def = DEF_NOT_SUBREG;
2011 }
2012 
2013 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2014 			 enum reg_arg_type t)
2015 {
2016 	struct bpf_verifier_state *vstate = env->cur_state;
2017 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2018 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2019 	struct bpf_reg_state *reg, *regs = state->regs;
2020 	bool rw64;
2021 
2022 	if (regno >= MAX_BPF_REG) {
2023 		verbose(env, "R%d is invalid\n", regno);
2024 		return -EINVAL;
2025 	}
2026 
2027 	reg = &regs[regno];
2028 	rw64 = is_reg64(env, insn, regno, reg, t);
2029 	if (t == SRC_OP) {
2030 		/* check whether register used as source operand can be read */
2031 		if (reg->type == NOT_INIT) {
2032 			verbose(env, "R%d !read_ok\n", regno);
2033 			return -EACCES;
2034 		}
2035 		/* We don't need to worry about FP liveness because it's read-only */
2036 		if (regno == BPF_REG_FP)
2037 			return 0;
2038 
2039 		if (rw64)
2040 			mark_insn_zext(env, reg);
2041 
2042 		return mark_reg_read(env, reg, reg->parent,
2043 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2044 	} else {
2045 		/* check whether register used as dest operand can be written to */
2046 		if (regno == BPF_REG_FP) {
2047 			verbose(env, "frame pointer is read only\n");
2048 			return -EACCES;
2049 		}
2050 		reg->live |= REG_LIVE_WRITTEN;
2051 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2052 		if (t == DST_OP)
2053 			mark_reg_unknown(env, regs, regno);
2054 	}
2055 	return 0;
2056 }
2057 
2058 /* for any branch, call, exit record the history of jmps in the given state */
2059 static int push_jmp_history(struct bpf_verifier_env *env,
2060 			    struct bpf_verifier_state *cur)
2061 {
2062 	u32 cnt = cur->jmp_history_cnt;
2063 	struct bpf_idx_pair *p;
2064 
2065 	cnt++;
2066 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2067 	if (!p)
2068 		return -ENOMEM;
2069 	p[cnt - 1].idx = env->insn_idx;
2070 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2071 	cur->jmp_history = p;
2072 	cur->jmp_history_cnt = cnt;
2073 	return 0;
2074 }
2075 
2076 /* Backtrack one insn at a time. If idx is not at the top of recorded
2077  * history then previous instruction came from straight line execution.
2078  */
2079 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2080 			     u32 *history)
2081 {
2082 	u32 cnt = *history;
2083 
2084 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2085 		i = st->jmp_history[cnt - 1].prev_idx;
2086 		(*history)--;
2087 	} else {
2088 		i--;
2089 	}
2090 	return i;
2091 }
2092 
2093 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2094 {
2095 	const struct btf_type *func;
2096 
2097 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2098 		return NULL;
2099 
2100 	func = btf_type_by_id(btf_vmlinux, insn->imm);
2101 	return btf_name_by_offset(btf_vmlinux, func->name_off);
2102 }
2103 
2104 /* For given verifier state backtrack_insn() is called from the last insn to
2105  * the first insn. Its purpose is to compute a bitmask of registers and
2106  * stack slots that needs precision in the parent verifier state.
2107  */
2108 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2109 			  u32 *reg_mask, u64 *stack_mask)
2110 {
2111 	const struct bpf_insn_cbs cbs = {
2112 		.cb_call	= disasm_kfunc_name,
2113 		.cb_print	= verbose,
2114 		.private_data	= env,
2115 	};
2116 	struct bpf_insn *insn = env->prog->insnsi + idx;
2117 	u8 class = BPF_CLASS(insn->code);
2118 	u8 opcode = BPF_OP(insn->code);
2119 	u8 mode = BPF_MODE(insn->code);
2120 	u32 dreg = 1u << insn->dst_reg;
2121 	u32 sreg = 1u << insn->src_reg;
2122 	u32 spi;
2123 
2124 	if (insn->code == 0)
2125 		return 0;
2126 	if (env->log.level & BPF_LOG_LEVEL) {
2127 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2128 		verbose(env, "%d: ", idx);
2129 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2130 	}
2131 
2132 	if (class == BPF_ALU || class == BPF_ALU64) {
2133 		if (!(*reg_mask & dreg))
2134 			return 0;
2135 		if (opcode == BPF_MOV) {
2136 			if (BPF_SRC(insn->code) == BPF_X) {
2137 				/* dreg = sreg
2138 				 * dreg needs precision after this insn
2139 				 * sreg needs precision before this insn
2140 				 */
2141 				*reg_mask &= ~dreg;
2142 				*reg_mask |= sreg;
2143 			} else {
2144 				/* dreg = K
2145 				 * dreg needs precision after this insn.
2146 				 * Corresponding register is already marked
2147 				 * as precise=true in this verifier state.
2148 				 * No further markings in parent are necessary
2149 				 */
2150 				*reg_mask &= ~dreg;
2151 			}
2152 		} else {
2153 			if (BPF_SRC(insn->code) == BPF_X) {
2154 				/* dreg += sreg
2155 				 * both dreg and sreg need precision
2156 				 * before this insn
2157 				 */
2158 				*reg_mask |= sreg;
2159 			} /* else dreg += K
2160 			   * dreg still needs precision before this insn
2161 			   */
2162 		}
2163 	} else if (class == BPF_LDX) {
2164 		if (!(*reg_mask & dreg))
2165 			return 0;
2166 		*reg_mask &= ~dreg;
2167 
2168 		/* scalars can only be spilled into stack w/o losing precision.
2169 		 * Load from any other memory can be zero extended.
2170 		 * The desire to keep that precision is already indicated
2171 		 * by 'precise' mark in corresponding register of this state.
2172 		 * No further tracking necessary.
2173 		 */
2174 		if (insn->src_reg != BPF_REG_FP)
2175 			return 0;
2176 		if (BPF_SIZE(insn->code) != BPF_DW)
2177 			return 0;
2178 
2179 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2180 		 * that [fp - off] slot contains scalar that needs to be
2181 		 * tracked with precision
2182 		 */
2183 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2184 		if (spi >= 64) {
2185 			verbose(env, "BUG spi %d\n", spi);
2186 			WARN_ONCE(1, "verifier backtracking bug");
2187 			return -EFAULT;
2188 		}
2189 		*stack_mask |= 1ull << spi;
2190 	} else if (class == BPF_STX || class == BPF_ST) {
2191 		if (*reg_mask & dreg)
2192 			/* stx & st shouldn't be using _scalar_ dst_reg
2193 			 * to access memory. It means backtracking
2194 			 * encountered a case of pointer subtraction.
2195 			 */
2196 			return -ENOTSUPP;
2197 		/* scalars can only be spilled into stack */
2198 		if (insn->dst_reg != BPF_REG_FP)
2199 			return 0;
2200 		if (BPF_SIZE(insn->code) != BPF_DW)
2201 			return 0;
2202 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2203 		if (spi >= 64) {
2204 			verbose(env, "BUG spi %d\n", spi);
2205 			WARN_ONCE(1, "verifier backtracking bug");
2206 			return -EFAULT;
2207 		}
2208 		if (!(*stack_mask & (1ull << spi)))
2209 			return 0;
2210 		*stack_mask &= ~(1ull << spi);
2211 		if (class == BPF_STX)
2212 			*reg_mask |= sreg;
2213 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2214 		if (opcode == BPF_CALL) {
2215 			if (insn->src_reg == BPF_PSEUDO_CALL)
2216 				return -ENOTSUPP;
2217 			/* regular helper call sets R0 */
2218 			*reg_mask &= ~1;
2219 			if (*reg_mask & 0x3f) {
2220 				/* if backtracing was looking for registers R1-R5
2221 				 * they should have been found already.
2222 				 */
2223 				verbose(env, "BUG regs %x\n", *reg_mask);
2224 				WARN_ONCE(1, "verifier backtracking bug");
2225 				return -EFAULT;
2226 			}
2227 		} else if (opcode == BPF_EXIT) {
2228 			return -ENOTSUPP;
2229 		}
2230 	} else if (class == BPF_LD) {
2231 		if (!(*reg_mask & dreg))
2232 			return 0;
2233 		*reg_mask &= ~dreg;
2234 		/* It's ld_imm64 or ld_abs or ld_ind.
2235 		 * For ld_imm64 no further tracking of precision
2236 		 * into parent is necessary
2237 		 */
2238 		if (mode == BPF_IND || mode == BPF_ABS)
2239 			/* to be analyzed */
2240 			return -ENOTSUPP;
2241 	}
2242 	return 0;
2243 }
2244 
2245 /* the scalar precision tracking algorithm:
2246  * . at the start all registers have precise=false.
2247  * . scalar ranges are tracked as normal through alu and jmp insns.
2248  * . once precise value of the scalar register is used in:
2249  *   .  ptr + scalar alu
2250  *   . if (scalar cond K|scalar)
2251  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2252  *   backtrack through the verifier states and mark all registers and
2253  *   stack slots with spilled constants that these scalar regisers
2254  *   should be precise.
2255  * . during state pruning two registers (or spilled stack slots)
2256  *   are equivalent if both are not precise.
2257  *
2258  * Note the verifier cannot simply walk register parentage chain,
2259  * since many different registers and stack slots could have been
2260  * used to compute single precise scalar.
2261  *
2262  * The approach of starting with precise=true for all registers and then
2263  * backtrack to mark a register as not precise when the verifier detects
2264  * that program doesn't care about specific value (e.g., when helper
2265  * takes register as ARG_ANYTHING parameter) is not safe.
2266  *
2267  * It's ok to walk single parentage chain of the verifier states.
2268  * It's possible that this backtracking will go all the way till 1st insn.
2269  * All other branches will be explored for needing precision later.
2270  *
2271  * The backtracking needs to deal with cases like:
2272  *   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)
2273  * r9 -= r8
2274  * r5 = r9
2275  * if r5 > 0x79f goto pc+7
2276  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2277  * r5 += 1
2278  * ...
2279  * call bpf_perf_event_output#25
2280  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2281  *
2282  * and this case:
2283  * r6 = 1
2284  * call foo // uses callee's r6 inside to compute r0
2285  * r0 += r6
2286  * if r0 == 0 goto
2287  *
2288  * to track above reg_mask/stack_mask needs to be independent for each frame.
2289  *
2290  * Also if parent's curframe > frame where backtracking started,
2291  * the verifier need to mark registers in both frames, otherwise callees
2292  * may incorrectly prune callers. This is similar to
2293  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2294  *
2295  * For now backtracking falls back into conservative marking.
2296  */
2297 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2298 				     struct bpf_verifier_state *st)
2299 {
2300 	struct bpf_func_state *func;
2301 	struct bpf_reg_state *reg;
2302 	int i, j;
2303 
2304 	/* big hammer: mark all scalars precise in this path.
2305 	 * pop_stack may still get !precise scalars.
2306 	 */
2307 	for (; st; st = st->parent)
2308 		for (i = 0; i <= st->curframe; i++) {
2309 			func = st->frame[i];
2310 			for (j = 0; j < BPF_REG_FP; j++) {
2311 				reg = &func->regs[j];
2312 				if (reg->type != SCALAR_VALUE)
2313 					continue;
2314 				reg->precise = true;
2315 			}
2316 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2317 				if (func->stack[j].slot_type[0] != STACK_SPILL)
2318 					continue;
2319 				reg = &func->stack[j].spilled_ptr;
2320 				if (reg->type != SCALAR_VALUE)
2321 					continue;
2322 				reg->precise = true;
2323 			}
2324 		}
2325 }
2326 
2327 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2328 				  int spi)
2329 {
2330 	struct bpf_verifier_state *st = env->cur_state;
2331 	int first_idx = st->first_insn_idx;
2332 	int last_idx = env->insn_idx;
2333 	struct bpf_func_state *func;
2334 	struct bpf_reg_state *reg;
2335 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2336 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2337 	bool skip_first = true;
2338 	bool new_marks = false;
2339 	int i, err;
2340 
2341 	if (!env->bpf_capable)
2342 		return 0;
2343 
2344 	func = st->frame[st->curframe];
2345 	if (regno >= 0) {
2346 		reg = &func->regs[regno];
2347 		if (reg->type != SCALAR_VALUE) {
2348 			WARN_ONCE(1, "backtracing misuse");
2349 			return -EFAULT;
2350 		}
2351 		if (!reg->precise)
2352 			new_marks = true;
2353 		else
2354 			reg_mask = 0;
2355 		reg->precise = true;
2356 	}
2357 
2358 	while (spi >= 0) {
2359 		if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2360 			stack_mask = 0;
2361 			break;
2362 		}
2363 		reg = &func->stack[spi].spilled_ptr;
2364 		if (reg->type != SCALAR_VALUE) {
2365 			stack_mask = 0;
2366 			break;
2367 		}
2368 		if (!reg->precise)
2369 			new_marks = true;
2370 		else
2371 			stack_mask = 0;
2372 		reg->precise = true;
2373 		break;
2374 	}
2375 
2376 	if (!new_marks)
2377 		return 0;
2378 	if (!reg_mask && !stack_mask)
2379 		return 0;
2380 	for (;;) {
2381 		DECLARE_BITMAP(mask, 64);
2382 		u32 history = st->jmp_history_cnt;
2383 
2384 		if (env->log.level & BPF_LOG_LEVEL)
2385 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2386 		for (i = last_idx;;) {
2387 			if (skip_first) {
2388 				err = 0;
2389 				skip_first = false;
2390 			} else {
2391 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2392 			}
2393 			if (err == -ENOTSUPP) {
2394 				mark_all_scalars_precise(env, st);
2395 				return 0;
2396 			} else if (err) {
2397 				return err;
2398 			}
2399 			if (!reg_mask && !stack_mask)
2400 				/* Found assignment(s) into tracked register in this state.
2401 				 * Since this state is already marked, just return.
2402 				 * Nothing to be tracked further in the parent state.
2403 				 */
2404 				return 0;
2405 			if (i == first_idx)
2406 				break;
2407 			i = get_prev_insn_idx(st, i, &history);
2408 			if (i >= env->prog->len) {
2409 				/* This can happen if backtracking reached insn 0
2410 				 * and there are still reg_mask or stack_mask
2411 				 * to backtrack.
2412 				 * It means the backtracking missed the spot where
2413 				 * particular register was initialized with a constant.
2414 				 */
2415 				verbose(env, "BUG backtracking idx %d\n", i);
2416 				WARN_ONCE(1, "verifier backtracking bug");
2417 				return -EFAULT;
2418 			}
2419 		}
2420 		st = st->parent;
2421 		if (!st)
2422 			break;
2423 
2424 		new_marks = false;
2425 		func = st->frame[st->curframe];
2426 		bitmap_from_u64(mask, reg_mask);
2427 		for_each_set_bit(i, mask, 32) {
2428 			reg = &func->regs[i];
2429 			if (reg->type != SCALAR_VALUE) {
2430 				reg_mask &= ~(1u << i);
2431 				continue;
2432 			}
2433 			if (!reg->precise)
2434 				new_marks = true;
2435 			reg->precise = true;
2436 		}
2437 
2438 		bitmap_from_u64(mask, stack_mask);
2439 		for_each_set_bit(i, mask, 64) {
2440 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2441 				/* the sequence of instructions:
2442 				 * 2: (bf) r3 = r10
2443 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2444 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2445 				 * doesn't contain jmps. It's backtracked
2446 				 * as a single block.
2447 				 * During backtracking insn 3 is not recognized as
2448 				 * stack access, so at the end of backtracking
2449 				 * stack slot fp-8 is still marked in stack_mask.
2450 				 * However the parent state may not have accessed
2451 				 * fp-8 and it's "unallocated" stack space.
2452 				 * In such case fallback to conservative.
2453 				 */
2454 				mark_all_scalars_precise(env, st);
2455 				return 0;
2456 			}
2457 
2458 			if (func->stack[i].slot_type[0] != STACK_SPILL) {
2459 				stack_mask &= ~(1ull << i);
2460 				continue;
2461 			}
2462 			reg = &func->stack[i].spilled_ptr;
2463 			if (reg->type != SCALAR_VALUE) {
2464 				stack_mask &= ~(1ull << i);
2465 				continue;
2466 			}
2467 			if (!reg->precise)
2468 				new_marks = true;
2469 			reg->precise = true;
2470 		}
2471 		if (env->log.level & BPF_LOG_LEVEL) {
2472 			print_verifier_state(env, func);
2473 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2474 				new_marks ? "didn't have" : "already had",
2475 				reg_mask, stack_mask);
2476 		}
2477 
2478 		if (!reg_mask && !stack_mask)
2479 			break;
2480 		if (!new_marks)
2481 			break;
2482 
2483 		last_idx = st->last_insn_idx;
2484 		first_idx = st->first_insn_idx;
2485 	}
2486 	return 0;
2487 }
2488 
2489 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2490 {
2491 	return __mark_chain_precision(env, regno, -1);
2492 }
2493 
2494 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2495 {
2496 	return __mark_chain_precision(env, -1, spi);
2497 }
2498 
2499 static bool is_spillable_regtype(enum bpf_reg_type type)
2500 {
2501 	switch (type) {
2502 	case PTR_TO_MAP_VALUE:
2503 	case PTR_TO_MAP_VALUE_OR_NULL:
2504 	case PTR_TO_STACK:
2505 	case PTR_TO_CTX:
2506 	case PTR_TO_PACKET:
2507 	case PTR_TO_PACKET_META:
2508 	case PTR_TO_PACKET_END:
2509 	case PTR_TO_FLOW_KEYS:
2510 	case CONST_PTR_TO_MAP:
2511 	case PTR_TO_SOCKET:
2512 	case PTR_TO_SOCKET_OR_NULL:
2513 	case PTR_TO_SOCK_COMMON:
2514 	case PTR_TO_SOCK_COMMON_OR_NULL:
2515 	case PTR_TO_TCP_SOCK:
2516 	case PTR_TO_TCP_SOCK_OR_NULL:
2517 	case PTR_TO_XDP_SOCK:
2518 	case PTR_TO_BTF_ID:
2519 	case PTR_TO_BTF_ID_OR_NULL:
2520 	case PTR_TO_RDONLY_BUF:
2521 	case PTR_TO_RDONLY_BUF_OR_NULL:
2522 	case PTR_TO_RDWR_BUF:
2523 	case PTR_TO_RDWR_BUF_OR_NULL:
2524 	case PTR_TO_PERCPU_BTF_ID:
2525 	case PTR_TO_MEM:
2526 	case PTR_TO_MEM_OR_NULL:
2527 	case PTR_TO_FUNC:
2528 	case PTR_TO_MAP_KEY:
2529 		return true;
2530 	default:
2531 		return false;
2532 	}
2533 }
2534 
2535 /* Does this register contain a constant zero? */
2536 static bool register_is_null(struct bpf_reg_state *reg)
2537 {
2538 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2539 }
2540 
2541 static bool register_is_const(struct bpf_reg_state *reg)
2542 {
2543 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2544 }
2545 
2546 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2547 {
2548 	return tnum_is_unknown(reg->var_off) &&
2549 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2550 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2551 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2552 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2553 }
2554 
2555 static bool register_is_bounded(struct bpf_reg_state *reg)
2556 {
2557 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2558 }
2559 
2560 static bool __is_pointer_value(bool allow_ptr_leaks,
2561 			       const struct bpf_reg_state *reg)
2562 {
2563 	if (allow_ptr_leaks)
2564 		return false;
2565 
2566 	return reg->type != SCALAR_VALUE;
2567 }
2568 
2569 static void save_register_state(struct bpf_func_state *state,
2570 				int spi, struct bpf_reg_state *reg)
2571 {
2572 	int i;
2573 
2574 	state->stack[spi].spilled_ptr = *reg;
2575 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2576 
2577 	for (i = 0; i < BPF_REG_SIZE; i++)
2578 		state->stack[spi].slot_type[i] = STACK_SPILL;
2579 }
2580 
2581 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2582  * stack boundary and alignment are checked in check_mem_access()
2583  */
2584 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2585 				       /* stack frame we're writing to */
2586 				       struct bpf_func_state *state,
2587 				       int off, int size, int value_regno,
2588 				       int insn_idx)
2589 {
2590 	struct bpf_func_state *cur; /* state of the current function */
2591 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2592 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2593 	struct bpf_reg_state *reg = NULL;
2594 
2595 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2596 				 state->acquired_refs, true);
2597 	if (err)
2598 		return err;
2599 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2600 	 * so it's aligned access and [off, off + size) are within stack limits
2601 	 */
2602 	if (!env->allow_ptr_leaks &&
2603 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2604 	    size != BPF_REG_SIZE) {
2605 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2606 		return -EACCES;
2607 	}
2608 
2609 	cur = env->cur_state->frame[env->cur_state->curframe];
2610 	if (value_regno >= 0)
2611 		reg = &cur->regs[value_regno];
2612 
2613 	if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2614 	    !register_is_null(reg) && env->bpf_capable) {
2615 		if (dst_reg != BPF_REG_FP) {
2616 			/* The backtracking logic can only recognize explicit
2617 			 * stack slot address like [fp - 8]. Other spill of
2618 			 * scalar via different register has to be conervative.
2619 			 * Backtrack from here and mark all registers as precise
2620 			 * that contributed into 'reg' being a constant.
2621 			 */
2622 			err = mark_chain_precision(env, value_regno);
2623 			if (err)
2624 				return err;
2625 		}
2626 		save_register_state(state, spi, reg);
2627 	} else if (reg && is_spillable_regtype(reg->type)) {
2628 		/* register containing pointer is being spilled into stack */
2629 		if (size != BPF_REG_SIZE) {
2630 			verbose_linfo(env, insn_idx, "; ");
2631 			verbose(env, "invalid size of register spill\n");
2632 			return -EACCES;
2633 		}
2634 
2635 		if (state != cur && reg->type == PTR_TO_STACK) {
2636 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2637 			return -EINVAL;
2638 		}
2639 
2640 		if (!env->bypass_spec_v4) {
2641 			bool sanitize = false;
2642 
2643 			if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2644 			    register_is_const(&state->stack[spi].spilled_ptr))
2645 				sanitize = true;
2646 			for (i = 0; i < BPF_REG_SIZE; i++)
2647 				if (state->stack[spi].slot_type[i] == STACK_MISC) {
2648 					sanitize = true;
2649 					break;
2650 				}
2651 			if (sanitize) {
2652 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2653 				int soff = (-spi - 1) * BPF_REG_SIZE;
2654 
2655 				/* detected reuse of integer stack slot with a pointer
2656 				 * which means either llvm is reusing stack slot or
2657 				 * an attacker is trying to exploit CVE-2018-3639
2658 				 * (speculative store bypass)
2659 				 * Have to sanitize that slot with preemptive
2660 				 * store of zero.
2661 				 */
2662 				if (*poff && *poff != soff) {
2663 					/* disallow programs where single insn stores
2664 					 * into two different stack slots, since verifier
2665 					 * cannot sanitize them
2666 					 */
2667 					verbose(env,
2668 						"insn %d cannot access two stack slots fp%d and fp%d",
2669 						insn_idx, *poff, soff);
2670 					return -EINVAL;
2671 				}
2672 				*poff = soff;
2673 			}
2674 		}
2675 		save_register_state(state, spi, reg);
2676 	} else {
2677 		u8 type = STACK_MISC;
2678 
2679 		/* regular write of data into stack destroys any spilled ptr */
2680 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2681 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2682 		if (state->stack[spi].slot_type[0] == STACK_SPILL)
2683 			for (i = 0; i < BPF_REG_SIZE; i++)
2684 				state->stack[spi].slot_type[i] = STACK_MISC;
2685 
2686 		/* only mark the slot as written if all 8 bytes were written
2687 		 * otherwise read propagation may incorrectly stop too soon
2688 		 * when stack slots are partially written.
2689 		 * This heuristic means that read propagation will be
2690 		 * conservative, since it will add reg_live_read marks
2691 		 * to stack slots all the way to first state when programs
2692 		 * writes+reads less than 8 bytes
2693 		 */
2694 		if (size == BPF_REG_SIZE)
2695 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2696 
2697 		/* when we zero initialize stack slots mark them as such */
2698 		if (reg && register_is_null(reg)) {
2699 			/* backtracking doesn't work for STACK_ZERO yet. */
2700 			err = mark_chain_precision(env, value_regno);
2701 			if (err)
2702 				return err;
2703 			type = STACK_ZERO;
2704 		}
2705 
2706 		/* Mark slots affected by this stack write. */
2707 		for (i = 0; i < size; i++)
2708 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2709 				type;
2710 	}
2711 	return 0;
2712 }
2713 
2714 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2715  * known to contain a variable offset.
2716  * This function checks whether the write is permitted and conservatively
2717  * tracks the effects of the write, considering that each stack slot in the
2718  * dynamic range is potentially written to.
2719  *
2720  * 'off' includes 'regno->off'.
2721  * 'value_regno' can be -1, meaning that an unknown value is being written to
2722  * the stack.
2723  *
2724  * Spilled pointers in range are not marked as written because we don't know
2725  * what's going to be actually written. This means that read propagation for
2726  * future reads cannot be terminated by this write.
2727  *
2728  * For privileged programs, uninitialized stack slots are considered
2729  * initialized by this write (even though we don't know exactly what offsets
2730  * are going to be written to). The idea is that we don't want the verifier to
2731  * reject future reads that access slots written to through variable offsets.
2732  */
2733 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2734 				     /* func where register points to */
2735 				     struct bpf_func_state *state,
2736 				     int ptr_regno, int off, int size,
2737 				     int value_regno, int insn_idx)
2738 {
2739 	struct bpf_func_state *cur; /* state of the current function */
2740 	int min_off, max_off;
2741 	int i, err;
2742 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2743 	bool writing_zero = false;
2744 	/* set if the fact that we're writing a zero is used to let any
2745 	 * stack slots remain STACK_ZERO
2746 	 */
2747 	bool zero_used = false;
2748 
2749 	cur = env->cur_state->frame[env->cur_state->curframe];
2750 	ptr_reg = &cur->regs[ptr_regno];
2751 	min_off = ptr_reg->smin_value + off;
2752 	max_off = ptr_reg->smax_value + off + size;
2753 	if (value_regno >= 0)
2754 		value_reg = &cur->regs[value_regno];
2755 	if (value_reg && register_is_null(value_reg))
2756 		writing_zero = true;
2757 
2758 	err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2759 				 state->acquired_refs, true);
2760 	if (err)
2761 		return err;
2762 
2763 
2764 	/* Variable offset writes destroy any spilled pointers in range. */
2765 	for (i = min_off; i < max_off; i++) {
2766 		u8 new_type, *stype;
2767 		int slot, spi;
2768 
2769 		slot = -i - 1;
2770 		spi = slot / BPF_REG_SIZE;
2771 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2772 
2773 		if (!env->allow_ptr_leaks
2774 				&& *stype != NOT_INIT
2775 				&& *stype != SCALAR_VALUE) {
2776 			/* Reject the write if there's are spilled pointers in
2777 			 * range. If we didn't reject here, the ptr status
2778 			 * would be erased below (even though not all slots are
2779 			 * actually overwritten), possibly opening the door to
2780 			 * leaks.
2781 			 */
2782 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2783 				insn_idx, i);
2784 			return -EINVAL;
2785 		}
2786 
2787 		/* Erase all spilled pointers. */
2788 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2789 
2790 		/* Update the slot type. */
2791 		new_type = STACK_MISC;
2792 		if (writing_zero && *stype == STACK_ZERO) {
2793 			new_type = STACK_ZERO;
2794 			zero_used = true;
2795 		}
2796 		/* If the slot is STACK_INVALID, we check whether it's OK to
2797 		 * pretend that it will be initialized by this write. The slot
2798 		 * might not actually be written to, and so if we mark it as
2799 		 * initialized future reads might leak uninitialized memory.
2800 		 * For privileged programs, we will accept such reads to slots
2801 		 * that may or may not be written because, if we're reject
2802 		 * them, the error would be too confusing.
2803 		 */
2804 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2805 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2806 					insn_idx, i);
2807 			return -EINVAL;
2808 		}
2809 		*stype = new_type;
2810 	}
2811 	if (zero_used) {
2812 		/* backtracking doesn't work for STACK_ZERO yet. */
2813 		err = mark_chain_precision(env, value_regno);
2814 		if (err)
2815 			return err;
2816 	}
2817 	return 0;
2818 }
2819 
2820 /* When register 'dst_regno' is assigned some values from stack[min_off,
2821  * max_off), we set the register's type according to the types of the
2822  * respective stack slots. If all the stack values are known to be zeros, then
2823  * so is the destination reg. Otherwise, the register is considered to be
2824  * SCALAR. This function does not deal with register filling; the caller must
2825  * ensure that all spilled registers in the stack range have been marked as
2826  * read.
2827  */
2828 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2829 				/* func where src register points to */
2830 				struct bpf_func_state *ptr_state,
2831 				int min_off, int max_off, int dst_regno)
2832 {
2833 	struct bpf_verifier_state *vstate = env->cur_state;
2834 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2835 	int i, slot, spi;
2836 	u8 *stype;
2837 	int zeros = 0;
2838 
2839 	for (i = min_off; i < max_off; i++) {
2840 		slot = -i - 1;
2841 		spi = slot / BPF_REG_SIZE;
2842 		stype = ptr_state->stack[spi].slot_type;
2843 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2844 			break;
2845 		zeros++;
2846 	}
2847 	if (zeros == max_off - min_off) {
2848 		/* any access_size read into register is zero extended,
2849 		 * so the whole register == const_zero
2850 		 */
2851 		__mark_reg_const_zero(&state->regs[dst_regno]);
2852 		/* backtracking doesn't support STACK_ZERO yet,
2853 		 * so mark it precise here, so that later
2854 		 * backtracking can stop here.
2855 		 * Backtracking may not need this if this register
2856 		 * doesn't participate in pointer adjustment.
2857 		 * Forward propagation of precise flag is not
2858 		 * necessary either. This mark is only to stop
2859 		 * backtracking. Any register that contributed
2860 		 * to const 0 was marked precise before spill.
2861 		 */
2862 		state->regs[dst_regno].precise = true;
2863 	} else {
2864 		/* have read misc data from the stack */
2865 		mark_reg_unknown(env, state->regs, dst_regno);
2866 	}
2867 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2868 }
2869 
2870 /* Read the stack at 'off' and put the results into the register indicated by
2871  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2872  * spilled reg.
2873  *
2874  * 'dst_regno' can be -1, meaning that the read value is not going to a
2875  * register.
2876  *
2877  * The access is assumed to be within the current stack bounds.
2878  */
2879 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2880 				      /* func where src register points to */
2881 				      struct bpf_func_state *reg_state,
2882 				      int off, int size, int dst_regno)
2883 {
2884 	struct bpf_verifier_state *vstate = env->cur_state;
2885 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2886 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2887 	struct bpf_reg_state *reg;
2888 	u8 *stype;
2889 
2890 	stype = reg_state->stack[spi].slot_type;
2891 	reg = &reg_state->stack[spi].spilled_ptr;
2892 
2893 	if (stype[0] == STACK_SPILL) {
2894 		if (size != BPF_REG_SIZE) {
2895 			if (reg->type != SCALAR_VALUE) {
2896 				verbose_linfo(env, env->insn_idx, "; ");
2897 				verbose(env, "invalid size of register fill\n");
2898 				return -EACCES;
2899 			}
2900 			if (dst_regno >= 0) {
2901 				mark_reg_unknown(env, state->regs, dst_regno);
2902 				state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2903 			}
2904 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2905 			return 0;
2906 		}
2907 		for (i = 1; i < BPF_REG_SIZE; i++) {
2908 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2909 				verbose(env, "corrupted spill memory\n");
2910 				return -EACCES;
2911 			}
2912 		}
2913 
2914 		if (dst_regno >= 0) {
2915 			/* restore register state from stack */
2916 			state->regs[dst_regno] = *reg;
2917 			/* mark reg as written since spilled pointer state likely
2918 			 * has its liveness marks cleared by is_state_visited()
2919 			 * which resets stack/reg liveness for state transitions
2920 			 */
2921 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2922 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2923 			/* If dst_regno==-1, the caller is asking us whether
2924 			 * it is acceptable to use this value as a SCALAR_VALUE
2925 			 * (e.g. for XADD).
2926 			 * We must not allow unprivileged callers to do that
2927 			 * with spilled pointers.
2928 			 */
2929 			verbose(env, "leaking pointer from stack off %d\n",
2930 				off);
2931 			return -EACCES;
2932 		}
2933 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2934 	} else {
2935 		u8 type;
2936 
2937 		for (i = 0; i < size; i++) {
2938 			type = stype[(slot - i) % BPF_REG_SIZE];
2939 			if (type == STACK_MISC)
2940 				continue;
2941 			if (type == STACK_ZERO)
2942 				continue;
2943 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2944 				off, i, size);
2945 			return -EACCES;
2946 		}
2947 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2948 		if (dst_regno >= 0)
2949 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2950 	}
2951 	return 0;
2952 }
2953 
2954 enum stack_access_src {
2955 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2956 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
2957 };
2958 
2959 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2960 					 int regno, int off, int access_size,
2961 					 bool zero_size_allowed,
2962 					 enum stack_access_src type,
2963 					 struct bpf_call_arg_meta *meta);
2964 
2965 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2966 {
2967 	return cur_regs(env) + regno;
2968 }
2969 
2970 /* Read the stack at 'ptr_regno + off' and put the result into the register
2971  * 'dst_regno'.
2972  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2973  * but not its variable offset.
2974  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2975  *
2976  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2977  * filling registers (i.e. reads of spilled register cannot be detected when
2978  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2979  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2980  * offset; for a fixed offset check_stack_read_fixed_off should be used
2981  * instead.
2982  */
2983 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2984 				    int ptr_regno, int off, int size, int dst_regno)
2985 {
2986 	/* The state of the source register. */
2987 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2988 	struct bpf_func_state *ptr_state = func(env, reg);
2989 	int err;
2990 	int min_off, max_off;
2991 
2992 	/* Note that we pass a NULL meta, so raw access will not be permitted.
2993 	 */
2994 	err = check_stack_range_initialized(env, ptr_regno, off, size,
2995 					    false, ACCESS_DIRECT, NULL);
2996 	if (err)
2997 		return err;
2998 
2999 	min_off = reg->smin_value + off;
3000 	max_off = reg->smax_value + off;
3001 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3002 	return 0;
3003 }
3004 
3005 /* check_stack_read dispatches to check_stack_read_fixed_off or
3006  * check_stack_read_var_off.
3007  *
3008  * The caller must ensure that the offset falls within the allocated stack
3009  * bounds.
3010  *
3011  * 'dst_regno' is a register which will receive the value from the stack. It
3012  * can be -1, meaning that the read value is not going to a register.
3013  */
3014 static int check_stack_read(struct bpf_verifier_env *env,
3015 			    int ptr_regno, int off, int size,
3016 			    int dst_regno)
3017 {
3018 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3019 	struct bpf_func_state *state = func(env, reg);
3020 	int err;
3021 	/* Some accesses are only permitted with a static offset. */
3022 	bool var_off = !tnum_is_const(reg->var_off);
3023 
3024 	/* The offset is required to be static when reads don't go to a
3025 	 * register, in order to not leak pointers (see
3026 	 * check_stack_read_fixed_off).
3027 	 */
3028 	if (dst_regno < 0 && var_off) {
3029 		char tn_buf[48];
3030 
3031 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3032 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3033 			tn_buf, off, size);
3034 		return -EACCES;
3035 	}
3036 	/* Variable offset is prohibited for unprivileged mode for simplicity
3037 	 * since it requires corresponding support in Spectre masking for stack
3038 	 * ALU. See also retrieve_ptr_limit().
3039 	 */
3040 	if (!env->bypass_spec_v1 && var_off) {
3041 		char tn_buf[48];
3042 
3043 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3044 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3045 				ptr_regno, tn_buf);
3046 		return -EACCES;
3047 	}
3048 
3049 	if (!var_off) {
3050 		off += reg->var_off.value;
3051 		err = check_stack_read_fixed_off(env, state, off, size,
3052 						 dst_regno);
3053 	} else {
3054 		/* Variable offset stack reads need more conservative handling
3055 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3056 		 * branch.
3057 		 */
3058 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3059 					       dst_regno);
3060 	}
3061 	return err;
3062 }
3063 
3064 
3065 /* check_stack_write dispatches to check_stack_write_fixed_off or
3066  * check_stack_write_var_off.
3067  *
3068  * 'ptr_regno' is the register used as a pointer into the stack.
3069  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3070  * 'value_regno' is the register whose value we're writing to the stack. It can
3071  * be -1, meaning that we're not writing from a register.
3072  *
3073  * The caller must ensure that the offset falls within the maximum stack size.
3074  */
3075 static int check_stack_write(struct bpf_verifier_env *env,
3076 			     int ptr_regno, int off, int size,
3077 			     int value_regno, int insn_idx)
3078 {
3079 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3080 	struct bpf_func_state *state = func(env, reg);
3081 	int err;
3082 
3083 	if (tnum_is_const(reg->var_off)) {
3084 		off += reg->var_off.value;
3085 		err = check_stack_write_fixed_off(env, state, off, size,
3086 						  value_regno, insn_idx);
3087 	} else {
3088 		/* Variable offset stack reads need more conservative handling
3089 		 * than fixed offset ones.
3090 		 */
3091 		err = check_stack_write_var_off(env, state,
3092 						ptr_regno, off, size,
3093 						value_regno, insn_idx);
3094 	}
3095 	return err;
3096 }
3097 
3098 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3099 				 int off, int size, enum bpf_access_type type)
3100 {
3101 	struct bpf_reg_state *regs = cur_regs(env);
3102 	struct bpf_map *map = regs[regno].map_ptr;
3103 	u32 cap = bpf_map_flags_to_cap(map);
3104 
3105 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3106 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3107 			map->value_size, off, size);
3108 		return -EACCES;
3109 	}
3110 
3111 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3112 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3113 			map->value_size, off, size);
3114 		return -EACCES;
3115 	}
3116 
3117 	return 0;
3118 }
3119 
3120 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3121 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3122 			      int off, int size, u32 mem_size,
3123 			      bool zero_size_allowed)
3124 {
3125 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3126 	struct bpf_reg_state *reg;
3127 
3128 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3129 		return 0;
3130 
3131 	reg = &cur_regs(env)[regno];
3132 	switch (reg->type) {
3133 	case PTR_TO_MAP_KEY:
3134 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3135 			mem_size, off, size);
3136 		break;
3137 	case PTR_TO_MAP_VALUE:
3138 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3139 			mem_size, off, size);
3140 		break;
3141 	case PTR_TO_PACKET:
3142 	case PTR_TO_PACKET_META:
3143 	case PTR_TO_PACKET_END:
3144 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3145 			off, size, regno, reg->id, off, mem_size);
3146 		break;
3147 	case PTR_TO_MEM:
3148 	default:
3149 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3150 			mem_size, off, size);
3151 	}
3152 
3153 	return -EACCES;
3154 }
3155 
3156 /* check read/write into a memory region with possible variable offset */
3157 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3158 				   int off, int size, u32 mem_size,
3159 				   bool zero_size_allowed)
3160 {
3161 	struct bpf_verifier_state *vstate = env->cur_state;
3162 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3163 	struct bpf_reg_state *reg = &state->regs[regno];
3164 	int err;
3165 
3166 	/* We may have adjusted the register pointing to memory region, so we
3167 	 * need to try adding each of min_value and max_value to off
3168 	 * to make sure our theoretical access will be safe.
3169 	 */
3170 	if (env->log.level & BPF_LOG_LEVEL)
3171 		print_verifier_state(env, state);
3172 
3173 	/* The minimum value is only important with signed
3174 	 * comparisons where we can't assume the floor of a
3175 	 * value is 0.  If we are using signed variables for our
3176 	 * index'es we need to make sure that whatever we use
3177 	 * will have a set floor within our range.
3178 	 */
3179 	if (reg->smin_value < 0 &&
3180 	    (reg->smin_value == S64_MIN ||
3181 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3182 	      reg->smin_value + off < 0)) {
3183 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3184 			regno);
3185 		return -EACCES;
3186 	}
3187 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3188 				 mem_size, zero_size_allowed);
3189 	if (err) {
3190 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3191 			regno);
3192 		return err;
3193 	}
3194 
3195 	/* If we haven't set a max value then we need to bail since we can't be
3196 	 * sure we won't do bad things.
3197 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3198 	 */
3199 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3200 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3201 			regno);
3202 		return -EACCES;
3203 	}
3204 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3205 				 mem_size, zero_size_allowed);
3206 	if (err) {
3207 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3208 			regno);
3209 		return err;
3210 	}
3211 
3212 	return 0;
3213 }
3214 
3215 /* check read/write into a map element with possible variable offset */
3216 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3217 			    int off, int size, bool zero_size_allowed)
3218 {
3219 	struct bpf_verifier_state *vstate = env->cur_state;
3220 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3221 	struct bpf_reg_state *reg = &state->regs[regno];
3222 	struct bpf_map *map = reg->map_ptr;
3223 	int err;
3224 
3225 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3226 				      zero_size_allowed);
3227 	if (err)
3228 		return err;
3229 
3230 	if (map_value_has_spin_lock(map)) {
3231 		u32 lock = map->spin_lock_off;
3232 
3233 		/* if any part of struct bpf_spin_lock can be touched by
3234 		 * load/store reject this program.
3235 		 * To check that [x1, x2) overlaps with [y1, y2)
3236 		 * it is sufficient to check x1 < y2 && y1 < x2.
3237 		 */
3238 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3239 		     lock < reg->umax_value + off + size) {
3240 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3241 			return -EACCES;
3242 		}
3243 	}
3244 	return err;
3245 }
3246 
3247 #define MAX_PACKET_OFF 0xffff
3248 
3249 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3250 {
3251 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3252 }
3253 
3254 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3255 				       const struct bpf_call_arg_meta *meta,
3256 				       enum bpf_access_type t)
3257 {
3258 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3259 
3260 	switch (prog_type) {
3261 	/* Program types only with direct read access go here! */
3262 	case BPF_PROG_TYPE_LWT_IN:
3263 	case BPF_PROG_TYPE_LWT_OUT:
3264 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3265 	case BPF_PROG_TYPE_SK_REUSEPORT:
3266 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3267 	case BPF_PROG_TYPE_CGROUP_SKB:
3268 		if (t == BPF_WRITE)
3269 			return false;
3270 		fallthrough;
3271 
3272 	/* Program types with direct read + write access go here! */
3273 	case BPF_PROG_TYPE_SCHED_CLS:
3274 	case BPF_PROG_TYPE_SCHED_ACT:
3275 	case BPF_PROG_TYPE_XDP:
3276 	case BPF_PROG_TYPE_LWT_XMIT:
3277 	case BPF_PROG_TYPE_SK_SKB:
3278 	case BPF_PROG_TYPE_SK_MSG:
3279 		if (meta)
3280 			return meta->pkt_access;
3281 
3282 		env->seen_direct_write = true;
3283 		return true;
3284 
3285 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3286 		if (t == BPF_WRITE)
3287 			env->seen_direct_write = true;
3288 
3289 		return true;
3290 
3291 	default:
3292 		return false;
3293 	}
3294 }
3295 
3296 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3297 			       int size, bool zero_size_allowed)
3298 {
3299 	struct bpf_reg_state *regs = cur_regs(env);
3300 	struct bpf_reg_state *reg = &regs[regno];
3301 	int err;
3302 
3303 	/* We may have added a variable offset to the packet pointer; but any
3304 	 * reg->range we have comes after that.  We are only checking the fixed
3305 	 * offset.
3306 	 */
3307 
3308 	/* We don't allow negative numbers, because we aren't tracking enough
3309 	 * detail to prove they're safe.
3310 	 */
3311 	if (reg->smin_value < 0) {
3312 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3313 			regno);
3314 		return -EACCES;
3315 	}
3316 
3317 	err = reg->range < 0 ? -EINVAL :
3318 	      __check_mem_access(env, regno, off, size, reg->range,
3319 				 zero_size_allowed);
3320 	if (err) {
3321 		verbose(env, "R%d offset is outside of the packet\n", regno);
3322 		return err;
3323 	}
3324 
3325 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3326 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3327 	 * otherwise find_good_pkt_pointers would have refused to set range info
3328 	 * that __check_mem_access would have rejected this pkt access.
3329 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3330 	 */
3331 	env->prog->aux->max_pkt_offset =
3332 		max_t(u32, env->prog->aux->max_pkt_offset,
3333 		      off + reg->umax_value + size - 1);
3334 
3335 	return err;
3336 }
3337 
3338 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3339 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3340 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3341 			    struct btf **btf, u32 *btf_id)
3342 {
3343 	struct bpf_insn_access_aux info = {
3344 		.reg_type = *reg_type,
3345 		.log = &env->log,
3346 	};
3347 
3348 	if (env->ops->is_valid_access &&
3349 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3350 		/* A non zero info.ctx_field_size indicates that this field is a
3351 		 * candidate for later verifier transformation to load the whole
3352 		 * field and then apply a mask when accessed with a narrower
3353 		 * access than actual ctx access size. A zero info.ctx_field_size
3354 		 * will only allow for whole field access and rejects any other
3355 		 * type of narrower access.
3356 		 */
3357 		*reg_type = info.reg_type;
3358 
3359 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3360 			*btf = info.btf;
3361 			*btf_id = info.btf_id;
3362 		} else {
3363 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3364 		}
3365 		/* remember the offset of last byte accessed in ctx */
3366 		if (env->prog->aux->max_ctx_offset < off + size)
3367 			env->prog->aux->max_ctx_offset = off + size;
3368 		return 0;
3369 	}
3370 
3371 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3372 	return -EACCES;
3373 }
3374 
3375 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3376 				  int size)
3377 {
3378 	if (size < 0 || off < 0 ||
3379 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3380 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3381 			off, size);
3382 		return -EACCES;
3383 	}
3384 	return 0;
3385 }
3386 
3387 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3388 			     u32 regno, int off, int size,
3389 			     enum bpf_access_type t)
3390 {
3391 	struct bpf_reg_state *regs = cur_regs(env);
3392 	struct bpf_reg_state *reg = &regs[regno];
3393 	struct bpf_insn_access_aux info = {};
3394 	bool valid;
3395 
3396 	if (reg->smin_value < 0) {
3397 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3398 			regno);
3399 		return -EACCES;
3400 	}
3401 
3402 	switch (reg->type) {
3403 	case PTR_TO_SOCK_COMMON:
3404 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3405 		break;
3406 	case PTR_TO_SOCKET:
3407 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3408 		break;
3409 	case PTR_TO_TCP_SOCK:
3410 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3411 		break;
3412 	case PTR_TO_XDP_SOCK:
3413 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3414 		break;
3415 	default:
3416 		valid = false;
3417 	}
3418 
3419 
3420 	if (valid) {
3421 		env->insn_aux_data[insn_idx].ctx_field_size =
3422 			info.ctx_field_size;
3423 		return 0;
3424 	}
3425 
3426 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3427 		regno, reg_type_str[reg->type], off, size);
3428 
3429 	return -EACCES;
3430 }
3431 
3432 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3433 {
3434 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3435 }
3436 
3437 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3438 {
3439 	const struct bpf_reg_state *reg = reg_state(env, regno);
3440 
3441 	return reg->type == PTR_TO_CTX;
3442 }
3443 
3444 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3445 {
3446 	const struct bpf_reg_state *reg = reg_state(env, regno);
3447 
3448 	return type_is_sk_pointer(reg->type);
3449 }
3450 
3451 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3452 {
3453 	const struct bpf_reg_state *reg = reg_state(env, regno);
3454 
3455 	return type_is_pkt_pointer(reg->type);
3456 }
3457 
3458 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3459 {
3460 	const struct bpf_reg_state *reg = reg_state(env, regno);
3461 
3462 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3463 	return reg->type == PTR_TO_FLOW_KEYS;
3464 }
3465 
3466 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3467 				   const struct bpf_reg_state *reg,
3468 				   int off, int size, bool strict)
3469 {
3470 	struct tnum reg_off;
3471 	int ip_align;
3472 
3473 	/* Byte size accesses are always allowed. */
3474 	if (!strict || size == 1)
3475 		return 0;
3476 
3477 	/* For platforms that do not have a Kconfig enabling
3478 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3479 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3480 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3481 	 * to this code only in strict mode where we want to emulate
3482 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3483 	 * unconditional IP align value of '2'.
3484 	 */
3485 	ip_align = 2;
3486 
3487 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3488 	if (!tnum_is_aligned(reg_off, size)) {
3489 		char tn_buf[48];
3490 
3491 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3492 		verbose(env,
3493 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3494 			ip_align, tn_buf, reg->off, off, size);
3495 		return -EACCES;
3496 	}
3497 
3498 	return 0;
3499 }
3500 
3501 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3502 				       const struct bpf_reg_state *reg,
3503 				       const char *pointer_desc,
3504 				       int off, int size, bool strict)
3505 {
3506 	struct tnum reg_off;
3507 
3508 	/* Byte size accesses are always allowed. */
3509 	if (!strict || size == 1)
3510 		return 0;
3511 
3512 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3513 	if (!tnum_is_aligned(reg_off, size)) {
3514 		char tn_buf[48];
3515 
3516 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3517 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3518 			pointer_desc, tn_buf, reg->off, off, size);
3519 		return -EACCES;
3520 	}
3521 
3522 	return 0;
3523 }
3524 
3525 static int check_ptr_alignment(struct bpf_verifier_env *env,
3526 			       const struct bpf_reg_state *reg, int off,
3527 			       int size, bool strict_alignment_once)
3528 {
3529 	bool strict = env->strict_alignment || strict_alignment_once;
3530 	const char *pointer_desc = "";
3531 
3532 	switch (reg->type) {
3533 	case PTR_TO_PACKET:
3534 	case PTR_TO_PACKET_META:
3535 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3536 		 * right in front, treat it the very same way.
3537 		 */
3538 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3539 	case PTR_TO_FLOW_KEYS:
3540 		pointer_desc = "flow keys ";
3541 		break;
3542 	case PTR_TO_MAP_KEY:
3543 		pointer_desc = "key ";
3544 		break;
3545 	case PTR_TO_MAP_VALUE:
3546 		pointer_desc = "value ";
3547 		break;
3548 	case PTR_TO_CTX:
3549 		pointer_desc = "context ";
3550 		break;
3551 	case PTR_TO_STACK:
3552 		pointer_desc = "stack ";
3553 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3554 		 * and check_stack_read_fixed_off() relies on stack accesses being
3555 		 * aligned.
3556 		 */
3557 		strict = true;
3558 		break;
3559 	case PTR_TO_SOCKET:
3560 		pointer_desc = "sock ";
3561 		break;
3562 	case PTR_TO_SOCK_COMMON:
3563 		pointer_desc = "sock_common ";
3564 		break;
3565 	case PTR_TO_TCP_SOCK:
3566 		pointer_desc = "tcp_sock ";
3567 		break;
3568 	case PTR_TO_XDP_SOCK:
3569 		pointer_desc = "xdp_sock ";
3570 		break;
3571 	default:
3572 		break;
3573 	}
3574 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3575 					   strict);
3576 }
3577 
3578 static int update_stack_depth(struct bpf_verifier_env *env,
3579 			      const struct bpf_func_state *func,
3580 			      int off)
3581 {
3582 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3583 
3584 	if (stack >= -off)
3585 		return 0;
3586 
3587 	/* update known max for given subprogram */
3588 	env->subprog_info[func->subprogno].stack_depth = -off;
3589 	return 0;
3590 }
3591 
3592 /* starting from main bpf function walk all instructions of the function
3593  * and recursively walk all callees that given function can call.
3594  * Ignore jump and exit insns.
3595  * Since recursion is prevented by check_cfg() this algorithm
3596  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3597  */
3598 static int check_max_stack_depth(struct bpf_verifier_env *env)
3599 {
3600 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3601 	struct bpf_subprog_info *subprog = env->subprog_info;
3602 	struct bpf_insn *insn = env->prog->insnsi;
3603 	bool tail_call_reachable = false;
3604 	int ret_insn[MAX_CALL_FRAMES];
3605 	int ret_prog[MAX_CALL_FRAMES];
3606 	int j;
3607 
3608 process_func:
3609 	/* protect against potential stack overflow that might happen when
3610 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3611 	 * depth for such case down to 256 so that the worst case scenario
3612 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3613 	 * 8k).
3614 	 *
3615 	 * To get the idea what might happen, see an example:
3616 	 * func1 -> sub rsp, 128
3617 	 *  subfunc1 -> sub rsp, 256
3618 	 *  tailcall1 -> add rsp, 256
3619 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3620 	 *   subfunc2 -> sub rsp, 64
3621 	 *   subfunc22 -> sub rsp, 128
3622 	 *   tailcall2 -> add rsp, 128
3623 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3624 	 *
3625 	 * tailcall will unwind the current stack frame but it will not get rid
3626 	 * of caller's stack as shown on the example above.
3627 	 */
3628 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3629 		verbose(env,
3630 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3631 			depth);
3632 		return -EACCES;
3633 	}
3634 	/* round up to 32-bytes, since this is granularity
3635 	 * of interpreter stack size
3636 	 */
3637 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3638 	if (depth > MAX_BPF_STACK) {
3639 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3640 			frame + 1, depth);
3641 		return -EACCES;
3642 	}
3643 continue_func:
3644 	subprog_end = subprog[idx + 1].start;
3645 	for (; i < subprog_end; i++) {
3646 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3647 			continue;
3648 		/* remember insn and function to return to */
3649 		ret_insn[frame] = i + 1;
3650 		ret_prog[frame] = idx;
3651 
3652 		/* find the callee */
3653 		i = i + insn[i].imm + 1;
3654 		idx = find_subprog(env, i);
3655 		if (idx < 0) {
3656 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3657 				  i);
3658 			return -EFAULT;
3659 		}
3660 
3661 		if (subprog[idx].has_tail_call)
3662 			tail_call_reachable = true;
3663 
3664 		frame++;
3665 		if (frame >= MAX_CALL_FRAMES) {
3666 			verbose(env, "the call stack of %d frames is too deep !\n",
3667 				frame);
3668 			return -E2BIG;
3669 		}
3670 		goto process_func;
3671 	}
3672 	/* if tail call got detected across bpf2bpf calls then mark each of the
3673 	 * currently present subprog frames as tail call reachable subprogs;
3674 	 * this info will be utilized by JIT so that we will be preserving the
3675 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3676 	 */
3677 	if (tail_call_reachable)
3678 		for (j = 0; j < frame; j++)
3679 			subprog[ret_prog[j]].tail_call_reachable = true;
3680 
3681 	/* end of for() loop means the last insn of the 'subprog'
3682 	 * was reached. Doesn't matter whether it was JA or EXIT
3683 	 */
3684 	if (frame == 0)
3685 		return 0;
3686 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3687 	frame--;
3688 	i = ret_insn[frame];
3689 	idx = ret_prog[frame];
3690 	goto continue_func;
3691 }
3692 
3693 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3694 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3695 				  const struct bpf_insn *insn, int idx)
3696 {
3697 	int start = idx + insn->imm + 1, subprog;
3698 
3699 	subprog = find_subprog(env, start);
3700 	if (subprog < 0) {
3701 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3702 			  start);
3703 		return -EFAULT;
3704 	}
3705 	return env->subprog_info[subprog].stack_depth;
3706 }
3707 #endif
3708 
3709 int check_ctx_reg(struct bpf_verifier_env *env,
3710 		  const struct bpf_reg_state *reg, int regno)
3711 {
3712 	/* Access to ctx or passing it to a helper is only allowed in
3713 	 * its original, unmodified form.
3714 	 */
3715 
3716 	if (reg->off) {
3717 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3718 			regno, reg->off);
3719 		return -EACCES;
3720 	}
3721 
3722 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3723 		char tn_buf[48];
3724 
3725 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3726 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3727 		return -EACCES;
3728 	}
3729 
3730 	return 0;
3731 }
3732 
3733 static int __check_buffer_access(struct bpf_verifier_env *env,
3734 				 const char *buf_info,
3735 				 const struct bpf_reg_state *reg,
3736 				 int regno, int off, int size)
3737 {
3738 	if (off < 0) {
3739 		verbose(env,
3740 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3741 			regno, buf_info, off, size);
3742 		return -EACCES;
3743 	}
3744 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3745 		char tn_buf[48];
3746 
3747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3748 		verbose(env,
3749 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3750 			regno, off, tn_buf);
3751 		return -EACCES;
3752 	}
3753 
3754 	return 0;
3755 }
3756 
3757 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3758 				  const struct bpf_reg_state *reg,
3759 				  int regno, int off, int size)
3760 {
3761 	int err;
3762 
3763 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3764 	if (err)
3765 		return err;
3766 
3767 	if (off + size > env->prog->aux->max_tp_access)
3768 		env->prog->aux->max_tp_access = off + size;
3769 
3770 	return 0;
3771 }
3772 
3773 static int check_buffer_access(struct bpf_verifier_env *env,
3774 			       const struct bpf_reg_state *reg,
3775 			       int regno, int off, int size,
3776 			       bool zero_size_allowed,
3777 			       const char *buf_info,
3778 			       u32 *max_access)
3779 {
3780 	int err;
3781 
3782 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3783 	if (err)
3784 		return err;
3785 
3786 	if (off + size > *max_access)
3787 		*max_access = off + size;
3788 
3789 	return 0;
3790 }
3791 
3792 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3793 static void zext_32_to_64(struct bpf_reg_state *reg)
3794 {
3795 	reg->var_off = tnum_subreg(reg->var_off);
3796 	__reg_assign_32_into_64(reg);
3797 }
3798 
3799 /* truncate register to smaller size (in bytes)
3800  * must be called with size < BPF_REG_SIZE
3801  */
3802 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3803 {
3804 	u64 mask;
3805 
3806 	/* clear high bits in bit representation */
3807 	reg->var_off = tnum_cast(reg->var_off, size);
3808 
3809 	/* fix arithmetic bounds */
3810 	mask = ((u64)1 << (size * 8)) - 1;
3811 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3812 		reg->umin_value &= mask;
3813 		reg->umax_value &= mask;
3814 	} else {
3815 		reg->umin_value = 0;
3816 		reg->umax_value = mask;
3817 	}
3818 	reg->smin_value = reg->umin_value;
3819 	reg->smax_value = reg->umax_value;
3820 
3821 	/* If size is smaller than 32bit register the 32bit register
3822 	 * values are also truncated so we push 64-bit bounds into
3823 	 * 32-bit bounds. Above were truncated < 32-bits already.
3824 	 */
3825 	if (size >= 4)
3826 		return;
3827 	__reg_combine_64_into_32(reg);
3828 }
3829 
3830 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3831 {
3832 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3833 }
3834 
3835 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3836 {
3837 	void *ptr;
3838 	u64 addr;
3839 	int err;
3840 
3841 	err = map->ops->map_direct_value_addr(map, &addr, off);
3842 	if (err)
3843 		return err;
3844 	ptr = (void *)(long)addr + off;
3845 
3846 	switch (size) {
3847 	case sizeof(u8):
3848 		*val = (u64)*(u8 *)ptr;
3849 		break;
3850 	case sizeof(u16):
3851 		*val = (u64)*(u16 *)ptr;
3852 		break;
3853 	case sizeof(u32):
3854 		*val = (u64)*(u32 *)ptr;
3855 		break;
3856 	case sizeof(u64):
3857 		*val = *(u64 *)ptr;
3858 		break;
3859 	default:
3860 		return -EINVAL;
3861 	}
3862 	return 0;
3863 }
3864 
3865 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3866 				   struct bpf_reg_state *regs,
3867 				   int regno, int off, int size,
3868 				   enum bpf_access_type atype,
3869 				   int value_regno)
3870 {
3871 	struct bpf_reg_state *reg = regs + regno;
3872 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3873 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3874 	u32 btf_id;
3875 	int ret;
3876 
3877 	if (off < 0) {
3878 		verbose(env,
3879 			"R%d is ptr_%s invalid negative access: off=%d\n",
3880 			regno, tname, off);
3881 		return -EACCES;
3882 	}
3883 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3884 		char tn_buf[48];
3885 
3886 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3887 		verbose(env,
3888 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3889 			regno, tname, off, tn_buf);
3890 		return -EACCES;
3891 	}
3892 
3893 	if (env->ops->btf_struct_access) {
3894 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3895 						  off, size, atype, &btf_id);
3896 	} else {
3897 		if (atype != BPF_READ) {
3898 			verbose(env, "only read is supported\n");
3899 			return -EACCES;
3900 		}
3901 
3902 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3903 					atype, &btf_id);
3904 	}
3905 
3906 	if (ret < 0)
3907 		return ret;
3908 
3909 	if (atype == BPF_READ && value_regno >= 0)
3910 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3911 
3912 	return 0;
3913 }
3914 
3915 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3916 				   struct bpf_reg_state *regs,
3917 				   int regno, int off, int size,
3918 				   enum bpf_access_type atype,
3919 				   int value_regno)
3920 {
3921 	struct bpf_reg_state *reg = regs + regno;
3922 	struct bpf_map *map = reg->map_ptr;
3923 	const struct btf_type *t;
3924 	const char *tname;
3925 	u32 btf_id;
3926 	int ret;
3927 
3928 	if (!btf_vmlinux) {
3929 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3930 		return -ENOTSUPP;
3931 	}
3932 
3933 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3934 		verbose(env, "map_ptr access not supported for map type %d\n",
3935 			map->map_type);
3936 		return -ENOTSUPP;
3937 	}
3938 
3939 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3940 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3941 
3942 	if (!env->allow_ptr_to_map_access) {
3943 		verbose(env,
3944 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3945 			tname);
3946 		return -EPERM;
3947 	}
3948 
3949 	if (off < 0) {
3950 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
3951 			regno, tname, off);
3952 		return -EACCES;
3953 	}
3954 
3955 	if (atype != BPF_READ) {
3956 		verbose(env, "only read from %s is supported\n", tname);
3957 		return -EACCES;
3958 	}
3959 
3960 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3961 	if (ret < 0)
3962 		return ret;
3963 
3964 	if (value_regno >= 0)
3965 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3966 
3967 	return 0;
3968 }
3969 
3970 /* Check that the stack access at the given offset is within bounds. The
3971  * maximum valid offset is -1.
3972  *
3973  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3974  * -state->allocated_stack for reads.
3975  */
3976 static int check_stack_slot_within_bounds(int off,
3977 					  struct bpf_func_state *state,
3978 					  enum bpf_access_type t)
3979 {
3980 	int min_valid_off;
3981 
3982 	if (t == BPF_WRITE)
3983 		min_valid_off = -MAX_BPF_STACK;
3984 	else
3985 		min_valid_off = -state->allocated_stack;
3986 
3987 	if (off < min_valid_off || off > -1)
3988 		return -EACCES;
3989 	return 0;
3990 }
3991 
3992 /* Check that the stack access at 'regno + off' falls within the maximum stack
3993  * bounds.
3994  *
3995  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3996  */
3997 static int check_stack_access_within_bounds(
3998 		struct bpf_verifier_env *env,
3999 		int regno, int off, int access_size,
4000 		enum stack_access_src src, enum bpf_access_type type)
4001 {
4002 	struct bpf_reg_state *regs = cur_regs(env);
4003 	struct bpf_reg_state *reg = regs + regno;
4004 	struct bpf_func_state *state = func(env, reg);
4005 	int min_off, max_off;
4006 	int err;
4007 	char *err_extra;
4008 
4009 	if (src == ACCESS_HELPER)
4010 		/* We don't know if helpers are reading or writing (or both). */
4011 		err_extra = " indirect access to";
4012 	else if (type == BPF_READ)
4013 		err_extra = " read from";
4014 	else
4015 		err_extra = " write to";
4016 
4017 	if (tnum_is_const(reg->var_off)) {
4018 		min_off = reg->var_off.value + off;
4019 		if (access_size > 0)
4020 			max_off = min_off + access_size - 1;
4021 		else
4022 			max_off = min_off;
4023 	} else {
4024 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4025 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4026 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4027 				err_extra, regno);
4028 			return -EACCES;
4029 		}
4030 		min_off = reg->smin_value + off;
4031 		if (access_size > 0)
4032 			max_off = reg->smax_value + off + access_size - 1;
4033 		else
4034 			max_off = min_off;
4035 	}
4036 
4037 	err = check_stack_slot_within_bounds(min_off, state, type);
4038 	if (!err)
4039 		err = check_stack_slot_within_bounds(max_off, state, type);
4040 
4041 	if (err) {
4042 		if (tnum_is_const(reg->var_off)) {
4043 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4044 				err_extra, regno, off, access_size);
4045 		} else {
4046 			char tn_buf[48];
4047 
4048 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4049 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4050 				err_extra, regno, tn_buf, access_size);
4051 		}
4052 	}
4053 	return err;
4054 }
4055 
4056 /* check whether memory at (regno + off) is accessible for t = (read | write)
4057  * if t==write, value_regno is a register which value is stored into memory
4058  * if t==read, value_regno is a register which will receive the value from memory
4059  * if t==write && value_regno==-1, some unknown value is stored into memory
4060  * if t==read && value_regno==-1, don't care what we read from memory
4061  */
4062 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4063 			    int off, int bpf_size, enum bpf_access_type t,
4064 			    int value_regno, bool strict_alignment_once)
4065 {
4066 	struct bpf_reg_state *regs = cur_regs(env);
4067 	struct bpf_reg_state *reg = regs + regno;
4068 	struct bpf_func_state *state;
4069 	int size, err = 0;
4070 
4071 	size = bpf_size_to_bytes(bpf_size);
4072 	if (size < 0)
4073 		return size;
4074 
4075 	/* alignment checks will add in reg->off themselves */
4076 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4077 	if (err)
4078 		return err;
4079 
4080 	/* for access checks, reg->off is just part of off */
4081 	off += reg->off;
4082 
4083 	if (reg->type == PTR_TO_MAP_KEY) {
4084 		if (t == BPF_WRITE) {
4085 			verbose(env, "write to change key R%d not allowed\n", regno);
4086 			return -EACCES;
4087 		}
4088 
4089 		err = check_mem_region_access(env, regno, off, size,
4090 					      reg->map_ptr->key_size, false);
4091 		if (err)
4092 			return err;
4093 		if (value_regno >= 0)
4094 			mark_reg_unknown(env, regs, value_regno);
4095 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4096 		if (t == BPF_WRITE && value_regno >= 0 &&
4097 		    is_pointer_value(env, value_regno)) {
4098 			verbose(env, "R%d leaks addr into map\n", value_regno);
4099 			return -EACCES;
4100 		}
4101 		err = check_map_access_type(env, regno, off, size, t);
4102 		if (err)
4103 			return err;
4104 		err = check_map_access(env, regno, off, size, false);
4105 		if (!err && t == BPF_READ && value_regno >= 0) {
4106 			struct bpf_map *map = reg->map_ptr;
4107 
4108 			/* if map is read-only, track its contents as scalars */
4109 			if (tnum_is_const(reg->var_off) &&
4110 			    bpf_map_is_rdonly(map) &&
4111 			    map->ops->map_direct_value_addr) {
4112 				int map_off = off + reg->var_off.value;
4113 				u64 val = 0;
4114 
4115 				err = bpf_map_direct_read(map, map_off, size,
4116 							  &val);
4117 				if (err)
4118 					return err;
4119 
4120 				regs[value_regno].type = SCALAR_VALUE;
4121 				__mark_reg_known(&regs[value_regno], val);
4122 			} else {
4123 				mark_reg_unknown(env, regs, value_regno);
4124 			}
4125 		}
4126 	} else if (reg->type == PTR_TO_MEM) {
4127 		if (t == BPF_WRITE && value_regno >= 0 &&
4128 		    is_pointer_value(env, value_regno)) {
4129 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4130 			return -EACCES;
4131 		}
4132 		err = check_mem_region_access(env, regno, off, size,
4133 					      reg->mem_size, false);
4134 		if (!err && t == BPF_READ && value_regno >= 0)
4135 			mark_reg_unknown(env, regs, value_regno);
4136 	} else if (reg->type == PTR_TO_CTX) {
4137 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4138 		struct btf *btf = NULL;
4139 		u32 btf_id = 0;
4140 
4141 		if (t == BPF_WRITE && value_regno >= 0 &&
4142 		    is_pointer_value(env, value_regno)) {
4143 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4144 			return -EACCES;
4145 		}
4146 
4147 		err = check_ctx_reg(env, reg, regno);
4148 		if (err < 0)
4149 			return err;
4150 
4151 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4152 		if (err)
4153 			verbose_linfo(env, insn_idx, "; ");
4154 		if (!err && t == BPF_READ && value_regno >= 0) {
4155 			/* ctx access returns either a scalar, or a
4156 			 * PTR_TO_PACKET[_META,_END]. In the latter
4157 			 * case, we know the offset is zero.
4158 			 */
4159 			if (reg_type == SCALAR_VALUE) {
4160 				mark_reg_unknown(env, regs, value_regno);
4161 			} else {
4162 				mark_reg_known_zero(env, regs,
4163 						    value_regno);
4164 				if (reg_type_may_be_null(reg_type))
4165 					regs[value_regno].id = ++env->id_gen;
4166 				/* A load of ctx field could have different
4167 				 * actual load size with the one encoded in the
4168 				 * insn. When the dst is PTR, it is for sure not
4169 				 * a sub-register.
4170 				 */
4171 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4172 				if (reg_type == PTR_TO_BTF_ID ||
4173 				    reg_type == PTR_TO_BTF_ID_OR_NULL) {
4174 					regs[value_regno].btf = btf;
4175 					regs[value_regno].btf_id = btf_id;
4176 				}
4177 			}
4178 			regs[value_regno].type = reg_type;
4179 		}
4180 
4181 	} else if (reg->type == PTR_TO_STACK) {
4182 		/* Basic bounds checks. */
4183 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4184 		if (err)
4185 			return err;
4186 
4187 		state = func(env, reg);
4188 		err = update_stack_depth(env, state, off);
4189 		if (err)
4190 			return err;
4191 
4192 		if (t == BPF_READ)
4193 			err = check_stack_read(env, regno, off, size,
4194 					       value_regno);
4195 		else
4196 			err = check_stack_write(env, regno, off, size,
4197 						value_regno, insn_idx);
4198 	} else if (reg_is_pkt_pointer(reg)) {
4199 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4200 			verbose(env, "cannot write into packet\n");
4201 			return -EACCES;
4202 		}
4203 		if (t == BPF_WRITE && value_regno >= 0 &&
4204 		    is_pointer_value(env, value_regno)) {
4205 			verbose(env, "R%d leaks addr into packet\n",
4206 				value_regno);
4207 			return -EACCES;
4208 		}
4209 		err = check_packet_access(env, regno, off, size, false);
4210 		if (!err && t == BPF_READ && value_regno >= 0)
4211 			mark_reg_unknown(env, regs, value_regno);
4212 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4213 		if (t == BPF_WRITE && value_regno >= 0 &&
4214 		    is_pointer_value(env, value_regno)) {
4215 			verbose(env, "R%d leaks addr into flow keys\n",
4216 				value_regno);
4217 			return -EACCES;
4218 		}
4219 
4220 		err = check_flow_keys_access(env, off, size);
4221 		if (!err && t == BPF_READ && value_regno >= 0)
4222 			mark_reg_unknown(env, regs, value_regno);
4223 	} else if (type_is_sk_pointer(reg->type)) {
4224 		if (t == BPF_WRITE) {
4225 			verbose(env, "R%d cannot write into %s\n",
4226 				regno, reg_type_str[reg->type]);
4227 			return -EACCES;
4228 		}
4229 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4230 		if (!err && value_regno >= 0)
4231 			mark_reg_unknown(env, regs, value_regno);
4232 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4233 		err = check_tp_buffer_access(env, reg, regno, off, size);
4234 		if (!err && t == BPF_READ && value_regno >= 0)
4235 			mark_reg_unknown(env, regs, value_regno);
4236 	} else if (reg->type == PTR_TO_BTF_ID) {
4237 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4238 					      value_regno);
4239 	} else if (reg->type == CONST_PTR_TO_MAP) {
4240 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4241 					      value_regno);
4242 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
4243 		if (t == BPF_WRITE) {
4244 			verbose(env, "R%d cannot write into %s\n",
4245 				regno, reg_type_str[reg->type]);
4246 			return -EACCES;
4247 		}
4248 		err = check_buffer_access(env, reg, regno, off, size, false,
4249 					  "rdonly",
4250 					  &env->prog->aux->max_rdonly_access);
4251 		if (!err && value_regno >= 0)
4252 			mark_reg_unknown(env, regs, value_regno);
4253 	} else if (reg->type == PTR_TO_RDWR_BUF) {
4254 		err = check_buffer_access(env, reg, regno, off, size, false,
4255 					  "rdwr",
4256 					  &env->prog->aux->max_rdwr_access);
4257 		if (!err && t == BPF_READ && value_regno >= 0)
4258 			mark_reg_unknown(env, regs, value_regno);
4259 	} else {
4260 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4261 			reg_type_str[reg->type]);
4262 		return -EACCES;
4263 	}
4264 
4265 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4266 	    regs[value_regno].type == SCALAR_VALUE) {
4267 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4268 		coerce_reg_to_size(&regs[value_regno], size);
4269 	}
4270 	return err;
4271 }
4272 
4273 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4274 {
4275 	int load_reg;
4276 	int err;
4277 
4278 	switch (insn->imm) {
4279 	case BPF_ADD:
4280 	case BPF_ADD | BPF_FETCH:
4281 	case BPF_AND:
4282 	case BPF_AND | BPF_FETCH:
4283 	case BPF_OR:
4284 	case BPF_OR | BPF_FETCH:
4285 	case BPF_XOR:
4286 	case BPF_XOR | BPF_FETCH:
4287 	case BPF_XCHG:
4288 	case BPF_CMPXCHG:
4289 		break;
4290 	default:
4291 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4292 		return -EINVAL;
4293 	}
4294 
4295 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4296 		verbose(env, "invalid atomic operand size\n");
4297 		return -EINVAL;
4298 	}
4299 
4300 	/* check src1 operand */
4301 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4302 	if (err)
4303 		return err;
4304 
4305 	/* check src2 operand */
4306 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4307 	if (err)
4308 		return err;
4309 
4310 	if (insn->imm == BPF_CMPXCHG) {
4311 		/* Check comparison of R0 with memory location */
4312 		err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4313 		if (err)
4314 			return err;
4315 	}
4316 
4317 	if (is_pointer_value(env, insn->src_reg)) {
4318 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4319 		return -EACCES;
4320 	}
4321 
4322 	if (is_ctx_reg(env, insn->dst_reg) ||
4323 	    is_pkt_reg(env, insn->dst_reg) ||
4324 	    is_flow_key_reg(env, insn->dst_reg) ||
4325 	    is_sk_reg(env, insn->dst_reg)) {
4326 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4327 			insn->dst_reg,
4328 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
4329 		return -EACCES;
4330 	}
4331 
4332 	if (insn->imm & BPF_FETCH) {
4333 		if (insn->imm == BPF_CMPXCHG)
4334 			load_reg = BPF_REG_0;
4335 		else
4336 			load_reg = insn->src_reg;
4337 
4338 		/* check and record load of old value */
4339 		err = check_reg_arg(env, load_reg, DST_OP);
4340 		if (err)
4341 			return err;
4342 	} else {
4343 		/* This instruction accesses a memory location but doesn't
4344 		 * actually load it into a register.
4345 		 */
4346 		load_reg = -1;
4347 	}
4348 
4349 	/* check whether we can read the memory */
4350 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4351 			       BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4352 	if (err)
4353 		return err;
4354 
4355 	/* check whether we can write into the same memory */
4356 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4357 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4358 	if (err)
4359 		return err;
4360 
4361 	return 0;
4362 }
4363 
4364 /* When register 'regno' is used to read the stack (either directly or through
4365  * a helper function) make sure that it's within stack boundary and, depending
4366  * on the access type, that all elements of the stack are initialized.
4367  *
4368  * 'off' includes 'regno->off', but not its dynamic part (if any).
4369  *
4370  * All registers that have been spilled on the stack in the slots within the
4371  * read offsets are marked as read.
4372  */
4373 static int check_stack_range_initialized(
4374 		struct bpf_verifier_env *env, int regno, int off,
4375 		int access_size, bool zero_size_allowed,
4376 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4377 {
4378 	struct bpf_reg_state *reg = reg_state(env, regno);
4379 	struct bpf_func_state *state = func(env, reg);
4380 	int err, min_off, max_off, i, j, slot, spi;
4381 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4382 	enum bpf_access_type bounds_check_type;
4383 	/* Some accesses can write anything into the stack, others are
4384 	 * read-only.
4385 	 */
4386 	bool clobber = false;
4387 
4388 	if (access_size == 0 && !zero_size_allowed) {
4389 		verbose(env, "invalid zero-sized read\n");
4390 		return -EACCES;
4391 	}
4392 
4393 	if (type == ACCESS_HELPER) {
4394 		/* The bounds checks for writes are more permissive than for
4395 		 * reads. However, if raw_mode is not set, we'll do extra
4396 		 * checks below.
4397 		 */
4398 		bounds_check_type = BPF_WRITE;
4399 		clobber = true;
4400 	} else {
4401 		bounds_check_type = BPF_READ;
4402 	}
4403 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4404 					       type, bounds_check_type);
4405 	if (err)
4406 		return err;
4407 
4408 
4409 	if (tnum_is_const(reg->var_off)) {
4410 		min_off = max_off = reg->var_off.value + off;
4411 	} else {
4412 		/* Variable offset is prohibited for unprivileged mode for
4413 		 * simplicity since it requires corresponding support in
4414 		 * Spectre masking for stack ALU.
4415 		 * See also retrieve_ptr_limit().
4416 		 */
4417 		if (!env->bypass_spec_v1) {
4418 			char tn_buf[48];
4419 
4420 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4421 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4422 				regno, err_extra, tn_buf);
4423 			return -EACCES;
4424 		}
4425 		/* Only initialized buffer on stack is allowed to be accessed
4426 		 * with variable offset. With uninitialized buffer it's hard to
4427 		 * guarantee that whole memory is marked as initialized on
4428 		 * helper return since specific bounds are unknown what may
4429 		 * cause uninitialized stack leaking.
4430 		 */
4431 		if (meta && meta->raw_mode)
4432 			meta = NULL;
4433 
4434 		min_off = reg->smin_value + off;
4435 		max_off = reg->smax_value + off;
4436 	}
4437 
4438 	if (meta && meta->raw_mode) {
4439 		meta->access_size = access_size;
4440 		meta->regno = regno;
4441 		return 0;
4442 	}
4443 
4444 	for (i = min_off; i < max_off + access_size; i++) {
4445 		u8 *stype;
4446 
4447 		slot = -i - 1;
4448 		spi = slot / BPF_REG_SIZE;
4449 		if (state->allocated_stack <= slot)
4450 			goto err;
4451 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4452 		if (*stype == STACK_MISC)
4453 			goto mark;
4454 		if (*stype == STACK_ZERO) {
4455 			if (clobber) {
4456 				/* helper can write anything into the stack */
4457 				*stype = STACK_MISC;
4458 			}
4459 			goto mark;
4460 		}
4461 
4462 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4463 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4464 			goto mark;
4465 
4466 		if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4467 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4468 		     env->allow_ptr_leaks)) {
4469 			if (clobber) {
4470 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4471 				for (j = 0; j < BPF_REG_SIZE; j++)
4472 					state->stack[spi].slot_type[j] = STACK_MISC;
4473 			}
4474 			goto mark;
4475 		}
4476 
4477 err:
4478 		if (tnum_is_const(reg->var_off)) {
4479 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4480 				err_extra, regno, min_off, i - min_off, access_size);
4481 		} else {
4482 			char tn_buf[48];
4483 
4484 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4485 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4486 				err_extra, regno, tn_buf, i - min_off, access_size);
4487 		}
4488 		return -EACCES;
4489 mark:
4490 		/* reading any byte out of 8-byte 'spill_slot' will cause
4491 		 * the whole slot to be marked as 'read'
4492 		 */
4493 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4494 			      state->stack[spi].spilled_ptr.parent,
4495 			      REG_LIVE_READ64);
4496 	}
4497 	return update_stack_depth(env, state, min_off);
4498 }
4499 
4500 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4501 				   int access_size, bool zero_size_allowed,
4502 				   struct bpf_call_arg_meta *meta)
4503 {
4504 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4505 
4506 	switch (reg->type) {
4507 	case PTR_TO_PACKET:
4508 	case PTR_TO_PACKET_META:
4509 		return check_packet_access(env, regno, reg->off, access_size,
4510 					   zero_size_allowed);
4511 	case PTR_TO_MAP_KEY:
4512 		return check_mem_region_access(env, regno, reg->off, access_size,
4513 					       reg->map_ptr->key_size, false);
4514 	case PTR_TO_MAP_VALUE:
4515 		if (check_map_access_type(env, regno, reg->off, access_size,
4516 					  meta && meta->raw_mode ? BPF_WRITE :
4517 					  BPF_READ))
4518 			return -EACCES;
4519 		return check_map_access(env, regno, reg->off, access_size,
4520 					zero_size_allowed);
4521 	case PTR_TO_MEM:
4522 		return check_mem_region_access(env, regno, reg->off,
4523 					       access_size, reg->mem_size,
4524 					       zero_size_allowed);
4525 	case PTR_TO_RDONLY_BUF:
4526 		if (meta && meta->raw_mode)
4527 			return -EACCES;
4528 		return check_buffer_access(env, reg, regno, reg->off,
4529 					   access_size, zero_size_allowed,
4530 					   "rdonly",
4531 					   &env->prog->aux->max_rdonly_access);
4532 	case PTR_TO_RDWR_BUF:
4533 		return check_buffer_access(env, reg, regno, reg->off,
4534 					   access_size, zero_size_allowed,
4535 					   "rdwr",
4536 					   &env->prog->aux->max_rdwr_access);
4537 	case PTR_TO_STACK:
4538 		return check_stack_range_initialized(
4539 				env,
4540 				regno, reg->off, access_size,
4541 				zero_size_allowed, ACCESS_HELPER, meta);
4542 	default: /* scalar_value or invalid ptr */
4543 		/* Allow zero-byte read from NULL, regardless of pointer type */
4544 		if (zero_size_allowed && access_size == 0 &&
4545 		    register_is_null(reg))
4546 			return 0;
4547 
4548 		verbose(env, "R%d type=%s expected=%s\n", regno,
4549 			reg_type_str[reg->type],
4550 			reg_type_str[PTR_TO_STACK]);
4551 		return -EACCES;
4552 	}
4553 }
4554 
4555 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4556 		   u32 regno, u32 mem_size)
4557 {
4558 	if (register_is_null(reg))
4559 		return 0;
4560 
4561 	if (reg_type_may_be_null(reg->type)) {
4562 		/* Assuming that the register contains a value check if the memory
4563 		 * access is safe. Temporarily save and restore the register's state as
4564 		 * the conversion shouldn't be visible to a caller.
4565 		 */
4566 		const struct bpf_reg_state saved_reg = *reg;
4567 		int rv;
4568 
4569 		mark_ptr_not_null_reg(reg);
4570 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4571 		*reg = saved_reg;
4572 		return rv;
4573 	}
4574 
4575 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4576 }
4577 
4578 /* Implementation details:
4579  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4580  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4581  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4582  * value_or_null->value transition, since the verifier only cares about
4583  * the range of access to valid map value pointer and doesn't care about actual
4584  * address of the map element.
4585  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4586  * reg->id > 0 after value_or_null->value transition. By doing so
4587  * two bpf_map_lookups will be considered two different pointers that
4588  * point to different bpf_spin_locks.
4589  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4590  * dead-locks.
4591  * Since only one bpf_spin_lock is allowed the checks are simpler than
4592  * reg_is_refcounted() logic. The verifier needs to remember only
4593  * one spin_lock instead of array of acquired_refs.
4594  * cur_state->active_spin_lock remembers which map value element got locked
4595  * and clears it after bpf_spin_unlock.
4596  */
4597 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4598 			     bool is_lock)
4599 {
4600 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4601 	struct bpf_verifier_state *cur = env->cur_state;
4602 	bool is_const = tnum_is_const(reg->var_off);
4603 	struct bpf_map *map = reg->map_ptr;
4604 	u64 val = reg->var_off.value;
4605 
4606 	if (!is_const) {
4607 		verbose(env,
4608 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4609 			regno);
4610 		return -EINVAL;
4611 	}
4612 	if (!map->btf) {
4613 		verbose(env,
4614 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4615 			map->name);
4616 		return -EINVAL;
4617 	}
4618 	if (!map_value_has_spin_lock(map)) {
4619 		if (map->spin_lock_off == -E2BIG)
4620 			verbose(env,
4621 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4622 				map->name);
4623 		else if (map->spin_lock_off == -ENOENT)
4624 			verbose(env,
4625 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4626 				map->name);
4627 		else
4628 			verbose(env,
4629 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4630 				map->name);
4631 		return -EINVAL;
4632 	}
4633 	if (map->spin_lock_off != val + reg->off) {
4634 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4635 			val + reg->off);
4636 		return -EINVAL;
4637 	}
4638 	if (is_lock) {
4639 		if (cur->active_spin_lock) {
4640 			verbose(env,
4641 				"Locking two bpf_spin_locks are not allowed\n");
4642 			return -EINVAL;
4643 		}
4644 		cur->active_spin_lock = reg->id;
4645 	} else {
4646 		if (!cur->active_spin_lock) {
4647 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4648 			return -EINVAL;
4649 		}
4650 		if (cur->active_spin_lock != reg->id) {
4651 			verbose(env, "bpf_spin_unlock of different lock\n");
4652 			return -EINVAL;
4653 		}
4654 		cur->active_spin_lock = 0;
4655 	}
4656 	return 0;
4657 }
4658 
4659 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4660 {
4661 	return type == ARG_PTR_TO_MEM ||
4662 	       type == ARG_PTR_TO_MEM_OR_NULL ||
4663 	       type == ARG_PTR_TO_UNINIT_MEM;
4664 }
4665 
4666 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4667 {
4668 	return type == ARG_CONST_SIZE ||
4669 	       type == ARG_CONST_SIZE_OR_ZERO;
4670 }
4671 
4672 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4673 {
4674 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4675 }
4676 
4677 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4678 {
4679 	return type == ARG_PTR_TO_INT ||
4680 	       type == ARG_PTR_TO_LONG;
4681 }
4682 
4683 static int int_ptr_type_to_size(enum bpf_arg_type type)
4684 {
4685 	if (type == ARG_PTR_TO_INT)
4686 		return sizeof(u32);
4687 	else if (type == ARG_PTR_TO_LONG)
4688 		return sizeof(u64);
4689 
4690 	return -EINVAL;
4691 }
4692 
4693 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4694 				 const struct bpf_call_arg_meta *meta,
4695 				 enum bpf_arg_type *arg_type)
4696 {
4697 	if (!meta->map_ptr) {
4698 		/* kernel subsystem misconfigured verifier */
4699 		verbose(env, "invalid map_ptr to access map->type\n");
4700 		return -EACCES;
4701 	}
4702 
4703 	switch (meta->map_ptr->map_type) {
4704 	case BPF_MAP_TYPE_SOCKMAP:
4705 	case BPF_MAP_TYPE_SOCKHASH:
4706 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4707 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4708 		} else {
4709 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4710 			return -EINVAL;
4711 		}
4712 		break;
4713 
4714 	default:
4715 		break;
4716 	}
4717 	return 0;
4718 }
4719 
4720 struct bpf_reg_types {
4721 	const enum bpf_reg_type types[10];
4722 	u32 *btf_id;
4723 };
4724 
4725 static const struct bpf_reg_types map_key_value_types = {
4726 	.types = {
4727 		PTR_TO_STACK,
4728 		PTR_TO_PACKET,
4729 		PTR_TO_PACKET_META,
4730 		PTR_TO_MAP_KEY,
4731 		PTR_TO_MAP_VALUE,
4732 	},
4733 };
4734 
4735 static const struct bpf_reg_types sock_types = {
4736 	.types = {
4737 		PTR_TO_SOCK_COMMON,
4738 		PTR_TO_SOCKET,
4739 		PTR_TO_TCP_SOCK,
4740 		PTR_TO_XDP_SOCK,
4741 	},
4742 };
4743 
4744 #ifdef CONFIG_NET
4745 static const struct bpf_reg_types btf_id_sock_common_types = {
4746 	.types = {
4747 		PTR_TO_SOCK_COMMON,
4748 		PTR_TO_SOCKET,
4749 		PTR_TO_TCP_SOCK,
4750 		PTR_TO_XDP_SOCK,
4751 		PTR_TO_BTF_ID,
4752 	},
4753 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4754 };
4755 #endif
4756 
4757 static const struct bpf_reg_types mem_types = {
4758 	.types = {
4759 		PTR_TO_STACK,
4760 		PTR_TO_PACKET,
4761 		PTR_TO_PACKET_META,
4762 		PTR_TO_MAP_KEY,
4763 		PTR_TO_MAP_VALUE,
4764 		PTR_TO_MEM,
4765 		PTR_TO_RDONLY_BUF,
4766 		PTR_TO_RDWR_BUF,
4767 	},
4768 };
4769 
4770 static const struct bpf_reg_types int_ptr_types = {
4771 	.types = {
4772 		PTR_TO_STACK,
4773 		PTR_TO_PACKET,
4774 		PTR_TO_PACKET_META,
4775 		PTR_TO_MAP_KEY,
4776 		PTR_TO_MAP_VALUE,
4777 	},
4778 };
4779 
4780 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4781 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4782 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4783 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4784 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4785 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4786 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4787 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4788 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4789 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4790 
4791 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4792 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4793 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4794 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4795 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
4796 	[ARG_CONST_SIZE]		= &scalar_types,
4797 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4798 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4799 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4800 	[ARG_PTR_TO_CTX]		= &context_types,
4801 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
4802 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4803 #ifdef CONFIG_NET
4804 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4805 #endif
4806 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4807 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
4808 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4809 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4810 	[ARG_PTR_TO_MEM]		= &mem_types,
4811 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
4812 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4813 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4814 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
4815 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4816 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4817 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4818 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
4819 	[ARG_PTR_TO_STACK_OR_NULL]	= &stack_ptr_types,
4820 };
4821 
4822 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4823 			  enum bpf_arg_type arg_type,
4824 			  const u32 *arg_btf_id)
4825 {
4826 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4827 	enum bpf_reg_type expected, type = reg->type;
4828 	const struct bpf_reg_types *compatible;
4829 	int i, j;
4830 
4831 	compatible = compatible_reg_types[arg_type];
4832 	if (!compatible) {
4833 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4834 		return -EFAULT;
4835 	}
4836 
4837 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4838 		expected = compatible->types[i];
4839 		if (expected == NOT_INIT)
4840 			break;
4841 
4842 		if (type == expected)
4843 			goto found;
4844 	}
4845 
4846 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4847 	for (j = 0; j + 1 < i; j++)
4848 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4849 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4850 	return -EACCES;
4851 
4852 found:
4853 	if (type == PTR_TO_BTF_ID) {
4854 		if (!arg_btf_id) {
4855 			if (!compatible->btf_id) {
4856 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4857 				return -EFAULT;
4858 			}
4859 			arg_btf_id = compatible->btf_id;
4860 		}
4861 
4862 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4863 					  btf_vmlinux, *arg_btf_id)) {
4864 			verbose(env, "R%d is of type %s but %s is expected\n",
4865 				regno, kernel_type_name(reg->btf, reg->btf_id),
4866 				kernel_type_name(btf_vmlinux, *arg_btf_id));
4867 			return -EACCES;
4868 		}
4869 
4870 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4871 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4872 				regno);
4873 			return -EACCES;
4874 		}
4875 	}
4876 
4877 	return 0;
4878 }
4879 
4880 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4881 			  struct bpf_call_arg_meta *meta,
4882 			  const struct bpf_func_proto *fn)
4883 {
4884 	u32 regno = BPF_REG_1 + arg;
4885 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4886 	enum bpf_arg_type arg_type = fn->arg_type[arg];
4887 	enum bpf_reg_type type = reg->type;
4888 	int err = 0;
4889 
4890 	if (arg_type == ARG_DONTCARE)
4891 		return 0;
4892 
4893 	err = check_reg_arg(env, regno, SRC_OP);
4894 	if (err)
4895 		return err;
4896 
4897 	if (arg_type == ARG_ANYTHING) {
4898 		if (is_pointer_value(env, regno)) {
4899 			verbose(env, "R%d leaks addr into helper function\n",
4900 				regno);
4901 			return -EACCES;
4902 		}
4903 		return 0;
4904 	}
4905 
4906 	if (type_is_pkt_pointer(type) &&
4907 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4908 		verbose(env, "helper access to the packet is not allowed\n");
4909 		return -EACCES;
4910 	}
4911 
4912 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4913 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4914 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4915 		err = resolve_map_arg_type(env, meta, &arg_type);
4916 		if (err)
4917 			return err;
4918 	}
4919 
4920 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4921 		/* A NULL register has a SCALAR_VALUE type, so skip
4922 		 * type checking.
4923 		 */
4924 		goto skip_type_check;
4925 
4926 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4927 	if (err)
4928 		return err;
4929 
4930 	if (type == PTR_TO_CTX) {
4931 		err = check_ctx_reg(env, reg, regno);
4932 		if (err < 0)
4933 			return err;
4934 	}
4935 
4936 skip_type_check:
4937 	if (reg->ref_obj_id) {
4938 		if (meta->ref_obj_id) {
4939 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4940 				regno, reg->ref_obj_id,
4941 				meta->ref_obj_id);
4942 			return -EFAULT;
4943 		}
4944 		meta->ref_obj_id = reg->ref_obj_id;
4945 	}
4946 
4947 	if (arg_type == ARG_CONST_MAP_PTR) {
4948 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4949 		meta->map_ptr = reg->map_ptr;
4950 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4951 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
4952 		 * check that [key, key + map->key_size) are within
4953 		 * stack limits and initialized
4954 		 */
4955 		if (!meta->map_ptr) {
4956 			/* in function declaration map_ptr must come before
4957 			 * map_key, so that it's verified and known before
4958 			 * we have to check map_key here. Otherwise it means
4959 			 * that kernel subsystem misconfigured verifier
4960 			 */
4961 			verbose(env, "invalid map_ptr to access map->key\n");
4962 			return -EACCES;
4963 		}
4964 		err = check_helper_mem_access(env, regno,
4965 					      meta->map_ptr->key_size, false,
4966 					      NULL);
4967 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4968 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4969 		    !register_is_null(reg)) ||
4970 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4971 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
4972 		 * check [value, value + map->value_size) validity
4973 		 */
4974 		if (!meta->map_ptr) {
4975 			/* kernel subsystem misconfigured verifier */
4976 			verbose(env, "invalid map_ptr to access map->value\n");
4977 			return -EACCES;
4978 		}
4979 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4980 		err = check_helper_mem_access(env, regno,
4981 					      meta->map_ptr->value_size, false,
4982 					      meta);
4983 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4984 		if (!reg->btf_id) {
4985 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4986 			return -EACCES;
4987 		}
4988 		meta->ret_btf = reg->btf;
4989 		meta->ret_btf_id = reg->btf_id;
4990 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4991 		if (meta->func_id == BPF_FUNC_spin_lock) {
4992 			if (process_spin_lock(env, regno, true))
4993 				return -EACCES;
4994 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
4995 			if (process_spin_lock(env, regno, false))
4996 				return -EACCES;
4997 		} else {
4998 			verbose(env, "verifier internal error\n");
4999 			return -EFAULT;
5000 		}
5001 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5002 		meta->subprogno = reg->subprogno;
5003 	} else if (arg_type_is_mem_ptr(arg_type)) {
5004 		/* The access to this pointer is only checked when we hit the
5005 		 * next is_mem_size argument below.
5006 		 */
5007 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5008 	} else if (arg_type_is_mem_size(arg_type)) {
5009 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5010 
5011 		/* This is used to refine r0 return value bounds for helpers
5012 		 * that enforce this value as an upper bound on return values.
5013 		 * See do_refine_retval_range() for helpers that can refine
5014 		 * the return value. C type of helper is u32 so we pull register
5015 		 * bound from umax_value however, if negative verifier errors
5016 		 * out. Only upper bounds can be learned because retval is an
5017 		 * int type and negative retvals are allowed.
5018 		 */
5019 		meta->msize_max_value = reg->umax_value;
5020 
5021 		/* The register is SCALAR_VALUE; the access check
5022 		 * happens using its boundaries.
5023 		 */
5024 		if (!tnum_is_const(reg->var_off))
5025 			/* For unprivileged variable accesses, disable raw
5026 			 * mode so that the program is required to
5027 			 * initialize all the memory that the helper could
5028 			 * just partially fill up.
5029 			 */
5030 			meta = NULL;
5031 
5032 		if (reg->smin_value < 0) {
5033 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5034 				regno);
5035 			return -EACCES;
5036 		}
5037 
5038 		if (reg->umin_value == 0) {
5039 			err = check_helper_mem_access(env, regno - 1, 0,
5040 						      zero_size_allowed,
5041 						      meta);
5042 			if (err)
5043 				return err;
5044 		}
5045 
5046 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5047 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5048 				regno);
5049 			return -EACCES;
5050 		}
5051 		err = check_helper_mem_access(env, regno - 1,
5052 					      reg->umax_value,
5053 					      zero_size_allowed, meta);
5054 		if (!err)
5055 			err = mark_chain_precision(env, regno);
5056 	} else if (arg_type_is_alloc_size(arg_type)) {
5057 		if (!tnum_is_const(reg->var_off)) {
5058 			verbose(env, "R%d is not a known constant'\n",
5059 				regno);
5060 			return -EACCES;
5061 		}
5062 		meta->mem_size = reg->var_off.value;
5063 	} else if (arg_type_is_int_ptr(arg_type)) {
5064 		int size = int_ptr_type_to_size(arg_type);
5065 
5066 		err = check_helper_mem_access(env, regno, size, false, meta);
5067 		if (err)
5068 			return err;
5069 		err = check_ptr_alignment(env, reg, 0, size, true);
5070 	}
5071 
5072 	return err;
5073 }
5074 
5075 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5076 {
5077 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5078 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5079 
5080 	if (func_id != BPF_FUNC_map_update_elem)
5081 		return false;
5082 
5083 	/* It's not possible to get access to a locked struct sock in these
5084 	 * contexts, so updating is safe.
5085 	 */
5086 	switch (type) {
5087 	case BPF_PROG_TYPE_TRACING:
5088 		if (eatype == BPF_TRACE_ITER)
5089 			return true;
5090 		break;
5091 	case BPF_PROG_TYPE_SOCKET_FILTER:
5092 	case BPF_PROG_TYPE_SCHED_CLS:
5093 	case BPF_PROG_TYPE_SCHED_ACT:
5094 	case BPF_PROG_TYPE_XDP:
5095 	case BPF_PROG_TYPE_SK_REUSEPORT:
5096 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5097 	case BPF_PROG_TYPE_SK_LOOKUP:
5098 		return true;
5099 	default:
5100 		break;
5101 	}
5102 
5103 	verbose(env, "cannot update sockmap in this context\n");
5104 	return false;
5105 }
5106 
5107 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5108 {
5109 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5110 }
5111 
5112 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5113 					struct bpf_map *map, int func_id)
5114 {
5115 	if (!map)
5116 		return 0;
5117 
5118 	/* We need a two way check, first is from map perspective ... */
5119 	switch (map->map_type) {
5120 	case BPF_MAP_TYPE_PROG_ARRAY:
5121 		if (func_id != BPF_FUNC_tail_call)
5122 			goto error;
5123 		break;
5124 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5125 		if (func_id != BPF_FUNC_perf_event_read &&
5126 		    func_id != BPF_FUNC_perf_event_output &&
5127 		    func_id != BPF_FUNC_skb_output &&
5128 		    func_id != BPF_FUNC_perf_event_read_value &&
5129 		    func_id != BPF_FUNC_xdp_output)
5130 			goto error;
5131 		break;
5132 	case BPF_MAP_TYPE_RINGBUF:
5133 		if (func_id != BPF_FUNC_ringbuf_output &&
5134 		    func_id != BPF_FUNC_ringbuf_reserve &&
5135 		    func_id != BPF_FUNC_ringbuf_submit &&
5136 		    func_id != BPF_FUNC_ringbuf_discard &&
5137 		    func_id != BPF_FUNC_ringbuf_query)
5138 			goto error;
5139 		break;
5140 	case BPF_MAP_TYPE_STACK_TRACE:
5141 		if (func_id != BPF_FUNC_get_stackid)
5142 			goto error;
5143 		break;
5144 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5145 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5146 		    func_id != BPF_FUNC_current_task_under_cgroup)
5147 			goto error;
5148 		break;
5149 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5150 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5151 		if (func_id != BPF_FUNC_get_local_storage)
5152 			goto error;
5153 		break;
5154 	case BPF_MAP_TYPE_DEVMAP:
5155 	case BPF_MAP_TYPE_DEVMAP_HASH:
5156 		if (func_id != BPF_FUNC_redirect_map &&
5157 		    func_id != BPF_FUNC_map_lookup_elem)
5158 			goto error;
5159 		break;
5160 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5161 	 * appear.
5162 	 */
5163 	case BPF_MAP_TYPE_CPUMAP:
5164 		if (func_id != BPF_FUNC_redirect_map)
5165 			goto error;
5166 		break;
5167 	case BPF_MAP_TYPE_XSKMAP:
5168 		if (func_id != BPF_FUNC_redirect_map &&
5169 		    func_id != BPF_FUNC_map_lookup_elem)
5170 			goto error;
5171 		break;
5172 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5173 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5174 		if (func_id != BPF_FUNC_map_lookup_elem)
5175 			goto error;
5176 		break;
5177 	case BPF_MAP_TYPE_SOCKMAP:
5178 		if (func_id != BPF_FUNC_sk_redirect_map &&
5179 		    func_id != BPF_FUNC_sock_map_update &&
5180 		    func_id != BPF_FUNC_map_delete_elem &&
5181 		    func_id != BPF_FUNC_msg_redirect_map &&
5182 		    func_id != BPF_FUNC_sk_select_reuseport &&
5183 		    func_id != BPF_FUNC_map_lookup_elem &&
5184 		    !may_update_sockmap(env, func_id))
5185 			goto error;
5186 		break;
5187 	case BPF_MAP_TYPE_SOCKHASH:
5188 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5189 		    func_id != BPF_FUNC_sock_hash_update &&
5190 		    func_id != BPF_FUNC_map_delete_elem &&
5191 		    func_id != BPF_FUNC_msg_redirect_hash &&
5192 		    func_id != BPF_FUNC_sk_select_reuseport &&
5193 		    func_id != BPF_FUNC_map_lookup_elem &&
5194 		    !may_update_sockmap(env, func_id))
5195 			goto error;
5196 		break;
5197 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5198 		if (func_id != BPF_FUNC_sk_select_reuseport)
5199 			goto error;
5200 		break;
5201 	case BPF_MAP_TYPE_QUEUE:
5202 	case BPF_MAP_TYPE_STACK:
5203 		if (func_id != BPF_FUNC_map_peek_elem &&
5204 		    func_id != BPF_FUNC_map_pop_elem &&
5205 		    func_id != BPF_FUNC_map_push_elem)
5206 			goto error;
5207 		break;
5208 	case BPF_MAP_TYPE_SK_STORAGE:
5209 		if (func_id != BPF_FUNC_sk_storage_get &&
5210 		    func_id != BPF_FUNC_sk_storage_delete)
5211 			goto error;
5212 		break;
5213 	case BPF_MAP_TYPE_INODE_STORAGE:
5214 		if (func_id != BPF_FUNC_inode_storage_get &&
5215 		    func_id != BPF_FUNC_inode_storage_delete)
5216 			goto error;
5217 		break;
5218 	case BPF_MAP_TYPE_TASK_STORAGE:
5219 		if (func_id != BPF_FUNC_task_storage_get &&
5220 		    func_id != BPF_FUNC_task_storage_delete)
5221 			goto error;
5222 		break;
5223 	default:
5224 		break;
5225 	}
5226 
5227 	/* ... and second from the function itself. */
5228 	switch (func_id) {
5229 	case BPF_FUNC_tail_call:
5230 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5231 			goto error;
5232 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5233 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5234 			return -EINVAL;
5235 		}
5236 		break;
5237 	case BPF_FUNC_perf_event_read:
5238 	case BPF_FUNC_perf_event_output:
5239 	case BPF_FUNC_perf_event_read_value:
5240 	case BPF_FUNC_skb_output:
5241 	case BPF_FUNC_xdp_output:
5242 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5243 			goto error;
5244 		break;
5245 	case BPF_FUNC_get_stackid:
5246 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5247 			goto error;
5248 		break;
5249 	case BPF_FUNC_current_task_under_cgroup:
5250 	case BPF_FUNC_skb_under_cgroup:
5251 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5252 			goto error;
5253 		break;
5254 	case BPF_FUNC_redirect_map:
5255 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5256 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5257 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5258 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5259 			goto error;
5260 		break;
5261 	case BPF_FUNC_sk_redirect_map:
5262 	case BPF_FUNC_msg_redirect_map:
5263 	case BPF_FUNC_sock_map_update:
5264 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5265 			goto error;
5266 		break;
5267 	case BPF_FUNC_sk_redirect_hash:
5268 	case BPF_FUNC_msg_redirect_hash:
5269 	case BPF_FUNC_sock_hash_update:
5270 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5271 			goto error;
5272 		break;
5273 	case BPF_FUNC_get_local_storage:
5274 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5275 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5276 			goto error;
5277 		break;
5278 	case BPF_FUNC_sk_select_reuseport:
5279 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5280 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5281 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5282 			goto error;
5283 		break;
5284 	case BPF_FUNC_map_peek_elem:
5285 	case BPF_FUNC_map_pop_elem:
5286 	case BPF_FUNC_map_push_elem:
5287 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5288 		    map->map_type != BPF_MAP_TYPE_STACK)
5289 			goto error;
5290 		break;
5291 	case BPF_FUNC_sk_storage_get:
5292 	case BPF_FUNC_sk_storage_delete:
5293 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5294 			goto error;
5295 		break;
5296 	case BPF_FUNC_inode_storage_get:
5297 	case BPF_FUNC_inode_storage_delete:
5298 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5299 			goto error;
5300 		break;
5301 	case BPF_FUNC_task_storage_get:
5302 	case BPF_FUNC_task_storage_delete:
5303 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5304 			goto error;
5305 		break;
5306 	default:
5307 		break;
5308 	}
5309 
5310 	return 0;
5311 error:
5312 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5313 		map->map_type, func_id_name(func_id), func_id);
5314 	return -EINVAL;
5315 }
5316 
5317 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5318 {
5319 	int count = 0;
5320 
5321 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5322 		count++;
5323 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5324 		count++;
5325 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5326 		count++;
5327 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5328 		count++;
5329 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5330 		count++;
5331 
5332 	/* We only support one arg being in raw mode at the moment,
5333 	 * which is sufficient for the helper functions we have
5334 	 * right now.
5335 	 */
5336 	return count <= 1;
5337 }
5338 
5339 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5340 				    enum bpf_arg_type arg_next)
5341 {
5342 	return (arg_type_is_mem_ptr(arg_curr) &&
5343 	        !arg_type_is_mem_size(arg_next)) ||
5344 	       (!arg_type_is_mem_ptr(arg_curr) &&
5345 		arg_type_is_mem_size(arg_next));
5346 }
5347 
5348 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5349 {
5350 	/* bpf_xxx(..., buf, len) call will access 'len'
5351 	 * bytes from memory 'buf'. Both arg types need
5352 	 * to be paired, so make sure there's no buggy
5353 	 * helper function specification.
5354 	 */
5355 	if (arg_type_is_mem_size(fn->arg1_type) ||
5356 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5357 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5358 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5359 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5360 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5361 		return false;
5362 
5363 	return true;
5364 }
5365 
5366 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5367 {
5368 	int count = 0;
5369 
5370 	if (arg_type_may_be_refcounted(fn->arg1_type))
5371 		count++;
5372 	if (arg_type_may_be_refcounted(fn->arg2_type))
5373 		count++;
5374 	if (arg_type_may_be_refcounted(fn->arg3_type))
5375 		count++;
5376 	if (arg_type_may_be_refcounted(fn->arg4_type))
5377 		count++;
5378 	if (arg_type_may_be_refcounted(fn->arg5_type))
5379 		count++;
5380 
5381 	/* A reference acquiring function cannot acquire
5382 	 * another refcounted ptr.
5383 	 */
5384 	if (may_be_acquire_function(func_id) && count)
5385 		return false;
5386 
5387 	/* We only support one arg being unreferenced at the moment,
5388 	 * which is sufficient for the helper functions we have right now.
5389 	 */
5390 	return count <= 1;
5391 }
5392 
5393 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5394 {
5395 	int i;
5396 
5397 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5398 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5399 			return false;
5400 
5401 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5402 			return false;
5403 	}
5404 
5405 	return true;
5406 }
5407 
5408 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5409 {
5410 	return check_raw_mode_ok(fn) &&
5411 	       check_arg_pair_ok(fn) &&
5412 	       check_btf_id_ok(fn) &&
5413 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5414 }
5415 
5416 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5417  * are now invalid, so turn them into unknown SCALAR_VALUE.
5418  */
5419 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5420 				     struct bpf_func_state *state)
5421 {
5422 	struct bpf_reg_state *regs = state->regs, *reg;
5423 	int i;
5424 
5425 	for (i = 0; i < MAX_BPF_REG; i++)
5426 		if (reg_is_pkt_pointer_any(&regs[i]))
5427 			mark_reg_unknown(env, regs, i);
5428 
5429 	bpf_for_each_spilled_reg(i, state, reg) {
5430 		if (!reg)
5431 			continue;
5432 		if (reg_is_pkt_pointer_any(reg))
5433 			__mark_reg_unknown(env, reg);
5434 	}
5435 }
5436 
5437 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5438 {
5439 	struct bpf_verifier_state *vstate = env->cur_state;
5440 	int i;
5441 
5442 	for (i = 0; i <= vstate->curframe; i++)
5443 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5444 }
5445 
5446 enum {
5447 	AT_PKT_END = -1,
5448 	BEYOND_PKT_END = -2,
5449 };
5450 
5451 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5452 {
5453 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5454 	struct bpf_reg_state *reg = &state->regs[regn];
5455 
5456 	if (reg->type != PTR_TO_PACKET)
5457 		/* PTR_TO_PACKET_META is not supported yet */
5458 		return;
5459 
5460 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5461 	 * How far beyond pkt_end it goes is unknown.
5462 	 * if (!range_open) it's the case of pkt >= pkt_end
5463 	 * if (range_open) it's the case of pkt > pkt_end
5464 	 * hence this pointer is at least 1 byte bigger than pkt_end
5465 	 */
5466 	if (range_open)
5467 		reg->range = BEYOND_PKT_END;
5468 	else
5469 		reg->range = AT_PKT_END;
5470 }
5471 
5472 static void release_reg_references(struct bpf_verifier_env *env,
5473 				   struct bpf_func_state *state,
5474 				   int ref_obj_id)
5475 {
5476 	struct bpf_reg_state *regs = state->regs, *reg;
5477 	int i;
5478 
5479 	for (i = 0; i < MAX_BPF_REG; i++)
5480 		if (regs[i].ref_obj_id == ref_obj_id)
5481 			mark_reg_unknown(env, regs, i);
5482 
5483 	bpf_for_each_spilled_reg(i, state, reg) {
5484 		if (!reg)
5485 			continue;
5486 		if (reg->ref_obj_id == ref_obj_id)
5487 			__mark_reg_unknown(env, reg);
5488 	}
5489 }
5490 
5491 /* The pointer with the specified id has released its reference to kernel
5492  * resources. Identify all copies of the same pointer and clear the reference.
5493  */
5494 static int release_reference(struct bpf_verifier_env *env,
5495 			     int ref_obj_id)
5496 {
5497 	struct bpf_verifier_state *vstate = env->cur_state;
5498 	int err;
5499 	int i;
5500 
5501 	err = release_reference_state(cur_func(env), ref_obj_id);
5502 	if (err)
5503 		return err;
5504 
5505 	for (i = 0; i <= vstate->curframe; i++)
5506 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5507 
5508 	return 0;
5509 }
5510 
5511 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5512 				    struct bpf_reg_state *regs)
5513 {
5514 	int i;
5515 
5516 	/* after the call registers r0 - r5 were scratched */
5517 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5518 		mark_reg_not_init(env, regs, caller_saved[i]);
5519 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5520 	}
5521 }
5522 
5523 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5524 				   struct bpf_func_state *caller,
5525 				   struct bpf_func_state *callee,
5526 				   int insn_idx);
5527 
5528 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5529 			     int *insn_idx, int subprog,
5530 			     set_callee_state_fn set_callee_state_cb)
5531 {
5532 	struct bpf_verifier_state *state = env->cur_state;
5533 	struct bpf_func_info_aux *func_info_aux;
5534 	struct bpf_func_state *caller, *callee;
5535 	int err;
5536 	bool is_global = false;
5537 
5538 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5539 		verbose(env, "the call stack of %d frames is too deep\n",
5540 			state->curframe + 2);
5541 		return -E2BIG;
5542 	}
5543 
5544 	caller = state->frame[state->curframe];
5545 	if (state->frame[state->curframe + 1]) {
5546 		verbose(env, "verifier bug. Frame %d already allocated\n",
5547 			state->curframe + 1);
5548 		return -EFAULT;
5549 	}
5550 
5551 	func_info_aux = env->prog->aux->func_info_aux;
5552 	if (func_info_aux)
5553 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5554 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5555 	if (err == -EFAULT)
5556 		return err;
5557 	if (is_global) {
5558 		if (err) {
5559 			verbose(env, "Caller passes invalid args into func#%d\n",
5560 				subprog);
5561 			return err;
5562 		} else {
5563 			if (env->log.level & BPF_LOG_LEVEL)
5564 				verbose(env,
5565 					"Func#%d is global and valid. Skipping.\n",
5566 					subprog);
5567 			clear_caller_saved_regs(env, caller->regs);
5568 
5569 			/* All global functions return a 64-bit SCALAR_VALUE */
5570 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5571 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5572 
5573 			/* continue with next insn after call */
5574 			return 0;
5575 		}
5576 	}
5577 
5578 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5579 	if (!callee)
5580 		return -ENOMEM;
5581 	state->frame[state->curframe + 1] = callee;
5582 
5583 	/* callee cannot access r0, r6 - r9 for reading and has to write
5584 	 * into its own stack before reading from it.
5585 	 * callee can read/write into caller's stack
5586 	 */
5587 	init_func_state(env, callee,
5588 			/* remember the callsite, it will be used by bpf_exit */
5589 			*insn_idx /* callsite */,
5590 			state->curframe + 1 /* frameno within this callchain */,
5591 			subprog /* subprog number within this prog */);
5592 
5593 	/* Transfer references to the callee */
5594 	err = transfer_reference_state(callee, caller);
5595 	if (err)
5596 		return err;
5597 
5598 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
5599 	if (err)
5600 		return err;
5601 
5602 	clear_caller_saved_regs(env, caller->regs);
5603 
5604 	/* only increment it after check_reg_arg() finished */
5605 	state->curframe++;
5606 
5607 	/* and go analyze first insn of the callee */
5608 	*insn_idx = env->subprog_info[subprog].start - 1;
5609 
5610 	if (env->log.level & BPF_LOG_LEVEL) {
5611 		verbose(env, "caller:\n");
5612 		print_verifier_state(env, caller);
5613 		verbose(env, "callee:\n");
5614 		print_verifier_state(env, callee);
5615 	}
5616 	return 0;
5617 }
5618 
5619 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5620 				   struct bpf_func_state *caller,
5621 				   struct bpf_func_state *callee)
5622 {
5623 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5624 	 *      void *callback_ctx, u64 flags);
5625 	 * callback_fn(struct bpf_map *map, void *key, void *value,
5626 	 *      void *callback_ctx);
5627 	 */
5628 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5629 
5630 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5631 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5632 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5633 
5634 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5635 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5636 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5637 
5638 	/* pointer to stack or null */
5639 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5640 
5641 	/* unused */
5642 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5643 	return 0;
5644 }
5645 
5646 static int set_callee_state(struct bpf_verifier_env *env,
5647 			    struct bpf_func_state *caller,
5648 			    struct bpf_func_state *callee, int insn_idx)
5649 {
5650 	int i;
5651 
5652 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5653 	 * pointers, which connects us up to the liveness chain
5654 	 */
5655 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5656 		callee->regs[i] = caller->regs[i];
5657 	return 0;
5658 }
5659 
5660 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5661 			   int *insn_idx)
5662 {
5663 	int subprog, target_insn;
5664 
5665 	target_insn = *insn_idx + insn->imm + 1;
5666 	subprog = find_subprog(env, target_insn);
5667 	if (subprog < 0) {
5668 		verbose(env, "verifier bug. No program starts at insn %d\n",
5669 			target_insn);
5670 		return -EFAULT;
5671 	}
5672 
5673 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5674 }
5675 
5676 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5677 				       struct bpf_func_state *caller,
5678 				       struct bpf_func_state *callee,
5679 				       int insn_idx)
5680 {
5681 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5682 	struct bpf_map *map;
5683 	int err;
5684 
5685 	if (bpf_map_ptr_poisoned(insn_aux)) {
5686 		verbose(env, "tail_call abusing map_ptr\n");
5687 		return -EINVAL;
5688 	}
5689 
5690 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5691 	if (!map->ops->map_set_for_each_callback_args ||
5692 	    !map->ops->map_for_each_callback) {
5693 		verbose(env, "callback function not allowed for map\n");
5694 		return -ENOTSUPP;
5695 	}
5696 
5697 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5698 	if (err)
5699 		return err;
5700 
5701 	callee->in_callback_fn = true;
5702 	return 0;
5703 }
5704 
5705 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5706 {
5707 	struct bpf_verifier_state *state = env->cur_state;
5708 	struct bpf_func_state *caller, *callee;
5709 	struct bpf_reg_state *r0;
5710 	int err;
5711 
5712 	callee = state->frame[state->curframe];
5713 	r0 = &callee->regs[BPF_REG_0];
5714 	if (r0->type == PTR_TO_STACK) {
5715 		/* technically it's ok to return caller's stack pointer
5716 		 * (or caller's caller's pointer) back to the caller,
5717 		 * since these pointers are valid. Only current stack
5718 		 * pointer will be invalid as soon as function exits,
5719 		 * but let's be conservative
5720 		 */
5721 		verbose(env, "cannot return stack pointer to the caller\n");
5722 		return -EINVAL;
5723 	}
5724 
5725 	state->curframe--;
5726 	caller = state->frame[state->curframe];
5727 	if (callee->in_callback_fn) {
5728 		/* enforce R0 return value range [0, 1]. */
5729 		struct tnum range = tnum_range(0, 1);
5730 
5731 		if (r0->type != SCALAR_VALUE) {
5732 			verbose(env, "R0 not a scalar value\n");
5733 			return -EACCES;
5734 		}
5735 		if (!tnum_in(range, r0->var_off)) {
5736 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5737 			return -EINVAL;
5738 		}
5739 	} else {
5740 		/* return to the caller whatever r0 had in the callee */
5741 		caller->regs[BPF_REG_0] = *r0;
5742 	}
5743 
5744 	/* Transfer references to the caller */
5745 	err = transfer_reference_state(caller, callee);
5746 	if (err)
5747 		return err;
5748 
5749 	*insn_idx = callee->callsite + 1;
5750 	if (env->log.level & BPF_LOG_LEVEL) {
5751 		verbose(env, "returning from callee:\n");
5752 		print_verifier_state(env, callee);
5753 		verbose(env, "to caller at %d:\n", *insn_idx);
5754 		print_verifier_state(env, caller);
5755 	}
5756 	/* clear everything in the callee */
5757 	free_func_state(callee);
5758 	state->frame[state->curframe + 1] = NULL;
5759 	return 0;
5760 }
5761 
5762 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5763 				   int func_id,
5764 				   struct bpf_call_arg_meta *meta)
5765 {
5766 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5767 
5768 	if (ret_type != RET_INTEGER ||
5769 	    (func_id != BPF_FUNC_get_stack &&
5770 	     func_id != BPF_FUNC_probe_read_str &&
5771 	     func_id != BPF_FUNC_probe_read_kernel_str &&
5772 	     func_id != BPF_FUNC_probe_read_user_str))
5773 		return;
5774 
5775 	ret_reg->smax_value = meta->msize_max_value;
5776 	ret_reg->s32_max_value = meta->msize_max_value;
5777 	ret_reg->smin_value = -MAX_ERRNO;
5778 	ret_reg->s32_min_value = -MAX_ERRNO;
5779 	__reg_deduce_bounds(ret_reg);
5780 	__reg_bound_offset(ret_reg);
5781 	__update_reg_bounds(ret_reg);
5782 }
5783 
5784 static int
5785 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5786 		int func_id, int insn_idx)
5787 {
5788 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5789 	struct bpf_map *map = meta->map_ptr;
5790 
5791 	if (func_id != BPF_FUNC_tail_call &&
5792 	    func_id != BPF_FUNC_map_lookup_elem &&
5793 	    func_id != BPF_FUNC_map_update_elem &&
5794 	    func_id != BPF_FUNC_map_delete_elem &&
5795 	    func_id != BPF_FUNC_map_push_elem &&
5796 	    func_id != BPF_FUNC_map_pop_elem &&
5797 	    func_id != BPF_FUNC_map_peek_elem &&
5798 	    func_id != BPF_FUNC_for_each_map_elem &&
5799 	    func_id != BPF_FUNC_redirect_map)
5800 		return 0;
5801 
5802 	if (map == NULL) {
5803 		verbose(env, "kernel subsystem misconfigured verifier\n");
5804 		return -EINVAL;
5805 	}
5806 
5807 	/* In case of read-only, some additional restrictions
5808 	 * need to be applied in order to prevent altering the
5809 	 * state of the map from program side.
5810 	 */
5811 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5812 	    (func_id == BPF_FUNC_map_delete_elem ||
5813 	     func_id == BPF_FUNC_map_update_elem ||
5814 	     func_id == BPF_FUNC_map_push_elem ||
5815 	     func_id == BPF_FUNC_map_pop_elem)) {
5816 		verbose(env, "write into map forbidden\n");
5817 		return -EACCES;
5818 	}
5819 
5820 	if (!BPF_MAP_PTR(aux->map_ptr_state))
5821 		bpf_map_ptr_store(aux, meta->map_ptr,
5822 				  !meta->map_ptr->bypass_spec_v1);
5823 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5824 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5825 				  !meta->map_ptr->bypass_spec_v1);
5826 	return 0;
5827 }
5828 
5829 static int
5830 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5831 		int func_id, int insn_idx)
5832 {
5833 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5834 	struct bpf_reg_state *regs = cur_regs(env), *reg;
5835 	struct bpf_map *map = meta->map_ptr;
5836 	struct tnum range;
5837 	u64 val;
5838 	int err;
5839 
5840 	if (func_id != BPF_FUNC_tail_call)
5841 		return 0;
5842 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5843 		verbose(env, "kernel subsystem misconfigured verifier\n");
5844 		return -EINVAL;
5845 	}
5846 
5847 	range = tnum_range(0, map->max_entries - 1);
5848 	reg = &regs[BPF_REG_3];
5849 
5850 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5851 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5852 		return 0;
5853 	}
5854 
5855 	err = mark_chain_precision(env, BPF_REG_3);
5856 	if (err)
5857 		return err;
5858 
5859 	val = reg->var_off.value;
5860 	if (bpf_map_key_unseen(aux))
5861 		bpf_map_key_store(aux, val);
5862 	else if (!bpf_map_key_poisoned(aux) &&
5863 		  bpf_map_key_immediate(aux) != val)
5864 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5865 	return 0;
5866 }
5867 
5868 static int check_reference_leak(struct bpf_verifier_env *env)
5869 {
5870 	struct bpf_func_state *state = cur_func(env);
5871 	int i;
5872 
5873 	for (i = 0; i < state->acquired_refs; i++) {
5874 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5875 			state->refs[i].id, state->refs[i].insn_idx);
5876 	}
5877 	return state->acquired_refs ? -EINVAL : 0;
5878 }
5879 
5880 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5881 			     int *insn_idx_p)
5882 {
5883 	const struct bpf_func_proto *fn = NULL;
5884 	struct bpf_reg_state *regs;
5885 	struct bpf_call_arg_meta meta;
5886 	int insn_idx = *insn_idx_p;
5887 	bool changes_data;
5888 	int i, err, func_id;
5889 
5890 	/* find function prototype */
5891 	func_id = insn->imm;
5892 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5893 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5894 			func_id);
5895 		return -EINVAL;
5896 	}
5897 
5898 	if (env->ops->get_func_proto)
5899 		fn = env->ops->get_func_proto(func_id, env->prog);
5900 	if (!fn) {
5901 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5902 			func_id);
5903 		return -EINVAL;
5904 	}
5905 
5906 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5907 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5908 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5909 		return -EINVAL;
5910 	}
5911 
5912 	if (fn->allowed && !fn->allowed(env->prog)) {
5913 		verbose(env, "helper call is not allowed in probe\n");
5914 		return -EINVAL;
5915 	}
5916 
5917 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5918 	changes_data = bpf_helper_changes_pkt_data(fn->func);
5919 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5920 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5921 			func_id_name(func_id), func_id);
5922 		return -EINVAL;
5923 	}
5924 
5925 	memset(&meta, 0, sizeof(meta));
5926 	meta.pkt_access = fn->pkt_access;
5927 
5928 	err = check_func_proto(fn, func_id);
5929 	if (err) {
5930 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5931 			func_id_name(func_id), func_id);
5932 		return err;
5933 	}
5934 
5935 	meta.func_id = func_id;
5936 	/* check args */
5937 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
5938 		err = check_func_arg(env, i, &meta, fn);
5939 		if (err)
5940 			return err;
5941 	}
5942 
5943 	err = record_func_map(env, &meta, func_id, insn_idx);
5944 	if (err)
5945 		return err;
5946 
5947 	err = record_func_key(env, &meta, func_id, insn_idx);
5948 	if (err)
5949 		return err;
5950 
5951 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5952 	 * is inferred from register state.
5953 	 */
5954 	for (i = 0; i < meta.access_size; i++) {
5955 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5956 				       BPF_WRITE, -1, false);
5957 		if (err)
5958 			return err;
5959 	}
5960 
5961 	if (func_id == BPF_FUNC_tail_call) {
5962 		err = check_reference_leak(env);
5963 		if (err) {
5964 			verbose(env, "tail_call would lead to reference leak\n");
5965 			return err;
5966 		}
5967 	} else if (is_release_function(func_id)) {
5968 		err = release_reference(env, meta.ref_obj_id);
5969 		if (err) {
5970 			verbose(env, "func %s#%d reference has not been acquired before\n",
5971 				func_id_name(func_id), func_id);
5972 			return err;
5973 		}
5974 	}
5975 
5976 	regs = cur_regs(env);
5977 
5978 	/* check that flags argument in get_local_storage(map, flags) is 0,
5979 	 * this is required because get_local_storage() can't return an error.
5980 	 */
5981 	if (func_id == BPF_FUNC_get_local_storage &&
5982 	    !register_is_null(&regs[BPF_REG_2])) {
5983 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5984 		return -EINVAL;
5985 	}
5986 
5987 	if (func_id == BPF_FUNC_for_each_map_elem) {
5988 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
5989 					set_map_elem_callback_state);
5990 		if (err < 0)
5991 			return -EINVAL;
5992 	}
5993 
5994 	/* reset caller saved regs */
5995 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5996 		mark_reg_not_init(env, regs, caller_saved[i]);
5997 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5998 	}
5999 
6000 	/* helper call returns 64-bit value. */
6001 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6002 
6003 	/* update return register (already marked as written above) */
6004 	if (fn->ret_type == RET_INTEGER) {
6005 		/* sets type to SCALAR_VALUE */
6006 		mark_reg_unknown(env, regs, BPF_REG_0);
6007 	} else if (fn->ret_type == RET_VOID) {
6008 		regs[BPF_REG_0].type = NOT_INIT;
6009 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6010 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6011 		/* There is no offset yet applied, variable or fixed */
6012 		mark_reg_known_zero(env, regs, BPF_REG_0);
6013 		/* remember map_ptr, so that check_map_access()
6014 		 * can check 'value_size' boundary of memory access
6015 		 * to map element returned from bpf_map_lookup_elem()
6016 		 */
6017 		if (meta.map_ptr == NULL) {
6018 			verbose(env,
6019 				"kernel subsystem misconfigured verifier\n");
6020 			return -EINVAL;
6021 		}
6022 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6023 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6024 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6025 			if (map_value_has_spin_lock(meta.map_ptr))
6026 				regs[BPF_REG_0].id = ++env->id_gen;
6027 		} else {
6028 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6029 		}
6030 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6031 		mark_reg_known_zero(env, regs, BPF_REG_0);
6032 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6033 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6034 		mark_reg_known_zero(env, regs, BPF_REG_0);
6035 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6036 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6037 		mark_reg_known_zero(env, regs, BPF_REG_0);
6038 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6039 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6040 		mark_reg_known_zero(env, regs, BPF_REG_0);
6041 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6042 		regs[BPF_REG_0].mem_size = meta.mem_size;
6043 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6044 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6045 		const struct btf_type *t;
6046 
6047 		mark_reg_known_zero(env, regs, BPF_REG_0);
6048 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6049 		if (!btf_type_is_struct(t)) {
6050 			u32 tsize;
6051 			const struct btf_type *ret;
6052 			const char *tname;
6053 
6054 			/* resolve the type size of ksym. */
6055 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6056 			if (IS_ERR(ret)) {
6057 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6058 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6059 					tname, PTR_ERR(ret));
6060 				return -EINVAL;
6061 			}
6062 			regs[BPF_REG_0].type =
6063 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6064 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6065 			regs[BPF_REG_0].mem_size = tsize;
6066 		} else {
6067 			regs[BPF_REG_0].type =
6068 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6069 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6070 			regs[BPF_REG_0].btf = meta.ret_btf;
6071 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6072 		}
6073 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6074 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
6075 		int ret_btf_id;
6076 
6077 		mark_reg_known_zero(env, regs, BPF_REG_0);
6078 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6079 						     PTR_TO_BTF_ID :
6080 						     PTR_TO_BTF_ID_OR_NULL;
6081 		ret_btf_id = *fn->ret_btf_id;
6082 		if (ret_btf_id == 0) {
6083 			verbose(env, "invalid return type %d of func %s#%d\n",
6084 				fn->ret_type, func_id_name(func_id), func_id);
6085 			return -EINVAL;
6086 		}
6087 		/* current BPF helper definitions are only coming from
6088 		 * built-in code with type IDs from  vmlinux BTF
6089 		 */
6090 		regs[BPF_REG_0].btf = btf_vmlinux;
6091 		regs[BPF_REG_0].btf_id = ret_btf_id;
6092 	} else {
6093 		verbose(env, "unknown return type %d of func %s#%d\n",
6094 			fn->ret_type, func_id_name(func_id), func_id);
6095 		return -EINVAL;
6096 	}
6097 
6098 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
6099 		regs[BPF_REG_0].id = ++env->id_gen;
6100 
6101 	if (is_ptr_cast_function(func_id)) {
6102 		/* For release_reference() */
6103 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6104 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6105 		int id = acquire_reference_state(env, insn_idx);
6106 
6107 		if (id < 0)
6108 			return id;
6109 		/* For mark_ptr_or_null_reg() */
6110 		regs[BPF_REG_0].id = id;
6111 		/* For release_reference() */
6112 		regs[BPF_REG_0].ref_obj_id = id;
6113 	}
6114 
6115 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6116 
6117 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6118 	if (err)
6119 		return err;
6120 
6121 	if ((func_id == BPF_FUNC_get_stack ||
6122 	     func_id == BPF_FUNC_get_task_stack) &&
6123 	    !env->prog->has_callchain_buf) {
6124 		const char *err_str;
6125 
6126 #ifdef CONFIG_PERF_EVENTS
6127 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6128 		err_str = "cannot get callchain buffer for func %s#%d\n";
6129 #else
6130 		err = -ENOTSUPP;
6131 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6132 #endif
6133 		if (err) {
6134 			verbose(env, err_str, func_id_name(func_id), func_id);
6135 			return err;
6136 		}
6137 
6138 		env->prog->has_callchain_buf = true;
6139 	}
6140 
6141 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6142 		env->prog->call_get_stack = true;
6143 
6144 	if (changes_data)
6145 		clear_all_pkt_pointers(env);
6146 	return 0;
6147 }
6148 
6149 /* mark_btf_func_reg_size() is used when the reg size is determined by
6150  * the BTF func_proto's return value size and argument.
6151  */
6152 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6153 				   size_t reg_size)
6154 {
6155 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6156 
6157 	if (regno == BPF_REG_0) {
6158 		/* Function return value */
6159 		reg->live |= REG_LIVE_WRITTEN;
6160 		reg->subreg_def = reg_size == sizeof(u64) ?
6161 			DEF_NOT_SUBREG : env->insn_idx + 1;
6162 	} else {
6163 		/* Function argument */
6164 		if (reg_size == sizeof(u64)) {
6165 			mark_insn_zext(env, reg);
6166 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6167 		} else {
6168 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6169 		}
6170 	}
6171 }
6172 
6173 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6174 {
6175 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6176 	struct bpf_reg_state *regs = cur_regs(env);
6177 	const char *func_name, *ptr_type_name;
6178 	u32 i, nargs, func_id, ptr_type_id;
6179 	const struct btf_param *args;
6180 	int err;
6181 
6182 	func_id = insn->imm;
6183 	func = btf_type_by_id(btf_vmlinux, func_id);
6184 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6185 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
6186 
6187 	if (!env->ops->check_kfunc_call ||
6188 	    !env->ops->check_kfunc_call(func_id)) {
6189 		verbose(env, "calling kernel function %s is not allowed\n",
6190 			func_name);
6191 		return -EACCES;
6192 	}
6193 
6194 	/* Check the arguments */
6195 	err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6196 	if (err)
6197 		return err;
6198 
6199 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6200 		mark_reg_not_init(env, regs, caller_saved[i]);
6201 
6202 	/* Check return type */
6203 	t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6204 	if (btf_type_is_scalar(t)) {
6205 		mark_reg_unknown(env, regs, BPF_REG_0);
6206 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6207 	} else if (btf_type_is_ptr(t)) {
6208 		ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6209 						   &ptr_type_id);
6210 		if (!btf_type_is_struct(ptr_type)) {
6211 			ptr_type_name = btf_name_by_offset(btf_vmlinux,
6212 							   ptr_type->name_off);
6213 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6214 				func_name, btf_type_str(ptr_type),
6215 				ptr_type_name);
6216 			return -EINVAL;
6217 		}
6218 		mark_reg_known_zero(env, regs, BPF_REG_0);
6219 		regs[BPF_REG_0].btf = btf_vmlinux;
6220 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6221 		regs[BPF_REG_0].btf_id = ptr_type_id;
6222 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6223 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6224 
6225 	nargs = btf_type_vlen(func_proto);
6226 	args = (const struct btf_param *)(func_proto + 1);
6227 	for (i = 0; i < nargs; i++) {
6228 		u32 regno = i + 1;
6229 
6230 		t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6231 		if (btf_type_is_ptr(t))
6232 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6233 		else
6234 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6235 			mark_btf_func_reg_size(env, regno, t->size);
6236 	}
6237 
6238 	return 0;
6239 }
6240 
6241 static bool signed_add_overflows(s64 a, s64 b)
6242 {
6243 	/* Do the add in u64, where overflow is well-defined */
6244 	s64 res = (s64)((u64)a + (u64)b);
6245 
6246 	if (b < 0)
6247 		return res > a;
6248 	return res < a;
6249 }
6250 
6251 static bool signed_add32_overflows(s32 a, s32 b)
6252 {
6253 	/* Do the add in u32, where overflow is well-defined */
6254 	s32 res = (s32)((u32)a + (u32)b);
6255 
6256 	if (b < 0)
6257 		return res > a;
6258 	return res < a;
6259 }
6260 
6261 static bool signed_sub_overflows(s64 a, s64 b)
6262 {
6263 	/* Do the sub in u64, where overflow is well-defined */
6264 	s64 res = (s64)((u64)a - (u64)b);
6265 
6266 	if (b < 0)
6267 		return res < a;
6268 	return res > a;
6269 }
6270 
6271 static bool signed_sub32_overflows(s32 a, s32 b)
6272 {
6273 	/* Do the sub in u32, where overflow is well-defined */
6274 	s32 res = (s32)((u32)a - (u32)b);
6275 
6276 	if (b < 0)
6277 		return res < a;
6278 	return res > a;
6279 }
6280 
6281 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6282 				  const struct bpf_reg_state *reg,
6283 				  enum bpf_reg_type type)
6284 {
6285 	bool known = tnum_is_const(reg->var_off);
6286 	s64 val = reg->var_off.value;
6287 	s64 smin = reg->smin_value;
6288 
6289 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6290 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6291 			reg_type_str[type], val);
6292 		return false;
6293 	}
6294 
6295 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6296 		verbose(env, "%s pointer offset %d is not allowed\n",
6297 			reg_type_str[type], reg->off);
6298 		return false;
6299 	}
6300 
6301 	if (smin == S64_MIN) {
6302 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6303 			reg_type_str[type]);
6304 		return false;
6305 	}
6306 
6307 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6308 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6309 			smin, reg_type_str[type]);
6310 		return false;
6311 	}
6312 
6313 	return true;
6314 }
6315 
6316 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6317 {
6318 	return &env->insn_aux_data[env->insn_idx];
6319 }
6320 
6321 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6322 			      u32 *ptr_limit, u8 opcode, bool off_is_neg)
6323 {
6324 	bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6325 			    (opcode == BPF_SUB && !off_is_neg);
6326 	u32 off, max;
6327 
6328 	switch (ptr_reg->type) {
6329 	case PTR_TO_STACK:
6330 		/* Offset 0 is out-of-bounds, but acceptable start for the
6331 		 * left direction, see BPF_REG_FP.
6332 		 */
6333 		max = MAX_BPF_STACK + mask_to_left;
6334 		/* Indirect variable offset stack access is prohibited in
6335 		 * unprivileged mode so it's not handled here.
6336 		 */
6337 		off = ptr_reg->off + ptr_reg->var_off.value;
6338 		if (mask_to_left)
6339 			*ptr_limit = MAX_BPF_STACK + off;
6340 		else
6341 			*ptr_limit = -off - 1;
6342 		return *ptr_limit >= max ? -ERANGE : 0;
6343 	case PTR_TO_MAP_VALUE:
6344 		max = ptr_reg->map_ptr->value_size;
6345 		if (mask_to_left) {
6346 			*ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6347 		} else {
6348 			off = ptr_reg->smin_value + ptr_reg->off;
6349 			*ptr_limit = ptr_reg->map_ptr->value_size - off - 1;
6350 		}
6351 		return *ptr_limit >= max ? -ERANGE : 0;
6352 	default:
6353 		return -EINVAL;
6354 	}
6355 }
6356 
6357 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6358 				    const struct bpf_insn *insn)
6359 {
6360 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6361 }
6362 
6363 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6364 				       u32 alu_state, u32 alu_limit)
6365 {
6366 	/* If we arrived here from different branches with different
6367 	 * state or limits to sanitize, then this won't work.
6368 	 */
6369 	if (aux->alu_state &&
6370 	    (aux->alu_state != alu_state ||
6371 	     aux->alu_limit != alu_limit))
6372 		return -EACCES;
6373 
6374 	/* Corresponding fixup done in do_misc_fixups(). */
6375 	aux->alu_state = alu_state;
6376 	aux->alu_limit = alu_limit;
6377 	return 0;
6378 }
6379 
6380 static int sanitize_val_alu(struct bpf_verifier_env *env,
6381 			    struct bpf_insn *insn)
6382 {
6383 	struct bpf_insn_aux_data *aux = cur_aux(env);
6384 
6385 	if (can_skip_alu_sanitation(env, insn))
6386 		return 0;
6387 
6388 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6389 }
6390 
6391 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6392 			    struct bpf_insn *insn,
6393 			    const struct bpf_reg_state *ptr_reg,
6394 			    struct bpf_reg_state *dst_reg,
6395 			    bool off_is_neg)
6396 {
6397 	struct bpf_verifier_state *vstate = env->cur_state;
6398 	struct bpf_insn_aux_data *aux = cur_aux(env);
6399 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6400 	u8 opcode = BPF_OP(insn->code);
6401 	u32 alu_state, alu_limit;
6402 	struct bpf_reg_state tmp;
6403 	bool ret;
6404 	int err;
6405 
6406 	if (can_skip_alu_sanitation(env, insn))
6407 		return 0;
6408 
6409 	/* We already marked aux for masking from non-speculative
6410 	 * paths, thus we got here in the first place. We only care
6411 	 * to explore bad access from here.
6412 	 */
6413 	if (vstate->speculative)
6414 		goto do_sim;
6415 
6416 	alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6417 	alu_state |= ptr_is_dst_reg ?
6418 		     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6419 
6420 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg);
6421 	if (err < 0)
6422 		return err;
6423 
6424 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6425 	if (err < 0)
6426 		return err;
6427 do_sim:
6428 	/* Simulate and find potential out-of-bounds access under
6429 	 * speculative execution from truncation as a result of
6430 	 * masking when off was not within expected range. If off
6431 	 * sits in dst, then we temporarily need to move ptr there
6432 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6433 	 * for cases where we use K-based arithmetic in one direction
6434 	 * and truncated reg-based in the other in order to explore
6435 	 * bad access.
6436 	 */
6437 	if (!ptr_is_dst_reg) {
6438 		tmp = *dst_reg;
6439 		*dst_reg = *ptr_reg;
6440 	}
6441 	ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
6442 	if (!ptr_is_dst_reg && ret)
6443 		*dst_reg = tmp;
6444 	return !ret ? -EFAULT : 0;
6445 }
6446 
6447 /* check that stack access falls within stack limits and that 'reg' doesn't
6448  * have a variable offset.
6449  *
6450  * Variable offset is prohibited for unprivileged mode for simplicity since it
6451  * requires corresponding support in Spectre masking for stack ALU.  See also
6452  * retrieve_ptr_limit().
6453  *
6454  *
6455  * 'off' includes 'reg->off'.
6456  */
6457 static int check_stack_access_for_ptr_arithmetic(
6458 				struct bpf_verifier_env *env,
6459 				int regno,
6460 				const struct bpf_reg_state *reg,
6461 				int off)
6462 {
6463 	if (!tnum_is_const(reg->var_off)) {
6464 		char tn_buf[48];
6465 
6466 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6467 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6468 			regno, tn_buf, off);
6469 		return -EACCES;
6470 	}
6471 
6472 	if (off >= 0 || off < -MAX_BPF_STACK) {
6473 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6474 			"prohibited for !root; off=%d\n", regno, off);
6475 		return -EACCES;
6476 	}
6477 
6478 	return 0;
6479 }
6480 
6481 
6482 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6483  * Caller should also handle BPF_MOV case separately.
6484  * If we return -EACCES, caller may want to try again treating pointer as a
6485  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6486  */
6487 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6488 				   struct bpf_insn *insn,
6489 				   const struct bpf_reg_state *ptr_reg,
6490 				   const struct bpf_reg_state *off_reg)
6491 {
6492 	struct bpf_verifier_state *vstate = env->cur_state;
6493 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6494 	struct bpf_reg_state *regs = state->regs, *dst_reg;
6495 	bool known = tnum_is_const(off_reg->var_off);
6496 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6497 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6498 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6499 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6500 	u32 dst = insn->dst_reg, src = insn->src_reg;
6501 	u8 opcode = BPF_OP(insn->code);
6502 	int ret;
6503 
6504 	dst_reg = &regs[dst];
6505 
6506 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6507 	    smin_val > smax_val || umin_val > umax_val) {
6508 		/* Taint dst register if offset had invalid bounds derived from
6509 		 * e.g. dead branches.
6510 		 */
6511 		__mark_reg_unknown(env, dst_reg);
6512 		return 0;
6513 	}
6514 
6515 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6516 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6517 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6518 			__mark_reg_unknown(env, dst_reg);
6519 			return 0;
6520 		}
6521 
6522 		verbose(env,
6523 			"R%d 32-bit pointer arithmetic prohibited\n",
6524 			dst);
6525 		return -EACCES;
6526 	}
6527 
6528 	switch (ptr_reg->type) {
6529 	case PTR_TO_MAP_VALUE_OR_NULL:
6530 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6531 			dst, reg_type_str[ptr_reg->type]);
6532 		return -EACCES;
6533 	case CONST_PTR_TO_MAP:
6534 		/* smin_val represents the known value */
6535 		if (known && smin_val == 0 && opcode == BPF_ADD)
6536 			break;
6537 		fallthrough;
6538 	case PTR_TO_PACKET_END:
6539 	case PTR_TO_SOCKET:
6540 	case PTR_TO_SOCKET_OR_NULL:
6541 	case PTR_TO_SOCK_COMMON:
6542 	case PTR_TO_SOCK_COMMON_OR_NULL:
6543 	case PTR_TO_TCP_SOCK:
6544 	case PTR_TO_TCP_SOCK_OR_NULL:
6545 	case PTR_TO_XDP_SOCK:
6546 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6547 			dst, reg_type_str[ptr_reg->type]);
6548 		return -EACCES;
6549 	case PTR_TO_MAP_VALUE:
6550 		if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6551 			verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6552 				off_reg == dst_reg ? dst : src);
6553 			return -EACCES;
6554 		}
6555 		fallthrough;
6556 	default:
6557 		break;
6558 	}
6559 
6560 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6561 	 * The id may be overwritten later if we create a new variable offset.
6562 	 */
6563 	dst_reg->type = ptr_reg->type;
6564 	dst_reg->id = ptr_reg->id;
6565 
6566 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6567 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6568 		return -EINVAL;
6569 
6570 	/* pointer types do not carry 32-bit bounds at the moment. */
6571 	__mark_reg32_unbounded(dst_reg);
6572 
6573 	switch (opcode) {
6574 	case BPF_ADD:
6575 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6576 		if (ret < 0) {
6577 			verbose(env, "R%d tried to add from different maps, paths, or prohibited types\n", dst);
6578 			return ret;
6579 		}
6580 		/* We can take a fixed offset as long as it doesn't overflow
6581 		 * the s32 'off' field
6582 		 */
6583 		if (known && (ptr_reg->off + smin_val ==
6584 			      (s64)(s32)(ptr_reg->off + smin_val))) {
6585 			/* pointer += K.  Accumulate it into fixed offset */
6586 			dst_reg->smin_value = smin_ptr;
6587 			dst_reg->smax_value = smax_ptr;
6588 			dst_reg->umin_value = umin_ptr;
6589 			dst_reg->umax_value = umax_ptr;
6590 			dst_reg->var_off = ptr_reg->var_off;
6591 			dst_reg->off = ptr_reg->off + smin_val;
6592 			dst_reg->raw = ptr_reg->raw;
6593 			break;
6594 		}
6595 		/* A new variable offset is created.  Note that off_reg->off
6596 		 * == 0, since it's a scalar.
6597 		 * dst_reg gets the pointer type and since some positive
6598 		 * integer value was added to the pointer, give it a new 'id'
6599 		 * if it's a PTR_TO_PACKET.
6600 		 * this creates a new 'base' pointer, off_reg (variable) gets
6601 		 * added into the variable offset, and we copy the fixed offset
6602 		 * from ptr_reg.
6603 		 */
6604 		if (signed_add_overflows(smin_ptr, smin_val) ||
6605 		    signed_add_overflows(smax_ptr, smax_val)) {
6606 			dst_reg->smin_value = S64_MIN;
6607 			dst_reg->smax_value = S64_MAX;
6608 		} else {
6609 			dst_reg->smin_value = smin_ptr + smin_val;
6610 			dst_reg->smax_value = smax_ptr + smax_val;
6611 		}
6612 		if (umin_ptr + umin_val < umin_ptr ||
6613 		    umax_ptr + umax_val < umax_ptr) {
6614 			dst_reg->umin_value = 0;
6615 			dst_reg->umax_value = U64_MAX;
6616 		} else {
6617 			dst_reg->umin_value = umin_ptr + umin_val;
6618 			dst_reg->umax_value = umax_ptr + umax_val;
6619 		}
6620 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6621 		dst_reg->off = ptr_reg->off;
6622 		dst_reg->raw = ptr_reg->raw;
6623 		if (reg_is_pkt_pointer(ptr_reg)) {
6624 			dst_reg->id = ++env->id_gen;
6625 			/* something was added to pkt_ptr, set range to zero */
6626 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6627 		}
6628 		break;
6629 	case BPF_SUB:
6630 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6631 		if (ret < 0) {
6632 			verbose(env, "R%d tried to sub from different maps, paths, or prohibited types\n", dst);
6633 			return ret;
6634 		}
6635 		if (dst_reg == off_reg) {
6636 			/* scalar -= pointer.  Creates an unknown scalar */
6637 			verbose(env, "R%d tried to subtract pointer from scalar\n",
6638 				dst);
6639 			return -EACCES;
6640 		}
6641 		/* We don't allow subtraction from FP, because (according to
6642 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
6643 		 * be able to deal with it.
6644 		 */
6645 		if (ptr_reg->type == PTR_TO_STACK) {
6646 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
6647 				dst);
6648 			return -EACCES;
6649 		}
6650 		if (known && (ptr_reg->off - smin_val ==
6651 			      (s64)(s32)(ptr_reg->off - smin_val))) {
6652 			/* pointer -= K.  Subtract it from fixed offset */
6653 			dst_reg->smin_value = smin_ptr;
6654 			dst_reg->smax_value = smax_ptr;
6655 			dst_reg->umin_value = umin_ptr;
6656 			dst_reg->umax_value = umax_ptr;
6657 			dst_reg->var_off = ptr_reg->var_off;
6658 			dst_reg->id = ptr_reg->id;
6659 			dst_reg->off = ptr_reg->off - smin_val;
6660 			dst_reg->raw = ptr_reg->raw;
6661 			break;
6662 		}
6663 		/* A new variable offset is created.  If the subtrahend is known
6664 		 * nonnegative, then any reg->range we had before is still good.
6665 		 */
6666 		if (signed_sub_overflows(smin_ptr, smax_val) ||
6667 		    signed_sub_overflows(smax_ptr, smin_val)) {
6668 			/* Overflow possible, we know nothing */
6669 			dst_reg->smin_value = S64_MIN;
6670 			dst_reg->smax_value = S64_MAX;
6671 		} else {
6672 			dst_reg->smin_value = smin_ptr - smax_val;
6673 			dst_reg->smax_value = smax_ptr - smin_val;
6674 		}
6675 		if (umin_ptr < umax_val) {
6676 			/* Overflow possible, we know nothing */
6677 			dst_reg->umin_value = 0;
6678 			dst_reg->umax_value = U64_MAX;
6679 		} else {
6680 			/* Cannot overflow (as long as bounds are consistent) */
6681 			dst_reg->umin_value = umin_ptr - umax_val;
6682 			dst_reg->umax_value = umax_ptr - umin_val;
6683 		}
6684 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6685 		dst_reg->off = ptr_reg->off;
6686 		dst_reg->raw = ptr_reg->raw;
6687 		if (reg_is_pkt_pointer(ptr_reg)) {
6688 			dst_reg->id = ++env->id_gen;
6689 			/* something was added to pkt_ptr, set range to zero */
6690 			if (smin_val < 0)
6691 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6692 		}
6693 		break;
6694 	case BPF_AND:
6695 	case BPF_OR:
6696 	case BPF_XOR:
6697 		/* bitwise ops on pointers are troublesome, prohibit. */
6698 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6699 			dst, bpf_alu_string[opcode >> 4]);
6700 		return -EACCES;
6701 	default:
6702 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
6703 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6704 			dst, bpf_alu_string[opcode >> 4]);
6705 		return -EACCES;
6706 	}
6707 
6708 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6709 		return -EINVAL;
6710 
6711 	__update_reg_bounds(dst_reg);
6712 	__reg_deduce_bounds(dst_reg);
6713 	__reg_bound_offset(dst_reg);
6714 
6715 	/* For unprivileged we require that resulting offset must be in bounds
6716 	 * in order to be able to sanitize access later on.
6717 	 */
6718 	if (!env->bypass_spec_v1) {
6719 		if (dst_reg->type == PTR_TO_MAP_VALUE &&
6720 		    check_map_access(env, dst, dst_reg->off, 1, false)) {
6721 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6722 				"prohibited for !root\n", dst);
6723 			return -EACCES;
6724 		} else if (dst_reg->type == PTR_TO_STACK &&
6725 			   check_stack_access_for_ptr_arithmetic(
6726 				   env, dst, dst_reg, dst_reg->off +
6727 				   dst_reg->var_off.value)) {
6728 			return -EACCES;
6729 		}
6730 	}
6731 
6732 	return 0;
6733 }
6734 
6735 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6736 				 struct bpf_reg_state *src_reg)
6737 {
6738 	s32 smin_val = src_reg->s32_min_value;
6739 	s32 smax_val = src_reg->s32_max_value;
6740 	u32 umin_val = src_reg->u32_min_value;
6741 	u32 umax_val = src_reg->u32_max_value;
6742 
6743 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6744 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6745 		dst_reg->s32_min_value = S32_MIN;
6746 		dst_reg->s32_max_value = S32_MAX;
6747 	} else {
6748 		dst_reg->s32_min_value += smin_val;
6749 		dst_reg->s32_max_value += smax_val;
6750 	}
6751 	if (dst_reg->u32_min_value + umin_val < umin_val ||
6752 	    dst_reg->u32_max_value + umax_val < umax_val) {
6753 		dst_reg->u32_min_value = 0;
6754 		dst_reg->u32_max_value = U32_MAX;
6755 	} else {
6756 		dst_reg->u32_min_value += umin_val;
6757 		dst_reg->u32_max_value += umax_val;
6758 	}
6759 }
6760 
6761 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6762 			       struct bpf_reg_state *src_reg)
6763 {
6764 	s64 smin_val = src_reg->smin_value;
6765 	s64 smax_val = src_reg->smax_value;
6766 	u64 umin_val = src_reg->umin_value;
6767 	u64 umax_val = src_reg->umax_value;
6768 
6769 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6770 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
6771 		dst_reg->smin_value = S64_MIN;
6772 		dst_reg->smax_value = S64_MAX;
6773 	} else {
6774 		dst_reg->smin_value += smin_val;
6775 		dst_reg->smax_value += smax_val;
6776 	}
6777 	if (dst_reg->umin_value + umin_val < umin_val ||
6778 	    dst_reg->umax_value + umax_val < umax_val) {
6779 		dst_reg->umin_value = 0;
6780 		dst_reg->umax_value = U64_MAX;
6781 	} else {
6782 		dst_reg->umin_value += umin_val;
6783 		dst_reg->umax_value += umax_val;
6784 	}
6785 }
6786 
6787 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6788 				 struct bpf_reg_state *src_reg)
6789 {
6790 	s32 smin_val = src_reg->s32_min_value;
6791 	s32 smax_val = src_reg->s32_max_value;
6792 	u32 umin_val = src_reg->u32_min_value;
6793 	u32 umax_val = src_reg->u32_max_value;
6794 
6795 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6796 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6797 		/* Overflow possible, we know nothing */
6798 		dst_reg->s32_min_value = S32_MIN;
6799 		dst_reg->s32_max_value = S32_MAX;
6800 	} else {
6801 		dst_reg->s32_min_value -= smax_val;
6802 		dst_reg->s32_max_value -= smin_val;
6803 	}
6804 	if (dst_reg->u32_min_value < umax_val) {
6805 		/* Overflow possible, we know nothing */
6806 		dst_reg->u32_min_value = 0;
6807 		dst_reg->u32_max_value = U32_MAX;
6808 	} else {
6809 		/* Cannot overflow (as long as bounds are consistent) */
6810 		dst_reg->u32_min_value -= umax_val;
6811 		dst_reg->u32_max_value -= umin_val;
6812 	}
6813 }
6814 
6815 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6816 			       struct bpf_reg_state *src_reg)
6817 {
6818 	s64 smin_val = src_reg->smin_value;
6819 	s64 smax_val = src_reg->smax_value;
6820 	u64 umin_val = src_reg->umin_value;
6821 	u64 umax_val = src_reg->umax_value;
6822 
6823 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6824 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6825 		/* Overflow possible, we know nothing */
6826 		dst_reg->smin_value = S64_MIN;
6827 		dst_reg->smax_value = S64_MAX;
6828 	} else {
6829 		dst_reg->smin_value -= smax_val;
6830 		dst_reg->smax_value -= smin_val;
6831 	}
6832 	if (dst_reg->umin_value < umax_val) {
6833 		/* Overflow possible, we know nothing */
6834 		dst_reg->umin_value = 0;
6835 		dst_reg->umax_value = U64_MAX;
6836 	} else {
6837 		/* Cannot overflow (as long as bounds are consistent) */
6838 		dst_reg->umin_value -= umax_val;
6839 		dst_reg->umax_value -= umin_val;
6840 	}
6841 }
6842 
6843 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6844 				 struct bpf_reg_state *src_reg)
6845 {
6846 	s32 smin_val = src_reg->s32_min_value;
6847 	u32 umin_val = src_reg->u32_min_value;
6848 	u32 umax_val = src_reg->u32_max_value;
6849 
6850 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6851 		/* Ain't nobody got time to multiply that sign */
6852 		__mark_reg32_unbounded(dst_reg);
6853 		return;
6854 	}
6855 	/* Both values are positive, so we can work with unsigned and
6856 	 * copy the result to signed (unless it exceeds S32_MAX).
6857 	 */
6858 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6859 		/* Potential overflow, we know nothing */
6860 		__mark_reg32_unbounded(dst_reg);
6861 		return;
6862 	}
6863 	dst_reg->u32_min_value *= umin_val;
6864 	dst_reg->u32_max_value *= umax_val;
6865 	if (dst_reg->u32_max_value > S32_MAX) {
6866 		/* Overflow possible, we know nothing */
6867 		dst_reg->s32_min_value = S32_MIN;
6868 		dst_reg->s32_max_value = S32_MAX;
6869 	} else {
6870 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6871 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6872 	}
6873 }
6874 
6875 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6876 			       struct bpf_reg_state *src_reg)
6877 {
6878 	s64 smin_val = src_reg->smin_value;
6879 	u64 umin_val = src_reg->umin_value;
6880 	u64 umax_val = src_reg->umax_value;
6881 
6882 	if (smin_val < 0 || dst_reg->smin_value < 0) {
6883 		/* Ain't nobody got time to multiply that sign */
6884 		__mark_reg64_unbounded(dst_reg);
6885 		return;
6886 	}
6887 	/* Both values are positive, so we can work with unsigned and
6888 	 * copy the result to signed (unless it exceeds S64_MAX).
6889 	 */
6890 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6891 		/* Potential overflow, we know nothing */
6892 		__mark_reg64_unbounded(dst_reg);
6893 		return;
6894 	}
6895 	dst_reg->umin_value *= umin_val;
6896 	dst_reg->umax_value *= umax_val;
6897 	if (dst_reg->umax_value > S64_MAX) {
6898 		/* Overflow possible, we know nothing */
6899 		dst_reg->smin_value = S64_MIN;
6900 		dst_reg->smax_value = S64_MAX;
6901 	} else {
6902 		dst_reg->smin_value = dst_reg->umin_value;
6903 		dst_reg->smax_value = dst_reg->umax_value;
6904 	}
6905 }
6906 
6907 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6908 				 struct bpf_reg_state *src_reg)
6909 {
6910 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6911 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6912 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6913 	s32 smin_val = src_reg->s32_min_value;
6914 	u32 umax_val = src_reg->u32_max_value;
6915 
6916 	/* Assuming scalar64_min_max_and will be called so its safe
6917 	 * to skip updating register for known 32-bit case.
6918 	 */
6919 	if (src_known && dst_known)
6920 		return;
6921 
6922 	/* We get our minimum from the var_off, since that's inherently
6923 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6924 	 */
6925 	dst_reg->u32_min_value = var32_off.value;
6926 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6927 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6928 		/* Lose signed bounds when ANDing negative numbers,
6929 		 * ain't nobody got time for that.
6930 		 */
6931 		dst_reg->s32_min_value = S32_MIN;
6932 		dst_reg->s32_max_value = S32_MAX;
6933 	} else {
6934 		/* ANDing two positives gives a positive, so safe to
6935 		 * cast result into s64.
6936 		 */
6937 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6938 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6939 	}
6940 
6941 }
6942 
6943 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6944 			       struct bpf_reg_state *src_reg)
6945 {
6946 	bool src_known = tnum_is_const(src_reg->var_off);
6947 	bool dst_known = tnum_is_const(dst_reg->var_off);
6948 	s64 smin_val = src_reg->smin_value;
6949 	u64 umax_val = src_reg->umax_value;
6950 
6951 	if (src_known && dst_known) {
6952 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6953 		return;
6954 	}
6955 
6956 	/* We get our minimum from the var_off, since that's inherently
6957 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6958 	 */
6959 	dst_reg->umin_value = dst_reg->var_off.value;
6960 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6961 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6962 		/* Lose signed bounds when ANDing negative numbers,
6963 		 * ain't nobody got time for that.
6964 		 */
6965 		dst_reg->smin_value = S64_MIN;
6966 		dst_reg->smax_value = S64_MAX;
6967 	} else {
6968 		/* ANDing two positives gives a positive, so safe to
6969 		 * cast result into s64.
6970 		 */
6971 		dst_reg->smin_value = dst_reg->umin_value;
6972 		dst_reg->smax_value = dst_reg->umax_value;
6973 	}
6974 	/* We may learn something more from the var_off */
6975 	__update_reg_bounds(dst_reg);
6976 }
6977 
6978 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6979 				struct bpf_reg_state *src_reg)
6980 {
6981 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6982 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6983 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6984 	s32 smin_val = src_reg->s32_min_value;
6985 	u32 umin_val = src_reg->u32_min_value;
6986 
6987 	/* Assuming scalar64_min_max_or will be called so it is safe
6988 	 * to skip updating register for known case.
6989 	 */
6990 	if (src_known && dst_known)
6991 		return;
6992 
6993 	/* We get our maximum from the var_off, and our minimum is the
6994 	 * maximum of the operands' minima
6995 	 */
6996 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6997 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6998 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6999 		/* Lose signed bounds when ORing negative numbers,
7000 		 * ain't nobody got time for that.
7001 		 */
7002 		dst_reg->s32_min_value = S32_MIN;
7003 		dst_reg->s32_max_value = S32_MAX;
7004 	} else {
7005 		/* ORing two positives gives a positive, so safe to
7006 		 * cast result into s64.
7007 		 */
7008 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7009 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7010 	}
7011 }
7012 
7013 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7014 			      struct bpf_reg_state *src_reg)
7015 {
7016 	bool src_known = tnum_is_const(src_reg->var_off);
7017 	bool dst_known = tnum_is_const(dst_reg->var_off);
7018 	s64 smin_val = src_reg->smin_value;
7019 	u64 umin_val = src_reg->umin_value;
7020 
7021 	if (src_known && dst_known) {
7022 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7023 		return;
7024 	}
7025 
7026 	/* We get our maximum from the var_off, and our minimum is the
7027 	 * maximum of the operands' minima
7028 	 */
7029 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7030 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7031 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7032 		/* Lose signed bounds when ORing negative numbers,
7033 		 * ain't nobody got time for that.
7034 		 */
7035 		dst_reg->smin_value = S64_MIN;
7036 		dst_reg->smax_value = S64_MAX;
7037 	} else {
7038 		/* ORing two positives gives a positive, so safe to
7039 		 * cast result into s64.
7040 		 */
7041 		dst_reg->smin_value = dst_reg->umin_value;
7042 		dst_reg->smax_value = dst_reg->umax_value;
7043 	}
7044 	/* We may learn something more from the var_off */
7045 	__update_reg_bounds(dst_reg);
7046 }
7047 
7048 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7049 				 struct bpf_reg_state *src_reg)
7050 {
7051 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7052 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7053 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7054 	s32 smin_val = src_reg->s32_min_value;
7055 
7056 	/* Assuming scalar64_min_max_xor will be called so it is safe
7057 	 * to skip updating register for known case.
7058 	 */
7059 	if (src_known && dst_known)
7060 		return;
7061 
7062 	/* We get both minimum and maximum from the var32_off. */
7063 	dst_reg->u32_min_value = var32_off.value;
7064 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7065 
7066 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7067 		/* XORing two positive sign numbers gives a positive,
7068 		 * so safe to cast u32 result into s32.
7069 		 */
7070 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7071 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7072 	} else {
7073 		dst_reg->s32_min_value = S32_MIN;
7074 		dst_reg->s32_max_value = S32_MAX;
7075 	}
7076 }
7077 
7078 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7079 			       struct bpf_reg_state *src_reg)
7080 {
7081 	bool src_known = tnum_is_const(src_reg->var_off);
7082 	bool dst_known = tnum_is_const(dst_reg->var_off);
7083 	s64 smin_val = src_reg->smin_value;
7084 
7085 	if (src_known && dst_known) {
7086 		/* dst_reg->var_off.value has been updated earlier */
7087 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7088 		return;
7089 	}
7090 
7091 	/* We get both minimum and maximum from the var_off. */
7092 	dst_reg->umin_value = dst_reg->var_off.value;
7093 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7094 
7095 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7096 		/* XORing two positive sign numbers gives a positive,
7097 		 * so safe to cast u64 result into s64.
7098 		 */
7099 		dst_reg->smin_value = dst_reg->umin_value;
7100 		dst_reg->smax_value = dst_reg->umax_value;
7101 	} else {
7102 		dst_reg->smin_value = S64_MIN;
7103 		dst_reg->smax_value = S64_MAX;
7104 	}
7105 
7106 	__update_reg_bounds(dst_reg);
7107 }
7108 
7109 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7110 				   u64 umin_val, u64 umax_val)
7111 {
7112 	/* We lose all sign bit information (except what we can pick
7113 	 * up from var_off)
7114 	 */
7115 	dst_reg->s32_min_value = S32_MIN;
7116 	dst_reg->s32_max_value = S32_MAX;
7117 	/* If we might shift our top bit out, then we know nothing */
7118 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7119 		dst_reg->u32_min_value = 0;
7120 		dst_reg->u32_max_value = U32_MAX;
7121 	} else {
7122 		dst_reg->u32_min_value <<= umin_val;
7123 		dst_reg->u32_max_value <<= umax_val;
7124 	}
7125 }
7126 
7127 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7128 				 struct bpf_reg_state *src_reg)
7129 {
7130 	u32 umax_val = src_reg->u32_max_value;
7131 	u32 umin_val = src_reg->u32_min_value;
7132 	/* u32 alu operation will zext upper bits */
7133 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7134 
7135 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7136 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7137 	/* Not required but being careful mark reg64 bounds as unknown so
7138 	 * that we are forced to pick them up from tnum and zext later and
7139 	 * if some path skips this step we are still safe.
7140 	 */
7141 	__mark_reg64_unbounded(dst_reg);
7142 	__update_reg32_bounds(dst_reg);
7143 }
7144 
7145 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7146 				   u64 umin_val, u64 umax_val)
7147 {
7148 	/* Special case <<32 because it is a common compiler pattern to sign
7149 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7150 	 * positive we know this shift will also be positive so we can track
7151 	 * bounds correctly. Otherwise we lose all sign bit information except
7152 	 * what we can pick up from var_off. Perhaps we can generalize this
7153 	 * later to shifts of any length.
7154 	 */
7155 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7156 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7157 	else
7158 		dst_reg->smax_value = S64_MAX;
7159 
7160 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7161 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7162 	else
7163 		dst_reg->smin_value = S64_MIN;
7164 
7165 	/* If we might shift our top bit out, then we know nothing */
7166 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7167 		dst_reg->umin_value = 0;
7168 		dst_reg->umax_value = U64_MAX;
7169 	} else {
7170 		dst_reg->umin_value <<= umin_val;
7171 		dst_reg->umax_value <<= umax_val;
7172 	}
7173 }
7174 
7175 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7176 			       struct bpf_reg_state *src_reg)
7177 {
7178 	u64 umax_val = src_reg->umax_value;
7179 	u64 umin_val = src_reg->umin_value;
7180 
7181 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7182 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7183 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7184 
7185 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7186 	/* We may learn something more from the var_off */
7187 	__update_reg_bounds(dst_reg);
7188 }
7189 
7190 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7191 				 struct bpf_reg_state *src_reg)
7192 {
7193 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7194 	u32 umax_val = src_reg->u32_max_value;
7195 	u32 umin_val = src_reg->u32_min_value;
7196 
7197 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7198 	 * be negative, then either:
7199 	 * 1) src_reg might be zero, so the sign bit of the result is
7200 	 *    unknown, so we lose our signed bounds
7201 	 * 2) it's known negative, thus the unsigned bounds capture the
7202 	 *    signed bounds
7203 	 * 3) the signed bounds cross zero, so they tell us nothing
7204 	 *    about the result
7205 	 * If the value in dst_reg is known nonnegative, then again the
7206 	 * unsigned bounds capture the signed bounds.
7207 	 * Thus, in all cases it suffices to blow away our signed bounds
7208 	 * and rely on inferring new ones from the unsigned bounds and
7209 	 * var_off of the result.
7210 	 */
7211 	dst_reg->s32_min_value = S32_MIN;
7212 	dst_reg->s32_max_value = S32_MAX;
7213 
7214 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7215 	dst_reg->u32_min_value >>= umax_val;
7216 	dst_reg->u32_max_value >>= umin_val;
7217 
7218 	__mark_reg64_unbounded(dst_reg);
7219 	__update_reg32_bounds(dst_reg);
7220 }
7221 
7222 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7223 			       struct bpf_reg_state *src_reg)
7224 {
7225 	u64 umax_val = src_reg->umax_value;
7226 	u64 umin_val = src_reg->umin_value;
7227 
7228 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7229 	 * be negative, then either:
7230 	 * 1) src_reg might be zero, so the sign bit of the result is
7231 	 *    unknown, so we lose our signed bounds
7232 	 * 2) it's known negative, thus the unsigned bounds capture the
7233 	 *    signed bounds
7234 	 * 3) the signed bounds cross zero, so they tell us nothing
7235 	 *    about the result
7236 	 * If the value in dst_reg is known nonnegative, then again the
7237 	 * unsigned bounds capture the signed bounds.
7238 	 * Thus, in all cases it suffices to blow away our signed bounds
7239 	 * and rely on inferring new ones from the unsigned bounds and
7240 	 * var_off of the result.
7241 	 */
7242 	dst_reg->smin_value = S64_MIN;
7243 	dst_reg->smax_value = S64_MAX;
7244 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7245 	dst_reg->umin_value >>= umax_val;
7246 	dst_reg->umax_value >>= umin_val;
7247 
7248 	/* Its not easy to operate on alu32 bounds here because it depends
7249 	 * on bits being shifted in. Take easy way out and mark unbounded
7250 	 * so we can recalculate later from tnum.
7251 	 */
7252 	__mark_reg32_unbounded(dst_reg);
7253 	__update_reg_bounds(dst_reg);
7254 }
7255 
7256 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7257 				  struct bpf_reg_state *src_reg)
7258 {
7259 	u64 umin_val = src_reg->u32_min_value;
7260 
7261 	/* Upon reaching here, src_known is true and
7262 	 * umax_val is equal to umin_val.
7263 	 */
7264 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7265 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7266 
7267 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7268 
7269 	/* blow away the dst_reg umin_value/umax_value and rely on
7270 	 * dst_reg var_off to refine the result.
7271 	 */
7272 	dst_reg->u32_min_value = 0;
7273 	dst_reg->u32_max_value = U32_MAX;
7274 
7275 	__mark_reg64_unbounded(dst_reg);
7276 	__update_reg32_bounds(dst_reg);
7277 }
7278 
7279 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7280 				struct bpf_reg_state *src_reg)
7281 {
7282 	u64 umin_val = src_reg->umin_value;
7283 
7284 	/* Upon reaching here, src_known is true and umax_val is equal
7285 	 * to umin_val.
7286 	 */
7287 	dst_reg->smin_value >>= umin_val;
7288 	dst_reg->smax_value >>= umin_val;
7289 
7290 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7291 
7292 	/* blow away the dst_reg umin_value/umax_value and rely on
7293 	 * dst_reg var_off to refine the result.
7294 	 */
7295 	dst_reg->umin_value = 0;
7296 	dst_reg->umax_value = U64_MAX;
7297 
7298 	/* Its not easy to operate on alu32 bounds here because it depends
7299 	 * on bits being shifted in from upper 32-bits. Take easy way out
7300 	 * and mark unbounded so we can recalculate later from tnum.
7301 	 */
7302 	__mark_reg32_unbounded(dst_reg);
7303 	__update_reg_bounds(dst_reg);
7304 }
7305 
7306 /* WARNING: This function does calculations on 64-bit values, but the actual
7307  * execution may occur on 32-bit values. Therefore, things like bitshifts
7308  * need extra checks in the 32-bit case.
7309  */
7310 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7311 				      struct bpf_insn *insn,
7312 				      struct bpf_reg_state *dst_reg,
7313 				      struct bpf_reg_state src_reg)
7314 {
7315 	struct bpf_reg_state *regs = cur_regs(env);
7316 	u8 opcode = BPF_OP(insn->code);
7317 	bool src_known;
7318 	s64 smin_val, smax_val;
7319 	u64 umin_val, umax_val;
7320 	s32 s32_min_val, s32_max_val;
7321 	u32 u32_min_val, u32_max_val;
7322 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7323 	u32 dst = insn->dst_reg;
7324 	int ret;
7325 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7326 
7327 	smin_val = src_reg.smin_value;
7328 	smax_val = src_reg.smax_value;
7329 	umin_val = src_reg.umin_value;
7330 	umax_val = src_reg.umax_value;
7331 
7332 	s32_min_val = src_reg.s32_min_value;
7333 	s32_max_val = src_reg.s32_max_value;
7334 	u32_min_val = src_reg.u32_min_value;
7335 	u32_max_val = src_reg.u32_max_value;
7336 
7337 	if (alu32) {
7338 		src_known = tnum_subreg_is_const(src_reg.var_off);
7339 		if ((src_known &&
7340 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7341 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7342 			/* Taint dst register if offset had invalid bounds
7343 			 * derived from e.g. dead branches.
7344 			 */
7345 			__mark_reg_unknown(env, dst_reg);
7346 			return 0;
7347 		}
7348 	} else {
7349 		src_known = tnum_is_const(src_reg.var_off);
7350 		if ((src_known &&
7351 		     (smin_val != smax_val || umin_val != umax_val)) ||
7352 		    smin_val > smax_val || umin_val > umax_val) {
7353 			/* Taint dst register if offset had invalid bounds
7354 			 * derived from e.g. dead branches.
7355 			 */
7356 			__mark_reg_unknown(env, dst_reg);
7357 			return 0;
7358 		}
7359 	}
7360 
7361 	if (!src_known &&
7362 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7363 		__mark_reg_unknown(env, dst_reg);
7364 		return 0;
7365 	}
7366 
7367 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7368 	 * There are two classes of instructions: The first class we track both
7369 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
7370 	 * greatest amount of precision when alu operations are mixed with jmp32
7371 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7372 	 * and BPF_OR. This is possible because these ops have fairly easy to
7373 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7374 	 * See alu32 verifier tests for examples. The second class of
7375 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7376 	 * with regards to tracking sign/unsigned bounds because the bits may
7377 	 * cross subreg boundaries in the alu64 case. When this happens we mark
7378 	 * the reg unbounded in the subreg bound space and use the resulting
7379 	 * tnum to calculate an approximation of the sign/unsigned bounds.
7380 	 */
7381 	switch (opcode) {
7382 	case BPF_ADD:
7383 		ret = sanitize_val_alu(env, insn);
7384 		if (ret < 0) {
7385 			verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7386 			return ret;
7387 		}
7388 		scalar32_min_max_add(dst_reg, &src_reg);
7389 		scalar_min_max_add(dst_reg, &src_reg);
7390 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7391 		break;
7392 	case BPF_SUB:
7393 		ret = sanitize_val_alu(env, insn);
7394 		if (ret < 0) {
7395 			verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7396 			return ret;
7397 		}
7398 		scalar32_min_max_sub(dst_reg, &src_reg);
7399 		scalar_min_max_sub(dst_reg, &src_reg);
7400 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7401 		break;
7402 	case BPF_MUL:
7403 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7404 		scalar32_min_max_mul(dst_reg, &src_reg);
7405 		scalar_min_max_mul(dst_reg, &src_reg);
7406 		break;
7407 	case BPF_AND:
7408 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7409 		scalar32_min_max_and(dst_reg, &src_reg);
7410 		scalar_min_max_and(dst_reg, &src_reg);
7411 		break;
7412 	case BPF_OR:
7413 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7414 		scalar32_min_max_or(dst_reg, &src_reg);
7415 		scalar_min_max_or(dst_reg, &src_reg);
7416 		break;
7417 	case BPF_XOR:
7418 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7419 		scalar32_min_max_xor(dst_reg, &src_reg);
7420 		scalar_min_max_xor(dst_reg, &src_reg);
7421 		break;
7422 	case BPF_LSH:
7423 		if (umax_val >= insn_bitness) {
7424 			/* Shifts greater than 31 or 63 are undefined.
7425 			 * This includes shifts by a negative number.
7426 			 */
7427 			mark_reg_unknown(env, regs, insn->dst_reg);
7428 			break;
7429 		}
7430 		if (alu32)
7431 			scalar32_min_max_lsh(dst_reg, &src_reg);
7432 		else
7433 			scalar_min_max_lsh(dst_reg, &src_reg);
7434 		break;
7435 	case BPF_RSH:
7436 		if (umax_val >= insn_bitness) {
7437 			/* Shifts greater than 31 or 63 are undefined.
7438 			 * This includes shifts by a negative number.
7439 			 */
7440 			mark_reg_unknown(env, regs, insn->dst_reg);
7441 			break;
7442 		}
7443 		if (alu32)
7444 			scalar32_min_max_rsh(dst_reg, &src_reg);
7445 		else
7446 			scalar_min_max_rsh(dst_reg, &src_reg);
7447 		break;
7448 	case BPF_ARSH:
7449 		if (umax_val >= insn_bitness) {
7450 			/* Shifts greater than 31 or 63 are undefined.
7451 			 * This includes shifts by a negative number.
7452 			 */
7453 			mark_reg_unknown(env, regs, insn->dst_reg);
7454 			break;
7455 		}
7456 		if (alu32)
7457 			scalar32_min_max_arsh(dst_reg, &src_reg);
7458 		else
7459 			scalar_min_max_arsh(dst_reg, &src_reg);
7460 		break;
7461 	default:
7462 		mark_reg_unknown(env, regs, insn->dst_reg);
7463 		break;
7464 	}
7465 
7466 	/* ALU32 ops are zero extended into 64bit register */
7467 	if (alu32)
7468 		zext_32_to_64(dst_reg);
7469 
7470 	__update_reg_bounds(dst_reg);
7471 	__reg_deduce_bounds(dst_reg);
7472 	__reg_bound_offset(dst_reg);
7473 	return 0;
7474 }
7475 
7476 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7477  * and var_off.
7478  */
7479 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7480 				   struct bpf_insn *insn)
7481 {
7482 	struct bpf_verifier_state *vstate = env->cur_state;
7483 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7484 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7485 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7486 	u8 opcode = BPF_OP(insn->code);
7487 	int err;
7488 
7489 	dst_reg = &regs[insn->dst_reg];
7490 	src_reg = NULL;
7491 	if (dst_reg->type != SCALAR_VALUE)
7492 		ptr_reg = dst_reg;
7493 	else
7494 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7495 		 * incorrectly propagated into other registers by find_equal_scalars()
7496 		 */
7497 		dst_reg->id = 0;
7498 	if (BPF_SRC(insn->code) == BPF_X) {
7499 		src_reg = &regs[insn->src_reg];
7500 		if (src_reg->type != SCALAR_VALUE) {
7501 			if (dst_reg->type != SCALAR_VALUE) {
7502 				/* Combining two pointers by any ALU op yields
7503 				 * an arbitrary scalar. Disallow all math except
7504 				 * pointer subtraction
7505 				 */
7506 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7507 					mark_reg_unknown(env, regs, insn->dst_reg);
7508 					return 0;
7509 				}
7510 				verbose(env, "R%d pointer %s pointer prohibited\n",
7511 					insn->dst_reg,
7512 					bpf_alu_string[opcode >> 4]);
7513 				return -EACCES;
7514 			} else {
7515 				/* scalar += pointer
7516 				 * This is legal, but we have to reverse our
7517 				 * src/dest handling in computing the range
7518 				 */
7519 				err = mark_chain_precision(env, insn->dst_reg);
7520 				if (err)
7521 					return err;
7522 				return adjust_ptr_min_max_vals(env, insn,
7523 							       src_reg, dst_reg);
7524 			}
7525 		} else if (ptr_reg) {
7526 			/* pointer += scalar */
7527 			err = mark_chain_precision(env, insn->src_reg);
7528 			if (err)
7529 				return err;
7530 			return adjust_ptr_min_max_vals(env, insn,
7531 						       dst_reg, src_reg);
7532 		}
7533 	} else {
7534 		/* Pretend the src is a reg with a known value, since we only
7535 		 * need to be able to read from this state.
7536 		 */
7537 		off_reg.type = SCALAR_VALUE;
7538 		__mark_reg_known(&off_reg, insn->imm);
7539 		src_reg = &off_reg;
7540 		if (ptr_reg) /* pointer += K */
7541 			return adjust_ptr_min_max_vals(env, insn,
7542 						       ptr_reg, src_reg);
7543 	}
7544 
7545 	/* Got here implies adding two SCALAR_VALUEs */
7546 	if (WARN_ON_ONCE(ptr_reg)) {
7547 		print_verifier_state(env, state);
7548 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
7549 		return -EINVAL;
7550 	}
7551 	if (WARN_ON(!src_reg)) {
7552 		print_verifier_state(env, state);
7553 		verbose(env, "verifier internal error: no src_reg\n");
7554 		return -EINVAL;
7555 	}
7556 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7557 }
7558 
7559 /* check validity of 32-bit and 64-bit arithmetic operations */
7560 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7561 {
7562 	struct bpf_reg_state *regs = cur_regs(env);
7563 	u8 opcode = BPF_OP(insn->code);
7564 	int err;
7565 
7566 	if (opcode == BPF_END || opcode == BPF_NEG) {
7567 		if (opcode == BPF_NEG) {
7568 			if (BPF_SRC(insn->code) != 0 ||
7569 			    insn->src_reg != BPF_REG_0 ||
7570 			    insn->off != 0 || insn->imm != 0) {
7571 				verbose(env, "BPF_NEG uses reserved fields\n");
7572 				return -EINVAL;
7573 			}
7574 		} else {
7575 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7576 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7577 			    BPF_CLASS(insn->code) == BPF_ALU64) {
7578 				verbose(env, "BPF_END uses reserved fields\n");
7579 				return -EINVAL;
7580 			}
7581 		}
7582 
7583 		/* check src operand */
7584 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7585 		if (err)
7586 			return err;
7587 
7588 		if (is_pointer_value(env, insn->dst_reg)) {
7589 			verbose(env, "R%d pointer arithmetic prohibited\n",
7590 				insn->dst_reg);
7591 			return -EACCES;
7592 		}
7593 
7594 		/* check dest operand */
7595 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
7596 		if (err)
7597 			return err;
7598 
7599 	} else if (opcode == BPF_MOV) {
7600 
7601 		if (BPF_SRC(insn->code) == BPF_X) {
7602 			if (insn->imm != 0 || insn->off != 0) {
7603 				verbose(env, "BPF_MOV uses reserved fields\n");
7604 				return -EINVAL;
7605 			}
7606 
7607 			/* check src operand */
7608 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7609 			if (err)
7610 				return err;
7611 		} else {
7612 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7613 				verbose(env, "BPF_MOV uses reserved fields\n");
7614 				return -EINVAL;
7615 			}
7616 		}
7617 
7618 		/* check dest operand, mark as required later */
7619 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7620 		if (err)
7621 			return err;
7622 
7623 		if (BPF_SRC(insn->code) == BPF_X) {
7624 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
7625 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7626 
7627 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7628 				/* case: R1 = R2
7629 				 * copy register state to dest reg
7630 				 */
7631 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7632 					/* Assign src and dst registers the same ID
7633 					 * that will be used by find_equal_scalars()
7634 					 * to propagate min/max range.
7635 					 */
7636 					src_reg->id = ++env->id_gen;
7637 				*dst_reg = *src_reg;
7638 				dst_reg->live |= REG_LIVE_WRITTEN;
7639 				dst_reg->subreg_def = DEF_NOT_SUBREG;
7640 			} else {
7641 				/* R1 = (u32) R2 */
7642 				if (is_pointer_value(env, insn->src_reg)) {
7643 					verbose(env,
7644 						"R%d partial copy of pointer\n",
7645 						insn->src_reg);
7646 					return -EACCES;
7647 				} else if (src_reg->type == SCALAR_VALUE) {
7648 					*dst_reg = *src_reg;
7649 					/* Make sure ID is cleared otherwise
7650 					 * dst_reg min/max could be incorrectly
7651 					 * propagated into src_reg by find_equal_scalars()
7652 					 */
7653 					dst_reg->id = 0;
7654 					dst_reg->live |= REG_LIVE_WRITTEN;
7655 					dst_reg->subreg_def = env->insn_idx + 1;
7656 				} else {
7657 					mark_reg_unknown(env, regs,
7658 							 insn->dst_reg);
7659 				}
7660 				zext_32_to_64(dst_reg);
7661 			}
7662 		} else {
7663 			/* case: R = imm
7664 			 * remember the value we stored into this reg
7665 			 */
7666 			/* clear any state __mark_reg_known doesn't set */
7667 			mark_reg_unknown(env, regs, insn->dst_reg);
7668 			regs[insn->dst_reg].type = SCALAR_VALUE;
7669 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7670 				__mark_reg_known(regs + insn->dst_reg,
7671 						 insn->imm);
7672 			} else {
7673 				__mark_reg_known(regs + insn->dst_reg,
7674 						 (u32)insn->imm);
7675 			}
7676 		}
7677 
7678 	} else if (opcode > BPF_END) {
7679 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7680 		return -EINVAL;
7681 
7682 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
7683 
7684 		if (BPF_SRC(insn->code) == BPF_X) {
7685 			if (insn->imm != 0 || insn->off != 0) {
7686 				verbose(env, "BPF_ALU uses reserved fields\n");
7687 				return -EINVAL;
7688 			}
7689 			/* check src1 operand */
7690 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7691 			if (err)
7692 				return err;
7693 		} else {
7694 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7695 				verbose(env, "BPF_ALU uses reserved fields\n");
7696 				return -EINVAL;
7697 			}
7698 		}
7699 
7700 		/* check src2 operand */
7701 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7702 		if (err)
7703 			return err;
7704 
7705 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7706 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7707 			verbose(env, "div by zero\n");
7708 			return -EINVAL;
7709 		}
7710 
7711 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7712 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7713 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7714 
7715 			if (insn->imm < 0 || insn->imm >= size) {
7716 				verbose(env, "invalid shift %d\n", insn->imm);
7717 				return -EINVAL;
7718 			}
7719 		}
7720 
7721 		/* check dest operand */
7722 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7723 		if (err)
7724 			return err;
7725 
7726 		return adjust_reg_min_max_vals(env, insn);
7727 	}
7728 
7729 	return 0;
7730 }
7731 
7732 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7733 				     struct bpf_reg_state *dst_reg,
7734 				     enum bpf_reg_type type, int new_range)
7735 {
7736 	struct bpf_reg_state *reg;
7737 	int i;
7738 
7739 	for (i = 0; i < MAX_BPF_REG; i++) {
7740 		reg = &state->regs[i];
7741 		if (reg->type == type && reg->id == dst_reg->id)
7742 			/* keep the maximum range already checked */
7743 			reg->range = max(reg->range, new_range);
7744 	}
7745 
7746 	bpf_for_each_spilled_reg(i, state, reg) {
7747 		if (!reg)
7748 			continue;
7749 		if (reg->type == type && reg->id == dst_reg->id)
7750 			reg->range = max(reg->range, new_range);
7751 	}
7752 }
7753 
7754 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7755 				   struct bpf_reg_state *dst_reg,
7756 				   enum bpf_reg_type type,
7757 				   bool range_right_open)
7758 {
7759 	int new_range, i;
7760 
7761 	if (dst_reg->off < 0 ||
7762 	    (dst_reg->off == 0 && range_right_open))
7763 		/* This doesn't give us any range */
7764 		return;
7765 
7766 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
7767 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7768 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
7769 		 * than pkt_end, but that's because it's also less than pkt.
7770 		 */
7771 		return;
7772 
7773 	new_range = dst_reg->off;
7774 	if (range_right_open)
7775 		new_range--;
7776 
7777 	/* Examples for register markings:
7778 	 *
7779 	 * pkt_data in dst register:
7780 	 *
7781 	 *   r2 = r3;
7782 	 *   r2 += 8;
7783 	 *   if (r2 > pkt_end) goto <handle exception>
7784 	 *   <access okay>
7785 	 *
7786 	 *   r2 = r3;
7787 	 *   r2 += 8;
7788 	 *   if (r2 < pkt_end) goto <access okay>
7789 	 *   <handle exception>
7790 	 *
7791 	 *   Where:
7792 	 *     r2 == dst_reg, pkt_end == src_reg
7793 	 *     r2=pkt(id=n,off=8,r=0)
7794 	 *     r3=pkt(id=n,off=0,r=0)
7795 	 *
7796 	 * pkt_data in src register:
7797 	 *
7798 	 *   r2 = r3;
7799 	 *   r2 += 8;
7800 	 *   if (pkt_end >= r2) goto <access okay>
7801 	 *   <handle exception>
7802 	 *
7803 	 *   r2 = r3;
7804 	 *   r2 += 8;
7805 	 *   if (pkt_end <= r2) goto <handle exception>
7806 	 *   <access okay>
7807 	 *
7808 	 *   Where:
7809 	 *     pkt_end == dst_reg, r2 == src_reg
7810 	 *     r2=pkt(id=n,off=8,r=0)
7811 	 *     r3=pkt(id=n,off=0,r=0)
7812 	 *
7813 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7814 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7815 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
7816 	 * the check.
7817 	 */
7818 
7819 	/* If our ids match, then we must have the same max_value.  And we
7820 	 * don't care about the other reg's fixed offset, since if it's too big
7821 	 * the range won't allow anything.
7822 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7823 	 */
7824 	for (i = 0; i <= vstate->curframe; i++)
7825 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7826 					 new_range);
7827 }
7828 
7829 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7830 {
7831 	struct tnum subreg = tnum_subreg(reg->var_off);
7832 	s32 sval = (s32)val;
7833 
7834 	switch (opcode) {
7835 	case BPF_JEQ:
7836 		if (tnum_is_const(subreg))
7837 			return !!tnum_equals_const(subreg, val);
7838 		break;
7839 	case BPF_JNE:
7840 		if (tnum_is_const(subreg))
7841 			return !tnum_equals_const(subreg, val);
7842 		break;
7843 	case BPF_JSET:
7844 		if ((~subreg.mask & subreg.value) & val)
7845 			return 1;
7846 		if (!((subreg.mask | subreg.value) & val))
7847 			return 0;
7848 		break;
7849 	case BPF_JGT:
7850 		if (reg->u32_min_value > val)
7851 			return 1;
7852 		else if (reg->u32_max_value <= val)
7853 			return 0;
7854 		break;
7855 	case BPF_JSGT:
7856 		if (reg->s32_min_value > sval)
7857 			return 1;
7858 		else if (reg->s32_max_value <= sval)
7859 			return 0;
7860 		break;
7861 	case BPF_JLT:
7862 		if (reg->u32_max_value < val)
7863 			return 1;
7864 		else if (reg->u32_min_value >= val)
7865 			return 0;
7866 		break;
7867 	case BPF_JSLT:
7868 		if (reg->s32_max_value < sval)
7869 			return 1;
7870 		else if (reg->s32_min_value >= sval)
7871 			return 0;
7872 		break;
7873 	case BPF_JGE:
7874 		if (reg->u32_min_value >= val)
7875 			return 1;
7876 		else if (reg->u32_max_value < val)
7877 			return 0;
7878 		break;
7879 	case BPF_JSGE:
7880 		if (reg->s32_min_value >= sval)
7881 			return 1;
7882 		else if (reg->s32_max_value < sval)
7883 			return 0;
7884 		break;
7885 	case BPF_JLE:
7886 		if (reg->u32_max_value <= val)
7887 			return 1;
7888 		else if (reg->u32_min_value > val)
7889 			return 0;
7890 		break;
7891 	case BPF_JSLE:
7892 		if (reg->s32_max_value <= sval)
7893 			return 1;
7894 		else if (reg->s32_min_value > sval)
7895 			return 0;
7896 		break;
7897 	}
7898 
7899 	return -1;
7900 }
7901 
7902 
7903 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7904 {
7905 	s64 sval = (s64)val;
7906 
7907 	switch (opcode) {
7908 	case BPF_JEQ:
7909 		if (tnum_is_const(reg->var_off))
7910 			return !!tnum_equals_const(reg->var_off, val);
7911 		break;
7912 	case BPF_JNE:
7913 		if (tnum_is_const(reg->var_off))
7914 			return !tnum_equals_const(reg->var_off, val);
7915 		break;
7916 	case BPF_JSET:
7917 		if ((~reg->var_off.mask & reg->var_off.value) & val)
7918 			return 1;
7919 		if (!((reg->var_off.mask | reg->var_off.value) & val))
7920 			return 0;
7921 		break;
7922 	case BPF_JGT:
7923 		if (reg->umin_value > val)
7924 			return 1;
7925 		else if (reg->umax_value <= val)
7926 			return 0;
7927 		break;
7928 	case BPF_JSGT:
7929 		if (reg->smin_value > sval)
7930 			return 1;
7931 		else if (reg->smax_value <= sval)
7932 			return 0;
7933 		break;
7934 	case BPF_JLT:
7935 		if (reg->umax_value < val)
7936 			return 1;
7937 		else if (reg->umin_value >= val)
7938 			return 0;
7939 		break;
7940 	case BPF_JSLT:
7941 		if (reg->smax_value < sval)
7942 			return 1;
7943 		else if (reg->smin_value >= sval)
7944 			return 0;
7945 		break;
7946 	case BPF_JGE:
7947 		if (reg->umin_value >= val)
7948 			return 1;
7949 		else if (reg->umax_value < val)
7950 			return 0;
7951 		break;
7952 	case BPF_JSGE:
7953 		if (reg->smin_value >= sval)
7954 			return 1;
7955 		else if (reg->smax_value < sval)
7956 			return 0;
7957 		break;
7958 	case BPF_JLE:
7959 		if (reg->umax_value <= val)
7960 			return 1;
7961 		else if (reg->umin_value > val)
7962 			return 0;
7963 		break;
7964 	case BPF_JSLE:
7965 		if (reg->smax_value <= sval)
7966 			return 1;
7967 		else if (reg->smin_value > sval)
7968 			return 0;
7969 		break;
7970 	}
7971 
7972 	return -1;
7973 }
7974 
7975 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7976  * and return:
7977  *  1 - branch will be taken and "goto target" will be executed
7978  *  0 - branch will not be taken and fall-through to next insn
7979  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7980  *      range [0,10]
7981  */
7982 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7983 			   bool is_jmp32)
7984 {
7985 	if (__is_pointer_value(false, reg)) {
7986 		if (!reg_type_not_null(reg->type))
7987 			return -1;
7988 
7989 		/* If pointer is valid tests against zero will fail so we can
7990 		 * use this to direct branch taken.
7991 		 */
7992 		if (val != 0)
7993 			return -1;
7994 
7995 		switch (opcode) {
7996 		case BPF_JEQ:
7997 			return 0;
7998 		case BPF_JNE:
7999 			return 1;
8000 		default:
8001 			return -1;
8002 		}
8003 	}
8004 
8005 	if (is_jmp32)
8006 		return is_branch32_taken(reg, val, opcode);
8007 	return is_branch64_taken(reg, val, opcode);
8008 }
8009 
8010 static int flip_opcode(u32 opcode)
8011 {
8012 	/* How can we transform "a <op> b" into "b <op> a"? */
8013 	static const u8 opcode_flip[16] = {
8014 		/* these stay the same */
8015 		[BPF_JEQ  >> 4] = BPF_JEQ,
8016 		[BPF_JNE  >> 4] = BPF_JNE,
8017 		[BPF_JSET >> 4] = BPF_JSET,
8018 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8019 		[BPF_JGE  >> 4] = BPF_JLE,
8020 		[BPF_JGT  >> 4] = BPF_JLT,
8021 		[BPF_JLE  >> 4] = BPF_JGE,
8022 		[BPF_JLT  >> 4] = BPF_JGT,
8023 		[BPF_JSGE >> 4] = BPF_JSLE,
8024 		[BPF_JSGT >> 4] = BPF_JSLT,
8025 		[BPF_JSLE >> 4] = BPF_JSGE,
8026 		[BPF_JSLT >> 4] = BPF_JSGT
8027 	};
8028 	return opcode_flip[opcode >> 4];
8029 }
8030 
8031 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8032 				   struct bpf_reg_state *src_reg,
8033 				   u8 opcode)
8034 {
8035 	struct bpf_reg_state *pkt;
8036 
8037 	if (src_reg->type == PTR_TO_PACKET_END) {
8038 		pkt = dst_reg;
8039 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8040 		pkt = src_reg;
8041 		opcode = flip_opcode(opcode);
8042 	} else {
8043 		return -1;
8044 	}
8045 
8046 	if (pkt->range >= 0)
8047 		return -1;
8048 
8049 	switch (opcode) {
8050 	case BPF_JLE:
8051 		/* pkt <= pkt_end */
8052 		fallthrough;
8053 	case BPF_JGT:
8054 		/* pkt > pkt_end */
8055 		if (pkt->range == BEYOND_PKT_END)
8056 			/* pkt has at last one extra byte beyond pkt_end */
8057 			return opcode == BPF_JGT;
8058 		break;
8059 	case BPF_JLT:
8060 		/* pkt < pkt_end */
8061 		fallthrough;
8062 	case BPF_JGE:
8063 		/* pkt >= pkt_end */
8064 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8065 			return opcode == BPF_JGE;
8066 		break;
8067 	}
8068 	return -1;
8069 }
8070 
8071 /* Adjusts the register min/max values in the case that the dst_reg is the
8072  * variable register that we are working on, and src_reg is a constant or we're
8073  * simply doing a BPF_K check.
8074  * In JEQ/JNE cases we also adjust the var_off values.
8075  */
8076 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8077 			    struct bpf_reg_state *false_reg,
8078 			    u64 val, u32 val32,
8079 			    u8 opcode, bool is_jmp32)
8080 {
8081 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8082 	struct tnum false_64off = false_reg->var_off;
8083 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8084 	struct tnum true_64off = true_reg->var_off;
8085 	s64 sval = (s64)val;
8086 	s32 sval32 = (s32)val32;
8087 
8088 	/* If the dst_reg is a pointer, we can't learn anything about its
8089 	 * variable offset from the compare (unless src_reg were a pointer into
8090 	 * the same object, but we don't bother with that.
8091 	 * Since false_reg and true_reg have the same type by construction, we
8092 	 * only need to check one of them for pointerness.
8093 	 */
8094 	if (__is_pointer_value(false, false_reg))
8095 		return;
8096 
8097 	switch (opcode) {
8098 	case BPF_JEQ:
8099 	case BPF_JNE:
8100 	{
8101 		struct bpf_reg_state *reg =
8102 			opcode == BPF_JEQ ? true_reg : false_reg;
8103 
8104 		/* JEQ/JNE comparison doesn't change the register equivalence.
8105 		 * r1 = r2;
8106 		 * if (r1 == 42) goto label;
8107 		 * ...
8108 		 * label: // here both r1 and r2 are known to be 42.
8109 		 *
8110 		 * Hence when marking register as known preserve it's ID.
8111 		 */
8112 		if (is_jmp32)
8113 			__mark_reg32_known(reg, val32);
8114 		else
8115 			___mark_reg_known(reg, val);
8116 		break;
8117 	}
8118 	case BPF_JSET:
8119 		if (is_jmp32) {
8120 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8121 			if (is_power_of_2(val32))
8122 				true_32off = tnum_or(true_32off,
8123 						     tnum_const(val32));
8124 		} else {
8125 			false_64off = tnum_and(false_64off, tnum_const(~val));
8126 			if (is_power_of_2(val))
8127 				true_64off = tnum_or(true_64off,
8128 						     tnum_const(val));
8129 		}
8130 		break;
8131 	case BPF_JGE:
8132 	case BPF_JGT:
8133 	{
8134 		if (is_jmp32) {
8135 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8136 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8137 
8138 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8139 						       false_umax);
8140 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8141 						      true_umin);
8142 		} else {
8143 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8144 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8145 
8146 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8147 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8148 		}
8149 		break;
8150 	}
8151 	case BPF_JSGE:
8152 	case BPF_JSGT:
8153 	{
8154 		if (is_jmp32) {
8155 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8156 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8157 
8158 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8159 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8160 		} else {
8161 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8162 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8163 
8164 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8165 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8166 		}
8167 		break;
8168 	}
8169 	case BPF_JLE:
8170 	case BPF_JLT:
8171 	{
8172 		if (is_jmp32) {
8173 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8174 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8175 
8176 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8177 						       false_umin);
8178 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8179 						      true_umax);
8180 		} else {
8181 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8182 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8183 
8184 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8185 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8186 		}
8187 		break;
8188 	}
8189 	case BPF_JSLE:
8190 	case BPF_JSLT:
8191 	{
8192 		if (is_jmp32) {
8193 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8194 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8195 
8196 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8197 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8198 		} else {
8199 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8200 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8201 
8202 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8203 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8204 		}
8205 		break;
8206 	}
8207 	default:
8208 		return;
8209 	}
8210 
8211 	if (is_jmp32) {
8212 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8213 					     tnum_subreg(false_32off));
8214 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8215 					    tnum_subreg(true_32off));
8216 		__reg_combine_32_into_64(false_reg);
8217 		__reg_combine_32_into_64(true_reg);
8218 	} else {
8219 		false_reg->var_off = false_64off;
8220 		true_reg->var_off = true_64off;
8221 		__reg_combine_64_into_32(false_reg);
8222 		__reg_combine_64_into_32(true_reg);
8223 	}
8224 }
8225 
8226 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8227  * the variable reg.
8228  */
8229 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8230 				struct bpf_reg_state *false_reg,
8231 				u64 val, u32 val32,
8232 				u8 opcode, bool is_jmp32)
8233 {
8234 	opcode = flip_opcode(opcode);
8235 	/* This uses zero as "not present in table"; luckily the zero opcode,
8236 	 * BPF_JA, can't get here.
8237 	 */
8238 	if (opcode)
8239 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8240 }
8241 
8242 /* Regs are known to be equal, so intersect their min/max/var_off */
8243 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8244 				  struct bpf_reg_state *dst_reg)
8245 {
8246 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8247 							dst_reg->umin_value);
8248 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8249 							dst_reg->umax_value);
8250 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8251 							dst_reg->smin_value);
8252 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8253 							dst_reg->smax_value);
8254 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8255 							     dst_reg->var_off);
8256 	/* We might have learned new bounds from the var_off. */
8257 	__update_reg_bounds(src_reg);
8258 	__update_reg_bounds(dst_reg);
8259 	/* We might have learned something about the sign bit. */
8260 	__reg_deduce_bounds(src_reg);
8261 	__reg_deduce_bounds(dst_reg);
8262 	/* We might have learned some bits from the bounds. */
8263 	__reg_bound_offset(src_reg);
8264 	__reg_bound_offset(dst_reg);
8265 	/* Intersecting with the old var_off might have improved our bounds
8266 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8267 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
8268 	 */
8269 	__update_reg_bounds(src_reg);
8270 	__update_reg_bounds(dst_reg);
8271 }
8272 
8273 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8274 				struct bpf_reg_state *true_dst,
8275 				struct bpf_reg_state *false_src,
8276 				struct bpf_reg_state *false_dst,
8277 				u8 opcode)
8278 {
8279 	switch (opcode) {
8280 	case BPF_JEQ:
8281 		__reg_combine_min_max(true_src, true_dst);
8282 		break;
8283 	case BPF_JNE:
8284 		__reg_combine_min_max(false_src, false_dst);
8285 		break;
8286 	}
8287 }
8288 
8289 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8290 				 struct bpf_reg_state *reg, u32 id,
8291 				 bool is_null)
8292 {
8293 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
8294 	    !WARN_ON_ONCE(!reg->id)) {
8295 		/* Old offset (both fixed and variable parts) should
8296 		 * have been known-zero, because we don't allow pointer
8297 		 * arithmetic on pointers that might be NULL.
8298 		 */
8299 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8300 				 !tnum_equals_const(reg->var_off, 0) ||
8301 				 reg->off)) {
8302 			__mark_reg_known_zero(reg);
8303 			reg->off = 0;
8304 		}
8305 		if (is_null) {
8306 			reg->type = SCALAR_VALUE;
8307 			/* We don't need id and ref_obj_id from this point
8308 			 * onwards anymore, thus we should better reset it,
8309 			 * so that state pruning has chances to take effect.
8310 			 */
8311 			reg->id = 0;
8312 			reg->ref_obj_id = 0;
8313 
8314 			return;
8315 		}
8316 
8317 		mark_ptr_not_null_reg(reg);
8318 
8319 		if (!reg_may_point_to_spin_lock(reg)) {
8320 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8321 			 * in release_reg_references().
8322 			 *
8323 			 * reg->id is still used by spin_lock ptr. Other
8324 			 * than spin_lock ptr type, reg->id can be reset.
8325 			 */
8326 			reg->id = 0;
8327 		}
8328 	}
8329 }
8330 
8331 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8332 				    bool is_null)
8333 {
8334 	struct bpf_reg_state *reg;
8335 	int i;
8336 
8337 	for (i = 0; i < MAX_BPF_REG; i++)
8338 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8339 
8340 	bpf_for_each_spilled_reg(i, state, reg) {
8341 		if (!reg)
8342 			continue;
8343 		mark_ptr_or_null_reg(state, reg, id, is_null);
8344 	}
8345 }
8346 
8347 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8348  * be folded together at some point.
8349  */
8350 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8351 				  bool is_null)
8352 {
8353 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8354 	struct bpf_reg_state *regs = state->regs;
8355 	u32 ref_obj_id = regs[regno].ref_obj_id;
8356 	u32 id = regs[regno].id;
8357 	int i;
8358 
8359 	if (ref_obj_id && ref_obj_id == id && is_null)
8360 		/* regs[regno] is in the " == NULL" branch.
8361 		 * No one could have freed the reference state before
8362 		 * doing the NULL check.
8363 		 */
8364 		WARN_ON_ONCE(release_reference_state(state, id));
8365 
8366 	for (i = 0; i <= vstate->curframe; i++)
8367 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8368 }
8369 
8370 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8371 				   struct bpf_reg_state *dst_reg,
8372 				   struct bpf_reg_state *src_reg,
8373 				   struct bpf_verifier_state *this_branch,
8374 				   struct bpf_verifier_state *other_branch)
8375 {
8376 	if (BPF_SRC(insn->code) != BPF_X)
8377 		return false;
8378 
8379 	/* Pointers are always 64-bit. */
8380 	if (BPF_CLASS(insn->code) == BPF_JMP32)
8381 		return false;
8382 
8383 	switch (BPF_OP(insn->code)) {
8384 	case BPF_JGT:
8385 		if ((dst_reg->type == PTR_TO_PACKET &&
8386 		     src_reg->type == PTR_TO_PACKET_END) ||
8387 		    (dst_reg->type == PTR_TO_PACKET_META &&
8388 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8389 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8390 			find_good_pkt_pointers(this_branch, dst_reg,
8391 					       dst_reg->type, false);
8392 			mark_pkt_end(other_branch, insn->dst_reg, true);
8393 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8394 			    src_reg->type == PTR_TO_PACKET) ||
8395 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8396 			    src_reg->type == PTR_TO_PACKET_META)) {
8397 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
8398 			find_good_pkt_pointers(other_branch, src_reg,
8399 					       src_reg->type, true);
8400 			mark_pkt_end(this_branch, insn->src_reg, false);
8401 		} else {
8402 			return false;
8403 		}
8404 		break;
8405 	case BPF_JLT:
8406 		if ((dst_reg->type == PTR_TO_PACKET &&
8407 		     src_reg->type == PTR_TO_PACKET_END) ||
8408 		    (dst_reg->type == PTR_TO_PACKET_META &&
8409 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8410 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8411 			find_good_pkt_pointers(other_branch, dst_reg,
8412 					       dst_reg->type, true);
8413 			mark_pkt_end(this_branch, insn->dst_reg, false);
8414 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8415 			    src_reg->type == PTR_TO_PACKET) ||
8416 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8417 			    src_reg->type == PTR_TO_PACKET_META)) {
8418 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
8419 			find_good_pkt_pointers(this_branch, src_reg,
8420 					       src_reg->type, false);
8421 			mark_pkt_end(other_branch, insn->src_reg, true);
8422 		} else {
8423 			return false;
8424 		}
8425 		break;
8426 	case BPF_JGE:
8427 		if ((dst_reg->type == PTR_TO_PACKET &&
8428 		     src_reg->type == PTR_TO_PACKET_END) ||
8429 		    (dst_reg->type == PTR_TO_PACKET_META &&
8430 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8431 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8432 			find_good_pkt_pointers(this_branch, dst_reg,
8433 					       dst_reg->type, true);
8434 			mark_pkt_end(other_branch, insn->dst_reg, false);
8435 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8436 			    src_reg->type == PTR_TO_PACKET) ||
8437 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8438 			    src_reg->type == PTR_TO_PACKET_META)) {
8439 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8440 			find_good_pkt_pointers(other_branch, src_reg,
8441 					       src_reg->type, false);
8442 			mark_pkt_end(this_branch, insn->src_reg, true);
8443 		} else {
8444 			return false;
8445 		}
8446 		break;
8447 	case BPF_JLE:
8448 		if ((dst_reg->type == PTR_TO_PACKET &&
8449 		     src_reg->type == PTR_TO_PACKET_END) ||
8450 		    (dst_reg->type == PTR_TO_PACKET_META &&
8451 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8452 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8453 			find_good_pkt_pointers(other_branch, dst_reg,
8454 					       dst_reg->type, false);
8455 			mark_pkt_end(this_branch, insn->dst_reg, true);
8456 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8457 			    src_reg->type == PTR_TO_PACKET) ||
8458 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8459 			    src_reg->type == PTR_TO_PACKET_META)) {
8460 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8461 			find_good_pkt_pointers(this_branch, src_reg,
8462 					       src_reg->type, true);
8463 			mark_pkt_end(other_branch, insn->src_reg, false);
8464 		} else {
8465 			return false;
8466 		}
8467 		break;
8468 	default:
8469 		return false;
8470 	}
8471 
8472 	return true;
8473 }
8474 
8475 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8476 			       struct bpf_reg_state *known_reg)
8477 {
8478 	struct bpf_func_state *state;
8479 	struct bpf_reg_state *reg;
8480 	int i, j;
8481 
8482 	for (i = 0; i <= vstate->curframe; i++) {
8483 		state = vstate->frame[i];
8484 		for (j = 0; j < MAX_BPF_REG; j++) {
8485 			reg = &state->regs[j];
8486 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8487 				*reg = *known_reg;
8488 		}
8489 
8490 		bpf_for_each_spilled_reg(j, state, reg) {
8491 			if (!reg)
8492 				continue;
8493 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8494 				*reg = *known_reg;
8495 		}
8496 	}
8497 }
8498 
8499 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8500 			     struct bpf_insn *insn, int *insn_idx)
8501 {
8502 	struct bpf_verifier_state *this_branch = env->cur_state;
8503 	struct bpf_verifier_state *other_branch;
8504 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8505 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8506 	u8 opcode = BPF_OP(insn->code);
8507 	bool is_jmp32;
8508 	int pred = -1;
8509 	int err;
8510 
8511 	/* Only conditional jumps are expected to reach here. */
8512 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8513 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8514 		return -EINVAL;
8515 	}
8516 
8517 	if (BPF_SRC(insn->code) == BPF_X) {
8518 		if (insn->imm != 0) {
8519 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8520 			return -EINVAL;
8521 		}
8522 
8523 		/* check src1 operand */
8524 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8525 		if (err)
8526 			return err;
8527 
8528 		if (is_pointer_value(env, insn->src_reg)) {
8529 			verbose(env, "R%d pointer comparison prohibited\n",
8530 				insn->src_reg);
8531 			return -EACCES;
8532 		}
8533 		src_reg = &regs[insn->src_reg];
8534 	} else {
8535 		if (insn->src_reg != BPF_REG_0) {
8536 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8537 			return -EINVAL;
8538 		}
8539 	}
8540 
8541 	/* check src2 operand */
8542 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8543 	if (err)
8544 		return err;
8545 
8546 	dst_reg = &regs[insn->dst_reg];
8547 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8548 
8549 	if (BPF_SRC(insn->code) == BPF_K) {
8550 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8551 	} else if (src_reg->type == SCALAR_VALUE &&
8552 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8553 		pred = is_branch_taken(dst_reg,
8554 				       tnum_subreg(src_reg->var_off).value,
8555 				       opcode,
8556 				       is_jmp32);
8557 	} else if (src_reg->type == SCALAR_VALUE &&
8558 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8559 		pred = is_branch_taken(dst_reg,
8560 				       src_reg->var_off.value,
8561 				       opcode,
8562 				       is_jmp32);
8563 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8564 		   reg_is_pkt_pointer_any(src_reg) &&
8565 		   !is_jmp32) {
8566 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8567 	}
8568 
8569 	if (pred >= 0) {
8570 		/* If we get here with a dst_reg pointer type it is because
8571 		 * above is_branch_taken() special cased the 0 comparison.
8572 		 */
8573 		if (!__is_pointer_value(false, dst_reg))
8574 			err = mark_chain_precision(env, insn->dst_reg);
8575 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8576 		    !__is_pointer_value(false, src_reg))
8577 			err = mark_chain_precision(env, insn->src_reg);
8578 		if (err)
8579 			return err;
8580 	}
8581 	if (pred == 1) {
8582 		/* only follow the goto, ignore fall-through */
8583 		*insn_idx += insn->off;
8584 		return 0;
8585 	} else if (pred == 0) {
8586 		/* only follow fall-through branch, since
8587 		 * that's where the program will go
8588 		 */
8589 		return 0;
8590 	}
8591 
8592 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8593 				  false);
8594 	if (!other_branch)
8595 		return -EFAULT;
8596 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8597 
8598 	/* detect if we are comparing against a constant value so we can adjust
8599 	 * our min/max values for our dst register.
8600 	 * this is only legit if both are scalars (or pointers to the same
8601 	 * object, I suppose, but we don't support that right now), because
8602 	 * otherwise the different base pointers mean the offsets aren't
8603 	 * comparable.
8604 	 */
8605 	if (BPF_SRC(insn->code) == BPF_X) {
8606 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8607 
8608 		if (dst_reg->type == SCALAR_VALUE &&
8609 		    src_reg->type == SCALAR_VALUE) {
8610 			if (tnum_is_const(src_reg->var_off) ||
8611 			    (is_jmp32 &&
8612 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8613 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8614 						dst_reg,
8615 						src_reg->var_off.value,
8616 						tnum_subreg(src_reg->var_off).value,
8617 						opcode, is_jmp32);
8618 			else if (tnum_is_const(dst_reg->var_off) ||
8619 				 (is_jmp32 &&
8620 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8621 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8622 						    src_reg,
8623 						    dst_reg->var_off.value,
8624 						    tnum_subreg(dst_reg->var_off).value,
8625 						    opcode, is_jmp32);
8626 			else if (!is_jmp32 &&
8627 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8628 				/* Comparing for equality, we can combine knowledge */
8629 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8630 						    &other_branch_regs[insn->dst_reg],
8631 						    src_reg, dst_reg, opcode);
8632 			if (src_reg->id &&
8633 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8634 				find_equal_scalars(this_branch, src_reg);
8635 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8636 			}
8637 
8638 		}
8639 	} else if (dst_reg->type == SCALAR_VALUE) {
8640 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8641 					dst_reg, insn->imm, (u32)insn->imm,
8642 					opcode, is_jmp32);
8643 	}
8644 
8645 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8646 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8647 		find_equal_scalars(this_branch, dst_reg);
8648 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8649 	}
8650 
8651 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8652 	 * NOTE: these optimizations below are related with pointer comparison
8653 	 *       which will never be JMP32.
8654 	 */
8655 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8656 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8657 	    reg_type_may_be_null(dst_reg->type)) {
8658 		/* Mark all identical registers in each branch as either
8659 		 * safe or unknown depending R == 0 or R != 0 conditional.
8660 		 */
8661 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8662 				      opcode == BPF_JNE);
8663 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8664 				      opcode == BPF_JEQ);
8665 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8666 					   this_branch, other_branch) &&
8667 		   is_pointer_value(env, insn->dst_reg)) {
8668 		verbose(env, "R%d pointer comparison prohibited\n",
8669 			insn->dst_reg);
8670 		return -EACCES;
8671 	}
8672 	if (env->log.level & BPF_LOG_LEVEL)
8673 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8674 	return 0;
8675 }
8676 
8677 /* verify BPF_LD_IMM64 instruction */
8678 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8679 {
8680 	struct bpf_insn_aux_data *aux = cur_aux(env);
8681 	struct bpf_reg_state *regs = cur_regs(env);
8682 	struct bpf_reg_state *dst_reg;
8683 	struct bpf_map *map;
8684 	int err;
8685 
8686 	if (BPF_SIZE(insn->code) != BPF_DW) {
8687 		verbose(env, "invalid BPF_LD_IMM insn\n");
8688 		return -EINVAL;
8689 	}
8690 	if (insn->off != 0) {
8691 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8692 		return -EINVAL;
8693 	}
8694 
8695 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8696 	if (err)
8697 		return err;
8698 
8699 	dst_reg = &regs[insn->dst_reg];
8700 	if (insn->src_reg == 0) {
8701 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8702 
8703 		dst_reg->type = SCALAR_VALUE;
8704 		__mark_reg_known(&regs[insn->dst_reg], imm);
8705 		return 0;
8706 	}
8707 
8708 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8709 		mark_reg_known_zero(env, regs, insn->dst_reg);
8710 
8711 		dst_reg->type = aux->btf_var.reg_type;
8712 		switch (dst_reg->type) {
8713 		case PTR_TO_MEM:
8714 			dst_reg->mem_size = aux->btf_var.mem_size;
8715 			break;
8716 		case PTR_TO_BTF_ID:
8717 		case PTR_TO_PERCPU_BTF_ID:
8718 			dst_reg->btf = aux->btf_var.btf;
8719 			dst_reg->btf_id = aux->btf_var.btf_id;
8720 			break;
8721 		default:
8722 			verbose(env, "bpf verifier is misconfigured\n");
8723 			return -EFAULT;
8724 		}
8725 		return 0;
8726 	}
8727 
8728 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
8729 		struct bpf_prog_aux *aux = env->prog->aux;
8730 		u32 subprogno = insn[1].imm;
8731 
8732 		if (!aux->func_info) {
8733 			verbose(env, "missing btf func_info\n");
8734 			return -EINVAL;
8735 		}
8736 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8737 			verbose(env, "callback function not static\n");
8738 			return -EINVAL;
8739 		}
8740 
8741 		dst_reg->type = PTR_TO_FUNC;
8742 		dst_reg->subprogno = subprogno;
8743 		return 0;
8744 	}
8745 
8746 	map = env->used_maps[aux->map_index];
8747 	mark_reg_known_zero(env, regs, insn->dst_reg);
8748 	dst_reg->map_ptr = map;
8749 
8750 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8751 		dst_reg->type = PTR_TO_MAP_VALUE;
8752 		dst_reg->off = aux->map_off;
8753 		if (map_value_has_spin_lock(map))
8754 			dst_reg->id = ++env->id_gen;
8755 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8756 		dst_reg->type = CONST_PTR_TO_MAP;
8757 	} else {
8758 		verbose(env, "bpf verifier is misconfigured\n");
8759 		return -EINVAL;
8760 	}
8761 
8762 	return 0;
8763 }
8764 
8765 static bool may_access_skb(enum bpf_prog_type type)
8766 {
8767 	switch (type) {
8768 	case BPF_PROG_TYPE_SOCKET_FILTER:
8769 	case BPF_PROG_TYPE_SCHED_CLS:
8770 	case BPF_PROG_TYPE_SCHED_ACT:
8771 		return true;
8772 	default:
8773 		return false;
8774 	}
8775 }
8776 
8777 /* verify safety of LD_ABS|LD_IND instructions:
8778  * - they can only appear in the programs where ctx == skb
8779  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8780  *   preserve R6-R9, and store return value into R0
8781  *
8782  * Implicit input:
8783  *   ctx == skb == R6 == CTX
8784  *
8785  * Explicit input:
8786  *   SRC == any register
8787  *   IMM == 32-bit immediate
8788  *
8789  * Output:
8790  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8791  */
8792 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8793 {
8794 	struct bpf_reg_state *regs = cur_regs(env);
8795 	static const int ctx_reg = BPF_REG_6;
8796 	u8 mode = BPF_MODE(insn->code);
8797 	int i, err;
8798 
8799 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8800 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8801 		return -EINVAL;
8802 	}
8803 
8804 	if (!env->ops->gen_ld_abs) {
8805 		verbose(env, "bpf verifier is misconfigured\n");
8806 		return -EINVAL;
8807 	}
8808 
8809 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8810 	    BPF_SIZE(insn->code) == BPF_DW ||
8811 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8812 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8813 		return -EINVAL;
8814 	}
8815 
8816 	/* check whether implicit source operand (register R6) is readable */
8817 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8818 	if (err)
8819 		return err;
8820 
8821 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8822 	 * gen_ld_abs() may terminate the program at runtime, leading to
8823 	 * reference leak.
8824 	 */
8825 	err = check_reference_leak(env);
8826 	if (err) {
8827 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8828 		return err;
8829 	}
8830 
8831 	if (env->cur_state->active_spin_lock) {
8832 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8833 		return -EINVAL;
8834 	}
8835 
8836 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8837 		verbose(env,
8838 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8839 		return -EINVAL;
8840 	}
8841 
8842 	if (mode == BPF_IND) {
8843 		/* check explicit source operand */
8844 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8845 		if (err)
8846 			return err;
8847 	}
8848 
8849 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8850 	if (err < 0)
8851 		return err;
8852 
8853 	/* reset caller saved regs to unreadable */
8854 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8855 		mark_reg_not_init(env, regs, caller_saved[i]);
8856 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8857 	}
8858 
8859 	/* mark destination R0 register as readable, since it contains
8860 	 * the value fetched from the packet.
8861 	 * Already marked as written above.
8862 	 */
8863 	mark_reg_unknown(env, regs, BPF_REG_0);
8864 	/* ld_abs load up to 32-bit skb data. */
8865 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8866 	return 0;
8867 }
8868 
8869 static int check_return_code(struct bpf_verifier_env *env)
8870 {
8871 	struct tnum enforce_attach_type_range = tnum_unknown;
8872 	const struct bpf_prog *prog = env->prog;
8873 	struct bpf_reg_state *reg;
8874 	struct tnum range = tnum_range(0, 1);
8875 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8876 	int err;
8877 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8878 
8879 	/* LSM and struct_ops func-ptr's return type could be "void" */
8880 	if (!is_subprog &&
8881 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8882 	     prog_type == BPF_PROG_TYPE_LSM) &&
8883 	    !prog->aux->attach_func_proto->type)
8884 		return 0;
8885 
8886 	/* eBPF calling convetion is such that R0 is used
8887 	 * to return the value from eBPF program.
8888 	 * Make sure that it's readable at this time
8889 	 * of bpf_exit, which means that program wrote
8890 	 * something into it earlier
8891 	 */
8892 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8893 	if (err)
8894 		return err;
8895 
8896 	if (is_pointer_value(env, BPF_REG_0)) {
8897 		verbose(env, "R0 leaks addr as return value\n");
8898 		return -EACCES;
8899 	}
8900 
8901 	reg = cur_regs(env) + BPF_REG_0;
8902 	if (is_subprog) {
8903 		if (reg->type != SCALAR_VALUE) {
8904 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8905 				reg_type_str[reg->type]);
8906 			return -EINVAL;
8907 		}
8908 		return 0;
8909 	}
8910 
8911 	switch (prog_type) {
8912 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8913 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8914 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8915 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8916 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8917 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8918 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8919 			range = tnum_range(1, 1);
8920 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8921 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8922 			range = tnum_range(0, 3);
8923 		break;
8924 	case BPF_PROG_TYPE_CGROUP_SKB:
8925 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8926 			range = tnum_range(0, 3);
8927 			enforce_attach_type_range = tnum_range(2, 3);
8928 		}
8929 		break;
8930 	case BPF_PROG_TYPE_CGROUP_SOCK:
8931 	case BPF_PROG_TYPE_SOCK_OPS:
8932 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8933 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8934 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8935 		break;
8936 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8937 		if (!env->prog->aux->attach_btf_id)
8938 			return 0;
8939 		range = tnum_const(0);
8940 		break;
8941 	case BPF_PROG_TYPE_TRACING:
8942 		switch (env->prog->expected_attach_type) {
8943 		case BPF_TRACE_FENTRY:
8944 		case BPF_TRACE_FEXIT:
8945 			range = tnum_const(0);
8946 			break;
8947 		case BPF_TRACE_RAW_TP:
8948 		case BPF_MODIFY_RETURN:
8949 			return 0;
8950 		case BPF_TRACE_ITER:
8951 			break;
8952 		default:
8953 			return -ENOTSUPP;
8954 		}
8955 		break;
8956 	case BPF_PROG_TYPE_SK_LOOKUP:
8957 		range = tnum_range(SK_DROP, SK_PASS);
8958 		break;
8959 	case BPF_PROG_TYPE_EXT:
8960 		/* freplace program can return anything as its return value
8961 		 * depends on the to-be-replaced kernel func or bpf program.
8962 		 */
8963 	default:
8964 		return 0;
8965 	}
8966 
8967 	if (reg->type != SCALAR_VALUE) {
8968 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8969 			reg_type_str[reg->type]);
8970 		return -EINVAL;
8971 	}
8972 
8973 	if (!tnum_in(range, reg->var_off)) {
8974 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
8975 		return -EINVAL;
8976 	}
8977 
8978 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8979 	    tnum_in(enforce_attach_type_range, reg->var_off))
8980 		env->prog->enforce_expected_attach_type = 1;
8981 	return 0;
8982 }
8983 
8984 /* non-recursive DFS pseudo code
8985  * 1  procedure DFS-iterative(G,v):
8986  * 2      label v as discovered
8987  * 3      let S be a stack
8988  * 4      S.push(v)
8989  * 5      while S is not empty
8990  * 6            t <- S.pop()
8991  * 7            if t is what we're looking for:
8992  * 8                return t
8993  * 9            for all edges e in G.adjacentEdges(t) do
8994  * 10               if edge e is already labelled
8995  * 11                   continue with the next edge
8996  * 12               w <- G.adjacentVertex(t,e)
8997  * 13               if vertex w is not discovered and not explored
8998  * 14                   label e as tree-edge
8999  * 15                   label w as discovered
9000  * 16                   S.push(w)
9001  * 17                   continue at 5
9002  * 18               else if vertex w is discovered
9003  * 19                   label e as back-edge
9004  * 20               else
9005  * 21                   // vertex w is explored
9006  * 22                   label e as forward- or cross-edge
9007  * 23           label t as explored
9008  * 24           S.pop()
9009  *
9010  * convention:
9011  * 0x10 - discovered
9012  * 0x11 - discovered and fall-through edge labelled
9013  * 0x12 - discovered and fall-through and branch edges labelled
9014  * 0x20 - explored
9015  */
9016 
9017 enum {
9018 	DISCOVERED = 0x10,
9019 	EXPLORED = 0x20,
9020 	FALLTHROUGH = 1,
9021 	BRANCH = 2,
9022 };
9023 
9024 static u32 state_htab_size(struct bpf_verifier_env *env)
9025 {
9026 	return env->prog->len;
9027 }
9028 
9029 static struct bpf_verifier_state_list **explored_state(
9030 					struct bpf_verifier_env *env,
9031 					int idx)
9032 {
9033 	struct bpf_verifier_state *cur = env->cur_state;
9034 	struct bpf_func_state *state = cur->frame[cur->curframe];
9035 
9036 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9037 }
9038 
9039 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9040 {
9041 	env->insn_aux_data[idx].prune_point = true;
9042 }
9043 
9044 enum {
9045 	DONE_EXPLORING = 0,
9046 	KEEP_EXPLORING = 1,
9047 };
9048 
9049 /* t, w, e - match pseudo-code above:
9050  * t - index of current instruction
9051  * w - next instruction
9052  * e - edge
9053  */
9054 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9055 		     bool loop_ok)
9056 {
9057 	int *insn_stack = env->cfg.insn_stack;
9058 	int *insn_state = env->cfg.insn_state;
9059 
9060 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9061 		return DONE_EXPLORING;
9062 
9063 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9064 		return DONE_EXPLORING;
9065 
9066 	if (w < 0 || w >= env->prog->len) {
9067 		verbose_linfo(env, t, "%d: ", t);
9068 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9069 		return -EINVAL;
9070 	}
9071 
9072 	if (e == BRANCH)
9073 		/* mark branch target for state pruning */
9074 		init_explored_state(env, w);
9075 
9076 	if (insn_state[w] == 0) {
9077 		/* tree-edge */
9078 		insn_state[t] = DISCOVERED | e;
9079 		insn_state[w] = DISCOVERED;
9080 		if (env->cfg.cur_stack >= env->prog->len)
9081 			return -E2BIG;
9082 		insn_stack[env->cfg.cur_stack++] = w;
9083 		return KEEP_EXPLORING;
9084 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9085 		if (loop_ok && env->bpf_capable)
9086 			return DONE_EXPLORING;
9087 		verbose_linfo(env, t, "%d: ", t);
9088 		verbose_linfo(env, w, "%d: ", w);
9089 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9090 		return -EINVAL;
9091 	} else if (insn_state[w] == EXPLORED) {
9092 		/* forward- or cross-edge */
9093 		insn_state[t] = DISCOVERED | e;
9094 	} else {
9095 		verbose(env, "insn state internal bug\n");
9096 		return -EFAULT;
9097 	}
9098 	return DONE_EXPLORING;
9099 }
9100 
9101 static int visit_func_call_insn(int t, int insn_cnt,
9102 				struct bpf_insn *insns,
9103 				struct bpf_verifier_env *env,
9104 				bool visit_callee)
9105 {
9106 	int ret;
9107 
9108 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9109 	if (ret)
9110 		return ret;
9111 
9112 	if (t + 1 < insn_cnt)
9113 		init_explored_state(env, t + 1);
9114 	if (visit_callee) {
9115 		init_explored_state(env, t);
9116 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9117 				env, false);
9118 	}
9119 	return ret;
9120 }
9121 
9122 /* Visits the instruction at index t and returns one of the following:
9123  *  < 0 - an error occurred
9124  *  DONE_EXPLORING - the instruction was fully explored
9125  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9126  */
9127 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9128 {
9129 	struct bpf_insn *insns = env->prog->insnsi;
9130 	int ret;
9131 
9132 	if (bpf_pseudo_func(insns + t))
9133 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9134 
9135 	/* All non-branch instructions have a single fall-through edge. */
9136 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9137 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9138 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9139 
9140 	switch (BPF_OP(insns[t].code)) {
9141 	case BPF_EXIT:
9142 		return DONE_EXPLORING;
9143 
9144 	case BPF_CALL:
9145 		return visit_func_call_insn(t, insn_cnt, insns, env,
9146 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9147 
9148 	case BPF_JA:
9149 		if (BPF_SRC(insns[t].code) != BPF_K)
9150 			return -EINVAL;
9151 
9152 		/* unconditional jump with single edge */
9153 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9154 				true);
9155 		if (ret)
9156 			return ret;
9157 
9158 		/* unconditional jmp is not a good pruning point,
9159 		 * but it's marked, since backtracking needs
9160 		 * to record jmp history in is_state_visited().
9161 		 */
9162 		init_explored_state(env, t + insns[t].off + 1);
9163 		/* tell verifier to check for equivalent states
9164 		 * after every call and jump
9165 		 */
9166 		if (t + 1 < insn_cnt)
9167 			init_explored_state(env, t + 1);
9168 
9169 		return ret;
9170 
9171 	default:
9172 		/* conditional jump with two edges */
9173 		init_explored_state(env, t);
9174 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9175 		if (ret)
9176 			return ret;
9177 
9178 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9179 	}
9180 }
9181 
9182 /* non-recursive depth-first-search to detect loops in BPF program
9183  * loop == back-edge in directed graph
9184  */
9185 static int check_cfg(struct bpf_verifier_env *env)
9186 {
9187 	int insn_cnt = env->prog->len;
9188 	int *insn_stack, *insn_state;
9189 	int ret = 0;
9190 	int i;
9191 
9192 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9193 	if (!insn_state)
9194 		return -ENOMEM;
9195 
9196 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9197 	if (!insn_stack) {
9198 		kvfree(insn_state);
9199 		return -ENOMEM;
9200 	}
9201 
9202 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9203 	insn_stack[0] = 0; /* 0 is the first instruction */
9204 	env->cfg.cur_stack = 1;
9205 
9206 	while (env->cfg.cur_stack > 0) {
9207 		int t = insn_stack[env->cfg.cur_stack - 1];
9208 
9209 		ret = visit_insn(t, insn_cnt, env);
9210 		switch (ret) {
9211 		case DONE_EXPLORING:
9212 			insn_state[t] = EXPLORED;
9213 			env->cfg.cur_stack--;
9214 			break;
9215 		case KEEP_EXPLORING:
9216 			break;
9217 		default:
9218 			if (ret > 0) {
9219 				verbose(env, "visit_insn internal bug\n");
9220 				ret = -EFAULT;
9221 			}
9222 			goto err_free;
9223 		}
9224 	}
9225 
9226 	if (env->cfg.cur_stack < 0) {
9227 		verbose(env, "pop stack internal bug\n");
9228 		ret = -EFAULT;
9229 		goto err_free;
9230 	}
9231 
9232 	for (i = 0; i < insn_cnt; i++) {
9233 		if (insn_state[i] != EXPLORED) {
9234 			verbose(env, "unreachable insn %d\n", i);
9235 			ret = -EINVAL;
9236 			goto err_free;
9237 		}
9238 	}
9239 	ret = 0; /* cfg looks good */
9240 
9241 err_free:
9242 	kvfree(insn_state);
9243 	kvfree(insn_stack);
9244 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9245 	return ret;
9246 }
9247 
9248 static int check_abnormal_return(struct bpf_verifier_env *env)
9249 {
9250 	int i;
9251 
9252 	for (i = 1; i < env->subprog_cnt; i++) {
9253 		if (env->subprog_info[i].has_ld_abs) {
9254 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9255 			return -EINVAL;
9256 		}
9257 		if (env->subprog_info[i].has_tail_call) {
9258 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9259 			return -EINVAL;
9260 		}
9261 	}
9262 	return 0;
9263 }
9264 
9265 /* The minimum supported BTF func info size */
9266 #define MIN_BPF_FUNCINFO_SIZE	8
9267 #define MAX_FUNCINFO_REC_SIZE	252
9268 
9269 static int check_btf_func(struct bpf_verifier_env *env,
9270 			  const union bpf_attr *attr,
9271 			  union bpf_attr __user *uattr)
9272 {
9273 	const struct btf_type *type, *func_proto, *ret_type;
9274 	u32 i, nfuncs, urec_size, min_size;
9275 	u32 krec_size = sizeof(struct bpf_func_info);
9276 	struct bpf_func_info *krecord;
9277 	struct bpf_func_info_aux *info_aux = NULL;
9278 	struct bpf_prog *prog;
9279 	const struct btf *btf;
9280 	void __user *urecord;
9281 	u32 prev_offset = 0;
9282 	bool scalar_return;
9283 	int ret = -ENOMEM;
9284 
9285 	nfuncs = attr->func_info_cnt;
9286 	if (!nfuncs) {
9287 		if (check_abnormal_return(env))
9288 			return -EINVAL;
9289 		return 0;
9290 	}
9291 
9292 	if (nfuncs != env->subprog_cnt) {
9293 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9294 		return -EINVAL;
9295 	}
9296 
9297 	urec_size = attr->func_info_rec_size;
9298 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9299 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
9300 	    urec_size % sizeof(u32)) {
9301 		verbose(env, "invalid func info rec size %u\n", urec_size);
9302 		return -EINVAL;
9303 	}
9304 
9305 	prog = env->prog;
9306 	btf = prog->aux->btf;
9307 
9308 	urecord = u64_to_user_ptr(attr->func_info);
9309 	min_size = min_t(u32, krec_size, urec_size);
9310 
9311 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9312 	if (!krecord)
9313 		return -ENOMEM;
9314 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9315 	if (!info_aux)
9316 		goto err_free;
9317 
9318 	for (i = 0; i < nfuncs; i++) {
9319 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9320 		if (ret) {
9321 			if (ret == -E2BIG) {
9322 				verbose(env, "nonzero tailing record in func info");
9323 				/* set the size kernel expects so loader can zero
9324 				 * out the rest of the record.
9325 				 */
9326 				if (put_user(min_size, &uattr->func_info_rec_size))
9327 					ret = -EFAULT;
9328 			}
9329 			goto err_free;
9330 		}
9331 
9332 		if (copy_from_user(&krecord[i], urecord, min_size)) {
9333 			ret = -EFAULT;
9334 			goto err_free;
9335 		}
9336 
9337 		/* check insn_off */
9338 		ret = -EINVAL;
9339 		if (i == 0) {
9340 			if (krecord[i].insn_off) {
9341 				verbose(env,
9342 					"nonzero insn_off %u for the first func info record",
9343 					krecord[i].insn_off);
9344 				goto err_free;
9345 			}
9346 		} else if (krecord[i].insn_off <= prev_offset) {
9347 			verbose(env,
9348 				"same or smaller insn offset (%u) than previous func info record (%u)",
9349 				krecord[i].insn_off, prev_offset);
9350 			goto err_free;
9351 		}
9352 
9353 		if (env->subprog_info[i].start != krecord[i].insn_off) {
9354 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9355 			goto err_free;
9356 		}
9357 
9358 		/* check type_id */
9359 		type = btf_type_by_id(btf, krecord[i].type_id);
9360 		if (!type || !btf_type_is_func(type)) {
9361 			verbose(env, "invalid type id %d in func info",
9362 				krecord[i].type_id);
9363 			goto err_free;
9364 		}
9365 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9366 
9367 		func_proto = btf_type_by_id(btf, type->type);
9368 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9369 			/* btf_func_check() already verified it during BTF load */
9370 			goto err_free;
9371 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9372 		scalar_return =
9373 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9374 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9375 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9376 			goto err_free;
9377 		}
9378 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9379 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9380 			goto err_free;
9381 		}
9382 
9383 		prev_offset = krecord[i].insn_off;
9384 		urecord += urec_size;
9385 	}
9386 
9387 	prog->aux->func_info = krecord;
9388 	prog->aux->func_info_cnt = nfuncs;
9389 	prog->aux->func_info_aux = info_aux;
9390 	return 0;
9391 
9392 err_free:
9393 	kvfree(krecord);
9394 	kfree(info_aux);
9395 	return ret;
9396 }
9397 
9398 static void adjust_btf_func(struct bpf_verifier_env *env)
9399 {
9400 	struct bpf_prog_aux *aux = env->prog->aux;
9401 	int i;
9402 
9403 	if (!aux->func_info)
9404 		return;
9405 
9406 	for (i = 0; i < env->subprog_cnt; i++)
9407 		aux->func_info[i].insn_off = env->subprog_info[i].start;
9408 }
9409 
9410 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
9411 		sizeof(((struct bpf_line_info *)(0))->line_col))
9412 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
9413 
9414 static int check_btf_line(struct bpf_verifier_env *env,
9415 			  const union bpf_attr *attr,
9416 			  union bpf_attr __user *uattr)
9417 {
9418 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9419 	struct bpf_subprog_info *sub;
9420 	struct bpf_line_info *linfo;
9421 	struct bpf_prog *prog;
9422 	const struct btf *btf;
9423 	void __user *ulinfo;
9424 	int err;
9425 
9426 	nr_linfo = attr->line_info_cnt;
9427 	if (!nr_linfo)
9428 		return 0;
9429 
9430 	rec_size = attr->line_info_rec_size;
9431 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9432 	    rec_size > MAX_LINEINFO_REC_SIZE ||
9433 	    rec_size & (sizeof(u32) - 1))
9434 		return -EINVAL;
9435 
9436 	/* Need to zero it in case the userspace may
9437 	 * pass in a smaller bpf_line_info object.
9438 	 */
9439 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9440 			 GFP_KERNEL | __GFP_NOWARN);
9441 	if (!linfo)
9442 		return -ENOMEM;
9443 
9444 	prog = env->prog;
9445 	btf = prog->aux->btf;
9446 
9447 	s = 0;
9448 	sub = env->subprog_info;
9449 	ulinfo = u64_to_user_ptr(attr->line_info);
9450 	expected_size = sizeof(struct bpf_line_info);
9451 	ncopy = min_t(u32, expected_size, rec_size);
9452 	for (i = 0; i < nr_linfo; i++) {
9453 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9454 		if (err) {
9455 			if (err == -E2BIG) {
9456 				verbose(env, "nonzero tailing record in line_info");
9457 				if (put_user(expected_size,
9458 					     &uattr->line_info_rec_size))
9459 					err = -EFAULT;
9460 			}
9461 			goto err_free;
9462 		}
9463 
9464 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9465 			err = -EFAULT;
9466 			goto err_free;
9467 		}
9468 
9469 		/*
9470 		 * Check insn_off to ensure
9471 		 * 1) strictly increasing AND
9472 		 * 2) bounded by prog->len
9473 		 *
9474 		 * The linfo[0].insn_off == 0 check logically falls into
9475 		 * the later "missing bpf_line_info for func..." case
9476 		 * because the first linfo[0].insn_off must be the
9477 		 * first sub also and the first sub must have
9478 		 * subprog_info[0].start == 0.
9479 		 */
9480 		if ((i && linfo[i].insn_off <= prev_offset) ||
9481 		    linfo[i].insn_off >= prog->len) {
9482 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9483 				i, linfo[i].insn_off, prev_offset,
9484 				prog->len);
9485 			err = -EINVAL;
9486 			goto err_free;
9487 		}
9488 
9489 		if (!prog->insnsi[linfo[i].insn_off].code) {
9490 			verbose(env,
9491 				"Invalid insn code at line_info[%u].insn_off\n",
9492 				i);
9493 			err = -EINVAL;
9494 			goto err_free;
9495 		}
9496 
9497 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9498 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9499 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9500 			err = -EINVAL;
9501 			goto err_free;
9502 		}
9503 
9504 		if (s != env->subprog_cnt) {
9505 			if (linfo[i].insn_off == sub[s].start) {
9506 				sub[s].linfo_idx = i;
9507 				s++;
9508 			} else if (sub[s].start < linfo[i].insn_off) {
9509 				verbose(env, "missing bpf_line_info for func#%u\n", s);
9510 				err = -EINVAL;
9511 				goto err_free;
9512 			}
9513 		}
9514 
9515 		prev_offset = linfo[i].insn_off;
9516 		ulinfo += rec_size;
9517 	}
9518 
9519 	if (s != env->subprog_cnt) {
9520 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9521 			env->subprog_cnt - s, s);
9522 		err = -EINVAL;
9523 		goto err_free;
9524 	}
9525 
9526 	prog->aux->linfo = linfo;
9527 	prog->aux->nr_linfo = nr_linfo;
9528 
9529 	return 0;
9530 
9531 err_free:
9532 	kvfree(linfo);
9533 	return err;
9534 }
9535 
9536 static int check_btf_info(struct bpf_verifier_env *env,
9537 			  const union bpf_attr *attr,
9538 			  union bpf_attr __user *uattr)
9539 {
9540 	struct btf *btf;
9541 	int err;
9542 
9543 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9544 		if (check_abnormal_return(env))
9545 			return -EINVAL;
9546 		return 0;
9547 	}
9548 
9549 	btf = btf_get_by_fd(attr->prog_btf_fd);
9550 	if (IS_ERR(btf))
9551 		return PTR_ERR(btf);
9552 	if (btf_is_kernel(btf)) {
9553 		btf_put(btf);
9554 		return -EACCES;
9555 	}
9556 	env->prog->aux->btf = btf;
9557 
9558 	err = check_btf_func(env, attr, uattr);
9559 	if (err)
9560 		return err;
9561 
9562 	err = check_btf_line(env, attr, uattr);
9563 	if (err)
9564 		return err;
9565 
9566 	return 0;
9567 }
9568 
9569 /* check %cur's range satisfies %old's */
9570 static bool range_within(struct bpf_reg_state *old,
9571 			 struct bpf_reg_state *cur)
9572 {
9573 	return old->umin_value <= cur->umin_value &&
9574 	       old->umax_value >= cur->umax_value &&
9575 	       old->smin_value <= cur->smin_value &&
9576 	       old->smax_value >= cur->smax_value &&
9577 	       old->u32_min_value <= cur->u32_min_value &&
9578 	       old->u32_max_value >= cur->u32_max_value &&
9579 	       old->s32_min_value <= cur->s32_min_value &&
9580 	       old->s32_max_value >= cur->s32_max_value;
9581 }
9582 
9583 /* Maximum number of register states that can exist at once */
9584 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9585 struct idpair {
9586 	u32 old;
9587 	u32 cur;
9588 };
9589 
9590 /* If in the old state two registers had the same id, then they need to have
9591  * the same id in the new state as well.  But that id could be different from
9592  * the old state, so we need to track the mapping from old to new ids.
9593  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9594  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9595  * regs with a different old id could still have new id 9, we don't care about
9596  * that.
9597  * So we look through our idmap to see if this old id has been seen before.  If
9598  * so, we require the new id to match; otherwise, we add the id pair to the map.
9599  */
9600 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9601 {
9602 	unsigned int i;
9603 
9604 	for (i = 0; i < ID_MAP_SIZE; i++) {
9605 		if (!idmap[i].old) {
9606 			/* Reached an empty slot; haven't seen this id before */
9607 			idmap[i].old = old_id;
9608 			idmap[i].cur = cur_id;
9609 			return true;
9610 		}
9611 		if (idmap[i].old == old_id)
9612 			return idmap[i].cur == cur_id;
9613 	}
9614 	/* We ran out of idmap slots, which should be impossible */
9615 	WARN_ON_ONCE(1);
9616 	return false;
9617 }
9618 
9619 static void clean_func_state(struct bpf_verifier_env *env,
9620 			     struct bpf_func_state *st)
9621 {
9622 	enum bpf_reg_liveness live;
9623 	int i, j;
9624 
9625 	for (i = 0; i < BPF_REG_FP; i++) {
9626 		live = st->regs[i].live;
9627 		/* liveness must not touch this register anymore */
9628 		st->regs[i].live |= REG_LIVE_DONE;
9629 		if (!(live & REG_LIVE_READ))
9630 			/* since the register is unused, clear its state
9631 			 * to make further comparison simpler
9632 			 */
9633 			__mark_reg_not_init(env, &st->regs[i]);
9634 	}
9635 
9636 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9637 		live = st->stack[i].spilled_ptr.live;
9638 		/* liveness must not touch this stack slot anymore */
9639 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9640 		if (!(live & REG_LIVE_READ)) {
9641 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9642 			for (j = 0; j < BPF_REG_SIZE; j++)
9643 				st->stack[i].slot_type[j] = STACK_INVALID;
9644 		}
9645 	}
9646 }
9647 
9648 static void clean_verifier_state(struct bpf_verifier_env *env,
9649 				 struct bpf_verifier_state *st)
9650 {
9651 	int i;
9652 
9653 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9654 		/* all regs in this state in all frames were already marked */
9655 		return;
9656 
9657 	for (i = 0; i <= st->curframe; i++)
9658 		clean_func_state(env, st->frame[i]);
9659 }
9660 
9661 /* the parentage chains form a tree.
9662  * the verifier states are added to state lists at given insn and
9663  * pushed into state stack for future exploration.
9664  * when the verifier reaches bpf_exit insn some of the verifer states
9665  * stored in the state lists have their final liveness state already,
9666  * but a lot of states will get revised from liveness point of view when
9667  * the verifier explores other branches.
9668  * Example:
9669  * 1: r0 = 1
9670  * 2: if r1 == 100 goto pc+1
9671  * 3: r0 = 2
9672  * 4: exit
9673  * when the verifier reaches exit insn the register r0 in the state list of
9674  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9675  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9676  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9677  *
9678  * Since the verifier pushes the branch states as it sees them while exploring
9679  * the program the condition of walking the branch instruction for the second
9680  * time means that all states below this branch were already explored and
9681  * their final liveness markes are already propagated.
9682  * Hence when the verifier completes the search of state list in is_state_visited()
9683  * we can call this clean_live_states() function to mark all liveness states
9684  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9685  * will not be used.
9686  * This function also clears the registers and stack for states that !READ
9687  * to simplify state merging.
9688  *
9689  * Important note here that walking the same branch instruction in the callee
9690  * doesn't meant that the states are DONE. The verifier has to compare
9691  * the callsites
9692  */
9693 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9694 			      struct bpf_verifier_state *cur)
9695 {
9696 	struct bpf_verifier_state_list *sl;
9697 	int i;
9698 
9699 	sl = *explored_state(env, insn);
9700 	while (sl) {
9701 		if (sl->state.branches)
9702 			goto next;
9703 		if (sl->state.insn_idx != insn ||
9704 		    sl->state.curframe != cur->curframe)
9705 			goto next;
9706 		for (i = 0; i <= cur->curframe; i++)
9707 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9708 				goto next;
9709 		clean_verifier_state(env, &sl->state);
9710 next:
9711 		sl = sl->next;
9712 	}
9713 }
9714 
9715 /* Returns true if (rold safe implies rcur safe) */
9716 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9717 		    struct idpair *idmap)
9718 {
9719 	bool equal;
9720 
9721 	if (!(rold->live & REG_LIVE_READ))
9722 		/* explored state didn't use this */
9723 		return true;
9724 
9725 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9726 
9727 	if (rold->type == PTR_TO_STACK)
9728 		/* two stack pointers are equal only if they're pointing to
9729 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9730 		 */
9731 		return equal && rold->frameno == rcur->frameno;
9732 
9733 	if (equal)
9734 		return true;
9735 
9736 	if (rold->type == NOT_INIT)
9737 		/* explored state can't have used this */
9738 		return true;
9739 	if (rcur->type == NOT_INIT)
9740 		return false;
9741 	switch (rold->type) {
9742 	case SCALAR_VALUE:
9743 		if (rcur->type == SCALAR_VALUE) {
9744 			if (!rold->precise && !rcur->precise)
9745 				return true;
9746 			/* new val must satisfy old val knowledge */
9747 			return range_within(rold, rcur) &&
9748 			       tnum_in(rold->var_off, rcur->var_off);
9749 		} else {
9750 			/* We're trying to use a pointer in place of a scalar.
9751 			 * Even if the scalar was unbounded, this could lead to
9752 			 * pointer leaks because scalars are allowed to leak
9753 			 * while pointers are not. We could make this safe in
9754 			 * special cases if root is calling us, but it's
9755 			 * probably not worth the hassle.
9756 			 */
9757 			return false;
9758 		}
9759 	case PTR_TO_MAP_KEY:
9760 	case PTR_TO_MAP_VALUE:
9761 		/* If the new min/max/var_off satisfy the old ones and
9762 		 * everything else matches, we are OK.
9763 		 * 'id' is not compared, since it's only used for maps with
9764 		 * bpf_spin_lock inside map element and in such cases if
9765 		 * the rest of the prog is valid for one map element then
9766 		 * it's valid for all map elements regardless of the key
9767 		 * used in bpf_map_lookup()
9768 		 */
9769 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9770 		       range_within(rold, rcur) &&
9771 		       tnum_in(rold->var_off, rcur->var_off);
9772 	case PTR_TO_MAP_VALUE_OR_NULL:
9773 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9774 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9775 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9776 		 * checked, doing so could have affected others with the same
9777 		 * id, and we can't check for that because we lost the id when
9778 		 * we converted to a PTR_TO_MAP_VALUE.
9779 		 */
9780 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9781 			return false;
9782 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9783 			return false;
9784 		/* Check our ids match any regs they're supposed to */
9785 		return check_ids(rold->id, rcur->id, idmap);
9786 	case PTR_TO_PACKET_META:
9787 	case PTR_TO_PACKET:
9788 		if (rcur->type != rold->type)
9789 			return false;
9790 		/* We must have at least as much range as the old ptr
9791 		 * did, so that any accesses which were safe before are
9792 		 * still safe.  This is true even if old range < old off,
9793 		 * since someone could have accessed through (ptr - k), or
9794 		 * even done ptr -= k in a register, to get a safe access.
9795 		 */
9796 		if (rold->range > rcur->range)
9797 			return false;
9798 		/* If the offsets don't match, we can't trust our alignment;
9799 		 * nor can we be sure that we won't fall out of range.
9800 		 */
9801 		if (rold->off != rcur->off)
9802 			return false;
9803 		/* id relations must be preserved */
9804 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9805 			return false;
9806 		/* new val must satisfy old val knowledge */
9807 		return range_within(rold, rcur) &&
9808 		       tnum_in(rold->var_off, rcur->var_off);
9809 	case PTR_TO_CTX:
9810 	case CONST_PTR_TO_MAP:
9811 	case PTR_TO_PACKET_END:
9812 	case PTR_TO_FLOW_KEYS:
9813 	case PTR_TO_SOCKET:
9814 	case PTR_TO_SOCKET_OR_NULL:
9815 	case PTR_TO_SOCK_COMMON:
9816 	case PTR_TO_SOCK_COMMON_OR_NULL:
9817 	case PTR_TO_TCP_SOCK:
9818 	case PTR_TO_TCP_SOCK_OR_NULL:
9819 	case PTR_TO_XDP_SOCK:
9820 		/* Only valid matches are exact, which memcmp() above
9821 		 * would have accepted
9822 		 */
9823 	default:
9824 		/* Don't know what's going on, just say it's not safe */
9825 		return false;
9826 	}
9827 
9828 	/* Shouldn't get here; if we do, say it's not safe */
9829 	WARN_ON_ONCE(1);
9830 	return false;
9831 }
9832 
9833 static bool stacksafe(struct bpf_func_state *old,
9834 		      struct bpf_func_state *cur,
9835 		      struct idpair *idmap)
9836 {
9837 	int i, spi;
9838 
9839 	/* walk slots of the explored stack and ignore any additional
9840 	 * slots in the current stack, since explored(safe) state
9841 	 * didn't use them
9842 	 */
9843 	for (i = 0; i < old->allocated_stack; i++) {
9844 		spi = i / BPF_REG_SIZE;
9845 
9846 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9847 			i += BPF_REG_SIZE - 1;
9848 			/* explored state didn't use this */
9849 			continue;
9850 		}
9851 
9852 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9853 			continue;
9854 
9855 		/* explored stack has more populated slots than current stack
9856 		 * and these slots were used
9857 		 */
9858 		if (i >= cur->allocated_stack)
9859 			return false;
9860 
9861 		/* if old state was safe with misc data in the stack
9862 		 * it will be safe with zero-initialized stack.
9863 		 * The opposite is not true
9864 		 */
9865 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9866 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9867 			continue;
9868 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9869 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9870 			/* Ex: old explored (safe) state has STACK_SPILL in
9871 			 * this stack slot, but current has STACK_MISC ->
9872 			 * this verifier states are not equivalent,
9873 			 * return false to continue verification of this path
9874 			 */
9875 			return false;
9876 		if (i % BPF_REG_SIZE)
9877 			continue;
9878 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
9879 			continue;
9880 		if (!regsafe(&old->stack[spi].spilled_ptr,
9881 			     &cur->stack[spi].spilled_ptr,
9882 			     idmap))
9883 			/* when explored and current stack slot are both storing
9884 			 * spilled registers, check that stored pointers types
9885 			 * are the same as well.
9886 			 * Ex: explored safe path could have stored
9887 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9888 			 * but current path has stored:
9889 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9890 			 * such verifier states are not equivalent.
9891 			 * return false to continue verification of this path
9892 			 */
9893 			return false;
9894 	}
9895 	return true;
9896 }
9897 
9898 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9899 {
9900 	if (old->acquired_refs != cur->acquired_refs)
9901 		return false;
9902 	return !memcmp(old->refs, cur->refs,
9903 		       sizeof(*old->refs) * old->acquired_refs);
9904 }
9905 
9906 /* compare two verifier states
9907  *
9908  * all states stored in state_list are known to be valid, since
9909  * verifier reached 'bpf_exit' instruction through them
9910  *
9911  * this function is called when verifier exploring different branches of
9912  * execution popped from the state stack. If it sees an old state that has
9913  * more strict register state and more strict stack state then this execution
9914  * branch doesn't need to be explored further, since verifier already
9915  * concluded that more strict state leads to valid finish.
9916  *
9917  * Therefore two states are equivalent if register state is more conservative
9918  * and explored stack state is more conservative than the current one.
9919  * Example:
9920  *       explored                   current
9921  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9922  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9923  *
9924  * In other words if current stack state (one being explored) has more
9925  * valid slots than old one that already passed validation, it means
9926  * the verifier can stop exploring and conclude that current state is valid too
9927  *
9928  * Similarly with registers. If explored state has register type as invalid
9929  * whereas register type in current state is meaningful, it means that
9930  * the current state will reach 'bpf_exit' instruction safely
9931  */
9932 static bool func_states_equal(struct bpf_func_state *old,
9933 			      struct bpf_func_state *cur)
9934 {
9935 	struct idpair *idmap;
9936 	bool ret = false;
9937 	int i;
9938 
9939 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9940 	/* If we failed to allocate the idmap, just say it's not safe */
9941 	if (!idmap)
9942 		return false;
9943 
9944 	for (i = 0; i < MAX_BPF_REG; i++) {
9945 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9946 			goto out_free;
9947 	}
9948 
9949 	if (!stacksafe(old, cur, idmap))
9950 		goto out_free;
9951 
9952 	if (!refsafe(old, cur))
9953 		goto out_free;
9954 	ret = true;
9955 out_free:
9956 	kfree(idmap);
9957 	return ret;
9958 }
9959 
9960 static bool states_equal(struct bpf_verifier_env *env,
9961 			 struct bpf_verifier_state *old,
9962 			 struct bpf_verifier_state *cur)
9963 {
9964 	int i;
9965 
9966 	if (old->curframe != cur->curframe)
9967 		return false;
9968 
9969 	/* Verification state from speculative execution simulation
9970 	 * must never prune a non-speculative execution one.
9971 	 */
9972 	if (old->speculative && !cur->speculative)
9973 		return false;
9974 
9975 	if (old->active_spin_lock != cur->active_spin_lock)
9976 		return false;
9977 
9978 	/* for states to be equal callsites have to be the same
9979 	 * and all frame states need to be equivalent
9980 	 */
9981 	for (i = 0; i <= old->curframe; i++) {
9982 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9983 			return false;
9984 		if (!func_states_equal(old->frame[i], cur->frame[i]))
9985 			return false;
9986 	}
9987 	return true;
9988 }
9989 
9990 /* Return 0 if no propagation happened. Return negative error code if error
9991  * happened. Otherwise, return the propagated bit.
9992  */
9993 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9994 				  struct bpf_reg_state *reg,
9995 				  struct bpf_reg_state *parent_reg)
9996 {
9997 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9998 	u8 flag = reg->live & REG_LIVE_READ;
9999 	int err;
10000 
10001 	/* When comes here, read flags of PARENT_REG or REG could be any of
10002 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10003 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10004 	 */
10005 	if (parent_flag == REG_LIVE_READ64 ||
10006 	    /* Or if there is no read flag from REG. */
10007 	    !flag ||
10008 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10009 	    parent_flag == flag)
10010 		return 0;
10011 
10012 	err = mark_reg_read(env, reg, parent_reg, flag);
10013 	if (err)
10014 		return err;
10015 
10016 	return flag;
10017 }
10018 
10019 /* A write screens off any subsequent reads; but write marks come from the
10020  * straight-line code between a state and its parent.  When we arrive at an
10021  * equivalent state (jump target or such) we didn't arrive by the straight-line
10022  * code, so read marks in the state must propagate to the parent regardless
10023  * of the state's write marks. That's what 'parent == state->parent' comparison
10024  * in mark_reg_read() is for.
10025  */
10026 static int propagate_liveness(struct bpf_verifier_env *env,
10027 			      const struct bpf_verifier_state *vstate,
10028 			      struct bpf_verifier_state *vparent)
10029 {
10030 	struct bpf_reg_state *state_reg, *parent_reg;
10031 	struct bpf_func_state *state, *parent;
10032 	int i, frame, err = 0;
10033 
10034 	if (vparent->curframe != vstate->curframe) {
10035 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10036 		     vparent->curframe, vstate->curframe);
10037 		return -EFAULT;
10038 	}
10039 	/* Propagate read liveness of registers... */
10040 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10041 	for (frame = 0; frame <= vstate->curframe; frame++) {
10042 		parent = vparent->frame[frame];
10043 		state = vstate->frame[frame];
10044 		parent_reg = parent->regs;
10045 		state_reg = state->regs;
10046 		/* We don't need to worry about FP liveness, it's read-only */
10047 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10048 			err = propagate_liveness_reg(env, &state_reg[i],
10049 						     &parent_reg[i]);
10050 			if (err < 0)
10051 				return err;
10052 			if (err == REG_LIVE_READ64)
10053 				mark_insn_zext(env, &parent_reg[i]);
10054 		}
10055 
10056 		/* Propagate stack slots. */
10057 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10058 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10059 			parent_reg = &parent->stack[i].spilled_ptr;
10060 			state_reg = &state->stack[i].spilled_ptr;
10061 			err = propagate_liveness_reg(env, state_reg,
10062 						     parent_reg);
10063 			if (err < 0)
10064 				return err;
10065 		}
10066 	}
10067 	return 0;
10068 }
10069 
10070 /* find precise scalars in the previous equivalent state and
10071  * propagate them into the current state
10072  */
10073 static int propagate_precision(struct bpf_verifier_env *env,
10074 			       const struct bpf_verifier_state *old)
10075 {
10076 	struct bpf_reg_state *state_reg;
10077 	struct bpf_func_state *state;
10078 	int i, err = 0;
10079 
10080 	state = old->frame[old->curframe];
10081 	state_reg = state->regs;
10082 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10083 		if (state_reg->type != SCALAR_VALUE ||
10084 		    !state_reg->precise)
10085 			continue;
10086 		if (env->log.level & BPF_LOG_LEVEL2)
10087 			verbose(env, "propagating r%d\n", i);
10088 		err = mark_chain_precision(env, i);
10089 		if (err < 0)
10090 			return err;
10091 	}
10092 
10093 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10094 		if (state->stack[i].slot_type[0] != STACK_SPILL)
10095 			continue;
10096 		state_reg = &state->stack[i].spilled_ptr;
10097 		if (state_reg->type != SCALAR_VALUE ||
10098 		    !state_reg->precise)
10099 			continue;
10100 		if (env->log.level & BPF_LOG_LEVEL2)
10101 			verbose(env, "propagating fp%d\n",
10102 				(-i - 1) * BPF_REG_SIZE);
10103 		err = mark_chain_precision_stack(env, i);
10104 		if (err < 0)
10105 			return err;
10106 	}
10107 	return 0;
10108 }
10109 
10110 static bool states_maybe_looping(struct bpf_verifier_state *old,
10111 				 struct bpf_verifier_state *cur)
10112 {
10113 	struct bpf_func_state *fold, *fcur;
10114 	int i, fr = cur->curframe;
10115 
10116 	if (old->curframe != fr)
10117 		return false;
10118 
10119 	fold = old->frame[fr];
10120 	fcur = cur->frame[fr];
10121 	for (i = 0; i < MAX_BPF_REG; i++)
10122 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10123 			   offsetof(struct bpf_reg_state, parent)))
10124 			return false;
10125 	return true;
10126 }
10127 
10128 
10129 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10130 {
10131 	struct bpf_verifier_state_list *new_sl;
10132 	struct bpf_verifier_state_list *sl, **pprev;
10133 	struct bpf_verifier_state *cur = env->cur_state, *new;
10134 	int i, j, err, states_cnt = 0;
10135 	bool add_new_state = env->test_state_freq ? true : false;
10136 
10137 	cur->last_insn_idx = env->prev_insn_idx;
10138 	if (!env->insn_aux_data[insn_idx].prune_point)
10139 		/* this 'insn_idx' instruction wasn't marked, so we will not
10140 		 * be doing state search here
10141 		 */
10142 		return 0;
10143 
10144 	/* bpf progs typically have pruning point every 4 instructions
10145 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10146 	 * Do not add new state for future pruning if the verifier hasn't seen
10147 	 * at least 2 jumps and at least 8 instructions.
10148 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10149 	 * In tests that amounts to up to 50% reduction into total verifier
10150 	 * memory consumption and 20% verifier time speedup.
10151 	 */
10152 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10153 	    env->insn_processed - env->prev_insn_processed >= 8)
10154 		add_new_state = true;
10155 
10156 	pprev = explored_state(env, insn_idx);
10157 	sl = *pprev;
10158 
10159 	clean_live_states(env, insn_idx, cur);
10160 
10161 	while (sl) {
10162 		states_cnt++;
10163 		if (sl->state.insn_idx != insn_idx)
10164 			goto next;
10165 		if (sl->state.branches) {
10166 			if (states_maybe_looping(&sl->state, cur) &&
10167 			    states_equal(env, &sl->state, cur)) {
10168 				verbose_linfo(env, insn_idx, "; ");
10169 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10170 				return -EINVAL;
10171 			}
10172 			/* if the verifier is processing a loop, avoid adding new state
10173 			 * too often, since different loop iterations have distinct
10174 			 * states and may not help future pruning.
10175 			 * This threshold shouldn't be too low to make sure that
10176 			 * a loop with large bound will be rejected quickly.
10177 			 * The most abusive loop will be:
10178 			 * r1 += 1
10179 			 * if r1 < 1000000 goto pc-2
10180 			 * 1M insn_procssed limit / 100 == 10k peak states.
10181 			 * This threshold shouldn't be too high either, since states
10182 			 * at the end of the loop are likely to be useful in pruning.
10183 			 */
10184 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10185 			    env->insn_processed - env->prev_insn_processed < 100)
10186 				add_new_state = false;
10187 			goto miss;
10188 		}
10189 		if (states_equal(env, &sl->state, cur)) {
10190 			sl->hit_cnt++;
10191 			/* reached equivalent register/stack state,
10192 			 * prune the search.
10193 			 * Registers read by the continuation are read by us.
10194 			 * If we have any write marks in env->cur_state, they
10195 			 * will prevent corresponding reads in the continuation
10196 			 * from reaching our parent (an explored_state).  Our
10197 			 * own state will get the read marks recorded, but
10198 			 * they'll be immediately forgotten as we're pruning
10199 			 * this state and will pop a new one.
10200 			 */
10201 			err = propagate_liveness(env, &sl->state, cur);
10202 
10203 			/* if previous state reached the exit with precision and
10204 			 * current state is equivalent to it (except precsion marks)
10205 			 * the precision needs to be propagated back in
10206 			 * the current state.
10207 			 */
10208 			err = err ? : push_jmp_history(env, cur);
10209 			err = err ? : propagate_precision(env, &sl->state);
10210 			if (err)
10211 				return err;
10212 			return 1;
10213 		}
10214 miss:
10215 		/* when new state is not going to be added do not increase miss count.
10216 		 * Otherwise several loop iterations will remove the state
10217 		 * recorded earlier. The goal of these heuristics is to have
10218 		 * states from some iterations of the loop (some in the beginning
10219 		 * and some at the end) to help pruning.
10220 		 */
10221 		if (add_new_state)
10222 			sl->miss_cnt++;
10223 		/* heuristic to determine whether this state is beneficial
10224 		 * to keep checking from state equivalence point of view.
10225 		 * Higher numbers increase max_states_per_insn and verification time,
10226 		 * but do not meaningfully decrease insn_processed.
10227 		 */
10228 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10229 			/* the state is unlikely to be useful. Remove it to
10230 			 * speed up verification
10231 			 */
10232 			*pprev = sl->next;
10233 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10234 				u32 br = sl->state.branches;
10235 
10236 				WARN_ONCE(br,
10237 					  "BUG live_done but branches_to_explore %d\n",
10238 					  br);
10239 				free_verifier_state(&sl->state, false);
10240 				kfree(sl);
10241 				env->peak_states--;
10242 			} else {
10243 				/* cannot free this state, since parentage chain may
10244 				 * walk it later. Add it for free_list instead to
10245 				 * be freed at the end of verification
10246 				 */
10247 				sl->next = env->free_list;
10248 				env->free_list = sl;
10249 			}
10250 			sl = *pprev;
10251 			continue;
10252 		}
10253 next:
10254 		pprev = &sl->next;
10255 		sl = *pprev;
10256 	}
10257 
10258 	if (env->max_states_per_insn < states_cnt)
10259 		env->max_states_per_insn = states_cnt;
10260 
10261 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10262 		return push_jmp_history(env, cur);
10263 
10264 	if (!add_new_state)
10265 		return push_jmp_history(env, cur);
10266 
10267 	/* There were no equivalent states, remember the current one.
10268 	 * Technically the current state is not proven to be safe yet,
10269 	 * but it will either reach outer most bpf_exit (which means it's safe)
10270 	 * or it will be rejected. When there are no loops the verifier won't be
10271 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10272 	 * again on the way to bpf_exit.
10273 	 * When looping the sl->state.branches will be > 0 and this state
10274 	 * will not be considered for equivalence until branches == 0.
10275 	 */
10276 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10277 	if (!new_sl)
10278 		return -ENOMEM;
10279 	env->total_states++;
10280 	env->peak_states++;
10281 	env->prev_jmps_processed = env->jmps_processed;
10282 	env->prev_insn_processed = env->insn_processed;
10283 
10284 	/* add new state to the head of linked list */
10285 	new = &new_sl->state;
10286 	err = copy_verifier_state(new, cur);
10287 	if (err) {
10288 		free_verifier_state(new, false);
10289 		kfree(new_sl);
10290 		return err;
10291 	}
10292 	new->insn_idx = insn_idx;
10293 	WARN_ONCE(new->branches != 1,
10294 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10295 
10296 	cur->parent = new;
10297 	cur->first_insn_idx = insn_idx;
10298 	clear_jmp_history(cur);
10299 	new_sl->next = *explored_state(env, insn_idx);
10300 	*explored_state(env, insn_idx) = new_sl;
10301 	/* connect new state to parentage chain. Current frame needs all
10302 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
10303 	 * to the stack implicitly by JITs) so in callers' frames connect just
10304 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10305 	 * the state of the call instruction (with WRITTEN set), and r0 comes
10306 	 * from callee with its full parentage chain, anyway.
10307 	 */
10308 	/* clear write marks in current state: the writes we did are not writes
10309 	 * our child did, so they don't screen off its reads from us.
10310 	 * (There are no read marks in current state, because reads always mark
10311 	 * their parent and current state never has children yet.  Only
10312 	 * explored_states can get read marks.)
10313 	 */
10314 	for (j = 0; j <= cur->curframe; j++) {
10315 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10316 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10317 		for (i = 0; i < BPF_REG_FP; i++)
10318 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10319 	}
10320 
10321 	/* all stack frames are accessible from callee, clear them all */
10322 	for (j = 0; j <= cur->curframe; j++) {
10323 		struct bpf_func_state *frame = cur->frame[j];
10324 		struct bpf_func_state *newframe = new->frame[j];
10325 
10326 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10327 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10328 			frame->stack[i].spilled_ptr.parent =
10329 						&newframe->stack[i].spilled_ptr;
10330 		}
10331 	}
10332 	return 0;
10333 }
10334 
10335 /* Return true if it's OK to have the same insn return a different type. */
10336 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10337 {
10338 	switch (type) {
10339 	case PTR_TO_CTX:
10340 	case PTR_TO_SOCKET:
10341 	case PTR_TO_SOCKET_OR_NULL:
10342 	case PTR_TO_SOCK_COMMON:
10343 	case PTR_TO_SOCK_COMMON_OR_NULL:
10344 	case PTR_TO_TCP_SOCK:
10345 	case PTR_TO_TCP_SOCK_OR_NULL:
10346 	case PTR_TO_XDP_SOCK:
10347 	case PTR_TO_BTF_ID:
10348 	case PTR_TO_BTF_ID_OR_NULL:
10349 		return false;
10350 	default:
10351 		return true;
10352 	}
10353 }
10354 
10355 /* If an instruction was previously used with particular pointer types, then we
10356  * need to be careful to avoid cases such as the below, where it may be ok
10357  * for one branch accessing the pointer, but not ok for the other branch:
10358  *
10359  * R1 = sock_ptr
10360  * goto X;
10361  * ...
10362  * R1 = some_other_valid_ptr;
10363  * goto X;
10364  * ...
10365  * R2 = *(u32 *)(R1 + 0);
10366  */
10367 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10368 {
10369 	return src != prev && (!reg_type_mismatch_ok(src) ||
10370 			       !reg_type_mismatch_ok(prev));
10371 }
10372 
10373 static int do_check(struct bpf_verifier_env *env)
10374 {
10375 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10376 	struct bpf_verifier_state *state = env->cur_state;
10377 	struct bpf_insn *insns = env->prog->insnsi;
10378 	struct bpf_reg_state *regs;
10379 	int insn_cnt = env->prog->len;
10380 	bool do_print_state = false;
10381 	int prev_insn_idx = -1;
10382 
10383 	for (;;) {
10384 		struct bpf_insn *insn;
10385 		u8 class;
10386 		int err;
10387 
10388 		env->prev_insn_idx = prev_insn_idx;
10389 		if (env->insn_idx >= insn_cnt) {
10390 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
10391 				env->insn_idx, insn_cnt);
10392 			return -EFAULT;
10393 		}
10394 
10395 		insn = &insns[env->insn_idx];
10396 		class = BPF_CLASS(insn->code);
10397 
10398 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10399 			verbose(env,
10400 				"BPF program is too large. Processed %d insn\n",
10401 				env->insn_processed);
10402 			return -E2BIG;
10403 		}
10404 
10405 		err = is_state_visited(env, env->insn_idx);
10406 		if (err < 0)
10407 			return err;
10408 		if (err == 1) {
10409 			/* found equivalent state, can prune the search */
10410 			if (env->log.level & BPF_LOG_LEVEL) {
10411 				if (do_print_state)
10412 					verbose(env, "\nfrom %d to %d%s: safe\n",
10413 						env->prev_insn_idx, env->insn_idx,
10414 						env->cur_state->speculative ?
10415 						" (speculative execution)" : "");
10416 				else
10417 					verbose(env, "%d: safe\n", env->insn_idx);
10418 			}
10419 			goto process_bpf_exit;
10420 		}
10421 
10422 		if (signal_pending(current))
10423 			return -EAGAIN;
10424 
10425 		if (need_resched())
10426 			cond_resched();
10427 
10428 		if (env->log.level & BPF_LOG_LEVEL2 ||
10429 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10430 			if (env->log.level & BPF_LOG_LEVEL2)
10431 				verbose(env, "%d:", env->insn_idx);
10432 			else
10433 				verbose(env, "\nfrom %d to %d%s:",
10434 					env->prev_insn_idx, env->insn_idx,
10435 					env->cur_state->speculative ?
10436 					" (speculative execution)" : "");
10437 			print_verifier_state(env, state->frame[state->curframe]);
10438 			do_print_state = false;
10439 		}
10440 
10441 		if (env->log.level & BPF_LOG_LEVEL) {
10442 			const struct bpf_insn_cbs cbs = {
10443 				.cb_call	= disasm_kfunc_name,
10444 				.cb_print	= verbose,
10445 				.private_data	= env,
10446 			};
10447 
10448 			verbose_linfo(env, env->insn_idx, "; ");
10449 			verbose(env, "%d: ", env->insn_idx);
10450 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10451 		}
10452 
10453 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
10454 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10455 							   env->prev_insn_idx);
10456 			if (err)
10457 				return err;
10458 		}
10459 
10460 		regs = cur_regs(env);
10461 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10462 		prev_insn_idx = env->insn_idx;
10463 
10464 		if (class == BPF_ALU || class == BPF_ALU64) {
10465 			err = check_alu_op(env, insn);
10466 			if (err)
10467 				return err;
10468 
10469 		} else if (class == BPF_LDX) {
10470 			enum bpf_reg_type *prev_src_type, src_reg_type;
10471 
10472 			/* check for reserved fields is already done */
10473 
10474 			/* check src operand */
10475 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10476 			if (err)
10477 				return err;
10478 
10479 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10480 			if (err)
10481 				return err;
10482 
10483 			src_reg_type = regs[insn->src_reg].type;
10484 
10485 			/* check that memory (src_reg + off) is readable,
10486 			 * the state of dst_reg will be updated by this func
10487 			 */
10488 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
10489 					       insn->off, BPF_SIZE(insn->code),
10490 					       BPF_READ, insn->dst_reg, false);
10491 			if (err)
10492 				return err;
10493 
10494 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10495 
10496 			if (*prev_src_type == NOT_INIT) {
10497 				/* saw a valid insn
10498 				 * dst_reg = *(u32 *)(src_reg + off)
10499 				 * save type to validate intersecting paths
10500 				 */
10501 				*prev_src_type = src_reg_type;
10502 
10503 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10504 				/* ABuser program is trying to use the same insn
10505 				 * dst_reg = *(u32*) (src_reg + off)
10506 				 * with different pointer types:
10507 				 * src_reg == ctx in one branch and
10508 				 * src_reg == stack|map in some other branch.
10509 				 * Reject it.
10510 				 */
10511 				verbose(env, "same insn cannot be used with different pointers\n");
10512 				return -EINVAL;
10513 			}
10514 
10515 		} else if (class == BPF_STX) {
10516 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
10517 
10518 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10519 				err = check_atomic(env, env->insn_idx, insn);
10520 				if (err)
10521 					return err;
10522 				env->insn_idx++;
10523 				continue;
10524 			}
10525 
10526 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10527 				verbose(env, "BPF_STX uses reserved fields\n");
10528 				return -EINVAL;
10529 			}
10530 
10531 			/* check src1 operand */
10532 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10533 			if (err)
10534 				return err;
10535 			/* check src2 operand */
10536 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10537 			if (err)
10538 				return err;
10539 
10540 			dst_reg_type = regs[insn->dst_reg].type;
10541 
10542 			/* check that memory (dst_reg + off) is writeable */
10543 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10544 					       insn->off, BPF_SIZE(insn->code),
10545 					       BPF_WRITE, insn->src_reg, false);
10546 			if (err)
10547 				return err;
10548 
10549 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10550 
10551 			if (*prev_dst_type == NOT_INIT) {
10552 				*prev_dst_type = dst_reg_type;
10553 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10554 				verbose(env, "same insn cannot be used with different pointers\n");
10555 				return -EINVAL;
10556 			}
10557 
10558 		} else if (class == BPF_ST) {
10559 			if (BPF_MODE(insn->code) != BPF_MEM ||
10560 			    insn->src_reg != BPF_REG_0) {
10561 				verbose(env, "BPF_ST uses reserved fields\n");
10562 				return -EINVAL;
10563 			}
10564 			/* check src operand */
10565 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10566 			if (err)
10567 				return err;
10568 
10569 			if (is_ctx_reg(env, insn->dst_reg)) {
10570 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10571 					insn->dst_reg,
10572 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
10573 				return -EACCES;
10574 			}
10575 
10576 			/* check that memory (dst_reg + off) is writeable */
10577 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10578 					       insn->off, BPF_SIZE(insn->code),
10579 					       BPF_WRITE, -1, false);
10580 			if (err)
10581 				return err;
10582 
10583 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10584 			u8 opcode = BPF_OP(insn->code);
10585 
10586 			env->jmps_processed++;
10587 			if (opcode == BPF_CALL) {
10588 				if (BPF_SRC(insn->code) != BPF_K ||
10589 				    insn->off != 0 ||
10590 				    (insn->src_reg != BPF_REG_0 &&
10591 				     insn->src_reg != BPF_PSEUDO_CALL &&
10592 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
10593 				    insn->dst_reg != BPF_REG_0 ||
10594 				    class == BPF_JMP32) {
10595 					verbose(env, "BPF_CALL uses reserved fields\n");
10596 					return -EINVAL;
10597 				}
10598 
10599 				if (env->cur_state->active_spin_lock &&
10600 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10601 				     insn->imm != BPF_FUNC_spin_unlock)) {
10602 					verbose(env, "function calls are not allowed while holding a lock\n");
10603 					return -EINVAL;
10604 				}
10605 				if (insn->src_reg == BPF_PSEUDO_CALL)
10606 					err = check_func_call(env, insn, &env->insn_idx);
10607 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10608 					err = check_kfunc_call(env, insn);
10609 				else
10610 					err = check_helper_call(env, insn, &env->insn_idx);
10611 				if (err)
10612 					return err;
10613 			} else if (opcode == BPF_JA) {
10614 				if (BPF_SRC(insn->code) != BPF_K ||
10615 				    insn->imm != 0 ||
10616 				    insn->src_reg != BPF_REG_0 ||
10617 				    insn->dst_reg != BPF_REG_0 ||
10618 				    class == BPF_JMP32) {
10619 					verbose(env, "BPF_JA uses reserved fields\n");
10620 					return -EINVAL;
10621 				}
10622 
10623 				env->insn_idx += insn->off + 1;
10624 				continue;
10625 
10626 			} else if (opcode == BPF_EXIT) {
10627 				if (BPF_SRC(insn->code) != BPF_K ||
10628 				    insn->imm != 0 ||
10629 				    insn->src_reg != BPF_REG_0 ||
10630 				    insn->dst_reg != BPF_REG_0 ||
10631 				    class == BPF_JMP32) {
10632 					verbose(env, "BPF_EXIT uses reserved fields\n");
10633 					return -EINVAL;
10634 				}
10635 
10636 				if (env->cur_state->active_spin_lock) {
10637 					verbose(env, "bpf_spin_unlock is missing\n");
10638 					return -EINVAL;
10639 				}
10640 
10641 				if (state->curframe) {
10642 					/* exit from nested function */
10643 					err = prepare_func_exit(env, &env->insn_idx);
10644 					if (err)
10645 						return err;
10646 					do_print_state = true;
10647 					continue;
10648 				}
10649 
10650 				err = check_reference_leak(env);
10651 				if (err)
10652 					return err;
10653 
10654 				err = check_return_code(env);
10655 				if (err)
10656 					return err;
10657 process_bpf_exit:
10658 				update_branch_counts(env, env->cur_state);
10659 				err = pop_stack(env, &prev_insn_idx,
10660 						&env->insn_idx, pop_log);
10661 				if (err < 0) {
10662 					if (err != -ENOENT)
10663 						return err;
10664 					break;
10665 				} else {
10666 					do_print_state = true;
10667 					continue;
10668 				}
10669 			} else {
10670 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10671 				if (err)
10672 					return err;
10673 			}
10674 		} else if (class == BPF_LD) {
10675 			u8 mode = BPF_MODE(insn->code);
10676 
10677 			if (mode == BPF_ABS || mode == BPF_IND) {
10678 				err = check_ld_abs(env, insn);
10679 				if (err)
10680 					return err;
10681 
10682 			} else if (mode == BPF_IMM) {
10683 				err = check_ld_imm(env, insn);
10684 				if (err)
10685 					return err;
10686 
10687 				env->insn_idx++;
10688 				env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10689 			} else {
10690 				verbose(env, "invalid BPF_LD mode\n");
10691 				return -EINVAL;
10692 			}
10693 		} else {
10694 			verbose(env, "unknown insn class %d\n", class);
10695 			return -EINVAL;
10696 		}
10697 
10698 		env->insn_idx++;
10699 	}
10700 
10701 	return 0;
10702 }
10703 
10704 static int find_btf_percpu_datasec(struct btf *btf)
10705 {
10706 	const struct btf_type *t;
10707 	const char *tname;
10708 	int i, n;
10709 
10710 	/*
10711 	 * Both vmlinux and module each have their own ".data..percpu"
10712 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10713 	 * types to look at only module's own BTF types.
10714 	 */
10715 	n = btf_nr_types(btf);
10716 	if (btf_is_module(btf))
10717 		i = btf_nr_types(btf_vmlinux);
10718 	else
10719 		i = 1;
10720 
10721 	for(; i < n; i++) {
10722 		t = btf_type_by_id(btf, i);
10723 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10724 			continue;
10725 
10726 		tname = btf_name_by_offset(btf, t->name_off);
10727 		if (!strcmp(tname, ".data..percpu"))
10728 			return i;
10729 	}
10730 
10731 	return -ENOENT;
10732 }
10733 
10734 /* replace pseudo btf_id with kernel symbol address */
10735 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10736 			       struct bpf_insn *insn,
10737 			       struct bpf_insn_aux_data *aux)
10738 {
10739 	const struct btf_var_secinfo *vsi;
10740 	const struct btf_type *datasec;
10741 	struct btf_mod_pair *btf_mod;
10742 	const struct btf_type *t;
10743 	const char *sym_name;
10744 	bool percpu = false;
10745 	u32 type, id = insn->imm;
10746 	struct btf *btf;
10747 	s32 datasec_id;
10748 	u64 addr;
10749 	int i, btf_fd, err;
10750 
10751 	btf_fd = insn[1].imm;
10752 	if (btf_fd) {
10753 		btf = btf_get_by_fd(btf_fd);
10754 		if (IS_ERR(btf)) {
10755 			verbose(env, "invalid module BTF object FD specified.\n");
10756 			return -EINVAL;
10757 		}
10758 	} else {
10759 		if (!btf_vmlinux) {
10760 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10761 			return -EINVAL;
10762 		}
10763 		btf = btf_vmlinux;
10764 		btf_get(btf);
10765 	}
10766 
10767 	t = btf_type_by_id(btf, id);
10768 	if (!t) {
10769 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10770 		err = -ENOENT;
10771 		goto err_put;
10772 	}
10773 
10774 	if (!btf_type_is_var(t)) {
10775 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10776 		err = -EINVAL;
10777 		goto err_put;
10778 	}
10779 
10780 	sym_name = btf_name_by_offset(btf, t->name_off);
10781 	addr = kallsyms_lookup_name(sym_name);
10782 	if (!addr) {
10783 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10784 			sym_name);
10785 		err = -ENOENT;
10786 		goto err_put;
10787 	}
10788 
10789 	datasec_id = find_btf_percpu_datasec(btf);
10790 	if (datasec_id > 0) {
10791 		datasec = btf_type_by_id(btf, datasec_id);
10792 		for_each_vsi(i, datasec, vsi) {
10793 			if (vsi->type == id) {
10794 				percpu = true;
10795 				break;
10796 			}
10797 		}
10798 	}
10799 
10800 	insn[0].imm = (u32)addr;
10801 	insn[1].imm = addr >> 32;
10802 
10803 	type = t->type;
10804 	t = btf_type_skip_modifiers(btf, type, NULL);
10805 	if (percpu) {
10806 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10807 		aux->btf_var.btf = btf;
10808 		aux->btf_var.btf_id = type;
10809 	} else if (!btf_type_is_struct(t)) {
10810 		const struct btf_type *ret;
10811 		const char *tname;
10812 		u32 tsize;
10813 
10814 		/* resolve the type size of ksym. */
10815 		ret = btf_resolve_size(btf, t, &tsize);
10816 		if (IS_ERR(ret)) {
10817 			tname = btf_name_by_offset(btf, t->name_off);
10818 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10819 				tname, PTR_ERR(ret));
10820 			err = -EINVAL;
10821 			goto err_put;
10822 		}
10823 		aux->btf_var.reg_type = PTR_TO_MEM;
10824 		aux->btf_var.mem_size = tsize;
10825 	} else {
10826 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10827 		aux->btf_var.btf = btf;
10828 		aux->btf_var.btf_id = type;
10829 	}
10830 
10831 	/* check whether we recorded this BTF (and maybe module) already */
10832 	for (i = 0; i < env->used_btf_cnt; i++) {
10833 		if (env->used_btfs[i].btf == btf) {
10834 			btf_put(btf);
10835 			return 0;
10836 		}
10837 	}
10838 
10839 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
10840 		err = -E2BIG;
10841 		goto err_put;
10842 	}
10843 
10844 	btf_mod = &env->used_btfs[env->used_btf_cnt];
10845 	btf_mod->btf = btf;
10846 	btf_mod->module = NULL;
10847 
10848 	/* if we reference variables from kernel module, bump its refcount */
10849 	if (btf_is_module(btf)) {
10850 		btf_mod->module = btf_try_get_module(btf);
10851 		if (!btf_mod->module) {
10852 			err = -ENXIO;
10853 			goto err_put;
10854 		}
10855 	}
10856 
10857 	env->used_btf_cnt++;
10858 
10859 	return 0;
10860 err_put:
10861 	btf_put(btf);
10862 	return err;
10863 }
10864 
10865 static int check_map_prealloc(struct bpf_map *map)
10866 {
10867 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10868 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10869 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10870 		!(map->map_flags & BPF_F_NO_PREALLOC);
10871 }
10872 
10873 static bool is_tracing_prog_type(enum bpf_prog_type type)
10874 {
10875 	switch (type) {
10876 	case BPF_PROG_TYPE_KPROBE:
10877 	case BPF_PROG_TYPE_TRACEPOINT:
10878 	case BPF_PROG_TYPE_PERF_EVENT:
10879 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10880 		return true;
10881 	default:
10882 		return false;
10883 	}
10884 }
10885 
10886 static bool is_preallocated_map(struct bpf_map *map)
10887 {
10888 	if (!check_map_prealloc(map))
10889 		return false;
10890 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10891 		return false;
10892 	return true;
10893 }
10894 
10895 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10896 					struct bpf_map *map,
10897 					struct bpf_prog *prog)
10898 
10899 {
10900 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10901 	/*
10902 	 * Validate that trace type programs use preallocated hash maps.
10903 	 *
10904 	 * For programs attached to PERF events this is mandatory as the
10905 	 * perf NMI can hit any arbitrary code sequence.
10906 	 *
10907 	 * All other trace types using preallocated hash maps are unsafe as
10908 	 * well because tracepoint or kprobes can be inside locked regions
10909 	 * of the memory allocator or at a place where a recursion into the
10910 	 * memory allocator would see inconsistent state.
10911 	 *
10912 	 * On RT enabled kernels run-time allocation of all trace type
10913 	 * programs is strictly prohibited due to lock type constraints. On
10914 	 * !RT kernels it is allowed for backwards compatibility reasons for
10915 	 * now, but warnings are emitted so developers are made aware of
10916 	 * the unsafety and can fix their programs before this is enforced.
10917 	 */
10918 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10919 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10920 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10921 			return -EINVAL;
10922 		}
10923 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10924 			verbose(env, "trace type programs can only use preallocated hash map\n");
10925 			return -EINVAL;
10926 		}
10927 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10928 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10929 	}
10930 
10931 	if (map_value_has_spin_lock(map)) {
10932 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10933 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10934 			return -EINVAL;
10935 		}
10936 
10937 		if (is_tracing_prog_type(prog_type)) {
10938 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10939 			return -EINVAL;
10940 		}
10941 
10942 		if (prog->aux->sleepable) {
10943 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10944 			return -EINVAL;
10945 		}
10946 	}
10947 
10948 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10949 	    !bpf_offload_prog_map_match(prog, map)) {
10950 		verbose(env, "offload device mismatch between prog and map\n");
10951 		return -EINVAL;
10952 	}
10953 
10954 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10955 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10956 		return -EINVAL;
10957 	}
10958 
10959 	if (prog->aux->sleepable)
10960 		switch (map->map_type) {
10961 		case BPF_MAP_TYPE_HASH:
10962 		case BPF_MAP_TYPE_LRU_HASH:
10963 		case BPF_MAP_TYPE_ARRAY:
10964 		case BPF_MAP_TYPE_PERCPU_HASH:
10965 		case BPF_MAP_TYPE_PERCPU_ARRAY:
10966 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10967 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10968 		case BPF_MAP_TYPE_HASH_OF_MAPS:
10969 			if (!is_preallocated_map(map)) {
10970 				verbose(env,
10971 					"Sleepable programs can only use preallocated maps\n");
10972 				return -EINVAL;
10973 			}
10974 			break;
10975 		case BPF_MAP_TYPE_RINGBUF:
10976 			break;
10977 		default:
10978 			verbose(env,
10979 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
10980 			return -EINVAL;
10981 		}
10982 
10983 	return 0;
10984 }
10985 
10986 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10987 {
10988 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10989 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10990 }
10991 
10992 /* find and rewrite pseudo imm in ld_imm64 instructions:
10993  *
10994  * 1. if it accesses map FD, replace it with actual map pointer.
10995  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10996  *
10997  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10998  */
10999 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11000 {
11001 	struct bpf_insn *insn = env->prog->insnsi;
11002 	int insn_cnt = env->prog->len;
11003 	int i, j, err;
11004 
11005 	err = bpf_prog_calc_tag(env->prog);
11006 	if (err)
11007 		return err;
11008 
11009 	for (i = 0; i < insn_cnt; i++, insn++) {
11010 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11011 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11012 			verbose(env, "BPF_LDX uses reserved fields\n");
11013 			return -EINVAL;
11014 		}
11015 
11016 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11017 			struct bpf_insn_aux_data *aux;
11018 			struct bpf_map *map;
11019 			struct fd f;
11020 			u64 addr;
11021 
11022 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11023 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11024 			    insn[1].off != 0) {
11025 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11026 				return -EINVAL;
11027 			}
11028 
11029 			if (insn[0].src_reg == 0)
11030 				/* valid generic load 64-bit imm */
11031 				goto next_insn;
11032 
11033 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11034 				aux = &env->insn_aux_data[i];
11035 				err = check_pseudo_btf_id(env, insn, aux);
11036 				if (err)
11037 					return err;
11038 				goto next_insn;
11039 			}
11040 
11041 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11042 				aux = &env->insn_aux_data[i];
11043 				aux->ptr_type = PTR_TO_FUNC;
11044 				goto next_insn;
11045 			}
11046 
11047 			/* In final convert_pseudo_ld_imm64() step, this is
11048 			 * converted into regular 64-bit imm load insn.
11049 			 */
11050 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11051 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11052 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11053 			     insn[1].imm != 0)) {
11054 				verbose(env,
11055 					"unrecognized bpf_ld_imm64 insn\n");
11056 				return -EINVAL;
11057 			}
11058 
11059 			f = fdget(insn[0].imm);
11060 			map = __bpf_map_get(f);
11061 			if (IS_ERR(map)) {
11062 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11063 					insn[0].imm);
11064 				return PTR_ERR(map);
11065 			}
11066 
11067 			err = check_map_prog_compatibility(env, map, env->prog);
11068 			if (err) {
11069 				fdput(f);
11070 				return err;
11071 			}
11072 
11073 			aux = &env->insn_aux_data[i];
11074 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11075 				addr = (unsigned long)map;
11076 			} else {
11077 				u32 off = insn[1].imm;
11078 
11079 				if (off >= BPF_MAX_VAR_OFF) {
11080 					verbose(env, "direct value offset of %u is not allowed\n", off);
11081 					fdput(f);
11082 					return -EINVAL;
11083 				}
11084 
11085 				if (!map->ops->map_direct_value_addr) {
11086 					verbose(env, "no direct value access support for this map type\n");
11087 					fdput(f);
11088 					return -EINVAL;
11089 				}
11090 
11091 				err = map->ops->map_direct_value_addr(map, &addr, off);
11092 				if (err) {
11093 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11094 						map->value_size, off);
11095 					fdput(f);
11096 					return err;
11097 				}
11098 
11099 				aux->map_off = off;
11100 				addr += off;
11101 			}
11102 
11103 			insn[0].imm = (u32)addr;
11104 			insn[1].imm = addr >> 32;
11105 
11106 			/* check whether we recorded this map already */
11107 			for (j = 0; j < env->used_map_cnt; j++) {
11108 				if (env->used_maps[j] == map) {
11109 					aux->map_index = j;
11110 					fdput(f);
11111 					goto next_insn;
11112 				}
11113 			}
11114 
11115 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11116 				fdput(f);
11117 				return -E2BIG;
11118 			}
11119 
11120 			/* hold the map. If the program is rejected by verifier,
11121 			 * the map will be released by release_maps() or it
11122 			 * will be used by the valid program until it's unloaded
11123 			 * and all maps are released in free_used_maps()
11124 			 */
11125 			bpf_map_inc(map);
11126 
11127 			aux->map_index = env->used_map_cnt;
11128 			env->used_maps[env->used_map_cnt++] = map;
11129 
11130 			if (bpf_map_is_cgroup_storage(map) &&
11131 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11132 				verbose(env, "only one cgroup storage of each type is allowed\n");
11133 				fdput(f);
11134 				return -EBUSY;
11135 			}
11136 
11137 			fdput(f);
11138 next_insn:
11139 			insn++;
11140 			i++;
11141 			continue;
11142 		}
11143 
11144 		/* Basic sanity check before we invest more work here. */
11145 		if (!bpf_opcode_in_insntable(insn->code)) {
11146 			verbose(env, "unknown opcode %02x\n", insn->code);
11147 			return -EINVAL;
11148 		}
11149 	}
11150 
11151 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11152 	 * 'struct bpf_map *' into a register instead of user map_fd.
11153 	 * These pointers will be used later by verifier to validate map access.
11154 	 */
11155 	return 0;
11156 }
11157 
11158 /* drop refcnt of maps used by the rejected program */
11159 static void release_maps(struct bpf_verifier_env *env)
11160 {
11161 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11162 			     env->used_map_cnt);
11163 }
11164 
11165 /* drop refcnt of maps used by the rejected program */
11166 static void release_btfs(struct bpf_verifier_env *env)
11167 {
11168 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11169 			     env->used_btf_cnt);
11170 }
11171 
11172 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11173 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11174 {
11175 	struct bpf_insn *insn = env->prog->insnsi;
11176 	int insn_cnt = env->prog->len;
11177 	int i;
11178 
11179 	for (i = 0; i < insn_cnt; i++, insn++) {
11180 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11181 			continue;
11182 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11183 			continue;
11184 		insn->src_reg = 0;
11185 	}
11186 }
11187 
11188 /* single env->prog->insni[off] instruction was replaced with the range
11189  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11190  * [0, off) and [off, end) to new locations, so the patched range stays zero
11191  */
11192 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11193 				struct bpf_prog *new_prog, u32 off, u32 cnt)
11194 {
11195 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
11196 	struct bpf_insn *insn = new_prog->insnsi;
11197 	u32 prog_len;
11198 	int i;
11199 
11200 	/* aux info at OFF always needs adjustment, no matter fast path
11201 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11202 	 * original insn at old prog.
11203 	 */
11204 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11205 
11206 	if (cnt == 1)
11207 		return 0;
11208 	prog_len = new_prog->len;
11209 	new_data = vzalloc(array_size(prog_len,
11210 				      sizeof(struct bpf_insn_aux_data)));
11211 	if (!new_data)
11212 		return -ENOMEM;
11213 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11214 	memcpy(new_data + off + cnt - 1, old_data + off,
11215 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11216 	for (i = off; i < off + cnt - 1; i++) {
11217 		new_data[i].seen = env->pass_cnt;
11218 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11219 	}
11220 	env->insn_aux_data = new_data;
11221 	vfree(old_data);
11222 	return 0;
11223 }
11224 
11225 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11226 {
11227 	int i;
11228 
11229 	if (len == 1)
11230 		return;
11231 	/* NOTE: fake 'exit' subprog should be updated as well. */
11232 	for (i = 0; i <= env->subprog_cnt; i++) {
11233 		if (env->subprog_info[i].start <= off)
11234 			continue;
11235 		env->subprog_info[i].start += len - 1;
11236 	}
11237 }
11238 
11239 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
11240 {
11241 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11242 	int i, sz = prog->aux->size_poke_tab;
11243 	struct bpf_jit_poke_descriptor *desc;
11244 
11245 	for (i = 0; i < sz; i++) {
11246 		desc = &tab[i];
11247 		desc->insn_idx += len - 1;
11248 	}
11249 }
11250 
11251 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11252 					    const struct bpf_insn *patch, u32 len)
11253 {
11254 	struct bpf_prog *new_prog;
11255 
11256 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11257 	if (IS_ERR(new_prog)) {
11258 		if (PTR_ERR(new_prog) == -ERANGE)
11259 			verbose(env,
11260 				"insn %d cannot be patched due to 16-bit range\n",
11261 				env->insn_aux_data[off].orig_idx);
11262 		return NULL;
11263 	}
11264 	if (adjust_insn_aux_data(env, new_prog, off, len))
11265 		return NULL;
11266 	adjust_subprog_starts(env, off, len);
11267 	adjust_poke_descs(new_prog, len);
11268 	return new_prog;
11269 }
11270 
11271 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11272 					      u32 off, u32 cnt)
11273 {
11274 	int i, j;
11275 
11276 	/* find first prog starting at or after off (first to remove) */
11277 	for (i = 0; i < env->subprog_cnt; i++)
11278 		if (env->subprog_info[i].start >= off)
11279 			break;
11280 	/* find first prog starting at or after off + cnt (first to stay) */
11281 	for (j = i; j < env->subprog_cnt; j++)
11282 		if (env->subprog_info[j].start >= off + cnt)
11283 			break;
11284 	/* if j doesn't start exactly at off + cnt, we are just removing
11285 	 * the front of previous prog
11286 	 */
11287 	if (env->subprog_info[j].start != off + cnt)
11288 		j--;
11289 
11290 	if (j > i) {
11291 		struct bpf_prog_aux *aux = env->prog->aux;
11292 		int move;
11293 
11294 		/* move fake 'exit' subprog as well */
11295 		move = env->subprog_cnt + 1 - j;
11296 
11297 		memmove(env->subprog_info + i,
11298 			env->subprog_info + j,
11299 			sizeof(*env->subprog_info) * move);
11300 		env->subprog_cnt -= j - i;
11301 
11302 		/* remove func_info */
11303 		if (aux->func_info) {
11304 			move = aux->func_info_cnt - j;
11305 
11306 			memmove(aux->func_info + i,
11307 				aux->func_info + j,
11308 				sizeof(*aux->func_info) * move);
11309 			aux->func_info_cnt -= j - i;
11310 			/* func_info->insn_off is set after all code rewrites,
11311 			 * in adjust_btf_func() - no need to adjust
11312 			 */
11313 		}
11314 	} else {
11315 		/* convert i from "first prog to remove" to "first to adjust" */
11316 		if (env->subprog_info[i].start == off)
11317 			i++;
11318 	}
11319 
11320 	/* update fake 'exit' subprog as well */
11321 	for (; i <= env->subprog_cnt; i++)
11322 		env->subprog_info[i].start -= cnt;
11323 
11324 	return 0;
11325 }
11326 
11327 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11328 				      u32 cnt)
11329 {
11330 	struct bpf_prog *prog = env->prog;
11331 	u32 i, l_off, l_cnt, nr_linfo;
11332 	struct bpf_line_info *linfo;
11333 
11334 	nr_linfo = prog->aux->nr_linfo;
11335 	if (!nr_linfo)
11336 		return 0;
11337 
11338 	linfo = prog->aux->linfo;
11339 
11340 	/* find first line info to remove, count lines to be removed */
11341 	for (i = 0; i < nr_linfo; i++)
11342 		if (linfo[i].insn_off >= off)
11343 			break;
11344 
11345 	l_off = i;
11346 	l_cnt = 0;
11347 	for (; i < nr_linfo; i++)
11348 		if (linfo[i].insn_off < off + cnt)
11349 			l_cnt++;
11350 		else
11351 			break;
11352 
11353 	/* First live insn doesn't match first live linfo, it needs to "inherit"
11354 	 * last removed linfo.  prog is already modified, so prog->len == off
11355 	 * means no live instructions after (tail of the program was removed).
11356 	 */
11357 	if (prog->len != off && l_cnt &&
11358 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11359 		l_cnt--;
11360 		linfo[--i].insn_off = off + cnt;
11361 	}
11362 
11363 	/* remove the line info which refer to the removed instructions */
11364 	if (l_cnt) {
11365 		memmove(linfo + l_off, linfo + i,
11366 			sizeof(*linfo) * (nr_linfo - i));
11367 
11368 		prog->aux->nr_linfo -= l_cnt;
11369 		nr_linfo = prog->aux->nr_linfo;
11370 	}
11371 
11372 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
11373 	for (i = l_off; i < nr_linfo; i++)
11374 		linfo[i].insn_off -= cnt;
11375 
11376 	/* fix up all subprogs (incl. 'exit') which start >= off */
11377 	for (i = 0; i <= env->subprog_cnt; i++)
11378 		if (env->subprog_info[i].linfo_idx > l_off) {
11379 			/* program may have started in the removed region but
11380 			 * may not be fully removed
11381 			 */
11382 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11383 				env->subprog_info[i].linfo_idx -= l_cnt;
11384 			else
11385 				env->subprog_info[i].linfo_idx = l_off;
11386 		}
11387 
11388 	return 0;
11389 }
11390 
11391 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11392 {
11393 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11394 	unsigned int orig_prog_len = env->prog->len;
11395 	int err;
11396 
11397 	if (bpf_prog_is_dev_bound(env->prog->aux))
11398 		bpf_prog_offload_remove_insns(env, off, cnt);
11399 
11400 	err = bpf_remove_insns(env->prog, off, cnt);
11401 	if (err)
11402 		return err;
11403 
11404 	err = adjust_subprog_starts_after_remove(env, off, cnt);
11405 	if (err)
11406 		return err;
11407 
11408 	err = bpf_adj_linfo_after_remove(env, off, cnt);
11409 	if (err)
11410 		return err;
11411 
11412 	memmove(aux_data + off,	aux_data + off + cnt,
11413 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
11414 
11415 	return 0;
11416 }
11417 
11418 /* The verifier does more data flow analysis than llvm and will not
11419  * explore branches that are dead at run time. Malicious programs can
11420  * have dead code too. Therefore replace all dead at-run-time code
11421  * with 'ja -1'.
11422  *
11423  * Just nops are not optimal, e.g. if they would sit at the end of the
11424  * program and through another bug we would manage to jump there, then
11425  * we'd execute beyond program memory otherwise. Returning exception
11426  * code also wouldn't work since we can have subprogs where the dead
11427  * code could be located.
11428  */
11429 static void sanitize_dead_code(struct bpf_verifier_env *env)
11430 {
11431 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11432 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11433 	struct bpf_insn *insn = env->prog->insnsi;
11434 	const int insn_cnt = env->prog->len;
11435 	int i;
11436 
11437 	for (i = 0; i < insn_cnt; i++) {
11438 		if (aux_data[i].seen)
11439 			continue;
11440 		memcpy(insn + i, &trap, sizeof(trap));
11441 	}
11442 }
11443 
11444 static bool insn_is_cond_jump(u8 code)
11445 {
11446 	u8 op;
11447 
11448 	if (BPF_CLASS(code) == BPF_JMP32)
11449 		return true;
11450 
11451 	if (BPF_CLASS(code) != BPF_JMP)
11452 		return false;
11453 
11454 	op = BPF_OP(code);
11455 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11456 }
11457 
11458 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11459 {
11460 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11461 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11462 	struct bpf_insn *insn = env->prog->insnsi;
11463 	const int insn_cnt = env->prog->len;
11464 	int i;
11465 
11466 	for (i = 0; i < insn_cnt; i++, insn++) {
11467 		if (!insn_is_cond_jump(insn->code))
11468 			continue;
11469 
11470 		if (!aux_data[i + 1].seen)
11471 			ja.off = insn->off;
11472 		else if (!aux_data[i + 1 + insn->off].seen)
11473 			ja.off = 0;
11474 		else
11475 			continue;
11476 
11477 		if (bpf_prog_is_dev_bound(env->prog->aux))
11478 			bpf_prog_offload_replace_insn(env, i, &ja);
11479 
11480 		memcpy(insn, &ja, sizeof(ja));
11481 	}
11482 }
11483 
11484 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11485 {
11486 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11487 	int insn_cnt = env->prog->len;
11488 	int i, err;
11489 
11490 	for (i = 0; i < insn_cnt; i++) {
11491 		int j;
11492 
11493 		j = 0;
11494 		while (i + j < insn_cnt && !aux_data[i + j].seen)
11495 			j++;
11496 		if (!j)
11497 			continue;
11498 
11499 		err = verifier_remove_insns(env, i, j);
11500 		if (err)
11501 			return err;
11502 		insn_cnt = env->prog->len;
11503 	}
11504 
11505 	return 0;
11506 }
11507 
11508 static int opt_remove_nops(struct bpf_verifier_env *env)
11509 {
11510 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11511 	struct bpf_insn *insn = env->prog->insnsi;
11512 	int insn_cnt = env->prog->len;
11513 	int i, err;
11514 
11515 	for (i = 0; i < insn_cnt; i++) {
11516 		if (memcmp(&insn[i], &ja, sizeof(ja)))
11517 			continue;
11518 
11519 		err = verifier_remove_insns(env, i, 1);
11520 		if (err)
11521 			return err;
11522 		insn_cnt--;
11523 		i--;
11524 	}
11525 
11526 	return 0;
11527 }
11528 
11529 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11530 					 const union bpf_attr *attr)
11531 {
11532 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11533 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
11534 	int i, patch_len, delta = 0, len = env->prog->len;
11535 	struct bpf_insn *insns = env->prog->insnsi;
11536 	struct bpf_prog *new_prog;
11537 	bool rnd_hi32;
11538 
11539 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11540 	zext_patch[1] = BPF_ZEXT_REG(0);
11541 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11542 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11543 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11544 	for (i = 0; i < len; i++) {
11545 		int adj_idx = i + delta;
11546 		struct bpf_insn insn;
11547 		int load_reg;
11548 
11549 		insn = insns[adj_idx];
11550 		load_reg = insn_def_regno(&insn);
11551 		if (!aux[adj_idx].zext_dst) {
11552 			u8 code, class;
11553 			u32 imm_rnd;
11554 
11555 			if (!rnd_hi32)
11556 				continue;
11557 
11558 			code = insn.code;
11559 			class = BPF_CLASS(code);
11560 			if (load_reg == -1)
11561 				continue;
11562 
11563 			/* NOTE: arg "reg" (the fourth one) is only used for
11564 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
11565 			 *       here.
11566 			 */
11567 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
11568 				if (class == BPF_LD &&
11569 				    BPF_MODE(code) == BPF_IMM)
11570 					i++;
11571 				continue;
11572 			}
11573 
11574 			/* ctx load could be transformed into wider load. */
11575 			if (class == BPF_LDX &&
11576 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
11577 				continue;
11578 
11579 			imm_rnd = get_random_int();
11580 			rnd_hi32_patch[0] = insn;
11581 			rnd_hi32_patch[1].imm = imm_rnd;
11582 			rnd_hi32_patch[3].dst_reg = load_reg;
11583 			patch = rnd_hi32_patch;
11584 			patch_len = 4;
11585 			goto apply_patch_buffer;
11586 		}
11587 
11588 		/* Add in an zero-extend instruction if a) the JIT has requested
11589 		 * it or b) it's a CMPXCHG.
11590 		 *
11591 		 * The latter is because: BPF_CMPXCHG always loads a value into
11592 		 * R0, therefore always zero-extends. However some archs'
11593 		 * equivalent instruction only does this load when the
11594 		 * comparison is successful. This detail of CMPXCHG is
11595 		 * orthogonal to the general zero-extension behaviour of the
11596 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
11597 		 */
11598 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
11599 			continue;
11600 
11601 		if (WARN_ON(load_reg == -1)) {
11602 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11603 			return -EFAULT;
11604 		}
11605 
11606 		zext_patch[0] = insn;
11607 		zext_patch[1].dst_reg = load_reg;
11608 		zext_patch[1].src_reg = load_reg;
11609 		patch = zext_patch;
11610 		patch_len = 2;
11611 apply_patch_buffer:
11612 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11613 		if (!new_prog)
11614 			return -ENOMEM;
11615 		env->prog = new_prog;
11616 		insns = new_prog->insnsi;
11617 		aux = env->insn_aux_data;
11618 		delta += patch_len - 1;
11619 	}
11620 
11621 	return 0;
11622 }
11623 
11624 /* convert load instructions that access fields of a context type into a
11625  * sequence of instructions that access fields of the underlying structure:
11626  *     struct __sk_buff    -> struct sk_buff
11627  *     struct bpf_sock_ops -> struct sock
11628  */
11629 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11630 {
11631 	const struct bpf_verifier_ops *ops = env->ops;
11632 	int i, cnt, size, ctx_field_size, delta = 0;
11633 	const int insn_cnt = env->prog->len;
11634 	struct bpf_insn insn_buf[16], *insn;
11635 	u32 target_size, size_default, off;
11636 	struct bpf_prog *new_prog;
11637 	enum bpf_access_type type;
11638 	bool is_narrower_load;
11639 
11640 	if (ops->gen_prologue || env->seen_direct_write) {
11641 		if (!ops->gen_prologue) {
11642 			verbose(env, "bpf verifier is misconfigured\n");
11643 			return -EINVAL;
11644 		}
11645 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11646 					env->prog);
11647 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11648 			verbose(env, "bpf verifier is misconfigured\n");
11649 			return -EINVAL;
11650 		} else if (cnt) {
11651 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11652 			if (!new_prog)
11653 				return -ENOMEM;
11654 
11655 			env->prog = new_prog;
11656 			delta += cnt - 1;
11657 		}
11658 	}
11659 
11660 	if (bpf_prog_is_dev_bound(env->prog->aux))
11661 		return 0;
11662 
11663 	insn = env->prog->insnsi + delta;
11664 
11665 	for (i = 0; i < insn_cnt; i++, insn++) {
11666 		bpf_convert_ctx_access_t convert_ctx_access;
11667 
11668 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11669 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11670 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11671 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11672 			type = BPF_READ;
11673 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11674 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11675 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11676 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11677 			type = BPF_WRITE;
11678 		else
11679 			continue;
11680 
11681 		if (type == BPF_WRITE &&
11682 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
11683 			struct bpf_insn patch[] = {
11684 				/* Sanitize suspicious stack slot with zero.
11685 				 * There are no memory dependencies for this store,
11686 				 * since it's only using frame pointer and immediate
11687 				 * constant of zero
11688 				 */
11689 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11690 					   env->insn_aux_data[i + delta].sanitize_stack_off,
11691 					   0),
11692 				/* the original STX instruction will immediately
11693 				 * overwrite the same stack slot with appropriate value
11694 				 */
11695 				*insn,
11696 			};
11697 
11698 			cnt = ARRAY_SIZE(patch);
11699 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11700 			if (!new_prog)
11701 				return -ENOMEM;
11702 
11703 			delta    += cnt - 1;
11704 			env->prog = new_prog;
11705 			insn      = new_prog->insnsi + i + delta;
11706 			continue;
11707 		}
11708 
11709 		switch (env->insn_aux_data[i + delta].ptr_type) {
11710 		case PTR_TO_CTX:
11711 			if (!ops->convert_ctx_access)
11712 				continue;
11713 			convert_ctx_access = ops->convert_ctx_access;
11714 			break;
11715 		case PTR_TO_SOCKET:
11716 		case PTR_TO_SOCK_COMMON:
11717 			convert_ctx_access = bpf_sock_convert_ctx_access;
11718 			break;
11719 		case PTR_TO_TCP_SOCK:
11720 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11721 			break;
11722 		case PTR_TO_XDP_SOCK:
11723 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11724 			break;
11725 		case PTR_TO_BTF_ID:
11726 			if (type == BPF_READ) {
11727 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11728 					BPF_SIZE((insn)->code);
11729 				env->prog->aux->num_exentries++;
11730 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11731 				verbose(env, "Writes through BTF pointers are not allowed\n");
11732 				return -EINVAL;
11733 			}
11734 			continue;
11735 		default:
11736 			continue;
11737 		}
11738 
11739 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11740 		size = BPF_LDST_BYTES(insn);
11741 
11742 		/* If the read access is a narrower load of the field,
11743 		 * convert to a 4/8-byte load, to minimum program type specific
11744 		 * convert_ctx_access changes. If conversion is successful,
11745 		 * we will apply proper mask to the result.
11746 		 */
11747 		is_narrower_load = size < ctx_field_size;
11748 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11749 		off = insn->off;
11750 		if (is_narrower_load) {
11751 			u8 size_code;
11752 
11753 			if (type == BPF_WRITE) {
11754 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11755 				return -EINVAL;
11756 			}
11757 
11758 			size_code = BPF_H;
11759 			if (ctx_field_size == 4)
11760 				size_code = BPF_W;
11761 			else if (ctx_field_size == 8)
11762 				size_code = BPF_DW;
11763 
11764 			insn->off = off & ~(size_default - 1);
11765 			insn->code = BPF_LDX | BPF_MEM | size_code;
11766 		}
11767 
11768 		target_size = 0;
11769 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11770 					 &target_size);
11771 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11772 		    (ctx_field_size && !target_size)) {
11773 			verbose(env, "bpf verifier is misconfigured\n");
11774 			return -EINVAL;
11775 		}
11776 
11777 		if (is_narrower_load && size < target_size) {
11778 			u8 shift = bpf_ctx_narrow_access_offset(
11779 				off, size, size_default) * 8;
11780 			if (ctx_field_size <= 4) {
11781 				if (shift)
11782 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11783 									insn->dst_reg,
11784 									shift);
11785 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11786 								(1 << size * 8) - 1);
11787 			} else {
11788 				if (shift)
11789 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11790 									insn->dst_reg,
11791 									shift);
11792 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11793 								(1ULL << size * 8) - 1);
11794 			}
11795 		}
11796 
11797 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11798 		if (!new_prog)
11799 			return -ENOMEM;
11800 
11801 		delta += cnt - 1;
11802 
11803 		/* keep walking new program and skip insns we just inserted */
11804 		env->prog = new_prog;
11805 		insn      = new_prog->insnsi + i + delta;
11806 	}
11807 
11808 	return 0;
11809 }
11810 
11811 static int jit_subprogs(struct bpf_verifier_env *env)
11812 {
11813 	struct bpf_prog *prog = env->prog, **func, *tmp;
11814 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11815 	struct bpf_map *map_ptr;
11816 	struct bpf_insn *insn;
11817 	void *old_bpf_func;
11818 	int err, num_exentries;
11819 
11820 	if (env->subprog_cnt <= 1)
11821 		return 0;
11822 
11823 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11824 		if (bpf_pseudo_func(insn)) {
11825 			env->insn_aux_data[i].call_imm = insn->imm;
11826 			/* subprog is encoded in insn[1].imm */
11827 			continue;
11828 		}
11829 
11830 		if (!bpf_pseudo_call(insn))
11831 			continue;
11832 		/* Upon error here we cannot fall back to interpreter but
11833 		 * need a hard reject of the program. Thus -EFAULT is
11834 		 * propagated in any case.
11835 		 */
11836 		subprog = find_subprog(env, i + insn->imm + 1);
11837 		if (subprog < 0) {
11838 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11839 				  i + insn->imm + 1);
11840 			return -EFAULT;
11841 		}
11842 		/* temporarily remember subprog id inside insn instead of
11843 		 * aux_data, since next loop will split up all insns into funcs
11844 		 */
11845 		insn->off = subprog;
11846 		/* remember original imm in case JIT fails and fallback
11847 		 * to interpreter will be needed
11848 		 */
11849 		env->insn_aux_data[i].call_imm = insn->imm;
11850 		/* point imm to __bpf_call_base+1 from JITs point of view */
11851 		insn->imm = 1;
11852 	}
11853 
11854 	err = bpf_prog_alloc_jited_linfo(prog);
11855 	if (err)
11856 		goto out_undo_insn;
11857 
11858 	err = -ENOMEM;
11859 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11860 	if (!func)
11861 		goto out_undo_insn;
11862 
11863 	for (i = 0; i < env->subprog_cnt; i++) {
11864 		subprog_start = subprog_end;
11865 		subprog_end = env->subprog_info[i + 1].start;
11866 
11867 		len = subprog_end - subprog_start;
11868 		/* BPF_PROG_RUN doesn't call subprogs directly,
11869 		 * hence main prog stats include the runtime of subprogs.
11870 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11871 		 * func[i]->stats will never be accessed and stays NULL
11872 		 */
11873 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11874 		if (!func[i])
11875 			goto out_free;
11876 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11877 		       len * sizeof(struct bpf_insn));
11878 		func[i]->type = prog->type;
11879 		func[i]->len = len;
11880 		if (bpf_prog_calc_tag(func[i]))
11881 			goto out_free;
11882 		func[i]->is_func = 1;
11883 		func[i]->aux->func_idx = i;
11884 		/* the btf and func_info will be freed only at prog->aux */
11885 		func[i]->aux->btf = prog->aux->btf;
11886 		func[i]->aux->func_info = prog->aux->func_info;
11887 
11888 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11889 			u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11890 			int ret;
11891 
11892 			if (!(insn_idx >= subprog_start &&
11893 			      insn_idx <= subprog_end))
11894 				continue;
11895 
11896 			ret = bpf_jit_add_poke_descriptor(func[i],
11897 							  &prog->aux->poke_tab[j]);
11898 			if (ret < 0) {
11899 				verbose(env, "adding tail call poke descriptor failed\n");
11900 				goto out_free;
11901 			}
11902 
11903 			func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11904 
11905 			map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11906 			ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11907 			if (ret < 0) {
11908 				verbose(env, "tracking tail call prog failed\n");
11909 				goto out_free;
11910 			}
11911 		}
11912 
11913 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
11914 		 * Long term would need debug info to populate names
11915 		 */
11916 		func[i]->aux->name[0] = 'F';
11917 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11918 		func[i]->jit_requested = 1;
11919 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
11920 		func[i]->aux->linfo = prog->aux->linfo;
11921 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11922 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11923 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11924 		num_exentries = 0;
11925 		insn = func[i]->insnsi;
11926 		for (j = 0; j < func[i]->len; j++, insn++) {
11927 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11928 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11929 				num_exentries++;
11930 		}
11931 		func[i]->aux->num_exentries = num_exentries;
11932 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11933 		func[i] = bpf_int_jit_compile(func[i]);
11934 		if (!func[i]->jited) {
11935 			err = -ENOTSUPP;
11936 			goto out_free;
11937 		}
11938 		cond_resched();
11939 	}
11940 
11941 	/* Untrack main program's aux structs so that during map_poke_run()
11942 	 * we will not stumble upon the unfilled poke descriptors; each
11943 	 * of the main program's poke descs got distributed across subprogs
11944 	 * and got tracked onto map, so we are sure that none of them will
11945 	 * be missed after the operation below
11946 	 */
11947 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11948 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11949 
11950 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11951 	}
11952 
11953 	/* at this point all bpf functions were successfully JITed
11954 	 * now populate all bpf_calls with correct addresses and
11955 	 * run last pass of JIT
11956 	 */
11957 	for (i = 0; i < env->subprog_cnt; i++) {
11958 		insn = func[i]->insnsi;
11959 		for (j = 0; j < func[i]->len; j++, insn++) {
11960 			if (bpf_pseudo_func(insn)) {
11961 				subprog = insn[1].imm;
11962 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
11963 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
11964 				continue;
11965 			}
11966 			if (!bpf_pseudo_call(insn))
11967 				continue;
11968 			subprog = insn->off;
11969 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11970 				    __bpf_call_base;
11971 		}
11972 
11973 		/* we use the aux data to keep a list of the start addresses
11974 		 * of the JITed images for each function in the program
11975 		 *
11976 		 * for some architectures, such as powerpc64, the imm field
11977 		 * might not be large enough to hold the offset of the start
11978 		 * address of the callee's JITed image from __bpf_call_base
11979 		 *
11980 		 * in such cases, we can lookup the start address of a callee
11981 		 * by using its subprog id, available from the off field of
11982 		 * the call instruction, as an index for this list
11983 		 */
11984 		func[i]->aux->func = func;
11985 		func[i]->aux->func_cnt = env->subprog_cnt;
11986 	}
11987 	for (i = 0; i < env->subprog_cnt; i++) {
11988 		old_bpf_func = func[i]->bpf_func;
11989 		tmp = bpf_int_jit_compile(func[i]);
11990 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11991 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11992 			err = -ENOTSUPP;
11993 			goto out_free;
11994 		}
11995 		cond_resched();
11996 	}
11997 
11998 	/* finally lock prog and jit images for all functions and
11999 	 * populate kallsysm
12000 	 */
12001 	for (i = 0; i < env->subprog_cnt; i++) {
12002 		bpf_prog_lock_ro(func[i]);
12003 		bpf_prog_kallsyms_add(func[i]);
12004 	}
12005 
12006 	/* Last step: make now unused interpreter insns from main
12007 	 * prog consistent for later dump requests, so they can
12008 	 * later look the same as if they were interpreted only.
12009 	 */
12010 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12011 		if (bpf_pseudo_func(insn)) {
12012 			insn[0].imm = env->insn_aux_data[i].call_imm;
12013 			insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12014 			continue;
12015 		}
12016 		if (!bpf_pseudo_call(insn))
12017 			continue;
12018 		insn->off = env->insn_aux_data[i].call_imm;
12019 		subprog = find_subprog(env, i + insn->off + 1);
12020 		insn->imm = subprog;
12021 	}
12022 
12023 	prog->jited = 1;
12024 	prog->bpf_func = func[0]->bpf_func;
12025 	prog->aux->func = func;
12026 	prog->aux->func_cnt = env->subprog_cnt;
12027 	bpf_prog_jit_attempt_done(prog);
12028 	return 0;
12029 out_free:
12030 	for (i = 0; i < env->subprog_cnt; i++) {
12031 		if (!func[i])
12032 			continue;
12033 
12034 		for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12035 			map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12036 			map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12037 		}
12038 		bpf_jit_free(func[i]);
12039 	}
12040 	kfree(func);
12041 out_undo_insn:
12042 	/* cleanup main prog to be interpreted */
12043 	prog->jit_requested = 0;
12044 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12045 		if (!bpf_pseudo_call(insn))
12046 			continue;
12047 		insn->off = 0;
12048 		insn->imm = env->insn_aux_data[i].call_imm;
12049 	}
12050 	bpf_prog_jit_attempt_done(prog);
12051 	return err;
12052 }
12053 
12054 static int fixup_call_args(struct bpf_verifier_env *env)
12055 {
12056 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12057 	struct bpf_prog *prog = env->prog;
12058 	struct bpf_insn *insn = prog->insnsi;
12059 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12060 	int i, depth;
12061 #endif
12062 	int err = 0;
12063 
12064 	if (env->prog->jit_requested &&
12065 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12066 		err = jit_subprogs(env);
12067 		if (err == 0)
12068 			return 0;
12069 		if (err == -EFAULT)
12070 			return err;
12071 	}
12072 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12073 	if (has_kfunc_call) {
12074 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12075 		return -EINVAL;
12076 	}
12077 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12078 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12079 		 * have to be rejected, since interpreter doesn't support them yet.
12080 		 */
12081 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12082 		return -EINVAL;
12083 	}
12084 	for (i = 0; i < prog->len; i++, insn++) {
12085 		if (bpf_pseudo_func(insn)) {
12086 			/* When JIT fails the progs with callback calls
12087 			 * have to be rejected, since interpreter doesn't support them yet.
12088 			 */
12089 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12090 			return -EINVAL;
12091 		}
12092 
12093 		if (!bpf_pseudo_call(insn))
12094 			continue;
12095 		depth = get_callee_stack_depth(env, insn, i);
12096 		if (depth < 0)
12097 			return depth;
12098 		bpf_patch_call_args(insn, depth);
12099 	}
12100 	err = 0;
12101 #endif
12102 	return err;
12103 }
12104 
12105 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12106 			    struct bpf_insn *insn)
12107 {
12108 	const struct bpf_kfunc_desc *desc;
12109 
12110 	/* insn->imm has the btf func_id. Replace it with
12111 	 * an address (relative to __bpf_base_call).
12112 	 */
12113 	desc = find_kfunc_desc(env->prog, insn->imm);
12114 	if (!desc) {
12115 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12116 			insn->imm);
12117 		return -EFAULT;
12118 	}
12119 
12120 	insn->imm = desc->imm;
12121 
12122 	return 0;
12123 }
12124 
12125 /* Do various post-verification rewrites in a single program pass.
12126  * These rewrites simplify JIT and interpreter implementations.
12127  */
12128 static int do_misc_fixups(struct bpf_verifier_env *env)
12129 {
12130 	struct bpf_prog *prog = env->prog;
12131 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12132 	struct bpf_insn *insn = prog->insnsi;
12133 	const struct bpf_func_proto *fn;
12134 	const int insn_cnt = prog->len;
12135 	const struct bpf_map_ops *ops;
12136 	struct bpf_insn_aux_data *aux;
12137 	struct bpf_insn insn_buf[16];
12138 	struct bpf_prog *new_prog;
12139 	struct bpf_map *map_ptr;
12140 	int i, ret, cnt, delta = 0;
12141 
12142 	for (i = 0; i < insn_cnt; i++, insn++) {
12143 		/* Make divide-by-zero exceptions impossible. */
12144 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12145 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12146 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12147 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12148 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12149 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12150 			struct bpf_insn *patchlet;
12151 			struct bpf_insn chk_and_div[] = {
12152 				/* [R,W]x div 0 -> 0 */
12153 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12154 					     BPF_JNE | BPF_K, insn->src_reg,
12155 					     0, 2, 0),
12156 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12157 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12158 				*insn,
12159 			};
12160 			struct bpf_insn chk_and_mod[] = {
12161 				/* [R,W]x mod 0 -> [R,W]x */
12162 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12163 					     BPF_JEQ | BPF_K, insn->src_reg,
12164 					     0, 1 + (is64 ? 0 : 1), 0),
12165 				*insn,
12166 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12167 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12168 			};
12169 
12170 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12171 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12172 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12173 
12174 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12175 			if (!new_prog)
12176 				return -ENOMEM;
12177 
12178 			delta    += cnt - 1;
12179 			env->prog = prog = new_prog;
12180 			insn      = new_prog->insnsi + i + delta;
12181 			continue;
12182 		}
12183 
12184 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12185 		if (BPF_CLASS(insn->code) == BPF_LD &&
12186 		    (BPF_MODE(insn->code) == BPF_ABS ||
12187 		     BPF_MODE(insn->code) == BPF_IND)) {
12188 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12189 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12190 				verbose(env, "bpf verifier is misconfigured\n");
12191 				return -EINVAL;
12192 			}
12193 
12194 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12195 			if (!new_prog)
12196 				return -ENOMEM;
12197 
12198 			delta    += cnt - 1;
12199 			env->prog = prog = new_prog;
12200 			insn      = new_prog->insnsi + i + delta;
12201 			continue;
12202 		}
12203 
12204 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12205 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12206 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12207 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12208 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12209 			struct bpf_insn *patch = &insn_buf[0];
12210 			bool issrc, isneg;
12211 			u32 off_reg;
12212 
12213 			aux = &env->insn_aux_data[i + delta];
12214 			if (!aux->alu_state ||
12215 			    aux->alu_state == BPF_ALU_NON_POINTER)
12216 				continue;
12217 
12218 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12219 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12220 				BPF_ALU_SANITIZE_SRC;
12221 
12222 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12223 			if (isneg)
12224 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12225 			*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12226 			*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12227 			*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12228 			*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12229 			*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12230 			if (issrc) {
12231 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
12232 							 off_reg);
12233 				insn->src_reg = BPF_REG_AX;
12234 			} else {
12235 				*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
12236 							 BPF_REG_AX);
12237 			}
12238 			if (isneg)
12239 				insn->code = insn->code == code_add ?
12240 					     code_sub : code_add;
12241 			*patch++ = *insn;
12242 			if (issrc && isneg)
12243 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12244 			cnt = patch - insn_buf;
12245 
12246 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12247 			if (!new_prog)
12248 				return -ENOMEM;
12249 
12250 			delta    += cnt - 1;
12251 			env->prog = prog = new_prog;
12252 			insn      = new_prog->insnsi + i + delta;
12253 			continue;
12254 		}
12255 
12256 		if (insn->code != (BPF_JMP | BPF_CALL))
12257 			continue;
12258 		if (insn->src_reg == BPF_PSEUDO_CALL)
12259 			continue;
12260 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12261 			ret = fixup_kfunc_call(env, insn);
12262 			if (ret)
12263 				return ret;
12264 			continue;
12265 		}
12266 
12267 		if (insn->imm == BPF_FUNC_get_route_realm)
12268 			prog->dst_needed = 1;
12269 		if (insn->imm == BPF_FUNC_get_prandom_u32)
12270 			bpf_user_rnd_init_once();
12271 		if (insn->imm == BPF_FUNC_override_return)
12272 			prog->kprobe_override = 1;
12273 		if (insn->imm == BPF_FUNC_tail_call) {
12274 			/* If we tail call into other programs, we
12275 			 * cannot make any assumptions since they can
12276 			 * be replaced dynamically during runtime in
12277 			 * the program array.
12278 			 */
12279 			prog->cb_access = 1;
12280 			if (!allow_tail_call_in_subprogs(env))
12281 				prog->aux->stack_depth = MAX_BPF_STACK;
12282 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12283 
12284 			/* mark bpf_tail_call as different opcode to avoid
12285 			 * conditional branch in the interpeter for every normal
12286 			 * call and to prevent accidental JITing by JIT compiler
12287 			 * that doesn't support bpf_tail_call yet
12288 			 */
12289 			insn->imm = 0;
12290 			insn->code = BPF_JMP | BPF_TAIL_CALL;
12291 
12292 			aux = &env->insn_aux_data[i + delta];
12293 			if (env->bpf_capable && !expect_blinding &&
12294 			    prog->jit_requested &&
12295 			    !bpf_map_key_poisoned(aux) &&
12296 			    !bpf_map_ptr_poisoned(aux) &&
12297 			    !bpf_map_ptr_unpriv(aux)) {
12298 				struct bpf_jit_poke_descriptor desc = {
12299 					.reason = BPF_POKE_REASON_TAIL_CALL,
12300 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12301 					.tail_call.key = bpf_map_key_immediate(aux),
12302 					.insn_idx = i + delta,
12303 				};
12304 
12305 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
12306 				if (ret < 0) {
12307 					verbose(env, "adding tail call poke descriptor failed\n");
12308 					return ret;
12309 				}
12310 
12311 				insn->imm = ret + 1;
12312 				continue;
12313 			}
12314 
12315 			if (!bpf_map_ptr_unpriv(aux))
12316 				continue;
12317 
12318 			/* instead of changing every JIT dealing with tail_call
12319 			 * emit two extra insns:
12320 			 * if (index >= max_entries) goto out;
12321 			 * index &= array->index_mask;
12322 			 * to avoid out-of-bounds cpu speculation
12323 			 */
12324 			if (bpf_map_ptr_poisoned(aux)) {
12325 				verbose(env, "tail_call abusing map_ptr\n");
12326 				return -EINVAL;
12327 			}
12328 
12329 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12330 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12331 						  map_ptr->max_entries, 2);
12332 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12333 						    container_of(map_ptr,
12334 								 struct bpf_array,
12335 								 map)->index_mask);
12336 			insn_buf[2] = *insn;
12337 			cnt = 3;
12338 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12339 			if (!new_prog)
12340 				return -ENOMEM;
12341 
12342 			delta    += cnt - 1;
12343 			env->prog = prog = new_prog;
12344 			insn      = new_prog->insnsi + i + delta;
12345 			continue;
12346 		}
12347 
12348 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12349 		 * and other inlining handlers are currently limited to 64 bit
12350 		 * only.
12351 		 */
12352 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
12353 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
12354 		     insn->imm == BPF_FUNC_map_update_elem ||
12355 		     insn->imm == BPF_FUNC_map_delete_elem ||
12356 		     insn->imm == BPF_FUNC_map_push_elem   ||
12357 		     insn->imm == BPF_FUNC_map_pop_elem    ||
12358 		     insn->imm == BPF_FUNC_map_peek_elem   ||
12359 		     insn->imm == BPF_FUNC_redirect_map)) {
12360 			aux = &env->insn_aux_data[i + delta];
12361 			if (bpf_map_ptr_poisoned(aux))
12362 				goto patch_call_imm;
12363 
12364 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12365 			ops = map_ptr->ops;
12366 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
12367 			    ops->map_gen_lookup) {
12368 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12369 				if (cnt == -EOPNOTSUPP)
12370 					goto patch_map_ops_generic;
12371 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12372 					verbose(env, "bpf verifier is misconfigured\n");
12373 					return -EINVAL;
12374 				}
12375 
12376 				new_prog = bpf_patch_insn_data(env, i + delta,
12377 							       insn_buf, cnt);
12378 				if (!new_prog)
12379 					return -ENOMEM;
12380 
12381 				delta    += cnt - 1;
12382 				env->prog = prog = new_prog;
12383 				insn      = new_prog->insnsi + i + delta;
12384 				continue;
12385 			}
12386 
12387 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12388 				     (void *(*)(struct bpf_map *map, void *key))NULL));
12389 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12390 				     (int (*)(struct bpf_map *map, void *key))NULL));
12391 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12392 				     (int (*)(struct bpf_map *map, void *key, void *value,
12393 					      u64 flags))NULL));
12394 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12395 				     (int (*)(struct bpf_map *map, void *value,
12396 					      u64 flags))NULL));
12397 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12398 				     (int (*)(struct bpf_map *map, void *value))NULL));
12399 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12400 				     (int (*)(struct bpf_map *map, void *value))NULL));
12401 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
12402 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12403 
12404 patch_map_ops_generic:
12405 			switch (insn->imm) {
12406 			case BPF_FUNC_map_lookup_elem:
12407 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12408 					    __bpf_call_base;
12409 				continue;
12410 			case BPF_FUNC_map_update_elem:
12411 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12412 					    __bpf_call_base;
12413 				continue;
12414 			case BPF_FUNC_map_delete_elem:
12415 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12416 					    __bpf_call_base;
12417 				continue;
12418 			case BPF_FUNC_map_push_elem:
12419 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12420 					    __bpf_call_base;
12421 				continue;
12422 			case BPF_FUNC_map_pop_elem:
12423 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12424 					    __bpf_call_base;
12425 				continue;
12426 			case BPF_FUNC_map_peek_elem:
12427 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12428 					    __bpf_call_base;
12429 				continue;
12430 			case BPF_FUNC_redirect_map:
12431 				insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12432 					    __bpf_call_base;
12433 				continue;
12434 			}
12435 
12436 			goto patch_call_imm;
12437 		}
12438 
12439 		/* Implement bpf_jiffies64 inline. */
12440 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
12441 		    insn->imm == BPF_FUNC_jiffies64) {
12442 			struct bpf_insn ld_jiffies_addr[2] = {
12443 				BPF_LD_IMM64(BPF_REG_0,
12444 					     (unsigned long)&jiffies),
12445 			};
12446 
12447 			insn_buf[0] = ld_jiffies_addr[0];
12448 			insn_buf[1] = ld_jiffies_addr[1];
12449 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12450 						  BPF_REG_0, 0);
12451 			cnt = 3;
12452 
12453 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12454 						       cnt);
12455 			if (!new_prog)
12456 				return -ENOMEM;
12457 
12458 			delta    += cnt - 1;
12459 			env->prog = prog = new_prog;
12460 			insn      = new_prog->insnsi + i + delta;
12461 			continue;
12462 		}
12463 
12464 patch_call_imm:
12465 		fn = env->ops->get_func_proto(insn->imm, env->prog);
12466 		/* all functions that have prototype and verifier allowed
12467 		 * programs to call them, must be real in-kernel functions
12468 		 */
12469 		if (!fn->func) {
12470 			verbose(env,
12471 				"kernel subsystem misconfigured func %s#%d\n",
12472 				func_id_name(insn->imm), insn->imm);
12473 			return -EFAULT;
12474 		}
12475 		insn->imm = fn->func - __bpf_call_base;
12476 	}
12477 
12478 	/* Since poke tab is now finalized, publish aux to tracker. */
12479 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12480 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12481 		if (!map_ptr->ops->map_poke_track ||
12482 		    !map_ptr->ops->map_poke_untrack ||
12483 		    !map_ptr->ops->map_poke_run) {
12484 			verbose(env, "bpf verifier is misconfigured\n");
12485 			return -EINVAL;
12486 		}
12487 
12488 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12489 		if (ret < 0) {
12490 			verbose(env, "tracking tail call prog failed\n");
12491 			return ret;
12492 		}
12493 	}
12494 
12495 	sort_kfunc_descs_by_imm(env->prog);
12496 
12497 	return 0;
12498 }
12499 
12500 static void free_states(struct bpf_verifier_env *env)
12501 {
12502 	struct bpf_verifier_state_list *sl, *sln;
12503 	int i;
12504 
12505 	sl = env->free_list;
12506 	while (sl) {
12507 		sln = sl->next;
12508 		free_verifier_state(&sl->state, false);
12509 		kfree(sl);
12510 		sl = sln;
12511 	}
12512 	env->free_list = NULL;
12513 
12514 	if (!env->explored_states)
12515 		return;
12516 
12517 	for (i = 0; i < state_htab_size(env); i++) {
12518 		sl = env->explored_states[i];
12519 
12520 		while (sl) {
12521 			sln = sl->next;
12522 			free_verifier_state(&sl->state, false);
12523 			kfree(sl);
12524 			sl = sln;
12525 		}
12526 		env->explored_states[i] = NULL;
12527 	}
12528 }
12529 
12530 /* The verifier is using insn_aux_data[] to store temporary data during
12531  * verification and to store information for passes that run after the
12532  * verification like dead code sanitization. do_check_common() for subprogram N
12533  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12534  * temporary data after do_check_common() finds that subprogram N cannot be
12535  * verified independently. pass_cnt counts the number of times
12536  * do_check_common() was run and insn->aux->seen tells the pass number
12537  * insn_aux_data was touched. These variables are compared to clear temporary
12538  * data from failed pass. For testing and experiments do_check_common() can be
12539  * run multiple times even when prior attempt to verify is unsuccessful.
12540  */
12541 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12542 {
12543 	struct bpf_insn *insn = env->prog->insnsi;
12544 	struct bpf_insn_aux_data *aux;
12545 	int i, class;
12546 
12547 	for (i = 0; i < env->prog->len; i++) {
12548 		class = BPF_CLASS(insn[i].code);
12549 		if (class != BPF_LDX && class != BPF_STX)
12550 			continue;
12551 		aux = &env->insn_aux_data[i];
12552 		if (aux->seen != env->pass_cnt)
12553 			continue;
12554 		memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12555 	}
12556 }
12557 
12558 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12559 {
12560 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12561 	struct bpf_verifier_state *state;
12562 	struct bpf_reg_state *regs;
12563 	int ret, i;
12564 
12565 	env->prev_linfo = NULL;
12566 	env->pass_cnt++;
12567 
12568 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12569 	if (!state)
12570 		return -ENOMEM;
12571 	state->curframe = 0;
12572 	state->speculative = false;
12573 	state->branches = 1;
12574 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12575 	if (!state->frame[0]) {
12576 		kfree(state);
12577 		return -ENOMEM;
12578 	}
12579 	env->cur_state = state;
12580 	init_func_state(env, state->frame[0],
12581 			BPF_MAIN_FUNC /* callsite */,
12582 			0 /* frameno */,
12583 			subprog);
12584 
12585 	regs = state->frame[state->curframe]->regs;
12586 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12587 		ret = btf_prepare_func_args(env, subprog, regs);
12588 		if (ret)
12589 			goto out;
12590 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12591 			if (regs[i].type == PTR_TO_CTX)
12592 				mark_reg_known_zero(env, regs, i);
12593 			else if (regs[i].type == SCALAR_VALUE)
12594 				mark_reg_unknown(env, regs, i);
12595 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12596 				const u32 mem_size = regs[i].mem_size;
12597 
12598 				mark_reg_known_zero(env, regs, i);
12599 				regs[i].mem_size = mem_size;
12600 				regs[i].id = ++env->id_gen;
12601 			}
12602 		}
12603 	} else {
12604 		/* 1st arg to a function */
12605 		regs[BPF_REG_1].type = PTR_TO_CTX;
12606 		mark_reg_known_zero(env, regs, BPF_REG_1);
12607 		ret = btf_check_subprog_arg_match(env, subprog, regs);
12608 		if (ret == -EFAULT)
12609 			/* unlikely verifier bug. abort.
12610 			 * ret == 0 and ret < 0 are sadly acceptable for
12611 			 * main() function due to backward compatibility.
12612 			 * Like socket filter program may be written as:
12613 			 * int bpf_prog(struct pt_regs *ctx)
12614 			 * and never dereference that ctx in the program.
12615 			 * 'struct pt_regs' is a type mismatch for socket
12616 			 * filter that should be using 'struct __sk_buff'.
12617 			 */
12618 			goto out;
12619 	}
12620 
12621 	ret = do_check(env);
12622 out:
12623 	/* check for NULL is necessary, since cur_state can be freed inside
12624 	 * do_check() under memory pressure.
12625 	 */
12626 	if (env->cur_state) {
12627 		free_verifier_state(env->cur_state, true);
12628 		env->cur_state = NULL;
12629 	}
12630 	while (!pop_stack(env, NULL, NULL, false));
12631 	if (!ret && pop_log)
12632 		bpf_vlog_reset(&env->log, 0);
12633 	free_states(env);
12634 	if (ret)
12635 		/* clean aux data in case subprog was rejected */
12636 		sanitize_insn_aux_data(env);
12637 	return ret;
12638 }
12639 
12640 /* Verify all global functions in a BPF program one by one based on their BTF.
12641  * All global functions must pass verification. Otherwise the whole program is rejected.
12642  * Consider:
12643  * int bar(int);
12644  * int foo(int f)
12645  * {
12646  *    return bar(f);
12647  * }
12648  * int bar(int b)
12649  * {
12650  *    ...
12651  * }
12652  * foo() will be verified first for R1=any_scalar_value. During verification it
12653  * will be assumed that bar() already verified successfully and call to bar()
12654  * from foo() will be checked for type match only. Later bar() will be verified
12655  * independently to check that it's safe for R1=any_scalar_value.
12656  */
12657 static int do_check_subprogs(struct bpf_verifier_env *env)
12658 {
12659 	struct bpf_prog_aux *aux = env->prog->aux;
12660 	int i, ret;
12661 
12662 	if (!aux->func_info)
12663 		return 0;
12664 
12665 	for (i = 1; i < env->subprog_cnt; i++) {
12666 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12667 			continue;
12668 		env->insn_idx = env->subprog_info[i].start;
12669 		WARN_ON_ONCE(env->insn_idx == 0);
12670 		ret = do_check_common(env, i);
12671 		if (ret) {
12672 			return ret;
12673 		} else if (env->log.level & BPF_LOG_LEVEL) {
12674 			verbose(env,
12675 				"Func#%d is safe for any args that match its prototype\n",
12676 				i);
12677 		}
12678 	}
12679 	return 0;
12680 }
12681 
12682 static int do_check_main(struct bpf_verifier_env *env)
12683 {
12684 	int ret;
12685 
12686 	env->insn_idx = 0;
12687 	ret = do_check_common(env, 0);
12688 	if (!ret)
12689 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12690 	return ret;
12691 }
12692 
12693 
12694 static void print_verification_stats(struct bpf_verifier_env *env)
12695 {
12696 	int i;
12697 
12698 	if (env->log.level & BPF_LOG_STATS) {
12699 		verbose(env, "verification time %lld usec\n",
12700 			div_u64(env->verification_time, 1000));
12701 		verbose(env, "stack depth ");
12702 		for (i = 0; i < env->subprog_cnt; i++) {
12703 			u32 depth = env->subprog_info[i].stack_depth;
12704 
12705 			verbose(env, "%d", depth);
12706 			if (i + 1 < env->subprog_cnt)
12707 				verbose(env, "+");
12708 		}
12709 		verbose(env, "\n");
12710 	}
12711 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12712 		"total_states %d peak_states %d mark_read %d\n",
12713 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12714 		env->max_states_per_insn, env->total_states,
12715 		env->peak_states, env->longest_mark_read_walk);
12716 }
12717 
12718 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12719 {
12720 	const struct btf_type *t, *func_proto;
12721 	const struct bpf_struct_ops *st_ops;
12722 	const struct btf_member *member;
12723 	struct bpf_prog *prog = env->prog;
12724 	u32 btf_id, member_idx;
12725 	const char *mname;
12726 
12727 	if (!prog->gpl_compatible) {
12728 		verbose(env, "struct ops programs must have a GPL compatible license\n");
12729 		return -EINVAL;
12730 	}
12731 
12732 	btf_id = prog->aux->attach_btf_id;
12733 	st_ops = bpf_struct_ops_find(btf_id);
12734 	if (!st_ops) {
12735 		verbose(env, "attach_btf_id %u is not a supported struct\n",
12736 			btf_id);
12737 		return -ENOTSUPP;
12738 	}
12739 
12740 	t = st_ops->type;
12741 	member_idx = prog->expected_attach_type;
12742 	if (member_idx >= btf_type_vlen(t)) {
12743 		verbose(env, "attach to invalid member idx %u of struct %s\n",
12744 			member_idx, st_ops->name);
12745 		return -EINVAL;
12746 	}
12747 
12748 	member = &btf_type_member(t)[member_idx];
12749 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12750 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12751 					       NULL);
12752 	if (!func_proto) {
12753 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12754 			mname, member_idx, st_ops->name);
12755 		return -EINVAL;
12756 	}
12757 
12758 	if (st_ops->check_member) {
12759 		int err = st_ops->check_member(t, member);
12760 
12761 		if (err) {
12762 			verbose(env, "attach to unsupported member %s of struct %s\n",
12763 				mname, st_ops->name);
12764 			return err;
12765 		}
12766 	}
12767 
12768 	prog->aux->attach_func_proto = func_proto;
12769 	prog->aux->attach_func_name = mname;
12770 	env->ops = st_ops->verifier_ops;
12771 
12772 	return 0;
12773 }
12774 #define SECURITY_PREFIX "security_"
12775 
12776 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12777 {
12778 	if (within_error_injection_list(addr) ||
12779 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12780 		return 0;
12781 
12782 	return -EINVAL;
12783 }
12784 
12785 /* list of non-sleepable functions that are otherwise on
12786  * ALLOW_ERROR_INJECTION list
12787  */
12788 BTF_SET_START(btf_non_sleepable_error_inject)
12789 /* Three functions below can be called from sleepable and non-sleepable context.
12790  * Assume non-sleepable from bpf safety point of view.
12791  */
12792 BTF_ID(func, __add_to_page_cache_locked)
12793 BTF_ID(func, should_fail_alloc_page)
12794 BTF_ID(func, should_failslab)
12795 BTF_SET_END(btf_non_sleepable_error_inject)
12796 
12797 static int check_non_sleepable_error_inject(u32 btf_id)
12798 {
12799 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12800 }
12801 
12802 int bpf_check_attach_target(struct bpf_verifier_log *log,
12803 			    const struct bpf_prog *prog,
12804 			    const struct bpf_prog *tgt_prog,
12805 			    u32 btf_id,
12806 			    struct bpf_attach_target_info *tgt_info)
12807 {
12808 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12809 	const char prefix[] = "btf_trace_";
12810 	int ret = 0, subprog = -1, i;
12811 	const struct btf_type *t;
12812 	bool conservative = true;
12813 	const char *tname;
12814 	struct btf *btf;
12815 	long addr = 0;
12816 
12817 	if (!btf_id) {
12818 		bpf_log(log, "Tracing programs must provide btf_id\n");
12819 		return -EINVAL;
12820 	}
12821 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12822 	if (!btf) {
12823 		bpf_log(log,
12824 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12825 		return -EINVAL;
12826 	}
12827 	t = btf_type_by_id(btf, btf_id);
12828 	if (!t) {
12829 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12830 		return -EINVAL;
12831 	}
12832 	tname = btf_name_by_offset(btf, t->name_off);
12833 	if (!tname) {
12834 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12835 		return -EINVAL;
12836 	}
12837 	if (tgt_prog) {
12838 		struct bpf_prog_aux *aux = tgt_prog->aux;
12839 
12840 		for (i = 0; i < aux->func_info_cnt; i++)
12841 			if (aux->func_info[i].type_id == btf_id) {
12842 				subprog = i;
12843 				break;
12844 			}
12845 		if (subprog == -1) {
12846 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12847 			return -EINVAL;
12848 		}
12849 		conservative = aux->func_info_aux[subprog].unreliable;
12850 		if (prog_extension) {
12851 			if (conservative) {
12852 				bpf_log(log,
12853 					"Cannot replace static functions\n");
12854 				return -EINVAL;
12855 			}
12856 			if (!prog->jit_requested) {
12857 				bpf_log(log,
12858 					"Extension programs should be JITed\n");
12859 				return -EINVAL;
12860 			}
12861 		}
12862 		if (!tgt_prog->jited) {
12863 			bpf_log(log, "Can attach to only JITed progs\n");
12864 			return -EINVAL;
12865 		}
12866 		if (tgt_prog->type == prog->type) {
12867 			/* Cannot fentry/fexit another fentry/fexit program.
12868 			 * Cannot attach program extension to another extension.
12869 			 * It's ok to attach fentry/fexit to extension program.
12870 			 */
12871 			bpf_log(log, "Cannot recursively attach\n");
12872 			return -EINVAL;
12873 		}
12874 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12875 		    prog_extension &&
12876 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12877 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12878 			/* Program extensions can extend all program types
12879 			 * except fentry/fexit. The reason is the following.
12880 			 * The fentry/fexit programs are used for performance
12881 			 * analysis, stats and can be attached to any program
12882 			 * type except themselves. When extension program is
12883 			 * replacing XDP function it is necessary to allow
12884 			 * performance analysis of all functions. Both original
12885 			 * XDP program and its program extension. Hence
12886 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12887 			 * allowed. If extending of fentry/fexit was allowed it
12888 			 * would be possible to create long call chain
12889 			 * fentry->extension->fentry->extension beyond
12890 			 * reasonable stack size. Hence extending fentry is not
12891 			 * allowed.
12892 			 */
12893 			bpf_log(log, "Cannot extend fentry/fexit\n");
12894 			return -EINVAL;
12895 		}
12896 	} else {
12897 		if (prog_extension) {
12898 			bpf_log(log, "Cannot replace kernel functions\n");
12899 			return -EINVAL;
12900 		}
12901 	}
12902 
12903 	switch (prog->expected_attach_type) {
12904 	case BPF_TRACE_RAW_TP:
12905 		if (tgt_prog) {
12906 			bpf_log(log,
12907 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12908 			return -EINVAL;
12909 		}
12910 		if (!btf_type_is_typedef(t)) {
12911 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12912 				btf_id);
12913 			return -EINVAL;
12914 		}
12915 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12916 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12917 				btf_id, tname);
12918 			return -EINVAL;
12919 		}
12920 		tname += sizeof(prefix) - 1;
12921 		t = btf_type_by_id(btf, t->type);
12922 		if (!btf_type_is_ptr(t))
12923 			/* should never happen in valid vmlinux build */
12924 			return -EINVAL;
12925 		t = btf_type_by_id(btf, t->type);
12926 		if (!btf_type_is_func_proto(t))
12927 			/* should never happen in valid vmlinux build */
12928 			return -EINVAL;
12929 
12930 		break;
12931 	case BPF_TRACE_ITER:
12932 		if (!btf_type_is_func(t)) {
12933 			bpf_log(log, "attach_btf_id %u is not a function\n",
12934 				btf_id);
12935 			return -EINVAL;
12936 		}
12937 		t = btf_type_by_id(btf, t->type);
12938 		if (!btf_type_is_func_proto(t))
12939 			return -EINVAL;
12940 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12941 		if (ret)
12942 			return ret;
12943 		break;
12944 	default:
12945 		if (!prog_extension)
12946 			return -EINVAL;
12947 		fallthrough;
12948 	case BPF_MODIFY_RETURN:
12949 	case BPF_LSM_MAC:
12950 	case BPF_TRACE_FENTRY:
12951 	case BPF_TRACE_FEXIT:
12952 		if (!btf_type_is_func(t)) {
12953 			bpf_log(log, "attach_btf_id %u is not a function\n",
12954 				btf_id);
12955 			return -EINVAL;
12956 		}
12957 		if (prog_extension &&
12958 		    btf_check_type_match(log, prog, btf, t))
12959 			return -EINVAL;
12960 		t = btf_type_by_id(btf, t->type);
12961 		if (!btf_type_is_func_proto(t))
12962 			return -EINVAL;
12963 
12964 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12965 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12966 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12967 			return -EINVAL;
12968 
12969 		if (tgt_prog && conservative)
12970 			t = NULL;
12971 
12972 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12973 		if (ret < 0)
12974 			return ret;
12975 
12976 		if (tgt_prog) {
12977 			if (subprog == 0)
12978 				addr = (long) tgt_prog->bpf_func;
12979 			else
12980 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12981 		} else {
12982 			addr = kallsyms_lookup_name(tname);
12983 			if (!addr) {
12984 				bpf_log(log,
12985 					"The address of function %s cannot be found\n",
12986 					tname);
12987 				return -ENOENT;
12988 			}
12989 		}
12990 
12991 		if (prog->aux->sleepable) {
12992 			ret = -EINVAL;
12993 			switch (prog->type) {
12994 			case BPF_PROG_TYPE_TRACING:
12995 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12996 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12997 				 */
12998 				if (!check_non_sleepable_error_inject(btf_id) &&
12999 				    within_error_injection_list(addr))
13000 					ret = 0;
13001 				break;
13002 			case BPF_PROG_TYPE_LSM:
13003 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13004 				 * Only some of them are sleepable.
13005 				 */
13006 				if (bpf_lsm_is_sleepable_hook(btf_id))
13007 					ret = 0;
13008 				break;
13009 			default:
13010 				break;
13011 			}
13012 			if (ret) {
13013 				bpf_log(log, "%s is not sleepable\n", tname);
13014 				return ret;
13015 			}
13016 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13017 			if (tgt_prog) {
13018 				bpf_log(log, "can't modify return codes of BPF programs\n");
13019 				return -EINVAL;
13020 			}
13021 			ret = check_attach_modify_return(addr, tname);
13022 			if (ret) {
13023 				bpf_log(log, "%s() is not modifiable\n", tname);
13024 				return ret;
13025 			}
13026 		}
13027 
13028 		break;
13029 	}
13030 	tgt_info->tgt_addr = addr;
13031 	tgt_info->tgt_name = tname;
13032 	tgt_info->tgt_type = t;
13033 	return 0;
13034 }
13035 
13036 static int check_attach_btf_id(struct bpf_verifier_env *env)
13037 {
13038 	struct bpf_prog *prog = env->prog;
13039 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13040 	struct bpf_attach_target_info tgt_info = {};
13041 	u32 btf_id = prog->aux->attach_btf_id;
13042 	struct bpf_trampoline *tr;
13043 	int ret;
13044 	u64 key;
13045 
13046 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13047 	    prog->type != BPF_PROG_TYPE_LSM) {
13048 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13049 		return -EINVAL;
13050 	}
13051 
13052 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13053 		return check_struct_ops_btf_id(env);
13054 
13055 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13056 	    prog->type != BPF_PROG_TYPE_LSM &&
13057 	    prog->type != BPF_PROG_TYPE_EXT)
13058 		return 0;
13059 
13060 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13061 	if (ret)
13062 		return ret;
13063 
13064 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13065 		/* to make freplace equivalent to their targets, they need to
13066 		 * inherit env->ops and expected_attach_type for the rest of the
13067 		 * verification
13068 		 */
13069 		env->ops = bpf_verifier_ops[tgt_prog->type];
13070 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13071 	}
13072 
13073 	/* store info about the attachment target that will be used later */
13074 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13075 	prog->aux->attach_func_name = tgt_info.tgt_name;
13076 
13077 	if (tgt_prog) {
13078 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13079 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13080 	}
13081 
13082 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13083 		prog->aux->attach_btf_trace = true;
13084 		return 0;
13085 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13086 		if (!bpf_iter_prog_supported(prog))
13087 			return -EINVAL;
13088 		return 0;
13089 	}
13090 
13091 	if (prog->type == BPF_PROG_TYPE_LSM) {
13092 		ret = bpf_lsm_verify_prog(&env->log, prog);
13093 		if (ret < 0)
13094 			return ret;
13095 	}
13096 
13097 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13098 	tr = bpf_trampoline_get(key, &tgt_info);
13099 	if (!tr)
13100 		return -ENOMEM;
13101 
13102 	prog->aux->dst_trampoline = tr;
13103 	return 0;
13104 }
13105 
13106 struct btf *bpf_get_btf_vmlinux(void)
13107 {
13108 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13109 		mutex_lock(&bpf_verifier_lock);
13110 		if (!btf_vmlinux)
13111 			btf_vmlinux = btf_parse_vmlinux();
13112 		mutex_unlock(&bpf_verifier_lock);
13113 	}
13114 	return btf_vmlinux;
13115 }
13116 
13117 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13118 	      union bpf_attr __user *uattr)
13119 {
13120 	u64 start_time = ktime_get_ns();
13121 	struct bpf_verifier_env *env;
13122 	struct bpf_verifier_log *log;
13123 	int i, len, ret = -EINVAL;
13124 	bool is_priv;
13125 
13126 	/* no program is valid */
13127 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13128 		return -EINVAL;
13129 
13130 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13131 	 * allocate/free it every time bpf_check() is called
13132 	 */
13133 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13134 	if (!env)
13135 		return -ENOMEM;
13136 	log = &env->log;
13137 
13138 	len = (*prog)->len;
13139 	env->insn_aux_data =
13140 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13141 	ret = -ENOMEM;
13142 	if (!env->insn_aux_data)
13143 		goto err_free_env;
13144 	for (i = 0; i < len; i++)
13145 		env->insn_aux_data[i].orig_idx = i;
13146 	env->prog = *prog;
13147 	env->ops = bpf_verifier_ops[env->prog->type];
13148 	is_priv = bpf_capable();
13149 
13150 	bpf_get_btf_vmlinux();
13151 
13152 	/* grab the mutex to protect few globals used by verifier */
13153 	if (!is_priv)
13154 		mutex_lock(&bpf_verifier_lock);
13155 
13156 	if (attr->log_level || attr->log_buf || attr->log_size) {
13157 		/* user requested verbose verifier output
13158 		 * and supplied buffer to store the verification trace
13159 		 */
13160 		log->level = attr->log_level;
13161 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13162 		log->len_total = attr->log_size;
13163 
13164 		ret = -EINVAL;
13165 		/* log attributes have to be sane */
13166 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13167 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13168 			goto err_unlock;
13169 	}
13170 
13171 	if (IS_ERR(btf_vmlinux)) {
13172 		/* Either gcc or pahole or kernel are broken. */
13173 		verbose(env, "in-kernel BTF is malformed\n");
13174 		ret = PTR_ERR(btf_vmlinux);
13175 		goto skip_full_check;
13176 	}
13177 
13178 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13179 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13180 		env->strict_alignment = true;
13181 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13182 		env->strict_alignment = false;
13183 
13184 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13185 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13186 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13187 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13188 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13189 	env->bpf_capable = bpf_capable();
13190 
13191 	if (is_priv)
13192 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13193 
13194 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
13195 		ret = bpf_prog_offload_verifier_prep(env->prog);
13196 		if (ret)
13197 			goto skip_full_check;
13198 	}
13199 
13200 	env->explored_states = kvcalloc(state_htab_size(env),
13201 				       sizeof(struct bpf_verifier_state_list *),
13202 				       GFP_USER);
13203 	ret = -ENOMEM;
13204 	if (!env->explored_states)
13205 		goto skip_full_check;
13206 
13207 	ret = add_subprog_and_kfunc(env);
13208 	if (ret < 0)
13209 		goto skip_full_check;
13210 
13211 	ret = check_subprogs(env);
13212 	if (ret < 0)
13213 		goto skip_full_check;
13214 
13215 	ret = check_btf_info(env, attr, uattr);
13216 	if (ret < 0)
13217 		goto skip_full_check;
13218 
13219 	ret = check_attach_btf_id(env);
13220 	if (ret)
13221 		goto skip_full_check;
13222 
13223 	ret = resolve_pseudo_ldimm64(env);
13224 	if (ret < 0)
13225 		goto skip_full_check;
13226 
13227 	ret = check_cfg(env);
13228 	if (ret < 0)
13229 		goto skip_full_check;
13230 
13231 	ret = do_check_subprogs(env);
13232 	ret = ret ?: do_check_main(env);
13233 
13234 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13235 		ret = bpf_prog_offload_finalize(env);
13236 
13237 skip_full_check:
13238 	kvfree(env->explored_states);
13239 
13240 	if (ret == 0)
13241 		ret = check_max_stack_depth(env);
13242 
13243 	/* instruction rewrites happen after this point */
13244 	if (is_priv) {
13245 		if (ret == 0)
13246 			opt_hard_wire_dead_code_branches(env);
13247 		if (ret == 0)
13248 			ret = opt_remove_dead_code(env);
13249 		if (ret == 0)
13250 			ret = opt_remove_nops(env);
13251 	} else {
13252 		if (ret == 0)
13253 			sanitize_dead_code(env);
13254 	}
13255 
13256 	if (ret == 0)
13257 		/* program is valid, convert *(u32*)(ctx + off) accesses */
13258 		ret = convert_ctx_accesses(env);
13259 
13260 	if (ret == 0)
13261 		ret = do_misc_fixups(env);
13262 
13263 	/* do 32-bit optimization after insn patching has done so those patched
13264 	 * insns could be handled correctly.
13265 	 */
13266 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13267 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13268 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13269 								     : false;
13270 	}
13271 
13272 	if (ret == 0)
13273 		ret = fixup_call_args(env);
13274 
13275 	env->verification_time = ktime_get_ns() - start_time;
13276 	print_verification_stats(env);
13277 
13278 	if (log->level && bpf_verifier_log_full(log))
13279 		ret = -ENOSPC;
13280 	if (log->level && !log->ubuf) {
13281 		ret = -EFAULT;
13282 		goto err_release_maps;
13283 	}
13284 
13285 	if (ret)
13286 		goto err_release_maps;
13287 
13288 	if (env->used_map_cnt) {
13289 		/* if program passed verifier, update used_maps in bpf_prog_info */
13290 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13291 							  sizeof(env->used_maps[0]),
13292 							  GFP_KERNEL);
13293 
13294 		if (!env->prog->aux->used_maps) {
13295 			ret = -ENOMEM;
13296 			goto err_release_maps;
13297 		}
13298 
13299 		memcpy(env->prog->aux->used_maps, env->used_maps,
13300 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
13301 		env->prog->aux->used_map_cnt = env->used_map_cnt;
13302 	}
13303 	if (env->used_btf_cnt) {
13304 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
13305 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13306 							  sizeof(env->used_btfs[0]),
13307 							  GFP_KERNEL);
13308 		if (!env->prog->aux->used_btfs) {
13309 			ret = -ENOMEM;
13310 			goto err_release_maps;
13311 		}
13312 
13313 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
13314 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13315 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13316 	}
13317 	if (env->used_map_cnt || env->used_btf_cnt) {
13318 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
13319 		 * bpf_ld_imm64 instructions
13320 		 */
13321 		convert_pseudo_ld_imm64(env);
13322 	}
13323 
13324 	adjust_btf_func(env);
13325 
13326 err_release_maps:
13327 	if (!env->prog->aux->used_maps)
13328 		/* if we didn't copy map pointers into bpf_prog_info, release
13329 		 * them now. Otherwise free_used_maps() will release them.
13330 		 */
13331 		release_maps(env);
13332 	if (!env->prog->aux->used_btfs)
13333 		release_btfs(env);
13334 
13335 	/* extension progs temporarily inherit the attach_type of their targets
13336 	   for verification purposes, so set it back to zero before returning
13337 	 */
13338 	if (env->prog->type == BPF_PROG_TYPE_EXT)
13339 		env->prog->expected_attach_type = 0;
13340 
13341 	*prog = env->prog;
13342 err_unlock:
13343 	if (!is_priv)
13344 		mutex_unlock(&bpf_verifier_lock);
13345 	vfree(env->insn_aux_data);
13346 err_free_env:
13347 	kfree(env);
13348 	return ret;
13349 }
13350