xref: /linux/kernel/bpf/verifier.c (revision dfd5e53dd72113f37663f59a6337fe9a0dfbf0f6)
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/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198 
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203 
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 			      const struct bpf_map *map, bool unpriv)
206 {
207 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 	unpriv |= bpf_map_ptr_unpriv(aux);
209 	aux->map_ptr_state = (unsigned long)map |
210 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212 
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217 
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222 
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227 
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230 	bool poisoned = bpf_map_key_poisoned(aux);
231 
232 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235 
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238 	return insn->code == (BPF_JMP | BPF_CALL) &&
239 	       insn->src_reg == BPF_PSEUDO_CALL;
240 }
241 
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244 	return insn->code == (BPF_JMP | BPF_CALL) &&
245 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247 
248 struct bpf_call_arg_meta {
249 	struct bpf_map *map_ptr;
250 	bool raw_mode;
251 	bool pkt_access;
252 	u8 release_regno;
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 	struct btf_field *kptr_field;
266 	u8 uninit_dynptr_regno;
267 };
268 
269 struct btf *btf_vmlinux;
270 
271 static DEFINE_MUTEX(bpf_verifier_lock);
272 
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276 	const struct bpf_line_info *linfo;
277 	const struct bpf_prog *prog;
278 	u32 i, nr_linfo;
279 
280 	prog = env->prog;
281 	nr_linfo = prog->aux->nr_linfo;
282 
283 	if (!nr_linfo || insn_off >= prog->len)
284 		return NULL;
285 
286 	linfo = prog->aux->linfo;
287 	for (i = 1; i < nr_linfo; i++)
288 		if (insn_off < linfo[i].insn_off)
289 			break;
290 
291 	return &linfo[i - 1];
292 }
293 
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 		       va_list args)
296 {
297 	unsigned int n;
298 
299 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300 
301 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 		  "verifier log line truncated - local buffer too short\n");
303 
304 	if (log->level == BPF_LOG_KERNEL) {
305 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306 
307 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308 		return;
309 	}
310 
311 	n = min(log->len_total - log->len_used - 1, n);
312 	log->kbuf[n] = '\0';
313 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 		log->len_used += n;
315 	else
316 		log->ubuf = NULL;
317 }
318 
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321 	char zero = 0;
322 
323 	if (!bpf_verifier_log_needed(log))
324 		return;
325 
326 	log->len_used = new_pos;
327 	if (put_user(zero, log->ubuf + new_pos))
328 		log->ubuf = NULL;
329 }
330 
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 					   const char *fmt, ...)
337 {
338 	va_list args;
339 
340 	if (!bpf_verifier_log_needed(&env->log))
341 		return;
342 
343 	va_start(args, fmt);
344 	bpf_verifier_vlog(&env->log, fmt, args);
345 	va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348 
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351 	struct bpf_verifier_env *env = private_data;
352 	va_list args;
353 
354 	if (!bpf_verifier_log_needed(&env->log))
355 		return;
356 
357 	va_start(args, fmt);
358 	bpf_verifier_vlog(&env->log, fmt, args);
359 	va_end(args);
360 }
361 
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 			    const char *fmt, ...)
364 {
365 	va_list args;
366 
367 	if (!bpf_verifier_log_needed(log))
368 		return;
369 
370 	va_start(args, fmt);
371 	bpf_verifier_vlog(log, fmt, args);
372 	va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375 
376 static const char *ltrim(const char *s)
377 {
378 	while (isspace(*s))
379 		s++;
380 
381 	return s;
382 }
383 
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 					 u32 insn_off,
386 					 const char *prefix_fmt, ...)
387 {
388 	const struct bpf_line_info *linfo;
389 
390 	if (!bpf_verifier_log_needed(&env->log))
391 		return;
392 
393 	linfo = find_linfo(env, insn_off);
394 	if (!linfo || linfo == env->prev_linfo)
395 		return;
396 
397 	if (prefix_fmt) {
398 		va_list args;
399 
400 		va_start(args, prefix_fmt);
401 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 		va_end(args);
403 	}
404 
405 	verbose(env, "%s\n",
406 		ltrim(btf_name_by_offset(env->prog->aux->btf,
407 					 linfo->line_off)));
408 
409 	env->prev_linfo = linfo;
410 }
411 
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 				   struct bpf_reg_state *reg,
414 				   struct tnum *range, const char *ctx,
415 				   const char *reg_name)
416 {
417 	char tn_buf[48];
418 
419 	verbose(env, "At %s the register %s ", ctx, reg_name);
420 	if (!tnum_is_unknown(reg->var_off)) {
421 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 		verbose(env, "has value %s", tn_buf);
423 	} else {
424 		verbose(env, "has unknown scalar value");
425 	}
426 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 	verbose(env, " should have been in %s\n", tn_buf);
428 }
429 
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432 	type = base_type(type);
433 	return type == PTR_TO_PACKET ||
434 	       type == PTR_TO_PACKET_META;
435 }
436 
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439 	return type == PTR_TO_SOCKET ||
440 		type == PTR_TO_SOCK_COMMON ||
441 		type == PTR_TO_TCP_SOCK ||
442 		type == PTR_TO_XDP_SOCK;
443 }
444 
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447 	return type == PTR_TO_SOCKET ||
448 		type == PTR_TO_TCP_SOCK ||
449 		type == PTR_TO_MAP_VALUE ||
450 		type == PTR_TO_MAP_KEY ||
451 		type == PTR_TO_SOCK_COMMON;
452 }
453 
454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456 	return reg->type == PTR_TO_MAP_VALUE &&
457 	       btf_record_has_field(reg->map_ptr->record, BPF_SPIN_LOCK);
458 }
459 
460 static bool type_is_rdonly_mem(u32 type)
461 {
462 	return type & MEM_RDONLY;
463 }
464 
465 static bool type_may_be_null(u32 type)
466 {
467 	return type & PTR_MAYBE_NULL;
468 }
469 
470 static bool is_acquire_function(enum bpf_func_id func_id,
471 				const struct bpf_map *map)
472 {
473 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
474 
475 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
476 	    func_id == BPF_FUNC_sk_lookup_udp ||
477 	    func_id == BPF_FUNC_skc_lookup_tcp ||
478 	    func_id == BPF_FUNC_ringbuf_reserve ||
479 	    func_id == BPF_FUNC_kptr_xchg)
480 		return true;
481 
482 	if (func_id == BPF_FUNC_map_lookup_elem &&
483 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
484 	     map_type == BPF_MAP_TYPE_SOCKHASH))
485 		return true;
486 
487 	return false;
488 }
489 
490 static bool is_ptr_cast_function(enum bpf_func_id func_id)
491 {
492 	return func_id == BPF_FUNC_tcp_sock ||
493 		func_id == BPF_FUNC_sk_fullsock ||
494 		func_id == BPF_FUNC_skc_to_tcp_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
496 		func_id == BPF_FUNC_skc_to_udp6_sock ||
497 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
498 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
499 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
500 }
501 
502 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
503 {
504 	return func_id == BPF_FUNC_dynptr_data;
505 }
506 
507 static bool is_callback_calling_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_for_each_map_elem ||
510 	       func_id == BPF_FUNC_timer_set_callback ||
511 	       func_id == BPF_FUNC_find_vma ||
512 	       func_id == BPF_FUNC_loop ||
513 	       func_id == BPF_FUNC_user_ringbuf_drain;
514 }
515 
516 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
517 					const struct bpf_map *map)
518 {
519 	int ref_obj_uses = 0;
520 
521 	if (is_ptr_cast_function(func_id))
522 		ref_obj_uses++;
523 	if (is_acquire_function(func_id, map))
524 		ref_obj_uses++;
525 	if (is_dynptr_ref_function(func_id))
526 		ref_obj_uses++;
527 
528 	return ref_obj_uses > 1;
529 }
530 
531 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
532 {
533 	return BPF_CLASS(insn->code) == BPF_STX &&
534 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
535 	       insn->imm == BPF_CMPXCHG;
536 }
537 
538 /* string representation of 'enum bpf_reg_type'
539  *
540  * Note that reg_type_str() can not appear more than once in a single verbose()
541  * statement.
542  */
543 static const char *reg_type_str(struct bpf_verifier_env *env,
544 				enum bpf_reg_type type)
545 {
546 	char postfix[16] = {0}, prefix[32] = {0};
547 	static const char * const str[] = {
548 		[NOT_INIT]		= "?",
549 		[SCALAR_VALUE]		= "scalar",
550 		[PTR_TO_CTX]		= "ctx",
551 		[CONST_PTR_TO_MAP]	= "map_ptr",
552 		[PTR_TO_MAP_VALUE]	= "map_value",
553 		[PTR_TO_STACK]		= "fp",
554 		[PTR_TO_PACKET]		= "pkt",
555 		[PTR_TO_PACKET_META]	= "pkt_meta",
556 		[PTR_TO_PACKET_END]	= "pkt_end",
557 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
558 		[PTR_TO_SOCKET]		= "sock",
559 		[PTR_TO_SOCK_COMMON]	= "sock_common",
560 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
561 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
562 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
563 		[PTR_TO_BTF_ID]		= "ptr_",
564 		[PTR_TO_MEM]		= "mem",
565 		[PTR_TO_BUF]		= "buf",
566 		[PTR_TO_FUNC]		= "func",
567 		[PTR_TO_MAP_KEY]	= "map_key",
568 		[PTR_TO_DYNPTR]		= "dynptr_ptr",
569 	};
570 
571 	if (type & PTR_MAYBE_NULL) {
572 		if (base_type(type) == PTR_TO_BTF_ID)
573 			strncpy(postfix, "or_null_", 16);
574 		else
575 			strncpy(postfix, "_or_null", 16);
576 	}
577 
578 	if (type & MEM_RDONLY)
579 		strncpy(prefix, "rdonly_", 32);
580 	if (type & MEM_ALLOC)
581 		strncpy(prefix, "alloc_", 32);
582 	if (type & MEM_USER)
583 		strncpy(prefix, "user_", 32);
584 	if (type & MEM_PERCPU)
585 		strncpy(prefix, "percpu_", 32);
586 	if (type & PTR_UNTRUSTED)
587 		strncpy(prefix, "untrusted_", 32);
588 
589 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
590 		 prefix, str[base_type(type)], postfix);
591 	return env->type_str_buf;
592 }
593 
594 static char slot_type_char[] = {
595 	[STACK_INVALID]	= '?',
596 	[STACK_SPILL]	= 'r',
597 	[STACK_MISC]	= 'm',
598 	[STACK_ZERO]	= '0',
599 	[STACK_DYNPTR]	= 'd',
600 };
601 
602 static void print_liveness(struct bpf_verifier_env *env,
603 			   enum bpf_reg_liveness live)
604 {
605 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
606 	    verbose(env, "_");
607 	if (live & REG_LIVE_READ)
608 		verbose(env, "r");
609 	if (live & REG_LIVE_WRITTEN)
610 		verbose(env, "w");
611 	if (live & REG_LIVE_DONE)
612 		verbose(env, "D");
613 }
614 
615 static int get_spi(s32 off)
616 {
617 	return (-off - 1) / BPF_REG_SIZE;
618 }
619 
620 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
621 {
622 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
623 
624 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
625 	 * within [0, allocated_stack).
626 	 *
627 	 * Please note that the spi grows downwards. For example, a dynptr
628 	 * takes the size of two stack slots; the first slot will be at
629 	 * spi and the second slot will be at spi - 1.
630 	 */
631 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
632 }
633 
634 static struct bpf_func_state *func(struct bpf_verifier_env *env,
635 				   const struct bpf_reg_state *reg)
636 {
637 	struct bpf_verifier_state *cur = env->cur_state;
638 
639 	return cur->frame[reg->frameno];
640 }
641 
642 static const char *kernel_type_name(const struct btf* btf, u32 id)
643 {
644 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
645 }
646 
647 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
648 {
649 	env->scratched_regs |= 1U << regno;
650 }
651 
652 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
653 {
654 	env->scratched_stack_slots |= 1ULL << spi;
655 }
656 
657 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
658 {
659 	return (env->scratched_regs >> regno) & 1;
660 }
661 
662 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
663 {
664 	return (env->scratched_stack_slots >> regno) & 1;
665 }
666 
667 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
668 {
669 	return env->scratched_regs || env->scratched_stack_slots;
670 }
671 
672 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
673 {
674 	env->scratched_regs = 0U;
675 	env->scratched_stack_slots = 0ULL;
676 }
677 
678 /* Used for printing the entire verifier state. */
679 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
680 {
681 	env->scratched_regs = ~0U;
682 	env->scratched_stack_slots = ~0ULL;
683 }
684 
685 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
686 {
687 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
688 	case DYNPTR_TYPE_LOCAL:
689 		return BPF_DYNPTR_TYPE_LOCAL;
690 	case DYNPTR_TYPE_RINGBUF:
691 		return BPF_DYNPTR_TYPE_RINGBUF;
692 	default:
693 		return BPF_DYNPTR_TYPE_INVALID;
694 	}
695 }
696 
697 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
698 {
699 	return type == BPF_DYNPTR_TYPE_RINGBUF;
700 }
701 
702 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
703 				   enum bpf_arg_type arg_type, int insn_idx)
704 {
705 	struct bpf_func_state *state = func(env, reg);
706 	enum bpf_dynptr_type type;
707 	int spi, i, id;
708 
709 	spi = get_spi(reg->off);
710 
711 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
712 		return -EINVAL;
713 
714 	for (i = 0; i < BPF_REG_SIZE; i++) {
715 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
716 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
717 	}
718 
719 	type = arg_to_dynptr_type(arg_type);
720 	if (type == BPF_DYNPTR_TYPE_INVALID)
721 		return -EINVAL;
722 
723 	state->stack[spi].spilled_ptr.dynptr.first_slot = true;
724 	state->stack[spi].spilled_ptr.dynptr.type = type;
725 	state->stack[spi - 1].spilled_ptr.dynptr.type = type;
726 
727 	if (dynptr_type_refcounted(type)) {
728 		/* The id is used to track proper releasing */
729 		id = acquire_reference_state(env, insn_idx);
730 		if (id < 0)
731 			return id;
732 
733 		state->stack[spi].spilled_ptr.id = id;
734 		state->stack[spi - 1].spilled_ptr.id = id;
735 	}
736 
737 	return 0;
738 }
739 
740 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
741 {
742 	struct bpf_func_state *state = func(env, reg);
743 	int spi, i;
744 
745 	spi = get_spi(reg->off);
746 
747 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
748 		return -EINVAL;
749 
750 	for (i = 0; i < BPF_REG_SIZE; i++) {
751 		state->stack[spi].slot_type[i] = STACK_INVALID;
752 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
753 	}
754 
755 	/* Invalidate any slices associated with this dynptr */
756 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
757 		release_reference(env, state->stack[spi].spilled_ptr.id);
758 		state->stack[spi].spilled_ptr.id = 0;
759 		state->stack[spi - 1].spilled_ptr.id = 0;
760 	}
761 
762 	state->stack[spi].spilled_ptr.dynptr.first_slot = false;
763 	state->stack[spi].spilled_ptr.dynptr.type = 0;
764 	state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
765 
766 	return 0;
767 }
768 
769 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
770 {
771 	struct bpf_func_state *state = func(env, reg);
772 	int spi = get_spi(reg->off);
773 	int i;
774 
775 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
776 		return true;
777 
778 	for (i = 0; i < BPF_REG_SIZE; i++) {
779 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
780 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
781 			return false;
782 	}
783 
784 	return true;
785 }
786 
787 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
788 			      struct bpf_reg_state *reg)
789 {
790 	struct bpf_func_state *state = func(env, reg);
791 	int spi = get_spi(reg->off);
792 	int i;
793 
794 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
795 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
796 		return false;
797 
798 	for (i = 0; i < BPF_REG_SIZE; i++) {
799 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
800 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
801 			return false;
802 	}
803 
804 	return true;
805 }
806 
807 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
808 			     struct bpf_reg_state *reg,
809 			     enum bpf_arg_type arg_type)
810 {
811 	struct bpf_func_state *state = func(env, reg);
812 	enum bpf_dynptr_type dynptr_type;
813 	int spi = get_spi(reg->off);
814 
815 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
816 	if (arg_type == ARG_PTR_TO_DYNPTR)
817 		return true;
818 
819 	dynptr_type = arg_to_dynptr_type(arg_type);
820 
821 	return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
822 }
823 
824 /* The reg state of a pointer or a bounded scalar was saved when
825  * it was spilled to the stack.
826  */
827 static bool is_spilled_reg(const struct bpf_stack_state *stack)
828 {
829 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
830 }
831 
832 static void scrub_spilled_slot(u8 *stype)
833 {
834 	if (*stype != STACK_INVALID)
835 		*stype = STACK_MISC;
836 }
837 
838 static void print_verifier_state(struct bpf_verifier_env *env,
839 				 const struct bpf_func_state *state,
840 				 bool print_all)
841 {
842 	const struct bpf_reg_state *reg;
843 	enum bpf_reg_type t;
844 	int i;
845 
846 	if (state->frameno)
847 		verbose(env, " frame%d:", state->frameno);
848 	for (i = 0; i < MAX_BPF_REG; i++) {
849 		reg = &state->regs[i];
850 		t = reg->type;
851 		if (t == NOT_INIT)
852 			continue;
853 		if (!print_all && !reg_scratched(env, i))
854 			continue;
855 		verbose(env, " R%d", i);
856 		print_liveness(env, reg->live);
857 		verbose(env, "=");
858 		if (t == SCALAR_VALUE && reg->precise)
859 			verbose(env, "P");
860 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
861 		    tnum_is_const(reg->var_off)) {
862 			/* reg->off should be 0 for SCALAR_VALUE */
863 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
864 			verbose(env, "%lld", reg->var_off.value + reg->off);
865 		} else {
866 			const char *sep = "";
867 
868 			verbose(env, "%s", reg_type_str(env, t));
869 			if (base_type(t) == PTR_TO_BTF_ID)
870 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
871 			verbose(env, "(");
872 /*
873  * _a stands for append, was shortened to avoid multiline statements below.
874  * This macro is used to output a comma separated list of attributes.
875  */
876 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
877 
878 			if (reg->id)
879 				verbose_a("id=%d", reg->id);
880 			if (reg->ref_obj_id)
881 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
882 			if (t != SCALAR_VALUE)
883 				verbose_a("off=%d", reg->off);
884 			if (type_is_pkt_pointer(t))
885 				verbose_a("r=%d", reg->range);
886 			else if (base_type(t) == CONST_PTR_TO_MAP ||
887 				 base_type(t) == PTR_TO_MAP_KEY ||
888 				 base_type(t) == PTR_TO_MAP_VALUE)
889 				verbose_a("ks=%d,vs=%d",
890 					  reg->map_ptr->key_size,
891 					  reg->map_ptr->value_size);
892 			if (tnum_is_const(reg->var_off)) {
893 				/* Typically an immediate SCALAR_VALUE, but
894 				 * could be a pointer whose offset is too big
895 				 * for reg->off
896 				 */
897 				verbose_a("imm=%llx", reg->var_off.value);
898 			} else {
899 				if (reg->smin_value != reg->umin_value &&
900 				    reg->smin_value != S64_MIN)
901 					verbose_a("smin=%lld", (long long)reg->smin_value);
902 				if (reg->smax_value != reg->umax_value &&
903 				    reg->smax_value != S64_MAX)
904 					verbose_a("smax=%lld", (long long)reg->smax_value);
905 				if (reg->umin_value != 0)
906 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
907 				if (reg->umax_value != U64_MAX)
908 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
909 				if (!tnum_is_unknown(reg->var_off)) {
910 					char tn_buf[48];
911 
912 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
913 					verbose_a("var_off=%s", tn_buf);
914 				}
915 				if (reg->s32_min_value != reg->smin_value &&
916 				    reg->s32_min_value != S32_MIN)
917 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
918 				if (reg->s32_max_value != reg->smax_value &&
919 				    reg->s32_max_value != S32_MAX)
920 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
921 				if (reg->u32_min_value != reg->umin_value &&
922 				    reg->u32_min_value != U32_MIN)
923 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
924 				if (reg->u32_max_value != reg->umax_value &&
925 				    reg->u32_max_value != U32_MAX)
926 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
927 			}
928 #undef verbose_a
929 
930 			verbose(env, ")");
931 		}
932 	}
933 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
934 		char types_buf[BPF_REG_SIZE + 1];
935 		bool valid = false;
936 		int j;
937 
938 		for (j = 0; j < BPF_REG_SIZE; j++) {
939 			if (state->stack[i].slot_type[j] != STACK_INVALID)
940 				valid = true;
941 			types_buf[j] = slot_type_char[
942 					state->stack[i].slot_type[j]];
943 		}
944 		types_buf[BPF_REG_SIZE] = 0;
945 		if (!valid)
946 			continue;
947 		if (!print_all && !stack_slot_scratched(env, i))
948 			continue;
949 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
950 		print_liveness(env, state->stack[i].spilled_ptr.live);
951 		if (is_spilled_reg(&state->stack[i])) {
952 			reg = &state->stack[i].spilled_ptr;
953 			t = reg->type;
954 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
955 			if (t == SCALAR_VALUE && reg->precise)
956 				verbose(env, "P");
957 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
958 				verbose(env, "%lld", reg->var_off.value + reg->off);
959 		} else {
960 			verbose(env, "=%s", types_buf);
961 		}
962 	}
963 	if (state->acquired_refs && state->refs[0].id) {
964 		verbose(env, " refs=%d", state->refs[0].id);
965 		for (i = 1; i < state->acquired_refs; i++)
966 			if (state->refs[i].id)
967 				verbose(env, ",%d", state->refs[i].id);
968 	}
969 	if (state->in_callback_fn)
970 		verbose(env, " cb");
971 	if (state->in_async_callback_fn)
972 		verbose(env, " async_cb");
973 	verbose(env, "\n");
974 	mark_verifier_state_clean(env);
975 }
976 
977 static inline u32 vlog_alignment(u32 pos)
978 {
979 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
980 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
981 }
982 
983 static void print_insn_state(struct bpf_verifier_env *env,
984 			     const struct bpf_func_state *state)
985 {
986 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
987 		/* remove new line character */
988 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
989 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
990 	} else {
991 		verbose(env, "%d:", env->insn_idx);
992 	}
993 	print_verifier_state(env, state, false);
994 }
995 
996 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
997  * small to hold src. This is different from krealloc since we don't want to preserve
998  * the contents of dst.
999  *
1000  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1001  * not be allocated.
1002  */
1003 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1004 {
1005 	size_t bytes;
1006 
1007 	if (ZERO_OR_NULL_PTR(src))
1008 		goto out;
1009 
1010 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1011 		return NULL;
1012 
1013 	if (ksize(dst) < bytes) {
1014 		kfree(dst);
1015 		dst = kmalloc_track_caller(bytes, flags);
1016 		if (!dst)
1017 			return NULL;
1018 	}
1019 
1020 	memcpy(dst, src, bytes);
1021 out:
1022 	return dst ? dst : ZERO_SIZE_PTR;
1023 }
1024 
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026  * small to hold new_n items. new items are zeroed out if the array grows.
1027  *
1028  * Contrary to krealloc_array, does not free arr if new_n is zero.
1029  */
1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1031 {
1032 	void *new_arr;
1033 
1034 	if (!new_n || old_n == new_n)
1035 		goto out;
1036 
1037 	new_arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1038 	if (!new_arr) {
1039 		kfree(arr);
1040 		return NULL;
1041 	}
1042 	arr = new_arr;
1043 
1044 	if (new_n > old_n)
1045 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1046 
1047 out:
1048 	return arr ? arr : ZERO_SIZE_PTR;
1049 }
1050 
1051 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1052 {
1053 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1054 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1055 	if (!dst->refs)
1056 		return -ENOMEM;
1057 
1058 	dst->acquired_refs = src->acquired_refs;
1059 	return 0;
1060 }
1061 
1062 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1063 {
1064 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1065 
1066 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1067 				GFP_KERNEL);
1068 	if (!dst->stack)
1069 		return -ENOMEM;
1070 
1071 	dst->allocated_stack = src->allocated_stack;
1072 	return 0;
1073 }
1074 
1075 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1076 {
1077 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1078 				    sizeof(struct bpf_reference_state));
1079 	if (!state->refs)
1080 		return -ENOMEM;
1081 
1082 	state->acquired_refs = n;
1083 	return 0;
1084 }
1085 
1086 static int grow_stack_state(struct bpf_func_state *state, int size)
1087 {
1088 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1089 
1090 	if (old_n >= n)
1091 		return 0;
1092 
1093 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1094 	if (!state->stack)
1095 		return -ENOMEM;
1096 
1097 	state->allocated_stack = size;
1098 	return 0;
1099 }
1100 
1101 /* Acquire a pointer id from the env and update the state->refs to include
1102  * this new pointer reference.
1103  * On success, returns a valid pointer id to associate with the register
1104  * On failure, returns a negative errno.
1105  */
1106 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1107 {
1108 	struct bpf_func_state *state = cur_func(env);
1109 	int new_ofs = state->acquired_refs;
1110 	int id, err;
1111 
1112 	err = resize_reference_state(state, state->acquired_refs + 1);
1113 	if (err)
1114 		return err;
1115 	id = ++env->id_gen;
1116 	state->refs[new_ofs].id = id;
1117 	state->refs[new_ofs].insn_idx = insn_idx;
1118 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1119 
1120 	return id;
1121 }
1122 
1123 /* release function corresponding to acquire_reference_state(). Idempotent. */
1124 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1125 {
1126 	int i, last_idx;
1127 
1128 	last_idx = state->acquired_refs - 1;
1129 	for (i = 0; i < state->acquired_refs; i++) {
1130 		if (state->refs[i].id == ptr_id) {
1131 			/* Cannot release caller references in callbacks */
1132 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1133 				return -EINVAL;
1134 			if (last_idx && i != last_idx)
1135 				memcpy(&state->refs[i], &state->refs[last_idx],
1136 				       sizeof(*state->refs));
1137 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1138 			state->acquired_refs--;
1139 			return 0;
1140 		}
1141 	}
1142 	return -EINVAL;
1143 }
1144 
1145 static void free_func_state(struct bpf_func_state *state)
1146 {
1147 	if (!state)
1148 		return;
1149 	kfree(state->refs);
1150 	kfree(state->stack);
1151 	kfree(state);
1152 }
1153 
1154 static void clear_jmp_history(struct bpf_verifier_state *state)
1155 {
1156 	kfree(state->jmp_history);
1157 	state->jmp_history = NULL;
1158 	state->jmp_history_cnt = 0;
1159 }
1160 
1161 static void free_verifier_state(struct bpf_verifier_state *state,
1162 				bool free_self)
1163 {
1164 	int i;
1165 
1166 	for (i = 0; i <= state->curframe; i++) {
1167 		free_func_state(state->frame[i]);
1168 		state->frame[i] = NULL;
1169 	}
1170 	clear_jmp_history(state);
1171 	if (free_self)
1172 		kfree(state);
1173 }
1174 
1175 /* copy verifier state from src to dst growing dst stack space
1176  * when necessary to accommodate larger src stack
1177  */
1178 static int copy_func_state(struct bpf_func_state *dst,
1179 			   const struct bpf_func_state *src)
1180 {
1181 	int err;
1182 
1183 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1184 	err = copy_reference_state(dst, src);
1185 	if (err)
1186 		return err;
1187 	return copy_stack_state(dst, src);
1188 }
1189 
1190 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1191 			       const struct bpf_verifier_state *src)
1192 {
1193 	struct bpf_func_state *dst;
1194 	int i, err;
1195 
1196 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1197 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1198 					    GFP_USER);
1199 	if (!dst_state->jmp_history)
1200 		return -ENOMEM;
1201 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1202 
1203 	/* if dst has more stack frames then src frame, free them */
1204 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1205 		free_func_state(dst_state->frame[i]);
1206 		dst_state->frame[i] = NULL;
1207 	}
1208 	dst_state->speculative = src->speculative;
1209 	dst_state->curframe = src->curframe;
1210 	dst_state->active_spin_lock = src->active_spin_lock;
1211 	dst_state->branches = src->branches;
1212 	dst_state->parent = src->parent;
1213 	dst_state->first_insn_idx = src->first_insn_idx;
1214 	dst_state->last_insn_idx = src->last_insn_idx;
1215 	for (i = 0; i <= src->curframe; i++) {
1216 		dst = dst_state->frame[i];
1217 		if (!dst) {
1218 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1219 			if (!dst)
1220 				return -ENOMEM;
1221 			dst_state->frame[i] = dst;
1222 		}
1223 		err = copy_func_state(dst, src->frame[i]);
1224 		if (err)
1225 			return err;
1226 	}
1227 	return 0;
1228 }
1229 
1230 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1231 {
1232 	while (st) {
1233 		u32 br = --st->branches;
1234 
1235 		/* WARN_ON(br > 1) technically makes sense here,
1236 		 * but see comment in push_stack(), hence:
1237 		 */
1238 		WARN_ONCE((int)br < 0,
1239 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1240 			  br);
1241 		if (br)
1242 			break;
1243 		st = st->parent;
1244 	}
1245 }
1246 
1247 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1248 		     int *insn_idx, bool pop_log)
1249 {
1250 	struct bpf_verifier_state *cur = env->cur_state;
1251 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1252 	int err;
1253 
1254 	if (env->head == NULL)
1255 		return -ENOENT;
1256 
1257 	if (cur) {
1258 		err = copy_verifier_state(cur, &head->st);
1259 		if (err)
1260 			return err;
1261 	}
1262 	if (pop_log)
1263 		bpf_vlog_reset(&env->log, head->log_pos);
1264 	if (insn_idx)
1265 		*insn_idx = head->insn_idx;
1266 	if (prev_insn_idx)
1267 		*prev_insn_idx = head->prev_insn_idx;
1268 	elem = head->next;
1269 	free_verifier_state(&head->st, false);
1270 	kfree(head);
1271 	env->head = elem;
1272 	env->stack_size--;
1273 	return 0;
1274 }
1275 
1276 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1277 					     int insn_idx, int prev_insn_idx,
1278 					     bool speculative)
1279 {
1280 	struct bpf_verifier_state *cur = env->cur_state;
1281 	struct bpf_verifier_stack_elem *elem;
1282 	int err;
1283 
1284 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1285 	if (!elem)
1286 		goto err;
1287 
1288 	elem->insn_idx = insn_idx;
1289 	elem->prev_insn_idx = prev_insn_idx;
1290 	elem->next = env->head;
1291 	elem->log_pos = env->log.len_used;
1292 	env->head = elem;
1293 	env->stack_size++;
1294 	err = copy_verifier_state(&elem->st, cur);
1295 	if (err)
1296 		goto err;
1297 	elem->st.speculative |= speculative;
1298 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1299 		verbose(env, "The sequence of %d jumps is too complex.\n",
1300 			env->stack_size);
1301 		goto err;
1302 	}
1303 	if (elem->st.parent) {
1304 		++elem->st.parent->branches;
1305 		/* WARN_ON(branches > 2) technically makes sense here,
1306 		 * but
1307 		 * 1. speculative states will bump 'branches' for non-branch
1308 		 * instructions
1309 		 * 2. is_state_visited() heuristics may decide not to create
1310 		 * a new state for a sequence of branches and all such current
1311 		 * and cloned states will be pointing to a single parent state
1312 		 * which might have large 'branches' count.
1313 		 */
1314 	}
1315 	return &elem->st;
1316 err:
1317 	free_verifier_state(env->cur_state, true);
1318 	env->cur_state = NULL;
1319 	/* pop all elements and return */
1320 	while (!pop_stack(env, NULL, NULL, false));
1321 	return NULL;
1322 }
1323 
1324 #define CALLER_SAVED_REGS 6
1325 static const int caller_saved[CALLER_SAVED_REGS] = {
1326 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1327 };
1328 
1329 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1330 				struct bpf_reg_state *reg);
1331 
1332 /* This helper doesn't clear reg->id */
1333 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1334 {
1335 	reg->var_off = tnum_const(imm);
1336 	reg->smin_value = (s64)imm;
1337 	reg->smax_value = (s64)imm;
1338 	reg->umin_value = imm;
1339 	reg->umax_value = imm;
1340 
1341 	reg->s32_min_value = (s32)imm;
1342 	reg->s32_max_value = (s32)imm;
1343 	reg->u32_min_value = (u32)imm;
1344 	reg->u32_max_value = (u32)imm;
1345 }
1346 
1347 /* Mark the unknown part of a register (variable offset or scalar value) as
1348  * known to have the value @imm.
1349  */
1350 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1351 {
1352 	/* Clear id, off, and union(map_ptr, range) */
1353 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1354 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1355 	___mark_reg_known(reg, imm);
1356 }
1357 
1358 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1359 {
1360 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1361 	reg->s32_min_value = (s32)imm;
1362 	reg->s32_max_value = (s32)imm;
1363 	reg->u32_min_value = (u32)imm;
1364 	reg->u32_max_value = (u32)imm;
1365 }
1366 
1367 /* Mark the 'variable offset' part of a register as zero.  This should be
1368  * used only on registers holding a pointer type.
1369  */
1370 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1371 {
1372 	__mark_reg_known(reg, 0);
1373 }
1374 
1375 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1376 {
1377 	__mark_reg_known(reg, 0);
1378 	reg->type = SCALAR_VALUE;
1379 }
1380 
1381 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1382 				struct bpf_reg_state *regs, u32 regno)
1383 {
1384 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1385 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1386 		/* Something bad happened, let's kill all regs */
1387 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1388 			__mark_reg_not_init(env, regs + regno);
1389 		return;
1390 	}
1391 	__mark_reg_known_zero(regs + regno);
1392 }
1393 
1394 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1395 {
1396 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1397 		const struct bpf_map *map = reg->map_ptr;
1398 
1399 		if (map->inner_map_meta) {
1400 			reg->type = CONST_PTR_TO_MAP;
1401 			reg->map_ptr = map->inner_map_meta;
1402 			/* transfer reg's id which is unique for every map_lookup_elem
1403 			 * as UID of the inner map.
1404 			 */
1405 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1406 				reg->map_uid = reg->id;
1407 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1408 			reg->type = PTR_TO_XDP_SOCK;
1409 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1410 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1411 			reg->type = PTR_TO_SOCKET;
1412 		} else {
1413 			reg->type = PTR_TO_MAP_VALUE;
1414 		}
1415 		return;
1416 	}
1417 
1418 	reg->type &= ~PTR_MAYBE_NULL;
1419 }
1420 
1421 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1422 {
1423 	return type_is_pkt_pointer(reg->type);
1424 }
1425 
1426 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1427 {
1428 	return reg_is_pkt_pointer(reg) ||
1429 	       reg->type == PTR_TO_PACKET_END;
1430 }
1431 
1432 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1433 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1434 				    enum bpf_reg_type which)
1435 {
1436 	/* The register can already have a range from prior markings.
1437 	 * This is fine as long as it hasn't been advanced from its
1438 	 * origin.
1439 	 */
1440 	return reg->type == which &&
1441 	       reg->id == 0 &&
1442 	       reg->off == 0 &&
1443 	       tnum_equals_const(reg->var_off, 0);
1444 }
1445 
1446 /* Reset the min/max bounds of a register */
1447 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1448 {
1449 	reg->smin_value = S64_MIN;
1450 	reg->smax_value = S64_MAX;
1451 	reg->umin_value = 0;
1452 	reg->umax_value = U64_MAX;
1453 
1454 	reg->s32_min_value = S32_MIN;
1455 	reg->s32_max_value = S32_MAX;
1456 	reg->u32_min_value = 0;
1457 	reg->u32_max_value = U32_MAX;
1458 }
1459 
1460 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1461 {
1462 	reg->smin_value = S64_MIN;
1463 	reg->smax_value = S64_MAX;
1464 	reg->umin_value = 0;
1465 	reg->umax_value = U64_MAX;
1466 }
1467 
1468 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1469 {
1470 	reg->s32_min_value = S32_MIN;
1471 	reg->s32_max_value = S32_MAX;
1472 	reg->u32_min_value = 0;
1473 	reg->u32_max_value = U32_MAX;
1474 }
1475 
1476 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1477 {
1478 	struct tnum var32_off = tnum_subreg(reg->var_off);
1479 
1480 	/* min signed is max(sign bit) | min(other bits) */
1481 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1482 			var32_off.value | (var32_off.mask & S32_MIN));
1483 	/* max signed is min(sign bit) | max(other bits) */
1484 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1485 			var32_off.value | (var32_off.mask & S32_MAX));
1486 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1487 	reg->u32_max_value = min(reg->u32_max_value,
1488 				 (u32)(var32_off.value | var32_off.mask));
1489 }
1490 
1491 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1492 {
1493 	/* min signed is max(sign bit) | min(other bits) */
1494 	reg->smin_value = max_t(s64, reg->smin_value,
1495 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1496 	/* max signed is min(sign bit) | max(other bits) */
1497 	reg->smax_value = min_t(s64, reg->smax_value,
1498 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1499 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1500 	reg->umax_value = min(reg->umax_value,
1501 			      reg->var_off.value | reg->var_off.mask);
1502 }
1503 
1504 static void __update_reg_bounds(struct bpf_reg_state *reg)
1505 {
1506 	__update_reg32_bounds(reg);
1507 	__update_reg64_bounds(reg);
1508 }
1509 
1510 /* Uses signed min/max values to inform unsigned, and vice-versa */
1511 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1512 {
1513 	/* Learn sign from signed bounds.
1514 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1515 	 * are the same, so combine.  This works even in the negative case, e.g.
1516 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1517 	 */
1518 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1519 		reg->s32_min_value = reg->u32_min_value =
1520 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1521 		reg->s32_max_value = reg->u32_max_value =
1522 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1523 		return;
1524 	}
1525 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1526 	 * boundary, so we must be careful.
1527 	 */
1528 	if ((s32)reg->u32_max_value >= 0) {
1529 		/* Positive.  We can't learn anything from the smin, but smax
1530 		 * is positive, hence safe.
1531 		 */
1532 		reg->s32_min_value = reg->u32_min_value;
1533 		reg->s32_max_value = reg->u32_max_value =
1534 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1535 	} else if ((s32)reg->u32_min_value < 0) {
1536 		/* Negative.  We can't learn anything from the smax, but smin
1537 		 * is negative, hence safe.
1538 		 */
1539 		reg->s32_min_value = reg->u32_min_value =
1540 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1541 		reg->s32_max_value = reg->u32_max_value;
1542 	}
1543 }
1544 
1545 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1546 {
1547 	/* Learn sign from signed bounds.
1548 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1549 	 * are the same, so combine.  This works even in the negative case, e.g.
1550 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1551 	 */
1552 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1553 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1554 							  reg->umin_value);
1555 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1556 							  reg->umax_value);
1557 		return;
1558 	}
1559 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1560 	 * boundary, so we must be careful.
1561 	 */
1562 	if ((s64)reg->umax_value >= 0) {
1563 		/* Positive.  We can't learn anything from the smin, but smax
1564 		 * is positive, hence safe.
1565 		 */
1566 		reg->smin_value = reg->umin_value;
1567 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1568 							  reg->umax_value);
1569 	} else if ((s64)reg->umin_value < 0) {
1570 		/* Negative.  We can't learn anything from the smax, but smin
1571 		 * is negative, hence safe.
1572 		 */
1573 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1574 							  reg->umin_value);
1575 		reg->smax_value = reg->umax_value;
1576 	}
1577 }
1578 
1579 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1580 {
1581 	__reg32_deduce_bounds(reg);
1582 	__reg64_deduce_bounds(reg);
1583 }
1584 
1585 /* Attempts to improve var_off based on unsigned min/max information */
1586 static void __reg_bound_offset(struct bpf_reg_state *reg)
1587 {
1588 	struct tnum var64_off = tnum_intersect(reg->var_off,
1589 					       tnum_range(reg->umin_value,
1590 							  reg->umax_value));
1591 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1592 						tnum_range(reg->u32_min_value,
1593 							   reg->u32_max_value));
1594 
1595 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1596 }
1597 
1598 static void reg_bounds_sync(struct bpf_reg_state *reg)
1599 {
1600 	/* We might have learned new bounds from the var_off. */
1601 	__update_reg_bounds(reg);
1602 	/* We might have learned something about the sign bit. */
1603 	__reg_deduce_bounds(reg);
1604 	/* We might have learned some bits from the bounds. */
1605 	__reg_bound_offset(reg);
1606 	/* Intersecting with the old var_off might have improved our bounds
1607 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1608 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1609 	 */
1610 	__update_reg_bounds(reg);
1611 }
1612 
1613 static bool __reg32_bound_s64(s32 a)
1614 {
1615 	return a >= 0 && a <= S32_MAX;
1616 }
1617 
1618 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1619 {
1620 	reg->umin_value = reg->u32_min_value;
1621 	reg->umax_value = reg->u32_max_value;
1622 
1623 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1624 	 * be positive otherwise set to worse case bounds and refine later
1625 	 * from tnum.
1626 	 */
1627 	if (__reg32_bound_s64(reg->s32_min_value) &&
1628 	    __reg32_bound_s64(reg->s32_max_value)) {
1629 		reg->smin_value = reg->s32_min_value;
1630 		reg->smax_value = reg->s32_max_value;
1631 	} else {
1632 		reg->smin_value = 0;
1633 		reg->smax_value = U32_MAX;
1634 	}
1635 }
1636 
1637 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1638 {
1639 	/* special case when 64-bit register has upper 32-bit register
1640 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1641 	 * allowing us to use 32-bit bounds directly,
1642 	 */
1643 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1644 		__reg_assign_32_into_64(reg);
1645 	} else {
1646 		/* Otherwise the best we can do is push lower 32bit known and
1647 		 * unknown bits into register (var_off set from jmp logic)
1648 		 * then learn as much as possible from the 64-bit tnum
1649 		 * known and unknown bits. The previous smin/smax bounds are
1650 		 * invalid here because of jmp32 compare so mark them unknown
1651 		 * so they do not impact tnum bounds calculation.
1652 		 */
1653 		__mark_reg64_unbounded(reg);
1654 	}
1655 	reg_bounds_sync(reg);
1656 }
1657 
1658 static bool __reg64_bound_s32(s64 a)
1659 {
1660 	return a >= S32_MIN && a <= S32_MAX;
1661 }
1662 
1663 static bool __reg64_bound_u32(u64 a)
1664 {
1665 	return a >= U32_MIN && a <= U32_MAX;
1666 }
1667 
1668 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1669 {
1670 	__mark_reg32_unbounded(reg);
1671 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1672 		reg->s32_min_value = (s32)reg->smin_value;
1673 		reg->s32_max_value = (s32)reg->smax_value;
1674 	}
1675 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1676 		reg->u32_min_value = (u32)reg->umin_value;
1677 		reg->u32_max_value = (u32)reg->umax_value;
1678 	}
1679 	reg_bounds_sync(reg);
1680 }
1681 
1682 /* Mark a register as having a completely unknown (scalar) value. */
1683 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1684 			       struct bpf_reg_state *reg)
1685 {
1686 	/*
1687 	 * Clear type, id, off, and union(map_ptr, range) and
1688 	 * padding between 'type' and union
1689 	 */
1690 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1691 	reg->type = SCALAR_VALUE;
1692 	reg->var_off = tnum_unknown;
1693 	reg->frameno = 0;
1694 	reg->precise = !env->bpf_capable;
1695 	__mark_reg_unbounded(reg);
1696 }
1697 
1698 static void mark_reg_unknown(struct bpf_verifier_env *env,
1699 			     struct bpf_reg_state *regs, u32 regno)
1700 {
1701 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1702 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1703 		/* Something bad happened, let's kill all regs except FP */
1704 		for (regno = 0; regno < BPF_REG_FP; regno++)
1705 			__mark_reg_not_init(env, regs + regno);
1706 		return;
1707 	}
1708 	__mark_reg_unknown(env, regs + regno);
1709 }
1710 
1711 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1712 				struct bpf_reg_state *reg)
1713 {
1714 	__mark_reg_unknown(env, reg);
1715 	reg->type = NOT_INIT;
1716 }
1717 
1718 static void mark_reg_not_init(struct bpf_verifier_env *env,
1719 			      struct bpf_reg_state *regs, u32 regno)
1720 {
1721 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1722 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1723 		/* Something bad happened, let's kill all regs except FP */
1724 		for (regno = 0; regno < BPF_REG_FP; regno++)
1725 			__mark_reg_not_init(env, regs + regno);
1726 		return;
1727 	}
1728 	__mark_reg_not_init(env, regs + regno);
1729 }
1730 
1731 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1732 			    struct bpf_reg_state *regs, u32 regno,
1733 			    enum bpf_reg_type reg_type,
1734 			    struct btf *btf, u32 btf_id,
1735 			    enum bpf_type_flag flag)
1736 {
1737 	if (reg_type == SCALAR_VALUE) {
1738 		mark_reg_unknown(env, regs, regno);
1739 		return;
1740 	}
1741 	mark_reg_known_zero(env, regs, regno);
1742 	regs[regno].type = PTR_TO_BTF_ID | flag;
1743 	regs[regno].btf = btf;
1744 	regs[regno].btf_id = btf_id;
1745 }
1746 
1747 #define DEF_NOT_SUBREG	(0)
1748 static void init_reg_state(struct bpf_verifier_env *env,
1749 			   struct bpf_func_state *state)
1750 {
1751 	struct bpf_reg_state *regs = state->regs;
1752 	int i;
1753 
1754 	for (i = 0; i < MAX_BPF_REG; i++) {
1755 		mark_reg_not_init(env, regs, i);
1756 		regs[i].live = REG_LIVE_NONE;
1757 		regs[i].parent = NULL;
1758 		regs[i].subreg_def = DEF_NOT_SUBREG;
1759 	}
1760 
1761 	/* frame pointer */
1762 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1763 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1764 	regs[BPF_REG_FP].frameno = state->frameno;
1765 }
1766 
1767 #define BPF_MAIN_FUNC (-1)
1768 static void init_func_state(struct bpf_verifier_env *env,
1769 			    struct bpf_func_state *state,
1770 			    int callsite, int frameno, int subprogno)
1771 {
1772 	state->callsite = callsite;
1773 	state->frameno = frameno;
1774 	state->subprogno = subprogno;
1775 	state->callback_ret_range = tnum_range(0, 0);
1776 	init_reg_state(env, state);
1777 	mark_verifier_state_scratched(env);
1778 }
1779 
1780 /* Similar to push_stack(), but for async callbacks */
1781 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1782 						int insn_idx, int prev_insn_idx,
1783 						int subprog)
1784 {
1785 	struct bpf_verifier_stack_elem *elem;
1786 	struct bpf_func_state *frame;
1787 
1788 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1789 	if (!elem)
1790 		goto err;
1791 
1792 	elem->insn_idx = insn_idx;
1793 	elem->prev_insn_idx = prev_insn_idx;
1794 	elem->next = env->head;
1795 	elem->log_pos = env->log.len_used;
1796 	env->head = elem;
1797 	env->stack_size++;
1798 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1799 		verbose(env,
1800 			"The sequence of %d jumps is too complex for async cb.\n",
1801 			env->stack_size);
1802 		goto err;
1803 	}
1804 	/* Unlike push_stack() do not copy_verifier_state().
1805 	 * The caller state doesn't matter.
1806 	 * This is async callback. It starts in a fresh stack.
1807 	 * Initialize it similar to do_check_common().
1808 	 */
1809 	elem->st.branches = 1;
1810 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1811 	if (!frame)
1812 		goto err;
1813 	init_func_state(env, frame,
1814 			BPF_MAIN_FUNC /* callsite */,
1815 			0 /* frameno within this callchain */,
1816 			subprog /* subprog number within this prog */);
1817 	elem->st.frame[0] = frame;
1818 	return &elem->st;
1819 err:
1820 	free_verifier_state(env->cur_state, true);
1821 	env->cur_state = NULL;
1822 	/* pop all elements and return */
1823 	while (!pop_stack(env, NULL, NULL, false));
1824 	return NULL;
1825 }
1826 
1827 
1828 enum reg_arg_type {
1829 	SRC_OP,		/* register is used as source operand */
1830 	DST_OP,		/* register is used as destination operand */
1831 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1832 };
1833 
1834 static int cmp_subprogs(const void *a, const void *b)
1835 {
1836 	return ((struct bpf_subprog_info *)a)->start -
1837 	       ((struct bpf_subprog_info *)b)->start;
1838 }
1839 
1840 static int find_subprog(struct bpf_verifier_env *env, int off)
1841 {
1842 	struct bpf_subprog_info *p;
1843 
1844 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1845 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1846 	if (!p)
1847 		return -ENOENT;
1848 	return p - env->subprog_info;
1849 
1850 }
1851 
1852 static int add_subprog(struct bpf_verifier_env *env, int off)
1853 {
1854 	int insn_cnt = env->prog->len;
1855 	int ret;
1856 
1857 	if (off >= insn_cnt || off < 0) {
1858 		verbose(env, "call to invalid destination\n");
1859 		return -EINVAL;
1860 	}
1861 	ret = find_subprog(env, off);
1862 	if (ret >= 0)
1863 		return ret;
1864 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1865 		verbose(env, "too many subprograms\n");
1866 		return -E2BIG;
1867 	}
1868 	/* determine subprog starts. The end is one before the next starts */
1869 	env->subprog_info[env->subprog_cnt++].start = off;
1870 	sort(env->subprog_info, env->subprog_cnt,
1871 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1872 	return env->subprog_cnt - 1;
1873 }
1874 
1875 #define MAX_KFUNC_DESCS 256
1876 #define MAX_KFUNC_BTFS	256
1877 
1878 struct bpf_kfunc_desc {
1879 	struct btf_func_model func_model;
1880 	u32 func_id;
1881 	s32 imm;
1882 	u16 offset;
1883 };
1884 
1885 struct bpf_kfunc_btf {
1886 	struct btf *btf;
1887 	struct module *module;
1888 	u16 offset;
1889 };
1890 
1891 struct bpf_kfunc_desc_tab {
1892 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1893 	u32 nr_descs;
1894 };
1895 
1896 struct bpf_kfunc_btf_tab {
1897 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1898 	u32 nr_descs;
1899 };
1900 
1901 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1902 {
1903 	const struct bpf_kfunc_desc *d0 = a;
1904 	const struct bpf_kfunc_desc *d1 = b;
1905 
1906 	/* func_id is not greater than BTF_MAX_TYPE */
1907 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1908 }
1909 
1910 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1911 {
1912 	const struct bpf_kfunc_btf *d0 = a;
1913 	const struct bpf_kfunc_btf *d1 = b;
1914 
1915 	return d0->offset - d1->offset;
1916 }
1917 
1918 static const struct bpf_kfunc_desc *
1919 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1920 {
1921 	struct bpf_kfunc_desc desc = {
1922 		.func_id = func_id,
1923 		.offset = offset,
1924 	};
1925 	struct bpf_kfunc_desc_tab *tab;
1926 
1927 	tab = prog->aux->kfunc_tab;
1928 	return bsearch(&desc, tab->descs, tab->nr_descs,
1929 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1930 }
1931 
1932 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1933 					 s16 offset)
1934 {
1935 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1936 	struct bpf_kfunc_btf_tab *tab;
1937 	struct bpf_kfunc_btf *b;
1938 	struct module *mod;
1939 	struct btf *btf;
1940 	int btf_fd;
1941 
1942 	tab = env->prog->aux->kfunc_btf_tab;
1943 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1944 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1945 	if (!b) {
1946 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1947 			verbose(env, "too many different module BTFs\n");
1948 			return ERR_PTR(-E2BIG);
1949 		}
1950 
1951 		if (bpfptr_is_null(env->fd_array)) {
1952 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1953 			return ERR_PTR(-EPROTO);
1954 		}
1955 
1956 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1957 					    offset * sizeof(btf_fd),
1958 					    sizeof(btf_fd)))
1959 			return ERR_PTR(-EFAULT);
1960 
1961 		btf = btf_get_by_fd(btf_fd);
1962 		if (IS_ERR(btf)) {
1963 			verbose(env, "invalid module BTF fd specified\n");
1964 			return btf;
1965 		}
1966 
1967 		if (!btf_is_module(btf)) {
1968 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1969 			btf_put(btf);
1970 			return ERR_PTR(-EINVAL);
1971 		}
1972 
1973 		mod = btf_try_get_module(btf);
1974 		if (!mod) {
1975 			btf_put(btf);
1976 			return ERR_PTR(-ENXIO);
1977 		}
1978 
1979 		b = &tab->descs[tab->nr_descs++];
1980 		b->btf = btf;
1981 		b->module = mod;
1982 		b->offset = offset;
1983 
1984 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1985 		     kfunc_btf_cmp_by_off, NULL);
1986 	}
1987 	return b->btf;
1988 }
1989 
1990 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1991 {
1992 	if (!tab)
1993 		return;
1994 
1995 	while (tab->nr_descs--) {
1996 		module_put(tab->descs[tab->nr_descs].module);
1997 		btf_put(tab->descs[tab->nr_descs].btf);
1998 	}
1999 	kfree(tab);
2000 }
2001 
2002 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2003 {
2004 	if (offset) {
2005 		if (offset < 0) {
2006 			/* In the future, this can be allowed to increase limit
2007 			 * of fd index into fd_array, interpreted as u16.
2008 			 */
2009 			verbose(env, "negative offset disallowed for kernel module function call\n");
2010 			return ERR_PTR(-EINVAL);
2011 		}
2012 
2013 		return __find_kfunc_desc_btf(env, offset);
2014 	}
2015 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2016 }
2017 
2018 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2019 {
2020 	const struct btf_type *func, *func_proto;
2021 	struct bpf_kfunc_btf_tab *btf_tab;
2022 	struct bpf_kfunc_desc_tab *tab;
2023 	struct bpf_prog_aux *prog_aux;
2024 	struct bpf_kfunc_desc *desc;
2025 	const char *func_name;
2026 	struct btf *desc_btf;
2027 	unsigned long call_imm;
2028 	unsigned long addr;
2029 	int err;
2030 
2031 	prog_aux = env->prog->aux;
2032 	tab = prog_aux->kfunc_tab;
2033 	btf_tab = prog_aux->kfunc_btf_tab;
2034 	if (!tab) {
2035 		if (!btf_vmlinux) {
2036 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2037 			return -ENOTSUPP;
2038 		}
2039 
2040 		if (!env->prog->jit_requested) {
2041 			verbose(env, "JIT is required for calling kernel function\n");
2042 			return -ENOTSUPP;
2043 		}
2044 
2045 		if (!bpf_jit_supports_kfunc_call()) {
2046 			verbose(env, "JIT does not support calling kernel function\n");
2047 			return -ENOTSUPP;
2048 		}
2049 
2050 		if (!env->prog->gpl_compatible) {
2051 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2052 			return -EINVAL;
2053 		}
2054 
2055 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2056 		if (!tab)
2057 			return -ENOMEM;
2058 		prog_aux->kfunc_tab = tab;
2059 	}
2060 
2061 	/* func_id == 0 is always invalid, but instead of returning an error, be
2062 	 * conservative and wait until the code elimination pass before returning
2063 	 * error, so that invalid calls that get pruned out can be in BPF programs
2064 	 * loaded from userspace.  It is also required that offset be untouched
2065 	 * for such calls.
2066 	 */
2067 	if (!func_id && !offset)
2068 		return 0;
2069 
2070 	if (!btf_tab && offset) {
2071 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2072 		if (!btf_tab)
2073 			return -ENOMEM;
2074 		prog_aux->kfunc_btf_tab = btf_tab;
2075 	}
2076 
2077 	desc_btf = find_kfunc_desc_btf(env, offset);
2078 	if (IS_ERR(desc_btf)) {
2079 		verbose(env, "failed to find BTF for kernel function\n");
2080 		return PTR_ERR(desc_btf);
2081 	}
2082 
2083 	if (find_kfunc_desc(env->prog, func_id, offset))
2084 		return 0;
2085 
2086 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2087 		verbose(env, "too many different kernel function calls\n");
2088 		return -E2BIG;
2089 	}
2090 
2091 	func = btf_type_by_id(desc_btf, func_id);
2092 	if (!func || !btf_type_is_func(func)) {
2093 		verbose(env, "kernel btf_id %u is not a function\n",
2094 			func_id);
2095 		return -EINVAL;
2096 	}
2097 	func_proto = btf_type_by_id(desc_btf, func->type);
2098 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2099 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2100 			func_id);
2101 		return -EINVAL;
2102 	}
2103 
2104 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2105 	addr = kallsyms_lookup_name(func_name);
2106 	if (!addr) {
2107 		verbose(env, "cannot find address for kernel function %s\n",
2108 			func_name);
2109 		return -EINVAL;
2110 	}
2111 
2112 	call_imm = BPF_CALL_IMM(addr);
2113 	/* Check whether or not the relative offset overflows desc->imm */
2114 	if ((unsigned long)(s32)call_imm != call_imm) {
2115 		verbose(env, "address of kernel function %s is out of range\n",
2116 			func_name);
2117 		return -EINVAL;
2118 	}
2119 
2120 	desc = &tab->descs[tab->nr_descs++];
2121 	desc->func_id = func_id;
2122 	desc->imm = call_imm;
2123 	desc->offset = offset;
2124 	err = btf_distill_func_proto(&env->log, desc_btf,
2125 				     func_proto, func_name,
2126 				     &desc->func_model);
2127 	if (!err)
2128 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2129 		     kfunc_desc_cmp_by_id_off, NULL);
2130 	return err;
2131 }
2132 
2133 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2134 {
2135 	const struct bpf_kfunc_desc *d0 = a;
2136 	const struct bpf_kfunc_desc *d1 = b;
2137 
2138 	if (d0->imm > d1->imm)
2139 		return 1;
2140 	else if (d0->imm < d1->imm)
2141 		return -1;
2142 	return 0;
2143 }
2144 
2145 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2146 {
2147 	struct bpf_kfunc_desc_tab *tab;
2148 
2149 	tab = prog->aux->kfunc_tab;
2150 	if (!tab)
2151 		return;
2152 
2153 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2154 	     kfunc_desc_cmp_by_imm, NULL);
2155 }
2156 
2157 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2158 {
2159 	return !!prog->aux->kfunc_tab;
2160 }
2161 
2162 const struct btf_func_model *
2163 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2164 			 const struct bpf_insn *insn)
2165 {
2166 	const struct bpf_kfunc_desc desc = {
2167 		.imm = insn->imm,
2168 	};
2169 	const struct bpf_kfunc_desc *res;
2170 	struct bpf_kfunc_desc_tab *tab;
2171 
2172 	tab = prog->aux->kfunc_tab;
2173 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2174 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2175 
2176 	return res ? &res->func_model : NULL;
2177 }
2178 
2179 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2180 {
2181 	struct bpf_subprog_info *subprog = env->subprog_info;
2182 	struct bpf_insn *insn = env->prog->insnsi;
2183 	int i, ret, insn_cnt = env->prog->len;
2184 
2185 	/* Add entry function. */
2186 	ret = add_subprog(env, 0);
2187 	if (ret)
2188 		return ret;
2189 
2190 	for (i = 0; i < insn_cnt; i++, insn++) {
2191 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2192 		    !bpf_pseudo_kfunc_call(insn))
2193 			continue;
2194 
2195 		if (!env->bpf_capable) {
2196 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2197 			return -EPERM;
2198 		}
2199 
2200 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2201 			ret = add_subprog(env, i + insn->imm + 1);
2202 		else
2203 			ret = add_kfunc_call(env, insn->imm, insn->off);
2204 
2205 		if (ret < 0)
2206 			return ret;
2207 	}
2208 
2209 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2210 	 * logic. 'subprog_cnt' should not be increased.
2211 	 */
2212 	subprog[env->subprog_cnt].start = insn_cnt;
2213 
2214 	if (env->log.level & BPF_LOG_LEVEL2)
2215 		for (i = 0; i < env->subprog_cnt; i++)
2216 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2217 
2218 	return 0;
2219 }
2220 
2221 static int check_subprogs(struct bpf_verifier_env *env)
2222 {
2223 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2224 	struct bpf_subprog_info *subprog = env->subprog_info;
2225 	struct bpf_insn *insn = env->prog->insnsi;
2226 	int insn_cnt = env->prog->len;
2227 
2228 	/* now check that all jumps are within the same subprog */
2229 	subprog_start = subprog[cur_subprog].start;
2230 	subprog_end = subprog[cur_subprog + 1].start;
2231 	for (i = 0; i < insn_cnt; i++) {
2232 		u8 code = insn[i].code;
2233 
2234 		if (code == (BPF_JMP | BPF_CALL) &&
2235 		    insn[i].imm == BPF_FUNC_tail_call &&
2236 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2237 			subprog[cur_subprog].has_tail_call = true;
2238 		if (BPF_CLASS(code) == BPF_LD &&
2239 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2240 			subprog[cur_subprog].has_ld_abs = true;
2241 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2242 			goto next;
2243 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2244 			goto next;
2245 		off = i + insn[i].off + 1;
2246 		if (off < subprog_start || off >= subprog_end) {
2247 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2248 			return -EINVAL;
2249 		}
2250 next:
2251 		if (i == subprog_end - 1) {
2252 			/* to avoid fall-through from one subprog into another
2253 			 * the last insn of the subprog should be either exit
2254 			 * or unconditional jump back
2255 			 */
2256 			if (code != (BPF_JMP | BPF_EXIT) &&
2257 			    code != (BPF_JMP | BPF_JA)) {
2258 				verbose(env, "last insn is not an exit or jmp\n");
2259 				return -EINVAL;
2260 			}
2261 			subprog_start = subprog_end;
2262 			cur_subprog++;
2263 			if (cur_subprog < env->subprog_cnt)
2264 				subprog_end = subprog[cur_subprog + 1].start;
2265 		}
2266 	}
2267 	return 0;
2268 }
2269 
2270 /* Parentage chain of this register (or stack slot) should take care of all
2271  * issues like callee-saved registers, stack slot allocation time, etc.
2272  */
2273 static int mark_reg_read(struct bpf_verifier_env *env,
2274 			 const struct bpf_reg_state *state,
2275 			 struct bpf_reg_state *parent, u8 flag)
2276 {
2277 	bool writes = parent == state->parent; /* Observe write marks */
2278 	int cnt = 0;
2279 
2280 	while (parent) {
2281 		/* if read wasn't screened by an earlier write ... */
2282 		if (writes && state->live & REG_LIVE_WRITTEN)
2283 			break;
2284 		if (parent->live & REG_LIVE_DONE) {
2285 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2286 				reg_type_str(env, parent->type),
2287 				parent->var_off.value, parent->off);
2288 			return -EFAULT;
2289 		}
2290 		/* The first condition is more likely to be true than the
2291 		 * second, checked it first.
2292 		 */
2293 		if ((parent->live & REG_LIVE_READ) == flag ||
2294 		    parent->live & REG_LIVE_READ64)
2295 			/* The parentage chain never changes and
2296 			 * this parent was already marked as LIVE_READ.
2297 			 * There is no need to keep walking the chain again and
2298 			 * keep re-marking all parents as LIVE_READ.
2299 			 * This case happens when the same register is read
2300 			 * multiple times without writes into it in-between.
2301 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2302 			 * then no need to set the weak REG_LIVE_READ32.
2303 			 */
2304 			break;
2305 		/* ... then we depend on parent's value */
2306 		parent->live |= flag;
2307 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2308 		if (flag == REG_LIVE_READ64)
2309 			parent->live &= ~REG_LIVE_READ32;
2310 		state = parent;
2311 		parent = state->parent;
2312 		writes = true;
2313 		cnt++;
2314 	}
2315 
2316 	if (env->longest_mark_read_walk < cnt)
2317 		env->longest_mark_read_walk = cnt;
2318 	return 0;
2319 }
2320 
2321 /* This function is supposed to be used by the following 32-bit optimization
2322  * code only. It returns TRUE if the source or destination register operates
2323  * on 64-bit, otherwise return FALSE.
2324  */
2325 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2326 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2327 {
2328 	u8 code, class, op;
2329 
2330 	code = insn->code;
2331 	class = BPF_CLASS(code);
2332 	op = BPF_OP(code);
2333 	if (class == BPF_JMP) {
2334 		/* BPF_EXIT for "main" will reach here. Return TRUE
2335 		 * conservatively.
2336 		 */
2337 		if (op == BPF_EXIT)
2338 			return true;
2339 		if (op == BPF_CALL) {
2340 			/* BPF to BPF call will reach here because of marking
2341 			 * caller saved clobber with DST_OP_NO_MARK for which we
2342 			 * don't care the register def because they are anyway
2343 			 * marked as NOT_INIT already.
2344 			 */
2345 			if (insn->src_reg == BPF_PSEUDO_CALL)
2346 				return false;
2347 			/* Helper call will reach here because of arg type
2348 			 * check, conservatively return TRUE.
2349 			 */
2350 			if (t == SRC_OP)
2351 				return true;
2352 
2353 			return false;
2354 		}
2355 	}
2356 
2357 	if (class == BPF_ALU64 || class == BPF_JMP ||
2358 	    /* BPF_END always use BPF_ALU class. */
2359 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2360 		return true;
2361 
2362 	if (class == BPF_ALU || class == BPF_JMP32)
2363 		return false;
2364 
2365 	if (class == BPF_LDX) {
2366 		if (t != SRC_OP)
2367 			return BPF_SIZE(code) == BPF_DW;
2368 		/* LDX source must be ptr. */
2369 		return true;
2370 	}
2371 
2372 	if (class == BPF_STX) {
2373 		/* BPF_STX (including atomic variants) has multiple source
2374 		 * operands, one of which is a ptr. Check whether the caller is
2375 		 * asking about it.
2376 		 */
2377 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2378 			return true;
2379 		return BPF_SIZE(code) == BPF_DW;
2380 	}
2381 
2382 	if (class == BPF_LD) {
2383 		u8 mode = BPF_MODE(code);
2384 
2385 		/* LD_IMM64 */
2386 		if (mode == BPF_IMM)
2387 			return true;
2388 
2389 		/* Both LD_IND and LD_ABS return 32-bit data. */
2390 		if (t != SRC_OP)
2391 			return  false;
2392 
2393 		/* Implicit ctx ptr. */
2394 		if (regno == BPF_REG_6)
2395 			return true;
2396 
2397 		/* Explicit source could be any width. */
2398 		return true;
2399 	}
2400 
2401 	if (class == BPF_ST)
2402 		/* The only source register for BPF_ST is a ptr. */
2403 		return true;
2404 
2405 	/* Conservatively return true at default. */
2406 	return true;
2407 }
2408 
2409 /* Return the regno defined by the insn, or -1. */
2410 static int insn_def_regno(const struct bpf_insn *insn)
2411 {
2412 	switch (BPF_CLASS(insn->code)) {
2413 	case BPF_JMP:
2414 	case BPF_JMP32:
2415 	case BPF_ST:
2416 		return -1;
2417 	case BPF_STX:
2418 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2419 		    (insn->imm & BPF_FETCH)) {
2420 			if (insn->imm == BPF_CMPXCHG)
2421 				return BPF_REG_0;
2422 			else
2423 				return insn->src_reg;
2424 		} else {
2425 			return -1;
2426 		}
2427 	default:
2428 		return insn->dst_reg;
2429 	}
2430 }
2431 
2432 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2433 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2434 {
2435 	int dst_reg = insn_def_regno(insn);
2436 
2437 	if (dst_reg == -1)
2438 		return false;
2439 
2440 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2441 }
2442 
2443 static void mark_insn_zext(struct bpf_verifier_env *env,
2444 			   struct bpf_reg_state *reg)
2445 {
2446 	s32 def_idx = reg->subreg_def;
2447 
2448 	if (def_idx == DEF_NOT_SUBREG)
2449 		return;
2450 
2451 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2452 	/* The dst will be zero extended, so won't be sub-register anymore. */
2453 	reg->subreg_def = DEF_NOT_SUBREG;
2454 }
2455 
2456 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2457 			 enum reg_arg_type t)
2458 {
2459 	struct bpf_verifier_state *vstate = env->cur_state;
2460 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2461 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2462 	struct bpf_reg_state *reg, *regs = state->regs;
2463 	bool rw64;
2464 
2465 	if (regno >= MAX_BPF_REG) {
2466 		verbose(env, "R%d is invalid\n", regno);
2467 		return -EINVAL;
2468 	}
2469 
2470 	mark_reg_scratched(env, regno);
2471 
2472 	reg = &regs[regno];
2473 	rw64 = is_reg64(env, insn, regno, reg, t);
2474 	if (t == SRC_OP) {
2475 		/* check whether register used as source operand can be read */
2476 		if (reg->type == NOT_INIT) {
2477 			verbose(env, "R%d !read_ok\n", regno);
2478 			return -EACCES;
2479 		}
2480 		/* We don't need to worry about FP liveness because it's read-only */
2481 		if (regno == BPF_REG_FP)
2482 			return 0;
2483 
2484 		if (rw64)
2485 			mark_insn_zext(env, reg);
2486 
2487 		return mark_reg_read(env, reg, reg->parent,
2488 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2489 	} else {
2490 		/* check whether register used as dest operand can be written to */
2491 		if (regno == BPF_REG_FP) {
2492 			verbose(env, "frame pointer is read only\n");
2493 			return -EACCES;
2494 		}
2495 		reg->live |= REG_LIVE_WRITTEN;
2496 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2497 		if (t == DST_OP)
2498 			mark_reg_unknown(env, regs, regno);
2499 	}
2500 	return 0;
2501 }
2502 
2503 /* for any branch, call, exit record the history of jmps in the given state */
2504 static int push_jmp_history(struct bpf_verifier_env *env,
2505 			    struct bpf_verifier_state *cur)
2506 {
2507 	u32 cnt = cur->jmp_history_cnt;
2508 	struct bpf_idx_pair *p;
2509 
2510 	cnt++;
2511 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2512 	if (!p)
2513 		return -ENOMEM;
2514 	p[cnt - 1].idx = env->insn_idx;
2515 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2516 	cur->jmp_history = p;
2517 	cur->jmp_history_cnt = cnt;
2518 	return 0;
2519 }
2520 
2521 /* Backtrack one insn at a time. If idx is not at the top of recorded
2522  * history then previous instruction came from straight line execution.
2523  */
2524 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2525 			     u32 *history)
2526 {
2527 	u32 cnt = *history;
2528 
2529 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2530 		i = st->jmp_history[cnt - 1].prev_idx;
2531 		(*history)--;
2532 	} else {
2533 		i--;
2534 	}
2535 	return i;
2536 }
2537 
2538 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2539 {
2540 	const struct btf_type *func;
2541 	struct btf *desc_btf;
2542 
2543 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2544 		return NULL;
2545 
2546 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2547 	if (IS_ERR(desc_btf))
2548 		return "<error>";
2549 
2550 	func = btf_type_by_id(desc_btf, insn->imm);
2551 	return btf_name_by_offset(desc_btf, func->name_off);
2552 }
2553 
2554 /* For given verifier state backtrack_insn() is called from the last insn to
2555  * the first insn. Its purpose is to compute a bitmask of registers and
2556  * stack slots that needs precision in the parent verifier state.
2557  */
2558 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2559 			  u32 *reg_mask, u64 *stack_mask)
2560 {
2561 	const struct bpf_insn_cbs cbs = {
2562 		.cb_call	= disasm_kfunc_name,
2563 		.cb_print	= verbose,
2564 		.private_data	= env,
2565 	};
2566 	struct bpf_insn *insn = env->prog->insnsi + idx;
2567 	u8 class = BPF_CLASS(insn->code);
2568 	u8 opcode = BPF_OP(insn->code);
2569 	u8 mode = BPF_MODE(insn->code);
2570 	u32 dreg = 1u << insn->dst_reg;
2571 	u32 sreg = 1u << insn->src_reg;
2572 	u32 spi;
2573 
2574 	if (insn->code == 0)
2575 		return 0;
2576 	if (env->log.level & BPF_LOG_LEVEL2) {
2577 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2578 		verbose(env, "%d: ", idx);
2579 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2580 	}
2581 
2582 	if (class == BPF_ALU || class == BPF_ALU64) {
2583 		if (!(*reg_mask & dreg))
2584 			return 0;
2585 		if (opcode == BPF_MOV) {
2586 			if (BPF_SRC(insn->code) == BPF_X) {
2587 				/* dreg = sreg
2588 				 * dreg needs precision after this insn
2589 				 * sreg needs precision before this insn
2590 				 */
2591 				*reg_mask &= ~dreg;
2592 				*reg_mask |= sreg;
2593 			} else {
2594 				/* dreg = K
2595 				 * dreg needs precision after this insn.
2596 				 * Corresponding register is already marked
2597 				 * as precise=true in this verifier state.
2598 				 * No further markings in parent are necessary
2599 				 */
2600 				*reg_mask &= ~dreg;
2601 			}
2602 		} else {
2603 			if (BPF_SRC(insn->code) == BPF_X) {
2604 				/* dreg += sreg
2605 				 * both dreg and sreg need precision
2606 				 * before this insn
2607 				 */
2608 				*reg_mask |= sreg;
2609 			} /* else dreg += K
2610 			   * dreg still needs precision before this insn
2611 			   */
2612 		}
2613 	} else if (class == BPF_LDX) {
2614 		if (!(*reg_mask & dreg))
2615 			return 0;
2616 		*reg_mask &= ~dreg;
2617 
2618 		/* scalars can only be spilled into stack w/o losing precision.
2619 		 * Load from any other memory can be zero extended.
2620 		 * The desire to keep that precision is already indicated
2621 		 * by 'precise' mark in corresponding register of this state.
2622 		 * No further tracking necessary.
2623 		 */
2624 		if (insn->src_reg != BPF_REG_FP)
2625 			return 0;
2626 
2627 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2628 		 * that [fp - off] slot contains scalar that needs to be
2629 		 * tracked with precision
2630 		 */
2631 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2632 		if (spi >= 64) {
2633 			verbose(env, "BUG spi %d\n", spi);
2634 			WARN_ONCE(1, "verifier backtracking bug");
2635 			return -EFAULT;
2636 		}
2637 		*stack_mask |= 1ull << spi;
2638 	} else if (class == BPF_STX || class == BPF_ST) {
2639 		if (*reg_mask & dreg)
2640 			/* stx & st shouldn't be using _scalar_ dst_reg
2641 			 * to access memory. It means backtracking
2642 			 * encountered a case of pointer subtraction.
2643 			 */
2644 			return -ENOTSUPP;
2645 		/* scalars can only be spilled into stack */
2646 		if (insn->dst_reg != BPF_REG_FP)
2647 			return 0;
2648 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2649 		if (spi >= 64) {
2650 			verbose(env, "BUG spi %d\n", spi);
2651 			WARN_ONCE(1, "verifier backtracking bug");
2652 			return -EFAULT;
2653 		}
2654 		if (!(*stack_mask & (1ull << spi)))
2655 			return 0;
2656 		*stack_mask &= ~(1ull << spi);
2657 		if (class == BPF_STX)
2658 			*reg_mask |= sreg;
2659 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2660 		if (opcode == BPF_CALL) {
2661 			if (insn->src_reg == BPF_PSEUDO_CALL)
2662 				return -ENOTSUPP;
2663 			/* BPF helpers that invoke callback subprogs are
2664 			 * equivalent to BPF_PSEUDO_CALL above
2665 			 */
2666 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2667 				return -ENOTSUPP;
2668 			/* regular helper call sets R0 */
2669 			*reg_mask &= ~1;
2670 			if (*reg_mask & 0x3f) {
2671 				/* if backtracing was looking for registers R1-R5
2672 				 * they should have been found already.
2673 				 */
2674 				verbose(env, "BUG regs %x\n", *reg_mask);
2675 				WARN_ONCE(1, "verifier backtracking bug");
2676 				return -EFAULT;
2677 			}
2678 		} else if (opcode == BPF_EXIT) {
2679 			return -ENOTSUPP;
2680 		}
2681 	} else if (class == BPF_LD) {
2682 		if (!(*reg_mask & dreg))
2683 			return 0;
2684 		*reg_mask &= ~dreg;
2685 		/* It's ld_imm64 or ld_abs or ld_ind.
2686 		 * For ld_imm64 no further tracking of precision
2687 		 * into parent is necessary
2688 		 */
2689 		if (mode == BPF_IND || mode == BPF_ABS)
2690 			/* to be analyzed */
2691 			return -ENOTSUPP;
2692 	}
2693 	return 0;
2694 }
2695 
2696 /* the scalar precision tracking algorithm:
2697  * . at the start all registers have precise=false.
2698  * . scalar ranges are tracked as normal through alu and jmp insns.
2699  * . once precise value of the scalar register is used in:
2700  *   .  ptr + scalar alu
2701  *   . if (scalar cond K|scalar)
2702  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2703  *   backtrack through the verifier states and mark all registers and
2704  *   stack slots with spilled constants that these scalar regisers
2705  *   should be precise.
2706  * . during state pruning two registers (or spilled stack slots)
2707  *   are equivalent if both are not precise.
2708  *
2709  * Note the verifier cannot simply walk register parentage chain,
2710  * since many different registers and stack slots could have been
2711  * used to compute single precise scalar.
2712  *
2713  * The approach of starting with precise=true for all registers and then
2714  * backtrack to mark a register as not precise when the verifier detects
2715  * that program doesn't care about specific value (e.g., when helper
2716  * takes register as ARG_ANYTHING parameter) is not safe.
2717  *
2718  * It's ok to walk single parentage chain of the verifier states.
2719  * It's possible that this backtracking will go all the way till 1st insn.
2720  * All other branches will be explored for needing precision later.
2721  *
2722  * The backtracking needs to deal with cases like:
2723  *   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)
2724  * r9 -= r8
2725  * r5 = r9
2726  * if r5 > 0x79f goto pc+7
2727  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2728  * r5 += 1
2729  * ...
2730  * call bpf_perf_event_output#25
2731  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2732  *
2733  * and this case:
2734  * r6 = 1
2735  * call foo // uses callee's r6 inside to compute r0
2736  * r0 += r6
2737  * if r0 == 0 goto
2738  *
2739  * to track above reg_mask/stack_mask needs to be independent for each frame.
2740  *
2741  * Also if parent's curframe > frame where backtracking started,
2742  * the verifier need to mark registers in both frames, otherwise callees
2743  * may incorrectly prune callers. This is similar to
2744  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2745  *
2746  * For now backtracking falls back into conservative marking.
2747  */
2748 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2749 				     struct bpf_verifier_state *st)
2750 {
2751 	struct bpf_func_state *func;
2752 	struct bpf_reg_state *reg;
2753 	int i, j;
2754 
2755 	/* big hammer: mark all scalars precise in this path.
2756 	 * pop_stack may still get !precise scalars.
2757 	 * We also skip current state and go straight to first parent state,
2758 	 * because precision markings in current non-checkpointed state are
2759 	 * not needed. See why in the comment in __mark_chain_precision below.
2760 	 */
2761 	for (st = st->parent; st; st = st->parent) {
2762 		for (i = 0; i <= st->curframe; i++) {
2763 			func = st->frame[i];
2764 			for (j = 0; j < BPF_REG_FP; j++) {
2765 				reg = &func->regs[j];
2766 				if (reg->type != SCALAR_VALUE)
2767 					continue;
2768 				reg->precise = true;
2769 			}
2770 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2771 				if (!is_spilled_reg(&func->stack[j]))
2772 					continue;
2773 				reg = &func->stack[j].spilled_ptr;
2774 				if (reg->type != SCALAR_VALUE)
2775 					continue;
2776 				reg->precise = true;
2777 			}
2778 		}
2779 	}
2780 }
2781 
2782 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2783 {
2784 	struct bpf_func_state *func;
2785 	struct bpf_reg_state *reg;
2786 	int i, j;
2787 
2788 	for (i = 0; i <= st->curframe; i++) {
2789 		func = st->frame[i];
2790 		for (j = 0; j < BPF_REG_FP; j++) {
2791 			reg = &func->regs[j];
2792 			if (reg->type != SCALAR_VALUE)
2793 				continue;
2794 			reg->precise = false;
2795 		}
2796 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2797 			if (!is_spilled_reg(&func->stack[j]))
2798 				continue;
2799 			reg = &func->stack[j].spilled_ptr;
2800 			if (reg->type != SCALAR_VALUE)
2801 				continue;
2802 			reg->precise = false;
2803 		}
2804 	}
2805 }
2806 
2807 /*
2808  * __mark_chain_precision() backtracks BPF program instruction sequence and
2809  * chain of verifier states making sure that register *regno* (if regno >= 0)
2810  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2811  * SCALARS, as well as any other registers and slots that contribute to
2812  * a tracked state of given registers/stack slots, depending on specific BPF
2813  * assembly instructions (see backtrack_insns() for exact instruction handling
2814  * logic). This backtracking relies on recorded jmp_history and is able to
2815  * traverse entire chain of parent states. This process ends only when all the
2816  * necessary registers/slots and their transitive dependencies are marked as
2817  * precise.
2818  *
2819  * One important and subtle aspect is that precise marks *do not matter* in
2820  * the currently verified state (current state). It is important to understand
2821  * why this is the case.
2822  *
2823  * First, note that current state is the state that is not yet "checkpointed",
2824  * i.e., it is not yet put into env->explored_states, and it has no children
2825  * states as well. It's ephemeral, and can end up either a) being discarded if
2826  * compatible explored state is found at some point or BPF_EXIT instruction is
2827  * reached or b) checkpointed and put into env->explored_states, branching out
2828  * into one or more children states.
2829  *
2830  * In the former case, precise markings in current state are completely
2831  * ignored by state comparison code (see regsafe() for details). Only
2832  * checkpointed ("old") state precise markings are important, and if old
2833  * state's register/slot is precise, regsafe() assumes current state's
2834  * register/slot as precise and checks value ranges exactly and precisely. If
2835  * states turn out to be compatible, current state's necessary precise
2836  * markings and any required parent states' precise markings are enforced
2837  * after the fact with propagate_precision() logic, after the fact. But it's
2838  * important to realize that in this case, even after marking current state
2839  * registers/slots as precise, we immediately discard current state. So what
2840  * actually matters is any of the precise markings propagated into current
2841  * state's parent states, which are always checkpointed (due to b) case above).
2842  * As such, for scenario a) it doesn't matter if current state has precise
2843  * markings set or not.
2844  *
2845  * Now, for the scenario b), checkpointing and forking into child(ren)
2846  * state(s). Note that before current state gets to checkpointing step, any
2847  * processed instruction always assumes precise SCALAR register/slot
2848  * knowledge: if precise value or range is useful to prune jump branch, BPF
2849  * verifier takes this opportunity enthusiastically. Similarly, when
2850  * register's value is used to calculate offset or memory address, exact
2851  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2852  * what we mentioned above about state comparison ignoring precise markings
2853  * during state comparison, BPF verifier ignores and also assumes precise
2854  * markings *at will* during instruction verification process. But as verifier
2855  * assumes precision, it also propagates any precision dependencies across
2856  * parent states, which are not yet finalized, so can be further restricted
2857  * based on new knowledge gained from restrictions enforced by their children
2858  * states. This is so that once those parent states are finalized, i.e., when
2859  * they have no more active children state, state comparison logic in
2860  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2861  * required for correctness.
2862  *
2863  * To build a bit more intuition, note also that once a state is checkpointed,
2864  * the path we took to get to that state is not important. This is crucial
2865  * property for state pruning. When state is checkpointed and finalized at
2866  * some instruction index, it can be correctly and safely used to "short
2867  * circuit" any *compatible* state that reaches exactly the same instruction
2868  * index. I.e., if we jumped to that instruction from a completely different
2869  * code path than original finalized state was derived from, it doesn't
2870  * matter, current state can be discarded because from that instruction
2871  * forward having a compatible state will ensure we will safely reach the
2872  * exit. States describe preconditions for further exploration, but completely
2873  * forget the history of how we got here.
2874  *
2875  * This also means that even if we needed precise SCALAR range to get to
2876  * finalized state, but from that point forward *that same* SCALAR register is
2877  * never used in a precise context (i.e., it's precise value is not needed for
2878  * correctness), it's correct and safe to mark such register as "imprecise"
2879  * (i.e., precise marking set to false). This is what we rely on when we do
2880  * not set precise marking in current state. If no child state requires
2881  * precision for any given SCALAR register, it's safe to dictate that it can
2882  * be imprecise. If any child state does require this register to be precise,
2883  * we'll mark it precise later retroactively during precise markings
2884  * propagation from child state to parent states.
2885  *
2886  * Skipping precise marking setting in current state is a mild version of
2887  * relying on the above observation. But we can utilize this property even
2888  * more aggressively by proactively forgetting any precise marking in the
2889  * current state (which we inherited from the parent state), right before we
2890  * checkpoint it and branch off into new child state. This is done by
2891  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2892  * finalized states which help in short circuiting more future states.
2893  */
2894 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2895 				  int spi)
2896 {
2897 	struct bpf_verifier_state *st = env->cur_state;
2898 	int first_idx = st->first_insn_idx;
2899 	int last_idx = env->insn_idx;
2900 	struct bpf_func_state *func;
2901 	struct bpf_reg_state *reg;
2902 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2903 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2904 	bool skip_first = true;
2905 	bool new_marks = false;
2906 	int i, err;
2907 
2908 	if (!env->bpf_capable)
2909 		return 0;
2910 
2911 	/* Do sanity checks against current state of register and/or stack
2912 	 * slot, but don't set precise flag in current state, as precision
2913 	 * tracking in the current state is unnecessary.
2914 	 */
2915 	func = st->frame[frame];
2916 	if (regno >= 0) {
2917 		reg = &func->regs[regno];
2918 		if (reg->type != SCALAR_VALUE) {
2919 			WARN_ONCE(1, "backtracing misuse");
2920 			return -EFAULT;
2921 		}
2922 		new_marks = true;
2923 	}
2924 
2925 	while (spi >= 0) {
2926 		if (!is_spilled_reg(&func->stack[spi])) {
2927 			stack_mask = 0;
2928 			break;
2929 		}
2930 		reg = &func->stack[spi].spilled_ptr;
2931 		if (reg->type != SCALAR_VALUE) {
2932 			stack_mask = 0;
2933 			break;
2934 		}
2935 		new_marks = true;
2936 		break;
2937 	}
2938 
2939 	if (!new_marks)
2940 		return 0;
2941 	if (!reg_mask && !stack_mask)
2942 		return 0;
2943 
2944 	for (;;) {
2945 		DECLARE_BITMAP(mask, 64);
2946 		u32 history = st->jmp_history_cnt;
2947 
2948 		if (env->log.level & BPF_LOG_LEVEL2)
2949 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2950 
2951 		if (last_idx < 0) {
2952 			/* we are at the entry into subprog, which
2953 			 * is expected for global funcs, but only if
2954 			 * requested precise registers are R1-R5
2955 			 * (which are global func's input arguments)
2956 			 */
2957 			if (st->curframe == 0 &&
2958 			    st->frame[0]->subprogno > 0 &&
2959 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
2960 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2961 				bitmap_from_u64(mask, reg_mask);
2962 				for_each_set_bit(i, mask, 32) {
2963 					reg = &st->frame[0]->regs[i];
2964 					if (reg->type != SCALAR_VALUE) {
2965 						reg_mask &= ~(1u << i);
2966 						continue;
2967 					}
2968 					reg->precise = true;
2969 				}
2970 				return 0;
2971 			}
2972 
2973 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2974 				st->frame[0]->subprogno, reg_mask, stack_mask);
2975 			WARN_ONCE(1, "verifier backtracking bug");
2976 			return -EFAULT;
2977 		}
2978 
2979 		for (i = last_idx;;) {
2980 			if (skip_first) {
2981 				err = 0;
2982 				skip_first = false;
2983 			} else {
2984 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2985 			}
2986 			if (err == -ENOTSUPP) {
2987 				mark_all_scalars_precise(env, st);
2988 				return 0;
2989 			} else if (err) {
2990 				return err;
2991 			}
2992 			if (!reg_mask && !stack_mask)
2993 				/* Found assignment(s) into tracked register in this state.
2994 				 * Since this state is already marked, just return.
2995 				 * Nothing to be tracked further in the parent state.
2996 				 */
2997 				return 0;
2998 			if (i == first_idx)
2999 				break;
3000 			i = get_prev_insn_idx(st, i, &history);
3001 			if (i >= env->prog->len) {
3002 				/* This can happen if backtracking reached insn 0
3003 				 * and there are still reg_mask or stack_mask
3004 				 * to backtrack.
3005 				 * It means the backtracking missed the spot where
3006 				 * particular register was initialized with a constant.
3007 				 */
3008 				verbose(env, "BUG backtracking idx %d\n", i);
3009 				WARN_ONCE(1, "verifier backtracking bug");
3010 				return -EFAULT;
3011 			}
3012 		}
3013 		st = st->parent;
3014 		if (!st)
3015 			break;
3016 
3017 		new_marks = false;
3018 		func = st->frame[frame];
3019 		bitmap_from_u64(mask, reg_mask);
3020 		for_each_set_bit(i, mask, 32) {
3021 			reg = &func->regs[i];
3022 			if (reg->type != SCALAR_VALUE) {
3023 				reg_mask &= ~(1u << i);
3024 				continue;
3025 			}
3026 			if (!reg->precise)
3027 				new_marks = true;
3028 			reg->precise = true;
3029 		}
3030 
3031 		bitmap_from_u64(mask, stack_mask);
3032 		for_each_set_bit(i, mask, 64) {
3033 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3034 				/* the sequence of instructions:
3035 				 * 2: (bf) r3 = r10
3036 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3037 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3038 				 * doesn't contain jmps. It's backtracked
3039 				 * as a single block.
3040 				 * During backtracking insn 3 is not recognized as
3041 				 * stack access, so at the end of backtracking
3042 				 * stack slot fp-8 is still marked in stack_mask.
3043 				 * However the parent state may not have accessed
3044 				 * fp-8 and it's "unallocated" stack space.
3045 				 * In such case fallback to conservative.
3046 				 */
3047 				mark_all_scalars_precise(env, st);
3048 				return 0;
3049 			}
3050 
3051 			if (!is_spilled_reg(&func->stack[i])) {
3052 				stack_mask &= ~(1ull << i);
3053 				continue;
3054 			}
3055 			reg = &func->stack[i].spilled_ptr;
3056 			if (reg->type != SCALAR_VALUE) {
3057 				stack_mask &= ~(1ull << i);
3058 				continue;
3059 			}
3060 			if (!reg->precise)
3061 				new_marks = true;
3062 			reg->precise = true;
3063 		}
3064 		if (env->log.level & BPF_LOG_LEVEL2) {
3065 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3066 				new_marks ? "didn't have" : "already had",
3067 				reg_mask, stack_mask);
3068 			print_verifier_state(env, func, true);
3069 		}
3070 
3071 		if (!reg_mask && !stack_mask)
3072 			break;
3073 		if (!new_marks)
3074 			break;
3075 
3076 		last_idx = st->last_insn_idx;
3077 		first_idx = st->first_insn_idx;
3078 	}
3079 	return 0;
3080 }
3081 
3082 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3083 {
3084 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3085 }
3086 
3087 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3088 {
3089 	return __mark_chain_precision(env, frame, regno, -1);
3090 }
3091 
3092 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3093 {
3094 	return __mark_chain_precision(env, frame, -1, spi);
3095 }
3096 
3097 static bool is_spillable_regtype(enum bpf_reg_type type)
3098 {
3099 	switch (base_type(type)) {
3100 	case PTR_TO_MAP_VALUE:
3101 	case PTR_TO_STACK:
3102 	case PTR_TO_CTX:
3103 	case PTR_TO_PACKET:
3104 	case PTR_TO_PACKET_META:
3105 	case PTR_TO_PACKET_END:
3106 	case PTR_TO_FLOW_KEYS:
3107 	case CONST_PTR_TO_MAP:
3108 	case PTR_TO_SOCKET:
3109 	case PTR_TO_SOCK_COMMON:
3110 	case PTR_TO_TCP_SOCK:
3111 	case PTR_TO_XDP_SOCK:
3112 	case PTR_TO_BTF_ID:
3113 	case PTR_TO_BUF:
3114 	case PTR_TO_MEM:
3115 	case PTR_TO_FUNC:
3116 	case PTR_TO_MAP_KEY:
3117 		return true;
3118 	default:
3119 		return false;
3120 	}
3121 }
3122 
3123 /* Does this register contain a constant zero? */
3124 static bool register_is_null(struct bpf_reg_state *reg)
3125 {
3126 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3127 }
3128 
3129 static bool register_is_const(struct bpf_reg_state *reg)
3130 {
3131 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3132 }
3133 
3134 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3135 {
3136 	return tnum_is_unknown(reg->var_off) &&
3137 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3138 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3139 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3140 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3141 }
3142 
3143 static bool register_is_bounded(struct bpf_reg_state *reg)
3144 {
3145 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3146 }
3147 
3148 static bool __is_pointer_value(bool allow_ptr_leaks,
3149 			       const struct bpf_reg_state *reg)
3150 {
3151 	if (allow_ptr_leaks)
3152 		return false;
3153 
3154 	return reg->type != SCALAR_VALUE;
3155 }
3156 
3157 static void save_register_state(struct bpf_func_state *state,
3158 				int spi, struct bpf_reg_state *reg,
3159 				int size)
3160 {
3161 	int i;
3162 
3163 	state->stack[spi].spilled_ptr = *reg;
3164 	if (size == BPF_REG_SIZE)
3165 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3166 
3167 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3168 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3169 
3170 	/* size < 8 bytes spill */
3171 	for (; i; i--)
3172 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3173 }
3174 
3175 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3176  * stack boundary and alignment are checked in check_mem_access()
3177  */
3178 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3179 				       /* stack frame we're writing to */
3180 				       struct bpf_func_state *state,
3181 				       int off, int size, int value_regno,
3182 				       int insn_idx)
3183 {
3184 	struct bpf_func_state *cur; /* state of the current function */
3185 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3186 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3187 	struct bpf_reg_state *reg = NULL;
3188 
3189 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3190 	if (err)
3191 		return err;
3192 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3193 	 * so it's aligned access and [off, off + size) are within stack limits
3194 	 */
3195 	if (!env->allow_ptr_leaks &&
3196 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3197 	    size != BPF_REG_SIZE) {
3198 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3199 		return -EACCES;
3200 	}
3201 
3202 	cur = env->cur_state->frame[env->cur_state->curframe];
3203 	if (value_regno >= 0)
3204 		reg = &cur->regs[value_regno];
3205 	if (!env->bypass_spec_v4) {
3206 		bool sanitize = reg && is_spillable_regtype(reg->type);
3207 
3208 		for (i = 0; i < size; i++) {
3209 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3210 				sanitize = true;
3211 				break;
3212 			}
3213 		}
3214 
3215 		if (sanitize)
3216 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3217 	}
3218 
3219 	mark_stack_slot_scratched(env, spi);
3220 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3221 	    !register_is_null(reg) && env->bpf_capable) {
3222 		if (dst_reg != BPF_REG_FP) {
3223 			/* The backtracking logic can only recognize explicit
3224 			 * stack slot address like [fp - 8]. Other spill of
3225 			 * scalar via different register has to be conservative.
3226 			 * Backtrack from here and mark all registers as precise
3227 			 * that contributed into 'reg' being a constant.
3228 			 */
3229 			err = mark_chain_precision(env, value_regno);
3230 			if (err)
3231 				return err;
3232 		}
3233 		save_register_state(state, spi, reg, size);
3234 	} else if (reg && is_spillable_regtype(reg->type)) {
3235 		/* register containing pointer is being spilled into stack */
3236 		if (size != BPF_REG_SIZE) {
3237 			verbose_linfo(env, insn_idx, "; ");
3238 			verbose(env, "invalid size of register spill\n");
3239 			return -EACCES;
3240 		}
3241 		if (state != cur && reg->type == PTR_TO_STACK) {
3242 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3243 			return -EINVAL;
3244 		}
3245 		save_register_state(state, spi, reg, size);
3246 	} else {
3247 		u8 type = STACK_MISC;
3248 
3249 		/* regular write of data into stack destroys any spilled ptr */
3250 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3251 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3252 		if (is_spilled_reg(&state->stack[spi]))
3253 			for (i = 0; i < BPF_REG_SIZE; i++)
3254 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3255 
3256 		/* only mark the slot as written if all 8 bytes were written
3257 		 * otherwise read propagation may incorrectly stop too soon
3258 		 * when stack slots are partially written.
3259 		 * This heuristic means that read propagation will be
3260 		 * conservative, since it will add reg_live_read marks
3261 		 * to stack slots all the way to first state when programs
3262 		 * writes+reads less than 8 bytes
3263 		 */
3264 		if (size == BPF_REG_SIZE)
3265 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3266 
3267 		/* when we zero initialize stack slots mark them as such */
3268 		if (reg && register_is_null(reg)) {
3269 			/* backtracking doesn't work for STACK_ZERO yet. */
3270 			err = mark_chain_precision(env, value_regno);
3271 			if (err)
3272 				return err;
3273 			type = STACK_ZERO;
3274 		}
3275 
3276 		/* Mark slots affected by this stack write. */
3277 		for (i = 0; i < size; i++)
3278 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3279 				type;
3280 	}
3281 	return 0;
3282 }
3283 
3284 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3285  * known to contain a variable offset.
3286  * This function checks whether the write is permitted and conservatively
3287  * tracks the effects of the write, considering that each stack slot in the
3288  * dynamic range is potentially written to.
3289  *
3290  * 'off' includes 'regno->off'.
3291  * 'value_regno' can be -1, meaning that an unknown value is being written to
3292  * the stack.
3293  *
3294  * Spilled pointers in range are not marked as written because we don't know
3295  * what's going to be actually written. This means that read propagation for
3296  * future reads cannot be terminated by this write.
3297  *
3298  * For privileged programs, uninitialized stack slots are considered
3299  * initialized by this write (even though we don't know exactly what offsets
3300  * are going to be written to). The idea is that we don't want the verifier to
3301  * reject future reads that access slots written to through variable offsets.
3302  */
3303 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3304 				     /* func where register points to */
3305 				     struct bpf_func_state *state,
3306 				     int ptr_regno, int off, int size,
3307 				     int value_regno, int insn_idx)
3308 {
3309 	struct bpf_func_state *cur; /* state of the current function */
3310 	int min_off, max_off;
3311 	int i, err;
3312 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3313 	bool writing_zero = false;
3314 	/* set if the fact that we're writing a zero is used to let any
3315 	 * stack slots remain STACK_ZERO
3316 	 */
3317 	bool zero_used = false;
3318 
3319 	cur = env->cur_state->frame[env->cur_state->curframe];
3320 	ptr_reg = &cur->regs[ptr_regno];
3321 	min_off = ptr_reg->smin_value + off;
3322 	max_off = ptr_reg->smax_value + off + size;
3323 	if (value_regno >= 0)
3324 		value_reg = &cur->regs[value_regno];
3325 	if (value_reg && register_is_null(value_reg))
3326 		writing_zero = true;
3327 
3328 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3329 	if (err)
3330 		return err;
3331 
3332 
3333 	/* Variable offset writes destroy any spilled pointers in range. */
3334 	for (i = min_off; i < max_off; i++) {
3335 		u8 new_type, *stype;
3336 		int slot, spi;
3337 
3338 		slot = -i - 1;
3339 		spi = slot / BPF_REG_SIZE;
3340 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3341 		mark_stack_slot_scratched(env, spi);
3342 
3343 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3344 			/* Reject the write if range we may write to has not
3345 			 * been initialized beforehand. If we didn't reject
3346 			 * here, the ptr status would be erased below (even
3347 			 * though not all slots are actually overwritten),
3348 			 * possibly opening the door to leaks.
3349 			 *
3350 			 * We do however catch STACK_INVALID case below, and
3351 			 * only allow reading possibly uninitialized memory
3352 			 * later for CAP_PERFMON, as the write may not happen to
3353 			 * that slot.
3354 			 */
3355 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3356 				insn_idx, i);
3357 			return -EINVAL;
3358 		}
3359 
3360 		/* Erase all spilled pointers. */
3361 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3362 
3363 		/* Update the slot type. */
3364 		new_type = STACK_MISC;
3365 		if (writing_zero && *stype == STACK_ZERO) {
3366 			new_type = STACK_ZERO;
3367 			zero_used = true;
3368 		}
3369 		/* If the slot is STACK_INVALID, we check whether it's OK to
3370 		 * pretend that it will be initialized by this write. The slot
3371 		 * might not actually be written to, and so if we mark it as
3372 		 * initialized future reads might leak uninitialized memory.
3373 		 * For privileged programs, we will accept such reads to slots
3374 		 * that may or may not be written because, if we're reject
3375 		 * them, the error would be too confusing.
3376 		 */
3377 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3378 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3379 					insn_idx, i);
3380 			return -EINVAL;
3381 		}
3382 		*stype = new_type;
3383 	}
3384 	if (zero_used) {
3385 		/* backtracking doesn't work for STACK_ZERO yet. */
3386 		err = mark_chain_precision(env, value_regno);
3387 		if (err)
3388 			return err;
3389 	}
3390 	return 0;
3391 }
3392 
3393 /* When register 'dst_regno' is assigned some values from stack[min_off,
3394  * max_off), we set the register's type according to the types of the
3395  * respective stack slots. If all the stack values are known to be zeros, then
3396  * so is the destination reg. Otherwise, the register is considered to be
3397  * SCALAR. This function does not deal with register filling; the caller must
3398  * ensure that all spilled registers in the stack range have been marked as
3399  * read.
3400  */
3401 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3402 				/* func where src register points to */
3403 				struct bpf_func_state *ptr_state,
3404 				int min_off, int max_off, int dst_regno)
3405 {
3406 	struct bpf_verifier_state *vstate = env->cur_state;
3407 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3408 	int i, slot, spi;
3409 	u8 *stype;
3410 	int zeros = 0;
3411 
3412 	for (i = min_off; i < max_off; i++) {
3413 		slot = -i - 1;
3414 		spi = slot / BPF_REG_SIZE;
3415 		stype = ptr_state->stack[spi].slot_type;
3416 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3417 			break;
3418 		zeros++;
3419 	}
3420 	if (zeros == max_off - min_off) {
3421 		/* any access_size read into register is zero extended,
3422 		 * so the whole register == const_zero
3423 		 */
3424 		__mark_reg_const_zero(&state->regs[dst_regno]);
3425 		/* backtracking doesn't support STACK_ZERO yet,
3426 		 * so mark it precise here, so that later
3427 		 * backtracking can stop here.
3428 		 * Backtracking may not need this if this register
3429 		 * doesn't participate in pointer adjustment.
3430 		 * Forward propagation of precise flag is not
3431 		 * necessary either. This mark is only to stop
3432 		 * backtracking. Any register that contributed
3433 		 * to const 0 was marked precise before spill.
3434 		 */
3435 		state->regs[dst_regno].precise = true;
3436 	} else {
3437 		/* have read misc data from the stack */
3438 		mark_reg_unknown(env, state->regs, dst_regno);
3439 	}
3440 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3441 }
3442 
3443 /* Read the stack at 'off' and put the results into the register indicated by
3444  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3445  * spilled reg.
3446  *
3447  * 'dst_regno' can be -1, meaning that the read value is not going to a
3448  * register.
3449  *
3450  * The access is assumed to be within the current stack bounds.
3451  */
3452 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3453 				      /* func where src register points to */
3454 				      struct bpf_func_state *reg_state,
3455 				      int off, int size, int dst_regno)
3456 {
3457 	struct bpf_verifier_state *vstate = env->cur_state;
3458 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3459 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3460 	struct bpf_reg_state *reg;
3461 	u8 *stype, type;
3462 
3463 	stype = reg_state->stack[spi].slot_type;
3464 	reg = &reg_state->stack[spi].spilled_ptr;
3465 
3466 	if (is_spilled_reg(&reg_state->stack[spi])) {
3467 		u8 spill_size = 1;
3468 
3469 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3470 			spill_size++;
3471 
3472 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3473 			if (reg->type != SCALAR_VALUE) {
3474 				verbose_linfo(env, env->insn_idx, "; ");
3475 				verbose(env, "invalid size of register fill\n");
3476 				return -EACCES;
3477 			}
3478 
3479 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3480 			if (dst_regno < 0)
3481 				return 0;
3482 
3483 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3484 				/* The earlier check_reg_arg() has decided the
3485 				 * subreg_def for this insn.  Save it first.
3486 				 */
3487 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3488 
3489 				state->regs[dst_regno] = *reg;
3490 				state->regs[dst_regno].subreg_def = subreg_def;
3491 			} else {
3492 				for (i = 0; i < size; i++) {
3493 					type = stype[(slot - i) % BPF_REG_SIZE];
3494 					if (type == STACK_SPILL)
3495 						continue;
3496 					if (type == STACK_MISC)
3497 						continue;
3498 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3499 						off, i, size);
3500 					return -EACCES;
3501 				}
3502 				mark_reg_unknown(env, state->regs, dst_regno);
3503 			}
3504 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3505 			return 0;
3506 		}
3507 
3508 		if (dst_regno >= 0) {
3509 			/* restore register state from stack */
3510 			state->regs[dst_regno] = *reg;
3511 			/* mark reg as written since spilled pointer state likely
3512 			 * has its liveness marks cleared by is_state_visited()
3513 			 * which resets stack/reg liveness for state transitions
3514 			 */
3515 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3516 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3517 			/* If dst_regno==-1, the caller is asking us whether
3518 			 * it is acceptable to use this value as a SCALAR_VALUE
3519 			 * (e.g. for XADD).
3520 			 * We must not allow unprivileged callers to do that
3521 			 * with spilled pointers.
3522 			 */
3523 			verbose(env, "leaking pointer from stack off %d\n",
3524 				off);
3525 			return -EACCES;
3526 		}
3527 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3528 	} else {
3529 		for (i = 0; i < size; i++) {
3530 			type = stype[(slot - i) % BPF_REG_SIZE];
3531 			if (type == STACK_MISC)
3532 				continue;
3533 			if (type == STACK_ZERO)
3534 				continue;
3535 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3536 				off, i, size);
3537 			return -EACCES;
3538 		}
3539 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3540 		if (dst_regno >= 0)
3541 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3542 	}
3543 	return 0;
3544 }
3545 
3546 enum bpf_access_src {
3547 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3548 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3549 };
3550 
3551 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3552 					 int regno, int off, int access_size,
3553 					 bool zero_size_allowed,
3554 					 enum bpf_access_src type,
3555 					 struct bpf_call_arg_meta *meta);
3556 
3557 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3558 {
3559 	return cur_regs(env) + regno;
3560 }
3561 
3562 /* Read the stack at 'ptr_regno + off' and put the result into the register
3563  * 'dst_regno'.
3564  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3565  * but not its variable offset.
3566  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3567  *
3568  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3569  * filling registers (i.e. reads of spilled register cannot be detected when
3570  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3571  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3572  * offset; for a fixed offset check_stack_read_fixed_off should be used
3573  * instead.
3574  */
3575 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3576 				    int ptr_regno, int off, int size, int dst_regno)
3577 {
3578 	/* The state of the source register. */
3579 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3580 	struct bpf_func_state *ptr_state = func(env, reg);
3581 	int err;
3582 	int min_off, max_off;
3583 
3584 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3585 	 */
3586 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3587 					    false, ACCESS_DIRECT, NULL);
3588 	if (err)
3589 		return err;
3590 
3591 	min_off = reg->smin_value + off;
3592 	max_off = reg->smax_value + off;
3593 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3594 	return 0;
3595 }
3596 
3597 /* check_stack_read dispatches to check_stack_read_fixed_off or
3598  * check_stack_read_var_off.
3599  *
3600  * The caller must ensure that the offset falls within the allocated stack
3601  * bounds.
3602  *
3603  * 'dst_regno' is a register which will receive the value from the stack. It
3604  * can be -1, meaning that the read value is not going to a register.
3605  */
3606 static int check_stack_read(struct bpf_verifier_env *env,
3607 			    int ptr_regno, int off, int size,
3608 			    int dst_regno)
3609 {
3610 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3611 	struct bpf_func_state *state = func(env, reg);
3612 	int err;
3613 	/* Some accesses are only permitted with a static offset. */
3614 	bool var_off = !tnum_is_const(reg->var_off);
3615 
3616 	/* The offset is required to be static when reads don't go to a
3617 	 * register, in order to not leak pointers (see
3618 	 * check_stack_read_fixed_off).
3619 	 */
3620 	if (dst_regno < 0 && var_off) {
3621 		char tn_buf[48];
3622 
3623 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3624 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3625 			tn_buf, off, size);
3626 		return -EACCES;
3627 	}
3628 	/* Variable offset is prohibited for unprivileged mode for simplicity
3629 	 * since it requires corresponding support in Spectre masking for stack
3630 	 * ALU. See also retrieve_ptr_limit().
3631 	 */
3632 	if (!env->bypass_spec_v1 && var_off) {
3633 		char tn_buf[48];
3634 
3635 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3636 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3637 				ptr_regno, tn_buf);
3638 		return -EACCES;
3639 	}
3640 
3641 	if (!var_off) {
3642 		off += reg->var_off.value;
3643 		err = check_stack_read_fixed_off(env, state, off, size,
3644 						 dst_regno);
3645 	} else {
3646 		/* Variable offset stack reads need more conservative handling
3647 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3648 		 * branch.
3649 		 */
3650 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3651 					       dst_regno);
3652 	}
3653 	return err;
3654 }
3655 
3656 
3657 /* check_stack_write dispatches to check_stack_write_fixed_off or
3658  * check_stack_write_var_off.
3659  *
3660  * 'ptr_regno' is the register used as a pointer into the stack.
3661  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3662  * 'value_regno' is the register whose value we're writing to the stack. It can
3663  * be -1, meaning that we're not writing from a register.
3664  *
3665  * The caller must ensure that the offset falls within the maximum stack size.
3666  */
3667 static int check_stack_write(struct bpf_verifier_env *env,
3668 			     int ptr_regno, int off, int size,
3669 			     int value_regno, int insn_idx)
3670 {
3671 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3672 	struct bpf_func_state *state = func(env, reg);
3673 	int err;
3674 
3675 	if (tnum_is_const(reg->var_off)) {
3676 		off += reg->var_off.value;
3677 		err = check_stack_write_fixed_off(env, state, off, size,
3678 						  value_regno, insn_idx);
3679 	} else {
3680 		/* Variable offset stack reads need more conservative handling
3681 		 * than fixed offset ones.
3682 		 */
3683 		err = check_stack_write_var_off(env, state,
3684 						ptr_regno, off, size,
3685 						value_regno, insn_idx);
3686 	}
3687 	return err;
3688 }
3689 
3690 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3691 				 int off, int size, enum bpf_access_type type)
3692 {
3693 	struct bpf_reg_state *regs = cur_regs(env);
3694 	struct bpf_map *map = regs[regno].map_ptr;
3695 	u32 cap = bpf_map_flags_to_cap(map);
3696 
3697 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3698 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3699 			map->value_size, off, size);
3700 		return -EACCES;
3701 	}
3702 
3703 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3704 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3705 			map->value_size, off, size);
3706 		return -EACCES;
3707 	}
3708 
3709 	return 0;
3710 }
3711 
3712 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3713 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3714 			      int off, int size, u32 mem_size,
3715 			      bool zero_size_allowed)
3716 {
3717 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3718 	struct bpf_reg_state *reg;
3719 
3720 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3721 		return 0;
3722 
3723 	reg = &cur_regs(env)[regno];
3724 	switch (reg->type) {
3725 	case PTR_TO_MAP_KEY:
3726 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3727 			mem_size, off, size);
3728 		break;
3729 	case PTR_TO_MAP_VALUE:
3730 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3731 			mem_size, off, size);
3732 		break;
3733 	case PTR_TO_PACKET:
3734 	case PTR_TO_PACKET_META:
3735 	case PTR_TO_PACKET_END:
3736 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3737 			off, size, regno, reg->id, off, mem_size);
3738 		break;
3739 	case PTR_TO_MEM:
3740 	default:
3741 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3742 			mem_size, off, size);
3743 	}
3744 
3745 	return -EACCES;
3746 }
3747 
3748 /* check read/write into a memory region with possible variable offset */
3749 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3750 				   int off, int size, u32 mem_size,
3751 				   bool zero_size_allowed)
3752 {
3753 	struct bpf_verifier_state *vstate = env->cur_state;
3754 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3755 	struct bpf_reg_state *reg = &state->regs[regno];
3756 	int err;
3757 
3758 	/* We may have adjusted the register pointing to memory region, so we
3759 	 * need to try adding each of min_value and max_value to off
3760 	 * to make sure our theoretical access will be safe.
3761 	 *
3762 	 * The minimum value is only important with signed
3763 	 * comparisons where we can't assume the floor of a
3764 	 * value is 0.  If we are using signed variables for our
3765 	 * index'es we need to make sure that whatever we use
3766 	 * will have a set floor within our range.
3767 	 */
3768 	if (reg->smin_value < 0 &&
3769 	    (reg->smin_value == S64_MIN ||
3770 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3771 	      reg->smin_value + off < 0)) {
3772 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3773 			regno);
3774 		return -EACCES;
3775 	}
3776 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3777 				 mem_size, zero_size_allowed);
3778 	if (err) {
3779 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3780 			regno);
3781 		return err;
3782 	}
3783 
3784 	/* If we haven't set a max value then we need to bail since we can't be
3785 	 * sure we won't do bad things.
3786 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3787 	 */
3788 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3789 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3790 			regno);
3791 		return -EACCES;
3792 	}
3793 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3794 				 mem_size, zero_size_allowed);
3795 	if (err) {
3796 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3797 			regno);
3798 		return err;
3799 	}
3800 
3801 	return 0;
3802 }
3803 
3804 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3805 			       const struct bpf_reg_state *reg, int regno,
3806 			       bool fixed_off_ok)
3807 {
3808 	/* Access to this pointer-typed register or passing it to a helper
3809 	 * is only allowed in its original, unmodified form.
3810 	 */
3811 
3812 	if (reg->off < 0) {
3813 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3814 			reg_type_str(env, reg->type), regno, reg->off);
3815 		return -EACCES;
3816 	}
3817 
3818 	if (!fixed_off_ok && reg->off) {
3819 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3820 			reg_type_str(env, reg->type), regno, reg->off);
3821 		return -EACCES;
3822 	}
3823 
3824 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3825 		char tn_buf[48];
3826 
3827 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3828 		verbose(env, "variable %s access var_off=%s disallowed\n",
3829 			reg_type_str(env, reg->type), tn_buf);
3830 		return -EACCES;
3831 	}
3832 
3833 	return 0;
3834 }
3835 
3836 int check_ptr_off_reg(struct bpf_verifier_env *env,
3837 		      const struct bpf_reg_state *reg, int regno)
3838 {
3839 	return __check_ptr_off_reg(env, reg, regno, false);
3840 }
3841 
3842 static int map_kptr_match_type(struct bpf_verifier_env *env,
3843 			       struct btf_field *kptr_field,
3844 			       struct bpf_reg_state *reg, u32 regno)
3845 {
3846 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3847 	int perm_flags = PTR_MAYBE_NULL;
3848 	const char *reg_name = "";
3849 
3850 	/* Only unreferenced case accepts untrusted pointers */
3851 	if (kptr_field->type == BPF_KPTR_UNREF)
3852 		perm_flags |= PTR_UNTRUSTED;
3853 
3854 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3855 		goto bad_type;
3856 
3857 	if (!btf_is_kernel(reg->btf)) {
3858 		verbose(env, "R%d must point to kernel BTF\n", regno);
3859 		return -EINVAL;
3860 	}
3861 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3862 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3863 
3864 	/* For ref_ptr case, release function check should ensure we get one
3865 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3866 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3867 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3868 	 * reg->off and reg->ref_obj_id are not needed here.
3869 	 */
3870 	if (__check_ptr_off_reg(env, reg, regno, true))
3871 		return -EACCES;
3872 
3873 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3874 	 * we also need to take into account the reg->off.
3875 	 *
3876 	 * We want to support cases like:
3877 	 *
3878 	 * struct foo {
3879 	 *         struct bar br;
3880 	 *         struct baz bz;
3881 	 * };
3882 	 *
3883 	 * struct foo *v;
3884 	 * v = func();	      // PTR_TO_BTF_ID
3885 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3886 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3887 	 *                    // first member type of struct after comparison fails
3888 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3889 	 *                    // to match type
3890 	 *
3891 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3892 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3893 	 * the struct to match type against first member of struct, i.e. reject
3894 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3895 	 * strict mode to true for type match.
3896 	 */
3897 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3898 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3899 				  kptr_field->type == BPF_KPTR_REF))
3900 		goto bad_type;
3901 	return 0;
3902 bad_type:
3903 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3904 		reg_type_str(env, reg->type), reg_name);
3905 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3906 	if (kptr_field->type == BPF_KPTR_UNREF)
3907 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3908 			targ_name);
3909 	else
3910 		verbose(env, "\n");
3911 	return -EINVAL;
3912 }
3913 
3914 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3915 				 int value_regno, int insn_idx,
3916 				 struct btf_field *kptr_field)
3917 {
3918 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3919 	int class = BPF_CLASS(insn->code);
3920 	struct bpf_reg_state *val_reg;
3921 
3922 	/* Things we already checked for in check_map_access and caller:
3923 	 *  - Reject cases where variable offset may touch kptr
3924 	 *  - size of access (must be BPF_DW)
3925 	 *  - tnum_is_const(reg->var_off)
3926 	 *  - kptr_field->offset == off + reg->var_off.value
3927 	 */
3928 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3929 	if (BPF_MODE(insn->code) != BPF_MEM) {
3930 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3931 		return -EACCES;
3932 	}
3933 
3934 	/* We only allow loading referenced kptr, since it will be marked as
3935 	 * untrusted, similar to unreferenced kptr.
3936 	 */
3937 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
3938 		verbose(env, "store to referenced kptr disallowed\n");
3939 		return -EACCES;
3940 	}
3941 
3942 	if (class == BPF_LDX) {
3943 		val_reg = reg_state(env, value_regno);
3944 		/* We can simply mark the value_regno receiving the pointer
3945 		 * value from map as PTR_TO_BTF_ID, with the correct type.
3946 		 */
3947 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
3948 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3949 		/* For mark_ptr_or_null_reg */
3950 		val_reg->id = ++env->id_gen;
3951 	} else if (class == BPF_STX) {
3952 		val_reg = reg_state(env, value_regno);
3953 		if (!register_is_null(val_reg) &&
3954 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
3955 			return -EACCES;
3956 	} else if (class == BPF_ST) {
3957 		if (insn->imm) {
3958 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3959 				kptr_field->offset);
3960 			return -EACCES;
3961 		}
3962 	} else {
3963 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3964 		return -EACCES;
3965 	}
3966 	return 0;
3967 }
3968 
3969 /* check read/write into a map element with possible variable offset */
3970 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3971 			    int off, int size, bool zero_size_allowed,
3972 			    enum bpf_access_src src)
3973 {
3974 	struct bpf_verifier_state *vstate = env->cur_state;
3975 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3976 	struct bpf_reg_state *reg = &state->regs[regno];
3977 	struct bpf_map *map = reg->map_ptr;
3978 	struct btf_record *rec;
3979 	int err, i;
3980 
3981 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3982 				      zero_size_allowed);
3983 	if (err)
3984 		return err;
3985 
3986 	if (IS_ERR_OR_NULL(map->record))
3987 		return 0;
3988 	rec = map->record;
3989 	for (i = 0; i < rec->cnt; i++) {
3990 		struct btf_field *field = &rec->fields[i];
3991 		u32 p = field->offset;
3992 
3993 		/* If any part of a field  can be touched by load/store, reject
3994 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
3995 		 * it is sufficient to check x1 < y2 && y1 < x2.
3996 		 */
3997 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
3998 		    p < reg->umax_value + off + size) {
3999 			switch (field->type) {
4000 			case BPF_KPTR_UNREF:
4001 			case BPF_KPTR_REF:
4002 				if (src != ACCESS_DIRECT) {
4003 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4004 					return -EACCES;
4005 				}
4006 				if (!tnum_is_const(reg->var_off)) {
4007 					verbose(env, "kptr access cannot have variable offset\n");
4008 					return -EACCES;
4009 				}
4010 				if (p != off + reg->var_off.value) {
4011 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4012 						p, off + reg->var_off.value);
4013 					return -EACCES;
4014 				}
4015 				if (size != bpf_size_to_bytes(BPF_DW)) {
4016 					verbose(env, "kptr access size must be BPF_DW\n");
4017 					return -EACCES;
4018 				}
4019 				break;
4020 			default:
4021 				verbose(env, "%s cannot be accessed directly by load/store\n",
4022 					btf_field_type_name(field->type));
4023 				return -EACCES;
4024 			}
4025 		}
4026 	}
4027 	return 0;
4028 }
4029 
4030 #define MAX_PACKET_OFF 0xffff
4031 
4032 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4033 				       const struct bpf_call_arg_meta *meta,
4034 				       enum bpf_access_type t)
4035 {
4036 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4037 
4038 	switch (prog_type) {
4039 	/* Program types only with direct read access go here! */
4040 	case BPF_PROG_TYPE_LWT_IN:
4041 	case BPF_PROG_TYPE_LWT_OUT:
4042 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4043 	case BPF_PROG_TYPE_SK_REUSEPORT:
4044 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4045 	case BPF_PROG_TYPE_CGROUP_SKB:
4046 		if (t == BPF_WRITE)
4047 			return false;
4048 		fallthrough;
4049 
4050 	/* Program types with direct read + write access go here! */
4051 	case BPF_PROG_TYPE_SCHED_CLS:
4052 	case BPF_PROG_TYPE_SCHED_ACT:
4053 	case BPF_PROG_TYPE_XDP:
4054 	case BPF_PROG_TYPE_LWT_XMIT:
4055 	case BPF_PROG_TYPE_SK_SKB:
4056 	case BPF_PROG_TYPE_SK_MSG:
4057 		if (meta)
4058 			return meta->pkt_access;
4059 
4060 		env->seen_direct_write = true;
4061 		return true;
4062 
4063 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4064 		if (t == BPF_WRITE)
4065 			env->seen_direct_write = true;
4066 
4067 		return true;
4068 
4069 	default:
4070 		return false;
4071 	}
4072 }
4073 
4074 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4075 			       int size, bool zero_size_allowed)
4076 {
4077 	struct bpf_reg_state *regs = cur_regs(env);
4078 	struct bpf_reg_state *reg = &regs[regno];
4079 	int err;
4080 
4081 	/* We may have added a variable offset to the packet pointer; but any
4082 	 * reg->range we have comes after that.  We are only checking the fixed
4083 	 * offset.
4084 	 */
4085 
4086 	/* We don't allow negative numbers, because we aren't tracking enough
4087 	 * detail to prove they're safe.
4088 	 */
4089 	if (reg->smin_value < 0) {
4090 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4091 			regno);
4092 		return -EACCES;
4093 	}
4094 
4095 	err = reg->range < 0 ? -EINVAL :
4096 	      __check_mem_access(env, regno, off, size, reg->range,
4097 				 zero_size_allowed);
4098 	if (err) {
4099 		verbose(env, "R%d offset is outside of the packet\n", regno);
4100 		return err;
4101 	}
4102 
4103 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4104 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4105 	 * otherwise find_good_pkt_pointers would have refused to set range info
4106 	 * that __check_mem_access would have rejected this pkt access.
4107 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4108 	 */
4109 	env->prog->aux->max_pkt_offset =
4110 		max_t(u32, env->prog->aux->max_pkt_offset,
4111 		      off + reg->umax_value + size - 1);
4112 
4113 	return err;
4114 }
4115 
4116 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4117 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4118 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4119 			    struct btf **btf, u32 *btf_id)
4120 {
4121 	struct bpf_insn_access_aux info = {
4122 		.reg_type = *reg_type,
4123 		.log = &env->log,
4124 	};
4125 
4126 	if (env->ops->is_valid_access &&
4127 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4128 		/* A non zero info.ctx_field_size indicates that this field is a
4129 		 * candidate for later verifier transformation to load the whole
4130 		 * field and then apply a mask when accessed with a narrower
4131 		 * access than actual ctx access size. A zero info.ctx_field_size
4132 		 * will only allow for whole field access and rejects any other
4133 		 * type of narrower access.
4134 		 */
4135 		*reg_type = info.reg_type;
4136 
4137 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4138 			*btf = info.btf;
4139 			*btf_id = info.btf_id;
4140 		} else {
4141 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4142 		}
4143 		/* remember the offset of last byte accessed in ctx */
4144 		if (env->prog->aux->max_ctx_offset < off + size)
4145 			env->prog->aux->max_ctx_offset = off + size;
4146 		return 0;
4147 	}
4148 
4149 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4150 	return -EACCES;
4151 }
4152 
4153 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4154 				  int size)
4155 {
4156 	if (size < 0 || off < 0 ||
4157 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4158 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4159 			off, size);
4160 		return -EACCES;
4161 	}
4162 	return 0;
4163 }
4164 
4165 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4166 			     u32 regno, int off, int size,
4167 			     enum bpf_access_type t)
4168 {
4169 	struct bpf_reg_state *regs = cur_regs(env);
4170 	struct bpf_reg_state *reg = &regs[regno];
4171 	struct bpf_insn_access_aux info = {};
4172 	bool valid;
4173 
4174 	if (reg->smin_value < 0) {
4175 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4176 			regno);
4177 		return -EACCES;
4178 	}
4179 
4180 	switch (reg->type) {
4181 	case PTR_TO_SOCK_COMMON:
4182 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4183 		break;
4184 	case PTR_TO_SOCKET:
4185 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4186 		break;
4187 	case PTR_TO_TCP_SOCK:
4188 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4189 		break;
4190 	case PTR_TO_XDP_SOCK:
4191 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4192 		break;
4193 	default:
4194 		valid = false;
4195 	}
4196 
4197 
4198 	if (valid) {
4199 		env->insn_aux_data[insn_idx].ctx_field_size =
4200 			info.ctx_field_size;
4201 		return 0;
4202 	}
4203 
4204 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4205 		regno, reg_type_str(env, reg->type), off, size);
4206 
4207 	return -EACCES;
4208 }
4209 
4210 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4211 {
4212 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4213 }
4214 
4215 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4216 {
4217 	const struct bpf_reg_state *reg = reg_state(env, regno);
4218 
4219 	return reg->type == PTR_TO_CTX;
4220 }
4221 
4222 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4223 {
4224 	const struct bpf_reg_state *reg = reg_state(env, regno);
4225 
4226 	return type_is_sk_pointer(reg->type);
4227 }
4228 
4229 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4230 {
4231 	const struct bpf_reg_state *reg = reg_state(env, regno);
4232 
4233 	return type_is_pkt_pointer(reg->type);
4234 }
4235 
4236 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4237 {
4238 	const struct bpf_reg_state *reg = reg_state(env, regno);
4239 
4240 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4241 	return reg->type == PTR_TO_FLOW_KEYS;
4242 }
4243 
4244 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4245 				   const struct bpf_reg_state *reg,
4246 				   int off, int size, bool strict)
4247 {
4248 	struct tnum reg_off;
4249 	int ip_align;
4250 
4251 	/* Byte size accesses are always allowed. */
4252 	if (!strict || size == 1)
4253 		return 0;
4254 
4255 	/* For platforms that do not have a Kconfig enabling
4256 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4257 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4258 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4259 	 * to this code only in strict mode where we want to emulate
4260 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4261 	 * unconditional IP align value of '2'.
4262 	 */
4263 	ip_align = 2;
4264 
4265 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4266 	if (!tnum_is_aligned(reg_off, size)) {
4267 		char tn_buf[48];
4268 
4269 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4270 		verbose(env,
4271 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4272 			ip_align, tn_buf, reg->off, off, size);
4273 		return -EACCES;
4274 	}
4275 
4276 	return 0;
4277 }
4278 
4279 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4280 				       const struct bpf_reg_state *reg,
4281 				       const char *pointer_desc,
4282 				       int off, int size, bool strict)
4283 {
4284 	struct tnum reg_off;
4285 
4286 	/* Byte size accesses are always allowed. */
4287 	if (!strict || size == 1)
4288 		return 0;
4289 
4290 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4291 	if (!tnum_is_aligned(reg_off, size)) {
4292 		char tn_buf[48];
4293 
4294 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4295 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4296 			pointer_desc, tn_buf, reg->off, off, size);
4297 		return -EACCES;
4298 	}
4299 
4300 	return 0;
4301 }
4302 
4303 static int check_ptr_alignment(struct bpf_verifier_env *env,
4304 			       const struct bpf_reg_state *reg, int off,
4305 			       int size, bool strict_alignment_once)
4306 {
4307 	bool strict = env->strict_alignment || strict_alignment_once;
4308 	const char *pointer_desc = "";
4309 
4310 	switch (reg->type) {
4311 	case PTR_TO_PACKET:
4312 	case PTR_TO_PACKET_META:
4313 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4314 		 * right in front, treat it the very same way.
4315 		 */
4316 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4317 	case PTR_TO_FLOW_KEYS:
4318 		pointer_desc = "flow keys ";
4319 		break;
4320 	case PTR_TO_MAP_KEY:
4321 		pointer_desc = "key ";
4322 		break;
4323 	case PTR_TO_MAP_VALUE:
4324 		pointer_desc = "value ";
4325 		break;
4326 	case PTR_TO_CTX:
4327 		pointer_desc = "context ";
4328 		break;
4329 	case PTR_TO_STACK:
4330 		pointer_desc = "stack ";
4331 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4332 		 * and check_stack_read_fixed_off() relies on stack accesses being
4333 		 * aligned.
4334 		 */
4335 		strict = true;
4336 		break;
4337 	case PTR_TO_SOCKET:
4338 		pointer_desc = "sock ";
4339 		break;
4340 	case PTR_TO_SOCK_COMMON:
4341 		pointer_desc = "sock_common ";
4342 		break;
4343 	case PTR_TO_TCP_SOCK:
4344 		pointer_desc = "tcp_sock ";
4345 		break;
4346 	case PTR_TO_XDP_SOCK:
4347 		pointer_desc = "xdp_sock ";
4348 		break;
4349 	default:
4350 		break;
4351 	}
4352 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4353 					   strict);
4354 }
4355 
4356 static int update_stack_depth(struct bpf_verifier_env *env,
4357 			      const struct bpf_func_state *func,
4358 			      int off)
4359 {
4360 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4361 
4362 	if (stack >= -off)
4363 		return 0;
4364 
4365 	/* update known max for given subprogram */
4366 	env->subprog_info[func->subprogno].stack_depth = -off;
4367 	return 0;
4368 }
4369 
4370 /* starting from main bpf function walk all instructions of the function
4371  * and recursively walk all callees that given function can call.
4372  * Ignore jump and exit insns.
4373  * Since recursion is prevented by check_cfg() this algorithm
4374  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4375  */
4376 static int check_max_stack_depth(struct bpf_verifier_env *env)
4377 {
4378 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4379 	struct bpf_subprog_info *subprog = env->subprog_info;
4380 	struct bpf_insn *insn = env->prog->insnsi;
4381 	bool tail_call_reachable = false;
4382 	int ret_insn[MAX_CALL_FRAMES];
4383 	int ret_prog[MAX_CALL_FRAMES];
4384 	int j;
4385 
4386 process_func:
4387 	/* protect against potential stack overflow that might happen when
4388 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4389 	 * depth for such case down to 256 so that the worst case scenario
4390 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4391 	 * 8k).
4392 	 *
4393 	 * To get the idea what might happen, see an example:
4394 	 * func1 -> sub rsp, 128
4395 	 *  subfunc1 -> sub rsp, 256
4396 	 *  tailcall1 -> add rsp, 256
4397 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4398 	 *   subfunc2 -> sub rsp, 64
4399 	 *   subfunc22 -> sub rsp, 128
4400 	 *   tailcall2 -> add rsp, 128
4401 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4402 	 *
4403 	 * tailcall will unwind the current stack frame but it will not get rid
4404 	 * of caller's stack as shown on the example above.
4405 	 */
4406 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4407 		verbose(env,
4408 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4409 			depth);
4410 		return -EACCES;
4411 	}
4412 	/* round up to 32-bytes, since this is granularity
4413 	 * of interpreter stack size
4414 	 */
4415 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4416 	if (depth > MAX_BPF_STACK) {
4417 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4418 			frame + 1, depth);
4419 		return -EACCES;
4420 	}
4421 continue_func:
4422 	subprog_end = subprog[idx + 1].start;
4423 	for (; i < subprog_end; i++) {
4424 		int next_insn;
4425 
4426 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4427 			continue;
4428 		/* remember insn and function to return to */
4429 		ret_insn[frame] = i + 1;
4430 		ret_prog[frame] = idx;
4431 
4432 		/* find the callee */
4433 		next_insn = i + insn[i].imm + 1;
4434 		idx = find_subprog(env, next_insn);
4435 		if (idx < 0) {
4436 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4437 				  next_insn);
4438 			return -EFAULT;
4439 		}
4440 		if (subprog[idx].is_async_cb) {
4441 			if (subprog[idx].has_tail_call) {
4442 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4443 				return -EFAULT;
4444 			}
4445 			 /* async callbacks don't increase bpf prog stack size */
4446 			continue;
4447 		}
4448 		i = next_insn;
4449 
4450 		if (subprog[idx].has_tail_call)
4451 			tail_call_reachable = true;
4452 
4453 		frame++;
4454 		if (frame >= MAX_CALL_FRAMES) {
4455 			verbose(env, "the call stack of %d frames is too deep !\n",
4456 				frame);
4457 			return -E2BIG;
4458 		}
4459 		goto process_func;
4460 	}
4461 	/* if tail call got detected across bpf2bpf calls then mark each of the
4462 	 * currently present subprog frames as tail call reachable subprogs;
4463 	 * this info will be utilized by JIT so that we will be preserving the
4464 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4465 	 */
4466 	if (tail_call_reachable)
4467 		for (j = 0; j < frame; j++)
4468 			subprog[ret_prog[j]].tail_call_reachable = true;
4469 	if (subprog[0].tail_call_reachable)
4470 		env->prog->aux->tail_call_reachable = true;
4471 
4472 	/* end of for() loop means the last insn of the 'subprog'
4473 	 * was reached. Doesn't matter whether it was JA or EXIT
4474 	 */
4475 	if (frame == 0)
4476 		return 0;
4477 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4478 	frame--;
4479 	i = ret_insn[frame];
4480 	idx = ret_prog[frame];
4481 	goto continue_func;
4482 }
4483 
4484 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4485 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4486 				  const struct bpf_insn *insn, int idx)
4487 {
4488 	int start = idx + insn->imm + 1, subprog;
4489 
4490 	subprog = find_subprog(env, start);
4491 	if (subprog < 0) {
4492 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4493 			  start);
4494 		return -EFAULT;
4495 	}
4496 	return env->subprog_info[subprog].stack_depth;
4497 }
4498 #endif
4499 
4500 static int __check_buffer_access(struct bpf_verifier_env *env,
4501 				 const char *buf_info,
4502 				 const struct bpf_reg_state *reg,
4503 				 int regno, int off, int size)
4504 {
4505 	if (off < 0) {
4506 		verbose(env,
4507 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4508 			regno, buf_info, off, size);
4509 		return -EACCES;
4510 	}
4511 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4512 		char tn_buf[48];
4513 
4514 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4515 		verbose(env,
4516 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4517 			regno, off, tn_buf);
4518 		return -EACCES;
4519 	}
4520 
4521 	return 0;
4522 }
4523 
4524 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4525 				  const struct bpf_reg_state *reg,
4526 				  int regno, int off, int size)
4527 {
4528 	int err;
4529 
4530 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4531 	if (err)
4532 		return err;
4533 
4534 	if (off + size > env->prog->aux->max_tp_access)
4535 		env->prog->aux->max_tp_access = off + size;
4536 
4537 	return 0;
4538 }
4539 
4540 static int check_buffer_access(struct bpf_verifier_env *env,
4541 			       const struct bpf_reg_state *reg,
4542 			       int regno, int off, int size,
4543 			       bool zero_size_allowed,
4544 			       u32 *max_access)
4545 {
4546 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4547 	int err;
4548 
4549 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4550 	if (err)
4551 		return err;
4552 
4553 	if (off + size > *max_access)
4554 		*max_access = off + size;
4555 
4556 	return 0;
4557 }
4558 
4559 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4560 static void zext_32_to_64(struct bpf_reg_state *reg)
4561 {
4562 	reg->var_off = tnum_subreg(reg->var_off);
4563 	__reg_assign_32_into_64(reg);
4564 }
4565 
4566 /* truncate register to smaller size (in bytes)
4567  * must be called with size < BPF_REG_SIZE
4568  */
4569 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4570 {
4571 	u64 mask;
4572 
4573 	/* clear high bits in bit representation */
4574 	reg->var_off = tnum_cast(reg->var_off, size);
4575 
4576 	/* fix arithmetic bounds */
4577 	mask = ((u64)1 << (size * 8)) - 1;
4578 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4579 		reg->umin_value &= mask;
4580 		reg->umax_value &= mask;
4581 	} else {
4582 		reg->umin_value = 0;
4583 		reg->umax_value = mask;
4584 	}
4585 	reg->smin_value = reg->umin_value;
4586 	reg->smax_value = reg->umax_value;
4587 
4588 	/* If size is smaller than 32bit register the 32bit register
4589 	 * values are also truncated so we push 64-bit bounds into
4590 	 * 32-bit bounds. Above were truncated < 32-bits already.
4591 	 */
4592 	if (size >= 4)
4593 		return;
4594 	__reg_combine_64_into_32(reg);
4595 }
4596 
4597 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4598 {
4599 	/* A map is considered read-only if the following condition are true:
4600 	 *
4601 	 * 1) BPF program side cannot change any of the map content. The
4602 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4603 	 *    and was set at map creation time.
4604 	 * 2) The map value(s) have been initialized from user space by a
4605 	 *    loader and then "frozen", such that no new map update/delete
4606 	 *    operations from syscall side are possible for the rest of
4607 	 *    the map's lifetime from that point onwards.
4608 	 * 3) Any parallel/pending map update/delete operations from syscall
4609 	 *    side have been completed. Only after that point, it's safe to
4610 	 *    assume that map value(s) are immutable.
4611 	 */
4612 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4613 	       READ_ONCE(map->frozen) &&
4614 	       !bpf_map_write_active(map);
4615 }
4616 
4617 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4618 {
4619 	void *ptr;
4620 	u64 addr;
4621 	int err;
4622 
4623 	err = map->ops->map_direct_value_addr(map, &addr, off);
4624 	if (err)
4625 		return err;
4626 	ptr = (void *)(long)addr + off;
4627 
4628 	switch (size) {
4629 	case sizeof(u8):
4630 		*val = (u64)*(u8 *)ptr;
4631 		break;
4632 	case sizeof(u16):
4633 		*val = (u64)*(u16 *)ptr;
4634 		break;
4635 	case sizeof(u32):
4636 		*val = (u64)*(u32 *)ptr;
4637 		break;
4638 	case sizeof(u64):
4639 		*val = *(u64 *)ptr;
4640 		break;
4641 	default:
4642 		return -EINVAL;
4643 	}
4644 	return 0;
4645 }
4646 
4647 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4648 				   struct bpf_reg_state *regs,
4649 				   int regno, int off, int size,
4650 				   enum bpf_access_type atype,
4651 				   int value_regno)
4652 {
4653 	struct bpf_reg_state *reg = regs + regno;
4654 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4655 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4656 	enum bpf_type_flag flag = 0;
4657 	u32 btf_id;
4658 	int ret;
4659 
4660 	if (off < 0) {
4661 		verbose(env,
4662 			"R%d is ptr_%s invalid negative access: off=%d\n",
4663 			regno, tname, off);
4664 		return -EACCES;
4665 	}
4666 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4667 		char tn_buf[48];
4668 
4669 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4670 		verbose(env,
4671 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4672 			regno, tname, off, tn_buf);
4673 		return -EACCES;
4674 	}
4675 
4676 	if (reg->type & MEM_USER) {
4677 		verbose(env,
4678 			"R%d is ptr_%s access user memory: off=%d\n",
4679 			regno, tname, off);
4680 		return -EACCES;
4681 	}
4682 
4683 	if (reg->type & MEM_PERCPU) {
4684 		verbose(env,
4685 			"R%d is ptr_%s access percpu memory: off=%d\n",
4686 			regno, tname, off);
4687 		return -EACCES;
4688 	}
4689 
4690 	if (env->ops->btf_struct_access) {
4691 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4692 						  off, size, atype, &btf_id, &flag);
4693 	} else {
4694 		if (atype != BPF_READ) {
4695 			verbose(env, "only read is supported\n");
4696 			return -EACCES;
4697 		}
4698 
4699 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4700 					atype, &btf_id, &flag);
4701 	}
4702 
4703 	if (ret < 0)
4704 		return ret;
4705 
4706 	/* If this is an untrusted pointer, all pointers formed by walking it
4707 	 * also inherit the untrusted flag.
4708 	 */
4709 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4710 		flag |= PTR_UNTRUSTED;
4711 
4712 	if (atype == BPF_READ && value_regno >= 0)
4713 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4714 
4715 	return 0;
4716 }
4717 
4718 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4719 				   struct bpf_reg_state *regs,
4720 				   int regno, int off, int size,
4721 				   enum bpf_access_type atype,
4722 				   int value_regno)
4723 {
4724 	struct bpf_reg_state *reg = regs + regno;
4725 	struct bpf_map *map = reg->map_ptr;
4726 	enum bpf_type_flag flag = 0;
4727 	const struct btf_type *t;
4728 	const char *tname;
4729 	u32 btf_id;
4730 	int ret;
4731 
4732 	if (!btf_vmlinux) {
4733 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4734 		return -ENOTSUPP;
4735 	}
4736 
4737 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4738 		verbose(env, "map_ptr access not supported for map type %d\n",
4739 			map->map_type);
4740 		return -ENOTSUPP;
4741 	}
4742 
4743 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4744 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4745 
4746 	if (!env->allow_ptr_to_map_access) {
4747 		verbose(env,
4748 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4749 			tname);
4750 		return -EPERM;
4751 	}
4752 
4753 	if (off < 0) {
4754 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4755 			regno, tname, off);
4756 		return -EACCES;
4757 	}
4758 
4759 	if (atype != BPF_READ) {
4760 		verbose(env, "only read from %s is supported\n", tname);
4761 		return -EACCES;
4762 	}
4763 
4764 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4765 	if (ret < 0)
4766 		return ret;
4767 
4768 	if (value_regno >= 0)
4769 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4770 
4771 	return 0;
4772 }
4773 
4774 /* Check that the stack access at the given offset is within bounds. The
4775  * maximum valid offset is -1.
4776  *
4777  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4778  * -state->allocated_stack for reads.
4779  */
4780 static int check_stack_slot_within_bounds(int off,
4781 					  struct bpf_func_state *state,
4782 					  enum bpf_access_type t)
4783 {
4784 	int min_valid_off;
4785 
4786 	if (t == BPF_WRITE)
4787 		min_valid_off = -MAX_BPF_STACK;
4788 	else
4789 		min_valid_off = -state->allocated_stack;
4790 
4791 	if (off < min_valid_off || off > -1)
4792 		return -EACCES;
4793 	return 0;
4794 }
4795 
4796 /* Check that the stack access at 'regno + off' falls within the maximum stack
4797  * bounds.
4798  *
4799  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4800  */
4801 static int check_stack_access_within_bounds(
4802 		struct bpf_verifier_env *env,
4803 		int regno, int off, int access_size,
4804 		enum bpf_access_src src, enum bpf_access_type type)
4805 {
4806 	struct bpf_reg_state *regs = cur_regs(env);
4807 	struct bpf_reg_state *reg = regs + regno;
4808 	struct bpf_func_state *state = func(env, reg);
4809 	int min_off, max_off;
4810 	int err;
4811 	char *err_extra;
4812 
4813 	if (src == ACCESS_HELPER)
4814 		/* We don't know if helpers are reading or writing (or both). */
4815 		err_extra = " indirect access to";
4816 	else if (type == BPF_READ)
4817 		err_extra = " read from";
4818 	else
4819 		err_extra = " write to";
4820 
4821 	if (tnum_is_const(reg->var_off)) {
4822 		min_off = reg->var_off.value + off;
4823 		if (access_size > 0)
4824 			max_off = min_off + access_size - 1;
4825 		else
4826 			max_off = min_off;
4827 	} else {
4828 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4829 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4830 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4831 				err_extra, regno);
4832 			return -EACCES;
4833 		}
4834 		min_off = reg->smin_value + off;
4835 		if (access_size > 0)
4836 			max_off = reg->smax_value + off + access_size - 1;
4837 		else
4838 			max_off = min_off;
4839 	}
4840 
4841 	err = check_stack_slot_within_bounds(min_off, state, type);
4842 	if (!err)
4843 		err = check_stack_slot_within_bounds(max_off, state, type);
4844 
4845 	if (err) {
4846 		if (tnum_is_const(reg->var_off)) {
4847 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4848 				err_extra, regno, off, access_size);
4849 		} else {
4850 			char tn_buf[48];
4851 
4852 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4853 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4854 				err_extra, regno, tn_buf, access_size);
4855 		}
4856 	}
4857 	return err;
4858 }
4859 
4860 /* check whether memory at (regno + off) is accessible for t = (read | write)
4861  * if t==write, value_regno is a register which value is stored into memory
4862  * if t==read, value_regno is a register which will receive the value from memory
4863  * if t==write && value_regno==-1, some unknown value is stored into memory
4864  * if t==read && value_regno==-1, don't care what we read from memory
4865  */
4866 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4867 			    int off, int bpf_size, enum bpf_access_type t,
4868 			    int value_regno, bool strict_alignment_once)
4869 {
4870 	struct bpf_reg_state *regs = cur_regs(env);
4871 	struct bpf_reg_state *reg = regs + regno;
4872 	struct bpf_func_state *state;
4873 	int size, err = 0;
4874 
4875 	size = bpf_size_to_bytes(bpf_size);
4876 	if (size < 0)
4877 		return size;
4878 
4879 	/* alignment checks will add in reg->off themselves */
4880 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4881 	if (err)
4882 		return err;
4883 
4884 	/* for access checks, reg->off is just part of off */
4885 	off += reg->off;
4886 
4887 	if (reg->type == PTR_TO_MAP_KEY) {
4888 		if (t == BPF_WRITE) {
4889 			verbose(env, "write to change key R%d not allowed\n", regno);
4890 			return -EACCES;
4891 		}
4892 
4893 		err = check_mem_region_access(env, regno, off, size,
4894 					      reg->map_ptr->key_size, false);
4895 		if (err)
4896 			return err;
4897 		if (value_regno >= 0)
4898 			mark_reg_unknown(env, regs, value_regno);
4899 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4900 		struct btf_field *kptr_field = NULL;
4901 
4902 		if (t == BPF_WRITE && value_regno >= 0 &&
4903 		    is_pointer_value(env, value_regno)) {
4904 			verbose(env, "R%d leaks addr into map\n", value_regno);
4905 			return -EACCES;
4906 		}
4907 		err = check_map_access_type(env, regno, off, size, t);
4908 		if (err)
4909 			return err;
4910 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4911 		if (err)
4912 			return err;
4913 		if (tnum_is_const(reg->var_off))
4914 			kptr_field = btf_record_find(reg->map_ptr->record,
4915 						     off + reg->var_off.value, BPF_KPTR);
4916 		if (kptr_field) {
4917 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
4918 		} else if (t == BPF_READ && value_regno >= 0) {
4919 			struct bpf_map *map = reg->map_ptr;
4920 
4921 			/* if map is read-only, track its contents as scalars */
4922 			if (tnum_is_const(reg->var_off) &&
4923 			    bpf_map_is_rdonly(map) &&
4924 			    map->ops->map_direct_value_addr) {
4925 				int map_off = off + reg->var_off.value;
4926 				u64 val = 0;
4927 
4928 				err = bpf_map_direct_read(map, map_off, size,
4929 							  &val);
4930 				if (err)
4931 					return err;
4932 
4933 				regs[value_regno].type = SCALAR_VALUE;
4934 				__mark_reg_known(&regs[value_regno], val);
4935 			} else {
4936 				mark_reg_unknown(env, regs, value_regno);
4937 			}
4938 		}
4939 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4940 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4941 
4942 		if (type_may_be_null(reg->type)) {
4943 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4944 				reg_type_str(env, reg->type));
4945 			return -EACCES;
4946 		}
4947 
4948 		if (t == BPF_WRITE && rdonly_mem) {
4949 			verbose(env, "R%d cannot write into %s\n",
4950 				regno, reg_type_str(env, reg->type));
4951 			return -EACCES;
4952 		}
4953 
4954 		if (t == BPF_WRITE && value_regno >= 0 &&
4955 		    is_pointer_value(env, value_regno)) {
4956 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4957 			return -EACCES;
4958 		}
4959 
4960 		err = check_mem_region_access(env, regno, off, size,
4961 					      reg->mem_size, false);
4962 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4963 			mark_reg_unknown(env, regs, value_regno);
4964 	} else if (reg->type == PTR_TO_CTX) {
4965 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4966 		struct btf *btf = NULL;
4967 		u32 btf_id = 0;
4968 
4969 		if (t == BPF_WRITE && value_regno >= 0 &&
4970 		    is_pointer_value(env, value_regno)) {
4971 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4972 			return -EACCES;
4973 		}
4974 
4975 		err = check_ptr_off_reg(env, reg, regno);
4976 		if (err < 0)
4977 			return err;
4978 
4979 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4980 				       &btf_id);
4981 		if (err)
4982 			verbose_linfo(env, insn_idx, "; ");
4983 		if (!err && t == BPF_READ && value_regno >= 0) {
4984 			/* ctx access returns either a scalar, or a
4985 			 * PTR_TO_PACKET[_META,_END]. In the latter
4986 			 * case, we know the offset is zero.
4987 			 */
4988 			if (reg_type == SCALAR_VALUE) {
4989 				mark_reg_unknown(env, regs, value_regno);
4990 			} else {
4991 				mark_reg_known_zero(env, regs,
4992 						    value_regno);
4993 				if (type_may_be_null(reg_type))
4994 					regs[value_regno].id = ++env->id_gen;
4995 				/* A load of ctx field could have different
4996 				 * actual load size with the one encoded in the
4997 				 * insn. When the dst is PTR, it is for sure not
4998 				 * a sub-register.
4999 				 */
5000 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5001 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5002 					regs[value_regno].btf = btf;
5003 					regs[value_regno].btf_id = btf_id;
5004 				}
5005 			}
5006 			regs[value_regno].type = reg_type;
5007 		}
5008 
5009 	} else if (reg->type == PTR_TO_STACK) {
5010 		/* Basic bounds checks. */
5011 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5012 		if (err)
5013 			return err;
5014 
5015 		state = func(env, reg);
5016 		err = update_stack_depth(env, state, off);
5017 		if (err)
5018 			return err;
5019 
5020 		if (t == BPF_READ)
5021 			err = check_stack_read(env, regno, off, size,
5022 					       value_regno);
5023 		else
5024 			err = check_stack_write(env, regno, off, size,
5025 						value_regno, insn_idx);
5026 	} else if (reg_is_pkt_pointer(reg)) {
5027 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5028 			verbose(env, "cannot write into packet\n");
5029 			return -EACCES;
5030 		}
5031 		if (t == BPF_WRITE && value_regno >= 0 &&
5032 		    is_pointer_value(env, value_regno)) {
5033 			verbose(env, "R%d leaks addr into packet\n",
5034 				value_regno);
5035 			return -EACCES;
5036 		}
5037 		err = check_packet_access(env, regno, off, size, false);
5038 		if (!err && t == BPF_READ && value_regno >= 0)
5039 			mark_reg_unknown(env, regs, value_regno);
5040 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5041 		if (t == BPF_WRITE && value_regno >= 0 &&
5042 		    is_pointer_value(env, value_regno)) {
5043 			verbose(env, "R%d leaks addr into flow keys\n",
5044 				value_regno);
5045 			return -EACCES;
5046 		}
5047 
5048 		err = check_flow_keys_access(env, off, size);
5049 		if (!err && t == BPF_READ && value_regno >= 0)
5050 			mark_reg_unknown(env, regs, value_regno);
5051 	} else if (type_is_sk_pointer(reg->type)) {
5052 		if (t == BPF_WRITE) {
5053 			verbose(env, "R%d cannot write into %s\n",
5054 				regno, reg_type_str(env, reg->type));
5055 			return -EACCES;
5056 		}
5057 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5058 		if (!err && value_regno >= 0)
5059 			mark_reg_unknown(env, regs, value_regno);
5060 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5061 		err = check_tp_buffer_access(env, reg, regno, off, size);
5062 		if (!err && t == BPF_READ && value_regno >= 0)
5063 			mark_reg_unknown(env, regs, value_regno);
5064 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5065 		   !type_may_be_null(reg->type)) {
5066 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5067 					      value_regno);
5068 	} else if (reg->type == CONST_PTR_TO_MAP) {
5069 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5070 					      value_regno);
5071 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5072 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5073 		u32 *max_access;
5074 
5075 		if (rdonly_mem) {
5076 			if (t == BPF_WRITE) {
5077 				verbose(env, "R%d cannot write into %s\n",
5078 					regno, reg_type_str(env, reg->type));
5079 				return -EACCES;
5080 			}
5081 			max_access = &env->prog->aux->max_rdonly_access;
5082 		} else {
5083 			max_access = &env->prog->aux->max_rdwr_access;
5084 		}
5085 
5086 		err = check_buffer_access(env, reg, regno, off, size, false,
5087 					  max_access);
5088 
5089 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5090 			mark_reg_unknown(env, regs, value_regno);
5091 	} else {
5092 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5093 			reg_type_str(env, reg->type));
5094 		return -EACCES;
5095 	}
5096 
5097 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5098 	    regs[value_regno].type == SCALAR_VALUE) {
5099 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5100 		coerce_reg_to_size(&regs[value_regno], size);
5101 	}
5102 	return err;
5103 }
5104 
5105 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5106 {
5107 	int load_reg;
5108 	int err;
5109 
5110 	switch (insn->imm) {
5111 	case BPF_ADD:
5112 	case BPF_ADD | BPF_FETCH:
5113 	case BPF_AND:
5114 	case BPF_AND | BPF_FETCH:
5115 	case BPF_OR:
5116 	case BPF_OR | BPF_FETCH:
5117 	case BPF_XOR:
5118 	case BPF_XOR | BPF_FETCH:
5119 	case BPF_XCHG:
5120 	case BPF_CMPXCHG:
5121 		break;
5122 	default:
5123 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5124 		return -EINVAL;
5125 	}
5126 
5127 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5128 		verbose(env, "invalid atomic operand size\n");
5129 		return -EINVAL;
5130 	}
5131 
5132 	/* check src1 operand */
5133 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5134 	if (err)
5135 		return err;
5136 
5137 	/* check src2 operand */
5138 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5139 	if (err)
5140 		return err;
5141 
5142 	if (insn->imm == BPF_CMPXCHG) {
5143 		/* Check comparison of R0 with memory location */
5144 		const u32 aux_reg = BPF_REG_0;
5145 
5146 		err = check_reg_arg(env, aux_reg, SRC_OP);
5147 		if (err)
5148 			return err;
5149 
5150 		if (is_pointer_value(env, aux_reg)) {
5151 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5152 			return -EACCES;
5153 		}
5154 	}
5155 
5156 	if (is_pointer_value(env, insn->src_reg)) {
5157 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5158 		return -EACCES;
5159 	}
5160 
5161 	if (is_ctx_reg(env, insn->dst_reg) ||
5162 	    is_pkt_reg(env, insn->dst_reg) ||
5163 	    is_flow_key_reg(env, insn->dst_reg) ||
5164 	    is_sk_reg(env, insn->dst_reg)) {
5165 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5166 			insn->dst_reg,
5167 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5168 		return -EACCES;
5169 	}
5170 
5171 	if (insn->imm & BPF_FETCH) {
5172 		if (insn->imm == BPF_CMPXCHG)
5173 			load_reg = BPF_REG_0;
5174 		else
5175 			load_reg = insn->src_reg;
5176 
5177 		/* check and record load of old value */
5178 		err = check_reg_arg(env, load_reg, DST_OP);
5179 		if (err)
5180 			return err;
5181 	} else {
5182 		/* This instruction accesses a memory location but doesn't
5183 		 * actually load it into a register.
5184 		 */
5185 		load_reg = -1;
5186 	}
5187 
5188 	/* Check whether we can read the memory, with second call for fetch
5189 	 * case to simulate the register fill.
5190 	 */
5191 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5192 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5193 	if (!err && load_reg >= 0)
5194 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5195 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5196 				       true);
5197 	if (err)
5198 		return err;
5199 
5200 	/* Check whether we can write into the same memory. */
5201 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5202 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5203 	if (err)
5204 		return err;
5205 
5206 	return 0;
5207 }
5208 
5209 /* When register 'regno' is used to read the stack (either directly or through
5210  * a helper function) make sure that it's within stack boundary and, depending
5211  * on the access type, that all elements of the stack are initialized.
5212  *
5213  * 'off' includes 'regno->off', but not its dynamic part (if any).
5214  *
5215  * All registers that have been spilled on the stack in the slots within the
5216  * read offsets are marked as read.
5217  */
5218 static int check_stack_range_initialized(
5219 		struct bpf_verifier_env *env, int regno, int off,
5220 		int access_size, bool zero_size_allowed,
5221 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5222 {
5223 	struct bpf_reg_state *reg = reg_state(env, regno);
5224 	struct bpf_func_state *state = func(env, reg);
5225 	int err, min_off, max_off, i, j, slot, spi;
5226 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5227 	enum bpf_access_type bounds_check_type;
5228 	/* Some accesses can write anything into the stack, others are
5229 	 * read-only.
5230 	 */
5231 	bool clobber = false;
5232 
5233 	if (access_size == 0 && !zero_size_allowed) {
5234 		verbose(env, "invalid zero-sized read\n");
5235 		return -EACCES;
5236 	}
5237 
5238 	if (type == ACCESS_HELPER) {
5239 		/* The bounds checks for writes are more permissive than for
5240 		 * reads. However, if raw_mode is not set, we'll do extra
5241 		 * checks below.
5242 		 */
5243 		bounds_check_type = BPF_WRITE;
5244 		clobber = true;
5245 	} else {
5246 		bounds_check_type = BPF_READ;
5247 	}
5248 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5249 					       type, bounds_check_type);
5250 	if (err)
5251 		return err;
5252 
5253 
5254 	if (tnum_is_const(reg->var_off)) {
5255 		min_off = max_off = reg->var_off.value + off;
5256 	} else {
5257 		/* Variable offset is prohibited for unprivileged mode for
5258 		 * simplicity since it requires corresponding support in
5259 		 * Spectre masking for stack ALU.
5260 		 * See also retrieve_ptr_limit().
5261 		 */
5262 		if (!env->bypass_spec_v1) {
5263 			char tn_buf[48];
5264 
5265 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5266 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5267 				regno, err_extra, tn_buf);
5268 			return -EACCES;
5269 		}
5270 		/* Only initialized buffer on stack is allowed to be accessed
5271 		 * with variable offset. With uninitialized buffer it's hard to
5272 		 * guarantee that whole memory is marked as initialized on
5273 		 * helper return since specific bounds are unknown what may
5274 		 * cause uninitialized stack leaking.
5275 		 */
5276 		if (meta && meta->raw_mode)
5277 			meta = NULL;
5278 
5279 		min_off = reg->smin_value + off;
5280 		max_off = reg->smax_value + off;
5281 	}
5282 
5283 	if (meta && meta->raw_mode) {
5284 		meta->access_size = access_size;
5285 		meta->regno = regno;
5286 		return 0;
5287 	}
5288 
5289 	for (i = min_off; i < max_off + access_size; i++) {
5290 		u8 *stype;
5291 
5292 		slot = -i - 1;
5293 		spi = slot / BPF_REG_SIZE;
5294 		if (state->allocated_stack <= slot)
5295 			goto err;
5296 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5297 		if (*stype == STACK_MISC)
5298 			goto mark;
5299 		if (*stype == STACK_ZERO) {
5300 			if (clobber) {
5301 				/* helper can write anything into the stack */
5302 				*stype = STACK_MISC;
5303 			}
5304 			goto mark;
5305 		}
5306 
5307 		if (is_spilled_reg(&state->stack[spi]) &&
5308 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5309 		     env->allow_ptr_leaks)) {
5310 			if (clobber) {
5311 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5312 				for (j = 0; j < BPF_REG_SIZE; j++)
5313 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5314 			}
5315 			goto mark;
5316 		}
5317 
5318 err:
5319 		if (tnum_is_const(reg->var_off)) {
5320 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5321 				err_extra, regno, min_off, i - min_off, access_size);
5322 		} else {
5323 			char tn_buf[48];
5324 
5325 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5326 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5327 				err_extra, regno, tn_buf, i - min_off, access_size);
5328 		}
5329 		return -EACCES;
5330 mark:
5331 		/* reading any byte out of 8-byte 'spill_slot' will cause
5332 		 * the whole slot to be marked as 'read'
5333 		 */
5334 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5335 			      state->stack[spi].spilled_ptr.parent,
5336 			      REG_LIVE_READ64);
5337 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5338 		 * be sure that whether stack slot is written to or not. Hence,
5339 		 * we must still conservatively propagate reads upwards even if
5340 		 * helper may write to the entire memory range.
5341 		 */
5342 	}
5343 	return update_stack_depth(env, state, min_off);
5344 }
5345 
5346 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5347 				   int access_size, bool zero_size_allowed,
5348 				   struct bpf_call_arg_meta *meta)
5349 {
5350 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5351 	u32 *max_access;
5352 
5353 	switch (base_type(reg->type)) {
5354 	case PTR_TO_PACKET:
5355 	case PTR_TO_PACKET_META:
5356 		return check_packet_access(env, regno, reg->off, access_size,
5357 					   zero_size_allowed);
5358 	case PTR_TO_MAP_KEY:
5359 		if (meta && meta->raw_mode) {
5360 			verbose(env, "R%d cannot write into %s\n", regno,
5361 				reg_type_str(env, reg->type));
5362 			return -EACCES;
5363 		}
5364 		return check_mem_region_access(env, regno, reg->off, access_size,
5365 					       reg->map_ptr->key_size, false);
5366 	case PTR_TO_MAP_VALUE:
5367 		if (check_map_access_type(env, regno, reg->off, access_size,
5368 					  meta && meta->raw_mode ? BPF_WRITE :
5369 					  BPF_READ))
5370 			return -EACCES;
5371 		return check_map_access(env, regno, reg->off, access_size,
5372 					zero_size_allowed, ACCESS_HELPER);
5373 	case PTR_TO_MEM:
5374 		if (type_is_rdonly_mem(reg->type)) {
5375 			if (meta && meta->raw_mode) {
5376 				verbose(env, "R%d cannot write into %s\n", regno,
5377 					reg_type_str(env, reg->type));
5378 				return -EACCES;
5379 			}
5380 		}
5381 		return check_mem_region_access(env, regno, reg->off,
5382 					       access_size, reg->mem_size,
5383 					       zero_size_allowed);
5384 	case PTR_TO_BUF:
5385 		if (type_is_rdonly_mem(reg->type)) {
5386 			if (meta && meta->raw_mode) {
5387 				verbose(env, "R%d cannot write into %s\n", regno,
5388 					reg_type_str(env, reg->type));
5389 				return -EACCES;
5390 			}
5391 
5392 			max_access = &env->prog->aux->max_rdonly_access;
5393 		} else {
5394 			max_access = &env->prog->aux->max_rdwr_access;
5395 		}
5396 		return check_buffer_access(env, reg, regno, reg->off,
5397 					   access_size, zero_size_allowed,
5398 					   max_access);
5399 	case PTR_TO_STACK:
5400 		return check_stack_range_initialized(
5401 				env,
5402 				regno, reg->off, access_size,
5403 				zero_size_allowed, ACCESS_HELPER, meta);
5404 	case PTR_TO_CTX:
5405 		/* in case the function doesn't know how to access the context,
5406 		 * (because we are in a program of type SYSCALL for example), we
5407 		 * can not statically check its size.
5408 		 * Dynamically check it now.
5409 		 */
5410 		if (!env->ops->convert_ctx_access) {
5411 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5412 			int offset = access_size - 1;
5413 
5414 			/* Allow zero-byte read from PTR_TO_CTX */
5415 			if (access_size == 0)
5416 				return zero_size_allowed ? 0 : -EACCES;
5417 
5418 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5419 						atype, -1, false);
5420 		}
5421 
5422 		fallthrough;
5423 	default: /* scalar_value or invalid ptr */
5424 		/* Allow zero-byte read from NULL, regardless of pointer type */
5425 		if (zero_size_allowed && access_size == 0 &&
5426 		    register_is_null(reg))
5427 			return 0;
5428 
5429 		verbose(env, "R%d type=%s ", regno,
5430 			reg_type_str(env, reg->type));
5431 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5432 		return -EACCES;
5433 	}
5434 }
5435 
5436 static int check_mem_size_reg(struct bpf_verifier_env *env,
5437 			      struct bpf_reg_state *reg, u32 regno,
5438 			      bool zero_size_allowed,
5439 			      struct bpf_call_arg_meta *meta)
5440 {
5441 	int err;
5442 
5443 	/* This is used to refine r0 return value bounds for helpers
5444 	 * that enforce this value as an upper bound on return values.
5445 	 * See do_refine_retval_range() for helpers that can refine
5446 	 * the return value. C type of helper is u32 so we pull register
5447 	 * bound from umax_value however, if negative verifier errors
5448 	 * out. Only upper bounds can be learned because retval is an
5449 	 * int type and negative retvals are allowed.
5450 	 */
5451 	meta->msize_max_value = reg->umax_value;
5452 
5453 	/* The register is SCALAR_VALUE; the access check
5454 	 * happens using its boundaries.
5455 	 */
5456 	if (!tnum_is_const(reg->var_off))
5457 		/* For unprivileged variable accesses, disable raw
5458 		 * mode so that the program is required to
5459 		 * initialize all the memory that the helper could
5460 		 * just partially fill up.
5461 		 */
5462 		meta = NULL;
5463 
5464 	if (reg->smin_value < 0) {
5465 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5466 			regno);
5467 		return -EACCES;
5468 	}
5469 
5470 	if (reg->umin_value == 0) {
5471 		err = check_helper_mem_access(env, regno - 1, 0,
5472 					      zero_size_allowed,
5473 					      meta);
5474 		if (err)
5475 			return err;
5476 	}
5477 
5478 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5479 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5480 			regno);
5481 		return -EACCES;
5482 	}
5483 	err = check_helper_mem_access(env, regno - 1,
5484 				      reg->umax_value,
5485 				      zero_size_allowed, meta);
5486 	if (!err)
5487 		err = mark_chain_precision(env, regno);
5488 	return err;
5489 }
5490 
5491 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5492 		   u32 regno, u32 mem_size)
5493 {
5494 	bool may_be_null = type_may_be_null(reg->type);
5495 	struct bpf_reg_state saved_reg;
5496 	struct bpf_call_arg_meta meta;
5497 	int err;
5498 
5499 	if (register_is_null(reg))
5500 		return 0;
5501 
5502 	memset(&meta, 0, sizeof(meta));
5503 	/* Assuming that the register contains a value check if the memory
5504 	 * access is safe. Temporarily save and restore the register's state as
5505 	 * the conversion shouldn't be visible to a caller.
5506 	 */
5507 	if (may_be_null) {
5508 		saved_reg = *reg;
5509 		mark_ptr_not_null_reg(reg);
5510 	}
5511 
5512 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5513 	/* Check access for BPF_WRITE */
5514 	meta.raw_mode = true;
5515 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5516 
5517 	if (may_be_null)
5518 		*reg = saved_reg;
5519 
5520 	return err;
5521 }
5522 
5523 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5524 			     u32 regno)
5525 {
5526 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5527 	bool may_be_null = type_may_be_null(mem_reg->type);
5528 	struct bpf_reg_state saved_reg;
5529 	struct bpf_call_arg_meta meta;
5530 	int err;
5531 
5532 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5533 
5534 	memset(&meta, 0, sizeof(meta));
5535 
5536 	if (may_be_null) {
5537 		saved_reg = *mem_reg;
5538 		mark_ptr_not_null_reg(mem_reg);
5539 	}
5540 
5541 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5542 	/* Check access for BPF_WRITE */
5543 	meta.raw_mode = true;
5544 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5545 
5546 	if (may_be_null)
5547 		*mem_reg = saved_reg;
5548 	return err;
5549 }
5550 
5551 /* Implementation details:
5552  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5553  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5554  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5555  * value_or_null->value transition, since the verifier only cares about
5556  * the range of access to valid map value pointer and doesn't care about actual
5557  * address of the map element.
5558  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5559  * reg->id > 0 after value_or_null->value transition. By doing so
5560  * two bpf_map_lookups will be considered two different pointers that
5561  * point to different bpf_spin_locks.
5562  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5563  * dead-locks.
5564  * Since only one bpf_spin_lock is allowed the checks are simpler than
5565  * reg_is_refcounted() logic. The verifier needs to remember only
5566  * one spin_lock instead of array of acquired_refs.
5567  * cur_state->active_spin_lock remembers which map value element got locked
5568  * and clears it after bpf_spin_unlock.
5569  */
5570 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5571 			     bool is_lock)
5572 {
5573 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5574 	struct bpf_verifier_state *cur = env->cur_state;
5575 	bool is_const = tnum_is_const(reg->var_off);
5576 	struct bpf_map *map = reg->map_ptr;
5577 	u64 val = reg->var_off.value;
5578 
5579 	if (!is_const) {
5580 		verbose(env,
5581 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5582 			regno);
5583 		return -EINVAL;
5584 	}
5585 	if (!map->btf) {
5586 		verbose(env,
5587 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5588 			map->name);
5589 		return -EINVAL;
5590 	}
5591 	if (!btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
5592 		verbose(env, "map '%s' has no valid bpf_spin_lock\n", map->name);
5593 		return -EINVAL;
5594 	}
5595 	if (map->record->spin_lock_off != val + reg->off) {
5596 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5597 			val + reg->off, map->record->spin_lock_off);
5598 		return -EINVAL;
5599 	}
5600 	if (is_lock) {
5601 		if (cur->active_spin_lock) {
5602 			verbose(env,
5603 				"Locking two bpf_spin_locks are not allowed\n");
5604 			return -EINVAL;
5605 		}
5606 		cur->active_spin_lock = reg->id;
5607 	} else {
5608 		if (!cur->active_spin_lock) {
5609 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5610 			return -EINVAL;
5611 		}
5612 		if (cur->active_spin_lock != reg->id) {
5613 			verbose(env, "bpf_spin_unlock of different lock\n");
5614 			return -EINVAL;
5615 		}
5616 		cur->active_spin_lock = 0;
5617 	}
5618 	return 0;
5619 }
5620 
5621 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5622 			      struct bpf_call_arg_meta *meta)
5623 {
5624 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5625 	bool is_const = tnum_is_const(reg->var_off);
5626 	struct bpf_map *map = reg->map_ptr;
5627 	u64 val = reg->var_off.value;
5628 
5629 	if (!is_const) {
5630 		verbose(env,
5631 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5632 			regno);
5633 		return -EINVAL;
5634 	}
5635 	if (!map->btf) {
5636 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5637 			map->name);
5638 		return -EINVAL;
5639 	}
5640 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
5641 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5642 		return -EINVAL;
5643 	}
5644 	if (map->record->timer_off != val + reg->off) {
5645 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5646 			val + reg->off, map->record->timer_off);
5647 		return -EINVAL;
5648 	}
5649 	if (meta->map_ptr) {
5650 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5651 		return -EFAULT;
5652 	}
5653 	meta->map_uid = reg->map_uid;
5654 	meta->map_ptr = map;
5655 	return 0;
5656 }
5657 
5658 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5659 			     struct bpf_call_arg_meta *meta)
5660 {
5661 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5662 	struct bpf_map *map_ptr = reg->map_ptr;
5663 	struct btf_field *kptr_field;
5664 	u32 kptr_off;
5665 
5666 	if (!tnum_is_const(reg->var_off)) {
5667 		verbose(env,
5668 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5669 			regno);
5670 		return -EINVAL;
5671 	}
5672 	if (!map_ptr->btf) {
5673 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5674 			map_ptr->name);
5675 		return -EINVAL;
5676 	}
5677 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5678 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5679 		return -EINVAL;
5680 	}
5681 
5682 	meta->map_ptr = map_ptr;
5683 	kptr_off = reg->off + reg->var_off.value;
5684 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5685 	if (!kptr_field) {
5686 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5687 		return -EACCES;
5688 	}
5689 	if (kptr_field->type != BPF_KPTR_REF) {
5690 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5691 		return -EACCES;
5692 	}
5693 	meta->kptr_field = kptr_field;
5694 	return 0;
5695 }
5696 
5697 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5698 {
5699 	return type == ARG_CONST_SIZE ||
5700 	       type == ARG_CONST_SIZE_OR_ZERO;
5701 }
5702 
5703 static bool arg_type_is_release(enum bpf_arg_type type)
5704 {
5705 	return type & OBJ_RELEASE;
5706 }
5707 
5708 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5709 {
5710 	return base_type(type) == ARG_PTR_TO_DYNPTR;
5711 }
5712 
5713 static int int_ptr_type_to_size(enum bpf_arg_type type)
5714 {
5715 	if (type == ARG_PTR_TO_INT)
5716 		return sizeof(u32);
5717 	else if (type == ARG_PTR_TO_LONG)
5718 		return sizeof(u64);
5719 
5720 	return -EINVAL;
5721 }
5722 
5723 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5724 				 const struct bpf_call_arg_meta *meta,
5725 				 enum bpf_arg_type *arg_type)
5726 {
5727 	if (!meta->map_ptr) {
5728 		/* kernel subsystem misconfigured verifier */
5729 		verbose(env, "invalid map_ptr to access map->type\n");
5730 		return -EACCES;
5731 	}
5732 
5733 	switch (meta->map_ptr->map_type) {
5734 	case BPF_MAP_TYPE_SOCKMAP:
5735 	case BPF_MAP_TYPE_SOCKHASH:
5736 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5737 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5738 		} else {
5739 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5740 			return -EINVAL;
5741 		}
5742 		break;
5743 	case BPF_MAP_TYPE_BLOOM_FILTER:
5744 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5745 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5746 		break;
5747 	default:
5748 		break;
5749 	}
5750 	return 0;
5751 }
5752 
5753 struct bpf_reg_types {
5754 	const enum bpf_reg_type types[10];
5755 	u32 *btf_id;
5756 };
5757 
5758 static const struct bpf_reg_types sock_types = {
5759 	.types = {
5760 		PTR_TO_SOCK_COMMON,
5761 		PTR_TO_SOCKET,
5762 		PTR_TO_TCP_SOCK,
5763 		PTR_TO_XDP_SOCK,
5764 	},
5765 };
5766 
5767 #ifdef CONFIG_NET
5768 static const struct bpf_reg_types btf_id_sock_common_types = {
5769 	.types = {
5770 		PTR_TO_SOCK_COMMON,
5771 		PTR_TO_SOCKET,
5772 		PTR_TO_TCP_SOCK,
5773 		PTR_TO_XDP_SOCK,
5774 		PTR_TO_BTF_ID,
5775 	},
5776 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5777 };
5778 #endif
5779 
5780 static const struct bpf_reg_types mem_types = {
5781 	.types = {
5782 		PTR_TO_STACK,
5783 		PTR_TO_PACKET,
5784 		PTR_TO_PACKET_META,
5785 		PTR_TO_MAP_KEY,
5786 		PTR_TO_MAP_VALUE,
5787 		PTR_TO_MEM,
5788 		PTR_TO_MEM | MEM_ALLOC,
5789 		PTR_TO_BUF,
5790 	},
5791 };
5792 
5793 static const struct bpf_reg_types int_ptr_types = {
5794 	.types = {
5795 		PTR_TO_STACK,
5796 		PTR_TO_PACKET,
5797 		PTR_TO_PACKET_META,
5798 		PTR_TO_MAP_KEY,
5799 		PTR_TO_MAP_VALUE,
5800 	},
5801 };
5802 
5803 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5804 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5805 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5806 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5807 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5808 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5809 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5810 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5811 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5812 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5813 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5814 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5815 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5816 static const struct bpf_reg_types dynptr_types = {
5817 	.types = {
5818 		PTR_TO_STACK,
5819 		PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5820 	}
5821 };
5822 
5823 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5824 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
5825 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
5826 	[ARG_CONST_SIZE]		= &scalar_types,
5827 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5828 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5829 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5830 	[ARG_PTR_TO_CTX]		= &context_types,
5831 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5832 #ifdef CONFIG_NET
5833 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5834 #endif
5835 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5836 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5837 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5838 	[ARG_PTR_TO_MEM]		= &mem_types,
5839 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5840 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5841 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5842 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5843 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5844 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5845 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5846 	[ARG_PTR_TO_TIMER]		= &timer_types,
5847 	[ARG_PTR_TO_KPTR]		= &kptr_types,
5848 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
5849 };
5850 
5851 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5852 			  enum bpf_arg_type arg_type,
5853 			  const u32 *arg_btf_id,
5854 			  struct bpf_call_arg_meta *meta)
5855 {
5856 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5857 	enum bpf_reg_type expected, type = reg->type;
5858 	const struct bpf_reg_types *compatible;
5859 	int i, j;
5860 
5861 	compatible = compatible_reg_types[base_type(arg_type)];
5862 	if (!compatible) {
5863 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5864 		return -EFAULT;
5865 	}
5866 
5867 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5868 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5869 	 *
5870 	 * Same for MAYBE_NULL:
5871 	 *
5872 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5873 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5874 	 *
5875 	 * Therefore we fold these flags depending on the arg_type before comparison.
5876 	 */
5877 	if (arg_type & MEM_RDONLY)
5878 		type &= ~MEM_RDONLY;
5879 	if (arg_type & PTR_MAYBE_NULL)
5880 		type &= ~PTR_MAYBE_NULL;
5881 
5882 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5883 		expected = compatible->types[i];
5884 		if (expected == NOT_INIT)
5885 			break;
5886 
5887 		if (type == expected)
5888 			goto found;
5889 	}
5890 
5891 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5892 	for (j = 0; j + 1 < i; j++)
5893 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5894 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5895 	return -EACCES;
5896 
5897 found:
5898 	if (reg->type == PTR_TO_BTF_ID) {
5899 		/* For bpf_sk_release, it needs to match against first member
5900 		 * 'struct sock_common', hence make an exception for it. This
5901 		 * allows bpf_sk_release to work for multiple socket types.
5902 		 */
5903 		bool strict_type_match = arg_type_is_release(arg_type) &&
5904 					 meta->func_id != BPF_FUNC_sk_release;
5905 
5906 		if (!arg_btf_id) {
5907 			if (!compatible->btf_id) {
5908 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5909 				return -EFAULT;
5910 			}
5911 			arg_btf_id = compatible->btf_id;
5912 		}
5913 
5914 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
5915 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
5916 				return -EACCES;
5917 		} else {
5918 			if (arg_btf_id == BPF_PTR_POISON) {
5919 				verbose(env, "verifier internal error:");
5920 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5921 					regno);
5922 				return -EACCES;
5923 			}
5924 
5925 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5926 						  btf_vmlinux, *arg_btf_id,
5927 						  strict_type_match)) {
5928 				verbose(env, "R%d is of type %s but %s is expected\n",
5929 					regno, kernel_type_name(reg->btf, reg->btf_id),
5930 					kernel_type_name(btf_vmlinux, *arg_btf_id));
5931 				return -EACCES;
5932 			}
5933 		}
5934 	}
5935 
5936 	return 0;
5937 }
5938 
5939 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5940 			   const struct bpf_reg_state *reg, int regno,
5941 			   enum bpf_arg_type arg_type)
5942 {
5943 	enum bpf_reg_type type = reg->type;
5944 	bool fixed_off_ok = false;
5945 
5946 	switch ((u32)type) {
5947 	/* Pointer types where reg offset is explicitly allowed: */
5948 	case PTR_TO_STACK:
5949 		if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5950 			verbose(env, "cannot pass in dynptr at an offset\n");
5951 			return -EINVAL;
5952 		}
5953 		fallthrough;
5954 	case PTR_TO_PACKET:
5955 	case PTR_TO_PACKET_META:
5956 	case PTR_TO_MAP_KEY:
5957 	case PTR_TO_MAP_VALUE:
5958 	case PTR_TO_MEM:
5959 	case PTR_TO_MEM | MEM_RDONLY:
5960 	case PTR_TO_MEM | MEM_ALLOC:
5961 	case PTR_TO_BUF:
5962 	case PTR_TO_BUF | MEM_RDONLY:
5963 	case SCALAR_VALUE:
5964 		/* Some of the argument types nevertheless require a
5965 		 * zero register offset.
5966 		 */
5967 		if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5968 			return 0;
5969 		break;
5970 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5971 	 * fixed offset.
5972 	 */
5973 	case PTR_TO_BTF_ID:
5974 		/* When referenced PTR_TO_BTF_ID is passed to release function,
5975 		 * it's fixed offset must be 0.	In the other cases, fixed offset
5976 		 * can be non-zero.
5977 		 */
5978 		if (arg_type_is_release(arg_type) && reg->off) {
5979 			verbose(env, "R%d must have zero offset when passed to release func\n",
5980 				regno);
5981 			return -EINVAL;
5982 		}
5983 		/* For arg is release pointer, fixed_off_ok must be false, but
5984 		 * we already checked and rejected reg->off != 0 above, so set
5985 		 * to true to allow fixed offset for all other cases.
5986 		 */
5987 		fixed_off_ok = true;
5988 		break;
5989 	default:
5990 		break;
5991 	}
5992 	return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5993 }
5994 
5995 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5996 {
5997 	struct bpf_func_state *state = func(env, reg);
5998 	int spi = get_spi(reg->off);
5999 
6000 	return state->stack[spi].spilled_ptr.id;
6001 }
6002 
6003 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6004 			  struct bpf_call_arg_meta *meta,
6005 			  const struct bpf_func_proto *fn)
6006 {
6007 	u32 regno = BPF_REG_1 + arg;
6008 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6009 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6010 	enum bpf_reg_type type = reg->type;
6011 	u32 *arg_btf_id = NULL;
6012 	int err = 0;
6013 
6014 	if (arg_type == ARG_DONTCARE)
6015 		return 0;
6016 
6017 	err = check_reg_arg(env, regno, SRC_OP);
6018 	if (err)
6019 		return err;
6020 
6021 	if (arg_type == ARG_ANYTHING) {
6022 		if (is_pointer_value(env, regno)) {
6023 			verbose(env, "R%d leaks addr into helper function\n",
6024 				regno);
6025 			return -EACCES;
6026 		}
6027 		return 0;
6028 	}
6029 
6030 	if (type_is_pkt_pointer(type) &&
6031 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6032 		verbose(env, "helper access to the packet is not allowed\n");
6033 		return -EACCES;
6034 	}
6035 
6036 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6037 		err = resolve_map_arg_type(env, meta, &arg_type);
6038 		if (err)
6039 			return err;
6040 	}
6041 
6042 	if (register_is_null(reg) && type_may_be_null(arg_type))
6043 		/* A NULL register has a SCALAR_VALUE type, so skip
6044 		 * type checking.
6045 		 */
6046 		goto skip_type_check;
6047 
6048 	/* arg_btf_id and arg_size are in a union. */
6049 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
6050 		arg_btf_id = fn->arg_btf_id[arg];
6051 
6052 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6053 	if (err)
6054 		return err;
6055 
6056 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6057 	if (err)
6058 		return err;
6059 
6060 skip_type_check:
6061 	if (arg_type_is_release(arg_type)) {
6062 		if (arg_type_is_dynptr(arg_type)) {
6063 			struct bpf_func_state *state = func(env, reg);
6064 			int spi = get_spi(reg->off);
6065 
6066 			if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6067 			    !state->stack[spi].spilled_ptr.id) {
6068 				verbose(env, "arg %d is an unacquired reference\n", regno);
6069 				return -EINVAL;
6070 			}
6071 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6072 			verbose(env, "R%d must be referenced when passed to release function\n",
6073 				regno);
6074 			return -EINVAL;
6075 		}
6076 		if (meta->release_regno) {
6077 			verbose(env, "verifier internal error: more than one release argument\n");
6078 			return -EFAULT;
6079 		}
6080 		meta->release_regno = regno;
6081 	}
6082 
6083 	if (reg->ref_obj_id) {
6084 		if (meta->ref_obj_id) {
6085 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6086 				regno, reg->ref_obj_id,
6087 				meta->ref_obj_id);
6088 			return -EFAULT;
6089 		}
6090 		meta->ref_obj_id = reg->ref_obj_id;
6091 	}
6092 
6093 	switch (base_type(arg_type)) {
6094 	case ARG_CONST_MAP_PTR:
6095 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6096 		if (meta->map_ptr) {
6097 			/* Use map_uid (which is unique id of inner map) to reject:
6098 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6099 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6100 			 * if (inner_map1 && inner_map2) {
6101 			 *     timer = bpf_map_lookup_elem(inner_map1);
6102 			 *     if (timer)
6103 			 *         // mismatch would have been allowed
6104 			 *         bpf_timer_init(timer, inner_map2);
6105 			 * }
6106 			 *
6107 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6108 			 */
6109 			if (meta->map_ptr != reg->map_ptr ||
6110 			    meta->map_uid != reg->map_uid) {
6111 				verbose(env,
6112 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6113 					meta->map_uid, reg->map_uid);
6114 				return -EINVAL;
6115 			}
6116 		}
6117 		meta->map_ptr = reg->map_ptr;
6118 		meta->map_uid = reg->map_uid;
6119 		break;
6120 	case ARG_PTR_TO_MAP_KEY:
6121 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6122 		 * check that [key, key + map->key_size) are within
6123 		 * stack limits and initialized
6124 		 */
6125 		if (!meta->map_ptr) {
6126 			/* in function declaration map_ptr must come before
6127 			 * map_key, so that it's verified and known before
6128 			 * we have to check map_key here. Otherwise it means
6129 			 * that kernel subsystem misconfigured verifier
6130 			 */
6131 			verbose(env, "invalid map_ptr to access map->key\n");
6132 			return -EACCES;
6133 		}
6134 		err = check_helper_mem_access(env, regno,
6135 					      meta->map_ptr->key_size, false,
6136 					      NULL);
6137 		break;
6138 	case ARG_PTR_TO_MAP_VALUE:
6139 		if (type_may_be_null(arg_type) && register_is_null(reg))
6140 			return 0;
6141 
6142 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6143 		 * check [value, value + map->value_size) validity
6144 		 */
6145 		if (!meta->map_ptr) {
6146 			/* kernel subsystem misconfigured verifier */
6147 			verbose(env, "invalid map_ptr to access map->value\n");
6148 			return -EACCES;
6149 		}
6150 		meta->raw_mode = arg_type & MEM_UNINIT;
6151 		err = check_helper_mem_access(env, regno,
6152 					      meta->map_ptr->value_size, false,
6153 					      meta);
6154 		break;
6155 	case ARG_PTR_TO_PERCPU_BTF_ID:
6156 		if (!reg->btf_id) {
6157 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6158 			return -EACCES;
6159 		}
6160 		meta->ret_btf = reg->btf;
6161 		meta->ret_btf_id = reg->btf_id;
6162 		break;
6163 	case ARG_PTR_TO_SPIN_LOCK:
6164 		if (meta->func_id == BPF_FUNC_spin_lock) {
6165 			if (process_spin_lock(env, regno, true))
6166 				return -EACCES;
6167 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6168 			if (process_spin_lock(env, regno, false))
6169 				return -EACCES;
6170 		} else {
6171 			verbose(env, "verifier internal error\n");
6172 			return -EFAULT;
6173 		}
6174 		break;
6175 	case ARG_PTR_TO_TIMER:
6176 		if (process_timer_func(env, regno, meta))
6177 			return -EACCES;
6178 		break;
6179 	case ARG_PTR_TO_FUNC:
6180 		meta->subprogno = reg->subprogno;
6181 		break;
6182 	case ARG_PTR_TO_MEM:
6183 		/* The access to this pointer is only checked when we hit the
6184 		 * next is_mem_size argument below.
6185 		 */
6186 		meta->raw_mode = arg_type & MEM_UNINIT;
6187 		if (arg_type & MEM_FIXED_SIZE) {
6188 			err = check_helper_mem_access(env, regno,
6189 						      fn->arg_size[arg], false,
6190 						      meta);
6191 		}
6192 		break;
6193 	case ARG_CONST_SIZE:
6194 		err = check_mem_size_reg(env, reg, regno, false, meta);
6195 		break;
6196 	case ARG_CONST_SIZE_OR_ZERO:
6197 		err = check_mem_size_reg(env, reg, regno, true, meta);
6198 		break;
6199 	case ARG_PTR_TO_DYNPTR:
6200 		/* We only need to check for initialized / uninitialized helper
6201 		 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6202 		 * assumption is that if it is, that a helper function
6203 		 * initialized the dynptr on behalf of the BPF program.
6204 		 */
6205 		if (base_type(reg->type) == PTR_TO_DYNPTR)
6206 			break;
6207 		if (arg_type & MEM_UNINIT) {
6208 			if (!is_dynptr_reg_valid_uninit(env, reg)) {
6209 				verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6210 				return -EINVAL;
6211 			}
6212 
6213 			/* We only support one dynptr being uninitialized at the moment,
6214 			 * which is sufficient for the helper functions we have right now.
6215 			 */
6216 			if (meta->uninit_dynptr_regno) {
6217 				verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6218 				return -EFAULT;
6219 			}
6220 
6221 			meta->uninit_dynptr_regno = regno;
6222 		} else if (!is_dynptr_reg_valid_init(env, reg)) {
6223 			verbose(env,
6224 				"Expected an initialized dynptr as arg #%d\n",
6225 				arg + 1);
6226 			return -EINVAL;
6227 		} else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6228 			const char *err_extra = "";
6229 
6230 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6231 			case DYNPTR_TYPE_LOCAL:
6232 				err_extra = "local";
6233 				break;
6234 			case DYNPTR_TYPE_RINGBUF:
6235 				err_extra = "ringbuf";
6236 				break;
6237 			default:
6238 				err_extra = "<unknown>";
6239 				break;
6240 			}
6241 			verbose(env,
6242 				"Expected a dynptr of type %s as arg #%d\n",
6243 				err_extra, arg + 1);
6244 			return -EINVAL;
6245 		}
6246 		break;
6247 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6248 		if (!tnum_is_const(reg->var_off)) {
6249 			verbose(env, "R%d is not a known constant'\n",
6250 				regno);
6251 			return -EACCES;
6252 		}
6253 		meta->mem_size = reg->var_off.value;
6254 		err = mark_chain_precision(env, regno);
6255 		if (err)
6256 			return err;
6257 		break;
6258 	case ARG_PTR_TO_INT:
6259 	case ARG_PTR_TO_LONG:
6260 	{
6261 		int size = int_ptr_type_to_size(arg_type);
6262 
6263 		err = check_helper_mem_access(env, regno, size, false, meta);
6264 		if (err)
6265 			return err;
6266 		err = check_ptr_alignment(env, reg, 0, size, true);
6267 		break;
6268 	}
6269 	case ARG_PTR_TO_CONST_STR:
6270 	{
6271 		struct bpf_map *map = reg->map_ptr;
6272 		int map_off;
6273 		u64 map_addr;
6274 		char *str_ptr;
6275 
6276 		if (!bpf_map_is_rdonly(map)) {
6277 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6278 			return -EACCES;
6279 		}
6280 
6281 		if (!tnum_is_const(reg->var_off)) {
6282 			verbose(env, "R%d is not a constant address'\n", regno);
6283 			return -EACCES;
6284 		}
6285 
6286 		if (!map->ops->map_direct_value_addr) {
6287 			verbose(env, "no direct value access support for this map type\n");
6288 			return -EACCES;
6289 		}
6290 
6291 		err = check_map_access(env, regno, reg->off,
6292 				       map->value_size - reg->off, false,
6293 				       ACCESS_HELPER);
6294 		if (err)
6295 			return err;
6296 
6297 		map_off = reg->off + reg->var_off.value;
6298 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6299 		if (err) {
6300 			verbose(env, "direct value access on string failed\n");
6301 			return err;
6302 		}
6303 
6304 		str_ptr = (char *)(long)(map_addr);
6305 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6306 			verbose(env, "string is not zero-terminated\n");
6307 			return -EINVAL;
6308 		}
6309 		break;
6310 	}
6311 	case ARG_PTR_TO_KPTR:
6312 		if (process_kptr_func(env, regno, meta))
6313 			return -EACCES;
6314 		break;
6315 	}
6316 
6317 	return err;
6318 }
6319 
6320 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6321 {
6322 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6323 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6324 
6325 	if (func_id != BPF_FUNC_map_update_elem)
6326 		return false;
6327 
6328 	/* It's not possible to get access to a locked struct sock in these
6329 	 * contexts, so updating is safe.
6330 	 */
6331 	switch (type) {
6332 	case BPF_PROG_TYPE_TRACING:
6333 		if (eatype == BPF_TRACE_ITER)
6334 			return true;
6335 		break;
6336 	case BPF_PROG_TYPE_SOCKET_FILTER:
6337 	case BPF_PROG_TYPE_SCHED_CLS:
6338 	case BPF_PROG_TYPE_SCHED_ACT:
6339 	case BPF_PROG_TYPE_XDP:
6340 	case BPF_PROG_TYPE_SK_REUSEPORT:
6341 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6342 	case BPF_PROG_TYPE_SK_LOOKUP:
6343 		return true;
6344 	default:
6345 		break;
6346 	}
6347 
6348 	verbose(env, "cannot update sockmap in this context\n");
6349 	return false;
6350 }
6351 
6352 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6353 {
6354 	return env->prog->jit_requested &&
6355 	       bpf_jit_supports_subprog_tailcalls();
6356 }
6357 
6358 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6359 					struct bpf_map *map, int func_id)
6360 {
6361 	if (!map)
6362 		return 0;
6363 
6364 	/* We need a two way check, first is from map perspective ... */
6365 	switch (map->map_type) {
6366 	case BPF_MAP_TYPE_PROG_ARRAY:
6367 		if (func_id != BPF_FUNC_tail_call)
6368 			goto error;
6369 		break;
6370 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6371 		if (func_id != BPF_FUNC_perf_event_read &&
6372 		    func_id != BPF_FUNC_perf_event_output &&
6373 		    func_id != BPF_FUNC_skb_output &&
6374 		    func_id != BPF_FUNC_perf_event_read_value &&
6375 		    func_id != BPF_FUNC_xdp_output)
6376 			goto error;
6377 		break;
6378 	case BPF_MAP_TYPE_RINGBUF:
6379 		if (func_id != BPF_FUNC_ringbuf_output &&
6380 		    func_id != BPF_FUNC_ringbuf_reserve &&
6381 		    func_id != BPF_FUNC_ringbuf_query &&
6382 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6383 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6384 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6385 			goto error;
6386 		break;
6387 	case BPF_MAP_TYPE_USER_RINGBUF:
6388 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6389 			goto error;
6390 		break;
6391 	case BPF_MAP_TYPE_STACK_TRACE:
6392 		if (func_id != BPF_FUNC_get_stackid)
6393 			goto error;
6394 		break;
6395 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6396 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6397 		    func_id != BPF_FUNC_current_task_under_cgroup)
6398 			goto error;
6399 		break;
6400 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6401 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6402 		if (func_id != BPF_FUNC_get_local_storage)
6403 			goto error;
6404 		break;
6405 	case BPF_MAP_TYPE_DEVMAP:
6406 	case BPF_MAP_TYPE_DEVMAP_HASH:
6407 		if (func_id != BPF_FUNC_redirect_map &&
6408 		    func_id != BPF_FUNC_map_lookup_elem)
6409 			goto error;
6410 		break;
6411 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6412 	 * appear.
6413 	 */
6414 	case BPF_MAP_TYPE_CPUMAP:
6415 		if (func_id != BPF_FUNC_redirect_map)
6416 			goto error;
6417 		break;
6418 	case BPF_MAP_TYPE_XSKMAP:
6419 		if (func_id != BPF_FUNC_redirect_map &&
6420 		    func_id != BPF_FUNC_map_lookup_elem)
6421 			goto error;
6422 		break;
6423 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6424 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6425 		if (func_id != BPF_FUNC_map_lookup_elem)
6426 			goto error;
6427 		break;
6428 	case BPF_MAP_TYPE_SOCKMAP:
6429 		if (func_id != BPF_FUNC_sk_redirect_map &&
6430 		    func_id != BPF_FUNC_sock_map_update &&
6431 		    func_id != BPF_FUNC_map_delete_elem &&
6432 		    func_id != BPF_FUNC_msg_redirect_map &&
6433 		    func_id != BPF_FUNC_sk_select_reuseport &&
6434 		    func_id != BPF_FUNC_map_lookup_elem &&
6435 		    !may_update_sockmap(env, func_id))
6436 			goto error;
6437 		break;
6438 	case BPF_MAP_TYPE_SOCKHASH:
6439 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6440 		    func_id != BPF_FUNC_sock_hash_update &&
6441 		    func_id != BPF_FUNC_map_delete_elem &&
6442 		    func_id != BPF_FUNC_msg_redirect_hash &&
6443 		    func_id != BPF_FUNC_sk_select_reuseport &&
6444 		    func_id != BPF_FUNC_map_lookup_elem &&
6445 		    !may_update_sockmap(env, func_id))
6446 			goto error;
6447 		break;
6448 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6449 		if (func_id != BPF_FUNC_sk_select_reuseport)
6450 			goto error;
6451 		break;
6452 	case BPF_MAP_TYPE_QUEUE:
6453 	case BPF_MAP_TYPE_STACK:
6454 		if (func_id != BPF_FUNC_map_peek_elem &&
6455 		    func_id != BPF_FUNC_map_pop_elem &&
6456 		    func_id != BPF_FUNC_map_push_elem)
6457 			goto error;
6458 		break;
6459 	case BPF_MAP_TYPE_SK_STORAGE:
6460 		if (func_id != BPF_FUNC_sk_storage_get &&
6461 		    func_id != BPF_FUNC_sk_storage_delete)
6462 			goto error;
6463 		break;
6464 	case BPF_MAP_TYPE_INODE_STORAGE:
6465 		if (func_id != BPF_FUNC_inode_storage_get &&
6466 		    func_id != BPF_FUNC_inode_storage_delete)
6467 			goto error;
6468 		break;
6469 	case BPF_MAP_TYPE_TASK_STORAGE:
6470 		if (func_id != BPF_FUNC_task_storage_get &&
6471 		    func_id != BPF_FUNC_task_storage_delete)
6472 			goto error;
6473 		break;
6474 	case BPF_MAP_TYPE_CGRP_STORAGE:
6475 		if (func_id != BPF_FUNC_cgrp_storage_get &&
6476 		    func_id != BPF_FUNC_cgrp_storage_delete)
6477 			goto error;
6478 		break;
6479 	case BPF_MAP_TYPE_BLOOM_FILTER:
6480 		if (func_id != BPF_FUNC_map_peek_elem &&
6481 		    func_id != BPF_FUNC_map_push_elem)
6482 			goto error;
6483 		break;
6484 	default:
6485 		break;
6486 	}
6487 
6488 	/* ... and second from the function itself. */
6489 	switch (func_id) {
6490 	case BPF_FUNC_tail_call:
6491 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6492 			goto error;
6493 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6494 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6495 			return -EINVAL;
6496 		}
6497 		break;
6498 	case BPF_FUNC_perf_event_read:
6499 	case BPF_FUNC_perf_event_output:
6500 	case BPF_FUNC_perf_event_read_value:
6501 	case BPF_FUNC_skb_output:
6502 	case BPF_FUNC_xdp_output:
6503 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6504 			goto error;
6505 		break;
6506 	case BPF_FUNC_ringbuf_output:
6507 	case BPF_FUNC_ringbuf_reserve:
6508 	case BPF_FUNC_ringbuf_query:
6509 	case BPF_FUNC_ringbuf_reserve_dynptr:
6510 	case BPF_FUNC_ringbuf_submit_dynptr:
6511 	case BPF_FUNC_ringbuf_discard_dynptr:
6512 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6513 			goto error;
6514 		break;
6515 	case BPF_FUNC_user_ringbuf_drain:
6516 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6517 			goto error;
6518 		break;
6519 	case BPF_FUNC_get_stackid:
6520 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6521 			goto error;
6522 		break;
6523 	case BPF_FUNC_current_task_under_cgroup:
6524 	case BPF_FUNC_skb_under_cgroup:
6525 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6526 			goto error;
6527 		break;
6528 	case BPF_FUNC_redirect_map:
6529 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6530 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6531 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6532 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6533 			goto error;
6534 		break;
6535 	case BPF_FUNC_sk_redirect_map:
6536 	case BPF_FUNC_msg_redirect_map:
6537 	case BPF_FUNC_sock_map_update:
6538 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6539 			goto error;
6540 		break;
6541 	case BPF_FUNC_sk_redirect_hash:
6542 	case BPF_FUNC_msg_redirect_hash:
6543 	case BPF_FUNC_sock_hash_update:
6544 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6545 			goto error;
6546 		break;
6547 	case BPF_FUNC_get_local_storage:
6548 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6549 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6550 			goto error;
6551 		break;
6552 	case BPF_FUNC_sk_select_reuseport:
6553 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6554 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6555 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6556 			goto error;
6557 		break;
6558 	case BPF_FUNC_map_pop_elem:
6559 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6560 		    map->map_type != BPF_MAP_TYPE_STACK)
6561 			goto error;
6562 		break;
6563 	case BPF_FUNC_map_peek_elem:
6564 	case BPF_FUNC_map_push_elem:
6565 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6566 		    map->map_type != BPF_MAP_TYPE_STACK &&
6567 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6568 			goto error;
6569 		break;
6570 	case BPF_FUNC_map_lookup_percpu_elem:
6571 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6572 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6573 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6574 			goto error;
6575 		break;
6576 	case BPF_FUNC_sk_storage_get:
6577 	case BPF_FUNC_sk_storage_delete:
6578 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6579 			goto error;
6580 		break;
6581 	case BPF_FUNC_inode_storage_get:
6582 	case BPF_FUNC_inode_storage_delete:
6583 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6584 			goto error;
6585 		break;
6586 	case BPF_FUNC_task_storage_get:
6587 	case BPF_FUNC_task_storage_delete:
6588 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6589 			goto error;
6590 		break;
6591 	case BPF_FUNC_cgrp_storage_get:
6592 	case BPF_FUNC_cgrp_storage_delete:
6593 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6594 			goto error;
6595 		break;
6596 	default:
6597 		break;
6598 	}
6599 
6600 	return 0;
6601 error:
6602 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6603 		map->map_type, func_id_name(func_id), func_id);
6604 	return -EINVAL;
6605 }
6606 
6607 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6608 {
6609 	int count = 0;
6610 
6611 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6612 		count++;
6613 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6614 		count++;
6615 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6616 		count++;
6617 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6618 		count++;
6619 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6620 		count++;
6621 
6622 	/* We only support one arg being in raw mode at the moment,
6623 	 * which is sufficient for the helper functions we have
6624 	 * right now.
6625 	 */
6626 	return count <= 1;
6627 }
6628 
6629 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6630 {
6631 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6632 	bool has_size = fn->arg_size[arg] != 0;
6633 	bool is_next_size = false;
6634 
6635 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6636 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6637 
6638 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6639 		return is_next_size;
6640 
6641 	return has_size == is_next_size || is_next_size == is_fixed;
6642 }
6643 
6644 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6645 {
6646 	/* bpf_xxx(..., buf, len) call will access 'len'
6647 	 * bytes from memory 'buf'. Both arg types need
6648 	 * to be paired, so make sure there's no buggy
6649 	 * helper function specification.
6650 	 */
6651 	if (arg_type_is_mem_size(fn->arg1_type) ||
6652 	    check_args_pair_invalid(fn, 0) ||
6653 	    check_args_pair_invalid(fn, 1) ||
6654 	    check_args_pair_invalid(fn, 2) ||
6655 	    check_args_pair_invalid(fn, 3) ||
6656 	    check_args_pair_invalid(fn, 4))
6657 		return false;
6658 
6659 	return true;
6660 }
6661 
6662 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6663 {
6664 	int i;
6665 
6666 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6667 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6668 			return false;
6669 
6670 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6671 		    /* arg_btf_id and arg_size are in a union. */
6672 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6673 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6674 			return false;
6675 	}
6676 
6677 	return true;
6678 }
6679 
6680 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6681 {
6682 	return check_raw_mode_ok(fn) &&
6683 	       check_arg_pair_ok(fn) &&
6684 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
6685 }
6686 
6687 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6688  * are now invalid, so turn them into unknown SCALAR_VALUE.
6689  */
6690 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6691 {
6692 	struct bpf_func_state *state;
6693 	struct bpf_reg_state *reg;
6694 
6695 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6696 		if (reg_is_pkt_pointer_any(reg))
6697 			__mark_reg_unknown(env, reg);
6698 	}));
6699 }
6700 
6701 enum {
6702 	AT_PKT_END = -1,
6703 	BEYOND_PKT_END = -2,
6704 };
6705 
6706 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6707 {
6708 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6709 	struct bpf_reg_state *reg = &state->regs[regn];
6710 
6711 	if (reg->type != PTR_TO_PACKET)
6712 		/* PTR_TO_PACKET_META is not supported yet */
6713 		return;
6714 
6715 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6716 	 * How far beyond pkt_end it goes is unknown.
6717 	 * if (!range_open) it's the case of pkt >= pkt_end
6718 	 * if (range_open) it's the case of pkt > pkt_end
6719 	 * hence this pointer is at least 1 byte bigger than pkt_end
6720 	 */
6721 	if (range_open)
6722 		reg->range = BEYOND_PKT_END;
6723 	else
6724 		reg->range = AT_PKT_END;
6725 }
6726 
6727 /* The pointer with the specified id has released its reference to kernel
6728  * resources. Identify all copies of the same pointer and clear the reference.
6729  */
6730 static int release_reference(struct bpf_verifier_env *env,
6731 			     int ref_obj_id)
6732 {
6733 	struct bpf_func_state *state;
6734 	struct bpf_reg_state *reg;
6735 	int err;
6736 
6737 	err = release_reference_state(cur_func(env), ref_obj_id);
6738 	if (err)
6739 		return err;
6740 
6741 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6742 		if (reg->ref_obj_id == ref_obj_id) {
6743 			if (!env->allow_ptr_leaks)
6744 				__mark_reg_not_init(env, reg);
6745 			else
6746 				__mark_reg_unknown(env, reg);
6747 		}
6748 	}));
6749 
6750 	return 0;
6751 }
6752 
6753 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6754 				    struct bpf_reg_state *regs)
6755 {
6756 	int i;
6757 
6758 	/* after the call registers r0 - r5 were scratched */
6759 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6760 		mark_reg_not_init(env, regs, caller_saved[i]);
6761 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6762 	}
6763 }
6764 
6765 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6766 				   struct bpf_func_state *caller,
6767 				   struct bpf_func_state *callee,
6768 				   int insn_idx);
6769 
6770 static int set_callee_state(struct bpf_verifier_env *env,
6771 			    struct bpf_func_state *caller,
6772 			    struct bpf_func_state *callee, int insn_idx);
6773 
6774 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6775 			     int *insn_idx, int subprog,
6776 			     set_callee_state_fn set_callee_state_cb)
6777 {
6778 	struct bpf_verifier_state *state = env->cur_state;
6779 	struct bpf_func_info_aux *func_info_aux;
6780 	struct bpf_func_state *caller, *callee;
6781 	int err;
6782 	bool is_global = false;
6783 
6784 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6785 		verbose(env, "the call stack of %d frames is too deep\n",
6786 			state->curframe + 2);
6787 		return -E2BIG;
6788 	}
6789 
6790 	caller = state->frame[state->curframe];
6791 	if (state->frame[state->curframe + 1]) {
6792 		verbose(env, "verifier bug. Frame %d already allocated\n",
6793 			state->curframe + 1);
6794 		return -EFAULT;
6795 	}
6796 
6797 	func_info_aux = env->prog->aux->func_info_aux;
6798 	if (func_info_aux)
6799 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6800 	err = btf_check_subprog_call(env, subprog, caller->regs);
6801 	if (err == -EFAULT)
6802 		return err;
6803 	if (is_global) {
6804 		if (err) {
6805 			verbose(env, "Caller passes invalid args into func#%d\n",
6806 				subprog);
6807 			return err;
6808 		} else {
6809 			if (env->log.level & BPF_LOG_LEVEL)
6810 				verbose(env,
6811 					"Func#%d is global and valid. Skipping.\n",
6812 					subprog);
6813 			clear_caller_saved_regs(env, caller->regs);
6814 
6815 			/* All global functions return a 64-bit SCALAR_VALUE */
6816 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6817 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6818 
6819 			/* continue with next insn after call */
6820 			return 0;
6821 		}
6822 	}
6823 
6824 	/* set_callee_state is used for direct subprog calls, but we are
6825 	 * interested in validating only BPF helpers that can call subprogs as
6826 	 * callbacks
6827 	 */
6828 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6829 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6830 			func_id_name(insn->imm), insn->imm);
6831 		return -EFAULT;
6832 	}
6833 
6834 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6835 	    insn->src_reg == 0 &&
6836 	    insn->imm == BPF_FUNC_timer_set_callback) {
6837 		struct bpf_verifier_state *async_cb;
6838 
6839 		/* there is no real recursion here. timer callbacks are async */
6840 		env->subprog_info[subprog].is_async_cb = true;
6841 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6842 					 *insn_idx, subprog);
6843 		if (!async_cb)
6844 			return -EFAULT;
6845 		callee = async_cb->frame[0];
6846 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6847 
6848 		/* Convert bpf_timer_set_callback() args into timer callback args */
6849 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6850 		if (err)
6851 			return err;
6852 
6853 		clear_caller_saved_regs(env, caller->regs);
6854 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6855 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6856 		/* continue with next insn after call */
6857 		return 0;
6858 	}
6859 
6860 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6861 	if (!callee)
6862 		return -ENOMEM;
6863 	state->frame[state->curframe + 1] = callee;
6864 
6865 	/* callee cannot access r0, r6 - r9 for reading and has to write
6866 	 * into its own stack before reading from it.
6867 	 * callee can read/write into caller's stack
6868 	 */
6869 	init_func_state(env, callee,
6870 			/* remember the callsite, it will be used by bpf_exit */
6871 			*insn_idx /* callsite */,
6872 			state->curframe + 1 /* frameno within this callchain */,
6873 			subprog /* subprog number within this prog */);
6874 
6875 	/* Transfer references to the callee */
6876 	err = copy_reference_state(callee, caller);
6877 	if (err)
6878 		goto err_out;
6879 
6880 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6881 	if (err)
6882 		goto err_out;
6883 
6884 	clear_caller_saved_regs(env, caller->regs);
6885 
6886 	/* only increment it after check_reg_arg() finished */
6887 	state->curframe++;
6888 
6889 	/* and go analyze first insn of the callee */
6890 	*insn_idx = env->subprog_info[subprog].start - 1;
6891 
6892 	if (env->log.level & BPF_LOG_LEVEL) {
6893 		verbose(env, "caller:\n");
6894 		print_verifier_state(env, caller, true);
6895 		verbose(env, "callee:\n");
6896 		print_verifier_state(env, callee, true);
6897 	}
6898 	return 0;
6899 
6900 err_out:
6901 	free_func_state(callee);
6902 	state->frame[state->curframe + 1] = NULL;
6903 	return err;
6904 }
6905 
6906 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6907 				   struct bpf_func_state *caller,
6908 				   struct bpf_func_state *callee)
6909 {
6910 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6911 	 *      void *callback_ctx, u64 flags);
6912 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6913 	 *      void *callback_ctx);
6914 	 */
6915 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6916 
6917 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6918 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6919 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6920 
6921 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6922 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6923 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6924 
6925 	/* pointer to stack or null */
6926 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6927 
6928 	/* unused */
6929 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6930 	return 0;
6931 }
6932 
6933 static int set_callee_state(struct bpf_verifier_env *env,
6934 			    struct bpf_func_state *caller,
6935 			    struct bpf_func_state *callee, int insn_idx)
6936 {
6937 	int i;
6938 
6939 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6940 	 * pointers, which connects us up to the liveness chain
6941 	 */
6942 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6943 		callee->regs[i] = caller->regs[i];
6944 	return 0;
6945 }
6946 
6947 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6948 			   int *insn_idx)
6949 {
6950 	int subprog, target_insn;
6951 
6952 	target_insn = *insn_idx + insn->imm + 1;
6953 	subprog = find_subprog(env, target_insn);
6954 	if (subprog < 0) {
6955 		verbose(env, "verifier bug. No program starts at insn %d\n",
6956 			target_insn);
6957 		return -EFAULT;
6958 	}
6959 
6960 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6961 }
6962 
6963 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6964 				       struct bpf_func_state *caller,
6965 				       struct bpf_func_state *callee,
6966 				       int insn_idx)
6967 {
6968 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6969 	struct bpf_map *map;
6970 	int err;
6971 
6972 	if (bpf_map_ptr_poisoned(insn_aux)) {
6973 		verbose(env, "tail_call abusing map_ptr\n");
6974 		return -EINVAL;
6975 	}
6976 
6977 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6978 	if (!map->ops->map_set_for_each_callback_args ||
6979 	    !map->ops->map_for_each_callback) {
6980 		verbose(env, "callback function not allowed for map\n");
6981 		return -ENOTSUPP;
6982 	}
6983 
6984 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6985 	if (err)
6986 		return err;
6987 
6988 	callee->in_callback_fn = true;
6989 	callee->callback_ret_range = tnum_range(0, 1);
6990 	return 0;
6991 }
6992 
6993 static int set_loop_callback_state(struct bpf_verifier_env *env,
6994 				   struct bpf_func_state *caller,
6995 				   struct bpf_func_state *callee,
6996 				   int insn_idx)
6997 {
6998 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6999 	 *	    u64 flags);
7000 	 * callback_fn(u32 index, void *callback_ctx);
7001 	 */
7002 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7003 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7004 
7005 	/* unused */
7006 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7007 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7008 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7009 
7010 	callee->in_callback_fn = true;
7011 	callee->callback_ret_range = tnum_range(0, 1);
7012 	return 0;
7013 }
7014 
7015 static int set_timer_callback_state(struct bpf_verifier_env *env,
7016 				    struct bpf_func_state *caller,
7017 				    struct bpf_func_state *callee,
7018 				    int insn_idx)
7019 {
7020 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7021 
7022 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7023 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7024 	 */
7025 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7026 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7027 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7028 
7029 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7030 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7031 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7032 
7033 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7034 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7035 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7036 
7037 	/* unused */
7038 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7039 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7040 	callee->in_async_callback_fn = true;
7041 	callee->callback_ret_range = tnum_range(0, 1);
7042 	return 0;
7043 }
7044 
7045 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7046 				       struct bpf_func_state *caller,
7047 				       struct bpf_func_state *callee,
7048 				       int insn_idx)
7049 {
7050 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7051 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7052 	 * (callback_fn)(struct task_struct *task,
7053 	 *               struct vm_area_struct *vma, void *callback_ctx);
7054 	 */
7055 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7056 
7057 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7058 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7059 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7060 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7061 
7062 	/* pointer to stack or null */
7063 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7064 
7065 	/* unused */
7066 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7067 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7068 	callee->in_callback_fn = true;
7069 	callee->callback_ret_range = tnum_range(0, 1);
7070 	return 0;
7071 }
7072 
7073 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7074 					   struct bpf_func_state *caller,
7075 					   struct bpf_func_state *callee,
7076 					   int insn_idx)
7077 {
7078 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7079 	 *			  callback_ctx, u64 flags);
7080 	 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7081 	 */
7082 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7083 	callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7084 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7085 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7086 
7087 	/* unused */
7088 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7089 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7090 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7091 
7092 	callee->in_callback_fn = true;
7093 	callee->callback_ret_range = tnum_range(0, 1);
7094 	return 0;
7095 }
7096 
7097 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7098 {
7099 	struct bpf_verifier_state *state = env->cur_state;
7100 	struct bpf_func_state *caller, *callee;
7101 	struct bpf_reg_state *r0;
7102 	int err;
7103 
7104 	callee = state->frame[state->curframe];
7105 	r0 = &callee->regs[BPF_REG_0];
7106 	if (r0->type == PTR_TO_STACK) {
7107 		/* technically it's ok to return caller's stack pointer
7108 		 * (or caller's caller's pointer) back to the caller,
7109 		 * since these pointers are valid. Only current stack
7110 		 * pointer will be invalid as soon as function exits,
7111 		 * but let's be conservative
7112 		 */
7113 		verbose(env, "cannot return stack pointer to the caller\n");
7114 		return -EINVAL;
7115 	}
7116 
7117 	caller = state->frame[state->curframe - 1];
7118 	if (callee->in_callback_fn) {
7119 		/* enforce R0 return value range [0, 1]. */
7120 		struct tnum range = callee->callback_ret_range;
7121 
7122 		if (r0->type != SCALAR_VALUE) {
7123 			verbose(env, "R0 not a scalar value\n");
7124 			return -EACCES;
7125 		}
7126 		if (!tnum_in(range, r0->var_off)) {
7127 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7128 			return -EINVAL;
7129 		}
7130 	} else {
7131 		/* return to the caller whatever r0 had in the callee */
7132 		caller->regs[BPF_REG_0] = *r0;
7133 	}
7134 
7135 	/* callback_fn frame should have released its own additions to parent's
7136 	 * reference state at this point, or check_reference_leak would
7137 	 * complain, hence it must be the same as the caller. There is no need
7138 	 * to copy it back.
7139 	 */
7140 	if (!callee->in_callback_fn) {
7141 		/* Transfer references to the caller */
7142 		err = copy_reference_state(caller, callee);
7143 		if (err)
7144 			return err;
7145 	}
7146 
7147 	*insn_idx = callee->callsite + 1;
7148 	if (env->log.level & BPF_LOG_LEVEL) {
7149 		verbose(env, "returning from callee:\n");
7150 		print_verifier_state(env, callee, true);
7151 		verbose(env, "to caller at %d:\n", *insn_idx);
7152 		print_verifier_state(env, caller, true);
7153 	}
7154 	/* clear everything in the callee */
7155 	free_func_state(callee);
7156 	state->frame[state->curframe--] = NULL;
7157 	return 0;
7158 }
7159 
7160 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7161 				   int func_id,
7162 				   struct bpf_call_arg_meta *meta)
7163 {
7164 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7165 
7166 	if (ret_type != RET_INTEGER ||
7167 	    (func_id != BPF_FUNC_get_stack &&
7168 	     func_id != BPF_FUNC_get_task_stack &&
7169 	     func_id != BPF_FUNC_probe_read_str &&
7170 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7171 	     func_id != BPF_FUNC_probe_read_user_str))
7172 		return;
7173 
7174 	ret_reg->smax_value = meta->msize_max_value;
7175 	ret_reg->s32_max_value = meta->msize_max_value;
7176 	ret_reg->smin_value = -MAX_ERRNO;
7177 	ret_reg->s32_min_value = -MAX_ERRNO;
7178 	reg_bounds_sync(ret_reg);
7179 }
7180 
7181 static int
7182 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7183 		int func_id, int insn_idx)
7184 {
7185 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7186 	struct bpf_map *map = meta->map_ptr;
7187 
7188 	if (func_id != BPF_FUNC_tail_call &&
7189 	    func_id != BPF_FUNC_map_lookup_elem &&
7190 	    func_id != BPF_FUNC_map_update_elem &&
7191 	    func_id != BPF_FUNC_map_delete_elem &&
7192 	    func_id != BPF_FUNC_map_push_elem &&
7193 	    func_id != BPF_FUNC_map_pop_elem &&
7194 	    func_id != BPF_FUNC_map_peek_elem &&
7195 	    func_id != BPF_FUNC_for_each_map_elem &&
7196 	    func_id != BPF_FUNC_redirect_map &&
7197 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7198 		return 0;
7199 
7200 	if (map == NULL) {
7201 		verbose(env, "kernel subsystem misconfigured verifier\n");
7202 		return -EINVAL;
7203 	}
7204 
7205 	/* In case of read-only, some additional restrictions
7206 	 * need to be applied in order to prevent altering the
7207 	 * state of the map from program side.
7208 	 */
7209 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7210 	    (func_id == BPF_FUNC_map_delete_elem ||
7211 	     func_id == BPF_FUNC_map_update_elem ||
7212 	     func_id == BPF_FUNC_map_push_elem ||
7213 	     func_id == BPF_FUNC_map_pop_elem)) {
7214 		verbose(env, "write into map forbidden\n");
7215 		return -EACCES;
7216 	}
7217 
7218 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7219 		bpf_map_ptr_store(aux, meta->map_ptr,
7220 				  !meta->map_ptr->bypass_spec_v1);
7221 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7222 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7223 				  !meta->map_ptr->bypass_spec_v1);
7224 	return 0;
7225 }
7226 
7227 static int
7228 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7229 		int func_id, int insn_idx)
7230 {
7231 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7232 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7233 	struct bpf_map *map = meta->map_ptr;
7234 	u64 val, max;
7235 	int err;
7236 
7237 	if (func_id != BPF_FUNC_tail_call)
7238 		return 0;
7239 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7240 		verbose(env, "kernel subsystem misconfigured verifier\n");
7241 		return -EINVAL;
7242 	}
7243 
7244 	reg = &regs[BPF_REG_3];
7245 	val = reg->var_off.value;
7246 	max = map->max_entries;
7247 
7248 	if (!(register_is_const(reg) && val < max)) {
7249 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7250 		return 0;
7251 	}
7252 
7253 	err = mark_chain_precision(env, BPF_REG_3);
7254 	if (err)
7255 		return err;
7256 	if (bpf_map_key_unseen(aux))
7257 		bpf_map_key_store(aux, val);
7258 	else if (!bpf_map_key_poisoned(aux) &&
7259 		  bpf_map_key_immediate(aux) != val)
7260 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7261 	return 0;
7262 }
7263 
7264 static int check_reference_leak(struct bpf_verifier_env *env)
7265 {
7266 	struct bpf_func_state *state = cur_func(env);
7267 	bool refs_lingering = false;
7268 	int i;
7269 
7270 	if (state->frameno && !state->in_callback_fn)
7271 		return 0;
7272 
7273 	for (i = 0; i < state->acquired_refs; i++) {
7274 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7275 			continue;
7276 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7277 			state->refs[i].id, state->refs[i].insn_idx);
7278 		refs_lingering = true;
7279 	}
7280 	return refs_lingering ? -EINVAL : 0;
7281 }
7282 
7283 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7284 				   struct bpf_reg_state *regs)
7285 {
7286 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7287 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7288 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7289 	int err, fmt_map_off, num_args;
7290 	u64 fmt_addr;
7291 	char *fmt;
7292 
7293 	/* data must be an array of u64 */
7294 	if (data_len_reg->var_off.value % 8)
7295 		return -EINVAL;
7296 	num_args = data_len_reg->var_off.value / 8;
7297 
7298 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7299 	 * and map_direct_value_addr is set.
7300 	 */
7301 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7302 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7303 						  fmt_map_off);
7304 	if (err) {
7305 		verbose(env, "verifier bug\n");
7306 		return -EFAULT;
7307 	}
7308 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7309 
7310 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7311 	 * can focus on validating the format specifiers.
7312 	 */
7313 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7314 	if (err < 0)
7315 		verbose(env, "Invalid format string\n");
7316 
7317 	return err;
7318 }
7319 
7320 static int check_get_func_ip(struct bpf_verifier_env *env)
7321 {
7322 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7323 	int func_id = BPF_FUNC_get_func_ip;
7324 
7325 	if (type == BPF_PROG_TYPE_TRACING) {
7326 		if (!bpf_prog_has_trampoline(env->prog)) {
7327 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7328 				func_id_name(func_id), func_id);
7329 			return -ENOTSUPP;
7330 		}
7331 		return 0;
7332 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7333 		return 0;
7334 	}
7335 
7336 	verbose(env, "func %s#%d not supported for program type %d\n",
7337 		func_id_name(func_id), func_id, type);
7338 	return -ENOTSUPP;
7339 }
7340 
7341 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7342 {
7343 	return &env->insn_aux_data[env->insn_idx];
7344 }
7345 
7346 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7347 {
7348 	struct bpf_reg_state *regs = cur_regs(env);
7349 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7350 	bool reg_is_null = register_is_null(reg);
7351 
7352 	if (reg_is_null)
7353 		mark_chain_precision(env, BPF_REG_4);
7354 
7355 	return reg_is_null;
7356 }
7357 
7358 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7359 {
7360 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7361 
7362 	if (!state->initialized) {
7363 		state->initialized = 1;
7364 		state->fit_for_inline = loop_flag_is_zero(env);
7365 		state->callback_subprogno = subprogno;
7366 		return;
7367 	}
7368 
7369 	if (!state->fit_for_inline)
7370 		return;
7371 
7372 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7373 				 state->callback_subprogno == subprogno);
7374 }
7375 
7376 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7377 			     int *insn_idx_p)
7378 {
7379 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7380 	const struct bpf_func_proto *fn = NULL;
7381 	enum bpf_return_type ret_type;
7382 	enum bpf_type_flag ret_flag;
7383 	struct bpf_reg_state *regs;
7384 	struct bpf_call_arg_meta meta;
7385 	int insn_idx = *insn_idx_p;
7386 	bool changes_data;
7387 	int i, err, func_id;
7388 
7389 	/* find function prototype */
7390 	func_id = insn->imm;
7391 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7392 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7393 			func_id);
7394 		return -EINVAL;
7395 	}
7396 
7397 	if (env->ops->get_func_proto)
7398 		fn = env->ops->get_func_proto(func_id, env->prog);
7399 	if (!fn) {
7400 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7401 			func_id);
7402 		return -EINVAL;
7403 	}
7404 
7405 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7406 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7407 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7408 		return -EINVAL;
7409 	}
7410 
7411 	if (fn->allowed && !fn->allowed(env->prog)) {
7412 		verbose(env, "helper call is not allowed in probe\n");
7413 		return -EINVAL;
7414 	}
7415 
7416 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7417 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7418 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7419 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7420 			func_id_name(func_id), func_id);
7421 		return -EINVAL;
7422 	}
7423 
7424 	memset(&meta, 0, sizeof(meta));
7425 	meta.pkt_access = fn->pkt_access;
7426 
7427 	err = check_func_proto(fn, func_id);
7428 	if (err) {
7429 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7430 			func_id_name(func_id), func_id);
7431 		return err;
7432 	}
7433 
7434 	meta.func_id = func_id;
7435 	/* check args */
7436 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7437 		err = check_func_arg(env, i, &meta, fn);
7438 		if (err)
7439 			return err;
7440 	}
7441 
7442 	err = record_func_map(env, &meta, func_id, insn_idx);
7443 	if (err)
7444 		return err;
7445 
7446 	err = record_func_key(env, &meta, func_id, insn_idx);
7447 	if (err)
7448 		return err;
7449 
7450 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7451 	 * is inferred from register state.
7452 	 */
7453 	for (i = 0; i < meta.access_size; i++) {
7454 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7455 				       BPF_WRITE, -1, false);
7456 		if (err)
7457 			return err;
7458 	}
7459 
7460 	regs = cur_regs(env);
7461 
7462 	if (meta.uninit_dynptr_regno) {
7463 		/* we write BPF_DW bits (8 bytes) at a time */
7464 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7465 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7466 					       i, BPF_DW, BPF_WRITE, -1, false);
7467 			if (err)
7468 				return err;
7469 		}
7470 
7471 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7472 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7473 					      insn_idx);
7474 		if (err)
7475 			return err;
7476 	}
7477 
7478 	if (meta.release_regno) {
7479 		err = -EINVAL;
7480 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7481 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7482 		else if (meta.ref_obj_id)
7483 			err = release_reference(env, meta.ref_obj_id);
7484 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7485 		 * released is NULL, which must be > R0.
7486 		 */
7487 		else if (register_is_null(&regs[meta.release_regno]))
7488 			err = 0;
7489 		if (err) {
7490 			verbose(env, "func %s#%d reference has not been acquired before\n",
7491 				func_id_name(func_id), func_id);
7492 			return err;
7493 		}
7494 	}
7495 
7496 	switch (func_id) {
7497 	case BPF_FUNC_tail_call:
7498 		err = check_reference_leak(env);
7499 		if (err) {
7500 			verbose(env, "tail_call would lead to reference leak\n");
7501 			return err;
7502 		}
7503 		break;
7504 	case BPF_FUNC_get_local_storage:
7505 		/* check that flags argument in get_local_storage(map, flags) is 0,
7506 		 * this is required because get_local_storage() can't return an error.
7507 		 */
7508 		if (!register_is_null(&regs[BPF_REG_2])) {
7509 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7510 			return -EINVAL;
7511 		}
7512 		break;
7513 	case BPF_FUNC_for_each_map_elem:
7514 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7515 					set_map_elem_callback_state);
7516 		break;
7517 	case BPF_FUNC_timer_set_callback:
7518 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7519 					set_timer_callback_state);
7520 		break;
7521 	case BPF_FUNC_find_vma:
7522 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7523 					set_find_vma_callback_state);
7524 		break;
7525 	case BPF_FUNC_snprintf:
7526 		err = check_bpf_snprintf_call(env, regs);
7527 		break;
7528 	case BPF_FUNC_loop:
7529 		update_loop_inline_state(env, meta.subprogno);
7530 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7531 					set_loop_callback_state);
7532 		break;
7533 	case BPF_FUNC_dynptr_from_mem:
7534 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7535 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7536 				reg_type_str(env, regs[BPF_REG_1].type));
7537 			return -EACCES;
7538 		}
7539 		break;
7540 	case BPF_FUNC_set_retval:
7541 		if (prog_type == BPF_PROG_TYPE_LSM &&
7542 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7543 			if (!env->prog->aux->attach_func_proto->type) {
7544 				/* Make sure programs that attach to void
7545 				 * hooks don't try to modify return value.
7546 				 */
7547 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7548 				return -EINVAL;
7549 			}
7550 		}
7551 		break;
7552 	case BPF_FUNC_dynptr_data:
7553 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7554 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7555 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7556 
7557 				if (meta.ref_obj_id) {
7558 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7559 					return -EFAULT;
7560 				}
7561 
7562 				if (base_type(reg->type) != PTR_TO_DYNPTR)
7563 					/* Find the id of the dynptr we're
7564 					 * tracking the reference of
7565 					 */
7566 					meta.ref_obj_id = stack_slot_get_id(env, reg);
7567 				break;
7568 			}
7569 		}
7570 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7571 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7572 			return -EFAULT;
7573 		}
7574 		break;
7575 	case BPF_FUNC_user_ringbuf_drain:
7576 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7577 					set_user_ringbuf_callback_state);
7578 		break;
7579 	}
7580 
7581 	if (err)
7582 		return err;
7583 
7584 	/* reset caller saved regs */
7585 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7586 		mark_reg_not_init(env, regs, caller_saved[i]);
7587 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7588 	}
7589 
7590 	/* helper call returns 64-bit value. */
7591 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7592 
7593 	/* update return register (already marked as written above) */
7594 	ret_type = fn->ret_type;
7595 	ret_flag = type_flag(ret_type);
7596 
7597 	switch (base_type(ret_type)) {
7598 	case RET_INTEGER:
7599 		/* sets type to SCALAR_VALUE */
7600 		mark_reg_unknown(env, regs, BPF_REG_0);
7601 		break;
7602 	case RET_VOID:
7603 		regs[BPF_REG_0].type = NOT_INIT;
7604 		break;
7605 	case RET_PTR_TO_MAP_VALUE:
7606 		/* There is no offset yet applied, variable or fixed */
7607 		mark_reg_known_zero(env, regs, BPF_REG_0);
7608 		/* remember map_ptr, so that check_map_access()
7609 		 * can check 'value_size' boundary of memory access
7610 		 * to map element returned from bpf_map_lookup_elem()
7611 		 */
7612 		if (meta.map_ptr == NULL) {
7613 			verbose(env,
7614 				"kernel subsystem misconfigured verifier\n");
7615 			return -EINVAL;
7616 		}
7617 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7618 		regs[BPF_REG_0].map_uid = meta.map_uid;
7619 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7620 		if (!type_may_be_null(ret_type) &&
7621 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7622 			regs[BPF_REG_0].id = ++env->id_gen;
7623 		}
7624 		break;
7625 	case RET_PTR_TO_SOCKET:
7626 		mark_reg_known_zero(env, regs, BPF_REG_0);
7627 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7628 		break;
7629 	case RET_PTR_TO_SOCK_COMMON:
7630 		mark_reg_known_zero(env, regs, BPF_REG_0);
7631 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7632 		break;
7633 	case RET_PTR_TO_TCP_SOCK:
7634 		mark_reg_known_zero(env, regs, BPF_REG_0);
7635 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7636 		break;
7637 	case RET_PTR_TO_ALLOC_MEM:
7638 		mark_reg_known_zero(env, regs, BPF_REG_0);
7639 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7640 		regs[BPF_REG_0].mem_size = meta.mem_size;
7641 		break;
7642 	case RET_PTR_TO_MEM_OR_BTF_ID:
7643 	{
7644 		const struct btf_type *t;
7645 
7646 		mark_reg_known_zero(env, regs, BPF_REG_0);
7647 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7648 		if (!btf_type_is_struct(t)) {
7649 			u32 tsize;
7650 			const struct btf_type *ret;
7651 			const char *tname;
7652 
7653 			/* resolve the type size of ksym. */
7654 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7655 			if (IS_ERR(ret)) {
7656 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7657 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7658 					tname, PTR_ERR(ret));
7659 				return -EINVAL;
7660 			}
7661 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7662 			regs[BPF_REG_0].mem_size = tsize;
7663 		} else {
7664 			/* MEM_RDONLY may be carried from ret_flag, but it
7665 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7666 			 * it will confuse the check of PTR_TO_BTF_ID in
7667 			 * check_mem_access().
7668 			 */
7669 			ret_flag &= ~MEM_RDONLY;
7670 
7671 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7672 			regs[BPF_REG_0].btf = meta.ret_btf;
7673 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7674 		}
7675 		break;
7676 	}
7677 	case RET_PTR_TO_BTF_ID:
7678 	{
7679 		struct btf *ret_btf;
7680 		int ret_btf_id;
7681 
7682 		mark_reg_known_zero(env, regs, BPF_REG_0);
7683 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7684 		if (func_id == BPF_FUNC_kptr_xchg) {
7685 			ret_btf = meta.kptr_field->kptr.btf;
7686 			ret_btf_id = meta.kptr_field->kptr.btf_id;
7687 		} else {
7688 			if (fn->ret_btf_id == BPF_PTR_POISON) {
7689 				verbose(env, "verifier internal error:");
7690 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7691 					func_id_name(func_id));
7692 				return -EINVAL;
7693 			}
7694 			ret_btf = btf_vmlinux;
7695 			ret_btf_id = *fn->ret_btf_id;
7696 		}
7697 		if (ret_btf_id == 0) {
7698 			verbose(env, "invalid return type %u of func %s#%d\n",
7699 				base_type(ret_type), func_id_name(func_id),
7700 				func_id);
7701 			return -EINVAL;
7702 		}
7703 		regs[BPF_REG_0].btf = ret_btf;
7704 		regs[BPF_REG_0].btf_id = ret_btf_id;
7705 		break;
7706 	}
7707 	default:
7708 		verbose(env, "unknown return type %u of func %s#%d\n",
7709 			base_type(ret_type), func_id_name(func_id), func_id);
7710 		return -EINVAL;
7711 	}
7712 
7713 	if (type_may_be_null(regs[BPF_REG_0].type))
7714 		regs[BPF_REG_0].id = ++env->id_gen;
7715 
7716 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7717 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7718 			func_id_name(func_id), func_id);
7719 		return -EFAULT;
7720 	}
7721 
7722 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7723 		/* For release_reference() */
7724 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7725 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7726 		int id = acquire_reference_state(env, insn_idx);
7727 
7728 		if (id < 0)
7729 			return id;
7730 		/* For mark_ptr_or_null_reg() */
7731 		regs[BPF_REG_0].id = id;
7732 		/* For release_reference() */
7733 		regs[BPF_REG_0].ref_obj_id = id;
7734 	}
7735 
7736 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7737 
7738 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7739 	if (err)
7740 		return err;
7741 
7742 	if ((func_id == BPF_FUNC_get_stack ||
7743 	     func_id == BPF_FUNC_get_task_stack) &&
7744 	    !env->prog->has_callchain_buf) {
7745 		const char *err_str;
7746 
7747 #ifdef CONFIG_PERF_EVENTS
7748 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7749 		err_str = "cannot get callchain buffer for func %s#%d\n";
7750 #else
7751 		err = -ENOTSUPP;
7752 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7753 #endif
7754 		if (err) {
7755 			verbose(env, err_str, func_id_name(func_id), func_id);
7756 			return err;
7757 		}
7758 
7759 		env->prog->has_callchain_buf = true;
7760 	}
7761 
7762 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7763 		env->prog->call_get_stack = true;
7764 
7765 	if (func_id == BPF_FUNC_get_func_ip) {
7766 		if (check_get_func_ip(env))
7767 			return -ENOTSUPP;
7768 		env->prog->call_get_func_ip = true;
7769 	}
7770 
7771 	if (changes_data)
7772 		clear_all_pkt_pointers(env);
7773 	return 0;
7774 }
7775 
7776 /* mark_btf_func_reg_size() is used when the reg size is determined by
7777  * the BTF func_proto's return value size and argument.
7778  */
7779 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7780 				   size_t reg_size)
7781 {
7782 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7783 
7784 	if (regno == BPF_REG_0) {
7785 		/* Function return value */
7786 		reg->live |= REG_LIVE_WRITTEN;
7787 		reg->subreg_def = reg_size == sizeof(u64) ?
7788 			DEF_NOT_SUBREG : env->insn_idx + 1;
7789 	} else {
7790 		/* Function argument */
7791 		if (reg_size == sizeof(u64)) {
7792 			mark_insn_zext(env, reg);
7793 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7794 		} else {
7795 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7796 		}
7797 	}
7798 }
7799 
7800 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7801 			    int *insn_idx_p)
7802 {
7803 	const struct btf_type *t, *func, *func_proto, *ptr_type;
7804 	struct bpf_reg_state *regs = cur_regs(env);
7805 	struct bpf_kfunc_arg_meta meta = { 0 };
7806 	const char *func_name, *ptr_type_name;
7807 	u32 i, nargs, func_id, ptr_type_id;
7808 	int err, insn_idx = *insn_idx_p;
7809 	const struct btf_param *args;
7810 	struct btf *desc_btf;
7811 	u32 *kfunc_flags;
7812 	bool acq;
7813 
7814 	/* skip for now, but return error when we find this in fixup_kfunc_call */
7815 	if (!insn->imm)
7816 		return 0;
7817 
7818 	desc_btf = find_kfunc_desc_btf(env, insn->off);
7819 	if (IS_ERR(desc_btf))
7820 		return PTR_ERR(desc_btf);
7821 
7822 	func_id = insn->imm;
7823 	func = btf_type_by_id(desc_btf, func_id);
7824 	func_name = btf_name_by_offset(desc_btf, func->name_off);
7825 	func_proto = btf_type_by_id(desc_btf, func->type);
7826 
7827 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7828 	if (!kfunc_flags) {
7829 		verbose(env, "calling kernel function %s is not allowed\n",
7830 			func_name);
7831 		return -EACCES;
7832 	}
7833 	if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7834 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7835 		return -EACCES;
7836 	}
7837 
7838 	acq = *kfunc_flags & KF_ACQUIRE;
7839 
7840 	meta.flags = *kfunc_flags;
7841 
7842 	/* Check the arguments */
7843 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7844 	if (err < 0)
7845 		return err;
7846 	/* In case of release function, we get register number of refcounted
7847 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7848 	 */
7849 	if (err) {
7850 		err = release_reference(env, regs[err].ref_obj_id);
7851 		if (err) {
7852 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7853 				func_name, func_id);
7854 			return err;
7855 		}
7856 	}
7857 
7858 	for (i = 0; i < CALLER_SAVED_REGS; i++)
7859 		mark_reg_not_init(env, regs, caller_saved[i]);
7860 
7861 	/* Check return type */
7862 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7863 
7864 	if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7865 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7866 		return -EINVAL;
7867 	}
7868 
7869 	if (btf_type_is_scalar(t)) {
7870 		mark_reg_unknown(env, regs, BPF_REG_0);
7871 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7872 	} else if (btf_type_is_ptr(t)) {
7873 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7874 						   &ptr_type_id);
7875 		if (!btf_type_is_struct(ptr_type)) {
7876 			if (!meta.r0_size) {
7877 				ptr_type_name = btf_name_by_offset(desc_btf,
7878 								   ptr_type->name_off);
7879 				verbose(env,
7880 					"kernel function %s returns pointer type %s %s is not supported\n",
7881 					func_name,
7882 					btf_type_str(ptr_type),
7883 					ptr_type_name);
7884 				return -EINVAL;
7885 			}
7886 
7887 			mark_reg_known_zero(env, regs, BPF_REG_0);
7888 			regs[BPF_REG_0].type = PTR_TO_MEM;
7889 			regs[BPF_REG_0].mem_size = meta.r0_size;
7890 
7891 			if (meta.r0_rdonly)
7892 				regs[BPF_REG_0].type |= MEM_RDONLY;
7893 
7894 			/* Ensures we don't access the memory after a release_reference() */
7895 			if (meta.ref_obj_id)
7896 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7897 		} else {
7898 			mark_reg_known_zero(env, regs, BPF_REG_0);
7899 			regs[BPF_REG_0].btf = desc_btf;
7900 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7901 			regs[BPF_REG_0].btf_id = ptr_type_id;
7902 		}
7903 		if (*kfunc_flags & KF_RET_NULL) {
7904 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7905 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7906 			regs[BPF_REG_0].id = ++env->id_gen;
7907 		}
7908 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7909 		if (acq) {
7910 			int id = acquire_reference_state(env, insn_idx);
7911 
7912 			if (id < 0)
7913 				return id;
7914 			regs[BPF_REG_0].id = id;
7915 			regs[BPF_REG_0].ref_obj_id = id;
7916 		}
7917 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7918 
7919 	nargs = btf_type_vlen(func_proto);
7920 	args = (const struct btf_param *)(func_proto + 1);
7921 	for (i = 0; i < nargs; i++) {
7922 		u32 regno = i + 1;
7923 
7924 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7925 		if (btf_type_is_ptr(t))
7926 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7927 		else
7928 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7929 			mark_btf_func_reg_size(env, regno, t->size);
7930 	}
7931 
7932 	return 0;
7933 }
7934 
7935 static bool signed_add_overflows(s64 a, s64 b)
7936 {
7937 	/* Do the add in u64, where overflow is well-defined */
7938 	s64 res = (s64)((u64)a + (u64)b);
7939 
7940 	if (b < 0)
7941 		return res > a;
7942 	return res < a;
7943 }
7944 
7945 static bool signed_add32_overflows(s32 a, s32 b)
7946 {
7947 	/* Do the add in u32, where overflow is well-defined */
7948 	s32 res = (s32)((u32)a + (u32)b);
7949 
7950 	if (b < 0)
7951 		return res > a;
7952 	return res < a;
7953 }
7954 
7955 static bool signed_sub_overflows(s64 a, s64 b)
7956 {
7957 	/* Do the sub in u64, where overflow is well-defined */
7958 	s64 res = (s64)((u64)a - (u64)b);
7959 
7960 	if (b < 0)
7961 		return res < a;
7962 	return res > a;
7963 }
7964 
7965 static bool signed_sub32_overflows(s32 a, s32 b)
7966 {
7967 	/* Do the sub in u32, where overflow is well-defined */
7968 	s32 res = (s32)((u32)a - (u32)b);
7969 
7970 	if (b < 0)
7971 		return res < a;
7972 	return res > a;
7973 }
7974 
7975 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7976 				  const struct bpf_reg_state *reg,
7977 				  enum bpf_reg_type type)
7978 {
7979 	bool known = tnum_is_const(reg->var_off);
7980 	s64 val = reg->var_off.value;
7981 	s64 smin = reg->smin_value;
7982 
7983 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7984 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7985 			reg_type_str(env, type), val);
7986 		return false;
7987 	}
7988 
7989 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7990 		verbose(env, "%s pointer offset %d is not allowed\n",
7991 			reg_type_str(env, type), reg->off);
7992 		return false;
7993 	}
7994 
7995 	if (smin == S64_MIN) {
7996 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7997 			reg_type_str(env, type));
7998 		return false;
7999 	}
8000 
8001 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
8002 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
8003 			smin, reg_type_str(env, type));
8004 		return false;
8005 	}
8006 
8007 	return true;
8008 }
8009 
8010 enum {
8011 	REASON_BOUNDS	= -1,
8012 	REASON_TYPE	= -2,
8013 	REASON_PATHS	= -3,
8014 	REASON_LIMIT	= -4,
8015 	REASON_STACK	= -5,
8016 };
8017 
8018 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
8019 			      u32 *alu_limit, bool mask_to_left)
8020 {
8021 	u32 max = 0, ptr_limit = 0;
8022 
8023 	switch (ptr_reg->type) {
8024 	case PTR_TO_STACK:
8025 		/* Offset 0 is out-of-bounds, but acceptable start for the
8026 		 * left direction, see BPF_REG_FP. Also, unknown scalar
8027 		 * offset where we would need to deal with min/max bounds is
8028 		 * currently prohibited for unprivileged.
8029 		 */
8030 		max = MAX_BPF_STACK + mask_to_left;
8031 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
8032 		break;
8033 	case PTR_TO_MAP_VALUE:
8034 		max = ptr_reg->map_ptr->value_size;
8035 		ptr_limit = (mask_to_left ?
8036 			     ptr_reg->smin_value :
8037 			     ptr_reg->umax_value) + ptr_reg->off;
8038 		break;
8039 	default:
8040 		return REASON_TYPE;
8041 	}
8042 
8043 	if (ptr_limit >= max)
8044 		return REASON_LIMIT;
8045 	*alu_limit = ptr_limit;
8046 	return 0;
8047 }
8048 
8049 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
8050 				    const struct bpf_insn *insn)
8051 {
8052 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
8053 }
8054 
8055 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
8056 				       u32 alu_state, u32 alu_limit)
8057 {
8058 	/* If we arrived here from different branches with different
8059 	 * state or limits to sanitize, then this won't work.
8060 	 */
8061 	if (aux->alu_state &&
8062 	    (aux->alu_state != alu_state ||
8063 	     aux->alu_limit != alu_limit))
8064 		return REASON_PATHS;
8065 
8066 	/* Corresponding fixup done in do_misc_fixups(). */
8067 	aux->alu_state = alu_state;
8068 	aux->alu_limit = alu_limit;
8069 	return 0;
8070 }
8071 
8072 static int sanitize_val_alu(struct bpf_verifier_env *env,
8073 			    struct bpf_insn *insn)
8074 {
8075 	struct bpf_insn_aux_data *aux = cur_aux(env);
8076 
8077 	if (can_skip_alu_sanitation(env, insn))
8078 		return 0;
8079 
8080 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8081 }
8082 
8083 static bool sanitize_needed(u8 opcode)
8084 {
8085 	return opcode == BPF_ADD || opcode == BPF_SUB;
8086 }
8087 
8088 struct bpf_sanitize_info {
8089 	struct bpf_insn_aux_data aux;
8090 	bool mask_to_left;
8091 };
8092 
8093 static struct bpf_verifier_state *
8094 sanitize_speculative_path(struct bpf_verifier_env *env,
8095 			  const struct bpf_insn *insn,
8096 			  u32 next_idx, u32 curr_idx)
8097 {
8098 	struct bpf_verifier_state *branch;
8099 	struct bpf_reg_state *regs;
8100 
8101 	branch = push_stack(env, next_idx, curr_idx, true);
8102 	if (branch && insn) {
8103 		regs = branch->frame[branch->curframe]->regs;
8104 		if (BPF_SRC(insn->code) == BPF_K) {
8105 			mark_reg_unknown(env, regs, insn->dst_reg);
8106 		} else if (BPF_SRC(insn->code) == BPF_X) {
8107 			mark_reg_unknown(env, regs, insn->dst_reg);
8108 			mark_reg_unknown(env, regs, insn->src_reg);
8109 		}
8110 	}
8111 	return branch;
8112 }
8113 
8114 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8115 			    struct bpf_insn *insn,
8116 			    const struct bpf_reg_state *ptr_reg,
8117 			    const struct bpf_reg_state *off_reg,
8118 			    struct bpf_reg_state *dst_reg,
8119 			    struct bpf_sanitize_info *info,
8120 			    const bool commit_window)
8121 {
8122 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8123 	struct bpf_verifier_state *vstate = env->cur_state;
8124 	bool off_is_imm = tnum_is_const(off_reg->var_off);
8125 	bool off_is_neg = off_reg->smin_value < 0;
8126 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
8127 	u8 opcode = BPF_OP(insn->code);
8128 	u32 alu_state, alu_limit;
8129 	struct bpf_reg_state tmp;
8130 	bool ret;
8131 	int err;
8132 
8133 	if (can_skip_alu_sanitation(env, insn))
8134 		return 0;
8135 
8136 	/* We already marked aux for masking from non-speculative
8137 	 * paths, thus we got here in the first place. We only care
8138 	 * to explore bad access from here.
8139 	 */
8140 	if (vstate->speculative)
8141 		goto do_sim;
8142 
8143 	if (!commit_window) {
8144 		if (!tnum_is_const(off_reg->var_off) &&
8145 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8146 			return REASON_BOUNDS;
8147 
8148 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8149 				     (opcode == BPF_SUB && !off_is_neg);
8150 	}
8151 
8152 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8153 	if (err < 0)
8154 		return err;
8155 
8156 	if (commit_window) {
8157 		/* In commit phase we narrow the masking window based on
8158 		 * the observed pointer move after the simulated operation.
8159 		 */
8160 		alu_state = info->aux.alu_state;
8161 		alu_limit = abs(info->aux.alu_limit - alu_limit);
8162 	} else {
8163 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8164 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8165 		alu_state |= ptr_is_dst_reg ?
8166 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8167 
8168 		/* Limit pruning on unknown scalars to enable deep search for
8169 		 * potential masking differences from other program paths.
8170 		 */
8171 		if (!off_is_imm)
8172 			env->explore_alu_limits = true;
8173 	}
8174 
8175 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8176 	if (err < 0)
8177 		return err;
8178 do_sim:
8179 	/* If we're in commit phase, we're done here given we already
8180 	 * pushed the truncated dst_reg into the speculative verification
8181 	 * stack.
8182 	 *
8183 	 * Also, when register is a known constant, we rewrite register-based
8184 	 * operation to immediate-based, and thus do not need masking (and as
8185 	 * a consequence, do not need to simulate the zero-truncation either).
8186 	 */
8187 	if (commit_window || off_is_imm)
8188 		return 0;
8189 
8190 	/* Simulate and find potential out-of-bounds access under
8191 	 * speculative execution from truncation as a result of
8192 	 * masking when off was not within expected range. If off
8193 	 * sits in dst, then we temporarily need to move ptr there
8194 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8195 	 * for cases where we use K-based arithmetic in one direction
8196 	 * and truncated reg-based in the other in order to explore
8197 	 * bad access.
8198 	 */
8199 	if (!ptr_is_dst_reg) {
8200 		tmp = *dst_reg;
8201 		*dst_reg = *ptr_reg;
8202 	}
8203 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8204 					env->insn_idx);
8205 	if (!ptr_is_dst_reg && ret)
8206 		*dst_reg = tmp;
8207 	return !ret ? REASON_STACK : 0;
8208 }
8209 
8210 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8211 {
8212 	struct bpf_verifier_state *vstate = env->cur_state;
8213 
8214 	/* If we simulate paths under speculation, we don't update the
8215 	 * insn as 'seen' such that when we verify unreachable paths in
8216 	 * the non-speculative domain, sanitize_dead_code() can still
8217 	 * rewrite/sanitize them.
8218 	 */
8219 	if (!vstate->speculative)
8220 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8221 }
8222 
8223 static int sanitize_err(struct bpf_verifier_env *env,
8224 			const struct bpf_insn *insn, int reason,
8225 			const struct bpf_reg_state *off_reg,
8226 			const struct bpf_reg_state *dst_reg)
8227 {
8228 	static const char *err = "pointer arithmetic with it prohibited for !root";
8229 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8230 	u32 dst = insn->dst_reg, src = insn->src_reg;
8231 
8232 	switch (reason) {
8233 	case REASON_BOUNDS:
8234 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8235 			off_reg == dst_reg ? dst : src, err);
8236 		break;
8237 	case REASON_TYPE:
8238 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8239 			off_reg == dst_reg ? src : dst, err);
8240 		break;
8241 	case REASON_PATHS:
8242 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8243 			dst, op, err);
8244 		break;
8245 	case REASON_LIMIT:
8246 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8247 			dst, op, err);
8248 		break;
8249 	case REASON_STACK:
8250 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8251 			dst, err);
8252 		break;
8253 	default:
8254 		verbose(env, "verifier internal error: unknown reason (%d)\n",
8255 			reason);
8256 		break;
8257 	}
8258 
8259 	return -EACCES;
8260 }
8261 
8262 /* check that stack access falls within stack limits and that 'reg' doesn't
8263  * have a variable offset.
8264  *
8265  * Variable offset is prohibited for unprivileged mode for simplicity since it
8266  * requires corresponding support in Spectre masking for stack ALU.  See also
8267  * retrieve_ptr_limit().
8268  *
8269  *
8270  * 'off' includes 'reg->off'.
8271  */
8272 static int check_stack_access_for_ptr_arithmetic(
8273 				struct bpf_verifier_env *env,
8274 				int regno,
8275 				const struct bpf_reg_state *reg,
8276 				int off)
8277 {
8278 	if (!tnum_is_const(reg->var_off)) {
8279 		char tn_buf[48];
8280 
8281 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8282 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8283 			regno, tn_buf, off);
8284 		return -EACCES;
8285 	}
8286 
8287 	if (off >= 0 || off < -MAX_BPF_STACK) {
8288 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
8289 			"prohibited for !root; off=%d\n", regno, off);
8290 		return -EACCES;
8291 	}
8292 
8293 	return 0;
8294 }
8295 
8296 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8297 				 const struct bpf_insn *insn,
8298 				 const struct bpf_reg_state *dst_reg)
8299 {
8300 	u32 dst = insn->dst_reg;
8301 
8302 	/* For unprivileged we require that resulting offset must be in bounds
8303 	 * in order to be able to sanitize access later on.
8304 	 */
8305 	if (env->bypass_spec_v1)
8306 		return 0;
8307 
8308 	switch (dst_reg->type) {
8309 	case PTR_TO_STACK:
8310 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8311 					dst_reg->off + dst_reg->var_off.value))
8312 			return -EACCES;
8313 		break;
8314 	case PTR_TO_MAP_VALUE:
8315 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8316 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8317 				"prohibited for !root\n", dst);
8318 			return -EACCES;
8319 		}
8320 		break;
8321 	default:
8322 		break;
8323 	}
8324 
8325 	return 0;
8326 }
8327 
8328 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8329  * Caller should also handle BPF_MOV case separately.
8330  * If we return -EACCES, caller may want to try again treating pointer as a
8331  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8332  */
8333 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8334 				   struct bpf_insn *insn,
8335 				   const struct bpf_reg_state *ptr_reg,
8336 				   const struct bpf_reg_state *off_reg)
8337 {
8338 	struct bpf_verifier_state *vstate = env->cur_state;
8339 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8340 	struct bpf_reg_state *regs = state->regs, *dst_reg;
8341 	bool known = tnum_is_const(off_reg->var_off);
8342 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8343 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8344 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8345 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8346 	struct bpf_sanitize_info info = {};
8347 	u8 opcode = BPF_OP(insn->code);
8348 	u32 dst = insn->dst_reg;
8349 	int ret;
8350 
8351 	dst_reg = &regs[dst];
8352 
8353 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8354 	    smin_val > smax_val || umin_val > umax_val) {
8355 		/* Taint dst register if offset had invalid bounds derived from
8356 		 * e.g. dead branches.
8357 		 */
8358 		__mark_reg_unknown(env, dst_reg);
8359 		return 0;
8360 	}
8361 
8362 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
8363 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
8364 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8365 			__mark_reg_unknown(env, dst_reg);
8366 			return 0;
8367 		}
8368 
8369 		verbose(env,
8370 			"R%d 32-bit pointer arithmetic prohibited\n",
8371 			dst);
8372 		return -EACCES;
8373 	}
8374 
8375 	if (ptr_reg->type & PTR_MAYBE_NULL) {
8376 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8377 			dst, reg_type_str(env, ptr_reg->type));
8378 		return -EACCES;
8379 	}
8380 
8381 	switch (base_type(ptr_reg->type)) {
8382 	case CONST_PTR_TO_MAP:
8383 		/* smin_val represents the known value */
8384 		if (known && smin_val == 0 && opcode == BPF_ADD)
8385 			break;
8386 		fallthrough;
8387 	case PTR_TO_PACKET_END:
8388 	case PTR_TO_SOCKET:
8389 	case PTR_TO_SOCK_COMMON:
8390 	case PTR_TO_TCP_SOCK:
8391 	case PTR_TO_XDP_SOCK:
8392 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8393 			dst, reg_type_str(env, ptr_reg->type));
8394 		return -EACCES;
8395 	default:
8396 		break;
8397 	}
8398 
8399 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8400 	 * The id may be overwritten later if we create a new variable offset.
8401 	 */
8402 	dst_reg->type = ptr_reg->type;
8403 	dst_reg->id = ptr_reg->id;
8404 
8405 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8406 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8407 		return -EINVAL;
8408 
8409 	/* pointer types do not carry 32-bit bounds at the moment. */
8410 	__mark_reg32_unbounded(dst_reg);
8411 
8412 	if (sanitize_needed(opcode)) {
8413 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8414 				       &info, false);
8415 		if (ret < 0)
8416 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8417 	}
8418 
8419 	switch (opcode) {
8420 	case BPF_ADD:
8421 		/* We can take a fixed offset as long as it doesn't overflow
8422 		 * the s32 'off' field
8423 		 */
8424 		if (known && (ptr_reg->off + smin_val ==
8425 			      (s64)(s32)(ptr_reg->off + smin_val))) {
8426 			/* pointer += K.  Accumulate it into fixed offset */
8427 			dst_reg->smin_value = smin_ptr;
8428 			dst_reg->smax_value = smax_ptr;
8429 			dst_reg->umin_value = umin_ptr;
8430 			dst_reg->umax_value = umax_ptr;
8431 			dst_reg->var_off = ptr_reg->var_off;
8432 			dst_reg->off = ptr_reg->off + smin_val;
8433 			dst_reg->raw = ptr_reg->raw;
8434 			break;
8435 		}
8436 		/* A new variable offset is created.  Note that off_reg->off
8437 		 * == 0, since it's a scalar.
8438 		 * dst_reg gets the pointer type and since some positive
8439 		 * integer value was added to the pointer, give it a new 'id'
8440 		 * if it's a PTR_TO_PACKET.
8441 		 * this creates a new 'base' pointer, off_reg (variable) gets
8442 		 * added into the variable offset, and we copy the fixed offset
8443 		 * from ptr_reg.
8444 		 */
8445 		if (signed_add_overflows(smin_ptr, smin_val) ||
8446 		    signed_add_overflows(smax_ptr, smax_val)) {
8447 			dst_reg->smin_value = S64_MIN;
8448 			dst_reg->smax_value = S64_MAX;
8449 		} else {
8450 			dst_reg->smin_value = smin_ptr + smin_val;
8451 			dst_reg->smax_value = smax_ptr + smax_val;
8452 		}
8453 		if (umin_ptr + umin_val < umin_ptr ||
8454 		    umax_ptr + umax_val < umax_ptr) {
8455 			dst_reg->umin_value = 0;
8456 			dst_reg->umax_value = U64_MAX;
8457 		} else {
8458 			dst_reg->umin_value = umin_ptr + umin_val;
8459 			dst_reg->umax_value = umax_ptr + umax_val;
8460 		}
8461 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8462 		dst_reg->off = ptr_reg->off;
8463 		dst_reg->raw = ptr_reg->raw;
8464 		if (reg_is_pkt_pointer(ptr_reg)) {
8465 			dst_reg->id = ++env->id_gen;
8466 			/* something was added to pkt_ptr, set range to zero */
8467 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8468 		}
8469 		break;
8470 	case BPF_SUB:
8471 		if (dst_reg == off_reg) {
8472 			/* scalar -= pointer.  Creates an unknown scalar */
8473 			verbose(env, "R%d tried to subtract pointer from scalar\n",
8474 				dst);
8475 			return -EACCES;
8476 		}
8477 		/* We don't allow subtraction from FP, because (according to
8478 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
8479 		 * be able to deal with it.
8480 		 */
8481 		if (ptr_reg->type == PTR_TO_STACK) {
8482 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
8483 				dst);
8484 			return -EACCES;
8485 		}
8486 		if (known && (ptr_reg->off - smin_val ==
8487 			      (s64)(s32)(ptr_reg->off - smin_val))) {
8488 			/* pointer -= K.  Subtract it from fixed offset */
8489 			dst_reg->smin_value = smin_ptr;
8490 			dst_reg->smax_value = smax_ptr;
8491 			dst_reg->umin_value = umin_ptr;
8492 			dst_reg->umax_value = umax_ptr;
8493 			dst_reg->var_off = ptr_reg->var_off;
8494 			dst_reg->id = ptr_reg->id;
8495 			dst_reg->off = ptr_reg->off - smin_val;
8496 			dst_reg->raw = ptr_reg->raw;
8497 			break;
8498 		}
8499 		/* A new variable offset is created.  If the subtrahend is known
8500 		 * nonnegative, then any reg->range we had before is still good.
8501 		 */
8502 		if (signed_sub_overflows(smin_ptr, smax_val) ||
8503 		    signed_sub_overflows(smax_ptr, smin_val)) {
8504 			/* Overflow possible, we know nothing */
8505 			dst_reg->smin_value = S64_MIN;
8506 			dst_reg->smax_value = S64_MAX;
8507 		} else {
8508 			dst_reg->smin_value = smin_ptr - smax_val;
8509 			dst_reg->smax_value = smax_ptr - smin_val;
8510 		}
8511 		if (umin_ptr < umax_val) {
8512 			/* Overflow possible, we know nothing */
8513 			dst_reg->umin_value = 0;
8514 			dst_reg->umax_value = U64_MAX;
8515 		} else {
8516 			/* Cannot overflow (as long as bounds are consistent) */
8517 			dst_reg->umin_value = umin_ptr - umax_val;
8518 			dst_reg->umax_value = umax_ptr - umin_val;
8519 		}
8520 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8521 		dst_reg->off = ptr_reg->off;
8522 		dst_reg->raw = ptr_reg->raw;
8523 		if (reg_is_pkt_pointer(ptr_reg)) {
8524 			dst_reg->id = ++env->id_gen;
8525 			/* something was added to pkt_ptr, set range to zero */
8526 			if (smin_val < 0)
8527 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8528 		}
8529 		break;
8530 	case BPF_AND:
8531 	case BPF_OR:
8532 	case BPF_XOR:
8533 		/* bitwise ops on pointers are troublesome, prohibit. */
8534 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8535 			dst, bpf_alu_string[opcode >> 4]);
8536 		return -EACCES;
8537 	default:
8538 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
8539 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8540 			dst, bpf_alu_string[opcode >> 4]);
8541 		return -EACCES;
8542 	}
8543 
8544 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8545 		return -EINVAL;
8546 	reg_bounds_sync(dst_reg);
8547 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8548 		return -EACCES;
8549 	if (sanitize_needed(opcode)) {
8550 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8551 				       &info, true);
8552 		if (ret < 0)
8553 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8554 	}
8555 
8556 	return 0;
8557 }
8558 
8559 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8560 				 struct bpf_reg_state *src_reg)
8561 {
8562 	s32 smin_val = src_reg->s32_min_value;
8563 	s32 smax_val = src_reg->s32_max_value;
8564 	u32 umin_val = src_reg->u32_min_value;
8565 	u32 umax_val = src_reg->u32_max_value;
8566 
8567 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8568 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8569 		dst_reg->s32_min_value = S32_MIN;
8570 		dst_reg->s32_max_value = S32_MAX;
8571 	} else {
8572 		dst_reg->s32_min_value += smin_val;
8573 		dst_reg->s32_max_value += smax_val;
8574 	}
8575 	if (dst_reg->u32_min_value + umin_val < umin_val ||
8576 	    dst_reg->u32_max_value + umax_val < umax_val) {
8577 		dst_reg->u32_min_value = 0;
8578 		dst_reg->u32_max_value = U32_MAX;
8579 	} else {
8580 		dst_reg->u32_min_value += umin_val;
8581 		dst_reg->u32_max_value += umax_val;
8582 	}
8583 }
8584 
8585 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8586 			       struct bpf_reg_state *src_reg)
8587 {
8588 	s64 smin_val = src_reg->smin_value;
8589 	s64 smax_val = src_reg->smax_value;
8590 	u64 umin_val = src_reg->umin_value;
8591 	u64 umax_val = src_reg->umax_value;
8592 
8593 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8594 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
8595 		dst_reg->smin_value = S64_MIN;
8596 		dst_reg->smax_value = S64_MAX;
8597 	} else {
8598 		dst_reg->smin_value += smin_val;
8599 		dst_reg->smax_value += smax_val;
8600 	}
8601 	if (dst_reg->umin_value + umin_val < umin_val ||
8602 	    dst_reg->umax_value + umax_val < umax_val) {
8603 		dst_reg->umin_value = 0;
8604 		dst_reg->umax_value = U64_MAX;
8605 	} else {
8606 		dst_reg->umin_value += umin_val;
8607 		dst_reg->umax_value += umax_val;
8608 	}
8609 }
8610 
8611 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8612 				 struct bpf_reg_state *src_reg)
8613 {
8614 	s32 smin_val = src_reg->s32_min_value;
8615 	s32 smax_val = src_reg->s32_max_value;
8616 	u32 umin_val = src_reg->u32_min_value;
8617 	u32 umax_val = src_reg->u32_max_value;
8618 
8619 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8620 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8621 		/* Overflow possible, we know nothing */
8622 		dst_reg->s32_min_value = S32_MIN;
8623 		dst_reg->s32_max_value = S32_MAX;
8624 	} else {
8625 		dst_reg->s32_min_value -= smax_val;
8626 		dst_reg->s32_max_value -= smin_val;
8627 	}
8628 	if (dst_reg->u32_min_value < umax_val) {
8629 		/* Overflow possible, we know nothing */
8630 		dst_reg->u32_min_value = 0;
8631 		dst_reg->u32_max_value = U32_MAX;
8632 	} else {
8633 		/* Cannot overflow (as long as bounds are consistent) */
8634 		dst_reg->u32_min_value -= umax_val;
8635 		dst_reg->u32_max_value -= umin_val;
8636 	}
8637 }
8638 
8639 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8640 			       struct bpf_reg_state *src_reg)
8641 {
8642 	s64 smin_val = src_reg->smin_value;
8643 	s64 smax_val = src_reg->smax_value;
8644 	u64 umin_val = src_reg->umin_value;
8645 	u64 umax_val = src_reg->umax_value;
8646 
8647 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8648 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8649 		/* Overflow possible, we know nothing */
8650 		dst_reg->smin_value = S64_MIN;
8651 		dst_reg->smax_value = S64_MAX;
8652 	} else {
8653 		dst_reg->smin_value -= smax_val;
8654 		dst_reg->smax_value -= smin_val;
8655 	}
8656 	if (dst_reg->umin_value < umax_val) {
8657 		/* Overflow possible, we know nothing */
8658 		dst_reg->umin_value = 0;
8659 		dst_reg->umax_value = U64_MAX;
8660 	} else {
8661 		/* Cannot overflow (as long as bounds are consistent) */
8662 		dst_reg->umin_value -= umax_val;
8663 		dst_reg->umax_value -= umin_val;
8664 	}
8665 }
8666 
8667 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8668 				 struct bpf_reg_state *src_reg)
8669 {
8670 	s32 smin_val = src_reg->s32_min_value;
8671 	u32 umin_val = src_reg->u32_min_value;
8672 	u32 umax_val = src_reg->u32_max_value;
8673 
8674 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8675 		/* Ain't nobody got time to multiply that sign */
8676 		__mark_reg32_unbounded(dst_reg);
8677 		return;
8678 	}
8679 	/* Both values are positive, so we can work with unsigned and
8680 	 * copy the result to signed (unless it exceeds S32_MAX).
8681 	 */
8682 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8683 		/* Potential overflow, we know nothing */
8684 		__mark_reg32_unbounded(dst_reg);
8685 		return;
8686 	}
8687 	dst_reg->u32_min_value *= umin_val;
8688 	dst_reg->u32_max_value *= umax_val;
8689 	if (dst_reg->u32_max_value > S32_MAX) {
8690 		/* Overflow possible, we know nothing */
8691 		dst_reg->s32_min_value = S32_MIN;
8692 		dst_reg->s32_max_value = S32_MAX;
8693 	} else {
8694 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8695 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8696 	}
8697 }
8698 
8699 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8700 			       struct bpf_reg_state *src_reg)
8701 {
8702 	s64 smin_val = src_reg->smin_value;
8703 	u64 umin_val = src_reg->umin_value;
8704 	u64 umax_val = src_reg->umax_value;
8705 
8706 	if (smin_val < 0 || dst_reg->smin_value < 0) {
8707 		/* Ain't nobody got time to multiply that sign */
8708 		__mark_reg64_unbounded(dst_reg);
8709 		return;
8710 	}
8711 	/* Both values are positive, so we can work with unsigned and
8712 	 * copy the result to signed (unless it exceeds S64_MAX).
8713 	 */
8714 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8715 		/* Potential overflow, we know nothing */
8716 		__mark_reg64_unbounded(dst_reg);
8717 		return;
8718 	}
8719 	dst_reg->umin_value *= umin_val;
8720 	dst_reg->umax_value *= umax_val;
8721 	if (dst_reg->umax_value > S64_MAX) {
8722 		/* Overflow possible, we know nothing */
8723 		dst_reg->smin_value = S64_MIN;
8724 		dst_reg->smax_value = S64_MAX;
8725 	} else {
8726 		dst_reg->smin_value = dst_reg->umin_value;
8727 		dst_reg->smax_value = dst_reg->umax_value;
8728 	}
8729 }
8730 
8731 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8732 				 struct bpf_reg_state *src_reg)
8733 {
8734 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8735 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8736 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8737 	s32 smin_val = src_reg->s32_min_value;
8738 	u32 umax_val = src_reg->u32_max_value;
8739 
8740 	if (src_known && dst_known) {
8741 		__mark_reg32_known(dst_reg, var32_off.value);
8742 		return;
8743 	}
8744 
8745 	/* We get our minimum from the var_off, since that's inherently
8746 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8747 	 */
8748 	dst_reg->u32_min_value = var32_off.value;
8749 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8750 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8751 		/* Lose signed bounds when ANDing negative numbers,
8752 		 * ain't nobody got time for that.
8753 		 */
8754 		dst_reg->s32_min_value = S32_MIN;
8755 		dst_reg->s32_max_value = S32_MAX;
8756 	} else {
8757 		/* ANDing two positives gives a positive, so safe to
8758 		 * cast result into s64.
8759 		 */
8760 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8761 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8762 	}
8763 }
8764 
8765 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8766 			       struct bpf_reg_state *src_reg)
8767 {
8768 	bool src_known = tnum_is_const(src_reg->var_off);
8769 	bool dst_known = tnum_is_const(dst_reg->var_off);
8770 	s64 smin_val = src_reg->smin_value;
8771 	u64 umax_val = src_reg->umax_value;
8772 
8773 	if (src_known && dst_known) {
8774 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8775 		return;
8776 	}
8777 
8778 	/* We get our minimum from the var_off, since that's inherently
8779 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8780 	 */
8781 	dst_reg->umin_value = dst_reg->var_off.value;
8782 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8783 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8784 		/* Lose signed bounds when ANDing negative numbers,
8785 		 * ain't nobody got time for that.
8786 		 */
8787 		dst_reg->smin_value = S64_MIN;
8788 		dst_reg->smax_value = S64_MAX;
8789 	} else {
8790 		/* ANDing two positives gives a positive, so safe to
8791 		 * cast result into s64.
8792 		 */
8793 		dst_reg->smin_value = dst_reg->umin_value;
8794 		dst_reg->smax_value = dst_reg->umax_value;
8795 	}
8796 	/* We may learn something more from the var_off */
8797 	__update_reg_bounds(dst_reg);
8798 }
8799 
8800 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8801 				struct bpf_reg_state *src_reg)
8802 {
8803 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8804 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8805 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8806 	s32 smin_val = src_reg->s32_min_value;
8807 	u32 umin_val = src_reg->u32_min_value;
8808 
8809 	if (src_known && dst_known) {
8810 		__mark_reg32_known(dst_reg, var32_off.value);
8811 		return;
8812 	}
8813 
8814 	/* We get our maximum from the var_off, and our minimum is the
8815 	 * maximum of the operands' minima
8816 	 */
8817 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8818 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8819 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8820 		/* Lose signed bounds when ORing negative numbers,
8821 		 * ain't nobody got time for that.
8822 		 */
8823 		dst_reg->s32_min_value = S32_MIN;
8824 		dst_reg->s32_max_value = S32_MAX;
8825 	} else {
8826 		/* ORing two positives gives a positive, so safe to
8827 		 * cast result into s64.
8828 		 */
8829 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8830 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8831 	}
8832 }
8833 
8834 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8835 			      struct bpf_reg_state *src_reg)
8836 {
8837 	bool src_known = tnum_is_const(src_reg->var_off);
8838 	bool dst_known = tnum_is_const(dst_reg->var_off);
8839 	s64 smin_val = src_reg->smin_value;
8840 	u64 umin_val = src_reg->umin_value;
8841 
8842 	if (src_known && dst_known) {
8843 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8844 		return;
8845 	}
8846 
8847 	/* We get our maximum from the var_off, and our minimum is the
8848 	 * maximum of the operands' minima
8849 	 */
8850 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8851 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8852 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8853 		/* Lose signed bounds when ORing negative numbers,
8854 		 * ain't nobody got time for that.
8855 		 */
8856 		dst_reg->smin_value = S64_MIN;
8857 		dst_reg->smax_value = S64_MAX;
8858 	} else {
8859 		/* ORing two positives gives a positive, so safe to
8860 		 * cast result into s64.
8861 		 */
8862 		dst_reg->smin_value = dst_reg->umin_value;
8863 		dst_reg->smax_value = dst_reg->umax_value;
8864 	}
8865 	/* We may learn something more from the var_off */
8866 	__update_reg_bounds(dst_reg);
8867 }
8868 
8869 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8870 				 struct bpf_reg_state *src_reg)
8871 {
8872 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8873 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8874 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8875 	s32 smin_val = src_reg->s32_min_value;
8876 
8877 	if (src_known && dst_known) {
8878 		__mark_reg32_known(dst_reg, var32_off.value);
8879 		return;
8880 	}
8881 
8882 	/* We get both minimum and maximum from the var32_off. */
8883 	dst_reg->u32_min_value = var32_off.value;
8884 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8885 
8886 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8887 		/* XORing two positive sign numbers gives a positive,
8888 		 * so safe to cast u32 result into s32.
8889 		 */
8890 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8891 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8892 	} else {
8893 		dst_reg->s32_min_value = S32_MIN;
8894 		dst_reg->s32_max_value = S32_MAX;
8895 	}
8896 }
8897 
8898 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8899 			       struct bpf_reg_state *src_reg)
8900 {
8901 	bool src_known = tnum_is_const(src_reg->var_off);
8902 	bool dst_known = tnum_is_const(dst_reg->var_off);
8903 	s64 smin_val = src_reg->smin_value;
8904 
8905 	if (src_known && dst_known) {
8906 		/* dst_reg->var_off.value has been updated earlier */
8907 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8908 		return;
8909 	}
8910 
8911 	/* We get both minimum and maximum from the var_off. */
8912 	dst_reg->umin_value = dst_reg->var_off.value;
8913 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8914 
8915 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8916 		/* XORing two positive sign numbers gives a positive,
8917 		 * so safe to cast u64 result into s64.
8918 		 */
8919 		dst_reg->smin_value = dst_reg->umin_value;
8920 		dst_reg->smax_value = dst_reg->umax_value;
8921 	} else {
8922 		dst_reg->smin_value = S64_MIN;
8923 		dst_reg->smax_value = S64_MAX;
8924 	}
8925 
8926 	__update_reg_bounds(dst_reg);
8927 }
8928 
8929 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8930 				   u64 umin_val, u64 umax_val)
8931 {
8932 	/* We lose all sign bit information (except what we can pick
8933 	 * up from var_off)
8934 	 */
8935 	dst_reg->s32_min_value = S32_MIN;
8936 	dst_reg->s32_max_value = S32_MAX;
8937 	/* If we might shift our top bit out, then we know nothing */
8938 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8939 		dst_reg->u32_min_value = 0;
8940 		dst_reg->u32_max_value = U32_MAX;
8941 	} else {
8942 		dst_reg->u32_min_value <<= umin_val;
8943 		dst_reg->u32_max_value <<= umax_val;
8944 	}
8945 }
8946 
8947 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8948 				 struct bpf_reg_state *src_reg)
8949 {
8950 	u32 umax_val = src_reg->u32_max_value;
8951 	u32 umin_val = src_reg->u32_min_value;
8952 	/* u32 alu operation will zext upper bits */
8953 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8954 
8955 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8956 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8957 	/* Not required but being careful mark reg64 bounds as unknown so
8958 	 * that we are forced to pick them up from tnum and zext later and
8959 	 * if some path skips this step we are still safe.
8960 	 */
8961 	__mark_reg64_unbounded(dst_reg);
8962 	__update_reg32_bounds(dst_reg);
8963 }
8964 
8965 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8966 				   u64 umin_val, u64 umax_val)
8967 {
8968 	/* Special case <<32 because it is a common compiler pattern to sign
8969 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8970 	 * positive we know this shift will also be positive so we can track
8971 	 * bounds correctly. Otherwise we lose all sign bit information except
8972 	 * what we can pick up from var_off. Perhaps we can generalize this
8973 	 * later to shifts of any length.
8974 	 */
8975 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8976 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8977 	else
8978 		dst_reg->smax_value = S64_MAX;
8979 
8980 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8981 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8982 	else
8983 		dst_reg->smin_value = S64_MIN;
8984 
8985 	/* If we might shift our top bit out, then we know nothing */
8986 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8987 		dst_reg->umin_value = 0;
8988 		dst_reg->umax_value = U64_MAX;
8989 	} else {
8990 		dst_reg->umin_value <<= umin_val;
8991 		dst_reg->umax_value <<= umax_val;
8992 	}
8993 }
8994 
8995 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8996 			       struct bpf_reg_state *src_reg)
8997 {
8998 	u64 umax_val = src_reg->umax_value;
8999 	u64 umin_val = src_reg->umin_value;
9000 
9001 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
9002 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
9003 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
9004 
9005 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
9006 	/* We may learn something more from the var_off */
9007 	__update_reg_bounds(dst_reg);
9008 }
9009 
9010 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
9011 				 struct bpf_reg_state *src_reg)
9012 {
9013 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
9014 	u32 umax_val = src_reg->u32_max_value;
9015 	u32 umin_val = src_reg->u32_min_value;
9016 
9017 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
9018 	 * be negative, then either:
9019 	 * 1) src_reg might be zero, so the sign bit of the result is
9020 	 *    unknown, so we lose our signed bounds
9021 	 * 2) it's known negative, thus the unsigned bounds capture the
9022 	 *    signed bounds
9023 	 * 3) the signed bounds cross zero, so they tell us nothing
9024 	 *    about the result
9025 	 * If the value in dst_reg is known nonnegative, then again the
9026 	 * unsigned bounds capture the signed bounds.
9027 	 * Thus, in all cases it suffices to blow away our signed bounds
9028 	 * and rely on inferring new ones from the unsigned bounds and
9029 	 * var_off of the result.
9030 	 */
9031 	dst_reg->s32_min_value = S32_MIN;
9032 	dst_reg->s32_max_value = S32_MAX;
9033 
9034 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
9035 	dst_reg->u32_min_value >>= umax_val;
9036 	dst_reg->u32_max_value >>= umin_val;
9037 
9038 	__mark_reg64_unbounded(dst_reg);
9039 	__update_reg32_bounds(dst_reg);
9040 }
9041 
9042 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
9043 			       struct bpf_reg_state *src_reg)
9044 {
9045 	u64 umax_val = src_reg->umax_value;
9046 	u64 umin_val = src_reg->umin_value;
9047 
9048 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
9049 	 * be negative, then either:
9050 	 * 1) src_reg might be zero, so the sign bit of the result is
9051 	 *    unknown, so we lose our signed bounds
9052 	 * 2) it's known negative, thus the unsigned bounds capture the
9053 	 *    signed bounds
9054 	 * 3) the signed bounds cross zero, so they tell us nothing
9055 	 *    about the result
9056 	 * If the value in dst_reg is known nonnegative, then again the
9057 	 * unsigned bounds capture the signed bounds.
9058 	 * Thus, in all cases it suffices to blow away our signed bounds
9059 	 * and rely on inferring new ones from the unsigned bounds and
9060 	 * var_off of the result.
9061 	 */
9062 	dst_reg->smin_value = S64_MIN;
9063 	dst_reg->smax_value = S64_MAX;
9064 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
9065 	dst_reg->umin_value >>= umax_val;
9066 	dst_reg->umax_value >>= umin_val;
9067 
9068 	/* Its not easy to operate on alu32 bounds here because it depends
9069 	 * on bits being shifted in. Take easy way out and mark unbounded
9070 	 * so we can recalculate later from tnum.
9071 	 */
9072 	__mark_reg32_unbounded(dst_reg);
9073 	__update_reg_bounds(dst_reg);
9074 }
9075 
9076 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
9077 				  struct bpf_reg_state *src_reg)
9078 {
9079 	u64 umin_val = src_reg->u32_min_value;
9080 
9081 	/* Upon reaching here, src_known is true and
9082 	 * umax_val is equal to umin_val.
9083 	 */
9084 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9085 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9086 
9087 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9088 
9089 	/* blow away the dst_reg umin_value/umax_value and rely on
9090 	 * dst_reg var_off to refine the result.
9091 	 */
9092 	dst_reg->u32_min_value = 0;
9093 	dst_reg->u32_max_value = U32_MAX;
9094 
9095 	__mark_reg64_unbounded(dst_reg);
9096 	__update_reg32_bounds(dst_reg);
9097 }
9098 
9099 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9100 				struct bpf_reg_state *src_reg)
9101 {
9102 	u64 umin_val = src_reg->umin_value;
9103 
9104 	/* Upon reaching here, src_known is true and umax_val is equal
9105 	 * to umin_val.
9106 	 */
9107 	dst_reg->smin_value >>= umin_val;
9108 	dst_reg->smax_value >>= umin_val;
9109 
9110 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9111 
9112 	/* blow away the dst_reg umin_value/umax_value and rely on
9113 	 * dst_reg var_off to refine the result.
9114 	 */
9115 	dst_reg->umin_value = 0;
9116 	dst_reg->umax_value = U64_MAX;
9117 
9118 	/* Its not easy to operate on alu32 bounds here because it depends
9119 	 * on bits being shifted in from upper 32-bits. Take easy way out
9120 	 * and mark unbounded so we can recalculate later from tnum.
9121 	 */
9122 	__mark_reg32_unbounded(dst_reg);
9123 	__update_reg_bounds(dst_reg);
9124 }
9125 
9126 /* WARNING: This function does calculations on 64-bit values, but the actual
9127  * execution may occur on 32-bit values. Therefore, things like bitshifts
9128  * need extra checks in the 32-bit case.
9129  */
9130 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9131 				      struct bpf_insn *insn,
9132 				      struct bpf_reg_state *dst_reg,
9133 				      struct bpf_reg_state src_reg)
9134 {
9135 	struct bpf_reg_state *regs = cur_regs(env);
9136 	u8 opcode = BPF_OP(insn->code);
9137 	bool src_known;
9138 	s64 smin_val, smax_val;
9139 	u64 umin_val, umax_val;
9140 	s32 s32_min_val, s32_max_val;
9141 	u32 u32_min_val, u32_max_val;
9142 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9143 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9144 	int ret;
9145 
9146 	smin_val = src_reg.smin_value;
9147 	smax_val = src_reg.smax_value;
9148 	umin_val = src_reg.umin_value;
9149 	umax_val = src_reg.umax_value;
9150 
9151 	s32_min_val = src_reg.s32_min_value;
9152 	s32_max_val = src_reg.s32_max_value;
9153 	u32_min_val = src_reg.u32_min_value;
9154 	u32_max_val = src_reg.u32_max_value;
9155 
9156 	if (alu32) {
9157 		src_known = tnum_subreg_is_const(src_reg.var_off);
9158 		if ((src_known &&
9159 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9160 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9161 			/* Taint dst register if offset had invalid bounds
9162 			 * derived from e.g. dead branches.
9163 			 */
9164 			__mark_reg_unknown(env, dst_reg);
9165 			return 0;
9166 		}
9167 	} else {
9168 		src_known = tnum_is_const(src_reg.var_off);
9169 		if ((src_known &&
9170 		     (smin_val != smax_val || umin_val != umax_val)) ||
9171 		    smin_val > smax_val || umin_val > umax_val) {
9172 			/* Taint dst register if offset had invalid bounds
9173 			 * derived from e.g. dead branches.
9174 			 */
9175 			__mark_reg_unknown(env, dst_reg);
9176 			return 0;
9177 		}
9178 	}
9179 
9180 	if (!src_known &&
9181 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9182 		__mark_reg_unknown(env, dst_reg);
9183 		return 0;
9184 	}
9185 
9186 	if (sanitize_needed(opcode)) {
9187 		ret = sanitize_val_alu(env, insn);
9188 		if (ret < 0)
9189 			return sanitize_err(env, insn, ret, NULL, NULL);
9190 	}
9191 
9192 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9193 	 * There are two classes of instructions: The first class we track both
9194 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
9195 	 * greatest amount of precision when alu operations are mixed with jmp32
9196 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9197 	 * and BPF_OR. This is possible because these ops have fairly easy to
9198 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9199 	 * See alu32 verifier tests for examples. The second class of
9200 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9201 	 * with regards to tracking sign/unsigned bounds because the bits may
9202 	 * cross subreg boundaries in the alu64 case. When this happens we mark
9203 	 * the reg unbounded in the subreg bound space and use the resulting
9204 	 * tnum to calculate an approximation of the sign/unsigned bounds.
9205 	 */
9206 	switch (opcode) {
9207 	case BPF_ADD:
9208 		scalar32_min_max_add(dst_reg, &src_reg);
9209 		scalar_min_max_add(dst_reg, &src_reg);
9210 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9211 		break;
9212 	case BPF_SUB:
9213 		scalar32_min_max_sub(dst_reg, &src_reg);
9214 		scalar_min_max_sub(dst_reg, &src_reg);
9215 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9216 		break;
9217 	case BPF_MUL:
9218 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9219 		scalar32_min_max_mul(dst_reg, &src_reg);
9220 		scalar_min_max_mul(dst_reg, &src_reg);
9221 		break;
9222 	case BPF_AND:
9223 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9224 		scalar32_min_max_and(dst_reg, &src_reg);
9225 		scalar_min_max_and(dst_reg, &src_reg);
9226 		break;
9227 	case BPF_OR:
9228 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9229 		scalar32_min_max_or(dst_reg, &src_reg);
9230 		scalar_min_max_or(dst_reg, &src_reg);
9231 		break;
9232 	case BPF_XOR:
9233 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9234 		scalar32_min_max_xor(dst_reg, &src_reg);
9235 		scalar_min_max_xor(dst_reg, &src_reg);
9236 		break;
9237 	case BPF_LSH:
9238 		if (umax_val >= insn_bitness) {
9239 			/* Shifts greater than 31 or 63 are undefined.
9240 			 * This includes shifts by a negative number.
9241 			 */
9242 			mark_reg_unknown(env, regs, insn->dst_reg);
9243 			break;
9244 		}
9245 		if (alu32)
9246 			scalar32_min_max_lsh(dst_reg, &src_reg);
9247 		else
9248 			scalar_min_max_lsh(dst_reg, &src_reg);
9249 		break;
9250 	case BPF_RSH:
9251 		if (umax_val >= insn_bitness) {
9252 			/* Shifts greater than 31 or 63 are undefined.
9253 			 * This includes shifts by a negative number.
9254 			 */
9255 			mark_reg_unknown(env, regs, insn->dst_reg);
9256 			break;
9257 		}
9258 		if (alu32)
9259 			scalar32_min_max_rsh(dst_reg, &src_reg);
9260 		else
9261 			scalar_min_max_rsh(dst_reg, &src_reg);
9262 		break;
9263 	case BPF_ARSH:
9264 		if (umax_val >= insn_bitness) {
9265 			/* Shifts greater than 31 or 63 are undefined.
9266 			 * This includes shifts by a negative number.
9267 			 */
9268 			mark_reg_unknown(env, regs, insn->dst_reg);
9269 			break;
9270 		}
9271 		if (alu32)
9272 			scalar32_min_max_arsh(dst_reg, &src_reg);
9273 		else
9274 			scalar_min_max_arsh(dst_reg, &src_reg);
9275 		break;
9276 	default:
9277 		mark_reg_unknown(env, regs, insn->dst_reg);
9278 		break;
9279 	}
9280 
9281 	/* ALU32 ops are zero extended into 64bit register */
9282 	if (alu32)
9283 		zext_32_to_64(dst_reg);
9284 	reg_bounds_sync(dst_reg);
9285 	return 0;
9286 }
9287 
9288 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9289  * and var_off.
9290  */
9291 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9292 				   struct bpf_insn *insn)
9293 {
9294 	struct bpf_verifier_state *vstate = env->cur_state;
9295 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9296 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9297 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9298 	u8 opcode = BPF_OP(insn->code);
9299 	int err;
9300 
9301 	dst_reg = &regs[insn->dst_reg];
9302 	src_reg = NULL;
9303 	if (dst_reg->type != SCALAR_VALUE)
9304 		ptr_reg = dst_reg;
9305 	else
9306 		/* Make sure ID is cleared otherwise dst_reg min/max could be
9307 		 * incorrectly propagated into other registers by find_equal_scalars()
9308 		 */
9309 		dst_reg->id = 0;
9310 	if (BPF_SRC(insn->code) == BPF_X) {
9311 		src_reg = &regs[insn->src_reg];
9312 		if (src_reg->type != SCALAR_VALUE) {
9313 			if (dst_reg->type != SCALAR_VALUE) {
9314 				/* Combining two pointers by any ALU op yields
9315 				 * an arbitrary scalar. Disallow all math except
9316 				 * pointer subtraction
9317 				 */
9318 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9319 					mark_reg_unknown(env, regs, insn->dst_reg);
9320 					return 0;
9321 				}
9322 				verbose(env, "R%d pointer %s pointer prohibited\n",
9323 					insn->dst_reg,
9324 					bpf_alu_string[opcode >> 4]);
9325 				return -EACCES;
9326 			} else {
9327 				/* scalar += pointer
9328 				 * This is legal, but we have to reverse our
9329 				 * src/dest handling in computing the range
9330 				 */
9331 				err = mark_chain_precision(env, insn->dst_reg);
9332 				if (err)
9333 					return err;
9334 				return adjust_ptr_min_max_vals(env, insn,
9335 							       src_reg, dst_reg);
9336 			}
9337 		} else if (ptr_reg) {
9338 			/* pointer += scalar */
9339 			err = mark_chain_precision(env, insn->src_reg);
9340 			if (err)
9341 				return err;
9342 			return adjust_ptr_min_max_vals(env, insn,
9343 						       dst_reg, src_reg);
9344 		} else if (dst_reg->precise) {
9345 			/* if dst_reg is precise, src_reg should be precise as well */
9346 			err = mark_chain_precision(env, insn->src_reg);
9347 			if (err)
9348 				return err;
9349 		}
9350 	} else {
9351 		/* Pretend the src is a reg with a known value, since we only
9352 		 * need to be able to read from this state.
9353 		 */
9354 		off_reg.type = SCALAR_VALUE;
9355 		__mark_reg_known(&off_reg, insn->imm);
9356 		src_reg = &off_reg;
9357 		if (ptr_reg) /* pointer += K */
9358 			return adjust_ptr_min_max_vals(env, insn,
9359 						       ptr_reg, src_reg);
9360 	}
9361 
9362 	/* Got here implies adding two SCALAR_VALUEs */
9363 	if (WARN_ON_ONCE(ptr_reg)) {
9364 		print_verifier_state(env, state, true);
9365 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
9366 		return -EINVAL;
9367 	}
9368 	if (WARN_ON(!src_reg)) {
9369 		print_verifier_state(env, state, true);
9370 		verbose(env, "verifier internal error: no src_reg\n");
9371 		return -EINVAL;
9372 	}
9373 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9374 }
9375 
9376 /* check validity of 32-bit and 64-bit arithmetic operations */
9377 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9378 {
9379 	struct bpf_reg_state *regs = cur_regs(env);
9380 	u8 opcode = BPF_OP(insn->code);
9381 	int err;
9382 
9383 	if (opcode == BPF_END || opcode == BPF_NEG) {
9384 		if (opcode == BPF_NEG) {
9385 			if (BPF_SRC(insn->code) != BPF_K ||
9386 			    insn->src_reg != BPF_REG_0 ||
9387 			    insn->off != 0 || insn->imm != 0) {
9388 				verbose(env, "BPF_NEG uses reserved fields\n");
9389 				return -EINVAL;
9390 			}
9391 		} else {
9392 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9393 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9394 			    BPF_CLASS(insn->code) == BPF_ALU64) {
9395 				verbose(env, "BPF_END uses reserved fields\n");
9396 				return -EINVAL;
9397 			}
9398 		}
9399 
9400 		/* check src operand */
9401 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9402 		if (err)
9403 			return err;
9404 
9405 		if (is_pointer_value(env, insn->dst_reg)) {
9406 			verbose(env, "R%d pointer arithmetic prohibited\n",
9407 				insn->dst_reg);
9408 			return -EACCES;
9409 		}
9410 
9411 		/* check dest operand */
9412 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
9413 		if (err)
9414 			return err;
9415 
9416 	} else if (opcode == BPF_MOV) {
9417 
9418 		if (BPF_SRC(insn->code) == BPF_X) {
9419 			if (insn->imm != 0 || insn->off != 0) {
9420 				verbose(env, "BPF_MOV uses reserved fields\n");
9421 				return -EINVAL;
9422 			}
9423 
9424 			/* check src operand */
9425 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9426 			if (err)
9427 				return err;
9428 		} else {
9429 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9430 				verbose(env, "BPF_MOV uses reserved fields\n");
9431 				return -EINVAL;
9432 			}
9433 		}
9434 
9435 		/* check dest operand, mark as required later */
9436 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9437 		if (err)
9438 			return err;
9439 
9440 		if (BPF_SRC(insn->code) == BPF_X) {
9441 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
9442 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9443 
9444 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9445 				/* case: R1 = R2
9446 				 * copy register state to dest reg
9447 				 */
9448 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9449 					/* Assign src and dst registers the same ID
9450 					 * that will be used by find_equal_scalars()
9451 					 * to propagate min/max range.
9452 					 */
9453 					src_reg->id = ++env->id_gen;
9454 				*dst_reg = *src_reg;
9455 				dst_reg->live |= REG_LIVE_WRITTEN;
9456 				dst_reg->subreg_def = DEF_NOT_SUBREG;
9457 			} else {
9458 				/* R1 = (u32) R2 */
9459 				if (is_pointer_value(env, insn->src_reg)) {
9460 					verbose(env,
9461 						"R%d partial copy of pointer\n",
9462 						insn->src_reg);
9463 					return -EACCES;
9464 				} else if (src_reg->type == SCALAR_VALUE) {
9465 					*dst_reg = *src_reg;
9466 					/* Make sure ID is cleared otherwise
9467 					 * dst_reg min/max could be incorrectly
9468 					 * propagated into src_reg by find_equal_scalars()
9469 					 */
9470 					dst_reg->id = 0;
9471 					dst_reg->live |= REG_LIVE_WRITTEN;
9472 					dst_reg->subreg_def = env->insn_idx + 1;
9473 				} else {
9474 					mark_reg_unknown(env, regs,
9475 							 insn->dst_reg);
9476 				}
9477 				zext_32_to_64(dst_reg);
9478 				reg_bounds_sync(dst_reg);
9479 			}
9480 		} else {
9481 			/* case: R = imm
9482 			 * remember the value we stored into this reg
9483 			 */
9484 			/* clear any state __mark_reg_known doesn't set */
9485 			mark_reg_unknown(env, regs, insn->dst_reg);
9486 			regs[insn->dst_reg].type = SCALAR_VALUE;
9487 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9488 				__mark_reg_known(regs + insn->dst_reg,
9489 						 insn->imm);
9490 			} else {
9491 				__mark_reg_known(regs + insn->dst_reg,
9492 						 (u32)insn->imm);
9493 			}
9494 		}
9495 
9496 	} else if (opcode > BPF_END) {
9497 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9498 		return -EINVAL;
9499 
9500 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
9501 
9502 		if (BPF_SRC(insn->code) == BPF_X) {
9503 			if (insn->imm != 0 || insn->off != 0) {
9504 				verbose(env, "BPF_ALU uses reserved fields\n");
9505 				return -EINVAL;
9506 			}
9507 			/* check src1 operand */
9508 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9509 			if (err)
9510 				return err;
9511 		} else {
9512 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9513 				verbose(env, "BPF_ALU uses reserved fields\n");
9514 				return -EINVAL;
9515 			}
9516 		}
9517 
9518 		/* check src2 operand */
9519 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9520 		if (err)
9521 			return err;
9522 
9523 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9524 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9525 			verbose(env, "div by zero\n");
9526 			return -EINVAL;
9527 		}
9528 
9529 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9530 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9531 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9532 
9533 			if (insn->imm < 0 || insn->imm >= size) {
9534 				verbose(env, "invalid shift %d\n", insn->imm);
9535 				return -EINVAL;
9536 			}
9537 		}
9538 
9539 		/* check dest operand */
9540 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9541 		if (err)
9542 			return err;
9543 
9544 		return adjust_reg_min_max_vals(env, insn);
9545 	}
9546 
9547 	return 0;
9548 }
9549 
9550 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9551 				   struct bpf_reg_state *dst_reg,
9552 				   enum bpf_reg_type type,
9553 				   bool range_right_open)
9554 {
9555 	struct bpf_func_state *state;
9556 	struct bpf_reg_state *reg;
9557 	int new_range;
9558 
9559 	if (dst_reg->off < 0 ||
9560 	    (dst_reg->off == 0 && range_right_open))
9561 		/* This doesn't give us any range */
9562 		return;
9563 
9564 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
9565 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9566 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
9567 		 * than pkt_end, but that's because it's also less than pkt.
9568 		 */
9569 		return;
9570 
9571 	new_range = dst_reg->off;
9572 	if (range_right_open)
9573 		new_range++;
9574 
9575 	/* Examples for register markings:
9576 	 *
9577 	 * pkt_data in dst register:
9578 	 *
9579 	 *   r2 = r3;
9580 	 *   r2 += 8;
9581 	 *   if (r2 > pkt_end) goto <handle exception>
9582 	 *   <access okay>
9583 	 *
9584 	 *   r2 = r3;
9585 	 *   r2 += 8;
9586 	 *   if (r2 < pkt_end) goto <access okay>
9587 	 *   <handle exception>
9588 	 *
9589 	 *   Where:
9590 	 *     r2 == dst_reg, pkt_end == src_reg
9591 	 *     r2=pkt(id=n,off=8,r=0)
9592 	 *     r3=pkt(id=n,off=0,r=0)
9593 	 *
9594 	 * pkt_data in src register:
9595 	 *
9596 	 *   r2 = r3;
9597 	 *   r2 += 8;
9598 	 *   if (pkt_end >= r2) goto <access okay>
9599 	 *   <handle exception>
9600 	 *
9601 	 *   r2 = r3;
9602 	 *   r2 += 8;
9603 	 *   if (pkt_end <= r2) goto <handle exception>
9604 	 *   <access okay>
9605 	 *
9606 	 *   Where:
9607 	 *     pkt_end == dst_reg, r2 == src_reg
9608 	 *     r2=pkt(id=n,off=8,r=0)
9609 	 *     r3=pkt(id=n,off=0,r=0)
9610 	 *
9611 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9612 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9613 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
9614 	 * the check.
9615 	 */
9616 
9617 	/* If our ids match, then we must have the same max_value.  And we
9618 	 * don't care about the other reg's fixed offset, since if it's too big
9619 	 * the range won't allow anything.
9620 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9621 	 */
9622 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9623 		if (reg->type == type && reg->id == dst_reg->id)
9624 			/* keep the maximum range already checked */
9625 			reg->range = max(reg->range, new_range);
9626 	}));
9627 }
9628 
9629 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9630 {
9631 	struct tnum subreg = tnum_subreg(reg->var_off);
9632 	s32 sval = (s32)val;
9633 
9634 	switch (opcode) {
9635 	case BPF_JEQ:
9636 		if (tnum_is_const(subreg))
9637 			return !!tnum_equals_const(subreg, val);
9638 		break;
9639 	case BPF_JNE:
9640 		if (tnum_is_const(subreg))
9641 			return !tnum_equals_const(subreg, val);
9642 		break;
9643 	case BPF_JSET:
9644 		if ((~subreg.mask & subreg.value) & val)
9645 			return 1;
9646 		if (!((subreg.mask | subreg.value) & val))
9647 			return 0;
9648 		break;
9649 	case BPF_JGT:
9650 		if (reg->u32_min_value > val)
9651 			return 1;
9652 		else if (reg->u32_max_value <= val)
9653 			return 0;
9654 		break;
9655 	case BPF_JSGT:
9656 		if (reg->s32_min_value > sval)
9657 			return 1;
9658 		else if (reg->s32_max_value <= sval)
9659 			return 0;
9660 		break;
9661 	case BPF_JLT:
9662 		if (reg->u32_max_value < val)
9663 			return 1;
9664 		else if (reg->u32_min_value >= val)
9665 			return 0;
9666 		break;
9667 	case BPF_JSLT:
9668 		if (reg->s32_max_value < sval)
9669 			return 1;
9670 		else if (reg->s32_min_value >= sval)
9671 			return 0;
9672 		break;
9673 	case BPF_JGE:
9674 		if (reg->u32_min_value >= val)
9675 			return 1;
9676 		else if (reg->u32_max_value < val)
9677 			return 0;
9678 		break;
9679 	case BPF_JSGE:
9680 		if (reg->s32_min_value >= sval)
9681 			return 1;
9682 		else if (reg->s32_max_value < sval)
9683 			return 0;
9684 		break;
9685 	case BPF_JLE:
9686 		if (reg->u32_max_value <= val)
9687 			return 1;
9688 		else if (reg->u32_min_value > val)
9689 			return 0;
9690 		break;
9691 	case BPF_JSLE:
9692 		if (reg->s32_max_value <= sval)
9693 			return 1;
9694 		else if (reg->s32_min_value > sval)
9695 			return 0;
9696 		break;
9697 	}
9698 
9699 	return -1;
9700 }
9701 
9702 
9703 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9704 {
9705 	s64 sval = (s64)val;
9706 
9707 	switch (opcode) {
9708 	case BPF_JEQ:
9709 		if (tnum_is_const(reg->var_off))
9710 			return !!tnum_equals_const(reg->var_off, val);
9711 		break;
9712 	case BPF_JNE:
9713 		if (tnum_is_const(reg->var_off))
9714 			return !tnum_equals_const(reg->var_off, val);
9715 		break;
9716 	case BPF_JSET:
9717 		if ((~reg->var_off.mask & reg->var_off.value) & val)
9718 			return 1;
9719 		if (!((reg->var_off.mask | reg->var_off.value) & val))
9720 			return 0;
9721 		break;
9722 	case BPF_JGT:
9723 		if (reg->umin_value > val)
9724 			return 1;
9725 		else if (reg->umax_value <= val)
9726 			return 0;
9727 		break;
9728 	case BPF_JSGT:
9729 		if (reg->smin_value > sval)
9730 			return 1;
9731 		else if (reg->smax_value <= sval)
9732 			return 0;
9733 		break;
9734 	case BPF_JLT:
9735 		if (reg->umax_value < val)
9736 			return 1;
9737 		else if (reg->umin_value >= val)
9738 			return 0;
9739 		break;
9740 	case BPF_JSLT:
9741 		if (reg->smax_value < sval)
9742 			return 1;
9743 		else if (reg->smin_value >= sval)
9744 			return 0;
9745 		break;
9746 	case BPF_JGE:
9747 		if (reg->umin_value >= val)
9748 			return 1;
9749 		else if (reg->umax_value < val)
9750 			return 0;
9751 		break;
9752 	case BPF_JSGE:
9753 		if (reg->smin_value >= sval)
9754 			return 1;
9755 		else if (reg->smax_value < sval)
9756 			return 0;
9757 		break;
9758 	case BPF_JLE:
9759 		if (reg->umax_value <= val)
9760 			return 1;
9761 		else if (reg->umin_value > val)
9762 			return 0;
9763 		break;
9764 	case BPF_JSLE:
9765 		if (reg->smax_value <= sval)
9766 			return 1;
9767 		else if (reg->smin_value > sval)
9768 			return 0;
9769 		break;
9770 	}
9771 
9772 	return -1;
9773 }
9774 
9775 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9776  * and return:
9777  *  1 - branch will be taken and "goto target" will be executed
9778  *  0 - branch will not be taken and fall-through to next insn
9779  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9780  *      range [0,10]
9781  */
9782 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9783 			   bool is_jmp32)
9784 {
9785 	if (__is_pointer_value(false, reg)) {
9786 		if (!reg_type_not_null(reg->type))
9787 			return -1;
9788 
9789 		/* If pointer is valid tests against zero will fail so we can
9790 		 * use this to direct branch taken.
9791 		 */
9792 		if (val != 0)
9793 			return -1;
9794 
9795 		switch (opcode) {
9796 		case BPF_JEQ:
9797 			return 0;
9798 		case BPF_JNE:
9799 			return 1;
9800 		default:
9801 			return -1;
9802 		}
9803 	}
9804 
9805 	if (is_jmp32)
9806 		return is_branch32_taken(reg, val, opcode);
9807 	return is_branch64_taken(reg, val, opcode);
9808 }
9809 
9810 static int flip_opcode(u32 opcode)
9811 {
9812 	/* How can we transform "a <op> b" into "b <op> a"? */
9813 	static const u8 opcode_flip[16] = {
9814 		/* these stay the same */
9815 		[BPF_JEQ  >> 4] = BPF_JEQ,
9816 		[BPF_JNE  >> 4] = BPF_JNE,
9817 		[BPF_JSET >> 4] = BPF_JSET,
9818 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
9819 		[BPF_JGE  >> 4] = BPF_JLE,
9820 		[BPF_JGT  >> 4] = BPF_JLT,
9821 		[BPF_JLE  >> 4] = BPF_JGE,
9822 		[BPF_JLT  >> 4] = BPF_JGT,
9823 		[BPF_JSGE >> 4] = BPF_JSLE,
9824 		[BPF_JSGT >> 4] = BPF_JSLT,
9825 		[BPF_JSLE >> 4] = BPF_JSGE,
9826 		[BPF_JSLT >> 4] = BPF_JSGT
9827 	};
9828 	return opcode_flip[opcode >> 4];
9829 }
9830 
9831 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9832 				   struct bpf_reg_state *src_reg,
9833 				   u8 opcode)
9834 {
9835 	struct bpf_reg_state *pkt;
9836 
9837 	if (src_reg->type == PTR_TO_PACKET_END) {
9838 		pkt = dst_reg;
9839 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
9840 		pkt = src_reg;
9841 		opcode = flip_opcode(opcode);
9842 	} else {
9843 		return -1;
9844 	}
9845 
9846 	if (pkt->range >= 0)
9847 		return -1;
9848 
9849 	switch (opcode) {
9850 	case BPF_JLE:
9851 		/* pkt <= pkt_end */
9852 		fallthrough;
9853 	case BPF_JGT:
9854 		/* pkt > pkt_end */
9855 		if (pkt->range == BEYOND_PKT_END)
9856 			/* pkt has at last one extra byte beyond pkt_end */
9857 			return opcode == BPF_JGT;
9858 		break;
9859 	case BPF_JLT:
9860 		/* pkt < pkt_end */
9861 		fallthrough;
9862 	case BPF_JGE:
9863 		/* pkt >= pkt_end */
9864 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9865 			return opcode == BPF_JGE;
9866 		break;
9867 	}
9868 	return -1;
9869 }
9870 
9871 /* Adjusts the register min/max values in the case that the dst_reg is the
9872  * variable register that we are working on, and src_reg is a constant or we're
9873  * simply doing a BPF_K check.
9874  * In JEQ/JNE cases we also adjust the var_off values.
9875  */
9876 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9877 			    struct bpf_reg_state *false_reg,
9878 			    u64 val, u32 val32,
9879 			    u8 opcode, bool is_jmp32)
9880 {
9881 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9882 	struct tnum false_64off = false_reg->var_off;
9883 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9884 	struct tnum true_64off = true_reg->var_off;
9885 	s64 sval = (s64)val;
9886 	s32 sval32 = (s32)val32;
9887 
9888 	/* If the dst_reg is a pointer, we can't learn anything about its
9889 	 * variable offset from the compare (unless src_reg were a pointer into
9890 	 * the same object, but we don't bother with that.
9891 	 * Since false_reg and true_reg have the same type by construction, we
9892 	 * only need to check one of them for pointerness.
9893 	 */
9894 	if (__is_pointer_value(false, false_reg))
9895 		return;
9896 
9897 	switch (opcode) {
9898 	/* JEQ/JNE comparison doesn't change the register equivalence.
9899 	 *
9900 	 * r1 = r2;
9901 	 * if (r1 == 42) goto label;
9902 	 * ...
9903 	 * label: // here both r1 and r2 are known to be 42.
9904 	 *
9905 	 * Hence when marking register as known preserve it's ID.
9906 	 */
9907 	case BPF_JEQ:
9908 		if (is_jmp32) {
9909 			__mark_reg32_known(true_reg, val32);
9910 			true_32off = tnum_subreg(true_reg->var_off);
9911 		} else {
9912 			___mark_reg_known(true_reg, val);
9913 			true_64off = true_reg->var_off;
9914 		}
9915 		break;
9916 	case BPF_JNE:
9917 		if (is_jmp32) {
9918 			__mark_reg32_known(false_reg, val32);
9919 			false_32off = tnum_subreg(false_reg->var_off);
9920 		} else {
9921 			___mark_reg_known(false_reg, val);
9922 			false_64off = false_reg->var_off;
9923 		}
9924 		break;
9925 	case BPF_JSET:
9926 		if (is_jmp32) {
9927 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9928 			if (is_power_of_2(val32))
9929 				true_32off = tnum_or(true_32off,
9930 						     tnum_const(val32));
9931 		} else {
9932 			false_64off = tnum_and(false_64off, tnum_const(~val));
9933 			if (is_power_of_2(val))
9934 				true_64off = tnum_or(true_64off,
9935 						     tnum_const(val));
9936 		}
9937 		break;
9938 	case BPF_JGE:
9939 	case BPF_JGT:
9940 	{
9941 		if (is_jmp32) {
9942 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9943 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9944 
9945 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9946 						       false_umax);
9947 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9948 						      true_umin);
9949 		} else {
9950 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9951 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9952 
9953 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9954 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9955 		}
9956 		break;
9957 	}
9958 	case BPF_JSGE:
9959 	case BPF_JSGT:
9960 	{
9961 		if (is_jmp32) {
9962 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9963 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9964 
9965 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9966 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9967 		} else {
9968 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9969 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9970 
9971 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9972 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9973 		}
9974 		break;
9975 	}
9976 	case BPF_JLE:
9977 	case BPF_JLT:
9978 	{
9979 		if (is_jmp32) {
9980 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9981 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9982 
9983 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9984 						       false_umin);
9985 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9986 						      true_umax);
9987 		} else {
9988 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9989 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9990 
9991 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9992 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9993 		}
9994 		break;
9995 	}
9996 	case BPF_JSLE:
9997 	case BPF_JSLT:
9998 	{
9999 		if (is_jmp32) {
10000 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
10001 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
10002 
10003 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
10004 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
10005 		} else {
10006 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
10007 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
10008 
10009 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
10010 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
10011 		}
10012 		break;
10013 	}
10014 	default:
10015 		return;
10016 	}
10017 
10018 	if (is_jmp32) {
10019 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
10020 					     tnum_subreg(false_32off));
10021 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
10022 					    tnum_subreg(true_32off));
10023 		__reg_combine_32_into_64(false_reg);
10024 		__reg_combine_32_into_64(true_reg);
10025 	} else {
10026 		false_reg->var_off = false_64off;
10027 		true_reg->var_off = true_64off;
10028 		__reg_combine_64_into_32(false_reg);
10029 		__reg_combine_64_into_32(true_reg);
10030 	}
10031 }
10032 
10033 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
10034  * the variable reg.
10035  */
10036 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
10037 				struct bpf_reg_state *false_reg,
10038 				u64 val, u32 val32,
10039 				u8 opcode, bool is_jmp32)
10040 {
10041 	opcode = flip_opcode(opcode);
10042 	/* This uses zero as "not present in table"; luckily the zero opcode,
10043 	 * BPF_JA, can't get here.
10044 	 */
10045 	if (opcode)
10046 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
10047 }
10048 
10049 /* Regs are known to be equal, so intersect their min/max/var_off */
10050 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
10051 				  struct bpf_reg_state *dst_reg)
10052 {
10053 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
10054 							dst_reg->umin_value);
10055 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
10056 							dst_reg->umax_value);
10057 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
10058 							dst_reg->smin_value);
10059 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
10060 							dst_reg->smax_value);
10061 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
10062 							     dst_reg->var_off);
10063 	reg_bounds_sync(src_reg);
10064 	reg_bounds_sync(dst_reg);
10065 }
10066 
10067 static void reg_combine_min_max(struct bpf_reg_state *true_src,
10068 				struct bpf_reg_state *true_dst,
10069 				struct bpf_reg_state *false_src,
10070 				struct bpf_reg_state *false_dst,
10071 				u8 opcode)
10072 {
10073 	switch (opcode) {
10074 	case BPF_JEQ:
10075 		__reg_combine_min_max(true_src, true_dst);
10076 		break;
10077 	case BPF_JNE:
10078 		__reg_combine_min_max(false_src, false_dst);
10079 		break;
10080 	}
10081 }
10082 
10083 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10084 				 struct bpf_reg_state *reg, u32 id,
10085 				 bool is_null)
10086 {
10087 	if (type_may_be_null(reg->type) && reg->id == id &&
10088 	    !WARN_ON_ONCE(!reg->id)) {
10089 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10090 				 !tnum_equals_const(reg->var_off, 0) ||
10091 				 reg->off)) {
10092 			/* Old offset (both fixed and variable parts) should
10093 			 * have been known-zero, because we don't allow pointer
10094 			 * arithmetic on pointers that might be NULL. If we
10095 			 * see this happening, don't convert the register.
10096 			 */
10097 			return;
10098 		}
10099 		if (is_null) {
10100 			reg->type = SCALAR_VALUE;
10101 			/* We don't need id and ref_obj_id from this point
10102 			 * onwards anymore, thus we should better reset it,
10103 			 * so that state pruning has chances to take effect.
10104 			 */
10105 			reg->id = 0;
10106 			reg->ref_obj_id = 0;
10107 
10108 			return;
10109 		}
10110 
10111 		mark_ptr_not_null_reg(reg);
10112 
10113 		if (!reg_may_point_to_spin_lock(reg)) {
10114 			/* For not-NULL ptr, reg->ref_obj_id will be reset
10115 			 * in release_reference().
10116 			 *
10117 			 * reg->id is still used by spin_lock ptr. Other
10118 			 * than spin_lock ptr type, reg->id can be reset.
10119 			 */
10120 			reg->id = 0;
10121 		}
10122 	}
10123 }
10124 
10125 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10126  * be folded together at some point.
10127  */
10128 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10129 				  bool is_null)
10130 {
10131 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10132 	struct bpf_reg_state *regs = state->regs, *reg;
10133 	u32 ref_obj_id = regs[regno].ref_obj_id;
10134 	u32 id = regs[regno].id;
10135 
10136 	if (ref_obj_id && ref_obj_id == id && is_null)
10137 		/* regs[regno] is in the " == NULL" branch.
10138 		 * No one could have freed the reference state before
10139 		 * doing the NULL check.
10140 		 */
10141 		WARN_ON_ONCE(release_reference_state(state, id));
10142 
10143 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10144 		mark_ptr_or_null_reg(state, reg, id, is_null);
10145 	}));
10146 }
10147 
10148 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10149 				   struct bpf_reg_state *dst_reg,
10150 				   struct bpf_reg_state *src_reg,
10151 				   struct bpf_verifier_state *this_branch,
10152 				   struct bpf_verifier_state *other_branch)
10153 {
10154 	if (BPF_SRC(insn->code) != BPF_X)
10155 		return false;
10156 
10157 	/* Pointers are always 64-bit. */
10158 	if (BPF_CLASS(insn->code) == BPF_JMP32)
10159 		return false;
10160 
10161 	switch (BPF_OP(insn->code)) {
10162 	case BPF_JGT:
10163 		if ((dst_reg->type == PTR_TO_PACKET &&
10164 		     src_reg->type == PTR_TO_PACKET_END) ||
10165 		    (dst_reg->type == PTR_TO_PACKET_META &&
10166 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10167 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10168 			find_good_pkt_pointers(this_branch, dst_reg,
10169 					       dst_reg->type, false);
10170 			mark_pkt_end(other_branch, insn->dst_reg, true);
10171 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10172 			    src_reg->type == PTR_TO_PACKET) ||
10173 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10174 			    src_reg->type == PTR_TO_PACKET_META)) {
10175 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
10176 			find_good_pkt_pointers(other_branch, src_reg,
10177 					       src_reg->type, true);
10178 			mark_pkt_end(this_branch, insn->src_reg, false);
10179 		} else {
10180 			return false;
10181 		}
10182 		break;
10183 	case BPF_JLT:
10184 		if ((dst_reg->type == PTR_TO_PACKET &&
10185 		     src_reg->type == PTR_TO_PACKET_END) ||
10186 		    (dst_reg->type == PTR_TO_PACKET_META &&
10187 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10188 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10189 			find_good_pkt_pointers(other_branch, dst_reg,
10190 					       dst_reg->type, true);
10191 			mark_pkt_end(this_branch, insn->dst_reg, false);
10192 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10193 			    src_reg->type == PTR_TO_PACKET) ||
10194 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10195 			    src_reg->type == PTR_TO_PACKET_META)) {
10196 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
10197 			find_good_pkt_pointers(this_branch, src_reg,
10198 					       src_reg->type, false);
10199 			mark_pkt_end(other_branch, insn->src_reg, true);
10200 		} else {
10201 			return false;
10202 		}
10203 		break;
10204 	case BPF_JGE:
10205 		if ((dst_reg->type == PTR_TO_PACKET &&
10206 		     src_reg->type == PTR_TO_PACKET_END) ||
10207 		    (dst_reg->type == PTR_TO_PACKET_META &&
10208 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10209 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10210 			find_good_pkt_pointers(this_branch, dst_reg,
10211 					       dst_reg->type, true);
10212 			mark_pkt_end(other_branch, insn->dst_reg, false);
10213 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10214 			    src_reg->type == PTR_TO_PACKET) ||
10215 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10216 			    src_reg->type == PTR_TO_PACKET_META)) {
10217 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10218 			find_good_pkt_pointers(other_branch, src_reg,
10219 					       src_reg->type, false);
10220 			mark_pkt_end(this_branch, insn->src_reg, true);
10221 		} else {
10222 			return false;
10223 		}
10224 		break;
10225 	case BPF_JLE:
10226 		if ((dst_reg->type == PTR_TO_PACKET &&
10227 		     src_reg->type == PTR_TO_PACKET_END) ||
10228 		    (dst_reg->type == PTR_TO_PACKET_META &&
10229 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10230 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10231 			find_good_pkt_pointers(other_branch, dst_reg,
10232 					       dst_reg->type, false);
10233 			mark_pkt_end(this_branch, insn->dst_reg, true);
10234 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10235 			    src_reg->type == PTR_TO_PACKET) ||
10236 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10237 			    src_reg->type == PTR_TO_PACKET_META)) {
10238 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10239 			find_good_pkt_pointers(this_branch, src_reg,
10240 					       src_reg->type, true);
10241 			mark_pkt_end(other_branch, insn->src_reg, false);
10242 		} else {
10243 			return false;
10244 		}
10245 		break;
10246 	default:
10247 		return false;
10248 	}
10249 
10250 	return true;
10251 }
10252 
10253 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10254 			       struct bpf_reg_state *known_reg)
10255 {
10256 	struct bpf_func_state *state;
10257 	struct bpf_reg_state *reg;
10258 
10259 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10260 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10261 			*reg = *known_reg;
10262 	}));
10263 }
10264 
10265 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10266 			     struct bpf_insn *insn, int *insn_idx)
10267 {
10268 	struct bpf_verifier_state *this_branch = env->cur_state;
10269 	struct bpf_verifier_state *other_branch;
10270 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10271 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10272 	u8 opcode = BPF_OP(insn->code);
10273 	bool is_jmp32;
10274 	int pred = -1;
10275 	int err;
10276 
10277 	/* Only conditional jumps are expected to reach here. */
10278 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
10279 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10280 		return -EINVAL;
10281 	}
10282 
10283 	if (BPF_SRC(insn->code) == BPF_X) {
10284 		if (insn->imm != 0) {
10285 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10286 			return -EINVAL;
10287 		}
10288 
10289 		/* check src1 operand */
10290 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10291 		if (err)
10292 			return err;
10293 
10294 		if (is_pointer_value(env, insn->src_reg)) {
10295 			verbose(env, "R%d pointer comparison prohibited\n",
10296 				insn->src_reg);
10297 			return -EACCES;
10298 		}
10299 		src_reg = &regs[insn->src_reg];
10300 	} else {
10301 		if (insn->src_reg != BPF_REG_0) {
10302 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10303 			return -EINVAL;
10304 		}
10305 	}
10306 
10307 	/* check src2 operand */
10308 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10309 	if (err)
10310 		return err;
10311 
10312 	dst_reg = &regs[insn->dst_reg];
10313 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10314 
10315 	if (BPF_SRC(insn->code) == BPF_K) {
10316 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10317 	} else if (src_reg->type == SCALAR_VALUE &&
10318 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10319 		pred = is_branch_taken(dst_reg,
10320 				       tnum_subreg(src_reg->var_off).value,
10321 				       opcode,
10322 				       is_jmp32);
10323 	} else if (src_reg->type == SCALAR_VALUE &&
10324 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10325 		pred = is_branch_taken(dst_reg,
10326 				       src_reg->var_off.value,
10327 				       opcode,
10328 				       is_jmp32);
10329 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
10330 		   reg_is_pkt_pointer_any(src_reg) &&
10331 		   !is_jmp32) {
10332 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10333 	}
10334 
10335 	if (pred >= 0) {
10336 		/* If we get here with a dst_reg pointer type it is because
10337 		 * above is_branch_taken() special cased the 0 comparison.
10338 		 */
10339 		if (!__is_pointer_value(false, dst_reg))
10340 			err = mark_chain_precision(env, insn->dst_reg);
10341 		if (BPF_SRC(insn->code) == BPF_X && !err &&
10342 		    !__is_pointer_value(false, src_reg))
10343 			err = mark_chain_precision(env, insn->src_reg);
10344 		if (err)
10345 			return err;
10346 	}
10347 
10348 	if (pred == 1) {
10349 		/* Only follow the goto, ignore fall-through. If needed, push
10350 		 * the fall-through branch for simulation under speculative
10351 		 * execution.
10352 		 */
10353 		if (!env->bypass_spec_v1 &&
10354 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
10355 					       *insn_idx))
10356 			return -EFAULT;
10357 		*insn_idx += insn->off;
10358 		return 0;
10359 	} else if (pred == 0) {
10360 		/* Only follow the fall-through branch, since that's where the
10361 		 * program will go. If needed, push the goto branch for
10362 		 * simulation under speculative execution.
10363 		 */
10364 		if (!env->bypass_spec_v1 &&
10365 		    !sanitize_speculative_path(env, insn,
10366 					       *insn_idx + insn->off + 1,
10367 					       *insn_idx))
10368 			return -EFAULT;
10369 		return 0;
10370 	}
10371 
10372 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10373 				  false);
10374 	if (!other_branch)
10375 		return -EFAULT;
10376 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10377 
10378 	/* detect if we are comparing against a constant value so we can adjust
10379 	 * our min/max values for our dst register.
10380 	 * this is only legit if both are scalars (or pointers to the same
10381 	 * object, I suppose, but we don't support that right now), because
10382 	 * otherwise the different base pointers mean the offsets aren't
10383 	 * comparable.
10384 	 */
10385 	if (BPF_SRC(insn->code) == BPF_X) {
10386 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10387 
10388 		if (dst_reg->type == SCALAR_VALUE &&
10389 		    src_reg->type == SCALAR_VALUE) {
10390 			if (tnum_is_const(src_reg->var_off) ||
10391 			    (is_jmp32 &&
10392 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
10393 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
10394 						dst_reg,
10395 						src_reg->var_off.value,
10396 						tnum_subreg(src_reg->var_off).value,
10397 						opcode, is_jmp32);
10398 			else if (tnum_is_const(dst_reg->var_off) ||
10399 				 (is_jmp32 &&
10400 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
10401 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10402 						    src_reg,
10403 						    dst_reg->var_off.value,
10404 						    tnum_subreg(dst_reg->var_off).value,
10405 						    opcode, is_jmp32);
10406 			else if (!is_jmp32 &&
10407 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
10408 				/* Comparing for equality, we can combine knowledge */
10409 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
10410 						    &other_branch_regs[insn->dst_reg],
10411 						    src_reg, dst_reg, opcode);
10412 			if (src_reg->id &&
10413 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10414 				find_equal_scalars(this_branch, src_reg);
10415 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10416 			}
10417 
10418 		}
10419 	} else if (dst_reg->type == SCALAR_VALUE) {
10420 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
10421 					dst_reg, insn->imm, (u32)insn->imm,
10422 					opcode, is_jmp32);
10423 	}
10424 
10425 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10426 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10427 		find_equal_scalars(this_branch, dst_reg);
10428 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10429 	}
10430 
10431 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10432 	 * NOTE: these optimizations below are related with pointer comparison
10433 	 *       which will never be JMP32.
10434 	 */
10435 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10436 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10437 	    type_may_be_null(dst_reg->type)) {
10438 		/* Mark all identical registers in each branch as either
10439 		 * safe or unknown depending R == 0 or R != 0 conditional.
10440 		 */
10441 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10442 				      opcode == BPF_JNE);
10443 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10444 				      opcode == BPF_JEQ);
10445 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10446 					   this_branch, other_branch) &&
10447 		   is_pointer_value(env, insn->dst_reg)) {
10448 		verbose(env, "R%d pointer comparison prohibited\n",
10449 			insn->dst_reg);
10450 		return -EACCES;
10451 	}
10452 	if (env->log.level & BPF_LOG_LEVEL)
10453 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
10454 	return 0;
10455 }
10456 
10457 /* verify BPF_LD_IMM64 instruction */
10458 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10459 {
10460 	struct bpf_insn_aux_data *aux = cur_aux(env);
10461 	struct bpf_reg_state *regs = cur_regs(env);
10462 	struct bpf_reg_state *dst_reg;
10463 	struct bpf_map *map;
10464 	int err;
10465 
10466 	if (BPF_SIZE(insn->code) != BPF_DW) {
10467 		verbose(env, "invalid BPF_LD_IMM insn\n");
10468 		return -EINVAL;
10469 	}
10470 	if (insn->off != 0) {
10471 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10472 		return -EINVAL;
10473 	}
10474 
10475 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
10476 	if (err)
10477 		return err;
10478 
10479 	dst_reg = &regs[insn->dst_reg];
10480 	if (insn->src_reg == 0) {
10481 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10482 
10483 		dst_reg->type = SCALAR_VALUE;
10484 		__mark_reg_known(&regs[insn->dst_reg], imm);
10485 		return 0;
10486 	}
10487 
10488 	/* All special src_reg cases are listed below. From this point onwards
10489 	 * we either succeed and assign a corresponding dst_reg->type after
10490 	 * zeroing the offset, or fail and reject the program.
10491 	 */
10492 	mark_reg_known_zero(env, regs, insn->dst_reg);
10493 
10494 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10495 		dst_reg->type = aux->btf_var.reg_type;
10496 		switch (base_type(dst_reg->type)) {
10497 		case PTR_TO_MEM:
10498 			dst_reg->mem_size = aux->btf_var.mem_size;
10499 			break;
10500 		case PTR_TO_BTF_ID:
10501 			dst_reg->btf = aux->btf_var.btf;
10502 			dst_reg->btf_id = aux->btf_var.btf_id;
10503 			break;
10504 		default:
10505 			verbose(env, "bpf verifier is misconfigured\n");
10506 			return -EFAULT;
10507 		}
10508 		return 0;
10509 	}
10510 
10511 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
10512 		struct bpf_prog_aux *aux = env->prog->aux;
10513 		u32 subprogno = find_subprog(env,
10514 					     env->insn_idx + insn->imm + 1);
10515 
10516 		if (!aux->func_info) {
10517 			verbose(env, "missing btf func_info\n");
10518 			return -EINVAL;
10519 		}
10520 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10521 			verbose(env, "callback function not static\n");
10522 			return -EINVAL;
10523 		}
10524 
10525 		dst_reg->type = PTR_TO_FUNC;
10526 		dst_reg->subprogno = subprogno;
10527 		return 0;
10528 	}
10529 
10530 	map = env->used_maps[aux->map_index];
10531 	dst_reg->map_ptr = map;
10532 
10533 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10534 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10535 		dst_reg->type = PTR_TO_MAP_VALUE;
10536 		dst_reg->off = aux->map_off;
10537 		if (btf_record_has_field(map->record, BPF_SPIN_LOCK))
10538 			dst_reg->id = ++env->id_gen;
10539 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10540 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10541 		dst_reg->type = CONST_PTR_TO_MAP;
10542 	} else {
10543 		verbose(env, "bpf verifier is misconfigured\n");
10544 		return -EINVAL;
10545 	}
10546 
10547 	return 0;
10548 }
10549 
10550 static bool may_access_skb(enum bpf_prog_type type)
10551 {
10552 	switch (type) {
10553 	case BPF_PROG_TYPE_SOCKET_FILTER:
10554 	case BPF_PROG_TYPE_SCHED_CLS:
10555 	case BPF_PROG_TYPE_SCHED_ACT:
10556 		return true;
10557 	default:
10558 		return false;
10559 	}
10560 }
10561 
10562 /* verify safety of LD_ABS|LD_IND instructions:
10563  * - they can only appear in the programs where ctx == skb
10564  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10565  *   preserve R6-R9, and store return value into R0
10566  *
10567  * Implicit input:
10568  *   ctx == skb == R6 == CTX
10569  *
10570  * Explicit input:
10571  *   SRC == any register
10572  *   IMM == 32-bit immediate
10573  *
10574  * Output:
10575  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10576  */
10577 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10578 {
10579 	struct bpf_reg_state *regs = cur_regs(env);
10580 	static const int ctx_reg = BPF_REG_6;
10581 	u8 mode = BPF_MODE(insn->code);
10582 	int i, err;
10583 
10584 	if (!may_access_skb(resolve_prog_type(env->prog))) {
10585 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10586 		return -EINVAL;
10587 	}
10588 
10589 	if (!env->ops->gen_ld_abs) {
10590 		verbose(env, "bpf verifier is misconfigured\n");
10591 		return -EINVAL;
10592 	}
10593 
10594 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10595 	    BPF_SIZE(insn->code) == BPF_DW ||
10596 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10597 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10598 		return -EINVAL;
10599 	}
10600 
10601 	/* check whether implicit source operand (register R6) is readable */
10602 	err = check_reg_arg(env, ctx_reg, SRC_OP);
10603 	if (err)
10604 		return err;
10605 
10606 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10607 	 * gen_ld_abs() may terminate the program at runtime, leading to
10608 	 * reference leak.
10609 	 */
10610 	err = check_reference_leak(env);
10611 	if (err) {
10612 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10613 		return err;
10614 	}
10615 
10616 	if (env->cur_state->active_spin_lock) {
10617 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10618 		return -EINVAL;
10619 	}
10620 
10621 	if (regs[ctx_reg].type != PTR_TO_CTX) {
10622 		verbose(env,
10623 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10624 		return -EINVAL;
10625 	}
10626 
10627 	if (mode == BPF_IND) {
10628 		/* check explicit source operand */
10629 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10630 		if (err)
10631 			return err;
10632 	}
10633 
10634 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10635 	if (err < 0)
10636 		return err;
10637 
10638 	/* reset caller saved regs to unreadable */
10639 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10640 		mark_reg_not_init(env, regs, caller_saved[i]);
10641 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10642 	}
10643 
10644 	/* mark destination R0 register as readable, since it contains
10645 	 * the value fetched from the packet.
10646 	 * Already marked as written above.
10647 	 */
10648 	mark_reg_unknown(env, regs, BPF_REG_0);
10649 	/* ld_abs load up to 32-bit skb data. */
10650 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10651 	return 0;
10652 }
10653 
10654 static int check_return_code(struct bpf_verifier_env *env)
10655 {
10656 	struct tnum enforce_attach_type_range = tnum_unknown;
10657 	const struct bpf_prog *prog = env->prog;
10658 	struct bpf_reg_state *reg;
10659 	struct tnum range = tnum_range(0, 1);
10660 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10661 	int err;
10662 	struct bpf_func_state *frame = env->cur_state->frame[0];
10663 	const bool is_subprog = frame->subprogno;
10664 
10665 	/* LSM and struct_ops func-ptr's return type could be "void" */
10666 	if (!is_subprog) {
10667 		switch (prog_type) {
10668 		case BPF_PROG_TYPE_LSM:
10669 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
10670 				/* See below, can be 0 or 0-1 depending on hook. */
10671 				break;
10672 			fallthrough;
10673 		case BPF_PROG_TYPE_STRUCT_OPS:
10674 			if (!prog->aux->attach_func_proto->type)
10675 				return 0;
10676 			break;
10677 		default:
10678 			break;
10679 		}
10680 	}
10681 
10682 	/* eBPF calling convention is such that R0 is used
10683 	 * to return the value from eBPF program.
10684 	 * Make sure that it's readable at this time
10685 	 * of bpf_exit, which means that program wrote
10686 	 * something into it earlier
10687 	 */
10688 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10689 	if (err)
10690 		return err;
10691 
10692 	if (is_pointer_value(env, BPF_REG_0)) {
10693 		verbose(env, "R0 leaks addr as return value\n");
10694 		return -EACCES;
10695 	}
10696 
10697 	reg = cur_regs(env) + BPF_REG_0;
10698 
10699 	if (frame->in_async_callback_fn) {
10700 		/* enforce return zero from async callbacks like timer */
10701 		if (reg->type != SCALAR_VALUE) {
10702 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10703 				reg_type_str(env, reg->type));
10704 			return -EINVAL;
10705 		}
10706 
10707 		if (!tnum_in(tnum_const(0), reg->var_off)) {
10708 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10709 			return -EINVAL;
10710 		}
10711 		return 0;
10712 	}
10713 
10714 	if (is_subprog) {
10715 		if (reg->type != SCALAR_VALUE) {
10716 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10717 				reg_type_str(env, reg->type));
10718 			return -EINVAL;
10719 		}
10720 		return 0;
10721 	}
10722 
10723 	switch (prog_type) {
10724 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10725 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10726 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10727 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10728 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10729 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10730 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10731 			range = tnum_range(1, 1);
10732 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10733 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10734 			range = tnum_range(0, 3);
10735 		break;
10736 	case BPF_PROG_TYPE_CGROUP_SKB:
10737 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10738 			range = tnum_range(0, 3);
10739 			enforce_attach_type_range = tnum_range(2, 3);
10740 		}
10741 		break;
10742 	case BPF_PROG_TYPE_CGROUP_SOCK:
10743 	case BPF_PROG_TYPE_SOCK_OPS:
10744 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10745 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10746 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10747 		break;
10748 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10749 		if (!env->prog->aux->attach_btf_id)
10750 			return 0;
10751 		range = tnum_const(0);
10752 		break;
10753 	case BPF_PROG_TYPE_TRACING:
10754 		switch (env->prog->expected_attach_type) {
10755 		case BPF_TRACE_FENTRY:
10756 		case BPF_TRACE_FEXIT:
10757 			range = tnum_const(0);
10758 			break;
10759 		case BPF_TRACE_RAW_TP:
10760 		case BPF_MODIFY_RETURN:
10761 			return 0;
10762 		case BPF_TRACE_ITER:
10763 			break;
10764 		default:
10765 			return -ENOTSUPP;
10766 		}
10767 		break;
10768 	case BPF_PROG_TYPE_SK_LOOKUP:
10769 		range = tnum_range(SK_DROP, SK_PASS);
10770 		break;
10771 
10772 	case BPF_PROG_TYPE_LSM:
10773 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10774 			/* Regular BPF_PROG_TYPE_LSM programs can return
10775 			 * any value.
10776 			 */
10777 			return 0;
10778 		}
10779 		if (!env->prog->aux->attach_func_proto->type) {
10780 			/* Make sure programs that attach to void
10781 			 * hooks don't try to modify return value.
10782 			 */
10783 			range = tnum_range(1, 1);
10784 		}
10785 		break;
10786 
10787 	case BPF_PROG_TYPE_EXT:
10788 		/* freplace program can return anything as its return value
10789 		 * depends on the to-be-replaced kernel func or bpf program.
10790 		 */
10791 	default:
10792 		return 0;
10793 	}
10794 
10795 	if (reg->type != SCALAR_VALUE) {
10796 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10797 			reg_type_str(env, reg->type));
10798 		return -EINVAL;
10799 	}
10800 
10801 	if (!tnum_in(range, reg->var_off)) {
10802 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10803 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10804 		    prog_type == BPF_PROG_TYPE_LSM &&
10805 		    !prog->aux->attach_func_proto->type)
10806 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10807 		return -EINVAL;
10808 	}
10809 
10810 	if (!tnum_is_unknown(enforce_attach_type_range) &&
10811 	    tnum_in(enforce_attach_type_range, reg->var_off))
10812 		env->prog->enforce_expected_attach_type = 1;
10813 	return 0;
10814 }
10815 
10816 /* non-recursive DFS pseudo code
10817  * 1  procedure DFS-iterative(G,v):
10818  * 2      label v as discovered
10819  * 3      let S be a stack
10820  * 4      S.push(v)
10821  * 5      while S is not empty
10822  * 6            t <- S.peek()
10823  * 7            if t is what we're looking for:
10824  * 8                return t
10825  * 9            for all edges e in G.adjacentEdges(t) do
10826  * 10               if edge e is already labelled
10827  * 11                   continue with the next edge
10828  * 12               w <- G.adjacentVertex(t,e)
10829  * 13               if vertex w is not discovered and not explored
10830  * 14                   label e as tree-edge
10831  * 15                   label w as discovered
10832  * 16                   S.push(w)
10833  * 17                   continue at 5
10834  * 18               else if vertex w is discovered
10835  * 19                   label e as back-edge
10836  * 20               else
10837  * 21                   // vertex w is explored
10838  * 22                   label e as forward- or cross-edge
10839  * 23           label t as explored
10840  * 24           S.pop()
10841  *
10842  * convention:
10843  * 0x10 - discovered
10844  * 0x11 - discovered and fall-through edge labelled
10845  * 0x12 - discovered and fall-through and branch edges labelled
10846  * 0x20 - explored
10847  */
10848 
10849 enum {
10850 	DISCOVERED = 0x10,
10851 	EXPLORED = 0x20,
10852 	FALLTHROUGH = 1,
10853 	BRANCH = 2,
10854 };
10855 
10856 static u32 state_htab_size(struct bpf_verifier_env *env)
10857 {
10858 	return env->prog->len;
10859 }
10860 
10861 static struct bpf_verifier_state_list **explored_state(
10862 					struct bpf_verifier_env *env,
10863 					int idx)
10864 {
10865 	struct bpf_verifier_state *cur = env->cur_state;
10866 	struct bpf_func_state *state = cur->frame[cur->curframe];
10867 
10868 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10869 }
10870 
10871 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10872 {
10873 	env->insn_aux_data[idx].prune_point = true;
10874 }
10875 
10876 enum {
10877 	DONE_EXPLORING = 0,
10878 	KEEP_EXPLORING = 1,
10879 };
10880 
10881 /* t, w, e - match pseudo-code above:
10882  * t - index of current instruction
10883  * w - next instruction
10884  * e - edge
10885  */
10886 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10887 		     bool loop_ok)
10888 {
10889 	int *insn_stack = env->cfg.insn_stack;
10890 	int *insn_state = env->cfg.insn_state;
10891 
10892 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10893 		return DONE_EXPLORING;
10894 
10895 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10896 		return DONE_EXPLORING;
10897 
10898 	if (w < 0 || w >= env->prog->len) {
10899 		verbose_linfo(env, t, "%d: ", t);
10900 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10901 		return -EINVAL;
10902 	}
10903 
10904 	if (e == BRANCH)
10905 		/* mark branch target for state pruning */
10906 		init_explored_state(env, w);
10907 
10908 	if (insn_state[w] == 0) {
10909 		/* tree-edge */
10910 		insn_state[t] = DISCOVERED | e;
10911 		insn_state[w] = DISCOVERED;
10912 		if (env->cfg.cur_stack >= env->prog->len)
10913 			return -E2BIG;
10914 		insn_stack[env->cfg.cur_stack++] = w;
10915 		return KEEP_EXPLORING;
10916 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10917 		if (loop_ok && env->bpf_capable)
10918 			return DONE_EXPLORING;
10919 		verbose_linfo(env, t, "%d: ", t);
10920 		verbose_linfo(env, w, "%d: ", w);
10921 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10922 		return -EINVAL;
10923 	} else if (insn_state[w] == EXPLORED) {
10924 		/* forward- or cross-edge */
10925 		insn_state[t] = DISCOVERED | e;
10926 	} else {
10927 		verbose(env, "insn state internal bug\n");
10928 		return -EFAULT;
10929 	}
10930 	return DONE_EXPLORING;
10931 }
10932 
10933 static int visit_func_call_insn(int t, int insn_cnt,
10934 				struct bpf_insn *insns,
10935 				struct bpf_verifier_env *env,
10936 				bool visit_callee)
10937 {
10938 	int ret;
10939 
10940 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10941 	if (ret)
10942 		return ret;
10943 
10944 	if (t + 1 < insn_cnt)
10945 		init_explored_state(env, t + 1);
10946 	if (visit_callee) {
10947 		init_explored_state(env, t);
10948 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10949 				/* It's ok to allow recursion from CFG point of
10950 				 * view. __check_func_call() will do the actual
10951 				 * check.
10952 				 */
10953 				bpf_pseudo_func(insns + t));
10954 	}
10955 	return ret;
10956 }
10957 
10958 /* Visits the instruction at index t and returns one of the following:
10959  *  < 0 - an error occurred
10960  *  DONE_EXPLORING - the instruction was fully explored
10961  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10962  */
10963 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10964 {
10965 	struct bpf_insn *insns = env->prog->insnsi;
10966 	int ret;
10967 
10968 	if (bpf_pseudo_func(insns + t))
10969 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10970 
10971 	/* All non-branch instructions have a single fall-through edge. */
10972 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10973 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10974 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10975 
10976 	switch (BPF_OP(insns[t].code)) {
10977 	case BPF_EXIT:
10978 		return DONE_EXPLORING;
10979 
10980 	case BPF_CALL:
10981 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10982 			/* Mark this call insn to trigger is_state_visited() check
10983 			 * before call itself is processed by __check_func_call().
10984 			 * Otherwise new async state will be pushed for further
10985 			 * exploration.
10986 			 */
10987 			init_explored_state(env, t);
10988 		return visit_func_call_insn(t, insn_cnt, insns, env,
10989 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10990 
10991 	case BPF_JA:
10992 		if (BPF_SRC(insns[t].code) != BPF_K)
10993 			return -EINVAL;
10994 
10995 		/* unconditional jump with single edge */
10996 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10997 				true);
10998 		if (ret)
10999 			return ret;
11000 
11001 		/* unconditional jmp is not a good pruning point,
11002 		 * but it's marked, since backtracking needs
11003 		 * to record jmp history in is_state_visited().
11004 		 */
11005 		init_explored_state(env, t + insns[t].off + 1);
11006 		/* tell verifier to check for equivalent states
11007 		 * after every call and jump
11008 		 */
11009 		if (t + 1 < insn_cnt)
11010 			init_explored_state(env, t + 1);
11011 
11012 		return ret;
11013 
11014 	default:
11015 		/* conditional jump with two edges */
11016 		init_explored_state(env, t);
11017 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
11018 		if (ret)
11019 			return ret;
11020 
11021 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
11022 	}
11023 }
11024 
11025 /* non-recursive depth-first-search to detect loops in BPF program
11026  * loop == back-edge in directed graph
11027  */
11028 static int check_cfg(struct bpf_verifier_env *env)
11029 {
11030 	int insn_cnt = env->prog->len;
11031 	int *insn_stack, *insn_state;
11032 	int ret = 0;
11033 	int i;
11034 
11035 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
11036 	if (!insn_state)
11037 		return -ENOMEM;
11038 
11039 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
11040 	if (!insn_stack) {
11041 		kvfree(insn_state);
11042 		return -ENOMEM;
11043 	}
11044 
11045 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
11046 	insn_stack[0] = 0; /* 0 is the first instruction */
11047 	env->cfg.cur_stack = 1;
11048 
11049 	while (env->cfg.cur_stack > 0) {
11050 		int t = insn_stack[env->cfg.cur_stack - 1];
11051 
11052 		ret = visit_insn(t, insn_cnt, env);
11053 		switch (ret) {
11054 		case DONE_EXPLORING:
11055 			insn_state[t] = EXPLORED;
11056 			env->cfg.cur_stack--;
11057 			break;
11058 		case KEEP_EXPLORING:
11059 			break;
11060 		default:
11061 			if (ret > 0) {
11062 				verbose(env, "visit_insn internal bug\n");
11063 				ret = -EFAULT;
11064 			}
11065 			goto err_free;
11066 		}
11067 	}
11068 
11069 	if (env->cfg.cur_stack < 0) {
11070 		verbose(env, "pop stack internal bug\n");
11071 		ret = -EFAULT;
11072 		goto err_free;
11073 	}
11074 
11075 	for (i = 0; i < insn_cnt; i++) {
11076 		if (insn_state[i] != EXPLORED) {
11077 			verbose(env, "unreachable insn %d\n", i);
11078 			ret = -EINVAL;
11079 			goto err_free;
11080 		}
11081 	}
11082 	ret = 0; /* cfg looks good */
11083 
11084 err_free:
11085 	kvfree(insn_state);
11086 	kvfree(insn_stack);
11087 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
11088 	return ret;
11089 }
11090 
11091 static int check_abnormal_return(struct bpf_verifier_env *env)
11092 {
11093 	int i;
11094 
11095 	for (i = 1; i < env->subprog_cnt; i++) {
11096 		if (env->subprog_info[i].has_ld_abs) {
11097 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11098 			return -EINVAL;
11099 		}
11100 		if (env->subprog_info[i].has_tail_call) {
11101 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11102 			return -EINVAL;
11103 		}
11104 	}
11105 	return 0;
11106 }
11107 
11108 /* The minimum supported BTF func info size */
11109 #define MIN_BPF_FUNCINFO_SIZE	8
11110 #define MAX_FUNCINFO_REC_SIZE	252
11111 
11112 static int check_btf_func(struct bpf_verifier_env *env,
11113 			  const union bpf_attr *attr,
11114 			  bpfptr_t uattr)
11115 {
11116 	const struct btf_type *type, *func_proto, *ret_type;
11117 	u32 i, nfuncs, urec_size, min_size;
11118 	u32 krec_size = sizeof(struct bpf_func_info);
11119 	struct bpf_func_info *krecord;
11120 	struct bpf_func_info_aux *info_aux = NULL;
11121 	struct bpf_prog *prog;
11122 	const struct btf *btf;
11123 	bpfptr_t urecord;
11124 	u32 prev_offset = 0;
11125 	bool scalar_return;
11126 	int ret = -ENOMEM;
11127 
11128 	nfuncs = attr->func_info_cnt;
11129 	if (!nfuncs) {
11130 		if (check_abnormal_return(env))
11131 			return -EINVAL;
11132 		return 0;
11133 	}
11134 
11135 	if (nfuncs != env->subprog_cnt) {
11136 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11137 		return -EINVAL;
11138 	}
11139 
11140 	urec_size = attr->func_info_rec_size;
11141 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11142 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
11143 	    urec_size % sizeof(u32)) {
11144 		verbose(env, "invalid func info rec size %u\n", urec_size);
11145 		return -EINVAL;
11146 	}
11147 
11148 	prog = env->prog;
11149 	btf = prog->aux->btf;
11150 
11151 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11152 	min_size = min_t(u32, krec_size, urec_size);
11153 
11154 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11155 	if (!krecord)
11156 		return -ENOMEM;
11157 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11158 	if (!info_aux)
11159 		goto err_free;
11160 
11161 	for (i = 0; i < nfuncs; i++) {
11162 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11163 		if (ret) {
11164 			if (ret == -E2BIG) {
11165 				verbose(env, "nonzero tailing record in func info");
11166 				/* set the size kernel expects so loader can zero
11167 				 * out the rest of the record.
11168 				 */
11169 				if (copy_to_bpfptr_offset(uattr,
11170 							  offsetof(union bpf_attr, func_info_rec_size),
11171 							  &min_size, sizeof(min_size)))
11172 					ret = -EFAULT;
11173 			}
11174 			goto err_free;
11175 		}
11176 
11177 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11178 			ret = -EFAULT;
11179 			goto err_free;
11180 		}
11181 
11182 		/* check insn_off */
11183 		ret = -EINVAL;
11184 		if (i == 0) {
11185 			if (krecord[i].insn_off) {
11186 				verbose(env,
11187 					"nonzero insn_off %u for the first func info record",
11188 					krecord[i].insn_off);
11189 				goto err_free;
11190 			}
11191 		} else if (krecord[i].insn_off <= prev_offset) {
11192 			verbose(env,
11193 				"same or smaller insn offset (%u) than previous func info record (%u)",
11194 				krecord[i].insn_off, prev_offset);
11195 			goto err_free;
11196 		}
11197 
11198 		if (env->subprog_info[i].start != krecord[i].insn_off) {
11199 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11200 			goto err_free;
11201 		}
11202 
11203 		/* check type_id */
11204 		type = btf_type_by_id(btf, krecord[i].type_id);
11205 		if (!type || !btf_type_is_func(type)) {
11206 			verbose(env, "invalid type id %d in func info",
11207 				krecord[i].type_id);
11208 			goto err_free;
11209 		}
11210 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11211 
11212 		func_proto = btf_type_by_id(btf, type->type);
11213 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11214 			/* btf_func_check() already verified it during BTF load */
11215 			goto err_free;
11216 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11217 		scalar_return =
11218 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11219 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11220 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11221 			goto err_free;
11222 		}
11223 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11224 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11225 			goto err_free;
11226 		}
11227 
11228 		prev_offset = krecord[i].insn_off;
11229 		bpfptr_add(&urecord, urec_size);
11230 	}
11231 
11232 	prog->aux->func_info = krecord;
11233 	prog->aux->func_info_cnt = nfuncs;
11234 	prog->aux->func_info_aux = info_aux;
11235 	return 0;
11236 
11237 err_free:
11238 	kvfree(krecord);
11239 	kfree(info_aux);
11240 	return ret;
11241 }
11242 
11243 static void adjust_btf_func(struct bpf_verifier_env *env)
11244 {
11245 	struct bpf_prog_aux *aux = env->prog->aux;
11246 	int i;
11247 
11248 	if (!aux->func_info)
11249 		return;
11250 
11251 	for (i = 0; i < env->subprog_cnt; i++)
11252 		aux->func_info[i].insn_off = env->subprog_info[i].start;
11253 }
11254 
11255 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
11256 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
11257 
11258 static int check_btf_line(struct bpf_verifier_env *env,
11259 			  const union bpf_attr *attr,
11260 			  bpfptr_t uattr)
11261 {
11262 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11263 	struct bpf_subprog_info *sub;
11264 	struct bpf_line_info *linfo;
11265 	struct bpf_prog *prog;
11266 	const struct btf *btf;
11267 	bpfptr_t ulinfo;
11268 	int err;
11269 
11270 	nr_linfo = attr->line_info_cnt;
11271 	if (!nr_linfo)
11272 		return 0;
11273 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11274 		return -EINVAL;
11275 
11276 	rec_size = attr->line_info_rec_size;
11277 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11278 	    rec_size > MAX_LINEINFO_REC_SIZE ||
11279 	    rec_size & (sizeof(u32) - 1))
11280 		return -EINVAL;
11281 
11282 	/* Need to zero it in case the userspace may
11283 	 * pass in a smaller bpf_line_info object.
11284 	 */
11285 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11286 			 GFP_KERNEL | __GFP_NOWARN);
11287 	if (!linfo)
11288 		return -ENOMEM;
11289 
11290 	prog = env->prog;
11291 	btf = prog->aux->btf;
11292 
11293 	s = 0;
11294 	sub = env->subprog_info;
11295 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11296 	expected_size = sizeof(struct bpf_line_info);
11297 	ncopy = min_t(u32, expected_size, rec_size);
11298 	for (i = 0; i < nr_linfo; i++) {
11299 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11300 		if (err) {
11301 			if (err == -E2BIG) {
11302 				verbose(env, "nonzero tailing record in line_info");
11303 				if (copy_to_bpfptr_offset(uattr,
11304 							  offsetof(union bpf_attr, line_info_rec_size),
11305 							  &expected_size, sizeof(expected_size)))
11306 					err = -EFAULT;
11307 			}
11308 			goto err_free;
11309 		}
11310 
11311 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11312 			err = -EFAULT;
11313 			goto err_free;
11314 		}
11315 
11316 		/*
11317 		 * Check insn_off to ensure
11318 		 * 1) strictly increasing AND
11319 		 * 2) bounded by prog->len
11320 		 *
11321 		 * The linfo[0].insn_off == 0 check logically falls into
11322 		 * the later "missing bpf_line_info for func..." case
11323 		 * because the first linfo[0].insn_off must be the
11324 		 * first sub also and the first sub must have
11325 		 * subprog_info[0].start == 0.
11326 		 */
11327 		if ((i && linfo[i].insn_off <= prev_offset) ||
11328 		    linfo[i].insn_off >= prog->len) {
11329 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11330 				i, linfo[i].insn_off, prev_offset,
11331 				prog->len);
11332 			err = -EINVAL;
11333 			goto err_free;
11334 		}
11335 
11336 		if (!prog->insnsi[linfo[i].insn_off].code) {
11337 			verbose(env,
11338 				"Invalid insn code at line_info[%u].insn_off\n",
11339 				i);
11340 			err = -EINVAL;
11341 			goto err_free;
11342 		}
11343 
11344 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11345 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11346 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11347 			err = -EINVAL;
11348 			goto err_free;
11349 		}
11350 
11351 		if (s != env->subprog_cnt) {
11352 			if (linfo[i].insn_off == sub[s].start) {
11353 				sub[s].linfo_idx = i;
11354 				s++;
11355 			} else if (sub[s].start < linfo[i].insn_off) {
11356 				verbose(env, "missing bpf_line_info for func#%u\n", s);
11357 				err = -EINVAL;
11358 				goto err_free;
11359 			}
11360 		}
11361 
11362 		prev_offset = linfo[i].insn_off;
11363 		bpfptr_add(&ulinfo, rec_size);
11364 	}
11365 
11366 	if (s != env->subprog_cnt) {
11367 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11368 			env->subprog_cnt - s, s);
11369 		err = -EINVAL;
11370 		goto err_free;
11371 	}
11372 
11373 	prog->aux->linfo = linfo;
11374 	prog->aux->nr_linfo = nr_linfo;
11375 
11376 	return 0;
11377 
11378 err_free:
11379 	kvfree(linfo);
11380 	return err;
11381 }
11382 
11383 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
11384 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
11385 
11386 static int check_core_relo(struct bpf_verifier_env *env,
11387 			   const union bpf_attr *attr,
11388 			   bpfptr_t uattr)
11389 {
11390 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11391 	struct bpf_core_relo core_relo = {};
11392 	struct bpf_prog *prog = env->prog;
11393 	const struct btf *btf = prog->aux->btf;
11394 	struct bpf_core_ctx ctx = {
11395 		.log = &env->log,
11396 		.btf = btf,
11397 	};
11398 	bpfptr_t u_core_relo;
11399 	int err;
11400 
11401 	nr_core_relo = attr->core_relo_cnt;
11402 	if (!nr_core_relo)
11403 		return 0;
11404 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11405 		return -EINVAL;
11406 
11407 	rec_size = attr->core_relo_rec_size;
11408 	if (rec_size < MIN_CORE_RELO_SIZE ||
11409 	    rec_size > MAX_CORE_RELO_SIZE ||
11410 	    rec_size % sizeof(u32))
11411 		return -EINVAL;
11412 
11413 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11414 	expected_size = sizeof(struct bpf_core_relo);
11415 	ncopy = min_t(u32, expected_size, rec_size);
11416 
11417 	/* Unlike func_info and line_info, copy and apply each CO-RE
11418 	 * relocation record one at a time.
11419 	 */
11420 	for (i = 0; i < nr_core_relo; i++) {
11421 		/* future proofing when sizeof(bpf_core_relo) changes */
11422 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11423 		if (err) {
11424 			if (err == -E2BIG) {
11425 				verbose(env, "nonzero tailing record in core_relo");
11426 				if (copy_to_bpfptr_offset(uattr,
11427 							  offsetof(union bpf_attr, core_relo_rec_size),
11428 							  &expected_size, sizeof(expected_size)))
11429 					err = -EFAULT;
11430 			}
11431 			break;
11432 		}
11433 
11434 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11435 			err = -EFAULT;
11436 			break;
11437 		}
11438 
11439 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11440 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11441 				i, core_relo.insn_off, prog->len);
11442 			err = -EINVAL;
11443 			break;
11444 		}
11445 
11446 		err = bpf_core_apply(&ctx, &core_relo, i,
11447 				     &prog->insnsi[core_relo.insn_off / 8]);
11448 		if (err)
11449 			break;
11450 		bpfptr_add(&u_core_relo, rec_size);
11451 	}
11452 	return err;
11453 }
11454 
11455 static int check_btf_info(struct bpf_verifier_env *env,
11456 			  const union bpf_attr *attr,
11457 			  bpfptr_t uattr)
11458 {
11459 	struct btf *btf;
11460 	int err;
11461 
11462 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
11463 		if (check_abnormal_return(env))
11464 			return -EINVAL;
11465 		return 0;
11466 	}
11467 
11468 	btf = btf_get_by_fd(attr->prog_btf_fd);
11469 	if (IS_ERR(btf))
11470 		return PTR_ERR(btf);
11471 	if (btf_is_kernel(btf)) {
11472 		btf_put(btf);
11473 		return -EACCES;
11474 	}
11475 	env->prog->aux->btf = btf;
11476 
11477 	err = check_btf_func(env, attr, uattr);
11478 	if (err)
11479 		return err;
11480 
11481 	err = check_btf_line(env, attr, uattr);
11482 	if (err)
11483 		return err;
11484 
11485 	err = check_core_relo(env, attr, uattr);
11486 	if (err)
11487 		return err;
11488 
11489 	return 0;
11490 }
11491 
11492 /* check %cur's range satisfies %old's */
11493 static bool range_within(struct bpf_reg_state *old,
11494 			 struct bpf_reg_state *cur)
11495 {
11496 	return old->umin_value <= cur->umin_value &&
11497 	       old->umax_value >= cur->umax_value &&
11498 	       old->smin_value <= cur->smin_value &&
11499 	       old->smax_value >= cur->smax_value &&
11500 	       old->u32_min_value <= cur->u32_min_value &&
11501 	       old->u32_max_value >= cur->u32_max_value &&
11502 	       old->s32_min_value <= cur->s32_min_value &&
11503 	       old->s32_max_value >= cur->s32_max_value;
11504 }
11505 
11506 /* If in the old state two registers had the same id, then they need to have
11507  * the same id in the new state as well.  But that id could be different from
11508  * the old state, so we need to track the mapping from old to new ids.
11509  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11510  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11511  * regs with a different old id could still have new id 9, we don't care about
11512  * that.
11513  * So we look through our idmap to see if this old id has been seen before.  If
11514  * so, we require the new id to match; otherwise, we add the id pair to the map.
11515  */
11516 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11517 {
11518 	unsigned int i;
11519 
11520 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11521 		if (!idmap[i].old) {
11522 			/* Reached an empty slot; haven't seen this id before */
11523 			idmap[i].old = old_id;
11524 			idmap[i].cur = cur_id;
11525 			return true;
11526 		}
11527 		if (idmap[i].old == old_id)
11528 			return idmap[i].cur == cur_id;
11529 	}
11530 	/* We ran out of idmap slots, which should be impossible */
11531 	WARN_ON_ONCE(1);
11532 	return false;
11533 }
11534 
11535 static void clean_func_state(struct bpf_verifier_env *env,
11536 			     struct bpf_func_state *st)
11537 {
11538 	enum bpf_reg_liveness live;
11539 	int i, j;
11540 
11541 	for (i = 0; i < BPF_REG_FP; i++) {
11542 		live = st->regs[i].live;
11543 		/* liveness must not touch this register anymore */
11544 		st->regs[i].live |= REG_LIVE_DONE;
11545 		if (!(live & REG_LIVE_READ))
11546 			/* since the register is unused, clear its state
11547 			 * to make further comparison simpler
11548 			 */
11549 			__mark_reg_not_init(env, &st->regs[i]);
11550 	}
11551 
11552 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11553 		live = st->stack[i].spilled_ptr.live;
11554 		/* liveness must not touch this stack slot anymore */
11555 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11556 		if (!(live & REG_LIVE_READ)) {
11557 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11558 			for (j = 0; j < BPF_REG_SIZE; j++)
11559 				st->stack[i].slot_type[j] = STACK_INVALID;
11560 		}
11561 	}
11562 }
11563 
11564 static void clean_verifier_state(struct bpf_verifier_env *env,
11565 				 struct bpf_verifier_state *st)
11566 {
11567 	int i;
11568 
11569 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11570 		/* all regs in this state in all frames were already marked */
11571 		return;
11572 
11573 	for (i = 0; i <= st->curframe; i++)
11574 		clean_func_state(env, st->frame[i]);
11575 }
11576 
11577 /* the parentage chains form a tree.
11578  * the verifier states are added to state lists at given insn and
11579  * pushed into state stack for future exploration.
11580  * when the verifier reaches bpf_exit insn some of the verifer states
11581  * stored in the state lists have their final liveness state already,
11582  * but a lot of states will get revised from liveness point of view when
11583  * the verifier explores other branches.
11584  * Example:
11585  * 1: r0 = 1
11586  * 2: if r1 == 100 goto pc+1
11587  * 3: r0 = 2
11588  * 4: exit
11589  * when the verifier reaches exit insn the register r0 in the state list of
11590  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11591  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11592  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11593  *
11594  * Since the verifier pushes the branch states as it sees them while exploring
11595  * the program the condition of walking the branch instruction for the second
11596  * time means that all states below this branch were already explored and
11597  * their final liveness marks are already propagated.
11598  * Hence when the verifier completes the search of state list in is_state_visited()
11599  * we can call this clean_live_states() function to mark all liveness states
11600  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11601  * will not be used.
11602  * This function also clears the registers and stack for states that !READ
11603  * to simplify state merging.
11604  *
11605  * Important note here that walking the same branch instruction in the callee
11606  * doesn't meant that the states are DONE. The verifier has to compare
11607  * the callsites
11608  */
11609 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11610 			      struct bpf_verifier_state *cur)
11611 {
11612 	struct bpf_verifier_state_list *sl;
11613 	int i;
11614 
11615 	sl = *explored_state(env, insn);
11616 	while (sl) {
11617 		if (sl->state.branches)
11618 			goto next;
11619 		if (sl->state.insn_idx != insn ||
11620 		    sl->state.curframe != cur->curframe)
11621 			goto next;
11622 		for (i = 0; i <= cur->curframe; i++)
11623 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11624 				goto next;
11625 		clean_verifier_state(env, &sl->state);
11626 next:
11627 		sl = sl->next;
11628 	}
11629 }
11630 
11631 /* Returns true if (rold safe implies rcur safe) */
11632 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11633 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11634 {
11635 	bool equal;
11636 
11637 	if (!(rold->live & REG_LIVE_READ))
11638 		/* explored state didn't use this */
11639 		return true;
11640 
11641 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11642 
11643 	if (rold->type == PTR_TO_STACK)
11644 		/* two stack pointers are equal only if they're pointing to
11645 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
11646 		 */
11647 		return equal && rold->frameno == rcur->frameno;
11648 
11649 	if (equal)
11650 		return true;
11651 
11652 	if (rold->type == NOT_INIT)
11653 		/* explored state can't have used this */
11654 		return true;
11655 	if (rcur->type == NOT_INIT)
11656 		return false;
11657 	switch (base_type(rold->type)) {
11658 	case SCALAR_VALUE:
11659 		if (env->explore_alu_limits)
11660 			return false;
11661 		if (rcur->type == SCALAR_VALUE) {
11662 			if (!rold->precise)
11663 				return true;
11664 			/* new val must satisfy old val knowledge */
11665 			return range_within(rold, rcur) &&
11666 			       tnum_in(rold->var_off, rcur->var_off);
11667 		} else {
11668 			/* We're trying to use a pointer in place of a scalar.
11669 			 * Even if the scalar was unbounded, this could lead to
11670 			 * pointer leaks because scalars are allowed to leak
11671 			 * while pointers are not. We could make this safe in
11672 			 * special cases if root is calling us, but it's
11673 			 * probably not worth the hassle.
11674 			 */
11675 			return false;
11676 		}
11677 	case PTR_TO_MAP_KEY:
11678 	case PTR_TO_MAP_VALUE:
11679 		/* a PTR_TO_MAP_VALUE could be safe to use as a
11680 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11681 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11682 		 * checked, doing so could have affected others with the same
11683 		 * id, and we can't check for that because we lost the id when
11684 		 * we converted to a PTR_TO_MAP_VALUE.
11685 		 */
11686 		if (type_may_be_null(rold->type)) {
11687 			if (!type_may_be_null(rcur->type))
11688 				return false;
11689 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11690 				return false;
11691 			/* Check our ids match any regs they're supposed to */
11692 			return check_ids(rold->id, rcur->id, idmap);
11693 		}
11694 
11695 		/* If the new min/max/var_off satisfy the old ones and
11696 		 * everything else matches, we are OK.
11697 		 * 'id' is not compared, since it's only used for maps with
11698 		 * bpf_spin_lock inside map element and in such cases if
11699 		 * the rest of the prog is valid for one map element then
11700 		 * it's valid for all map elements regardless of the key
11701 		 * used in bpf_map_lookup()
11702 		 */
11703 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11704 		       range_within(rold, rcur) &&
11705 		       tnum_in(rold->var_off, rcur->var_off);
11706 	case PTR_TO_PACKET_META:
11707 	case PTR_TO_PACKET:
11708 		if (rcur->type != rold->type)
11709 			return false;
11710 		/* We must have at least as much range as the old ptr
11711 		 * did, so that any accesses which were safe before are
11712 		 * still safe.  This is true even if old range < old off,
11713 		 * since someone could have accessed through (ptr - k), or
11714 		 * even done ptr -= k in a register, to get a safe access.
11715 		 */
11716 		if (rold->range > rcur->range)
11717 			return false;
11718 		/* If the offsets don't match, we can't trust our alignment;
11719 		 * nor can we be sure that we won't fall out of range.
11720 		 */
11721 		if (rold->off != rcur->off)
11722 			return false;
11723 		/* id relations must be preserved */
11724 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11725 			return false;
11726 		/* new val must satisfy old val knowledge */
11727 		return range_within(rold, rcur) &&
11728 		       tnum_in(rold->var_off, rcur->var_off);
11729 	case PTR_TO_CTX:
11730 	case CONST_PTR_TO_MAP:
11731 	case PTR_TO_PACKET_END:
11732 	case PTR_TO_FLOW_KEYS:
11733 	case PTR_TO_SOCKET:
11734 	case PTR_TO_SOCK_COMMON:
11735 	case PTR_TO_TCP_SOCK:
11736 	case PTR_TO_XDP_SOCK:
11737 		/* Only valid matches are exact, which memcmp() above
11738 		 * would have accepted
11739 		 */
11740 	default:
11741 		/* Don't know what's going on, just say it's not safe */
11742 		return false;
11743 	}
11744 
11745 	/* Shouldn't get here; if we do, say it's not safe */
11746 	WARN_ON_ONCE(1);
11747 	return false;
11748 }
11749 
11750 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11751 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11752 {
11753 	int i, spi;
11754 
11755 	/* walk slots of the explored stack and ignore any additional
11756 	 * slots in the current stack, since explored(safe) state
11757 	 * didn't use them
11758 	 */
11759 	for (i = 0; i < old->allocated_stack; i++) {
11760 		spi = i / BPF_REG_SIZE;
11761 
11762 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11763 			i += BPF_REG_SIZE - 1;
11764 			/* explored state didn't use this */
11765 			continue;
11766 		}
11767 
11768 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11769 			continue;
11770 
11771 		/* explored stack has more populated slots than current stack
11772 		 * and these slots were used
11773 		 */
11774 		if (i >= cur->allocated_stack)
11775 			return false;
11776 
11777 		/* if old state was safe with misc data in the stack
11778 		 * it will be safe with zero-initialized stack.
11779 		 * The opposite is not true
11780 		 */
11781 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11782 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11783 			continue;
11784 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11785 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11786 			/* Ex: old explored (safe) state has STACK_SPILL in
11787 			 * this stack slot, but current has STACK_MISC ->
11788 			 * this verifier states are not equivalent,
11789 			 * return false to continue verification of this path
11790 			 */
11791 			return false;
11792 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11793 			continue;
11794 		if (!is_spilled_reg(&old->stack[spi]))
11795 			continue;
11796 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
11797 			     &cur->stack[spi].spilled_ptr, idmap))
11798 			/* when explored and current stack slot are both storing
11799 			 * spilled registers, check that stored pointers types
11800 			 * are the same as well.
11801 			 * Ex: explored safe path could have stored
11802 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11803 			 * but current path has stored:
11804 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11805 			 * such verifier states are not equivalent.
11806 			 * return false to continue verification of this path
11807 			 */
11808 			return false;
11809 	}
11810 	return true;
11811 }
11812 
11813 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11814 {
11815 	if (old->acquired_refs != cur->acquired_refs)
11816 		return false;
11817 	return !memcmp(old->refs, cur->refs,
11818 		       sizeof(*old->refs) * old->acquired_refs);
11819 }
11820 
11821 /* compare two verifier states
11822  *
11823  * all states stored in state_list are known to be valid, since
11824  * verifier reached 'bpf_exit' instruction through them
11825  *
11826  * this function is called when verifier exploring different branches of
11827  * execution popped from the state stack. If it sees an old state that has
11828  * more strict register state and more strict stack state then this execution
11829  * branch doesn't need to be explored further, since verifier already
11830  * concluded that more strict state leads to valid finish.
11831  *
11832  * Therefore two states are equivalent if register state is more conservative
11833  * and explored stack state is more conservative than the current one.
11834  * Example:
11835  *       explored                   current
11836  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11837  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11838  *
11839  * In other words if current stack state (one being explored) has more
11840  * valid slots than old one that already passed validation, it means
11841  * the verifier can stop exploring and conclude that current state is valid too
11842  *
11843  * Similarly with registers. If explored state has register type as invalid
11844  * whereas register type in current state is meaningful, it means that
11845  * the current state will reach 'bpf_exit' instruction safely
11846  */
11847 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11848 			      struct bpf_func_state *cur)
11849 {
11850 	int i;
11851 
11852 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11853 	for (i = 0; i < MAX_BPF_REG; i++)
11854 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11855 			     env->idmap_scratch))
11856 			return false;
11857 
11858 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11859 		return false;
11860 
11861 	if (!refsafe(old, cur))
11862 		return false;
11863 
11864 	return true;
11865 }
11866 
11867 static bool states_equal(struct bpf_verifier_env *env,
11868 			 struct bpf_verifier_state *old,
11869 			 struct bpf_verifier_state *cur)
11870 {
11871 	int i;
11872 
11873 	if (old->curframe != cur->curframe)
11874 		return false;
11875 
11876 	/* Verification state from speculative execution simulation
11877 	 * must never prune a non-speculative execution one.
11878 	 */
11879 	if (old->speculative && !cur->speculative)
11880 		return false;
11881 
11882 	if (old->active_spin_lock != cur->active_spin_lock)
11883 		return false;
11884 
11885 	/* for states to be equal callsites have to be the same
11886 	 * and all frame states need to be equivalent
11887 	 */
11888 	for (i = 0; i <= old->curframe; i++) {
11889 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11890 			return false;
11891 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11892 			return false;
11893 	}
11894 	return true;
11895 }
11896 
11897 /* Return 0 if no propagation happened. Return negative error code if error
11898  * happened. Otherwise, return the propagated bit.
11899  */
11900 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11901 				  struct bpf_reg_state *reg,
11902 				  struct bpf_reg_state *parent_reg)
11903 {
11904 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11905 	u8 flag = reg->live & REG_LIVE_READ;
11906 	int err;
11907 
11908 	/* When comes here, read flags of PARENT_REG or REG could be any of
11909 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11910 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11911 	 */
11912 	if (parent_flag == REG_LIVE_READ64 ||
11913 	    /* Or if there is no read flag from REG. */
11914 	    !flag ||
11915 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11916 	    parent_flag == flag)
11917 		return 0;
11918 
11919 	err = mark_reg_read(env, reg, parent_reg, flag);
11920 	if (err)
11921 		return err;
11922 
11923 	return flag;
11924 }
11925 
11926 /* A write screens off any subsequent reads; but write marks come from the
11927  * straight-line code between a state and its parent.  When we arrive at an
11928  * equivalent state (jump target or such) we didn't arrive by the straight-line
11929  * code, so read marks in the state must propagate to the parent regardless
11930  * of the state's write marks. That's what 'parent == state->parent' comparison
11931  * in mark_reg_read() is for.
11932  */
11933 static int propagate_liveness(struct bpf_verifier_env *env,
11934 			      const struct bpf_verifier_state *vstate,
11935 			      struct bpf_verifier_state *vparent)
11936 {
11937 	struct bpf_reg_state *state_reg, *parent_reg;
11938 	struct bpf_func_state *state, *parent;
11939 	int i, frame, err = 0;
11940 
11941 	if (vparent->curframe != vstate->curframe) {
11942 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11943 		     vparent->curframe, vstate->curframe);
11944 		return -EFAULT;
11945 	}
11946 	/* Propagate read liveness of registers... */
11947 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11948 	for (frame = 0; frame <= vstate->curframe; frame++) {
11949 		parent = vparent->frame[frame];
11950 		state = vstate->frame[frame];
11951 		parent_reg = parent->regs;
11952 		state_reg = state->regs;
11953 		/* We don't need to worry about FP liveness, it's read-only */
11954 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11955 			err = propagate_liveness_reg(env, &state_reg[i],
11956 						     &parent_reg[i]);
11957 			if (err < 0)
11958 				return err;
11959 			if (err == REG_LIVE_READ64)
11960 				mark_insn_zext(env, &parent_reg[i]);
11961 		}
11962 
11963 		/* Propagate stack slots. */
11964 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11965 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11966 			parent_reg = &parent->stack[i].spilled_ptr;
11967 			state_reg = &state->stack[i].spilled_ptr;
11968 			err = propagate_liveness_reg(env, state_reg,
11969 						     parent_reg);
11970 			if (err < 0)
11971 				return err;
11972 		}
11973 	}
11974 	return 0;
11975 }
11976 
11977 /* find precise scalars in the previous equivalent state and
11978  * propagate them into the current state
11979  */
11980 static int propagate_precision(struct bpf_verifier_env *env,
11981 			       const struct bpf_verifier_state *old)
11982 {
11983 	struct bpf_reg_state *state_reg;
11984 	struct bpf_func_state *state;
11985 	int i, err = 0, fr;
11986 
11987 	for (fr = old->curframe; fr >= 0; fr--) {
11988 		state = old->frame[fr];
11989 		state_reg = state->regs;
11990 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11991 			if (state_reg->type != SCALAR_VALUE ||
11992 			    !state_reg->precise)
11993 				continue;
11994 			if (env->log.level & BPF_LOG_LEVEL2)
11995 				verbose(env, "frame %d: propagating r%d\n", i, fr);
11996 			err = mark_chain_precision_frame(env, fr, i);
11997 			if (err < 0)
11998 				return err;
11999 		}
12000 
12001 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
12002 			if (!is_spilled_reg(&state->stack[i]))
12003 				continue;
12004 			state_reg = &state->stack[i].spilled_ptr;
12005 			if (state_reg->type != SCALAR_VALUE ||
12006 			    !state_reg->precise)
12007 				continue;
12008 			if (env->log.level & BPF_LOG_LEVEL2)
12009 				verbose(env, "frame %d: propagating fp%d\n",
12010 					(-i - 1) * BPF_REG_SIZE, fr);
12011 			err = mark_chain_precision_stack_frame(env, fr, i);
12012 			if (err < 0)
12013 				return err;
12014 		}
12015 	}
12016 	return 0;
12017 }
12018 
12019 static bool states_maybe_looping(struct bpf_verifier_state *old,
12020 				 struct bpf_verifier_state *cur)
12021 {
12022 	struct bpf_func_state *fold, *fcur;
12023 	int i, fr = cur->curframe;
12024 
12025 	if (old->curframe != fr)
12026 		return false;
12027 
12028 	fold = old->frame[fr];
12029 	fcur = cur->frame[fr];
12030 	for (i = 0; i < MAX_BPF_REG; i++)
12031 		if (memcmp(&fold->regs[i], &fcur->regs[i],
12032 			   offsetof(struct bpf_reg_state, parent)))
12033 			return false;
12034 	return true;
12035 }
12036 
12037 
12038 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
12039 {
12040 	struct bpf_verifier_state_list *new_sl;
12041 	struct bpf_verifier_state_list *sl, **pprev;
12042 	struct bpf_verifier_state *cur = env->cur_state, *new;
12043 	int i, j, err, states_cnt = 0;
12044 	bool add_new_state = env->test_state_freq ? true : false;
12045 
12046 	cur->last_insn_idx = env->prev_insn_idx;
12047 	if (!env->insn_aux_data[insn_idx].prune_point)
12048 		/* this 'insn_idx' instruction wasn't marked, so we will not
12049 		 * be doing state search here
12050 		 */
12051 		return 0;
12052 
12053 	/* bpf progs typically have pruning point every 4 instructions
12054 	 * http://vger.kernel.org/bpfconf2019.html#session-1
12055 	 * Do not add new state for future pruning if the verifier hasn't seen
12056 	 * at least 2 jumps and at least 8 instructions.
12057 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
12058 	 * In tests that amounts to up to 50% reduction into total verifier
12059 	 * memory consumption and 20% verifier time speedup.
12060 	 */
12061 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
12062 	    env->insn_processed - env->prev_insn_processed >= 8)
12063 		add_new_state = true;
12064 
12065 	pprev = explored_state(env, insn_idx);
12066 	sl = *pprev;
12067 
12068 	clean_live_states(env, insn_idx, cur);
12069 
12070 	while (sl) {
12071 		states_cnt++;
12072 		if (sl->state.insn_idx != insn_idx)
12073 			goto next;
12074 
12075 		if (sl->state.branches) {
12076 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
12077 
12078 			if (frame->in_async_callback_fn &&
12079 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
12080 				/* Different async_entry_cnt means that the verifier is
12081 				 * processing another entry into async callback.
12082 				 * Seeing the same state is not an indication of infinite
12083 				 * loop or infinite recursion.
12084 				 * But finding the same state doesn't mean that it's safe
12085 				 * to stop processing the current state. The previous state
12086 				 * hasn't yet reached bpf_exit, since state.branches > 0.
12087 				 * Checking in_async_callback_fn alone is not enough either.
12088 				 * Since the verifier still needs to catch infinite loops
12089 				 * inside async callbacks.
12090 				 */
12091 			} else if (states_maybe_looping(&sl->state, cur) &&
12092 				   states_equal(env, &sl->state, cur)) {
12093 				verbose_linfo(env, insn_idx, "; ");
12094 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12095 				return -EINVAL;
12096 			}
12097 			/* if the verifier is processing a loop, avoid adding new state
12098 			 * too often, since different loop iterations have distinct
12099 			 * states and may not help future pruning.
12100 			 * This threshold shouldn't be too low to make sure that
12101 			 * a loop with large bound will be rejected quickly.
12102 			 * The most abusive loop will be:
12103 			 * r1 += 1
12104 			 * if r1 < 1000000 goto pc-2
12105 			 * 1M insn_procssed limit / 100 == 10k peak states.
12106 			 * This threshold shouldn't be too high either, since states
12107 			 * at the end of the loop are likely to be useful in pruning.
12108 			 */
12109 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12110 			    env->insn_processed - env->prev_insn_processed < 100)
12111 				add_new_state = false;
12112 			goto miss;
12113 		}
12114 		if (states_equal(env, &sl->state, cur)) {
12115 			sl->hit_cnt++;
12116 			/* reached equivalent register/stack state,
12117 			 * prune the search.
12118 			 * Registers read by the continuation are read by us.
12119 			 * If we have any write marks in env->cur_state, they
12120 			 * will prevent corresponding reads in the continuation
12121 			 * from reaching our parent (an explored_state).  Our
12122 			 * own state will get the read marks recorded, but
12123 			 * they'll be immediately forgotten as we're pruning
12124 			 * this state and will pop a new one.
12125 			 */
12126 			err = propagate_liveness(env, &sl->state, cur);
12127 
12128 			/* if previous state reached the exit with precision and
12129 			 * current state is equivalent to it (except precsion marks)
12130 			 * the precision needs to be propagated back in
12131 			 * the current state.
12132 			 */
12133 			err = err ? : push_jmp_history(env, cur);
12134 			err = err ? : propagate_precision(env, &sl->state);
12135 			if (err)
12136 				return err;
12137 			return 1;
12138 		}
12139 miss:
12140 		/* when new state is not going to be added do not increase miss count.
12141 		 * Otherwise several loop iterations will remove the state
12142 		 * recorded earlier. The goal of these heuristics is to have
12143 		 * states from some iterations of the loop (some in the beginning
12144 		 * and some at the end) to help pruning.
12145 		 */
12146 		if (add_new_state)
12147 			sl->miss_cnt++;
12148 		/* heuristic to determine whether this state is beneficial
12149 		 * to keep checking from state equivalence point of view.
12150 		 * Higher numbers increase max_states_per_insn and verification time,
12151 		 * but do not meaningfully decrease insn_processed.
12152 		 */
12153 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12154 			/* the state is unlikely to be useful. Remove it to
12155 			 * speed up verification
12156 			 */
12157 			*pprev = sl->next;
12158 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12159 				u32 br = sl->state.branches;
12160 
12161 				WARN_ONCE(br,
12162 					  "BUG live_done but branches_to_explore %d\n",
12163 					  br);
12164 				free_verifier_state(&sl->state, false);
12165 				kfree(sl);
12166 				env->peak_states--;
12167 			} else {
12168 				/* cannot free this state, since parentage chain may
12169 				 * walk it later. Add it for free_list instead to
12170 				 * be freed at the end of verification
12171 				 */
12172 				sl->next = env->free_list;
12173 				env->free_list = sl;
12174 			}
12175 			sl = *pprev;
12176 			continue;
12177 		}
12178 next:
12179 		pprev = &sl->next;
12180 		sl = *pprev;
12181 	}
12182 
12183 	if (env->max_states_per_insn < states_cnt)
12184 		env->max_states_per_insn = states_cnt;
12185 
12186 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12187 		return push_jmp_history(env, cur);
12188 
12189 	if (!add_new_state)
12190 		return push_jmp_history(env, cur);
12191 
12192 	/* There were no equivalent states, remember the current one.
12193 	 * Technically the current state is not proven to be safe yet,
12194 	 * but it will either reach outer most bpf_exit (which means it's safe)
12195 	 * or it will be rejected. When there are no loops the verifier won't be
12196 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12197 	 * again on the way to bpf_exit.
12198 	 * When looping the sl->state.branches will be > 0 and this state
12199 	 * will not be considered for equivalence until branches == 0.
12200 	 */
12201 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12202 	if (!new_sl)
12203 		return -ENOMEM;
12204 	env->total_states++;
12205 	env->peak_states++;
12206 	env->prev_jmps_processed = env->jmps_processed;
12207 	env->prev_insn_processed = env->insn_processed;
12208 
12209 	/* forget precise markings we inherited, see __mark_chain_precision */
12210 	if (env->bpf_capable)
12211 		mark_all_scalars_imprecise(env, cur);
12212 
12213 	/* add new state to the head of linked list */
12214 	new = &new_sl->state;
12215 	err = copy_verifier_state(new, cur);
12216 	if (err) {
12217 		free_verifier_state(new, false);
12218 		kfree(new_sl);
12219 		return err;
12220 	}
12221 	new->insn_idx = insn_idx;
12222 	WARN_ONCE(new->branches != 1,
12223 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12224 
12225 	cur->parent = new;
12226 	cur->first_insn_idx = insn_idx;
12227 	clear_jmp_history(cur);
12228 	new_sl->next = *explored_state(env, insn_idx);
12229 	*explored_state(env, insn_idx) = new_sl;
12230 	/* connect new state to parentage chain. Current frame needs all
12231 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
12232 	 * to the stack implicitly by JITs) so in callers' frames connect just
12233 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12234 	 * the state of the call instruction (with WRITTEN set), and r0 comes
12235 	 * from callee with its full parentage chain, anyway.
12236 	 */
12237 	/* clear write marks in current state: the writes we did are not writes
12238 	 * our child did, so they don't screen off its reads from us.
12239 	 * (There are no read marks in current state, because reads always mark
12240 	 * their parent and current state never has children yet.  Only
12241 	 * explored_states can get read marks.)
12242 	 */
12243 	for (j = 0; j <= cur->curframe; j++) {
12244 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12245 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12246 		for (i = 0; i < BPF_REG_FP; i++)
12247 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12248 	}
12249 
12250 	/* all stack frames are accessible from callee, clear them all */
12251 	for (j = 0; j <= cur->curframe; j++) {
12252 		struct bpf_func_state *frame = cur->frame[j];
12253 		struct bpf_func_state *newframe = new->frame[j];
12254 
12255 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12256 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12257 			frame->stack[i].spilled_ptr.parent =
12258 						&newframe->stack[i].spilled_ptr;
12259 		}
12260 	}
12261 	return 0;
12262 }
12263 
12264 /* Return true if it's OK to have the same insn return a different type. */
12265 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12266 {
12267 	switch (base_type(type)) {
12268 	case PTR_TO_CTX:
12269 	case PTR_TO_SOCKET:
12270 	case PTR_TO_SOCK_COMMON:
12271 	case PTR_TO_TCP_SOCK:
12272 	case PTR_TO_XDP_SOCK:
12273 	case PTR_TO_BTF_ID:
12274 		return false;
12275 	default:
12276 		return true;
12277 	}
12278 }
12279 
12280 /* If an instruction was previously used with particular pointer types, then we
12281  * need to be careful to avoid cases such as the below, where it may be ok
12282  * for one branch accessing the pointer, but not ok for the other branch:
12283  *
12284  * R1 = sock_ptr
12285  * goto X;
12286  * ...
12287  * R1 = some_other_valid_ptr;
12288  * goto X;
12289  * ...
12290  * R2 = *(u32 *)(R1 + 0);
12291  */
12292 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12293 {
12294 	return src != prev && (!reg_type_mismatch_ok(src) ||
12295 			       !reg_type_mismatch_ok(prev));
12296 }
12297 
12298 static int do_check(struct bpf_verifier_env *env)
12299 {
12300 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12301 	struct bpf_verifier_state *state = env->cur_state;
12302 	struct bpf_insn *insns = env->prog->insnsi;
12303 	struct bpf_reg_state *regs;
12304 	int insn_cnt = env->prog->len;
12305 	bool do_print_state = false;
12306 	int prev_insn_idx = -1;
12307 
12308 	for (;;) {
12309 		struct bpf_insn *insn;
12310 		u8 class;
12311 		int err;
12312 
12313 		env->prev_insn_idx = prev_insn_idx;
12314 		if (env->insn_idx >= insn_cnt) {
12315 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
12316 				env->insn_idx, insn_cnt);
12317 			return -EFAULT;
12318 		}
12319 
12320 		insn = &insns[env->insn_idx];
12321 		class = BPF_CLASS(insn->code);
12322 
12323 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12324 			verbose(env,
12325 				"BPF program is too large. Processed %d insn\n",
12326 				env->insn_processed);
12327 			return -E2BIG;
12328 		}
12329 
12330 		err = is_state_visited(env, env->insn_idx);
12331 		if (err < 0)
12332 			return err;
12333 		if (err == 1) {
12334 			/* found equivalent state, can prune the search */
12335 			if (env->log.level & BPF_LOG_LEVEL) {
12336 				if (do_print_state)
12337 					verbose(env, "\nfrom %d to %d%s: safe\n",
12338 						env->prev_insn_idx, env->insn_idx,
12339 						env->cur_state->speculative ?
12340 						" (speculative execution)" : "");
12341 				else
12342 					verbose(env, "%d: safe\n", env->insn_idx);
12343 			}
12344 			goto process_bpf_exit;
12345 		}
12346 
12347 		if (signal_pending(current))
12348 			return -EAGAIN;
12349 
12350 		if (need_resched())
12351 			cond_resched();
12352 
12353 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12354 			verbose(env, "\nfrom %d to %d%s:",
12355 				env->prev_insn_idx, env->insn_idx,
12356 				env->cur_state->speculative ?
12357 				" (speculative execution)" : "");
12358 			print_verifier_state(env, state->frame[state->curframe], true);
12359 			do_print_state = false;
12360 		}
12361 
12362 		if (env->log.level & BPF_LOG_LEVEL) {
12363 			const struct bpf_insn_cbs cbs = {
12364 				.cb_call	= disasm_kfunc_name,
12365 				.cb_print	= verbose,
12366 				.private_data	= env,
12367 			};
12368 
12369 			if (verifier_state_scratched(env))
12370 				print_insn_state(env, state->frame[state->curframe]);
12371 
12372 			verbose_linfo(env, env->insn_idx, "; ");
12373 			env->prev_log_len = env->log.len_used;
12374 			verbose(env, "%d: ", env->insn_idx);
12375 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12376 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12377 			env->prev_log_len = env->log.len_used;
12378 		}
12379 
12380 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
12381 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12382 							   env->prev_insn_idx);
12383 			if (err)
12384 				return err;
12385 		}
12386 
12387 		regs = cur_regs(env);
12388 		sanitize_mark_insn_seen(env);
12389 		prev_insn_idx = env->insn_idx;
12390 
12391 		if (class == BPF_ALU || class == BPF_ALU64) {
12392 			err = check_alu_op(env, insn);
12393 			if (err)
12394 				return err;
12395 
12396 		} else if (class == BPF_LDX) {
12397 			enum bpf_reg_type *prev_src_type, src_reg_type;
12398 
12399 			/* check for reserved fields is already done */
12400 
12401 			/* check src operand */
12402 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12403 			if (err)
12404 				return err;
12405 
12406 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12407 			if (err)
12408 				return err;
12409 
12410 			src_reg_type = regs[insn->src_reg].type;
12411 
12412 			/* check that memory (src_reg + off) is readable,
12413 			 * the state of dst_reg will be updated by this func
12414 			 */
12415 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
12416 					       insn->off, BPF_SIZE(insn->code),
12417 					       BPF_READ, insn->dst_reg, false);
12418 			if (err)
12419 				return err;
12420 
12421 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12422 
12423 			if (*prev_src_type == NOT_INIT) {
12424 				/* saw a valid insn
12425 				 * dst_reg = *(u32 *)(src_reg + off)
12426 				 * save type to validate intersecting paths
12427 				 */
12428 				*prev_src_type = src_reg_type;
12429 
12430 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12431 				/* ABuser program is trying to use the same insn
12432 				 * dst_reg = *(u32*) (src_reg + off)
12433 				 * with different pointer types:
12434 				 * src_reg == ctx in one branch and
12435 				 * src_reg == stack|map in some other branch.
12436 				 * Reject it.
12437 				 */
12438 				verbose(env, "same insn cannot be used with different pointers\n");
12439 				return -EINVAL;
12440 			}
12441 
12442 		} else if (class == BPF_STX) {
12443 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
12444 
12445 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12446 				err = check_atomic(env, env->insn_idx, insn);
12447 				if (err)
12448 					return err;
12449 				env->insn_idx++;
12450 				continue;
12451 			}
12452 
12453 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12454 				verbose(env, "BPF_STX uses reserved fields\n");
12455 				return -EINVAL;
12456 			}
12457 
12458 			/* check src1 operand */
12459 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12460 			if (err)
12461 				return err;
12462 			/* check src2 operand */
12463 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12464 			if (err)
12465 				return err;
12466 
12467 			dst_reg_type = regs[insn->dst_reg].type;
12468 
12469 			/* check that memory (dst_reg + off) is writeable */
12470 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12471 					       insn->off, BPF_SIZE(insn->code),
12472 					       BPF_WRITE, insn->src_reg, false);
12473 			if (err)
12474 				return err;
12475 
12476 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12477 
12478 			if (*prev_dst_type == NOT_INIT) {
12479 				*prev_dst_type = dst_reg_type;
12480 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12481 				verbose(env, "same insn cannot be used with different pointers\n");
12482 				return -EINVAL;
12483 			}
12484 
12485 		} else if (class == BPF_ST) {
12486 			if (BPF_MODE(insn->code) != BPF_MEM ||
12487 			    insn->src_reg != BPF_REG_0) {
12488 				verbose(env, "BPF_ST uses reserved fields\n");
12489 				return -EINVAL;
12490 			}
12491 			/* check src operand */
12492 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12493 			if (err)
12494 				return err;
12495 
12496 			if (is_ctx_reg(env, insn->dst_reg)) {
12497 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12498 					insn->dst_reg,
12499 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12500 				return -EACCES;
12501 			}
12502 
12503 			/* check that memory (dst_reg + off) is writeable */
12504 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12505 					       insn->off, BPF_SIZE(insn->code),
12506 					       BPF_WRITE, -1, false);
12507 			if (err)
12508 				return err;
12509 
12510 		} else if (class == BPF_JMP || class == BPF_JMP32) {
12511 			u8 opcode = BPF_OP(insn->code);
12512 
12513 			env->jmps_processed++;
12514 			if (opcode == BPF_CALL) {
12515 				if (BPF_SRC(insn->code) != BPF_K ||
12516 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12517 				     && insn->off != 0) ||
12518 				    (insn->src_reg != BPF_REG_0 &&
12519 				     insn->src_reg != BPF_PSEUDO_CALL &&
12520 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12521 				    insn->dst_reg != BPF_REG_0 ||
12522 				    class == BPF_JMP32) {
12523 					verbose(env, "BPF_CALL uses reserved fields\n");
12524 					return -EINVAL;
12525 				}
12526 
12527 				if (env->cur_state->active_spin_lock &&
12528 				    (insn->src_reg == BPF_PSEUDO_CALL ||
12529 				     insn->imm != BPF_FUNC_spin_unlock)) {
12530 					verbose(env, "function calls are not allowed while holding a lock\n");
12531 					return -EINVAL;
12532 				}
12533 				if (insn->src_reg == BPF_PSEUDO_CALL)
12534 					err = check_func_call(env, insn, &env->insn_idx);
12535 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12536 					err = check_kfunc_call(env, insn, &env->insn_idx);
12537 				else
12538 					err = check_helper_call(env, insn, &env->insn_idx);
12539 				if (err)
12540 					return err;
12541 			} else if (opcode == BPF_JA) {
12542 				if (BPF_SRC(insn->code) != BPF_K ||
12543 				    insn->imm != 0 ||
12544 				    insn->src_reg != BPF_REG_0 ||
12545 				    insn->dst_reg != BPF_REG_0 ||
12546 				    class == BPF_JMP32) {
12547 					verbose(env, "BPF_JA uses reserved fields\n");
12548 					return -EINVAL;
12549 				}
12550 
12551 				env->insn_idx += insn->off + 1;
12552 				continue;
12553 
12554 			} else if (opcode == BPF_EXIT) {
12555 				if (BPF_SRC(insn->code) != BPF_K ||
12556 				    insn->imm != 0 ||
12557 				    insn->src_reg != BPF_REG_0 ||
12558 				    insn->dst_reg != BPF_REG_0 ||
12559 				    class == BPF_JMP32) {
12560 					verbose(env, "BPF_EXIT uses reserved fields\n");
12561 					return -EINVAL;
12562 				}
12563 
12564 				if (env->cur_state->active_spin_lock) {
12565 					verbose(env, "bpf_spin_unlock is missing\n");
12566 					return -EINVAL;
12567 				}
12568 
12569 				/* We must do check_reference_leak here before
12570 				 * prepare_func_exit to handle the case when
12571 				 * state->curframe > 0, it may be a callback
12572 				 * function, for which reference_state must
12573 				 * match caller reference state when it exits.
12574 				 */
12575 				err = check_reference_leak(env);
12576 				if (err)
12577 					return err;
12578 
12579 				if (state->curframe) {
12580 					/* exit from nested function */
12581 					err = prepare_func_exit(env, &env->insn_idx);
12582 					if (err)
12583 						return err;
12584 					do_print_state = true;
12585 					continue;
12586 				}
12587 
12588 				err = check_return_code(env);
12589 				if (err)
12590 					return err;
12591 process_bpf_exit:
12592 				mark_verifier_state_scratched(env);
12593 				update_branch_counts(env, env->cur_state);
12594 				err = pop_stack(env, &prev_insn_idx,
12595 						&env->insn_idx, pop_log);
12596 				if (err < 0) {
12597 					if (err != -ENOENT)
12598 						return err;
12599 					break;
12600 				} else {
12601 					do_print_state = true;
12602 					continue;
12603 				}
12604 			} else {
12605 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
12606 				if (err)
12607 					return err;
12608 			}
12609 		} else if (class == BPF_LD) {
12610 			u8 mode = BPF_MODE(insn->code);
12611 
12612 			if (mode == BPF_ABS || mode == BPF_IND) {
12613 				err = check_ld_abs(env, insn);
12614 				if (err)
12615 					return err;
12616 
12617 			} else if (mode == BPF_IMM) {
12618 				err = check_ld_imm(env, insn);
12619 				if (err)
12620 					return err;
12621 
12622 				env->insn_idx++;
12623 				sanitize_mark_insn_seen(env);
12624 			} else {
12625 				verbose(env, "invalid BPF_LD mode\n");
12626 				return -EINVAL;
12627 			}
12628 		} else {
12629 			verbose(env, "unknown insn class %d\n", class);
12630 			return -EINVAL;
12631 		}
12632 
12633 		env->insn_idx++;
12634 	}
12635 
12636 	return 0;
12637 }
12638 
12639 static int find_btf_percpu_datasec(struct btf *btf)
12640 {
12641 	const struct btf_type *t;
12642 	const char *tname;
12643 	int i, n;
12644 
12645 	/*
12646 	 * Both vmlinux and module each have their own ".data..percpu"
12647 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12648 	 * types to look at only module's own BTF types.
12649 	 */
12650 	n = btf_nr_types(btf);
12651 	if (btf_is_module(btf))
12652 		i = btf_nr_types(btf_vmlinux);
12653 	else
12654 		i = 1;
12655 
12656 	for(; i < n; i++) {
12657 		t = btf_type_by_id(btf, i);
12658 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12659 			continue;
12660 
12661 		tname = btf_name_by_offset(btf, t->name_off);
12662 		if (!strcmp(tname, ".data..percpu"))
12663 			return i;
12664 	}
12665 
12666 	return -ENOENT;
12667 }
12668 
12669 /* replace pseudo btf_id with kernel symbol address */
12670 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12671 			       struct bpf_insn *insn,
12672 			       struct bpf_insn_aux_data *aux)
12673 {
12674 	const struct btf_var_secinfo *vsi;
12675 	const struct btf_type *datasec;
12676 	struct btf_mod_pair *btf_mod;
12677 	const struct btf_type *t;
12678 	const char *sym_name;
12679 	bool percpu = false;
12680 	u32 type, id = insn->imm;
12681 	struct btf *btf;
12682 	s32 datasec_id;
12683 	u64 addr;
12684 	int i, btf_fd, err;
12685 
12686 	btf_fd = insn[1].imm;
12687 	if (btf_fd) {
12688 		btf = btf_get_by_fd(btf_fd);
12689 		if (IS_ERR(btf)) {
12690 			verbose(env, "invalid module BTF object FD specified.\n");
12691 			return -EINVAL;
12692 		}
12693 	} else {
12694 		if (!btf_vmlinux) {
12695 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12696 			return -EINVAL;
12697 		}
12698 		btf = btf_vmlinux;
12699 		btf_get(btf);
12700 	}
12701 
12702 	t = btf_type_by_id(btf, id);
12703 	if (!t) {
12704 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12705 		err = -ENOENT;
12706 		goto err_put;
12707 	}
12708 
12709 	if (!btf_type_is_var(t)) {
12710 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12711 		err = -EINVAL;
12712 		goto err_put;
12713 	}
12714 
12715 	sym_name = btf_name_by_offset(btf, t->name_off);
12716 	addr = kallsyms_lookup_name(sym_name);
12717 	if (!addr) {
12718 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12719 			sym_name);
12720 		err = -ENOENT;
12721 		goto err_put;
12722 	}
12723 
12724 	datasec_id = find_btf_percpu_datasec(btf);
12725 	if (datasec_id > 0) {
12726 		datasec = btf_type_by_id(btf, datasec_id);
12727 		for_each_vsi(i, datasec, vsi) {
12728 			if (vsi->type == id) {
12729 				percpu = true;
12730 				break;
12731 			}
12732 		}
12733 	}
12734 
12735 	insn[0].imm = (u32)addr;
12736 	insn[1].imm = addr >> 32;
12737 
12738 	type = t->type;
12739 	t = btf_type_skip_modifiers(btf, type, NULL);
12740 	if (percpu) {
12741 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12742 		aux->btf_var.btf = btf;
12743 		aux->btf_var.btf_id = type;
12744 	} else if (!btf_type_is_struct(t)) {
12745 		const struct btf_type *ret;
12746 		const char *tname;
12747 		u32 tsize;
12748 
12749 		/* resolve the type size of ksym. */
12750 		ret = btf_resolve_size(btf, t, &tsize);
12751 		if (IS_ERR(ret)) {
12752 			tname = btf_name_by_offset(btf, t->name_off);
12753 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12754 				tname, PTR_ERR(ret));
12755 			err = -EINVAL;
12756 			goto err_put;
12757 		}
12758 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12759 		aux->btf_var.mem_size = tsize;
12760 	} else {
12761 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
12762 		aux->btf_var.btf = btf;
12763 		aux->btf_var.btf_id = type;
12764 	}
12765 
12766 	/* check whether we recorded this BTF (and maybe module) already */
12767 	for (i = 0; i < env->used_btf_cnt; i++) {
12768 		if (env->used_btfs[i].btf == btf) {
12769 			btf_put(btf);
12770 			return 0;
12771 		}
12772 	}
12773 
12774 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
12775 		err = -E2BIG;
12776 		goto err_put;
12777 	}
12778 
12779 	btf_mod = &env->used_btfs[env->used_btf_cnt];
12780 	btf_mod->btf = btf;
12781 	btf_mod->module = NULL;
12782 
12783 	/* if we reference variables from kernel module, bump its refcount */
12784 	if (btf_is_module(btf)) {
12785 		btf_mod->module = btf_try_get_module(btf);
12786 		if (!btf_mod->module) {
12787 			err = -ENXIO;
12788 			goto err_put;
12789 		}
12790 	}
12791 
12792 	env->used_btf_cnt++;
12793 
12794 	return 0;
12795 err_put:
12796 	btf_put(btf);
12797 	return err;
12798 }
12799 
12800 static bool is_tracing_prog_type(enum bpf_prog_type type)
12801 {
12802 	switch (type) {
12803 	case BPF_PROG_TYPE_KPROBE:
12804 	case BPF_PROG_TYPE_TRACEPOINT:
12805 	case BPF_PROG_TYPE_PERF_EVENT:
12806 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12807 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12808 		return true;
12809 	default:
12810 		return false;
12811 	}
12812 }
12813 
12814 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12815 					struct bpf_map *map,
12816 					struct bpf_prog *prog)
12817 
12818 {
12819 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12820 
12821 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
12822 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12823 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12824 			return -EINVAL;
12825 		}
12826 
12827 		if (is_tracing_prog_type(prog_type)) {
12828 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12829 			return -EINVAL;
12830 		}
12831 
12832 		if (prog->aux->sleepable) {
12833 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12834 			return -EINVAL;
12835 		}
12836 	}
12837 
12838 	if (btf_record_has_field(map->record, BPF_TIMER)) {
12839 		if (is_tracing_prog_type(prog_type)) {
12840 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12841 			return -EINVAL;
12842 		}
12843 	}
12844 
12845 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12846 	    !bpf_offload_prog_map_match(prog, map)) {
12847 		verbose(env, "offload device mismatch between prog and map\n");
12848 		return -EINVAL;
12849 	}
12850 
12851 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12852 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12853 		return -EINVAL;
12854 	}
12855 
12856 	if (prog->aux->sleepable)
12857 		switch (map->map_type) {
12858 		case BPF_MAP_TYPE_HASH:
12859 		case BPF_MAP_TYPE_LRU_HASH:
12860 		case BPF_MAP_TYPE_ARRAY:
12861 		case BPF_MAP_TYPE_PERCPU_HASH:
12862 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12863 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12864 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12865 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12866 		case BPF_MAP_TYPE_RINGBUF:
12867 		case BPF_MAP_TYPE_USER_RINGBUF:
12868 		case BPF_MAP_TYPE_INODE_STORAGE:
12869 		case BPF_MAP_TYPE_SK_STORAGE:
12870 		case BPF_MAP_TYPE_TASK_STORAGE:
12871 			break;
12872 		default:
12873 			verbose(env,
12874 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12875 			return -EINVAL;
12876 		}
12877 
12878 	return 0;
12879 }
12880 
12881 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12882 {
12883 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12884 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12885 }
12886 
12887 /* find and rewrite pseudo imm in ld_imm64 instructions:
12888  *
12889  * 1. if it accesses map FD, replace it with actual map pointer.
12890  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12891  *
12892  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12893  */
12894 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12895 {
12896 	struct bpf_insn *insn = env->prog->insnsi;
12897 	int insn_cnt = env->prog->len;
12898 	int i, j, err;
12899 
12900 	err = bpf_prog_calc_tag(env->prog);
12901 	if (err)
12902 		return err;
12903 
12904 	for (i = 0; i < insn_cnt; i++, insn++) {
12905 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12906 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12907 			verbose(env, "BPF_LDX uses reserved fields\n");
12908 			return -EINVAL;
12909 		}
12910 
12911 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12912 			struct bpf_insn_aux_data *aux;
12913 			struct bpf_map *map;
12914 			struct fd f;
12915 			u64 addr;
12916 			u32 fd;
12917 
12918 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12919 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12920 			    insn[1].off != 0) {
12921 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12922 				return -EINVAL;
12923 			}
12924 
12925 			if (insn[0].src_reg == 0)
12926 				/* valid generic load 64-bit imm */
12927 				goto next_insn;
12928 
12929 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12930 				aux = &env->insn_aux_data[i];
12931 				err = check_pseudo_btf_id(env, insn, aux);
12932 				if (err)
12933 					return err;
12934 				goto next_insn;
12935 			}
12936 
12937 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12938 				aux = &env->insn_aux_data[i];
12939 				aux->ptr_type = PTR_TO_FUNC;
12940 				goto next_insn;
12941 			}
12942 
12943 			/* In final convert_pseudo_ld_imm64() step, this is
12944 			 * converted into regular 64-bit imm load insn.
12945 			 */
12946 			switch (insn[0].src_reg) {
12947 			case BPF_PSEUDO_MAP_VALUE:
12948 			case BPF_PSEUDO_MAP_IDX_VALUE:
12949 				break;
12950 			case BPF_PSEUDO_MAP_FD:
12951 			case BPF_PSEUDO_MAP_IDX:
12952 				if (insn[1].imm == 0)
12953 					break;
12954 				fallthrough;
12955 			default:
12956 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12957 				return -EINVAL;
12958 			}
12959 
12960 			switch (insn[0].src_reg) {
12961 			case BPF_PSEUDO_MAP_IDX_VALUE:
12962 			case BPF_PSEUDO_MAP_IDX:
12963 				if (bpfptr_is_null(env->fd_array)) {
12964 					verbose(env, "fd_idx without fd_array is invalid\n");
12965 					return -EPROTO;
12966 				}
12967 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12968 							    insn[0].imm * sizeof(fd),
12969 							    sizeof(fd)))
12970 					return -EFAULT;
12971 				break;
12972 			default:
12973 				fd = insn[0].imm;
12974 				break;
12975 			}
12976 
12977 			f = fdget(fd);
12978 			map = __bpf_map_get(f);
12979 			if (IS_ERR(map)) {
12980 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12981 					insn[0].imm);
12982 				return PTR_ERR(map);
12983 			}
12984 
12985 			err = check_map_prog_compatibility(env, map, env->prog);
12986 			if (err) {
12987 				fdput(f);
12988 				return err;
12989 			}
12990 
12991 			aux = &env->insn_aux_data[i];
12992 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12993 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12994 				addr = (unsigned long)map;
12995 			} else {
12996 				u32 off = insn[1].imm;
12997 
12998 				if (off >= BPF_MAX_VAR_OFF) {
12999 					verbose(env, "direct value offset of %u is not allowed\n", off);
13000 					fdput(f);
13001 					return -EINVAL;
13002 				}
13003 
13004 				if (!map->ops->map_direct_value_addr) {
13005 					verbose(env, "no direct value access support for this map type\n");
13006 					fdput(f);
13007 					return -EINVAL;
13008 				}
13009 
13010 				err = map->ops->map_direct_value_addr(map, &addr, off);
13011 				if (err) {
13012 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
13013 						map->value_size, off);
13014 					fdput(f);
13015 					return err;
13016 				}
13017 
13018 				aux->map_off = off;
13019 				addr += off;
13020 			}
13021 
13022 			insn[0].imm = (u32)addr;
13023 			insn[1].imm = addr >> 32;
13024 
13025 			/* check whether we recorded this map already */
13026 			for (j = 0; j < env->used_map_cnt; j++) {
13027 				if (env->used_maps[j] == map) {
13028 					aux->map_index = j;
13029 					fdput(f);
13030 					goto next_insn;
13031 				}
13032 			}
13033 
13034 			if (env->used_map_cnt >= MAX_USED_MAPS) {
13035 				fdput(f);
13036 				return -E2BIG;
13037 			}
13038 
13039 			/* hold the map. If the program is rejected by verifier,
13040 			 * the map will be released by release_maps() or it
13041 			 * will be used by the valid program until it's unloaded
13042 			 * and all maps are released in free_used_maps()
13043 			 */
13044 			bpf_map_inc(map);
13045 
13046 			aux->map_index = env->used_map_cnt;
13047 			env->used_maps[env->used_map_cnt++] = map;
13048 
13049 			if (bpf_map_is_cgroup_storage(map) &&
13050 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
13051 				verbose(env, "only one cgroup storage of each type is allowed\n");
13052 				fdput(f);
13053 				return -EBUSY;
13054 			}
13055 
13056 			fdput(f);
13057 next_insn:
13058 			insn++;
13059 			i++;
13060 			continue;
13061 		}
13062 
13063 		/* Basic sanity check before we invest more work here. */
13064 		if (!bpf_opcode_in_insntable(insn->code)) {
13065 			verbose(env, "unknown opcode %02x\n", insn->code);
13066 			return -EINVAL;
13067 		}
13068 	}
13069 
13070 	/* now all pseudo BPF_LD_IMM64 instructions load valid
13071 	 * 'struct bpf_map *' into a register instead of user map_fd.
13072 	 * These pointers will be used later by verifier to validate map access.
13073 	 */
13074 	return 0;
13075 }
13076 
13077 /* drop refcnt of maps used by the rejected program */
13078 static void release_maps(struct bpf_verifier_env *env)
13079 {
13080 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
13081 			     env->used_map_cnt);
13082 }
13083 
13084 /* drop refcnt of maps used by the rejected program */
13085 static void release_btfs(struct bpf_verifier_env *env)
13086 {
13087 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13088 			     env->used_btf_cnt);
13089 }
13090 
13091 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13092 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13093 {
13094 	struct bpf_insn *insn = env->prog->insnsi;
13095 	int insn_cnt = env->prog->len;
13096 	int i;
13097 
13098 	for (i = 0; i < insn_cnt; i++, insn++) {
13099 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13100 			continue;
13101 		if (insn->src_reg == BPF_PSEUDO_FUNC)
13102 			continue;
13103 		insn->src_reg = 0;
13104 	}
13105 }
13106 
13107 /* single env->prog->insni[off] instruction was replaced with the range
13108  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
13109  * [0, off) and [off, end) to new locations, so the patched range stays zero
13110  */
13111 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13112 				 struct bpf_insn_aux_data *new_data,
13113 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
13114 {
13115 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13116 	struct bpf_insn *insn = new_prog->insnsi;
13117 	u32 old_seen = old_data[off].seen;
13118 	u32 prog_len;
13119 	int i;
13120 
13121 	/* aux info at OFF always needs adjustment, no matter fast path
13122 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13123 	 * original insn at old prog.
13124 	 */
13125 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13126 
13127 	if (cnt == 1)
13128 		return;
13129 	prog_len = new_prog->len;
13130 
13131 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13132 	memcpy(new_data + off + cnt - 1, old_data + off,
13133 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13134 	for (i = off; i < off + cnt - 1; i++) {
13135 		/* Expand insni[off]'s seen count to the patched range. */
13136 		new_data[i].seen = old_seen;
13137 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
13138 	}
13139 	env->insn_aux_data = new_data;
13140 	vfree(old_data);
13141 }
13142 
13143 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13144 {
13145 	int i;
13146 
13147 	if (len == 1)
13148 		return;
13149 	/* NOTE: fake 'exit' subprog should be updated as well. */
13150 	for (i = 0; i <= env->subprog_cnt; i++) {
13151 		if (env->subprog_info[i].start <= off)
13152 			continue;
13153 		env->subprog_info[i].start += len - 1;
13154 	}
13155 }
13156 
13157 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13158 {
13159 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13160 	int i, sz = prog->aux->size_poke_tab;
13161 	struct bpf_jit_poke_descriptor *desc;
13162 
13163 	for (i = 0; i < sz; i++) {
13164 		desc = &tab[i];
13165 		if (desc->insn_idx <= off)
13166 			continue;
13167 		desc->insn_idx += len - 1;
13168 	}
13169 }
13170 
13171 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13172 					    const struct bpf_insn *patch, u32 len)
13173 {
13174 	struct bpf_prog *new_prog;
13175 	struct bpf_insn_aux_data *new_data = NULL;
13176 
13177 	if (len > 1) {
13178 		new_data = vzalloc(array_size(env->prog->len + len - 1,
13179 					      sizeof(struct bpf_insn_aux_data)));
13180 		if (!new_data)
13181 			return NULL;
13182 	}
13183 
13184 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13185 	if (IS_ERR(new_prog)) {
13186 		if (PTR_ERR(new_prog) == -ERANGE)
13187 			verbose(env,
13188 				"insn %d cannot be patched due to 16-bit range\n",
13189 				env->insn_aux_data[off].orig_idx);
13190 		vfree(new_data);
13191 		return NULL;
13192 	}
13193 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
13194 	adjust_subprog_starts(env, off, len);
13195 	adjust_poke_descs(new_prog, off, len);
13196 	return new_prog;
13197 }
13198 
13199 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13200 					      u32 off, u32 cnt)
13201 {
13202 	int i, j;
13203 
13204 	/* find first prog starting at or after off (first to remove) */
13205 	for (i = 0; i < env->subprog_cnt; i++)
13206 		if (env->subprog_info[i].start >= off)
13207 			break;
13208 	/* find first prog starting at or after off + cnt (first to stay) */
13209 	for (j = i; j < env->subprog_cnt; j++)
13210 		if (env->subprog_info[j].start >= off + cnt)
13211 			break;
13212 	/* if j doesn't start exactly at off + cnt, we are just removing
13213 	 * the front of previous prog
13214 	 */
13215 	if (env->subprog_info[j].start != off + cnt)
13216 		j--;
13217 
13218 	if (j > i) {
13219 		struct bpf_prog_aux *aux = env->prog->aux;
13220 		int move;
13221 
13222 		/* move fake 'exit' subprog as well */
13223 		move = env->subprog_cnt + 1 - j;
13224 
13225 		memmove(env->subprog_info + i,
13226 			env->subprog_info + j,
13227 			sizeof(*env->subprog_info) * move);
13228 		env->subprog_cnt -= j - i;
13229 
13230 		/* remove func_info */
13231 		if (aux->func_info) {
13232 			move = aux->func_info_cnt - j;
13233 
13234 			memmove(aux->func_info + i,
13235 				aux->func_info + j,
13236 				sizeof(*aux->func_info) * move);
13237 			aux->func_info_cnt -= j - i;
13238 			/* func_info->insn_off is set after all code rewrites,
13239 			 * in adjust_btf_func() - no need to adjust
13240 			 */
13241 		}
13242 	} else {
13243 		/* convert i from "first prog to remove" to "first to adjust" */
13244 		if (env->subprog_info[i].start == off)
13245 			i++;
13246 	}
13247 
13248 	/* update fake 'exit' subprog as well */
13249 	for (; i <= env->subprog_cnt; i++)
13250 		env->subprog_info[i].start -= cnt;
13251 
13252 	return 0;
13253 }
13254 
13255 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13256 				      u32 cnt)
13257 {
13258 	struct bpf_prog *prog = env->prog;
13259 	u32 i, l_off, l_cnt, nr_linfo;
13260 	struct bpf_line_info *linfo;
13261 
13262 	nr_linfo = prog->aux->nr_linfo;
13263 	if (!nr_linfo)
13264 		return 0;
13265 
13266 	linfo = prog->aux->linfo;
13267 
13268 	/* find first line info to remove, count lines to be removed */
13269 	for (i = 0; i < nr_linfo; i++)
13270 		if (linfo[i].insn_off >= off)
13271 			break;
13272 
13273 	l_off = i;
13274 	l_cnt = 0;
13275 	for (; i < nr_linfo; i++)
13276 		if (linfo[i].insn_off < off + cnt)
13277 			l_cnt++;
13278 		else
13279 			break;
13280 
13281 	/* First live insn doesn't match first live linfo, it needs to "inherit"
13282 	 * last removed linfo.  prog is already modified, so prog->len == off
13283 	 * means no live instructions after (tail of the program was removed).
13284 	 */
13285 	if (prog->len != off && l_cnt &&
13286 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13287 		l_cnt--;
13288 		linfo[--i].insn_off = off + cnt;
13289 	}
13290 
13291 	/* remove the line info which refer to the removed instructions */
13292 	if (l_cnt) {
13293 		memmove(linfo + l_off, linfo + i,
13294 			sizeof(*linfo) * (nr_linfo - i));
13295 
13296 		prog->aux->nr_linfo -= l_cnt;
13297 		nr_linfo = prog->aux->nr_linfo;
13298 	}
13299 
13300 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
13301 	for (i = l_off; i < nr_linfo; i++)
13302 		linfo[i].insn_off -= cnt;
13303 
13304 	/* fix up all subprogs (incl. 'exit') which start >= off */
13305 	for (i = 0; i <= env->subprog_cnt; i++)
13306 		if (env->subprog_info[i].linfo_idx > l_off) {
13307 			/* program may have started in the removed region but
13308 			 * may not be fully removed
13309 			 */
13310 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13311 				env->subprog_info[i].linfo_idx -= l_cnt;
13312 			else
13313 				env->subprog_info[i].linfo_idx = l_off;
13314 		}
13315 
13316 	return 0;
13317 }
13318 
13319 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13320 {
13321 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13322 	unsigned int orig_prog_len = env->prog->len;
13323 	int err;
13324 
13325 	if (bpf_prog_is_dev_bound(env->prog->aux))
13326 		bpf_prog_offload_remove_insns(env, off, cnt);
13327 
13328 	err = bpf_remove_insns(env->prog, off, cnt);
13329 	if (err)
13330 		return err;
13331 
13332 	err = adjust_subprog_starts_after_remove(env, off, cnt);
13333 	if (err)
13334 		return err;
13335 
13336 	err = bpf_adj_linfo_after_remove(env, off, cnt);
13337 	if (err)
13338 		return err;
13339 
13340 	memmove(aux_data + off,	aux_data + off + cnt,
13341 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
13342 
13343 	return 0;
13344 }
13345 
13346 /* The verifier does more data flow analysis than llvm and will not
13347  * explore branches that are dead at run time. Malicious programs can
13348  * have dead code too. Therefore replace all dead at-run-time code
13349  * with 'ja -1'.
13350  *
13351  * Just nops are not optimal, e.g. if they would sit at the end of the
13352  * program and through another bug we would manage to jump there, then
13353  * we'd execute beyond program memory otherwise. Returning exception
13354  * code also wouldn't work since we can have subprogs where the dead
13355  * code could be located.
13356  */
13357 static void sanitize_dead_code(struct bpf_verifier_env *env)
13358 {
13359 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13360 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13361 	struct bpf_insn *insn = env->prog->insnsi;
13362 	const int insn_cnt = env->prog->len;
13363 	int i;
13364 
13365 	for (i = 0; i < insn_cnt; i++) {
13366 		if (aux_data[i].seen)
13367 			continue;
13368 		memcpy(insn + i, &trap, sizeof(trap));
13369 		aux_data[i].zext_dst = false;
13370 	}
13371 }
13372 
13373 static bool insn_is_cond_jump(u8 code)
13374 {
13375 	u8 op;
13376 
13377 	if (BPF_CLASS(code) == BPF_JMP32)
13378 		return true;
13379 
13380 	if (BPF_CLASS(code) != BPF_JMP)
13381 		return false;
13382 
13383 	op = BPF_OP(code);
13384 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13385 }
13386 
13387 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13388 {
13389 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13390 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13391 	struct bpf_insn *insn = env->prog->insnsi;
13392 	const int insn_cnt = env->prog->len;
13393 	int i;
13394 
13395 	for (i = 0; i < insn_cnt; i++, insn++) {
13396 		if (!insn_is_cond_jump(insn->code))
13397 			continue;
13398 
13399 		if (!aux_data[i + 1].seen)
13400 			ja.off = insn->off;
13401 		else if (!aux_data[i + 1 + insn->off].seen)
13402 			ja.off = 0;
13403 		else
13404 			continue;
13405 
13406 		if (bpf_prog_is_dev_bound(env->prog->aux))
13407 			bpf_prog_offload_replace_insn(env, i, &ja);
13408 
13409 		memcpy(insn, &ja, sizeof(ja));
13410 	}
13411 }
13412 
13413 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13414 {
13415 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13416 	int insn_cnt = env->prog->len;
13417 	int i, err;
13418 
13419 	for (i = 0; i < insn_cnt; i++) {
13420 		int j;
13421 
13422 		j = 0;
13423 		while (i + j < insn_cnt && !aux_data[i + j].seen)
13424 			j++;
13425 		if (!j)
13426 			continue;
13427 
13428 		err = verifier_remove_insns(env, i, j);
13429 		if (err)
13430 			return err;
13431 		insn_cnt = env->prog->len;
13432 	}
13433 
13434 	return 0;
13435 }
13436 
13437 static int opt_remove_nops(struct bpf_verifier_env *env)
13438 {
13439 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13440 	struct bpf_insn *insn = env->prog->insnsi;
13441 	int insn_cnt = env->prog->len;
13442 	int i, err;
13443 
13444 	for (i = 0; i < insn_cnt; i++) {
13445 		if (memcmp(&insn[i], &ja, sizeof(ja)))
13446 			continue;
13447 
13448 		err = verifier_remove_insns(env, i, 1);
13449 		if (err)
13450 			return err;
13451 		insn_cnt--;
13452 		i--;
13453 	}
13454 
13455 	return 0;
13456 }
13457 
13458 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13459 					 const union bpf_attr *attr)
13460 {
13461 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13462 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
13463 	int i, patch_len, delta = 0, len = env->prog->len;
13464 	struct bpf_insn *insns = env->prog->insnsi;
13465 	struct bpf_prog *new_prog;
13466 	bool rnd_hi32;
13467 
13468 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13469 	zext_patch[1] = BPF_ZEXT_REG(0);
13470 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13471 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13472 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13473 	for (i = 0; i < len; i++) {
13474 		int adj_idx = i + delta;
13475 		struct bpf_insn insn;
13476 		int load_reg;
13477 
13478 		insn = insns[adj_idx];
13479 		load_reg = insn_def_regno(&insn);
13480 		if (!aux[adj_idx].zext_dst) {
13481 			u8 code, class;
13482 			u32 imm_rnd;
13483 
13484 			if (!rnd_hi32)
13485 				continue;
13486 
13487 			code = insn.code;
13488 			class = BPF_CLASS(code);
13489 			if (load_reg == -1)
13490 				continue;
13491 
13492 			/* NOTE: arg "reg" (the fourth one) is only used for
13493 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
13494 			 *       here.
13495 			 */
13496 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13497 				if (class == BPF_LD &&
13498 				    BPF_MODE(code) == BPF_IMM)
13499 					i++;
13500 				continue;
13501 			}
13502 
13503 			/* ctx load could be transformed into wider load. */
13504 			if (class == BPF_LDX &&
13505 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
13506 				continue;
13507 
13508 			imm_rnd = get_random_u32();
13509 			rnd_hi32_patch[0] = insn;
13510 			rnd_hi32_patch[1].imm = imm_rnd;
13511 			rnd_hi32_patch[3].dst_reg = load_reg;
13512 			patch = rnd_hi32_patch;
13513 			patch_len = 4;
13514 			goto apply_patch_buffer;
13515 		}
13516 
13517 		/* Add in an zero-extend instruction if a) the JIT has requested
13518 		 * it or b) it's a CMPXCHG.
13519 		 *
13520 		 * The latter is because: BPF_CMPXCHG always loads a value into
13521 		 * R0, therefore always zero-extends. However some archs'
13522 		 * equivalent instruction only does this load when the
13523 		 * comparison is successful. This detail of CMPXCHG is
13524 		 * orthogonal to the general zero-extension behaviour of the
13525 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
13526 		 */
13527 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13528 			continue;
13529 
13530 		if (WARN_ON(load_reg == -1)) {
13531 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13532 			return -EFAULT;
13533 		}
13534 
13535 		zext_patch[0] = insn;
13536 		zext_patch[1].dst_reg = load_reg;
13537 		zext_patch[1].src_reg = load_reg;
13538 		patch = zext_patch;
13539 		patch_len = 2;
13540 apply_patch_buffer:
13541 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13542 		if (!new_prog)
13543 			return -ENOMEM;
13544 		env->prog = new_prog;
13545 		insns = new_prog->insnsi;
13546 		aux = env->insn_aux_data;
13547 		delta += patch_len - 1;
13548 	}
13549 
13550 	return 0;
13551 }
13552 
13553 /* convert load instructions that access fields of a context type into a
13554  * sequence of instructions that access fields of the underlying structure:
13555  *     struct __sk_buff    -> struct sk_buff
13556  *     struct bpf_sock_ops -> struct sock
13557  */
13558 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13559 {
13560 	const struct bpf_verifier_ops *ops = env->ops;
13561 	int i, cnt, size, ctx_field_size, delta = 0;
13562 	const int insn_cnt = env->prog->len;
13563 	struct bpf_insn insn_buf[16], *insn;
13564 	u32 target_size, size_default, off;
13565 	struct bpf_prog *new_prog;
13566 	enum bpf_access_type type;
13567 	bool is_narrower_load;
13568 
13569 	if (ops->gen_prologue || env->seen_direct_write) {
13570 		if (!ops->gen_prologue) {
13571 			verbose(env, "bpf verifier is misconfigured\n");
13572 			return -EINVAL;
13573 		}
13574 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13575 					env->prog);
13576 		if (cnt >= ARRAY_SIZE(insn_buf)) {
13577 			verbose(env, "bpf verifier is misconfigured\n");
13578 			return -EINVAL;
13579 		} else if (cnt) {
13580 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13581 			if (!new_prog)
13582 				return -ENOMEM;
13583 
13584 			env->prog = new_prog;
13585 			delta += cnt - 1;
13586 		}
13587 	}
13588 
13589 	if (bpf_prog_is_dev_bound(env->prog->aux))
13590 		return 0;
13591 
13592 	insn = env->prog->insnsi + delta;
13593 
13594 	for (i = 0; i < insn_cnt; i++, insn++) {
13595 		bpf_convert_ctx_access_t convert_ctx_access;
13596 		bool ctx_access;
13597 
13598 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13599 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13600 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13601 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13602 			type = BPF_READ;
13603 			ctx_access = true;
13604 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13605 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13606 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13607 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13608 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13609 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13610 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13611 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13612 			type = BPF_WRITE;
13613 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13614 		} else {
13615 			continue;
13616 		}
13617 
13618 		if (type == BPF_WRITE &&
13619 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
13620 			struct bpf_insn patch[] = {
13621 				*insn,
13622 				BPF_ST_NOSPEC(),
13623 			};
13624 
13625 			cnt = ARRAY_SIZE(patch);
13626 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13627 			if (!new_prog)
13628 				return -ENOMEM;
13629 
13630 			delta    += cnt - 1;
13631 			env->prog = new_prog;
13632 			insn      = new_prog->insnsi + i + delta;
13633 			continue;
13634 		}
13635 
13636 		if (!ctx_access)
13637 			continue;
13638 
13639 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13640 		case PTR_TO_CTX:
13641 			if (!ops->convert_ctx_access)
13642 				continue;
13643 			convert_ctx_access = ops->convert_ctx_access;
13644 			break;
13645 		case PTR_TO_SOCKET:
13646 		case PTR_TO_SOCK_COMMON:
13647 			convert_ctx_access = bpf_sock_convert_ctx_access;
13648 			break;
13649 		case PTR_TO_TCP_SOCK:
13650 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13651 			break;
13652 		case PTR_TO_XDP_SOCK:
13653 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13654 			break;
13655 		case PTR_TO_BTF_ID:
13656 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13657 			if (type == BPF_READ) {
13658 				insn->code = BPF_LDX | BPF_PROBE_MEM |
13659 					BPF_SIZE((insn)->code);
13660 				env->prog->aux->num_exentries++;
13661 			}
13662 			continue;
13663 		default:
13664 			continue;
13665 		}
13666 
13667 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13668 		size = BPF_LDST_BYTES(insn);
13669 
13670 		/* If the read access is a narrower load of the field,
13671 		 * convert to a 4/8-byte load, to minimum program type specific
13672 		 * convert_ctx_access changes. If conversion is successful,
13673 		 * we will apply proper mask to the result.
13674 		 */
13675 		is_narrower_load = size < ctx_field_size;
13676 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13677 		off = insn->off;
13678 		if (is_narrower_load) {
13679 			u8 size_code;
13680 
13681 			if (type == BPF_WRITE) {
13682 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13683 				return -EINVAL;
13684 			}
13685 
13686 			size_code = BPF_H;
13687 			if (ctx_field_size == 4)
13688 				size_code = BPF_W;
13689 			else if (ctx_field_size == 8)
13690 				size_code = BPF_DW;
13691 
13692 			insn->off = off & ~(size_default - 1);
13693 			insn->code = BPF_LDX | BPF_MEM | size_code;
13694 		}
13695 
13696 		target_size = 0;
13697 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13698 					 &target_size);
13699 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13700 		    (ctx_field_size && !target_size)) {
13701 			verbose(env, "bpf verifier is misconfigured\n");
13702 			return -EINVAL;
13703 		}
13704 
13705 		if (is_narrower_load && size < target_size) {
13706 			u8 shift = bpf_ctx_narrow_access_offset(
13707 				off, size, size_default) * 8;
13708 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13709 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13710 				return -EINVAL;
13711 			}
13712 			if (ctx_field_size <= 4) {
13713 				if (shift)
13714 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13715 									insn->dst_reg,
13716 									shift);
13717 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13718 								(1 << size * 8) - 1);
13719 			} else {
13720 				if (shift)
13721 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13722 									insn->dst_reg,
13723 									shift);
13724 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13725 								(1ULL << size * 8) - 1);
13726 			}
13727 		}
13728 
13729 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13730 		if (!new_prog)
13731 			return -ENOMEM;
13732 
13733 		delta += cnt - 1;
13734 
13735 		/* keep walking new program and skip insns we just inserted */
13736 		env->prog = new_prog;
13737 		insn      = new_prog->insnsi + i + delta;
13738 	}
13739 
13740 	return 0;
13741 }
13742 
13743 static int jit_subprogs(struct bpf_verifier_env *env)
13744 {
13745 	struct bpf_prog *prog = env->prog, **func, *tmp;
13746 	int i, j, subprog_start, subprog_end = 0, len, subprog;
13747 	struct bpf_map *map_ptr;
13748 	struct bpf_insn *insn;
13749 	void *old_bpf_func;
13750 	int err, num_exentries;
13751 
13752 	if (env->subprog_cnt <= 1)
13753 		return 0;
13754 
13755 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13756 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13757 			continue;
13758 
13759 		/* Upon error here we cannot fall back to interpreter but
13760 		 * need a hard reject of the program. Thus -EFAULT is
13761 		 * propagated in any case.
13762 		 */
13763 		subprog = find_subprog(env, i + insn->imm + 1);
13764 		if (subprog < 0) {
13765 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13766 				  i + insn->imm + 1);
13767 			return -EFAULT;
13768 		}
13769 		/* temporarily remember subprog id inside insn instead of
13770 		 * aux_data, since next loop will split up all insns into funcs
13771 		 */
13772 		insn->off = subprog;
13773 		/* remember original imm in case JIT fails and fallback
13774 		 * to interpreter will be needed
13775 		 */
13776 		env->insn_aux_data[i].call_imm = insn->imm;
13777 		/* point imm to __bpf_call_base+1 from JITs point of view */
13778 		insn->imm = 1;
13779 		if (bpf_pseudo_func(insn))
13780 			/* jit (e.g. x86_64) may emit fewer instructions
13781 			 * if it learns a u32 imm is the same as a u64 imm.
13782 			 * Force a non zero here.
13783 			 */
13784 			insn[1].imm = 1;
13785 	}
13786 
13787 	err = bpf_prog_alloc_jited_linfo(prog);
13788 	if (err)
13789 		goto out_undo_insn;
13790 
13791 	err = -ENOMEM;
13792 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13793 	if (!func)
13794 		goto out_undo_insn;
13795 
13796 	for (i = 0; i < env->subprog_cnt; i++) {
13797 		subprog_start = subprog_end;
13798 		subprog_end = env->subprog_info[i + 1].start;
13799 
13800 		len = subprog_end - subprog_start;
13801 		/* bpf_prog_run() doesn't call subprogs directly,
13802 		 * hence main prog stats include the runtime of subprogs.
13803 		 * subprogs don't have IDs and not reachable via prog_get_next_id
13804 		 * func[i]->stats will never be accessed and stays NULL
13805 		 */
13806 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13807 		if (!func[i])
13808 			goto out_free;
13809 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13810 		       len * sizeof(struct bpf_insn));
13811 		func[i]->type = prog->type;
13812 		func[i]->len = len;
13813 		if (bpf_prog_calc_tag(func[i]))
13814 			goto out_free;
13815 		func[i]->is_func = 1;
13816 		func[i]->aux->func_idx = i;
13817 		/* Below members will be freed only at prog->aux */
13818 		func[i]->aux->btf = prog->aux->btf;
13819 		func[i]->aux->func_info = prog->aux->func_info;
13820 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13821 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13822 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13823 
13824 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13825 			struct bpf_jit_poke_descriptor *poke;
13826 
13827 			poke = &prog->aux->poke_tab[j];
13828 			if (poke->insn_idx < subprog_end &&
13829 			    poke->insn_idx >= subprog_start)
13830 				poke->aux = func[i]->aux;
13831 		}
13832 
13833 		func[i]->aux->name[0] = 'F';
13834 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13835 		func[i]->jit_requested = 1;
13836 		func[i]->blinding_requested = prog->blinding_requested;
13837 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13838 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13839 		func[i]->aux->linfo = prog->aux->linfo;
13840 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13841 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13842 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13843 		num_exentries = 0;
13844 		insn = func[i]->insnsi;
13845 		for (j = 0; j < func[i]->len; j++, insn++) {
13846 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13847 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13848 				num_exentries++;
13849 		}
13850 		func[i]->aux->num_exentries = num_exentries;
13851 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13852 		func[i] = bpf_int_jit_compile(func[i]);
13853 		if (!func[i]->jited) {
13854 			err = -ENOTSUPP;
13855 			goto out_free;
13856 		}
13857 		cond_resched();
13858 	}
13859 
13860 	/* at this point all bpf functions were successfully JITed
13861 	 * now populate all bpf_calls with correct addresses and
13862 	 * run last pass of JIT
13863 	 */
13864 	for (i = 0; i < env->subprog_cnt; i++) {
13865 		insn = func[i]->insnsi;
13866 		for (j = 0; j < func[i]->len; j++, insn++) {
13867 			if (bpf_pseudo_func(insn)) {
13868 				subprog = insn->off;
13869 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13870 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13871 				continue;
13872 			}
13873 			if (!bpf_pseudo_call(insn))
13874 				continue;
13875 			subprog = insn->off;
13876 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13877 		}
13878 
13879 		/* we use the aux data to keep a list of the start addresses
13880 		 * of the JITed images for each function in the program
13881 		 *
13882 		 * for some architectures, such as powerpc64, the imm field
13883 		 * might not be large enough to hold the offset of the start
13884 		 * address of the callee's JITed image from __bpf_call_base
13885 		 *
13886 		 * in such cases, we can lookup the start address of a callee
13887 		 * by using its subprog id, available from the off field of
13888 		 * the call instruction, as an index for this list
13889 		 */
13890 		func[i]->aux->func = func;
13891 		func[i]->aux->func_cnt = env->subprog_cnt;
13892 	}
13893 	for (i = 0; i < env->subprog_cnt; i++) {
13894 		old_bpf_func = func[i]->bpf_func;
13895 		tmp = bpf_int_jit_compile(func[i]);
13896 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13897 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13898 			err = -ENOTSUPP;
13899 			goto out_free;
13900 		}
13901 		cond_resched();
13902 	}
13903 
13904 	/* finally lock prog and jit images for all functions and
13905 	 * populate kallsysm
13906 	 */
13907 	for (i = 0; i < env->subprog_cnt; i++) {
13908 		bpf_prog_lock_ro(func[i]);
13909 		bpf_prog_kallsyms_add(func[i]);
13910 	}
13911 
13912 	/* Last step: make now unused interpreter insns from main
13913 	 * prog consistent for later dump requests, so they can
13914 	 * later look the same as if they were interpreted only.
13915 	 */
13916 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13917 		if (bpf_pseudo_func(insn)) {
13918 			insn[0].imm = env->insn_aux_data[i].call_imm;
13919 			insn[1].imm = insn->off;
13920 			insn->off = 0;
13921 			continue;
13922 		}
13923 		if (!bpf_pseudo_call(insn))
13924 			continue;
13925 		insn->off = env->insn_aux_data[i].call_imm;
13926 		subprog = find_subprog(env, i + insn->off + 1);
13927 		insn->imm = subprog;
13928 	}
13929 
13930 	prog->jited = 1;
13931 	prog->bpf_func = func[0]->bpf_func;
13932 	prog->jited_len = func[0]->jited_len;
13933 	prog->aux->func = func;
13934 	prog->aux->func_cnt = env->subprog_cnt;
13935 	bpf_prog_jit_attempt_done(prog);
13936 	return 0;
13937 out_free:
13938 	/* We failed JIT'ing, so at this point we need to unregister poke
13939 	 * descriptors from subprogs, so that kernel is not attempting to
13940 	 * patch it anymore as we're freeing the subprog JIT memory.
13941 	 */
13942 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13943 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13944 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13945 	}
13946 	/* At this point we're guaranteed that poke descriptors are not
13947 	 * live anymore. We can just unlink its descriptor table as it's
13948 	 * released with the main prog.
13949 	 */
13950 	for (i = 0; i < env->subprog_cnt; i++) {
13951 		if (!func[i])
13952 			continue;
13953 		func[i]->aux->poke_tab = NULL;
13954 		bpf_jit_free(func[i]);
13955 	}
13956 	kfree(func);
13957 out_undo_insn:
13958 	/* cleanup main prog to be interpreted */
13959 	prog->jit_requested = 0;
13960 	prog->blinding_requested = 0;
13961 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13962 		if (!bpf_pseudo_call(insn))
13963 			continue;
13964 		insn->off = 0;
13965 		insn->imm = env->insn_aux_data[i].call_imm;
13966 	}
13967 	bpf_prog_jit_attempt_done(prog);
13968 	return err;
13969 }
13970 
13971 static int fixup_call_args(struct bpf_verifier_env *env)
13972 {
13973 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13974 	struct bpf_prog *prog = env->prog;
13975 	struct bpf_insn *insn = prog->insnsi;
13976 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13977 	int i, depth;
13978 #endif
13979 	int err = 0;
13980 
13981 	if (env->prog->jit_requested &&
13982 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13983 		err = jit_subprogs(env);
13984 		if (err == 0)
13985 			return 0;
13986 		if (err == -EFAULT)
13987 			return err;
13988 	}
13989 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13990 	if (has_kfunc_call) {
13991 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13992 		return -EINVAL;
13993 	}
13994 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13995 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13996 		 * have to be rejected, since interpreter doesn't support them yet.
13997 		 */
13998 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13999 		return -EINVAL;
14000 	}
14001 	for (i = 0; i < prog->len; i++, insn++) {
14002 		if (bpf_pseudo_func(insn)) {
14003 			/* When JIT fails the progs with callback calls
14004 			 * have to be rejected, since interpreter doesn't support them yet.
14005 			 */
14006 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
14007 			return -EINVAL;
14008 		}
14009 
14010 		if (!bpf_pseudo_call(insn))
14011 			continue;
14012 		depth = get_callee_stack_depth(env, insn, i);
14013 		if (depth < 0)
14014 			return depth;
14015 		bpf_patch_call_args(insn, depth);
14016 	}
14017 	err = 0;
14018 #endif
14019 	return err;
14020 }
14021 
14022 static int fixup_kfunc_call(struct bpf_verifier_env *env,
14023 			    struct bpf_insn *insn)
14024 {
14025 	const struct bpf_kfunc_desc *desc;
14026 
14027 	if (!insn->imm) {
14028 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
14029 		return -EINVAL;
14030 	}
14031 
14032 	/* insn->imm has the btf func_id. Replace it with
14033 	 * an address (relative to __bpf_base_call).
14034 	 */
14035 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
14036 	if (!desc) {
14037 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
14038 			insn->imm);
14039 		return -EFAULT;
14040 	}
14041 
14042 	insn->imm = desc->imm;
14043 
14044 	return 0;
14045 }
14046 
14047 /* Do various post-verification rewrites in a single program pass.
14048  * These rewrites simplify JIT and interpreter implementations.
14049  */
14050 static int do_misc_fixups(struct bpf_verifier_env *env)
14051 {
14052 	struct bpf_prog *prog = env->prog;
14053 	enum bpf_attach_type eatype = prog->expected_attach_type;
14054 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
14055 	struct bpf_insn *insn = prog->insnsi;
14056 	const struct bpf_func_proto *fn;
14057 	const int insn_cnt = prog->len;
14058 	const struct bpf_map_ops *ops;
14059 	struct bpf_insn_aux_data *aux;
14060 	struct bpf_insn insn_buf[16];
14061 	struct bpf_prog *new_prog;
14062 	struct bpf_map *map_ptr;
14063 	int i, ret, cnt, delta = 0;
14064 
14065 	for (i = 0; i < insn_cnt; i++, insn++) {
14066 		/* Make divide-by-zero exceptions impossible. */
14067 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
14068 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
14069 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
14070 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
14071 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
14072 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
14073 			struct bpf_insn *patchlet;
14074 			struct bpf_insn chk_and_div[] = {
14075 				/* [R,W]x div 0 -> 0 */
14076 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14077 					     BPF_JNE | BPF_K, insn->src_reg,
14078 					     0, 2, 0),
14079 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
14080 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14081 				*insn,
14082 			};
14083 			struct bpf_insn chk_and_mod[] = {
14084 				/* [R,W]x mod 0 -> [R,W]x */
14085 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14086 					     BPF_JEQ | BPF_K, insn->src_reg,
14087 					     0, 1 + (is64 ? 0 : 1), 0),
14088 				*insn,
14089 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14090 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14091 			};
14092 
14093 			patchlet = isdiv ? chk_and_div : chk_and_mod;
14094 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14095 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14096 
14097 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14098 			if (!new_prog)
14099 				return -ENOMEM;
14100 
14101 			delta    += cnt - 1;
14102 			env->prog = prog = new_prog;
14103 			insn      = new_prog->insnsi + i + delta;
14104 			continue;
14105 		}
14106 
14107 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14108 		if (BPF_CLASS(insn->code) == BPF_LD &&
14109 		    (BPF_MODE(insn->code) == BPF_ABS ||
14110 		     BPF_MODE(insn->code) == BPF_IND)) {
14111 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
14112 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14113 				verbose(env, "bpf verifier is misconfigured\n");
14114 				return -EINVAL;
14115 			}
14116 
14117 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14118 			if (!new_prog)
14119 				return -ENOMEM;
14120 
14121 			delta    += cnt - 1;
14122 			env->prog = prog = new_prog;
14123 			insn      = new_prog->insnsi + i + delta;
14124 			continue;
14125 		}
14126 
14127 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
14128 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14129 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14130 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14131 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14132 			struct bpf_insn *patch = &insn_buf[0];
14133 			bool issrc, isneg, isimm;
14134 			u32 off_reg;
14135 
14136 			aux = &env->insn_aux_data[i + delta];
14137 			if (!aux->alu_state ||
14138 			    aux->alu_state == BPF_ALU_NON_POINTER)
14139 				continue;
14140 
14141 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14142 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14143 				BPF_ALU_SANITIZE_SRC;
14144 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14145 
14146 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
14147 			if (isimm) {
14148 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14149 			} else {
14150 				if (isneg)
14151 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14152 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14153 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14154 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14155 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14156 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14157 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14158 			}
14159 			if (!issrc)
14160 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14161 			insn->src_reg = BPF_REG_AX;
14162 			if (isneg)
14163 				insn->code = insn->code == code_add ?
14164 					     code_sub : code_add;
14165 			*patch++ = *insn;
14166 			if (issrc && isneg && !isimm)
14167 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14168 			cnt = patch - insn_buf;
14169 
14170 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14171 			if (!new_prog)
14172 				return -ENOMEM;
14173 
14174 			delta    += cnt - 1;
14175 			env->prog = prog = new_prog;
14176 			insn      = new_prog->insnsi + i + delta;
14177 			continue;
14178 		}
14179 
14180 		if (insn->code != (BPF_JMP | BPF_CALL))
14181 			continue;
14182 		if (insn->src_reg == BPF_PSEUDO_CALL)
14183 			continue;
14184 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14185 			ret = fixup_kfunc_call(env, insn);
14186 			if (ret)
14187 				return ret;
14188 			continue;
14189 		}
14190 
14191 		if (insn->imm == BPF_FUNC_get_route_realm)
14192 			prog->dst_needed = 1;
14193 		if (insn->imm == BPF_FUNC_get_prandom_u32)
14194 			bpf_user_rnd_init_once();
14195 		if (insn->imm == BPF_FUNC_override_return)
14196 			prog->kprobe_override = 1;
14197 		if (insn->imm == BPF_FUNC_tail_call) {
14198 			/* If we tail call into other programs, we
14199 			 * cannot make any assumptions since they can
14200 			 * be replaced dynamically during runtime in
14201 			 * the program array.
14202 			 */
14203 			prog->cb_access = 1;
14204 			if (!allow_tail_call_in_subprogs(env))
14205 				prog->aux->stack_depth = MAX_BPF_STACK;
14206 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14207 
14208 			/* mark bpf_tail_call as different opcode to avoid
14209 			 * conditional branch in the interpreter for every normal
14210 			 * call and to prevent accidental JITing by JIT compiler
14211 			 * that doesn't support bpf_tail_call yet
14212 			 */
14213 			insn->imm = 0;
14214 			insn->code = BPF_JMP | BPF_TAIL_CALL;
14215 
14216 			aux = &env->insn_aux_data[i + delta];
14217 			if (env->bpf_capable && !prog->blinding_requested &&
14218 			    prog->jit_requested &&
14219 			    !bpf_map_key_poisoned(aux) &&
14220 			    !bpf_map_ptr_poisoned(aux) &&
14221 			    !bpf_map_ptr_unpriv(aux)) {
14222 				struct bpf_jit_poke_descriptor desc = {
14223 					.reason = BPF_POKE_REASON_TAIL_CALL,
14224 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14225 					.tail_call.key = bpf_map_key_immediate(aux),
14226 					.insn_idx = i + delta,
14227 				};
14228 
14229 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
14230 				if (ret < 0) {
14231 					verbose(env, "adding tail call poke descriptor failed\n");
14232 					return ret;
14233 				}
14234 
14235 				insn->imm = ret + 1;
14236 				continue;
14237 			}
14238 
14239 			if (!bpf_map_ptr_unpriv(aux))
14240 				continue;
14241 
14242 			/* instead of changing every JIT dealing with tail_call
14243 			 * emit two extra insns:
14244 			 * if (index >= max_entries) goto out;
14245 			 * index &= array->index_mask;
14246 			 * to avoid out-of-bounds cpu speculation
14247 			 */
14248 			if (bpf_map_ptr_poisoned(aux)) {
14249 				verbose(env, "tail_call abusing map_ptr\n");
14250 				return -EINVAL;
14251 			}
14252 
14253 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14254 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14255 						  map_ptr->max_entries, 2);
14256 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14257 						    container_of(map_ptr,
14258 								 struct bpf_array,
14259 								 map)->index_mask);
14260 			insn_buf[2] = *insn;
14261 			cnt = 3;
14262 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14263 			if (!new_prog)
14264 				return -ENOMEM;
14265 
14266 			delta    += cnt - 1;
14267 			env->prog = prog = new_prog;
14268 			insn      = new_prog->insnsi + i + delta;
14269 			continue;
14270 		}
14271 
14272 		if (insn->imm == BPF_FUNC_timer_set_callback) {
14273 			/* The verifier will process callback_fn as many times as necessary
14274 			 * with different maps and the register states prepared by
14275 			 * set_timer_callback_state will be accurate.
14276 			 *
14277 			 * The following use case is valid:
14278 			 *   map1 is shared by prog1, prog2, prog3.
14279 			 *   prog1 calls bpf_timer_init for some map1 elements
14280 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
14281 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
14282 			 *   prog3 calls bpf_timer_start for some map1 elements.
14283 			 *     Those that were not both bpf_timer_init-ed and
14284 			 *     bpf_timer_set_callback-ed will return -EINVAL.
14285 			 */
14286 			struct bpf_insn ld_addrs[2] = {
14287 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14288 			};
14289 
14290 			insn_buf[0] = ld_addrs[0];
14291 			insn_buf[1] = ld_addrs[1];
14292 			insn_buf[2] = *insn;
14293 			cnt = 3;
14294 
14295 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14296 			if (!new_prog)
14297 				return -ENOMEM;
14298 
14299 			delta    += cnt - 1;
14300 			env->prog = prog = new_prog;
14301 			insn      = new_prog->insnsi + i + delta;
14302 			goto patch_call_imm;
14303 		}
14304 
14305 		if (insn->imm == BPF_FUNC_task_storage_get ||
14306 		    insn->imm == BPF_FUNC_sk_storage_get ||
14307 		    insn->imm == BPF_FUNC_inode_storage_get ||
14308 		    insn->imm == BPF_FUNC_cgrp_storage_get) {
14309 			if (env->prog->aux->sleepable)
14310 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14311 			else
14312 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14313 			insn_buf[1] = *insn;
14314 			cnt = 2;
14315 
14316 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14317 			if (!new_prog)
14318 				return -ENOMEM;
14319 
14320 			delta += cnt - 1;
14321 			env->prog = prog = new_prog;
14322 			insn = new_prog->insnsi + i + delta;
14323 			goto patch_call_imm;
14324 		}
14325 
14326 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14327 		 * and other inlining handlers are currently limited to 64 bit
14328 		 * only.
14329 		 */
14330 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14331 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
14332 		     insn->imm == BPF_FUNC_map_update_elem ||
14333 		     insn->imm == BPF_FUNC_map_delete_elem ||
14334 		     insn->imm == BPF_FUNC_map_push_elem   ||
14335 		     insn->imm == BPF_FUNC_map_pop_elem    ||
14336 		     insn->imm == BPF_FUNC_map_peek_elem   ||
14337 		     insn->imm == BPF_FUNC_redirect_map    ||
14338 		     insn->imm == BPF_FUNC_for_each_map_elem ||
14339 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14340 			aux = &env->insn_aux_data[i + delta];
14341 			if (bpf_map_ptr_poisoned(aux))
14342 				goto patch_call_imm;
14343 
14344 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14345 			ops = map_ptr->ops;
14346 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
14347 			    ops->map_gen_lookup) {
14348 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14349 				if (cnt == -EOPNOTSUPP)
14350 					goto patch_map_ops_generic;
14351 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14352 					verbose(env, "bpf verifier is misconfigured\n");
14353 					return -EINVAL;
14354 				}
14355 
14356 				new_prog = bpf_patch_insn_data(env, i + delta,
14357 							       insn_buf, cnt);
14358 				if (!new_prog)
14359 					return -ENOMEM;
14360 
14361 				delta    += cnt - 1;
14362 				env->prog = prog = new_prog;
14363 				insn      = new_prog->insnsi + i + delta;
14364 				continue;
14365 			}
14366 
14367 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14368 				     (void *(*)(struct bpf_map *map, void *key))NULL));
14369 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14370 				     (int (*)(struct bpf_map *map, void *key))NULL));
14371 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14372 				     (int (*)(struct bpf_map *map, void *key, void *value,
14373 					      u64 flags))NULL));
14374 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14375 				     (int (*)(struct bpf_map *map, void *value,
14376 					      u64 flags))NULL));
14377 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14378 				     (int (*)(struct bpf_map *map, void *value))NULL));
14379 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14380 				     (int (*)(struct bpf_map *map, void *value))NULL));
14381 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
14382 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14383 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14384 				     (int (*)(struct bpf_map *map,
14385 					      bpf_callback_t callback_fn,
14386 					      void *callback_ctx,
14387 					      u64 flags))NULL));
14388 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14389 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14390 
14391 patch_map_ops_generic:
14392 			switch (insn->imm) {
14393 			case BPF_FUNC_map_lookup_elem:
14394 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14395 				continue;
14396 			case BPF_FUNC_map_update_elem:
14397 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14398 				continue;
14399 			case BPF_FUNC_map_delete_elem:
14400 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14401 				continue;
14402 			case BPF_FUNC_map_push_elem:
14403 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14404 				continue;
14405 			case BPF_FUNC_map_pop_elem:
14406 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14407 				continue;
14408 			case BPF_FUNC_map_peek_elem:
14409 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14410 				continue;
14411 			case BPF_FUNC_redirect_map:
14412 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
14413 				continue;
14414 			case BPF_FUNC_for_each_map_elem:
14415 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14416 				continue;
14417 			case BPF_FUNC_map_lookup_percpu_elem:
14418 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14419 				continue;
14420 			}
14421 
14422 			goto patch_call_imm;
14423 		}
14424 
14425 		/* Implement bpf_jiffies64 inline. */
14426 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14427 		    insn->imm == BPF_FUNC_jiffies64) {
14428 			struct bpf_insn ld_jiffies_addr[2] = {
14429 				BPF_LD_IMM64(BPF_REG_0,
14430 					     (unsigned long)&jiffies),
14431 			};
14432 
14433 			insn_buf[0] = ld_jiffies_addr[0];
14434 			insn_buf[1] = ld_jiffies_addr[1];
14435 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14436 						  BPF_REG_0, 0);
14437 			cnt = 3;
14438 
14439 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14440 						       cnt);
14441 			if (!new_prog)
14442 				return -ENOMEM;
14443 
14444 			delta    += cnt - 1;
14445 			env->prog = prog = new_prog;
14446 			insn      = new_prog->insnsi + i + delta;
14447 			continue;
14448 		}
14449 
14450 		/* Implement bpf_get_func_arg inline. */
14451 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14452 		    insn->imm == BPF_FUNC_get_func_arg) {
14453 			/* Load nr_args from ctx - 8 */
14454 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14455 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14456 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14457 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14458 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14459 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14460 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14461 			insn_buf[7] = BPF_JMP_A(1);
14462 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14463 			cnt = 9;
14464 
14465 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14466 			if (!new_prog)
14467 				return -ENOMEM;
14468 
14469 			delta    += cnt - 1;
14470 			env->prog = prog = new_prog;
14471 			insn      = new_prog->insnsi + i + delta;
14472 			continue;
14473 		}
14474 
14475 		/* Implement bpf_get_func_ret inline. */
14476 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14477 		    insn->imm == BPF_FUNC_get_func_ret) {
14478 			if (eatype == BPF_TRACE_FEXIT ||
14479 			    eatype == BPF_MODIFY_RETURN) {
14480 				/* Load nr_args from ctx - 8 */
14481 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14482 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14483 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14484 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14485 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14486 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14487 				cnt = 6;
14488 			} else {
14489 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14490 				cnt = 1;
14491 			}
14492 
14493 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14494 			if (!new_prog)
14495 				return -ENOMEM;
14496 
14497 			delta    += cnt - 1;
14498 			env->prog = prog = new_prog;
14499 			insn      = new_prog->insnsi + i + delta;
14500 			continue;
14501 		}
14502 
14503 		/* Implement get_func_arg_cnt inline. */
14504 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14505 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
14506 			/* Load nr_args from ctx - 8 */
14507 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14508 
14509 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14510 			if (!new_prog)
14511 				return -ENOMEM;
14512 
14513 			env->prog = prog = new_prog;
14514 			insn      = new_prog->insnsi + i + delta;
14515 			continue;
14516 		}
14517 
14518 		/* Implement bpf_get_func_ip inline. */
14519 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14520 		    insn->imm == BPF_FUNC_get_func_ip) {
14521 			/* Load IP address from ctx - 16 */
14522 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14523 
14524 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14525 			if (!new_prog)
14526 				return -ENOMEM;
14527 
14528 			env->prog = prog = new_prog;
14529 			insn      = new_prog->insnsi + i + delta;
14530 			continue;
14531 		}
14532 
14533 patch_call_imm:
14534 		fn = env->ops->get_func_proto(insn->imm, env->prog);
14535 		/* all functions that have prototype and verifier allowed
14536 		 * programs to call them, must be real in-kernel functions
14537 		 */
14538 		if (!fn->func) {
14539 			verbose(env,
14540 				"kernel subsystem misconfigured func %s#%d\n",
14541 				func_id_name(insn->imm), insn->imm);
14542 			return -EFAULT;
14543 		}
14544 		insn->imm = fn->func - __bpf_call_base;
14545 	}
14546 
14547 	/* Since poke tab is now finalized, publish aux to tracker. */
14548 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
14549 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
14550 		if (!map_ptr->ops->map_poke_track ||
14551 		    !map_ptr->ops->map_poke_untrack ||
14552 		    !map_ptr->ops->map_poke_run) {
14553 			verbose(env, "bpf verifier is misconfigured\n");
14554 			return -EINVAL;
14555 		}
14556 
14557 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14558 		if (ret < 0) {
14559 			verbose(env, "tracking tail call prog failed\n");
14560 			return ret;
14561 		}
14562 	}
14563 
14564 	sort_kfunc_descs_by_imm(env->prog);
14565 
14566 	return 0;
14567 }
14568 
14569 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14570 					int position,
14571 					s32 stack_base,
14572 					u32 callback_subprogno,
14573 					u32 *cnt)
14574 {
14575 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14576 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14577 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14578 	int reg_loop_max = BPF_REG_6;
14579 	int reg_loop_cnt = BPF_REG_7;
14580 	int reg_loop_ctx = BPF_REG_8;
14581 
14582 	struct bpf_prog *new_prog;
14583 	u32 callback_start;
14584 	u32 call_insn_offset;
14585 	s32 callback_offset;
14586 
14587 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
14588 	 * be careful to modify this code in sync.
14589 	 */
14590 	struct bpf_insn insn_buf[] = {
14591 		/* Return error and jump to the end of the patch if
14592 		 * expected number of iterations is too big.
14593 		 */
14594 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14595 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14596 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14597 		/* spill R6, R7, R8 to use these as loop vars */
14598 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14599 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14600 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14601 		/* initialize loop vars */
14602 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14603 		BPF_MOV32_IMM(reg_loop_cnt, 0),
14604 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14605 		/* loop header,
14606 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
14607 		 */
14608 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14609 		/* callback call,
14610 		 * correct callback offset would be set after patching
14611 		 */
14612 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14613 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14614 		BPF_CALL_REL(0),
14615 		/* increment loop counter */
14616 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14617 		/* jump to loop header if callback returned 0 */
14618 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14619 		/* return value of bpf_loop,
14620 		 * set R0 to the number of iterations
14621 		 */
14622 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14623 		/* restore original values of R6, R7, R8 */
14624 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14625 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14626 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14627 	};
14628 
14629 	*cnt = ARRAY_SIZE(insn_buf);
14630 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14631 	if (!new_prog)
14632 		return new_prog;
14633 
14634 	/* callback start is known only after patching */
14635 	callback_start = env->subprog_info[callback_subprogno].start;
14636 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14637 	call_insn_offset = position + 12;
14638 	callback_offset = callback_start - call_insn_offset - 1;
14639 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
14640 
14641 	return new_prog;
14642 }
14643 
14644 static bool is_bpf_loop_call(struct bpf_insn *insn)
14645 {
14646 	return insn->code == (BPF_JMP | BPF_CALL) &&
14647 		insn->src_reg == 0 &&
14648 		insn->imm == BPF_FUNC_loop;
14649 }
14650 
14651 /* For all sub-programs in the program (including main) check
14652  * insn_aux_data to see if there are bpf_loop calls that require
14653  * inlining. If such calls are found the calls are replaced with a
14654  * sequence of instructions produced by `inline_bpf_loop` function and
14655  * subprog stack_depth is increased by the size of 3 registers.
14656  * This stack space is used to spill values of the R6, R7, R8.  These
14657  * registers are used to store the loop bound, counter and context
14658  * variables.
14659  */
14660 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14661 {
14662 	struct bpf_subprog_info *subprogs = env->subprog_info;
14663 	int i, cur_subprog = 0, cnt, delta = 0;
14664 	struct bpf_insn *insn = env->prog->insnsi;
14665 	int insn_cnt = env->prog->len;
14666 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
14667 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14668 	u16 stack_depth_extra = 0;
14669 
14670 	for (i = 0; i < insn_cnt; i++, insn++) {
14671 		struct bpf_loop_inline_state *inline_state =
14672 			&env->insn_aux_data[i + delta].loop_inline_state;
14673 
14674 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14675 			struct bpf_prog *new_prog;
14676 
14677 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14678 			new_prog = inline_bpf_loop(env,
14679 						   i + delta,
14680 						   -(stack_depth + stack_depth_extra),
14681 						   inline_state->callback_subprogno,
14682 						   &cnt);
14683 			if (!new_prog)
14684 				return -ENOMEM;
14685 
14686 			delta     += cnt - 1;
14687 			env->prog  = new_prog;
14688 			insn       = new_prog->insnsi + i + delta;
14689 		}
14690 
14691 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14692 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
14693 			cur_subprog++;
14694 			stack_depth = subprogs[cur_subprog].stack_depth;
14695 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14696 			stack_depth_extra = 0;
14697 		}
14698 	}
14699 
14700 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14701 
14702 	return 0;
14703 }
14704 
14705 static void free_states(struct bpf_verifier_env *env)
14706 {
14707 	struct bpf_verifier_state_list *sl, *sln;
14708 	int i;
14709 
14710 	sl = env->free_list;
14711 	while (sl) {
14712 		sln = sl->next;
14713 		free_verifier_state(&sl->state, false);
14714 		kfree(sl);
14715 		sl = sln;
14716 	}
14717 	env->free_list = NULL;
14718 
14719 	if (!env->explored_states)
14720 		return;
14721 
14722 	for (i = 0; i < state_htab_size(env); i++) {
14723 		sl = env->explored_states[i];
14724 
14725 		while (sl) {
14726 			sln = sl->next;
14727 			free_verifier_state(&sl->state, false);
14728 			kfree(sl);
14729 			sl = sln;
14730 		}
14731 		env->explored_states[i] = NULL;
14732 	}
14733 }
14734 
14735 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14736 {
14737 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14738 	struct bpf_verifier_state *state;
14739 	struct bpf_reg_state *regs;
14740 	int ret, i;
14741 
14742 	env->prev_linfo = NULL;
14743 	env->pass_cnt++;
14744 
14745 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14746 	if (!state)
14747 		return -ENOMEM;
14748 	state->curframe = 0;
14749 	state->speculative = false;
14750 	state->branches = 1;
14751 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14752 	if (!state->frame[0]) {
14753 		kfree(state);
14754 		return -ENOMEM;
14755 	}
14756 	env->cur_state = state;
14757 	init_func_state(env, state->frame[0],
14758 			BPF_MAIN_FUNC /* callsite */,
14759 			0 /* frameno */,
14760 			subprog);
14761 	state->first_insn_idx = env->subprog_info[subprog].start;
14762 	state->last_insn_idx = -1;
14763 
14764 	regs = state->frame[state->curframe]->regs;
14765 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14766 		ret = btf_prepare_func_args(env, subprog, regs);
14767 		if (ret)
14768 			goto out;
14769 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14770 			if (regs[i].type == PTR_TO_CTX)
14771 				mark_reg_known_zero(env, regs, i);
14772 			else if (regs[i].type == SCALAR_VALUE)
14773 				mark_reg_unknown(env, regs, i);
14774 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
14775 				const u32 mem_size = regs[i].mem_size;
14776 
14777 				mark_reg_known_zero(env, regs, i);
14778 				regs[i].mem_size = mem_size;
14779 				regs[i].id = ++env->id_gen;
14780 			}
14781 		}
14782 	} else {
14783 		/* 1st arg to a function */
14784 		regs[BPF_REG_1].type = PTR_TO_CTX;
14785 		mark_reg_known_zero(env, regs, BPF_REG_1);
14786 		ret = btf_check_subprog_arg_match(env, subprog, regs);
14787 		if (ret == -EFAULT)
14788 			/* unlikely verifier bug. abort.
14789 			 * ret == 0 and ret < 0 are sadly acceptable for
14790 			 * main() function due to backward compatibility.
14791 			 * Like socket filter program may be written as:
14792 			 * int bpf_prog(struct pt_regs *ctx)
14793 			 * and never dereference that ctx in the program.
14794 			 * 'struct pt_regs' is a type mismatch for socket
14795 			 * filter that should be using 'struct __sk_buff'.
14796 			 */
14797 			goto out;
14798 	}
14799 
14800 	ret = do_check(env);
14801 out:
14802 	/* check for NULL is necessary, since cur_state can be freed inside
14803 	 * do_check() under memory pressure.
14804 	 */
14805 	if (env->cur_state) {
14806 		free_verifier_state(env->cur_state, true);
14807 		env->cur_state = NULL;
14808 	}
14809 	while (!pop_stack(env, NULL, NULL, false));
14810 	if (!ret && pop_log)
14811 		bpf_vlog_reset(&env->log, 0);
14812 	free_states(env);
14813 	return ret;
14814 }
14815 
14816 /* Verify all global functions in a BPF program one by one based on their BTF.
14817  * All global functions must pass verification. Otherwise the whole program is rejected.
14818  * Consider:
14819  * int bar(int);
14820  * int foo(int f)
14821  * {
14822  *    return bar(f);
14823  * }
14824  * int bar(int b)
14825  * {
14826  *    ...
14827  * }
14828  * foo() will be verified first for R1=any_scalar_value. During verification it
14829  * will be assumed that bar() already verified successfully and call to bar()
14830  * from foo() will be checked for type match only. Later bar() will be verified
14831  * independently to check that it's safe for R1=any_scalar_value.
14832  */
14833 static int do_check_subprogs(struct bpf_verifier_env *env)
14834 {
14835 	struct bpf_prog_aux *aux = env->prog->aux;
14836 	int i, ret;
14837 
14838 	if (!aux->func_info)
14839 		return 0;
14840 
14841 	for (i = 1; i < env->subprog_cnt; i++) {
14842 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14843 			continue;
14844 		env->insn_idx = env->subprog_info[i].start;
14845 		WARN_ON_ONCE(env->insn_idx == 0);
14846 		ret = do_check_common(env, i);
14847 		if (ret) {
14848 			return ret;
14849 		} else if (env->log.level & BPF_LOG_LEVEL) {
14850 			verbose(env,
14851 				"Func#%d is safe for any args that match its prototype\n",
14852 				i);
14853 		}
14854 	}
14855 	return 0;
14856 }
14857 
14858 static int do_check_main(struct bpf_verifier_env *env)
14859 {
14860 	int ret;
14861 
14862 	env->insn_idx = 0;
14863 	ret = do_check_common(env, 0);
14864 	if (!ret)
14865 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14866 	return ret;
14867 }
14868 
14869 
14870 static void print_verification_stats(struct bpf_verifier_env *env)
14871 {
14872 	int i;
14873 
14874 	if (env->log.level & BPF_LOG_STATS) {
14875 		verbose(env, "verification time %lld usec\n",
14876 			div_u64(env->verification_time, 1000));
14877 		verbose(env, "stack depth ");
14878 		for (i = 0; i < env->subprog_cnt; i++) {
14879 			u32 depth = env->subprog_info[i].stack_depth;
14880 
14881 			verbose(env, "%d", depth);
14882 			if (i + 1 < env->subprog_cnt)
14883 				verbose(env, "+");
14884 		}
14885 		verbose(env, "\n");
14886 	}
14887 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14888 		"total_states %d peak_states %d mark_read %d\n",
14889 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14890 		env->max_states_per_insn, env->total_states,
14891 		env->peak_states, env->longest_mark_read_walk);
14892 }
14893 
14894 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14895 {
14896 	const struct btf_type *t, *func_proto;
14897 	const struct bpf_struct_ops *st_ops;
14898 	const struct btf_member *member;
14899 	struct bpf_prog *prog = env->prog;
14900 	u32 btf_id, member_idx;
14901 	const char *mname;
14902 
14903 	if (!prog->gpl_compatible) {
14904 		verbose(env, "struct ops programs must have a GPL compatible license\n");
14905 		return -EINVAL;
14906 	}
14907 
14908 	btf_id = prog->aux->attach_btf_id;
14909 	st_ops = bpf_struct_ops_find(btf_id);
14910 	if (!st_ops) {
14911 		verbose(env, "attach_btf_id %u is not a supported struct\n",
14912 			btf_id);
14913 		return -ENOTSUPP;
14914 	}
14915 
14916 	t = st_ops->type;
14917 	member_idx = prog->expected_attach_type;
14918 	if (member_idx >= btf_type_vlen(t)) {
14919 		verbose(env, "attach to invalid member idx %u of struct %s\n",
14920 			member_idx, st_ops->name);
14921 		return -EINVAL;
14922 	}
14923 
14924 	member = &btf_type_member(t)[member_idx];
14925 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14926 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14927 					       NULL);
14928 	if (!func_proto) {
14929 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14930 			mname, member_idx, st_ops->name);
14931 		return -EINVAL;
14932 	}
14933 
14934 	if (st_ops->check_member) {
14935 		int err = st_ops->check_member(t, member);
14936 
14937 		if (err) {
14938 			verbose(env, "attach to unsupported member %s of struct %s\n",
14939 				mname, st_ops->name);
14940 			return err;
14941 		}
14942 	}
14943 
14944 	prog->aux->attach_func_proto = func_proto;
14945 	prog->aux->attach_func_name = mname;
14946 	env->ops = st_ops->verifier_ops;
14947 
14948 	return 0;
14949 }
14950 #define SECURITY_PREFIX "security_"
14951 
14952 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14953 {
14954 	if (within_error_injection_list(addr) ||
14955 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14956 		return 0;
14957 
14958 	return -EINVAL;
14959 }
14960 
14961 /* list of non-sleepable functions that are otherwise on
14962  * ALLOW_ERROR_INJECTION list
14963  */
14964 BTF_SET_START(btf_non_sleepable_error_inject)
14965 /* Three functions below can be called from sleepable and non-sleepable context.
14966  * Assume non-sleepable from bpf safety point of view.
14967  */
14968 BTF_ID(func, __filemap_add_folio)
14969 BTF_ID(func, should_fail_alloc_page)
14970 BTF_ID(func, should_failslab)
14971 BTF_SET_END(btf_non_sleepable_error_inject)
14972 
14973 static int check_non_sleepable_error_inject(u32 btf_id)
14974 {
14975 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14976 }
14977 
14978 int bpf_check_attach_target(struct bpf_verifier_log *log,
14979 			    const struct bpf_prog *prog,
14980 			    const struct bpf_prog *tgt_prog,
14981 			    u32 btf_id,
14982 			    struct bpf_attach_target_info *tgt_info)
14983 {
14984 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14985 	const char prefix[] = "btf_trace_";
14986 	int ret = 0, subprog = -1, i;
14987 	const struct btf_type *t;
14988 	bool conservative = true;
14989 	const char *tname;
14990 	struct btf *btf;
14991 	long addr = 0;
14992 
14993 	if (!btf_id) {
14994 		bpf_log(log, "Tracing programs must provide btf_id\n");
14995 		return -EINVAL;
14996 	}
14997 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14998 	if (!btf) {
14999 		bpf_log(log,
15000 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
15001 		return -EINVAL;
15002 	}
15003 	t = btf_type_by_id(btf, btf_id);
15004 	if (!t) {
15005 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
15006 		return -EINVAL;
15007 	}
15008 	tname = btf_name_by_offset(btf, t->name_off);
15009 	if (!tname) {
15010 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
15011 		return -EINVAL;
15012 	}
15013 	if (tgt_prog) {
15014 		struct bpf_prog_aux *aux = tgt_prog->aux;
15015 
15016 		for (i = 0; i < aux->func_info_cnt; i++)
15017 			if (aux->func_info[i].type_id == btf_id) {
15018 				subprog = i;
15019 				break;
15020 			}
15021 		if (subprog == -1) {
15022 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
15023 			return -EINVAL;
15024 		}
15025 		conservative = aux->func_info_aux[subprog].unreliable;
15026 		if (prog_extension) {
15027 			if (conservative) {
15028 				bpf_log(log,
15029 					"Cannot replace static functions\n");
15030 				return -EINVAL;
15031 			}
15032 			if (!prog->jit_requested) {
15033 				bpf_log(log,
15034 					"Extension programs should be JITed\n");
15035 				return -EINVAL;
15036 			}
15037 		}
15038 		if (!tgt_prog->jited) {
15039 			bpf_log(log, "Can attach to only JITed progs\n");
15040 			return -EINVAL;
15041 		}
15042 		if (tgt_prog->type == prog->type) {
15043 			/* Cannot fentry/fexit another fentry/fexit program.
15044 			 * Cannot attach program extension to another extension.
15045 			 * It's ok to attach fentry/fexit to extension program.
15046 			 */
15047 			bpf_log(log, "Cannot recursively attach\n");
15048 			return -EINVAL;
15049 		}
15050 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
15051 		    prog_extension &&
15052 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
15053 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
15054 			/* Program extensions can extend all program types
15055 			 * except fentry/fexit. The reason is the following.
15056 			 * The fentry/fexit programs are used for performance
15057 			 * analysis, stats and can be attached to any program
15058 			 * type except themselves. When extension program is
15059 			 * replacing XDP function it is necessary to allow
15060 			 * performance analysis of all functions. Both original
15061 			 * XDP program and its program extension. Hence
15062 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
15063 			 * allowed. If extending of fentry/fexit was allowed it
15064 			 * would be possible to create long call chain
15065 			 * fentry->extension->fentry->extension beyond
15066 			 * reasonable stack size. Hence extending fentry is not
15067 			 * allowed.
15068 			 */
15069 			bpf_log(log, "Cannot extend fentry/fexit\n");
15070 			return -EINVAL;
15071 		}
15072 	} else {
15073 		if (prog_extension) {
15074 			bpf_log(log, "Cannot replace kernel functions\n");
15075 			return -EINVAL;
15076 		}
15077 	}
15078 
15079 	switch (prog->expected_attach_type) {
15080 	case BPF_TRACE_RAW_TP:
15081 		if (tgt_prog) {
15082 			bpf_log(log,
15083 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15084 			return -EINVAL;
15085 		}
15086 		if (!btf_type_is_typedef(t)) {
15087 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
15088 				btf_id);
15089 			return -EINVAL;
15090 		}
15091 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15092 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15093 				btf_id, tname);
15094 			return -EINVAL;
15095 		}
15096 		tname += sizeof(prefix) - 1;
15097 		t = btf_type_by_id(btf, t->type);
15098 		if (!btf_type_is_ptr(t))
15099 			/* should never happen in valid vmlinux build */
15100 			return -EINVAL;
15101 		t = btf_type_by_id(btf, t->type);
15102 		if (!btf_type_is_func_proto(t))
15103 			/* should never happen in valid vmlinux build */
15104 			return -EINVAL;
15105 
15106 		break;
15107 	case BPF_TRACE_ITER:
15108 		if (!btf_type_is_func(t)) {
15109 			bpf_log(log, "attach_btf_id %u is not a function\n",
15110 				btf_id);
15111 			return -EINVAL;
15112 		}
15113 		t = btf_type_by_id(btf, t->type);
15114 		if (!btf_type_is_func_proto(t))
15115 			return -EINVAL;
15116 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15117 		if (ret)
15118 			return ret;
15119 		break;
15120 	default:
15121 		if (!prog_extension)
15122 			return -EINVAL;
15123 		fallthrough;
15124 	case BPF_MODIFY_RETURN:
15125 	case BPF_LSM_MAC:
15126 	case BPF_LSM_CGROUP:
15127 	case BPF_TRACE_FENTRY:
15128 	case BPF_TRACE_FEXIT:
15129 		if (!btf_type_is_func(t)) {
15130 			bpf_log(log, "attach_btf_id %u is not a function\n",
15131 				btf_id);
15132 			return -EINVAL;
15133 		}
15134 		if (prog_extension &&
15135 		    btf_check_type_match(log, prog, btf, t))
15136 			return -EINVAL;
15137 		t = btf_type_by_id(btf, t->type);
15138 		if (!btf_type_is_func_proto(t))
15139 			return -EINVAL;
15140 
15141 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15142 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15143 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15144 			return -EINVAL;
15145 
15146 		if (tgt_prog && conservative)
15147 			t = NULL;
15148 
15149 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15150 		if (ret < 0)
15151 			return ret;
15152 
15153 		if (tgt_prog) {
15154 			if (subprog == 0)
15155 				addr = (long) tgt_prog->bpf_func;
15156 			else
15157 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15158 		} else {
15159 			addr = kallsyms_lookup_name(tname);
15160 			if (!addr) {
15161 				bpf_log(log,
15162 					"The address of function %s cannot be found\n",
15163 					tname);
15164 				return -ENOENT;
15165 			}
15166 		}
15167 
15168 		if (prog->aux->sleepable) {
15169 			ret = -EINVAL;
15170 			switch (prog->type) {
15171 			case BPF_PROG_TYPE_TRACING:
15172 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
15173 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15174 				 */
15175 				if (!check_non_sleepable_error_inject(btf_id) &&
15176 				    within_error_injection_list(addr))
15177 					ret = 0;
15178 				break;
15179 			case BPF_PROG_TYPE_LSM:
15180 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
15181 				 * Only some of them are sleepable.
15182 				 */
15183 				if (bpf_lsm_is_sleepable_hook(btf_id))
15184 					ret = 0;
15185 				break;
15186 			default:
15187 				break;
15188 			}
15189 			if (ret) {
15190 				bpf_log(log, "%s is not sleepable\n", tname);
15191 				return ret;
15192 			}
15193 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15194 			if (tgt_prog) {
15195 				bpf_log(log, "can't modify return codes of BPF programs\n");
15196 				return -EINVAL;
15197 			}
15198 			ret = check_attach_modify_return(addr, tname);
15199 			if (ret) {
15200 				bpf_log(log, "%s() is not modifiable\n", tname);
15201 				return ret;
15202 			}
15203 		}
15204 
15205 		break;
15206 	}
15207 	tgt_info->tgt_addr = addr;
15208 	tgt_info->tgt_name = tname;
15209 	tgt_info->tgt_type = t;
15210 	return 0;
15211 }
15212 
15213 BTF_SET_START(btf_id_deny)
15214 BTF_ID_UNUSED
15215 #ifdef CONFIG_SMP
15216 BTF_ID(func, migrate_disable)
15217 BTF_ID(func, migrate_enable)
15218 #endif
15219 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15220 BTF_ID(func, rcu_read_unlock_strict)
15221 #endif
15222 BTF_SET_END(btf_id_deny)
15223 
15224 static int check_attach_btf_id(struct bpf_verifier_env *env)
15225 {
15226 	struct bpf_prog *prog = env->prog;
15227 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15228 	struct bpf_attach_target_info tgt_info = {};
15229 	u32 btf_id = prog->aux->attach_btf_id;
15230 	struct bpf_trampoline *tr;
15231 	int ret;
15232 	u64 key;
15233 
15234 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15235 		if (prog->aux->sleepable)
15236 			/* attach_btf_id checked to be zero already */
15237 			return 0;
15238 		verbose(env, "Syscall programs can only be sleepable\n");
15239 		return -EINVAL;
15240 	}
15241 
15242 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15243 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15244 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15245 		return -EINVAL;
15246 	}
15247 
15248 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15249 		return check_struct_ops_btf_id(env);
15250 
15251 	if (prog->type != BPF_PROG_TYPE_TRACING &&
15252 	    prog->type != BPF_PROG_TYPE_LSM &&
15253 	    prog->type != BPF_PROG_TYPE_EXT)
15254 		return 0;
15255 
15256 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15257 	if (ret)
15258 		return ret;
15259 
15260 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15261 		/* to make freplace equivalent to their targets, they need to
15262 		 * inherit env->ops and expected_attach_type for the rest of the
15263 		 * verification
15264 		 */
15265 		env->ops = bpf_verifier_ops[tgt_prog->type];
15266 		prog->expected_attach_type = tgt_prog->expected_attach_type;
15267 	}
15268 
15269 	/* store info about the attachment target that will be used later */
15270 	prog->aux->attach_func_proto = tgt_info.tgt_type;
15271 	prog->aux->attach_func_name = tgt_info.tgt_name;
15272 
15273 	if (tgt_prog) {
15274 		prog->aux->saved_dst_prog_type = tgt_prog->type;
15275 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15276 	}
15277 
15278 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15279 		prog->aux->attach_btf_trace = true;
15280 		return 0;
15281 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15282 		if (!bpf_iter_prog_supported(prog))
15283 			return -EINVAL;
15284 		return 0;
15285 	}
15286 
15287 	if (prog->type == BPF_PROG_TYPE_LSM) {
15288 		ret = bpf_lsm_verify_prog(&env->log, prog);
15289 		if (ret < 0)
15290 			return ret;
15291 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
15292 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
15293 		return -EINVAL;
15294 	}
15295 
15296 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15297 	tr = bpf_trampoline_get(key, &tgt_info);
15298 	if (!tr)
15299 		return -ENOMEM;
15300 
15301 	prog->aux->dst_trampoline = tr;
15302 	return 0;
15303 }
15304 
15305 struct btf *bpf_get_btf_vmlinux(void)
15306 {
15307 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15308 		mutex_lock(&bpf_verifier_lock);
15309 		if (!btf_vmlinux)
15310 			btf_vmlinux = btf_parse_vmlinux();
15311 		mutex_unlock(&bpf_verifier_lock);
15312 	}
15313 	return btf_vmlinux;
15314 }
15315 
15316 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15317 {
15318 	u64 start_time = ktime_get_ns();
15319 	struct bpf_verifier_env *env;
15320 	struct bpf_verifier_log *log;
15321 	int i, len, ret = -EINVAL;
15322 	bool is_priv;
15323 
15324 	/* no program is valid */
15325 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15326 		return -EINVAL;
15327 
15328 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
15329 	 * allocate/free it every time bpf_check() is called
15330 	 */
15331 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15332 	if (!env)
15333 		return -ENOMEM;
15334 	log = &env->log;
15335 
15336 	len = (*prog)->len;
15337 	env->insn_aux_data =
15338 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15339 	ret = -ENOMEM;
15340 	if (!env->insn_aux_data)
15341 		goto err_free_env;
15342 	for (i = 0; i < len; i++)
15343 		env->insn_aux_data[i].orig_idx = i;
15344 	env->prog = *prog;
15345 	env->ops = bpf_verifier_ops[env->prog->type];
15346 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15347 	is_priv = bpf_capable();
15348 
15349 	bpf_get_btf_vmlinux();
15350 
15351 	/* grab the mutex to protect few globals used by verifier */
15352 	if (!is_priv)
15353 		mutex_lock(&bpf_verifier_lock);
15354 
15355 	if (attr->log_level || attr->log_buf || attr->log_size) {
15356 		/* user requested verbose verifier output
15357 		 * and supplied buffer to store the verification trace
15358 		 */
15359 		log->level = attr->log_level;
15360 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15361 		log->len_total = attr->log_size;
15362 
15363 		/* log attributes have to be sane */
15364 		if (!bpf_verifier_log_attr_valid(log)) {
15365 			ret = -EINVAL;
15366 			goto err_unlock;
15367 		}
15368 	}
15369 
15370 	mark_verifier_state_clean(env);
15371 
15372 	if (IS_ERR(btf_vmlinux)) {
15373 		/* Either gcc or pahole or kernel are broken. */
15374 		verbose(env, "in-kernel BTF is malformed\n");
15375 		ret = PTR_ERR(btf_vmlinux);
15376 		goto skip_full_check;
15377 	}
15378 
15379 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15380 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15381 		env->strict_alignment = true;
15382 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15383 		env->strict_alignment = false;
15384 
15385 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15386 	env->allow_uninit_stack = bpf_allow_uninit_stack();
15387 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15388 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
15389 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
15390 	env->bpf_capable = bpf_capable();
15391 
15392 	if (is_priv)
15393 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15394 
15395 	env->explored_states = kvcalloc(state_htab_size(env),
15396 				       sizeof(struct bpf_verifier_state_list *),
15397 				       GFP_USER);
15398 	ret = -ENOMEM;
15399 	if (!env->explored_states)
15400 		goto skip_full_check;
15401 
15402 	ret = add_subprog_and_kfunc(env);
15403 	if (ret < 0)
15404 		goto skip_full_check;
15405 
15406 	ret = check_subprogs(env);
15407 	if (ret < 0)
15408 		goto skip_full_check;
15409 
15410 	ret = check_btf_info(env, attr, uattr);
15411 	if (ret < 0)
15412 		goto skip_full_check;
15413 
15414 	ret = check_attach_btf_id(env);
15415 	if (ret)
15416 		goto skip_full_check;
15417 
15418 	ret = resolve_pseudo_ldimm64(env);
15419 	if (ret < 0)
15420 		goto skip_full_check;
15421 
15422 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
15423 		ret = bpf_prog_offload_verifier_prep(env->prog);
15424 		if (ret)
15425 			goto skip_full_check;
15426 	}
15427 
15428 	ret = check_cfg(env);
15429 	if (ret < 0)
15430 		goto skip_full_check;
15431 
15432 	ret = do_check_subprogs(env);
15433 	ret = ret ?: do_check_main(env);
15434 
15435 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15436 		ret = bpf_prog_offload_finalize(env);
15437 
15438 skip_full_check:
15439 	kvfree(env->explored_states);
15440 
15441 	if (ret == 0)
15442 		ret = check_max_stack_depth(env);
15443 
15444 	/* instruction rewrites happen after this point */
15445 	if (ret == 0)
15446 		ret = optimize_bpf_loop(env);
15447 
15448 	if (is_priv) {
15449 		if (ret == 0)
15450 			opt_hard_wire_dead_code_branches(env);
15451 		if (ret == 0)
15452 			ret = opt_remove_dead_code(env);
15453 		if (ret == 0)
15454 			ret = opt_remove_nops(env);
15455 	} else {
15456 		if (ret == 0)
15457 			sanitize_dead_code(env);
15458 	}
15459 
15460 	if (ret == 0)
15461 		/* program is valid, convert *(u32*)(ctx + off) accesses */
15462 		ret = convert_ctx_accesses(env);
15463 
15464 	if (ret == 0)
15465 		ret = do_misc_fixups(env);
15466 
15467 	/* do 32-bit optimization after insn patching has done so those patched
15468 	 * insns could be handled correctly.
15469 	 */
15470 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15471 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15472 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15473 								     : false;
15474 	}
15475 
15476 	if (ret == 0)
15477 		ret = fixup_call_args(env);
15478 
15479 	env->verification_time = ktime_get_ns() - start_time;
15480 	print_verification_stats(env);
15481 	env->prog->aux->verified_insns = env->insn_processed;
15482 
15483 	if (log->level && bpf_verifier_log_full(log))
15484 		ret = -ENOSPC;
15485 	if (log->level && !log->ubuf) {
15486 		ret = -EFAULT;
15487 		goto err_release_maps;
15488 	}
15489 
15490 	if (ret)
15491 		goto err_release_maps;
15492 
15493 	if (env->used_map_cnt) {
15494 		/* if program passed verifier, update used_maps in bpf_prog_info */
15495 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15496 							  sizeof(env->used_maps[0]),
15497 							  GFP_KERNEL);
15498 
15499 		if (!env->prog->aux->used_maps) {
15500 			ret = -ENOMEM;
15501 			goto err_release_maps;
15502 		}
15503 
15504 		memcpy(env->prog->aux->used_maps, env->used_maps,
15505 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
15506 		env->prog->aux->used_map_cnt = env->used_map_cnt;
15507 	}
15508 	if (env->used_btf_cnt) {
15509 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
15510 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15511 							  sizeof(env->used_btfs[0]),
15512 							  GFP_KERNEL);
15513 		if (!env->prog->aux->used_btfs) {
15514 			ret = -ENOMEM;
15515 			goto err_release_maps;
15516 		}
15517 
15518 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
15519 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15520 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15521 	}
15522 	if (env->used_map_cnt || env->used_btf_cnt) {
15523 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
15524 		 * bpf_ld_imm64 instructions
15525 		 */
15526 		convert_pseudo_ld_imm64(env);
15527 	}
15528 
15529 	adjust_btf_func(env);
15530 
15531 err_release_maps:
15532 	if (!env->prog->aux->used_maps)
15533 		/* if we didn't copy map pointers into bpf_prog_info, release
15534 		 * them now. Otherwise free_used_maps() will release them.
15535 		 */
15536 		release_maps(env);
15537 	if (!env->prog->aux->used_btfs)
15538 		release_btfs(env);
15539 
15540 	/* extension progs temporarily inherit the attach_type of their targets
15541 	   for verification purposes, so set it back to zero before returning
15542 	 */
15543 	if (env->prog->type == BPF_PROG_TYPE_EXT)
15544 		env->prog->expected_attach_type = 0;
15545 
15546 	*prog = env->prog;
15547 err_unlock:
15548 	if (!is_priv)
15549 		mutex_unlock(&bpf_verifier_lock);
15550 	vfree(env->insn_aux_data);
15551 err_free_env:
15552 	kfree(env);
15553 	return ret;
15554 }
15555