xref: /linux/kernel/bpf/verifier.c (revision 7eba4505394e21df44dcace6b5d741a8e2deea3a)
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 		return err;
6879 
6880 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6881 	if (err)
6882 		return err;
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 
6901 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6902 				   struct bpf_func_state *caller,
6903 				   struct bpf_func_state *callee)
6904 {
6905 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6906 	 *      void *callback_ctx, u64 flags);
6907 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6908 	 *      void *callback_ctx);
6909 	 */
6910 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6911 
6912 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6913 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6914 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6915 
6916 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6917 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6918 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6919 
6920 	/* pointer to stack or null */
6921 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6922 
6923 	/* unused */
6924 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6925 	return 0;
6926 }
6927 
6928 static int set_callee_state(struct bpf_verifier_env *env,
6929 			    struct bpf_func_state *caller,
6930 			    struct bpf_func_state *callee, int insn_idx)
6931 {
6932 	int i;
6933 
6934 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6935 	 * pointers, which connects us up to the liveness chain
6936 	 */
6937 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6938 		callee->regs[i] = caller->regs[i];
6939 	return 0;
6940 }
6941 
6942 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6943 			   int *insn_idx)
6944 {
6945 	int subprog, target_insn;
6946 
6947 	target_insn = *insn_idx + insn->imm + 1;
6948 	subprog = find_subprog(env, target_insn);
6949 	if (subprog < 0) {
6950 		verbose(env, "verifier bug. No program starts at insn %d\n",
6951 			target_insn);
6952 		return -EFAULT;
6953 	}
6954 
6955 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6956 }
6957 
6958 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6959 				       struct bpf_func_state *caller,
6960 				       struct bpf_func_state *callee,
6961 				       int insn_idx)
6962 {
6963 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6964 	struct bpf_map *map;
6965 	int err;
6966 
6967 	if (bpf_map_ptr_poisoned(insn_aux)) {
6968 		verbose(env, "tail_call abusing map_ptr\n");
6969 		return -EINVAL;
6970 	}
6971 
6972 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6973 	if (!map->ops->map_set_for_each_callback_args ||
6974 	    !map->ops->map_for_each_callback) {
6975 		verbose(env, "callback function not allowed for map\n");
6976 		return -ENOTSUPP;
6977 	}
6978 
6979 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6980 	if (err)
6981 		return err;
6982 
6983 	callee->in_callback_fn = true;
6984 	callee->callback_ret_range = tnum_range(0, 1);
6985 	return 0;
6986 }
6987 
6988 static int set_loop_callback_state(struct bpf_verifier_env *env,
6989 				   struct bpf_func_state *caller,
6990 				   struct bpf_func_state *callee,
6991 				   int insn_idx)
6992 {
6993 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6994 	 *	    u64 flags);
6995 	 * callback_fn(u32 index, void *callback_ctx);
6996 	 */
6997 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6998 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6999 
7000 	/* unused */
7001 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7002 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7003 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7004 
7005 	callee->in_callback_fn = true;
7006 	callee->callback_ret_range = tnum_range(0, 1);
7007 	return 0;
7008 }
7009 
7010 static int set_timer_callback_state(struct bpf_verifier_env *env,
7011 				    struct bpf_func_state *caller,
7012 				    struct bpf_func_state *callee,
7013 				    int insn_idx)
7014 {
7015 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7016 
7017 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7018 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7019 	 */
7020 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7021 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7022 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7023 
7024 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7025 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7026 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7027 
7028 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7029 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7030 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7031 
7032 	/* unused */
7033 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7034 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7035 	callee->in_async_callback_fn = true;
7036 	callee->callback_ret_range = tnum_range(0, 1);
7037 	return 0;
7038 }
7039 
7040 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7041 				       struct bpf_func_state *caller,
7042 				       struct bpf_func_state *callee,
7043 				       int insn_idx)
7044 {
7045 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7046 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7047 	 * (callback_fn)(struct task_struct *task,
7048 	 *               struct vm_area_struct *vma, void *callback_ctx);
7049 	 */
7050 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7051 
7052 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7053 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7054 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7055 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7056 
7057 	/* pointer to stack or null */
7058 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7059 
7060 	/* unused */
7061 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7062 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7063 	callee->in_callback_fn = true;
7064 	callee->callback_ret_range = tnum_range(0, 1);
7065 	return 0;
7066 }
7067 
7068 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7069 					   struct bpf_func_state *caller,
7070 					   struct bpf_func_state *callee,
7071 					   int insn_idx)
7072 {
7073 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7074 	 *			  callback_ctx, u64 flags);
7075 	 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7076 	 */
7077 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7078 	callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7079 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7080 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7081 
7082 	/* unused */
7083 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7084 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7085 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7086 
7087 	callee->in_callback_fn = true;
7088 	callee->callback_ret_range = tnum_range(0, 1);
7089 	return 0;
7090 }
7091 
7092 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7093 {
7094 	struct bpf_verifier_state *state = env->cur_state;
7095 	struct bpf_func_state *caller, *callee;
7096 	struct bpf_reg_state *r0;
7097 	int err;
7098 
7099 	callee = state->frame[state->curframe];
7100 	r0 = &callee->regs[BPF_REG_0];
7101 	if (r0->type == PTR_TO_STACK) {
7102 		/* technically it's ok to return caller's stack pointer
7103 		 * (or caller's caller's pointer) back to the caller,
7104 		 * since these pointers are valid. Only current stack
7105 		 * pointer will be invalid as soon as function exits,
7106 		 * but let's be conservative
7107 		 */
7108 		verbose(env, "cannot return stack pointer to the caller\n");
7109 		return -EINVAL;
7110 	}
7111 
7112 	state->curframe--;
7113 	caller = state->frame[state->curframe];
7114 	if (callee->in_callback_fn) {
7115 		/* enforce R0 return value range [0, 1]. */
7116 		struct tnum range = callee->callback_ret_range;
7117 
7118 		if (r0->type != SCALAR_VALUE) {
7119 			verbose(env, "R0 not a scalar value\n");
7120 			return -EACCES;
7121 		}
7122 		if (!tnum_in(range, r0->var_off)) {
7123 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7124 			return -EINVAL;
7125 		}
7126 	} else {
7127 		/* return to the caller whatever r0 had in the callee */
7128 		caller->regs[BPF_REG_0] = *r0;
7129 	}
7130 
7131 	/* callback_fn frame should have released its own additions to parent's
7132 	 * reference state at this point, or check_reference_leak would
7133 	 * complain, hence it must be the same as the caller. There is no need
7134 	 * to copy it back.
7135 	 */
7136 	if (!callee->in_callback_fn) {
7137 		/* Transfer references to the caller */
7138 		err = copy_reference_state(caller, callee);
7139 		if (err)
7140 			return err;
7141 	}
7142 
7143 	*insn_idx = callee->callsite + 1;
7144 	if (env->log.level & BPF_LOG_LEVEL) {
7145 		verbose(env, "returning from callee:\n");
7146 		print_verifier_state(env, callee, true);
7147 		verbose(env, "to caller at %d:\n", *insn_idx);
7148 		print_verifier_state(env, caller, true);
7149 	}
7150 	/* clear everything in the callee */
7151 	free_func_state(callee);
7152 	state->frame[state->curframe + 1] = NULL;
7153 	return 0;
7154 }
7155 
7156 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7157 				   int func_id,
7158 				   struct bpf_call_arg_meta *meta)
7159 {
7160 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7161 
7162 	if (ret_type != RET_INTEGER ||
7163 	    (func_id != BPF_FUNC_get_stack &&
7164 	     func_id != BPF_FUNC_get_task_stack &&
7165 	     func_id != BPF_FUNC_probe_read_str &&
7166 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7167 	     func_id != BPF_FUNC_probe_read_user_str))
7168 		return;
7169 
7170 	ret_reg->smax_value = meta->msize_max_value;
7171 	ret_reg->s32_max_value = meta->msize_max_value;
7172 	ret_reg->smin_value = -MAX_ERRNO;
7173 	ret_reg->s32_min_value = -MAX_ERRNO;
7174 	reg_bounds_sync(ret_reg);
7175 }
7176 
7177 static int
7178 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7179 		int func_id, int insn_idx)
7180 {
7181 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7182 	struct bpf_map *map = meta->map_ptr;
7183 
7184 	if (func_id != BPF_FUNC_tail_call &&
7185 	    func_id != BPF_FUNC_map_lookup_elem &&
7186 	    func_id != BPF_FUNC_map_update_elem &&
7187 	    func_id != BPF_FUNC_map_delete_elem &&
7188 	    func_id != BPF_FUNC_map_push_elem &&
7189 	    func_id != BPF_FUNC_map_pop_elem &&
7190 	    func_id != BPF_FUNC_map_peek_elem &&
7191 	    func_id != BPF_FUNC_for_each_map_elem &&
7192 	    func_id != BPF_FUNC_redirect_map &&
7193 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7194 		return 0;
7195 
7196 	if (map == NULL) {
7197 		verbose(env, "kernel subsystem misconfigured verifier\n");
7198 		return -EINVAL;
7199 	}
7200 
7201 	/* In case of read-only, some additional restrictions
7202 	 * need to be applied in order to prevent altering the
7203 	 * state of the map from program side.
7204 	 */
7205 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7206 	    (func_id == BPF_FUNC_map_delete_elem ||
7207 	     func_id == BPF_FUNC_map_update_elem ||
7208 	     func_id == BPF_FUNC_map_push_elem ||
7209 	     func_id == BPF_FUNC_map_pop_elem)) {
7210 		verbose(env, "write into map forbidden\n");
7211 		return -EACCES;
7212 	}
7213 
7214 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7215 		bpf_map_ptr_store(aux, meta->map_ptr,
7216 				  !meta->map_ptr->bypass_spec_v1);
7217 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7218 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7219 				  !meta->map_ptr->bypass_spec_v1);
7220 	return 0;
7221 }
7222 
7223 static int
7224 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7225 		int func_id, int insn_idx)
7226 {
7227 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7228 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7229 	struct bpf_map *map = meta->map_ptr;
7230 	u64 val, max;
7231 	int err;
7232 
7233 	if (func_id != BPF_FUNC_tail_call)
7234 		return 0;
7235 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7236 		verbose(env, "kernel subsystem misconfigured verifier\n");
7237 		return -EINVAL;
7238 	}
7239 
7240 	reg = &regs[BPF_REG_3];
7241 	val = reg->var_off.value;
7242 	max = map->max_entries;
7243 
7244 	if (!(register_is_const(reg) && val < max)) {
7245 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7246 		return 0;
7247 	}
7248 
7249 	err = mark_chain_precision(env, BPF_REG_3);
7250 	if (err)
7251 		return err;
7252 	if (bpf_map_key_unseen(aux))
7253 		bpf_map_key_store(aux, val);
7254 	else if (!bpf_map_key_poisoned(aux) &&
7255 		  bpf_map_key_immediate(aux) != val)
7256 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7257 	return 0;
7258 }
7259 
7260 static int check_reference_leak(struct bpf_verifier_env *env)
7261 {
7262 	struct bpf_func_state *state = cur_func(env);
7263 	bool refs_lingering = false;
7264 	int i;
7265 
7266 	if (state->frameno && !state->in_callback_fn)
7267 		return 0;
7268 
7269 	for (i = 0; i < state->acquired_refs; i++) {
7270 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7271 			continue;
7272 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7273 			state->refs[i].id, state->refs[i].insn_idx);
7274 		refs_lingering = true;
7275 	}
7276 	return refs_lingering ? -EINVAL : 0;
7277 }
7278 
7279 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7280 				   struct bpf_reg_state *regs)
7281 {
7282 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7283 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7284 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7285 	int err, fmt_map_off, num_args;
7286 	u64 fmt_addr;
7287 	char *fmt;
7288 
7289 	/* data must be an array of u64 */
7290 	if (data_len_reg->var_off.value % 8)
7291 		return -EINVAL;
7292 	num_args = data_len_reg->var_off.value / 8;
7293 
7294 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7295 	 * and map_direct_value_addr is set.
7296 	 */
7297 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7298 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7299 						  fmt_map_off);
7300 	if (err) {
7301 		verbose(env, "verifier bug\n");
7302 		return -EFAULT;
7303 	}
7304 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7305 
7306 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7307 	 * can focus on validating the format specifiers.
7308 	 */
7309 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7310 	if (err < 0)
7311 		verbose(env, "Invalid format string\n");
7312 
7313 	return err;
7314 }
7315 
7316 static int check_get_func_ip(struct bpf_verifier_env *env)
7317 {
7318 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7319 	int func_id = BPF_FUNC_get_func_ip;
7320 
7321 	if (type == BPF_PROG_TYPE_TRACING) {
7322 		if (!bpf_prog_has_trampoline(env->prog)) {
7323 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7324 				func_id_name(func_id), func_id);
7325 			return -ENOTSUPP;
7326 		}
7327 		return 0;
7328 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7329 		return 0;
7330 	}
7331 
7332 	verbose(env, "func %s#%d not supported for program type %d\n",
7333 		func_id_name(func_id), func_id, type);
7334 	return -ENOTSUPP;
7335 }
7336 
7337 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7338 {
7339 	return &env->insn_aux_data[env->insn_idx];
7340 }
7341 
7342 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7343 {
7344 	struct bpf_reg_state *regs = cur_regs(env);
7345 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7346 	bool reg_is_null = register_is_null(reg);
7347 
7348 	if (reg_is_null)
7349 		mark_chain_precision(env, BPF_REG_4);
7350 
7351 	return reg_is_null;
7352 }
7353 
7354 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7355 {
7356 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7357 
7358 	if (!state->initialized) {
7359 		state->initialized = 1;
7360 		state->fit_for_inline = loop_flag_is_zero(env);
7361 		state->callback_subprogno = subprogno;
7362 		return;
7363 	}
7364 
7365 	if (!state->fit_for_inline)
7366 		return;
7367 
7368 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7369 				 state->callback_subprogno == subprogno);
7370 }
7371 
7372 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7373 			     int *insn_idx_p)
7374 {
7375 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7376 	const struct bpf_func_proto *fn = NULL;
7377 	enum bpf_return_type ret_type;
7378 	enum bpf_type_flag ret_flag;
7379 	struct bpf_reg_state *regs;
7380 	struct bpf_call_arg_meta meta;
7381 	int insn_idx = *insn_idx_p;
7382 	bool changes_data;
7383 	int i, err, func_id;
7384 
7385 	/* find function prototype */
7386 	func_id = insn->imm;
7387 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7388 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7389 			func_id);
7390 		return -EINVAL;
7391 	}
7392 
7393 	if (env->ops->get_func_proto)
7394 		fn = env->ops->get_func_proto(func_id, env->prog);
7395 	if (!fn) {
7396 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7397 			func_id);
7398 		return -EINVAL;
7399 	}
7400 
7401 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7402 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7403 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7404 		return -EINVAL;
7405 	}
7406 
7407 	if (fn->allowed && !fn->allowed(env->prog)) {
7408 		verbose(env, "helper call is not allowed in probe\n");
7409 		return -EINVAL;
7410 	}
7411 
7412 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7413 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7414 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7415 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7416 			func_id_name(func_id), func_id);
7417 		return -EINVAL;
7418 	}
7419 
7420 	memset(&meta, 0, sizeof(meta));
7421 	meta.pkt_access = fn->pkt_access;
7422 
7423 	err = check_func_proto(fn, func_id);
7424 	if (err) {
7425 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7426 			func_id_name(func_id), func_id);
7427 		return err;
7428 	}
7429 
7430 	meta.func_id = func_id;
7431 	/* check args */
7432 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7433 		err = check_func_arg(env, i, &meta, fn);
7434 		if (err)
7435 			return err;
7436 	}
7437 
7438 	err = record_func_map(env, &meta, func_id, insn_idx);
7439 	if (err)
7440 		return err;
7441 
7442 	err = record_func_key(env, &meta, func_id, insn_idx);
7443 	if (err)
7444 		return err;
7445 
7446 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7447 	 * is inferred from register state.
7448 	 */
7449 	for (i = 0; i < meta.access_size; i++) {
7450 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7451 				       BPF_WRITE, -1, false);
7452 		if (err)
7453 			return err;
7454 	}
7455 
7456 	regs = cur_regs(env);
7457 
7458 	if (meta.uninit_dynptr_regno) {
7459 		/* we write BPF_DW bits (8 bytes) at a time */
7460 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7461 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7462 					       i, BPF_DW, BPF_WRITE, -1, false);
7463 			if (err)
7464 				return err;
7465 		}
7466 
7467 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7468 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7469 					      insn_idx);
7470 		if (err)
7471 			return err;
7472 	}
7473 
7474 	if (meta.release_regno) {
7475 		err = -EINVAL;
7476 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7477 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7478 		else if (meta.ref_obj_id)
7479 			err = release_reference(env, meta.ref_obj_id);
7480 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7481 		 * released is NULL, which must be > R0.
7482 		 */
7483 		else if (register_is_null(&regs[meta.release_regno]))
7484 			err = 0;
7485 		if (err) {
7486 			verbose(env, "func %s#%d reference has not been acquired before\n",
7487 				func_id_name(func_id), func_id);
7488 			return err;
7489 		}
7490 	}
7491 
7492 	switch (func_id) {
7493 	case BPF_FUNC_tail_call:
7494 		err = check_reference_leak(env);
7495 		if (err) {
7496 			verbose(env, "tail_call would lead to reference leak\n");
7497 			return err;
7498 		}
7499 		break;
7500 	case BPF_FUNC_get_local_storage:
7501 		/* check that flags argument in get_local_storage(map, flags) is 0,
7502 		 * this is required because get_local_storage() can't return an error.
7503 		 */
7504 		if (!register_is_null(&regs[BPF_REG_2])) {
7505 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7506 			return -EINVAL;
7507 		}
7508 		break;
7509 	case BPF_FUNC_for_each_map_elem:
7510 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7511 					set_map_elem_callback_state);
7512 		break;
7513 	case BPF_FUNC_timer_set_callback:
7514 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7515 					set_timer_callback_state);
7516 		break;
7517 	case BPF_FUNC_find_vma:
7518 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7519 					set_find_vma_callback_state);
7520 		break;
7521 	case BPF_FUNC_snprintf:
7522 		err = check_bpf_snprintf_call(env, regs);
7523 		break;
7524 	case BPF_FUNC_loop:
7525 		update_loop_inline_state(env, meta.subprogno);
7526 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7527 					set_loop_callback_state);
7528 		break;
7529 	case BPF_FUNC_dynptr_from_mem:
7530 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7531 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7532 				reg_type_str(env, regs[BPF_REG_1].type));
7533 			return -EACCES;
7534 		}
7535 		break;
7536 	case BPF_FUNC_set_retval:
7537 		if (prog_type == BPF_PROG_TYPE_LSM &&
7538 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7539 			if (!env->prog->aux->attach_func_proto->type) {
7540 				/* Make sure programs that attach to void
7541 				 * hooks don't try to modify return value.
7542 				 */
7543 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7544 				return -EINVAL;
7545 			}
7546 		}
7547 		break;
7548 	case BPF_FUNC_dynptr_data:
7549 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7550 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7551 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7552 
7553 				if (meta.ref_obj_id) {
7554 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7555 					return -EFAULT;
7556 				}
7557 
7558 				if (base_type(reg->type) != PTR_TO_DYNPTR)
7559 					/* Find the id of the dynptr we're
7560 					 * tracking the reference of
7561 					 */
7562 					meta.ref_obj_id = stack_slot_get_id(env, reg);
7563 				break;
7564 			}
7565 		}
7566 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7567 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7568 			return -EFAULT;
7569 		}
7570 		break;
7571 	case BPF_FUNC_user_ringbuf_drain:
7572 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7573 					set_user_ringbuf_callback_state);
7574 		break;
7575 	}
7576 
7577 	if (err)
7578 		return err;
7579 
7580 	/* reset caller saved regs */
7581 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7582 		mark_reg_not_init(env, regs, caller_saved[i]);
7583 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7584 	}
7585 
7586 	/* helper call returns 64-bit value. */
7587 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7588 
7589 	/* update return register (already marked as written above) */
7590 	ret_type = fn->ret_type;
7591 	ret_flag = type_flag(ret_type);
7592 
7593 	switch (base_type(ret_type)) {
7594 	case RET_INTEGER:
7595 		/* sets type to SCALAR_VALUE */
7596 		mark_reg_unknown(env, regs, BPF_REG_0);
7597 		break;
7598 	case RET_VOID:
7599 		regs[BPF_REG_0].type = NOT_INIT;
7600 		break;
7601 	case RET_PTR_TO_MAP_VALUE:
7602 		/* There is no offset yet applied, variable or fixed */
7603 		mark_reg_known_zero(env, regs, BPF_REG_0);
7604 		/* remember map_ptr, so that check_map_access()
7605 		 * can check 'value_size' boundary of memory access
7606 		 * to map element returned from bpf_map_lookup_elem()
7607 		 */
7608 		if (meta.map_ptr == NULL) {
7609 			verbose(env,
7610 				"kernel subsystem misconfigured verifier\n");
7611 			return -EINVAL;
7612 		}
7613 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7614 		regs[BPF_REG_0].map_uid = meta.map_uid;
7615 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7616 		if (!type_may_be_null(ret_type) &&
7617 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7618 			regs[BPF_REG_0].id = ++env->id_gen;
7619 		}
7620 		break;
7621 	case RET_PTR_TO_SOCKET:
7622 		mark_reg_known_zero(env, regs, BPF_REG_0);
7623 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7624 		break;
7625 	case RET_PTR_TO_SOCK_COMMON:
7626 		mark_reg_known_zero(env, regs, BPF_REG_0);
7627 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7628 		break;
7629 	case RET_PTR_TO_TCP_SOCK:
7630 		mark_reg_known_zero(env, regs, BPF_REG_0);
7631 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7632 		break;
7633 	case RET_PTR_TO_ALLOC_MEM:
7634 		mark_reg_known_zero(env, regs, BPF_REG_0);
7635 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7636 		regs[BPF_REG_0].mem_size = meta.mem_size;
7637 		break;
7638 	case RET_PTR_TO_MEM_OR_BTF_ID:
7639 	{
7640 		const struct btf_type *t;
7641 
7642 		mark_reg_known_zero(env, regs, BPF_REG_0);
7643 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7644 		if (!btf_type_is_struct(t)) {
7645 			u32 tsize;
7646 			const struct btf_type *ret;
7647 			const char *tname;
7648 
7649 			/* resolve the type size of ksym. */
7650 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7651 			if (IS_ERR(ret)) {
7652 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7653 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7654 					tname, PTR_ERR(ret));
7655 				return -EINVAL;
7656 			}
7657 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7658 			regs[BPF_REG_0].mem_size = tsize;
7659 		} else {
7660 			/* MEM_RDONLY may be carried from ret_flag, but it
7661 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7662 			 * it will confuse the check of PTR_TO_BTF_ID in
7663 			 * check_mem_access().
7664 			 */
7665 			ret_flag &= ~MEM_RDONLY;
7666 
7667 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7668 			regs[BPF_REG_0].btf = meta.ret_btf;
7669 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7670 		}
7671 		break;
7672 	}
7673 	case RET_PTR_TO_BTF_ID:
7674 	{
7675 		struct btf *ret_btf;
7676 		int ret_btf_id;
7677 
7678 		mark_reg_known_zero(env, regs, BPF_REG_0);
7679 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7680 		if (func_id == BPF_FUNC_kptr_xchg) {
7681 			ret_btf = meta.kptr_field->kptr.btf;
7682 			ret_btf_id = meta.kptr_field->kptr.btf_id;
7683 		} else {
7684 			if (fn->ret_btf_id == BPF_PTR_POISON) {
7685 				verbose(env, "verifier internal error:");
7686 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7687 					func_id_name(func_id));
7688 				return -EINVAL;
7689 			}
7690 			ret_btf = btf_vmlinux;
7691 			ret_btf_id = *fn->ret_btf_id;
7692 		}
7693 		if (ret_btf_id == 0) {
7694 			verbose(env, "invalid return type %u of func %s#%d\n",
7695 				base_type(ret_type), func_id_name(func_id),
7696 				func_id);
7697 			return -EINVAL;
7698 		}
7699 		regs[BPF_REG_0].btf = ret_btf;
7700 		regs[BPF_REG_0].btf_id = ret_btf_id;
7701 		break;
7702 	}
7703 	default:
7704 		verbose(env, "unknown return type %u of func %s#%d\n",
7705 			base_type(ret_type), func_id_name(func_id), func_id);
7706 		return -EINVAL;
7707 	}
7708 
7709 	if (type_may_be_null(regs[BPF_REG_0].type))
7710 		regs[BPF_REG_0].id = ++env->id_gen;
7711 
7712 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7713 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7714 			func_id_name(func_id), func_id);
7715 		return -EFAULT;
7716 	}
7717 
7718 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7719 		/* For release_reference() */
7720 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7721 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7722 		int id = acquire_reference_state(env, insn_idx);
7723 
7724 		if (id < 0)
7725 			return id;
7726 		/* For mark_ptr_or_null_reg() */
7727 		regs[BPF_REG_0].id = id;
7728 		/* For release_reference() */
7729 		regs[BPF_REG_0].ref_obj_id = id;
7730 	}
7731 
7732 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7733 
7734 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7735 	if (err)
7736 		return err;
7737 
7738 	if ((func_id == BPF_FUNC_get_stack ||
7739 	     func_id == BPF_FUNC_get_task_stack) &&
7740 	    !env->prog->has_callchain_buf) {
7741 		const char *err_str;
7742 
7743 #ifdef CONFIG_PERF_EVENTS
7744 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7745 		err_str = "cannot get callchain buffer for func %s#%d\n";
7746 #else
7747 		err = -ENOTSUPP;
7748 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7749 #endif
7750 		if (err) {
7751 			verbose(env, err_str, func_id_name(func_id), func_id);
7752 			return err;
7753 		}
7754 
7755 		env->prog->has_callchain_buf = true;
7756 	}
7757 
7758 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7759 		env->prog->call_get_stack = true;
7760 
7761 	if (func_id == BPF_FUNC_get_func_ip) {
7762 		if (check_get_func_ip(env))
7763 			return -ENOTSUPP;
7764 		env->prog->call_get_func_ip = true;
7765 	}
7766 
7767 	if (changes_data)
7768 		clear_all_pkt_pointers(env);
7769 	return 0;
7770 }
7771 
7772 /* mark_btf_func_reg_size() is used when the reg size is determined by
7773  * the BTF func_proto's return value size and argument.
7774  */
7775 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7776 				   size_t reg_size)
7777 {
7778 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7779 
7780 	if (regno == BPF_REG_0) {
7781 		/* Function return value */
7782 		reg->live |= REG_LIVE_WRITTEN;
7783 		reg->subreg_def = reg_size == sizeof(u64) ?
7784 			DEF_NOT_SUBREG : env->insn_idx + 1;
7785 	} else {
7786 		/* Function argument */
7787 		if (reg_size == sizeof(u64)) {
7788 			mark_insn_zext(env, reg);
7789 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7790 		} else {
7791 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7792 		}
7793 	}
7794 }
7795 
7796 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7797 			    int *insn_idx_p)
7798 {
7799 	const struct btf_type *t, *func, *func_proto, *ptr_type;
7800 	struct bpf_reg_state *regs = cur_regs(env);
7801 	struct bpf_kfunc_arg_meta meta = { 0 };
7802 	const char *func_name, *ptr_type_name;
7803 	u32 i, nargs, func_id, ptr_type_id;
7804 	int err, insn_idx = *insn_idx_p;
7805 	const struct btf_param *args;
7806 	struct btf *desc_btf;
7807 	u32 *kfunc_flags;
7808 	bool acq;
7809 
7810 	/* skip for now, but return error when we find this in fixup_kfunc_call */
7811 	if (!insn->imm)
7812 		return 0;
7813 
7814 	desc_btf = find_kfunc_desc_btf(env, insn->off);
7815 	if (IS_ERR(desc_btf))
7816 		return PTR_ERR(desc_btf);
7817 
7818 	func_id = insn->imm;
7819 	func = btf_type_by_id(desc_btf, func_id);
7820 	func_name = btf_name_by_offset(desc_btf, func->name_off);
7821 	func_proto = btf_type_by_id(desc_btf, func->type);
7822 
7823 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7824 	if (!kfunc_flags) {
7825 		verbose(env, "calling kernel function %s is not allowed\n",
7826 			func_name);
7827 		return -EACCES;
7828 	}
7829 	if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7830 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7831 		return -EACCES;
7832 	}
7833 
7834 	acq = *kfunc_flags & KF_ACQUIRE;
7835 
7836 	meta.flags = *kfunc_flags;
7837 
7838 	/* Check the arguments */
7839 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7840 	if (err < 0)
7841 		return err;
7842 	/* In case of release function, we get register number of refcounted
7843 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7844 	 */
7845 	if (err) {
7846 		err = release_reference(env, regs[err].ref_obj_id);
7847 		if (err) {
7848 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7849 				func_name, func_id);
7850 			return err;
7851 		}
7852 	}
7853 
7854 	for (i = 0; i < CALLER_SAVED_REGS; i++)
7855 		mark_reg_not_init(env, regs, caller_saved[i]);
7856 
7857 	/* Check return type */
7858 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7859 
7860 	if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7861 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7862 		return -EINVAL;
7863 	}
7864 
7865 	if (btf_type_is_scalar(t)) {
7866 		mark_reg_unknown(env, regs, BPF_REG_0);
7867 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7868 	} else if (btf_type_is_ptr(t)) {
7869 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7870 						   &ptr_type_id);
7871 		if (!btf_type_is_struct(ptr_type)) {
7872 			if (!meta.r0_size) {
7873 				ptr_type_name = btf_name_by_offset(desc_btf,
7874 								   ptr_type->name_off);
7875 				verbose(env,
7876 					"kernel function %s returns pointer type %s %s is not supported\n",
7877 					func_name,
7878 					btf_type_str(ptr_type),
7879 					ptr_type_name);
7880 				return -EINVAL;
7881 			}
7882 
7883 			mark_reg_known_zero(env, regs, BPF_REG_0);
7884 			regs[BPF_REG_0].type = PTR_TO_MEM;
7885 			regs[BPF_REG_0].mem_size = meta.r0_size;
7886 
7887 			if (meta.r0_rdonly)
7888 				regs[BPF_REG_0].type |= MEM_RDONLY;
7889 
7890 			/* Ensures we don't access the memory after a release_reference() */
7891 			if (meta.ref_obj_id)
7892 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7893 		} else {
7894 			mark_reg_known_zero(env, regs, BPF_REG_0);
7895 			regs[BPF_REG_0].btf = desc_btf;
7896 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7897 			regs[BPF_REG_0].btf_id = ptr_type_id;
7898 		}
7899 		if (*kfunc_flags & KF_RET_NULL) {
7900 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7901 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7902 			regs[BPF_REG_0].id = ++env->id_gen;
7903 		}
7904 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7905 		if (acq) {
7906 			int id = acquire_reference_state(env, insn_idx);
7907 
7908 			if (id < 0)
7909 				return id;
7910 			regs[BPF_REG_0].id = id;
7911 			regs[BPF_REG_0].ref_obj_id = id;
7912 		}
7913 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7914 
7915 	nargs = btf_type_vlen(func_proto);
7916 	args = (const struct btf_param *)(func_proto + 1);
7917 	for (i = 0; i < nargs; i++) {
7918 		u32 regno = i + 1;
7919 
7920 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7921 		if (btf_type_is_ptr(t))
7922 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7923 		else
7924 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7925 			mark_btf_func_reg_size(env, regno, t->size);
7926 	}
7927 
7928 	return 0;
7929 }
7930 
7931 static bool signed_add_overflows(s64 a, s64 b)
7932 {
7933 	/* Do the add in u64, where overflow is well-defined */
7934 	s64 res = (s64)((u64)a + (u64)b);
7935 
7936 	if (b < 0)
7937 		return res > a;
7938 	return res < a;
7939 }
7940 
7941 static bool signed_add32_overflows(s32 a, s32 b)
7942 {
7943 	/* Do the add in u32, where overflow is well-defined */
7944 	s32 res = (s32)((u32)a + (u32)b);
7945 
7946 	if (b < 0)
7947 		return res > a;
7948 	return res < a;
7949 }
7950 
7951 static bool signed_sub_overflows(s64 a, s64 b)
7952 {
7953 	/* Do the sub in u64, where overflow is well-defined */
7954 	s64 res = (s64)((u64)a - (u64)b);
7955 
7956 	if (b < 0)
7957 		return res < a;
7958 	return res > a;
7959 }
7960 
7961 static bool signed_sub32_overflows(s32 a, s32 b)
7962 {
7963 	/* Do the sub in u32, where overflow is well-defined */
7964 	s32 res = (s32)((u32)a - (u32)b);
7965 
7966 	if (b < 0)
7967 		return res < a;
7968 	return res > a;
7969 }
7970 
7971 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7972 				  const struct bpf_reg_state *reg,
7973 				  enum bpf_reg_type type)
7974 {
7975 	bool known = tnum_is_const(reg->var_off);
7976 	s64 val = reg->var_off.value;
7977 	s64 smin = reg->smin_value;
7978 
7979 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7980 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7981 			reg_type_str(env, type), val);
7982 		return false;
7983 	}
7984 
7985 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7986 		verbose(env, "%s pointer offset %d is not allowed\n",
7987 			reg_type_str(env, type), reg->off);
7988 		return false;
7989 	}
7990 
7991 	if (smin == S64_MIN) {
7992 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7993 			reg_type_str(env, type));
7994 		return false;
7995 	}
7996 
7997 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7998 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
7999 			smin, reg_type_str(env, type));
8000 		return false;
8001 	}
8002 
8003 	return true;
8004 }
8005 
8006 enum {
8007 	REASON_BOUNDS	= -1,
8008 	REASON_TYPE	= -2,
8009 	REASON_PATHS	= -3,
8010 	REASON_LIMIT	= -4,
8011 	REASON_STACK	= -5,
8012 };
8013 
8014 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
8015 			      u32 *alu_limit, bool mask_to_left)
8016 {
8017 	u32 max = 0, ptr_limit = 0;
8018 
8019 	switch (ptr_reg->type) {
8020 	case PTR_TO_STACK:
8021 		/* Offset 0 is out-of-bounds, but acceptable start for the
8022 		 * left direction, see BPF_REG_FP. Also, unknown scalar
8023 		 * offset where we would need to deal with min/max bounds is
8024 		 * currently prohibited for unprivileged.
8025 		 */
8026 		max = MAX_BPF_STACK + mask_to_left;
8027 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
8028 		break;
8029 	case PTR_TO_MAP_VALUE:
8030 		max = ptr_reg->map_ptr->value_size;
8031 		ptr_limit = (mask_to_left ?
8032 			     ptr_reg->smin_value :
8033 			     ptr_reg->umax_value) + ptr_reg->off;
8034 		break;
8035 	default:
8036 		return REASON_TYPE;
8037 	}
8038 
8039 	if (ptr_limit >= max)
8040 		return REASON_LIMIT;
8041 	*alu_limit = ptr_limit;
8042 	return 0;
8043 }
8044 
8045 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
8046 				    const struct bpf_insn *insn)
8047 {
8048 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
8049 }
8050 
8051 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
8052 				       u32 alu_state, u32 alu_limit)
8053 {
8054 	/* If we arrived here from different branches with different
8055 	 * state or limits to sanitize, then this won't work.
8056 	 */
8057 	if (aux->alu_state &&
8058 	    (aux->alu_state != alu_state ||
8059 	     aux->alu_limit != alu_limit))
8060 		return REASON_PATHS;
8061 
8062 	/* Corresponding fixup done in do_misc_fixups(). */
8063 	aux->alu_state = alu_state;
8064 	aux->alu_limit = alu_limit;
8065 	return 0;
8066 }
8067 
8068 static int sanitize_val_alu(struct bpf_verifier_env *env,
8069 			    struct bpf_insn *insn)
8070 {
8071 	struct bpf_insn_aux_data *aux = cur_aux(env);
8072 
8073 	if (can_skip_alu_sanitation(env, insn))
8074 		return 0;
8075 
8076 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8077 }
8078 
8079 static bool sanitize_needed(u8 opcode)
8080 {
8081 	return opcode == BPF_ADD || opcode == BPF_SUB;
8082 }
8083 
8084 struct bpf_sanitize_info {
8085 	struct bpf_insn_aux_data aux;
8086 	bool mask_to_left;
8087 };
8088 
8089 static struct bpf_verifier_state *
8090 sanitize_speculative_path(struct bpf_verifier_env *env,
8091 			  const struct bpf_insn *insn,
8092 			  u32 next_idx, u32 curr_idx)
8093 {
8094 	struct bpf_verifier_state *branch;
8095 	struct bpf_reg_state *regs;
8096 
8097 	branch = push_stack(env, next_idx, curr_idx, true);
8098 	if (branch && insn) {
8099 		regs = branch->frame[branch->curframe]->regs;
8100 		if (BPF_SRC(insn->code) == BPF_K) {
8101 			mark_reg_unknown(env, regs, insn->dst_reg);
8102 		} else if (BPF_SRC(insn->code) == BPF_X) {
8103 			mark_reg_unknown(env, regs, insn->dst_reg);
8104 			mark_reg_unknown(env, regs, insn->src_reg);
8105 		}
8106 	}
8107 	return branch;
8108 }
8109 
8110 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8111 			    struct bpf_insn *insn,
8112 			    const struct bpf_reg_state *ptr_reg,
8113 			    const struct bpf_reg_state *off_reg,
8114 			    struct bpf_reg_state *dst_reg,
8115 			    struct bpf_sanitize_info *info,
8116 			    const bool commit_window)
8117 {
8118 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8119 	struct bpf_verifier_state *vstate = env->cur_state;
8120 	bool off_is_imm = tnum_is_const(off_reg->var_off);
8121 	bool off_is_neg = off_reg->smin_value < 0;
8122 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
8123 	u8 opcode = BPF_OP(insn->code);
8124 	u32 alu_state, alu_limit;
8125 	struct bpf_reg_state tmp;
8126 	bool ret;
8127 	int err;
8128 
8129 	if (can_skip_alu_sanitation(env, insn))
8130 		return 0;
8131 
8132 	/* We already marked aux for masking from non-speculative
8133 	 * paths, thus we got here in the first place. We only care
8134 	 * to explore bad access from here.
8135 	 */
8136 	if (vstate->speculative)
8137 		goto do_sim;
8138 
8139 	if (!commit_window) {
8140 		if (!tnum_is_const(off_reg->var_off) &&
8141 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8142 			return REASON_BOUNDS;
8143 
8144 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8145 				     (opcode == BPF_SUB && !off_is_neg);
8146 	}
8147 
8148 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8149 	if (err < 0)
8150 		return err;
8151 
8152 	if (commit_window) {
8153 		/* In commit phase we narrow the masking window based on
8154 		 * the observed pointer move after the simulated operation.
8155 		 */
8156 		alu_state = info->aux.alu_state;
8157 		alu_limit = abs(info->aux.alu_limit - alu_limit);
8158 	} else {
8159 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8160 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8161 		alu_state |= ptr_is_dst_reg ?
8162 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8163 
8164 		/* Limit pruning on unknown scalars to enable deep search for
8165 		 * potential masking differences from other program paths.
8166 		 */
8167 		if (!off_is_imm)
8168 			env->explore_alu_limits = true;
8169 	}
8170 
8171 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8172 	if (err < 0)
8173 		return err;
8174 do_sim:
8175 	/* If we're in commit phase, we're done here given we already
8176 	 * pushed the truncated dst_reg into the speculative verification
8177 	 * stack.
8178 	 *
8179 	 * Also, when register is a known constant, we rewrite register-based
8180 	 * operation to immediate-based, and thus do not need masking (and as
8181 	 * a consequence, do not need to simulate the zero-truncation either).
8182 	 */
8183 	if (commit_window || off_is_imm)
8184 		return 0;
8185 
8186 	/* Simulate and find potential out-of-bounds access under
8187 	 * speculative execution from truncation as a result of
8188 	 * masking when off was not within expected range. If off
8189 	 * sits in dst, then we temporarily need to move ptr there
8190 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8191 	 * for cases where we use K-based arithmetic in one direction
8192 	 * and truncated reg-based in the other in order to explore
8193 	 * bad access.
8194 	 */
8195 	if (!ptr_is_dst_reg) {
8196 		tmp = *dst_reg;
8197 		*dst_reg = *ptr_reg;
8198 	}
8199 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8200 					env->insn_idx);
8201 	if (!ptr_is_dst_reg && ret)
8202 		*dst_reg = tmp;
8203 	return !ret ? REASON_STACK : 0;
8204 }
8205 
8206 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8207 {
8208 	struct bpf_verifier_state *vstate = env->cur_state;
8209 
8210 	/* If we simulate paths under speculation, we don't update the
8211 	 * insn as 'seen' such that when we verify unreachable paths in
8212 	 * the non-speculative domain, sanitize_dead_code() can still
8213 	 * rewrite/sanitize them.
8214 	 */
8215 	if (!vstate->speculative)
8216 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8217 }
8218 
8219 static int sanitize_err(struct bpf_verifier_env *env,
8220 			const struct bpf_insn *insn, int reason,
8221 			const struct bpf_reg_state *off_reg,
8222 			const struct bpf_reg_state *dst_reg)
8223 {
8224 	static const char *err = "pointer arithmetic with it prohibited for !root";
8225 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8226 	u32 dst = insn->dst_reg, src = insn->src_reg;
8227 
8228 	switch (reason) {
8229 	case REASON_BOUNDS:
8230 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8231 			off_reg == dst_reg ? dst : src, err);
8232 		break;
8233 	case REASON_TYPE:
8234 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8235 			off_reg == dst_reg ? src : dst, err);
8236 		break;
8237 	case REASON_PATHS:
8238 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8239 			dst, op, err);
8240 		break;
8241 	case REASON_LIMIT:
8242 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8243 			dst, op, err);
8244 		break;
8245 	case REASON_STACK:
8246 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8247 			dst, err);
8248 		break;
8249 	default:
8250 		verbose(env, "verifier internal error: unknown reason (%d)\n",
8251 			reason);
8252 		break;
8253 	}
8254 
8255 	return -EACCES;
8256 }
8257 
8258 /* check that stack access falls within stack limits and that 'reg' doesn't
8259  * have a variable offset.
8260  *
8261  * Variable offset is prohibited for unprivileged mode for simplicity since it
8262  * requires corresponding support in Spectre masking for stack ALU.  See also
8263  * retrieve_ptr_limit().
8264  *
8265  *
8266  * 'off' includes 'reg->off'.
8267  */
8268 static int check_stack_access_for_ptr_arithmetic(
8269 				struct bpf_verifier_env *env,
8270 				int regno,
8271 				const struct bpf_reg_state *reg,
8272 				int off)
8273 {
8274 	if (!tnum_is_const(reg->var_off)) {
8275 		char tn_buf[48];
8276 
8277 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8278 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8279 			regno, tn_buf, off);
8280 		return -EACCES;
8281 	}
8282 
8283 	if (off >= 0 || off < -MAX_BPF_STACK) {
8284 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
8285 			"prohibited for !root; off=%d\n", regno, off);
8286 		return -EACCES;
8287 	}
8288 
8289 	return 0;
8290 }
8291 
8292 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8293 				 const struct bpf_insn *insn,
8294 				 const struct bpf_reg_state *dst_reg)
8295 {
8296 	u32 dst = insn->dst_reg;
8297 
8298 	/* For unprivileged we require that resulting offset must be in bounds
8299 	 * in order to be able to sanitize access later on.
8300 	 */
8301 	if (env->bypass_spec_v1)
8302 		return 0;
8303 
8304 	switch (dst_reg->type) {
8305 	case PTR_TO_STACK:
8306 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8307 					dst_reg->off + dst_reg->var_off.value))
8308 			return -EACCES;
8309 		break;
8310 	case PTR_TO_MAP_VALUE:
8311 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8312 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8313 				"prohibited for !root\n", dst);
8314 			return -EACCES;
8315 		}
8316 		break;
8317 	default:
8318 		break;
8319 	}
8320 
8321 	return 0;
8322 }
8323 
8324 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8325  * Caller should also handle BPF_MOV case separately.
8326  * If we return -EACCES, caller may want to try again treating pointer as a
8327  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8328  */
8329 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8330 				   struct bpf_insn *insn,
8331 				   const struct bpf_reg_state *ptr_reg,
8332 				   const struct bpf_reg_state *off_reg)
8333 {
8334 	struct bpf_verifier_state *vstate = env->cur_state;
8335 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8336 	struct bpf_reg_state *regs = state->regs, *dst_reg;
8337 	bool known = tnum_is_const(off_reg->var_off);
8338 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8339 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8340 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8341 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8342 	struct bpf_sanitize_info info = {};
8343 	u8 opcode = BPF_OP(insn->code);
8344 	u32 dst = insn->dst_reg;
8345 	int ret;
8346 
8347 	dst_reg = &regs[dst];
8348 
8349 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8350 	    smin_val > smax_val || umin_val > umax_val) {
8351 		/* Taint dst register if offset had invalid bounds derived from
8352 		 * e.g. dead branches.
8353 		 */
8354 		__mark_reg_unknown(env, dst_reg);
8355 		return 0;
8356 	}
8357 
8358 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
8359 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
8360 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8361 			__mark_reg_unknown(env, dst_reg);
8362 			return 0;
8363 		}
8364 
8365 		verbose(env,
8366 			"R%d 32-bit pointer arithmetic prohibited\n",
8367 			dst);
8368 		return -EACCES;
8369 	}
8370 
8371 	if (ptr_reg->type & PTR_MAYBE_NULL) {
8372 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8373 			dst, reg_type_str(env, ptr_reg->type));
8374 		return -EACCES;
8375 	}
8376 
8377 	switch (base_type(ptr_reg->type)) {
8378 	case CONST_PTR_TO_MAP:
8379 		/* smin_val represents the known value */
8380 		if (known && smin_val == 0 && opcode == BPF_ADD)
8381 			break;
8382 		fallthrough;
8383 	case PTR_TO_PACKET_END:
8384 	case PTR_TO_SOCKET:
8385 	case PTR_TO_SOCK_COMMON:
8386 	case PTR_TO_TCP_SOCK:
8387 	case PTR_TO_XDP_SOCK:
8388 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8389 			dst, reg_type_str(env, ptr_reg->type));
8390 		return -EACCES;
8391 	default:
8392 		break;
8393 	}
8394 
8395 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8396 	 * The id may be overwritten later if we create a new variable offset.
8397 	 */
8398 	dst_reg->type = ptr_reg->type;
8399 	dst_reg->id = ptr_reg->id;
8400 
8401 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8402 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8403 		return -EINVAL;
8404 
8405 	/* pointer types do not carry 32-bit bounds at the moment. */
8406 	__mark_reg32_unbounded(dst_reg);
8407 
8408 	if (sanitize_needed(opcode)) {
8409 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8410 				       &info, false);
8411 		if (ret < 0)
8412 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8413 	}
8414 
8415 	switch (opcode) {
8416 	case BPF_ADD:
8417 		/* We can take a fixed offset as long as it doesn't overflow
8418 		 * the s32 'off' field
8419 		 */
8420 		if (known && (ptr_reg->off + smin_val ==
8421 			      (s64)(s32)(ptr_reg->off + smin_val))) {
8422 			/* pointer += K.  Accumulate it into fixed offset */
8423 			dst_reg->smin_value = smin_ptr;
8424 			dst_reg->smax_value = smax_ptr;
8425 			dst_reg->umin_value = umin_ptr;
8426 			dst_reg->umax_value = umax_ptr;
8427 			dst_reg->var_off = ptr_reg->var_off;
8428 			dst_reg->off = ptr_reg->off + smin_val;
8429 			dst_reg->raw = ptr_reg->raw;
8430 			break;
8431 		}
8432 		/* A new variable offset is created.  Note that off_reg->off
8433 		 * == 0, since it's a scalar.
8434 		 * dst_reg gets the pointer type and since some positive
8435 		 * integer value was added to the pointer, give it a new 'id'
8436 		 * if it's a PTR_TO_PACKET.
8437 		 * this creates a new 'base' pointer, off_reg (variable) gets
8438 		 * added into the variable offset, and we copy the fixed offset
8439 		 * from ptr_reg.
8440 		 */
8441 		if (signed_add_overflows(smin_ptr, smin_val) ||
8442 		    signed_add_overflows(smax_ptr, smax_val)) {
8443 			dst_reg->smin_value = S64_MIN;
8444 			dst_reg->smax_value = S64_MAX;
8445 		} else {
8446 			dst_reg->smin_value = smin_ptr + smin_val;
8447 			dst_reg->smax_value = smax_ptr + smax_val;
8448 		}
8449 		if (umin_ptr + umin_val < umin_ptr ||
8450 		    umax_ptr + umax_val < umax_ptr) {
8451 			dst_reg->umin_value = 0;
8452 			dst_reg->umax_value = U64_MAX;
8453 		} else {
8454 			dst_reg->umin_value = umin_ptr + umin_val;
8455 			dst_reg->umax_value = umax_ptr + umax_val;
8456 		}
8457 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8458 		dst_reg->off = ptr_reg->off;
8459 		dst_reg->raw = ptr_reg->raw;
8460 		if (reg_is_pkt_pointer(ptr_reg)) {
8461 			dst_reg->id = ++env->id_gen;
8462 			/* something was added to pkt_ptr, set range to zero */
8463 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8464 		}
8465 		break;
8466 	case BPF_SUB:
8467 		if (dst_reg == off_reg) {
8468 			/* scalar -= pointer.  Creates an unknown scalar */
8469 			verbose(env, "R%d tried to subtract pointer from scalar\n",
8470 				dst);
8471 			return -EACCES;
8472 		}
8473 		/* We don't allow subtraction from FP, because (according to
8474 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
8475 		 * be able to deal with it.
8476 		 */
8477 		if (ptr_reg->type == PTR_TO_STACK) {
8478 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
8479 				dst);
8480 			return -EACCES;
8481 		}
8482 		if (known && (ptr_reg->off - smin_val ==
8483 			      (s64)(s32)(ptr_reg->off - smin_val))) {
8484 			/* pointer -= K.  Subtract it from fixed offset */
8485 			dst_reg->smin_value = smin_ptr;
8486 			dst_reg->smax_value = smax_ptr;
8487 			dst_reg->umin_value = umin_ptr;
8488 			dst_reg->umax_value = umax_ptr;
8489 			dst_reg->var_off = ptr_reg->var_off;
8490 			dst_reg->id = ptr_reg->id;
8491 			dst_reg->off = ptr_reg->off - smin_val;
8492 			dst_reg->raw = ptr_reg->raw;
8493 			break;
8494 		}
8495 		/* A new variable offset is created.  If the subtrahend is known
8496 		 * nonnegative, then any reg->range we had before is still good.
8497 		 */
8498 		if (signed_sub_overflows(smin_ptr, smax_val) ||
8499 		    signed_sub_overflows(smax_ptr, smin_val)) {
8500 			/* Overflow possible, we know nothing */
8501 			dst_reg->smin_value = S64_MIN;
8502 			dst_reg->smax_value = S64_MAX;
8503 		} else {
8504 			dst_reg->smin_value = smin_ptr - smax_val;
8505 			dst_reg->smax_value = smax_ptr - smin_val;
8506 		}
8507 		if (umin_ptr < umax_val) {
8508 			/* Overflow possible, we know nothing */
8509 			dst_reg->umin_value = 0;
8510 			dst_reg->umax_value = U64_MAX;
8511 		} else {
8512 			/* Cannot overflow (as long as bounds are consistent) */
8513 			dst_reg->umin_value = umin_ptr - umax_val;
8514 			dst_reg->umax_value = umax_ptr - umin_val;
8515 		}
8516 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8517 		dst_reg->off = ptr_reg->off;
8518 		dst_reg->raw = ptr_reg->raw;
8519 		if (reg_is_pkt_pointer(ptr_reg)) {
8520 			dst_reg->id = ++env->id_gen;
8521 			/* something was added to pkt_ptr, set range to zero */
8522 			if (smin_val < 0)
8523 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8524 		}
8525 		break;
8526 	case BPF_AND:
8527 	case BPF_OR:
8528 	case BPF_XOR:
8529 		/* bitwise ops on pointers are troublesome, prohibit. */
8530 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8531 			dst, bpf_alu_string[opcode >> 4]);
8532 		return -EACCES;
8533 	default:
8534 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
8535 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8536 			dst, bpf_alu_string[opcode >> 4]);
8537 		return -EACCES;
8538 	}
8539 
8540 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8541 		return -EINVAL;
8542 	reg_bounds_sync(dst_reg);
8543 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8544 		return -EACCES;
8545 	if (sanitize_needed(opcode)) {
8546 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8547 				       &info, true);
8548 		if (ret < 0)
8549 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8550 	}
8551 
8552 	return 0;
8553 }
8554 
8555 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8556 				 struct bpf_reg_state *src_reg)
8557 {
8558 	s32 smin_val = src_reg->s32_min_value;
8559 	s32 smax_val = src_reg->s32_max_value;
8560 	u32 umin_val = src_reg->u32_min_value;
8561 	u32 umax_val = src_reg->u32_max_value;
8562 
8563 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8564 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8565 		dst_reg->s32_min_value = S32_MIN;
8566 		dst_reg->s32_max_value = S32_MAX;
8567 	} else {
8568 		dst_reg->s32_min_value += smin_val;
8569 		dst_reg->s32_max_value += smax_val;
8570 	}
8571 	if (dst_reg->u32_min_value + umin_val < umin_val ||
8572 	    dst_reg->u32_max_value + umax_val < umax_val) {
8573 		dst_reg->u32_min_value = 0;
8574 		dst_reg->u32_max_value = U32_MAX;
8575 	} else {
8576 		dst_reg->u32_min_value += umin_val;
8577 		dst_reg->u32_max_value += umax_val;
8578 	}
8579 }
8580 
8581 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8582 			       struct bpf_reg_state *src_reg)
8583 {
8584 	s64 smin_val = src_reg->smin_value;
8585 	s64 smax_val = src_reg->smax_value;
8586 	u64 umin_val = src_reg->umin_value;
8587 	u64 umax_val = src_reg->umax_value;
8588 
8589 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8590 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
8591 		dst_reg->smin_value = S64_MIN;
8592 		dst_reg->smax_value = S64_MAX;
8593 	} else {
8594 		dst_reg->smin_value += smin_val;
8595 		dst_reg->smax_value += smax_val;
8596 	}
8597 	if (dst_reg->umin_value + umin_val < umin_val ||
8598 	    dst_reg->umax_value + umax_val < umax_val) {
8599 		dst_reg->umin_value = 0;
8600 		dst_reg->umax_value = U64_MAX;
8601 	} else {
8602 		dst_reg->umin_value += umin_val;
8603 		dst_reg->umax_value += umax_val;
8604 	}
8605 }
8606 
8607 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8608 				 struct bpf_reg_state *src_reg)
8609 {
8610 	s32 smin_val = src_reg->s32_min_value;
8611 	s32 smax_val = src_reg->s32_max_value;
8612 	u32 umin_val = src_reg->u32_min_value;
8613 	u32 umax_val = src_reg->u32_max_value;
8614 
8615 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8616 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8617 		/* Overflow possible, we know nothing */
8618 		dst_reg->s32_min_value = S32_MIN;
8619 		dst_reg->s32_max_value = S32_MAX;
8620 	} else {
8621 		dst_reg->s32_min_value -= smax_val;
8622 		dst_reg->s32_max_value -= smin_val;
8623 	}
8624 	if (dst_reg->u32_min_value < umax_val) {
8625 		/* Overflow possible, we know nothing */
8626 		dst_reg->u32_min_value = 0;
8627 		dst_reg->u32_max_value = U32_MAX;
8628 	} else {
8629 		/* Cannot overflow (as long as bounds are consistent) */
8630 		dst_reg->u32_min_value -= umax_val;
8631 		dst_reg->u32_max_value -= umin_val;
8632 	}
8633 }
8634 
8635 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8636 			       struct bpf_reg_state *src_reg)
8637 {
8638 	s64 smin_val = src_reg->smin_value;
8639 	s64 smax_val = src_reg->smax_value;
8640 	u64 umin_val = src_reg->umin_value;
8641 	u64 umax_val = src_reg->umax_value;
8642 
8643 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8644 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8645 		/* Overflow possible, we know nothing */
8646 		dst_reg->smin_value = S64_MIN;
8647 		dst_reg->smax_value = S64_MAX;
8648 	} else {
8649 		dst_reg->smin_value -= smax_val;
8650 		dst_reg->smax_value -= smin_val;
8651 	}
8652 	if (dst_reg->umin_value < umax_val) {
8653 		/* Overflow possible, we know nothing */
8654 		dst_reg->umin_value = 0;
8655 		dst_reg->umax_value = U64_MAX;
8656 	} else {
8657 		/* Cannot overflow (as long as bounds are consistent) */
8658 		dst_reg->umin_value -= umax_val;
8659 		dst_reg->umax_value -= umin_val;
8660 	}
8661 }
8662 
8663 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8664 				 struct bpf_reg_state *src_reg)
8665 {
8666 	s32 smin_val = src_reg->s32_min_value;
8667 	u32 umin_val = src_reg->u32_min_value;
8668 	u32 umax_val = src_reg->u32_max_value;
8669 
8670 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8671 		/* Ain't nobody got time to multiply that sign */
8672 		__mark_reg32_unbounded(dst_reg);
8673 		return;
8674 	}
8675 	/* Both values are positive, so we can work with unsigned and
8676 	 * copy the result to signed (unless it exceeds S32_MAX).
8677 	 */
8678 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8679 		/* Potential overflow, we know nothing */
8680 		__mark_reg32_unbounded(dst_reg);
8681 		return;
8682 	}
8683 	dst_reg->u32_min_value *= umin_val;
8684 	dst_reg->u32_max_value *= umax_val;
8685 	if (dst_reg->u32_max_value > S32_MAX) {
8686 		/* Overflow possible, we know nothing */
8687 		dst_reg->s32_min_value = S32_MIN;
8688 		dst_reg->s32_max_value = S32_MAX;
8689 	} else {
8690 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8691 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8692 	}
8693 }
8694 
8695 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8696 			       struct bpf_reg_state *src_reg)
8697 {
8698 	s64 smin_val = src_reg->smin_value;
8699 	u64 umin_val = src_reg->umin_value;
8700 	u64 umax_val = src_reg->umax_value;
8701 
8702 	if (smin_val < 0 || dst_reg->smin_value < 0) {
8703 		/* Ain't nobody got time to multiply that sign */
8704 		__mark_reg64_unbounded(dst_reg);
8705 		return;
8706 	}
8707 	/* Both values are positive, so we can work with unsigned and
8708 	 * copy the result to signed (unless it exceeds S64_MAX).
8709 	 */
8710 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8711 		/* Potential overflow, we know nothing */
8712 		__mark_reg64_unbounded(dst_reg);
8713 		return;
8714 	}
8715 	dst_reg->umin_value *= umin_val;
8716 	dst_reg->umax_value *= umax_val;
8717 	if (dst_reg->umax_value > S64_MAX) {
8718 		/* Overflow possible, we know nothing */
8719 		dst_reg->smin_value = S64_MIN;
8720 		dst_reg->smax_value = S64_MAX;
8721 	} else {
8722 		dst_reg->smin_value = dst_reg->umin_value;
8723 		dst_reg->smax_value = dst_reg->umax_value;
8724 	}
8725 }
8726 
8727 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8728 				 struct bpf_reg_state *src_reg)
8729 {
8730 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8731 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8732 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8733 	s32 smin_val = src_reg->s32_min_value;
8734 	u32 umax_val = src_reg->u32_max_value;
8735 
8736 	if (src_known && dst_known) {
8737 		__mark_reg32_known(dst_reg, var32_off.value);
8738 		return;
8739 	}
8740 
8741 	/* We get our minimum from the var_off, since that's inherently
8742 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8743 	 */
8744 	dst_reg->u32_min_value = var32_off.value;
8745 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8746 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8747 		/* Lose signed bounds when ANDing negative numbers,
8748 		 * ain't nobody got time for that.
8749 		 */
8750 		dst_reg->s32_min_value = S32_MIN;
8751 		dst_reg->s32_max_value = S32_MAX;
8752 	} else {
8753 		/* ANDing two positives gives a positive, so safe to
8754 		 * cast result into s64.
8755 		 */
8756 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8757 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8758 	}
8759 }
8760 
8761 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8762 			       struct bpf_reg_state *src_reg)
8763 {
8764 	bool src_known = tnum_is_const(src_reg->var_off);
8765 	bool dst_known = tnum_is_const(dst_reg->var_off);
8766 	s64 smin_val = src_reg->smin_value;
8767 	u64 umax_val = src_reg->umax_value;
8768 
8769 	if (src_known && dst_known) {
8770 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8771 		return;
8772 	}
8773 
8774 	/* We get our minimum from the var_off, since that's inherently
8775 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8776 	 */
8777 	dst_reg->umin_value = dst_reg->var_off.value;
8778 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8779 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8780 		/* Lose signed bounds when ANDing negative numbers,
8781 		 * ain't nobody got time for that.
8782 		 */
8783 		dst_reg->smin_value = S64_MIN;
8784 		dst_reg->smax_value = S64_MAX;
8785 	} else {
8786 		/* ANDing two positives gives a positive, so safe to
8787 		 * cast result into s64.
8788 		 */
8789 		dst_reg->smin_value = dst_reg->umin_value;
8790 		dst_reg->smax_value = dst_reg->umax_value;
8791 	}
8792 	/* We may learn something more from the var_off */
8793 	__update_reg_bounds(dst_reg);
8794 }
8795 
8796 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8797 				struct bpf_reg_state *src_reg)
8798 {
8799 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8800 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8801 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8802 	s32 smin_val = src_reg->s32_min_value;
8803 	u32 umin_val = src_reg->u32_min_value;
8804 
8805 	if (src_known && dst_known) {
8806 		__mark_reg32_known(dst_reg, var32_off.value);
8807 		return;
8808 	}
8809 
8810 	/* We get our maximum from the var_off, and our minimum is the
8811 	 * maximum of the operands' minima
8812 	 */
8813 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8814 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8815 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8816 		/* Lose signed bounds when ORing negative numbers,
8817 		 * ain't nobody got time for that.
8818 		 */
8819 		dst_reg->s32_min_value = S32_MIN;
8820 		dst_reg->s32_max_value = S32_MAX;
8821 	} else {
8822 		/* ORing two positives gives a positive, so safe to
8823 		 * cast result into s64.
8824 		 */
8825 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8826 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8827 	}
8828 }
8829 
8830 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8831 			      struct bpf_reg_state *src_reg)
8832 {
8833 	bool src_known = tnum_is_const(src_reg->var_off);
8834 	bool dst_known = tnum_is_const(dst_reg->var_off);
8835 	s64 smin_val = src_reg->smin_value;
8836 	u64 umin_val = src_reg->umin_value;
8837 
8838 	if (src_known && dst_known) {
8839 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8840 		return;
8841 	}
8842 
8843 	/* We get our maximum from the var_off, and our minimum is the
8844 	 * maximum of the operands' minima
8845 	 */
8846 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8847 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8848 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8849 		/* Lose signed bounds when ORing negative numbers,
8850 		 * ain't nobody got time for that.
8851 		 */
8852 		dst_reg->smin_value = S64_MIN;
8853 		dst_reg->smax_value = S64_MAX;
8854 	} else {
8855 		/* ORing two positives gives a positive, so safe to
8856 		 * cast result into s64.
8857 		 */
8858 		dst_reg->smin_value = dst_reg->umin_value;
8859 		dst_reg->smax_value = dst_reg->umax_value;
8860 	}
8861 	/* We may learn something more from the var_off */
8862 	__update_reg_bounds(dst_reg);
8863 }
8864 
8865 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8866 				 struct bpf_reg_state *src_reg)
8867 {
8868 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8869 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8870 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8871 	s32 smin_val = src_reg->s32_min_value;
8872 
8873 	if (src_known && dst_known) {
8874 		__mark_reg32_known(dst_reg, var32_off.value);
8875 		return;
8876 	}
8877 
8878 	/* We get both minimum and maximum from the var32_off. */
8879 	dst_reg->u32_min_value = var32_off.value;
8880 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8881 
8882 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8883 		/* XORing two positive sign numbers gives a positive,
8884 		 * so safe to cast u32 result into s32.
8885 		 */
8886 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8887 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8888 	} else {
8889 		dst_reg->s32_min_value = S32_MIN;
8890 		dst_reg->s32_max_value = S32_MAX;
8891 	}
8892 }
8893 
8894 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8895 			       struct bpf_reg_state *src_reg)
8896 {
8897 	bool src_known = tnum_is_const(src_reg->var_off);
8898 	bool dst_known = tnum_is_const(dst_reg->var_off);
8899 	s64 smin_val = src_reg->smin_value;
8900 
8901 	if (src_known && dst_known) {
8902 		/* dst_reg->var_off.value has been updated earlier */
8903 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8904 		return;
8905 	}
8906 
8907 	/* We get both minimum and maximum from the var_off. */
8908 	dst_reg->umin_value = dst_reg->var_off.value;
8909 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8910 
8911 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8912 		/* XORing two positive sign numbers gives a positive,
8913 		 * so safe to cast u64 result into s64.
8914 		 */
8915 		dst_reg->smin_value = dst_reg->umin_value;
8916 		dst_reg->smax_value = dst_reg->umax_value;
8917 	} else {
8918 		dst_reg->smin_value = S64_MIN;
8919 		dst_reg->smax_value = S64_MAX;
8920 	}
8921 
8922 	__update_reg_bounds(dst_reg);
8923 }
8924 
8925 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8926 				   u64 umin_val, u64 umax_val)
8927 {
8928 	/* We lose all sign bit information (except what we can pick
8929 	 * up from var_off)
8930 	 */
8931 	dst_reg->s32_min_value = S32_MIN;
8932 	dst_reg->s32_max_value = S32_MAX;
8933 	/* If we might shift our top bit out, then we know nothing */
8934 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8935 		dst_reg->u32_min_value = 0;
8936 		dst_reg->u32_max_value = U32_MAX;
8937 	} else {
8938 		dst_reg->u32_min_value <<= umin_val;
8939 		dst_reg->u32_max_value <<= umax_val;
8940 	}
8941 }
8942 
8943 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8944 				 struct bpf_reg_state *src_reg)
8945 {
8946 	u32 umax_val = src_reg->u32_max_value;
8947 	u32 umin_val = src_reg->u32_min_value;
8948 	/* u32 alu operation will zext upper bits */
8949 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8950 
8951 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8952 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8953 	/* Not required but being careful mark reg64 bounds as unknown so
8954 	 * that we are forced to pick them up from tnum and zext later and
8955 	 * if some path skips this step we are still safe.
8956 	 */
8957 	__mark_reg64_unbounded(dst_reg);
8958 	__update_reg32_bounds(dst_reg);
8959 }
8960 
8961 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8962 				   u64 umin_val, u64 umax_val)
8963 {
8964 	/* Special case <<32 because it is a common compiler pattern to sign
8965 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8966 	 * positive we know this shift will also be positive so we can track
8967 	 * bounds correctly. Otherwise we lose all sign bit information except
8968 	 * what we can pick up from var_off. Perhaps we can generalize this
8969 	 * later to shifts of any length.
8970 	 */
8971 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8972 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8973 	else
8974 		dst_reg->smax_value = S64_MAX;
8975 
8976 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8977 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8978 	else
8979 		dst_reg->smin_value = S64_MIN;
8980 
8981 	/* If we might shift our top bit out, then we know nothing */
8982 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8983 		dst_reg->umin_value = 0;
8984 		dst_reg->umax_value = U64_MAX;
8985 	} else {
8986 		dst_reg->umin_value <<= umin_val;
8987 		dst_reg->umax_value <<= umax_val;
8988 	}
8989 }
8990 
8991 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8992 			       struct bpf_reg_state *src_reg)
8993 {
8994 	u64 umax_val = src_reg->umax_value;
8995 	u64 umin_val = src_reg->umin_value;
8996 
8997 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
8998 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8999 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
9000 
9001 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
9002 	/* We may learn something more from the var_off */
9003 	__update_reg_bounds(dst_reg);
9004 }
9005 
9006 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
9007 				 struct bpf_reg_state *src_reg)
9008 {
9009 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
9010 	u32 umax_val = src_reg->u32_max_value;
9011 	u32 umin_val = src_reg->u32_min_value;
9012 
9013 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
9014 	 * be negative, then either:
9015 	 * 1) src_reg might be zero, so the sign bit of the result is
9016 	 *    unknown, so we lose our signed bounds
9017 	 * 2) it's known negative, thus the unsigned bounds capture the
9018 	 *    signed bounds
9019 	 * 3) the signed bounds cross zero, so they tell us nothing
9020 	 *    about the result
9021 	 * If the value in dst_reg is known nonnegative, then again the
9022 	 * unsigned bounds capture the signed bounds.
9023 	 * Thus, in all cases it suffices to blow away our signed bounds
9024 	 * and rely on inferring new ones from the unsigned bounds and
9025 	 * var_off of the result.
9026 	 */
9027 	dst_reg->s32_min_value = S32_MIN;
9028 	dst_reg->s32_max_value = S32_MAX;
9029 
9030 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
9031 	dst_reg->u32_min_value >>= umax_val;
9032 	dst_reg->u32_max_value >>= umin_val;
9033 
9034 	__mark_reg64_unbounded(dst_reg);
9035 	__update_reg32_bounds(dst_reg);
9036 }
9037 
9038 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
9039 			       struct bpf_reg_state *src_reg)
9040 {
9041 	u64 umax_val = src_reg->umax_value;
9042 	u64 umin_val = src_reg->umin_value;
9043 
9044 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
9045 	 * be negative, then either:
9046 	 * 1) src_reg might be zero, so the sign bit of the result is
9047 	 *    unknown, so we lose our signed bounds
9048 	 * 2) it's known negative, thus the unsigned bounds capture the
9049 	 *    signed bounds
9050 	 * 3) the signed bounds cross zero, so they tell us nothing
9051 	 *    about the result
9052 	 * If the value in dst_reg is known nonnegative, then again the
9053 	 * unsigned bounds capture the signed bounds.
9054 	 * Thus, in all cases it suffices to blow away our signed bounds
9055 	 * and rely on inferring new ones from the unsigned bounds and
9056 	 * var_off of the result.
9057 	 */
9058 	dst_reg->smin_value = S64_MIN;
9059 	dst_reg->smax_value = S64_MAX;
9060 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
9061 	dst_reg->umin_value >>= umax_val;
9062 	dst_reg->umax_value >>= umin_val;
9063 
9064 	/* Its not easy to operate on alu32 bounds here because it depends
9065 	 * on bits being shifted in. Take easy way out and mark unbounded
9066 	 * so we can recalculate later from tnum.
9067 	 */
9068 	__mark_reg32_unbounded(dst_reg);
9069 	__update_reg_bounds(dst_reg);
9070 }
9071 
9072 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
9073 				  struct bpf_reg_state *src_reg)
9074 {
9075 	u64 umin_val = src_reg->u32_min_value;
9076 
9077 	/* Upon reaching here, src_known is true and
9078 	 * umax_val is equal to umin_val.
9079 	 */
9080 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9081 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9082 
9083 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9084 
9085 	/* blow away the dst_reg umin_value/umax_value and rely on
9086 	 * dst_reg var_off to refine the result.
9087 	 */
9088 	dst_reg->u32_min_value = 0;
9089 	dst_reg->u32_max_value = U32_MAX;
9090 
9091 	__mark_reg64_unbounded(dst_reg);
9092 	__update_reg32_bounds(dst_reg);
9093 }
9094 
9095 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9096 				struct bpf_reg_state *src_reg)
9097 {
9098 	u64 umin_val = src_reg->umin_value;
9099 
9100 	/* Upon reaching here, src_known is true and umax_val is equal
9101 	 * to umin_val.
9102 	 */
9103 	dst_reg->smin_value >>= umin_val;
9104 	dst_reg->smax_value >>= umin_val;
9105 
9106 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9107 
9108 	/* blow away the dst_reg umin_value/umax_value and rely on
9109 	 * dst_reg var_off to refine the result.
9110 	 */
9111 	dst_reg->umin_value = 0;
9112 	dst_reg->umax_value = U64_MAX;
9113 
9114 	/* Its not easy to operate on alu32 bounds here because it depends
9115 	 * on bits being shifted in from upper 32-bits. Take easy way out
9116 	 * and mark unbounded so we can recalculate later from tnum.
9117 	 */
9118 	__mark_reg32_unbounded(dst_reg);
9119 	__update_reg_bounds(dst_reg);
9120 }
9121 
9122 /* WARNING: This function does calculations on 64-bit values, but the actual
9123  * execution may occur on 32-bit values. Therefore, things like bitshifts
9124  * need extra checks in the 32-bit case.
9125  */
9126 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9127 				      struct bpf_insn *insn,
9128 				      struct bpf_reg_state *dst_reg,
9129 				      struct bpf_reg_state src_reg)
9130 {
9131 	struct bpf_reg_state *regs = cur_regs(env);
9132 	u8 opcode = BPF_OP(insn->code);
9133 	bool src_known;
9134 	s64 smin_val, smax_val;
9135 	u64 umin_val, umax_val;
9136 	s32 s32_min_val, s32_max_val;
9137 	u32 u32_min_val, u32_max_val;
9138 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9139 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9140 	int ret;
9141 
9142 	smin_val = src_reg.smin_value;
9143 	smax_val = src_reg.smax_value;
9144 	umin_val = src_reg.umin_value;
9145 	umax_val = src_reg.umax_value;
9146 
9147 	s32_min_val = src_reg.s32_min_value;
9148 	s32_max_val = src_reg.s32_max_value;
9149 	u32_min_val = src_reg.u32_min_value;
9150 	u32_max_val = src_reg.u32_max_value;
9151 
9152 	if (alu32) {
9153 		src_known = tnum_subreg_is_const(src_reg.var_off);
9154 		if ((src_known &&
9155 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9156 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9157 			/* Taint dst register if offset had invalid bounds
9158 			 * derived from e.g. dead branches.
9159 			 */
9160 			__mark_reg_unknown(env, dst_reg);
9161 			return 0;
9162 		}
9163 	} else {
9164 		src_known = tnum_is_const(src_reg.var_off);
9165 		if ((src_known &&
9166 		     (smin_val != smax_val || umin_val != umax_val)) ||
9167 		    smin_val > smax_val || umin_val > umax_val) {
9168 			/* Taint dst register if offset had invalid bounds
9169 			 * derived from e.g. dead branches.
9170 			 */
9171 			__mark_reg_unknown(env, dst_reg);
9172 			return 0;
9173 		}
9174 	}
9175 
9176 	if (!src_known &&
9177 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9178 		__mark_reg_unknown(env, dst_reg);
9179 		return 0;
9180 	}
9181 
9182 	if (sanitize_needed(opcode)) {
9183 		ret = sanitize_val_alu(env, insn);
9184 		if (ret < 0)
9185 			return sanitize_err(env, insn, ret, NULL, NULL);
9186 	}
9187 
9188 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9189 	 * There are two classes of instructions: The first class we track both
9190 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
9191 	 * greatest amount of precision when alu operations are mixed with jmp32
9192 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9193 	 * and BPF_OR. This is possible because these ops have fairly easy to
9194 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9195 	 * See alu32 verifier tests for examples. The second class of
9196 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9197 	 * with regards to tracking sign/unsigned bounds because the bits may
9198 	 * cross subreg boundaries in the alu64 case. When this happens we mark
9199 	 * the reg unbounded in the subreg bound space and use the resulting
9200 	 * tnum to calculate an approximation of the sign/unsigned bounds.
9201 	 */
9202 	switch (opcode) {
9203 	case BPF_ADD:
9204 		scalar32_min_max_add(dst_reg, &src_reg);
9205 		scalar_min_max_add(dst_reg, &src_reg);
9206 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9207 		break;
9208 	case BPF_SUB:
9209 		scalar32_min_max_sub(dst_reg, &src_reg);
9210 		scalar_min_max_sub(dst_reg, &src_reg);
9211 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9212 		break;
9213 	case BPF_MUL:
9214 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9215 		scalar32_min_max_mul(dst_reg, &src_reg);
9216 		scalar_min_max_mul(dst_reg, &src_reg);
9217 		break;
9218 	case BPF_AND:
9219 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9220 		scalar32_min_max_and(dst_reg, &src_reg);
9221 		scalar_min_max_and(dst_reg, &src_reg);
9222 		break;
9223 	case BPF_OR:
9224 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9225 		scalar32_min_max_or(dst_reg, &src_reg);
9226 		scalar_min_max_or(dst_reg, &src_reg);
9227 		break;
9228 	case BPF_XOR:
9229 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9230 		scalar32_min_max_xor(dst_reg, &src_reg);
9231 		scalar_min_max_xor(dst_reg, &src_reg);
9232 		break;
9233 	case BPF_LSH:
9234 		if (umax_val >= insn_bitness) {
9235 			/* Shifts greater than 31 or 63 are undefined.
9236 			 * This includes shifts by a negative number.
9237 			 */
9238 			mark_reg_unknown(env, regs, insn->dst_reg);
9239 			break;
9240 		}
9241 		if (alu32)
9242 			scalar32_min_max_lsh(dst_reg, &src_reg);
9243 		else
9244 			scalar_min_max_lsh(dst_reg, &src_reg);
9245 		break;
9246 	case BPF_RSH:
9247 		if (umax_val >= insn_bitness) {
9248 			/* Shifts greater than 31 or 63 are undefined.
9249 			 * This includes shifts by a negative number.
9250 			 */
9251 			mark_reg_unknown(env, regs, insn->dst_reg);
9252 			break;
9253 		}
9254 		if (alu32)
9255 			scalar32_min_max_rsh(dst_reg, &src_reg);
9256 		else
9257 			scalar_min_max_rsh(dst_reg, &src_reg);
9258 		break;
9259 	case BPF_ARSH:
9260 		if (umax_val >= insn_bitness) {
9261 			/* Shifts greater than 31 or 63 are undefined.
9262 			 * This includes shifts by a negative number.
9263 			 */
9264 			mark_reg_unknown(env, regs, insn->dst_reg);
9265 			break;
9266 		}
9267 		if (alu32)
9268 			scalar32_min_max_arsh(dst_reg, &src_reg);
9269 		else
9270 			scalar_min_max_arsh(dst_reg, &src_reg);
9271 		break;
9272 	default:
9273 		mark_reg_unknown(env, regs, insn->dst_reg);
9274 		break;
9275 	}
9276 
9277 	/* ALU32 ops are zero extended into 64bit register */
9278 	if (alu32)
9279 		zext_32_to_64(dst_reg);
9280 	reg_bounds_sync(dst_reg);
9281 	return 0;
9282 }
9283 
9284 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9285  * and var_off.
9286  */
9287 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9288 				   struct bpf_insn *insn)
9289 {
9290 	struct bpf_verifier_state *vstate = env->cur_state;
9291 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9292 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9293 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9294 	u8 opcode = BPF_OP(insn->code);
9295 	int err;
9296 
9297 	dst_reg = &regs[insn->dst_reg];
9298 	src_reg = NULL;
9299 	if (dst_reg->type != SCALAR_VALUE)
9300 		ptr_reg = dst_reg;
9301 	else
9302 		/* Make sure ID is cleared otherwise dst_reg min/max could be
9303 		 * incorrectly propagated into other registers by find_equal_scalars()
9304 		 */
9305 		dst_reg->id = 0;
9306 	if (BPF_SRC(insn->code) == BPF_X) {
9307 		src_reg = &regs[insn->src_reg];
9308 		if (src_reg->type != SCALAR_VALUE) {
9309 			if (dst_reg->type != SCALAR_VALUE) {
9310 				/* Combining two pointers by any ALU op yields
9311 				 * an arbitrary scalar. Disallow all math except
9312 				 * pointer subtraction
9313 				 */
9314 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9315 					mark_reg_unknown(env, regs, insn->dst_reg);
9316 					return 0;
9317 				}
9318 				verbose(env, "R%d pointer %s pointer prohibited\n",
9319 					insn->dst_reg,
9320 					bpf_alu_string[opcode >> 4]);
9321 				return -EACCES;
9322 			} else {
9323 				/* scalar += pointer
9324 				 * This is legal, but we have to reverse our
9325 				 * src/dest handling in computing the range
9326 				 */
9327 				err = mark_chain_precision(env, insn->dst_reg);
9328 				if (err)
9329 					return err;
9330 				return adjust_ptr_min_max_vals(env, insn,
9331 							       src_reg, dst_reg);
9332 			}
9333 		} else if (ptr_reg) {
9334 			/* pointer += scalar */
9335 			err = mark_chain_precision(env, insn->src_reg);
9336 			if (err)
9337 				return err;
9338 			return adjust_ptr_min_max_vals(env, insn,
9339 						       dst_reg, src_reg);
9340 		} else if (dst_reg->precise) {
9341 			/* if dst_reg is precise, src_reg should be precise as well */
9342 			err = mark_chain_precision(env, insn->src_reg);
9343 			if (err)
9344 				return err;
9345 		}
9346 	} else {
9347 		/* Pretend the src is a reg with a known value, since we only
9348 		 * need to be able to read from this state.
9349 		 */
9350 		off_reg.type = SCALAR_VALUE;
9351 		__mark_reg_known(&off_reg, insn->imm);
9352 		src_reg = &off_reg;
9353 		if (ptr_reg) /* pointer += K */
9354 			return adjust_ptr_min_max_vals(env, insn,
9355 						       ptr_reg, src_reg);
9356 	}
9357 
9358 	/* Got here implies adding two SCALAR_VALUEs */
9359 	if (WARN_ON_ONCE(ptr_reg)) {
9360 		print_verifier_state(env, state, true);
9361 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
9362 		return -EINVAL;
9363 	}
9364 	if (WARN_ON(!src_reg)) {
9365 		print_verifier_state(env, state, true);
9366 		verbose(env, "verifier internal error: no src_reg\n");
9367 		return -EINVAL;
9368 	}
9369 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9370 }
9371 
9372 /* check validity of 32-bit and 64-bit arithmetic operations */
9373 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9374 {
9375 	struct bpf_reg_state *regs = cur_regs(env);
9376 	u8 opcode = BPF_OP(insn->code);
9377 	int err;
9378 
9379 	if (opcode == BPF_END || opcode == BPF_NEG) {
9380 		if (opcode == BPF_NEG) {
9381 			if (BPF_SRC(insn->code) != BPF_K ||
9382 			    insn->src_reg != BPF_REG_0 ||
9383 			    insn->off != 0 || insn->imm != 0) {
9384 				verbose(env, "BPF_NEG uses reserved fields\n");
9385 				return -EINVAL;
9386 			}
9387 		} else {
9388 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9389 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9390 			    BPF_CLASS(insn->code) == BPF_ALU64) {
9391 				verbose(env, "BPF_END uses reserved fields\n");
9392 				return -EINVAL;
9393 			}
9394 		}
9395 
9396 		/* check src operand */
9397 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9398 		if (err)
9399 			return err;
9400 
9401 		if (is_pointer_value(env, insn->dst_reg)) {
9402 			verbose(env, "R%d pointer arithmetic prohibited\n",
9403 				insn->dst_reg);
9404 			return -EACCES;
9405 		}
9406 
9407 		/* check dest operand */
9408 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
9409 		if (err)
9410 			return err;
9411 
9412 	} else if (opcode == BPF_MOV) {
9413 
9414 		if (BPF_SRC(insn->code) == BPF_X) {
9415 			if (insn->imm != 0 || insn->off != 0) {
9416 				verbose(env, "BPF_MOV uses reserved fields\n");
9417 				return -EINVAL;
9418 			}
9419 
9420 			/* check src operand */
9421 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9422 			if (err)
9423 				return err;
9424 		} else {
9425 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9426 				verbose(env, "BPF_MOV uses reserved fields\n");
9427 				return -EINVAL;
9428 			}
9429 		}
9430 
9431 		/* check dest operand, mark as required later */
9432 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9433 		if (err)
9434 			return err;
9435 
9436 		if (BPF_SRC(insn->code) == BPF_X) {
9437 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
9438 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9439 
9440 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9441 				/* case: R1 = R2
9442 				 * copy register state to dest reg
9443 				 */
9444 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9445 					/* Assign src and dst registers the same ID
9446 					 * that will be used by find_equal_scalars()
9447 					 * to propagate min/max range.
9448 					 */
9449 					src_reg->id = ++env->id_gen;
9450 				*dst_reg = *src_reg;
9451 				dst_reg->live |= REG_LIVE_WRITTEN;
9452 				dst_reg->subreg_def = DEF_NOT_SUBREG;
9453 			} else {
9454 				/* R1 = (u32) R2 */
9455 				if (is_pointer_value(env, insn->src_reg)) {
9456 					verbose(env,
9457 						"R%d partial copy of pointer\n",
9458 						insn->src_reg);
9459 					return -EACCES;
9460 				} else if (src_reg->type == SCALAR_VALUE) {
9461 					*dst_reg = *src_reg;
9462 					/* Make sure ID is cleared otherwise
9463 					 * dst_reg min/max could be incorrectly
9464 					 * propagated into src_reg by find_equal_scalars()
9465 					 */
9466 					dst_reg->id = 0;
9467 					dst_reg->live |= REG_LIVE_WRITTEN;
9468 					dst_reg->subreg_def = env->insn_idx + 1;
9469 				} else {
9470 					mark_reg_unknown(env, regs,
9471 							 insn->dst_reg);
9472 				}
9473 				zext_32_to_64(dst_reg);
9474 				reg_bounds_sync(dst_reg);
9475 			}
9476 		} else {
9477 			/* case: R = imm
9478 			 * remember the value we stored into this reg
9479 			 */
9480 			/* clear any state __mark_reg_known doesn't set */
9481 			mark_reg_unknown(env, regs, insn->dst_reg);
9482 			regs[insn->dst_reg].type = SCALAR_VALUE;
9483 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9484 				__mark_reg_known(regs + insn->dst_reg,
9485 						 insn->imm);
9486 			} else {
9487 				__mark_reg_known(regs + insn->dst_reg,
9488 						 (u32)insn->imm);
9489 			}
9490 		}
9491 
9492 	} else if (opcode > BPF_END) {
9493 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9494 		return -EINVAL;
9495 
9496 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
9497 
9498 		if (BPF_SRC(insn->code) == BPF_X) {
9499 			if (insn->imm != 0 || insn->off != 0) {
9500 				verbose(env, "BPF_ALU uses reserved fields\n");
9501 				return -EINVAL;
9502 			}
9503 			/* check src1 operand */
9504 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9505 			if (err)
9506 				return err;
9507 		} else {
9508 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9509 				verbose(env, "BPF_ALU uses reserved fields\n");
9510 				return -EINVAL;
9511 			}
9512 		}
9513 
9514 		/* check src2 operand */
9515 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9516 		if (err)
9517 			return err;
9518 
9519 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9520 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9521 			verbose(env, "div by zero\n");
9522 			return -EINVAL;
9523 		}
9524 
9525 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9526 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9527 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9528 
9529 			if (insn->imm < 0 || insn->imm >= size) {
9530 				verbose(env, "invalid shift %d\n", insn->imm);
9531 				return -EINVAL;
9532 			}
9533 		}
9534 
9535 		/* check dest operand */
9536 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9537 		if (err)
9538 			return err;
9539 
9540 		return adjust_reg_min_max_vals(env, insn);
9541 	}
9542 
9543 	return 0;
9544 }
9545 
9546 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9547 				   struct bpf_reg_state *dst_reg,
9548 				   enum bpf_reg_type type,
9549 				   bool range_right_open)
9550 {
9551 	struct bpf_func_state *state;
9552 	struct bpf_reg_state *reg;
9553 	int new_range;
9554 
9555 	if (dst_reg->off < 0 ||
9556 	    (dst_reg->off == 0 && range_right_open))
9557 		/* This doesn't give us any range */
9558 		return;
9559 
9560 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
9561 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9562 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
9563 		 * than pkt_end, but that's because it's also less than pkt.
9564 		 */
9565 		return;
9566 
9567 	new_range = dst_reg->off;
9568 	if (range_right_open)
9569 		new_range++;
9570 
9571 	/* Examples for register markings:
9572 	 *
9573 	 * pkt_data in dst register:
9574 	 *
9575 	 *   r2 = r3;
9576 	 *   r2 += 8;
9577 	 *   if (r2 > pkt_end) goto <handle exception>
9578 	 *   <access okay>
9579 	 *
9580 	 *   r2 = r3;
9581 	 *   r2 += 8;
9582 	 *   if (r2 < pkt_end) goto <access okay>
9583 	 *   <handle exception>
9584 	 *
9585 	 *   Where:
9586 	 *     r2 == dst_reg, pkt_end == src_reg
9587 	 *     r2=pkt(id=n,off=8,r=0)
9588 	 *     r3=pkt(id=n,off=0,r=0)
9589 	 *
9590 	 * pkt_data in src register:
9591 	 *
9592 	 *   r2 = r3;
9593 	 *   r2 += 8;
9594 	 *   if (pkt_end >= r2) goto <access okay>
9595 	 *   <handle exception>
9596 	 *
9597 	 *   r2 = r3;
9598 	 *   r2 += 8;
9599 	 *   if (pkt_end <= r2) goto <handle exception>
9600 	 *   <access okay>
9601 	 *
9602 	 *   Where:
9603 	 *     pkt_end == dst_reg, r2 == src_reg
9604 	 *     r2=pkt(id=n,off=8,r=0)
9605 	 *     r3=pkt(id=n,off=0,r=0)
9606 	 *
9607 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9608 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9609 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
9610 	 * the check.
9611 	 */
9612 
9613 	/* If our ids match, then we must have the same max_value.  And we
9614 	 * don't care about the other reg's fixed offset, since if it's too big
9615 	 * the range won't allow anything.
9616 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9617 	 */
9618 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9619 		if (reg->type == type && reg->id == dst_reg->id)
9620 			/* keep the maximum range already checked */
9621 			reg->range = max(reg->range, new_range);
9622 	}));
9623 }
9624 
9625 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9626 {
9627 	struct tnum subreg = tnum_subreg(reg->var_off);
9628 	s32 sval = (s32)val;
9629 
9630 	switch (opcode) {
9631 	case BPF_JEQ:
9632 		if (tnum_is_const(subreg))
9633 			return !!tnum_equals_const(subreg, val);
9634 		break;
9635 	case BPF_JNE:
9636 		if (tnum_is_const(subreg))
9637 			return !tnum_equals_const(subreg, val);
9638 		break;
9639 	case BPF_JSET:
9640 		if ((~subreg.mask & subreg.value) & val)
9641 			return 1;
9642 		if (!((subreg.mask | subreg.value) & val))
9643 			return 0;
9644 		break;
9645 	case BPF_JGT:
9646 		if (reg->u32_min_value > val)
9647 			return 1;
9648 		else if (reg->u32_max_value <= val)
9649 			return 0;
9650 		break;
9651 	case BPF_JSGT:
9652 		if (reg->s32_min_value > sval)
9653 			return 1;
9654 		else if (reg->s32_max_value <= sval)
9655 			return 0;
9656 		break;
9657 	case BPF_JLT:
9658 		if (reg->u32_max_value < val)
9659 			return 1;
9660 		else if (reg->u32_min_value >= val)
9661 			return 0;
9662 		break;
9663 	case BPF_JSLT:
9664 		if (reg->s32_max_value < sval)
9665 			return 1;
9666 		else if (reg->s32_min_value >= sval)
9667 			return 0;
9668 		break;
9669 	case BPF_JGE:
9670 		if (reg->u32_min_value >= val)
9671 			return 1;
9672 		else if (reg->u32_max_value < val)
9673 			return 0;
9674 		break;
9675 	case BPF_JSGE:
9676 		if (reg->s32_min_value >= sval)
9677 			return 1;
9678 		else if (reg->s32_max_value < sval)
9679 			return 0;
9680 		break;
9681 	case BPF_JLE:
9682 		if (reg->u32_max_value <= val)
9683 			return 1;
9684 		else if (reg->u32_min_value > val)
9685 			return 0;
9686 		break;
9687 	case BPF_JSLE:
9688 		if (reg->s32_max_value <= sval)
9689 			return 1;
9690 		else if (reg->s32_min_value > sval)
9691 			return 0;
9692 		break;
9693 	}
9694 
9695 	return -1;
9696 }
9697 
9698 
9699 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9700 {
9701 	s64 sval = (s64)val;
9702 
9703 	switch (opcode) {
9704 	case BPF_JEQ:
9705 		if (tnum_is_const(reg->var_off))
9706 			return !!tnum_equals_const(reg->var_off, val);
9707 		break;
9708 	case BPF_JNE:
9709 		if (tnum_is_const(reg->var_off))
9710 			return !tnum_equals_const(reg->var_off, val);
9711 		break;
9712 	case BPF_JSET:
9713 		if ((~reg->var_off.mask & reg->var_off.value) & val)
9714 			return 1;
9715 		if (!((reg->var_off.mask | reg->var_off.value) & val))
9716 			return 0;
9717 		break;
9718 	case BPF_JGT:
9719 		if (reg->umin_value > val)
9720 			return 1;
9721 		else if (reg->umax_value <= val)
9722 			return 0;
9723 		break;
9724 	case BPF_JSGT:
9725 		if (reg->smin_value > sval)
9726 			return 1;
9727 		else if (reg->smax_value <= sval)
9728 			return 0;
9729 		break;
9730 	case BPF_JLT:
9731 		if (reg->umax_value < val)
9732 			return 1;
9733 		else if (reg->umin_value >= val)
9734 			return 0;
9735 		break;
9736 	case BPF_JSLT:
9737 		if (reg->smax_value < sval)
9738 			return 1;
9739 		else if (reg->smin_value >= sval)
9740 			return 0;
9741 		break;
9742 	case BPF_JGE:
9743 		if (reg->umin_value >= val)
9744 			return 1;
9745 		else if (reg->umax_value < val)
9746 			return 0;
9747 		break;
9748 	case BPF_JSGE:
9749 		if (reg->smin_value >= sval)
9750 			return 1;
9751 		else if (reg->smax_value < sval)
9752 			return 0;
9753 		break;
9754 	case BPF_JLE:
9755 		if (reg->umax_value <= val)
9756 			return 1;
9757 		else if (reg->umin_value > val)
9758 			return 0;
9759 		break;
9760 	case BPF_JSLE:
9761 		if (reg->smax_value <= sval)
9762 			return 1;
9763 		else if (reg->smin_value > sval)
9764 			return 0;
9765 		break;
9766 	}
9767 
9768 	return -1;
9769 }
9770 
9771 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9772  * and return:
9773  *  1 - branch will be taken and "goto target" will be executed
9774  *  0 - branch will not be taken and fall-through to next insn
9775  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9776  *      range [0,10]
9777  */
9778 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9779 			   bool is_jmp32)
9780 {
9781 	if (__is_pointer_value(false, reg)) {
9782 		if (!reg_type_not_null(reg->type))
9783 			return -1;
9784 
9785 		/* If pointer is valid tests against zero will fail so we can
9786 		 * use this to direct branch taken.
9787 		 */
9788 		if (val != 0)
9789 			return -1;
9790 
9791 		switch (opcode) {
9792 		case BPF_JEQ:
9793 			return 0;
9794 		case BPF_JNE:
9795 			return 1;
9796 		default:
9797 			return -1;
9798 		}
9799 	}
9800 
9801 	if (is_jmp32)
9802 		return is_branch32_taken(reg, val, opcode);
9803 	return is_branch64_taken(reg, val, opcode);
9804 }
9805 
9806 static int flip_opcode(u32 opcode)
9807 {
9808 	/* How can we transform "a <op> b" into "b <op> a"? */
9809 	static const u8 opcode_flip[16] = {
9810 		/* these stay the same */
9811 		[BPF_JEQ  >> 4] = BPF_JEQ,
9812 		[BPF_JNE  >> 4] = BPF_JNE,
9813 		[BPF_JSET >> 4] = BPF_JSET,
9814 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
9815 		[BPF_JGE  >> 4] = BPF_JLE,
9816 		[BPF_JGT  >> 4] = BPF_JLT,
9817 		[BPF_JLE  >> 4] = BPF_JGE,
9818 		[BPF_JLT  >> 4] = BPF_JGT,
9819 		[BPF_JSGE >> 4] = BPF_JSLE,
9820 		[BPF_JSGT >> 4] = BPF_JSLT,
9821 		[BPF_JSLE >> 4] = BPF_JSGE,
9822 		[BPF_JSLT >> 4] = BPF_JSGT
9823 	};
9824 	return opcode_flip[opcode >> 4];
9825 }
9826 
9827 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9828 				   struct bpf_reg_state *src_reg,
9829 				   u8 opcode)
9830 {
9831 	struct bpf_reg_state *pkt;
9832 
9833 	if (src_reg->type == PTR_TO_PACKET_END) {
9834 		pkt = dst_reg;
9835 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
9836 		pkt = src_reg;
9837 		opcode = flip_opcode(opcode);
9838 	} else {
9839 		return -1;
9840 	}
9841 
9842 	if (pkt->range >= 0)
9843 		return -1;
9844 
9845 	switch (opcode) {
9846 	case BPF_JLE:
9847 		/* pkt <= pkt_end */
9848 		fallthrough;
9849 	case BPF_JGT:
9850 		/* pkt > pkt_end */
9851 		if (pkt->range == BEYOND_PKT_END)
9852 			/* pkt has at last one extra byte beyond pkt_end */
9853 			return opcode == BPF_JGT;
9854 		break;
9855 	case BPF_JLT:
9856 		/* pkt < pkt_end */
9857 		fallthrough;
9858 	case BPF_JGE:
9859 		/* pkt >= pkt_end */
9860 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9861 			return opcode == BPF_JGE;
9862 		break;
9863 	}
9864 	return -1;
9865 }
9866 
9867 /* Adjusts the register min/max values in the case that the dst_reg is the
9868  * variable register that we are working on, and src_reg is a constant or we're
9869  * simply doing a BPF_K check.
9870  * In JEQ/JNE cases we also adjust the var_off values.
9871  */
9872 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9873 			    struct bpf_reg_state *false_reg,
9874 			    u64 val, u32 val32,
9875 			    u8 opcode, bool is_jmp32)
9876 {
9877 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9878 	struct tnum false_64off = false_reg->var_off;
9879 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9880 	struct tnum true_64off = true_reg->var_off;
9881 	s64 sval = (s64)val;
9882 	s32 sval32 = (s32)val32;
9883 
9884 	/* If the dst_reg is a pointer, we can't learn anything about its
9885 	 * variable offset from the compare (unless src_reg were a pointer into
9886 	 * the same object, but we don't bother with that.
9887 	 * Since false_reg and true_reg have the same type by construction, we
9888 	 * only need to check one of them for pointerness.
9889 	 */
9890 	if (__is_pointer_value(false, false_reg))
9891 		return;
9892 
9893 	switch (opcode) {
9894 	/* JEQ/JNE comparison doesn't change the register equivalence.
9895 	 *
9896 	 * r1 = r2;
9897 	 * if (r1 == 42) goto label;
9898 	 * ...
9899 	 * label: // here both r1 and r2 are known to be 42.
9900 	 *
9901 	 * Hence when marking register as known preserve it's ID.
9902 	 */
9903 	case BPF_JEQ:
9904 		if (is_jmp32) {
9905 			__mark_reg32_known(true_reg, val32);
9906 			true_32off = tnum_subreg(true_reg->var_off);
9907 		} else {
9908 			___mark_reg_known(true_reg, val);
9909 			true_64off = true_reg->var_off;
9910 		}
9911 		break;
9912 	case BPF_JNE:
9913 		if (is_jmp32) {
9914 			__mark_reg32_known(false_reg, val32);
9915 			false_32off = tnum_subreg(false_reg->var_off);
9916 		} else {
9917 			___mark_reg_known(false_reg, val);
9918 			false_64off = false_reg->var_off;
9919 		}
9920 		break;
9921 	case BPF_JSET:
9922 		if (is_jmp32) {
9923 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9924 			if (is_power_of_2(val32))
9925 				true_32off = tnum_or(true_32off,
9926 						     tnum_const(val32));
9927 		} else {
9928 			false_64off = tnum_and(false_64off, tnum_const(~val));
9929 			if (is_power_of_2(val))
9930 				true_64off = tnum_or(true_64off,
9931 						     tnum_const(val));
9932 		}
9933 		break;
9934 	case BPF_JGE:
9935 	case BPF_JGT:
9936 	{
9937 		if (is_jmp32) {
9938 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9939 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9940 
9941 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9942 						       false_umax);
9943 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9944 						      true_umin);
9945 		} else {
9946 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9947 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9948 
9949 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9950 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9951 		}
9952 		break;
9953 	}
9954 	case BPF_JSGE:
9955 	case BPF_JSGT:
9956 	{
9957 		if (is_jmp32) {
9958 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9959 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9960 
9961 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9962 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9963 		} else {
9964 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9965 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9966 
9967 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9968 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9969 		}
9970 		break;
9971 	}
9972 	case BPF_JLE:
9973 	case BPF_JLT:
9974 	{
9975 		if (is_jmp32) {
9976 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9977 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9978 
9979 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9980 						       false_umin);
9981 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9982 						      true_umax);
9983 		} else {
9984 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9985 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9986 
9987 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9988 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9989 		}
9990 		break;
9991 	}
9992 	case BPF_JSLE:
9993 	case BPF_JSLT:
9994 	{
9995 		if (is_jmp32) {
9996 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9997 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9998 
9999 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
10000 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
10001 		} else {
10002 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
10003 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
10004 
10005 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
10006 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
10007 		}
10008 		break;
10009 	}
10010 	default:
10011 		return;
10012 	}
10013 
10014 	if (is_jmp32) {
10015 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
10016 					     tnum_subreg(false_32off));
10017 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
10018 					    tnum_subreg(true_32off));
10019 		__reg_combine_32_into_64(false_reg);
10020 		__reg_combine_32_into_64(true_reg);
10021 	} else {
10022 		false_reg->var_off = false_64off;
10023 		true_reg->var_off = true_64off;
10024 		__reg_combine_64_into_32(false_reg);
10025 		__reg_combine_64_into_32(true_reg);
10026 	}
10027 }
10028 
10029 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
10030  * the variable reg.
10031  */
10032 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
10033 				struct bpf_reg_state *false_reg,
10034 				u64 val, u32 val32,
10035 				u8 opcode, bool is_jmp32)
10036 {
10037 	opcode = flip_opcode(opcode);
10038 	/* This uses zero as "not present in table"; luckily the zero opcode,
10039 	 * BPF_JA, can't get here.
10040 	 */
10041 	if (opcode)
10042 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
10043 }
10044 
10045 /* Regs are known to be equal, so intersect their min/max/var_off */
10046 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
10047 				  struct bpf_reg_state *dst_reg)
10048 {
10049 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
10050 							dst_reg->umin_value);
10051 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
10052 							dst_reg->umax_value);
10053 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
10054 							dst_reg->smin_value);
10055 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
10056 							dst_reg->smax_value);
10057 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
10058 							     dst_reg->var_off);
10059 	reg_bounds_sync(src_reg);
10060 	reg_bounds_sync(dst_reg);
10061 }
10062 
10063 static void reg_combine_min_max(struct bpf_reg_state *true_src,
10064 				struct bpf_reg_state *true_dst,
10065 				struct bpf_reg_state *false_src,
10066 				struct bpf_reg_state *false_dst,
10067 				u8 opcode)
10068 {
10069 	switch (opcode) {
10070 	case BPF_JEQ:
10071 		__reg_combine_min_max(true_src, true_dst);
10072 		break;
10073 	case BPF_JNE:
10074 		__reg_combine_min_max(false_src, false_dst);
10075 		break;
10076 	}
10077 }
10078 
10079 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10080 				 struct bpf_reg_state *reg, u32 id,
10081 				 bool is_null)
10082 {
10083 	if (type_may_be_null(reg->type) && reg->id == id &&
10084 	    !WARN_ON_ONCE(!reg->id)) {
10085 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10086 				 !tnum_equals_const(reg->var_off, 0) ||
10087 				 reg->off)) {
10088 			/* Old offset (both fixed and variable parts) should
10089 			 * have been known-zero, because we don't allow pointer
10090 			 * arithmetic on pointers that might be NULL. If we
10091 			 * see this happening, don't convert the register.
10092 			 */
10093 			return;
10094 		}
10095 		if (is_null) {
10096 			reg->type = SCALAR_VALUE;
10097 			/* We don't need id and ref_obj_id from this point
10098 			 * onwards anymore, thus we should better reset it,
10099 			 * so that state pruning has chances to take effect.
10100 			 */
10101 			reg->id = 0;
10102 			reg->ref_obj_id = 0;
10103 
10104 			return;
10105 		}
10106 
10107 		mark_ptr_not_null_reg(reg);
10108 
10109 		if (!reg_may_point_to_spin_lock(reg)) {
10110 			/* For not-NULL ptr, reg->ref_obj_id will be reset
10111 			 * in release_reference().
10112 			 *
10113 			 * reg->id is still used by spin_lock ptr. Other
10114 			 * than spin_lock ptr type, reg->id can be reset.
10115 			 */
10116 			reg->id = 0;
10117 		}
10118 	}
10119 }
10120 
10121 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10122  * be folded together at some point.
10123  */
10124 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10125 				  bool is_null)
10126 {
10127 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10128 	struct bpf_reg_state *regs = state->regs, *reg;
10129 	u32 ref_obj_id = regs[regno].ref_obj_id;
10130 	u32 id = regs[regno].id;
10131 
10132 	if (ref_obj_id && ref_obj_id == id && is_null)
10133 		/* regs[regno] is in the " == NULL" branch.
10134 		 * No one could have freed the reference state before
10135 		 * doing the NULL check.
10136 		 */
10137 		WARN_ON_ONCE(release_reference_state(state, id));
10138 
10139 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10140 		mark_ptr_or_null_reg(state, reg, id, is_null);
10141 	}));
10142 }
10143 
10144 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10145 				   struct bpf_reg_state *dst_reg,
10146 				   struct bpf_reg_state *src_reg,
10147 				   struct bpf_verifier_state *this_branch,
10148 				   struct bpf_verifier_state *other_branch)
10149 {
10150 	if (BPF_SRC(insn->code) != BPF_X)
10151 		return false;
10152 
10153 	/* Pointers are always 64-bit. */
10154 	if (BPF_CLASS(insn->code) == BPF_JMP32)
10155 		return false;
10156 
10157 	switch (BPF_OP(insn->code)) {
10158 	case BPF_JGT:
10159 		if ((dst_reg->type == PTR_TO_PACKET &&
10160 		     src_reg->type == PTR_TO_PACKET_END) ||
10161 		    (dst_reg->type == PTR_TO_PACKET_META &&
10162 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10163 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10164 			find_good_pkt_pointers(this_branch, dst_reg,
10165 					       dst_reg->type, false);
10166 			mark_pkt_end(other_branch, insn->dst_reg, true);
10167 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10168 			    src_reg->type == PTR_TO_PACKET) ||
10169 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10170 			    src_reg->type == PTR_TO_PACKET_META)) {
10171 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
10172 			find_good_pkt_pointers(other_branch, src_reg,
10173 					       src_reg->type, true);
10174 			mark_pkt_end(this_branch, insn->src_reg, false);
10175 		} else {
10176 			return false;
10177 		}
10178 		break;
10179 	case BPF_JLT:
10180 		if ((dst_reg->type == PTR_TO_PACKET &&
10181 		     src_reg->type == PTR_TO_PACKET_END) ||
10182 		    (dst_reg->type == PTR_TO_PACKET_META &&
10183 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10184 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10185 			find_good_pkt_pointers(other_branch, dst_reg,
10186 					       dst_reg->type, true);
10187 			mark_pkt_end(this_branch, insn->dst_reg, false);
10188 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10189 			    src_reg->type == PTR_TO_PACKET) ||
10190 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10191 			    src_reg->type == PTR_TO_PACKET_META)) {
10192 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
10193 			find_good_pkt_pointers(this_branch, src_reg,
10194 					       src_reg->type, false);
10195 			mark_pkt_end(other_branch, insn->src_reg, true);
10196 		} else {
10197 			return false;
10198 		}
10199 		break;
10200 	case BPF_JGE:
10201 		if ((dst_reg->type == PTR_TO_PACKET &&
10202 		     src_reg->type == PTR_TO_PACKET_END) ||
10203 		    (dst_reg->type == PTR_TO_PACKET_META &&
10204 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10205 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10206 			find_good_pkt_pointers(this_branch, dst_reg,
10207 					       dst_reg->type, true);
10208 			mark_pkt_end(other_branch, insn->dst_reg, false);
10209 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10210 			    src_reg->type == PTR_TO_PACKET) ||
10211 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10212 			    src_reg->type == PTR_TO_PACKET_META)) {
10213 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10214 			find_good_pkt_pointers(other_branch, src_reg,
10215 					       src_reg->type, false);
10216 			mark_pkt_end(this_branch, insn->src_reg, true);
10217 		} else {
10218 			return false;
10219 		}
10220 		break;
10221 	case BPF_JLE:
10222 		if ((dst_reg->type == PTR_TO_PACKET &&
10223 		     src_reg->type == PTR_TO_PACKET_END) ||
10224 		    (dst_reg->type == PTR_TO_PACKET_META &&
10225 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10226 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10227 			find_good_pkt_pointers(other_branch, dst_reg,
10228 					       dst_reg->type, false);
10229 			mark_pkt_end(this_branch, insn->dst_reg, true);
10230 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10231 			    src_reg->type == PTR_TO_PACKET) ||
10232 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10233 			    src_reg->type == PTR_TO_PACKET_META)) {
10234 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10235 			find_good_pkt_pointers(this_branch, src_reg,
10236 					       src_reg->type, true);
10237 			mark_pkt_end(other_branch, insn->src_reg, false);
10238 		} else {
10239 			return false;
10240 		}
10241 		break;
10242 	default:
10243 		return false;
10244 	}
10245 
10246 	return true;
10247 }
10248 
10249 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10250 			       struct bpf_reg_state *known_reg)
10251 {
10252 	struct bpf_func_state *state;
10253 	struct bpf_reg_state *reg;
10254 
10255 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10256 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10257 			*reg = *known_reg;
10258 	}));
10259 }
10260 
10261 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10262 			     struct bpf_insn *insn, int *insn_idx)
10263 {
10264 	struct bpf_verifier_state *this_branch = env->cur_state;
10265 	struct bpf_verifier_state *other_branch;
10266 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10267 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10268 	u8 opcode = BPF_OP(insn->code);
10269 	bool is_jmp32;
10270 	int pred = -1;
10271 	int err;
10272 
10273 	/* Only conditional jumps are expected to reach here. */
10274 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
10275 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10276 		return -EINVAL;
10277 	}
10278 
10279 	if (BPF_SRC(insn->code) == BPF_X) {
10280 		if (insn->imm != 0) {
10281 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10282 			return -EINVAL;
10283 		}
10284 
10285 		/* check src1 operand */
10286 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10287 		if (err)
10288 			return err;
10289 
10290 		if (is_pointer_value(env, insn->src_reg)) {
10291 			verbose(env, "R%d pointer comparison prohibited\n",
10292 				insn->src_reg);
10293 			return -EACCES;
10294 		}
10295 		src_reg = &regs[insn->src_reg];
10296 	} else {
10297 		if (insn->src_reg != BPF_REG_0) {
10298 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10299 			return -EINVAL;
10300 		}
10301 	}
10302 
10303 	/* check src2 operand */
10304 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10305 	if (err)
10306 		return err;
10307 
10308 	dst_reg = &regs[insn->dst_reg];
10309 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10310 
10311 	if (BPF_SRC(insn->code) == BPF_K) {
10312 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10313 	} else if (src_reg->type == SCALAR_VALUE &&
10314 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10315 		pred = is_branch_taken(dst_reg,
10316 				       tnum_subreg(src_reg->var_off).value,
10317 				       opcode,
10318 				       is_jmp32);
10319 	} else if (src_reg->type == SCALAR_VALUE &&
10320 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10321 		pred = is_branch_taken(dst_reg,
10322 				       src_reg->var_off.value,
10323 				       opcode,
10324 				       is_jmp32);
10325 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
10326 		   reg_is_pkt_pointer_any(src_reg) &&
10327 		   !is_jmp32) {
10328 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10329 	}
10330 
10331 	if (pred >= 0) {
10332 		/* If we get here with a dst_reg pointer type it is because
10333 		 * above is_branch_taken() special cased the 0 comparison.
10334 		 */
10335 		if (!__is_pointer_value(false, dst_reg))
10336 			err = mark_chain_precision(env, insn->dst_reg);
10337 		if (BPF_SRC(insn->code) == BPF_X && !err &&
10338 		    !__is_pointer_value(false, src_reg))
10339 			err = mark_chain_precision(env, insn->src_reg);
10340 		if (err)
10341 			return err;
10342 	}
10343 
10344 	if (pred == 1) {
10345 		/* Only follow the goto, ignore fall-through. If needed, push
10346 		 * the fall-through branch for simulation under speculative
10347 		 * execution.
10348 		 */
10349 		if (!env->bypass_spec_v1 &&
10350 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
10351 					       *insn_idx))
10352 			return -EFAULT;
10353 		*insn_idx += insn->off;
10354 		return 0;
10355 	} else if (pred == 0) {
10356 		/* Only follow the fall-through branch, since that's where the
10357 		 * program will go. If needed, push the goto branch for
10358 		 * simulation under speculative execution.
10359 		 */
10360 		if (!env->bypass_spec_v1 &&
10361 		    !sanitize_speculative_path(env, insn,
10362 					       *insn_idx + insn->off + 1,
10363 					       *insn_idx))
10364 			return -EFAULT;
10365 		return 0;
10366 	}
10367 
10368 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10369 				  false);
10370 	if (!other_branch)
10371 		return -EFAULT;
10372 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10373 
10374 	/* detect if we are comparing against a constant value so we can adjust
10375 	 * our min/max values for our dst register.
10376 	 * this is only legit if both are scalars (or pointers to the same
10377 	 * object, I suppose, but we don't support that right now), because
10378 	 * otherwise the different base pointers mean the offsets aren't
10379 	 * comparable.
10380 	 */
10381 	if (BPF_SRC(insn->code) == BPF_X) {
10382 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10383 
10384 		if (dst_reg->type == SCALAR_VALUE &&
10385 		    src_reg->type == SCALAR_VALUE) {
10386 			if (tnum_is_const(src_reg->var_off) ||
10387 			    (is_jmp32 &&
10388 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
10389 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
10390 						dst_reg,
10391 						src_reg->var_off.value,
10392 						tnum_subreg(src_reg->var_off).value,
10393 						opcode, is_jmp32);
10394 			else if (tnum_is_const(dst_reg->var_off) ||
10395 				 (is_jmp32 &&
10396 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
10397 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10398 						    src_reg,
10399 						    dst_reg->var_off.value,
10400 						    tnum_subreg(dst_reg->var_off).value,
10401 						    opcode, is_jmp32);
10402 			else if (!is_jmp32 &&
10403 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
10404 				/* Comparing for equality, we can combine knowledge */
10405 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
10406 						    &other_branch_regs[insn->dst_reg],
10407 						    src_reg, dst_reg, opcode);
10408 			if (src_reg->id &&
10409 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10410 				find_equal_scalars(this_branch, src_reg);
10411 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10412 			}
10413 
10414 		}
10415 	} else if (dst_reg->type == SCALAR_VALUE) {
10416 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
10417 					dst_reg, insn->imm, (u32)insn->imm,
10418 					opcode, is_jmp32);
10419 	}
10420 
10421 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10422 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10423 		find_equal_scalars(this_branch, dst_reg);
10424 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10425 	}
10426 
10427 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10428 	 * NOTE: these optimizations below are related with pointer comparison
10429 	 *       which will never be JMP32.
10430 	 */
10431 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10432 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10433 	    type_may_be_null(dst_reg->type)) {
10434 		/* Mark all identical registers in each branch as either
10435 		 * safe or unknown depending R == 0 or R != 0 conditional.
10436 		 */
10437 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10438 				      opcode == BPF_JNE);
10439 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10440 				      opcode == BPF_JEQ);
10441 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10442 					   this_branch, other_branch) &&
10443 		   is_pointer_value(env, insn->dst_reg)) {
10444 		verbose(env, "R%d pointer comparison prohibited\n",
10445 			insn->dst_reg);
10446 		return -EACCES;
10447 	}
10448 	if (env->log.level & BPF_LOG_LEVEL)
10449 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
10450 	return 0;
10451 }
10452 
10453 /* verify BPF_LD_IMM64 instruction */
10454 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10455 {
10456 	struct bpf_insn_aux_data *aux = cur_aux(env);
10457 	struct bpf_reg_state *regs = cur_regs(env);
10458 	struct bpf_reg_state *dst_reg;
10459 	struct bpf_map *map;
10460 	int err;
10461 
10462 	if (BPF_SIZE(insn->code) != BPF_DW) {
10463 		verbose(env, "invalid BPF_LD_IMM insn\n");
10464 		return -EINVAL;
10465 	}
10466 	if (insn->off != 0) {
10467 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10468 		return -EINVAL;
10469 	}
10470 
10471 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
10472 	if (err)
10473 		return err;
10474 
10475 	dst_reg = &regs[insn->dst_reg];
10476 	if (insn->src_reg == 0) {
10477 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10478 
10479 		dst_reg->type = SCALAR_VALUE;
10480 		__mark_reg_known(&regs[insn->dst_reg], imm);
10481 		return 0;
10482 	}
10483 
10484 	/* All special src_reg cases are listed below. From this point onwards
10485 	 * we either succeed and assign a corresponding dst_reg->type after
10486 	 * zeroing the offset, or fail and reject the program.
10487 	 */
10488 	mark_reg_known_zero(env, regs, insn->dst_reg);
10489 
10490 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10491 		dst_reg->type = aux->btf_var.reg_type;
10492 		switch (base_type(dst_reg->type)) {
10493 		case PTR_TO_MEM:
10494 			dst_reg->mem_size = aux->btf_var.mem_size;
10495 			break;
10496 		case PTR_TO_BTF_ID:
10497 			dst_reg->btf = aux->btf_var.btf;
10498 			dst_reg->btf_id = aux->btf_var.btf_id;
10499 			break;
10500 		default:
10501 			verbose(env, "bpf verifier is misconfigured\n");
10502 			return -EFAULT;
10503 		}
10504 		return 0;
10505 	}
10506 
10507 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
10508 		struct bpf_prog_aux *aux = env->prog->aux;
10509 		u32 subprogno = find_subprog(env,
10510 					     env->insn_idx + insn->imm + 1);
10511 
10512 		if (!aux->func_info) {
10513 			verbose(env, "missing btf func_info\n");
10514 			return -EINVAL;
10515 		}
10516 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10517 			verbose(env, "callback function not static\n");
10518 			return -EINVAL;
10519 		}
10520 
10521 		dst_reg->type = PTR_TO_FUNC;
10522 		dst_reg->subprogno = subprogno;
10523 		return 0;
10524 	}
10525 
10526 	map = env->used_maps[aux->map_index];
10527 	dst_reg->map_ptr = map;
10528 
10529 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10530 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10531 		dst_reg->type = PTR_TO_MAP_VALUE;
10532 		dst_reg->off = aux->map_off;
10533 		if (btf_record_has_field(map->record, BPF_SPIN_LOCK))
10534 			dst_reg->id = ++env->id_gen;
10535 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10536 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10537 		dst_reg->type = CONST_PTR_TO_MAP;
10538 	} else {
10539 		verbose(env, "bpf verifier is misconfigured\n");
10540 		return -EINVAL;
10541 	}
10542 
10543 	return 0;
10544 }
10545 
10546 static bool may_access_skb(enum bpf_prog_type type)
10547 {
10548 	switch (type) {
10549 	case BPF_PROG_TYPE_SOCKET_FILTER:
10550 	case BPF_PROG_TYPE_SCHED_CLS:
10551 	case BPF_PROG_TYPE_SCHED_ACT:
10552 		return true;
10553 	default:
10554 		return false;
10555 	}
10556 }
10557 
10558 /* verify safety of LD_ABS|LD_IND instructions:
10559  * - they can only appear in the programs where ctx == skb
10560  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10561  *   preserve R6-R9, and store return value into R0
10562  *
10563  * Implicit input:
10564  *   ctx == skb == R6 == CTX
10565  *
10566  * Explicit input:
10567  *   SRC == any register
10568  *   IMM == 32-bit immediate
10569  *
10570  * Output:
10571  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10572  */
10573 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10574 {
10575 	struct bpf_reg_state *regs = cur_regs(env);
10576 	static const int ctx_reg = BPF_REG_6;
10577 	u8 mode = BPF_MODE(insn->code);
10578 	int i, err;
10579 
10580 	if (!may_access_skb(resolve_prog_type(env->prog))) {
10581 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10582 		return -EINVAL;
10583 	}
10584 
10585 	if (!env->ops->gen_ld_abs) {
10586 		verbose(env, "bpf verifier is misconfigured\n");
10587 		return -EINVAL;
10588 	}
10589 
10590 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10591 	    BPF_SIZE(insn->code) == BPF_DW ||
10592 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10593 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10594 		return -EINVAL;
10595 	}
10596 
10597 	/* check whether implicit source operand (register R6) is readable */
10598 	err = check_reg_arg(env, ctx_reg, SRC_OP);
10599 	if (err)
10600 		return err;
10601 
10602 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10603 	 * gen_ld_abs() may terminate the program at runtime, leading to
10604 	 * reference leak.
10605 	 */
10606 	err = check_reference_leak(env);
10607 	if (err) {
10608 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10609 		return err;
10610 	}
10611 
10612 	if (env->cur_state->active_spin_lock) {
10613 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10614 		return -EINVAL;
10615 	}
10616 
10617 	if (regs[ctx_reg].type != PTR_TO_CTX) {
10618 		verbose(env,
10619 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10620 		return -EINVAL;
10621 	}
10622 
10623 	if (mode == BPF_IND) {
10624 		/* check explicit source operand */
10625 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10626 		if (err)
10627 			return err;
10628 	}
10629 
10630 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10631 	if (err < 0)
10632 		return err;
10633 
10634 	/* reset caller saved regs to unreadable */
10635 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10636 		mark_reg_not_init(env, regs, caller_saved[i]);
10637 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10638 	}
10639 
10640 	/* mark destination R0 register as readable, since it contains
10641 	 * the value fetched from the packet.
10642 	 * Already marked as written above.
10643 	 */
10644 	mark_reg_unknown(env, regs, BPF_REG_0);
10645 	/* ld_abs load up to 32-bit skb data. */
10646 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10647 	return 0;
10648 }
10649 
10650 static int check_return_code(struct bpf_verifier_env *env)
10651 {
10652 	struct tnum enforce_attach_type_range = tnum_unknown;
10653 	const struct bpf_prog *prog = env->prog;
10654 	struct bpf_reg_state *reg;
10655 	struct tnum range = tnum_range(0, 1);
10656 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10657 	int err;
10658 	struct bpf_func_state *frame = env->cur_state->frame[0];
10659 	const bool is_subprog = frame->subprogno;
10660 
10661 	/* LSM and struct_ops func-ptr's return type could be "void" */
10662 	if (!is_subprog) {
10663 		switch (prog_type) {
10664 		case BPF_PROG_TYPE_LSM:
10665 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
10666 				/* See below, can be 0 or 0-1 depending on hook. */
10667 				break;
10668 			fallthrough;
10669 		case BPF_PROG_TYPE_STRUCT_OPS:
10670 			if (!prog->aux->attach_func_proto->type)
10671 				return 0;
10672 			break;
10673 		default:
10674 			break;
10675 		}
10676 	}
10677 
10678 	/* eBPF calling convention is such that R0 is used
10679 	 * to return the value from eBPF program.
10680 	 * Make sure that it's readable at this time
10681 	 * of bpf_exit, which means that program wrote
10682 	 * something into it earlier
10683 	 */
10684 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10685 	if (err)
10686 		return err;
10687 
10688 	if (is_pointer_value(env, BPF_REG_0)) {
10689 		verbose(env, "R0 leaks addr as return value\n");
10690 		return -EACCES;
10691 	}
10692 
10693 	reg = cur_regs(env) + BPF_REG_0;
10694 
10695 	if (frame->in_async_callback_fn) {
10696 		/* enforce return zero from async callbacks like timer */
10697 		if (reg->type != SCALAR_VALUE) {
10698 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10699 				reg_type_str(env, reg->type));
10700 			return -EINVAL;
10701 		}
10702 
10703 		if (!tnum_in(tnum_const(0), reg->var_off)) {
10704 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10705 			return -EINVAL;
10706 		}
10707 		return 0;
10708 	}
10709 
10710 	if (is_subprog) {
10711 		if (reg->type != SCALAR_VALUE) {
10712 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10713 				reg_type_str(env, reg->type));
10714 			return -EINVAL;
10715 		}
10716 		return 0;
10717 	}
10718 
10719 	switch (prog_type) {
10720 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10721 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10722 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10723 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10724 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10725 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10726 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10727 			range = tnum_range(1, 1);
10728 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10729 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10730 			range = tnum_range(0, 3);
10731 		break;
10732 	case BPF_PROG_TYPE_CGROUP_SKB:
10733 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10734 			range = tnum_range(0, 3);
10735 			enforce_attach_type_range = tnum_range(2, 3);
10736 		}
10737 		break;
10738 	case BPF_PROG_TYPE_CGROUP_SOCK:
10739 	case BPF_PROG_TYPE_SOCK_OPS:
10740 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10741 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10742 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10743 		break;
10744 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10745 		if (!env->prog->aux->attach_btf_id)
10746 			return 0;
10747 		range = tnum_const(0);
10748 		break;
10749 	case BPF_PROG_TYPE_TRACING:
10750 		switch (env->prog->expected_attach_type) {
10751 		case BPF_TRACE_FENTRY:
10752 		case BPF_TRACE_FEXIT:
10753 			range = tnum_const(0);
10754 			break;
10755 		case BPF_TRACE_RAW_TP:
10756 		case BPF_MODIFY_RETURN:
10757 			return 0;
10758 		case BPF_TRACE_ITER:
10759 			break;
10760 		default:
10761 			return -ENOTSUPP;
10762 		}
10763 		break;
10764 	case BPF_PROG_TYPE_SK_LOOKUP:
10765 		range = tnum_range(SK_DROP, SK_PASS);
10766 		break;
10767 
10768 	case BPF_PROG_TYPE_LSM:
10769 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10770 			/* Regular BPF_PROG_TYPE_LSM programs can return
10771 			 * any value.
10772 			 */
10773 			return 0;
10774 		}
10775 		if (!env->prog->aux->attach_func_proto->type) {
10776 			/* Make sure programs that attach to void
10777 			 * hooks don't try to modify return value.
10778 			 */
10779 			range = tnum_range(1, 1);
10780 		}
10781 		break;
10782 
10783 	case BPF_PROG_TYPE_EXT:
10784 		/* freplace program can return anything as its return value
10785 		 * depends on the to-be-replaced kernel func or bpf program.
10786 		 */
10787 	default:
10788 		return 0;
10789 	}
10790 
10791 	if (reg->type != SCALAR_VALUE) {
10792 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10793 			reg_type_str(env, reg->type));
10794 		return -EINVAL;
10795 	}
10796 
10797 	if (!tnum_in(range, reg->var_off)) {
10798 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10799 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10800 		    prog_type == BPF_PROG_TYPE_LSM &&
10801 		    !prog->aux->attach_func_proto->type)
10802 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10803 		return -EINVAL;
10804 	}
10805 
10806 	if (!tnum_is_unknown(enforce_attach_type_range) &&
10807 	    tnum_in(enforce_attach_type_range, reg->var_off))
10808 		env->prog->enforce_expected_attach_type = 1;
10809 	return 0;
10810 }
10811 
10812 /* non-recursive DFS pseudo code
10813  * 1  procedure DFS-iterative(G,v):
10814  * 2      label v as discovered
10815  * 3      let S be a stack
10816  * 4      S.push(v)
10817  * 5      while S is not empty
10818  * 6            t <- S.peek()
10819  * 7            if t is what we're looking for:
10820  * 8                return t
10821  * 9            for all edges e in G.adjacentEdges(t) do
10822  * 10               if edge e is already labelled
10823  * 11                   continue with the next edge
10824  * 12               w <- G.adjacentVertex(t,e)
10825  * 13               if vertex w is not discovered and not explored
10826  * 14                   label e as tree-edge
10827  * 15                   label w as discovered
10828  * 16                   S.push(w)
10829  * 17                   continue at 5
10830  * 18               else if vertex w is discovered
10831  * 19                   label e as back-edge
10832  * 20               else
10833  * 21                   // vertex w is explored
10834  * 22                   label e as forward- or cross-edge
10835  * 23           label t as explored
10836  * 24           S.pop()
10837  *
10838  * convention:
10839  * 0x10 - discovered
10840  * 0x11 - discovered and fall-through edge labelled
10841  * 0x12 - discovered and fall-through and branch edges labelled
10842  * 0x20 - explored
10843  */
10844 
10845 enum {
10846 	DISCOVERED = 0x10,
10847 	EXPLORED = 0x20,
10848 	FALLTHROUGH = 1,
10849 	BRANCH = 2,
10850 };
10851 
10852 static u32 state_htab_size(struct bpf_verifier_env *env)
10853 {
10854 	return env->prog->len;
10855 }
10856 
10857 static struct bpf_verifier_state_list **explored_state(
10858 					struct bpf_verifier_env *env,
10859 					int idx)
10860 {
10861 	struct bpf_verifier_state *cur = env->cur_state;
10862 	struct bpf_func_state *state = cur->frame[cur->curframe];
10863 
10864 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10865 }
10866 
10867 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10868 {
10869 	env->insn_aux_data[idx].prune_point = true;
10870 }
10871 
10872 enum {
10873 	DONE_EXPLORING = 0,
10874 	KEEP_EXPLORING = 1,
10875 };
10876 
10877 /* t, w, e - match pseudo-code above:
10878  * t - index of current instruction
10879  * w - next instruction
10880  * e - edge
10881  */
10882 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10883 		     bool loop_ok)
10884 {
10885 	int *insn_stack = env->cfg.insn_stack;
10886 	int *insn_state = env->cfg.insn_state;
10887 
10888 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10889 		return DONE_EXPLORING;
10890 
10891 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10892 		return DONE_EXPLORING;
10893 
10894 	if (w < 0 || w >= env->prog->len) {
10895 		verbose_linfo(env, t, "%d: ", t);
10896 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10897 		return -EINVAL;
10898 	}
10899 
10900 	if (e == BRANCH)
10901 		/* mark branch target for state pruning */
10902 		init_explored_state(env, w);
10903 
10904 	if (insn_state[w] == 0) {
10905 		/* tree-edge */
10906 		insn_state[t] = DISCOVERED | e;
10907 		insn_state[w] = DISCOVERED;
10908 		if (env->cfg.cur_stack >= env->prog->len)
10909 			return -E2BIG;
10910 		insn_stack[env->cfg.cur_stack++] = w;
10911 		return KEEP_EXPLORING;
10912 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10913 		if (loop_ok && env->bpf_capable)
10914 			return DONE_EXPLORING;
10915 		verbose_linfo(env, t, "%d: ", t);
10916 		verbose_linfo(env, w, "%d: ", w);
10917 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10918 		return -EINVAL;
10919 	} else if (insn_state[w] == EXPLORED) {
10920 		/* forward- or cross-edge */
10921 		insn_state[t] = DISCOVERED | e;
10922 	} else {
10923 		verbose(env, "insn state internal bug\n");
10924 		return -EFAULT;
10925 	}
10926 	return DONE_EXPLORING;
10927 }
10928 
10929 static int visit_func_call_insn(int t, int insn_cnt,
10930 				struct bpf_insn *insns,
10931 				struct bpf_verifier_env *env,
10932 				bool visit_callee)
10933 {
10934 	int ret;
10935 
10936 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10937 	if (ret)
10938 		return ret;
10939 
10940 	if (t + 1 < insn_cnt)
10941 		init_explored_state(env, t + 1);
10942 	if (visit_callee) {
10943 		init_explored_state(env, t);
10944 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10945 				/* It's ok to allow recursion from CFG point of
10946 				 * view. __check_func_call() will do the actual
10947 				 * check.
10948 				 */
10949 				bpf_pseudo_func(insns + t));
10950 	}
10951 	return ret;
10952 }
10953 
10954 /* Visits the instruction at index t and returns one of the following:
10955  *  < 0 - an error occurred
10956  *  DONE_EXPLORING - the instruction was fully explored
10957  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10958  */
10959 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10960 {
10961 	struct bpf_insn *insns = env->prog->insnsi;
10962 	int ret;
10963 
10964 	if (bpf_pseudo_func(insns + t))
10965 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10966 
10967 	/* All non-branch instructions have a single fall-through edge. */
10968 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10969 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10970 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10971 
10972 	switch (BPF_OP(insns[t].code)) {
10973 	case BPF_EXIT:
10974 		return DONE_EXPLORING;
10975 
10976 	case BPF_CALL:
10977 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10978 			/* Mark this call insn to trigger is_state_visited() check
10979 			 * before call itself is processed by __check_func_call().
10980 			 * Otherwise new async state will be pushed for further
10981 			 * exploration.
10982 			 */
10983 			init_explored_state(env, t);
10984 		return visit_func_call_insn(t, insn_cnt, insns, env,
10985 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10986 
10987 	case BPF_JA:
10988 		if (BPF_SRC(insns[t].code) != BPF_K)
10989 			return -EINVAL;
10990 
10991 		/* unconditional jump with single edge */
10992 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10993 				true);
10994 		if (ret)
10995 			return ret;
10996 
10997 		/* unconditional jmp is not a good pruning point,
10998 		 * but it's marked, since backtracking needs
10999 		 * to record jmp history in is_state_visited().
11000 		 */
11001 		init_explored_state(env, t + insns[t].off + 1);
11002 		/* tell verifier to check for equivalent states
11003 		 * after every call and jump
11004 		 */
11005 		if (t + 1 < insn_cnt)
11006 			init_explored_state(env, t + 1);
11007 
11008 		return ret;
11009 
11010 	default:
11011 		/* conditional jump with two edges */
11012 		init_explored_state(env, t);
11013 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
11014 		if (ret)
11015 			return ret;
11016 
11017 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
11018 	}
11019 }
11020 
11021 /* non-recursive depth-first-search to detect loops in BPF program
11022  * loop == back-edge in directed graph
11023  */
11024 static int check_cfg(struct bpf_verifier_env *env)
11025 {
11026 	int insn_cnt = env->prog->len;
11027 	int *insn_stack, *insn_state;
11028 	int ret = 0;
11029 	int i;
11030 
11031 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
11032 	if (!insn_state)
11033 		return -ENOMEM;
11034 
11035 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
11036 	if (!insn_stack) {
11037 		kvfree(insn_state);
11038 		return -ENOMEM;
11039 	}
11040 
11041 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
11042 	insn_stack[0] = 0; /* 0 is the first instruction */
11043 	env->cfg.cur_stack = 1;
11044 
11045 	while (env->cfg.cur_stack > 0) {
11046 		int t = insn_stack[env->cfg.cur_stack - 1];
11047 
11048 		ret = visit_insn(t, insn_cnt, env);
11049 		switch (ret) {
11050 		case DONE_EXPLORING:
11051 			insn_state[t] = EXPLORED;
11052 			env->cfg.cur_stack--;
11053 			break;
11054 		case KEEP_EXPLORING:
11055 			break;
11056 		default:
11057 			if (ret > 0) {
11058 				verbose(env, "visit_insn internal bug\n");
11059 				ret = -EFAULT;
11060 			}
11061 			goto err_free;
11062 		}
11063 	}
11064 
11065 	if (env->cfg.cur_stack < 0) {
11066 		verbose(env, "pop stack internal bug\n");
11067 		ret = -EFAULT;
11068 		goto err_free;
11069 	}
11070 
11071 	for (i = 0; i < insn_cnt; i++) {
11072 		if (insn_state[i] != EXPLORED) {
11073 			verbose(env, "unreachable insn %d\n", i);
11074 			ret = -EINVAL;
11075 			goto err_free;
11076 		}
11077 	}
11078 	ret = 0; /* cfg looks good */
11079 
11080 err_free:
11081 	kvfree(insn_state);
11082 	kvfree(insn_stack);
11083 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
11084 	return ret;
11085 }
11086 
11087 static int check_abnormal_return(struct bpf_verifier_env *env)
11088 {
11089 	int i;
11090 
11091 	for (i = 1; i < env->subprog_cnt; i++) {
11092 		if (env->subprog_info[i].has_ld_abs) {
11093 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11094 			return -EINVAL;
11095 		}
11096 		if (env->subprog_info[i].has_tail_call) {
11097 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11098 			return -EINVAL;
11099 		}
11100 	}
11101 	return 0;
11102 }
11103 
11104 /* The minimum supported BTF func info size */
11105 #define MIN_BPF_FUNCINFO_SIZE	8
11106 #define MAX_FUNCINFO_REC_SIZE	252
11107 
11108 static int check_btf_func(struct bpf_verifier_env *env,
11109 			  const union bpf_attr *attr,
11110 			  bpfptr_t uattr)
11111 {
11112 	const struct btf_type *type, *func_proto, *ret_type;
11113 	u32 i, nfuncs, urec_size, min_size;
11114 	u32 krec_size = sizeof(struct bpf_func_info);
11115 	struct bpf_func_info *krecord;
11116 	struct bpf_func_info_aux *info_aux = NULL;
11117 	struct bpf_prog *prog;
11118 	const struct btf *btf;
11119 	bpfptr_t urecord;
11120 	u32 prev_offset = 0;
11121 	bool scalar_return;
11122 	int ret = -ENOMEM;
11123 
11124 	nfuncs = attr->func_info_cnt;
11125 	if (!nfuncs) {
11126 		if (check_abnormal_return(env))
11127 			return -EINVAL;
11128 		return 0;
11129 	}
11130 
11131 	if (nfuncs != env->subprog_cnt) {
11132 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11133 		return -EINVAL;
11134 	}
11135 
11136 	urec_size = attr->func_info_rec_size;
11137 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11138 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
11139 	    urec_size % sizeof(u32)) {
11140 		verbose(env, "invalid func info rec size %u\n", urec_size);
11141 		return -EINVAL;
11142 	}
11143 
11144 	prog = env->prog;
11145 	btf = prog->aux->btf;
11146 
11147 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11148 	min_size = min_t(u32, krec_size, urec_size);
11149 
11150 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11151 	if (!krecord)
11152 		return -ENOMEM;
11153 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11154 	if (!info_aux)
11155 		goto err_free;
11156 
11157 	for (i = 0; i < nfuncs; i++) {
11158 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11159 		if (ret) {
11160 			if (ret == -E2BIG) {
11161 				verbose(env, "nonzero tailing record in func info");
11162 				/* set the size kernel expects so loader can zero
11163 				 * out the rest of the record.
11164 				 */
11165 				if (copy_to_bpfptr_offset(uattr,
11166 							  offsetof(union bpf_attr, func_info_rec_size),
11167 							  &min_size, sizeof(min_size)))
11168 					ret = -EFAULT;
11169 			}
11170 			goto err_free;
11171 		}
11172 
11173 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11174 			ret = -EFAULT;
11175 			goto err_free;
11176 		}
11177 
11178 		/* check insn_off */
11179 		ret = -EINVAL;
11180 		if (i == 0) {
11181 			if (krecord[i].insn_off) {
11182 				verbose(env,
11183 					"nonzero insn_off %u for the first func info record",
11184 					krecord[i].insn_off);
11185 				goto err_free;
11186 			}
11187 		} else if (krecord[i].insn_off <= prev_offset) {
11188 			verbose(env,
11189 				"same or smaller insn offset (%u) than previous func info record (%u)",
11190 				krecord[i].insn_off, prev_offset);
11191 			goto err_free;
11192 		}
11193 
11194 		if (env->subprog_info[i].start != krecord[i].insn_off) {
11195 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11196 			goto err_free;
11197 		}
11198 
11199 		/* check type_id */
11200 		type = btf_type_by_id(btf, krecord[i].type_id);
11201 		if (!type || !btf_type_is_func(type)) {
11202 			verbose(env, "invalid type id %d in func info",
11203 				krecord[i].type_id);
11204 			goto err_free;
11205 		}
11206 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11207 
11208 		func_proto = btf_type_by_id(btf, type->type);
11209 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11210 			/* btf_func_check() already verified it during BTF load */
11211 			goto err_free;
11212 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11213 		scalar_return =
11214 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11215 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11216 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11217 			goto err_free;
11218 		}
11219 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11220 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11221 			goto err_free;
11222 		}
11223 
11224 		prev_offset = krecord[i].insn_off;
11225 		bpfptr_add(&urecord, urec_size);
11226 	}
11227 
11228 	prog->aux->func_info = krecord;
11229 	prog->aux->func_info_cnt = nfuncs;
11230 	prog->aux->func_info_aux = info_aux;
11231 	return 0;
11232 
11233 err_free:
11234 	kvfree(krecord);
11235 	kfree(info_aux);
11236 	return ret;
11237 }
11238 
11239 static void adjust_btf_func(struct bpf_verifier_env *env)
11240 {
11241 	struct bpf_prog_aux *aux = env->prog->aux;
11242 	int i;
11243 
11244 	if (!aux->func_info)
11245 		return;
11246 
11247 	for (i = 0; i < env->subprog_cnt; i++)
11248 		aux->func_info[i].insn_off = env->subprog_info[i].start;
11249 }
11250 
11251 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
11252 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
11253 
11254 static int check_btf_line(struct bpf_verifier_env *env,
11255 			  const union bpf_attr *attr,
11256 			  bpfptr_t uattr)
11257 {
11258 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11259 	struct bpf_subprog_info *sub;
11260 	struct bpf_line_info *linfo;
11261 	struct bpf_prog *prog;
11262 	const struct btf *btf;
11263 	bpfptr_t ulinfo;
11264 	int err;
11265 
11266 	nr_linfo = attr->line_info_cnt;
11267 	if (!nr_linfo)
11268 		return 0;
11269 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11270 		return -EINVAL;
11271 
11272 	rec_size = attr->line_info_rec_size;
11273 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11274 	    rec_size > MAX_LINEINFO_REC_SIZE ||
11275 	    rec_size & (sizeof(u32) - 1))
11276 		return -EINVAL;
11277 
11278 	/* Need to zero it in case the userspace may
11279 	 * pass in a smaller bpf_line_info object.
11280 	 */
11281 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11282 			 GFP_KERNEL | __GFP_NOWARN);
11283 	if (!linfo)
11284 		return -ENOMEM;
11285 
11286 	prog = env->prog;
11287 	btf = prog->aux->btf;
11288 
11289 	s = 0;
11290 	sub = env->subprog_info;
11291 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11292 	expected_size = sizeof(struct bpf_line_info);
11293 	ncopy = min_t(u32, expected_size, rec_size);
11294 	for (i = 0; i < nr_linfo; i++) {
11295 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11296 		if (err) {
11297 			if (err == -E2BIG) {
11298 				verbose(env, "nonzero tailing record in line_info");
11299 				if (copy_to_bpfptr_offset(uattr,
11300 							  offsetof(union bpf_attr, line_info_rec_size),
11301 							  &expected_size, sizeof(expected_size)))
11302 					err = -EFAULT;
11303 			}
11304 			goto err_free;
11305 		}
11306 
11307 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11308 			err = -EFAULT;
11309 			goto err_free;
11310 		}
11311 
11312 		/*
11313 		 * Check insn_off to ensure
11314 		 * 1) strictly increasing AND
11315 		 * 2) bounded by prog->len
11316 		 *
11317 		 * The linfo[0].insn_off == 0 check logically falls into
11318 		 * the later "missing bpf_line_info for func..." case
11319 		 * because the first linfo[0].insn_off must be the
11320 		 * first sub also and the first sub must have
11321 		 * subprog_info[0].start == 0.
11322 		 */
11323 		if ((i && linfo[i].insn_off <= prev_offset) ||
11324 		    linfo[i].insn_off >= prog->len) {
11325 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11326 				i, linfo[i].insn_off, prev_offset,
11327 				prog->len);
11328 			err = -EINVAL;
11329 			goto err_free;
11330 		}
11331 
11332 		if (!prog->insnsi[linfo[i].insn_off].code) {
11333 			verbose(env,
11334 				"Invalid insn code at line_info[%u].insn_off\n",
11335 				i);
11336 			err = -EINVAL;
11337 			goto err_free;
11338 		}
11339 
11340 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11341 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11342 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11343 			err = -EINVAL;
11344 			goto err_free;
11345 		}
11346 
11347 		if (s != env->subprog_cnt) {
11348 			if (linfo[i].insn_off == sub[s].start) {
11349 				sub[s].linfo_idx = i;
11350 				s++;
11351 			} else if (sub[s].start < linfo[i].insn_off) {
11352 				verbose(env, "missing bpf_line_info for func#%u\n", s);
11353 				err = -EINVAL;
11354 				goto err_free;
11355 			}
11356 		}
11357 
11358 		prev_offset = linfo[i].insn_off;
11359 		bpfptr_add(&ulinfo, rec_size);
11360 	}
11361 
11362 	if (s != env->subprog_cnt) {
11363 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11364 			env->subprog_cnt - s, s);
11365 		err = -EINVAL;
11366 		goto err_free;
11367 	}
11368 
11369 	prog->aux->linfo = linfo;
11370 	prog->aux->nr_linfo = nr_linfo;
11371 
11372 	return 0;
11373 
11374 err_free:
11375 	kvfree(linfo);
11376 	return err;
11377 }
11378 
11379 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
11380 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
11381 
11382 static int check_core_relo(struct bpf_verifier_env *env,
11383 			   const union bpf_attr *attr,
11384 			   bpfptr_t uattr)
11385 {
11386 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11387 	struct bpf_core_relo core_relo = {};
11388 	struct bpf_prog *prog = env->prog;
11389 	const struct btf *btf = prog->aux->btf;
11390 	struct bpf_core_ctx ctx = {
11391 		.log = &env->log,
11392 		.btf = btf,
11393 	};
11394 	bpfptr_t u_core_relo;
11395 	int err;
11396 
11397 	nr_core_relo = attr->core_relo_cnt;
11398 	if (!nr_core_relo)
11399 		return 0;
11400 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11401 		return -EINVAL;
11402 
11403 	rec_size = attr->core_relo_rec_size;
11404 	if (rec_size < MIN_CORE_RELO_SIZE ||
11405 	    rec_size > MAX_CORE_RELO_SIZE ||
11406 	    rec_size % sizeof(u32))
11407 		return -EINVAL;
11408 
11409 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11410 	expected_size = sizeof(struct bpf_core_relo);
11411 	ncopy = min_t(u32, expected_size, rec_size);
11412 
11413 	/* Unlike func_info and line_info, copy and apply each CO-RE
11414 	 * relocation record one at a time.
11415 	 */
11416 	for (i = 0; i < nr_core_relo; i++) {
11417 		/* future proofing when sizeof(bpf_core_relo) changes */
11418 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11419 		if (err) {
11420 			if (err == -E2BIG) {
11421 				verbose(env, "nonzero tailing record in core_relo");
11422 				if (copy_to_bpfptr_offset(uattr,
11423 							  offsetof(union bpf_attr, core_relo_rec_size),
11424 							  &expected_size, sizeof(expected_size)))
11425 					err = -EFAULT;
11426 			}
11427 			break;
11428 		}
11429 
11430 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11431 			err = -EFAULT;
11432 			break;
11433 		}
11434 
11435 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11436 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11437 				i, core_relo.insn_off, prog->len);
11438 			err = -EINVAL;
11439 			break;
11440 		}
11441 
11442 		err = bpf_core_apply(&ctx, &core_relo, i,
11443 				     &prog->insnsi[core_relo.insn_off / 8]);
11444 		if (err)
11445 			break;
11446 		bpfptr_add(&u_core_relo, rec_size);
11447 	}
11448 	return err;
11449 }
11450 
11451 static int check_btf_info(struct bpf_verifier_env *env,
11452 			  const union bpf_attr *attr,
11453 			  bpfptr_t uattr)
11454 {
11455 	struct btf *btf;
11456 	int err;
11457 
11458 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
11459 		if (check_abnormal_return(env))
11460 			return -EINVAL;
11461 		return 0;
11462 	}
11463 
11464 	btf = btf_get_by_fd(attr->prog_btf_fd);
11465 	if (IS_ERR(btf))
11466 		return PTR_ERR(btf);
11467 	if (btf_is_kernel(btf)) {
11468 		btf_put(btf);
11469 		return -EACCES;
11470 	}
11471 	env->prog->aux->btf = btf;
11472 
11473 	err = check_btf_func(env, attr, uattr);
11474 	if (err)
11475 		return err;
11476 
11477 	err = check_btf_line(env, attr, uattr);
11478 	if (err)
11479 		return err;
11480 
11481 	err = check_core_relo(env, attr, uattr);
11482 	if (err)
11483 		return err;
11484 
11485 	return 0;
11486 }
11487 
11488 /* check %cur's range satisfies %old's */
11489 static bool range_within(struct bpf_reg_state *old,
11490 			 struct bpf_reg_state *cur)
11491 {
11492 	return old->umin_value <= cur->umin_value &&
11493 	       old->umax_value >= cur->umax_value &&
11494 	       old->smin_value <= cur->smin_value &&
11495 	       old->smax_value >= cur->smax_value &&
11496 	       old->u32_min_value <= cur->u32_min_value &&
11497 	       old->u32_max_value >= cur->u32_max_value &&
11498 	       old->s32_min_value <= cur->s32_min_value &&
11499 	       old->s32_max_value >= cur->s32_max_value;
11500 }
11501 
11502 /* If in the old state two registers had the same id, then they need to have
11503  * the same id in the new state as well.  But that id could be different from
11504  * the old state, so we need to track the mapping from old to new ids.
11505  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11506  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11507  * regs with a different old id could still have new id 9, we don't care about
11508  * that.
11509  * So we look through our idmap to see if this old id has been seen before.  If
11510  * so, we require the new id to match; otherwise, we add the id pair to the map.
11511  */
11512 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11513 {
11514 	unsigned int i;
11515 
11516 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11517 		if (!idmap[i].old) {
11518 			/* Reached an empty slot; haven't seen this id before */
11519 			idmap[i].old = old_id;
11520 			idmap[i].cur = cur_id;
11521 			return true;
11522 		}
11523 		if (idmap[i].old == old_id)
11524 			return idmap[i].cur == cur_id;
11525 	}
11526 	/* We ran out of idmap slots, which should be impossible */
11527 	WARN_ON_ONCE(1);
11528 	return false;
11529 }
11530 
11531 static void clean_func_state(struct bpf_verifier_env *env,
11532 			     struct bpf_func_state *st)
11533 {
11534 	enum bpf_reg_liveness live;
11535 	int i, j;
11536 
11537 	for (i = 0; i < BPF_REG_FP; i++) {
11538 		live = st->regs[i].live;
11539 		/* liveness must not touch this register anymore */
11540 		st->regs[i].live |= REG_LIVE_DONE;
11541 		if (!(live & REG_LIVE_READ))
11542 			/* since the register is unused, clear its state
11543 			 * to make further comparison simpler
11544 			 */
11545 			__mark_reg_not_init(env, &st->regs[i]);
11546 	}
11547 
11548 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11549 		live = st->stack[i].spilled_ptr.live;
11550 		/* liveness must not touch this stack slot anymore */
11551 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11552 		if (!(live & REG_LIVE_READ)) {
11553 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11554 			for (j = 0; j < BPF_REG_SIZE; j++)
11555 				st->stack[i].slot_type[j] = STACK_INVALID;
11556 		}
11557 	}
11558 }
11559 
11560 static void clean_verifier_state(struct bpf_verifier_env *env,
11561 				 struct bpf_verifier_state *st)
11562 {
11563 	int i;
11564 
11565 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11566 		/* all regs in this state in all frames were already marked */
11567 		return;
11568 
11569 	for (i = 0; i <= st->curframe; i++)
11570 		clean_func_state(env, st->frame[i]);
11571 }
11572 
11573 /* the parentage chains form a tree.
11574  * the verifier states are added to state lists at given insn and
11575  * pushed into state stack for future exploration.
11576  * when the verifier reaches bpf_exit insn some of the verifer states
11577  * stored in the state lists have their final liveness state already,
11578  * but a lot of states will get revised from liveness point of view when
11579  * the verifier explores other branches.
11580  * Example:
11581  * 1: r0 = 1
11582  * 2: if r1 == 100 goto pc+1
11583  * 3: r0 = 2
11584  * 4: exit
11585  * when the verifier reaches exit insn the register r0 in the state list of
11586  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11587  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11588  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11589  *
11590  * Since the verifier pushes the branch states as it sees them while exploring
11591  * the program the condition of walking the branch instruction for the second
11592  * time means that all states below this branch were already explored and
11593  * their final liveness marks are already propagated.
11594  * Hence when the verifier completes the search of state list in is_state_visited()
11595  * we can call this clean_live_states() function to mark all liveness states
11596  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11597  * will not be used.
11598  * This function also clears the registers and stack for states that !READ
11599  * to simplify state merging.
11600  *
11601  * Important note here that walking the same branch instruction in the callee
11602  * doesn't meant that the states are DONE. The verifier has to compare
11603  * the callsites
11604  */
11605 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11606 			      struct bpf_verifier_state *cur)
11607 {
11608 	struct bpf_verifier_state_list *sl;
11609 	int i;
11610 
11611 	sl = *explored_state(env, insn);
11612 	while (sl) {
11613 		if (sl->state.branches)
11614 			goto next;
11615 		if (sl->state.insn_idx != insn ||
11616 		    sl->state.curframe != cur->curframe)
11617 			goto next;
11618 		for (i = 0; i <= cur->curframe; i++)
11619 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11620 				goto next;
11621 		clean_verifier_state(env, &sl->state);
11622 next:
11623 		sl = sl->next;
11624 	}
11625 }
11626 
11627 /* Returns true if (rold safe implies rcur safe) */
11628 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11629 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11630 {
11631 	bool equal;
11632 
11633 	if (!(rold->live & REG_LIVE_READ))
11634 		/* explored state didn't use this */
11635 		return true;
11636 
11637 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11638 
11639 	if (rold->type == PTR_TO_STACK)
11640 		/* two stack pointers are equal only if they're pointing to
11641 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
11642 		 */
11643 		return equal && rold->frameno == rcur->frameno;
11644 
11645 	if (equal)
11646 		return true;
11647 
11648 	if (rold->type == NOT_INIT)
11649 		/* explored state can't have used this */
11650 		return true;
11651 	if (rcur->type == NOT_INIT)
11652 		return false;
11653 	switch (base_type(rold->type)) {
11654 	case SCALAR_VALUE:
11655 		if (env->explore_alu_limits)
11656 			return false;
11657 		if (rcur->type == SCALAR_VALUE) {
11658 			if (!rold->precise)
11659 				return true;
11660 			/* new val must satisfy old val knowledge */
11661 			return range_within(rold, rcur) &&
11662 			       tnum_in(rold->var_off, rcur->var_off);
11663 		} else {
11664 			/* We're trying to use a pointer in place of a scalar.
11665 			 * Even if the scalar was unbounded, this could lead to
11666 			 * pointer leaks because scalars are allowed to leak
11667 			 * while pointers are not. We could make this safe in
11668 			 * special cases if root is calling us, but it's
11669 			 * probably not worth the hassle.
11670 			 */
11671 			return false;
11672 		}
11673 	case PTR_TO_MAP_KEY:
11674 	case PTR_TO_MAP_VALUE:
11675 		/* a PTR_TO_MAP_VALUE could be safe to use as a
11676 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11677 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11678 		 * checked, doing so could have affected others with the same
11679 		 * id, and we can't check for that because we lost the id when
11680 		 * we converted to a PTR_TO_MAP_VALUE.
11681 		 */
11682 		if (type_may_be_null(rold->type)) {
11683 			if (!type_may_be_null(rcur->type))
11684 				return false;
11685 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11686 				return false;
11687 			/* Check our ids match any regs they're supposed to */
11688 			return check_ids(rold->id, rcur->id, idmap);
11689 		}
11690 
11691 		/* If the new min/max/var_off satisfy the old ones and
11692 		 * everything else matches, we are OK.
11693 		 * 'id' is not compared, since it's only used for maps with
11694 		 * bpf_spin_lock inside map element and in such cases if
11695 		 * the rest of the prog is valid for one map element then
11696 		 * it's valid for all map elements regardless of the key
11697 		 * used in bpf_map_lookup()
11698 		 */
11699 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11700 		       range_within(rold, rcur) &&
11701 		       tnum_in(rold->var_off, rcur->var_off);
11702 	case PTR_TO_PACKET_META:
11703 	case PTR_TO_PACKET:
11704 		if (rcur->type != rold->type)
11705 			return false;
11706 		/* We must have at least as much range as the old ptr
11707 		 * did, so that any accesses which were safe before are
11708 		 * still safe.  This is true even if old range < old off,
11709 		 * since someone could have accessed through (ptr - k), or
11710 		 * even done ptr -= k in a register, to get a safe access.
11711 		 */
11712 		if (rold->range > rcur->range)
11713 			return false;
11714 		/* If the offsets don't match, we can't trust our alignment;
11715 		 * nor can we be sure that we won't fall out of range.
11716 		 */
11717 		if (rold->off != rcur->off)
11718 			return false;
11719 		/* id relations must be preserved */
11720 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11721 			return false;
11722 		/* new val must satisfy old val knowledge */
11723 		return range_within(rold, rcur) &&
11724 		       tnum_in(rold->var_off, rcur->var_off);
11725 	case PTR_TO_CTX:
11726 	case CONST_PTR_TO_MAP:
11727 	case PTR_TO_PACKET_END:
11728 	case PTR_TO_FLOW_KEYS:
11729 	case PTR_TO_SOCKET:
11730 	case PTR_TO_SOCK_COMMON:
11731 	case PTR_TO_TCP_SOCK:
11732 	case PTR_TO_XDP_SOCK:
11733 		/* Only valid matches are exact, which memcmp() above
11734 		 * would have accepted
11735 		 */
11736 	default:
11737 		/* Don't know what's going on, just say it's not safe */
11738 		return false;
11739 	}
11740 
11741 	/* Shouldn't get here; if we do, say it's not safe */
11742 	WARN_ON_ONCE(1);
11743 	return false;
11744 }
11745 
11746 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11747 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11748 {
11749 	int i, spi;
11750 
11751 	/* walk slots of the explored stack and ignore any additional
11752 	 * slots in the current stack, since explored(safe) state
11753 	 * didn't use them
11754 	 */
11755 	for (i = 0; i < old->allocated_stack; i++) {
11756 		spi = i / BPF_REG_SIZE;
11757 
11758 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11759 			i += BPF_REG_SIZE - 1;
11760 			/* explored state didn't use this */
11761 			continue;
11762 		}
11763 
11764 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11765 			continue;
11766 
11767 		/* explored stack has more populated slots than current stack
11768 		 * and these slots were used
11769 		 */
11770 		if (i >= cur->allocated_stack)
11771 			return false;
11772 
11773 		/* if old state was safe with misc data in the stack
11774 		 * it will be safe with zero-initialized stack.
11775 		 * The opposite is not true
11776 		 */
11777 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11778 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11779 			continue;
11780 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11781 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11782 			/* Ex: old explored (safe) state has STACK_SPILL in
11783 			 * this stack slot, but current has STACK_MISC ->
11784 			 * this verifier states are not equivalent,
11785 			 * return false to continue verification of this path
11786 			 */
11787 			return false;
11788 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11789 			continue;
11790 		if (!is_spilled_reg(&old->stack[spi]))
11791 			continue;
11792 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
11793 			     &cur->stack[spi].spilled_ptr, idmap))
11794 			/* when explored and current stack slot are both storing
11795 			 * spilled registers, check that stored pointers types
11796 			 * are the same as well.
11797 			 * Ex: explored safe path could have stored
11798 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11799 			 * but current path has stored:
11800 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11801 			 * such verifier states are not equivalent.
11802 			 * return false to continue verification of this path
11803 			 */
11804 			return false;
11805 	}
11806 	return true;
11807 }
11808 
11809 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11810 {
11811 	if (old->acquired_refs != cur->acquired_refs)
11812 		return false;
11813 	return !memcmp(old->refs, cur->refs,
11814 		       sizeof(*old->refs) * old->acquired_refs);
11815 }
11816 
11817 /* compare two verifier states
11818  *
11819  * all states stored in state_list are known to be valid, since
11820  * verifier reached 'bpf_exit' instruction through them
11821  *
11822  * this function is called when verifier exploring different branches of
11823  * execution popped from the state stack. If it sees an old state that has
11824  * more strict register state and more strict stack state then this execution
11825  * branch doesn't need to be explored further, since verifier already
11826  * concluded that more strict state leads to valid finish.
11827  *
11828  * Therefore two states are equivalent if register state is more conservative
11829  * and explored stack state is more conservative than the current one.
11830  * Example:
11831  *       explored                   current
11832  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11833  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11834  *
11835  * In other words if current stack state (one being explored) has more
11836  * valid slots than old one that already passed validation, it means
11837  * the verifier can stop exploring and conclude that current state is valid too
11838  *
11839  * Similarly with registers. If explored state has register type as invalid
11840  * whereas register type in current state is meaningful, it means that
11841  * the current state will reach 'bpf_exit' instruction safely
11842  */
11843 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11844 			      struct bpf_func_state *cur)
11845 {
11846 	int i;
11847 
11848 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11849 	for (i = 0; i < MAX_BPF_REG; i++)
11850 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11851 			     env->idmap_scratch))
11852 			return false;
11853 
11854 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11855 		return false;
11856 
11857 	if (!refsafe(old, cur))
11858 		return false;
11859 
11860 	return true;
11861 }
11862 
11863 static bool states_equal(struct bpf_verifier_env *env,
11864 			 struct bpf_verifier_state *old,
11865 			 struct bpf_verifier_state *cur)
11866 {
11867 	int i;
11868 
11869 	if (old->curframe != cur->curframe)
11870 		return false;
11871 
11872 	/* Verification state from speculative execution simulation
11873 	 * must never prune a non-speculative execution one.
11874 	 */
11875 	if (old->speculative && !cur->speculative)
11876 		return false;
11877 
11878 	if (old->active_spin_lock != cur->active_spin_lock)
11879 		return false;
11880 
11881 	/* for states to be equal callsites have to be the same
11882 	 * and all frame states need to be equivalent
11883 	 */
11884 	for (i = 0; i <= old->curframe; i++) {
11885 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11886 			return false;
11887 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11888 			return false;
11889 	}
11890 	return true;
11891 }
11892 
11893 /* Return 0 if no propagation happened. Return negative error code if error
11894  * happened. Otherwise, return the propagated bit.
11895  */
11896 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11897 				  struct bpf_reg_state *reg,
11898 				  struct bpf_reg_state *parent_reg)
11899 {
11900 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11901 	u8 flag = reg->live & REG_LIVE_READ;
11902 	int err;
11903 
11904 	/* When comes here, read flags of PARENT_REG or REG could be any of
11905 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11906 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11907 	 */
11908 	if (parent_flag == REG_LIVE_READ64 ||
11909 	    /* Or if there is no read flag from REG. */
11910 	    !flag ||
11911 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11912 	    parent_flag == flag)
11913 		return 0;
11914 
11915 	err = mark_reg_read(env, reg, parent_reg, flag);
11916 	if (err)
11917 		return err;
11918 
11919 	return flag;
11920 }
11921 
11922 /* A write screens off any subsequent reads; but write marks come from the
11923  * straight-line code between a state and its parent.  When we arrive at an
11924  * equivalent state (jump target or such) we didn't arrive by the straight-line
11925  * code, so read marks in the state must propagate to the parent regardless
11926  * of the state's write marks. That's what 'parent == state->parent' comparison
11927  * in mark_reg_read() is for.
11928  */
11929 static int propagate_liveness(struct bpf_verifier_env *env,
11930 			      const struct bpf_verifier_state *vstate,
11931 			      struct bpf_verifier_state *vparent)
11932 {
11933 	struct bpf_reg_state *state_reg, *parent_reg;
11934 	struct bpf_func_state *state, *parent;
11935 	int i, frame, err = 0;
11936 
11937 	if (vparent->curframe != vstate->curframe) {
11938 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11939 		     vparent->curframe, vstate->curframe);
11940 		return -EFAULT;
11941 	}
11942 	/* Propagate read liveness of registers... */
11943 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11944 	for (frame = 0; frame <= vstate->curframe; frame++) {
11945 		parent = vparent->frame[frame];
11946 		state = vstate->frame[frame];
11947 		parent_reg = parent->regs;
11948 		state_reg = state->regs;
11949 		/* We don't need to worry about FP liveness, it's read-only */
11950 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11951 			err = propagate_liveness_reg(env, &state_reg[i],
11952 						     &parent_reg[i]);
11953 			if (err < 0)
11954 				return err;
11955 			if (err == REG_LIVE_READ64)
11956 				mark_insn_zext(env, &parent_reg[i]);
11957 		}
11958 
11959 		/* Propagate stack slots. */
11960 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11961 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11962 			parent_reg = &parent->stack[i].spilled_ptr;
11963 			state_reg = &state->stack[i].spilled_ptr;
11964 			err = propagate_liveness_reg(env, state_reg,
11965 						     parent_reg);
11966 			if (err < 0)
11967 				return err;
11968 		}
11969 	}
11970 	return 0;
11971 }
11972 
11973 /* find precise scalars in the previous equivalent state and
11974  * propagate them into the current state
11975  */
11976 static int propagate_precision(struct bpf_verifier_env *env,
11977 			       const struct bpf_verifier_state *old)
11978 {
11979 	struct bpf_reg_state *state_reg;
11980 	struct bpf_func_state *state;
11981 	int i, err = 0, fr;
11982 
11983 	for (fr = old->curframe; fr >= 0; fr--) {
11984 		state = old->frame[fr];
11985 		state_reg = state->regs;
11986 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11987 			if (state_reg->type != SCALAR_VALUE ||
11988 			    !state_reg->precise)
11989 				continue;
11990 			if (env->log.level & BPF_LOG_LEVEL2)
11991 				verbose(env, "frame %d: propagating r%d\n", i, fr);
11992 			err = mark_chain_precision_frame(env, fr, i);
11993 			if (err < 0)
11994 				return err;
11995 		}
11996 
11997 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11998 			if (!is_spilled_reg(&state->stack[i]))
11999 				continue;
12000 			state_reg = &state->stack[i].spilled_ptr;
12001 			if (state_reg->type != SCALAR_VALUE ||
12002 			    !state_reg->precise)
12003 				continue;
12004 			if (env->log.level & BPF_LOG_LEVEL2)
12005 				verbose(env, "frame %d: propagating fp%d\n",
12006 					(-i - 1) * BPF_REG_SIZE, fr);
12007 			err = mark_chain_precision_stack_frame(env, fr, i);
12008 			if (err < 0)
12009 				return err;
12010 		}
12011 	}
12012 	return 0;
12013 }
12014 
12015 static bool states_maybe_looping(struct bpf_verifier_state *old,
12016 				 struct bpf_verifier_state *cur)
12017 {
12018 	struct bpf_func_state *fold, *fcur;
12019 	int i, fr = cur->curframe;
12020 
12021 	if (old->curframe != fr)
12022 		return false;
12023 
12024 	fold = old->frame[fr];
12025 	fcur = cur->frame[fr];
12026 	for (i = 0; i < MAX_BPF_REG; i++)
12027 		if (memcmp(&fold->regs[i], &fcur->regs[i],
12028 			   offsetof(struct bpf_reg_state, parent)))
12029 			return false;
12030 	return true;
12031 }
12032 
12033 
12034 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
12035 {
12036 	struct bpf_verifier_state_list *new_sl;
12037 	struct bpf_verifier_state_list *sl, **pprev;
12038 	struct bpf_verifier_state *cur = env->cur_state, *new;
12039 	int i, j, err, states_cnt = 0;
12040 	bool add_new_state = env->test_state_freq ? true : false;
12041 
12042 	cur->last_insn_idx = env->prev_insn_idx;
12043 	if (!env->insn_aux_data[insn_idx].prune_point)
12044 		/* this 'insn_idx' instruction wasn't marked, so we will not
12045 		 * be doing state search here
12046 		 */
12047 		return 0;
12048 
12049 	/* bpf progs typically have pruning point every 4 instructions
12050 	 * http://vger.kernel.org/bpfconf2019.html#session-1
12051 	 * Do not add new state for future pruning if the verifier hasn't seen
12052 	 * at least 2 jumps and at least 8 instructions.
12053 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
12054 	 * In tests that amounts to up to 50% reduction into total verifier
12055 	 * memory consumption and 20% verifier time speedup.
12056 	 */
12057 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
12058 	    env->insn_processed - env->prev_insn_processed >= 8)
12059 		add_new_state = true;
12060 
12061 	pprev = explored_state(env, insn_idx);
12062 	sl = *pprev;
12063 
12064 	clean_live_states(env, insn_idx, cur);
12065 
12066 	while (sl) {
12067 		states_cnt++;
12068 		if (sl->state.insn_idx != insn_idx)
12069 			goto next;
12070 
12071 		if (sl->state.branches) {
12072 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
12073 
12074 			if (frame->in_async_callback_fn &&
12075 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
12076 				/* Different async_entry_cnt means that the verifier is
12077 				 * processing another entry into async callback.
12078 				 * Seeing the same state is not an indication of infinite
12079 				 * loop or infinite recursion.
12080 				 * But finding the same state doesn't mean that it's safe
12081 				 * to stop processing the current state. The previous state
12082 				 * hasn't yet reached bpf_exit, since state.branches > 0.
12083 				 * Checking in_async_callback_fn alone is not enough either.
12084 				 * Since the verifier still needs to catch infinite loops
12085 				 * inside async callbacks.
12086 				 */
12087 			} else if (states_maybe_looping(&sl->state, cur) &&
12088 				   states_equal(env, &sl->state, cur)) {
12089 				verbose_linfo(env, insn_idx, "; ");
12090 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12091 				return -EINVAL;
12092 			}
12093 			/* if the verifier is processing a loop, avoid adding new state
12094 			 * too often, since different loop iterations have distinct
12095 			 * states and may not help future pruning.
12096 			 * This threshold shouldn't be too low to make sure that
12097 			 * a loop with large bound will be rejected quickly.
12098 			 * The most abusive loop will be:
12099 			 * r1 += 1
12100 			 * if r1 < 1000000 goto pc-2
12101 			 * 1M insn_procssed limit / 100 == 10k peak states.
12102 			 * This threshold shouldn't be too high either, since states
12103 			 * at the end of the loop are likely to be useful in pruning.
12104 			 */
12105 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12106 			    env->insn_processed - env->prev_insn_processed < 100)
12107 				add_new_state = false;
12108 			goto miss;
12109 		}
12110 		if (states_equal(env, &sl->state, cur)) {
12111 			sl->hit_cnt++;
12112 			/* reached equivalent register/stack state,
12113 			 * prune the search.
12114 			 * Registers read by the continuation are read by us.
12115 			 * If we have any write marks in env->cur_state, they
12116 			 * will prevent corresponding reads in the continuation
12117 			 * from reaching our parent (an explored_state).  Our
12118 			 * own state will get the read marks recorded, but
12119 			 * they'll be immediately forgotten as we're pruning
12120 			 * this state and will pop a new one.
12121 			 */
12122 			err = propagate_liveness(env, &sl->state, cur);
12123 
12124 			/* if previous state reached the exit with precision and
12125 			 * current state is equivalent to it (except precsion marks)
12126 			 * the precision needs to be propagated back in
12127 			 * the current state.
12128 			 */
12129 			err = err ? : push_jmp_history(env, cur);
12130 			err = err ? : propagate_precision(env, &sl->state);
12131 			if (err)
12132 				return err;
12133 			return 1;
12134 		}
12135 miss:
12136 		/* when new state is not going to be added do not increase miss count.
12137 		 * Otherwise several loop iterations will remove the state
12138 		 * recorded earlier. The goal of these heuristics is to have
12139 		 * states from some iterations of the loop (some in the beginning
12140 		 * and some at the end) to help pruning.
12141 		 */
12142 		if (add_new_state)
12143 			sl->miss_cnt++;
12144 		/* heuristic to determine whether this state is beneficial
12145 		 * to keep checking from state equivalence point of view.
12146 		 * Higher numbers increase max_states_per_insn and verification time,
12147 		 * but do not meaningfully decrease insn_processed.
12148 		 */
12149 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12150 			/* the state is unlikely to be useful. Remove it to
12151 			 * speed up verification
12152 			 */
12153 			*pprev = sl->next;
12154 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12155 				u32 br = sl->state.branches;
12156 
12157 				WARN_ONCE(br,
12158 					  "BUG live_done but branches_to_explore %d\n",
12159 					  br);
12160 				free_verifier_state(&sl->state, false);
12161 				kfree(sl);
12162 				env->peak_states--;
12163 			} else {
12164 				/* cannot free this state, since parentage chain may
12165 				 * walk it later. Add it for free_list instead to
12166 				 * be freed at the end of verification
12167 				 */
12168 				sl->next = env->free_list;
12169 				env->free_list = sl;
12170 			}
12171 			sl = *pprev;
12172 			continue;
12173 		}
12174 next:
12175 		pprev = &sl->next;
12176 		sl = *pprev;
12177 	}
12178 
12179 	if (env->max_states_per_insn < states_cnt)
12180 		env->max_states_per_insn = states_cnt;
12181 
12182 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12183 		return push_jmp_history(env, cur);
12184 
12185 	if (!add_new_state)
12186 		return push_jmp_history(env, cur);
12187 
12188 	/* There were no equivalent states, remember the current one.
12189 	 * Technically the current state is not proven to be safe yet,
12190 	 * but it will either reach outer most bpf_exit (which means it's safe)
12191 	 * or it will be rejected. When there are no loops the verifier won't be
12192 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12193 	 * again on the way to bpf_exit.
12194 	 * When looping the sl->state.branches will be > 0 and this state
12195 	 * will not be considered for equivalence until branches == 0.
12196 	 */
12197 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12198 	if (!new_sl)
12199 		return -ENOMEM;
12200 	env->total_states++;
12201 	env->peak_states++;
12202 	env->prev_jmps_processed = env->jmps_processed;
12203 	env->prev_insn_processed = env->insn_processed;
12204 
12205 	/* forget precise markings we inherited, see __mark_chain_precision */
12206 	if (env->bpf_capable)
12207 		mark_all_scalars_imprecise(env, cur);
12208 
12209 	/* add new state to the head of linked list */
12210 	new = &new_sl->state;
12211 	err = copy_verifier_state(new, cur);
12212 	if (err) {
12213 		free_verifier_state(new, false);
12214 		kfree(new_sl);
12215 		return err;
12216 	}
12217 	new->insn_idx = insn_idx;
12218 	WARN_ONCE(new->branches != 1,
12219 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12220 
12221 	cur->parent = new;
12222 	cur->first_insn_idx = insn_idx;
12223 	clear_jmp_history(cur);
12224 	new_sl->next = *explored_state(env, insn_idx);
12225 	*explored_state(env, insn_idx) = new_sl;
12226 	/* connect new state to parentage chain. Current frame needs all
12227 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
12228 	 * to the stack implicitly by JITs) so in callers' frames connect just
12229 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12230 	 * the state of the call instruction (with WRITTEN set), and r0 comes
12231 	 * from callee with its full parentage chain, anyway.
12232 	 */
12233 	/* clear write marks in current state: the writes we did are not writes
12234 	 * our child did, so they don't screen off its reads from us.
12235 	 * (There are no read marks in current state, because reads always mark
12236 	 * their parent and current state never has children yet.  Only
12237 	 * explored_states can get read marks.)
12238 	 */
12239 	for (j = 0; j <= cur->curframe; j++) {
12240 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12241 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12242 		for (i = 0; i < BPF_REG_FP; i++)
12243 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12244 	}
12245 
12246 	/* all stack frames are accessible from callee, clear them all */
12247 	for (j = 0; j <= cur->curframe; j++) {
12248 		struct bpf_func_state *frame = cur->frame[j];
12249 		struct bpf_func_state *newframe = new->frame[j];
12250 
12251 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12252 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12253 			frame->stack[i].spilled_ptr.parent =
12254 						&newframe->stack[i].spilled_ptr;
12255 		}
12256 	}
12257 	return 0;
12258 }
12259 
12260 /* Return true if it's OK to have the same insn return a different type. */
12261 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12262 {
12263 	switch (base_type(type)) {
12264 	case PTR_TO_CTX:
12265 	case PTR_TO_SOCKET:
12266 	case PTR_TO_SOCK_COMMON:
12267 	case PTR_TO_TCP_SOCK:
12268 	case PTR_TO_XDP_SOCK:
12269 	case PTR_TO_BTF_ID:
12270 		return false;
12271 	default:
12272 		return true;
12273 	}
12274 }
12275 
12276 /* If an instruction was previously used with particular pointer types, then we
12277  * need to be careful to avoid cases such as the below, where it may be ok
12278  * for one branch accessing the pointer, but not ok for the other branch:
12279  *
12280  * R1 = sock_ptr
12281  * goto X;
12282  * ...
12283  * R1 = some_other_valid_ptr;
12284  * goto X;
12285  * ...
12286  * R2 = *(u32 *)(R1 + 0);
12287  */
12288 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12289 {
12290 	return src != prev && (!reg_type_mismatch_ok(src) ||
12291 			       !reg_type_mismatch_ok(prev));
12292 }
12293 
12294 static int do_check(struct bpf_verifier_env *env)
12295 {
12296 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12297 	struct bpf_verifier_state *state = env->cur_state;
12298 	struct bpf_insn *insns = env->prog->insnsi;
12299 	struct bpf_reg_state *regs;
12300 	int insn_cnt = env->prog->len;
12301 	bool do_print_state = false;
12302 	int prev_insn_idx = -1;
12303 
12304 	for (;;) {
12305 		struct bpf_insn *insn;
12306 		u8 class;
12307 		int err;
12308 
12309 		env->prev_insn_idx = prev_insn_idx;
12310 		if (env->insn_idx >= insn_cnt) {
12311 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
12312 				env->insn_idx, insn_cnt);
12313 			return -EFAULT;
12314 		}
12315 
12316 		insn = &insns[env->insn_idx];
12317 		class = BPF_CLASS(insn->code);
12318 
12319 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12320 			verbose(env,
12321 				"BPF program is too large. Processed %d insn\n",
12322 				env->insn_processed);
12323 			return -E2BIG;
12324 		}
12325 
12326 		err = is_state_visited(env, env->insn_idx);
12327 		if (err < 0)
12328 			return err;
12329 		if (err == 1) {
12330 			/* found equivalent state, can prune the search */
12331 			if (env->log.level & BPF_LOG_LEVEL) {
12332 				if (do_print_state)
12333 					verbose(env, "\nfrom %d to %d%s: safe\n",
12334 						env->prev_insn_idx, env->insn_idx,
12335 						env->cur_state->speculative ?
12336 						" (speculative execution)" : "");
12337 				else
12338 					verbose(env, "%d: safe\n", env->insn_idx);
12339 			}
12340 			goto process_bpf_exit;
12341 		}
12342 
12343 		if (signal_pending(current))
12344 			return -EAGAIN;
12345 
12346 		if (need_resched())
12347 			cond_resched();
12348 
12349 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12350 			verbose(env, "\nfrom %d to %d%s:",
12351 				env->prev_insn_idx, env->insn_idx,
12352 				env->cur_state->speculative ?
12353 				" (speculative execution)" : "");
12354 			print_verifier_state(env, state->frame[state->curframe], true);
12355 			do_print_state = false;
12356 		}
12357 
12358 		if (env->log.level & BPF_LOG_LEVEL) {
12359 			const struct bpf_insn_cbs cbs = {
12360 				.cb_call	= disasm_kfunc_name,
12361 				.cb_print	= verbose,
12362 				.private_data	= env,
12363 			};
12364 
12365 			if (verifier_state_scratched(env))
12366 				print_insn_state(env, state->frame[state->curframe]);
12367 
12368 			verbose_linfo(env, env->insn_idx, "; ");
12369 			env->prev_log_len = env->log.len_used;
12370 			verbose(env, "%d: ", env->insn_idx);
12371 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12372 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12373 			env->prev_log_len = env->log.len_used;
12374 		}
12375 
12376 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
12377 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12378 							   env->prev_insn_idx);
12379 			if (err)
12380 				return err;
12381 		}
12382 
12383 		regs = cur_regs(env);
12384 		sanitize_mark_insn_seen(env);
12385 		prev_insn_idx = env->insn_idx;
12386 
12387 		if (class == BPF_ALU || class == BPF_ALU64) {
12388 			err = check_alu_op(env, insn);
12389 			if (err)
12390 				return err;
12391 
12392 		} else if (class == BPF_LDX) {
12393 			enum bpf_reg_type *prev_src_type, src_reg_type;
12394 
12395 			/* check for reserved fields is already done */
12396 
12397 			/* check src operand */
12398 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12399 			if (err)
12400 				return err;
12401 
12402 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12403 			if (err)
12404 				return err;
12405 
12406 			src_reg_type = regs[insn->src_reg].type;
12407 
12408 			/* check that memory (src_reg + off) is readable,
12409 			 * the state of dst_reg will be updated by this func
12410 			 */
12411 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
12412 					       insn->off, BPF_SIZE(insn->code),
12413 					       BPF_READ, insn->dst_reg, false);
12414 			if (err)
12415 				return err;
12416 
12417 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12418 
12419 			if (*prev_src_type == NOT_INIT) {
12420 				/* saw a valid insn
12421 				 * dst_reg = *(u32 *)(src_reg + off)
12422 				 * save type to validate intersecting paths
12423 				 */
12424 				*prev_src_type = src_reg_type;
12425 
12426 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12427 				/* ABuser program is trying to use the same insn
12428 				 * dst_reg = *(u32*) (src_reg + off)
12429 				 * with different pointer types:
12430 				 * src_reg == ctx in one branch and
12431 				 * src_reg == stack|map in some other branch.
12432 				 * Reject it.
12433 				 */
12434 				verbose(env, "same insn cannot be used with different pointers\n");
12435 				return -EINVAL;
12436 			}
12437 
12438 		} else if (class == BPF_STX) {
12439 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
12440 
12441 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12442 				err = check_atomic(env, env->insn_idx, insn);
12443 				if (err)
12444 					return err;
12445 				env->insn_idx++;
12446 				continue;
12447 			}
12448 
12449 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12450 				verbose(env, "BPF_STX uses reserved fields\n");
12451 				return -EINVAL;
12452 			}
12453 
12454 			/* check src1 operand */
12455 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12456 			if (err)
12457 				return err;
12458 			/* check src2 operand */
12459 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12460 			if (err)
12461 				return err;
12462 
12463 			dst_reg_type = regs[insn->dst_reg].type;
12464 
12465 			/* check that memory (dst_reg + off) is writeable */
12466 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12467 					       insn->off, BPF_SIZE(insn->code),
12468 					       BPF_WRITE, insn->src_reg, false);
12469 			if (err)
12470 				return err;
12471 
12472 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12473 
12474 			if (*prev_dst_type == NOT_INIT) {
12475 				*prev_dst_type = dst_reg_type;
12476 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12477 				verbose(env, "same insn cannot be used with different pointers\n");
12478 				return -EINVAL;
12479 			}
12480 
12481 		} else if (class == BPF_ST) {
12482 			if (BPF_MODE(insn->code) != BPF_MEM ||
12483 			    insn->src_reg != BPF_REG_0) {
12484 				verbose(env, "BPF_ST uses reserved fields\n");
12485 				return -EINVAL;
12486 			}
12487 			/* check src operand */
12488 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12489 			if (err)
12490 				return err;
12491 
12492 			if (is_ctx_reg(env, insn->dst_reg)) {
12493 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12494 					insn->dst_reg,
12495 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12496 				return -EACCES;
12497 			}
12498 
12499 			/* check that memory (dst_reg + off) is writeable */
12500 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12501 					       insn->off, BPF_SIZE(insn->code),
12502 					       BPF_WRITE, -1, false);
12503 			if (err)
12504 				return err;
12505 
12506 		} else if (class == BPF_JMP || class == BPF_JMP32) {
12507 			u8 opcode = BPF_OP(insn->code);
12508 
12509 			env->jmps_processed++;
12510 			if (opcode == BPF_CALL) {
12511 				if (BPF_SRC(insn->code) != BPF_K ||
12512 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12513 				     && insn->off != 0) ||
12514 				    (insn->src_reg != BPF_REG_0 &&
12515 				     insn->src_reg != BPF_PSEUDO_CALL &&
12516 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12517 				    insn->dst_reg != BPF_REG_0 ||
12518 				    class == BPF_JMP32) {
12519 					verbose(env, "BPF_CALL uses reserved fields\n");
12520 					return -EINVAL;
12521 				}
12522 
12523 				if (env->cur_state->active_spin_lock &&
12524 				    (insn->src_reg == BPF_PSEUDO_CALL ||
12525 				     insn->imm != BPF_FUNC_spin_unlock)) {
12526 					verbose(env, "function calls are not allowed while holding a lock\n");
12527 					return -EINVAL;
12528 				}
12529 				if (insn->src_reg == BPF_PSEUDO_CALL)
12530 					err = check_func_call(env, insn, &env->insn_idx);
12531 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12532 					err = check_kfunc_call(env, insn, &env->insn_idx);
12533 				else
12534 					err = check_helper_call(env, insn, &env->insn_idx);
12535 				if (err)
12536 					return err;
12537 			} else if (opcode == BPF_JA) {
12538 				if (BPF_SRC(insn->code) != BPF_K ||
12539 				    insn->imm != 0 ||
12540 				    insn->src_reg != BPF_REG_0 ||
12541 				    insn->dst_reg != BPF_REG_0 ||
12542 				    class == BPF_JMP32) {
12543 					verbose(env, "BPF_JA uses reserved fields\n");
12544 					return -EINVAL;
12545 				}
12546 
12547 				env->insn_idx += insn->off + 1;
12548 				continue;
12549 
12550 			} else if (opcode == BPF_EXIT) {
12551 				if (BPF_SRC(insn->code) != BPF_K ||
12552 				    insn->imm != 0 ||
12553 				    insn->src_reg != BPF_REG_0 ||
12554 				    insn->dst_reg != BPF_REG_0 ||
12555 				    class == BPF_JMP32) {
12556 					verbose(env, "BPF_EXIT uses reserved fields\n");
12557 					return -EINVAL;
12558 				}
12559 
12560 				if (env->cur_state->active_spin_lock) {
12561 					verbose(env, "bpf_spin_unlock is missing\n");
12562 					return -EINVAL;
12563 				}
12564 
12565 				/* We must do check_reference_leak here before
12566 				 * prepare_func_exit to handle the case when
12567 				 * state->curframe > 0, it may be a callback
12568 				 * function, for which reference_state must
12569 				 * match caller reference state when it exits.
12570 				 */
12571 				err = check_reference_leak(env);
12572 				if (err)
12573 					return err;
12574 
12575 				if (state->curframe) {
12576 					/* exit from nested function */
12577 					err = prepare_func_exit(env, &env->insn_idx);
12578 					if (err)
12579 						return err;
12580 					do_print_state = true;
12581 					continue;
12582 				}
12583 
12584 				err = check_return_code(env);
12585 				if (err)
12586 					return err;
12587 process_bpf_exit:
12588 				mark_verifier_state_scratched(env);
12589 				update_branch_counts(env, env->cur_state);
12590 				err = pop_stack(env, &prev_insn_idx,
12591 						&env->insn_idx, pop_log);
12592 				if (err < 0) {
12593 					if (err != -ENOENT)
12594 						return err;
12595 					break;
12596 				} else {
12597 					do_print_state = true;
12598 					continue;
12599 				}
12600 			} else {
12601 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
12602 				if (err)
12603 					return err;
12604 			}
12605 		} else if (class == BPF_LD) {
12606 			u8 mode = BPF_MODE(insn->code);
12607 
12608 			if (mode == BPF_ABS || mode == BPF_IND) {
12609 				err = check_ld_abs(env, insn);
12610 				if (err)
12611 					return err;
12612 
12613 			} else if (mode == BPF_IMM) {
12614 				err = check_ld_imm(env, insn);
12615 				if (err)
12616 					return err;
12617 
12618 				env->insn_idx++;
12619 				sanitize_mark_insn_seen(env);
12620 			} else {
12621 				verbose(env, "invalid BPF_LD mode\n");
12622 				return -EINVAL;
12623 			}
12624 		} else {
12625 			verbose(env, "unknown insn class %d\n", class);
12626 			return -EINVAL;
12627 		}
12628 
12629 		env->insn_idx++;
12630 	}
12631 
12632 	return 0;
12633 }
12634 
12635 static int find_btf_percpu_datasec(struct btf *btf)
12636 {
12637 	const struct btf_type *t;
12638 	const char *tname;
12639 	int i, n;
12640 
12641 	/*
12642 	 * Both vmlinux and module each have their own ".data..percpu"
12643 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12644 	 * types to look at only module's own BTF types.
12645 	 */
12646 	n = btf_nr_types(btf);
12647 	if (btf_is_module(btf))
12648 		i = btf_nr_types(btf_vmlinux);
12649 	else
12650 		i = 1;
12651 
12652 	for(; i < n; i++) {
12653 		t = btf_type_by_id(btf, i);
12654 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12655 			continue;
12656 
12657 		tname = btf_name_by_offset(btf, t->name_off);
12658 		if (!strcmp(tname, ".data..percpu"))
12659 			return i;
12660 	}
12661 
12662 	return -ENOENT;
12663 }
12664 
12665 /* replace pseudo btf_id with kernel symbol address */
12666 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12667 			       struct bpf_insn *insn,
12668 			       struct bpf_insn_aux_data *aux)
12669 {
12670 	const struct btf_var_secinfo *vsi;
12671 	const struct btf_type *datasec;
12672 	struct btf_mod_pair *btf_mod;
12673 	const struct btf_type *t;
12674 	const char *sym_name;
12675 	bool percpu = false;
12676 	u32 type, id = insn->imm;
12677 	struct btf *btf;
12678 	s32 datasec_id;
12679 	u64 addr;
12680 	int i, btf_fd, err;
12681 
12682 	btf_fd = insn[1].imm;
12683 	if (btf_fd) {
12684 		btf = btf_get_by_fd(btf_fd);
12685 		if (IS_ERR(btf)) {
12686 			verbose(env, "invalid module BTF object FD specified.\n");
12687 			return -EINVAL;
12688 		}
12689 	} else {
12690 		if (!btf_vmlinux) {
12691 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12692 			return -EINVAL;
12693 		}
12694 		btf = btf_vmlinux;
12695 		btf_get(btf);
12696 	}
12697 
12698 	t = btf_type_by_id(btf, id);
12699 	if (!t) {
12700 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12701 		err = -ENOENT;
12702 		goto err_put;
12703 	}
12704 
12705 	if (!btf_type_is_var(t)) {
12706 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12707 		err = -EINVAL;
12708 		goto err_put;
12709 	}
12710 
12711 	sym_name = btf_name_by_offset(btf, t->name_off);
12712 	addr = kallsyms_lookup_name(sym_name);
12713 	if (!addr) {
12714 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12715 			sym_name);
12716 		err = -ENOENT;
12717 		goto err_put;
12718 	}
12719 
12720 	datasec_id = find_btf_percpu_datasec(btf);
12721 	if (datasec_id > 0) {
12722 		datasec = btf_type_by_id(btf, datasec_id);
12723 		for_each_vsi(i, datasec, vsi) {
12724 			if (vsi->type == id) {
12725 				percpu = true;
12726 				break;
12727 			}
12728 		}
12729 	}
12730 
12731 	insn[0].imm = (u32)addr;
12732 	insn[1].imm = addr >> 32;
12733 
12734 	type = t->type;
12735 	t = btf_type_skip_modifiers(btf, type, NULL);
12736 	if (percpu) {
12737 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12738 		aux->btf_var.btf = btf;
12739 		aux->btf_var.btf_id = type;
12740 	} else if (!btf_type_is_struct(t)) {
12741 		const struct btf_type *ret;
12742 		const char *tname;
12743 		u32 tsize;
12744 
12745 		/* resolve the type size of ksym. */
12746 		ret = btf_resolve_size(btf, t, &tsize);
12747 		if (IS_ERR(ret)) {
12748 			tname = btf_name_by_offset(btf, t->name_off);
12749 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12750 				tname, PTR_ERR(ret));
12751 			err = -EINVAL;
12752 			goto err_put;
12753 		}
12754 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12755 		aux->btf_var.mem_size = tsize;
12756 	} else {
12757 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
12758 		aux->btf_var.btf = btf;
12759 		aux->btf_var.btf_id = type;
12760 	}
12761 
12762 	/* check whether we recorded this BTF (and maybe module) already */
12763 	for (i = 0; i < env->used_btf_cnt; i++) {
12764 		if (env->used_btfs[i].btf == btf) {
12765 			btf_put(btf);
12766 			return 0;
12767 		}
12768 	}
12769 
12770 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
12771 		err = -E2BIG;
12772 		goto err_put;
12773 	}
12774 
12775 	btf_mod = &env->used_btfs[env->used_btf_cnt];
12776 	btf_mod->btf = btf;
12777 	btf_mod->module = NULL;
12778 
12779 	/* if we reference variables from kernel module, bump its refcount */
12780 	if (btf_is_module(btf)) {
12781 		btf_mod->module = btf_try_get_module(btf);
12782 		if (!btf_mod->module) {
12783 			err = -ENXIO;
12784 			goto err_put;
12785 		}
12786 	}
12787 
12788 	env->used_btf_cnt++;
12789 
12790 	return 0;
12791 err_put:
12792 	btf_put(btf);
12793 	return err;
12794 }
12795 
12796 static bool is_tracing_prog_type(enum bpf_prog_type type)
12797 {
12798 	switch (type) {
12799 	case BPF_PROG_TYPE_KPROBE:
12800 	case BPF_PROG_TYPE_TRACEPOINT:
12801 	case BPF_PROG_TYPE_PERF_EVENT:
12802 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12803 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12804 		return true;
12805 	default:
12806 		return false;
12807 	}
12808 }
12809 
12810 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12811 					struct bpf_map *map,
12812 					struct bpf_prog *prog)
12813 
12814 {
12815 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12816 
12817 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
12818 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12819 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12820 			return -EINVAL;
12821 		}
12822 
12823 		if (is_tracing_prog_type(prog_type)) {
12824 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12825 			return -EINVAL;
12826 		}
12827 
12828 		if (prog->aux->sleepable) {
12829 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12830 			return -EINVAL;
12831 		}
12832 	}
12833 
12834 	if (btf_record_has_field(map->record, BPF_TIMER)) {
12835 		if (is_tracing_prog_type(prog_type)) {
12836 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12837 			return -EINVAL;
12838 		}
12839 	}
12840 
12841 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12842 	    !bpf_offload_prog_map_match(prog, map)) {
12843 		verbose(env, "offload device mismatch between prog and map\n");
12844 		return -EINVAL;
12845 	}
12846 
12847 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12848 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12849 		return -EINVAL;
12850 	}
12851 
12852 	if (prog->aux->sleepable)
12853 		switch (map->map_type) {
12854 		case BPF_MAP_TYPE_HASH:
12855 		case BPF_MAP_TYPE_LRU_HASH:
12856 		case BPF_MAP_TYPE_ARRAY:
12857 		case BPF_MAP_TYPE_PERCPU_HASH:
12858 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12859 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12860 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12861 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12862 		case BPF_MAP_TYPE_RINGBUF:
12863 		case BPF_MAP_TYPE_USER_RINGBUF:
12864 		case BPF_MAP_TYPE_INODE_STORAGE:
12865 		case BPF_MAP_TYPE_SK_STORAGE:
12866 		case BPF_MAP_TYPE_TASK_STORAGE:
12867 			break;
12868 		default:
12869 			verbose(env,
12870 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12871 			return -EINVAL;
12872 		}
12873 
12874 	return 0;
12875 }
12876 
12877 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12878 {
12879 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12880 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12881 }
12882 
12883 /* find and rewrite pseudo imm in ld_imm64 instructions:
12884  *
12885  * 1. if it accesses map FD, replace it with actual map pointer.
12886  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12887  *
12888  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12889  */
12890 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12891 {
12892 	struct bpf_insn *insn = env->prog->insnsi;
12893 	int insn_cnt = env->prog->len;
12894 	int i, j, err;
12895 
12896 	err = bpf_prog_calc_tag(env->prog);
12897 	if (err)
12898 		return err;
12899 
12900 	for (i = 0; i < insn_cnt; i++, insn++) {
12901 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12902 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12903 			verbose(env, "BPF_LDX uses reserved fields\n");
12904 			return -EINVAL;
12905 		}
12906 
12907 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12908 			struct bpf_insn_aux_data *aux;
12909 			struct bpf_map *map;
12910 			struct fd f;
12911 			u64 addr;
12912 			u32 fd;
12913 
12914 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12915 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12916 			    insn[1].off != 0) {
12917 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12918 				return -EINVAL;
12919 			}
12920 
12921 			if (insn[0].src_reg == 0)
12922 				/* valid generic load 64-bit imm */
12923 				goto next_insn;
12924 
12925 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12926 				aux = &env->insn_aux_data[i];
12927 				err = check_pseudo_btf_id(env, insn, aux);
12928 				if (err)
12929 					return err;
12930 				goto next_insn;
12931 			}
12932 
12933 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12934 				aux = &env->insn_aux_data[i];
12935 				aux->ptr_type = PTR_TO_FUNC;
12936 				goto next_insn;
12937 			}
12938 
12939 			/* In final convert_pseudo_ld_imm64() step, this is
12940 			 * converted into regular 64-bit imm load insn.
12941 			 */
12942 			switch (insn[0].src_reg) {
12943 			case BPF_PSEUDO_MAP_VALUE:
12944 			case BPF_PSEUDO_MAP_IDX_VALUE:
12945 				break;
12946 			case BPF_PSEUDO_MAP_FD:
12947 			case BPF_PSEUDO_MAP_IDX:
12948 				if (insn[1].imm == 0)
12949 					break;
12950 				fallthrough;
12951 			default:
12952 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12953 				return -EINVAL;
12954 			}
12955 
12956 			switch (insn[0].src_reg) {
12957 			case BPF_PSEUDO_MAP_IDX_VALUE:
12958 			case BPF_PSEUDO_MAP_IDX:
12959 				if (bpfptr_is_null(env->fd_array)) {
12960 					verbose(env, "fd_idx without fd_array is invalid\n");
12961 					return -EPROTO;
12962 				}
12963 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12964 							    insn[0].imm * sizeof(fd),
12965 							    sizeof(fd)))
12966 					return -EFAULT;
12967 				break;
12968 			default:
12969 				fd = insn[0].imm;
12970 				break;
12971 			}
12972 
12973 			f = fdget(fd);
12974 			map = __bpf_map_get(f);
12975 			if (IS_ERR(map)) {
12976 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12977 					insn[0].imm);
12978 				return PTR_ERR(map);
12979 			}
12980 
12981 			err = check_map_prog_compatibility(env, map, env->prog);
12982 			if (err) {
12983 				fdput(f);
12984 				return err;
12985 			}
12986 
12987 			aux = &env->insn_aux_data[i];
12988 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12989 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12990 				addr = (unsigned long)map;
12991 			} else {
12992 				u32 off = insn[1].imm;
12993 
12994 				if (off >= BPF_MAX_VAR_OFF) {
12995 					verbose(env, "direct value offset of %u is not allowed\n", off);
12996 					fdput(f);
12997 					return -EINVAL;
12998 				}
12999 
13000 				if (!map->ops->map_direct_value_addr) {
13001 					verbose(env, "no direct value access support for this map type\n");
13002 					fdput(f);
13003 					return -EINVAL;
13004 				}
13005 
13006 				err = map->ops->map_direct_value_addr(map, &addr, off);
13007 				if (err) {
13008 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
13009 						map->value_size, off);
13010 					fdput(f);
13011 					return err;
13012 				}
13013 
13014 				aux->map_off = off;
13015 				addr += off;
13016 			}
13017 
13018 			insn[0].imm = (u32)addr;
13019 			insn[1].imm = addr >> 32;
13020 
13021 			/* check whether we recorded this map already */
13022 			for (j = 0; j < env->used_map_cnt; j++) {
13023 				if (env->used_maps[j] == map) {
13024 					aux->map_index = j;
13025 					fdput(f);
13026 					goto next_insn;
13027 				}
13028 			}
13029 
13030 			if (env->used_map_cnt >= MAX_USED_MAPS) {
13031 				fdput(f);
13032 				return -E2BIG;
13033 			}
13034 
13035 			/* hold the map. If the program is rejected by verifier,
13036 			 * the map will be released by release_maps() or it
13037 			 * will be used by the valid program until it's unloaded
13038 			 * and all maps are released in free_used_maps()
13039 			 */
13040 			bpf_map_inc(map);
13041 
13042 			aux->map_index = env->used_map_cnt;
13043 			env->used_maps[env->used_map_cnt++] = map;
13044 
13045 			if (bpf_map_is_cgroup_storage(map) &&
13046 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
13047 				verbose(env, "only one cgroup storage of each type is allowed\n");
13048 				fdput(f);
13049 				return -EBUSY;
13050 			}
13051 
13052 			fdput(f);
13053 next_insn:
13054 			insn++;
13055 			i++;
13056 			continue;
13057 		}
13058 
13059 		/* Basic sanity check before we invest more work here. */
13060 		if (!bpf_opcode_in_insntable(insn->code)) {
13061 			verbose(env, "unknown opcode %02x\n", insn->code);
13062 			return -EINVAL;
13063 		}
13064 	}
13065 
13066 	/* now all pseudo BPF_LD_IMM64 instructions load valid
13067 	 * 'struct bpf_map *' into a register instead of user map_fd.
13068 	 * These pointers will be used later by verifier to validate map access.
13069 	 */
13070 	return 0;
13071 }
13072 
13073 /* drop refcnt of maps used by the rejected program */
13074 static void release_maps(struct bpf_verifier_env *env)
13075 {
13076 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
13077 			     env->used_map_cnt);
13078 }
13079 
13080 /* drop refcnt of maps used by the rejected program */
13081 static void release_btfs(struct bpf_verifier_env *env)
13082 {
13083 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13084 			     env->used_btf_cnt);
13085 }
13086 
13087 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13088 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13089 {
13090 	struct bpf_insn *insn = env->prog->insnsi;
13091 	int insn_cnt = env->prog->len;
13092 	int i;
13093 
13094 	for (i = 0; i < insn_cnt; i++, insn++) {
13095 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13096 			continue;
13097 		if (insn->src_reg == BPF_PSEUDO_FUNC)
13098 			continue;
13099 		insn->src_reg = 0;
13100 	}
13101 }
13102 
13103 /* single env->prog->insni[off] instruction was replaced with the range
13104  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
13105  * [0, off) and [off, end) to new locations, so the patched range stays zero
13106  */
13107 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13108 				 struct bpf_insn_aux_data *new_data,
13109 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
13110 {
13111 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13112 	struct bpf_insn *insn = new_prog->insnsi;
13113 	u32 old_seen = old_data[off].seen;
13114 	u32 prog_len;
13115 	int i;
13116 
13117 	/* aux info at OFF always needs adjustment, no matter fast path
13118 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13119 	 * original insn at old prog.
13120 	 */
13121 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13122 
13123 	if (cnt == 1)
13124 		return;
13125 	prog_len = new_prog->len;
13126 
13127 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13128 	memcpy(new_data + off + cnt - 1, old_data + off,
13129 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13130 	for (i = off; i < off + cnt - 1; i++) {
13131 		/* Expand insni[off]'s seen count to the patched range. */
13132 		new_data[i].seen = old_seen;
13133 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
13134 	}
13135 	env->insn_aux_data = new_data;
13136 	vfree(old_data);
13137 }
13138 
13139 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13140 {
13141 	int i;
13142 
13143 	if (len == 1)
13144 		return;
13145 	/* NOTE: fake 'exit' subprog should be updated as well. */
13146 	for (i = 0; i <= env->subprog_cnt; i++) {
13147 		if (env->subprog_info[i].start <= off)
13148 			continue;
13149 		env->subprog_info[i].start += len - 1;
13150 	}
13151 }
13152 
13153 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13154 {
13155 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13156 	int i, sz = prog->aux->size_poke_tab;
13157 	struct bpf_jit_poke_descriptor *desc;
13158 
13159 	for (i = 0; i < sz; i++) {
13160 		desc = &tab[i];
13161 		if (desc->insn_idx <= off)
13162 			continue;
13163 		desc->insn_idx += len - 1;
13164 	}
13165 }
13166 
13167 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13168 					    const struct bpf_insn *patch, u32 len)
13169 {
13170 	struct bpf_prog *new_prog;
13171 	struct bpf_insn_aux_data *new_data = NULL;
13172 
13173 	if (len > 1) {
13174 		new_data = vzalloc(array_size(env->prog->len + len - 1,
13175 					      sizeof(struct bpf_insn_aux_data)));
13176 		if (!new_data)
13177 			return NULL;
13178 	}
13179 
13180 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13181 	if (IS_ERR(new_prog)) {
13182 		if (PTR_ERR(new_prog) == -ERANGE)
13183 			verbose(env,
13184 				"insn %d cannot be patched due to 16-bit range\n",
13185 				env->insn_aux_data[off].orig_idx);
13186 		vfree(new_data);
13187 		return NULL;
13188 	}
13189 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
13190 	adjust_subprog_starts(env, off, len);
13191 	adjust_poke_descs(new_prog, off, len);
13192 	return new_prog;
13193 }
13194 
13195 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13196 					      u32 off, u32 cnt)
13197 {
13198 	int i, j;
13199 
13200 	/* find first prog starting at or after off (first to remove) */
13201 	for (i = 0; i < env->subprog_cnt; i++)
13202 		if (env->subprog_info[i].start >= off)
13203 			break;
13204 	/* find first prog starting at or after off + cnt (first to stay) */
13205 	for (j = i; j < env->subprog_cnt; j++)
13206 		if (env->subprog_info[j].start >= off + cnt)
13207 			break;
13208 	/* if j doesn't start exactly at off + cnt, we are just removing
13209 	 * the front of previous prog
13210 	 */
13211 	if (env->subprog_info[j].start != off + cnt)
13212 		j--;
13213 
13214 	if (j > i) {
13215 		struct bpf_prog_aux *aux = env->prog->aux;
13216 		int move;
13217 
13218 		/* move fake 'exit' subprog as well */
13219 		move = env->subprog_cnt + 1 - j;
13220 
13221 		memmove(env->subprog_info + i,
13222 			env->subprog_info + j,
13223 			sizeof(*env->subprog_info) * move);
13224 		env->subprog_cnt -= j - i;
13225 
13226 		/* remove func_info */
13227 		if (aux->func_info) {
13228 			move = aux->func_info_cnt - j;
13229 
13230 			memmove(aux->func_info + i,
13231 				aux->func_info + j,
13232 				sizeof(*aux->func_info) * move);
13233 			aux->func_info_cnt -= j - i;
13234 			/* func_info->insn_off is set after all code rewrites,
13235 			 * in adjust_btf_func() - no need to adjust
13236 			 */
13237 		}
13238 	} else {
13239 		/* convert i from "first prog to remove" to "first to adjust" */
13240 		if (env->subprog_info[i].start == off)
13241 			i++;
13242 	}
13243 
13244 	/* update fake 'exit' subprog as well */
13245 	for (; i <= env->subprog_cnt; i++)
13246 		env->subprog_info[i].start -= cnt;
13247 
13248 	return 0;
13249 }
13250 
13251 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13252 				      u32 cnt)
13253 {
13254 	struct bpf_prog *prog = env->prog;
13255 	u32 i, l_off, l_cnt, nr_linfo;
13256 	struct bpf_line_info *linfo;
13257 
13258 	nr_linfo = prog->aux->nr_linfo;
13259 	if (!nr_linfo)
13260 		return 0;
13261 
13262 	linfo = prog->aux->linfo;
13263 
13264 	/* find first line info to remove, count lines to be removed */
13265 	for (i = 0; i < nr_linfo; i++)
13266 		if (linfo[i].insn_off >= off)
13267 			break;
13268 
13269 	l_off = i;
13270 	l_cnt = 0;
13271 	for (; i < nr_linfo; i++)
13272 		if (linfo[i].insn_off < off + cnt)
13273 			l_cnt++;
13274 		else
13275 			break;
13276 
13277 	/* First live insn doesn't match first live linfo, it needs to "inherit"
13278 	 * last removed linfo.  prog is already modified, so prog->len == off
13279 	 * means no live instructions after (tail of the program was removed).
13280 	 */
13281 	if (prog->len != off && l_cnt &&
13282 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13283 		l_cnt--;
13284 		linfo[--i].insn_off = off + cnt;
13285 	}
13286 
13287 	/* remove the line info which refer to the removed instructions */
13288 	if (l_cnt) {
13289 		memmove(linfo + l_off, linfo + i,
13290 			sizeof(*linfo) * (nr_linfo - i));
13291 
13292 		prog->aux->nr_linfo -= l_cnt;
13293 		nr_linfo = prog->aux->nr_linfo;
13294 	}
13295 
13296 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
13297 	for (i = l_off; i < nr_linfo; i++)
13298 		linfo[i].insn_off -= cnt;
13299 
13300 	/* fix up all subprogs (incl. 'exit') which start >= off */
13301 	for (i = 0; i <= env->subprog_cnt; i++)
13302 		if (env->subprog_info[i].linfo_idx > l_off) {
13303 			/* program may have started in the removed region but
13304 			 * may not be fully removed
13305 			 */
13306 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13307 				env->subprog_info[i].linfo_idx -= l_cnt;
13308 			else
13309 				env->subprog_info[i].linfo_idx = l_off;
13310 		}
13311 
13312 	return 0;
13313 }
13314 
13315 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13316 {
13317 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13318 	unsigned int orig_prog_len = env->prog->len;
13319 	int err;
13320 
13321 	if (bpf_prog_is_dev_bound(env->prog->aux))
13322 		bpf_prog_offload_remove_insns(env, off, cnt);
13323 
13324 	err = bpf_remove_insns(env->prog, off, cnt);
13325 	if (err)
13326 		return err;
13327 
13328 	err = adjust_subprog_starts_after_remove(env, off, cnt);
13329 	if (err)
13330 		return err;
13331 
13332 	err = bpf_adj_linfo_after_remove(env, off, cnt);
13333 	if (err)
13334 		return err;
13335 
13336 	memmove(aux_data + off,	aux_data + off + cnt,
13337 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
13338 
13339 	return 0;
13340 }
13341 
13342 /* The verifier does more data flow analysis than llvm and will not
13343  * explore branches that are dead at run time. Malicious programs can
13344  * have dead code too. Therefore replace all dead at-run-time code
13345  * with 'ja -1'.
13346  *
13347  * Just nops are not optimal, e.g. if they would sit at the end of the
13348  * program and through another bug we would manage to jump there, then
13349  * we'd execute beyond program memory otherwise. Returning exception
13350  * code also wouldn't work since we can have subprogs where the dead
13351  * code could be located.
13352  */
13353 static void sanitize_dead_code(struct bpf_verifier_env *env)
13354 {
13355 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13356 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13357 	struct bpf_insn *insn = env->prog->insnsi;
13358 	const int insn_cnt = env->prog->len;
13359 	int i;
13360 
13361 	for (i = 0; i < insn_cnt; i++) {
13362 		if (aux_data[i].seen)
13363 			continue;
13364 		memcpy(insn + i, &trap, sizeof(trap));
13365 		aux_data[i].zext_dst = false;
13366 	}
13367 }
13368 
13369 static bool insn_is_cond_jump(u8 code)
13370 {
13371 	u8 op;
13372 
13373 	if (BPF_CLASS(code) == BPF_JMP32)
13374 		return true;
13375 
13376 	if (BPF_CLASS(code) != BPF_JMP)
13377 		return false;
13378 
13379 	op = BPF_OP(code);
13380 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13381 }
13382 
13383 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13384 {
13385 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13386 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13387 	struct bpf_insn *insn = env->prog->insnsi;
13388 	const int insn_cnt = env->prog->len;
13389 	int i;
13390 
13391 	for (i = 0; i < insn_cnt; i++, insn++) {
13392 		if (!insn_is_cond_jump(insn->code))
13393 			continue;
13394 
13395 		if (!aux_data[i + 1].seen)
13396 			ja.off = insn->off;
13397 		else if (!aux_data[i + 1 + insn->off].seen)
13398 			ja.off = 0;
13399 		else
13400 			continue;
13401 
13402 		if (bpf_prog_is_dev_bound(env->prog->aux))
13403 			bpf_prog_offload_replace_insn(env, i, &ja);
13404 
13405 		memcpy(insn, &ja, sizeof(ja));
13406 	}
13407 }
13408 
13409 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13410 {
13411 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13412 	int insn_cnt = env->prog->len;
13413 	int i, err;
13414 
13415 	for (i = 0; i < insn_cnt; i++) {
13416 		int j;
13417 
13418 		j = 0;
13419 		while (i + j < insn_cnt && !aux_data[i + j].seen)
13420 			j++;
13421 		if (!j)
13422 			continue;
13423 
13424 		err = verifier_remove_insns(env, i, j);
13425 		if (err)
13426 			return err;
13427 		insn_cnt = env->prog->len;
13428 	}
13429 
13430 	return 0;
13431 }
13432 
13433 static int opt_remove_nops(struct bpf_verifier_env *env)
13434 {
13435 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13436 	struct bpf_insn *insn = env->prog->insnsi;
13437 	int insn_cnt = env->prog->len;
13438 	int i, err;
13439 
13440 	for (i = 0; i < insn_cnt; i++) {
13441 		if (memcmp(&insn[i], &ja, sizeof(ja)))
13442 			continue;
13443 
13444 		err = verifier_remove_insns(env, i, 1);
13445 		if (err)
13446 			return err;
13447 		insn_cnt--;
13448 		i--;
13449 	}
13450 
13451 	return 0;
13452 }
13453 
13454 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13455 					 const union bpf_attr *attr)
13456 {
13457 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13458 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
13459 	int i, patch_len, delta = 0, len = env->prog->len;
13460 	struct bpf_insn *insns = env->prog->insnsi;
13461 	struct bpf_prog *new_prog;
13462 	bool rnd_hi32;
13463 
13464 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13465 	zext_patch[1] = BPF_ZEXT_REG(0);
13466 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13467 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13468 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13469 	for (i = 0; i < len; i++) {
13470 		int adj_idx = i + delta;
13471 		struct bpf_insn insn;
13472 		int load_reg;
13473 
13474 		insn = insns[adj_idx];
13475 		load_reg = insn_def_regno(&insn);
13476 		if (!aux[adj_idx].zext_dst) {
13477 			u8 code, class;
13478 			u32 imm_rnd;
13479 
13480 			if (!rnd_hi32)
13481 				continue;
13482 
13483 			code = insn.code;
13484 			class = BPF_CLASS(code);
13485 			if (load_reg == -1)
13486 				continue;
13487 
13488 			/* NOTE: arg "reg" (the fourth one) is only used for
13489 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
13490 			 *       here.
13491 			 */
13492 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13493 				if (class == BPF_LD &&
13494 				    BPF_MODE(code) == BPF_IMM)
13495 					i++;
13496 				continue;
13497 			}
13498 
13499 			/* ctx load could be transformed into wider load. */
13500 			if (class == BPF_LDX &&
13501 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
13502 				continue;
13503 
13504 			imm_rnd = get_random_u32();
13505 			rnd_hi32_patch[0] = insn;
13506 			rnd_hi32_patch[1].imm = imm_rnd;
13507 			rnd_hi32_patch[3].dst_reg = load_reg;
13508 			patch = rnd_hi32_patch;
13509 			patch_len = 4;
13510 			goto apply_patch_buffer;
13511 		}
13512 
13513 		/* Add in an zero-extend instruction if a) the JIT has requested
13514 		 * it or b) it's a CMPXCHG.
13515 		 *
13516 		 * The latter is because: BPF_CMPXCHG always loads a value into
13517 		 * R0, therefore always zero-extends. However some archs'
13518 		 * equivalent instruction only does this load when the
13519 		 * comparison is successful. This detail of CMPXCHG is
13520 		 * orthogonal to the general zero-extension behaviour of the
13521 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
13522 		 */
13523 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13524 			continue;
13525 
13526 		if (WARN_ON(load_reg == -1)) {
13527 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13528 			return -EFAULT;
13529 		}
13530 
13531 		zext_patch[0] = insn;
13532 		zext_patch[1].dst_reg = load_reg;
13533 		zext_patch[1].src_reg = load_reg;
13534 		patch = zext_patch;
13535 		patch_len = 2;
13536 apply_patch_buffer:
13537 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13538 		if (!new_prog)
13539 			return -ENOMEM;
13540 		env->prog = new_prog;
13541 		insns = new_prog->insnsi;
13542 		aux = env->insn_aux_data;
13543 		delta += patch_len - 1;
13544 	}
13545 
13546 	return 0;
13547 }
13548 
13549 /* convert load instructions that access fields of a context type into a
13550  * sequence of instructions that access fields of the underlying structure:
13551  *     struct __sk_buff    -> struct sk_buff
13552  *     struct bpf_sock_ops -> struct sock
13553  */
13554 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13555 {
13556 	const struct bpf_verifier_ops *ops = env->ops;
13557 	int i, cnt, size, ctx_field_size, delta = 0;
13558 	const int insn_cnt = env->prog->len;
13559 	struct bpf_insn insn_buf[16], *insn;
13560 	u32 target_size, size_default, off;
13561 	struct bpf_prog *new_prog;
13562 	enum bpf_access_type type;
13563 	bool is_narrower_load;
13564 
13565 	if (ops->gen_prologue || env->seen_direct_write) {
13566 		if (!ops->gen_prologue) {
13567 			verbose(env, "bpf verifier is misconfigured\n");
13568 			return -EINVAL;
13569 		}
13570 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13571 					env->prog);
13572 		if (cnt >= ARRAY_SIZE(insn_buf)) {
13573 			verbose(env, "bpf verifier is misconfigured\n");
13574 			return -EINVAL;
13575 		} else if (cnt) {
13576 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13577 			if (!new_prog)
13578 				return -ENOMEM;
13579 
13580 			env->prog = new_prog;
13581 			delta += cnt - 1;
13582 		}
13583 	}
13584 
13585 	if (bpf_prog_is_dev_bound(env->prog->aux))
13586 		return 0;
13587 
13588 	insn = env->prog->insnsi + delta;
13589 
13590 	for (i = 0; i < insn_cnt; i++, insn++) {
13591 		bpf_convert_ctx_access_t convert_ctx_access;
13592 		bool ctx_access;
13593 
13594 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13595 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13596 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13597 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13598 			type = BPF_READ;
13599 			ctx_access = true;
13600 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13601 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13602 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13603 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13604 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13605 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13606 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13607 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13608 			type = BPF_WRITE;
13609 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13610 		} else {
13611 			continue;
13612 		}
13613 
13614 		if (type == BPF_WRITE &&
13615 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
13616 			struct bpf_insn patch[] = {
13617 				*insn,
13618 				BPF_ST_NOSPEC(),
13619 			};
13620 
13621 			cnt = ARRAY_SIZE(patch);
13622 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13623 			if (!new_prog)
13624 				return -ENOMEM;
13625 
13626 			delta    += cnt - 1;
13627 			env->prog = new_prog;
13628 			insn      = new_prog->insnsi + i + delta;
13629 			continue;
13630 		}
13631 
13632 		if (!ctx_access)
13633 			continue;
13634 
13635 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13636 		case PTR_TO_CTX:
13637 			if (!ops->convert_ctx_access)
13638 				continue;
13639 			convert_ctx_access = ops->convert_ctx_access;
13640 			break;
13641 		case PTR_TO_SOCKET:
13642 		case PTR_TO_SOCK_COMMON:
13643 			convert_ctx_access = bpf_sock_convert_ctx_access;
13644 			break;
13645 		case PTR_TO_TCP_SOCK:
13646 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13647 			break;
13648 		case PTR_TO_XDP_SOCK:
13649 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13650 			break;
13651 		case PTR_TO_BTF_ID:
13652 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13653 			if (type == BPF_READ) {
13654 				insn->code = BPF_LDX | BPF_PROBE_MEM |
13655 					BPF_SIZE((insn)->code);
13656 				env->prog->aux->num_exentries++;
13657 			}
13658 			continue;
13659 		default:
13660 			continue;
13661 		}
13662 
13663 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13664 		size = BPF_LDST_BYTES(insn);
13665 
13666 		/* If the read access is a narrower load of the field,
13667 		 * convert to a 4/8-byte load, to minimum program type specific
13668 		 * convert_ctx_access changes. If conversion is successful,
13669 		 * we will apply proper mask to the result.
13670 		 */
13671 		is_narrower_load = size < ctx_field_size;
13672 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13673 		off = insn->off;
13674 		if (is_narrower_load) {
13675 			u8 size_code;
13676 
13677 			if (type == BPF_WRITE) {
13678 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13679 				return -EINVAL;
13680 			}
13681 
13682 			size_code = BPF_H;
13683 			if (ctx_field_size == 4)
13684 				size_code = BPF_W;
13685 			else if (ctx_field_size == 8)
13686 				size_code = BPF_DW;
13687 
13688 			insn->off = off & ~(size_default - 1);
13689 			insn->code = BPF_LDX | BPF_MEM | size_code;
13690 		}
13691 
13692 		target_size = 0;
13693 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13694 					 &target_size);
13695 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13696 		    (ctx_field_size && !target_size)) {
13697 			verbose(env, "bpf verifier is misconfigured\n");
13698 			return -EINVAL;
13699 		}
13700 
13701 		if (is_narrower_load && size < target_size) {
13702 			u8 shift = bpf_ctx_narrow_access_offset(
13703 				off, size, size_default) * 8;
13704 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13705 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13706 				return -EINVAL;
13707 			}
13708 			if (ctx_field_size <= 4) {
13709 				if (shift)
13710 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13711 									insn->dst_reg,
13712 									shift);
13713 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13714 								(1 << size * 8) - 1);
13715 			} else {
13716 				if (shift)
13717 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13718 									insn->dst_reg,
13719 									shift);
13720 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13721 								(1ULL << size * 8) - 1);
13722 			}
13723 		}
13724 
13725 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13726 		if (!new_prog)
13727 			return -ENOMEM;
13728 
13729 		delta += cnt - 1;
13730 
13731 		/* keep walking new program and skip insns we just inserted */
13732 		env->prog = new_prog;
13733 		insn      = new_prog->insnsi + i + delta;
13734 	}
13735 
13736 	return 0;
13737 }
13738 
13739 static int jit_subprogs(struct bpf_verifier_env *env)
13740 {
13741 	struct bpf_prog *prog = env->prog, **func, *tmp;
13742 	int i, j, subprog_start, subprog_end = 0, len, subprog;
13743 	struct bpf_map *map_ptr;
13744 	struct bpf_insn *insn;
13745 	void *old_bpf_func;
13746 	int err, num_exentries;
13747 
13748 	if (env->subprog_cnt <= 1)
13749 		return 0;
13750 
13751 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13752 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13753 			continue;
13754 
13755 		/* Upon error here we cannot fall back to interpreter but
13756 		 * need a hard reject of the program. Thus -EFAULT is
13757 		 * propagated in any case.
13758 		 */
13759 		subprog = find_subprog(env, i + insn->imm + 1);
13760 		if (subprog < 0) {
13761 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13762 				  i + insn->imm + 1);
13763 			return -EFAULT;
13764 		}
13765 		/* temporarily remember subprog id inside insn instead of
13766 		 * aux_data, since next loop will split up all insns into funcs
13767 		 */
13768 		insn->off = subprog;
13769 		/* remember original imm in case JIT fails and fallback
13770 		 * to interpreter will be needed
13771 		 */
13772 		env->insn_aux_data[i].call_imm = insn->imm;
13773 		/* point imm to __bpf_call_base+1 from JITs point of view */
13774 		insn->imm = 1;
13775 		if (bpf_pseudo_func(insn))
13776 			/* jit (e.g. x86_64) may emit fewer instructions
13777 			 * if it learns a u32 imm is the same as a u64 imm.
13778 			 * Force a non zero here.
13779 			 */
13780 			insn[1].imm = 1;
13781 	}
13782 
13783 	err = bpf_prog_alloc_jited_linfo(prog);
13784 	if (err)
13785 		goto out_undo_insn;
13786 
13787 	err = -ENOMEM;
13788 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13789 	if (!func)
13790 		goto out_undo_insn;
13791 
13792 	for (i = 0; i < env->subprog_cnt; i++) {
13793 		subprog_start = subprog_end;
13794 		subprog_end = env->subprog_info[i + 1].start;
13795 
13796 		len = subprog_end - subprog_start;
13797 		/* bpf_prog_run() doesn't call subprogs directly,
13798 		 * hence main prog stats include the runtime of subprogs.
13799 		 * subprogs don't have IDs and not reachable via prog_get_next_id
13800 		 * func[i]->stats will never be accessed and stays NULL
13801 		 */
13802 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13803 		if (!func[i])
13804 			goto out_free;
13805 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13806 		       len * sizeof(struct bpf_insn));
13807 		func[i]->type = prog->type;
13808 		func[i]->len = len;
13809 		if (bpf_prog_calc_tag(func[i]))
13810 			goto out_free;
13811 		func[i]->is_func = 1;
13812 		func[i]->aux->func_idx = i;
13813 		/* Below members will be freed only at prog->aux */
13814 		func[i]->aux->btf = prog->aux->btf;
13815 		func[i]->aux->func_info = prog->aux->func_info;
13816 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13817 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13818 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13819 
13820 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13821 			struct bpf_jit_poke_descriptor *poke;
13822 
13823 			poke = &prog->aux->poke_tab[j];
13824 			if (poke->insn_idx < subprog_end &&
13825 			    poke->insn_idx >= subprog_start)
13826 				poke->aux = func[i]->aux;
13827 		}
13828 
13829 		func[i]->aux->name[0] = 'F';
13830 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13831 		func[i]->jit_requested = 1;
13832 		func[i]->blinding_requested = prog->blinding_requested;
13833 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13834 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13835 		func[i]->aux->linfo = prog->aux->linfo;
13836 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13837 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13838 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13839 		num_exentries = 0;
13840 		insn = func[i]->insnsi;
13841 		for (j = 0; j < func[i]->len; j++, insn++) {
13842 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13843 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13844 				num_exentries++;
13845 		}
13846 		func[i]->aux->num_exentries = num_exentries;
13847 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13848 		func[i] = bpf_int_jit_compile(func[i]);
13849 		if (!func[i]->jited) {
13850 			err = -ENOTSUPP;
13851 			goto out_free;
13852 		}
13853 		cond_resched();
13854 	}
13855 
13856 	/* at this point all bpf functions were successfully JITed
13857 	 * now populate all bpf_calls with correct addresses and
13858 	 * run last pass of JIT
13859 	 */
13860 	for (i = 0; i < env->subprog_cnt; i++) {
13861 		insn = func[i]->insnsi;
13862 		for (j = 0; j < func[i]->len; j++, insn++) {
13863 			if (bpf_pseudo_func(insn)) {
13864 				subprog = insn->off;
13865 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13866 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13867 				continue;
13868 			}
13869 			if (!bpf_pseudo_call(insn))
13870 				continue;
13871 			subprog = insn->off;
13872 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13873 		}
13874 
13875 		/* we use the aux data to keep a list of the start addresses
13876 		 * of the JITed images for each function in the program
13877 		 *
13878 		 * for some architectures, such as powerpc64, the imm field
13879 		 * might not be large enough to hold the offset of the start
13880 		 * address of the callee's JITed image from __bpf_call_base
13881 		 *
13882 		 * in such cases, we can lookup the start address of a callee
13883 		 * by using its subprog id, available from the off field of
13884 		 * the call instruction, as an index for this list
13885 		 */
13886 		func[i]->aux->func = func;
13887 		func[i]->aux->func_cnt = env->subprog_cnt;
13888 	}
13889 	for (i = 0; i < env->subprog_cnt; i++) {
13890 		old_bpf_func = func[i]->bpf_func;
13891 		tmp = bpf_int_jit_compile(func[i]);
13892 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13893 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13894 			err = -ENOTSUPP;
13895 			goto out_free;
13896 		}
13897 		cond_resched();
13898 	}
13899 
13900 	/* finally lock prog and jit images for all functions and
13901 	 * populate kallsysm
13902 	 */
13903 	for (i = 0; i < env->subprog_cnt; i++) {
13904 		bpf_prog_lock_ro(func[i]);
13905 		bpf_prog_kallsyms_add(func[i]);
13906 	}
13907 
13908 	/* Last step: make now unused interpreter insns from main
13909 	 * prog consistent for later dump requests, so they can
13910 	 * later look the same as if they were interpreted only.
13911 	 */
13912 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13913 		if (bpf_pseudo_func(insn)) {
13914 			insn[0].imm = env->insn_aux_data[i].call_imm;
13915 			insn[1].imm = insn->off;
13916 			insn->off = 0;
13917 			continue;
13918 		}
13919 		if (!bpf_pseudo_call(insn))
13920 			continue;
13921 		insn->off = env->insn_aux_data[i].call_imm;
13922 		subprog = find_subprog(env, i + insn->off + 1);
13923 		insn->imm = subprog;
13924 	}
13925 
13926 	prog->jited = 1;
13927 	prog->bpf_func = func[0]->bpf_func;
13928 	prog->jited_len = func[0]->jited_len;
13929 	prog->aux->func = func;
13930 	prog->aux->func_cnt = env->subprog_cnt;
13931 	bpf_prog_jit_attempt_done(prog);
13932 	return 0;
13933 out_free:
13934 	/* We failed JIT'ing, so at this point we need to unregister poke
13935 	 * descriptors from subprogs, so that kernel is not attempting to
13936 	 * patch it anymore as we're freeing the subprog JIT memory.
13937 	 */
13938 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13939 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13940 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13941 	}
13942 	/* At this point we're guaranteed that poke descriptors are not
13943 	 * live anymore. We can just unlink its descriptor table as it's
13944 	 * released with the main prog.
13945 	 */
13946 	for (i = 0; i < env->subprog_cnt; i++) {
13947 		if (!func[i])
13948 			continue;
13949 		func[i]->aux->poke_tab = NULL;
13950 		bpf_jit_free(func[i]);
13951 	}
13952 	kfree(func);
13953 out_undo_insn:
13954 	/* cleanup main prog to be interpreted */
13955 	prog->jit_requested = 0;
13956 	prog->blinding_requested = 0;
13957 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13958 		if (!bpf_pseudo_call(insn))
13959 			continue;
13960 		insn->off = 0;
13961 		insn->imm = env->insn_aux_data[i].call_imm;
13962 	}
13963 	bpf_prog_jit_attempt_done(prog);
13964 	return err;
13965 }
13966 
13967 static int fixup_call_args(struct bpf_verifier_env *env)
13968 {
13969 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13970 	struct bpf_prog *prog = env->prog;
13971 	struct bpf_insn *insn = prog->insnsi;
13972 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13973 	int i, depth;
13974 #endif
13975 	int err = 0;
13976 
13977 	if (env->prog->jit_requested &&
13978 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13979 		err = jit_subprogs(env);
13980 		if (err == 0)
13981 			return 0;
13982 		if (err == -EFAULT)
13983 			return err;
13984 	}
13985 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13986 	if (has_kfunc_call) {
13987 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13988 		return -EINVAL;
13989 	}
13990 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13991 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13992 		 * have to be rejected, since interpreter doesn't support them yet.
13993 		 */
13994 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13995 		return -EINVAL;
13996 	}
13997 	for (i = 0; i < prog->len; i++, insn++) {
13998 		if (bpf_pseudo_func(insn)) {
13999 			/* When JIT fails the progs with callback calls
14000 			 * have to be rejected, since interpreter doesn't support them yet.
14001 			 */
14002 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
14003 			return -EINVAL;
14004 		}
14005 
14006 		if (!bpf_pseudo_call(insn))
14007 			continue;
14008 		depth = get_callee_stack_depth(env, insn, i);
14009 		if (depth < 0)
14010 			return depth;
14011 		bpf_patch_call_args(insn, depth);
14012 	}
14013 	err = 0;
14014 #endif
14015 	return err;
14016 }
14017 
14018 static int fixup_kfunc_call(struct bpf_verifier_env *env,
14019 			    struct bpf_insn *insn)
14020 {
14021 	const struct bpf_kfunc_desc *desc;
14022 
14023 	if (!insn->imm) {
14024 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
14025 		return -EINVAL;
14026 	}
14027 
14028 	/* insn->imm has the btf func_id. Replace it with
14029 	 * an address (relative to __bpf_base_call).
14030 	 */
14031 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
14032 	if (!desc) {
14033 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
14034 			insn->imm);
14035 		return -EFAULT;
14036 	}
14037 
14038 	insn->imm = desc->imm;
14039 
14040 	return 0;
14041 }
14042 
14043 /* Do various post-verification rewrites in a single program pass.
14044  * These rewrites simplify JIT and interpreter implementations.
14045  */
14046 static int do_misc_fixups(struct bpf_verifier_env *env)
14047 {
14048 	struct bpf_prog *prog = env->prog;
14049 	enum bpf_attach_type eatype = prog->expected_attach_type;
14050 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
14051 	struct bpf_insn *insn = prog->insnsi;
14052 	const struct bpf_func_proto *fn;
14053 	const int insn_cnt = prog->len;
14054 	const struct bpf_map_ops *ops;
14055 	struct bpf_insn_aux_data *aux;
14056 	struct bpf_insn insn_buf[16];
14057 	struct bpf_prog *new_prog;
14058 	struct bpf_map *map_ptr;
14059 	int i, ret, cnt, delta = 0;
14060 
14061 	for (i = 0; i < insn_cnt; i++, insn++) {
14062 		/* Make divide-by-zero exceptions impossible. */
14063 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
14064 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
14065 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
14066 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
14067 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
14068 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
14069 			struct bpf_insn *patchlet;
14070 			struct bpf_insn chk_and_div[] = {
14071 				/* [R,W]x div 0 -> 0 */
14072 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14073 					     BPF_JNE | BPF_K, insn->src_reg,
14074 					     0, 2, 0),
14075 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
14076 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14077 				*insn,
14078 			};
14079 			struct bpf_insn chk_and_mod[] = {
14080 				/* [R,W]x mod 0 -> [R,W]x */
14081 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14082 					     BPF_JEQ | BPF_K, insn->src_reg,
14083 					     0, 1 + (is64 ? 0 : 1), 0),
14084 				*insn,
14085 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14086 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14087 			};
14088 
14089 			patchlet = isdiv ? chk_and_div : chk_and_mod;
14090 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14091 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14092 
14093 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14094 			if (!new_prog)
14095 				return -ENOMEM;
14096 
14097 			delta    += cnt - 1;
14098 			env->prog = prog = new_prog;
14099 			insn      = new_prog->insnsi + i + delta;
14100 			continue;
14101 		}
14102 
14103 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14104 		if (BPF_CLASS(insn->code) == BPF_LD &&
14105 		    (BPF_MODE(insn->code) == BPF_ABS ||
14106 		     BPF_MODE(insn->code) == BPF_IND)) {
14107 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
14108 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14109 				verbose(env, "bpf verifier is misconfigured\n");
14110 				return -EINVAL;
14111 			}
14112 
14113 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14114 			if (!new_prog)
14115 				return -ENOMEM;
14116 
14117 			delta    += cnt - 1;
14118 			env->prog = prog = new_prog;
14119 			insn      = new_prog->insnsi + i + delta;
14120 			continue;
14121 		}
14122 
14123 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
14124 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14125 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14126 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14127 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14128 			struct bpf_insn *patch = &insn_buf[0];
14129 			bool issrc, isneg, isimm;
14130 			u32 off_reg;
14131 
14132 			aux = &env->insn_aux_data[i + delta];
14133 			if (!aux->alu_state ||
14134 			    aux->alu_state == BPF_ALU_NON_POINTER)
14135 				continue;
14136 
14137 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14138 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14139 				BPF_ALU_SANITIZE_SRC;
14140 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14141 
14142 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
14143 			if (isimm) {
14144 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14145 			} else {
14146 				if (isneg)
14147 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14148 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14149 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14150 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14151 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14152 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14153 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14154 			}
14155 			if (!issrc)
14156 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14157 			insn->src_reg = BPF_REG_AX;
14158 			if (isneg)
14159 				insn->code = insn->code == code_add ?
14160 					     code_sub : code_add;
14161 			*patch++ = *insn;
14162 			if (issrc && isneg && !isimm)
14163 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14164 			cnt = patch - insn_buf;
14165 
14166 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14167 			if (!new_prog)
14168 				return -ENOMEM;
14169 
14170 			delta    += cnt - 1;
14171 			env->prog = prog = new_prog;
14172 			insn      = new_prog->insnsi + i + delta;
14173 			continue;
14174 		}
14175 
14176 		if (insn->code != (BPF_JMP | BPF_CALL))
14177 			continue;
14178 		if (insn->src_reg == BPF_PSEUDO_CALL)
14179 			continue;
14180 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14181 			ret = fixup_kfunc_call(env, insn);
14182 			if (ret)
14183 				return ret;
14184 			continue;
14185 		}
14186 
14187 		if (insn->imm == BPF_FUNC_get_route_realm)
14188 			prog->dst_needed = 1;
14189 		if (insn->imm == BPF_FUNC_get_prandom_u32)
14190 			bpf_user_rnd_init_once();
14191 		if (insn->imm == BPF_FUNC_override_return)
14192 			prog->kprobe_override = 1;
14193 		if (insn->imm == BPF_FUNC_tail_call) {
14194 			/* If we tail call into other programs, we
14195 			 * cannot make any assumptions since they can
14196 			 * be replaced dynamically during runtime in
14197 			 * the program array.
14198 			 */
14199 			prog->cb_access = 1;
14200 			if (!allow_tail_call_in_subprogs(env))
14201 				prog->aux->stack_depth = MAX_BPF_STACK;
14202 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14203 
14204 			/* mark bpf_tail_call as different opcode to avoid
14205 			 * conditional branch in the interpreter for every normal
14206 			 * call and to prevent accidental JITing by JIT compiler
14207 			 * that doesn't support bpf_tail_call yet
14208 			 */
14209 			insn->imm = 0;
14210 			insn->code = BPF_JMP | BPF_TAIL_CALL;
14211 
14212 			aux = &env->insn_aux_data[i + delta];
14213 			if (env->bpf_capable && !prog->blinding_requested &&
14214 			    prog->jit_requested &&
14215 			    !bpf_map_key_poisoned(aux) &&
14216 			    !bpf_map_ptr_poisoned(aux) &&
14217 			    !bpf_map_ptr_unpriv(aux)) {
14218 				struct bpf_jit_poke_descriptor desc = {
14219 					.reason = BPF_POKE_REASON_TAIL_CALL,
14220 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14221 					.tail_call.key = bpf_map_key_immediate(aux),
14222 					.insn_idx = i + delta,
14223 				};
14224 
14225 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
14226 				if (ret < 0) {
14227 					verbose(env, "adding tail call poke descriptor failed\n");
14228 					return ret;
14229 				}
14230 
14231 				insn->imm = ret + 1;
14232 				continue;
14233 			}
14234 
14235 			if (!bpf_map_ptr_unpriv(aux))
14236 				continue;
14237 
14238 			/* instead of changing every JIT dealing with tail_call
14239 			 * emit two extra insns:
14240 			 * if (index >= max_entries) goto out;
14241 			 * index &= array->index_mask;
14242 			 * to avoid out-of-bounds cpu speculation
14243 			 */
14244 			if (bpf_map_ptr_poisoned(aux)) {
14245 				verbose(env, "tail_call abusing map_ptr\n");
14246 				return -EINVAL;
14247 			}
14248 
14249 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14250 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14251 						  map_ptr->max_entries, 2);
14252 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14253 						    container_of(map_ptr,
14254 								 struct bpf_array,
14255 								 map)->index_mask);
14256 			insn_buf[2] = *insn;
14257 			cnt = 3;
14258 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14259 			if (!new_prog)
14260 				return -ENOMEM;
14261 
14262 			delta    += cnt - 1;
14263 			env->prog = prog = new_prog;
14264 			insn      = new_prog->insnsi + i + delta;
14265 			continue;
14266 		}
14267 
14268 		if (insn->imm == BPF_FUNC_timer_set_callback) {
14269 			/* The verifier will process callback_fn as many times as necessary
14270 			 * with different maps and the register states prepared by
14271 			 * set_timer_callback_state will be accurate.
14272 			 *
14273 			 * The following use case is valid:
14274 			 *   map1 is shared by prog1, prog2, prog3.
14275 			 *   prog1 calls bpf_timer_init for some map1 elements
14276 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
14277 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
14278 			 *   prog3 calls bpf_timer_start for some map1 elements.
14279 			 *     Those that were not both bpf_timer_init-ed and
14280 			 *     bpf_timer_set_callback-ed will return -EINVAL.
14281 			 */
14282 			struct bpf_insn ld_addrs[2] = {
14283 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14284 			};
14285 
14286 			insn_buf[0] = ld_addrs[0];
14287 			insn_buf[1] = ld_addrs[1];
14288 			insn_buf[2] = *insn;
14289 			cnt = 3;
14290 
14291 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14292 			if (!new_prog)
14293 				return -ENOMEM;
14294 
14295 			delta    += cnt - 1;
14296 			env->prog = prog = new_prog;
14297 			insn      = new_prog->insnsi + i + delta;
14298 			goto patch_call_imm;
14299 		}
14300 
14301 		if (insn->imm == BPF_FUNC_task_storage_get ||
14302 		    insn->imm == BPF_FUNC_sk_storage_get ||
14303 		    insn->imm == BPF_FUNC_inode_storage_get ||
14304 		    insn->imm == BPF_FUNC_cgrp_storage_get) {
14305 			if (env->prog->aux->sleepable)
14306 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14307 			else
14308 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14309 			insn_buf[1] = *insn;
14310 			cnt = 2;
14311 
14312 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14313 			if (!new_prog)
14314 				return -ENOMEM;
14315 
14316 			delta += cnt - 1;
14317 			env->prog = prog = new_prog;
14318 			insn = new_prog->insnsi + i + delta;
14319 			goto patch_call_imm;
14320 		}
14321 
14322 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14323 		 * and other inlining handlers are currently limited to 64 bit
14324 		 * only.
14325 		 */
14326 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14327 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
14328 		     insn->imm == BPF_FUNC_map_update_elem ||
14329 		     insn->imm == BPF_FUNC_map_delete_elem ||
14330 		     insn->imm == BPF_FUNC_map_push_elem   ||
14331 		     insn->imm == BPF_FUNC_map_pop_elem    ||
14332 		     insn->imm == BPF_FUNC_map_peek_elem   ||
14333 		     insn->imm == BPF_FUNC_redirect_map    ||
14334 		     insn->imm == BPF_FUNC_for_each_map_elem ||
14335 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14336 			aux = &env->insn_aux_data[i + delta];
14337 			if (bpf_map_ptr_poisoned(aux))
14338 				goto patch_call_imm;
14339 
14340 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14341 			ops = map_ptr->ops;
14342 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
14343 			    ops->map_gen_lookup) {
14344 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14345 				if (cnt == -EOPNOTSUPP)
14346 					goto patch_map_ops_generic;
14347 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14348 					verbose(env, "bpf verifier is misconfigured\n");
14349 					return -EINVAL;
14350 				}
14351 
14352 				new_prog = bpf_patch_insn_data(env, i + delta,
14353 							       insn_buf, cnt);
14354 				if (!new_prog)
14355 					return -ENOMEM;
14356 
14357 				delta    += cnt - 1;
14358 				env->prog = prog = new_prog;
14359 				insn      = new_prog->insnsi + i + delta;
14360 				continue;
14361 			}
14362 
14363 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14364 				     (void *(*)(struct bpf_map *map, void *key))NULL));
14365 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14366 				     (int (*)(struct bpf_map *map, void *key))NULL));
14367 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14368 				     (int (*)(struct bpf_map *map, void *key, void *value,
14369 					      u64 flags))NULL));
14370 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14371 				     (int (*)(struct bpf_map *map, void *value,
14372 					      u64 flags))NULL));
14373 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14374 				     (int (*)(struct bpf_map *map, void *value))NULL));
14375 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14376 				     (int (*)(struct bpf_map *map, void *value))NULL));
14377 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
14378 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14379 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14380 				     (int (*)(struct bpf_map *map,
14381 					      bpf_callback_t callback_fn,
14382 					      void *callback_ctx,
14383 					      u64 flags))NULL));
14384 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14385 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14386 
14387 patch_map_ops_generic:
14388 			switch (insn->imm) {
14389 			case BPF_FUNC_map_lookup_elem:
14390 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14391 				continue;
14392 			case BPF_FUNC_map_update_elem:
14393 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14394 				continue;
14395 			case BPF_FUNC_map_delete_elem:
14396 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14397 				continue;
14398 			case BPF_FUNC_map_push_elem:
14399 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14400 				continue;
14401 			case BPF_FUNC_map_pop_elem:
14402 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14403 				continue;
14404 			case BPF_FUNC_map_peek_elem:
14405 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14406 				continue;
14407 			case BPF_FUNC_redirect_map:
14408 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
14409 				continue;
14410 			case BPF_FUNC_for_each_map_elem:
14411 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14412 				continue;
14413 			case BPF_FUNC_map_lookup_percpu_elem:
14414 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14415 				continue;
14416 			}
14417 
14418 			goto patch_call_imm;
14419 		}
14420 
14421 		/* Implement bpf_jiffies64 inline. */
14422 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14423 		    insn->imm == BPF_FUNC_jiffies64) {
14424 			struct bpf_insn ld_jiffies_addr[2] = {
14425 				BPF_LD_IMM64(BPF_REG_0,
14426 					     (unsigned long)&jiffies),
14427 			};
14428 
14429 			insn_buf[0] = ld_jiffies_addr[0];
14430 			insn_buf[1] = ld_jiffies_addr[1];
14431 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14432 						  BPF_REG_0, 0);
14433 			cnt = 3;
14434 
14435 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14436 						       cnt);
14437 			if (!new_prog)
14438 				return -ENOMEM;
14439 
14440 			delta    += cnt - 1;
14441 			env->prog = prog = new_prog;
14442 			insn      = new_prog->insnsi + i + delta;
14443 			continue;
14444 		}
14445 
14446 		/* Implement bpf_get_func_arg inline. */
14447 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14448 		    insn->imm == BPF_FUNC_get_func_arg) {
14449 			/* Load nr_args from ctx - 8 */
14450 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14451 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14452 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14453 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14454 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14455 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14456 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14457 			insn_buf[7] = BPF_JMP_A(1);
14458 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14459 			cnt = 9;
14460 
14461 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14462 			if (!new_prog)
14463 				return -ENOMEM;
14464 
14465 			delta    += cnt - 1;
14466 			env->prog = prog = new_prog;
14467 			insn      = new_prog->insnsi + i + delta;
14468 			continue;
14469 		}
14470 
14471 		/* Implement bpf_get_func_ret inline. */
14472 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14473 		    insn->imm == BPF_FUNC_get_func_ret) {
14474 			if (eatype == BPF_TRACE_FEXIT ||
14475 			    eatype == BPF_MODIFY_RETURN) {
14476 				/* Load nr_args from ctx - 8 */
14477 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14478 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14479 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14480 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14481 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14482 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14483 				cnt = 6;
14484 			} else {
14485 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14486 				cnt = 1;
14487 			}
14488 
14489 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14490 			if (!new_prog)
14491 				return -ENOMEM;
14492 
14493 			delta    += cnt - 1;
14494 			env->prog = prog = new_prog;
14495 			insn      = new_prog->insnsi + i + delta;
14496 			continue;
14497 		}
14498 
14499 		/* Implement get_func_arg_cnt inline. */
14500 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14501 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
14502 			/* Load nr_args from ctx - 8 */
14503 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14504 
14505 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14506 			if (!new_prog)
14507 				return -ENOMEM;
14508 
14509 			env->prog = prog = new_prog;
14510 			insn      = new_prog->insnsi + i + delta;
14511 			continue;
14512 		}
14513 
14514 		/* Implement bpf_get_func_ip inline. */
14515 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14516 		    insn->imm == BPF_FUNC_get_func_ip) {
14517 			/* Load IP address from ctx - 16 */
14518 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14519 
14520 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14521 			if (!new_prog)
14522 				return -ENOMEM;
14523 
14524 			env->prog = prog = new_prog;
14525 			insn      = new_prog->insnsi + i + delta;
14526 			continue;
14527 		}
14528 
14529 patch_call_imm:
14530 		fn = env->ops->get_func_proto(insn->imm, env->prog);
14531 		/* all functions that have prototype and verifier allowed
14532 		 * programs to call them, must be real in-kernel functions
14533 		 */
14534 		if (!fn->func) {
14535 			verbose(env,
14536 				"kernel subsystem misconfigured func %s#%d\n",
14537 				func_id_name(insn->imm), insn->imm);
14538 			return -EFAULT;
14539 		}
14540 		insn->imm = fn->func - __bpf_call_base;
14541 	}
14542 
14543 	/* Since poke tab is now finalized, publish aux to tracker. */
14544 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
14545 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
14546 		if (!map_ptr->ops->map_poke_track ||
14547 		    !map_ptr->ops->map_poke_untrack ||
14548 		    !map_ptr->ops->map_poke_run) {
14549 			verbose(env, "bpf verifier is misconfigured\n");
14550 			return -EINVAL;
14551 		}
14552 
14553 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14554 		if (ret < 0) {
14555 			verbose(env, "tracking tail call prog failed\n");
14556 			return ret;
14557 		}
14558 	}
14559 
14560 	sort_kfunc_descs_by_imm(env->prog);
14561 
14562 	return 0;
14563 }
14564 
14565 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14566 					int position,
14567 					s32 stack_base,
14568 					u32 callback_subprogno,
14569 					u32 *cnt)
14570 {
14571 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14572 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14573 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14574 	int reg_loop_max = BPF_REG_6;
14575 	int reg_loop_cnt = BPF_REG_7;
14576 	int reg_loop_ctx = BPF_REG_8;
14577 
14578 	struct bpf_prog *new_prog;
14579 	u32 callback_start;
14580 	u32 call_insn_offset;
14581 	s32 callback_offset;
14582 
14583 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
14584 	 * be careful to modify this code in sync.
14585 	 */
14586 	struct bpf_insn insn_buf[] = {
14587 		/* Return error and jump to the end of the patch if
14588 		 * expected number of iterations is too big.
14589 		 */
14590 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14591 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14592 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14593 		/* spill R6, R7, R8 to use these as loop vars */
14594 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14595 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14596 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14597 		/* initialize loop vars */
14598 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14599 		BPF_MOV32_IMM(reg_loop_cnt, 0),
14600 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14601 		/* loop header,
14602 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
14603 		 */
14604 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14605 		/* callback call,
14606 		 * correct callback offset would be set after patching
14607 		 */
14608 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14609 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14610 		BPF_CALL_REL(0),
14611 		/* increment loop counter */
14612 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14613 		/* jump to loop header if callback returned 0 */
14614 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14615 		/* return value of bpf_loop,
14616 		 * set R0 to the number of iterations
14617 		 */
14618 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14619 		/* restore original values of R6, R7, R8 */
14620 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14621 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14622 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14623 	};
14624 
14625 	*cnt = ARRAY_SIZE(insn_buf);
14626 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14627 	if (!new_prog)
14628 		return new_prog;
14629 
14630 	/* callback start is known only after patching */
14631 	callback_start = env->subprog_info[callback_subprogno].start;
14632 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14633 	call_insn_offset = position + 12;
14634 	callback_offset = callback_start - call_insn_offset - 1;
14635 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
14636 
14637 	return new_prog;
14638 }
14639 
14640 static bool is_bpf_loop_call(struct bpf_insn *insn)
14641 {
14642 	return insn->code == (BPF_JMP | BPF_CALL) &&
14643 		insn->src_reg == 0 &&
14644 		insn->imm == BPF_FUNC_loop;
14645 }
14646 
14647 /* For all sub-programs in the program (including main) check
14648  * insn_aux_data to see if there are bpf_loop calls that require
14649  * inlining. If such calls are found the calls are replaced with a
14650  * sequence of instructions produced by `inline_bpf_loop` function and
14651  * subprog stack_depth is increased by the size of 3 registers.
14652  * This stack space is used to spill values of the R6, R7, R8.  These
14653  * registers are used to store the loop bound, counter and context
14654  * variables.
14655  */
14656 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14657 {
14658 	struct bpf_subprog_info *subprogs = env->subprog_info;
14659 	int i, cur_subprog = 0, cnt, delta = 0;
14660 	struct bpf_insn *insn = env->prog->insnsi;
14661 	int insn_cnt = env->prog->len;
14662 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
14663 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14664 	u16 stack_depth_extra = 0;
14665 
14666 	for (i = 0; i < insn_cnt; i++, insn++) {
14667 		struct bpf_loop_inline_state *inline_state =
14668 			&env->insn_aux_data[i + delta].loop_inline_state;
14669 
14670 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14671 			struct bpf_prog *new_prog;
14672 
14673 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14674 			new_prog = inline_bpf_loop(env,
14675 						   i + delta,
14676 						   -(stack_depth + stack_depth_extra),
14677 						   inline_state->callback_subprogno,
14678 						   &cnt);
14679 			if (!new_prog)
14680 				return -ENOMEM;
14681 
14682 			delta     += cnt - 1;
14683 			env->prog  = new_prog;
14684 			insn       = new_prog->insnsi + i + delta;
14685 		}
14686 
14687 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14688 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
14689 			cur_subprog++;
14690 			stack_depth = subprogs[cur_subprog].stack_depth;
14691 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14692 			stack_depth_extra = 0;
14693 		}
14694 	}
14695 
14696 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14697 
14698 	return 0;
14699 }
14700 
14701 static void free_states(struct bpf_verifier_env *env)
14702 {
14703 	struct bpf_verifier_state_list *sl, *sln;
14704 	int i;
14705 
14706 	sl = env->free_list;
14707 	while (sl) {
14708 		sln = sl->next;
14709 		free_verifier_state(&sl->state, false);
14710 		kfree(sl);
14711 		sl = sln;
14712 	}
14713 	env->free_list = NULL;
14714 
14715 	if (!env->explored_states)
14716 		return;
14717 
14718 	for (i = 0; i < state_htab_size(env); i++) {
14719 		sl = env->explored_states[i];
14720 
14721 		while (sl) {
14722 			sln = sl->next;
14723 			free_verifier_state(&sl->state, false);
14724 			kfree(sl);
14725 			sl = sln;
14726 		}
14727 		env->explored_states[i] = NULL;
14728 	}
14729 }
14730 
14731 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14732 {
14733 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14734 	struct bpf_verifier_state *state;
14735 	struct bpf_reg_state *regs;
14736 	int ret, i;
14737 
14738 	env->prev_linfo = NULL;
14739 	env->pass_cnt++;
14740 
14741 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14742 	if (!state)
14743 		return -ENOMEM;
14744 	state->curframe = 0;
14745 	state->speculative = false;
14746 	state->branches = 1;
14747 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14748 	if (!state->frame[0]) {
14749 		kfree(state);
14750 		return -ENOMEM;
14751 	}
14752 	env->cur_state = state;
14753 	init_func_state(env, state->frame[0],
14754 			BPF_MAIN_FUNC /* callsite */,
14755 			0 /* frameno */,
14756 			subprog);
14757 	state->first_insn_idx = env->subprog_info[subprog].start;
14758 	state->last_insn_idx = -1;
14759 
14760 	regs = state->frame[state->curframe]->regs;
14761 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14762 		ret = btf_prepare_func_args(env, subprog, regs);
14763 		if (ret)
14764 			goto out;
14765 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14766 			if (regs[i].type == PTR_TO_CTX)
14767 				mark_reg_known_zero(env, regs, i);
14768 			else if (regs[i].type == SCALAR_VALUE)
14769 				mark_reg_unknown(env, regs, i);
14770 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
14771 				const u32 mem_size = regs[i].mem_size;
14772 
14773 				mark_reg_known_zero(env, regs, i);
14774 				regs[i].mem_size = mem_size;
14775 				regs[i].id = ++env->id_gen;
14776 			}
14777 		}
14778 	} else {
14779 		/* 1st arg to a function */
14780 		regs[BPF_REG_1].type = PTR_TO_CTX;
14781 		mark_reg_known_zero(env, regs, BPF_REG_1);
14782 		ret = btf_check_subprog_arg_match(env, subprog, regs);
14783 		if (ret == -EFAULT)
14784 			/* unlikely verifier bug. abort.
14785 			 * ret == 0 and ret < 0 are sadly acceptable for
14786 			 * main() function due to backward compatibility.
14787 			 * Like socket filter program may be written as:
14788 			 * int bpf_prog(struct pt_regs *ctx)
14789 			 * and never dereference that ctx in the program.
14790 			 * 'struct pt_regs' is a type mismatch for socket
14791 			 * filter that should be using 'struct __sk_buff'.
14792 			 */
14793 			goto out;
14794 	}
14795 
14796 	ret = do_check(env);
14797 out:
14798 	/* check for NULL is necessary, since cur_state can be freed inside
14799 	 * do_check() under memory pressure.
14800 	 */
14801 	if (env->cur_state) {
14802 		free_verifier_state(env->cur_state, true);
14803 		env->cur_state = NULL;
14804 	}
14805 	while (!pop_stack(env, NULL, NULL, false));
14806 	if (!ret && pop_log)
14807 		bpf_vlog_reset(&env->log, 0);
14808 	free_states(env);
14809 	return ret;
14810 }
14811 
14812 /* Verify all global functions in a BPF program one by one based on their BTF.
14813  * All global functions must pass verification. Otherwise the whole program is rejected.
14814  * Consider:
14815  * int bar(int);
14816  * int foo(int f)
14817  * {
14818  *    return bar(f);
14819  * }
14820  * int bar(int b)
14821  * {
14822  *    ...
14823  * }
14824  * foo() will be verified first for R1=any_scalar_value. During verification it
14825  * will be assumed that bar() already verified successfully and call to bar()
14826  * from foo() will be checked for type match only. Later bar() will be verified
14827  * independently to check that it's safe for R1=any_scalar_value.
14828  */
14829 static int do_check_subprogs(struct bpf_verifier_env *env)
14830 {
14831 	struct bpf_prog_aux *aux = env->prog->aux;
14832 	int i, ret;
14833 
14834 	if (!aux->func_info)
14835 		return 0;
14836 
14837 	for (i = 1; i < env->subprog_cnt; i++) {
14838 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14839 			continue;
14840 		env->insn_idx = env->subprog_info[i].start;
14841 		WARN_ON_ONCE(env->insn_idx == 0);
14842 		ret = do_check_common(env, i);
14843 		if (ret) {
14844 			return ret;
14845 		} else if (env->log.level & BPF_LOG_LEVEL) {
14846 			verbose(env,
14847 				"Func#%d is safe for any args that match its prototype\n",
14848 				i);
14849 		}
14850 	}
14851 	return 0;
14852 }
14853 
14854 static int do_check_main(struct bpf_verifier_env *env)
14855 {
14856 	int ret;
14857 
14858 	env->insn_idx = 0;
14859 	ret = do_check_common(env, 0);
14860 	if (!ret)
14861 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14862 	return ret;
14863 }
14864 
14865 
14866 static void print_verification_stats(struct bpf_verifier_env *env)
14867 {
14868 	int i;
14869 
14870 	if (env->log.level & BPF_LOG_STATS) {
14871 		verbose(env, "verification time %lld usec\n",
14872 			div_u64(env->verification_time, 1000));
14873 		verbose(env, "stack depth ");
14874 		for (i = 0; i < env->subprog_cnt; i++) {
14875 			u32 depth = env->subprog_info[i].stack_depth;
14876 
14877 			verbose(env, "%d", depth);
14878 			if (i + 1 < env->subprog_cnt)
14879 				verbose(env, "+");
14880 		}
14881 		verbose(env, "\n");
14882 	}
14883 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14884 		"total_states %d peak_states %d mark_read %d\n",
14885 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14886 		env->max_states_per_insn, env->total_states,
14887 		env->peak_states, env->longest_mark_read_walk);
14888 }
14889 
14890 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14891 {
14892 	const struct btf_type *t, *func_proto;
14893 	const struct bpf_struct_ops *st_ops;
14894 	const struct btf_member *member;
14895 	struct bpf_prog *prog = env->prog;
14896 	u32 btf_id, member_idx;
14897 	const char *mname;
14898 
14899 	if (!prog->gpl_compatible) {
14900 		verbose(env, "struct ops programs must have a GPL compatible license\n");
14901 		return -EINVAL;
14902 	}
14903 
14904 	btf_id = prog->aux->attach_btf_id;
14905 	st_ops = bpf_struct_ops_find(btf_id);
14906 	if (!st_ops) {
14907 		verbose(env, "attach_btf_id %u is not a supported struct\n",
14908 			btf_id);
14909 		return -ENOTSUPP;
14910 	}
14911 
14912 	t = st_ops->type;
14913 	member_idx = prog->expected_attach_type;
14914 	if (member_idx >= btf_type_vlen(t)) {
14915 		verbose(env, "attach to invalid member idx %u of struct %s\n",
14916 			member_idx, st_ops->name);
14917 		return -EINVAL;
14918 	}
14919 
14920 	member = &btf_type_member(t)[member_idx];
14921 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14922 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14923 					       NULL);
14924 	if (!func_proto) {
14925 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14926 			mname, member_idx, st_ops->name);
14927 		return -EINVAL;
14928 	}
14929 
14930 	if (st_ops->check_member) {
14931 		int err = st_ops->check_member(t, member);
14932 
14933 		if (err) {
14934 			verbose(env, "attach to unsupported member %s of struct %s\n",
14935 				mname, st_ops->name);
14936 			return err;
14937 		}
14938 	}
14939 
14940 	prog->aux->attach_func_proto = func_proto;
14941 	prog->aux->attach_func_name = mname;
14942 	env->ops = st_ops->verifier_ops;
14943 
14944 	return 0;
14945 }
14946 #define SECURITY_PREFIX "security_"
14947 
14948 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14949 {
14950 	if (within_error_injection_list(addr) ||
14951 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14952 		return 0;
14953 
14954 	return -EINVAL;
14955 }
14956 
14957 /* list of non-sleepable functions that are otherwise on
14958  * ALLOW_ERROR_INJECTION list
14959  */
14960 BTF_SET_START(btf_non_sleepable_error_inject)
14961 /* Three functions below can be called from sleepable and non-sleepable context.
14962  * Assume non-sleepable from bpf safety point of view.
14963  */
14964 BTF_ID(func, __filemap_add_folio)
14965 BTF_ID(func, should_fail_alloc_page)
14966 BTF_ID(func, should_failslab)
14967 BTF_SET_END(btf_non_sleepable_error_inject)
14968 
14969 static int check_non_sleepable_error_inject(u32 btf_id)
14970 {
14971 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14972 }
14973 
14974 int bpf_check_attach_target(struct bpf_verifier_log *log,
14975 			    const struct bpf_prog *prog,
14976 			    const struct bpf_prog *tgt_prog,
14977 			    u32 btf_id,
14978 			    struct bpf_attach_target_info *tgt_info)
14979 {
14980 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14981 	const char prefix[] = "btf_trace_";
14982 	int ret = 0, subprog = -1, i;
14983 	const struct btf_type *t;
14984 	bool conservative = true;
14985 	const char *tname;
14986 	struct btf *btf;
14987 	long addr = 0;
14988 
14989 	if (!btf_id) {
14990 		bpf_log(log, "Tracing programs must provide btf_id\n");
14991 		return -EINVAL;
14992 	}
14993 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14994 	if (!btf) {
14995 		bpf_log(log,
14996 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14997 		return -EINVAL;
14998 	}
14999 	t = btf_type_by_id(btf, btf_id);
15000 	if (!t) {
15001 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
15002 		return -EINVAL;
15003 	}
15004 	tname = btf_name_by_offset(btf, t->name_off);
15005 	if (!tname) {
15006 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
15007 		return -EINVAL;
15008 	}
15009 	if (tgt_prog) {
15010 		struct bpf_prog_aux *aux = tgt_prog->aux;
15011 
15012 		for (i = 0; i < aux->func_info_cnt; i++)
15013 			if (aux->func_info[i].type_id == btf_id) {
15014 				subprog = i;
15015 				break;
15016 			}
15017 		if (subprog == -1) {
15018 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
15019 			return -EINVAL;
15020 		}
15021 		conservative = aux->func_info_aux[subprog].unreliable;
15022 		if (prog_extension) {
15023 			if (conservative) {
15024 				bpf_log(log,
15025 					"Cannot replace static functions\n");
15026 				return -EINVAL;
15027 			}
15028 			if (!prog->jit_requested) {
15029 				bpf_log(log,
15030 					"Extension programs should be JITed\n");
15031 				return -EINVAL;
15032 			}
15033 		}
15034 		if (!tgt_prog->jited) {
15035 			bpf_log(log, "Can attach to only JITed progs\n");
15036 			return -EINVAL;
15037 		}
15038 		if (tgt_prog->type == prog->type) {
15039 			/* Cannot fentry/fexit another fentry/fexit program.
15040 			 * Cannot attach program extension to another extension.
15041 			 * It's ok to attach fentry/fexit to extension program.
15042 			 */
15043 			bpf_log(log, "Cannot recursively attach\n");
15044 			return -EINVAL;
15045 		}
15046 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
15047 		    prog_extension &&
15048 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
15049 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
15050 			/* Program extensions can extend all program types
15051 			 * except fentry/fexit. The reason is the following.
15052 			 * The fentry/fexit programs are used for performance
15053 			 * analysis, stats and can be attached to any program
15054 			 * type except themselves. When extension program is
15055 			 * replacing XDP function it is necessary to allow
15056 			 * performance analysis of all functions. Both original
15057 			 * XDP program and its program extension. Hence
15058 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
15059 			 * allowed. If extending of fentry/fexit was allowed it
15060 			 * would be possible to create long call chain
15061 			 * fentry->extension->fentry->extension beyond
15062 			 * reasonable stack size. Hence extending fentry is not
15063 			 * allowed.
15064 			 */
15065 			bpf_log(log, "Cannot extend fentry/fexit\n");
15066 			return -EINVAL;
15067 		}
15068 	} else {
15069 		if (prog_extension) {
15070 			bpf_log(log, "Cannot replace kernel functions\n");
15071 			return -EINVAL;
15072 		}
15073 	}
15074 
15075 	switch (prog->expected_attach_type) {
15076 	case BPF_TRACE_RAW_TP:
15077 		if (tgt_prog) {
15078 			bpf_log(log,
15079 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15080 			return -EINVAL;
15081 		}
15082 		if (!btf_type_is_typedef(t)) {
15083 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
15084 				btf_id);
15085 			return -EINVAL;
15086 		}
15087 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15088 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15089 				btf_id, tname);
15090 			return -EINVAL;
15091 		}
15092 		tname += sizeof(prefix) - 1;
15093 		t = btf_type_by_id(btf, t->type);
15094 		if (!btf_type_is_ptr(t))
15095 			/* should never happen in valid vmlinux build */
15096 			return -EINVAL;
15097 		t = btf_type_by_id(btf, t->type);
15098 		if (!btf_type_is_func_proto(t))
15099 			/* should never happen in valid vmlinux build */
15100 			return -EINVAL;
15101 
15102 		break;
15103 	case BPF_TRACE_ITER:
15104 		if (!btf_type_is_func(t)) {
15105 			bpf_log(log, "attach_btf_id %u is not a function\n",
15106 				btf_id);
15107 			return -EINVAL;
15108 		}
15109 		t = btf_type_by_id(btf, t->type);
15110 		if (!btf_type_is_func_proto(t))
15111 			return -EINVAL;
15112 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15113 		if (ret)
15114 			return ret;
15115 		break;
15116 	default:
15117 		if (!prog_extension)
15118 			return -EINVAL;
15119 		fallthrough;
15120 	case BPF_MODIFY_RETURN:
15121 	case BPF_LSM_MAC:
15122 	case BPF_LSM_CGROUP:
15123 	case BPF_TRACE_FENTRY:
15124 	case BPF_TRACE_FEXIT:
15125 		if (!btf_type_is_func(t)) {
15126 			bpf_log(log, "attach_btf_id %u is not a function\n",
15127 				btf_id);
15128 			return -EINVAL;
15129 		}
15130 		if (prog_extension &&
15131 		    btf_check_type_match(log, prog, btf, t))
15132 			return -EINVAL;
15133 		t = btf_type_by_id(btf, t->type);
15134 		if (!btf_type_is_func_proto(t))
15135 			return -EINVAL;
15136 
15137 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15138 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15139 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15140 			return -EINVAL;
15141 
15142 		if (tgt_prog && conservative)
15143 			t = NULL;
15144 
15145 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15146 		if (ret < 0)
15147 			return ret;
15148 
15149 		if (tgt_prog) {
15150 			if (subprog == 0)
15151 				addr = (long) tgt_prog->bpf_func;
15152 			else
15153 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15154 		} else {
15155 			addr = kallsyms_lookup_name(tname);
15156 			if (!addr) {
15157 				bpf_log(log,
15158 					"The address of function %s cannot be found\n",
15159 					tname);
15160 				return -ENOENT;
15161 			}
15162 		}
15163 
15164 		if (prog->aux->sleepable) {
15165 			ret = -EINVAL;
15166 			switch (prog->type) {
15167 			case BPF_PROG_TYPE_TRACING:
15168 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
15169 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15170 				 */
15171 				if (!check_non_sleepable_error_inject(btf_id) &&
15172 				    within_error_injection_list(addr))
15173 					ret = 0;
15174 				break;
15175 			case BPF_PROG_TYPE_LSM:
15176 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
15177 				 * Only some of them are sleepable.
15178 				 */
15179 				if (bpf_lsm_is_sleepable_hook(btf_id))
15180 					ret = 0;
15181 				break;
15182 			default:
15183 				break;
15184 			}
15185 			if (ret) {
15186 				bpf_log(log, "%s is not sleepable\n", tname);
15187 				return ret;
15188 			}
15189 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15190 			if (tgt_prog) {
15191 				bpf_log(log, "can't modify return codes of BPF programs\n");
15192 				return -EINVAL;
15193 			}
15194 			ret = check_attach_modify_return(addr, tname);
15195 			if (ret) {
15196 				bpf_log(log, "%s() is not modifiable\n", tname);
15197 				return ret;
15198 			}
15199 		}
15200 
15201 		break;
15202 	}
15203 	tgt_info->tgt_addr = addr;
15204 	tgt_info->tgt_name = tname;
15205 	tgt_info->tgt_type = t;
15206 	return 0;
15207 }
15208 
15209 BTF_SET_START(btf_id_deny)
15210 BTF_ID_UNUSED
15211 #ifdef CONFIG_SMP
15212 BTF_ID(func, migrate_disable)
15213 BTF_ID(func, migrate_enable)
15214 #endif
15215 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15216 BTF_ID(func, rcu_read_unlock_strict)
15217 #endif
15218 BTF_SET_END(btf_id_deny)
15219 
15220 static int check_attach_btf_id(struct bpf_verifier_env *env)
15221 {
15222 	struct bpf_prog *prog = env->prog;
15223 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15224 	struct bpf_attach_target_info tgt_info = {};
15225 	u32 btf_id = prog->aux->attach_btf_id;
15226 	struct bpf_trampoline *tr;
15227 	int ret;
15228 	u64 key;
15229 
15230 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15231 		if (prog->aux->sleepable)
15232 			/* attach_btf_id checked to be zero already */
15233 			return 0;
15234 		verbose(env, "Syscall programs can only be sleepable\n");
15235 		return -EINVAL;
15236 	}
15237 
15238 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15239 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15240 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15241 		return -EINVAL;
15242 	}
15243 
15244 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15245 		return check_struct_ops_btf_id(env);
15246 
15247 	if (prog->type != BPF_PROG_TYPE_TRACING &&
15248 	    prog->type != BPF_PROG_TYPE_LSM &&
15249 	    prog->type != BPF_PROG_TYPE_EXT)
15250 		return 0;
15251 
15252 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15253 	if (ret)
15254 		return ret;
15255 
15256 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15257 		/* to make freplace equivalent to their targets, they need to
15258 		 * inherit env->ops and expected_attach_type for the rest of the
15259 		 * verification
15260 		 */
15261 		env->ops = bpf_verifier_ops[tgt_prog->type];
15262 		prog->expected_attach_type = tgt_prog->expected_attach_type;
15263 	}
15264 
15265 	/* store info about the attachment target that will be used later */
15266 	prog->aux->attach_func_proto = tgt_info.tgt_type;
15267 	prog->aux->attach_func_name = tgt_info.tgt_name;
15268 
15269 	if (tgt_prog) {
15270 		prog->aux->saved_dst_prog_type = tgt_prog->type;
15271 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15272 	}
15273 
15274 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15275 		prog->aux->attach_btf_trace = true;
15276 		return 0;
15277 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15278 		if (!bpf_iter_prog_supported(prog))
15279 			return -EINVAL;
15280 		return 0;
15281 	}
15282 
15283 	if (prog->type == BPF_PROG_TYPE_LSM) {
15284 		ret = bpf_lsm_verify_prog(&env->log, prog);
15285 		if (ret < 0)
15286 			return ret;
15287 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
15288 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
15289 		return -EINVAL;
15290 	}
15291 
15292 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15293 	tr = bpf_trampoline_get(key, &tgt_info);
15294 	if (!tr)
15295 		return -ENOMEM;
15296 
15297 	prog->aux->dst_trampoline = tr;
15298 	return 0;
15299 }
15300 
15301 struct btf *bpf_get_btf_vmlinux(void)
15302 {
15303 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15304 		mutex_lock(&bpf_verifier_lock);
15305 		if (!btf_vmlinux)
15306 			btf_vmlinux = btf_parse_vmlinux();
15307 		mutex_unlock(&bpf_verifier_lock);
15308 	}
15309 	return btf_vmlinux;
15310 }
15311 
15312 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15313 {
15314 	u64 start_time = ktime_get_ns();
15315 	struct bpf_verifier_env *env;
15316 	struct bpf_verifier_log *log;
15317 	int i, len, ret = -EINVAL;
15318 	bool is_priv;
15319 
15320 	/* no program is valid */
15321 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15322 		return -EINVAL;
15323 
15324 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
15325 	 * allocate/free it every time bpf_check() is called
15326 	 */
15327 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15328 	if (!env)
15329 		return -ENOMEM;
15330 	log = &env->log;
15331 
15332 	len = (*prog)->len;
15333 	env->insn_aux_data =
15334 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15335 	ret = -ENOMEM;
15336 	if (!env->insn_aux_data)
15337 		goto err_free_env;
15338 	for (i = 0; i < len; i++)
15339 		env->insn_aux_data[i].orig_idx = i;
15340 	env->prog = *prog;
15341 	env->ops = bpf_verifier_ops[env->prog->type];
15342 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15343 	is_priv = bpf_capable();
15344 
15345 	bpf_get_btf_vmlinux();
15346 
15347 	/* grab the mutex to protect few globals used by verifier */
15348 	if (!is_priv)
15349 		mutex_lock(&bpf_verifier_lock);
15350 
15351 	if (attr->log_level || attr->log_buf || attr->log_size) {
15352 		/* user requested verbose verifier output
15353 		 * and supplied buffer to store the verification trace
15354 		 */
15355 		log->level = attr->log_level;
15356 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15357 		log->len_total = attr->log_size;
15358 
15359 		/* log attributes have to be sane */
15360 		if (!bpf_verifier_log_attr_valid(log)) {
15361 			ret = -EINVAL;
15362 			goto err_unlock;
15363 		}
15364 	}
15365 
15366 	mark_verifier_state_clean(env);
15367 
15368 	if (IS_ERR(btf_vmlinux)) {
15369 		/* Either gcc or pahole or kernel are broken. */
15370 		verbose(env, "in-kernel BTF is malformed\n");
15371 		ret = PTR_ERR(btf_vmlinux);
15372 		goto skip_full_check;
15373 	}
15374 
15375 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15376 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15377 		env->strict_alignment = true;
15378 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15379 		env->strict_alignment = false;
15380 
15381 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15382 	env->allow_uninit_stack = bpf_allow_uninit_stack();
15383 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15384 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
15385 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
15386 	env->bpf_capable = bpf_capable();
15387 
15388 	if (is_priv)
15389 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15390 
15391 	env->explored_states = kvcalloc(state_htab_size(env),
15392 				       sizeof(struct bpf_verifier_state_list *),
15393 				       GFP_USER);
15394 	ret = -ENOMEM;
15395 	if (!env->explored_states)
15396 		goto skip_full_check;
15397 
15398 	ret = add_subprog_and_kfunc(env);
15399 	if (ret < 0)
15400 		goto skip_full_check;
15401 
15402 	ret = check_subprogs(env);
15403 	if (ret < 0)
15404 		goto skip_full_check;
15405 
15406 	ret = check_btf_info(env, attr, uattr);
15407 	if (ret < 0)
15408 		goto skip_full_check;
15409 
15410 	ret = check_attach_btf_id(env);
15411 	if (ret)
15412 		goto skip_full_check;
15413 
15414 	ret = resolve_pseudo_ldimm64(env);
15415 	if (ret < 0)
15416 		goto skip_full_check;
15417 
15418 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
15419 		ret = bpf_prog_offload_verifier_prep(env->prog);
15420 		if (ret)
15421 			goto skip_full_check;
15422 	}
15423 
15424 	ret = check_cfg(env);
15425 	if (ret < 0)
15426 		goto skip_full_check;
15427 
15428 	ret = do_check_subprogs(env);
15429 	ret = ret ?: do_check_main(env);
15430 
15431 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15432 		ret = bpf_prog_offload_finalize(env);
15433 
15434 skip_full_check:
15435 	kvfree(env->explored_states);
15436 
15437 	if (ret == 0)
15438 		ret = check_max_stack_depth(env);
15439 
15440 	/* instruction rewrites happen after this point */
15441 	if (ret == 0)
15442 		ret = optimize_bpf_loop(env);
15443 
15444 	if (is_priv) {
15445 		if (ret == 0)
15446 			opt_hard_wire_dead_code_branches(env);
15447 		if (ret == 0)
15448 			ret = opt_remove_dead_code(env);
15449 		if (ret == 0)
15450 			ret = opt_remove_nops(env);
15451 	} else {
15452 		if (ret == 0)
15453 			sanitize_dead_code(env);
15454 	}
15455 
15456 	if (ret == 0)
15457 		/* program is valid, convert *(u32*)(ctx + off) accesses */
15458 		ret = convert_ctx_accesses(env);
15459 
15460 	if (ret == 0)
15461 		ret = do_misc_fixups(env);
15462 
15463 	/* do 32-bit optimization after insn patching has done so those patched
15464 	 * insns could be handled correctly.
15465 	 */
15466 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15467 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15468 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15469 								     : false;
15470 	}
15471 
15472 	if (ret == 0)
15473 		ret = fixup_call_args(env);
15474 
15475 	env->verification_time = ktime_get_ns() - start_time;
15476 	print_verification_stats(env);
15477 	env->prog->aux->verified_insns = env->insn_processed;
15478 
15479 	if (log->level && bpf_verifier_log_full(log))
15480 		ret = -ENOSPC;
15481 	if (log->level && !log->ubuf) {
15482 		ret = -EFAULT;
15483 		goto err_release_maps;
15484 	}
15485 
15486 	if (ret)
15487 		goto err_release_maps;
15488 
15489 	if (env->used_map_cnt) {
15490 		/* if program passed verifier, update used_maps in bpf_prog_info */
15491 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15492 							  sizeof(env->used_maps[0]),
15493 							  GFP_KERNEL);
15494 
15495 		if (!env->prog->aux->used_maps) {
15496 			ret = -ENOMEM;
15497 			goto err_release_maps;
15498 		}
15499 
15500 		memcpy(env->prog->aux->used_maps, env->used_maps,
15501 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
15502 		env->prog->aux->used_map_cnt = env->used_map_cnt;
15503 	}
15504 	if (env->used_btf_cnt) {
15505 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
15506 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15507 							  sizeof(env->used_btfs[0]),
15508 							  GFP_KERNEL);
15509 		if (!env->prog->aux->used_btfs) {
15510 			ret = -ENOMEM;
15511 			goto err_release_maps;
15512 		}
15513 
15514 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
15515 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15516 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15517 	}
15518 	if (env->used_map_cnt || env->used_btf_cnt) {
15519 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
15520 		 * bpf_ld_imm64 instructions
15521 		 */
15522 		convert_pseudo_ld_imm64(env);
15523 	}
15524 
15525 	adjust_btf_func(env);
15526 
15527 err_release_maps:
15528 	if (!env->prog->aux->used_maps)
15529 		/* if we didn't copy map pointers into bpf_prog_info, release
15530 		 * them now. Otherwise free_used_maps() will release them.
15531 		 */
15532 		release_maps(env);
15533 	if (!env->prog->aux->used_btfs)
15534 		release_btfs(env);
15535 
15536 	/* extension progs temporarily inherit the attach_type of their targets
15537 	   for verification purposes, so set it back to zero before returning
15538 	 */
15539 	if (env->prog->type == BPF_PROG_TYPE_EXT)
15540 		env->prog->expected_attach_type = 0;
15541 
15542 	*prog = env->prog;
15543 err_unlock:
15544 	if (!is_priv)
15545 		mutex_unlock(&bpf_verifier_lock);
15546 	vfree(env->insn_aux_data);
15547 err_free_env:
15548 	kfree(env);
15549 	return ret;
15550 }
15551