xref: /openbmc/linux/kernel/bpf/verifier.c (revision f3956ebb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25 
26 #include "disasm.h"
27 
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 	[_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38 
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all paths through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns either pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163 
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 	/* verifer state is 'st'
167 	 * before processing instruction 'insn_idx'
168 	 * and after processing instruction 'prev_insn_idx'
169 	 */
170 	struct bpf_verifier_state st;
171 	int insn_idx;
172 	int prev_insn_idx;
173 	struct bpf_verifier_stack_elem *next;
174 	/* length of verifier log at the time this state was pushed on stack */
175 	u32 log_pos;
176 };
177 
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
179 #define BPF_COMPLEXITY_LIMIT_STATES	64
180 
181 #define BPF_MAP_KEY_POISON	(1ULL << 63)
182 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
183 
184 #define BPF_MAP_PTR_UNPRIV	1UL
185 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
186 					  POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193 
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198 
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 			      const struct bpf_map *map, bool unpriv)
201 {
202 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 	unpriv |= bpf_map_ptr_unpriv(aux);
204 	aux->map_ptr_state = (unsigned long)map |
205 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207 
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212 
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217 
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222 
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225 	bool poisoned = bpf_map_key_poisoned(aux);
226 
227 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230 
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233 	return insn->code == (BPF_JMP | BPF_CALL) &&
234 	       insn->src_reg == BPF_PSEUDO_CALL;
235 }
236 
237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238 {
239 	return insn->code == (BPF_JMP | BPF_CALL) &&
240 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241 }
242 
243 static bool bpf_pseudo_func(const struct bpf_insn *insn)
244 {
245 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246 	       insn->src_reg == BPF_PSEUDO_FUNC;
247 }
248 
249 struct bpf_call_arg_meta {
250 	struct bpf_map *map_ptr;
251 	bool raw_mode;
252 	bool pkt_access;
253 	int regno;
254 	int access_size;
255 	int mem_size;
256 	u64 msize_max_value;
257 	int ref_obj_id;
258 	int map_uid;
259 	int func_id;
260 	struct btf *btf;
261 	u32 btf_id;
262 	struct btf *ret_btf;
263 	u32 ret_btf_id;
264 	u32 subprogno;
265 };
266 
267 struct btf *btf_vmlinux;
268 
269 static DEFINE_MUTEX(bpf_verifier_lock);
270 
271 static const struct bpf_line_info *
272 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
273 {
274 	const struct bpf_line_info *linfo;
275 	const struct bpf_prog *prog;
276 	u32 i, nr_linfo;
277 
278 	prog = env->prog;
279 	nr_linfo = prog->aux->nr_linfo;
280 
281 	if (!nr_linfo || insn_off >= prog->len)
282 		return NULL;
283 
284 	linfo = prog->aux->linfo;
285 	for (i = 1; i < nr_linfo; i++)
286 		if (insn_off < linfo[i].insn_off)
287 			break;
288 
289 	return &linfo[i - 1];
290 }
291 
292 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
293 		       va_list args)
294 {
295 	unsigned int n;
296 
297 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
298 
299 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
300 		  "verifier log line truncated - local buffer too short\n");
301 
302 	n = min(log->len_total - log->len_used - 1, n);
303 	log->kbuf[n] = '\0';
304 
305 	if (log->level == BPF_LOG_KERNEL) {
306 		pr_err("BPF:%s\n", log->kbuf);
307 		return;
308 	}
309 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
310 		log->len_used += n;
311 	else
312 		log->ubuf = NULL;
313 }
314 
315 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
316 {
317 	char zero = 0;
318 
319 	if (!bpf_verifier_log_needed(log))
320 		return;
321 
322 	log->len_used = new_pos;
323 	if (put_user(zero, log->ubuf + new_pos))
324 		log->ubuf = NULL;
325 }
326 
327 /* log_level controls verbosity level of eBPF verifier.
328  * bpf_verifier_log_write() is used to dump the verification trace to the log,
329  * so the user can figure out what's wrong with the program
330  */
331 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
332 					   const char *fmt, ...)
333 {
334 	va_list args;
335 
336 	if (!bpf_verifier_log_needed(&env->log))
337 		return;
338 
339 	va_start(args, fmt);
340 	bpf_verifier_vlog(&env->log, fmt, args);
341 	va_end(args);
342 }
343 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
344 
345 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
346 {
347 	struct bpf_verifier_env *env = private_data;
348 	va_list args;
349 
350 	if (!bpf_verifier_log_needed(&env->log))
351 		return;
352 
353 	va_start(args, fmt);
354 	bpf_verifier_vlog(&env->log, fmt, args);
355 	va_end(args);
356 }
357 
358 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
359 			    const char *fmt, ...)
360 {
361 	va_list args;
362 
363 	if (!bpf_verifier_log_needed(log))
364 		return;
365 
366 	va_start(args, fmt);
367 	bpf_verifier_vlog(log, fmt, args);
368 	va_end(args);
369 }
370 
371 static const char *ltrim(const char *s)
372 {
373 	while (isspace(*s))
374 		s++;
375 
376 	return s;
377 }
378 
379 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
380 					 u32 insn_off,
381 					 const char *prefix_fmt, ...)
382 {
383 	const struct bpf_line_info *linfo;
384 
385 	if (!bpf_verifier_log_needed(&env->log))
386 		return;
387 
388 	linfo = find_linfo(env, insn_off);
389 	if (!linfo || linfo == env->prev_linfo)
390 		return;
391 
392 	if (prefix_fmt) {
393 		va_list args;
394 
395 		va_start(args, prefix_fmt);
396 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
397 		va_end(args);
398 	}
399 
400 	verbose(env, "%s\n",
401 		ltrim(btf_name_by_offset(env->prog->aux->btf,
402 					 linfo->line_off)));
403 
404 	env->prev_linfo = linfo;
405 }
406 
407 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
408 				   struct bpf_reg_state *reg,
409 				   struct tnum *range, const char *ctx,
410 				   const char *reg_name)
411 {
412 	char tn_buf[48];
413 
414 	verbose(env, "At %s the register %s ", ctx, reg_name);
415 	if (!tnum_is_unknown(reg->var_off)) {
416 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
417 		verbose(env, "has value %s", tn_buf);
418 	} else {
419 		verbose(env, "has unknown scalar value");
420 	}
421 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
422 	verbose(env, " should have been in %s\n", tn_buf);
423 }
424 
425 static bool type_is_pkt_pointer(enum bpf_reg_type type)
426 {
427 	return type == PTR_TO_PACKET ||
428 	       type == PTR_TO_PACKET_META;
429 }
430 
431 static bool type_is_sk_pointer(enum bpf_reg_type type)
432 {
433 	return type == PTR_TO_SOCKET ||
434 		type == PTR_TO_SOCK_COMMON ||
435 		type == PTR_TO_TCP_SOCK ||
436 		type == PTR_TO_XDP_SOCK;
437 }
438 
439 static bool reg_type_not_null(enum bpf_reg_type type)
440 {
441 	return type == PTR_TO_SOCKET ||
442 		type == PTR_TO_TCP_SOCK ||
443 		type == PTR_TO_MAP_VALUE ||
444 		type == PTR_TO_MAP_KEY ||
445 		type == PTR_TO_SOCK_COMMON;
446 }
447 
448 static bool reg_type_may_be_null(enum bpf_reg_type type)
449 {
450 	return type == PTR_TO_MAP_VALUE_OR_NULL ||
451 	       type == PTR_TO_SOCKET_OR_NULL ||
452 	       type == PTR_TO_SOCK_COMMON_OR_NULL ||
453 	       type == PTR_TO_TCP_SOCK_OR_NULL ||
454 	       type == PTR_TO_BTF_ID_OR_NULL ||
455 	       type == PTR_TO_MEM_OR_NULL ||
456 	       type == PTR_TO_RDONLY_BUF_OR_NULL ||
457 	       type == PTR_TO_RDWR_BUF_OR_NULL;
458 }
459 
460 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
461 {
462 	return reg->type == PTR_TO_MAP_VALUE &&
463 		map_value_has_spin_lock(reg->map_ptr);
464 }
465 
466 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
467 {
468 	return type == PTR_TO_SOCKET ||
469 		type == PTR_TO_SOCKET_OR_NULL ||
470 		type == PTR_TO_TCP_SOCK ||
471 		type == PTR_TO_TCP_SOCK_OR_NULL ||
472 		type == PTR_TO_MEM ||
473 		type == PTR_TO_MEM_OR_NULL;
474 }
475 
476 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
477 {
478 	return type == ARG_PTR_TO_SOCK_COMMON;
479 }
480 
481 static bool arg_type_may_be_null(enum bpf_arg_type type)
482 {
483 	return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
484 	       type == ARG_PTR_TO_MEM_OR_NULL ||
485 	       type == ARG_PTR_TO_CTX_OR_NULL ||
486 	       type == ARG_PTR_TO_SOCKET_OR_NULL ||
487 	       type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
488 	       type == ARG_PTR_TO_STACK_OR_NULL;
489 }
490 
491 /* Determine whether the function releases some resources allocated by another
492  * function call. The first reference type argument will be assumed to be
493  * released by release_reference().
494  */
495 static bool is_release_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_sk_release ||
498 	       func_id == BPF_FUNC_ringbuf_submit ||
499 	       func_id == BPF_FUNC_ringbuf_discard;
500 }
501 
502 static bool may_be_acquire_function(enum bpf_func_id func_id)
503 {
504 	return func_id == BPF_FUNC_sk_lookup_tcp ||
505 		func_id == BPF_FUNC_sk_lookup_udp ||
506 		func_id == BPF_FUNC_skc_lookup_tcp ||
507 		func_id == BPF_FUNC_map_lookup_elem ||
508 	        func_id == BPF_FUNC_ringbuf_reserve;
509 }
510 
511 static bool is_acquire_function(enum bpf_func_id func_id,
512 				const struct bpf_map *map)
513 {
514 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
515 
516 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
517 	    func_id == BPF_FUNC_sk_lookup_udp ||
518 	    func_id == BPF_FUNC_skc_lookup_tcp ||
519 	    func_id == BPF_FUNC_ringbuf_reserve)
520 		return true;
521 
522 	if (func_id == BPF_FUNC_map_lookup_elem &&
523 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
524 	     map_type == BPF_MAP_TYPE_SOCKHASH))
525 		return true;
526 
527 	return false;
528 }
529 
530 static bool is_ptr_cast_function(enum bpf_func_id func_id)
531 {
532 	return func_id == BPF_FUNC_tcp_sock ||
533 		func_id == BPF_FUNC_sk_fullsock ||
534 		func_id == BPF_FUNC_skc_to_tcp_sock ||
535 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
536 		func_id == BPF_FUNC_skc_to_udp6_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
538 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
539 }
540 
541 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
542 {
543 	return BPF_CLASS(insn->code) == BPF_STX &&
544 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
545 	       insn->imm == BPF_CMPXCHG;
546 }
547 
548 /* string representation of 'enum bpf_reg_type' */
549 static const char * const reg_type_str[] = {
550 	[NOT_INIT]		= "?",
551 	[SCALAR_VALUE]		= "inv",
552 	[PTR_TO_CTX]		= "ctx",
553 	[CONST_PTR_TO_MAP]	= "map_ptr",
554 	[PTR_TO_MAP_VALUE]	= "map_value",
555 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
556 	[PTR_TO_STACK]		= "fp",
557 	[PTR_TO_PACKET]		= "pkt",
558 	[PTR_TO_PACKET_META]	= "pkt_meta",
559 	[PTR_TO_PACKET_END]	= "pkt_end",
560 	[PTR_TO_FLOW_KEYS]	= "flow_keys",
561 	[PTR_TO_SOCKET]		= "sock",
562 	[PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
563 	[PTR_TO_SOCK_COMMON]	= "sock_common",
564 	[PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
565 	[PTR_TO_TCP_SOCK]	= "tcp_sock",
566 	[PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
567 	[PTR_TO_TP_BUFFER]	= "tp_buffer",
568 	[PTR_TO_XDP_SOCK]	= "xdp_sock",
569 	[PTR_TO_BTF_ID]		= "ptr_",
570 	[PTR_TO_BTF_ID_OR_NULL]	= "ptr_or_null_",
571 	[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
572 	[PTR_TO_MEM]		= "mem",
573 	[PTR_TO_MEM_OR_NULL]	= "mem_or_null",
574 	[PTR_TO_RDONLY_BUF]	= "rdonly_buf",
575 	[PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
576 	[PTR_TO_RDWR_BUF]	= "rdwr_buf",
577 	[PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
578 	[PTR_TO_FUNC]		= "func",
579 	[PTR_TO_MAP_KEY]	= "map_key",
580 };
581 
582 static char slot_type_char[] = {
583 	[STACK_INVALID]	= '?',
584 	[STACK_SPILL]	= 'r',
585 	[STACK_MISC]	= 'm',
586 	[STACK_ZERO]	= '0',
587 };
588 
589 static void print_liveness(struct bpf_verifier_env *env,
590 			   enum bpf_reg_liveness live)
591 {
592 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
593 	    verbose(env, "_");
594 	if (live & REG_LIVE_READ)
595 		verbose(env, "r");
596 	if (live & REG_LIVE_WRITTEN)
597 		verbose(env, "w");
598 	if (live & REG_LIVE_DONE)
599 		verbose(env, "D");
600 }
601 
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
610 static const char *kernel_type_name(const struct btf* btf, u32 id)
611 {
612 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
613 }
614 
615 /* The reg state of a pointer or a bounded scalar was saved when
616  * it was spilled to the stack.
617  */
618 static bool is_spilled_reg(const struct bpf_stack_state *stack)
619 {
620 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
621 }
622 
623 static void scrub_spilled_slot(u8 *stype)
624 {
625 	if (*stype != STACK_INVALID)
626 		*stype = STACK_MISC;
627 }
628 
629 static void print_verifier_state(struct bpf_verifier_env *env,
630 				 const struct bpf_func_state *state)
631 {
632 	const struct bpf_reg_state *reg;
633 	enum bpf_reg_type t;
634 	int i;
635 
636 	if (state->frameno)
637 		verbose(env, " frame%d:", state->frameno);
638 	for (i = 0; i < MAX_BPF_REG; i++) {
639 		reg = &state->regs[i];
640 		t = reg->type;
641 		if (t == NOT_INIT)
642 			continue;
643 		verbose(env, " R%d", i);
644 		print_liveness(env, reg->live);
645 		verbose(env, "=%s", reg_type_str[t]);
646 		if (t == SCALAR_VALUE && reg->precise)
647 			verbose(env, "P");
648 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
649 		    tnum_is_const(reg->var_off)) {
650 			/* reg->off should be 0 for SCALAR_VALUE */
651 			verbose(env, "%lld", reg->var_off.value + reg->off);
652 		} else {
653 			if (t == PTR_TO_BTF_ID ||
654 			    t == PTR_TO_BTF_ID_OR_NULL ||
655 			    t == PTR_TO_PERCPU_BTF_ID)
656 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
657 			verbose(env, "(id=%d", reg->id);
658 			if (reg_type_may_be_refcounted_or_null(t))
659 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
660 			if (t != SCALAR_VALUE)
661 				verbose(env, ",off=%d", reg->off);
662 			if (type_is_pkt_pointer(t))
663 				verbose(env, ",r=%d", reg->range);
664 			else if (t == CONST_PTR_TO_MAP ||
665 				 t == PTR_TO_MAP_KEY ||
666 				 t == PTR_TO_MAP_VALUE ||
667 				 t == PTR_TO_MAP_VALUE_OR_NULL)
668 				verbose(env, ",ks=%d,vs=%d",
669 					reg->map_ptr->key_size,
670 					reg->map_ptr->value_size);
671 			if (tnum_is_const(reg->var_off)) {
672 				/* Typically an immediate SCALAR_VALUE, but
673 				 * could be a pointer whose offset is too big
674 				 * for reg->off
675 				 */
676 				verbose(env, ",imm=%llx", reg->var_off.value);
677 			} else {
678 				if (reg->smin_value != reg->umin_value &&
679 				    reg->smin_value != S64_MIN)
680 					verbose(env, ",smin_value=%lld",
681 						(long long)reg->smin_value);
682 				if (reg->smax_value != reg->umax_value &&
683 				    reg->smax_value != S64_MAX)
684 					verbose(env, ",smax_value=%lld",
685 						(long long)reg->smax_value);
686 				if (reg->umin_value != 0)
687 					verbose(env, ",umin_value=%llu",
688 						(unsigned long long)reg->umin_value);
689 				if (reg->umax_value != U64_MAX)
690 					verbose(env, ",umax_value=%llu",
691 						(unsigned long long)reg->umax_value);
692 				if (!tnum_is_unknown(reg->var_off)) {
693 					char tn_buf[48];
694 
695 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
696 					verbose(env, ",var_off=%s", tn_buf);
697 				}
698 				if (reg->s32_min_value != reg->smin_value &&
699 				    reg->s32_min_value != S32_MIN)
700 					verbose(env, ",s32_min_value=%d",
701 						(int)(reg->s32_min_value));
702 				if (reg->s32_max_value != reg->smax_value &&
703 				    reg->s32_max_value != S32_MAX)
704 					verbose(env, ",s32_max_value=%d",
705 						(int)(reg->s32_max_value));
706 				if (reg->u32_min_value != reg->umin_value &&
707 				    reg->u32_min_value != U32_MIN)
708 					verbose(env, ",u32_min_value=%d",
709 						(int)(reg->u32_min_value));
710 				if (reg->u32_max_value != reg->umax_value &&
711 				    reg->u32_max_value != U32_MAX)
712 					verbose(env, ",u32_max_value=%d",
713 						(int)(reg->u32_max_value));
714 			}
715 			verbose(env, ")");
716 		}
717 	}
718 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
719 		char types_buf[BPF_REG_SIZE + 1];
720 		bool valid = false;
721 		int j;
722 
723 		for (j = 0; j < BPF_REG_SIZE; j++) {
724 			if (state->stack[i].slot_type[j] != STACK_INVALID)
725 				valid = true;
726 			types_buf[j] = slot_type_char[
727 					state->stack[i].slot_type[j]];
728 		}
729 		types_buf[BPF_REG_SIZE] = 0;
730 		if (!valid)
731 			continue;
732 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
733 		print_liveness(env, state->stack[i].spilled_ptr.live);
734 		if (is_spilled_reg(&state->stack[i])) {
735 			reg = &state->stack[i].spilled_ptr;
736 			t = reg->type;
737 			verbose(env, "=%s", reg_type_str[t]);
738 			if (t == SCALAR_VALUE && reg->precise)
739 				verbose(env, "P");
740 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
741 				verbose(env, "%lld", reg->var_off.value + reg->off);
742 		} else {
743 			verbose(env, "=%s", types_buf);
744 		}
745 	}
746 	if (state->acquired_refs && state->refs[0].id) {
747 		verbose(env, " refs=%d", state->refs[0].id);
748 		for (i = 1; i < state->acquired_refs; i++)
749 			if (state->refs[i].id)
750 				verbose(env, ",%d", state->refs[i].id);
751 	}
752 	if (state->in_callback_fn)
753 		verbose(env, " cb");
754 	if (state->in_async_callback_fn)
755 		verbose(env, " async_cb");
756 	verbose(env, "\n");
757 }
758 
759 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
760  * small to hold src. This is different from krealloc since we don't want to preserve
761  * the contents of dst.
762  *
763  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
764  * not be allocated.
765  */
766 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
767 {
768 	size_t bytes;
769 
770 	if (ZERO_OR_NULL_PTR(src))
771 		goto out;
772 
773 	if (unlikely(check_mul_overflow(n, size, &bytes)))
774 		return NULL;
775 
776 	if (ksize(dst) < bytes) {
777 		kfree(dst);
778 		dst = kmalloc_track_caller(bytes, flags);
779 		if (!dst)
780 			return NULL;
781 	}
782 
783 	memcpy(dst, src, bytes);
784 out:
785 	return dst ? dst : ZERO_SIZE_PTR;
786 }
787 
788 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
789  * small to hold new_n items. new items are zeroed out if the array grows.
790  *
791  * Contrary to krealloc_array, does not free arr if new_n is zero.
792  */
793 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
794 {
795 	if (!new_n || old_n == new_n)
796 		goto out;
797 
798 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
799 	if (!arr)
800 		return NULL;
801 
802 	if (new_n > old_n)
803 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
804 
805 out:
806 	return arr ? arr : ZERO_SIZE_PTR;
807 }
808 
809 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
810 {
811 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
812 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
813 	if (!dst->refs)
814 		return -ENOMEM;
815 
816 	dst->acquired_refs = src->acquired_refs;
817 	return 0;
818 }
819 
820 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
821 {
822 	size_t n = src->allocated_stack / BPF_REG_SIZE;
823 
824 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
825 				GFP_KERNEL);
826 	if (!dst->stack)
827 		return -ENOMEM;
828 
829 	dst->allocated_stack = src->allocated_stack;
830 	return 0;
831 }
832 
833 static int resize_reference_state(struct bpf_func_state *state, size_t n)
834 {
835 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
836 				    sizeof(struct bpf_reference_state));
837 	if (!state->refs)
838 		return -ENOMEM;
839 
840 	state->acquired_refs = n;
841 	return 0;
842 }
843 
844 static int grow_stack_state(struct bpf_func_state *state, int size)
845 {
846 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
847 
848 	if (old_n >= n)
849 		return 0;
850 
851 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
852 	if (!state->stack)
853 		return -ENOMEM;
854 
855 	state->allocated_stack = size;
856 	return 0;
857 }
858 
859 /* Acquire a pointer id from the env and update the state->refs to include
860  * this new pointer reference.
861  * On success, returns a valid pointer id to associate with the register
862  * On failure, returns a negative errno.
863  */
864 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
865 {
866 	struct bpf_func_state *state = cur_func(env);
867 	int new_ofs = state->acquired_refs;
868 	int id, err;
869 
870 	err = resize_reference_state(state, state->acquired_refs + 1);
871 	if (err)
872 		return err;
873 	id = ++env->id_gen;
874 	state->refs[new_ofs].id = id;
875 	state->refs[new_ofs].insn_idx = insn_idx;
876 
877 	return id;
878 }
879 
880 /* release function corresponding to acquire_reference_state(). Idempotent. */
881 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
882 {
883 	int i, last_idx;
884 
885 	last_idx = state->acquired_refs - 1;
886 	for (i = 0; i < state->acquired_refs; i++) {
887 		if (state->refs[i].id == ptr_id) {
888 			if (last_idx && i != last_idx)
889 				memcpy(&state->refs[i], &state->refs[last_idx],
890 				       sizeof(*state->refs));
891 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
892 			state->acquired_refs--;
893 			return 0;
894 		}
895 	}
896 	return -EINVAL;
897 }
898 
899 static void free_func_state(struct bpf_func_state *state)
900 {
901 	if (!state)
902 		return;
903 	kfree(state->refs);
904 	kfree(state->stack);
905 	kfree(state);
906 }
907 
908 static void clear_jmp_history(struct bpf_verifier_state *state)
909 {
910 	kfree(state->jmp_history);
911 	state->jmp_history = NULL;
912 	state->jmp_history_cnt = 0;
913 }
914 
915 static void free_verifier_state(struct bpf_verifier_state *state,
916 				bool free_self)
917 {
918 	int i;
919 
920 	for (i = 0; i <= state->curframe; i++) {
921 		free_func_state(state->frame[i]);
922 		state->frame[i] = NULL;
923 	}
924 	clear_jmp_history(state);
925 	if (free_self)
926 		kfree(state);
927 }
928 
929 /* copy verifier state from src to dst growing dst stack space
930  * when necessary to accommodate larger src stack
931  */
932 static int copy_func_state(struct bpf_func_state *dst,
933 			   const struct bpf_func_state *src)
934 {
935 	int err;
936 
937 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
938 	err = copy_reference_state(dst, src);
939 	if (err)
940 		return err;
941 	return copy_stack_state(dst, src);
942 }
943 
944 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
945 			       const struct bpf_verifier_state *src)
946 {
947 	struct bpf_func_state *dst;
948 	int i, err;
949 
950 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
951 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
952 					    GFP_USER);
953 	if (!dst_state->jmp_history)
954 		return -ENOMEM;
955 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
956 
957 	/* if dst has more stack frames then src frame, free them */
958 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
959 		free_func_state(dst_state->frame[i]);
960 		dst_state->frame[i] = NULL;
961 	}
962 	dst_state->speculative = src->speculative;
963 	dst_state->curframe = src->curframe;
964 	dst_state->active_spin_lock = src->active_spin_lock;
965 	dst_state->branches = src->branches;
966 	dst_state->parent = src->parent;
967 	dst_state->first_insn_idx = src->first_insn_idx;
968 	dst_state->last_insn_idx = src->last_insn_idx;
969 	for (i = 0; i <= src->curframe; i++) {
970 		dst = dst_state->frame[i];
971 		if (!dst) {
972 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
973 			if (!dst)
974 				return -ENOMEM;
975 			dst_state->frame[i] = dst;
976 		}
977 		err = copy_func_state(dst, src->frame[i]);
978 		if (err)
979 			return err;
980 	}
981 	return 0;
982 }
983 
984 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
985 {
986 	while (st) {
987 		u32 br = --st->branches;
988 
989 		/* WARN_ON(br > 1) technically makes sense here,
990 		 * but see comment in push_stack(), hence:
991 		 */
992 		WARN_ONCE((int)br < 0,
993 			  "BUG update_branch_counts:branches_to_explore=%d\n",
994 			  br);
995 		if (br)
996 			break;
997 		st = st->parent;
998 	}
999 }
1000 
1001 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1002 		     int *insn_idx, bool pop_log)
1003 {
1004 	struct bpf_verifier_state *cur = env->cur_state;
1005 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1006 	int err;
1007 
1008 	if (env->head == NULL)
1009 		return -ENOENT;
1010 
1011 	if (cur) {
1012 		err = copy_verifier_state(cur, &head->st);
1013 		if (err)
1014 			return err;
1015 	}
1016 	if (pop_log)
1017 		bpf_vlog_reset(&env->log, head->log_pos);
1018 	if (insn_idx)
1019 		*insn_idx = head->insn_idx;
1020 	if (prev_insn_idx)
1021 		*prev_insn_idx = head->prev_insn_idx;
1022 	elem = head->next;
1023 	free_verifier_state(&head->st, false);
1024 	kfree(head);
1025 	env->head = elem;
1026 	env->stack_size--;
1027 	return 0;
1028 }
1029 
1030 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1031 					     int insn_idx, int prev_insn_idx,
1032 					     bool speculative)
1033 {
1034 	struct bpf_verifier_state *cur = env->cur_state;
1035 	struct bpf_verifier_stack_elem *elem;
1036 	int err;
1037 
1038 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1039 	if (!elem)
1040 		goto err;
1041 
1042 	elem->insn_idx = insn_idx;
1043 	elem->prev_insn_idx = prev_insn_idx;
1044 	elem->next = env->head;
1045 	elem->log_pos = env->log.len_used;
1046 	env->head = elem;
1047 	env->stack_size++;
1048 	err = copy_verifier_state(&elem->st, cur);
1049 	if (err)
1050 		goto err;
1051 	elem->st.speculative |= speculative;
1052 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1053 		verbose(env, "The sequence of %d jumps is too complex.\n",
1054 			env->stack_size);
1055 		goto err;
1056 	}
1057 	if (elem->st.parent) {
1058 		++elem->st.parent->branches;
1059 		/* WARN_ON(branches > 2) technically makes sense here,
1060 		 * but
1061 		 * 1. speculative states will bump 'branches' for non-branch
1062 		 * instructions
1063 		 * 2. is_state_visited() heuristics may decide not to create
1064 		 * a new state for a sequence of branches and all such current
1065 		 * and cloned states will be pointing to a single parent state
1066 		 * which might have large 'branches' count.
1067 		 */
1068 	}
1069 	return &elem->st;
1070 err:
1071 	free_verifier_state(env->cur_state, true);
1072 	env->cur_state = NULL;
1073 	/* pop all elements and return */
1074 	while (!pop_stack(env, NULL, NULL, false));
1075 	return NULL;
1076 }
1077 
1078 #define CALLER_SAVED_REGS 6
1079 static const int caller_saved[CALLER_SAVED_REGS] = {
1080 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1081 };
1082 
1083 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1084 				struct bpf_reg_state *reg);
1085 
1086 /* This helper doesn't clear reg->id */
1087 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1088 {
1089 	reg->var_off = tnum_const(imm);
1090 	reg->smin_value = (s64)imm;
1091 	reg->smax_value = (s64)imm;
1092 	reg->umin_value = imm;
1093 	reg->umax_value = imm;
1094 
1095 	reg->s32_min_value = (s32)imm;
1096 	reg->s32_max_value = (s32)imm;
1097 	reg->u32_min_value = (u32)imm;
1098 	reg->u32_max_value = (u32)imm;
1099 }
1100 
1101 /* Mark the unknown part of a register (variable offset or scalar value) as
1102  * known to have the value @imm.
1103  */
1104 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1105 {
1106 	/* Clear id, off, and union(map_ptr, range) */
1107 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1108 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1109 	___mark_reg_known(reg, imm);
1110 }
1111 
1112 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1113 {
1114 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1115 	reg->s32_min_value = (s32)imm;
1116 	reg->s32_max_value = (s32)imm;
1117 	reg->u32_min_value = (u32)imm;
1118 	reg->u32_max_value = (u32)imm;
1119 }
1120 
1121 /* Mark the 'variable offset' part of a register as zero.  This should be
1122  * used only on registers holding a pointer type.
1123  */
1124 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1125 {
1126 	__mark_reg_known(reg, 0);
1127 }
1128 
1129 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1130 {
1131 	__mark_reg_known(reg, 0);
1132 	reg->type = SCALAR_VALUE;
1133 }
1134 
1135 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1136 				struct bpf_reg_state *regs, u32 regno)
1137 {
1138 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1139 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1140 		/* Something bad happened, let's kill all regs */
1141 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1142 			__mark_reg_not_init(env, regs + regno);
1143 		return;
1144 	}
1145 	__mark_reg_known_zero(regs + regno);
1146 }
1147 
1148 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1149 {
1150 	switch (reg->type) {
1151 	case PTR_TO_MAP_VALUE_OR_NULL: {
1152 		const struct bpf_map *map = reg->map_ptr;
1153 
1154 		if (map->inner_map_meta) {
1155 			reg->type = CONST_PTR_TO_MAP;
1156 			reg->map_ptr = map->inner_map_meta;
1157 			/* transfer reg's id which is unique for every map_lookup_elem
1158 			 * as UID of the inner map.
1159 			 */
1160 			reg->map_uid = reg->id;
1161 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1162 			reg->type = PTR_TO_XDP_SOCK;
1163 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1164 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1165 			reg->type = PTR_TO_SOCKET;
1166 		} else {
1167 			reg->type = PTR_TO_MAP_VALUE;
1168 		}
1169 		break;
1170 	}
1171 	case PTR_TO_SOCKET_OR_NULL:
1172 		reg->type = PTR_TO_SOCKET;
1173 		break;
1174 	case PTR_TO_SOCK_COMMON_OR_NULL:
1175 		reg->type = PTR_TO_SOCK_COMMON;
1176 		break;
1177 	case PTR_TO_TCP_SOCK_OR_NULL:
1178 		reg->type = PTR_TO_TCP_SOCK;
1179 		break;
1180 	case PTR_TO_BTF_ID_OR_NULL:
1181 		reg->type = PTR_TO_BTF_ID;
1182 		break;
1183 	case PTR_TO_MEM_OR_NULL:
1184 		reg->type = PTR_TO_MEM;
1185 		break;
1186 	case PTR_TO_RDONLY_BUF_OR_NULL:
1187 		reg->type = PTR_TO_RDONLY_BUF;
1188 		break;
1189 	case PTR_TO_RDWR_BUF_OR_NULL:
1190 		reg->type = PTR_TO_RDWR_BUF;
1191 		break;
1192 	default:
1193 		WARN_ONCE(1, "unknown nullable register type");
1194 	}
1195 }
1196 
1197 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1198 {
1199 	return type_is_pkt_pointer(reg->type);
1200 }
1201 
1202 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1203 {
1204 	return reg_is_pkt_pointer(reg) ||
1205 	       reg->type == PTR_TO_PACKET_END;
1206 }
1207 
1208 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1209 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1210 				    enum bpf_reg_type which)
1211 {
1212 	/* The register can already have a range from prior markings.
1213 	 * This is fine as long as it hasn't been advanced from its
1214 	 * origin.
1215 	 */
1216 	return reg->type == which &&
1217 	       reg->id == 0 &&
1218 	       reg->off == 0 &&
1219 	       tnum_equals_const(reg->var_off, 0);
1220 }
1221 
1222 /* Reset the min/max bounds of a register */
1223 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1224 {
1225 	reg->smin_value = S64_MIN;
1226 	reg->smax_value = S64_MAX;
1227 	reg->umin_value = 0;
1228 	reg->umax_value = U64_MAX;
1229 
1230 	reg->s32_min_value = S32_MIN;
1231 	reg->s32_max_value = S32_MAX;
1232 	reg->u32_min_value = 0;
1233 	reg->u32_max_value = U32_MAX;
1234 }
1235 
1236 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1237 {
1238 	reg->smin_value = S64_MIN;
1239 	reg->smax_value = S64_MAX;
1240 	reg->umin_value = 0;
1241 	reg->umax_value = U64_MAX;
1242 }
1243 
1244 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1245 {
1246 	reg->s32_min_value = S32_MIN;
1247 	reg->s32_max_value = S32_MAX;
1248 	reg->u32_min_value = 0;
1249 	reg->u32_max_value = U32_MAX;
1250 }
1251 
1252 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1253 {
1254 	struct tnum var32_off = tnum_subreg(reg->var_off);
1255 
1256 	/* min signed is max(sign bit) | min(other bits) */
1257 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1258 			var32_off.value | (var32_off.mask & S32_MIN));
1259 	/* max signed is min(sign bit) | max(other bits) */
1260 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1261 			var32_off.value | (var32_off.mask & S32_MAX));
1262 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1263 	reg->u32_max_value = min(reg->u32_max_value,
1264 				 (u32)(var32_off.value | var32_off.mask));
1265 }
1266 
1267 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1268 {
1269 	/* min signed is max(sign bit) | min(other bits) */
1270 	reg->smin_value = max_t(s64, reg->smin_value,
1271 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1272 	/* max signed is min(sign bit) | max(other bits) */
1273 	reg->smax_value = min_t(s64, reg->smax_value,
1274 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1275 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1276 	reg->umax_value = min(reg->umax_value,
1277 			      reg->var_off.value | reg->var_off.mask);
1278 }
1279 
1280 static void __update_reg_bounds(struct bpf_reg_state *reg)
1281 {
1282 	__update_reg32_bounds(reg);
1283 	__update_reg64_bounds(reg);
1284 }
1285 
1286 /* Uses signed min/max values to inform unsigned, and vice-versa */
1287 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1288 {
1289 	/* Learn sign from signed bounds.
1290 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1291 	 * are the same, so combine.  This works even in the negative case, e.g.
1292 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1293 	 */
1294 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1295 		reg->s32_min_value = reg->u32_min_value =
1296 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1297 		reg->s32_max_value = reg->u32_max_value =
1298 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1299 		return;
1300 	}
1301 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1302 	 * boundary, so we must be careful.
1303 	 */
1304 	if ((s32)reg->u32_max_value >= 0) {
1305 		/* Positive.  We can't learn anything from the smin, but smax
1306 		 * is positive, hence safe.
1307 		 */
1308 		reg->s32_min_value = reg->u32_min_value;
1309 		reg->s32_max_value = reg->u32_max_value =
1310 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1311 	} else if ((s32)reg->u32_min_value < 0) {
1312 		/* Negative.  We can't learn anything from the smax, but smin
1313 		 * is negative, hence safe.
1314 		 */
1315 		reg->s32_min_value = reg->u32_min_value =
1316 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1317 		reg->s32_max_value = reg->u32_max_value;
1318 	}
1319 }
1320 
1321 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1322 {
1323 	/* Learn sign from signed bounds.
1324 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1325 	 * are the same, so combine.  This works even in the negative case, e.g.
1326 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1327 	 */
1328 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1329 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1330 							  reg->umin_value);
1331 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1332 							  reg->umax_value);
1333 		return;
1334 	}
1335 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1336 	 * boundary, so we must be careful.
1337 	 */
1338 	if ((s64)reg->umax_value >= 0) {
1339 		/* Positive.  We can't learn anything from the smin, but smax
1340 		 * is positive, hence safe.
1341 		 */
1342 		reg->smin_value = reg->umin_value;
1343 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1344 							  reg->umax_value);
1345 	} else if ((s64)reg->umin_value < 0) {
1346 		/* Negative.  We can't learn anything from the smax, but smin
1347 		 * is negative, hence safe.
1348 		 */
1349 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1350 							  reg->umin_value);
1351 		reg->smax_value = reg->umax_value;
1352 	}
1353 }
1354 
1355 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1356 {
1357 	__reg32_deduce_bounds(reg);
1358 	__reg64_deduce_bounds(reg);
1359 }
1360 
1361 /* Attempts to improve var_off based on unsigned min/max information */
1362 static void __reg_bound_offset(struct bpf_reg_state *reg)
1363 {
1364 	struct tnum var64_off = tnum_intersect(reg->var_off,
1365 					       tnum_range(reg->umin_value,
1366 							  reg->umax_value));
1367 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1368 						tnum_range(reg->u32_min_value,
1369 							   reg->u32_max_value));
1370 
1371 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1372 }
1373 
1374 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1375 {
1376 	reg->umin_value = reg->u32_min_value;
1377 	reg->umax_value = reg->u32_max_value;
1378 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds
1379 	 * but must be positive otherwise set to worse case bounds
1380 	 * and refine later from tnum.
1381 	 */
1382 	if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1383 		reg->smax_value = reg->s32_max_value;
1384 	else
1385 		reg->smax_value = U32_MAX;
1386 	if (reg->s32_min_value >= 0)
1387 		reg->smin_value = reg->s32_min_value;
1388 	else
1389 		reg->smin_value = 0;
1390 }
1391 
1392 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1393 {
1394 	/* special case when 64-bit register has upper 32-bit register
1395 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1396 	 * allowing us to use 32-bit bounds directly,
1397 	 */
1398 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1399 		__reg_assign_32_into_64(reg);
1400 	} else {
1401 		/* Otherwise the best we can do is push lower 32bit known and
1402 		 * unknown bits into register (var_off set from jmp logic)
1403 		 * then learn as much as possible from the 64-bit tnum
1404 		 * known and unknown bits. The previous smin/smax bounds are
1405 		 * invalid here because of jmp32 compare so mark them unknown
1406 		 * so they do not impact tnum bounds calculation.
1407 		 */
1408 		__mark_reg64_unbounded(reg);
1409 		__update_reg_bounds(reg);
1410 	}
1411 
1412 	/* Intersecting with the old var_off might have improved our bounds
1413 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1414 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1415 	 */
1416 	__reg_deduce_bounds(reg);
1417 	__reg_bound_offset(reg);
1418 	__update_reg_bounds(reg);
1419 }
1420 
1421 static bool __reg64_bound_s32(s64 a)
1422 {
1423 	return a > S32_MIN && a < S32_MAX;
1424 }
1425 
1426 static bool __reg64_bound_u32(u64 a)
1427 {
1428 	return a > U32_MIN && a < U32_MAX;
1429 }
1430 
1431 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1432 {
1433 	__mark_reg32_unbounded(reg);
1434 
1435 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1436 		reg->s32_min_value = (s32)reg->smin_value;
1437 		reg->s32_max_value = (s32)reg->smax_value;
1438 	}
1439 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1440 		reg->u32_min_value = (u32)reg->umin_value;
1441 		reg->u32_max_value = (u32)reg->umax_value;
1442 	}
1443 
1444 	/* Intersecting with the old var_off might have improved our bounds
1445 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1446 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1447 	 */
1448 	__reg_deduce_bounds(reg);
1449 	__reg_bound_offset(reg);
1450 	__update_reg_bounds(reg);
1451 }
1452 
1453 /* Mark a register as having a completely unknown (scalar) value. */
1454 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1455 			       struct bpf_reg_state *reg)
1456 {
1457 	/*
1458 	 * Clear type, id, off, and union(map_ptr, range) and
1459 	 * padding between 'type' and union
1460 	 */
1461 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1462 	reg->type = SCALAR_VALUE;
1463 	reg->var_off = tnum_unknown;
1464 	reg->frameno = 0;
1465 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1466 	__mark_reg_unbounded(reg);
1467 }
1468 
1469 static void mark_reg_unknown(struct bpf_verifier_env *env,
1470 			     struct bpf_reg_state *regs, u32 regno)
1471 {
1472 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1473 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1474 		/* Something bad happened, let's kill all regs except FP */
1475 		for (regno = 0; regno < BPF_REG_FP; regno++)
1476 			__mark_reg_not_init(env, regs + regno);
1477 		return;
1478 	}
1479 	__mark_reg_unknown(env, regs + regno);
1480 }
1481 
1482 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1483 				struct bpf_reg_state *reg)
1484 {
1485 	__mark_reg_unknown(env, reg);
1486 	reg->type = NOT_INIT;
1487 }
1488 
1489 static void mark_reg_not_init(struct bpf_verifier_env *env,
1490 			      struct bpf_reg_state *regs, u32 regno)
1491 {
1492 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1493 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1494 		/* Something bad happened, let's kill all regs except FP */
1495 		for (regno = 0; regno < BPF_REG_FP; regno++)
1496 			__mark_reg_not_init(env, regs + regno);
1497 		return;
1498 	}
1499 	__mark_reg_not_init(env, regs + regno);
1500 }
1501 
1502 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1503 			    struct bpf_reg_state *regs, u32 regno,
1504 			    enum bpf_reg_type reg_type,
1505 			    struct btf *btf, u32 btf_id)
1506 {
1507 	if (reg_type == SCALAR_VALUE) {
1508 		mark_reg_unknown(env, regs, regno);
1509 		return;
1510 	}
1511 	mark_reg_known_zero(env, regs, regno);
1512 	regs[regno].type = PTR_TO_BTF_ID;
1513 	regs[regno].btf = btf;
1514 	regs[regno].btf_id = btf_id;
1515 }
1516 
1517 #define DEF_NOT_SUBREG	(0)
1518 static void init_reg_state(struct bpf_verifier_env *env,
1519 			   struct bpf_func_state *state)
1520 {
1521 	struct bpf_reg_state *regs = state->regs;
1522 	int i;
1523 
1524 	for (i = 0; i < MAX_BPF_REG; i++) {
1525 		mark_reg_not_init(env, regs, i);
1526 		regs[i].live = REG_LIVE_NONE;
1527 		regs[i].parent = NULL;
1528 		regs[i].subreg_def = DEF_NOT_SUBREG;
1529 	}
1530 
1531 	/* frame pointer */
1532 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1533 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1534 	regs[BPF_REG_FP].frameno = state->frameno;
1535 }
1536 
1537 #define BPF_MAIN_FUNC (-1)
1538 static void init_func_state(struct bpf_verifier_env *env,
1539 			    struct bpf_func_state *state,
1540 			    int callsite, int frameno, int subprogno)
1541 {
1542 	state->callsite = callsite;
1543 	state->frameno = frameno;
1544 	state->subprogno = subprogno;
1545 	init_reg_state(env, state);
1546 }
1547 
1548 /* Similar to push_stack(), but for async callbacks */
1549 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1550 						int insn_idx, int prev_insn_idx,
1551 						int subprog)
1552 {
1553 	struct bpf_verifier_stack_elem *elem;
1554 	struct bpf_func_state *frame;
1555 
1556 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1557 	if (!elem)
1558 		goto err;
1559 
1560 	elem->insn_idx = insn_idx;
1561 	elem->prev_insn_idx = prev_insn_idx;
1562 	elem->next = env->head;
1563 	elem->log_pos = env->log.len_used;
1564 	env->head = elem;
1565 	env->stack_size++;
1566 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1567 		verbose(env,
1568 			"The sequence of %d jumps is too complex for async cb.\n",
1569 			env->stack_size);
1570 		goto err;
1571 	}
1572 	/* Unlike push_stack() do not copy_verifier_state().
1573 	 * The caller state doesn't matter.
1574 	 * This is async callback. It starts in a fresh stack.
1575 	 * Initialize it similar to do_check_common().
1576 	 */
1577 	elem->st.branches = 1;
1578 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1579 	if (!frame)
1580 		goto err;
1581 	init_func_state(env, frame,
1582 			BPF_MAIN_FUNC /* callsite */,
1583 			0 /* frameno within this callchain */,
1584 			subprog /* subprog number within this prog */);
1585 	elem->st.frame[0] = frame;
1586 	return &elem->st;
1587 err:
1588 	free_verifier_state(env->cur_state, true);
1589 	env->cur_state = NULL;
1590 	/* pop all elements and return */
1591 	while (!pop_stack(env, NULL, NULL, false));
1592 	return NULL;
1593 }
1594 
1595 
1596 enum reg_arg_type {
1597 	SRC_OP,		/* register is used as source operand */
1598 	DST_OP,		/* register is used as destination operand */
1599 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1600 };
1601 
1602 static int cmp_subprogs(const void *a, const void *b)
1603 {
1604 	return ((struct bpf_subprog_info *)a)->start -
1605 	       ((struct bpf_subprog_info *)b)->start;
1606 }
1607 
1608 static int find_subprog(struct bpf_verifier_env *env, int off)
1609 {
1610 	struct bpf_subprog_info *p;
1611 
1612 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1613 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1614 	if (!p)
1615 		return -ENOENT;
1616 	return p - env->subprog_info;
1617 
1618 }
1619 
1620 static int add_subprog(struct bpf_verifier_env *env, int off)
1621 {
1622 	int insn_cnt = env->prog->len;
1623 	int ret;
1624 
1625 	if (off >= insn_cnt || off < 0) {
1626 		verbose(env, "call to invalid destination\n");
1627 		return -EINVAL;
1628 	}
1629 	ret = find_subprog(env, off);
1630 	if (ret >= 0)
1631 		return ret;
1632 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1633 		verbose(env, "too many subprograms\n");
1634 		return -E2BIG;
1635 	}
1636 	/* determine subprog starts. The end is one before the next starts */
1637 	env->subprog_info[env->subprog_cnt++].start = off;
1638 	sort(env->subprog_info, env->subprog_cnt,
1639 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1640 	return env->subprog_cnt - 1;
1641 }
1642 
1643 struct bpf_kfunc_desc {
1644 	struct btf_func_model func_model;
1645 	u32 func_id;
1646 	s32 imm;
1647 };
1648 
1649 #define MAX_KFUNC_DESCS 256
1650 struct bpf_kfunc_desc_tab {
1651 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1652 	u32 nr_descs;
1653 };
1654 
1655 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1656 {
1657 	const struct bpf_kfunc_desc *d0 = a;
1658 	const struct bpf_kfunc_desc *d1 = b;
1659 
1660 	/* func_id is not greater than BTF_MAX_TYPE */
1661 	return d0->func_id - d1->func_id;
1662 }
1663 
1664 static const struct bpf_kfunc_desc *
1665 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1666 {
1667 	struct bpf_kfunc_desc desc = {
1668 		.func_id = func_id,
1669 	};
1670 	struct bpf_kfunc_desc_tab *tab;
1671 
1672 	tab = prog->aux->kfunc_tab;
1673 	return bsearch(&desc, tab->descs, tab->nr_descs,
1674 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1675 }
1676 
1677 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1678 {
1679 	const struct btf_type *func, *func_proto;
1680 	struct bpf_kfunc_desc_tab *tab;
1681 	struct bpf_prog_aux *prog_aux;
1682 	struct bpf_kfunc_desc *desc;
1683 	const char *func_name;
1684 	unsigned long addr;
1685 	int err;
1686 
1687 	prog_aux = env->prog->aux;
1688 	tab = prog_aux->kfunc_tab;
1689 	if (!tab) {
1690 		if (!btf_vmlinux) {
1691 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1692 			return -ENOTSUPP;
1693 		}
1694 
1695 		if (!env->prog->jit_requested) {
1696 			verbose(env, "JIT is required for calling kernel function\n");
1697 			return -ENOTSUPP;
1698 		}
1699 
1700 		if (!bpf_jit_supports_kfunc_call()) {
1701 			verbose(env, "JIT does not support calling kernel function\n");
1702 			return -ENOTSUPP;
1703 		}
1704 
1705 		if (!env->prog->gpl_compatible) {
1706 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1707 			return -EINVAL;
1708 		}
1709 
1710 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1711 		if (!tab)
1712 			return -ENOMEM;
1713 		prog_aux->kfunc_tab = tab;
1714 	}
1715 
1716 	if (find_kfunc_desc(env->prog, func_id))
1717 		return 0;
1718 
1719 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1720 		verbose(env, "too many different kernel function calls\n");
1721 		return -E2BIG;
1722 	}
1723 
1724 	func = btf_type_by_id(btf_vmlinux, func_id);
1725 	if (!func || !btf_type_is_func(func)) {
1726 		verbose(env, "kernel btf_id %u is not a function\n",
1727 			func_id);
1728 		return -EINVAL;
1729 	}
1730 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
1731 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1732 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1733 			func_id);
1734 		return -EINVAL;
1735 	}
1736 
1737 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1738 	addr = kallsyms_lookup_name(func_name);
1739 	if (!addr) {
1740 		verbose(env, "cannot find address for kernel function %s\n",
1741 			func_name);
1742 		return -EINVAL;
1743 	}
1744 
1745 	desc = &tab->descs[tab->nr_descs++];
1746 	desc->func_id = func_id;
1747 	desc->imm = BPF_CALL_IMM(addr);
1748 	err = btf_distill_func_proto(&env->log, btf_vmlinux,
1749 				     func_proto, func_name,
1750 				     &desc->func_model);
1751 	if (!err)
1752 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1753 		     kfunc_desc_cmp_by_id, NULL);
1754 	return err;
1755 }
1756 
1757 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1758 {
1759 	const struct bpf_kfunc_desc *d0 = a;
1760 	const struct bpf_kfunc_desc *d1 = b;
1761 
1762 	if (d0->imm > d1->imm)
1763 		return 1;
1764 	else if (d0->imm < d1->imm)
1765 		return -1;
1766 	return 0;
1767 }
1768 
1769 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1770 {
1771 	struct bpf_kfunc_desc_tab *tab;
1772 
1773 	tab = prog->aux->kfunc_tab;
1774 	if (!tab)
1775 		return;
1776 
1777 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1778 	     kfunc_desc_cmp_by_imm, NULL);
1779 }
1780 
1781 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1782 {
1783 	return !!prog->aux->kfunc_tab;
1784 }
1785 
1786 const struct btf_func_model *
1787 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1788 			 const struct bpf_insn *insn)
1789 {
1790 	const struct bpf_kfunc_desc desc = {
1791 		.imm = insn->imm,
1792 	};
1793 	const struct bpf_kfunc_desc *res;
1794 	struct bpf_kfunc_desc_tab *tab;
1795 
1796 	tab = prog->aux->kfunc_tab;
1797 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1798 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1799 
1800 	return res ? &res->func_model : NULL;
1801 }
1802 
1803 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1804 {
1805 	struct bpf_subprog_info *subprog = env->subprog_info;
1806 	struct bpf_insn *insn = env->prog->insnsi;
1807 	int i, ret, insn_cnt = env->prog->len;
1808 
1809 	/* Add entry function. */
1810 	ret = add_subprog(env, 0);
1811 	if (ret)
1812 		return ret;
1813 
1814 	for (i = 0; i < insn_cnt; i++, insn++) {
1815 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1816 		    !bpf_pseudo_kfunc_call(insn))
1817 			continue;
1818 
1819 		if (!env->bpf_capable) {
1820 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1821 			return -EPERM;
1822 		}
1823 
1824 		if (bpf_pseudo_func(insn)) {
1825 			ret = add_subprog(env, i + insn->imm + 1);
1826 			if (ret >= 0)
1827 				/* remember subprog */
1828 				insn[1].imm = ret;
1829 		} else if (bpf_pseudo_call(insn)) {
1830 			ret = add_subprog(env, i + insn->imm + 1);
1831 		} else {
1832 			ret = add_kfunc_call(env, insn->imm);
1833 		}
1834 
1835 		if (ret < 0)
1836 			return ret;
1837 	}
1838 
1839 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1840 	 * logic. 'subprog_cnt' should not be increased.
1841 	 */
1842 	subprog[env->subprog_cnt].start = insn_cnt;
1843 
1844 	if (env->log.level & BPF_LOG_LEVEL2)
1845 		for (i = 0; i < env->subprog_cnt; i++)
1846 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1847 
1848 	return 0;
1849 }
1850 
1851 static int check_subprogs(struct bpf_verifier_env *env)
1852 {
1853 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1854 	struct bpf_subprog_info *subprog = env->subprog_info;
1855 	struct bpf_insn *insn = env->prog->insnsi;
1856 	int insn_cnt = env->prog->len;
1857 
1858 	/* now check that all jumps are within the same subprog */
1859 	subprog_start = subprog[cur_subprog].start;
1860 	subprog_end = subprog[cur_subprog + 1].start;
1861 	for (i = 0; i < insn_cnt; i++) {
1862 		u8 code = insn[i].code;
1863 
1864 		if (code == (BPF_JMP | BPF_CALL) &&
1865 		    insn[i].imm == BPF_FUNC_tail_call &&
1866 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1867 			subprog[cur_subprog].has_tail_call = true;
1868 		if (BPF_CLASS(code) == BPF_LD &&
1869 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1870 			subprog[cur_subprog].has_ld_abs = true;
1871 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1872 			goto next;
1873 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1874 			goto next;
1875 		off = i + insn[i].off + 1;
1876 		if (off < subprog_start || off >= subprog_end) {
1877 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1878 			return -EINVAL;
1879 		}
1880 next:
1881 		if (i == subprog_end - 1) {
1882 			/* to avoid fall-through from one subprog into another
1883 			 * the last insn of the subprog should be either exit
1884 			 * or unconditional jump back
1885 			 */
1886 			if (code != (BPF_JMP | BPF_EXIT) &&
1887 			    code != (BPF_JMP | BPF_JA)) {
1888 				verbose(env, "last insn is not an exit or jmp\n");
1889 				return -EINVAL;
1890 			}
1891 			subprog_start = subprog_end;
1892 			cur_subprog++;
1893 			if (cur_subprog < env->subprog_cnt)
1894 				subprog_end = subprog[cur_subprog + 1].start;
1895 		}
1896 	}
1897 	return 0;
1898 }
1899 
1900 /* Parentage chain of this register (or stack slot) should take care of all
1901  * issues like callee-saved registers, stack slot allocation time, etc.
1902  */
1903 static int mark_reg_read(struct bpf_verifier_env *env,
1904 			 const struct bpf_reg_state *state,
1905 			 struct bpf_reg_state *parent, u8 flag)
1906 {
1907 	bool writes = parent == state->parent; /* Observe write marks */
1908 	int cnt = 0;
1909 
1910 	while (parent) {
1911 		/* if read wasn't screened by an earlier write ... */
1912 		if (writes && state->live & REG_LIVE_WRITTEN)
1913 			break;
1914 		if (parent->live & REG_LIVE_DONE) {
1915 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1916 				reg_type_str[parent->type],
1917 				parent->var_off.value, parent->off);
1918 			return -EFAULT;
1919 		}
1920 		/* The first condition is more likely to be true than the
1921 		 * second, checked it first.
1922 		 */
1923 		if ((parent->live & REG_LIVE_READ) == flag ||
1924 		    parent->live & REG_LIVE_READ64)
1925 			/* The parentage chain never changes and
1926 			 * this parent was already marked as LIVE_READ.
1927 			 * There is no need to keep walking the chain again and
1928 			 * keep re-marking all parents as LIVE_READ.
1929 			 * This case happens when the same register is read
1930 			 * multiple times without writes into it in-between.
1931 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1932 			 * then no need to set the weak REG_LIVE_READ32.
1933 			 */
1934 			break;
1935 		/* ... then we depend on parent's value */
1936 		parent->live |= flag;
1937 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1938 		if (flag == REG_LIVE_READ64)
1939 			parent->live &= ~REG_LIVE_READ32;
1940 		state = parent;
1941 		parent = state->parent;
1942 		writes = true;
1943 		cnt++;
1944 	}
1945 
1946 	if (env->longest_mark_read_walk < cnt)
1947 		env->longest_mark_read_walk = cnt;
1948 	return 0;
1949 }
1950 
1951 /* This function is supposed to be used by the following 32-bit optimization
1952  * code only. It returns TRUE if the source or destination register operates
1953  * on 64-bit, otherwise return FALSE.
1954  */
1955 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1956 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1957 {
1958 	u8 code, class, op;
1959 
1960 	code = insn->code;
1961 	class = BPF_CLASS(code);
1962 	op = BPF_OP(code);
1963 	if (class == BPF_JMP) {
1964 		/* BPF_EXIT for "main" will reach here. Return TRUE
1965 		 * conservatively.
1966 		 */
1967 		if (op == BPF_EXIT)
1968 			return true;
1969 		if (op == BPF_CALL) {
1970 			/* BPF to BPF call will reach here because of marking
1971 			 * caller saved clobber with DST_OP_NO_MARK for which we
1972 			 * don't care the register def because they are anyway
1973 			 * marked as NOT_INIT already.
1974 			 */
1975 			if (insn->src_reg == BPF_PSEUDO_CALL)
1976 				return false;
1977 			/* Helper call will reach here because of arg type
1978 			 * check, conservatively return TRUE.
1979 			 */
1980 			if (t == SRC_OP)
1981 				return true;
1982 
1983 			return false;
1984 		}
1985 	}
1986 
1987 	if (class == BPF_ALU64 || class == BPF_JMP ||
1988 	    /* BPF_END always use BPF_ALU class. */
1989 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1990 		return true;
1991 
1992 	if (class == BPF_ALU || class == BPF_JMP32)
1993 		return false;
1994 
1995 	if (class == BPF_LDX) {
1996 		if (t != SRC_OP)
1997 			return BPF_SIZE(code) == BPF_DW;
1998 		/* LDX source must be ptr. */
1999 		return true;
2000 	}
2001 
2002 	if (class == BPF_STX) {
2003 		/* BPF_STX (including atomic variants) has multiple source
2004 		 * operands, one of which is a ptr. Check whether the caller is
2005 		 * asking about it.
2006 		 */
2007 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2008 			return true;
2009 		return BPF_SIZE(code) == BPF_DW;
2010 	}
2011 
2012 	if (class == BPF_LD) {
2013 		u8 mode = BPF_MODE(code);
2014 
2015 		/* LD_IMM64 */
2016 		if (mode == BPF_IMM)
2017 			return true;
2018 
2019 		/* Both LD_IND and LD_ABS return 32-bit data. */
2020 		if (t != SRC_OP)
2021 			return  false;
2022 
2023 		/* Implicit ctx ptr. */
2024 		if (regno == BPF_REG_6)
2025 			return true;
2026 
2027 		/* Explicit source could be any width. */
2028 		return true;
2029 	}
2030 
2031 	if (class == BPF_ST)
2032 		/* The only source register for BPF_ST is a ptr. */
2033 		return true;
2034 
2035 	/* Conservatively return true at default. */
2036 	return true;
2037 }
2038 
2039 /* Return the regno defined by the insn, or -1. */
2040 static int insn_def_regno(const struct bpf_insn *insn)
2041 {
2042 	switch (BPF_CLASS(insn->code)) {
2043 	case BPF_JMP:
2044 	case BPF_JMP32:
2045 	case BPF_ST:
2046 		return -1;
2047 	case BPF_STX:
2048 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2049 		    (insn->imm & BPF_FETCH)) {
2050 			if (insn->imm == BPF_CMPXCHG)
2051 				return BPF_REG_0;
2052 			else
2053 				return insn->src_reg;
2054 		} else {
2055 			return -1;
2056 		}
2057 	default:
2058 		return insn->dst_reg;
2059 	}
2060 }
2061 
2062 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2063 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2064 {
2065 	int dst_reg = insn_def_regno(insn);
2066 
2067 	if (dst_reg == -1)
2068 		return false;
2069 
2070 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2071 }
2072 
2073 static void mark_insn_zext(struct bpf_verifier_env *env,
2074 			   struct bpf_reg_state *reg)
2075 {
2076 	s32 def_idx = reg->subreg_def;
2077 
2078 	if (def_idx == DEF_NOT_SUBREG)
2079 		return;
2080 
2081 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2082 	/* The dst will be zero extended, so won't be sub-register anymore. */
2083 	reg->subreg_def = DEF_NOT_SUBREG;
2084 }
2085 
2086 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2087 			 enum reg_arg_type t)
2088 {
2089 	struct bpf_verifier_state *vstate = env->cur_state;
2090 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2091 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2092 	struct bpf_reg_state *reg, *regs = state->regs;
2093 	bool rw64;
2094 
2095 	if (regno >= MAX_BPF_REG) {
2096 		verbose(env, "R%d is invalid\n", regno);
2097 		return -EINVAL;
2098 	}
2099 
2100 	reg = &regs[regno];
2101 	rw64 = is_reg64(env, insn, regno, reg, t);
2102 	if (t == SRC_OP) {
2103 		/* check whether register used as source operand can be read */
2104 		if (reg->type == NOT_INIT) {
2105 			verbose(env, "R%d !read_ok\n", regno);
2106 			return -EACCES;
2107 		}
2108 		/* We don't need to worry about FP liveness because it's read-only */
2109 		if (regno == BPF_REG_FP)
2110 			return 0;
2111 
2112 		if (rw64)
2113 			mark_insn_zext(env, reg);
2114 
2115 		return mark_reg_read(env, reg, reg->parent,
2116 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2117 	} else {
2118 		/* check whether register used as dest operand can be written to */
2119 		if (regno == BPF_REG_FP) {
2120 			verbose(env, "frame pointer is read only\n");
2121 			return -EACCES;
2122 		}
2123 		reg->live |= REG_LIVE_WRITTEN;
2124 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2125 		if (t == DST_OP)
2126 			mark_reg_unknown(env, regs, regno);
2127 	}
2128 	return 0;
2129 }
2130 
2131 /* for any branch, call, exit record the history of jmps in the given state */
2132 static int push_jmp_history(struct bpf_verifier_env *env,
2133 			    struct bpf_verifier_state *cur)
2134 {
2135 	u32 cnt = cur->jmp_history_cnt;
2136 	struct bpf_idx_pair *p;
2137 
2138 	cnt++;
2139 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2140 	if (!p)
2141 		return -ENOMEM;
2142 	p[cnt - 1].idx = env->insn_idx;
2143 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2144 	cur->jmp_history = p;
2145 	cur->jmp_history_cnt = cnt;
2146 	return 0;
2147 }
2148 
2149 /* Backtrack one insn at a time. If idx is not at the top of recorded
2150  * history then previous instruction came from straight line execution.
2151  */
2152 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2153 			     u32 *history)
2154 {
2155 	u32 cnt = *history;
2156 
2157 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2158 		i = st->jmp_history[cnt - 1].prev_idx;
2159 		(*history)--;
2160 	} else {
2161 		i--;
2162 	}
2163 	return i;
2164 }
2165 
2166 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2167 {
2168 	const struct btf_type *func;
2169 
2170 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2171 		return NULL;
2172 
2173 	func = btf_type_by_id(btf_vmlinux, insn->imm);
2174 	return btf_name_by_offset(btf_vmlinux, func->name_off);
2175 }
2176 
2177 /* For given verifier state backtrack_insn() is called from the last insn to
2178  * the first insn. Its purpose is to compute a bitmask of registers and
2179  * stack slots that needs precision in the parent verifier state.
2180  */
2181 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2182 			  u32 *reg_mask, u64 *stack_mask)
2183 {
2184 	const struct bpf_insn_cbs cbs = {
2185 		.cb_call	= disasm_kfunc_name,
2186 		.cb_print	= verbose,
2187 		.private_data	= env,
2188 	};
2189 	struct bpf_insn *insn = env->prog->insnsi + idx;
2190 	u8 class = BPF_CLASS(insn->code);
2191 	u8 opcode = BPF_OP(insn->code);
2192 	u8 mode = BPF_MODE(insn->code);
2193 	u32 dreg = 1u << insn->dst_reg;
2194 	u32 sreg = 1u << insn->src_reg;
2195 	u32 spi;
2196 
2197 	if (insn->code == 0)
2198 		return 0;
2199 	if (env->log.level & BPF_LOG_LEVEL) {
2200 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2201 		verbose(env, "%d: ", idx);
2202 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2203 	}
2204 
2205 	if (class == BPF_ALU || class == BPF_ALU64) {
2206 		if (!(*reg_mask & dreg))
2207 			return 0;
2208 		if (opcode == BPF_MOV) {
2209 			if (BPF_SRC(insn->code) == BPF_X) {
2210 				/* dreg = sreg
2211 				 * dreg needs precision after this insn
2212 				 * sreg needs precision before this insn
2213 				 */
2214 				*reg_mask &= ~dreg;
2215 				*reg_mask |= sreg;
2216 			} else {
2217 				/* dreg = K
2218 				 * dreg needs precision after this insn.
2219 				 * Corresponding register is already marked
2220 				 * as precise=true in this verifier state.
2221 				 * No further markings in parent are necessary
2222 				 */
2223 				*reg_mask &= ~dreg;
2224 			}
2225 		} else {
2226 			if (BPF_SRC(insn->code) == BPF_X) {
2227 				/* dreg += sreg
2228 				 * both dreg and sreg need precision
2229 				 * before this insn
2230 				 */
2231 				*reg_mask |= sreg;
2232 			} /* else dreg += K
2233 			   * dreg still needs precision before this insn
2234 			   */
2235 		}
2236 	} else if (class == BPF_LDX) {
2237 		if (!(*reg_mask & dreg))
2238 			return 0;
2239 		*reg_mask &= ~dreg;
2240 
2241 		/* scalars can only be spilled into stack w/o losing precision.
2242 		 * Load from any other memory can be zero extended.
2243 		 * The desire to keep that precision is already indicated
2244 		 * by 'precise' mark in corresponding register of this state.
2245 		 * No further tracking necessary.
2246 		 */
2247 		if (insn->src_reg != BPF_REG_FP)
2248 			return 0;
2249 		if (BPF_SIZE(insn->code) != BPF_DW)
2250 			return 0;
2251 
2252 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2253 		 * that [fp - off] slot contains scalar that needs to be
2254 		 * tracked with precision
2255 		 */
2256 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2257 		if (spi >= 64) {
2258 			verbose(env, "BUG spi %d\n", spi);
2259 			WARN_ONCE(1, "verifier backtracking bug");
2260 			return -EFAULT;
2261 		}
2262 		*stack_mask |= 1ull << spi;
2263 	} else if (class == BPF_STX || class == BPF_ST) {
2264 		if (*reg_mask & dreg)
2265 			/* stx & st shouldn't be using _scalar_ dst_reg
2266 			 * to access memory. It means backtracking
2267 			 * encountered a case of pointer subtraction.
2268 			 */
2269 			return -ENOTSUPP;
2270 		/* scalars can only be spilled into stack */
2271 		if (insn->dst_reg != BPF_REG_FP)
2272 			return 0;
2273 		if (BPF_SIZE(insn->code) != BPF_DW)
2274 			return 0;
2275 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2276 		if (spi >= 64) {
2277 			verbose(env, "BUG spi %d\n", spi);
2278 			WARN_ONCE(1, "verifier backtracking bug");
2279 			return -EFAULT;
2280 		}
2281 		if (!(*stack_mask & (1ull << spi)))
2282 			return 0;
2283 		*stack_mask &= ~(1ull << spi);
2284 		if (class == BPF_STX)
2285 			*reg_mask |= sreg;
2286 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2287 		if (opcode == BPF_CALL) {
2288 			if (insn->src_reg == BPF_PSEUDO_CALL)
2289 				return -ENOTSUPP;
2290 			/* regular helper call sets R0 */
2291 			*reg_mask &= ~1;
2292 			if (*reg_mask & 0x3f) {
2293 				/* if backtracing was looking for registers R1-R5
2294 				 * they should have been found already.
2295 				 */
2296 				verbose(env, "BUG regs %x\n", *reg_mask);
2297 				WARN_ONCE(1, "verifier backtracking bug");
2298 				return -EFAULT;
2299 			}
2300 		} else if (opcode == BPF_EXIT) {
2301 			return -ENOTSUPP;
2302 		}
2303 	} else if (class == BPF_LD) {
2304 		if (!(*reg_mask & dreg))
2305 			return 0;
2306 		*reg_mask &= ~dreg;
2307 		/* It's ld_imm64 or ld_abs or ld_ind.
2308 		 * For ld_imm64 no further tracking of precision
2309 		 * into parent is necessary
2310 		 */
2311 		if (mode == BPF_IND || mode == BPF_ABS)
2312 			/* to be analyzed */
2313 			return -ENOTSUPP;
2314 	}
2315 	return 0;
2316 }
2317 
2318 /* the scalar precision tracking algorithm:
2319  * . at the start all registers have precise=false.
2320  * . scalar ranges are tracked as normal through alu and jmp insns.
2321  * . once precise value of the scalar register is used in:
2322  *   .  ptr + scalar alu
2323  *   . if (scalar cond K|scalar)
2324  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2325  *   backtrack through the verifier states and mark all registers and
2326  *   stack slots with spilled constants that these scalar regisers
2327  *   should be precise.
2328  * . during state pruning two registers (or spilled stack slots)
2329  *   are equivalent if both are not precise.
2330  *
2331  * Note the verifier cannot simply walk register parentage chain,
2332  * since many different registers and stack slots could have been
2333  * used to compute single precise scalar.
2334  *
2335  * The approach of starting with precise=true for all registers and then
2336  * backtrack to mark a register as not precise when the verifier detects
2337  * that program doesn't care about specific value (e.g., when helper
2338  * takes register as ARG_ANYTHING parameter) is not safe.
2339  *
2340  * It's ok to walk single parentage chain of the verifier states.
2341  * It's possible that this backtracking will go all the way till 1st insn.
2342  * All other branches will be explored for needing precision later.
2343  *
2344  * The backtracking needs to deal with cases like:
2345  *   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)
2346  * r9 -= r8
2347  * r5 = r9
2348  * if r5 > 0x79f goto pc+7
2349  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2350  * r5 += 1
2351  * ...
2352  * call bpf_perf_event_output#25
2353  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2354  *
2355  * and this case:
2356  * r6 = 1
2357  * call foo // uses callee's r6 inside to compute r0
2358  * r0 += r6
2359  * if r0 == 0 goto
2360  *
2361  * to track above reg_mask/stack_mask needs to be independent for each frame.
2362  *
2363  * Also if parent's curframe > frame where backtracking started,
2364  * the verifier need to mark registers in both frames, otherwise callees
2365  * may incorrectly prune callers. This is similar to
2366  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2367  *
2368  * For now backtracking falls back into conservative marking.
2369  */
2370 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2371 				     struct bpf_verifier_state *st)
2372 {
2373 	struct bpf_func_state *func;
2374 	struct bpf_reg_state *reg;
2375 	int i, j;
2376 
2377 	/* big hammer: mark all scalars precise in this path.
2378 	 * pop_stack may still get !precise scalars.
2379 	 */
2380 	for (; st; st = st->parent)
2381 		for (i = 0; i <= st->curframe; i++) {
2382 			func = st->frame[i];
2383 			for (j = 0; j < BPF_REG_FP; j++) {
2384 				reg = &func->regs[j];
2385 				if (reg->type != SCALAR_VALUE)
2386 					continue;
2387 				reg->precise = true;
2388 			}
2389 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2390 				if (!is_spilled_reg(&func->stack[j]))
2391 					continue;
2392 				reg = &func->stack[j].spilled_ptr;
2393 				if (reg->type != SCALAR_VALUE)
2394 					continue;
2395 				reg->precise = true;
2396 			}
2397 		}
2398 }
2399 
2400 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2401 				  int spi)
2402 {
2403 	struct bpf_verifier_state *st = env->cur_state;
2404 	int first_idx = st->first_insn_idx;
2405 	int last_idx = env->insn_idx;
2406 	struct bpf_func_state *func;
2407 	struct bpf_reg_state *reg;
2408 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2409 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2410 	bool skip_first = true;
2411 	bool new_marks = false;
2412 	int i, err;
2413 
2414 	if (!env->bpf_capable)
2415 		return 0;
2416 
2417 	func = st->frame[st->curframe];
2418 	if (regno >= 0) {
2419 		reg = &func->regs[regno];
2420 		if (reg->type != SCALAR_VALUE) {
2421 			WARN_ONCE(1, "backtracing misuse");
2422 			return -EFAULT;
2423 		}
2424 		if (!reg->precise)
2425 			new_marks = true;
2426 		else
2427 			reg_mask = 0;
2428 		reg->precise = true;
2429 	}
2430 
2431 	while (spi >= 0) {
2432 		if (!is_spilled_reg(&func->stack[spi])) {
2433 			stack_mask = 0;
2434 			break;
2435 		}
2436 		reg = &func->stack[spi].spilled_ptr;
2437 		if (reg->type != SCALAR_VALUE) {
2438 			stack_mask = 0;
2439 			break;
2440 		}
2441 		if (!reg->precise)
2442 			new_marks = true;
2443 		else
2444 			stack_mask = 0;
2445 		reg->precise = true;
2446 		break;
2447 	}
2448 
2449 	if (!new_marks)
2450 		return 0;
2451 	if (!reg_mask && !stack_mask)
2452 		return 0;
2453 	for (;;) {
2454 		DECLARE_BITMAP(mask, 64);
2455 		u32 history = st->jmp_history_cnt;
2456 
2457 		if (env->log.level & BPF_LOG_LEVEL)
2458 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2459 		for (i = last_idx;;) {
2460 			if (skip_first) {
2461 				err = 0;
2462 				skip_first = false;
2463 			} else {
2464 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2465 			}
2466 			if (err == -ENOTSUPP) {
2467 				mark_all_scalars_precise(env, st);
2468 				return 0;
2469 			} else if (err) {
2470 				return err;
2471 			}
2472 			if (!reg_mask && !stack_mask)
2473 				/* Found assignment(s) into tracked register in this state.
2474 				 * Since this state is already marked, just return.
2475 				 * Nothing to be tracked further in the parent state.
2476 				 */
2477 				return 0;
2478 			if (i == first_idx)
2479 				break;
2480 			i = get_prev_insn_idx(st, i, &history);
2481 			if (i >= env->prog->len) {
2482 				/* This can happen if backtracking reached insn 0
2483 				 * and there are still reg_mask or stack_mask
2484 				 * to backtrack.
2485 				 * It means the backtracking missed the spot where
2486 				 * particular register was initialized with a constant.
2487 				 */
2488 				verbose(env, "BUG backtracking idx %d\n", i);
2489 				WARN_ONCE(1, "verifier backtracking bug");
2490 				return -EFAULT;
2491 			}
2492 		}
2493 		st = st->parent;
2494 		if (!st)
2495 			break;
2496 
2497 		new_marks = false;
2498 		func = st->frame[st->curframe];
2499 		bitmap_from_u64(mask, reg_mask);
2500 		for_each_set_bit(i, mask, 32) {
2501 			reg = &func->regs[i];
2502 			if (reg->type != SCALAR_VALUE) {
2503 				reg_mask &= ~(1u << i);
2504 				continue;
2505 			}
2506 			if (!reg->precise)
2507 				new_marks = true;
2508 			reg->precise = true;
2509 		}
2510 
2511 		bitmap_from_u64(mask, stack_mask);
2512 		for_each_set_bit(i, mask, 64) {
2513 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2514 				/* the sequence of instructions:
2515 				 * 2: (bf) r3 = r10
2516 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2517 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2518 				 * doesn't contain jmps. It's backtracked
2519 				 * as a single block.
2520 				 * During backtracking insn 3 is not recognized as
2521 				 * stack access, so at the end of backtracking
2522 				 * stack slot fp-8 is still marked in stack_mask.
2523 				 * However the parent state may not have accessed
2524 				 * fp-8 and it's "unallocated" stack space.
2525 				 * In such case fallback to conservative.
2526 				 */
2527 				mark_all_scalars_precise(env, st);
2528 				return 0;
2529 			}
2530 
2531 			if (!is_spilled_reg(&func->stack[i])) {
2532 				stack_mask &= ~(1ull << i);
2533 				continue;
2534 			}
2535 			reg = &func->stack[i].spilled_ptr;
2536 			if (reg->type != SCALAR_VALUE) {
2537 				stack_mask &= ~(1ull << i);
2538 				continue;
2539 			}
2540 			if (!reg->precise)
2541 				new_marks = true;
2542 			reg->precise = true;
2543 		}
2544 		if (env->log.level & BPF_LOG_LEVEL) {
2545 			print_verifier_state(env, func);
2546 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2547 				new_marks ? "didn't have" : "already had",
2548 				reg_mask, stack_mask);
2549 		}
2550 
2551 		if (!reg_mask && !stack_mask)
2552 			break;
2553 		if (!new_marks)
2554 			break;
2555 
2556 		last_idx = st->last_insn_idx;
2557 		first_idx = st->first_insn_idx;
2558 	}
2559 	return 0;
2560 }
2561 
2562 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2563 {
2564 	return __mark_chain_precision(env, regno, -1);
2565 }
2566 
2567 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2568 {
2569 	return __mark_chain_precision(env, -1, spi);
2570 }
2571 
2572 static bool is_spillable_regtype(enum bpf_reg_type type)
2573 {
2574 	switch (type) {
2575 	case PTR_TO_MAP_VALUE:
2576 	case PTR_TO_MAP_VALUE_OR_NULL:
2577 	case PTR_TO_STACK:
2578 	case PTR_TO_CTX:
2579 	case PTR_TO_PACKET:
2580 	case PTR_TO_PACKET_META:
2581 	case PTR_TO_PACKET_END:
2582 	case PTR_TO_FLOW_KEYS:
2583 	case CONST_PTR_TO_MAP:
2584 	case PTR_TO_SOCKET:
2585 	case PTR_TO_SOCKET_OR_NULL:
2586 	case PTR_TO_SOCK_COMMON:
2587 	case PTR_TO_SOCK_COMMON_OR_NULL:
2588 	case PTR_TO_TCP_SOCK:
2589 	case PTR_TO_TCP_SOCK_OR_NULL:
2590 	case PTR_TO_XDP_SOCK:
2591 	case PTR_TO_BTF_ID:
2592 	case PTR_TO_BTF_ID_OR_NULL:
2593 	case PTR_TO_RDONLY_BUF:
2594 	case PTR_TO_RDONLY_BUF_OR_NULL:
2595 	case PTR_TO_RDWR_BUF:
2596 	case PTR_TO_RDWR_BUF_OR_NULL:
2597 	case PTR_TO_PERCPU_BTF_ID:
2598 	case PTR_TO_MEM:
2599 	case PTR_TO_MEM_OR_NULL:
2600 	case PTR_TO_FUNC:
2601 	case PTR_TO_MAP_KEY:
2602 		return true;
2603 	default:
2604 		return false;
2605 	}
2606 }
2607 
2608 /* Does this register contain a constant zero? */
2609 static bool register_is_null(struct bpf_reg_state *reg)
2610 {
2611 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2612 }
2613 
2614 static bool register_is_const(struct bpf_reg_state *reg)
2615 {
2616 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2617 }
2618 
2619 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2620 {
2621 	return tnum_is_unknown(reg->var_off) &&
2622 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2623 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2624 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2625 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2626 }
2627 
2628 static bool register_is_bounded(struct bpf_reg_state *reg)
2629 {
2630 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2631 }
2632 
2633 static bool __is_pointer_value(bool allow_ptr_leaks,
2634 			       const struct bpf_reg_state *reg)
2635 {
2636 	if (allow_ptr_leaks)
2637 		return false;
2638 
2639 	return reg->type != SCALAR_VALUE;
2640 }
2641 
2642 static void save_register_state(struct bpf_func_state *state,
2643 				int spi, struct bpf_reg_state *reg,
2644 				int size)
2645 {
2646 	int i;
2647 
2648 	state->stack[spi].spilled_ptr = *reg;
2649 	if (size == BPF_REG_SIZE)
2650 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2651 
2652 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2653 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2654 
2655 	/* size < 8 bytes spill */
2656 	for (; i; i--)
2657 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2658 }
2659 
2660 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2661  * stack boundary and alignment are checked in check_mem_access()
2662  */
2663 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2664 				       /* stack frame we're writing to */
2665 				       struct bpf_func_state *state,
2666 				       int off, int size, int value_regno,
2667 				       int insn_idx)
2668 {
2669 	struct bpf_func_state *cur; /* state of the current function */
2670 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2671 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2672 	struct bpf_reg_state *reg = NULL;
2673 
2674 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2675 	if (err)
2676 		return err;
2677 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2678 	 * so it's aligned access and [off, off + size) are within stack limits
2679 	 */
2680 	if (!env->allow_ptr_leaks &&
2681 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2682 	    size != BPF_REG_SIZE) {
2683 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2684 		return -EACCES;
2685 	}
2686 
2687 	cur = env->cur_state->frame[env->cur_state->curframe];
2688 	if (value_regno >= 0)
2689 		reg = &cur->regs[value_regno];
2690 	if (!env->bypass_spec_v4) {
2691 		bool sanitize = reg && is_spillable_regtype(reg->type);
2692 
2693 		for (i = 0; i < size; i++) {
2694 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2695 				sanitize = true;
2696 				break;
2697 			}
2698 		}
2699 
2700 		if (sanitize)
2701 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2702 	}
2703 
2704 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2705 	    !register_is_null(reg) && env->bpf_capable) {
2706 		if (dst_reg != BPF_REG_FP) {
2707 			/* The backtracking logic can only recognize explicit
2708 			 * stack slot address like [fp - 8]. Other spill of
2709 			 * scalar via different register has to be conservative.
2710 			 * Backtrack from here and mark all registers as precise
2711 			 * that contributed into 'reg' being a constant.
2712 			 */
2713 			err = mark_chain_precision(env, value_regno);
2714 			if (err)
2715 				return err;
2716 		}
2717 		save_register_state(state, spi, reg, size);
2718 	} else if (reg && is_spillable_regtype(reg->type)) {
2719 		/* register containing pointer is being spilled into stack */
2720 		if (size != BPF_REG_SIZE) {
2721 			verbose_linfo(env, insn_idx, "; ");
2722 			verbose(env, "invalid size of register spill\n");
2723 			return -EACCES;
2724 		}
2725 		if (state != cur && reg->type == PTR_TO_STACK) {
2726 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2727 			return -EINVAL;
2728 		}
2729 		save_register_state(state, spi, reg, size);
2730 	} else {
2731 		u8 type = STACK_MISC;
2732 
2733 		/* regular write of data into stack destroys any spilled ptr */
2734 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2735 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2736 		if (is_spilled_reg(&state->stack[spi]))
2737 			for (i = 0; i < BPF_REG_SIZE; i++)
2738 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2739 
2740 		/* only mark the slot as written if all 8 bytes were written
2741 		 * otherwise read propagation may incorrectly stop too soon
2742 		 * when stack slots are partially written.
2743 		 * This heuristic means that read propagation will be
2744 		 * conservative, since it will add reg_live_read marks
2745 		 * to stack slots all the way to first state when programs
2746 		 * writes+reads less than 8 bytes
2747 		 */
2748 		if (size == BPF_REG_SIZE)
2749 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2750 
2751 		/* when we zero initialize stack slots mark them as such */
2752 		if (reg && register_is_null(reg)) {
2753 			/* backtracking doesn't work for STACK_ZERO yet. */
2754 			err = mark_chain_precision(env, value_regno);
2755 			if (err)
2756 				return err;
2757 			type = STACK_ZERO;
2758 		}
2759 
2760 		/* Mark slots affected by this stack write. */
2761 		for (i = 0; i < size; i++)
2762 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2763 				type;
2764 	}
2765 	return 0;
2766 }
2767 
2768 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2769  * known to contain a variable offset.
2770  * This function checks whether the write is permitted and conservatively
2771  * tracks the effects of the write, considering that each stack slot in the
2772  * dynamic range is potentially written to.
2773  *
2774  * 'off' includes 'regno->off'.
2775  * 'value_regno' can be -1, meaning that an unknown value is being written to
2776  * the stack.
2777  *
2778  * Spilled pointers in range are not marked as written because we don't know
2779  * what's going to be actually written. This means that read propagation for
2780  * future reads cannot be terminated by this write.
2781  *
2782  * For privileged programs, uninitialized stack slots are considered
2783  * initialized by this write (even though we don't know exactly what offsets
2784  * are going to be written to). The idea is that we don't want the verifier to
2785  * reject future reads that access slots written to through variable offsets.
2786  */
2787 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2788 				     /* func where register points to */
2789 				     struct bpf_func_state *state,
2790 				     int ptr_regno, int off, int size,
2791 				     int value_regno, int insn_idx)
2792 {
2793 	struct bpf_func_state *cur; /* state of the current function */
2794 	int min_off, max_off;
2795 	int i, err;
2796 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2797 	bool writing_zero = false;
2798 	/* set if the fact that we're writing a zero is used to let any
2799 	 * stack slots remain STACK_ZERO
2800 	 */
2801 	bool zero_used = false;
2802 
2803 	cur = env->cur_state->frame[env->cur_state->curframe];
2804 	ptr_reg = &cur->regs[ptr_regno];
2805 	min_off = ptr_reg->smin_value + off;
2806 	max_off = ptr_reg->smax_value + off + size;
2807 	if (value_regno >= 0)
2808 		value_reg = &cur->regs[value_regno];
2809 	if (value_reg && register_is_null(value_reg))
2810 		writing_zero = true;
2811 
2812 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2813 	if (err)
2814 		return err;
2815 
2816 
2817 	/* Variable offset writes destroy any spilled pointers in range. */
2818 	for (i = min_off; i < max_off; i++) {
2819 		u8 new_type, *stype;
2820 		int slot, spi;
2821 
2822 		slot = -i - 1;
2823 		spi = slot / BPF_REG_SIZE;
2824 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2825 
2826 		if (!env->allow_ptr_leaks
2827 				&& *stype != NOT_INIT
2828 				&& *stype != SCALAR_VALUE) {
2829 			/* Reject the write if there's are spilled pointers in
2830 			 * range. If we didn't reject here, the ptr status
2831 			 * would be erased below (even though not all slots are
2832 			 * actually overwritten), possibly opening the door to
2833 			 * leaks.
2834 			 */
2835 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2836 				insn_idx, i);
2837 			return -EINVAL;
2838 		}
2839 
2840 		/* Erase all spilled pointers. */
2841 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2842 
2843 		/* Update the slot type. */
2844 		new_type = STACK_MISC;
2845 		if (writing_zero && *stype == STACK_ZERO) {
2846 			new_type = STACK_ZERO;
2847 			zero_used = true;
2848 		}
2849 		/* If the slot is STACK_INVALID, we check whether it's OK to
2850 		 * pretend that it will be initialized by this write. The slot
2851 		 * might not actually be written to, and so if we mark it as
2852 		 * initialized future reads might leak uninitialized memory.
2853 		 * For privileged programs, we will accept such reads to slots
2854 		 * that may or may not be written because, if we're reject
2855 		 * them, the error would be too confusing.
2856 		 */
2857 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2858 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2859 					insn_idx, i);
2860 			return -EINVAL;
2861 		}
2862 		*stype = new_type;
2863 	}
2864 	if (zero_used) {
2865 		/* backtracking doesn't work for STACK_ZERO yet. */
2866 		err = mark_chain_precision(env, value_regno);
2867 		if (err)
2868 			return err;
2869 	}
2870 	return 0;
2871 }
2872 
2873 /* When register 'dst_regno' is assigned some values from stack[min_off,
2874  * max_off), we set the register's type according to the types of the
2875  * respective stack slots. If all the stack values are known to be zeros, then
2876  * so is the destination reg. Otherwise, the register is considered to be
2877  * SCALAR. This function does not deal with register filling; the caller must
2878  * ensure that all spilled registers in the stack range have been marked as
2879  * read.
2880  */
2881 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2882 				/* func where src register points to */
2883 				struct bpf_func_state *ptr_state,
2884 				int min_off, int max_off, int dst_regno)
2885 {
2886 	struct bpf_verifier_state *vstate = env->cur_state;
2887 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2888 	int i, slot, spi;
2889 	u8 *stype;
2890 	int zeros = 0;
2891 
2892 	for (i = min_off; i < max_off; i++) {
2893 		slot = -i - 1;
2894 		spi = slot / BPF_REG_SIZE;
2895 		stype = ptr_state->stack[spi].slot_type;
2896 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2897 			break;
2898 		zeros++;
2899 	}
2900 	if (zeros == max_off - min_off) {
2901 		/* any access_size read into register is zero extended,
2902 		 * so the whole register == const_zero
2903 		 */
2904 		__mark_reg_const_zero(&state->regs[dst_regno]);
2905 		/* backtracking doesn't support STACK_ZERO yet,
2906 		 * so mark it precise here, so that later
2907 		 * backtracking can stop here.
2908 		 * Backtracking may not need this if this register
2909 		 * doesn't participate in pointer adjustment.
2910 		 * Forward propagation of precise flag is not
2911 		 * necessary either. This mark is only to stop
2912 		 * backtracking. Any register that contributed
2913 		 * to const 0 was marked precise before spill.
2914 		 */
2915 		state->regs[dst_regno].precise = true;
2916 	} else {
2917 		/* have read misc data from the stack */
2918 		mark_reg_unknown(env, state->regs, dst_regno);
2919 	}
2920 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2921 }
2922 
2923 /* Read the stack at 'off' and put the results into the register indicated by
2924  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2925  * spilled reg.
2926  *
2927  * 'dst_regno' can be -1, meaning that the read value is not going to a
2928  * register.
2929  *
2930  * The access is assumed to be within the current stack bounds.
2931  */
2932 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2933 				      /* func where src register points to */
2934 				      struct bpf_func_state *reg_state,
2935 				      int off, int size, int dst_regno)
2936 {
2937 	struct bpf_verifier_state *vstate = env->cur_state;
2938 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2939 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2940 	struct bpf_reg_state *reg;
2941 	u8 *stype, type;
2942 
2943 	stype = reg_state->stack[spi].slot_type;
2944 	reg = &reg_state->stack[spi].spilled_ptr;
2945 
2946 	if (is_spilled_reg(&reg_state->stack[spi])) {
2947 		if (size != BPF_REG_SIZE) {
2948 			u8 scalar_size = 0;
2949 
2950 			if (reg->type != SCALAR_VALUE) {
2951 				verbose_linfo(env, env->insn_idx, "; ");
2952 				verbose(env, "invalid size of register fill\n");
2953 				return -EACCES;
2954 			}
2955 
2956 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2957 			if (dst_regno < 0)
2958 				return 0;
2959 
2960 			for (i = BPF_REG_SIZE; i > 0 && stype[i - 1] == STACK_SPILL; i--)
2961 				scalar_size++;
2962 
2963 			if (!(off % BPF_REG_SIZE) && size == scalar_size) {
2964 				/* The earlier check_reg_arg() has decided the
2965 				 * subreg_def for this insn.  Save it first.
2966 				 */
2967 				s32 subreg_def = state->regs[dst_regno].subreg_def;
2968 
2969 				state->regs[dst_regno] = *reg;
2970 				state->regs[dst_regno].subreg_def = subreg_def;
2971 			} else {
2972 				for (i = 0; i < size; i++) {
2973 					type = stype[(slot - i) % BPF_REG_SIZE];
2974 					if (type == STACK_SPILL)
2975 						continue;
2976 					if (type == STACK_MISC)
2977 						continue;
2978 					verbose(env, "invalid read from stack off %d+%d size %d\n",
2979 						off, i, size);
2980 					return -EACCES;
2981 				}
2982 				mark_reg_unknown(env, state->regs, dst_regno);
2983 			}
2984 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2985 			return 0;
2986 		}
2987 		for (i = 1; i < BPF_REG_SIZE; i++) {
2988 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2989 				verbose(env, "corrupted spill memory\n");
2990 				return -EACCES;
2991 			}
2992 		}
2993 
2994 		if (dst_regno >= 0) {
2995 			/* restore register state from stack */
2996 			state->regs[dst_regno] = *reg;
2997 			/* mark reg as written since spilled pointer state likely
2998 			 * has its liveness marks cleared by is_state_visited()
2999 			 * which resets stack/reg liveness for state transitions
3000 			 */
3001 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3002 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3003 			/* If dst_regno==-1, the caller is asking us whether
3004 			 * it is acceptable to use this value as a SCALAR_VALUE
3005 			 * (e.g. for XADD).
3006 			 * We must not allow unprivileged callers to do that
3007 			 * with spilled pointers.
3008 			 */
3009 			verbose(env, "leaking pointer from stack off %d\n",
3010 				off);
3011 			return -EACCES;
3012 		}
3013 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3014 	} else {
3015 		for (i = 0; i < size; i++) {
3016 			type = stype[(slot - i) % BPF_REG_SIZE];
3017 			if (type == STACK_MISC)
3018 				continue;
3019 			if (type == STACK_ZERO)
3020 				continue;
3021 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3022 				off, i, size);
3023 			return -EACCES;
3024 		}
3025 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3026 		if (dst_regno >= 0)
3027 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3028 	}
3029 	return 0;
3030 }
3031 
3032 enum stack_access_src {
3033 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3034 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3035 };
3036 
3037 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3038 					 int regno, int off, int access_size,
3039 					 bool zero_size_allowed,
3040 					 enum stack_access_src type,
3041 					 struct bpf_call_arg_meta *meta);
3042 
3043 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3044 {
3045 	return cur_regs(env) + regno;
3046 }
3047 
3048 /* Read the stack at 'ptr_regno + off' and put the result into the register
3049  * 'dst_regno'.
3050  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3051  * but not its variable offset.
3052  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3053  *
3054  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3055  * filling registers (i.e. reads of spilled register cannot be detected when
3056  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3057  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3058  * offset; for a fixed offset check_stack_read_fixed_off should be used
3059  * instead.
3060  */
3061 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3062 				    int ptr_regno, int off, int size, int dst_regno)
3063 {
3064 	/* The state of the source register. */
3065 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3066 	struct bpf_func_state *ptr_state = func(env, reg);
3067 	int err;
3068 	int min_off, max_off;
3069 
3070 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3071 	 */
3072 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3073 					    false, ACCESS_DIRECT, NULL);
3074 	if (err)
3075 		return err;
3076 
3077 	min_off = reg->smin_value + off;
3078 	max_off = reg->smax_value + off;
3079 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3080 	return 0;
3081 }
3082 
3083 /* check_stack_read dispatches to check_stack_read_fixed_off or
3084  * check_stack_read_var_off.
3085  *
3086  * The caller must ensure that the offset falls within the allocated stack
3087  * bounds.
3088  *
3089  * 'dst_regno' is a register which will receive the value from the stack. It
3090  * can be -1, meaning that the read value is not going to a register.
3091  */
3092 static int check_stack_read(struct bpf_verifier_env *env,
3093 			    int ptr_regno, int off, int size,
3094 			    int dst_regno)
3095 {
3096 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3097 	struct bpf_func_state *state = func(env, reg);
3098 	int err;
3099 	/* Some accesses are only permitted with a static offset. */
3100 	bool var_off = !tnum_is_const(reg->var_off);
3101 
3102 	/* The offset is required to be static when reads don't go to a
3103 	 * register, in order to not leak pointers (see
3104 	 * check_stack_read_fixed_off).
3105 	 */
3106 	if (dst_regno < 0 && var_off) {
3107 		char tn_buf[48];
3108 
3109 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3110 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3111 			tn_buf, off, size);
3112 		return -EACCES;
3113 	}
3114 	/* Variable offset is prohibited for unprivileged mode for simplicity
3115 	 * since it requires corresponding support in Spectre masking for stack
3116 	 * ALU. See also retrieve_ptr_limit().
3117 	 */
3118 	if (!env->bypass_spec_v1 && var_off) {
3119 		char tn_buf[48];
3120 
3121 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3122 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3123 				ptr_regno, tn_buf);
3124 		return -EACCES;
3125 	}
3126 
3127 	if (!var_off) {
3128 		off += reg->var_off.value;
3129 		err = check_stack_read_fixed_off(env, state, off, size,
3130 						 dst_regno);
3131 	} else {
3132 		/* Variable offset stack reads need more conservative handling
3133 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3134 		 * branch.
3135 		 */
3136 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3137 					       dst_regno);
3138 	}
3139 	return err;
3140 }
3141 
3142 
3143 /* check_stack_write dispatches to check_stack_write_fixed_off or
3144  * check_stack_write_var_off.
3145  *
3146  * 'ptr_regno' is the register used as a pointer into the stack.
3147  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3148  * 'value_regno' is the register whose value we're writing to the stack. It can
3149  * be -1, meaning that we're not writing from a register.
3150  *
3151  * The caller must ensure that the offset falls within the maximum stack size.
3152  */
3153 static int check_stack_write(struct bpf_verifier_env *env,
3154 			     int ptr_regno, int off, int size,
3155 			     int value_regno, int insn_idx)
3156 {
3157 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3158 	struct bpf_func_state *state = func(env, reg);
3159 	int err;
3160 
3161 	if (tnum_is_const(reg->var_off)) {
3162 		off += reg->var_off.value;
3163 		err = check_stack_write_fixed_off(env, state, off, size,
3164 						  value_regno, insn_idx);
3165 	} else {
3166 		/* Variable offset stack reads need more conservative handling
3167 		 * than fixed offset ones.
3168 		 */
3169 		err = check_stack_write_var_off(env, state,
3170 						ptr_regno, off, size,
3171 						value_regno, insn_idx);
3172 	}
3173 	return err;
3174 }
3175 
3176 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3177 				 int off, int size, enum bpf_access_type type)
3178 {
3179 	struct bpf_reg_state *regs = cur_regs(env);
3180 	struct bpf_map *map = regs[regno].map_ptr;
3181 	u32 cap = bpf_map_flags_to_cap(map);
3182 
3183 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3184 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3185 			map->value_size, off, size);
3186 		return -EACCES;
3187 	}
3188 
3189 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3190 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3191 			map->value_size, off, size);
3192 		return -EACCES;
3193 	}
3194 
3195 	return 0;
3196 }
3197 
3198 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3199 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3200 			      int off, int size, u32 mem_size,
3201 			      bool zero_size_allowed)
3202 {
3203 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3204 	struct bpf_reg_state *reg;
3205 
3206 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3207 		return 0;
3208 
3209 	reg = &cur_regs(env)[regno];
3210 	switch (reg->type) {
3211 	case PTR_TO_MAP_KEY:
3212 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3213 			mem_size, off, size);
3214 		break;
3215 	case PTR_TO_MAP_VALUE:
3216 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3217 			mem_size, off, size);
3218 		break;
3219 	case PTR_TO_PACKET:
3220 	case PTR_TO_PACKET_META:
3221 	case PTR_TO_PACKET_END:
3222 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3223 			off, size, regno, reg->id, off, mem_size);
3224 		break;
3225 	case PTR_TO_MEM:
3226 	default:
3227 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3228 			mem_size, off, size);
3229 	}
3230 
3231 	return -EACCES;
3232 }
3233 
3234 /* check read/write into a memory region with possible variable offset */
3235 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3236 				   int off, int size, u32 mem_size,
3237 				   bool zero_size_allowed)
3238 {
3239 	struct bpf_verifier_state *vstate = env->cur_state;
3240 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3241 	struct bpf_reg_state *reg = &state->regs[regno];
3242 	int err;
3243 
3244 	/* We may have adjusted the register pointing to memory region, so we
3245 	 * need to try adding each of min_value and max_value to off
3246 	 * to make sure our theoretical access will be safe.
3247 	 */
3248 	if (env->log.level & BPF_LOG_LEVEL)
3249 		print_verifier_state(env, state);
3250 
3251 	/* The minimum value is only important with signed
3252 	 * comparisons where we can't assume the floor of a
3253 	 * value is 0.  If we are using signed variables for our
3254 	 * index'es we need to make sure that whatever we use
3255 	 * will have a set floor within our range.
3256 	 */
3257 	if (reg->smin_value < 0 &&
3258 	    (reg->smin_value == S64_MIN ||
3259 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3260 	      reg->smin_value + off < 0)) {
3261 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3262 			regno);
3263 		return -EACCES;
3264 	}
3265 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3266 				 mem_size, zero_size_allowed);
3267 	if (err) {
3268 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3269 			regno);
3270 		return err;
3271 	}
3272 
3273 	/* If we haven't set a max value then we need to bail since we can't be
3274 	 * sure we won't do bad things.
3275 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3276 	 */
3277 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3278 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3279 			regno);
3280 		return -EACCES;
3281 	}
3282 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3283 				 mem_size, zero_size_allowed);
3284 	if (err) {
3285 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3286 			regno);
3287 		return err;
3288 	}
3289 
3290 	return 0;
3291 }
3292 
3293 /* check read/write into a map element with possible variable offset */
3294 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3295 			    int off, int size, bool zero_size_allowed)
3296 {
3297 	struct bpf_verifier_state *vstate = env->cur_state;
3298 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3299 	struct bpf_reg_state *reg = &state->regs[regno];
3300 	struct bpf_map *map = reg->map_ptr;
3301 	int err;
3302 
3303 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3304 				      zero_size_allowed);
3305 	if (err)
3306 		return err;
3307 
3308 	if (map_value_has_spin_lock(map)) {
3309 		u32 lock = map->spin_lock_off;
3310 
3311 		/* if any part of struct bpf_spin_lock can be touched by
3312 		 * load/store reject this program.
3313 		 * To check that [x1, x2) overlaps with [y1, y2)
3314 		 * it is sufficient to check x1 < y2 && y1 < x2.
3315 		 */
3316 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3317 		     lock < reg->umax_value + off + size) {
3318 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3319 			return -EACCES;
3320 		}
3321 	}
3322 	if (map_value_has_timer(map)) {
3323 		u32 t = map->timer_off;
3324 
3325 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3326 		     t < reg->umax_value + off + size) {
3327 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3328 			return -EACCES;
3329 		}
3330 	}
3331 	return err;
3332 }
3333 
3334 #define MAX_PACKET_OFF 0xffff
3335 
3336 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3337 {
3338 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3339 }
3340 
3341 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3342 				       const struct bpf_call_arg_meta *meta,
3343 				       enum bpf_access_type t)
3344 {
3345 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3346 
3347 	switch (prog_type) {
3348 	/* Program types only with direct read access go here! */
3349 	case BPF_PROG_TYPE_LWT_IN:
3350 	case BPF_PROG_TYPE_LWT_OUT:
3351 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3352 	case BPF_PROG_TYPE_SK_REUSEPORT:
3353 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3354 	case BPF_PROG_TYPE_CGROUP_SKB:
3355 		if (t == BPF_WRITE)
3356 			return false;
3357 		fallthrough;
3358 
3359 	/* Program types with direct read + write access go here! */
3360 	case BPF_PROG_TYPE_SCHED_CLS:
3361 	case BPF_PROG_TYPE_SCHED_ACT:
3362 	case BPF_PROG_TYPE_XDP:
3363 	case BPF_PROG_TYPE_LWT_XMIT:
3364 	case BPF_PROG_TYPE_SK_SKB:
3365 	case BPF_PROG_TYPE_SK_MSG:
3366 		if (meta)
3367 			return meta->pkt_access;
3368 
3369 		env->seen_direct_write = true;
3370 		return true;
3371 
3372 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3373 		if (t == BPF_WRITE)
3374 			env->seen_direct_write = true;
3375 
3376 		return true;
3377 
3378 	default:
3379 		return false;
3380 	}
3381 }
3382 
3383 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3384 			       int size, bool zero_size_allowed)
3385 {
3386 	struct bpf_reg_state *regs = cur_regs(env);
3387 	struct bpf_reg_state *reg = &regs[regno];
3388 	int err;
3389 
3390 	/* We may have added a variable offset to the packet pointer; but any
3391 	 * reg->range we have comes after that.  We are only checking the fixed
3392 	 * offset.
3393 	 */
3394 
3395 	/* We don't allow negative numbers, because we aren't tracking enough
3396 	 * detail to prove they're safe.
3397 	 */
3398 	if (reg->smin_value < 0) {
3399 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3400 			regno);
3401 		return -EACCES;
3402 	}
3403 
3404 	err = reg->range < 0 ? -EINVAL :
3405 	      __check_mem_access(env, regno, off, size, reg->range,
3406 				 zero_size_allowed);
3407 	if (err) {
3408 		verbose(env, "R%d offset is outside of the packet\n", regno);
3409 		return err;
3410 	}
3411 
3412 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3413 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3414 	 * otherwise find_good_pkt_pointers would have refused to set range info
3415 	 * that __check_mem_access would have rejected this pkt access.
3416 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3417 	 */
3418 	env->prog->aux->max_pkt_offset =
3419 		max_t(u32, env->prog->aux->max_pkt_offset,
3420 		      off + reg->umax_value + size - 1);
3421 
3422 	return err;
3423 }
3424 
3425 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3426 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3427 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3428 			    struct btf **btf, u32 *btf_id)
3429 {
3430 	struct bpf_insn_access_aux info = {
3431 		.reg_type = *reg_type,
3432 		.log = &env->log,
3433 	};
3434 
3435 	if (env->ops->is_valid_access &&
3436 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3437 		/* A non zero info.ctx_field_size indicates that this field is a
3438 		 * candidate for later verifier transformation to load the whole
3439 		 * field and then apply a mask when accessed with a narrower
3440 		 * access than actual ctx access size. A zero info.ctx_field_size
3441 		 * will only allow for whole field access and rejects any other
3442 		 * type of narrower access.
3443 		 */
3444 		*reg_type = info.reg_type;
3445 
3446 		if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3447 			*btf = info.btf;
3448 			*btf_id = info.btf_id;
3449 		} else {
3450 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3451 		}
3452 		/* remember the offset of last byte accessed in ctx */
3453 		if (env->prog->aux->max_ctx_offset < off + size)
3454 			env->prog->aux->max_ctx_offset = off + size;
3455 		return 0;
3456 	}
3457 
3458 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3459 	return -EACCES;
3460 }
3461 
3462 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3463 				  int size)
3464 {
3465 	if (size < 0 || off < 0 ||
3466 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3467 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3468 			off, size);
3469 		return -EACCES;
3470 	}
3471 	return 0;
3472 }
3473 
3474 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3475 			     u32 regno, int off, int size,
3476 			     enum bpf_access_type t)
3477 {
3478 	struct bpf_reg_state *regs = cur_regs(env);
3479 	struct bpf_reg_state *reg = &regs[regno];
3480 	struct bpf_insn_access_aux info = {};
3481 	bool valid;
3482 
3483 	if (reg->smin_value < 0) {
3484 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3485 			regno);
3486 		return -EACCES;
3487 	}
3488 
3489 	switch (reg->type) {
3490 	case PTR_TO_SOCK_COMMON:
3491 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3492 		break;
3493 	case PTR_TO_SOCKET:
3494 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3495 		break;
3496 	case PTR_TO_TCP_SOCK:
3497 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3498 		break;
3499 	case PTR_TO_XDP_SOCK:
3500 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3501 		break;
3502 	default:
3503 		valid = false;
3504 	}
3505 
3506 
3507 	if (valid) {
3508 		env->insn_aux_data[insn_idx].ctx_field_size =
3509 			info.ctx_field_size;
3510 		return 0;
3511 	}
3512 
3513 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3514 		regno, reg_type_str[reg->type], off, size);
3515 
3516 	return -EACCES;
3517 }
3518 
3519 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3520 {
3521 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3522 }
3523 
3524 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3525 {
3526 	const struct bpf_reg_state *reg = reg_state(env, regno);
3527 
3528 	return reg->type == PTR_TO_CTX;
3529 }
3530 
3531 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3532 {
3533 	const struct bpf_reg_state *reg = reg_state(env, regno);
3534 
3535 	return type_is_sk_pointer(reg->type);
3536 }
3537 
3538 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3539 {
3540 	const struct bpf_reg_state *reg = reg_state(env, regno);
3541 
3542 	return type_is_pkt_pointer(reg->type);
3543 }
3544 
3545 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3546 {
3547 	const struct bpf_reg_state *reg = reg_state(env, regno);
3548 
3549 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3550 	return reg->type == PTR_TO_FLOW_KEYS;
3551 }
3552 
3553 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3554 				   const struct bpf_reg_state *reg,
3555 				   int off, int size, bool strict)
3556 {
3557 	struct tnum reg_off;
3558 	int ip_align;
3559 
3560 	/* Byte size accesses are always allowed. */
3561 	if (!strict || size == 1)
3562 		return 0;
3563 
3564 	/* For platforms that do not have a Kconfig enabling
3565 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3566 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3567 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3568 	 * to this code only in strict mode where we want to emulate
3569 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3570 	 * unconditional IP align value of '2'.
3571 	 */
3572 	ip_align = 2;
3573 
3574 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3575 	if (!tnum_is_aligned(reg_off, size)) {
3576 		char tn_buf[48];
3577 
3578 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3579 		verbose(env,
3580 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3581 			ip_align, tn_buf, reg->off, off, size);
3582 		return -EACCES;
3583 	}
3584 
3585 	return 0;
3586 }
3587 
3588 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3589 				       const struct bpf_reg_state *reg,
3590 				       const char *pointer_desc,
3591 				       int off, int size, bool strict)
3592 {
3593 	struct tnum reg_off;
3594 
3595 	/* Byte size accesses are always allowed. */
3596 	if (!strict || size == 1)
3597 		return 0;
3598 
3599 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3600 	if (!tnum_is_aligned(reg_off, size)) {
3601 		char tn_buf[48];
3602 
3603 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3604 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3605 			pointer_desc, tn_buf, reg->off, off, size);
3606 		return -EACCES;
3607 	}
3608 
3609 	return 0;
3610 }
3611 
3612 static int check_ptr_alignment(struct bpf_verifier_env *env,
3613 			       const struct bpf_reg_state *reg, int off,
3614 			       int size, bool strict_alignment_once)
3615 {
3616 	bool strict = env->strict_alignment || strict_alignment_once;
3617 	const char *pointer_desc = "";
3618 
3619 	switch (reg->type) {
3620 	case PTR_TO_PACKET:
3621 	case PTR_TO_PACKET_META:
3622 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3623 		 * right in front, treat it the very same way.
3624 		 */
3625 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3626 	case PTR_TO_FLOW_KEYS:
3627 		pointer_desc = "flow keys ";
3628 		break;
3629 	case PTR_TO_MAP_KEY:
3630 		pointer_desc = "key ";
3631 		break;
3632 	case PTR_TO_MAP_VALUE:
3633 		pointer_desc = "value ";
3634 		break;
3635 	case PTR_TO_CTX:
3636 		pointer_desc = "context ";
3637 		break;
3638 	case PTR_TO_STACK:
3639 		pointer_desc = "stack ";
3640 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3641 		 * and check_stack_read_fixed_off() relies on stack accesses being
3642 		 * aligned.
3643 		 */
3644 		strict = true;
3645 		break;
3646 	case PTR_TO_SOCKET:
3647 		pointer_desc = "sock ";
3648 		break;
3649 	case PTR_TO_SOCK_COMMON:
3650 		pointer_desc = "sock_common ";
3651 		break;
3652 	case PTR_TO_TCP_SOCK:
3653 		pointer_desc = "tcp_sock ";
3654 		break;
3655 	case PTR_TO_XDP_SOCK:
3656 		pointer_desc = "xdp_sock ";
3657 		break;
3658 	default:
3659 		break;
3660 	}
3661 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3662 					   strict);
3663 }
3664 
3665 static int update_stack_depth(struct bpf_verifier_env *env,
3666 			      const struct bpf_func_state *func,
3667 			      int off)
3668 {
3669 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3670 
3671 	if (stack >= -off)
3672 		return 0;
3673 
3674 	/* update known max for given subprogram */
3675 	env->subprog_info[func->subprogno].stack_depth = -off;
3676 	return 0;
3677 }
3678 
3679 /* starting from main bpf function walk all instructions of the function
3680  * and recursively walk all callees that given function can call.
3681  * Ignore jump and exit insns.
3682  * Since recursion is prevented by check_cfg() this algorithm
3683  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3684  */
3685 static int check_max_stack_depth(struct bpf_verifier_env *env)
3686 {
3687 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3688 	struct bpf_subprog_info *subprog = env->subprog_info;
3689 	struct bpf_insn *insn = env->prog->insnsi;
3690 	bool tail_call_reachable = false;
3691 	int ret_insn[MAX_CALL_FRAMES];
3692 	int ret_prog[MAX_CALL_FRAMES];
3693 	int j;
3694 
3695 process_func:
3696 	/* protect against potential stack overflow that might happen when
3697 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3698 	 * depth for such case down to 256 so that the worst case scenario
3699 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3700 	 * 8k).
3701 	 *
3702 	 * To get the idea what might happen, see an example:
3703 	 * func1 -> sub rsp, 128
3704 	 *  subfunc1 -> sub rsp, 256
3705 	 *  tailcall1 -> add rsp, 256
3706 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3707 	 *   subfunc2 -> sub rsp, 64
3708 	 *   subfunc22 -> sub rsp, 128
3709 	 *   tailcall2 -> add rsp, 128
3710 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3711 	 *
3712 	 * tailcall will unwind the current stack frame but it will not get rid
3713 	 * of caller's stack as shown on the example above.
3714 	 */
3715 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3716 		verbose(env,
3717 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3718 			depth);
3719 		return -EACCES;
3720 	}
3721 	/* round up to 32-bytes, since this is granularity
3722 	 * of interpreter stack size
3723 	 */
3724 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3725 	if (depth > MAX_BPF_STACK) {
3726 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3727 			frame + 1, depth);
3728 		return -EACCES;
3729 	}
3730 continue_func:
3731 	subprog_end = subprog[idx + 1].start;
3732 	for (; i < subprog_end; i++) {
3733 		int next_insn;
3734 
3735 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3736 			continue;
3737 		/* remember insn and function to return to */
3738 		ret_insn[frame] = i + 1;
3739 		ret_prog[frame] = idx;
3740 
3741 		/* find the callee */
3742 		next_insn = i + insn[i].imm + 1;
3743 		idx = find_subprog(env, next_insn);
3744 		if (idx < 0) {
3745 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3746 				  next_insn);
3747 			return -EFAULT;
3748 		}
3749 		if (subprog[idx].is_async_cb) {
3750 			if (subprog[idx].has_tail_call) {
3751 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3752 				return -EFAULT;
3753 			}
3754 			 /* async callbacks don't increase bpf prog stack size */
3755 			continue;
3756 		}
3757 		i = next_insn;
3758 
3759 		if (subprog[idx].has_tail_call)
3760 			tail_call_reachable = true;
3761 
3762 		frame++;
3763 		if (frame >= MAX_CALL_FRAMES) {
3764 			verbose(env, "the call stack of %d frames is too deep !\n",
3765 				frame);
3766 			return -E2BIG;
3767 		}
3768 		goto process_func;
3769 	}
3770 	/* if tail call got detected across bpf2bpf calls then mark each of the
3771 	 * currently present subprog frames as tail call reachable subprogs;
3772 	 * this info will be utilized by JIT so that we will be preserving the
3773 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3774 	 */
3775 	if (tail_call_reachable)
3776 		for (j = 0; j < frame; j++)
3777 			subprog[ret_prog[j]].tail_call_reachable = true;
3778 	if (subprog[0].tail_call_reachable)
3779 		env->prog->aux->tail_call_reachable = true;
3780 
3781 	/* end of for() loop means the last insn of the 'subprog'
3782 	 * was reached. Doesn't matter whether it was JA or EXIT
3783 	 */
3784 	if (frame == 0)
3785 		return 0;
3786 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3787 	frame--;
3788 	i = ret_insn[frame];
3789 	idx = ret_prog[frame];
3790 	goto continue_func;
3791 }
3792 
3793 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3794 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3795 				  const struct bpf_insn *insn, int idx)
3796 {
3797 	int start = idx + insn->imm + 1, subprog;
3798 
3799 	subprog = find_subprog(env, start);
3800 	if (subprog < 0) {
3801 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3802 			  start);
3803 		return -EFAULT;
3804 	}
3805 	return env->subprog_info[subprog].stack_depth;
3806 }
3807 #endif
3808 
3809 int check_ctx_reg(struct bpf_verifier_env *env,
3810 		  const struct bpf_reg_state *reg, int regno)
3811 {
3812 	/* Access to ctx or passing it to a helper is only allowed in
3813 	 * its original, unmodified form.
3814 	 */
3815 
3816 	if (reg->off) {
3817 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3818 			regno, reg->off);
3819 		return -EACCES;
3820 	}
3821 
3822 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3823 		char tn_buf[48];
3824 
3825 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3826 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3827 		return -EACCES;
3828 	}
3829 
3830 	return 0;
3831 }
3832 
3833 static int __check_buffer_access(struct bpf_verifier_env *env,
3834 				 const char *buf_info,
3835 				 const struct bpf_reg_state *reg,
3836 				 int regno, int off, int size)
3837 {
3838 	if (off < 0) {
3839 		verbose(env,
3840 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3841 			regno, buf_info, off, size);
3842 		return -EACCES;
3843 	}
3844 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3845 		char tn_buf[48];
3846 
3847 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3848 		verbose(env,
3849 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3850 			regno, off, tn_buf);
3851 		return -EACCES;
3852 	}
3853 
3854 	return 0;
3855 }
3856 
3857 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3858 				  const struct bpf_reg_state *reg,
3859 				  int regno, int off, int size)
3860 {
3861 	int err;
3862 
3863 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3864 	if (err)
3865 		return err;
3866 
3867 	if (off + size > env->prog->aux->max_tp_access)
3868 		env->prog->aux->max_tp_access = off + size;
3869 
3870 	return 0;
3871 }
3872 
3873 static int check_buffer_access(struct bpf_verifier_env *env,
3874 			       const struct bpf_reg_state *reg,
3875 			       int regno, int off, int size,
3876 			       bool zero_size_allowed,
3877 			       const char *buf_info,
3878 			       u32 *max_access)
3879 {
3880 	int err;
3881 
3882 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3883 	if (err)
3884 		return err;
3885 
3886 	if (off + size > *max_access)
3887 		*max_access = off + size;
3888 
3889 	return 0;
3890 }
3891 
3892 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3893 static void zext_32_to_64(struct bpf_reg_state *reg)
3894 {
3895 	reg->var_off = tnum_subreg(reg->var_off);
3896 	__reg_assign_32_into_64(reg);
3897 }
3898 
3899 /* truncate register to smaller size (in bytes)
3900  * must be called with size < BPF_REG_SIZE
3901  */
3902 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3903 {
3904 	u64 mask;
3905 
3906 	/* clear high bits in bit representation */
3907 	reg->var_off = tnum_cast(reg->var_off, size);
3908 
3909 	/* fix arithmetic bounds */
3910 	mask = ((u64)1 << (size * 8)) - 1;
3911 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3912 		reg->umin_value &= mask;
3913 		reg->umax_value &= mask;
3914 	} else {
3915 		reg->umin_value = 0;
3916 		reg->umax_value = mask;
3917 	}
3918 	reg->smin_value = reg->umin_value;
3919 	reg->smax_value = reg->umax_value;
3920 
3921 	/* If size is smaller than 32bit register the 32bit register
3922 	 * values are also truncated so we push 64-bit bounds into
3923 	 * 32-bit bounds. Above were truncated < 32-bits already.
3924 	 */
3925 	if (size >= 4)
3926 		return;
3927 	__reg_combine_64_into_32(reg);
3928 }
3929 
3930 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3931 {
3932 	return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3933 }
3934 
3935 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3936 {
3937 	void *ptr;
3938 	u64 addr;
3939 	int err;
3940 
3941 	err = map->ops->map_direct_value_addr(map, &addr, off);
3942 	if (err)
3943 		return err;
3944 	ptr = (void *)(long)addr + off;
3945 
3946 	switch (size) {
3947 	case sizeof(u8):
3948 		*val = (u64)*(u8 *)ptr;
3949 		break;
3950 	case sizeof(u16):
3951 		*val = (u64)*(u16 *)ptr;
3952 		break;
3953 	case sizeof(u32):
3954 		*val = (u64)*(u32 *)ptr;
3955 		break;
3956 	case sizeof(u64):
3957 		*val = *(u64 *)ptr;
3958 		break;
3959 	default:
3960 		return -EINVAL;
3961 	}
3962 	return 0;
3963 }
3964 
3965 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3966 				   struct bpf_reg_state *regs,
3967 				   int regno, int off, int size,
3968 				   enum bpf_access_type atype,
3969 				   int value_regno)
3970 {
3971 	struct bpf_reg_state *reg = regs + regno;
3972 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3973 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3974 	u32 btf_id;
3975 	int ret;
3976 
3977 	if (off < 0) {
3978 		verbose(env,
3979 			"R%d is ptr_%s invalid negative access: off=%d\n",
3980 			regno, tname, off);
3981 		return -EACCES;
3982 	}
3983 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3984 		char tn_buf[48];
3985 
3986 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3987 		verbose(env,
3988 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3989 			regno, tname, off, tn_buf);
3990 		return -EACCES;
3991 	}
3992 
3993 	if (env->ops->btf_struct_access) {
3994 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3995 						  off, size, atype, &btf_id);
3996 	} else {
3997 		if (atype != BPF_READ) {
3998 			verbose(env, "only read is supported\n");
3999 			return -EACCES;
4000 		}
4001 
4002 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4003 					atype, &btf_id);
4004 	}
4005 
4006 	if (ret < 0)
4007 		return ret;
4008 
4009 	if (atype == BPF_READ && value_regno >= 0)
4010 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4011 
4012 	return 0;
4013 }
4014 
4015 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4016 				   struct bpf_reg_state *regs,
4017 				   int regno, int off, int size,
4018 				   enum bpf_access_type atype,
4019 				   int value_regno)
4020 {
4021 	struct bpf_reg_state *reg = regs + regno;
4022 	struct bpf_map *map = reg->map_ptr;
4023 	const struct btf_type *t;
4024 	const char *tname;
4025 	u32 btf_id;
4026 	int ret;
4027 
4028 	if (!btf_vmlinux) {
4029 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4030 		return -ENOTSUPP;
4031 	}
4032 
4033 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4034 		verbose(env, "map_ptr access not supported for map type %d\n",
4035 			map->map_type);
4036 		return -ENOTSUPP;
4037 	}
4038 
4039 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4040 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4041 
4042 	if (!env->allow_ptr_to_map_access) {
4043 		verbose(env,
4044 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4045 			tname);
4046 		return -EPERM;
4047 	}
4048 
4049 	if (off < 0) {
4050 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4051 			regno, tname, off);
4052 		return -EACCES;
4053 	}
4054 
4055 	if (atype != BPF_READ) {
4056 		verbose(env, "only read from %s is supported\n", tname);
4057 		return -EACCES;
4058 	}
4059 
4060 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4061 	if (ret < 0)
4062 		return ret;
4063 
4064 	if (value_regno >= 0)
4065 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4066 
4067 	return 0;
4068 }
4069 
4070 /* Check that the stack access at the given offset is within bounds. The
4071  * maximum valid offset is -1.
4072  *
4073  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4074  * -state->allocated_stack for reads.
4075  */
4076 static int check_stack_slot_within_bounds(int off,
4077 					  struct bpf_func_state *state,
4078 					  enum bpf_access_type t)
4079 {
4080 	int min_valid_off;
4081 
4082 	if (t == BPF_WRITE)
4083 		min_valid_off = -MAX_BPF_STACK;
4084 	else
4085 		min_valid_off = -state->allocated_stack;
4086 
4087 	if (off < min_valid_off || off > -1)
4088 		return -EACCES;
4089 	return 0;
4090 }
4091 
4092 /* Check that the stack access at 'regno + off' falls within the maximum stack
4093  * bounds.
4094  *
4095  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4096  */
4097 static int check_stack_access_within_bounds(
4098 		struct bpf_verifier_env *env,
4099 		int regno, int off, int access_size,
4100 		enum stack_access_src src, enum bpf_access_type type)
4101 {
4102 	struct bpf_reg_state *regs = cur_regs(env);
4103 	struct bpf_reg_state *reg = regs + regno;
4104 	struct bpf_func_state *state = func(env, reg);
4105 	int min_off, max_off;
4106 	int err;
4107 	char *err_extra;
4108 
4109 	if (src == ACCESS_HELPER)
4110 		/* We don't know if helpers are reading or writing (or both). */
4111 		err_extra = " indirect access to";
4112 	else if (type == BPF_READ)
4113 		err_extra = " read from";
4114 	else
4115 		err_extra = " write to";
4116 
4117 	if (tnum_is_const(reg->var_off)) {
4118 		min_off = reg->var_off.value + off;
4119 		if (access_size > 0)
4120 			max_off = min_off + access_size - 1;
4121 		else
4122 			max_off = min_off;
4123 	} else {
4124 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4125 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4126 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4127 				err_extra, regno);
4128 			return -EACCES;
4129 		}
4130 		min_off = reg->smin_value + off;
4131 		if (access_size > 0)
4132 			max_off = reg->smax_value + off + access_size - 1;
4133 		else
4134 			max_off = min_off;
4135 	}
4136 
4137 	err = check_stack_slot_within_bounds(min_off, state, type);
4138 	if (!err)
4139 		err = check_stack_slot_within_bounds(max_off, state, type);
4140 
4141 	if (err) {
4142 		if (tnum_is_const(reg->var_off)) {
4143 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4144 				err_extra, regno, off, access_size);
4145 		} else {
4146 			char tn_buf[48];
4147 
4148 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4149 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4150 				err_extra, regno, tn_buf, access_size);
4151 		}
4152 	}
4153 	return err;
4154 }
4155 
4156 /* check whether memory at (regno + off) is accessible for t = (read | write)
4157  * if t==write, value_regno is a register which value is stored into memory
4158  * if t==read, value_regno is a register which will receive the value from memory
4159  * if t==write && value_regno==-1, some unknown value is stored into memory
4160  * if t==read && value_regno==-1, don't care what we read from memory
4161  */
4162 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4163 			    int off, int bpf_size, enum bpf_access_type t,
4164 			    int value_regno, bool strict_alignment_once)
4165 {
4166 	struct bpf_reg_state *regs = cur_regs(env);
4167 	struct bpf_reg_state *reg = regs + regno;
4168 	struct bpf_func_state *state;
4169 	int size, err = 0;
4170 
4171 	size = bpf_size_to_bytes(bpf_size);
4172 	if (size < 0)
4173 		return size;
4174 
4175 	/* alignment checks will add in reg->off themselves */
4176 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4177 	if (err)
4178 		return err;
4179 
4180 	/* for access checks, reg->off is just part of off */
4181 	off += reg->off;
4182 
4183 	if (reg->type == PTR_TO_MAP_KEY) {
4184 		if (t == BPF_WRITE) {
4185 			verbose(env, "write to change key R%d not allowed\n", regno);
4186 			return -EACCES;
4187 		}
4188 
4189 		err = check_mem_region_access(env, regno, off, size,
4190 					      reg->map_ptr->key_size, false);
4191 		if (err)
4192 			return err;
4193 		if (value_regno >= 0)
4194 			mark_reg_unknown(env, regs, value_regno);
4195 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4196 		if (t == BPF_WRITE && value_regno >= 0 &&
4197 		    is_pointer_value(env, value_regno)) {
4198 			verbose(env, "R%d leaks addr into map\n", value_regno);
4199 			return -EACCES;
4200 		}
4201 		err = check_map_access_type(env, regno, off, size, t);
4202 		if (err)
4203 			return err;
4204 		err = check_map_access(env, regno, off, size, false);
4205 		if (!err && t == BPF_READ && value_regno >= 0) {
4206 			struct bpf_map *map = reg->map_ptr;
4207 
4208 			/* if map is read-only, track its contents as scalars */
4209 			if (tnum_is_const(reg->var_off) &&
4210 			    bpf_map_is_rdonly(map) &&
4211 			    map->ops->map_direct_value_addr) {
4212 				int map_off = off + reg->var_off.value;
4213 				u64 val = 0;
4214 
4215 				err = bpf_map_direct_read(map, map_off, size,
4216 							  &val);
4217 				if (err)
4218 					return err;
4219 
4220 				regs[value_regno].type = SCALAR_VALUE;
4221 				__mark_reg_known(&regs[value_regno], val);
4222 			} else {
4223 				mark_reg_unknown(env, regs, value_regno);
4224 			}
4225 		}
4226 	} else if (reg->type == PTR_TO_MEM) {
4227 		if (t == BPF_WRITE && value_regno >= 0 &&
4228 		    is_pointer_value(env, value_regno)) {
4229 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4230 			return -EACCES;
4231 		}
4232 		err = check_mem_region_access(env, regno, off, size,
4233 					      reg->mem_size, false);
4234 		if (!err && t == BPF_READ && value_regno >= 0)
4235 			mark_reg_unknown(env, regs, value_regno);
4236 	} else if (reg->type == PTR_TO_CTX) {
4237 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4238 		struct btf *btf = NULL;
4239 		u32 btf_id = 0;
4240 
4241 		if (t == BPF_WRITE && value_regno >= 0 &&
4242 		    is_pointer_value(env, value_regno)) {
4243 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4244 			return -EACCES;
4245 		}
4246 
4247 		err = check_ctx_reg(env, reg, regno);
4248 		if (err < 0)
4249 			return err;
4250 
4251 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4252 		if (err)
4253 			verbose_linfo(env, insn_idx, "; ");
4254 		if (!err && t == BPF_READ && value_regno >= 0) {
4255 			/* ctx access returns either a scalar, or a
4256 			 * PTR_TO_PACKET[_META,_END]. In the latter
4257 			 * case, we know the offset is zero.
4258 			 */
4259 			if (reg_type == SCALAR_VALUE) {
4260 				mark_reg_unknown(env, regs, value_regno);
4261 			} else {
4262 				mark_reg_known_zero(env, regs,
4263 						    value_regno);
4264 				if (reg_type_may_be_null(reg_type))
4265 					regs[value_regno].id = ++env->id_gen;
4266 				/* A load of ctx field could have different
4267 				 * actual load size with the one encoded in the
4268 				 * insn. When the dst is PTR, it is for sure not
4269 				 * a sub-register.
4270 				 */
4271 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4272 				if (reg_type == PTR_TO_BTF_ID ||
4273 				    reg_type == PTR_TO_BTF_ID_OR_NULL) {
4274 					regs[value_regno].btf = btf;
4275 					regs[value_regno].btf_id = btf_id;
4276 				}
4277 			}
4278 			regs[value_regno].type = reg_type;
4279 		}
4280 
4281 	} else if (reg->type == PTR_TO_STACK) {
4282 		/* Basic bounds checks. */
4283 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4284 		if (err)
4285 			return err;
4286 
4287 		state = func(env, reg);
4288 		err = update_stack_depth(env, state, off);
4289 		if (err)
4290 			return err;
4291 
4292 		if (t == BPF_READ)
4293 			err = check_stack_read(env, regno, off, size,
4294 					       value_regno);
4295 		else
4296 			err = check_stack_write(env, regno, off, size,
4297 						value_regno, insn_idx);
4298 	} else if (reg_is_pkt_pointer(reg)) {
4299 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4300 			verbose(env, "cannot write into packet\n");
4301 			return -EACCES;
4302 		}
4303 		if (t == BPF_WRITE && value_regno >= 0 &&
4304 		    is_pointer_value(env, value_regno)) {
4305 			verbose(env, "R%d leaks addr into packet\n",
4306 				value_regno);
4307 			return -EACCES;
4308 		}
4309 		err = check_packet_access(env, regno, off, size, false);
4310 		if (!err && t == BPF_READ && value_regno >= 0)
4311 			mark_reg_unknown(env, regs, value_regno);
4312 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4313 		if (t == BPF_WRITE && value_regno >= 0 &&
4314 		    is_pointer_value(env, value_regno)) {
4315 			verbose(env, "R%d leaks addr into flow keys\n",
4316 				value_regno);
4317 			return -EACCES;
4318 		}
4319 
4320 		err = check_flow_keys_access(env, off, size);
4321 		if (!err && t == BPF_READ && value_regno >= 0)
4322 			mark_reg_unknown(env, regs, value_regno);
4323 	} else if (type_is_sk_pointer(reg->type)) {
4324 		if (t == BPF_WRITE) {
4325 			verbose(env, "R%d cannot write into %s\n",
4326 				regno, reg_type_str[reg->type]);
4327 			return -EACCES;
4328 		}
4329 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4330 		if (!err && value_regno >= 0)
4331 			mark_reg_unknown(env, regs, value_regno);
4332 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4333 		err = check_tp_buffer_access(env, reg, regno, off, size);
4334 		if (!err && t == BPF_READ && value_regno >= 0)
4335 			mark_reg_unknown(env, regs, value_regno);
4336 	} else if (reg->type == PTR_TO_BTF_ID) {
4337 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4338 					      value_regno);
4339 	} else if (reg->type == CONST_PTR_TO_MAP) {
4340 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4341 					      value_regno);
4342 	} else if (reg->type == PTR_TO_RDONLY_BUF) {
4343 		if (t == BPF_WRITE) {
4344 			verbose(env, "R%d cannot write into %s\n",
4345 				regno, reg_type_str[reg->type]);
4346 			return -EACCES;
4347 		}
4348 		err = check_buffer_access(env, reg, regno, off, size, false,
4349 					  "rdonly",
4350 					  &env->prog->aux->max_rdonly_access);
4351 		if (!err && value_regno >= 0)
4352 			mark_reg_unknown(env, regs, value_regno);
4353 	} else if (reg->type == PTR_TO_RDWR_BUF) {
4354 		err = check_buffer_access(env, reg, regno, off, size, false,
4355 					  "rdwr",
4356 					  &env->prog->aux->max_rdwr_access);
4357 		if (!err && t == BPF_READ && value_regno >= 0)
4358 			mark_reg_unknown(env, regs, value_regno);
4359 	} else {
4360 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4361 			reg_type_str[reg->type]);
4362 		return -EACCES;
4363 	}
4364 
4365 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4366 	    regs[value_regno].type == SCALAR_VALUE) {
4367 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4368 		coerce_reg_to_size(&regs[value_regno], size);
4369 	}
4370 	return err;
4371 }
4372 
4373 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4374 {
4375 	int load_reg;
4376 	int err;
4377 
4378 	switch (insn->imm) {
4379 	case BPF_ADD:
4380 	case BPF_ADD | BPF_FETCH:
4381 	case BPF_AND:
4382 	case BPF_AND | BPF_FETCH:
4383 	case BPF_OR:
4384 	case BPF_OR | BPF_FETCH:
4385 	case BPF_XOR:
4386 	case BPF_XOR | BPF_FETCH:
4387 	case BPF_XCHG:
4388 	case BPF_CMPXCHG:
4389 		break;
4390 	default:
4391 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4392 		return -EINVAL;
4393 	}
4394 
4395 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4396 		verbose(env, "invalid atomic operand size\n");
4397 		return -EINVAL;
4398 	}
4399 
4400 	/* check src1 operand */
4401 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4402 	if (err)
4403 		return err;
4404 
4405 	/* check src2 operand */
4406 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4407 	if (err)
4408 		return err;
4409 
4410 	if (insn->imm == BPF_CMPXCHG) {
4411 		/* Check comparison of R0 with memory location */
4412 		err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4413 		if (err)
4414 			return err;
4415 	}
4416 
4417 	if (is_pointer_value(env, insn->src_reg)) {
4418 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4419 		return -EACCES;
4420 	}
4421 
4422 	if (is_ctx_reg(env, insn->dst_reg) ||
4423 	    is_pkt_reg(env, insn->dst_reg) ||
4424 	    is_flow_key_reg(env, insn->dst_reg) ||
4425 	    is_sk_reg(env, insn->dst_reg)) {
4426 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4427 			insn->dst_reg,
4428 			reg_type_str[reg_state(env, insn->dst_reg)->type]);
4429 		return -EACCES;
4430 	}
4431 
4432 	if (insn->imm & BPF_FETCH) {
4433 		if (insn->imm == BPF_CMPXCHG)
4434 			load_reg = BPF_REG_0;
4435 		else
4436 			load_reg = insn->src_reg;
4437 
4438 		/* check and record load of old value */
4439 		err = check_reg_arg(env, load_reg, DST_OP);
4440 		if (err)
4441 			return err;
4442 	} else {
4443 		/* This instruction accesses a memory location but doesn't
4444 		 * actually load it into a register.
4445 		 */
4446 		load_reg = -1;
4447 	}
4448 
4449 	/* check whether we can read the memory */
4450 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4451 			       BPF_SIZE(insn->code), BPF_READ, load_reg, true);
4452 	if (err)
4453 		return err;
4454 
4455 	/* check whether we can write into the same memory */
4456 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4457 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4458 	if (err)
4459 		return err;
4460 
4461 	return 0;
4462 }
4463 
4464 /* When register 'regno' is used to read the stack (either directly or through
4465  * a helper function) make sure that it's within stack boundary and, depending
4466  * on the access type, that all elements of the stack are initialized.
4467  *
4468  * 'off' includes 'regno->off', but not its dynamic part (if any).
4469  *
4470  * All registers that have been spilled on the stack in the slots within the
4471  * read offsets are marked as read.
4472  */
4473 static int check_stack_range_initialized(
4474 		struct bpf_verifier_env *env, int regno, int off,
4475 		int access_size, bool zero_size_allowed,
4476 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4477 {
4478 	struct bpf_reg_state *reg = reg_state(env, regno);
4479 	struct bpf_func_state *state = func(env, reg);
4480 	int err, min_off, max_off, i, j, slot, spi;
4481 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4482 	enum bpf_access_type bounds_check_type;
4483 	/* Some accesses can write anything into the stack, others are
4484 	 * read-only.
4485 	 */
4486 	bool clobber = false;
4487 
4488 	if (access_size == 0 && !zero_size_allowed) {
4489 		verbose(env, "invalid zero-sized read\n");
4490 		return -EACCES;
4491 	}
4492 
4493 	if (type == ACCESS_HELPER) {
4494 		/* The bounds checks for writes are more permissive than for
4495 		 * reads. However, if raw_mode is not set, we'll do extra
4496 		 * checks below.
4497 		 */
4498 		bounds_check_type = BPF_WRITE;
4499 		clobber = true;
4500 	} else {
4501 		bounds_check_type = BPF_READ;
4502 	}
4503 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4504 					       type, bounds_check_type);
4505 	if (err)
4506 		return err;
4507 
4508 
4509 	if (tnum_is_const(reg->var_off)) {
4510 		min_off = max_off = reg->var_off.value + off;
4511 	} else {
4512 		/* Variable offset is prohibited for unprivileged mode for
4513 		 * simplicity since it requires corresponding support in
4514 		 * Spectre masking for stack ALU.
4515 		 * See also retrieve_ptr_limit().
4516 		 */
4517 		if (!env->bypass_spec_v1) {
4518 			char tn_buf[48];
4519 
4520 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4521 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4522 				regno, err_extra, tn_buf);
4523 			return -EACCES;
4524 		}
4525 		/* Only initialized buffer on stack is allowed to be accessed
4526 		 * with variable offset. With uninitialized buffer it's hard to
4527 		 * guarantee that whole memory is marked as initialized on
4528 		 * helper return since specific bounds are unknown what may
4529 		 * cause uninitialized stack leaking.
4530 		 */
4531 		if (meta && meta->raw_mode)
4532 			meta = NULL;
4533 
4534 		min_off = reg->smin_value + off;
4535 		max_off = reg->smax_value + off;
4536 	}
4537 
4538 	if (meta && meta->raw_mode) {
4539 		meta->access_size = access_size;
4540 		meta->regno = regno;
4541 		return 0;
4542 	}
4543 
4544 	for (i = min_off; i < max_off + access_size; i++) {
4545 		u8 *stype;
4546 
4547 		slot = -i - 1;
4548 		spi = slot / BPF_REG_SIZE;
4549 		if (state->allocated_stack <= slot)
4550 			goto err;
4551 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4552 		if (*stype == STACK_MISC)
4553 			goto mark;
4554 		if (*stype == STACK_ZERO) {
4555 			if (clobber) {
4556 				/* helper can write anything into the stack */
4557 				*stype = STACK_MISC;
4558 			}
4559 			goto mark;
4560 		}
4561 
4562 		if (is_spilled_reg(&state->stack[spi]) &&
4563 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4564 			goto mark;
4565 
4566 		if (is_spilled_reg(&state->stack[spi]) &&
4567 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4568 		     env->allow_ptr_leaks)) {
4569 			if (clobber) {
4570 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4571 				for (j = 0; j < BPF_REG_SIZE; j++)
4572 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4573 			}
4574 			goto mark;
4575 		}
4576 
4577 err:
4578 		if (tnum_is_const(reg->var_off)) {
4579 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4580 				err_extra, regno, min_off, i - min_off, access_size);
4581 		} else {
4582 			char tn_buf[48];
4583 
4584 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4585 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4586 				err_extra, regno, tn_buf, i - min_off, access_size);
4587 		}
4588 		return -EACCES;
4589 mark:
4590 		/* reading any byte out of 8-byte 'spill_slot' will cause
4591 		 * the whole slot to be marked as 'read'
4592 		 */
4593 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4594 			      state->stack[spi].spilled_ptr.parent,
4595 			      REG_LIVE_READ64);
4596 	}
4597 	return update_stack_depth(env, state, min_off);
4598 }
4599 
4600 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4601 				   int access_size, bool zero_size_allowed,
4602 				   struct bpf_call_arg_meta *meta)
4603 {
4604 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4605 
4606 	switch (reg->type) {
4607 	case PTR_TO_PACKET:
4608 	case PTR_TO_PACKET_META:
4609 		return check_packet_access(env, regno, reg->off, access_size,
4610 					   zero_size_allowed);
4611 	case PTR_TO_MAP_KEY:
4612 		return check_mem_region_access(env, regno, reg->off, access_size,
4613 					       reg->map_ptr->key_size, false);
4614 	case PTR_TO_MAP_VALUE:
4615 		if (check_map_access_type(env, regno, reg->off, access_size,
4616 					  meta && meta->raw_mode ? BPF_WRITE :
4617 					  BPF_READ))
4618 			return -EACCES;
4619 		return check_map_access(env, regno, reg->off, access_size,
4620 					zero_size_allowed);
4621 	case PTR_TO_MEM:
4622 		return check_mem_region_access(env, regno, reg->off,
4623 					       access_size, reg->mem_size,
4624 					       zero_size_allowed);
4625 	case PTR_TO_RDONLY_BUF:
4626 		if (meta && meta->raw_mode)
4627 			return -EACCES;
4628 		return check_buffer_access(env, reg, regno, reg->off,
4629 					   access_size, zero_size_allowed,
4630 					   "rdonly",
4631 					   &env->prog->aux->max_rdonly_access);
4632 	case PTR_TO_RDWR_BUF:
4633 		return check_buffer_access(env, reg, regno, reg->off,
4634 					   access_size, zero_size_allowed,
4635 					   "rdwr",
4636 					   &env->prog->aux->max_rdwr_access);
4637 	case PTR_TO_STACK:
4638 		return check_stack_range_initialized(
4639 				env,
4640 				regno, reg->off, access_size,
4641 				zero_size_allowed, ACCESS_HELPER, meta);
4642 	default: /* scalar_value or invalid ptr */
4643 		/* Allow zero-byte read from NULL, regardless of pointer type */
4644 		if (zero_size_allowed && access_size == 0 &&
4645 		    register_is_null(reg))
4646 			return 0;
4647 
4648 		verbose(env, "R%d type=%s expected=%s\n", regno,
4649 			reg_type_str[reg->type],
4650 			reg_type_str[PTR_TO_STACK]);
4651 		return -EACCES;
4652 	}
4653 }
4654 
4655 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4656 		   u32 regno, u32 mem_size)
4657 {
4658 	if (register_is_null(reg))
4659 		return 0;
4660 
4661 	if (reg_type_may_be_null(reg->type)) {
4662 		/* Assuming that the register contains a value check if the memory
4663 		 * access is safe. Temporarily save and restore the register's state as
4664 		 * the conversion shouldn't be visible to a caller.
4665 		 */
4666 		const struct bpf_reg_state saved_reg = *reg;
4667 		int rv;
4668 
4669 		mark_ptr_not_null_reg(reg);
4670 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4671 		*reg = saved_reg;
4672 		return rv;
4673 	}
4674 
4675 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4676 }
4677 
4678 /* Implementation details:
4679  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4680  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4681  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4682  * value_or_null->value transition, since the verifier only cares about
4683  * the range of access to valid map value pointer and doesn't care about actual
4684  * address of the map element.
4685  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4686  * reg->id > 0 after value_or_null->value transition. By doing so
4687  * two bpf_map_lookups will be considered two different pointers that
4688  * point to different bpf_spin_locks.
4689  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4690  * dead-locks.
4691  * Since only one bpf_spin_lock is allowed the checks are simpler than
4692  * reg_is_refcounted() logic. The verifier needs to remember only
4693  * one spin_lock instead of array of acquired_refs.
4694  * cur_state->active_spin_lock remembers which map value element got locked
4695  * and clears it after bpf_spin_unlock.
4696  */
4697 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4698 			     bool is_lock)
4699 {
4700 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4701 	struct bpf_verifier_state *cur = env->cur_state;
4702 	bool is_const = tnum_is_const(reg->var_off);
4703 	struct bpf_map *map = reg->map_ptr;
4704 	u64 val = reg->var_off.value;
4705 
4706 	if (!is_const) {
4707 		verbose(env,
4708 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4709 			regno);
4710 		return -EINVAL;
4711 	}
4712 	if (!map->btf) {
4713 		verbose(env,
4714 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4715 			map->name);
4716 		return -EINVAL;
4717 	}
4718 	if (!map_value_has_spin_lock(map)) {
4719 		if (map->spin_lock_off == -E2BIG)
4720 			verbose(env,
4721 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4722 				map->name);
4723 		else if (map->spin_lock_off == -ENOENT)
4724 			verbose(env,
4725 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4726 				map->name);
4727 		else
4728 			verbose(env,
4729 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4730 				map->name);
4731 		return -EINVAL;
4732 	}
4733 	if (map->spin_lock_off != val + reg->off) {
4734 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4735 			val + reg->off);
4736 		return -EINVAL;
4737 	}
4738 	if (is_lock) {
4739 		if (cur->active_spin_lock) {
4740 			verbose(env,
4741 				"Locking two bpf_spin_locks are not allowed\n");
4742 			return -EINVAL;
4743 		}
4744 		cur->active_spin_lock = reg->id;
4745 	} else {
4746 		if (!cur->active_spin_lock) {
4747 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4748 			return -EINVAL;
4749 		}
4750 		if (cur->active_spin_lock != reg->id) {
4751 			verbose(env, "bpf_spin_unlock of different lock\n");
4752 			return -EINVAL;
4753 		}
4754 		cur->active_spin_lock = 0;
4755 	}
4756 	return 0;
4757 }
4758 
4759 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4760 			      struct bpf_call_arg_meta *meta)
4761 {
4762 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4763 	bool is_const = tnum_is_const(reg->var_off);
4764 	struct bpf_map *map = reg->map_ptr;
4765 	u64 val = reg->var_off.value;
4766 
4767 	if (!is_const) {
4768 		verbose(env,
4769 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4770 			regno);
4771 		return -EINVAL;
4772 	}
4773 	if (!map->btf) {
4774 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4775 			map->name);
4776 		return -EINVAL;
4777 	}
4778 	if (!map_value_has_timer(map)) {
4779 		if (map->timer_off == -E2BIG)
4780 			verbose(env,
4781 				"map '%s' has more than one 'struct bpf_timer'\n",
4782 				map->name);
4783 		else if (map->timer_off == -ENOENT)
4784 			verbose(env,
4785 				"map '%s' doesn't have 'struct bpf_timer'\n",
4786 				map->name);
4787 		else
4788 			verbose(env,
4789 				"map '%s' is not a struct type or bpf_timer is mangled\n",
4790 				map->name);
4791 		return -EINVAL;
4792 	}
4793 	if (map->timer_off != val + reg->off) {
4794 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4795 			val + reg->off, map->timer_off);
4796 		return -EINVAL;
4797 	}
4798 	if (meta->map_ptr) {
4799 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4800 		return -EFAULT;
4801 	}
4802 	meta->map_uid = reg->map_uid;
4803 	meta->map_ptr = map;
4804 	return 0;
4805 }
4806 
4807 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4808 {
4809 	return type == ARG_PTR_TO_MEM ||
4810 	       type == ARG_PTR_TO_MEM_OR_NULL ||
4811 	       type == ARG_PTR_TO_UNINIT_MEM;
4812 }
4813 
4814 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4815 {
4816 	return type == ARG_CONST_SIZE ||
4817 	       type == ARG_CONST_SIZE_OR_ZERO;
4818 }
4819 
4820 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4821 {
4822 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4823 }
4824 
4825 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4826 {
4827 	return type == ARG_PTR_TO_INT ||
4828 	       type == ARG_PTR_TO_LONG;
4829 }
4830 
4831 static int int_ptr_type_to_size(enum bpf_arg_type type)
4832 {
4833 	if (type == ARG_PTR_TO_INT)
4834 		return sizeof(u32);
4835 	else if (type == ARG_PTR_TO_LONG)
4836 		return sizeof(u64);
4837 
4838 	return -EINVAL;
4839 }
4840 
4841 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4842 				 const struct bpf_call_arg_meta *meta,
4843 				 enum bpf_arg_type *arg_type)
4844 {
4845 	if (!meta->map_ptr) {
4846 		/* kernel subsystem misconfigured verifier */
4847 		verbose(env, "invalid map_ptr to access map->type\n");
4848 		return -EACCES;
4849 	}
4850 
4851 	switch (meta->map_ptr->map_type) {
4852 	case BPF_MAP_TYPE_SOCKMAP:
4853 	case BPF_MAP_TYPE_SOCKHASH:
4854 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4855 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4856 		} else {
4857 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4858 			return -EINVAL;
4859 		}
4860 		break;
4861 
4862 	default:
4863 		break;
4864 	}
4865 	return 0;
4866 }
4867 
4868 struct bpf_reg_types {
4869 	const enum bpf_reg_type types[10];
4870 	u32 *btf_id;
4871 };
4872 
4873 static const struct bpf_reg_types map_key_value_types = {
4874 	.types = {
4875 		PTR_TO_STACK,
4876 		PTR_TO_PACKET,
4877 		PTR_TO_PACKET_META,
4878 		PTR_TO_MAP_KEY,
4879 		PTR_TO_MAP_VALUE,
4880 	},
4881 };
4882 
4883 static const struct bpf_reg_types sock_types = {
4884 	.types = {
4885 		PTR_TO_SOCK_COMMON,
4886 		PTR_TO_SOCKET,
4887 		PTR_TO_TCP_SOCK,
4888 		PTR_TO_XDP_SOCK,
4889 	},
4890 };
4891 
4892 #ifdef CONFIG_NET
4893 static const struct bpf_reg_types btf_id_sock_common_types = {
4894 	.types = {
4895 		PTR_TO_SOCK_COMMON,
4896 		PTR_TO_SOCKET,
4897 		PTR_TO_TCP_SOCK,
4898 		PTR_TO_XDP_SOCK,
4899 		PTR_TO_BTF_ID,
4900 	},
4901 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4902 };
4903 #endif
4904 
4905 static const struct bpf_reg_types mem_types = {
4906 	.types = {
4907 		PTR_TO_STACK,
4908 		PTR_TO_PACKET,
4909 		PTR_TO_PACKET_META,
4910 		PTR_TO_MAP_KEY,
4911 		PTR_TO_MAP_VALUE,
4912 		PTR_TO_MEM,
4913 		PTR_TO_RDONLY_BUF,
4914 		PTR_TO_RDWR_BUF,
4915 	},
4916 };
4917 
4918 static const struct bpf_reg_types int_ptr_types = {
4919 	.types = {
4920 		PTR_TO_STACK,
4921 		PTR_TO_PACKET,
4922 		PTR_TO_PACKET_META,
4923 		PTR_TO_MAP_KEY,
4924 		PTR_TO_MAP_VALUE,
4925 	},
4926 };
4927 
4928 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4929 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4930 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4931 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4932 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4933 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4934 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4935 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4936 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4937 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4938 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4939 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
4940 
4941 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4942 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4943 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4944 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4945 	[ARG_PTR_TO_MAP_VALUE_OR_NULL]	= &map_key_value_types,
4946 	[ARG_CONST_SIZE]		= &scalar_types,
4947 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4948 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4949 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4950 	[ARG_PTR_TO_CTX]		= &context_types,
4951 	[ARG_PTR_TO_CTX_OR_NULL]	= &context_types,
4952 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4953 #ifdef CONFIG_NET
4954 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4955 #endif
4956 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4957 	[ARG_PTR_TO_SOCKET_OR_NULL]	= &fullsock_types,
4958 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4959 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4960 	[ARG_PTR_TO_MEM]		= &mem_types,
4961 	[ARG_PTR_TO_MEM_OR_NULL]	= &mem_types,
4962 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4963 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4964 	[ARG_PTR_TO_ALLOC_MEM_OR_NULL]	= &alloc_mem_types,
4965 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4966 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4967 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4968 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
4969 	[ARG_PTR_TO_STACK_OR_NULL]	= &stack_ptr_types,
4970 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
4971 	[ARG_PTR_TO_TIMER]		= &timer_types,
4972 };
4973 
4974 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4975 			  enum bpf_arg_type arg_type,
4976 			  const u32 *arg_btf_id)
4977 {
4978 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4979 	enum bpf_reg_type expected, type = reg->type;
4980 	const struct bpf_reg_types *compatible;
4981 	int i, j;
4982 
4983 	compatible = compatible_reg_types[arg_type];
4984 	if (!compatible) {
4985 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4986 		return -EFAULT;
4987 	}
4988 
4989 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4990 		expected = compatible->types[i];
4991 		if (expected == NOT_INIT)
4992 			break;
4993 
4994 		if (type == expected)
4995 			goto found;
4996 	}
4997 
4998 	verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4999 	for (j = 0; j + 1 < i; j++)
5000 		verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
5001 	verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
5002 	return -EACCES;
5003 
5004 found:
5005 	if (type == PTR_TO_BTF_ID) {
5006 		if (!arg_btf_id) {
5007 			if (!compatible->btf_id) {
5008 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5009 				return -EFAULT;
5010 			}
5011 			arg_btf_id = compatible->btf_id;
5012 		}
5013 
5014 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5015 					  btf_vmlinux, *arg_btf_id)) {
5016 			verbose(env, "R%d is of type %s but %s is expected\n",
5017 				regno, kernel_type_name(reg->btf, reg->btf_id),
5018 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5019 			return -EACCES;
5020 		}
5021 
5022 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5023 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5024 				regno);
5025 			return -EACCES;
5026 		}
5027 	}
5028 
5029 	return 0;
5030 }
5031 
5032 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5033 			  struct bpf_call_arg_meta *meta,
5034 			  const struct bpf_func_proto *fn)
5035 {
5036 	u32 regno = BPF_REG_1 + arg;
5037 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5038 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5039 	enum bpf_reg_type type = reg->type;
5040 	int err = 0;
5041 
5042 	if (arg_type == ARG_DONTCARE)
5043 		return 0;
5044 
5045 	err = check_reg_arg(env, regno, SRC_OP);
5046 	if (err)
5047 		return err;
5048 
5049 	if (arg_type == ARG_ANYTHING) {
5050 		if (is_pointer_value(env, regno)) {
5051 			verbose(env, "R%d leaks addr into helper function\n",
5052 				regno);
5053 			return -EACCES;
5054 		}
5055 		return 0;
5056 	}
5057 
5058 	if (type_is_pkt_pointer(type) &&
5059 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5060 		verbose(env, "helper access to the packet is not allowed\n");
5061 		return -EACCES;
5062 	}
5063 
5064 	if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5065 	    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5066 	    arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5067 		err = resolve_map_arg_type(env, meta, &arg_type);
5068 		if (err)
5069 			return err;
5070 	}
5071 
5072 	if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5073 		/* A NULL register has a SCALAR_VALUE type, so skip
5074 		 * type checking.
5075 		 */
5076 		goto skip_type_check;
5077 
5078 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5079 	if (err)
5080 		return err;
5081 
5082 	if (type == PTR_TO_CTX) {
5083 		err = check_ctx_reg(env, reg, regno);
5084 		if (err < 0)
5085 			return err;
5086 	}
5087 
5088 skip_type_check:
5089 	if (reg->ref_obj_id) {
5090 		if (meta->ref_obj_id) {
5091 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5092 				regno, reg->ref_obj_id,
5093 				meta->ref_obj_id);
5094 			return -EFAULT;
5095 		}
5096 		meta->ref_obj_id = reg->ref_obj_id;
5097 	}
5098 
5099 	if (arg_type == ARG_CONST_MAP_PTR) {
5100 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5101 		if (meta->map_ptr) {
5102 			/* Use map_uid (which is unique id of inner map) to reject:
5103 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5104 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5105 			 * if (inner_map1 && inner_map2) {
5106 			 *     timer = bpf_map_lookup_elem(inner_map1);
5107 			 *     if (timer)
5108 			 *         // mismatch would have been allowed
5109 			 *         bpf_timer_init(timer, inner_map2);
5110 			 * }
5111 			 *
5112 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5113 			 */
5114 			if (meta->map_ptr != reg->map_ptr ||
5115 			    meta->map_uid != reg->map_uid) {
5116 				verbose(env,
5117 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5118 					meta->map_uid, reg->map_uid);
5119 				return -EINVAL;
5120 			}
5121 		}
5122 		meta->map_ptr = reg->map_ptr;
5123 		meta->map_uid = reg->map_uid;
5124 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5125 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5126 		 * check that [key, key + map->key_size) are within
5127 		 * stack limits and initialized
5128 		 */
5129 		if (!meta->map_ptr) {
5130 			/* in function declaration map_ptr must come before
5131 			 * map_key, so that it's verified and known before
5132 			 * we have to check map_key here. Otherwise it means
5133 			 * that kernel subsystem misconfigured verifier
5134 			 */
5135 			verbose(env, "invalid map_ptr to access map->key\n");
5136 			return -EACCES;
5137 		}
5138 		err = check_helper_mem_access(env, regno,
5139 					      meta->map_ptr->key_size, false,
5140 					      NULL);
5141 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5142 		   (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5143 		    !register_is_null(reg)) ||
5144 		   arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5145 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5146 		 * check [value, value + map->value_size) validity
5147 		 */
5148 		if (!meta->map_ptr) {
5149 			/* kernel subsystem misconfigured verifier */
5150 			verbose(env, "invalid map_ptr to access map->value\n");
5151 			return -EACCES;
5152 		}
5153 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5154 		err = check_helper_mem_access(env, regno,
5155 					      meta->map_ptr->value_size, false,
5156 					      meta);
5157 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5158 		if (!reg->btf_id) {
5159 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5160 			return -EACCES;
5161 		}
5162 		meta->ret_btf = reg->btf;
5163 		meta->ret_btf_id = reg->btf_id;
5164 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5165 		if (meta->func_id == BPF_FUNC_spin_lock) {
5166 			if (process_spin_lock(env, regno, true))
5167 				return -EACCES;
5168 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5169 			if (process_spin_lock(env, regno, false))
5170 				return -EACCES;
5171 		} else {
5172 			verbose(env, "verifier internal error\n");
5173 			return -EFAULT;
5174 		}
5175 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5176 		if (process_timer_func(env, regno, meta))
5177 			return -EACCES;
5178 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5179 		meta->subprogno = reg->subprogno;
5180 	} else if (arg_type_is_mem_ptr(arg_type)) {
5181 		/* The access to this pointer is only checked when we hit the
5182 		 * next is_mem_size argument below.
5183 		 */
5184 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5185 	} else if (arg_type_is_mem_size(arg_type)) {
5186 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5187 
5188 		/* This is used to refine r0 return value bounds for helpers
5189 		 * that enforce this value as an upper bound on return values.
5190 		 * See do_refine_retval_range() for helpers that can refine
5191 		 * the return value. C type of helper is u32 so we pull register
5192 		 * bound from umax_value however, if negative verifier errors
5193 		 * out. Only upper bounds can be learned because retval is an
5194 		 * int type and negative retvals are allowed.
5195 		 */
5196 		meta->msize_max_value = reg->umax_value;
5197 
5198 		/* The register is SCALAR_VALUE; the access check
5199 		 * happens using its boundaries.
5200 		 */
5201 		if (!tnum_is_const(reg->var_off))
5202 			/* For unprivileged variable accesses, disable raw
5203 			 * mode so that the program is required to
5204 			 * initialize all the memory that the helper could
5205 			 * just partially fill up.
5206 			 */
5207 			meta = NULL;
5208 
5209 		if (reg->smin_value < 0) {
5210 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5211 				regno);
5212 			return -EACCES;
5213 		}
5214 
5215 		if (reg->umin_value == 0) {
5216 			err = check_helper_mem_access(env, regno - 1, 0,
5217 						      zero_size_allowed,
5218 						      meta);
5219 			if (err)
5220 				return err;
5221 		}
5222 
5223 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5224 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5225 				regno);
5226 			return -EACCES;
5227 		}
5228 		err = check_helper_mem_access(env, regno - 1,
5229 					      reg->umax_value,
5230 					      zero_size_allowed, meta);
5231 		if (!err)
5232 			err = mark_chain_precision(env, regno);
5233 	} else if (arg_type_is_alloc_size(arg_type)) {
5234 		if (!tnum_is_const(reg->var_off)) {
5235 			verbose(env, "R%d is not a known constant'\n",
5236 				regno);
5237 			return -EACCES;
5238 		}
5239 		meta->mem_size = reg->var_off.value;
5240 	} else if (arg_type_is_int_ptr(arg_type)) {
5241 		int size = int_ptr_type_to_size(arg_type);
5242 
5243 		err = check_helper_mem_access(env, regno, size, false, meta);
5244 		if (err)
5245 			return err;
5246 		err = check_ptr_alignment(env, reg, 0, size, true);
5247 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5248 		struct bpf_map *map = reg->map_ptr;
5249 		int map_off;
5250 		u64 map_addr;
5251 		char *str_ptr;
5252 
5253 		if (!bpf_map_is_rdonly(map)) {
5254 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5255 			return -EACCES;
5256 		}
5257 
5258 		if (!tnum_is_const(reg->var_off)) {
5259 			verbose(env, "R%d is not a constant address'\n", regno);
5260 			return -EACCES;
5261 		}
5262 
5263 		if (!map->ops->map_direct_value_addr) {
5264 			verbose(env, "no direct value access support for this map type\n");
5265 			return -EACCES;
5266 		}
5267 
5268 		err = check_map_access(env, regno, reg->off,
5269 				       map->value_size - reg->off, false);
5270 		if (err)
5271 			return err;
5272 
5273 		map_off = reg->off + reg->var_off.value;
5274 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5275 		if (err) {
5276 			verbose(env, "direct value access on string failed\n");
5277 			return err;
5278 		}
5279 
5280 		str_ptr = (char *)(long)(map_addr);
5281 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5282 			verbose(env, "string is not zero-terminated\n");
5283 			return -EINVAL;
5284 		}
5285 	}
5286 
5287 	return err;
5288 }
5289 
5290 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5291 {
5292 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5293 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5294 
5295 	if (func_id != BPF_FUNC_map_update_elem)
5296 		return false;
5297 
5298 	/* It's not possible to get access to a locked struct sock in these
5299 	 * contexts, so updating is safe.
5300 	 */
5301 	switch (type) {
5302 	case BPF_PROG_TYPE_TRACING:
5303 		if (eatype == BPF_TRACE_ITER)
5304 			return true;
5305 		break;
5306 	case BPF_PROG_TYPE_SOCKET_FILTER:
5307 	case BPF_PROG_TYPE_SCHED_CLS:
5308 	case BPF_PROG_TYPE_SCHED_ACT:
5309 	case BPF_PROG_TYPE_XDP:
5310 	case BPF_PROG_TYPE_SK_REUSEPORT:
5311 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5312 	case BPF_PROG_TYPE_SK_LOOKUP:
5313 		return true;
5314 	default:
5315 		break;
5316 	}
5317 
5318 	verbose(env, "cannot update sockmap in this context\n");
5319 	return false;
5320 }
5321 
5322 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5323 {
5324 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5325 }
5326 
5327 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5328 					struct bpf_map *map, int func_id)
5329 {
5330 	if (!map)
5331 		return 0;
5332 
5333 	/* We need a two way check, first is from map perspective ... */
5334 	switch (map->map_type) {
5335 	case BPF_MAP_TYPE_PROG_ARRAY:
5336 		if (func_id != BPF_FUNC_tail_call)
5337 			goto error;
5338 		break;
5339 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5340 		if (func_id != BPF_FUNC_perf_event_read &&
5341 		    func_id != BPF_FUNC_perf_event_output &&
5342 		    func_id != BPF_FUNC_skb_output &&
5343 		    func_id != BPF_FUNC_perf_event_read_value &&
5344 		    func_id != BPF_FUNC_xdp_output)
5345 			goto error;
5346 		break;
5347 	case BPF_MAP_TYPE_RINGBUF:
5348 		if (func_id != BPF_FUNC_ringbuf_output &&
5349 		    func_id != BPF_FUNC_ringbuf_reserve &&
5350 		    func_id != BPF_FUNC_ringbuf_query)
5351 			goto error;
5352 		break;
5353 	case BPF_MAP_TYPE_STACK_TRACE:
5354 		if (func_id != BPF_FUNC_get_stackid)
5355 			goto error;
5356 		break;
5357 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5358 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5359 		    func_id != BPF_FUNC_current_task_under_cgroup)
5360 			goto error;
5361 		break;
5362 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5363 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5364 		if (func_id != BPF_FUNC_get_local_storage)
5365 			goto error;
5366 		break;
5367 	case BPF_MAP_TYPE_DEVMAP:
5368 	case BPF_MAP_TYPE_DEVMAP_HASH:
5369 		if (func_id != BPF_FUNC_redirect_map &&
5370 		    func_id != BPF_FUNC_map_lookup_elem)
5371 			goto error;
5372 		break;
5373 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5374 	 * appear.
5375 	 */
5376 	case BPF_MAP_TYPE_CPUMAP:
5377 		if (func_id != BPF_FUNC_redirect_map)
5378 			goto error;
5379 		break;
5380 	case BPF_MAP_TYPE_XSKMAP:
5381 		if (func_id != BPF_FUNC_redirect_map &&
5382 		    func_id != BPF_FUNC_map_lookup_elem)
5383 			goto error;
5384 		break;
5385 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5386 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5387 		if (func_id != BPF_FUNC_map_lookup_elem)
5388 			goto error;
5389 		break;
5390 	case BPF_MAP_TYPE_SOCKMAP:
5391 		if (func_id != BPF_FUNC_sk_redirect_map &&
5392 		    func_id != BPF_FUNC_sock_map_update &&
5393 		    func_id != BPF_FUNC_map_delete_elem &&
5394 		    func_id != BPF_FUNC_msg_redirect_map &&
5395 		    func_id != BPF_FUNC_sk_select_reuseport &&
5396 		    func_id != BPF_FUNC_map_lookup_elem &&
5397 		    !may_update_sockmap(env, func_id))
5398 			goto error;
5399 		break;
5400 	case BPF_MAP_TYPE_SOCKHASH:
5401 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5402 		    func_id != BPF_FUNC_sock_hash_update &&
5403 		    func_id != BPF_FUNC_map_delete_elem &&
5404 		    func_id != BPF_FUNC_msg_redirect_hash &&
5405 		    func_id != BPF_FUNC_sk_select_reuseport &&
5406 		    func_id != BPF_FUNC_map_lookup_elem &&
5407 		    !may_update_sockmap(env, func_id))
5408 			goto error;
5409 		break;
5410 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5411 		if (func_id != BPF_FUNC_sk_select_reuseport)
5412 			goto error;
5413 		break;
5414 	case BPF_MAP_TYPE_QUEUE:
5415 	case BPF_MAP_TYPE_STACK:
5416 		if (func_id != BPF_FUNC_map_peek_elem &&
5417 		    func_id != BPF_FUNC_map_pop_elem &&
5418 		    func_id != BPF_FUNC_map_push_elem)
5419 			goto error;
5420 		break;
5421 	case BPF_MAP_TYPE_SK_STORAGE:
5422 		if (func_id != BPF_FUNC_sk_storage_get &&
5423 		    func_id != BPF_FUNC_sk_storage_delete)
5424 			goto error;
5425 		break;
5426 	case BPF_MAP_TYPE_INODE_STORAGE:
5427 		if (func_id != BPF_FUNC_inode_storage_get &&
5428 		    func_id != BPF_FUNC_inode_storage_delete)
5429 			goto error;
5430 		break;
5431 	case BPF_MAP_TYPE_TASK_STORAGE:
5432 		if (func_id != BPF_FUNC_task_storage_get &&
5433 		    func_id != BPF_FUNC_task_storage_delete)
5434 			goto error;
5435 		break;
5436 	default:
5437 		break;
5438 	}
5439 
5440 	/* ... and second from the function itself. */
5441 	switch (func_id) {
5442 	case BPF_FUNC_tail_call:
5443 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5444 			goto error;
5445 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5446 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5447 			return -EINVAL;
5448 		}
5449 		break;
5450 	case BPF_FUNC_perf_event_read:
5451 	case BPF_FUNC_perf_event_output:
5452 	case BPF_FUNC_perf_event_read_value:
5453 	case BPF_FUNC_skb_output:
5454 	case BPF_FUNC_xdp_output:
5455 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5456 			goto error;
5457 		break;
5458 	case BPF_FUNC_ringbuf_output:
5459 	case BPF_FUNC_ringbuf_reserve:
5460 	case BPF_FUNC_ringbuf_query:
5461 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5462 			goto error;
5463 		break;
5464 	case BPF_FUNC_get_stackid:
5465 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5466 			goto error;
5467 		break;
5468 	case BPF_FUNC_current_task_under_cgroup:
5469 	case BPF_FUNC_skb_under_cgroup:
5470 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5471 			goto error;
5472 		break;
5473 	case BPF_FUNC_redirect_map:
5474 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5475 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5476 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5477 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5478 			goto error;
5479 		break;
5480 	case BPF_FUNC_sk_redirect_map:
5481 	case BPF_FUNC_msg_redirect_map:
5482 	case BPF_FUNC_sock_map_update:
5483 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5484 			goto error;
5485 		break;
5486 	case BPF_FUNC_sk_redirect_hash:
5487 	case BPF_FUNC_msg_redirect_hash:
5488 	case BPF_FUNC_sock_hash_update:
5489 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5490 			goto error;
5491 		break;
5492 	case BPF_FUNC_get_local_storage:
5493 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5494 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5495 			goto error;
5496 		break;
5497 	case BPF_FUNC_sk_select_reuseport:
5498 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5499 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5500 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5501 			goto error;
5502 		break;
5503 	case BPF_FUNC_map_peek_elem:
5504 	case BPF_FUNC_map_pop_elem:
5505 	case BPF_FUNC_map_push_elem:
5506 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5507 		    map->map_type != BPF_MAP_TYPE_STACK)
5508 			goto error;
5509 		break;
5510 	case BPF_FUNC_sk_storage_get:
5511 	case BPF_FUNC_sk_storage_delete:
5512 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5513 			goto error;
5514 		break;
5515 	case BPF_FUNC_inode_storage_get:
5516 	case BPF_FUNC_inode_storage_delete:
5517 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5518 			goto error;
5519 		break;
5520 	case BPF_FUNC_task_storage_get:
5521 	case BPF_FUNC_task_storage_delete:
5522 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5523 			goto error;
5524 		break;
5525 	default:
5526 		break;
5527 	}
5528 
5529 	return 0;
5530 error:
5531 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5532 		map->map_type, func_id_name(func_id), func_id);
5533 	return -EINVAL;
5534 }
5535 
5536 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5537 {
5538 	int count = 0;
5539 
5540 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5541 		count++;
5542 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5543 		count++;
5544 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5545 		count++;
5546 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5547 		count++;
5548 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5549 		count++;
5550 
5551 	/* We only support one arg being in raw mode at the moment,
5552 	 * which is sufficient for the helper functions we have
5553 	 * right now.
5554 	 */
5555 	return count <= 1;
5556 }
5557 
5558 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5559 				    enum bpf_arg_type arg_next)
5560 {
5561 	return (arg_type_is_mem_ptr(arg_curr) &&
5562 	        !arg_type_is_mem_size(arg_next)) ||
5563 	       (!arg_type_is_mem_ptr(arg_curr) &&
5564 		arg_type_is_mem_size(arg_next));
5565 }
5566 
5567 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5568 {
5569 	/* bpf_xxx(..., buf, len) call will access 'len'
5570 	 * bytes from memory 'buf'. Both arg types need
5571 	 * to be paired, so make sure there's no buggy
5572 	 * helper function specification.
5573 	 */
5574 	if (arg_type_is_mem_size(fn->arg1_type) ||
5575 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5576 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5577 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5578 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5579 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5580 		return false;
5581 
5582 	return true;
5583 }
5584 
5585 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5586 {
5587 	int count = 0;
5588 
5589 	if (arg_type_may_be_refcounted(fn->arg1_type))
5590 		count++;
5591 	if (arg_type_may_be_refcounted(fn->arg2_type))
5592 		count++;
5593 	if (arg_type_may_be_refcounted(fn->arg3_type))
5594 		count++;
5595 	if (arg_type_may_be_refcounted(fn->arg4_type))
5596 		count++;
5597 	if (arg_type_may_be_refcounted(fn->arg5_type))
5598 		count++;
5599 
5600 	/* A reference acquiring function cannot acquire
5601 	 * another refcounted ptr.
5602 	 */
5603 	if (may_be_acquire_function(func_id) && count)
5604 		return false;
5605 
5606 	/* We only support one arg being unreferenced at the moment,
5607 	 * which is sufficient for the helper functions we have right now.
5608 	 */
5609 	return count <= 1;
5610 }
5611 
5612 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5613 {
5614 	int i;
5615 
5616 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5617 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5618 			return false;
5619 
5620 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5621 			return false;
5622 	}
5623 
5624 	return true;
5625 }
5626 
5627 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5628 {
5629 	return check_raw_mode_ok(fn) &&
5630 	       check_arg_pair_ok(fn) &&
5631 	       check_btf_id_ok(fn) &&
5632 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5633 }
5634 
5635 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5636  * are now invalid, so turn them into unknown SCALAR_VALUE.
5637  */
5638 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5639 				     struct bpf_func_state *state)
5640 {
5641 	struct bpf_reg_state *regs = state->regs, *reg;
5642 	int i;
5643 
5644 	for (i = 0; i < MAX_BPF_REG; i++)
5645 		if (reg_is_pkt_pointer_any(&regs[i]))
5646 			mark_reg_unknown(env, regs, i);
5647 
5648 	bpf_for_each_spilled_reg(i, state, reg) {
5649 		if (!reg)
5650 			continue;
5651 		if (reg_is_pkt_pointer_any(reg))
5652 			__mark_reg_unknown(env, reg);
5653 	}
5654 }
5655 
5656 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5657 {
5658 	struct bpf_verifier_state *vstate = env->cur_state;
5659 	int i;
5660 
5661 	for (i = 0; i <= vstate->curframe; i++)
5662 		__clear_all_pkt_pointers(env, vstate->frame[i]);
5663 }
5664 
5665 enum {
5666 	AT_PKT_END = -1,
5667 	BEYOND_PKT_END = -2,
5668 };
5669 
5670 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5671 {
5672 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5673 	struct bpf_reg_state *reg = &state->regs[regn];
5674 
5675 	if (reg->type != PTR_TO_PACKET)
5676 		/* PTR_TO_PACKET_META is not supported yet */
5677 		return;
5678 
5679 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5680 	 * How far beyond pkt_end it goes is unknown.
5681 	 * if (!range_open) it's the case of pkt >= pkt_end
5682 	 * if (range_open) it's the case of pkt > pkt_end
5683 	 * hence this pointer is at least 1 byte bigger than pkt_end
5684 	 */
5685 	if (range_open)
5686 		reg->range = BEYOND_PKT_END;
5687 	else
5688 		reg->range = AT_PKT_END;
5689 }
5690 
5691 static void release_reg_references(struct bpf_verifier_env *env,
5692 				   struct bpf_func_state *state,
5693 				   int ref_obj_id)
5694 {
5695 	struct bpf_reg_state *regs = state->regs, *reg;
5696 	int i;
5697 
5698 	for (i = 0; i < MAX_BPF_REG; i++)
5699 		if (regs[i].ref_obj_id == ref_obj_id)
5700 			mark_reg_unknown(env, regs, i);
5701 
5702 	bpf_for_each_spilled_reg(i, state, reg) {
5703 		if (!reg)
5704 			continue;
5705 		if (reg->ref_obj_id == ref_obj_id)
5706 			__mark_reg_unknown(env, reg);
5707 	}
5708 }
5709 
5710 /* The pointer with the specified id has released its reference to kernel
5711  * resources. Identify all copies of the same pointer and clear the reference.
5712  */
5713 static int release_reference(struct bpf_verifier_env *env,
5714 			     int ref_obj_id)
5715 {
5716 	struct bpf_verifier_state *vstate = env->cur_state;
5717 	int err;
5718 	int i;
5719 
5720 	err = release_reference_state(cur_func(env), ref_obj_id);
5721 	if (err)
5722 		return err;
5723 
5724 	for (i = 0; i <= vstate->curframe; i++)
5725 		release_reg_references(env, vstate->frame[i], ref_obj_id);
5726 
5727 	return 0;
5728 }
5729 
5730 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5731 				    struct bpf_reg_state *regs)
5732 {
5733 	int i;
5734 
5735 	/* after the call registers r0 - r5 were scratched */
5736 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5737 		mark_reg_not_init(env, regs, caller_saved[i]);
5738 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5739 	}
5740 }
5741 
5742 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5743 				   struct bpf_func_state *caller,
5744 				   struct bpf_func_state *callee,
5745 				   int insn_idx);
5746 
5747 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5748 			     int *insn_idx, int subprog,
5749 			     set_callee_state_fn set_callee_state_cb)
5750 {
5751 	struct bpf_verifier_state *state = env->cur_state;
5752 	struct bpf_func_info_aux *func_info_aux;
5753 	struct bpf_func_state *caller, *callee;
5754 	int err;
5755 	bool is_global = false;
5756 
5757 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5758 		verbose(env, "the call stack of %d frames is too deep\n",
5759 			state->curframe + 2);
5760 		return -E2BIG;
5761 	}
5762 
5763 	caller = state->frame[state->curframe];
5764 	if (state->frame[state->curframe + 1]) {
5765 		verbose(env, "verifier bug. Frame %d already allocated\n",
5766 			state->curframe + 1);
5767 		return -EFAULT;
5768 	}
5769 
5770 	func_info_aux = env->prog->aux->func_info_aux;
5771 	if (func_info_aux)
5772 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5773 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5774 	if (err == -EFAULT)
5775 		return err;
5776 	if (is_global) {
5777 		if (err) {
5778 			verbose(env, "Caller passes invalid args into func#%d\n",
5779 				subprog);
5780 			return err;
5781 		} else {
5782 			if (env->log.level & BPF_LOG_LEVEL)
5783 				verbose(env,
5784 					"Func#%d is global and valid. Skipping.\n",
5785 					subprog);
5786 			clear_caller_saved_regs(env, caller->regs);
5787 
5788 			/* All global functions return a 64-bit SCALAR_VALUE */
5789 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5790 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5791 
5792 			/* continue with next insn after call */
5793 			return 0;
5794 		}
5795 	}
5796 
5797 	if (insn->code == (BPF_JMP | BPF_CALL) &&
5798 	    insn->imm == BPF_FUNC_timer_set_callback) {
5799 		struct bpf_verifier_state *async_cb;
5800 
5801 		/* there is no real recursion here. timer callbacks are async */
5802 		env->subprog_info[subprog].is_async_cb = true;
5803 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5804 					 *insn_idx, subprog);
5805 		if (!async_cb)
5806 			return -EFAULT;
5807 		callee = async_cb->frame[0];
5808 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
5809 
5810 		/* Convert bpf_timer_set_callback() args into timer callback args */
5811 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
5812 		if (err)
5813 			return err;
5814 
5815 		clear_caller_saved_regs(env, caller->regs);
5816 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
5817 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5818 		/* continue with next insn after call */
5819 		return 0;
5820 	}
5821 
5822 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5823 	if (!callee)
5824 		return -ENOMEM;
5825 	state->frame[state->curframe + 1] = callee;
5826 
5827 	/* callee cannot access r0, r6 - r9 for reading and has to write
5828 	 * into its own stack before reading from it.
5829 	 * callee can read/write into caller's stack
5830 	 */
5831 	init_func_state(env, callee,
5832 			/* remember the callsite, it will be used by bpf_exit */
5833 			*insn_idx /* callsite */,
5834 			state->curframe + 1 /* frameno within this callchain */,
5835 			subprog /* subprog number within this prog */);
5836 
5837 	/* Transfer references to the callee */
5838 	err = copy_reference_state(callee, caller);
5839 	if (err)
5840 		return err;
5841 
5842 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
5843 	if (err)
5844 		return err;
5845 
5846 	clear_caller_saved_regs(env, caller->regs);
5847 
5848 	/* only increment it after check_reg_arg() finished */
5849 	state->curframe++;
5850 
5851 	/* and go analyze first insn of the callee */
5852 	*insn_idx = env->subprog_info[subprog].start - 1;
5853 
5854 	if (env->log.level & BPF_LOG_LEVEL) {
5855 		verbose(env, "caller:\n");
5856 		print_verifier_state(env, caller);
5857 		verbose(env, "callee:\n");
5858 		print_verifier_state(env, callee);
5859 	}
5860 	return 0;
5861 }
5862 
5863 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5864 				   struct bpf_func_state *caller,
5865 				   struct bpf_func_state *callee)
5866 {
5867 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5868 	 *      void *callback_ctx, u64 flags);
5869 	 * callback_fn(struct bpf_map *map, void *key, void *value,
5870 	 *      void *callback_ctx);
5871 	 */
5872 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5873 
5874 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5875 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5876 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5877 
5878 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5879 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5880 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5881 
5882 	/* pointer to stack or null */
5883 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5884 
5885 	/* unused */
5886 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5887 	return 0;
5888 }
5889 
5890 static int set_callee_state(struct bpf_verifier_env *env,
5891 			    struct bpf_func_state *caller,
5892 			    struct bpf_func_state *callee, int insn_idx)
5893 {
5894 	int i;
5895 
5896 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5897 	 * pointers, which connects us up to the liveness chain
5898 	 */
5899 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5900 		callee->regs[i] = caller->regs[i];
5901 	return 0;
5902 }
5903 
5904 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5905 			   int *insn_idx)
5906 {
5907 	int subprog, target_insn;
5908 
5909 	target_insn = *insn_idx + insn->imm + 1;
5910 	subprog = find_subprog(env, target_insn);
5911 	if (subprog < 0) {
5912 		verbose(env, "verifier bug. No program starts at insn %d\n",
5913 			target_insn);
5914 		return -EFAULT;
5915 	}
5916 
5917 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5918 }
5919 
5920 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5921 				       struct bpf_func_state *caller,
5922 				       struct bpf_func_state *callee,
5923 				       int insn_idx)
5924 {
5925 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5926 	struct bpf_map *map;
5927 	int err;
5928 
5929 	if (bpf_map_ptr_poisoned(insn_aux)) {
5930 		verbose(env, "tail_call abusing map_ptr\n");
5931 		return -EINVAL;
5932 	}
5933 
5934 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5935 	if (!map->ops->map_set_for_each_callback_args ||
5936 	    !map->ops->map_for_each_callback) {
5937 		verbose(env, "callback function not allowed for map\n");
5938 		return -ENOTSUPP;
5939 	}
5940 
5941 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5942 	if (err)
5943 		return err;
5944 
5945 	callee->in_callback_fn = true;
5946 	return 0;
5947 }
5948 
5949 static int set_timer_callback_state(struct bpf_verifier_env *env,
5950 				    struct bpf_func_state *caller,
5951 				    struct bpf_func_state *callee,
5952 				    int insn_idx)
5953 {
5954 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
5955 
5956 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
5957 	 * callback_fn(struct bpf_map *map, void *key, void *value);
5958 	 */
5959 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
5960 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
5961 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
5962 
5963 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5964 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5965 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
5966 
5967 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5968 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5969 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
5970 
5971 	/* unused */
5972 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
5973 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5974 	callee->in_async_callback_fn = true;
5975 	return 0;
5976 }
5977 
5978 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5979 {
5980 	struct bpf_verifier_state *state = env->cur_state;
5981 	struct bpf_func_state *caller, *callee;
5982 	struct bpf_reg_state *r0;
5983 	int err;
5984 
5985 	callee = state->frame[state->curframe];
5986 	r0 = &callee->regs[BPF_REG_0];
5987 	if (r0->type == PTR_TO_STACK) {
5988 		/* technically it's ok to return caller's stack pointer
5989 		 * (or caller's caller's pointer) back to the caller,
5990 		 * since these pointers are valid. Only current stack
5991 		 * pointer will be invalid as soon as function exits,
5992 		 * but let's be conservative
5993 		 */
5994 		verbose(env, "cannot return stack pointer to the caller\n");
5995 		return -EINVAL;
5996 	}
5997 
5998 	state->curframe--;
5999 	caller = state->frame[state->curframe];
6000 	if (callee->in_callback_fn) {
6001 		/* enforce R0 return value range [0, 1]. */
6002 		struct tnum range = tnum_range(0, 1);
6003 
6004 		if (r0->type != SCALAR_VALUE) {
6005 			verbose(env, "R0 not a scalar value\n");
6006 			return -EACCES;
6007 		}
6008 		if (!tnum_in(range, r0->var_off)) {
6009 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6010 			return -EINVAL;
6011 		}
6012 	} else {
6013 		/* return to the caller whatever r0 had in the callee */
6014 		caller->regs[BPF_REG_0] = *r0;
6015 	}
6016 
6017 	/* Transfer references to the caller */
6018 	err = copy_reference_state(caller, callee);
6019 	if (err)
6020 		return err;
6021 
6022 	*insn_idx = callee->callsite + 1;
6023 	if (env->log.level & BPF_LOG_LEVEL) {
6024 		verbose(env, "returning from callee:\n");
6025 		print_verifier_state(env, callee);
6026 		verbose(env, "to caller at %d:\n", *insn_idx);
6027 		print_verifier_state(env, caller);
6028 	}
6029 	/* clear everything in the callee */
6030 	free_func_state(callee);
6031 	state->frame[state->curframe + 1] = NULL;
6032 	return 0;
6033 }
6034 
6035 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6036 				   int func_id,
6037 				   struct bpf_call_arg_meta *meta)
6038 {
6039 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6040 
6041 	if (ret_type != RET_INTEGER ||
6042 	    (func_id != BPF_FUNC_get_stack &&
6043 	     func_id != BPF_FUNC_get_task_stack &&
6044 	     func_id != BPF_FUNC_probe_read_str &&
6045 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6046 	     func_id != BPF_FUNC_probe_read_user_str))
6047 		return;
6048 
6049 	ret_reg->smax_value = meta->msize_max_value;
6050 	ret_reg->s32_max_value = meta->msize_max_value;
6051 	ret_reg->smin_value = -MAX_ERRNO;
6052 	ret_reg->s32_min_value = -MAX_ERRNO;
6053 	__reg_deduce_bounds(ret_reg);
6054 	__reg_bound_offset(ret_reg);
6055 	__update_reg_bounds(ret_reg);
6056 }
6057 
6058 static int
6059 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6060 		int func_id, int insn_idx)
6061 {
6062 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6063 	struct bpf_map *map = meta->map_ptr;
6064 
6065 	if (func_id != BPF_FUNC_tail_call &&
6066 	    func_id != BPF_FUNC_map_lookup_elem &&
6067 	    func_id != BPF_FUNC_map_update_elem &&
6068 	    func_id != BPF_FUNC_map_delete_elem &&
6069 	    func_id != BPF_FUNC_map_push_elem &&
6070 	    func_id != BPF_FUNC_map_pop_elem &&
6071 	    func_id != BPF_FUNC_map_peek_elem &&
6072 	    func_id != BPF_FUNC_for_each_map_elem &&
6073 	    func_id != BPF_FUNC_redirect_map)
6074 		return 0;
6075 
6076 	if (map == NULL) {
6077 		verbose(env, "kernel subsystem misconfigured verifier\n");
6078 		return -EINVAL;
6079 	}
6080 
6081 	/* In case of read-only, some additional restrictions
6082 	 * need to be applied in order to prevent altering the
6083 	 * state of the map from program side.
6084 	 */
6085 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6086 	    (func_id == BPF_FUNC_map_delete_elem ||
6087 	     func_id == BPF_FUNC_map_update_elem ||
6088 	     func_id == BPF_FUNC_map_push_elem ||
6089 	     func_id == BPF_FUNC_map_pop_elem)) {
6090 		verbose(env, "write into map forbidden\n");
6091 		return -EACCES;
6092 	}
6093 
6094 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6095 		bpf_map_ptr_store(aux, meta->map_ptr,
6096 				  !meta->map_ptr->bypass_spec_v1);
6097 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6098 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6099 				  !meta->map_ptr->bypass_spec_v1);
6100 	return 0;
6101 }
6102 
6103 static int
6104 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6105 		int func_id, int insn_idx)
6106 {
6107 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6108 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6109 	struct bpf_map *map = meta->map_ptr;
6110 	struct tnum range;
6111 	u64 val;
6112 	int err;
6113 
6114 	if (func_id != BPF_FUNC_tail_call)
6115 		return 0;
6116 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6117 		verbose(env, "kernel subsystem misconfigured verifier\n");
6118 		return -EINVAL;
6119 	}
6120 
6121 	range = tnum_range(0, map->max_entries - 1);
6122 	reg = &regs[BPF_REG_3];
6123 
6124 	if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6125 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6126 		return 0;
6127 	}
6128 
6129 	err = mark_chain_precision(env, BPF_REG_3);
6130 	if (err)
6131 		return err;
6132 
6133 	val = reg->var_off.value;
6134 	if (bpf_map_key_unseen(aux))
6135 		bpf_map_key_store(aux, val);
6136 	else if (!bpf_map_key_poisoned(aux) &&
6137 		  bpf_map_key_immediate(aux) != val)
6138 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6139 	return 0;
6140 }
6141 
6142 static int check_reference_leak(struct bpf_verifier_env *env)
6143 {
6144 	struct bpf_func_state *state = cur_func(env);
6145 	int i;
6146 
6147 	for (i = 0; i < state->acquired_refs; i++) {
6148 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6149 			state->refs[i].id, state->refs[i].insn_idx);
6150 	}
6151 	return state->acquired_refs ? -EINVAL : 0;
6152 }
6153 
6154 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6155 				   struct bpf_reg_state *regs)
6156 {
6157 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6158 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6159 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6160 	int err, fmt_map_off, num_args;
6161 	u64 fmt_addr;
6162 	char *fmt;
6163 
6164 	/* data must be an array of u64 */
6165 	if (data_len_reg->var_off.value % 8)
6166 		return -EINVAL;
6167 	num_args = data_len_reg->var_off.value / 8;
6168 
6169 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6170 	 * and map_direct_value_addr is set.
6171 	 */
6172 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6173 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6174 						  fmt_map_off);
6175 	if (err) {
6176 		verbose(env, "verifier bug\n");
6177 		return -EFAULT;
6178 	}
6179 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6180 
6181 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6182 	 * can focus on validating the format specifiers.
6183 	 */
6184 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6185 	if (err < 0)
6186 		verbose(env, "Invalid format string\n");
6187 
6188 	return err;
6189 }
6190 
6191 static int check_get_func_ip(struct bpf_verifier_env *env)
6192 {
6193 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6194 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6195 	int func_id = BPF_FUNC_get_func_ip;
6196 
6197 	if (type == BPF_PROG_TYPE_TRACING) {
6198 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6199 		    eatype != BPF_MODIFY_RETURN) {
6200 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6201 				func_id_name(func_id), func_id);
6202 			return -ENOTSUPP;
6203 		}
6204 		return 0;
6205 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6206 		return 0;
6207 	}
6208 
6209 	verbose(env, "func %s#%d not supported for program type %d\n",
6210 		func_id_name(func_id), func_id, type);
6211 	return -ENOTSUPP;
6212 }
6213 
6214 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6215 			     int *insn_idx_p)
6216 {
6217 	const struct bpf_func_proto *fn = NULL;
6218 	struct bpf_reg_state *regs;
6219 	struct bpf_call_arg_meta meta;
6220 	int insn_idx = *insn_idx_p;
6221 	bool changes_data;
6222 	int i, err, func_id;
6223 
6224 	/* find function prototype */
6225 	func_id = insn->imm;
6226 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6227 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6228 			func_id);
6229 		return -EINVAL;
6230 	}
6231 
6232 	if (env->ops->get_func_proto)
6233 		fn = env->ops->get_func_proto(func_id, env->prog);
6234 	if (!fn) {
6235 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6236 			func_id);
6237 		return -EINVAL;
6238 	}
6239 
6240 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6241 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6242 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6243 		return -EINVAL;
6244 	}
6245 
6246 	if (fn->allowed && !fn->allowed(env->prog)) {
6247 		verbose(env, "helper call is not allowed in probe\n");
6248 		return -EINVAL;
6249 	}
6250 
6251 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6252 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6253 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6254 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6255 			func_id_name(func_id), func_id);
6256 		return -EINVAL;
6257 	}
6258 
6259 	memset(&meta, 0, sizeof(meta));
6260 	meta.pkt_access = fn->pkt_access;
6261 
6262 	err = check_func_proto(fn, func_id);
6263 	if (err) {
6264 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6265 			func_id_name(func_id), func_id);
6266 		return err;
6267 	}
6268 
6269 	meta.func_id = func_id;
6270 	/* check args */
6271 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6272 		err = check_func_arg(env, i, &meta, fn);
6273 		if (err)
6274 			return err;
6275 	}
6276 
6277 	err = record_func_map(env, &meta, func_id, insn_idx);
6278 	if (err)
6279 		return err;
6280 
6281 	err = record_func_key(env, &meta, func_id, insn_idx);
6282 	if (err)
6283 		return err;
6284 
6285 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6286 	 * is inferred from register state.
6287 	 */
6288 	for (i = 0; i < meta.access_size; i++) {
6289 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6290 				       BPF_WRITE, -1, false);
6291 		if (err)
6292 			return err;
6293 	}
6294 
6295 	if (func_id == BPF_FUNC_tail_call) {
6296 		err = check_reference_leak(env);
6297 		if (err) {
6298 			verbose(env, "tail_call would lead to reference leak\n");
6299 			return err;
6300 		}
6301 	} else if (is_release_function(func_id)) {
6302 		err = release_reference(env, meta.ref_obj_id);
6303 		if (err) {
6304 			verbose(env, "func %s#%d reference has not been acquired before\n",
6305 				func_id_name(func_id), func_id);
6306 			return err;
6307 		}
6308 	}
6309 
6310 	regs = cur_regs(env);
6311 
6312 	/* check that flags argument in get_local_storage(map, flags) is 0,
6313 	 * this is required because get_local_storage() can't return an error.
6314 	 */
6315 	if (func_id == BPF_FUNC_get_local_storage &&
6316 	    !register_is_null(&regs[BPF_REG_2])) {
6317 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6318 		return -EINVAL;
6319 	}
6320 
6321 	if (func_id == BPF_FUNC_for_each_map_elem) {
6322 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6323 					set_map_elem_callback_state);
6324 		if (err < 0)
6325 			return -EINVAL;
6326 	}
6327 
6328 	if (func_id == BPF_FUNC_timer_set_callback) {
6329 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6330 					set_timer_callback_state);
6331 		if (err < 0)
6332 			return -EINVAL;
6333 	}
6334 
6335 	if (func_id == BPF_FUNC_snprintf) {
6336 		err = check_bpf_snprintf_call(env, regs);
6337 		if (err < 0)
6338 			return err;
6339 	}
6340 
6341 	/* reset caller saved regs */
6342 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6343 		mark_reg_not_init(env, regs, caller_saved[i]);
6344 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6345 	}
6346 
6347 	/* helper call returns 64-bit value. */
6348 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6349 
6350 	/* update return register (already marked as written above) */
6351 	if (fn->ret_type == RET_INTEGER) {
6352 		/* sets type to SCALAR_VALUE */
6353 		mark_reg_unknown(env, regs, BPF_REG_0);
6354 	} else if (fn->ret_type == RET_VOID) {
6355 		regs[BPF_REG_0].type = NOT_INIT;
6356 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6357 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6358 		/* There is no offset yet applied, variable or fixed */
6359 		mark_reg_known_zero(env, regs, BPF_REG_0);
6360 		/* remember map_ptr, so that check_map_access()
6361 		 * can check 'value_size' boundary of memory access
6362 		 * to map element returned from bpf_map_lookup_elem()
6363 		 */
6364 		if (meta.map_ptr == NULL) {
6365 			verbose(env,
6366 				"kernel subsystem misconfigured verifier\n");
6367 			return -EINVAL;
6368 		}
6369 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6370 		regs[BPF_REG_0].map_uid = meta.map_uid;
6371 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6372 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6373 			if (map_value_has_spin_lock(meta.map_ptr))
6374 				regs[BPF_REG_0].id = ++env->id_gen;
6375 		} else {
6376 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6377 		}
6378 	} else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6379 		mark_reg_known_zero(env, regs, BPF_REG_0);
6380 		regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6381 	} else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6382 		mark_reg_known_zero(env, regs, BPF_REG_0);
6383 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6384 	} else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6385 		mark_reg_known_zero(env, regs, BPF_REG_0);
6386 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6387 	} else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6388 		mark_reg_known_zero(env, regs, BPF_REG_0);
6389 		regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6390 		regs[BPF_REG_0].mem_size = meta.mem_size;
6391 	} else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6392 		   fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6393 		const struct btf_type *t;
6394 
6395 		mark_reg_known_zero(env, regs, BPF_REG_0);
6396 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6397 		if (!btf_type_is_struct(t)) {
6398 			u32 tsize;
6399 			const struct btf_type *ret;
6400 			const char *tname;
6401 
6402 			/* resolve the type size of ksym. */
6403 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6404 			if (IS_ERR(ret)) {
6405 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6406 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6407 					tname, PTR_ERR(ret));
6408 				return -EINVAL;
6409 			}
6410 			regs[BPF_REG_0].type =
6411 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6412 				PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6413 			regs[BPF_REG_0].mem_size = tsize;
6414 		} else {
6415 			regs[BPF_REG_0].type =
6416 				fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6417 				PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6418 			regs[BPF_REG_0].btf = meta.ret_btf;
6419 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6420 		}
6421 	} else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6422 		   fn->ret_type == RET_PTR_TO_BTF_ID) {
6423 		int ret_btf_id;
6424 
6425 		mark_reg_known_zero(env, regs, BPF_REG_0);
6426 		regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6427 						     PTR_TO_BTF_ID :
6428 						     PTR_TO_BTF_ID_OR_NULL;
6429 		ret_btf_id = *fn->ret_btf_id;
6430 		if (ret_btf_id == 0) {
6431 			verbose(env, "invalid return type %d of func %s#%d\n",
6432 				fn->ret_type, func_id_name(func_id), func_id);
6433 			return -EINVAL;
6434 		}
6435 		/* current BPF helper definitions are only coming from
6436 		 * built-in code with type IDs from  vmlinux BTF
6437 		 */
6438 		regs[BPF_REG_0].btf = btf_vmlinux;
6439 		regs[BPF_REG_0].btf_id = ret_btf_id;
6440 	} else {
6441 		verbose(env, "unknown return type %d of func %s#%d\n",
6442 			fn->ret_type, func_id_name(func_id), func_id);
6443 		return -EINVAL;
6444 	}
6445 
6446 	if (reg_type_may_be_null(regs[BPF_REG_0].type))
6447 		regs[BPF_REG_0].id = ++env->id_gen;
6448 
6449 	if (is_ptr_cast_function(func_id)) {
6450 		/* For release_reference() */
6451 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6452 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6453 		int id = acquire_reference_state(env, insn_idx);
6454 
6455 		if (id < 0)
6456 			return id;
6457 		/* For mark_ptr_or_null_reg() */
6458 		regs[BPF_REG_0].id = id;
6459 		/* For release_reference() */
6460 		regs[BPF_REG_0].ref_obj_id = id;
6461 	}
6462 
6463 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6464 
6465 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6466 	if (err)
6467 		return err;
6468 
6469 	if ((func_id == BPF_FUNC_get_stack ||
6470 	     func_id == BPF_FUNC_get_task_stack) &&
6471 	    !env->prog->has_callchain_buf) {
6472 		const char *err_str;
6473 
6474 #ifdef CONFIG_PERF_EVENTS
6475 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6476 		err_str = "cannot get callchain buffer for func %s#%d\n";
6477 #else
6478 		err = -ENOTSUPP;
6479 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6480 #endif
6481 		if (err) {
6482 			verbose(env, err_str, func_id_name(func_id), func_id);
6483 			return err;
6484 		}
6485 
6486 		env->prog->has_callchain_buf = true;
6487 	}
6488 
6489 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6490 		env->prog->call_get_stack = true;
6491 
6492 	if (func_id == BPF_FUNC_get_func_ip) {
6493 		if (check_get_func_ip(env))
6494 			return -ENOTSUPP;
6495 		env->prog->call_get_func_ip = true;
6496 	}
6497 
6498 	if (changes_data)
6499 		clear_all_pkt_pointers(env);
6500 	return 0;
6501 }
6502 
6503 /* mark_btf_func_reg_size() is used when the reg size is determined by
6504  * the BTF func_proto's return value size and argument.
6505  */
6506 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6507 				   size_t reg_size)
6508 {
6509 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6510 
6511 	if (regno == BPF_REG_0) {
6512 		/* Function return value */
6513 		reg->live |= REG_LIVE_WRITTEN;
6514 		reg->subreg_def = reg_size == sizeof(u64) ?
6515 			DEF_NOT_SUBREG : env->insn_idx + 1;
6516 	} else {
6517 		/* Function argument */
6518 		if (reg_size == sizeof(u64)) {
6519 			mark_insn_zext(env, reg);
6520 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6521 		} else {
6522 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6523 		}
6524 	}
6525 }
6526 
6527 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6528 {
6529 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6530 	struct bpf_reg_state *regs = cur_regs(env);
6531 	const char *func_name, *ptr_type_name;
6532 	u32 i, nargs, func_id, ptr_type_id;
6533 	const struct btf_param *args;
6534 	int err;
6535 
6536 	func_id = insn->imm;
6537 	func = btf_type_by_id(btf_vmlinux, func_id);
6538 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6539 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
6540 
6541 	if (!env->ops->check_kfunc_call ||
6542 	    !env->ops->check_kfunc_call(func_id)) {
6543 		verbose(env, "calling kernel function %s is not allowed\n",
6544 			func_name);
6545 		return -EACCES;
6546 	}
6547 
6548 	/* Check the arguments */
6549 	err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6550 	if (err)
6551 		return err;
6552 
6553 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6554 		mark_reg_not_init(env, regs, caller_saved[i]);
6555 
6556 	/* Check return type */
6557 	t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6558 	if (btf_type_is_scalar(t)) {
6559 		mark_reg_unknown(env, regs, BPF_REG_0);
6560 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6561 	} else if (btf_type_is_ptr(t)) {
6562 		ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6563 						   &ptr_type_id);
6564 		if (!btf_type_is_struct(ptr_type)) {
6565 			ptr_type_name = btf_name_by_offset(btf_vmlinux,
6566 							   ptr_type->name_off);
6567 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6568 				func_name, btf_type_str(ptr_type),
6569 				ptr_type_name);
6570 			return -EINVAL;
6571 		}
6572 		mark_reg_known_zero(env, regs, BPF_REG_0);
6573 		regs[BPF_REG_0].btf = btf_vmlinux;
6574 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6575 		regs[BPF_REG_0].btf_id = ptr_type_id;
6576 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6577 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6578 
6579 	nargs = btf_type_vlen(func_proto);
6580 	args = (const struct btf_param *)(func_proto + 1);
6581 	for (i = 0; i < nargs; i++) {
6582 		u32 regno = i + 1;
6583 
6584 		t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6585 		if (btf_type_is_ptr(t))
6586 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6587 		else
6588 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6589 			mark_btf_func_reg_size(env, regno, t->size);
6590 	}
6591 
6592 	return 0;
6593 }
6594 
6595 static bool signed_add_overflows(s64 a, s64 b)
6596 {
6597 	/* Do the add in u64, where overflow is well-defined */
6598 	s64 res = (s64)((u64)a + (u64)b);
6599 
6600 	if (b < 0)
6601 		return res > a;
6602 	return res < a;
6603 }
6604 
6605 static bool signed_add32_overflows(s32 a, s32 b)
6606 {
6607 	/* Do the add in u32, where overflow is well-defined */
6608 	s32 res = (s32)((u32)a + (u32)b);
6609 
6610 	if (b < 0)
6611 		return res > a;
6612 	return res < a;
6613 }
6614 
6615 static bool signed_sub_overflows(s64 a, s64 b)
6616 {
6617 	/* Do the sub in u64, where overflow is well-defined */
6618 	s64 res = (s64)((u64)a - (u64)b);
6619 
6620 	if (b < 0)
6621 		return res < a;
6622 	return res > a;
6623 }
6624 
6625 static bool signed_sub32_overflows(s32 a, s32 b)
6626 {
6627 	/* Do the sub in u32, where overflow is well-defined */
6628 	s32 res = (s32)((u32)a - (u32)b);
6629 
6630 	if (b < 0)
6631 		return res < a;
6632 	return res > a;
6633 }
6634 
6635 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6636 				  const struct bpf_reg_state *reg,
6637 				  enum bpf_reg_type type)
6638 {
6639 	bool known = tnum_is_const(reg->var_off);
6640 	s64 val = reg->var_off.value;
6641 	s64 smin = reg->smin_value;
6642 
6643 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6644 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6645 			reg_type_str[type], val);
6646 		return false;
6647 	}
6648 
6649 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6650 		verbose(env, "%s pointer offset %d is not allowed\n",
6651 			reg_type_str[type], reg->off);
6652 		return false;
6653 	}
6654 
6655 	if (smin == S64_MIN) {
6656 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6657 			reg_type_str[type]);
6658 		return false;
6659 	}
6660 
6661 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6662 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6663 			smin, reg_type_str[type]);
6664 		return false;
6665 	}
6666 
6667 	return true;
6668 }
6669 
6670 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6671 {
6672 	return &env->insn_aux_data[env->insn_idx];
6673 }
6674 
6675 enum {
6676 	REASON_BOUNDS	= -1,
6677 	REASON_TYPE	= -2,
6678 	REASON_PATHS	= -3,
6679 	REASON_LIMIT	= -4,
6680 	REASON_STACK	= -5,
6681 };
6682 
6683 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6684 			      u32 *alu_limit, bool mask_to_left)
6685 {
6686 	u32 max = 0, ptr_limit = 0;
6687 
6688 	switch (ptr_reg->type) {
6689 	case PTR_TO_STACK:
6690 		/* Offset 0 is out-of-bounds, but acceptable start for the
6691 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6692 		 * offset where we would need to deal with min/max bounds is
6693 		 * currently prohibited for unprivileged.
6694 		 */
6695 		max = MAX_BPF_STACK + mask_to_left;
6696 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6697 		break;
6698 	case PTR_TO_MAP_VALUE:
6699 		max = ptr_reg->map_ptr->value_size;
6700 		ptr_limit = (mask_to_left ?
6701 			     ptr_reg->smin_value :
6702 			     ptr_reg->umax_value) + ptr_reg->off;
6703 		break;
6704 	default:
6705 		return REASON_TYPE;
6706 	}
6707 
6708 	if (ptr_limit >= max)
6709 		return REASON_LIMIT;
6710 	*alu_limit = ptr_limit;
6711 	return 0;
6712 }
6713 
6714 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6715 				    const struct bpf_insn *insn)
6716 {
6717 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6718 }
6719 
6720 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6721 				       u32 alu_state, u32 alu_limit)
6722 {
6723 	/* If we arrived here from different branches with different
6724 	 * state or limits to sanitize, then this won't work.
6725 	 */
6726 	if (aux->alu_state &&
6727 	    (aux->alu_state != alu_state ||
6728 	     aux->alu_limit != alu_limit))
6729 		return REASON_PATHS;
6730 
6731 	/* Corresponding fixup done in do_misc_fixups(). */
6732 	aux->alu_state = alu_state;
6733 	aux->alu_limit = alu_limit;
6734 	return 0;
6735 }
6736 
6737 static int sanitize_val_alu(struct bpf_verifier_env *env,
6738 			    struct bpf_insn *insn)
6739 {
6740 	struct bpf_insn_aux_data *aux = cur_aux(env);
6741 
6742 	if (can_skip_alu_sanitation(env, insn))
6743 		return 0;
6744 
6745 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6746 }
6747 
6748 static bool sanitize_needed(u8 opcode)
6749 {
6750 	return opcode == BPF_ADD || opcode == BPF_SUB;
6751 }
6752 
6753 struct bpf_sanitize_info {
6754 	struct bpf_insn_aux_data aux;
6755 	bool mask_to_left;
6756 };
6757 
6758 static struct bpf_verifier_state *
6759 sanitize_speculative_path(struct bpf_verifier_env *env,
6760 			  const struct bpf_insn *insn,
6761 			  u32 next_idx, u32 curr_idx)
6762 {
6763 	struct bpf_verifier_state *branch;
6764 	struct bpf_reg_state *regs;
6765 
6766 	branch = push_stack(env, next_idx, curr_idx, true);
6767 	if (branch && insn) {
6768 		regs = branch->frame[branch->curframe]->regs;
6769 		if (BPF_SRC(insn->code) == BPF_K) {
6770 			mark_reg_unknown(env, regs, insn->dst_reg);
6771 		} else if (BPF_SRC(insn->code) == BPF_X) {
6772 			mark_reg_unknown(env, regs, insn->dst_reg);
6773 			mark_reg_unknown(env, regs, insn->src_reg);
6774 		}
6775 	}
6776 	return branch;
6777 }
6778 
6779 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6780 			    struct bpf_insn *insn,
6781 			    const struct bpf_reg_state *ptr_reg,
6782 			    const struct bpf_reg_state *off_reg,
6783 			    struct bpf_reg_state *dst_reg,
6784 			    struct bpf_sanitize_info *info,
6785 			    const bool commit_window)
6786 {
6787 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6788 	struct bpf_verifier_state *vstate = env->cur_state;
6789 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6790 	bool off_is_neg = off_reg->smin_value < 0;
6791 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6792 	u8 opcode = BPF_OP(insn->code);
6793 	u32 alu_state, alu_limit;
6794 	struct bpf_reg_state tmp;
6795 	bool ret;
6796 	int err;
6797 
6798 	if (can_skip_alu_sanitation(env, insn))
6799 		return 0;
6800 
6801 	/* We already marked aux for masking from non-speculative
6802 	 * paths, thus we got here in the first place. We only care
6803 	 * to explore bad access from here.
6804 	 */
6805 	if (vstate->speculative)
6806 		goto do_sim;
6807 
6808 	if (!commit_window) {
6809 		if (!tnum_is_const(off_reg->var_off) &&
6810 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6811 			return REASON_BOUNDS;
6812 
6813 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6814 				     (opcode == BPF_SUB && !off_is_neg);
6815 	}
6816 
6817 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6818 	if (err < 0)
6819 		return err;
6820 
6821 	if (commit_window) {
6822 		/* In commit phase we narrow the masking window based on
6823 		 * the observed pointer move after the simulated operation.
6824 		 */
6825 		alu_state = info->aux.alu_state;
6826 		alu_limit = abs(info->aux.alu_limit - alu_limit);
6827 	} else {
6828 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6829 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6830 		alu_state |= ptr_is_dst_reg ?
6831 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6832 
6833 		/* Limit pruning on unknown scalars to enable deep search for
6834 		 * potential masking differences from other program paths.
6835 		 */
6836 		if (!off_is_imm)
6837 			env->explore_alu_limits = true;
6838 	}
6839 
6840 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6841 	if (err < 0)
6842 		return err;
6843 do_sim:
6844 	/* If we're in commit phase, we're done here given we already
6845 	 * pushed the truncated dst_reg into the speculative verification
6846 	 * stack.
6847 	 *
6848 	 * Also, when register is a known constant, we rewrite register-based
6849 	 * operation to immediate-based, and thus do not need masking (and as
6850 	 * a consequence, do not need to simulate the zero-truncation either).
6851 	 */
6852 	if (commit_window || off_is_imm)
6853 		return 0;
6854 
6855 	/* Simulate and find potential out-of-bounds access under
6856 	 * speculative execution from truncation as a result of
6857 	 * masking when off was not within expected range. If off
6858 	 * sits in dst, then we temporarily need to move ptr there
6859 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6860 	 * for cases where we use K-based arithmetic in one direction
6861 	 * and truncated reg-based in the other in order to explore
6862 	 * bad access.
6863 	 */
6864 	if (!ptr_is_dst_reg) {
6865 		tmp = *dst_reg;
6866 		*dst_reg = *ptr_reg;
6867 	}
6868 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6869 					env->insn_idx);
6870 	if (!ptr_is_dst_reg && ret)
6871 		*dst_reg = tmp;
6872 	return !ret ? REASON_STACK : 0;
6873 }
6874 
6875 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6876 {
6877 	struct bpf_verifier_state *vstate = env->cur_state;
6878 
6879 	/* If we simulate paths under speculation, we don't update the
6880 	 * insn as 'seen' such that when we verify unreachable paths in
6881 	 * the non-speculative domain, sanitize_dead_code() can still
6882 	 * rewrite/sanitize them.
6883 	 */
6884 	if (!vstate->speculative)
6885 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6886 }
6887 
6888 static int sanitize_err(struct bpf_verifier_env *env,
6889 			const struct bpf_insn *insn, int reason,
6890 			const struct bpf_reg_state *off_reg,
6891 			const struct bpf_reg_state *dst_reg)
6892 {
6893 	static const char *err = "pointer arithmetic with it prohibited for !root";
6894 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6895 	u32 dst = insn->dst_reg, src = insn->src_reg;
6896 
6897 	switch (reason) {
6898 	case REASON_BOUNDS:
6899 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6900 			off_reg == dst_reg ? dst : src, err);
6901 		break;
6902 	case REASON_TYPE:
6903 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6904 			off_reg == dst_reg ? src : dst, err);
6905 		break;
6906 	case REASON_PATHS:
6907 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6908 			dst, op, err);
6909 		break;
6910 	case REASON_LIMIT:
6911 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6912 			dst, op, err);
6913 		break;
6914 	case REASON_STACK:
6915 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6916 			dst, err);
6917 		break;
6918 	default:
6919 		verbose(env, "verifier internal error: unknown reason (%d)\n",
6920 			reason);
6921 		break;
6922 	}
6923 
6924 	return -EACCES;
6925 }
6926 
6927 /* check that stack access falls within stack limits and that 'reg' doesn't
6928  * have a variable offset.
6929  *
6930  * Variable offset is prohibited for unprivileged mode for simplicity since it
6931  * requires corresponding support in Spectre masking for stack ALU.  See also
6932  * retrieve_ptr_limit().
6933  *
6934  *
6935  * 'off' includes 'reg->off'.
6936  */
6937 static int check_stack_access_for_ptr_arithmetic(
6938 				struct bpf_verifier_env *env,
6939 				int regno,
6940 				const struct bpf_reg_state *reg,
6941 				int off)
6942 {
6943 	if (!tnum_is_const(reg->var_off)) {
6944 		char tn_buf[48];
6945 
6946 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6947 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6948 			regno, tn_buf, off);
6949 		return -EACCES;
6950 	}
6951 
6952 	if (off >= 0 || off < -MAX_BPF_STACK) {
6953 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6954 			"prohibited for !root; off=%d\n", regno, off);
6955 		return -EACCES;
6956 	}
6957 
6958 	return 0;
6959 }
6960 
6961 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6962 				 const struct bpf_insn *insn,
6963 				 const struct bpf_reg_state *dst_reg)
6964 {
6965 	u32 dst = insn->dst_reg;
6966 
6967 	/* For unprivileged we require that resulting offset must be in bounds
6968 	 * in order to be able to sanitize access later on.
6969 	 */
6970 	if (env->bypass_spec_v1)
6971 		return 0;
6972 
6973 	switch (dst_reg->type) {
6974 	case PTR_TO_STACK:
6975 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6976 					dst_reg->off + dst_reg->var_off.value))
6977 			return -EACCES;
6978 		break;
6979 	case PTR_TO_MAP_VALUE:
6980 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6981 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6982 				"prohibited for !root\n", dst);
6983 			return -EACCES;
6984 		}
6985 		break;
6986 	default:
6987 		break;
6988 	}
6989 
6990 	return 0;
6991 }
6992 
6993 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6994  * Caller should also handle BPF_MOV case separately.
6995  * If we return -EACCES, caller may want to try again treating pointer as a
6996  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6997  */
6998 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6999 				   struct bpf_insn *insn,
7000 				   const struct bpf_reg_state *ptr_reg,
7001 				   const struct bpf_reg_state *off_reg)
7002 {
7003 	struct bpf_verifier_state *vstate = env->cur_state;
7004 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7005 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7006 	bool known = tnum_is_const(off_reg->var_off);
7007 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7008 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7009 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7010 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7011 	struct bpf_sanitize_info info = {};
7012 	u8 opcode = BPF_OP(insn->code);
7013 	u32 dst = insn->dst_reg;
7014 	int ret;
7015 
7016 	dst_reg = &regs[dst];
7017 
7018 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7019 	    smin_val > smax_val || umin_val > umax_val) {
7020 		/* Taint dst register if offset had invalid bounds derived from
7021 		 * e.g. dead branches.
7022 		 */
7023 		__mark_reg_unknown(env, dst_reg);
7024 		return 0;
7025 	}
7026 
7027 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7028 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7029 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7030 			__mark_reg_unknown(env, dst_reg);
7031 			return 0;
7032 		}
7033 
7034 		verbose(env,
7035 			"R%d 32-bit pointer arithmetic prohibited\n",
7036 			dst);
7037 		return -EACCES;
7038 	}
7039 
7040 	switch (ptr_reg->type) {
7041 	case PTR_TO_MAP_VALUE_OR_NULL:
7042 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7043 			dst, reg_type_str[ptr_reg->type]);
7044 		return -EACCES;
7045 	case CONST_PTR_TO_MAP:
7046 		/* smin_val represents the known value */
7047 		if (known && smin_val == 0 && opcode == BPF_ADD)
7048 			break;
7049 		fallthrough;
7050 	case PTR_TO_PACKET_END:
7051 	case PTR_TO_SOCKET:
7052 	case PTR_TO_SOCKET_OR_NULL:
7053 	case PTR_TO_SOCK_COMMON:
7054 	case PTR_TO_SOCK_COMMON_OR_NULL:
7055 	case PTR_TO_TCP_SOCK:
7056 	case PTR_TO_TCP_SOCK_OR_NULL:
7057 	case PTR_TO_XDP_SOCK:
7058 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7059 			dst, reg_type_str[ptr_reg->type]);
7060 		return -EACCES;
7061 	default:
7062 		break;
7063 	}
7064 
7065 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7066 	 * The id may be overwritten later if we create a new variable offset.
7067 	 */
7068 	dst_reg->type = ptr_reg->type;
7069 	dst_reg->id = ptr_reg->id;
7070 
7071 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7072 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7073 		return -EINVAL;
7074 
7075 	/* pointer types do not carry 32-bit bounds at the moment. */
7076 	__mark_reg32_unbounded(dst_reg);
7077 
7078 	if (sanitize_needed(opcode)) {
7079 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7080 				       &info, false);
7081 		if (ret < 0)
7082 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7083 	}
7084 
7085 	switch (opcode) {
7086 	case BPF_ADD:
7087 		/* We can take a fixed offset as long as it doesn't overflow
7088 		 * the s32 'off' field
7089 		 */
7090 		if (known && (ptr_reg->off + smin_val ==
7091 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7092 			/* pointer += K.  Accumulate it into fixed offset */
7093 			dst_reg->smin_value = smin_ptr;
7094 			dst_reg->smax_value = smax_ptr;
7095 			dst_reg->umin_value = umin_ptr;
7096 			dst_reg->umax_value = umax_ptr;
7097 			dst_reg->var_off = ptr_reg->var_off;
7098 			dst_reg->off = ptr_reg->off + smin_val;
7099 			dst_reg->raw = ptr_reg->raw;
7100 			break;
7101 		}
7102 		/* A new variable offset is created.  Note that off_reg->off
7103 		 * == 0, since it's a scalar.
7104 		 * dst_reg gets the pointer type and since some positive
7105 		 * integer value was added to the pointer, give it a new 'id'
7106 		 * if it's a PTR_TO_PACKET.
7107 		 * this creates a new 'base' pointer, off_reg (variable) gets
7108 		 * added into the variable offset, and we copy the fixed offset
7109 		 * from ptr_reg.
7110 		 */
7111 		if (signed_add_overflows(smin_ptr, smin_val) ||
7112 		    signed_add_overflows(smax_ptr, smax_val)) {
7113 			dst_reg->smin_value = S64_MIN;
7114 			dst_reg->smax_value = S64_MAX;
7115 		} else {
7116 			dst_reg->smin_value = smin_ptr + smin_val;
7117 			dst_reg->smax_value = smax_ptr + smax_val;
7118 		}
7119 		if (umin_ptr + umin_val < umin_ptr ||
7120 		    umax_ptr + umax_val < umax_ptr) {
7121 			dst_reg->umin_value = 0;
7122 			dst_reg->umax_value = U64_MAX;
7123 		} else {
7124 			dst_reg->umin_value = umin_ptr + umin_val;
7125 			dst_reg->umax_value = umax_ptr + umax_val;
7126 		}
7127 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7128 		dst_reg->off = ptr_reg->off;
7129 		dst_reg->raw = ptr_reg->raw;
7130 		if (reg_is_pkt_pointer(ptr_reg)) {
7131 			dst_reg->id = ++env->id_gen;
7132 			/* something was added to pkt_ptr, set range to zero */
7133 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7134 		}
7135 		break;
7136 	case BPF_SUB:
7137 		if (dst_reg == off_reg) {
7138 			/* scalar -= pointer.  Creates an unknown scalar */
7139 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7140 				dst);
7141 			return -EACCES;
7142 		}
7143 		/* We don't allow subtraction from FP, because (according to
7144 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7145 		 * be able to deal with it.
7146 		 */
7147 		if (ptr_reg->type == PTR_TO_STACK) {
7148 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7149 				dst);
7150 			return -EACCES;
7151 		}
7152 		if (known && (ptr_reg->off - smin_val ==
7153 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7154 			/* pointer -= K.  Subtract it from fixed offset */
7155 			dst_reg->smin_value = smin_ptr;
7156 			dst_reg->smax_value = smax_ptr;
7157 			dst_reg->umin_value = umin_ptr;
7158 			dst_reg->umax_value = umax_ptr;
7159 			dst_reg->var_off = ptr_reg->var_off;
7160 			dst_reg->id = ptr_reg->id;
7161 			dst_reg->off = ptr_reg->off - smin_val;
7162 			dst_reg->raw = ptr_reg->raw;
7163 			break;
7164 		}
7165 		/* A new variable offset is created.  If the subtrahend is known
7166 		 * nonnegative, then any reg->range we had before is still good.
7167 		 */
7168 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7169 		    signed_sub_overflows(smax_ptr, smin_val)) {
7170 			/* Overflow possible, we know nothing */
7171 			dst_reg->smin_value = S64_MIN;
7172 			dst_reg->smax_value = S64_MAX;
7173 		} else {
7174 			dst_reg->smin_value = smin_ptr - smax_val;
7175 			dst_reg->smax_value = smax_ptr - smin_val;
7176 		}
7177 		if (umin_ptr < umax_val) {
7178 			/* Overflow possible, we know nothing */
7179 			dst_reg->umin_value = 0;
7180 			dst_reg->umax_value = U64_MAX;
7181 		} else {
7182 			/* Cannot overflow (as long as bounds are consistent) */
7183 			dst_reg->umin_value = umin_ptr - umax_val;
7184 			dst_reg->umax_value = umax_ptr - umin_val;
7185 		}
7186 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7187 		dst_reg->off = ptr_reg->off;
7188 		dst_reg->raw = ptr_reg->raw;
7189 		if (reg_is_pkt_pointer(ptr_reg)) {
7190 			dst_reg->id = ++env->id_gen;
7191 			/* something was added to pkt_ptr, set range to zero */
7192 			if (smin_val < 0)
7193 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7194 		}
7195 		break;
7196 	case BPF_AND:
7197 	case BPF_OR:
7198 	case BPF_XOR:
7199 		/* bitwise ops on pointers are troublesome, prohibit. */
7200 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7201 			dst, bpf_alu_string[opcode >> 4]);
7202 		return -EACCES;
7203 	default:
7204 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7205 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7206 			dst, bpf_alu_string[opcode >> 4]);
7207 		return -EACCES;
7208 	}
7209 
7210 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7211 		return -EINVAL;
7212 
7213 	__update_reg_bounds(dst_reg);
7214 	__reg_deduce_bounds(dst_reg);
7215 	__reg_bound_offset(dst_reg);
7216 
7217 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7218 		return -EACCES;
7219 	if (sanitize_needed(opcode)) {
7220 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7221 				       &info, true);
7222 		if (ret < 0)
7223 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7224 	}
7225 
7226 	return 0;
7227 }
7228 
7229 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7230 				 struct bpf_reg_state *src_reg)
7231 {
7232 	s32 smin_val = src_reg->s32_min_value;
7233 	s32 smax_val = src_reg->s32_max_value;
7234 	u32 umin_val = src_reg->u32_min_value;
7235 	u32 umax_val = src_reg->u32_max_value;
7236 
7237 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7238 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7239 		dst_reg->s32_min_value = S32_MIN;
7240 		dst_reg->s32_max_value = S32_MAX;
7241 	} else {
7242 		dst_reg->s32_min_value += smin_val;
7243 		dst_reg->s32_max_value += smax_val;
7244 	}
7245 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7246 	    dst_reg->u32_max_value + umax_val < umax_val) {
7247 		dst_reg->u32_min_value = 0;
7248 		dst_reg->u32_max_value = U32_MAX;
7249 	} else {
7250 		dst_reg->u32_min_value += umin_val;
7251 		dst_reg->u32_max_value += umax_val;
7252 	}
7253 }
7254 
7255 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7256 			       struct bpf_reg_state *src_reg)
7257 {
7258 	s64 smin_val = src_reg->smin_value;
7259 	s64 smax_val = src_reg->smax_value;
7260 	u64 umin_val = src_reg->umin_value;
7261 	u64 umax_val = src_reg->umax_value;
7262 
7263 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7264 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7265 		dst_reg->smin_value = S64_MIN;
7266 		dst_reg->smax_value = S64_MAX;
7267 	} else {
7268 		dst_reg->smin_value += smin_val;
7269 		dst_reg->smax_value += smax_val;
7270 	}
7271 	if (dst_reg->umin_value + umin_val < umin_val ||
7272 	    dst_reg->umax_value + umax_val < umax_val) {
7273 		dst_reg->umin_value = 0;
7274 		dst_reg->umax_value = U64_MAX;
7275 	} else {
7276 		dst_reg->umin_value += umin_val;
7277 		dst_reg->umax_value += umax_val;
7278 	}
7279 }
7280 
7281 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7282 				 struct bpf_reg_state *src_reg)
7283 {
7284 	s32 smin_val = src_reg->s32_min_value;
7285 	s32 smax_val = src_reg->s32_max_value;
7286 	u32 umin_val = src_reg->u32_min_value;
7287 	u32 umax_val = src_reg->u32_max_value;
7288 
7289 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7290 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7291 		/* Overflow possible, we know nothing */
7292 		dst_reg->s32_min_value = S32_MIN;
7293 		dst_reg->s32_max_value = S32_MAX;
7294 	} else {
7295 		dst_reg->s32_min_value -= smax_val;
7296 		dst_reg->s32_max_value -= smin_val;
7297 	}
7298 	if (dst_reg->u32_min_value < umax_val) {
7299 		/* Overflow possible, we know nothing */
7300 		dst_reg->u32_min_value = 0;
7301 		dst_reg->u32_max_value = U32_MAX;
7302 	} else {
7303 		/* Cannot overflow (as long as bounds are consistent) */
7304 		dst_reg->u32_min_value -= umax_val;
7305 		dst_reg->u32_max_value -= umin_val;
7306 	}
7307 }
7308 
7309 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7310 			       struct bpf_reg_state *src_reg)
7311 {
7312 	s64 smin_val = src_reg->smin_value;
7313 	s64 smax_val = src_reg->smax_value;
7314 	u64 umin_val = src_reg->umin_value;
7315 	u64 umax_val = src_reg->umax_value;
7316 
7317 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7318 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7319 		/* Overflow possible, we know nothing */
7320 		dst_reg->smin_value = S64_MIN;
7321 		dst_reg->smax_value = S64_MAX;
7322 	} else {
7323 		dst_reg->smin_value -= smax_val;
7324 		dst_reg->smax_value -= smin_val;
7325 	}
7326 	if (dst_reg->umin_value < umax_val) {
7327 		/* Overflow possible, we know nothing */
7328 		dst_reg->umin_value = 0;
7329 		dst_reg->umax_value = U64_MAX;
7330 	} else {
7331 		/* Cannot overflow (as long as bounds are consistent) */
7332 		dst_reg->umin_value -= umax_val;
7333 		dst_reg->umax_value -= umin_val;
7334 	}
7335 }
7336 
7337 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7338 				 struct bpf_reg_state *src_reg)
7339 {
7340 	s32 smin_val = src_reg->s32_min_value;
7341 	u32 umin_val = src_reg->u32_min_value;
7342 	u32 umax_val = src_reg->u32_max_value;
7343 
7344 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7345 		/* Ain't nobody got time to multiply that sign */
7346 		__mark_reg32_unbounded(dst_reg);
7347 		return;
7348 	}
7349 	/* Both values are positive, so we can work with unsigned and
7350 	 * copy the result to signed (unless it exceeds S32_MAX).
7351 	 */
7352 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7353 		/* Potential overflow, we know nothing */
7354 		__mark_reg32_unbounded(dst_reg);
7355 		return;
7356 	}
7357 	dst_reg->u32_min_value *= umin_val;
7358 	dst_reg->u32_max_value *= umax_val;
7359 	if (dst_reg->u32_max_value > S32_MAX) {
7360 		/* Overflow possible, we know nothing */
7361 		dst_reg->s32_min_value = S32_MIN;
7362 		dst_reg->s32_max_value = S32_MAX;
7363 	} else {
7364 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7365 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7366 	}
7367 }
7368 
7369 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7370 			       struct bpf_reg_state *src_reg)
7371 {
7372 	s64 smin_val = src_reg->smin_value;
7373 	u64 umin_val = src_reg->umin_value;
7374 	u64 umax_val = src_reg->umax_value;
7375 
7376 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7377 		/* Ain't nobody got time to multiply that sign */
7378 		__mark_reg64_unbounded(dst_reg);
7379 		return;
7380 	}
7381 	/* Both values are positive, so we can work with unsigned and
7382 	 * copy the result to signed (unless it exceeds S64_MAX).
7383 	 */
7384 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7385 		/* Potential overflow, we know nothing */
7386 		__mark_reg64_unbounded(dst_reg);
7387 		return;
7388 	}
7389 	dst_reg->umin_value *= umin_val;
7390 	dst_reg->umax_value *= umax_val;
7391 	if (dst_reg->umax_value > S64_MAX) {
7392 		/* Overflow possible, we know nothing */
7393 		dst_reg->smin_value = S64_MIN;
7394 		dst_reg->smax_value = S64_MAX;
7395 	} else {
7396 		dst_reg->smin_value = dst_reg->umin_value;
7397 		dst_reg->smax_value = dst_reg->umax_value;
7398 	}
7399 }
7400 
7401 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7402 				 struct bpf_reg_state *src_reg)
7403 {
7404 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7405 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7406 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7407 	s32 smin_val = src_reg->s32_min_value;
7408 	u32 umax_val = src_reg->u32_max_value;
7409 
7410 	if (src_known && dst_known) {
7411 		__mark_reg32_known(dst_reg, var32_off.value);
7412 		return;
7413 	}
7414 
7415 	/* We get our minimum from the var_off, since that's inherently
7416 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7417 	 */
7418 	dst_reg->u32_min_value = var32_off.value;
7419 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7420 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7421 		/* Lose signed bounds when ANDing negative numbers,
7422 		 * ain't nobody got time for that.
7423 		 */
7424 		dst_reg->s32_min_value = S32_MIN;
7425 		dst_reg->s32_max_value = S32_MAX;
7426 	} else {
7427 		/* ANDing two positives gives a positive, so safe to
7428 		 * cast result into s64.
7429 		 */
7430 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7431 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7432 	}
7433 }
7434 
7435 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7436 			       struct bpf_reg_state *src_reg)
7437 {
7438 	bool src_known = tnum_is_const(src_reg->var_off);
7439 	bool dst_known = tnum_is_const(dst_reg->var_off);
7440 	s64 smin_val = src_reg->smin_value;
7441 	u64 umax_val = src_reg->umax_value;
7442 
7443 	if (src_known && dst_known) {
7444 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7445 		return;
7446 	}
7447 
7448 	/* We get our minimum from the var_off, since that's inherently
7449 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7450 	 */
7451 	dst_reg->umin_value = dst_reg->var_off.value;
7452 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7453 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7454 		/* Lose signed bounds when ANDing negative numbers,
7455 		 * ain't nobody got time for that.
7456 		 */
7457 		dst_reg->smin_value = S64_MIN;
7458 		dst_reg->smax_value = S64_MAX;
7459 	} else {
7460 		/* ANDing two positives gives a positive, so safe to
7461 		 * cast result into s64.
7462 		 */
7463 		dst_reg->smin_value = dst_reg->umin_value;
7464 		dst_reg->smax_value = dst_reg->umax_value;
7465 	}
7466 	/* We may learn something more from the var_off */
7467 	__update_reg_bounds(dst_reg);
7468 }
7469 
7470 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7471 				struct bpf_reg_state *src_reg)
7472 {
7473 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7474 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7475 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7476 	s32 smin_val = src_reg->s32_min_value;
7477 	u32 umin_val = src_reg->u32_min_value;
7478 
7479 	if (src_known && dst_known) {
7480 		__mark_reg32_known(dst_reg, var32_off.value);
7481 		return;
7482 	}
7483 
7484 	/* We get our maximum from the var_off, and our minimum is the
7485 	 * maximum of the operands' minima
7486 	 */
7487 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7488 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7489 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7490 		/* Lose signed bounds when ORing negative numbers,
7491 		 * ain't nobody got time for that.
7492 		 */
7493 		dst_reg->s32_min_value = S32_MIN;
7494 		dst_reg->s32_max_value = S32_MAX;
7495 	} else {
7496 		/* ORing two positives gives a positive, so safe to
7497 		 * cast result into s64.
7498 		 */
7499 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7500 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7501 	}
7502 }
7503 
7504 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7505 			      struct bpf_reg_state *src_reg)
7506 {
7507 	bool src_known = tnum_is_const(src_reg->var_off);
7508 	bool dst_known = tnum_is_const(dst_reg->var_off);
7509 	s64 smin_val = src_reg->smin_value;
7510 	u64 umin_val = src_reg->umin_value;
7511 
7512 	if (src_known && dst_known) {
7513 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7514 		return;
7515 	}
7516 
7517 	/* We get our maximum from the var_off, and our minimum is the
7518 	 * maximum of the operands' minima
7519 	 */
7520 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7521 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7522 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7523 		/* Lose signed bounds when ORing negative numbers,
7524 		 * ain't nobody got time for that.
7525 		 */
7526 		dst_reg->smin_value = S64_MIN;
7527 		dst_reg->smax_value = S64_MAX;
7528 	} else {
7529 		/* ORing two positives gives a positive, so safe to
7530 		 * cast result into s64.
7531 		 */
7532 		dst_reg->smin_value = dst_reg->umin_value;
7533 		dst_reg->smax_value = dst_reg->umax_value;
7534 	}
7535 	/* We may learn something more from the var_off */
7536 	__update_reg_bounds(dst_reg);
7537 }
7538 
7539 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7540 				 struct bpf_reg_state *src_reg)
7541 {
7542 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7543 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7544 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7545 	s32 smin_val = src_reg->s32_min_value;
7546 
7547 	if (src_known && dst_known) {
7548 		__mark_reg32_known(dst_reg, var32_off.value);
7549 		return;
7550 	}
7551 
7552 	/* We get both minimum and maximum from the var32_off. */
7553 	dst_reg->u32_min_value = var32_off.value;
7554 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7555 
7556 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7557 		/* XORing two positive sign numbers gives a positive,
7558 		 * so safe to cast u32 result into s32.
7559 		 */
7560 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7561 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7562 	} else {
7563 		dst_reg->s32_min_value = S32_MIN;
7564 		dst_reg->s32_max_value = S32_MAX;
7565 	}
7566 }
7567 
7568 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7569 			       struct bpf_reg_state *src_reg)
7570 {
7571 	bool src_known = tnum_is_const(src_reg->var_off);
7572 	bool dst_known = tnum_is_const(dst_reg->var_off);
7573 	s64 smin_val = src_reg->smin_value;
7574 
7575 	if (src_known && dst_known) {
7576 		/* dst_reg->var_off.value has been updated earlier */
7577 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7578 		return;
7579 	}
7580 
7581 	/* We get both minimum and maximum from the var_off. */
7582 	dst_reg->umin_value = dst_reg->var_off.value;
7583 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7584 
7585 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7586 		/* XORing two positive sign numbers gives a positive,
7587 		 * so safe to cast u64 result into s64.
7588 		 */
7589 		dst_reg->smin_value = dst_reg->umin_value;
7590 		dst_reg->smax_value = dst_reg->umax_value;
7591 	} else {
7592 		dst_reg->smin_value = S64_MIN;
7593 		dst_reg->smax_value = S64_MAX;
7594 	}
7595 
7596 	__update_reg_bounds(dst_reg);
7597 }
7598 
7599 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7600 				   u64 umin_val, u64 umax_val)
7601 {
7602 	/* We lose all sign bit information (except what we can pick
7603 	 * up from var_off)
7604 	 */
7605 	dst_reg->s32_min_value = S32_MIN;
7606 	dst_reg->s32_max_value = S32_MAX;
7607 	/* If we might shift our top bit out, then we know nothing */
7608 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7609 		dst_reg->u32_min_value = 0;
7610 		dst_reg->u32_max_value = U32_MAX;
7611 	} else {
7612 		dst_reg->u32_min_value <<= umin_val;
7613 		dst_reg->u32_max_value <<= umax_val;
7614 	}
7615 }
7616 
7617 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7618 				 struct bpf_reg_state *src_reg)
7619 {
7620 	u32 umax_val = src_reg->u32_max_value;
7621 	u32 umin_val = src_reg->u32_min_value;
7622 	/* u32 alu operation will zext upper bits */
7623 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7624 
7625 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7626 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7627 	/* Not required but being careful mark reg64 bounds as unknown so
7628 	 * that we are forced to pick them up from tnum and zext later and
7629 	 * if some path skips this step we are still safe.
7630 	 */
7631 	__mark_reg64_unbounded(dst_reg);
7632 	__update_reg32_bounds(dst_reg);
7633 }
7634 
7635 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7636 				   u64 umin_val, u64 umax_val)
7637 {
7638 	/* Special case <<32 because it is a common compiler pattern to sign
7639 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7640 	 * positive we know this shift will also be positive so we can track
7641 	 * bounds correctly. Otherwise we lose all sign bit information except
7642 	 * what we can pick up from var_off. Perhaps we can generalize this
7643 	 * later to shifts of any length.
7644 	 */
7645 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7646 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7647 	else
7648 		dst_reg->smax_value = S64_MAX;
7649 
7650 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7651 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7652 	else
7653 		dst_reg->smin_value = S64_MIN;
7654 
7655 	/* If we might shift our top bit out, then we know nothing */
7656 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7657 		dst_reg->umin_value = 0;
7658 		dst_reg->umax_value = U64_MAX;
7659 	} else {
7660 		dst_reg->umin_value <<= umin_val;
7661 		dst_reg->umax_value <<= umax_val;
7662 	}
7663 }
7664 
7665 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7666 			       struct bpf_reg_state *src_reg)
7667 {
7668 	u64 umax_val = src_reg->umax_value;
7669 	u64 umin_val = src_reg->umin_value;
7670 
7671 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7672 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7673 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7674 
7675 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7676 	/* We may learn something more from the var_off */
7677 	__update_reg_bounds(dst_reg);
7678 }
7679 
7680 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7681 				 struct bpf_reg_state *src_reg)
7682 {
7683 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7684 	u32 umax_val = src_reg->u32_max_value;
7685 	u32 umin_val = src_reg->u32_min_value;
7686 
7687 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7688 	 * be negative, then either:
7689 	 * 1) src_reg might be zero, so the sign bit of the result is
7690 	 *    unknown, so we lose our signed bounds
7691 	 * 2) it's known negative, thus the unsigned bounds capture the
7692 	 *    signed bounds
7693 	 * 3) the signed bounds cross zero, so they tell us nothing
7694 	 *    about the result
7695 	 * If the value in dst_reg is known nonnegative, then again the
7696 	 * unsigned bounds capture the signed bounds.
7697 	 * Thus, in all cases it suffices to blow away our signed bounds
7698 	 * and rely on inferring new ones from the unsigned bounds and
7699 	 * var_off of the result.
7700 	 */
7701 	dst_reg->s32_min_value = S32_MIN;
7702 	dst_reg->s32_max_value = S32_MAX;
7703 
7704 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7705 	dst_reg->u32_min_value >>= umax_val;
7706 	dst_reg->u32_max_value >>= umin_val;
7707 
7708 	__mark_reg64_unbounded(dst_reg);
7709 	__update_reg32_bounds(dst_reg);
7710 }
7711 
7712 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7713 			       struct bpf_reg_state *src_reg)
7714 {
7715 	u64 umax_val = src_reg->umax_value;
7716 	u64 umin_val = src_reg->umin_value;
7717 
7718 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7719 	 * be negative, then either:
7720 	 * 1) src_reg might be zero, so the sign bit of the result is
7721 	 *    unknown, so we lose our signed bounds
7722 	 * 2) it's known negative, thus the unsigned bounds capture the
7723 	 *    signed bounds
7724 	 * 3) the signed bounds cross zero, so they tell us nothing
7725 	 *    about the result
7726 	 * If the value in dst_reg is known nonnegative, then again the
7727 	 * unsigned bounds capture the signed bounds.
7728 	 * Thus, in all cases it suffices to blow away our signed bounds
7729 	 * and rely on inferring new ones from the unsigned bounds and
7730 	 * var_off of the result.
7731 	 */
7732 	dst_reg->smin_value = S64_MIN;
7733 	dst_reg->smax_value = S64_MAX;
7734 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7735 	dst_reg->umin_value >>= umax_val;
7736 	dst_reg->umax_value >>= umin_val;
7737 
7738 	/* Its not easy to operate on alu32 bounds here because it depends
7739 	 * on bits being shifted in. Take easy way out and mark unbounded
7740 	 * so we can recalculate later from tnum.
7741 	 */
7742 	__mark_reg32_unbounded(dst_reg);
7743 	__update_reg_bounds(dst_reg);
7744 }
7745 
7746 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7747 				  struct bpf_reg_state *src_reg)
7748 {
7749 	u64 umin_val = src_reg->u32_min_value;
7750 
7751 	/* Upon reaching here, src_known is true and
7752 	 * umax_val is equal to umin_val.
7753 	 */
7754 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7755 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7756 
7757 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7758 
7759 	/* blow away the dst_reg umin_value/umax_value and rely on
7760 	 * dst_reg var_off to refine the result.
7761 	 */
7762 	dst_reg->u32_min_value = 0;
7763 	dst_reg->u32_max_value = U32_MAX;
7764 
7765 	__mark_reg64_unbounded(dst_reg);
7766 	__update_reg32_bounds(dst_reg);
7767 }
7768 
7769 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7770 				struct bpf_reg_state *src_reg)
7771 {
7772 	u64 umin_val = src_reg->umin_value;
7773 
7774 	/* Upon reaching here, src_known is true and umax_val is equal
7775 	 * to umin_val.
7776 	 */
7777 	dst_reg->smin_value >>= umin_val;
7778 	dst_reg->smax_value >>= umin_val;
7779 
7780 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7781 
7782 	/* blow away the dst_reg umin_value/umax_value and rely on
7783 	 * dst_reg var_off to refine the result.
7784 	 */
7785 	dst_reg->umin_value = 0;
7786 	dst_reg->umax_value = U64_MAX;
7787 
7788 	/* Its not easy to operate on alu32 bounds here because it depends
7789 	 * on bits being shifted in from upper 32-bits. Take easy way out
7790 	 * and mark unbounded so we can recalculate later from tnum.
7791 	 */
7792 	__mark_reg32_unbounded(dst_reg);
7793 	__update_reg_bounds(dst_reg);
7794 }
7795 
7796 /* WARNING: This function does calculations on 64-bit values, but the actual
7797  * execution may occur on 32-bit values. Therefore, things like bitshifts
7798  * need extra checks in the 32-bit case.
7799  */
7800 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7801 				      struct bpf_insn *insn,
7802 				      struct bpf_reg_state *dst_reg,
7803 				      struct bpf_reg_state src_reg)
7804 {
7805 	struct bpf_reg_state *regs = cur_regs(env);
7806 	u8 opcode = BPF_OP(insn->code);
7807 	bool src_known;
7808 	s64 smin_val, smax_val;
7809 	u64 umin_val, umax_val;
7810 	s32 s32_min_val, s32_max_val;
7811 	u32 u32_min_val, u32_max_val;
7812 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7813 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7814 	int ret;
7815 
7816 	smin_val = src_reg.smin_value;
7817 	smax_val = src_reg.smax_value;
7818 	umin_val = src_reg.umin_value;
7819 	umax_val = src_reg.umax_value;
7820 
7821 	s32_min_val = src_reg.s32_min_value;
7822 	s32_max_val = src_reg.s32_max_value;
7823 	u32_min_val = src_reg.u32_min_value;
7824 	u32_max_val = src_reg.u32_max_value;
7825 
7826 	if (alu32) {
7827 		src_known = tnum_subreg_is_const(src_reg.var_off);
7828 		if ((src_known &&
7829 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7830 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7831 			/* Taint dst register if offset had invalid bounds
7832 			 * derived from e.g. dead branches.
7833 			 */
7834 			__mark_reg_unknown(env, dst_reg);
7835 			return 0;
7836 		}
7837 	} else {
7838 		src_known = tnum_is_const(src_reg.var_off);
7839 		if ((src_known &&
7840 		     (smin_val != smax_val || umin_val != umax_val)) ||
7841 		    smin_val > smax_val || umin_val > umax_val) {
7842 			/* Taint dst register if offset had invalid bounds
7843 			 * derived from e.g. dead branches.
7844 			 */
7845 			__mark_reg_unknown(env, dst_reg);
7846 			return 0;
7847 		}
7848 	}
7849 
7850 	if (!src_known &&
7851 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7852 		__mark_reg_unknown(env, dst_reg);
7853 		return 0;
7854 	}
7855 
7856 	if (sanitize_needed(opcode)) {
7857 		ret = sanitize_val_alu(env, insn);
7858 		if (ret < 0)
7859 			return sanitize_err(env, insn, ret, NULL, NULL);
7860 	}
7861 
7862 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7863 	 * There are two classes of instructions: The first class we track both
7864 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
7865 	 * greatest amount of precision when alu operations are mixed with jmp32
7866 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7867 	 * and BPF_OR. This is possible because these ops have fairly easy to
7868 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7869 	 * See alu32 verifier tests for examples. The second class of
7870 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7871 	 * with regards to tracking sign/unsigned bounds because the bits may
7872 	 * cross subreg boundaries in the alu64 case. When this happens we mark
7873 	 * the reg unbounded in the subreg bound space and use the resulting
7874 	 * tnum to calculate an approximation of the sign/unsigned bounds.
7875 	 */
7876 	switch (opcode) {
7877 	case BPF_ADD:
7878 		scalar32_min_max_add(dst_reg, &src_reg);
7879 		scalar_min_max_add(dst_reg, &src_reg);
7880 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7881 		break;
7882 	case BPF_SUB:
7883 		scalar32_min_max_sub(dst_reg, &src_reg);
7884 		scalar_min_max_sub(dst_reg, &src_reg);
7885 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7886 		break;
7887 	case BPF_MUL:
7888 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7889 		scalar32_min_max_mul(dst_reg, &src_reg);
7890 		scalar_min_max_mul(dst_reg, &src_reg);
7891 		break;
7892 	case BPF_AND:
7893 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7894 		scalar32_min_max_and(dst_reg, &src_reg);
7895 		scalar_min_max_and(dst_reg, &src_reg);
7896 		break;
7897 	case BPF_OR:
7898 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7899 		scalar32_min_max_or(dst_reg, &src_reg);
7900 		scalar_min_max_or(dst_reg, &src_reg);
7901 		break;
7902 	case BPF_XOR:
7903 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7904 		scalar32_min_max_xor(dst_reg, &src_reg);
7905 		scalar_min_max_xor(dst_reg, &src_reg);
7906 		break;
7907 	case BPF_LSH:
7908 		if (umax_val >= insn_bitness) {
7909 			/* Shifts greater than 31 or 63 are undefined.
7910 			 * This includes shifts by a negative number.
7911 			 */
7912 			mark_reg_unknown(env, regs, insn->dst_reg);
7913 			break;
7914 		}
7915 		if (alu32)
7916 			scalar32_min_max_lsh(dst_reg, &src_reg);
7917 		else
7918 			scalar_min_max_lsh(dst_reg, &src_reg);
7919 		break;
7920 	case BPF_RSH:
7921 		if (umax_val >= insn_bitness) {
7922 			/* Shifts greater than 31 or 63 are undefined.
7923 			 * This includes shifts by a negative number.
7924 			 */
7925 			mark_reg_unknown(env, regs, insn->dst_reg);
7926 			break;
7927 		}
7928 		if (alu32)
7929 			scalar32_min_max_rsh(dst_reg, &src_reg);
7930 		else
7931 			scalar_min_max_rsh(dst_reg, &src_reg);
7932 		break;
7933 	case BPF_ARSH:
7934 		if (umax_val >= insn_bitness) {
7935 			/* Shifts greater than 31 or 63 are undefined.
7936 			 * This includes shifts by a negative number.
7937 			 */
7938 			mark_reg_unknown(env, regs, insn->dst_reg);
7939 			break;
7940 		}
7941 		if (alu32)
7942 			scalar32_min_max_arsh(dst_reg, &src_reg);
7943 		else
7944 			scalar_min_max_arsh(dst_reg, &src_reg);
7945 		break;
7946 	default:
7947 		mark_reg_unknown(env, regs, insn->dst_reg);
7948 		break;
7949 	}
7950 
7951 	/* ALU32 ops are zero extended into 64bit register */
7952 	if (alu32)
7953 		zext_32_to_64(dst_reg);
7954 
7955 	__update_reg_bounds(dst_reg);
7956 	__reg_deduce_bounds(dst_reg);
7957 	__reg_bound_offset(dst_reg);
7958 	return 0;
7959 }
7960 
7961 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7962  * and var_off.
7963  */
7964 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7965 				   struct bpf_insn *insn)
7966 {
7967 	struct bpf_verifier_state *vstate = env->cur_state;
7968 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7969 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7970 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7971 	u8 opcode = BPF_OP(insn->code);
7972 	int err;
7973 
7974 	dst_reg = &regs[insn->dst_reg];
7975 	src_reg = NULL;
7976 	if (dst_reg->type != SCALAR_VALUE)
7977 		ptr_reg = dst_reg;
7978 	else
7979 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7980 		 * incorrectly propagated into other registers by find_equal_scalars()
7981 		 */
7982 		dst_reg->id = 0;
7983 	if (BPF_SRC(insn->code) == BPF_X) {
7984 		src_reg = &regs[insn->src_reg];
7985 		if (src_reg->type != SCALAR_VALUE) {
7986 			if (dst_reg->type != SCALAR_VALUE) {
7987 				/* Combining two pointers by any ALU op yields
7988 				 * an arbitrary scalar. Disallow all math except
7989 				 * pointer subtraction
7990 				 */
7991 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7992 					mark_reg_unknown(env, regs, insn->dst_reg);
7993 					return 0;
7994 				}
7995 				verbose(env, "R%d pointer %s pointer prohibited\n",
7996 					insn->dst_reg,
7997 					bpf_alu_string[opcode >> 4]);
7998 				return -EACCES;
7999 			} else {
8000 				/* scalar += pointer
8001 				 * This is legal, but we have to reverse our
8002 				 * src/dest handling in computing the range
8003 				 */
8004 				err = mark_chain_precision(env, insn->dst_reg);
8005 				if (err)
8006 					return err;
8007 				return adjust_ptr_min_max_vals(env, insn,
8008 							       src_reg, dst_reg);
8009 			}
8010 		} else if (ptr_reg) {
8011 			/* pointer += scalar */
8012 			err = mark_chain_precision(env, insn->src_reg);
8013 			if (err)
8014 				return err;
8015 			return adjust_ptr_min_max_vals(env, insn,
8016 						       dst_reg, src_reg);
8017 		}
8018 	} else {
8019 		/* Pretend the src is a reg with a known value, since we only
8020 		 * need to be able to read from this state.
8021 		 */
8022 		off_reg.type = SCALAR_VALUE;
8023 		__mark_reg_known(&off_reg, insn->imm);
8024 		src_reg = &off_reg;
8025 		if (ptr_reg) /* pointer += K */
8026 			return adjust_ptr_min_max_vals(env, insn,
8027 						       ptr_reg, src_reg);
8028 	}
8029 
8030 	/* Got here implies adding two SCALAR_VALUEs */
8031 	if (WARN_ON_ONCE(ptr_reg)) {
8032 		print_verifier_state(env, state);
8033 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8034 		return -EINVAL;
8035 	}
8036 	if (WARN_ON(!src_reg)) {
8037 		print_verifier_state(env, state);
8038 		verbose(env, "verifier internal error: no src_reg\n");
8039 		return -EINVAL;
8040 	}
8041 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8042 }
8043 
8044 /* check validity of 32-bit and 64-bit arithmetic operations */
8045 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8046 {
8047 	struct bpf_reg_state *regs = cur_regs(env);
8048 	u8 opcode = BPF_OP(insn->code);
8049 	int err;
8050 
8051 	if (opcode == BPF_END || opcode == BPF_NEG) {
8052 		if (opcode == BPF_NEG) {
8053 			if (BPF_SRC(insn->code) != 0 ||
8054 			    insn->src_reg != BPF_REG_0 ||
8055 			    insn->off != 0 || insn->imm != 0) {
8056 				verbose(env, "BPF_NEG uses reserved fields\n");
8057 				return -EINVAL;
8058 			}
8059 		} else {
8060 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8061 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8062 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8063 				verbose(env, "BPF_END uses reserved fields\n");
8064 				return -EINVAL;
8065 			}
8066 		}
8067 
8068 		/* check src operand */
8069 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8070 		if (err)
8071 			return err;
8072 
8073 		if (is_pointer_value(env, insn->dst_reg)) {
8074 			verbose(env, "R%d pointer arithmetic prohibited\n",
8075 				insn->dst_reg);
8076 			return -EACCES;
8077 		}
8078 
8079 		/* check dest operand */
8080 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8081 		if (err)
8082 			return err;
8083 
8084 	} else if (opcode == BPF_MOV) {
8085 
8086 		if (BPF_SRC(insn->code) == BPF_X) {
8087 			if (insn->imm != 0 || insn->off != 0) {
8088 				verbose(env, "BPF_MOV uses reserved fields\n");
8089 				return -EINVAL;
8090 			}
8091 
8092 			/* check src operand */
8093 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8094 			if (err)
8095 				return err;
8096 		} else {
8097 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8098 				verbose(env, "BPF_MOV uses reserved fields\n");
8099 				return -EINVAL;
8100 			}
8101 		}
8102 
8103 		/* check dest operand, mark as required later */
8104 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8105 		if (err)
8106 			return err;
8107 
8108 		if (BPF_SRC(insn->code) == BPF_X) {
8109 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8110 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8111 
8112 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8113 				/* case: R1 = R2
8114 				 * copy register state to dest reg
8115 				 */
8116 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8117 					/* Assign src and dst registers the same ID
8118 					 * that will be used by find_equal_scalars()
8119 					 * to propagate min/max range.
8120 					 */
8121 					src_reg->id = ++env->id_gen;
8122 				*dst_reg = *src_reg;
8123 				dst_reg->live |= REG_LIVE_WRITTEN;
8124 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8125 			} else {
8126 				/* R1 = (u32) R2 */
8127 				if (is_pointer_value(env, insn->src_reg)) {
8128 					verbose(env,
8129 						"R%d partial copy of pointer\n",
8130 						insn->src_reg);
8131 					return -EACCES;
8132 				} else if (src_reg->type == SCALAR_VALUE) {
8133 					*dst_reg = *src_reg;
8134 					/* Make sure ID is cleared otherwise
8135 					 * dst_reg min/max could be incorrectly
8136 					 * propagated into src_reg by find_equal_scalars()
8137 					 */
8138 					dst_reg->id = 0;
8139 					dst_reg->live |= REG_LIVE_WRITTEN;
8140 					dst_reg->subreg_def = env->insn_idx + 1;
8141 				} else {
8142 					mark_reg_unknown(env, regs,
8143 							 insn->dst_reg);
8144 				}
8145 				zext_32_to_64(dst_reg);
8146 			}
8147 		} else {
8148 			/* case: R = imm
8149 			 * remember the value we stored into this reg
8150 			 */
8151 			/* clear any state __mark_reg_known doesn't set */
8152 			mark_reg_unknown(env, regs, insn->dst_reg);
8153 			regs[insn->dst_reg].type = SCALAR_VALUE;
8154 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8155 				__mark_reg_known(regs + insn->dst_reg,
8156 						 insn->imm);
8157 			} else {
8158 				__mark_reg_known(regs + insn->dst_reg,
8159 						 (u32)insn->imm);
8160 			}
8161 		}
8162 
8163 	} else if (opcode > BPF_END) {
8164 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8165 		return -EINVAL;
8166 
8167 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8168 
8169 		if (BPF_SRC(insn->code) == BPF_X) {
8170 			if (insn->imm != 0 || insn->off != 0) {
8171 				verbose(env, "BPF_ALU uses reserved fields\n");
8172 				return -EINVAL;
8173 			}
8174 			/* check src1 operand */
8175 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8176 			if (err)
8177 				return err;
8178 		} else {
8179 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8180 				verbose(env, "BPF_ALU uses reserved fields\n");
8181 				return -EINVAL;
8182 			}
8183 		}
8184 
8185 		/* check src2 operand */
8186 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8187 		if (err)
8188 			return err;
8189 
8190 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8191 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8192 			verbose(env, "div by zero\n");
8193 			return -EINVAL;
8194 		}
8195 
8196 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8197 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8198 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8199 
8200 			if (insn->imm < 0 || insn->imm >= size) {
8201 				verbose(env, "invalid shift %d\n", insn->imm);
8202 				return -EINVAL;
8203 			}
8204 		}
8205 
8206 		/* check dest operand */
8207 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8208 		if (err)
8209 			return err;
8210 
8211 		return adjust_reg_min_max_vals(env, insn);
8212 	}
8213 
8214 	return 0;
8215 }
8216 
8217 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8218 				     struct bpf_reg_state *dst_reg,
8219 				     enum bpf_reg_type type, int new_range)
8220 {
8221 	struct bpf_reg_state *reg;
8222 	int i;
8223 
8224 	for (i = 0; i < MAX_BPF_REG; i++) {
8225 		reg = &state->regs[i];
8226 		if (reg->type == type && reg->id == dst_reg->id)
8227 			/* keep the maximum range already checked */
8228 			reg->range = max(reg->range, new_range);
8229 	}
8230 
8231 	bpf_for_each_spilled_reg(i, state, reg) {
8232 		if (!reg)
8233 			continue;
8234 		if (reg->type == type && reg->id == dst_reg->id)
8235 			reg->range = max(reg->range, new_range);
8236 	}
8237 }
8238 
8239 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8240 				   struct bpf_reg_state *dst_reg,
8241 				   enum bpf_reg_type type,
8242 				   bool range_right_open)
8243 {
8244 	int new_range, i;
8245 
8246 	if (dst_reg->off < 0 ||
8247 	    (dst_reg->off == 0 && range_right_open))
8248 		/* This doesn't give us any range */
8249 		return;
8250 
8251 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8252 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8253 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8254 		 * than pkt_end, but that's because it's also less than pkt.
8255 		 */
8256 		return;
8257 
8258 	new_range = dst_reg->off;
8259 	if (range_right_open)
8260 		new_range--;
8261 
8262 	/* Examples for register markings:
8263 	 *
8264 	 * pkt_data in dst register:
8265 	 *
8266 	 *   r2 = r3;
8267 	 *   r2 += 8;
8268 	 *   if (r2 > pkt_end) goto <handle exception>
8269 	 *   <access okay>
8270 	 *
8271 	 *   r2 = r3;
8272 	 *   r2 += 8;
8273 	 *   if (r2 < pkt_end) goto <access okay>
8274 	 *   <handle exception>
8275 	 *
8276 	 *   Where:
8277 	 *     r2 == dst_reg, pkt_end == src_reg
8278 	 *     r2=pkt(id=n,off=8,r=0)
8279 	 *     r3=pkt(id=n,off=0,r=0)
8280 	 *
8281 	 * pkt_data in src register:
8282 	 *
8283 	 *   r2 = r3;
8284 	 *   r2 += 8;
8285 	 *   if (pkt_end >= r2) goto <access okay>
8286 	 *   <handle exception>
8287 	 *
8288 	 *   r2 = r3;
8289 	 *   r2 += 8;
8290 	 *   if (pkt_end <= r2) goto <handle exception>
8291 	 *   <access okay>
8292 	 *
8293 	 *   Where:
8294 	 *     pkt_end == dst_reg, r2 == src_reg
8295 	 *     r2=pkt(id=n,off=8,r=0)
8296 	 *     r3=pkt(id=n,off=0,r=0)
8297 	 *
8298 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8299 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8300 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8301 	 * the check.
8302 	 */
8303 
8304 	/* If our ids match, then we must have the same max_value.  And we
8305 	 * don't care about the other reg's fixed offset, since if it's too big
8306 	 * the range won't allow anything.
8307 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8308 	 */
8309 	for (i = 0; i <= vstate->curframe; i++)
8310 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8311 					 new_range);
8312 }
8313 
8314 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8315 {
8316 	struct tnum subreg = tnum_subreg(reg->var_off);
8317 	s32 sval = (s32)val;
8318 
8319 	switch (opcode) {
8320 	case BPF_JEQ:
8321 		if (tnum_is_const(subreg))
8322 			return !!tnum_equals_const(subreg, val);
8323 		break;
8324 	case BPF_JNE:
8325 		if (tnum_is_const(subreg))
8326 			return !tnum_equals_const(subreg, val);
8327 		break;
8328 	case BPF_JSET:
8329 		if ((~subreg.mask & subreg.value) & val)
8330 			return 1;
8331 		if (!((subreg.mask | subreg.value) & val))
8332 			return 0;
8333 		break;
8334 	case BPF_JGT:
8335 		if (reg->u32_min_value > val)
8336 			return 1;
8337 		else if (reg->u32_max_value <= val)
8338 			return 0;
8339 		break;
8340 	case BPF_JSGT:
8341 		if (reg->s32_min_value > sval)
8342 			return 1;
8343 		else if (reg->s32_max_value <= sval)
8344 			return 0;
8345 		break;
8346 	case BPF_JLT:
8347 		if (reg->u32_max_value < val)
8348 			return 1;
8349 		else if (reg->u32_min_value >= val)
8350 			return 0;
8351 		break;
8352 	case BPF_JSLT:
8353 		if (reg->s32_max_value < sval)
8354 			return 1;
8355 		else if (reg->s32_min_value >= sval)
8356 			return 0;
8357 		break;
8358 	case BPF_JGE:
8359 		if (reg->u32_min_value >= val)
8360 			return 1;
8361 		else if (reg->u32_max_value < val)
8362 			return 0;
8363 		break;
8364 	case BPF_JSGE:
8365 		if (reg->s32_min_value >= sval)
8366 			return 1;
8367 		else if (reg->s32_max_value < sval)
8368 			return 0;
8369 		break;
8370 	case BPF_JLE:
8371 		if (reg->u32_max_value <= val)
8372 			return 1;
8373 		else if (reg->u32_min_value > val)
8374 			return 0;
8375 		break;
8376 	case BPF_JSLE:
8377 		if (reg->s32_max_value <= sval)
8378 			return 1;
8379 		else if (reg->s32_min_value > sval)
8380 			return 0;
8381 		break;
8382 	}
8383 
8384 	return -1;
8385 }
8386 
8387 
8388 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8389 {
8390 	s64 sval = (s64)val;
8391 
8392 	switch (opcode) {
8393 	case BPF_JEQ:
8394 		if (tnum_is_const(reg->var_off))
8395 			return !!tnum_equals_const(reg->var_off, val);
8396 		break;
8397 	case BPF_JNE:
8398 		if (tnum_is_const(reg->var_off))
8399 			return !tnum_equals_const(reg->var_off, val);
8400 		break;
8401 	case BPF_JSET:
8402 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8403 			return 1;
8404 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8405 			return 0;
8406 		break;
8407 	case BPF_JGT:
8408 		if (reg->umin_value > val)
8409 			return 1;
8410 		else if (reg->umax_value <= val)
8411 			return 0;
8412 		break;
8413 	case BPF_JSGT:
8414 		if (reg->smin_value > sval)
8415 			return 1;
8416 		else if (reg->smax_value <= sval)
8417 			return 0;
8418 		break;
8419 	case BPF_JLT:
8420 		if (reg->umax_value < val)
8421 			return 1;
8422 		else if (reg->umin_value >= val)
8423 			return 0;
8424 		break;
8425 	case BPF_JSLT:
8426 		if (reg->smax_value < sval)
8427 			return 1;
8428 		else if (reg->smin_value >= sval)
8429 			return 0;
8430 		break;
8431 	case BPF_JGE:
8432 		if (reg->umin_value >= val)
8433 			return 1;
8434 		else if (reg->umax_value < val)
8435 			return 0;
8436 		break;
8437 	case BPF_JSGE:
8438 		if (reg->smin_value >= sval)
8439 			return 1;
8440 		else if (reg->smax_value < sval)
8441 			return 0;
8442 		break;
8443 	case BPF_JLE:
8444 		if (reg->umax_value <= val)
8445 			return 1;
8446 		else if (reg->umin_value > val)
8447 			return 0;
8448 		break;
8449 	case BPF_JSLE:
8450 		if (reg->smax_value <= sval)
8451 			return 1;
8452 		else if (reg->smin_value > sval)
8453 			return 0;
8454 		break;
8455 	}
8456 
8457 	return -1;
8458 }
8459 
8460 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8461  * and return:
8462  *  1 - branch will be taken and "goto target" will be executed
8463  *  0 - branch will not be taken and fall-through to next insn
8464  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8465  *      range [0,10]
8466  */
8467 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8468 			   bool is_jmp32)
8469 {
8470 	if (__is_pointer_value(false, reg)) {
8471 		if (!reg_type_not_null(reg->type))
8472 			return -1;
8473 
8474 		/* If pointer is valid tests against zero will fail so we can
8475 		 * use this to direct branch taken.
8476 		 */
8477 		if (val != 0)
8478 			return -1;
8479 
8480 		switch (opcode) {
8481 		case BPF_JEQ:
8482 			return 0;
8483 		case BPF_JNE:
8484 			return 1;
8485 		default:
8486 			return -1;
8487 		}
8488 	}
8489 
8490 	if (is_jmp32)
8491 		return is_branch32_taken(reg, val, opcode);
8492 	return is_branch64_taken(reg, val, opcode);
8493 }
8494 
8495 static int flip_opcode(u32 opcode)
8496 {
8497 	/* How can we transform "a <op> b" into "b <op> a"? */
8498 	static const u8 opcode_flip[16] = {
8499 		/* these stay the same */
8500 		[BPF_JEQ  >> 4] = BPF_JEQ,
8501 		[BPF_JNE  >> 4] = BPF_JNE,
8502 		[BPF_JSET >> 4] = BPF_JSET,
8503 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8504 		[BPF_JGE  >> 4] = BPF_JLE,
8505 		[BPF_JGT  >> 4] = BPF_JLT,
8506 		[BPF_JLE  >> 4] = BPF_JGE,
8507 		[BPF_JLT  >> 4] = BPF_JGT,
8508 		[BPF_JSGE >> 4] = BPF_JSLE,
8509 		[BPF_JSGT >> 4] = BPF_JSLT,
8510 		[BPF_JSLE >> 4] = BPF_JSGE,
8511 		[BPF_JSLT >> 4] = BPF_JSGT
8512 	};
8513 	return opcode_flip[opcode >> 4];
8514 }
8515 
8516 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8517 				   struct bpf_reg_state *src_reg,
8518 				   u8 opcode)
8519 {
8520 	struct bpf_reg_state *pkt;
8521 
8522 	if (src_reg->type == PTR_TO_PACKET_END) {
8523 		pkt = dst_reg;
8524 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8525 		pkt = src_reg;
8526 		opcode = flip_opcode(opcode);
8527 	} else {
8528 		return -1;
8529 	}
8530 
8531 	if (pkt->range >= 0)
8532 		return -1;
8533 
8534 	switch (opcode) {
8535 	case BPF_JLE:
8536 		/* pkt <= pkt_end */
8537 		fallthrough;
8538 	case BPF_JGT:
8539 		/* pkt > pkt_end */
8540 		if (pkt->range == BEYOND_PKT_END)
8541 			/* pkt has at last one extra byte beyond pkt_end */
8542 			return opcode == BPF_JGT;
8543 		break;
8544 	case BPF_JLT:
8545 		/* pkt < pkt_end */
8546 		fallthrough;
8547 	case BPF_JGE:
8548 		/* pkt >= pkt_end */
8549 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8550 			return opcode == BPF_JGE;
8551 		break;
8552 	}
8553 	return -1;
8554 }
8555 
8556 /* Adjusts the register min/max values in the case that the dst_reg is the
8557  * variable register that we are working on, and src_reg is a constant or we're
8558  * simply doing a BPF_K check.
8559  * In JEQ/JNE cases we also adjust the var_off values.
8560  */
8561 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8562 			    struct bpf_reg_state *false_reg,
8563 			    u64 val, u32 val32,
8564 			    u8 opcode, bool is_jmp32)
8565 {
8566 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8567 	struct tnum false_64off = false_reg->var_off;
8568 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8569 	struct tnum true_64off = true_reg->var_off;
8570 	s64 sval = (s64)val;
8571 	s32 sval32 = (s32)val32;
8572 
8573 	/* If the dst_reg is a pointer, we can't learn anything about its
8574 	 * variable offset from the compare (unless src_reg were a pointer into
8575 	 * the same object, but we don't bother with that.
8576 	 * Since false_reg and true_reg have the same type by construction, we
8577 	 * only need to check one of them for pointerness.
8578 	 */
8579 	if (__is_pointer_value(false, false_reg))
8580 		return;
8581 
8582 	switch (opcode) {
8583 	case BPF_JEQ:
8584 	case BPF_JNE:
8585 	{
8586 		struct bpf_reg_state *reg =
8587 			opcode == BPF_JEQ ? true_reg : false_reg;
8588 
8589 		/* JEQ/JNE comparison doesn't change the register equivalence.
8590 		 * r1 = r2;
8591 		 * if (r1 == 42) goto label;
8592 		 * ...
8593 		 * label: // here both r1 and r2 are known to be 42.
8594 		 *
8595 		 * Hence when marking register as known preserve it's ID.
8596 		 */
8597 		if (is_jmp32)
8598 			__mark_reg32_known(reg, val32);
8599 		else
8600 			___mark_reg_known(reg, val);
8601 		break;
8602 	}
8603 	case BPF_JSET:
8604 		if (is_jmp32) {
8605 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8606 			if (is_power_of_2(val32))
8607 				true_32off = tnum_or(true_32off,
8608 						     tnum_const(val32));
8609 		} else {
8610 			false_64off = tnum_and(false_64off, tnum_const(~val));
8611 			if (is_power_of_2(val))
8612 				true_64off = tnum_or(true_64off,
8613 						     tnum_const(val));
8614 		}
8615 		break;
8616 	case BPF_JGE:
8617 	case BPF_JGT:
8618 	{
8619 		if (is_jmp32) {
8620 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8621 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8622 
8623 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8624 						       false_umax);
8625 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8626 						      true_umin);
8627 		} else {
8628 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8629 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8630 
8631 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8632 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8633 		}
8634 		break;
8635 	}
8636 	case BPF_JSGE:
8637 	case BPF_JSGT:
8638 	{
8639 		if (is_jmp32) {
8640 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8641 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8642 
8643 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8644 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8645 		} else {
8646 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8647 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8648 
8649 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8650 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8651 		}
8652 		break;
8653 	}
8654 	case BPF_JLE:
8655 	case BPF_JLT:
8656 	{
8657 		if (is_jmp32) {
8658 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8659 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8660 
8661 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8662 						       false_umin);
8663 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8664 						      true_umax);
8665 		} else {
8666 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8667 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8668 
8669 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8670 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8671 		}
8672 		break;
8673 	}
8674 	case BPF_JSLE:
8675 	case BPF_JSLT:
8676 	{
8677 		if (is_jmp32) {
8678 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8679 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8680 
8681 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8682 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8683 		} else {
8684 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8685 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8686 
8687 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8688 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8689 		}
8690 		break;
8691 	}
8692 	default:
8693 		return;
8694 	}
8695 
8696 	if (is_jmp32) {
8697 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8698 					     tnum_subreg(false_32off));
8699 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8700 					    tnum_subreg(true_32off));
8701 		__reg_combine_32_into_64(false_reg);
8702 		__reg_combine_32_into_64(true_reg);
8703 	} else {
8704 		false_reg->var_off = false_64off;
8705 		true_reg->var_off = true_64off;
8706 		__reg_combine_64_into_32(false_reg);
8707 		__reg_combine_64_into_32(true_reg);
8708 	}
8709 }
8710 
8711 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8712  * the variable reg.
8713  */
8714 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8715 				struct bpf_reg_state *false_reg,
8716 				u64 val, u32 val32,
8717 				u8 opcode, bool is_jmp32)
8718 {
8719 	opcode = flip_opcode(opcode);
8720 	/* This uses zero as "not present in table"; luckily the zero opcode,
8721 	 * BPF_JA, can't get here.
8722 	 */
8723 	if (opcode)
8724 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8725 }
8726 
8727 /* Regs are known to be equal, so intersect their min/max/var_off */
8728 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8729 				  struct bpf_reg_state *dst_reg)
8730 {
8731 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8732 							dst_reg->umin_value);
8733 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8734 							dst_reg->umax_value);
8735 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8736 							dst_reg->smin_value);
8737 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8738 							dst_reg->smax_value);
8739 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8740 							     dst_reg->var_off);
8741 	/* We might have learned new bounds from the var_off. */
8742 	__update_reg_bounds(src_reg);
8743 	__update_reg_bounds(dst_reg);
8744 	/* We might have learned something about the sign bit. */
8745 	__reg_deduce_bounds(src_reg);
8746 	__reg_deduce_bounds(dst_reg);
8747 	/* We might have learned some bits from the bounds. */
8748 	__reg_bound_offset(src_reg);
8749 	__reg_bound_offset(dst_reg);
8750 	/* Intersecting with the old var_off might have improved our bounds
8751 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8752 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
8753 	 */
8754 	__update_reg_bounds(src_reg);
8755 	__update_reg_bounds(dst_reg);
8756 }
8757 
8758 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8759 				struct bpf_reg_state *true_dst,
8760 				struct bpf_reg_state *false_src,
8761 				struct bpf_reg_state *false_dst,
8762 				u8 opcode)
8763 {
8764 	switch (opcode) {
8765 	case BPF_JEQ:
8766 		__reg_combine_min_max(true_src, true_dst);
8767 		break;
8768 	case BPF_JNE:
8769 		__reg_combine_min_max(false_src, false_dst);
8770 		break;
8771 	}
8772 }
8773 
8774 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8775 				 struct bpf_reg_state *reg, u32 id,
8776 				 bool is_null)
8777 {
8778 	if (reg_type_may_be_null(reg->type) && reg->id == id &&
8779 	    !WARN_ON_ONCE(!reg->id)) {
8780 		/* Old offset (both fixed and variable parts) should
8781 		 * have been known-zero, because we don't allow pointer
8782 		 * arithmetic on pointers that might be NULL.
8783 		 */
8784 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8785 				 !tnum_equals_const(reg->var_off, 0) ||
8786 				 reg->off)) {
8787 			__mark_reg_known_zero(reg);
8788 			reg->off = 0;
8789 		}
8790 		if (is_null) {
8791 			reg->type = SCALAR_VALUE;
8792 			/* We don't need id and ref_obj_id from this point
8793 			 * onwards anymore, thus we should better reset it,
8794 			 * so that state pruning has chances to take effect.
8795 			 */
8796 			reg->id = 0;
8797 			reg->ref_obj_id = 0;
8798 
8799 			return;
8800 		}
8801 
8802 		mark_ptr_not_null_reg(reg);
8803 
8804 		if (!reg_may_point_to_spin_lock(reg)) {
8805 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8806 			 * in release_reg_references().
8807 			 *
8808 			 * reg->id is still used by spin_lock ptr. Other
8809 			 * than spin_lock ptr type, reg->id can be reset.
8810 			 */
8811 			reg->id = 0;
8812 		}
8813 	}
8814 }
8815 
8816 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8817 				    bool is_null)
8818 {
8819 	struct bpf_reg_state *reg;
8820 	int i;
8821 
8822 	for (i = 0; i < MAX_BPF_REG; i++)
8823 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8824 
8825 	bpf_for_each_spilled_reg(i, state, reg) {
8826 		if (!reg)
8827 			continue;
8828 		mark_ptr_or_null_reg(state, reg, id, is_null);
8829 	}
8830 }
8831 
8832 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8833  * be folded together at some point.
8834  */
8835 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8836 				  bool is_null)
8837 {
8838 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8839 	struct bpf_reg_state *regs = state->regs;
8840 	u32 ref_obj_id = regs[regno].ref_obj_id;
8841 	u32 id = regs[regno].id;
8842 	int i;
8843 
8844 	if (ref_obj_id && ref_obj_id == id && is_null)
8845 		/* regs[regno] is in the " == NULL" branch.
8846 		 * No one could have freed the reference state before
8847 		 * doing the NULL check.
8848 		 */
8849 		WARN_ON_ONCE(release_reference_state(state, id));
8850 
8851 	for (i = 0; i <= vstate->curframe; i++)
8852 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8853 }
8854 
8855 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8856 				   struct bpf_reg_state *dst_reg,
8857 				   struct bpf_reg_state *src_reg,
8858 				   struct bpf_verifier_state *this_branch,
8859 				   struct bpf_verifier_state *other_branch)
8860 {
8861 	if (BPF_SRC(insn->code) != BPF_X)
8862 		return false;
8863 
8864 	/* Pointers are always 64-bit. */
8865 	if (BPF_CLASS(insn->code) == BPF_JMP32)
8866 		return false;
8867 
8868 	switch (BPF_OP(insn->code)) {
8869 	case BPF_JGT:
8870 		if ((dst_reg->type == PTR_TO_PACKET &&
8871 		     src_reg->type == PTR_TO_PACKET_END) ||
8872 		    (dst_reg->type == PTR_TO_PACKET_META &&
8873 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8874 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8875 			find_good_pkt_pointers(this_branch, dst_reg,
8876 					       dst_reg->type, false);
8877 			mark_pkt_end(other_branch, insn->dst_reg, true);
8878 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8879 			    src_reg->type == PTR_TO_PACKET) ||
8880 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8881 			    src_reg->type == PTR_TO_PACKET_META)) {
8882 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
8883 			find_good_pkt_pointers(other_branch, src_reg,
8884 					       src_reg->type, true);
8885 			mark_pkt_end(this_branch, insn->src_reg, false);
8886 		} else {
8887 			return false;
8888 		}
8889 		break;
8890 	case BPF_JLT:
8891 		if ((dst_reg->type == PTR_TO_PACKET &&
8892 		     src_reg->type == PTR_TO_PACKET_END) ||
8893 		    (dst_reg->type == PTR_TO_PACKET_META &&
8894 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8895 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8896 			find_good_pkt_pointers(other_branch, dst_reg,
8897 					       dst_reg->type, true);
8898 			mark_pkt_end(this_branch, insn->dst_reg, false);
8899 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8900 			    src_reg->type == PTR_TO_PACKET) ||
8901 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8902 			    src_reg->type == PTR_TO_PACKET_META)) {
8903 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
8904 			find_good_pkt_pointers(this_branch, src_reg,
8905 					       src_reg->type, false);
8906 			mark_pkt_end(other_branch, insn->src_reg, true);
8907 		} else {
8908 			return false;
8909 		}
8910 		break;
8911 	case BPF_JGE:
8912 		if ((dst_reg->type == PTR_TO_PACKET &&
8913 		     src_reg->type == PTR_TO_PACKET_END) ||
8914 		    (dst_reg->type == PTR_TO_PACKET_META &&
8915 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8916 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8917 			find_good_pkt_pointers(this_branch, dst_reg,
8918 					       dst_reg->type, true);
8919 			mark_pkt_end(other_branch, insn->dst_reg, false);
8920 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8921 			    src_reg->type == PTR_TO_PACKET) ||
8922 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8923 			    src_reg->type == PTR_TO_PACKET_META)) {
8924 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8925 			find_good_pkt_pointers(other_branch, src_reg,
8926 					       src_reg->type, false);
8927 			mark_pkt_end(this_branch, insn->src_reg, true);
8928 		} else {
8929 			return false;
8930 		}
8931 		break;
8932 	case BPF_JLE:
8933 		if ((dst_reg->type == PTR_TO_PACKET &&
8934 		     src_reg->type == PTR_TO_PACKET_END) ||
8935 		    (dst_reg->type == PTR_TO_PACKET_META &&
8936 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8937 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8938 			find_good_pkt_pointers(other_branch, dst_reg,
8939 					       dst_reg->type, false);
8940 			mark_pkt_end(this_branch, insn->dst_reg, true);
8941 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8942 			    src_reg->type == PTR_TO_PACKET) ||
8943 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8944 			    src_reg->type == PTR_TO_PACKET_META)) {
8945 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8946 			find_good_pkt_pointers(this_branch, src_reg,
8947 					       src_reg->type, true);
8948 			mark_pkt_end(other_branch, insn->src_reg, false);
8949 		} else {
8950 			return false;
8951 		}
8952 		break;
8953 	default:
8954 		return false;
8955 	}
8956 
8957 	return true;
8958 }
8959 
8960 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8961 			       struct bpf_reg_state *known_reg)
8962 {
8963 	struct bpf_func_state *state;
8964 	struct bpf_reg_state *reg;
8965 	int i, j;
8966 
8967 	for (i = 0; i <= vstate->curframe; i++) {
8968 		state = vstate->frame[i];
8969 		for (j = 0; j < MAX_BPF_REG; j++) {
8970 			reg = &state->regs[j];
8971 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8972 				*reg = *known_reg;
8973 		}
8974 
8975 		bpf_for_each_spilled_reg(j, state, reg) {
8976 			if (!reg)
8977 				continue;
8978 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8979 				*reg = *known_reg;
8980 		}
8981 	}
8982 }
8983 
8984 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8985 			     struct bpf_insn *insn, int *insn_idx)
8986 {
8987 	struct bpf_verifier_state *this_branch = env->cur_state;
8988 	struct bpf_verifier_state *other_branch;
8989 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8990 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8991 	u8 opcode = BPF_OP(insn->code);
8992 	bool is_jmp32;
8993 	int pred = -1;
8994 	int err;
8995 
8996 	/* Only conditional jumps are expected to reach here. */
8997 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8998 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8999 		return -EINVAL;
9000 	}
9001 
9002 	if (BPF_SRC(insn->code) == BPF_X) {
9003 		if (insn->imm != 0) {
9004 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9005 			return -EINVAL;
9006 		}
9007 
9008 		/* check src1 operand */
9009 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9010 		if (err)
9011 			return err;
9012 
9013 		if (is_pointer_value(env, insn->src_reg)) {
9014 			verbose(env, "R%d pointer comparison prohibited\n",
9015 				insn->src_reg);
9016 			return -EACCES;
9017 		}
9018 		src_reg = &regs[insn->src_reg];
9019 	} else {
9020 		if (insn->src_reg != BPF_REG_0) {
9021 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9022 			return -EINVAL;
9023 		}
9024 	}
9025 
9026 	/* check src2 operand */
9027 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9028 	if (err)
9029 		return err;
9030 
9031 	dst_reg = &regs[insn->dst_reg];
9032 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9033 
9034 	if (BPF_SRC(insn->code) == BPF_K) {
9035 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9036 	} else if (src_reg->type == SCALAR_VALUE &&
9037 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9038 		pred = is_branch_taken(dst_reg,
9039 				       tnum_subreg(src_reg->var_off).value,
9040 				       opcode,
9041 				       is_jmp32);
9042 	} else if (src_reg->type == SCALAR_VALUE &&
9043 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9044 		pred = is_branch_taken(dst_reg,
9045 				       src_reg->var_off.value,
9046 				       opcode,
9047 				       is_jmp32);
9048 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9049 		   reg_is_pkt_pointer_any(src_reg) &&
9050 		   !is_jmp32) {
9051 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9052 	}
9053 
9054 	if (pred >= 0) {
9055 		/* If we get here with a dst_reg pointer type it is because
9056 		 * above is_branch_taken() special cased the 0 comparison.
9057 		 */
9058 		if (!__is_pointer_value(false, dst_reg))
9059 			err = mark_chain_precision(env, insn->dst_reg);
9060 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9061 		    !__is_pointer_value(false, src_reg))
9062 			err = mark_chain_precision(env, insn->src_reg);
9063 		if (err)
9064 			return err;
9065 	}
9066 
9067 	if (pred == 1) {
9068 		/* Only follow the goto, ignore fall-through. If needed, push
9069 		 * the fall-through branch for simulation under speculative
9070 		 * execution.
9071 		 */
9072 		if (!env->bypass_spec_v1 &&
9073 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9074 					       *insn_idx))
9075 			return -EFAULT;
9076 		*insn_idx += insn->off;
9077 		return 0;
9078 	} else if (pred == 0) {
9079 		/* Only follow the fall-through branch, since that's where the
9080 		 * program will go. If needed, push the goto branch for
9081 		 * simulation under speculative execution.
9082 		 */
9083 		if (!env->bypass_spec_v1 &&
9084 		    !sanitize_speculative_path(env, insn,
9085 					       *insn_idx + insn->off + 1,
9086 					       *insn_idx))
9087 			return -EFAULT;
9088 		return 0;
9089 	}
9090 
9091 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9092 				  false);
9093 	if (!other_branch)
9094 		return -EFAULT;
9095 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9096 
9097 	/* detect if we are comparing against a constant value so we can adjust
9098 	 * our min/max values for our dst register.
9099 	 * this is only legit if both are scalars (or pointers to the same
9100 	 * object, I suppose, but we don't support that right now), because
9101 	 * otherwise the different base pointers mean the offsets aren't
9102 	 * comparable.
9103 	 */
9104 	if (BPF_SRC(insn->code) == BPF_X) {
9105 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9106 
9107 		if (dst_reg->type == SCALAR_VALUE &&
9108 		    src_reg->type == SCALAR_VALUE) {
9109 			if (tnum_is_const(src_reg->var_off) ||
9110 			    (is_jmp32 &&
9111 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9112 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9113 						dst_reg,
9114 						src_reg->var_off.value,
9115 						tnum_subreg(src_reg->var_off).value,
9116 						opcode, is_jmp32);
9117 			else if (tnum_is_const(dst_reg->var_off) ||
9118 				 (is_jmp32 &&
9119 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9120 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9121 						    src_reg,
9122 						    dst_reg->var_off.value,
9123 						    tnum_subreg(dst_reg->var_off).value,
9124 						    opcode, is_jmp32);
9125 			else if (!is_jmp32 &&
9126 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9127 				/* Comparing for equality, we can combine knowledge */
9128 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9129 						    &other_branch_regs[insn->dst_reg],
9130 						    src_reg, dst_reg, opcode);
9131 			if (src_reg->id &&
9132 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9133 				find_equal_scalars(this_branch, src_reg);
9134 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9135 			}
9136 
9137 		}
9138 	} else if (dst_reg->type == SCALAR_VALUE) {
9139 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9140 					dst_reg, insn->imm, (u32)insn->imm,
9141 					opcode, is_jmp32);
9142 	}
9143 
9144 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9145 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9146 		find_equal_scalars(this_branch, dst_reg);
9147 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9148 	}
9149 
9150 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9151 	 * NOTE: these optimizations below are related with pointer comparison
9152 	 *       which will never be JMP32.
9153 	 */
9154 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9155 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9156 	    reg_type_may_be_null(dst_reg->type)) {
9157 		/* Mark all identical registers in each branch as either
9158 		 * safe or unknown depending R == 0 or R != 0 conditional.
9159 		 */
9160 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9161 				      opcode == BPF_JNE);
9162 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9163 				      opcode == BPF_JEQ);
9164 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9165 					   this_branch, other_branch) &&
9166 		   is_pointer_value(env, insn->dst_reg)) {
9167 		verbose(env, "R%d pointer comparison prohibited\n",
9168 			insn->dst_reg);
9169 		return -EACCES;
9170 	}
9171 	if (env->log.level & BPF_LOG_LEVEL)
9172 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9173 	return 0;
9174 }
9175 
9176 /* verify BPF_LD_IMM64 instruction */
9177 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9178 {
9179 	struct bpf_insn_aux_data *aux = cur_aux(env);
9180 	struct bpf_reg_state *regs = cur_regs(env);
9181 	struct bpf_reg_state *dst_reg;
9182 	struct bpf_map *map;
9183 	int err;
9184 
9185 	if (BPF_SIZE(insn->code) != BPF_DW) {
9186 		verbose(env, "invalid BPF_LD_IMM insn\n");
9187 		return -EINVAL;
9188 	}
9189 	if (insn->off != 0) {
9190 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9191 		return -EINVAL;
9192 	}
9193 
9194 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9195 	if (err)
9196 		return err;
9197 
9198 	dst_reg = &regs[insn->dst_reg];
9199 	if (insn->src_reg == 0) {
9200 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9201 
9202 		dst_reg->type = SCALAR_VALUE;
9203 		__mark_reg_known(&regs[insn->dst_reg], imm);
9204 		return 0;
9205 	}
9206 
9207 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9208 		mark_reg_known_zero(env, regs, insn->dst_reg);
9209 
9210 		dst_reg->type = aux->btf_var.reg_type;
9211 		switch (dst_reg->type) {
9212 		case PTR_TO_MEM:
9213 			dst_reg->mem_size = aux->btf_var.mem_size;
9214 			break;
9215 		case PTR_TO_BTF_ID:
9216 		case PTR_TO_PERCPU_BTF_ID:
9217 			dst_reg->btf = aux->btf_var.btf;
9218 			dst_reg->btf_id = aux->btf_var.btf_id;
9219 			break;
9220 		default:
9221 			verbose(env, "bpf verifier is misconfigured\n");
9222 			return -EFAULT;
9223 		}
9224 		return 0;
9225 	}
9226 
9227 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9228 		struct bpf_prog_aux *aux = env->prog->aux;
9229 		u32 subprogno = insn[1].imm;
9230 
9231 		if (!aux->func_info) {
9232 			verbose(env, "missing btf func_info\n");
9233 			return -EINVAL;
9234 		}
9235 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9236 			verbose(env, "callback function not static\n");
9237 			return -EINVAL;
9238 		}
9239 
9240 		dst_reg->type = PTR_TO_FUNC;
9241 		dst_reg->subprogno = subprogno;
9242 		return 0;
9243 	}
9244 
9245 	map = env->used_maps[aux->map_index];
9246 	mark_reg_known_zero(env, regs, insn->dst_reg);
9247 	dst_reg->map_ptr = map;
9248 
9249 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9250 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9251 		dst_reg->type = PTR_TO_MAP_VALUE;
9252 		dst_reg->off = aux->map_off;
9253 		if (map_value_has_spin_lock(map))
9254 			dst_reg->id = ++env->id_gen;
9255 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9256 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9257 		dst_reg->type = CONST_PTR_TO_MAP;
9258 	} else {
9259 		verbose(env, "bpf verifier is misconfigured\n");
9260 		return -EINVAL;
9261 	}
9262 
9263 	return 0;
9264 }
9265 
9266 static bool may_access_skb(enum bpf_prog_type type)
9267 {
9268 	switch (type) {
9269 	case BPF_PROG_TYPE_SOCKET_FILTER:
9270 	case BPF_PROG_TYPE_SCHED_CLS:
9271 	case BPF_PROG_TYPE_SCHED_ACT:
9272 		return true;
9273 	default:
9274 		return false;
9275 	}
9276 }
9277 
9278 /* verify safety of LD_ABS|LD_IND instructions:
9279  * - they can only appear in the programs where ctx == skb
9280  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9281  *   preserve R6-R9, and store return value into R0
9282  *
9283  * Implicit input:
9284  *   ctx == skb == R6 == CTX
9285  *
9286  * Explicit input:
9287  *   SRC == any register
9288  *   IMM == 32-bit immediate
9289  *
9290  * Output:
9291  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9292  */
9293 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9294 {
9295 	struct bpf_reg_state *regs = cur_regs(env);
9296 	static const int ctx_reg = BPF_REG_6;
9297 	u8 mode = BPF_MODE(insn->code);
9298 	int i, err;
9299 
9300 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9301 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9302 		return -EINVAL;
9303 	}
9304 
9305 	if (!env->ops->gen_ld_abs) {
9306 		verbose(env, "bpf verifier is misconfigured\n");
9307 		return -EINVAL;
9308 	}
9309 
9310 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9311 	    BPF_SIZE(insn->code) == BPF_DW ||
9312 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9313 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9314 		return -EINVAL;
9315 	}
9316 
9317 	/* check whether implicit source operand (register R6) is readable */
9318 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9319 	if (err)
9320 		return err;
9321 
9322 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9323 	 * gen_ld_abs() may terminate the program at runtime, leading to
9324 	 * reference leak.
9325 	 */
9326 	err = check_reference_leak(env);
9327 	if (err) {
9328 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9329 		return err;
9330 	}
9331 
9332 	if (env->cur_state->active_spin_lock) {
9333 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9334 		return -EINVAL;
9335 	}
9336 
9337 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9338 		verbose(env,
9339 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9340 		return -EINVAL;
9341 	}
9342 
9343 	if (mode == BPF_IND) {
9344 		/* check explicit source operand */
9345 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9346 		if (err)
9347 			return err;
9348 	}
9349 
9350 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9351 	if (err < 0)
9352 		return err;
9353 
9354 	/* reset caller saved regs to unreadable */
9355 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9356 		mark_reg_not_init(env, regs, caller_saved[i]);
9357 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9358 	}
9359 
9360 	/* mark destination R0 register as readable, since it contains
9361 	 * the value fetched from the packet.
9362 	 * Already marked as written above.
9363 	 */
9364 	mark_reg_unknown(env, regs, BPF_REG_0);
9365 	/* ld_abs load up to 32-bit skb data. */
9366 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9367 	return 0;
9368 }
9369 
9370 static int check_return_code(struct bpf_verifier_env *env)
9371 {
9372 	struct tnum enforce_attach_type_range = tnum_unknown;
9373 	const struct bpf_prog *prog = env->prog;
9374 	struct bpf_reg_state *reg;
9375 	struct tnum range = tnum_range(0, 1);
9376 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9377 	int err;
9378 	struct bpf_func_state *frame = env->cur_state->frame[0];
9379 	const bool is_subprog = frame->subprogno;
9380 
9381 	/* LSM and struct_ops func-ptr's return type could be "void" */
9382 	if (!is_subprog &&
9383 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9384 	     prog_type == BPF_PROG_TYPE_LSM) &&
9385 	    !prog->aux->attach_func_proto->type)
9386 		return 0;
9387 
9388 	/* eBPF calling convention is such that R0 is used
9389 	 * to return the value from eBPF program.
9390 	 * Make sure that it's readable at this time
9391 	 * of bpf_exit, which means that program wrote
9392 	 * something into it earlier
9393 	 */
9394 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9395 	if (err)
9396 		return err;
9397 
9398 	if (is_pointer_value(env, BPF_REG_0)) {
9399 		verbose(env, "R0 leaks addr as return value\n");
9400 		return -EACCES;
9401 	}
9402 
9403 	reg = cur_regs(env) + BPF_REG_0;
9404 
9405 	if (frame->in_async_callback_fn) {
9406 		/* enforce return zero from async callbacks like timer */
9407 		if (reg->type != SCALAR_VALUE) {
9408 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9409 				reg_type_str[reg->type]);
9410 			return -EINVAL;
9411 		}
9412 
9413 		if (!tnum_in(tnum_const(0), reg->var_off)) {
9414 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9415 			return -EINVAL;
9416 		}
9417 		return 0;
9418 	}
9419 
9420 	if (is_subprog) {
9421 		if (reg->type != SCALAR_VALUE) {
9422 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9423 				reg_type_str[reg->type]);
9424 			return -EINVAL;
9425 		}
9426 		return 0;
9427 	}
9428 
9429 	switch (prog_type) {
9430 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9431 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9432 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9433 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9434 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9435 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9436 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9437 			range = tnum_range(1, 1);
9438 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9439 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9440 			range = tnum_range(0, 3);
9441 		break;
9442 	case BPF_PROG_TYPE_CGROUP_SKB:
9443 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9444 			range = tnum_range(0, 3);
9445 			enforce_attach_type_range = tnum_range(2, 3);
9446 		}
9447 		break;
9448 	case BPF_PROG_TYPE_CGROUP_SOCK:
9449 	case BPF_PROG_TYPE_SOCK_OPS:
9450 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9451 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9452 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9453 		break;
9454 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9455 		if (!env->prog->aux->attach_btf_id)
9456 			return 0;
9457 		range = tnum_const(0);
9458 		break;
9459 	case BPF_PROG_TYPE_TRACING:
9460 		switch (env->prog->expected_attach_type) {
9461 		case BPF_TRACE_FENTRY:
9462 		case BPF_TRACE_FEXIT:
9463 			range = tnum_const(0);
9464 			break;
9465 		case BPF_TRACE_RAW_TP:
9466 		case BPF_MODIFY_RETURN:
9467 			return 0;
9468 		case BPF_TRACE_ITER:
9469 			break;
9470 		default:
9471 			return -ENOTSUPP;
9472 		}
9473 		break;
9474 	case BPF_PROG_TYPE_SK_LOOKUP:
9475 		range = tnum_range(SK_DROP, SK_PASS);
9476 		break;
9477 	case BPF_PROG_TYPE_EXT:
9478 		/* freplace program can return anything as its return value
9479 		 * depends on the to-be-replaced kernel func or bpf program.
9480 		 */
9481 	default:
9482 		return 0;
9483 	}
9484 
9485 	if (reg->type != SCALAR_VALUE) {
9486 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9487 			reg_type_str[reg->type]);
9488 		return -EINVAL;
9489 	}
9490 
9491 	if (!tnum_in(range, reg->var_off)) {
9492 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9493 		return -EINVAL;
9494 	}
9495 
9496 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9497 	    tnum_in(enforce_attach_type_range, reg->var_off))
9498 		env->prog->enforce_expected_attach_type = 1;
9499 	return 0;
9500 }
9501 
9502 /* non-recursive DFS pseudo code
9503  * 1  procedure DFS-iterative(G,v):
9504  * 2      label v as discovered
9505  * 3      let S be a stack
9506  * 4      S.push(v)
9507  * 5      while S is not empty
9508  * 6            t <- S.pop()
9509  * 7            if t is what we're looking for:
9510  * 8                return t
9511  * 9            for all edges e in G.adjacentEdges(t) do
9512  * 10               if edge e is already labelled
9513  * 11                   continue with the next edge
9514  * 12               w <- G.adjacentVertex(t,e)
9515  * 13               if vertex w is not discovered and not explored
9516  * 14                   label e as tree-edge
9517  * 15                   label w as discovered
9518  * 16                   S.push(w)
9519  * 17                   continue at 5
9520  * 18               else if vertex w is discovered
9521  * 19                   label e as back-edge
9522  * 20               else
9523  * 21                   // vertex w is explored
9524  * 22                   label e as forward- or cross-edge
9525  * 23           label t as explored
9526  * 24           S.pop()
9527  *
9528  * convention:
9529  * 0x10 - discovered
9530  * 0x11 - discovered and fall-through edge labelled
9531  * 0x12 - discovered and fall-through and branch edges labelled
9532  * 0x20 - explored
9533  */
9534 
9535 enum {
9536 	DISCOVERED = 0x10,
9537 	EXPLORED = 0x20,
9538 	FALLTHROUGH = 1,
9539 	BRANCH = 2,
9540 };
9541 
9542 static u32 state_htab_size(struct bpf_verifier_env *env)
9543 {
9544 	return env->prog->len;
9545 }
9546 
9547 static struct bpf_verifier_state_list **explored_state(
9548 					struct bpf_verifier_env *env,
9549 					int idx)
9550 {
9551 	struct bpf_verifier_state *cur = env->cur_state;
9552 	struct bpf_func_state *state = cur->frame[cur->curframe];
9553 
9554 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9555 }
9556 
9557 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9558 {
9559 	env->insn_aux_data[idx].prune_point = true;
9560 }
9561 
9562 enum {
9563 	DONE_EXPLORING = 0,
9564 	KEEP_EXPLORING = 1,
9565 };
9566 
9567 /* t, w, e - match pseudo-code above:
9568  * t - index of current instruction
9569  * w - next instruction
9570  * e - edge
9571  */
9572 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9573 		     bool loop_ok)
9574 {
9575 	int *insn_stack = env->cfg.insn_stack;
9576 	int *insn_state = env->cfg.insn_state;
9577 
9578 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9579 		return DONE_EXPLORING;
9580 
9581 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9582 		return DONE_EXPLORING;
9583 
9584 	if (w < 0 || w >= env->prog->len) {
9585 		verbose_linfo(env, t, "%d: ", t);
9586 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9587 		return -EINVAL;
9588 	}
9589 
9590 	if (e == BRANCH)
9591 		/* mark branch target for state pruning */
9592 		init_explored_state(env, w);
9593 
9594 	if (insn_state[w] == 0) {
9595 		/* tree-edge */
9596 		insn_state[t] = DISCOVERED | e;
9597 		insn_state[w] = DISCOVERED;
9598 		if (env->cfg.cur_stack >= env->prog->len)
9599 			return -E2BIG;
9600 		insn_stack[env->cfg.cur_stack++] = w;
9601 		return KEEP_EXPLORING;
9602 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9603 		if (loop_ok && env->bpf_capable)
9604 			return DONE_EXPLORING;
9605 		verbose_linfo(env, t, "%d: ", t);
9606 		verbose_linfo(env, w, "%d: ", w);
9607 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9608 		return -EINVAL;
9609 	} else if (insn_state[w] == EXPLORED) {
9610 		/* forward- or cross-edge */
9611 		insn_state[t] = DISCOVERED | e;
9612 	} else {
9613 		verbose(env, "insn state internal bug\n");
9614 		return -EFAULT;
9615 	}
9616 	return DONE_EXPLORING;
9617 }
9618 
9619 static int visit_func_call_insn(int t, int insn_cnt,
9620 				struct bpf_insn *insns,
9621 				struct bpf_verifier_env *env,
9622 				bool visit_callee)
9623 {
9624 	int ret;
9625 
9626 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9627 	if (ret)
9628 		return ret;
9629 
9630 	if (t + 1 < insn_cnt)
9631 		init_explored_state(env, t + 1);
9632 	if (visit_callee) {
9633 		init_explored_state(env, t);
9634 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9635 				/* It's ok to allow recursion from CFG point of
9636 				 * view. __check_func_call() will do the actual
9637 				 * check.
9638 				 */
9639 				bpf_pseudo_func(insns + t));
9640 	}
9641 	return ret;
9642 }
9643 
9644 /* Visits the instruction at index t and returns one of the following:
9645  *  < 0 - an error occurred
9646  *  DONE_EXPLORING - the instruction was fully explored
9647  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9648  */
9649 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9650 {
9651 	struct bpf_insn *insns = env->prog->insnsi;
9652 	int ret;
9653 
9654 	if (bpf_pseudo_func(insns + t))
9655 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9656 
9657 	/* All non-branch instructions have a single fall-through edge. */
9658 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9659 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9660 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9661 
9662 	switch (BPF_OP(insns[t].code)) {
9663 	case BPF_EXIT:
9664 		return DONE_EXPLORING;
9665 
9666 	case BPF_CALL:
9667 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9668 			/* Mark this call insn to trigger is_state_visited() check
9669 			 * before call itself is processed by __check_func_call().
9670 			 * Otherwise new async state will be pushed for further
9671 			 * exploration.
9672 			 */
9673 			init_explored_state(env, t);
9674 		return visit_func_call_insn(t, insn_cnt, insns, env,
9675 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9676 
9677 	case BPF_JA:
9678 		if (BPF_SRC(insns[t].code) != BPF_K)
9679 			return -EINVAL;
9680 
9681 		/* unconditional jump with single edge */
9682 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9683 				true);
9684 		if (ret)
9685 			return ret;
9686 
9687 		/* unconditional jmp is not a good pruning point,
9688 		 * but it's marked, since backtracking needs
9689 		 * to record jmp history in is_state_visited().
9690 		 */
9691 		init_explored_state(env, t + insns[t].off + 1);
9692 		/* tell verifier to check for equivalent states
9693 		 * after every call and jump
9694 		 */
9695 		if (t + 1 < insn_cnt)
9696 			init_explored_state(env, t + 1);
9697 
9698 		return ret;
9699 
9700 	default:
9701 		/* conditional jump with two edges */
9702 		init_explored_state(env, t);
9703 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9704 		if (ret)
9705 			return ret;
9706 
9707 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9708 	}
9709 }
9710 
9711 /* non-recursive depth-first-search to detect loops in BPF program
9712  * loop == back-edge in directed graph
9713  */
9714 static int check_cfg(struct bpf_verifier_env *env)
9715 {
9716 	int insn_cnt = env->prog->len;
9717 	int *insn_stack, *insn_state;
9718 	int ret = 0;
9719 	int i;
9720 
9721 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9722 	if (!insn_state)
9723 		return -ENOMEM;
9724 
9725 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9726 	if (!insn_stack) {
9727 		kvfree(insn_state);
9728 		return -ENOMEM;
9729 	}
9730 
9731 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9732 	insn_stack[0] = 0; /* 0 is the first instruction */
9733 	env->cfg.cur_stack = 1;
9734 
9735 	while (env->cfg.cur_stack > 0) {
9736 		int t = insn_stack[env->cfg.cur_stack - 1];
9737 
9738 		ret = visit_insn(t, insn_cnt, env);
9739 		switch (ret) {
9740 		case DONE_EXPLORING:
9741 			insn_state[t] = EXPLORED;
9742 			env->cfg.cur_stack--;
9743 			break;
9744 		case KEEP_EXPLORING:
9745 			break;
9746 		default:
9747 			if (ret > 0) {
9748 				verbose(env, "visit_insn internal bug\n");
9749 				ret = -EFAULT;
9750 			}
9751 			goto err_free;
9752 		}
9753 	}
9754 
9755 	if (env->cfg.cur_stack < 0) {
9756 		verbose(env, "pop stack internal bug\n");
9757 		ret = -EFAULT;
9758 		goto err_free;
9759 	}
9760 
9761 	for (i = 0; i < insn_cnt; i++) {
9762 		if (insn_state[i] != EXPLORED) {
9763 			verbose(env, "unreachable insn %d\n", i);
9764 			ret = -EINVAL;
9765 			goto err_free;
9766 		}
9767 	}
9768 	ret = 0; /* cfg looks good */
9769 
9770 err_free:
9771 	kvfree(insn_state);
9772 	kvfree(insn_stack);
9773 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9774 	return ret;
9775 }
9776 
9777 static int check_abnormal_return(struct bpf_verifier_env *env)
9778 {
9779 	int i;
9780 
9781 	for (i = 1; i < env->subprog_cnt; i++) {
9782 		if (env->subprog_info[i].has_ld_abs) {
9783 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9784 			return -EINVAL;
9785 		}
9786 		if (env->subprog_info[i].has_tail_call) {
9787 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9788 			return -EINVAL;
9789 		}
9790 	}
9791 	return 0;
9792 }
9793 
9794 /* The minimum supported BTF func info size */
9795 #define MIN_BPF_FUNCINFO_SIZE	8
9796 #define MAX_FUNCINFO_REC_SIZE	252
9797 
9798 static int check_btf_func(struct bpf_verifier_env *env,
9799 			  const union bpf_attr *attr,
9800 			  bpfptr_t uattr)
9801 {
9802 	const struct btf_type *type, *func_proto, *ret_type;
9803 	u32 i, nfuncs, urec_size, min_size;
9804 	u32 krec_size = sizeof(struct bpf_func_info);
9805 	struct bpf_func_info *krecord;
9806 	struct bpf_func_info_aux *info_aux = NULL;
9807 	struct bpf_prog *prog;
9808 	const struct btf *btf;
9809 	bpfptr_t urecord;
9810 	u32 prev_offset = 0;
9811 	bool scalar_return;
9812 	int ret = -ENOMEM;
9813 
9814 	nfuncs = attr->func_info_cnt;
9815 	if (!nfuncs) {
9816 		if (check_abnormal_return(env))
9817 			return -EINVAL;
9818 		return 0;
9819 	}
9820 
9821 	if (nfuncs != env->subprog_cnt) {
9822 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9823 		return -EINVAL;
9824 	}
9825 
9826 	urec_size = attr->func_info_rec_size;
9827 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9828 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
9829 	    urec_size % sizeof(u32)) {
9830 		verbose(env, "invalid func info rec size %u\n", urec_size);
9831 		return -EINVAL;
9832 	}
9833 
9834 	prog = env->prog;
9835 	btf = prog->aux->btf;
9836 
9837 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9838 	min_size = min_t(u32, krec_size, urec_size);
9839 
9840 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9841 	if (!krecord)
9842 		return -ENOMEM;
9843 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9844 	if (!info_aux)
9845 		goto err_free;
9846 
9847 	for (i = 0; i < nfuncs; i++) {
9848 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9849 		if (ret) {
9850 			if (ret == -E2BIG) {
9851 				verbose(env, "nonzero tailing record in func info");
9852 				/* set the size kernel expects so loader can zero
9853 				 * out the rest of the record.
9854 				 */
9855 				if (copy_to_bpfptr_offset(uattr,
9856 							  offsetof(union bpf_attr, func_info_rec_size),
9857 							  &min_size, sizeof(min_size)))
9858 					ret = -EFAULT;
9859 			}
9860 			goto err_free;
9861 		}
9862 
9863 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
9864 			ret = -EFAULT;
9865 			goto err_free;
9866 		}
9867 
9868 		/* check insn_off */
9869 		ret = -EINVAL;
9870 		if (i == 0) {
9871 			if (krecord[i].insn_off) {
9872 				verbose(env,
9873 					"nonzero insn_off %u for the first func info record",
9874 					krecord[i].insn_off);
9875 				goto err_free;
9876 			}
9877 		} else if (krecord[i].insn_off <= prev_offset) {
9878 			verbose(env,
9879 				"same or smaller insn offset (%u) than previous func info record (%u)",
9880 				krecord[i].insn_off, prev_offset);
9881 			goto err_free;
9882 		}
9883 
9884 		if (env->subprog_info[i].start != krecord[i].insn_off) {
9885 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9886 			goto err_free;
9887 		}
9888 
9889 		/* check type_id */
9890 		type = btf_type_by_id(btf, krecord[i].type_id);
9891 		if (!type || !btf_type_is_func(type)) {
9892 			verbose(env, "invalid type id %d in func info",
9893 				krecord[i].type_id);
9894 			goto err_free;
9895 		}
9896 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9897 
9898 		func_proto = btf_type_by_id(btf, type->type);
9899 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9900 			/* btf_func_check() already verified it during BTF load */
9901 			goto err_free;
9902 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9903 		scalar_return =
9904 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9905 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9906 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9907 			goto err_free;
9908 		}
9909 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9910 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9911 			goto err_free;
9912 		}
9913 
9914 		prev_offset = krecord[i].insn_off;
9915 		bpfptr_add(&urecord, urec_size);
9916 	}
9917 
9918 	prog->aux->func_info = krecord;
9919 	prog->aux->func_info_cnt = nfuncs;
9920 	prog->aux->func_info_aux = info_aux;
9921 	return 0;
9922 
9923 err_free:
9924 	kvfree(krecord);
9925 	kfree(info_aux);
9926 	return ret;
9927 }
9928 
9929 static void adjust_btf_func(struct bpf_verifier_env *env)
9930 {
9931 	struct bpf_prog_aux *aux = env->prog->aux;
9932 	int i;
9933 
9934 	if (!aux->func_info)
9935 		return;
9936 
9937 	for (i = 0; i < env->subprog_cnt; i++)
9938 		aux->func_info[i].insn_off = env->subprog_info[i].start;
9939 }
9940 
9941 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
9942 		sizeof(((struct bpf_line_info *)(0))->line_col))
9943 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
9944 
9945 static int check_btf_line(struct bpf_verifier_env *env,
9946 			  const union bpf_attr *attr,
9947 			  bpfptr_t uattr)
9948 {
9949 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9950 	struct bpf_subprog_info *sub;
9951 	struct bpf_line_info *linfo;
9952 	struct bpf_prog *prog;
9953 	const struct btf *btf;
9954 	bpfptr_t ulinfo;
9955 	int err;
9956 
9957 	nr_linfo = attr->line_info_cnt;
9958 	if (!nr_linfo)
9959 		return 0;
9960 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9961 		return -EINVAL;
9962 
9963 	rec_size = attr->line_info_rec_size;
9964 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9965 	    rec_size > MAX_LINEINFO_REC_SIZE ||
9966 	    rec_size & (sizeof(u32) - 1))
9967 		return -EINVAL;
9968 
9969 	/* Need to zero it in case the userspace may
9970 	 * pass in a smaller bpf_line_info object.
9971 	 */
9972 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9973 			 GFP_KERNEL | __GFP_NOWARN);
9974 	if (!linfo)
9975 		return -ENOMEM;
9976 
9977 	prog = env->prog;
9978 	btf = prog->aux->btf;
9979 
9980 	s = 0;
9981 	sub = env->subprog_info;
9982 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
9983 	expected_size = sizeof(struct bpf_line_info);
9984 	ncopy = min_t(u32, expected_size, rec_size);
9985 	for (i = 0; i < nr_linfo; i++) {
9986 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9987 		if (err) {
9988 			if (err == -E2BIG) {
9989 				verbose(env, "nonzero tailing record in line_info");
9990 				if (copy_to_bpfptr_offset(uattr,
9991 							  offsetof(union bpf_attr, line_info_rec_size),
9992 							  &expected_size, sizeof(expected_size)))
9993 					err = -EFAULT;
9994 			}
9995 			goto err_free;
9996 		}
9997 
9998 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
9999 			err = -EFAULT;
10000 			goto err_free;
10001 		}
10002 
10003 		/*
10004 		 * Check insn_off to ensure
10005 		 * 1) strictly increasing AND
10006 		 * 2) bounded by prog->len
10007 		 *
10008 		 * The linfo[0].insn_off == 0 check logically falls into
10009 		 * the later "missing bpf_line_info for func..." case
10010 		 * because the first linfo[0].insn_off must be the
10011 		 * first sub also and the first sub must have
10012 		 * subprog_info[0].start == 0.
10013 		 */
10014 		if ((i && linfo[i].insn_off <= prev_offset) ||
10015 		    linfo[i].insn_off >= prog->len) {
10016 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10017 				i, linfo[i].insn_off, prev_offset,
10018 				prog->len);
10019 			err = -EINVAL;
10020 			goto err_free;
10021 		}
10022 
10023 		if (!prog->insnsi[linfo[i].insn_off].code) {
10024 			verbose(env,
10025 				"Invalid insn code at line_info[%u].insn_off\n",
10026 				i);
10027 			err = -EINVAL;
10028 			goto err_free;
10029 		}
10030 
10031 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10032 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10033 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10034 			err = -EINVAL;
10035 			goto err_free;
10036 		}
10037 
10038 		if (s != env->subprog_cnt) {
10039 			if (linfo[i].insn_off == sub[s].start) {
10040 				sub[s].linfo_idx = i;
10041 				s++;
10042 			} else if (sub[s].start < linfo[i].insn_off) {
10043 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10044 				err = -EINVAL;
10045 				goto err_free;
10046 			}
10047 		}
10048 
10049 		prev_offset = linfo[i].insn_off;
10050 		bpfptr_add(&ulinfo, rec_size);
10051 	}
10052 
10053 	if (s != env->subprog_cnt) {
10054 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10055 			env->subprog_cnt - s, s);
10056 		err = -EINVAL;
10057 		goto err_free;
10058 	}
10059 
10060 	prog->aux->linfo = linfo;
10061 	prog->aux->nr_linfo = nr_linfo;
10062 
10063 	return 0;
10064 
10065 err_free:
10066 	kvfree(linfo);
10067 	return err;
10068 }
10069 
10070 static int check_btf_info(struct bpf_verifier_env *env,
10071 			  const union bpf_attr *attr,
10072 			  bpfptr_t uattr)
10073 {
10074 	struct btf *btf;
10075 	int err;
10076 
10077 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10078 		if (check_abnormal_return(env))
10079 			return -EINVAL;
10080 		return 0;
10081 	}
10082 
10083 	btf = btf_get_by_fd(attr->prog_btf_fd);
10084 	if (IS_ERR(btf))
10085 		return PTR_ERR(btf);
10086 	if (btf_is_kernel(btf)) {
10087 		btf_put(btf);
10088 		return -EACCES;
10089 	}
10090 	env->prog->aux->btf = btf;
10091 
10092 	err = check_btf_func(env, attr, uattr);
10093 	if (err)
10094 		return err;
10095 
10096 	err = check_btf_line(env, attr, uattr);
10097 	if (err)
10098 		return err;
10099 
10100 	return 0;
10101 }
10102 
10103 /* check %cur's range satisfies %old's */
10104 static bool range_within(struct bpf_reg_state *old,
10105 			 struct bpf_reg_state *cur)
10106 {
10107 	return old->umin_value <= cur->umin_value &&
10108 	       old->umax_value >= cur->umax_value &&
10109 	       old->smin_value <= cur->smin_value &&
10110 	       old->smax_value >= cur->smax_value &&
10111 	       old->u32_min_value <= cur->u32_min_value &&
10112 	       old->u32_max_value >= cur->u32_max_value &&
10113 	       old->s32_min_value <= cur->s32_min_value &&
10114 	       old->s32_max_value >= cur->s32_max_value;
10115 }
10116 
10117 /* If in the old state two registers had the same id, then they need to have
10118  * the same id in the new state as well.  But that id could be different from
10119  * the old state, so we need to track the mapping from old to new ids.
10120  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10121  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10122  * regs with a different old id could still have new id 9, we don't care about
10123  * that.
10124  * So we look through our idmap to see if this old id has been seen before.  If
10125  * so, we require the new id to match; otherwise, we add the id pair to the map.
10126  */
10127 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10128 {
10129 	unsigned int i;
10130 
10131 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10132 		if (!idmap[i].old) {
10133 			/* Reached an empty slot; haven't seen this id before */
10134 			idmap[i].old = old_id;
10135 			idmap[i].cur = cur_id;
10136 			return true;
10137 		}
10138 		if (idmap[i].old == old_id)
10139 			return idmap[i].cur == cur_id;
10140 	}
10141 	/* We ran out of idmap slots, which should be impossible */
10142 	WARN_ON_ONCE(1);
10143 	return false;
10144 }
10145 
10146 static void clean_func_state(struct bpf_verifier_env *env,
10147 			     struct bpf_func_state *st)
10148 {
10149 	enum bpf_reg_liveness live;
10150 	int i, j;
10151 
10152 	for (i = 0; i < BPF_REG_FP; i++) {
10153 		live = st->regs[i].live;
10154 		/* liveness must not touch this register anymore */
10155 		st->regs[i].live |= REG_LIVE_DONE;
10156 		if (!(live & REG_LIVE_READ))
10157 			/* since the register is unused, clear its state
10158 			 * to make further comparison simpler
10159 			 */
10160 			__mark_reg_not_init(env, &st->regs[i]);
10161 	}
10162 
10163 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10164 		live = st->stack[i].spilled_ptr.live;
10165 		/* liveness must not touch this stack slot anymore */
10166 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10167 		if (!(live & REG_LIVE_READ)) {
10168 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10169 			for (j = 0; j < BPF_REG_SIZE; j++)
10170 				st->stack[i].slot_type[j] = STACK_INVALID;
10171 		}
10172 	}
10173 }
10174 
10175 static void clean_verifier_state(struct bpf_verifier_env *env,
10176 				 struct bpf_verifier_state *st)
10177 {
10178 	int i;
10179 
10180 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10181 		/* all regs in this state in all frames were already marked */
10182 		return;
10183 
10184 	for (i = 0; i <= st->curframe; i++)
10185 		clean_func_state(env, st->frame[i]);
10186 }
10187 
10188 /* the parentage chains form a tree.
10189  * the verifier states are added to state lists at given insn and
10190  * pushed into state stack for future exploration.
10191  * when the verifier reaches bpf_exit insn some of the verifer states
10192  * stored in the state lists have their final liveness state already,
10193  * but a lot of states will get revised from liveness point of view when
10194  * the verifier explores other branches.
10195  * Example:
10196  * 1: r0 = 1
10197  * 2: if r1 == 100 goto pc+1
10198  * 3: r0 = 2
10199  * 4: exit
10200  * when the verifier reaches exit insn the register r0 in the state list of
10201  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10202  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10203  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10204  *
10205  * Since the verifier pushes the branch states as it sees them while exploring
10206  * the program the condition of walking the branch instruction for the second
10207  * time means that all states below this branch were already explored and
10208  * their final liveness marks are already propagated.
10209  * Hence when the verifier completes the search of state list in is_state_visited()
10210  * we can call this clean_live_states() function to mark all liveness states
10211  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10212  * will not be used.
10213  * This function also clears the registers and stack for states that !READ
10214  * to simplify state merging.
10215  *
10216  * Important note here that walking the same branch instruction in the callee
10217  * doesn't meant that the states are DONE. The verifier has to compare
10218  * the callsites
10219  */
10220 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10221 			      struct bpf_verifier_state *cur)
10222 {
10223 	struct bpf_verifier_state_list *sl;
10224 	int i;
10225 
10226 	sl = *explored_state(env, insn);
10227 	while (sl) {
10228 		if (sl->state.branches)
10229 			goto next;
10230 		if (sl->state.insn_idx != insn ||
10231 		    sl->state.curframe != cur->curframe)
10232 			goto next;
10233 		for (i = 0; i <= cur->curframe; i++)
10234 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10235 				goto next;
10236 		clean_verifier_state(env, &sl->state);
10237 next:
10238 		sl = sl->next;
10239 	}
10240 }
10241 
10242 /* Returns true if (rold safe implies rcur safe) */
10243 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10244 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10245 {
10246 	bool equal;
10247 
10248 	if (!(rold->live & REG_LIVE_READ))
10249 		/* explored state didn't use this */
10250 		return true;
10251 
10252 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10253 
10254 	if (rold->type == PTR_TO_STACK)
10255 		/* two stack pointers are equal only if they're pointing to
10256 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10257 		 */
10258 		return equal && rold->frameno == rcur->frameno;
10259 
10260 	if (equal)
10261 		return true;
10262 
10263 	if (rold->type == NOT_INIT)
10264 		/* explored state can't have used this */
10265 		return true;
10266 	if (rcur->type == NOT_INIT)
10267 		return false;
10268 	switch (rold->type) {
10269 	case SCALAR_VALUE:
10270 		if (env->explore_alu_limits)
10271 			return false;
10272 		if (rcur->type == SCALAR_VALUE) {
10273 			if (!rold->precise && !rcur->precise)
10274 				return true;
10275 			/* new val must satisfy old val knowledge */
10276 			return range_within(rold, rcur) &&
10277 			       tnum_in(rold->var_off, rcur->var_off);
10278 		} else {
10279 			/* We're trying to use a pointer in place of a scalar.
10280 			 * Even if the scalar was unbounded, this could lead to
10281 			 * pointer leaks because scalars are allowed to leak
10282 			 * while pointers are not. We could make this safe in
10283 			 * special cases if root is calling us, but it's
10284 			 * probably not worth the hassle.
10285 			 */
10286 			return false;
10287 		}
10288 	case PTR_TO_MAP_KEY:
10289 	case PTR_TO_MAP_VALUE:
10290 		/* If the new min/max/var_off satisfy the old ones and
10291 		 * everything else matches, we are OK.
10292 		 * 'id' is not compared, since it's only used for maps with
10293 		 * bpf_spin_lock inside map element and in such cases if
10294 		 * the rest of the prog is valid for one map element then
10295 		 * it's valid for all map elements regardless of the key
10296 		 * used in bpf_map_lookup()
10297 		 */
10298 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10299 		       range_within(rold, rcur) &&
10300 		       tnum_in(rold->var_off, rcur->var_off);
10301 	case PTR_TO_MAP_VALUE_OR_NULL:
10302 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10303 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10304 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10305 		 * checked, doing so could have affected others with the same
10306 		 * id, and we can't check for that because we lost the id when
10307 		 * we converted to a PTR_TO_MAP_VALUE.
10308 		 */
10309 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10310 			return false;
10311 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10312 			return false;
10313 		/* Check our ids match any regs they're supposed to */
10314 		return check_ids(rold->id, rcur->id, idmap);
10315 	case PTR_TO_PACKET_META:
10316 	case PTR_TO_PACKET:
10317 		if (rcur->type != rold->type)
10318 			return false;
10319 		/* We must have at least as much range as the old ptr
10320 		 * did, so that any accesses which were safe before are
10321 		 * still safe.  This is true even if old range < old off,
10322 		 * since someone could have accessed through (ptr - k), or
10323 		 * even done ptr -= k in a register, to get a safe access.
10324 		 */
10325 		if (rold->range > rcur->range)
10326 			return false;
10327 		/* If the offsets don't match, we can't trust our alignment;
10328 		 * nor can we be sure that we won't fall out of range.
10329 		 */
10330 		if (rold->off != rcur->off)
10331 			return false;
10332 		/* id relations must be preserved */
10333 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10334 			return false;
10335 		/* new val must satisfy old val knowledge */
10336 		return range_within(rold, rcur) &&
10337 		       tnum_in(rold->var_off, rcur->var_off);
10338 	case PTR_TO_CTX:
10339 	case CONST_PTR_TO_MAP:
10340 	case PTR_TO_PACKET_END:
10341 	case PTR_TO_FLOW_KEYS:
10342 	case PTR_TO_SOCKET:
10343 	case PTR_TO_SOCKET_OR_NULL:
10344 	case PTR_TO_SOCK_COMMON:
10345 	case PTR_TO_SOCK_COMMON_OR_NULL:
10346 	case PTR_TO_TCP_SOCK:
10347 	case PTR_TO_TCP_SOCK_OR_NULL:
10348 	case PTR_TO_XDP_SOCK:
10349 		/* Only valid matches are exact, which memcmp() above
10350 		 * would have accepted
10351 		 */
10352 	default:
10353 		/* Don't know what's going on, just say it's not safe */
10354 		return false;
10355 	}
10356 
10357 	/* Shouldn't get here; if we do, say it's not safe */
10358 	WARN_ON_ONCE(1);
10359 	return false;
10360 }
10361 
10362 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10363 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10364 {
10365 	int i, spi;
10366 
10367 	/* walk slots of the explored stack and ignore any additional
10368 	 * slots in the current stack, since explored(safe) state
10369 	 * didn't use them
10370 	 */
10371 	for (i = 0; i < old->allocated_stack; i++) {
10372 		spi = i / BPF_REG_SIZE;
10373 
10374 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10375 			i += BPF_REG_SIZE - 1;
10376 			/* explored state didn't use this */
10377 			continue;
10378 		}
10379 
10380 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10381 			continue;
10382 
10383 		/* explored stack has more populated slots than current stack
10384 		 * and these slots were used
10385 		 */
10386 		if (i >= cur->allocated_stack)
10387 			return false;
10388 
10389 		/* if old state was safe with misc data in the stack
10390 		 * it will be safe with zero-initialized stack.
10391 		 * The opposite is not true
10392 		 */
10393 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10394 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10395 			continue;
10396 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10397 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10398 			/* Ex: old explored (safe) state has STACK_SPILL in
10399 			 * this stack slot, but current has STACK_MISC ->
10400 			 * this verifier states are not equivalent,
10401 			 * return false to continue verification of this path
10402 			 */
10403 			return false;
10404 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10405 			continue;
10406 		if (!is_spilled_reg(&old->stack[spi]))
10407 			continue;
10408 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10409 			     &cur->stack[spi].spilled_ptr, idmap))
10410 			/* when explored and current stack slot are both storing
10411 			 * spilled registers, check that stored pointers types
10412 			 * are the same as well.
10413 			 * Ex: explored safe path could have stored
10414 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10415 			 * but current path has stored:
10416 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10417 			 * such verifier states are not equivalent.
10418 			 * return false to continue verification of this path
10419 			 */
10420 			return false;
10421 	}
10422 	return true;
10423 }
10424 
10425 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10426 {
10427 	if (old->acquired_refs != cur->acquired_refs)
10428 		return false;
10429 	return !memcmp(old->refs, cur->refs,
10430 		       sizeof(*old->refs) * old->acquired_refs);
10431 }
10432 
10433 /* compare two verifier states
10434  *
10435  * all states stored in state_list are known to be valid, since
10436  * verifier reached 'bpf_exit' instruction through them
10437  *
10438  * this function is called when verifier exploring different branches of
10439  * execution popped from the state stack. If it sees an old state that has
10440  * more strict register state and more strict stack state then this execution
10441  * branch doesn't need to be explored further, since verifier already
10442  * concluded that more strict state leads to valid finish.
10443  *
10444  * Therefore two states are equivalent if register state is more conservative
10445  * and explored stack state is more conservative than the current one.
10446  * Example:
10447  *       explored                   current
10448  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10449  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10450  *
10451  * In other words if current stack state (one being explored) has more
10452  * valid slots than old one that already passed validation, it means
10453  * the verifier can stop exploring and conclude that current state is valid too
10454  *
10455  * Similarly with registers. If explored state has register type as invalid
10456  * whereas register type in current state is meaningful, it means that
10457  * the current state will reach 'bpf_exit' instruction safely
10458  */
10459 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10460 			      struct bpf_func_state *cur)
10461 {
10462 	int i;
10463 
10464 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10465 	for (i = 0; i < MAX_BPF_REG; i++)
10466 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10467 			     env->idmap_scratch))
10468 			return false;
10469 
10470 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10471 		return false;
10472 
10473 	if (!refsafe(old, cur))
10474 		return false;
10475 
10476 	return true;
10477 }
10478 
10479 static bool states_equal(struct bpf_verifier_env *env,
10480 			 struct bpf_verifier_state *old,
10481 			 struct bpf_verifier_state *cur)
10482 {
10483 	int i;
10484 
10485 	if (old->curframe != cur->curframe)
10486 		return false;
10487 
10488 	/* Verification state from speculative execution simulation
10489 	 * must never prune a non-speculative execution one.
10490 	 */
10491 	if (old->speculative && !cur->speculative)
10492 		return false;
10493 
10494 	if (old->active_spin_lock != cur->active_spin_lock)
10495 		return false;
10496 
10497 	/* for states to be equal callsites have to be the same
10498 	 * and all frame states need to be equivalent
10499 	 */
10500 	for (i = 0; i <= old->curframe; i++) {
10501 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10502 			return false;
10503 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10504 			return false;
10505 	}
10506 	return true;
10507 }
10508 
10509 /* Return 0 if no propagation happened. Return negative error code if error
10510  * happened. Otherwise, return the propagated bit.
10511  */
10512 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10513 				  struct bpf_reg_state *reg,
10514 				  struct bpf_reg_state *parent_reg)
10515 {
10516 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10517 	u8 flag = reg->live & REG_LIVE_READ;
10518 	int err;
10519 
10520 	/* When comes here, read flags of PARENT_REG or REG could be any of
10521 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10522 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10523 	 */
10524 	if (parent_flag == REG_LIVE_READ64 ||
10525 	    /* Or if there is no read flag from REG. */
10526 	    !flag ||
10527 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10528 	    parent_flag == flag)
10529 		return 0;
10530 
10531 	err = mark_reg_read(env, reg, parent_reg, flag);
10532 	if (err)
10533 		return err;
10534 
10535 	return flag;
10536 }
10537 
10538 /* A write screens off any subsequent reads; but write marks come from the
10539  * straight-line code between a state and its parent.  When we arrive at an
10540  * equivalent state (jump target or such) we didn't arrive by the straight-line
10541  * code, so read marks in the state must propagate to the parent regardless
10542  * of the state's write marks. That's what 'parent == state->parent' comparison
10543  * in mark_reg_read() is for.
10544  */
10545 static int propagate_liveness(struct bpf_verifier_env *env,
10546 			      const struct bpf_verifier_state *vstate,
10547 			      struct bpf_verifier_state *vparent)
10548 {
10549 	struct bpf_reg_state *state_reg, *parent_reg;
10550 	struct bpf_func_state *state, *parent;
10551 	int i, frame, err = 0;
10552 
10553 	if (vparent->curframe != vstate->curframe) {
10554 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10555 		     vparent->curframe, vstate->curframe);
10556 		return -EFAULT;
10557 	}
10558 	/* Propagate read liveness of registers... */
10559 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10560 	for (frame = 0; frame <= vstate->curframe; frame++) {
10561 		parent = vparent->frame[frame];
10562 		state = vstate->frame[frame];
10563 		parent_reg = parent->regs;
10564 		state_reg = state->regs;
10565 		/* We don't need to worry about FP liveness, it's read-only */
10566 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10567 			err = propagate_liveness_reg(env, &state_reg[i],
10568 						     &parent_reg[i]);
10569 			if (err < 0)
10570 				return err;
10571 			if (err == REG_LIVE_READ64)
10572 				mark_insn_zext(env, &parent_reg[i]);
10573 		}
10574 
10575 		/* Propagate stack slots. */
10576 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10577 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10578 			parent_reg = &parent->stack[i].spilled_ptr;
10579 			state_reg = &state->stack[i].spilled_ptr;
10580 			err = propagate_liveness_reg(env, state_reg,
10581 						     parent_reg);
10582 			if (err < 0)
10583 				return err;
10584 		}
10585 	}
10586 	return 0;
10587 }
10588 
10589 /* find precise scalars in the previous equivalent state and
10590  * propagate them into the current state
10591  */
10592 static int propagate_precision(struct bpf_verifier_env *env,
10593 			       const struct bpf_verifier_state *old)
10594 {
10595 	struct bpf_reg_state *state_reg;
10596 	struct bpf_func_state *state;
10597 	int i, err = 0;
10598 
10599 	state = old->frame[old->curframe];
10600 	state_reg = state->regs;
10601 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10602 		if (state_reg->type != SCALAR_VALUE ||
10603 		    !state_reg->precise)
10604 			continue;
10605 		if (env->log.level & BPF_LOG_LEVEL2)
10606 			verbose(env, "propagating r%d\n", i);
10607 		err = mark_chain_precision(env, i);
10608 		if (err < 0)
10609 			return err;
10610 	}
10611 
10612 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10613 		if (!is_spilled_reg(&state->stack[i]))
10614 			continue;
10615 		state_reg = &state->stack[i].spilled_ptr;
10616 		if (state_reg->type != SCALAR_VALUE ||
10617 		    !state_reg->precise)
10618 			continue;
10619 		if (env->log.level & BPF_LOG_LEVEL2)
10620 			verbose(env, "propagating fp%d\n",
10621 				(-i - 1) * BPF_REG_SIZE);
10622 		err = mark_chain_precision_stack(env, i);
10623 		if (err < 0)
10624 			return err;
10625 	}
10626 	return 0;
10627 }
10628 
10629 static bool states_maybe_looping(struct bpf_verifier_state *old,
10630 				 struct bpf_verifier_state *cur)
10631 {
10632 	struct bpf_func_state *fold, *fcur;
10633 	int i, fr = cur->curframe;
10634 
10635 	if (old->curframe != fr)
10636 		return false;
10637 
10638 	fold = old->frame[fr];
10639 	fcur = cur->frame[fr];
10640 	for (i = 0; i < MAX_BPF_REG; i++)
10641 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10642 			   offsetof(struct bpf_reg_state, parent)))
10643 			return false;
10644 	return true;
10645 }
10646 
10647 
10648 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10649 {
10650 	struct bpf_verifier_state_list *new_sl;
10651 	struct bpf_verifier_state_list *sl, **pprev;
10652 	struct bpf_verifier_state *cur = env->cur_state, *new;
10653 	int i, j, err, states_cnt = 0;
10654 	bool add_new_state = env->test_state_freq ? true : false;
10655 
10656 	cur->last_insn_idx = env->prev_insn_idx;
10657 	if (!env->insn_aux_data[insn_idx].prune_point)
10658 		/* this 'insn_idx' instruction wasn't marked, so we will not
10659 		 * be doing state search here
10660 		 */
10661 		return 0;
10662 
10663 	/* bpf progs typically have pruning point every 4 instructions
10664 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10665 	 * Do not add new state for future pruning if the verifier hasn't seen
10666 	 * at least 2 jumps and at least 8 instructions.
10667 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10668 	 * In tests that amounts to up to 50% reduction into total verifier
10669 	 * memory consumption and 20% verifier time speedup.
10670 	 */
10671 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10672 	    env->insn_processed - env->prev_insn_processed >= 8)
10673 		add_new_state = true;
10674 
10675 	pprev = explored_state(env, insn_idx);
10676 	sl = *pprev;
10677 
10678 	clean_live_states(env, insn_idx, cur);
10679 
10680 	while (sl) {
10681 		states_cnt++;
10682 		if (sl->state.insn_idx != insn_idx)
10683 			goto next;
10684 
10685 		if (sl->state.branches) {
10686 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10687 
10688 			if (frame->in_async_callback_fn &&
10689 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10690 				/* Different async_entry_cnt means that the verifier is
10691 				 * processing another entry into async callback.
10692 				 * Seeing the same state is not an indication of infinite
10693 				 * loop or infinite recursion.
10694 				 * But finding the same state doesn't mean that it's safe
10695 				 * to stop processing the current state. The previous state
10696 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10697 				 * Checking in_async_callback_fn alone is not enough either.
10698 				 * Since the verifier still needs to catch infinite loops
10699 				 * inside async callbacks.
10700 				 */
10701 			} else if (states_maybe_looping(&sl->state, cur) &&
10702 				   states_equal(env, &sl->state, cur)) {
10703 				verbose_linfo(env, insn_idx, "; ");
10704 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10705 				return -EINVAL;
10706 			}
10707 			/* if the verifier is processing a loop, avoid adding new state
10708 			 * too often, since different loop iterations have distinct
10709 			 * states and may not help future pruning.
10710 			 * This threshold shouldn't be too low to make sure that
10711 			 * a loop with large bound will be rejected quickly.
10712 			 * The most abusive loop will be:
10713 			 * r1 += 1
10714 			 * if r1 < 1000000 goto pc-2
10715 			 * 1M insn_procssed limit / 100 == 10k peak states.
10716 			 * This threshold shouldn't be too high either, since states
10717 			 * at the end of the loop are likely to be useful in pruning.
10718 			 */
10719 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10720 			    env->insn_processed - env->prev_insn_processed < 100)
10721 				add_new_state = false;
10722 			goto miss;
10723 		}
10724 		if (states_equal(env, &sl->state, cur)) {
10725 			sl->hit_cnt++;
10726 			/* reached equivalent register/stack state,
10727 			 * prune the search.
10728 			 * Registers read by the continuation are read by us.
10729 			 * If we have any write marks in env->cur_state, they
10730 			 * will prevent corresponding reads in the continuation
10731 			 * from reaching our parent (an explored_state).  Our
10732 			 * own state will get the read marks recorded, but
10733 			 * they'll be immediately forgotten as we're pruning
10734 			 * this state and will pop a new one.
10735 			 */
10736 			err = propagate_liveness(env, &sl->state, cur);
10737 
10738 			/* if previous state reached the exit with precision and
10739 			 * current state is equivalent to it (except precsion marks)
10740 			 * the precision needs to be propagated back in
10741 			 * the current state.
10742 			 */
10743 			err = err ? : push_jmp_history(env, cur);
10744 			err = err ? : propagate_precision(env, &sl->state);
10745 			if (err)
10746 				return err;
10747 			return 1;
10748 		}
10749 miss:
10750 		/* when new state is not going to be added do not increase miss count.
10751 		 * Otherwise several loop iterations will remove the state
10752 		 * recorded earlier. The goal of these heuristics is to have
10753 		 * states from some iterations of the loop (some in the beginning
10754 		 * and some at the end) to help pruning.
10755 		 */
10756 		if (add_new_state)
10757 			sl->miss_cnt++;
10758 		/* heuristic to determine whether this state is beneficial
10759 		 * to keep checking from state equivalence point of view.
10760 		 * Higher numbers increase max_states_per_insn and verification time,
10761 		 * but do not meaningfully decrease insn_processed.
10762 		 */
10763 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10764 			/* the state is unlikely to be useful. Remove it to
10765 			 * speed up verification
10766 			 */
10767 			*pprev = sl->next;
10768 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10769 				u32 br = sl->state.branches;
10770 
10771 				WARN_ONCE(br,
10772 					  "BUG live_done but branches_to_explore %d\n",
10773 					  br);
10774 				free_verifier_state(&sl->state, false);
10775 				kfree(sl);
10776 				env->peak_states--;
10777 			} else {
10778 				/* cannot free this state, since parentage chain may
10779 				 * walk it later. Add it for free_list instead to
10780 				 * be freed at the end of verification
10781 				 */
10782 				sl->next = env->free_list;
10783 				env->free_list = sl;
10784 			}
10785 			sl = *pprev;
10786 			continue;
10787 		}
10788 next:
10789 		pprev = &sl->next;
10790 		sl = *pprev;
10791 	}
10792 
10793 	if (env->max_states_per_insn < states_cnt)
10794 		env->max_states_per_insn = states_cnt;
10795 
10796 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10797 		return push_jmp_history(env, cur);
10798 
10799 	if (!add_new_state)
10800 		return push_jmp_history(env, cur);
10801 
10802 	/* There were no equivalent states, remember the current one.
10803 	 * Technically the current state is not proven to be safe yet,
10804 	 * but it will either reach outer most bpf_exit (which means it's safe)
10805 	 * or it will be rejected. When there are no loops the verifier won't be
10806 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10807 	 * again on the way to bpf_exit.
10808 	 * When looping the sl->state.branches will be > 0 and this state
10809 	 * will not be considered for equivalence until branches == 0.
10810 	 */
10811 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10812 	if (!new_sl)
10813 		return -ENOMEM;
10814 	env->total_states++;
10815 	env->peak_states++;
10816 	env->prev_jmps_processed = env->jmps_processed;
10817 	env->prev_insn_processed = env->insn_processed;
10818 
10819 	/* add new state to the head of linked list */
10820 	new = &new_sl->state;
10821 	err = copy_verifier_state(new, cur);
10822 	if (err) {
10823 		free_verifier_state(new, false);
10824 		kfree(new_sl);
10825 		return err;
10826 	}
10827 	new->insn_idx = insn_idx;
10828 	WARN_ONCE(new->branches != 1,
10829 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10830 
10831 	cur->parent = new;
10832 	cur->first_insn_idx = insn_idx;
10833 	clear_jmp_history(cur);
10834 	new_sl->next = *explored_state(env, insn_idx);
10835 	*explored_state(env, insn_idx) = new_sl;
10836 	/* connect new state to parentage chain. Current frame needs all
10837 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
10838 	 * to the stack implicitly by JITs) so in callers' frames connect just
10839 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10840 	 * the state of the call instruction (with WRITTEN set), and r0 comes
10841 	 * from callee with its full parentage chain, anyway.
10842 	 */
10843 	/* clear write marks in current state: the writes we did are not writes
10844 	 * our child did, so they don't screen off its reads from us.
10845 	 * (There are no read marks in current state, because reads always mark
10846 	 * their parent and current state never has children yet.  Only
10847 	 * explored_states can get read marks.)
10848 	 */
10849 	for (j = 0; j <= cur->curframe; j++) {
10850 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10851 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10852 		for (i = 0; i < BPF_REG_FP; i++)
10853 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10854 	}
10855 
10856 	/* all stack frames are accessible from callee, clear them all */
10857 	for (j = 0; j <= cur->curframe; j++) {
10858 		struct bpf_func_state *frame = cur->frame[j];
10859 		struct bpf_func_state *newframe = new->frame[j];
10860 
10861 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10862 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10863 			frame->stack[i].spilled_ptr.parent =
10864 						&newframe->stack[i].spilled_ptr;
10865 		}
10866 	}
10867 	return 0;
10868 }
10869 
10870 /* Return true if it's OK to have the same insn return a different type. */
10871 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10872 {
10873 	switch (type) {
10874 	case PTR_TO_CTX:
10875 	case PTR_TO_SOCKET:
10876 	case PTR_TO_SOCKET_OR_NULL:
10877 	case PTR_TO_SOCK_COMMON:
10878 	case PTR_TO_SOCK_COMMON_OR_NULL:
10879 	case PTR_TO_TCP_SOCK:
10880 	case PTR_TO_TCP_SOCK_OR_NULL:
10881 	case PTR_TO_XDP_SOCK:
10882 	case PTR_TO_BTF_ID:
10883 	case PTR_TO_BTF_ID_OR_NULL:
10884 		return false;
10885 	default:
10886 		return true;
10887 	}
10888 }
10889 
10890 /* If an instruction was previously used with particular pointer types, then we
10891  * need to be careful to avoid cases such as the below, where it may be ok
10892  * for one branch accessing the pointer, but not ok for the other branch:
10893  *
10894  * R1 = sock_ptr
10895  * goto X;
10896  * ...
10897  * R1 = some_other_valid_ptr;
10898  * goto X;
10899  * ...
10900  * R2 = *(u32 *)(R1 + 0);
10901  */
10902 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10903 {
10904 	return src != prev && (!reg_type_mismatch_ok(src) ||
10905 			       !reg_type_mismatch_ok(prev));
10906 }
10907 
10908 static int do_check(struct bpf_verifier_env *env)
10909 {
10910 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10911 	struct bpf_verifier_state *state = env->cur_state;
10912 	struct bpf_insn *insns = env->prog->insnsi;
10913 	struct bpf_reg_state *regs;
10914 	int insn_cnt = env->prog->len;
10915 	bool do_print_state = false;
10916 	int prev_insn_idx = -1;
10917 
10918 	for (;;) {
10919 		struct bpf_insn *insn;
10920 		u8 class;
10921 		int err;
10922 
10923 		env->prev_insn_idx = prev_insn_idx;
10924 		if (env->insn_idx >= insn_cnt) {
10925 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
10926 				env->insn_idx, insn_cnt);
10927 			return -EFAULT;
10928 		}
10929 
10930 		insn = &insns[env->insn_idx];
10931 		class = BPF_CLASS(insn->code);
10932 
10933 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10934 			verbose(env,
10935 				"BPF program is too large. Processed %d insn\n",
10936 				env->insn_processed);
10937 			return -E2BIG;
10938 		}
10939 
10940 		err = is_state_visited(env, env->insn_idx);
10941 		if (err < 0)
10942 			return err;
10943 		if (err == 1) {
10944 			/* found equivalent state, can prune the search */
10945 			if (env->log.level & BPF_LOG_LEVEL) {
10946 				if (do_print_state)
10947 					verbose(env, "\nfrom %d to %d%s: safe\n",
10948 						env->prev_insn_idx, env->insn_idx,
10949 						env->cur_state->speculative ?
10950 						" (speculative execution)" : "");
10951 				else
10952 					verbose(env, "%d: safe\n", env->insn_idx);
10953 			}
10954 			goto process_bpf_exit;
10955 		}
10956 
10957 		if (signal_pending(current))
10958 			return -EAGAIN;
10959 
10960 		if (need_resched())
10961 			cond_resched();
10962 
10963 		if (env->log.level & BPF_LOG_LEVEL2 ||
10964 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10965 			if (env->log.level & BPF_LOG_LEVEL2)
10966 				verbose(env, "%d:", env->insn_idx);
10967 			else
10968 				verbose(env, "\nfrom %d to %d%s:",
10969 					env->prev_insn_idx, env->insn_idx,
10970 					env->cur_state->speculative ?
10971 					" (speculative execution)" : "");
10972 			print_verifier_state(env, state->frame[state->curframe]);
10973 			do_print_state = false;
10974 		}
10975 
10976 		if (env->log.level & BPF_LOG_LEVEL) {
10977 			const struct bpf_insn_cbs cbs = {
10978 				.cb_call	= disasm_kfunc_name,
10979 				.cb_print	= verbose,
10980 				.private_data	= env,
10981 			};
10982 
10983 			verbose_linfo(env, env->insn_idx, "; ");
10984 			verbose(env, "%d: ", env->insn_idx);
10985 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10986 		}
10987 
10988 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
10989 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10990 							   env->prev_insn_idx);
10991 			if (err)
10992 				return err;
10993 		}
10994 
10995 		regs = cur_regs(env);
10996 		sanitize_mark_insn_seen(env);
10997 		prev_insn_idx = env->insn_idx;
10998 
10999 		if (class == BPF_ALU || class == BPF_ALU64) {
11000 			err = check_alu_op(env, insn);
11001 			if (err)
11002 				return err;
11003 
11004 		} else if (class == BPF_LDX) {
11005 			enum bpf_reg_type *prev_src_type, src_reg_type;
11006 
11007 			/* check for reserved fields is already done */
11008 
11009 			/* check src operand */
11010 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11011 			if (err)
11012 				return err;
11013 
11014 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11015 			if (err)
11016 				return err;
11017 
11018 			src_reg_type = regs[insn->src_reg].type;
11019 
11020 			/* check that memory (src_reg + off) is readable,
11021 			 * the state of dst_reg will be updated by this func
11022 			 */
11023 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11024 					       insn->off, BPF_SIZE(insn->code),
11025 					       BPF_READ, insn->dst_reg, false);
11026 			if (err)
11027 				return err;
11028 
11029 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11030 
11031 			if (*prev_src_type == NOT_INIT) {
11032 				/* saw a valid insn
11033 				 * dst_reg = *(u32 *)(src_reg + off)
11034 				 * save type to validate intersecting paths
11035 				 */
11036 				*prev_src_type = src_reg_type;
11037 
11038 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11039 				/* ABuser program is trying to use the same insn
11040 				 * dst_reg = *(u32*) (src_reg + off)
11041 				 * with different pointer types:
11042 				 * src_reg == ctx in one branch and
11043 				 * src_reg == stack|map in some other branch.
11044 				 * Reject it.
11045 				 */
11046 				verbose(env, "same insn cannot be used with different pointers\n");
11047 				return -EINVAL;
11048 			}
11049 
11050 		} else if (class == BPF_STX) {
11051 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11052 
11053 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11054 				err = check_atomic(env, env->insn_idx, insn);
11055 				if (err)
11056 					return err;
11057 				env->insn_idx++;
11058 				continue;
11059 			}
11060 
11061 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11062 				verbose(env, "BPF_STX uses reserved fields\n");
11063 				return -EINVAL;
11064 			}
11065 
11066 			/* check src1 operand */
11067 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11068 			if (err)
11069 				return err;
11070 			/* check src2 operand */
11071 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11072 			if (err)
11073 				return err;
11074 
11075 			dst_reg_type = regs[insn->dst_reg].type;
11076 
11077 			/* check that memory (dst_reg + off) is writeable */
11078 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11079 					       insn->off, BPF_SIZE(insn->code),
11080 					       BPF_WRITE, insn->src_reg, false);
11081 			if (err)
11082 				return err;
11083 
11084 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11085 
11086 			if (*prev_dst_type == NOT_INIT) {
11087 				*prev_dst_type = dst_reg_type;
11088 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11089 				verbose(env, "same insn cannot be used with different pointers\n");
11090 				return -EINVAL;
11091 			}
11092 
11093 		} else if (class == BPF_ST) {
11094 			if (BPF_MODE(insn->code) != BPF_MEM ||
11095 			    insn->src_reg != BPF_REG_0) {
11096 				verbose(env, "BPF_ST uses reserved fields\n");
11097 				return -EINVAL;
11098 			}
11099 			/* check src operand */
11100 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11101 			if (err)
11102 				return err;
11103 
11104 			if (is_ctx_reg(env, insn->dst_reg)) {
11105 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11106 					insn->dst_reg,
11107 					reg_type_str[reg_state(env, insn->dst_reg)->type]);
11108 				return -EACCES;
11109 			}
11110 
11111 			/* check that memory (dst_reg + off) is writeable */
11112 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11113 					       insn->off, BPF_SIZE(insn->code),
11114 					       BPF_WRITE, -1, false);
11115 			if (err)
11116 				return err;
11117 
11118 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11119 			u8 opcode = BPF_OP(insn->code);
11120 
11121 			env->jmps_processed++;
11122 			if (opcode == BPF_CALL) {
11123 				if (BPF_SRC(insn->code) != BPF_K ||
11124 				    insn->off != 0 ||
11125 				    (insn->src_reg != BPF_REG_0 &&
11126 				     insn->src_reg != BPF_PSEUDO_CALL &&
11127 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11128 				    insn->dst_reg != BPF_REG_0 ||
11129 				    class == BPF_JMP32) {
11130 					verbose(env, "BPF_CALL uses reserved fields\n");
11131 					return -EINVAL;
11132 				}
11133 
11134 				if (env->cur_state->active_spin_lock &&
11135 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11136 				     insn->imm != BPF_FUNC_spin_unlock)) {
11137 					verbose(env, "function calls are not allowed while holding a lock\n");
11138 					return -EINVAL;
11139 				}
11140 				if (insn->src_reg == BPF_PSEUDO_CALL)
11141 					err = check_func_call(env, insn, &env->insn_idx);
11142 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11143 					err = check_kfunc_call(env, insn);
11144 				else
11145 					err = check_helper_call(env, insn, &env->insn_idx);
11146 				if (err)
11147 					return err;
11148 			} else if (opcode == BPF_JA) {
11149 				if (BPF_SRC(insn->code) != BPF_K ||
11150 				    insn->imm != 0 ||
11151 				    insn->src_reg != BPF_REG_0 ||
11152 				    insn->dst_reg != BPF_REG_0 ||
11153 				    class == BPF_JMP32) {
11154 					verbose(env, "BPF_JA uses reserved fields\n");
11155 					return -EINVAL;
11156 				}
11157 
11158 				env->insn_idx += insn->off + 1;
11159 				continue;
11160 
11161 			} else if (opcode == BPF_EXIT) {
11162 				if (BPF_SRC(insn->code) != BPF_K ||
11163 				    insn->imm != 0 ||
11164 				    insn->src_reg != BPF_REG_0 ||
11165 				    insn->dst_reg != BPF_REG_0 ||
11166 				    class == BPF_JMP32) {
11167 					verbose(env, "BPF_EXIT uses reserved fields\n");
11168 					return -EINVAL;
11169 				}
11170 
11171 				if (env->cur_state->active_spin_lock) {
11172 					verbose(env, "bpf_spin_unlock is missing\n");
11173 					return -EINVAL;
11174 				}
11175 
11176 				if (state->curframe) {
11177 					/* exit from nested function */
11178 					err = prepare_func_exit(env, &env->insn_idx);
11179 					if (err)
11180 						return err;
11181 					do_print_state = true;
11182 					continue;
11183 				}
11184 
11185 				err = check_reference_leak(env);
11186 				if (err)
11187 					return err;
11188 
11189 				err = check_return_code(env);
11190 				if (err)
11191 					return err;
11192 process_bpf_exit:
11193 				update_branch_counts(env, env->cur_state);
11194 				err = pop_stack(env, &prev_insn_idx,
11195 						&env->insn_idx, pop_log);
11196 				if (err < 0) {
11197 					if (err != -ENOENT)
11198 						return err;
11199 					break;
11200 				} else {
11201 					do_print_state = true;
11202 					continue;
11203 				}
11204 			} else {
11205 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11206 				if (err)
11207 					return err;
11208 			}
11209 		} else if (class == BPF_LD) {
11210 			u8 mode = BPF_MODE(insn->code);
11211 
11212 			if (mode == BPF_ABS || mode == BPF_IND) {
11213 				err = check_ld_abs(env, insn);
11214 				if (err)
11215 					return err;
11216 
11217 			} else if (mode == BPF_IMM) {
11218 				err = check_ld_imm(env, insn);
11219 				if (err)
11220 					return err;
11221 
11222 				env->insn_idx++;
11223 				sanitize_mark_insn_seen(env);
11224 			} else {
11225 				verbose(env, "invalid BPF_LD mode\n");
11226 				return -EINVAL;
11227 			}
11228 		} else {
11229 			verbose(env, "unknown insn class %d\n", class);
11230 			return -EINVAL;
11231 		}
11232 
11233 		env->insn_idx++;
11234 	}
11235 
11236 	return 0;
11237 }
11238 
11239 static int find_btf_percpu_datasec(struct btf *btf)
11240 {
11241 	const struct btf_type *t;
11242 	const char *tname;
11243 	int i, n;
11244 
11245 	/*
11246 	 * Both vmlinux and module each have their own ".data..percpu"
11247 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11248 	 * types to look at only module's own BTF types.
11249 	 */
11250 	n = btf_nr_types(btf);
11251 	if (btf_is_module(btf))
11252 		i = btf_nr_types(btf_vmlinux);
11253 	else
11254 		i = 1;
11255 
11256 	for(; i < n; i++) {
11257 		t = btf_type_by_id(btf, i);
11258 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11259 			continue;
11260 
11261 		tname = btf_name_by_offset(btf, t->name_off);
11262 		if (!strcmp(tname, ".data..percpu"))
11263 			return i;
11264 	}
11265 
11266 	return -ENOENT;
11267 }
11268 
11269 /* replace pseudo btf_id with kernel symbol address */
11270 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11271 			       struct bpf_insn *insn,
11272 			       struct bpf_insn_aux_data *aux)
11273 {
11274 	const struct btf_var_secinfo *vsi;
11275 	const struct btf_type *datasec;
11276 	struct btf_mod_pair *btf_mod;
11277 	const struct btf_type *t;
11278 	const char *sym_name;
11279 	bool percpu = false;
11280 	u32 type, id = insn->imm;
11281 	struct btf *btf;
11282 	s32 datasec_id;
11283 	u64 addr;
11284 	int i, btf_fd, err;
11285 
11286 	btf_fd = insn[1].imm;
11287 	if (btf_fd) {
11288 		btf = btf_get_by_fd(btf_fd);
11289 		if (IS_ERR(btf)) {
11290 			verbose(env, "invalid module BTF object FD specified.\n");
11291 			return -EINVAL;
11292 		}
11293 	} else {
11294 		if (!btf_vmlinux) {
11295 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11296 			return -EINVAL;
11297 		}
11298 		btf = btf_vmlinux;
11299 		btf_get(btf);
11300 	}
11301 
11302 	t = btf_type_by_id(btf, id);
11303 	if (!t) {
11304 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11305 		err = -ENOENT;
11306 		goto err_put;
11307 	}
11308 
11309 	if (!btf_type_is_var(t)) {
11310 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11311 		err = -EINVAL;
11312 		goto err_put;
11313 	}
11314 
11315 	sym_name = btf_name_by_offset(btf, t->name_off);
11316 	addr = kallsyms_lookup_name(sym_name);
11317 	if (!addr) {
11318 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11319 			sym_name);
11320 		err = -ENOENT;
11321 		goto err_put;
11322 	}
11323 
11324 	datasec_id = find_btf_percpu_datasec(btf);
11325 	if (datasec_id > 0) {
11326 		datasec = btf_type_by_id(btf, datasec_id);
11327 		for_each_vsi(i, datasec, vsi) {
11328 			if (vsi->type == id) {
11329 				percpu = true;
11330 				break;
11331 			}
11332 		}
11333 	}
11334 
11335 	insn[0].imm = (u32)addr;
11336 	insn[1].imm = addr >> 32;
11337 
11338 	type = t->type;
11339 	t = btf_type_skip_modifiers(btf, type, NULL);
11340 	if (percpu) {
11341 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11342 		aux->btf_var.btf = btf;
11343 		aux->btf_var.btf_id = type;
11344 	} else if (!btf_type_is_struct(t)) {
11345 		const struct btf_type *ret;
11346 		const char *tname;
11347 		u32 tsize;
11348 
11349 		/* resolve the type size of ksym. */
11350 		ret = btf_resolve_size(btf, t, &tsize);
11351 		if (IS_ERR(ret)) {
11352 			tname = btf_name_by_offset(btf, t->name_off);
11353 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11354 				tname, PTR_ERR(ret));
11355 			err = -EINVAL;
11356 			goto err_put;
11357 		}
11358 		aux->btf_var.reg_type = PTR_TO_MEM;
11359 		aux->btf_var.mem_size = tsize;
11360 	} else {
11361 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11362 		aux->btf_var.btf = btf;
11363 		aux->btf_var.btf_id = type;
11364 	}
11365 
11366 	/* check whether we recorded this BTF (and maybe module) already */
11367 	for (i = 0; i < env->used_btf_cnt; i++) {
11368 		if (env->used_btfs[i].btf == btf) {
11369 			btf_put(btf);
11370 			return 0;
11371 		}
11372 	}
11373 
11374 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11375 		err = -E2BIG;
11376 		goto err_put;
11377 	}
11378 
11379 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11380 	btf_mod->btf = btf;
11381 	btf_mod->module = NULL;
11382 
11383 	/* if we reference variables from kernel module, bump its refcount */
11384 	if (btf_is_module(btf)) {
11385 		btf_mod->module = btf_try_get_module(btf);
11386 		if (!btf_mod->module) {
11387 			err = -ENXIO;
11388 			goto err_put;
11389 		}
11390 	}
11391 
11392 	env->used_btf_cnt++;
11393 
11394 	return 0;
11395 err_put:
11396 	btf_put(btf);
11397 	return err;
11398 }
11399 
11400 static int check_map_prealloc(struct bpf_map *map)
11401 {
11402 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11403 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11404 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11405 		!(map->map_flags & BPF_F_NO_PREALLOC);
11406 }
11407 
11408 static bool is_tracing_prog_type(enum bpf_prog_type type)
11409 {
11410 	switch (type) {
11411 	case BPF_PROG_TYPE_KPROBE:
11412 	case BPF_PROG_TYPE_TRACEPOINT:
11413 	case BPF_PROG_TYPE_PERF_EVENT:
11414 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11415 		return true;
11416 	default:
11417 		return false;
11418 	}
11419 }
11420 
11421 static bool is_preallocated_map(struct bpf_map *map)
11422 {
11423 	if (!check_map_prealloc(map))
11424 		return false;
11425 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11426 		return false;
11427 	return true;
11428 }
11429 
11430 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11431 					struct bpf_map *map,
11432 					struct bpf_prog *prog)
11433 
11434 {
11435 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11436 	/*
11437 	 * Validate that trace type programs use preallocated hash maps.
11438 	 *
11439 	 * For programs attached to PERF events this is mandatory as the
11440 	 * perf NMI can hit any arbitrary code sequence.
11441 	 *
11442 	 * All other trace types using preallocated hash maps are unsafe as
11443 	 * well because tracepoint or kprobes can be inside locked regions
11444 	 * of the memory allocator or at a place where a recursion into the
11445 	 * memory allocator would see inconsistent state.
11446 	 *
11447 	 * On RT enabled kernels run-time allocation of all trace type
11448 	 * programs is strictly prohibited due to lock type constraints. On
11449 	 * !RT kernels it is allowed for backwards compatibility reasons for
11450 	 * now, but warnings are emitted so developers are made aware of
11451 	 * the unsafety and can fix their programs before this is enforced.
11452 	 */
11453 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11454 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11455 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11456 			return -EINVAL;
11457 		}
11458 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11459 			verbose(env, "trace type programs can only use preallocated hash map\n");
11460 			return -EINVAL;
11461 		}
11462 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11463 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11464 	}
11465 
11466 	if (map_value_has_spin_lock(map)) {
11467 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11468 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11469 			return -EINVAL;
11470 		}
11471 
11472 		if (is_tracing_prog_type(prog_type)) {
11473 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11474 			return -EINVAL;
11475 		}
11476 
11477 		if (prog->aux->sleepable) {
11478 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11479 			return -EINVAL;
11480 		}
11481 	}
11482 
11483 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11484 	    !bpf_offload_prog_map_match(prog, map)) {
11485 		verbose(env, "offload device mismatch between prog and map\n");
11486 		return -EINVAL;
11487 	}
11488 
11489 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11490 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11491 		return -EINVAL;
11492 	}
11493 
11494 	if (prog->aux->sleepable)
11495 		switch (map->map_type) {
11496 		case BPF_MAP_TYPE_HASH:
11497 		case BPF_MAP_TYPE_LRU_HASH:
11498 		case BPF_MAP_TYPE_ARRAY:
11499 		case BPF_MAP_TYPE_PERCPU_HASH:
11500 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11501 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11502 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11503 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11504 			if (!is_preallocated_map(map)) {
11505 				verbose(env,
11506 					"Sleepable programs can only use preallocated maps\n");
11507 				return -EINVAL;
11508 			}
11509 			break;
11510 		case BPF_MAP_TYPE_RINGBUF:
11511 			break;
11512 		default:
11513 			verbose(env,
11514 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11515 			return -EINVAL;
11516 		}
11517 
11518 	return 0;
11519 }
11520 
11521 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11522 {
11523 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11524 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11525 }
11526 
11527 /* find and rewrite pseudo imm in ld_imm64 instructions:
11528  *
11529  * 1. if it accesses map FD, replace it with actual map pointer.
11530  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11531  *
11532  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11533  */
11534 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11535 {
11536 	struct bpf_insn *insn = env->prog->insnsi;
11537 	int insn_cnt = env->prog->len;
11538 	int i, j, err;
11539 
11540 	err = bpf_prog_calc_tag(env->prog);
11541 	if (err)
11542 		return err;
11543 
11544 	for (i = 0; i < insn_cnt; i++, insn++) {
11545 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11546 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11547 			verbose(env, "BPF_LDX uses reserved fields\n");
11548 			return -EINVAL;
11549 		}
11550 
11551 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11552 			struct bpf_insn_aux_data *aux;
11553 			struct bpf_map *map;
11554 			struct fd f;
11555 			u64 addr;
11556 			u32 fd;
11557 
11558 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11559 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11560 			    insn[1].off != 0) {
11561 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11562 				return -EINVAL;
11563 			}
11564 
11565 			if (insn[0].src_reg == 0)
11566 				/* valid generic load 64-bit imm */
11567 				goto next_insn;
11568 
11569 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11570 				aux = &env->insn_aux_data[i];
11571 				err = check_pseudo_btf_id(env, insn, aux);
11572 				if (err)
11573 					return err;
11574 				goto next_insn;
11575 			}
11576 
11577 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11578 				aux = &env->insn_aux_data[i];
11579 				aux->ptr_type = PTR_TO_FUNC;
11580 				goto next_insn;
11581 			}
11582 
11583 			/* In final convert_pseudo_ld_imm64() step, this is
11584 			 * converted into regular 64-bit imm load insn.
11585 			 */
11586 			switch (insn[0].src_reg) {
11587 			case BPF_PSEUDO_MAP_VALUE:
11588 			case BPF_PSEUDO_MAP_IDX_VALUE:
11589 				break;
11590 			case BPF_PSEUDO_MAP_FD:
11591 			case BPF_PSEUDO_MAP_IDX:
11592 				if (insn[1].imm == 0)
11593 					break;
11594 				fallthrough;
11595 			default:
11596 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11597 				return -EINVAL;
11598 			}
11599 
11600 			switch (insn[0].src_reg) {
11601 			case BPF_PSEUDO_MAP_IDX_VALUE:
11602 			case BPF_PSEUDO_MAP_IDX:
11603 				if (bpfptr_is_null(env->fd_array)) {
11604 					verbose(env, "fd_idx without fd_array is invalid\n");
11605 					return -EPROTO;
11606 				}
11607 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11608 							    insn[0].imm * sizeof(fd),
11609 							    sizeof(fd)))
11610 					return -EFAULT;
11611 				break;
11612 			default:
11613 				fd = insn[0].imm;
11614 				break;
11615 			}
11616 
11617 			f = fdget(fd);
11618 			map = __bpf_map_get(f);
11619 			if (IS_ERR(map)) {
11620 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11621 					insn[0].imm);
11622 				return PTR_ERR(map);
11623 			}
11624 
11625 			err = check_map_prog_compatibility(env, map, env->prog);
11626 			if (err) {
11627 				fdput(f);
11628 				return err;
11629 			}
11630 
11631 			aux = &env->insn_aux_data[i];
11632 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11633 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11634 				addr = (unsigned long)map;
11635 			} else {
11636 				u32 off = insn[1].imm;
11637 
11638 				if (off >= BPF_MAX_VAR_OFF) {
11639 					verbose(env, "direct value offset of %u is not allowed\n", off);
11640 					fdput(f);
11641 					return -EINVAL;
11642 				}
11643 
11644 				if (!map->ops->map_direct_value_addr) {
11645 					verbose(env, "no direct value access support for this map type\n");
11646 					fdput(f);
11647 					return -EINVAL;
11648 				}
11649 
11650 				err = map->ops->map_direct_value_addr(map, &addr, off);
11651 				if (err) {
11652 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11653 						map->value_size, off);
11654 					fdput(f);
11655 					return err;
11656 				}
11657 
11658 				aux->map_off = off;
11659 				addr += off;
11660 			}
11661 
11662 			insn[0].imm = (u32)addr;
11663 			insn[1].imm = addr >> 32;
11664 
11665 			/* check whether we recorded this map already */
11666 			for (j = 0; j < env->used_map_cnt; j++) {
11667 				if (env->used_maps[j] == map) {
11668 					aux->map_index = j;
11669 					fdput(f);
11670 					goto next_insn;
11671 				}
11672 			}
11673 
11674 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11675 				fdput(f);
11676 				return -E2BIG;
11677 			}
11678 
11679 			/* hold the map. If the program is rejected by verifier,
11680 			 * the map will be released by release_maps() or it
11681 			 * will be used by the valid program until it's unloaded
11682 			 * and all maps are released in free_used_maps()
11683 			 */
11684 			bpf_map_inc(map);
11685 
11686 			aux->map_index = env->used_map_cnt;
11687 			env->used_maps[env->used_map_cnt++] = map;
11688 
11689 			if (bpf_map_is_cgroup_storage(map) &&
11690 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11691 				verbose(env, "only one cgroup storage of each type is allowed\n");
11692 				fdput(f);
11693 				return -EBUSY;
11694 			}
11695 
11696 			fdput(f);
11697 next_insn:
11698 			insn++;
11699 			i++;
11700 			continue;
11701 		}
11702 
11703 		/* Basic sanity check before we invest more work here. */
11704 		if (!bpf_opcode_in_insntable(insn->code)) {
11705 			verbose(env, "unknown opcode %02x\n", insn->code);
11706 			return -EINVAL;
11707 		}
11708 	}
11709 
11710 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11711 	 * 'struct bpf_map *' into a register instead of user map_fd.
11712 	 * These pointers will be used later by verifier to validate map access.
11713 	 */
11714 	return 0;
11715 }
11716 
11717 /* drop refcnt of maps used by the rejected program */
11718 static void release_maps(struct bpf_verifier_env *env)
11719 {
11720 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11721 			     env->used_map_cnt);
11722 }
11723 
11724 /* drop refcnt of maps used by the rejected program */
11725 static void release_btfs(struct bpf_verifier_env *env)
11726 {
11727 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11728 			     env->used_btf_cnt);
11729 }
11730 
11731 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11732 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11733 {
11734 	struct bpf_insn *insn = env->prog->insnsi;
11735 	int insn_cnt = env->prog->len;
11736 	int i;
11737 
11738 	for (i = 0; i < insn_cnt; i++, insn++) {
11739 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11740 			continue;
11741 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11742 			continue;
11743 		insn->src_reg = 0;
11744 	}
11745 }
11746 
11747 /* single env->prog->insni[off] instruction was replaced with the range
11748  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11749  * [0, off) and [off, end) to new locations, so the patched range stays zero
11750  */
11751 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11752 				 struct bpf_insn_aux_data *new_data,
11753 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11754 {
11755 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11756 	struct bpf_insn *insn = new_prog->insnsi;
11757 	u32 old_seen = old_data[off].seen;
11758 	u32 prog_len;
11759 	int i;
11760 
11761 	/* aux info at OFF always needs adjustment, no matter fast path
11762 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11763 	 * original insn at old prog.
11764 	 */
11765 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11766 
11767 	if (cnt == 1)
11768 		return;
11769 	prog_len = new_prog->len;
11770 
11771 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11772 	memcpy(new_data + off + cnt - 1, old_data + off,
11773 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11774 	for (i = off; i < off + cnt - 1; i++) {
11775 		/* Expand insni[off]'s seen count to the patched range. */
11776 		new_data[i].seen = old_seen;
11777 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11778 	}
11779 	env->insn_aux_data = new_data;
11780 	vfree(old_data);
11781 }
11782 
11783 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11784 {
11785 	int i;
11786 
11787 	if (len == 1)
11788 		return;
11789 	/* NOTE: fake 'exit' subprog should be updated as well. */
11790 	for (i = 0; i <= env->subprog_cnt; i++) {
11791 		if (env->subprog_info[i].start <= off)
11792 			continue;
11793 		env->subprog_info[i].start += len - 1;
11794 	}
11795 }
11796 
11797 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11798 {
11799 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11800 	int i, sz = prog->aux->size_poke_tab;
11801 	struct bpf_jit_poke_descriptor *desc;
11802 
11803 	for (i = 0; i < sz; i++) {
11804 		desc = &tab[i];
11805 		if (desc->insn_idx <= off)
11806 			continue;
11807 		desc->insn_idx += len - 1;
11808 	}
11809 }
11810 
11811 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11812 					    const struct bpf_insn *patch, u32 len)
11813 {
11814 	struct bpf_prog *new_prog;
11815 	struct bpf_insn_aux_data *new_data = NULL;
11816 
11817 	if (len > 1) {
11818 		new_data = vzalloc(array_size(env->prog->len + len - 1,
11819 					      sizeof(struct bpf_insn_aux_data)));
11820 		if (!new_data)
11821 			return NULL;
11822 	}
11823 
11824 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11825 	if (IS_ERR(new_prog)) {
11826 		if (PTR_ERR(new_prog) == -ERANGE)
11827 			verbose(env,
11828 				"insn %d cannot be patched due to 16-bit range\n",
11829 				env->insn_aux_data[off].orig_idx);
11830 		vfree(new_data);
11831 		return NULL;
11832 	}
11833 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
11834 	adjust_subprog_starts(env, off, len);
11835 	adjust_poke_descs(new_prog, off, len);
11836 	return new_prog;
11837 }
11838 
11839 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11840 					      u32 off, u32 cnt)
11841 {
11842 	int i, j;
11843 
11844 	/* find first prog starting at or after off (first to remove) */
11845 	for (i = 0; i < env->subprog_cnt; i++)
11846 		if (env->subprog_info[i].start >= off)
11847 			break;
11848 	/* find first prog starting at or after off + cnt (first to stay) */
11849 	for (j = i; j < env->subprog_cnt; j++)
11850 		if (env->subprog_info[j].start >= off + cnt)
11851 			break;
11852 	/* if j doesn't start exactly at off + cnt, we are just removing
11853 	 * the front of previous prog
11854 	 */
11855 	if (env->subprog_info[j].start != off + cnt)
11856 		j--;
11857 
11858 	if (j > i) {
11859 		struct bpf_prog_aux *aux = env->prog->aux;
11860 		int move;
11861 
11862 		/* move fake 'exit' subprog as well */
11863 		move = env->subprog_cnt + 1 - j;
11864 
11865 		memmove(env->subprog_info + i,
11866 			env->subprog_info + j,
11867 			sizeof(*env->subprog_info) * move);
11868 		env->subprog_cnt -= j - i;
11869 
11870 		/* remove func_info */
11871 		if (aux->func_info) {
11872 			move = aux->func_info_cnt - j;
11873 
11874 			memmove(aux->func_info + i,
11875 				aux->func_info + j,
11876 				sizeof(*aux->func_info) * move);
11877 			aux->func_info_cnt -= j - i;
11878 			/* func_info->insn_off is set after all code rewrites,
11879 			 * in adjust_btf_func() - no need to adjust
11880 			 */
11881 		}
11882 	} else {
11883 		/* convert i from "first prog to remove" to "first to adjust" */
11884 		if (env->subprog_info[i].start == off)
11885 			i++;
11886 	}
11887 
11888 	/* update fake 'exit' subprog as well */
11889 	for (; i <= env->subprog_cnt; i++)
11890 		env->subprog_info[i].start -= cnt;
11891 
11892 	return 0;
11893 }
11894 
11895 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11896 				      u32 cnt)
11897 {
11898 	struct bpf_prog *prog = env->prog;
11899 	u32 i, l_off, l_cnt, nr_linfo;
11900 	struct bpf_line_info *linfo;
11901 
11902 	nr_linfo = prog->aux->nr_linfo;
11903 	if (!nr_linfo)
11904 		return 0;
11905 
11906 	linfo = prog->aux->linfo;
11907 
11908 	/* find first line info to remove, count lines to be removed */
11909 	for (i = 0; i < nr_linfo; i++)
11910 		if (linfo[i].insn_off >= off)
11911 			break;
11912 
11913 	l_off = i;
11914 	l_cnt = 0;
11915 	for (; i < nr_linfo; i++)
11916 		if (linfo[i].insn_off < off + cnt)
11917 			l_cnt++;
11918 		else
11919 			break;
11920 
11921 	/* First live insn doesn't match first live linfo, it needs to "inherit"
11922 	 * last removed linfo.  prog is already modified, so prog->len == off
11923 	 * means no live instructions after (tail of the program was removed).
11924 	 */
11925 	if (prog->len != off && l_cnt &&
11926 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11927 		l_cnt--;
11928 		linfo[--i].insn_off = off + cnt;
11929 	}
11930 
11931 	/* remove the line info which refer to the removed instructions */
11932 	if (l_cnt) {
11933 		memmove(linfo + l_off, linfo + i,
11934 			sizeof(*linfo) * (nr_linfo - i));
11935 
11936 		prog->aux->nr_linfo -= l_cnt;
11937 		nr_linfo = prog->aux->nr_linfo;
11938 	}
11939 
11940 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
11941 	for (i = l_off; i < nr_linfo; i++)
11942 		linfo[i].insn_off -= cnt;
11943 
11944 	/* fix up all subprogs (incl. 'exit') which start >= off */
11945 	for (i = 0; i <= env->subprog_cnt; i++)
11946 		if (env->subprog_info[i].linfo_idx > l_off) {
11947 			/* program may have started in the removed region but
11948 			 * may not be fully removed
11949 			 */
11950 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11951 				env->subprog_info[i].linfo_idx -= l_cnt;
11952 			else
11953 				env->subprog_info[i].linfo_idx = l_off;
11954 		}
11955 
11956 	return 0;
11957 }
11958 
11959 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11960 {
11961 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11962 	unsigned int orig_prog_len = env->prog->len;
11963 	int err;
11964 
11965 	if (bpf_prog_is_dev_bound(env->prog->aux))
11966 		bpf_prog_offload_remove_insns(env, off, cnt);
11967 
11968 	err = bpf_remove_insns(env->prog, off, cnt);
11969 	if (err)
11970 		return err;
11971 
11972 	err = adjust_subprog_starts_after_remove(env, off, cnt);
11973 	if (err)
11974 		return err;
11975 
11976 	err = bpf_adj_linfo_after_remove(env, off, cnt);
11977 	if (err)
11978 		return err;
11979 
11980 	memmove(aux_data + off,	aux_data + off + cnt,
11981 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
11982 
11983 	return 0;
11984 }
11985 
11986 /* The verifier does more data flow analysis than llvm and will not
11987  * explore branches that are dead at run time. Malicious programs can
11988  * have dead code too. Therefore replace all dead at-run-time code
11989  * with 'ja -1'.
11990  *
11991  * Just nops are not optimal, e.g. if they would sit at the end of the
11992  * program and through another bug we would manage to jump there, then
11993  * we'd execute beyond program memory otherwise. Returning exception
11994  * code also wouldn't work since we can have subprogs where the dead
11995  * code could be located.
11996  */
11997 static void sanitize_dead_code(struct bpf_verifier_env *env)
11998 {
11999 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12000 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12001 	struct bpf_insn *insn = env->prog->insnsi;
12002 	const int insn_cnt = env->prog->len;
12003 	int i;
12004 
12005 	for (i = 0; i < insn_cnt; i++) {
12006 		if (aux_data[i].seen)
12007 			continue;
12008 		memcpy(insn + i, &trap, sizeof(trap));
12009 		aux_data[i].zext_dst = false;
12010 	}
12011 }
12012 
12013 static bool insn_is_cond_jump(u8 code)
12014 {
12015 	u8 op;
12016 
12017 	if (BPF_CLASS(code) == BPF_JMP32)
12018 		return true;
12019 
12020 	if (BPF_CLASS(code) != BPF_JMP)
12021 		return false;
12022 
12023 	op = BPF_OP(code);
12024 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12025 }
12026 
12027 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12028 {
12029 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12030 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12031 	struct bpf_insn *insn = env->prog->insnsi;
12032 	const int insn_cnt = env->prog->len;
12033 	int i;
12034 
12035 	for (i = 0; i < insn_cnt; i++, insn++) {
12036 		if (!insn_is_cond_jump(insn->code))
12037 			continue;
12038 
12039 		if (!aux_data[i + 1].seen)
12040 			ja.off = insn->off;
12041 		else if (!aux_data[i + 1 + insn->off].seen)
12042 			ja.off = 0;
12043 		else
12044 			continue;
12045 
12046 		if (bpf_prog_is_dev_bound(env->prog->aux))
12047 			bpf_prog_offload_replace_insn(env, i, &ja);
12048 
12049 		memcpy(insn, &ja, sizeof(ja));
12050 	}
12051 }
12052 
12053 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12054 {
12055 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12056 	int insn_cnt = env->prog->len;
12057 	int i, err;
12058 
12059 	for (i = 0; i < insn_cnt; i++) {
12060 		int j;
12061 
12062 		j = 0;
12063 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12064 			j++;
12065 		if (!j)
12066 			continue;
12067 
12068 		err = verifier_remove_insns(env, i, j);
12069 		if (err)
12070 			return err;
12071 		insn_cnt = env->prog->len;
12072 	}
12073 
12074 	return 0;
12075 }
12076 
12077 static int opt_remove_nops(struct bpf_verifier_env *env)
12078 {
12079 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12080 	struct bpf_insn *insn = env->prog->insnsi;
12081 	int insn_cnt = env->prog->len;
12082 	int i, err;
12083 
12084 	for (i = 0; i < insn_cnt; i++) {
12085 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12086 			continue;
12087 
12088 		err = verifier_remove_insns(env, i, 1);
12089 		if (err)
12090 			return err;
12091 		insn_cnt--;
12092 		i--;
12093 	}
12094 
12095 	return 0;
12096 }
12097 
12098 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12099 					 const union bpf_attr *attr)
12100 {
12101 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12102 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12103 	int i, patch_len, delta = 0, len = env->prog->len;
12104 	struct bpf_insn *insns = env->prog->insnsi;
12105 	struct bpf_prog *new_prog;
12106 	bool rnd_hi32;
12107 
12108 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12109 	zext_patch[1] = BPF_ZEXT_REG(0);
12110 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12111 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12112 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12113 	for (i = 0; i < len; i++) {
12114 		int adj_idx = i + delta;
12115 		struct bpf_insn insn;
12116 		int load_reg;
12117 
12118 		insn = insns[adj_idx];
12119 		load_reg = insn_def_regno(&insn);
12120 		if (!aux[adj_idx].zext_dst) {
12121 			u8 code, class;
12122 			u32 imm_rnd;
12123 
12124 			if (!rnd_hi32)
12125 				continue;
12126 
12127 			code = insn.code;
12128 			class = BPF_CLASS(code);
12129 			if (load_reg == -1)
12130 				continue;
12131 
12132 			/* NOTE: arg "reg" (the fourth one) is only used for
12133 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12134 			 *       here.
12135 			 */
12136 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12137 				if (class == BPF_LD &&
12138 				    BPF_MODE(code) == BPF_IMM)
12139 					i++;
12140 				continue;
12141 			}
12142 
12143 			/* ctx load could be transformed into wider load. */
12144 			if (class == BPF_LDX &&
12145 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12146 				continue;
12147 
12148 			imm_rnd = get_random_int();
12149 			rnd_hi32_patch[0] = insn;
12150 			rnd_hi32_patch[1].imm = imm_rnd;
12151 			rnd_hi32_patch[3].dst_reg = load_reg;
12152 			patch = rnd_hi32_patch;
12153 			patch_len = 4;
12154 			goto apply_patch_buffer;
12155 		}
12156 
12157 		/* Add in an zero-extend instruction if a) the JIT has requested
12158 		 * it or b) it's a CMPXCHG.
12159 		 *
12160 		 * The latter is because: BPF_CMPXCHG always loads a value into
12161 		 * R0, therefore always zero-extends. However some archs'
12162 		 * equivalent instruction only does this load when the
12163 		 * comparison is successful. This detail of CMPXCHG is
12164 		 * orthogonal to the general zero-extension behaviour of the
12165 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12166 		 */
12167 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12168 			continue;
12169 
12170 		if (WARN_ON(load_reg == -1)) {
12171 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12172 			return -EFAULT;
12173 		}
12174 
12175 		zext_patch[0] = insn;
12176 		zext_patch[1].dst_reg = load_reg;
12177 		zext_patch[1].src_reg = load_reg;
12178 		patch = zext_patch;
12179 		patch_len = 2;
12180 apply_patch_buffer:
12181 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12182 		if (!new_prog)
12183 			return -ENOMEM;
12184 		env->prog = new_prog;
12185 		insns = new_prog->insnsi;
12186 		aux = env->insn_aux_data;
12187 		delta += patch_len - 1;
12188 	}
12189 
12190 	return 0;
12191 }
12192 
12193 /* convert load instructions that access fields of a context type into a
12194  * sequence of instructions that access fields of the underlying structure:
12195  *     struct __sk_buff    -> struct sk_buff
12196  *     struct bpf_sock_ops -> struct sock
12197  */
12198 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12199 {
12200 	const struct bpf_verifier_ops *ops = env->ops;
12201 	int i, cnt, size, ctx_field_size, delta = 0;
12202 	const int insn_cnt = env->prog->len;
12203 	struct bpf_insn insn_buf[16], *insn;
12204 	u32 target_size, size_default, off;
12205 	struct bpf_prog *new_prog;
12206 	enum bpf_access_type type;
12207 	bool is_narrower_load;
12208 
12209 	if (ops->gen_prologue || env->seen_direct_write) {
12210 		if (!ops->gen_prologue) {
12211 			verbose(env, "bpf verifier is misconfigured\n");
12212 			return -EINVAL;
12213 		}
12214 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12215 					env->prog);
12216 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12217 			verbose(env, "bpf verifier is misconfigured\n");
12218 			return -EINVAL;
12219 		} else if (cnt) {
12220 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12221 			if (!new_prog)
12222 				return -ENOMEM;
12223 
12224 			env->prog = new_prog;
12225 			delta += cnt - 1;
12226 		}
12227 	}
12228 
12229 	if (bpf_prog_is_dev_bound(env->prog->aux))
12230 		return 0;
12231 
12232 	insn = env->prog->insnsi + delta;
12233 
12234 	for (i = 0; i < insn_cnt; i++, insn++) {
12235 		bpf_convert_ctx_access_t convert_ctx_access;
12236 		bool ctx_access;
12237 
12238 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12239 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12240 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12241 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12242 			type = BPF_READ;
12243 			ctx_access = true;
12244 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12245 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12246 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12247 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12248 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12249 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12250 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12251 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12252 			type = BPF_WRITE;
12253 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12254 		} else {
12255 			continue;
12256 		}
12257 
12258 		if (type == BPF_WRITE &&
12259 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12260 			struct bpf_insn patch[] = {
12261 				*insn,
12262 				BPF_ST_NOSPEC(),
12263 			};
12264 
12265 			cnt = ARRAY_SIZE(patch);
12266 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12267 			if (!new_prog)
12268 				return -ENOMEM;
12269 
12270 			delta    += cnt - 1;
12271 			env->prog = new_prog;
12272 			insn      = new_prog->insnsi + i + delta;
12273 			continue;
12274 		}
12275 
12276 		if (!ctx_access)
12277 			continue;
12278 
12279 		switch (env->insn_aux_data[i + delta].ptr_type) {
12280 		case PTR_TO_CTX:
12281 			if (!ops->convert_ctx_access)
12282 				continue;
12283 			convert_ctx_access = ops->convert_ctx_access;
12284 			break;
12285 		case PTR_TO_SOCKET:
12286 		case PTR_TO_SOCK_COMMON:
12287 			convert_ctx_access = bpf_sock_convert_ctx_access;
12288 			break;
12289 		case PTR_TO_TCP_SOCK:
12290 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12291 			break;
12292 		case PTR_TO_XDP_SOCK:
12293 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12294 			break;
12295 		case PTR_TO_BTF_ID:
12296 			if (type == BPF_READ) {
12297 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12298 					BPF_SIZE((insn)->code);
12299 				env->prog->aux->num_exentries++;
12300 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12301 				verbose(env, "Writes through BTF pointers are not allowed\n");
12302 				return -EINVAL;
12303 			}
12304 			continue;
12305 		default:
12306 			continue;
12307 		}
12308 
12309 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12310 		size = BPF_LDST_BYTES(insn);
12311 
12312 		/* If the read access is a narrower load of the field,
12313 		 * convert to a 4/8-byte load, to minimum program type specific
12314 		 * convert_ctx_access changes. If conversion is successful,
12315 		 * we will apply proper mask to the result.
12316 		 */
12317 		is_narrower_load = size < ctx_field_size;
12318 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12319 		off = insn->off;
12320 		if (is_narrower_load) {
12321 			u8 size_code;
12322 
12323 			if (type == BPF_WRITE) {
12324 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12325 				return -EINVAL;
12326 			}
12327 
12328 			size_code = BPF_H;
12329 			if (ctx_field_size == 4)
12330 				size_code = BPF_W;
12331 			else if (ctx_field_size == 8)
12332 				size_code = BPF_DW;
12333 
12334 			insn->off = off & ~(size_default - 1);
12335 			insn->code = BPF_LDX | BPF_MEM | size_code;
12336 		}
12337 
12338 		target_size = 0;
12339 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12340 					 &target_size);
12341 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12342 		    (ctx_field_size && !target_size)) {
12343 			verbose(env, "bpf verifier is misconfigured\n");
12344 			return -EINVAL;
12345 		}
12346 
12347 		if (is_narrower_load && size < target_size) {
12348 			u8 shift = bpf_ctx_narrow_access_offset(
12349 				off, size, size_default) * 8;
12350 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12351 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12352 				return -EINVAL;
12353 			}
12354 			if (ctx_field_size <= 4) {
12355 				if (shift)
12356 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12357 									insn->dst_reg,
12358 									shift);
12359 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12360 								(1 << size * 8) - 1);
12361 			} else {
12362 				if (shift)
12363 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12364 									insn->dst_reg,
12365 									shift);
12366 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12367 								(1ULL << size * 8) - 1);
12368 			}
12369 		}
12370 
12371 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12372 		if (!new_prog)
12373 			return -ENOMEM;
12374 
12375 		delta += cnt - 1;
12376 
12377 		/* keep walking new program and skip insns we just inserted */
12378 		env->prog = new_prog;
12379 		insn      = new_prog->insnsi + i + delta;
12380 	}
12381 
12382 	return 0;
12383 }
12384 
12385 static int jit_subprogs(struct bpf_verifier_env *env)
12386 {
12387 	struct bpf_prog *prog = env->prog, **func, *tmp;
12388 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12389 	struct bpf_map *map_ptr;
12390 	struct bpf_insn *insn;
12391 	void *old_bpf_func;
12392 	int err, num_exentries;
12393 
12394 	if (env->subprog_cnt <= 1)
12395 		return 0;
12396 
12397 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12398 		if (bpf_pseudo_func(insn)) {
12399 			env->insn_aux_data[i].call_imm = insn->imm;
12400 			/* subprog is encoded in insn[1].imm */
12401 			continue;
12402 		}
12403 
12404 		if (!bpf_pseudo_call(insn))
12405 			continue;
12406 		/* Upon error here we cannot fall back to interpreter but
12407 		 * need a hard reject of the program. Thus -EFAULT is
12408 		 * propagated in any case.
12409 		 */
12410 		subprog = find_subprog(env, i + insn->imm + 1);
12411 		if (subprog < 0) {
12412 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12413 				  i + insn->imm + 1);
12414 			return -EFAULT;
12415 		}
12416 		/* temporarily remember subprog id inside insn instead of
12417 		 * aux_data, since next loop will split up all insns into funcs
12418 		 */
12419 		insn->off = subprog;
12420 		/* remember original imm in case JIT fails and fallback
12421 		 * to interpreter will be needed
12422 		 */
12423 		env->insn_aux_data[i].call_imm = insn->imm;
12424 		/* point imm to __bpf_call_base+1 from JITs point of view */
12425 		insn->imm = 1;
12426 	}
12427 
12428 	err = bpf_prog_alloc_jited_linfo(prog);
12429 	if (err)
12430 		goto out_undo_insn;
12431 
12432 	err = -ENOMEM;
12433 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12434 	if (!func)
12435 		goto out_undo_insn;
12436 
12437 	for (i = 0; i < env->subprog_cnt; i++) {
12438 		subprog_start = subprog_end;
12439 		subprog_end = env->subprog_info[i + 1].start;
12440 
12441 		len = subprog_end - subprog_start;
12442 		/* bpf_prog_run() doesn't call subprogs directly,
12443 		 * hence main prog stats include the runtime of subprogs.
12444 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12445 		 * func[i]->stats will never be accessed and stays NULL
12446 		 */
12447 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12448 		if (!func[i])
12449 			goto out_free;
12450 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12451 		       len * sizeof(struct bpf_insn));
12452 		func[i]->type = prog->type;
12453 		func[i]->len = len;
12454 		if (bpf_prog_calc_tag(func[i]))
12455 			goto out_free;
12456 		func[i]->is_func = 1;
12457 		func[i]->aux->func_idx = i;
12458 		/* Below members will be freed only at prog->aux */
12459 		func[i]->aux->btf = prog->aux->btf;
12460 		func[i]->aux->func_info = prog->aux->func_info;
12461 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12462 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12463 
12464 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12465 			struct bpf_jit_poke_descriptor *poke;
12466 
12467 			poke = &prog->aux->poke_tab[j];
12468 			if (poke->insn_idx < subprog_end &&
12469 			    poke->insn_idx >= subprog_start)
12470 				poke->aux = func[i]->aux;
12471 		}
12472 
12473 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
12474 		 * Long term would need debug info to populate names
12475 		 */
12476 		func[i]->aux->name[0] = 'F';
12477 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12478 		func[i]->jit_requested = 1;
12479 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12480 		func[i]->aux->linfo = prog->aux->linfo;
12481 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12482 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12483 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12484 		num_exentries = 0;
12485 		insn = func[i]->insnsi;
12486 		for (j = 0; j < func[i]->len; j++, insn++) {
12487 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12488 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12489 				num_exentries++;
12490 		}
12491 		func[i]->aux->num_exentries = num_exentries;
12492 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12493 		func[i] = bpf_int_jit_compile(func[i]);
12494 		if (!func[i]->jited) {
12495 			err = -ENOTSUPP;
12496 			goto out_free;
12497 		}
12498 		cond_resched();
12499 	}
12500 
12501 	/* at this point all bpf functions were successfully JITed
12502 	 * now populate all bpf_calls with correct addresses and
12503 	 * run last pass of JIT
12504 	 */
12505 	for (i = 0; i < env->subprog_cnt; i++) {
12506 		insn = func[i]->insnsi;
12507 		for (j = 0; j < func[i]->len; j++, insn++) {
12508 			if (bpf_pseudo_func(insn)) {
12509 				subprog = insn[1].imm;
12510 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12511 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12512 				continue;
12513 			}
12514 			if (!bpf_pseudo_call(insn))
12515 				continue;
12516 			subprog = insn->off;
12517 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
12518 		}
12519 
12520 		/* we use the aux data to keep a list of the start addresses
12521 		 * of the JITed images for each function in the program
12522 		 *
12523 		 * for some architectures, such as powerpc64, the imm field
12524 		 * might not be large enough to hold the offset of the start
12525 		 * address of the callee's JITed image from __bpf_call_base
12526 		 *
12527 		 * in such cases, we can lookup the start address of a callee
12528 		 * by using its subprog id, available from the off field of
12529 		 * the call instruction, as an index for this list
12530 		 */
12531 		func[i]->aux->func = func;
12532 		func[i]->aux->func_cnt = env->subprog_cnt;
12533 	}
12534 	for (i = 0; i < env->subprog_cnt; i++) {
12535 		old_bpf_func = func[i]->bpf_func;
12536 		tmp = bpf_int_jit_compile(func[i]);
12537 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12538 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12539 			err = -ENOTSUPP;
12540 			goto out_free;
12541 		}
12542 		cond_resched();
12543 	}
12544 
12545 	/* finally lock prog and jit images for all functions and
12546 	 * populate kallsysm
12547 	 */
12548 	for (i = 0; i < env->subprog_cnt; i++) {
12549 		bpf_prog_lock_ro(func[i]);
12550 		bpf_prog_kallsyms_add(func[i]);
12551 	}
12552 
12553 	/* Last step: make now unused interpreter insns from main
12554 	 * prog consistent for later dump requests, so they can
12555 	 * later look the same as if they were interpreted only.
12556 	 */
12557 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12558 		if (bpf_pseudo_func(insn)) {
12559 			insn[0].imm = env->insn_aux_data[i].call_imm;
12560 			insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12561 			continue;
12562 		}
12563 		if (!bpf_pseudo_call(insn))
12564 			continue;
12565 		insn->off = env->insn_aux_data[i].call_imm;
12566 		subprog = find_subprog(env, i + insn->off + 1);
12567 		insn->imm = subprog;
12568 	}
12569 
12570 	prog->jited = 1;
12571 	prog->bpf_func = func[0]->bpf_func;
12572 	prog->aux->func = func;
12573 	prog->aux->func_cnt = env->subprog_cnt;
12574 	bpf_prog_jit_attempt_done(prog);
12575 	return 0;
12576 out_free:
12577 	/* We failed JIT'ing, so at this point we need to unregister poke
12578 	 * descriptors from subprogs, so that kernel is not attempting to
12579 	 * patch it anymore as we're freeing the subprog JIT memory.
12580 	 */
12581 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12582 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12583 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12584 	}
12585 	/* At this point we're guaranteed that poke descriptors are not
12586 	 * live anymore. We can just unlink its descriptor table as it's
12587 	 * released with the main prog.
12588 	 */
12589 	for (i = 0; i < env->subprog_cnt; i++) {
12590 		if (!func[i])
12591 			continue;
12592 		func[i]->aux->poke_tab = NULL;
12593 		bpf_jit_free(func[i]);
12594 	}
12595 	kfree(func);
12596 out_undo_insn:
12597 	/* cleanup main prog to be interpreted */
12598 	prog->jit_requested = 0;
12599 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12600 		if (!bpf_pseudo_call(insn))
12601 			continue;
12602 		insn->off = 0;
12603 		insn->imm = env->insn_aux_data[i].call_imm;
12604 	}
12605 	bpf_prog_jit_attempt_done(prog);
12606 	return err;
12607 }
12608 
12609 static int fixup_call_args(struct bpf_verifier_env *env)
12610 {
12611 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12612 	struct bpf_prog *prog = env->prog;
12613 	struct bpf_insn *insn = prog->insnsi;
12614 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12615 	int i, depth;
12616 #endif
12617 	int err = 0;
12618 
12619 	if (env->prog->jit_requested &&
12620 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12621 		err = jit_subprogs(env);
12622 		if (err == 0)
12623 			return 0;
12624 		if (err == -EFAULT)
12625 			return err;
12626 	}
12627 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12628 	if (has_kfunc_call) {
12629 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12630 		return -EINVAL;
12631 	}
12632 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12633 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12634 		 * have to be rejected, since interpreter doesn't support them yet.
12635 		 */
12636 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12637 		return -EINVAL;
12638 	}
12639 	for (i = 0; i < prog->len; i++, insn++) {
12640 		if (bpf_pseudo_func(insn)) {
12641 			/* When JIT fails the progs with callback calls
12642 			 * have to be rejected, since interpreter doesn't support them yet.
12643 			 */
12644 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12645 			return -EINVAL;
12646 		}
12647 
12648 		if (!bpf_pseudo_call(insn))
12649 			continue;
12650 		depth = get_callee_stack_depth(env, insn, i);
12651 		if (depth < 0)
12652 			return depth;
12653 		bpf_patch_call_args(insn, depth);
12654 	}
12655 	err = 0;
12656 #endif
12657 	return err;
12658 }
12659 
12660 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12661 			    struct bpf_insn *insn)
12662 {
12663 	const struct bpf_kfunc_desc *desc;
12664 
12665 	/* insn->imm has the btf func_id. Replace it with
12666 	 * an address (relative to __bpf_base_call).
12667 	 */
12668 	desc = find_kfunc_desc(env->prog, insn->imm);
12669 	if (!desc) {
12670 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12671 			insn->imm);
12672 		return -EFAULT;
12673 	}
12674 
12675 	insn->imm = desc->imm;
12676 
12677 	return 0;
12678 }
12679 
12680 /* Do various post-verification rewrites in a single program pass.
12681  * These rewrites simplify JIT and interpreter implementations.
12682  */
12683 static int do_misc_fixups(struct bpf_verifier_env *env)
12684 {
12685 	struct bpf_prog *prog = env->prog;
12686 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12687 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12688 	struct bpf_insn *insn = prog->insnsi;
12689 	const struct bpf_func_proto *fn;
12690 	const int insn_cnt = prog->len;
12691 	const struct bpf_map_ops *ops;
12692 	struct bpf_insn_aux_data *aux;
12693 	struct bpf_insn insn_buf[16];
12694 	struct bpf_prog *new_prog;
12695 	struct bpf_map *map_ptr;
12696 	int i, ret, cnt, delta = 0;
12697 
12698 	for (i = 0; i < insn_cnt; i++, insn++) {
12699 		/* Make divide-by-zero exceptions impossible. */
12700 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12701 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12702 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12703 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12704 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12705 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12706 			struct bpf_insn *patchlet;
12707 			struct bpf_insn chk_and_div[] = {
12708 				/* [R,W]x div 0 -> 0 */
12709 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12710 					     BPF_JNE | BPF_K, insn->src_reg,
12711 					     0, 2, 0),
12712 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12713 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12714 				*insn,
12715 			};
12716 			struct bpf_insn chk_and_mod[] = {
12717 				/* [R,W]x mod 0 -> [R,W]x */
12718 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12719 					     BPF_JEQ | BPF_K, insn->src_reg,
12720 					     0, 1 + (is64 ? 0 : 1), 0),
12721 				*insn,
12722 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12723 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12724 			};
12725 
12726 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12727 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12728 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12729 
12730 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12731 			if (!new_prog)
12732 				return -ENOMEM;
12733 
12734 			delta    += cnt - 1;
12735 			env->prog = prog = new_prog;
12736 			insn      = new_prog->insnsi + i + delta;
12737 			continue;
12738 		}
12739 
12740 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12741 		if (BPF_CLASS(insn->code) == BPF_LD &&
12742 		    (BPF_MODE(insn->code) == BPF_ABS ||
12743 		     BPF_MODE(insn->code) == BPF_IND)) {
12744 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12745 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12746 				verbose(env, "bpf verifier is misconfigured\n");
12747 				return -EINVAL;
12748 			}
12749 
12750 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12751 			if (!new_prog)
12752 				return -ENOMEM;
12753 
12754 			delta    += cnt - 1;
12755 			env->prog = prog = new_prog;
12756 			insn      = new_prog->insnsi + i + delta;
12757 			continue;
12758 		}
12759 
12760 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12761 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12762 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12763 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12764 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12765 			struct bpf_insn *patch = &insn_buf[0];
12766 			bool issrc, isneg, isimm;
12767 			u32 off_reg;
12768 
12769 			aux = &env->insn_aux_data[i + delta];
12770 			if (!aux->alu_state ||
12771 			    aux->alu_state == BPF_ALU_NON_POINTER)
12772 				continue;
12773 
12774 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12775 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12776 				BPF_ALU_SANITIZE_SRC;
12777 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12778 
12779 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12780 			if (isimm) {
12781 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12782 			} else {
12783 				if (isneg)
12784 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12785 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12786 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12787 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12788 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12789 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12790 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12791 			}
12792 			if (!issrc)
12793 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12794 			insn->src_reg = BPF_REG_AX;
12795 			if (isneg)
12796 				insn->code = insn->code == code_add ?
12797 					     code_sub : code_add;
12798 			*patch++ = *insn;
12799 			if (issrc && isneg && !isimm)
12800 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12801 			cnt = patch - insn_buf;
12802 
12803 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12804 			if (!new_prog)
12805 				return -ENOMEM;
12806 
12807 			delta    += cnt - 1;
12808 			env->prog = prog = new_prog;
12809 			insn      = new_prog->insnsi + i + delta;
12810 			continue;
12811 		}
12812 
12813 		if (insn->code != (BPF_JMP | BPF_CALL))
12814 			continue;
12815 		if (insn->src_reg == BPF_PSEUDO_CALL)
12816 			continue;
12817 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12818 			ret = fixup_kfunc_call(env, insn);
12819 			if (ret)
12820 				return ret;
12821 			continue;
12822 		}
12823 
12824 		if (insn->imm == BPF_FUNC_get_route_realm)
12825 			prog->dst_needed = 1;
12826 		if (insn->imm == BPF_FUNC_get_prandom_u32)
12827 			bpf_user_rnd_init_once();
12828 		if (insn->imm == BPF_FUNC_override_return)
12829 			prog->kprobe_override = 1;
12830 		if (insn->imm == BPF_FUNC_tail_call) {
12831 			/* If we tail call into other programs, we
12832 			 * cannot make any assumptions since they can
12833 			 * be replaced dynamically during runtime in
12834 			 * the program array.
12835 			 */
12836 			prog->cb_access = 1;
12837 			if (!allow_tail_call_in_subprogs(env))
12838 				prog->aux->stack_depth = MAX_BPF_STACK;
12839 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12840 
12841 			/* mark bpf_tail_call as different opcode to avoid
12842 			 * conditional branch in the interpreter for every normal
12843 			 * call and to prevent accidental JITing by JIT compiler
12844 			 * that doesn't support bpf_tail_call yet
12845 			 */
12846 			insn->imm = 0;
12847 			insn->code = BPF_JMP | BPF_TAIL_CALL;
12848 
12849 			aux = &env->insn_aux_data[i + delta];
12850 			if (env->bpf_capable && !expect_blinding &&
12851 			    prog->jit_requested &&
12852 			    !bpf_map_key_poisoned(aux) &&
12853 			    !bpf_map_ptr_poisoned(aux) &&
12854 			    !bpf_map_ptr_unpriv(aux)) {
12855 				struct bpf_jit_poke_descriptor desc = {
12856 					.reason = BPF_POKE_REASON_TAIL_CALL,
12857 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12858 					.tail_call.key = bpf_map_key_immediate(aux),
12859 					.insn_idx = i + delta,
12860 				};
12861 
12862 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
12863 				if (ret < 0) {
12864 					verbose(env, "adding tail call poke descriptor failed\n");
12865 					return ret;
12866 				}
12867 
12868 				insn->imm = ret + 1;
12869 				continue;
12870 			}
12871 
12872 			if (!bpf_map_ptr_unpriv(aux))
12873 				continue;
12874 
12875 			/* instead of changing every JIT dealing with tail_call
12876 			 * emit two extra insns:
12877 			 * if (index >= max_entries) goto out;
12878 			 * index &= array->index_mask;
12879 			 * to avoid out-of-bounds cpu speculation
12880 			 */
12881 			if (bpf_map_ptr_poisoned(aux)) {
12882 				verbose(env, "tail_call abusing map_ptr\n");
12883 				return -EINVAL;
12884 			}
12885 
12886 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12887 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12888 						  map_ptr->max_entries, 2);
12889 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12890 						    container_of(map_ptr,
12891 								 struct bpf_array,
12892 								 map)->index_mask);
12893 			insn_buf[2] = *insn;
12894 			cnt = 3;
12895 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12896 			if (!new_prog)
12897 				return -ENOMEM;
12898 
12899 			delta    += cnt - 1;
12900 			env->prog = prog = new_prog;
12901 			insn      = new_prog->insnsi + i + delta;
12902 			continue;
12903 		}
12904 
12905 		if (insn->imm == BPF_FUNC_timer_set_callback) {
12906 			/* The verifier will process callback_fn as many times as necessary
12907 			 * with different maps and the register states prepared by
12908 			 * set_timer_callback_state will be accurate.
12909 			 *
12910 			 * The following use case is valid:
12911 			 *   map1 is shared by prog1, prog2, prog3.
12912 			 *   prog1 calls bpf_timer_init for some map1 elements
12913 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
12914 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
12915 			 *   prog3 calls bpf_timer_start for some map1 elements.
12916 			 *     Those that were not both bpf_timer_init-ed and
12917 			 *     bpf_timer_set_callback-ed will return -EINVAL.
12918 			 */
12919 			struct bpf_insn ld_addrs[2] = {
12920 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
12921 			};
12922 
12923 			insn_buf[0] = ld_addrs[0];
12924 			insn_buf[1] = ld_addrs[1];
12925 			insn_buf[2] = *insn;
12926 			cnt = 3;
12927 
12928 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12929 			if (!new_prog)
12930 				return -ENOMEM;
12931 
12932 			delta    += cnt - 1;
12933 			env->prog = prog = new_prog;
12934 			insn      = new_prog->insnsi + i + delta;
12935 			goto patch_call_imm;
12936 		}
12937 
12938 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12939 		 * and other inlining handlers are currently limited to 64 bit
12940 		 * only.
12941 		 */
12942 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
12943 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
12944 		     insn->imm == BPF_FUNC_map_update_elem ||
12945 		     insn->imm == BPF_FUNC_map_delete_elem ||
12946 		     insn->imm == BPF_FUNC_map_push_elem   ||
12947 		     insn->imm == BPF_FUNC_map_pop_elem    ||
12948 		     insn->imm == BPF_FUNC_map_peek_elem   ||
12949 		     insn->imm == BPF_FUNC_redirect_map)) {
12950 			aux = &env->insn_aux_data[i + delta];
12951 			if (bpf_map_ptr_poisoned(aux))
12952 				goto patch_call_imm;
12953 
12954 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12955 			ops = map_ptr->ops;
12956 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
12957 			    ops->map_gen_lookup) {
12958 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12959 				if (cnt == -EOPNOTSUPP)
12960 					goto patch_map_ops_generic;
12961 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12962 					verbose(env, "bpf verifier is misconfigured\n");
12963 					return -EINVAL;
12964 				}
12965 
12966 				new_prog = bpf_patch_insn_data(env, i + delta,
12967 							       insn_buf, cnt);
12968 				if (!new_prog)
12969 					return -ENOMEM;
12970 
12971 				delta    += cnt - 1;
12972 				env->prog = prog = new_prog;
12973 				insn      = new_prog->insnsi + i + delta;
12974 				continue;
12975 			}
12976 
12977 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12978 				     (void *(*)(struct bpf_map *map, void *key))NULL));
12979 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12980 				     (int (*)(struct bpf_map *map, void *key))NULL));
12981 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12982 				     (int (*)(struct bpf_map *map, void *key, void *value,
12983 					      u64 flags))NULL));
12984 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12985 				     (int (*)(struct bpf_map *map, void *value,
12986 					      u64 flags))NULL));
12987 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12988 				     (int (*)(struct bpf_map *map, void *value))NULL));
12989 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12990 				     (int (*)(struct bpf_map *map, void *value))NULL));
12991 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
12992 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12993 
12994 patch_map_ops_generic:
12995 			switch (insn->imm) {
12996 			case BPF_FUNC_map_lookup_elem:
12997 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
12998 				continue;
12999 			case BPF_FUNC_map_update_elem:
13000 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
13001 				continue;
13002 			case BPF_FUNC_map_delete_elem:
13003 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
13004 				continue;
13005 			case BPF_FUNC_map_push_elem:
13006 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
13007 				continue;
13008 			case BPF_FUNC_map_pop_elem:
13009 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
13010 				continue;
13011 			case BPF_FUNC_map_peek_elem:
13012 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
13013 				continue;
13014 			case BPF_FUNC_redirect_map:
13015 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
13016 				continue;
13017 			}
13018 
13019 			goto patch_call_imm;
13020 		}
13021 
13022 		/* Implement bpf_jiffies64 inline. */
13023 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13024 		    insn->imm == BPF_FUNC_jiffies64) {
13025 			struct bpf_insn ld_jiffies_addr[2] = {
13026 				BPF_LD_IMM64(BPF_REG_0,
13027 					     (unsigned long)&jiffies),
13028 			};
13029 
13030 			insn_buf[0] = ld_jiffies_addr[0];
13031 			insn_buf[1] = ld_jiffies_addr[1];
13032 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13033 						  BPF_REG_0, 0);
13034 			cnt = 3;
13035 
13036 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13037 						       cnt);
13038 			if (!new_prog)
13039 				return -ENOMEM;
13040 
13041 			delta    += cnt - 1;
13042 			env->prog = prog = new_prog;
13043 			insn      = new_prog->insnsi + i + delta;
13044 			continue;
13045 		}
13046 
13047 		/* Implement bpf_get_func_ip inline. */
13048 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13049 		    insn->imm == BPF_FUNC_get_func_ip) {
13050 			/* Load IP address from ctx - 8 */
13051 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13052 
13053 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13054 			if (!new_prog)
13055 				return -ENOMEM;
13056 
13057 			env->prog = prog = new_prog;
13058 			insn      = new_prog->insnsi + i + delta;
13059 			continue;
13060 		}
13061 
13062 patch_call_imm:
13063 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13064 		/* all functions that have prototype and verifier allowed
13065 		 * programs to call them, must be real in-kernel functions
13066 		 */
13067 		if (!fn->func) {
13068 			verbose(env,
13069 				"kernel subsystem misconfigured func %s#%d\n",
13070 				func_id_name(insn->imm), insn->imm);
13071 			return -EFAULT;
13072 		}
13073 		insn->imm = fn->func - __bpf_call_base;
13074 	}
13075 
13076 	/* Since poke tab is now finalized, publish aux to tracker. */
13077 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13078 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13079 		if (!map_ptr->ops->map_poke_track ||
13080 		    !map_ptr->ops->map_poke_untrack ||
13081 		    !map_ptr->ops->map_poke_run) {
13082 			verbose(env, "bpf verifier is misconfigured\n");
13083 			return -EINVAL;
13084 		}
13085 
13086 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13087 		if (ret < 0) {
13088 			verbose(env, "tracking tail call prog failed\n");
13089 			return ret;
13090 		}
13091 	}
13092 
13093 	sort_kfunc_descs_by_imm(env->prog);
13094 
13095 	return 0;
13096 }
13097 
13098 static void free_states(struct bpf_verifier_env *env)
13099 {
13100 	struct bpf_verifier_state_list *sl, *sln;
13101 	int i;
13102 
13103 	sl = env->free_list;
13104 	while (sl) {
13105 		sln = sl->next;
13106 		free_verifier_state(&sl->state, false);
13107 		kfree(sl);
13108 		sl = sln;
13109 	}
13110 	env->free_list = NULL;
13111 
13112 	if (!env->explored_states)
13113 		return;
13114 
13115 	for (i = 0; i < state_htab_size(env); i++) {
13116 		sl = env->explored_states[i];
13117 
13118 		while (sl) {
13119 			sln = sl->next;
13120 			free_verifier_state(&sl->state, false);
13121 			kfree(sl);
13122 			sl = sln;
13123 		}
13124 		env->explored_states[i] = NULL;
13125 	}
13126 }
13127 
13128 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13129 {
13130 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13131 	struct bpf_verifier_state *state;
13132 	struct bpf_reg_state *regs;
13133 	int ret, i;
13134 
13135 	env->prev_linfo = NULL;
13136 	env->pass_cnt++;
13137 
13138 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13139 	if (!state)
13140 		return -ENOMEM;
13141 	state->curframe = 0;
13142 	state->speculative = false;
13143 	state->branches = 1;
13144 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13145 	if (!state->frame[0]) {
13146 		kfree(state);
13147 		return -ENOMEM;
13148 	}
13149 	env->cur_state = state;
13150 	init_func_state(env, state->frame[0],
13151 			BPF_MAIN_FUNC /* callsite */,
13152 			0 /* frameno */,
13153 			subprog);
13154 
13155 	regs = state->frame[state->curframe]->regs;
13156 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13157 		ret = btf_prepare_func_args(env, subprog, regs);
13158 		if (ret)
13159 			goto out;
13160 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13161 			if (regs[i].type == PTR_TO_CTX)
13162 				mark_reg_known_zero(env, regs, i);
13163 			else if (regs[i].type == SCALAR_VALUE)
13164 				mark_reg_unknown(env, regs, i);
13165 			else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13166 				const u32 mem_size = regs[i].mem_size;
13167 
13168 				mark_reg_known_zero(env, regs, i);
13169 				regs[i].mem_size = mem_size;
13170 				regs[i].id = ++env->id_gen;
13171 			}
13172 		}
13173 	} else {
13174 		/* 1st arg to a function */
13175 		regs[BPF_REG_1].type = PTR_TO_CTX;
13176 		mark_reg_known_zero(env, regs, BPF_REG_1);
13177 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13178 		if (ret == -EFAULT)
13179 			/* unlikely verifier bug. abort.
13180 			 * ret == 0 and ret < 0 are sadly acceptable for
13181 			 * main() function due to backward compatibility.
13182 			 * Like socket filter program may be written as:
13183 			 * int bpf_prog(struct pt_regs *ctx)
13184 			 * and never dereference that ctx in the program.
13185 			 * 'struct pt_regs' is a type mismatch for socket
13186 			 * filter that should be using 'struct __sk_buff'.
13187 			 */
13188 			goto out;
13189 	}
13190 
13191 	ret = do_check(env);
13192 out:
13193 	/* check for NULL is necessary, since cur_state can be freed inside
13194 	 * do_check() under memory pressure.
13195 	 */
13196 	if (env->cur_state) {
13197 		free_verifier_state(env->cur_state, true);
13198 		env->cur_state = NULL;
13199 	}
13200 	while (!pop_stack(env, NULL, NULL, false));
13201 	if (!ret && pop_log)
13202 		bpf_vlog_reset(&env->log, 0);
13203 	free_states(env);
13204 	return ret;
13205 }
13206 
13207 /* Verify all global functions in a BPF program one by one based on their BTF.
13208  * All global functions must pass verification. Otherwise the whole program is rejected.
13209  * Consider:
13210  * int bar(int);
13211  * int foo(int f)
13212  * {
13213  *    return bar(f);
13214  * }
13215  * int bar(int b)
13216  * {
13217  *    ...
13218  * }
13219  * foo() will be verified first for R1=any_scalar_value. During verification it
13220  * will be assumed that bar() already verified successfully and call to bar()
13221  * from foo() will be checked for type match only. Later bar() will be verified
13222  * independently to check that it's safe for R1=any_scalar_value.
13223  */
13224 static int do_check_subprogs(struct bpf_verifier_env *env)
13225 {
13226 	struct bpf_prog_aux *aux = env->prog->aux;
13227 	int i, ret;
13228 
13229 	if (!aux->func_info)
13230 		return 0;
13231 
13232 	for (i = 1; i < env->subprog_cnt; i++) {
13233 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13234 			continue;
13235 		env->insn_idx = env->subprog_info[i].start;
13236 		WARN_ON_ONCE(env->insn_idx == 0);
13237 		ret = do_check_common(env, i);
13238 		if (ret) {
13239 			return ret;
13240 		} else if (env->log.level & BPF_LOG_LEVEL) {
13241 			verbose(env,
13242 				"Func#%d is safe for any args that match its prototype\n",
13243 				i);
13244 		}
13245 	}
13246 	return 0;
13247 }
13248 
13249 static int do_check_main(struct bpf_verifier_env *env)
13250 {
13251 	int ret;
13252 
13253 	env->insn_idx = 0;
13254 	ret = do_check_common(env, 0);
13255 	if (!ret)
13256 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13257 	return ret;
13258 }
13259 
13260 
13261 static void print_verification_stats(struct bpf_verifier_env *env)
13262 {
13263 	int i;
13264 
13265 	if (env->log.level & BPF_LOG_STATS) {
13266 		verbose(env, "verification time %lld usec\n",
13267 			div_u64(env->verification_time, 1000));
13268 		verbose(env, "stack depth ");
13269 		for (i = 0; i < env->subprog_cnt; i++) {
13270 			u32 depth = env->subprog_info[i].stack_depth;
13271 
13272 			verbose(env, "%d", depth);
13273 			if (i + 1 < env->subprog_cnt)
13274 				verbose(env, "+");
13275 		}
13276 		verbose(env, "\n");
13277 	}
13278 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13279 		"total_states %d peak_states %d mark_read %d\n",
13280 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13281 		env->max_states_per_insn, env->total_states,
13282 		env->peak_states, env->longest_mark_read_walk);
13283 }
13284 
13285 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13286 {
13287 	const struct btf_type *t, *func_proto;
13288 	const struct bpf_struct_ops *st_ops;
13289 	const struct btf_member *member;
13290 	struct bpf_prog *prog = env->prog;
13291 	u32 btf_id, member_idx;
13292 	const char *mname;
13293 
13294 	if (!prog->gpl_compatible) {
13295 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13296 		return -EINVAL;
13297 	}
13298 
13299 	btf_id = prog->aux->attach_btf_id;
13300 	st_ops = bpf_struct_ops_find(btf_id);
13301 	if (!st_ops) {
13302 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13303 			btf_id);
13304 		return -ENOTSUPP;
13305 	}
13306 
13307 	t = st_ops->type;
13308 	member_idx = prog->expected_attach_type;
13309 	if (member_idx >= btf_type_vlen(t)) {
13310 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13311 			member_idx, st_ops->name);
13312 		return -EINVAL;
13313 	}
13314 
13315 	member = &btf_type_member(t)[member_idx];
13316 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13317 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13318 					       NULL);
13319 	if (!func_proto) {
13320 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13321 			mname, member_idx, st_ops->name);
13322 		return -EINVAL;
13323 	}
13324 
13325 	if (st_ops->check_member) {
13326 		int err = st_ops->check_member(t, member);
13327 
13328 		if (err) {
13329 			verbose(env, "attach to unsupported member %s of struct %s\n",
13330 				mname, st_ops->name);
13331 			return err;
13332 		}
13333 	}
13334 
13335 	prog->aux->attach_func_proto = func_proto;
13336 	prog->aux->attach_func_name = mname;
13337 	env->ops = st_ops->verifier_ops;
13338 
13339 	return 0;
13340 }
13341 #define SECURITY_PREFIX "security_"
13342 
13343 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13344 {
13345 	if (within_error_injection_list(addr) ||
13346 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13347 		return 0;
13348 
13349 	return -EINVAL;
13350 }
13351 
13352 /* list of non-sleepable functions that are otherwise on
13353  * ALLOW_ERROR_INJECTION list
13354  */
13355 BTF_SET_START(btf_non_sleepable_error_inject)
13356 /* Three functions below can be called from sleepable and non-sleepable context.
13357  * Assume non-sleepable from bpf safety point of view.
13358  */
13359 BTF_ID(func, __add_to_page_cache_locked)
13360 BTF_ID(func, should_fail_alloc_page)
13361 BTF_ID(func, should_failslab)
13362 BTF_SET_END(btf_non_sleepable_error_inject)
13363 
13364 static int check_non_sleepable_error_inject(u32 btf_id)
13365 {
13366 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13367 }
13368 
13369 int bpf_check_attach_target(struct bpf_verifier_log *log,
13370 			    const struct bpf_prog *prog,
13371 			    const struct bpf_prog *tgt_prog,
13372 			    u32 btf_id,
13373 			    struct bpf_attach_target_info *tgt_info)
13374 {
13375 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13376 	const char prefix[] = "btf_trace_";
13377 	int ret = 0, subprog = -1, i;
13378 	const struct btf_type *t;
13379 	bool conservative = true;
13380 	const char *tname;
13381 	struct btf *btf;
13382 	long addr = 0;
13383 
13384 	if (!btf_id) {
13385 		bpf_log(log, "Tracing programs must provide btf_id\n");
13386 		return -EINVAL;
13387 	}
13388 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13389 	if (!btf) {
13390 		bpf_log(log,
13391 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13392 		return -EINVAL;
13393 	}
13394 	t = btf_type_by_id(btf, btf_id);
13395 	if (!t) {
13396 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13397 		return -EINVAL;
13398 	}
13399 	tname = btf_name_by_offset(btf, t->name_off);
13400 	if (!tname) {
13401 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13402 		return -EINVAL;
13403 	}
13404 	if (tgt_prog) {
13405 		struct bpf_prog_aux *aux = tgt_prog->aux;
13406 
13407 		for (i = 0; i < aux->func_info_cnt; i++)
13408 			if (aux->func_info[i].type_id == btf_id) {
13409 				subprog = i;
13410 				break;
13411 			}
13412 		if (subprog == -1) {
13413 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13414 			return -EINVAL;
13415 		}
13416 		conservative = aux->func_info_aux[subprog].unreliable;
13417 		if (prog_extension) {
13418 			if (conservative) {
13419 				bpf_log(log,
13420 					"Cannot replace static functions\n");
13421 				return -EINVAL;
13422 			}
13423 			if (!prog->jit_requested) {
13424 				bpf_log(log,
13425 					"Extension programs should be JITed\n");
13426 				return -EINVAL;
13427 			}
13428 		}
13429 		if (!tgt_prog->jited) {
13430 			bpf_log(log, "Can attach to only JITed progs\n");
13431 			return -EINVAL;
13432 		}
13433 		if (tgt_prog->type == prog->type) {
13434 			/* Cannot fentry/fexit another fentry/fexit program.
13435 			 * Cannot attach program extension to another extension.
13436 			 * It's ok to attach fentry/fexit to extension program.
13437 			 */
13438 			bpf_log(log, "Cannot recursively attach\n");
13439 			return -EINVAL;
13440 		}
13441 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13442 		    prog_extension &&
13443 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13444 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13445 			/* Program extensions can extend all program types
13446 			 * except fentry/fexit. The reason is the following.
13447 			 * The fentry/fexit programs are used for performance
13448 			 * analysis, stats and can be attached to any program
13449 			 * type except themselves. When extension program is
13450 			 * replacing XDP function it is necessary to allow
13451 			 * performance analysis of all functions. Both original
13452 			 * XDP program and its program extension. Hence
13453 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13454 			 * allowed. If extending of fentry/fexit was allowed it
13455 			 * would be possible to create long call chain
13456 			 * fentry->extension->fentry->extension beyond
13457 			 * reasonable stack size. Hence extending fentry is not
13458 			 * allowed.
13459 			 */
13460 			bpf_log(log, "Cannot extend fentry/fexit\n");
13461 			return -EINVAL;
13462 		}
13463 	} else {
13464 		if (prog_extension) {
13465 			bpf_log(log, "Cannot replace kernel functions\n");
13466 			return -EINVAL;
13467 		}
13468 	}
13469 
13470 	switch (prog->expected_attach_type) {
13471 	case BPF_TRACE_RAW_TP:
13472 		if (tgt_prog) {
13473 			bpf_log(log,
13474 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13475 			return -EINVAL;
13476 		}
13477 		if (!btf_type_is_typedef(t)) {
13478 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13479 				btf_id);
13480 			return -EINVAL;
13481 		}
13482 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13483 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13484 				btf_id, tname);
13485 			return -EINVAL;
13486 		}
13487 		tname += sizeof(prefix) - 1;
13488 		t = btf_type_by_id(btf, t->type);
13489 		if (!btf_type_is_ptr(t))
13490 			/* should never happen in valid vmlinux build */
13491 			return -EINVAL;
13492 		t = btf_type_by_id(btf, t->type);
13493 		if (!btf_type_is_func_proto(t))
13494 			/* should never happen in valid vmlinux build */
13495 			return -EINVAL;
13496 
13497 		break;
13498 	case BPF_TRACE_ITER:
13499 		if (!btf_type_is_func(t)) {
13500 			bpf_log(log, "attach_btf_id %u is not a function\n",
13501 				btf_id);
13502 			return -EINVAL;
13503 		}
13504 		t = btf_type_by_id(btf, t->type);
13505 		if (!btf_type_is_func_proto(t))
13506 			return -EINVAL;
13507 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13508 		if (ret)
13509 			return ret;
13510 		break;
13511 	default:
13512 		if (!prog_extension)
13513 			return -EINVAL;
13514 		fallthrough;
13515 	case BPF_MODIFY_RETURN:
13516 	case BPF_LSM_MAC:
13517 	case BPF_TRACE_FENTRY:
13518 	case BPF_TRACE_FEXIT:
13519 		if (!btf_type_is_func(t)) {
13520 			bpf_log(log, "attach_btf_id %u is not a function\n",
13521 				btf_id);
13522 			return -EINVAL;
13523 		}
13524 		if (prog_extension &&
13525 		    btf_check_type_match(log, prog, btf, t))
13526 			return -EINVAL;
13527 		t = btf_type_by_id(btf, t->type);
13528 		if (!btf_type_is_func_proto(t))
13529 			return -EINVAL;
13530 
13531 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13532 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13533 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13534 			return -EINVAL;
13535 
13536 		if (tgt_prog && conservative)
13537 			t = NULL;
13538 
13539 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13540 		if (ret < 0)
13541 			return ret;
13542 
13543 		if (tgt_prog) {
13544 			if (subprog == 0)
13545 				addr = (long) tgt_prog->bpf_func;
13546 			else
13547 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13548 		} else {
13549 			addr = kallsyms_lookup_name(tname);
13550 			if (!addr) {
13551 				bpf_log(log,
13552 					"The address of function %s cannot be found\n",
13553 					tname);
13554 				return -ENOENT;
13555 			}
13556 		}
13557 
13558 		if (prog->aux->sleepable) {
13559 			ret = -EINVAL;
13560 			switch (prog->type) {
13561 			case BPF_PROG_TYPE_TRACING:
13562 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13563 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13564 				 */
13565 				if (!check_non_sleepable_error_inject(btf_id) &&
13566 				    within_error_injection_list(addr))
13567 					ret = 0;
13568 				break;
13569 			case BPF_PROG_TYPE_LSM:
13570 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13571 				 * Only some of them are sleepable.
13572 				 */
13573 				if (bpf_lsm_is_sleepable_hook(btf_id))
13574 					ret = 0;
13575 				break;
13576 			default:
13577 				break;
13578 			}
13579 			if (ret) {
13580 				bpf_log(log, "%s is not sleepable\n", tname);
13581 				return ret;
13582 			}
13583 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13584 			if (tgt_prog) {
13585 				bpf_log(log, "can't modify return codes of BPF programs\n");
13586 				return -EINVAL;
13587 			}
13588 			ret = check_attach_modify_return(addr, tname);
13589 			if (ret) {
13590 				bpf_log(log, "%s() is not modifiable\n", tname);
13591 				return ret;
13592 			}
13593 		}
13594 
13595 		break;
13596 	}
13597 	tgt_info->tgt_addr = addr;
13598 	tgt_info->tgt_name = tname;
13599 	tgt_info->tgt_type = t;
13600 	return 0;
13601 }
13602 
13603 BTF_SET_START(btf_id_deny)
13604 BTF_ID_UNUSED
13605 #ifdef CONFIG_SMP
13606 BTF_ID(func, migrate_disable)
13607 BTF_ID(func, migrate_enable)
13608 #endif
13609 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13610 BTF_ID(func, rcu_read_unlock_strict)
13611 #endif
13612 BTF_SET_END(btf_id_deny)
13613 
13614 static int check_attach_btf_id(struct bpf_verifier_env *env)
13615 {
13616 	struct bpf_prog *prog = env->prog;
13617 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13618 	struct bpf_attach_target_info tgt_info = {};
13619 	u32 btf_id = prog->aux->attach_btf_id;
13620 	struct bpf_trampoline *tr;
13621 	int ret;
13622 	u64 key;
13623 
13624 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13625 		if (prog->aux->sleepable)
13626 			/* attach_btf_id checked to be zero already */
13627 			return 0;
13628 		verbose(env, "Syscall programs can only be sleepable\n");
13629 		return -EINVAL;
13630 	}
13631 
13632 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13633 	    prog->type != BPF_PROG_TYPE_LSM) {
13634 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13635 		return -EINVAL;
13636 	}
13637 
13638 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13639 		return check_struct_ops_btf_id(env);
13640 
13641 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13642 	    prog->type != BPF_PROG_TYPE_LSM &&
13643 	    prog->type != BPF_PROG_TYPE_EXT)
13644 		return 0;
13645 
13646 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13647 	if (ret)
13648 		return ret;
13649 
13650 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13651 		/* to make freplace equivalent to their targets, they need to
13652 		 * inherit env->ops and expected_attach_type for the rest of the
13653 		 * verification
13654 		 */
13655 		env->ops = bpf_verifier_ops[tgt_prog->type];
13656 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13657 	}
13658 
13659 	/* store info about the attachment target that will be used later */
13660 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13661 	prog->aux->attach_func_name = tgt_info.tgt_name;
13662 
13663 	if (tgt_prog) {
13664 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13665 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13666 	}
13667 
13668 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13669 		prog->aux->attach_btf_trace = true;
13670 		return 0;
13671 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13672 		if (!bpf_iter_prog_supported(prog))
13673 			return -EINVAL;
13674 		return 0;
13675 	}
13676 
13677 	if (prog->type == BPF_PROG_TYPE_LSM) {
13678 		ret = bpf_lsm_verify_prog(&env->log, prog);
13679 		if (ret < 0)
13680 			return ret;
13681 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13682 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13683 		return -EINVAL;
13684 	}
13685 
13686 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13687 	tr = bpf_trampoline_get(key, &tgt_info);
13688 	if (!tr)
13689 		return -ENOMEM;
13690 
13691 	prog->aux->dst_trampoline = tr;
13692 	return 0;
13693 }
13694 
13695 struct btf *bpf_get_btf_vmlinux(void)
13696 {
13697 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13698 		mutex_lock(&bpf_verifier_lock);
13699 		if (!btf_vmlinux)
13700 			btf_vmlinux = btf_parse_vmlinux();
13701 		mutex_unlock(&bpf_verifier_lock);
13702 	}
13703 	return btf_vmlinux;
13704 }
13705 
13706 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13707 {
13708 	u64 start_time = ktime_get_ns();
13709 	struct bpf_verifier_env *env;
13710 	struct bpf_verifier_log *log;
13711 	int i, len, ret = -EINVAL;
13712 	bool is_priv;
13713 
13714 	/* no program is valid */
13715 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13716 		return -EINVAL;
13717 
13718 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13719 	 * allocate/free it every time bpf_check() is called
13720 	 */
13721 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13722 	if (!env)
13723 		return -ENOMEM;
13724 	log = &env->log;
13725 
13726 	len = (*prog)->len;
13727 	env->insn_aux_data =
13728 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13729 	ret = -ENOMEM;
13730 	if (!env->insn_aux_data)
13731 		goto err_free_env;
13732 	for (i = 0; i < len; i++)
13733 		env->insn_aux_data[i].orig_idx = i;
13734 	env->prog = *prog;
13735 	env->ops = bpf_verifier_ops[env->prog->type];
13736 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13737 	is_priv = bpf_capable();
13738 
13739 	bpf_get_btf_vmlinux();
13740 
13741 	/* grab the mutex to protect few globals used by verifier */
13742 	if (!is_priv)
13743 		mutex_lock(&bpf_verifier_lock);
13744 
13745 	if (attr->log_level || attr->log_buf || attr->log_size) {
13746 		/* user requested verbose verifier output
13747 		 * and supplied buffer to store the verification trace
13748 		 */
13749 		log->level = attr->log_level;
13750 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13751 		log->len_total = attr->log_size;
13752 
13753 		ret = -EINVAL;
13754 		/* log attributes have to be sane */
13755 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
13756 		    !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
13757 			goto err_unlock;
13758 	}
13759 
13760 	if (IS_ERR(btf_vmlinux)) {
13761 		/* Either gcc or pahole or kernel are broken. */
13762 		verbose(env, "in-kernel BTF is malformed\n");
13763 		ret = PTR_ERR(btf_vmlinux);
13764 		goto skip_full_check;
13765 	}
13766 
13767 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13768 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13769 		env->strict_alignment = true;
13770 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13771 		env->strict_alignment = false;
13772 
13773 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13774 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13775 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13776 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13777 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13778 	env->bpf_capable = bpf_capable();
13779 
13780 	if (is_priv)
13781 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13782 
13783 	env->explored_states = kvcalloc(state_htab_size(env),
13784 				       sizeof(struct bpf_verifier_state_list *),
13785 				       GFP_USER);
13786 	ret = -ENOMEM;
13787 	if (!env->explored_states)
13788 		goto skip_full_check;
13789 
13790 	ret = add_subprog_and_kfunc(env);
13791 	if (ret < 0)
13792 		goto skip_full_check;
13793 
13794 	ret = check_subprogs(env);
13795 	if (ret < 0)
13796 		goto skip_full_check;
13797 
13798 	ret = check_btf_info(env, attr, uattr);
13799 	if (ret < 0)
13800 		goto skip_full_check;
13801 
13802 	ret = check_attach_btf_id(env);
13803 	if (ret)
13804 		goto skip_full_check;
13805 
13806 	ret = resolve_pseudo_ldimm64(env);
13807 	if (ret < 0)
13808 		goto skip_full_check;
13809 
13810 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
13811 		ret = bpf_prog_offload_verifier_prep(env->prog);
13812 		if (ret)
13813 			goto skip_full_check;
13814 	}
13815 
13816 	ret = check_cfg(env);
13817 	if (ret < 0)
13818 		goto skip_full_check;
13819 
13820 	ret = do_check_subprogs(env);
13821 	ret = ret ?: do_check_main(env);
13822 
13823 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13824 		ret = bpf_prog_offload_finalize(env);
13825 
13826 skip_full_check:
13827 	kvfree(env->explored_states);
13828 
13829 	if (ret == 0)
13830 		ret = check_max_stack_depth(env);
13831 
13832 	/* instruction rewrites happen after this point */
13833 	if (is_priv) {
13834 		if (ret == 0)
13835 			opt_hard_wire_dead_code_branches(env);
13836 		if (ret == 0)
13837 			ret = opt_remove_dead_code(env);
13838 		if (ret == 0)
13839 			ret = opt_remove_nops(env);
13840 	} else {
13841 		if (ret == 0)
13842 			sanitize_dead_code(env);
13843 	}
13844 
13845 	if (ret == 0)
13846 		/* program is valid, convert *(u32*)(ctx + off) accesses */
13847 		ret = convert_ctx_accesses(env);
13848 
13849 	if (ret == 0)
13850 		ret = do_misc_fixups(env);
13851 
13852 	/* do 32-bit optimization after insn patching has done so those patched
13853 	 * insns could be handled correctly.
13854 	 */
13855 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13856 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13857 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13858 								     : false;
13859 	}
13860 
13861 	if (ret == 0)
13862 		ret = fixup_call_args(env);
13863 
13864 	env->verification_time = ktime_get_ns() - start_time;
13865 	print_verification_stats(env);
13866 
13867 	if (log->level && bpf_verifier_log_full(log))
13868 		ret = -ENOSPC;
13869 	if (log->level && !log->ubuf) {
13870 		ret = -EFAULT;
13871 		goto err_release_maps;
13872 	}
13873 
13874 	if (ret)
13875 		goto err_release_maps;
13876 
13877 	if (env->used_map_cnt) {
13878 		/* if program passed verifier, update used_maps in bpf_prog_info */
13879 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13880 							  sizeof(env->used_maps[0]),
13881 							  GFP_KERNEL);
13882 
13883 		if (!env->prog->aux->used_maps) {
13884 			ret = -ENOMEM;
13885 			goto err_release_maps;
13886 		}
13887 
13888 		memcpy(env->prog->aux->used_maps, env->used_maps,
13889 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
13890 		env->prog->aux->used_map_cnt = env->used_map_cnt;
13891 	}
13892 	if (env->used_btf_cnt) {
13893 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
13894 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13895 							  sizeof(env->used_btfs[0]),
13896 							  GFP_KERNEL);
13897 		if (!env->prog->aux->used_btfs) {
13898 			ret = -ENOMEM;
13899 			goto err_release_maps;
13900 		}
13901 
13902 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
13903 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13904 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13905 	}
13906 	if (env->used_map_cnt || env->used_btf_cnt) {
13907 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
13908 		 * bpf_ld_imm64 instructions
13909 		 */
13910 		convert_pseudo_ld_imm64(env);
13911 	}
13912 
13913 	adjust_btf_func(env);
13914 
13915 err_release_maps:
13916 	if (!env->prog->aux->used_maps)
13917 		/* if we didn't copy map pointers into bpf_prog_info, release
13918 		 * them now. Otherwise free_used_maps() will release them.
13919 		 */
13920 		release_maps(env);
13921 	if (!env->prog->aux->used_btfs)
13922 		release_btfs(env);
13923 
13924 	/* extension progs temporarily inherit the attach_type of their targets
13925 	   for verification purposes, so set it back to zero before returning
13926 	 */
13927 	if (env->prog->type == BPF_PROG_TYPE_EXT)
13928 		env->prog->expected_attach_type = 0;
13929 
13930 	*prog = env->prog;
13931 err_unlock:
13932 	if (!is_priv)
13933 		mutex_unlock(&bpf_verifier_lock);
13934 	vfree(env->insn_aux_data);
13935 err_free_env:
13936 	kfree(env);
13937 	return ret;
13938 }
13939