xref: /linux-6.15/kernel/bpf/verifier.c (revision 9b810755)
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 struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
455 {
456 	struct btf_record *rec = NULL;
457 	struct btf_struct_meta *meta;
458 
459 	if (reg->type == PTR_TO_MAP_VALUE) {
460 		rec = reg->map_ptr->record;
461 	} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
462 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
463 		if (meta)
464 			rec = meta->record;
465 	}
466 	return rec;
467 }
468 
469 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
470 {
471 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
472 }
473 
474 static bool type_is_rdonly_mem(u32 type)
475 {
476 	return type & MEM_RDONLY;
477 }
478 
479 static bool type_may_be_null(u32 type)
480 {
481 	return type & PTR_MAYBE_NULL;
482 }
483 
484 static bool is_acquire_function(enum bpf_func_id func_id,
485 				const struct bpf_map *map)
486 {
487 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
488 
489 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
490 	    func_id == BPF_FUNC_sk_lookup_udp ||
491 	    func_id == BPF_FUNC_skc_lookup_tcp ||
492 	    func_id == BPF_FUNC_ringbuf_reserve ||
493 	    func_id == BPF_FUNC_kptr_xchg)
494 		return true;
495 
496 	if (func_id == BPF_FUNC_map_lookup_elem &&
497 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
498 	     map_type == BPF_MAP_TYPE_SOCKHASH))
499 		return true;
500 
501 	return false;
502 }
503 
504 static bool is_ptr_cast_function(enum bpf_func_id func_id)
505 {
506 	return func_id == BPF_FUNC_tcp_sock ||
507 		func_id == BPF_FUNC_sk_fullsock ||
508 		func_id == BPF_FUNC_skc_to_tcp_sock ||
509 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
510 		func_id == BPF_FUNC_skc_to_udp6_sock ||
511 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
512 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
513 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
514 }
515 
516 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
517 {
518 	return func_id == BPF_FUNC_dynptr_data;
519 }
520 
521 static bool is_callback_calling_function(enum bpf_func_id func_id)
522 {
523 	return func_id == BPF_FUNC_for_each_map_elem ||
524 	       func_id == BPF_FUNC_timer_set_callback ||
525 	       func_id == BPF_FUNC_find_vma ||
526 	       func_id == BPF_FUNC_loop ||
527 	       func_id == BPF_FUNC_user_ringbuf_drain;
528 }
529 
530 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
531 					const struct bpf_map *map)
532 {
533 	int ref_obj_uses = 0;
534 
535 	if (is_ptr_cast_function(func_id))
536 		ref_obj_uses++;
537 	if (is_acquire_function(func_id, map))
538 		ref_obj_uses++;
539 	if (is_dynptr_ref_function(func_id))
540 		ref_obj_uses++;
541 
542 	return ref_obj_uses > 1;
543 }
544 
545 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
546 {
547 	return BPF_CLASS(insn->code) == BPF_STX &&
548 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
549 	       insn->imm == BPF_CMPXCHG;
550 }
551 
552 /* string representation of 'enum bpf_reg_type'
553  *
554  * Note that reg_type_str() can not appear more than once in a single verbose()
555  * statement.
556  */
557 static const char *reg_type_str(struct bpf_verifier_env *env,
558 				enum bpf_reg_type type)
559 {
560 	char postfix[16] = {0}, prefix[64] = {0};
561 	static const char * const str[] = {
562 		[NOT_INIT]		= "?",
563 		[SCALAR_VALUE]		= "scalar",
564 		[PTR_TO_CTX]		= "ctx",
565 		[CONST_PTR_TO_MAP]	= "map_ptr",
566 		[PTR_TO_MAP_VALUE]	= "map_value",
567 		[PTR_TO_STACK]		= "fp",
568 		[PTR_TO_PACKET]		= "pkt",
569 		[PTR_TO_PACKET_META]	= "pkt_meta",
570 		[PTR_TO_PACKET_END]	= "pkt_end",
571 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
572 		[PTR_TO_SOCKET]		= "sock",
573 		[PTR_TO_SOCK_COMMON]	= "sock_common",
574 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
575 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
576 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
577 		[PTR_TO_BTF_ID]		= "ptr_",
578 		[PTR_TO_MEM]		= "mem",
579 		[PTR_TO_BUF]		= "buf",
580 		[PTR_TO_FUNC]		= "func",
581 		[PTR_TO_MAP_KEY]	= "map_key",
582 		[PTR_TO_DYNPTR]		= "dynptr_ptr",
583 	};
584 
585 	if (type & PTR_MAYBE_NULL) {
586 		if (base_type(type) == PTR_TO_BTF_ID)
587 			strncpy(postfix, "or_null_", 16);
588 		else
589 			strncpy(postfix, "_or_null", 16);
590 	}
591 
592 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s",
593 		 type & MEM_RDONLY ? "rdonly_" : "",
594 		 type & MEM_RINGBUF ? "ringbuf_" : "",
595 		 type & MEM_USER ? "user_" : "",
596 		 type & MEM_PERCPU ? "percpu_" : "",
597 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
598 		 type & PTR_TRUSTED ? "trusted_" : ""
599 	);
600 
601 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
602 		 prefix, str[base_type(type)], postfix);
603 	return env->type_str_buf;
604 }
605 
606 static char slot_type_char[] = {
607 	[STACK_INVALID]	= '?',
608 	[STACK_SPILL]	= 'r',
609 	[STACK_MISC]	= 'm',
610 	[STACK_ZERO]	= '0',
611 	[STACK_DYNPTR]	= 'd',
612 };
613 
614 static void print_liveness(struct bpf_verifier_env *env,
615 			   enum bpf_reg_liveness live)
616 {
617 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
618 	    verbose(env, "_");
619 	if (live & REG_LIVE_READ)
620 		verbose(env, "r");
621 	if (live & REG_LIVE_WRITTEN)
622 		verbose(env, "w");
623 	if (live & REG_LIVE_DONE)
624 		verbose(env, "D");
625 }
626 
627 static int get_spi(s32 off)
628 {
629 	return (-off - 1) / BPF_REG_SIZE;
630 }
631 
632 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
633 {
634 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
635 
636 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
637 	 * within [0, allocated_stack).
638 	 *
639 	 * Please note that the spi grows downwards. For example, a dynptr
640 	 * takes the size of two stack slots; the first slot will be at
641 	 * spi and the second slot will be at spi - 1.
642 	 */
643 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
644 }
645 
646 static struct bpf_func_state *func(struct bpf_verifier_env *env,
647 				   const struct bpf_reg_state *reg)
648 {
649 	struct bpf_verifier_state *cur = env->cur_state;
650 
651 	return cur->frame[reg->frameno];
652 }
653 
654 static const char *kernel_type_name(const struct btf* btf, u32 id)
655 {
656 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
657 }
658 
659 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
660 {
661 	env->scratched_regs |= 1U << regno;
662 }
663 
664 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
665 {
666 	env->scratched_stack_slots |= 1ULL << spi;
667 }
668 
669 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
670 {
671 	return (env->scratched_regs >> regno) & 1;
672 }
673 
674 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
675 {
676 	return (env->scratched_stack_slots >> regno) & 1;
677 }
678 
679 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
680 {
681 	return env->scratched_regs || env->scratched_stack_slots;
682 }
683 
684 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
685 {
686 	env->scratched_regs = 0U;
687 	env->scratched_stack_slots = 0ULL;
688 }
689 
690 /* Used for printing the entire verifier state. */
691 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
692 {
693 	env->scratched_regs = ~0U;
694 	env->scratched_stack_slots = ~0ULL;
695 }
696 
697 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
698 {
699 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
700 	case DYNPTR_TYPE_LOCAL:
701 		return BPF_DYNPTR_TYPE_LOCAL;
702 	case DYNPTR_TYPE_RINGBUF:
703 		return BPF_DYNPTR_TYPE_RINGBUF;
704 	default:
705 		return BPF_DYNPTR_TYPE_INVALID;
706 	}
707 }
708 
709 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
710 {
711 	return type == BPF_DYNPTR_TYPE_RINGBUF;
712 }
713 
714 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
715 				   enum bpf_arg_type arg_type, int insn_idx)
716 {
717 	struct bpf_func_state *state = func(env, reg);
718 	enum bpf_dynptr_type type;
719 	int spi, i, id;
720 
721 	spi = get_spi(reg->off);
722 
723 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
724 		return -EINVAL;
725 
726 	for (i = 0; i < BPF_REG_SIZE; i++) {
727 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
728 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
729 	}
730 
731 	type = arg_to_dynptr_type(arg_type);
732 	if (type == BPF_DYNPTR_TYPE_INVALID)
733 		return -EINVAL;
734 
735 	state->stack[spi].spilled_ptr.dynptr.first_slot = true;
736 	state->stack[spi].spilled_ptr.dynptr.type = type;
737 	state->stack[spi - 1].spilled_ptr.dynptr.type = type;
738 
739 	if (dynptr_type_refcounted(type)) {
740 		/* The id is used to track proper releasing */
741 		id = acquire_reference_state(env, insn_idx);
742 		if (id < 0)
743 			return id;
744 
745 		state->stack[spi].spilled_ptr.id = id;
746 		state->stack[spi - 1].spilled_ptr.id = id;
747 	}
748 
749 	return 0;
750 }
751 
752 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
753 {
754 	struct bpf_func_state *state = func(env, reg);
755 	int spi, i;
756 
757 	spi = get_spi(reg->off);
758 
759 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760 		return -EINVAL;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_INVALID;
764 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
765 	}
766 
767 	/* Invalidate any slices associated with this dynptr */
768 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
769 		release_reference(env, state->stack[spi].spilled_ptr.id);
770 		state->stack[spi].spilled_ptr.id = 0;
771 		state->stack[spi - 1].spilled_ptr.id = 0;
772 	}
773 
774 	state->stack[spi].spilled_ptr.dynptr.first_slot = false;
775 	state->stack[spi].spilled_ptr.dynptr.type = 0;
776 	state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
777 
778 	return 0;
779 }
780 
781 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
782 {
783 	struct bpf_func_state *state = func(env, reg);
784 	int spi = get_spi(reg->off);
785 	int i;
786 
787 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
788 		return true;
789 
790 	for (i = 0; i < BPF_REG_SIZE; i++) {
791 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
792 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
793 			return false;
794 	}
795 
796 	return true;
797 }
798 
799 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
800 			      struct bpf_reg_state *reg)
801 {
802 	struct bpf_func_state *state = func(env, reg);
803 	int spi = get_spi(reg->off);
804 	int i;
805 
806 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
807 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
808 		return false;
809 
810 	for (i = 0; i < BPF_REG_SIZE; i++) {
811 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
812 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
813 			return false;
814 	}
815 
816 	return true;
817 }
818 
819 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
820 			     struct bpf_reg_state *reg,
821 			     enum bpf_arg_type arg_type)
822 {
823 	struct bpf_func_state *state = func(env, reg);
824 	enum bpf_dynptr_type dynptr_type;
825 	int spi = get_spi(reg->off);
826 
827 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
828 	if (arg_type == ARG_PTR_TO_DYNPTR)
829 		return true;
830 
831 	dynptr_type = arg_to_dynptr_type(arg_type);
832 
833 	return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
834 }
835 
836 /* The reg state of a pointer or a bounded scalar was saved when
837  * it was spilled to the stack.
838  */
839 static bool is_spilled_reg(const struct bpf_stack_state *stack)
840 {
841 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
842 }
843 
844 static void scrub_spilled_slot(u8 *stype)
845 {
846 	if (*stype != STACK_INVALID)
847 		*stype = STACK_MISC;
848 }
849 
850 static void print_verifier_state(struct bpf_verifier_env *env,
851 				 const struct bpf_func_state *state,
852 				 bool print_all)
853 {
854 	const struct bpf_reg_state *reg;
855 	enum bpf_reg_type t;
856 	int i;
857 
858 	if (state->frameno)
859 		verbose(env, " frame%d:", state->frameno);
860 	for (i = 0; i < MAX_BPF_REG; i++) {
861 		reg = &state->regs[i];
862 		t = reg->type;
863 		if (t == NOT_INIT)
864 			continue;
865 		if (!print_all && !reg_scratched(env, i))
866 			continue;
867 		verbose(env, " R%d", i);
868 		print_liveness(env, reg->live);
869 		verbose(env, "=");
870 		if (t == SCALAR_VALUE && reg->precise)
871 			verbose(env, "P");
872 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
873 		    tnum_is_const(reg->var_off)) {
874 			/* reg->off should be 0 for SCALAR_VALUE */
875 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
876 			verbose(env, "%lld", reg->var_off.value + reg->off);
877 		} else {
878 			const char *sep = "";
879 
880 			verbose(env, "%s", reg_type_str(env, t));
881 			if (base_type(t) == PTR_TO_BTF_ID)
882 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
883 			verbose(env, "(");
884 /*
885  * _a stands for append, was shortened to avoid multiline statements below.
886  * This macro is used to output a comma separated list of attributes.
887  */
888 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
889 
890 			if (reg->id)
891 				verbose_a("id=%d", reg->id);
892 			if (reg->ref_obj_id)
893 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
894 			if (t != SCALAR_VALUE)
895 				verbose_a("off=%d", reg->off);
896 			if (type_is_pkt_pointer(t))
897 				verbose_a("r=%d", reg->range);
898 			else if (base_type(t) == CONST_PTR_TO_MAP ||
899 				 base_type(t) == PTR_TO_MAP_KEY ||
900 				 base_type(t) == PTR_TO_MAP_VALUE)
901 				verbose_a("ks=%d,vs=%d",
902 					  reg->map_ptr->key_size,
903 					  reg->map_ptr->value_size);
904 			if (tnum_is_const(reg->var_off)) {
905 				/* Typically an immediate SCALAR_VALUE, but
906 				 * could be a pointer whose offset is too big
907 				 * for reg->off
908 				 */
909 				verbose_a("imm=%llx", reg->var_off.value);
910 			} else {
911 				if (reg->smin_value != reg->umin_value &&
912 				    reg->smin_value != S64_MIN)
913 					verbose_a("smin=%lld", (long long)reg->smin_value);
914 				if (reg->smax_value != reg->umax_value &&
915 				    reg->smax_value != S64_MAX)
916 					verbose_a("smax=%lld", (long long)reg->smax_value);
917 				if (reg->umin_value != 0)
918 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
919 				if (reg->umax_value != U64_MAX)
920 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
921 				if (!tnum_is_unknown(reg->var_off)) {
922 					char tn_buf[48];
923 
924 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
925 					verbose_a("var_off=%s", tn_buf);
926 				}
927 				if (reg->s32_min_value != reg->smin_value &&
928 				    reg->s32_min_value != S32_MIN)
929 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
930 				if (reg->s32_max_value != reg->smax_value &&
931 				    reg->s32_max_value != S32_MAX)
932 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
933 				if (reg->u32_min_value != reg->umin_value &&
934 				    reg->u32_min_value != U32_MIN)
935 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
936 				if (reg->u32_max_value != reg->umax_value &&
937 				    reg->u32_max_value != U32_MAX)
938 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
939 			}
940 #undef verbose_a
941 
942 			verbose(env, ")");
943 		}
944 	}
945 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
946 		char types_buf[BPF_REG_SIZE + 1];
947 		bool valid = false;
948 		int j;
949 
950 		for (j = 0; j < BPF_REG_SIZE; j++) {
951 			if (state->stack[i].slot_type[j] != STACK_INVALID)
952 				valid = true;
953 			types_buf[j] = slot_type_char[
954 					state->stack[i].slot_type[j]];
955 		}
956 		types_buf[BPF_REG_SIZE] = 0;
957 		if (!valid)
958 			continue;
959 		if (!print_all && !stack_slot_scratched(env, i))
960 			continue;
961 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
962 		print_liveness(env, state->stack[i].spilled_ptr.live);
963 		if (is_spilled_reg(&state->stack[i])) {
964 			reg = &state->stack[i].spilled_ptr;
965 			t = reg->type;
966 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
967 			if (t == SCALAR_VALUE && reg->precise)
968 				verbose(env, "P");
969 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
970 				verbose(env, "%lld", reg->var_off.value + reg->off);
971 		} else {
972 			verbose(env, "=%s", types_buf);
973 		}
974 	}
975 	if (state->acquired_refs && state->refs[0].id) {
976 		verbose(env, " refs=%d", state->refs[0].id);
977 		for (i = 1; i < state->acquired_refs; i++)
978 			if (state->refs[i].id)
979 				verbose(env, ",%d", state->refs[i].id);
980 	}
981 	if (state->in_callback_fn)
982 		verbose(env, " cb");
983 	if (state->in_async_callback_fn)
984 		verbose(env, " async_cb");
985 	verbose(env, "\n");
986 	mark_verifier_state_clean(env);
987 }
988 
989 static inline u32 vlog_alignment(u32 pos)
990 {
991 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
992 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
993 }
994 
995 static void print_insn_state(struct bpf_verifier_env *env,
996 			     const struct bpf_func_state *state)
997 {
998 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
999 		/* remove new line character */
1000 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1001 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1002 	} else {
1003 		verbose(env, "%d:", env->insn_idx);
1004 	}
1005 	print_verifier_state(env, state, false);
1006 }
1007 
1008 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1009  * small to hold src. This is different from krealloc since we don't want to preserve
1010  * the contents of dst.
1011  *
1012  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1013  * not be allocated.
1014  */
1015 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1016 {
1017 	size_t bytes;
1018 
1019 	if (ZERO_OR_NULL_PTR(src))
1020 		goto out;
1021 
1022 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1023 		return NULL;
1024 
1025 	if (ksize(dst) < bytes) {
1026 		kfree(dst);
1027 		dst = kmalloc_track_caller(bytes, flags);
1028 		if (!dst)
1029 			return NULL;
1030 	}
1031 
1032 	memcpy(dst, src, bytes);
1033 out:
1034 	return dst ? dst : ZERO_SIZE_PTR;
1035 }
1036 
1037 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1038  * small to hold new_n items. new items are zeroed out if the array grows.
1039  *
1040  * Contrary to krealloc_array, does not free arr if new_n is zero.
1041  */
1042 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1043 {
1044 	void *new_arr;
1045 
1046 	if (!new_n || old_n == new_n)
1047 		goto out;
1048 
1049 	new_arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1050 	if (!new_arr) {
1051 		kfree(arr);
1052 		return NULL;
1053 	}
1054 	arr = new_arr;
1055 
1056 	if (new_n > old_n)
1057 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1058 
1059 out:
1060 	return arr ? arr : ZERO_SIZE_PTR;
1061 }
1062 
1063 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1064 {
1065 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1066 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1067 	if (!dst->refs)
1068 		return -ENOMEM;
1069 
1070 	dst->acquired_refs = src->acquired_refs;
1071 	return 0;
1072 }
1073 
1074 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1075 {
1076 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1077 
1078 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1079 				GFP_KERNEL);
1080 	if (!dst->stack)
1081 		return -ENOMEM;
1082 
1083 	dst->allocated_stack = src->allocated_stack;
1084 	return 0;
1085 }
1086 
1087 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1088 {
1089 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1090 				    sizeof(struct bpf_reference_state));
1091 	if (!state->refs)
1092 		return -ENOMEM;
1093 
1094 	state->acquired_refs = n;
1095 	return 0;
1096 }
1097 
1098 static int grow_stack_state(struct bpf_func_state *state, int size)
1099 {
1100 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1101 
1102 	if (old_n >= n)
1103 		return 0;
1104 
1105 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1106 	if (!state->stack)
1107 		return -ENOMEM;
1108 
1109 	state->allocated_stack = size;
1110 	return 0;
1111 }
1112 
1113 /* Acquire a pointer id from the env and update the state->refs to include
1114  * this new pointer reference.
1115  * On success, returns a valid pointer id to associate with the register
1116  * On failure, returns a negative errno.
1117  */
1118 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1119 {
1120 	struct bpf_func_state *state = cur_func(env);
1121 	int new_ofs = state->acquired_refs;
1122 	int id, err;
1123 
1124 	err = resize_reference_state(state, state->acquired_refs + 1);
1125 	if (err)
1126 		return err;
1127 	id = ++env->id_gen;
1128 	state->refs[new_ofs].id = id;
1129 	state->refs[new_ofs].insn_idx = insn_idx;
1130 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1131 
1132 	return id;
1133 }
1134 
1135 /* release function corresponding to acquire_reference_state(). Idempotent. */
1136 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1137 {
1138 	int i, last_idx;
1139 
1140 	last_idx = state->acquired_refs - 1;
1141 	for (i = 0; i < state->acquired_refs; i++) {
1142 		if (state->refs[i].id == ptr_id) {
1143 			/* Cannot release caller references in callbacks */
1144 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1145 				return -EINVAL;
1146 			if (last_idx && i != last_idx)
1147 				memcpy(&state->refs[i], &state->refs[last_idx],
1148 				       sizeof(*state->refs));
1149 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1150 			state->acquired_refs--;
1151 			return 0;
1152 		}
1153 	}
1154 	return -EINVAL;
1155 }
1156 
1157 static void free_func_state(struct bpf_func_state *state)
1158 {
1159 	if (!state)
1160 		return;
1161 	kfree(state->refs);
1162 	kfree(state->stack);
1163 	kfree(state);
1164 }
1165 
1166 static void clear_jmp_history(struct bpf_verifier_state *state)
1167 {
1168 	kfree(state->jmp_history);
1169 	state->jmp_history = NULL;
1170 	state->jmp_history_cnt = 0;
1171 }
1172 
1173 static void free_verifier_state(struct bpf_verifier_state *state,
1174 				bool free_self)
1175 {
1176 	int i;
1177 
1178 	for (i = 0; i <= state->curframe; i++) {
1179 		free_func_state(state->frame[i]);
1180 		state->frame[i] = NULL;
1181 	}
1182 	clear_jmp_history(state);
1183 	if (free_self)
1184 		kfree(state);
1185 }
1186 
1187 /* copy verifier state from src to dst growing dst stack space
1188  * when necessary to accommodate larger src stack
1189  */
1190 static int copy_func_state(struct bpf_func_state *dst,
1191 			   const struct bpf_func_state *src)
1192 {
1193 	int err;
1194 
1195 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1196 	err = copy_reference_state(dst, src);
1197 	if (err)
1198 		return err;
1199 	return copy_stack_state(dst, src);
1200 }
1201 
1202 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1203 			       const struct bpf_verifier_state *src)
1204 {
1205 	struct bpf_func_state *dst;
1206 	int i, err;
1207 
1208 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1209 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1210 					    GFP_USER);
1211 	if (!dst_state->jmp_history)
1212 		return -ENOMEM;
1213 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1214 
1215 	/* if dst has more stack frames then src frame, free them */
1216 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1217 		free_func_state(dst_state->frame[i]);
1218 		dst_state->frame[i] = NULL;
1219 	}
1220 	dst_state->speculative = src->speculative;
1221 	dst_state->curframe = src->curframe;
1222 	dst_state->active_lock.ptr = src->active_lock.ptr;
1223 	dst_state->active_lock.id = src->active_lock.id;
1224 	dst_state->branches = src->branches;
1225 	dst_state->parent = src->parent;
1226 	dst_state->first_insn_idx = src->first_insn_idx;
1227 	dst_state->last_insn_idx = src->last_insn_idx;
1228 	for (i = 0; i <= src->curframe; i++) {
1229 		dst = dst_state->frame[i];
1230 		if (!dst) {
1231 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1232 			if (!dst)
1233 				return -ENOMEM;
1234 			dst_state->frame[i] = dst;
1235 		}
1236 		err = copy_func_state(dst, src->frame[i]);
1237 		if (err)
1238 			return err;
1239 	}
1240 	return 0;
1241 }
1242 
1243 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1244 {
1245 	while (st) {
1246 		u32 br = --st->branches;
1247 
1248 		/* WARN_ON(br > 1) technically makes sense here,
1249 		 * but see comment in push_stack(), hence:
1250 		 */
1251 		WARN_ONCE((int)br < 0,
1252 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1253 			  br);
1254 		if (br)
1255 			break;
1256 		st = st->parent;
1257 	}
1258 }
1259 
1260 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1261 		     int *insn_idx, bool pop_log)
1262 {
1263 	struct bpf_verifier_state *cur = env->cur_state;
1264 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1265 	int err;
1266 
1267 	if (env->head == NULL)
1268 		return -ENOENT;
1269 
1270 	if (cur) {
1271 		err = copy_verifier_state(cur, &head->st);
1272 		if (err)
1273 			return err;
1274 	}
1275 	if (pop_log)
1276 		bpf_vlog_reset(&env->log, head->log_pos);
1277 	if (insn_idx)
1278 		*insn_idx = head->insn_idx;
1279 	if (prev_insn_idx)
1280 		*prev_insn_idx = head->prev_insn_idx;
1281 	elem = head->next;
1282 	free_verifier_state(&head->st, false);
1283 	kfree(head);
1284 	env->head = elem;
1285 	env->stack_size--;
1286 	return 0;
1287 }
1288 
1289 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1290 					     int insn_idx, int prev_insn_idx,
1291 					     bool speculative)
1292 {
1293 	struct bpf_verifier_state *cur = env->cur_state;
1294 	struct bpf_verifier_stack_elem *elem;
1295 	int err;
1296 
1297 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1298 	if (!elem)
1299 		goto err;
1300 
1301 	elem->insn_idx = insn_idx;
1302 	elem->prev_insn_idx = prev_insn_idx;
1303 	elem->next = env->head;
1304 	elem->log_pos = env->log.len_used;
1305 	env->head = elem;
1306 	env->stack_size++;
1307 	err = copy_verifier_state(&elem->st, cur);
1308 	if (err)
1309 		goto err;
1310 	elem->st.speculative |= speculative;
1311 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1312 		verbose(env, "The sequence of %d jumps is too complex.\n",
1313 			env->stack_size);
1314 		goto err;
1315 	}
1316 	if (elem->st.parent) {
1317 		++elem->st.parent->branches;
1318 		/* WARN_ON(branches > 2) technically makes sense here,
1319 		 * but
1320 		 * 1. speculative states will bump 'branches' for non-branch
1321 		 * instructions
1322 		 * 2. is_state_visited() heuristics may decide not to create
1323 		 * a new state for a sequence of branches and all such current
1324 		 * and cloned states will be pointing to a single parent state
1325 		 * which might have large 'branches' count.
1326 		 */
1327 	}
1328 	return &elem->st;
1329 err:
1330 	free_verifier_state(env->cur_state, true);
1331 	env->cur_state = NULL;
1332 	/* pop all elements and return */
1333 	while (!pop_stack(env, NULL, NULL, false));
1334 	return NULL;
1335 }
1336 
1337 #define CALLER_SAVED_REGS 6
1338 static const int caller_saved[CALLER_SAVED_REGS] = {
1339 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1340 };
1341 
1342 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1343 				struct bpf_reg_state *reg);
1344 
1345 /* This helper doesn't clear reg->id */
1346 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1347 {
1348 	reg->var_off = tnum_const(imm);
1349 	reg->smin_value = (s64)imm;
1350 	reg->smax_value = (s64)imm;
1351 	reg->umin_value = imm;
1352 	reg->umax_value = imm;
1353 
1354 	reg->s32_min_value = (s32)imm;
1355 	reg->s32_max_value = (s32)imm;
1356 	reg->u32_min_value = (u32)imm;
1357 	reg->u32_max_value = (u32)imm;
1358 }
1359 
1360 /* Mark the unknown part of a register (variable offset or scalar value) as
1361  * known to have the value @imm.
1362  */
1363 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1364 {
1365 	/* Clear id, off, and union(map_ptr, range) */
1366 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1367 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1368 	___mark_reg_known(reg, imm);
1369 }
1370 
1371 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1372 {
1373 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1374 	reg->s32_min_value = (s32)imm;
1375 	reg->s32_max_value = (s32)imm;
1376 	reg->u32_min_value = (u32)imm;
1377 	reg->u32_max_value = (u32)imm;
1378 }
1379 
1380 /* Mark the 'variable offset' part of a register as zero.  This should be
1381  * used only on registers holding a pointer type.
1382  */
1383 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1384 {
1385 	__mark_reg_known(reg, 0);
1386 }
1387 
1388 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1389 {
1390 	__mark_reg_known(reg, 0);
1391 	reg->type = SCALAR_VALUE;
1392 }
1393 
1394 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1395 				struct bpf_reg_state *regs, u32 regno)
1396 {
1397 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1398 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1399 		/* Something bad happened, let's kill all regs */
1400 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1401 			__mark_reg_not_init(env, regs + regno);
1402 		return;
1403 	}
1404 	__mark_reg_known_zero(regs + regno);
1405 }
1406 
1407 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1408 {
1409 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1410 		const struct bpf_map *map = reg->map_ptr;
1411 
1412 		if (map->inner_map_meta) {
1413 			reg->type = CONST_PTR_TO_MAP;
1414 			reg->map_ptr = map->inner_map_meta;
1415 			/* transfer reg's id which is unique for every map_lookup_elem
1416 			 * as UID of the inner map.
1417 			 */
1418 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1419 				reg->map_uid = reg->id;
1420 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1421 			reg->type = PTR_TO_XDP_SOCK;
1422 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1423 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1424 			reg->type = PTR_TO_SOCKET;
1425 		} else {
1426 			reg->type = PTR_TO_MAP_VALUE;
1427 		}
1428 		return;
1429 	}
1430 
1431 	reg->type &= ~PTR_MAYBE_NULL;
1432 }
1433 
1434 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1435 {
1436 	return type_is_pkt_pointer(reg->type);
1437 }
1438 
1439 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1440 {
1441 	return reg_is_pkt_pointer(reg) ||
1442 	       reg->type == PTR_TO_PACKET_END;
1443 }
1444 
1445 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1446 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1447 				    enum bpf_reg_type which)
1448 {
1449 	/* The register can already have a range from prior markings.
1450 	 * This is fine as long as it hasn't been advanced from its
1451 	 * origin.
1452 	 */
1453 	return reg->type == which &&
1454 	       reg->id == 0 &&
1455 	       reg->off == 0 &&
1456 	       tnum_equals_const(reg->var_off, 0);
1457 }
1458 
1459 /* Reset the min/max bounds of a register */
1460 static void __mark_reg_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 	reg->s32_min_value = S32_MIN;
1468 	reg->s32_max_value = S32_MAX;
1469 	reg->u32_min_value = 0;
1470 	reg->u32_max_value = U32_MAX;
1471 }
1472 
1473 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1474 {
1475 	reg->smin_value = S64_MIN;
1476 	reg->smax_value = S64_MAX;
1477 	reg->umin_value = 0;
1478 	reg->umax_value = U64_MAX;
1479 }
1480 
1481 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1482 {
1483 	reg->s32_min_value = S32_MIN;
1484 	reg->s32_max_value = S32_MAX;
1485 	reg->u32_min_value = 0;
1486 	reg->u32_max_value = U32_MAX;
1487 }
1488 
1489 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1490 {
1491 	struct tnum var32_off = tnum_subreg(reg->var_off);
1492 
1493 	/* min signed is max(sign bit) | min(other bits) */
1494 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1495 			var32_off.value | (var32_off.mask & S32_MIN));
1496 	/* max signed is min(sign bit) | max(other bits) */
1497 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1498 			var32_off.value | (var32_off.mask & S32_MAX));
1499 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1500 	reg->u32_max_value = min(reg->u32_max_value,
1501 				 (u32)(var32_off.value | var32_off.mask));
1502 }
1503 
1504 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1505 {
1506 	/* min signed is max(sign bit) | min(other bits) */
1507 	reg->smin_value = max_t(s64, reg->smin_value,
1508 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1509 	/* max signed is min(sign bit) | max(other bits) */
1510 	reg->smax_value = min_t(s64, reg->smax_value,
1511 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1512 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1513 	reg->umax_value = min(reg->umax_value,
1514 			      reg->var_off.value | reg->var_off.mask);
1515 }
1516 
1517 static void __update_reg_bounds(struct bpf_reg_state *reg)
1518 {
1519 	__update_reg32_bounds(reg);
1520 	__update_reg64_bounds(reg);
1521 }
1522 
1523 /* Uses signed min/max values to inform unsigned, and vice-versa */
1524 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1525 {
1526 	/* Learn sign from signed bounds.
1527 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1528 	 * are the same, so combine.  This works even in the negative case, e.g.
1529 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1530 	 */
1531 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1532 		reg->s32_min_value = reg->u32_min_value =
1533 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1534 		reg->s32_max_value = reg->u32_max_value =
1535 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1536 		return;
1537 	}
1538 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1539 	 * boundary, so we must be careful.
1540 	 */
1541 	if ((s32)reg->u32_max_value >= 0) {
1542 		/* Positive.  We can't learn anything from the smin, but smax
1543 		 * is positive, hence safe.
1544 		 */
1545 		reg->s32_min_value = reg->u32_min_value;
1546 		reg->s32_max_value = reg->u32_max_value =
1547 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1548 	} else if ((s32)reg->u32_min_value < 0) {
1549 		/* Negative.  We can't learn anything from the smax, but smin
1550 		 * is negative, hence safe.
1551 		 */
1552 		reg->s32_min_value = reg->u32_min_value =
1553 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1554 		reg->s32_max_value = reg->u32_max_value;
1555 	}
1556 }
1557 
1558 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1559 {
1560 	/* Learn sign from signed bounds.
1561 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1562 	 * are the same, so combine.  This works even in the negative case, e.g.
1563 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1564 	 */
1565 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1566 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1567 							  reg->umin_value);
1568 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1569 							  reg->umax_value);
1570 		return;
1571 	}
1572 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1573 	 * boundary, so we must be careful.
1574 	 */
1575 	if ((s64)reg->umax_value >= 0) {
1576 		/* Positive.  We can't learn anything from the smin, but smax
1577 		 * is positive, hence safe.
1578 		 */
1579 		reg->smin_value = reg->umin_value;
1580 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1581 							  reg->umax_value);
1582 	} else if ((s64)reg->umin_value < 0) {
1583 		/* Negative.  We can't learn anything from the smax, but smin
1584 		 * is negative, hence safe.
1585 		 */
1586 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1587 							  reg->umin_value);
1588 		reg->smax_value = reg->umax_value;
1589 	}
1590 }
1591 
1592 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1593 {
1594 	__reg32_deduce_bounds(reg);
1595 	__reg64_deduce_bounds(reg);
1596 }
1597 
1598 /* Attempts to improve var_off based on unsigned min/max information */
1599 static void __reg_bound_offset(struct bpf_reg_state *reg)
1600 {
1601 	struct tnum var64_off = tnum_intersect(reg->var_off,
1602 					       tnum_range(reg->umin_value,
1603 							  reg->umax_value));
1604 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1605 						tnum_range(reg->u32_min_value,
1606 							   reg->u32_max_value));
1607 
1608 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1609 }
1610 
1611 static void reg_bounds_sync(struct bpf_reg_state *reg)
1612 {
1613 	/* We might have learned new bounds from the var_off. */
1614 	__update_reg_bounds(reg);
1615 	/* We might have learned something about the sign bit. */
1616 	__reg_deduce_bounds(reg);
1617 	/* We might have learned some bits from the bounds. */
1618 	__reg_bound_offset(reg);
1619 	/* Intersecting with the old var_off might have improved our bounds
1620 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1621 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1622 	 */
1623 	__update_reg_bounds(reg);
1624 }
1625 
1626 static bool __reg32_bound_s64(s32 a)
1627 {
1628 	return a >= 0 && a <= S32_MAX;
1629 }
1630 
1631 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1632 {
1633 	reg->umin_value = reg->u32_min_value;
1634 	reg->umax_value = reg->u32_max_value;
1635 
1636 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1637 	 * be positive otherwise set to worse case bounds and refine later
1638 	 * from tnum.
1639 	 */
1640 	if (__reg32_bound_s64(reg->s32_min_value) &&
1641 	    __reg32_bound_s64(reg->s32_max_value)) {
1642 		reg->smin_value = reg->s32_min_value;
1643 		reg->smax_value = reg->s32_max_value;
1644 	} else {
1645 		reg->smin_value = 0;
1646 		reg->smax_value = U32_MAX;
1647 	}
1648 }
1649 
1650 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1651 {
1652 	/* special case when 64-bit register has upper 32-bit register
1653 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1654 	 * allowing us to use 32-bit bounds directly,
1655 	 */
1656 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1657 		__reg_assign_32_into_64(reg);
1658 	} else {
1659 		/* Otherwise the best we can do is push lower 32bit known and
1660 		 * unknown bits into register (var_off set from jmp logic)
1661 		 * then learn as much as possible from the 64-bit tnum
1662 		 * known and unknown bits. The previous smin/smax bounds are
1663 		 * invalid here because of jmp32 compare so mark them unknown
1664 		 * so they do not impact tnum bounds calculation.
1665 		 */
1666 		__mark_reg64_unbounded(reg);
1667 	}
1668 	reg_bounds_sync(reg);
1669 }
1670 
1671 static bool __reg64_bound_s32(s64 a)
1672 {
1673 	return a >= S32_MIN && a <= S32_MAX;
1674 }
1675 
1676 static bool __reg64_bound_u32(u64 a)
1677 {
1678 	return a >= U32_MIN && a <= U32_MAX;
1679 }
1680 
1681 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1682 {
1683 	__mark_reg32_unbounded(reg);
1684 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1685 		reg->s32_min_value = (s32)reg->smin_value;
1686 		reg->s32_max_value = (s32)reg->smax_value;
1687 	}
1688 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1689 		reg->u32_min_value = (u32)reg->umin_value;
1690 		reg->u32_max_value = (u32)reg->umax_value;
1691 	}
1692 	reg_bounds_sync(reg);
1693 }
1694 
1695 /* Mark a register as having a completely unknown (scalar) value. */
1696 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1697 			       struct bpf_reg_state *reg)
1698 {
1699 	/*
1700 	 * Clear type, id, off, and union(map_ptr, range) and
1701 	 * padding between 'type' and union
1702 	 */
1703 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1704 	reg->type = SCALAR_VALUE;
1705 	reg->var_off = tnum_unknown;
1706 	reg->frameno = 0;
1707 	reg->precise = !env->bpf_capable;
1708 	__mark_reg_unbounded(reg);
1709 }
1710 
1711 static void mark_reg_unknown(struct bpf_verifier_env *env,
1712 			     struct bpf_reg_state *regs, u32 regno)
1713 {
1714 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1715 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1716 		/* Something bad happened, let's kill all regs except FP */
1717 		for (regno = 0; regno < BPF_REG_FP; regno++)
1718 			__mark_reg_not_init(env, regs + regno);
1719 		return;
1720 	}
1721 	__mark_reg_unknown(env, regs + regno);
1722 }
1723 
1724 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1725 				struct bpf_reg_state *reg)
1726 {
1727 	__mark_reg_unknown(env, reg);
1728 	reg->type = NOT_INIT;
1729 }
1730 
1731 static void mark_reg_not_init(struct bpf_verifier_env *env,
1732 			      struct bpf_reg_state *regs, u32 regno)
1733 {
1734 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1735 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1736 		/* Something bad happened, let's kill all regs except FP */
1737 		for (regno = 0; regno < BPF_REG_FP; regno++)
1738 			__mark_reg_not_init(env, regs + regno);
1739 		return;
1740 	}
1741 	__mark_reg_not_init(env, regs + regno);
1742 }
1743 
1744 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1745 			    struct bpf_reg_state *regs, u32 regno,
1746 			    enum bpf_reg_type reg_type,
1747 			    struct btf *btf, u32 btf_id,
1748 			    enum bpf_type_flag flag)
1749 {
1750 	if (reg_type == SCALAR_VALUE) {
1751 		mark_reg_unknown(env, regs, regno);
1752 		return;
1753 	}
1754 	mark_reg_known_zero(env, regs, regno);
1755 	regs[regno].type = PTR_TO_BTF_ID | flag;
1756 	regs[regno].btf = btf;
1757 	regs[regno].btf_id = btf_id;
1758 }
1759 
1760 #define DEF_NOT_SUBREG	(0)
1761 static void init_reg_state(struct bpf_verifier_env *env,
1762 			   struct bpf_func_state *state)
1763 {
1764 	struct bpf_reg_state *regs = state->regs;
1765 	int i;
1766 
1767 	for (i = 0; i < MAX_BPF_REG; i++) {
1768 		mark_reg_not_init(env, regs, i);
1769 		regs[i].live = REG_LIVE_NONE;
1770 		regs[i].parent = NULL;
1771 		regs[i].subreg_def = DEF_NOT_SUBREG;
1772 	}
1773 
1774 	/* frame pointer */
1775 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1776 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1777 	regs[BPF_REG_FP].frameno = state->frameno;
1778 }
1779 
1780 #define BPF_MAIN_FUNC (-1)
1781 static void init_func_state(struct bpf_verifier_env *env,
1782 			    struct bpf_func_state *state,
1783 			    int callsite, int frameno, int subprogno)
1784 {
1785 	state->callsite = callsite;
1786 	state->frameno = frameno;
1787 	state->subprogno = subprogno;
1788 	state->callback_ret_range = tnum_range(0, 0);
1789 	init_reg_state(env, state);
1790 	mark_verifier_state_scratched(env);
1791 }
1792 
1793 /* Similar to push_stack(), but for async callbacks */
1794 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1795 						int insn_idx, int prev_insn_idx,
1796 						int subprog)
1797 {
1798 	struct bpf_verifier_stack_elem *elem;
1799 	struct bpf_func_state *frame;
1800 
1801 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1802 	if (!elem)
1803 		goto err;
1804 
1805 	elem->insn_idx = insn_idx;
1806 	elem->prev_insn_idx = prev_insn_idx;
1807 	elem->next = env->head;
1808 	elem->log_pos = env->log.len_used;
1809 	env->head = elem;
1810 	env->stack_size++;
1811 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1812 		verbose(env,
1813 			"The sequence of %d jumps is too complex for async cb.\n",
1814 			env->stack_size);
1815 		goto err;
1816 	}
1817 	/* Unlike push_stack() do not copy_verifier_state().
1818 	 * The caller state doesn't matter.
1819 	 * This is async callback. It starts in a fresh stack.
1820 	 * Initialize it similar to do_check_common().
1821 	 */
1822 	elem->st.branches = 1;
1823 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1824 	if (!frame)
1825 		goto err;
1826 	init_func_state(env, frame,
1827 			BPF_MAIN_FUNC /* callsite */,
1828 			0 /* frameno within this callchain */,
1829 			subprog /* subprog number within this prog */);
1830 	elem->st.frame[0] = frame;
1831 	return &elem->st;
1832 err:
1833 	free_verifier_state(env->cur_state, true);
1834 	env->cur_state = NULL;
1835 	/* pop all elements and return */
1836 	while (!pop_stack(env, NULL, NULL, false));
1837 	return NULL;
1838 }
1839 
1840 
1841 enum reg_arg_type {
1842 	SRC_OP,		/* register is used as source operand */
1843 	DST_OP,		/* register is used as destination operand */
1844 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1845 };
1846 
1847 static int cmp_subprogs(const void *a, const void *b)
1848 {
1849 	return ((struct bpf_subprog_info *)a)->start -
1850 	       ((struct bpf_subprog_info *)b)->start;
1851 }
1852 
1853 static int find_subprog(struct bpf_verifier_env *env, int off)
1854 {
1855 	struct bpf_subprog_info *p;
1856 
1857 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1858 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1859 	if (!p)
1860 		return -ENOENT;
1861 	return p - env->subprog_info;
1862 
1863 }
1864 
1865 static int add_subprog(struct bpf_verifier_env *env, int off)
1866 {
1867 	int insn_cnt = env->prog->len;
1868 	int ret;
1869 
1870 	if (off >= insn_cnt || off < 0) {
1871 		verbose(env, "call to invalid destination\n");
1872 		return -EINVAL;
1873 	}
1874 	ret = find_subprog(env, off);
1875 	if (ret >= 0)
1876 		return ret;
1877 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1878 		verbose(env, "too many subprograms\n");
1879 		return -E2BIG;
1880 	}
1881 	/* determine subprog starts. The end is one before the next starts */
1882 	env->subprog_info[env->subprog_cnt++].start = off;
1883 	sort(env->subprog_info, env->subprog_cnt,
1884 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1885 	return env->subprog_cnt - 1;
1886 }
1887 
1888 #define MAX_KFUNC_DESCS 256
1889 #define MAX_KFUNC_BTFS	256
1890 
1891 struct bpf_kfunc_desc {
1892 	struct btf_func_model func_model;
1893 	u32 func_id;
1894 	s32 imm;
1895 	u16 offset;
1896 };
1897 
1898 struct bpf_kfunc_btf {
1899 	struct btf *btf;
1900 	struct module *module;
1901 	u16 offset;
1902 };
1903 
1904 struct bpf_kfunc_desc_tab {
1905 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1906 	u32 nr_descs;
1907 };
1908 
1909 struct bpf_kfunc_btf_tab {
1910 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1911 	u32 nr_descs;
1912 };
1913 
1914 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1915 {
1916 	const struct bpf_kfunc_desc *d0 = a;
1917 	const struct bpf_kfunc_desc *d1 = b;
1918 
1919 	/* func_id is not greater than BTF_MAX_TYPE */
1920 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1921 }
1922 
1923 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1924 {
1925 	const struct bpf_kfunc_btf *d0 = a;
1926 	const struct bpf_kfunc_btf *d1 = b;
1927 
1928 	return d0->offset - d1->offset;
1929 }
1930 
1931 static const struct bpf_kfunc_desc *
1932 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1933 {
1934 	struct bpf_kfunc_desc desc = {
1935 		.func_id = func_id,
1936 		.offset = offset,
1937 	};
1938 	struct bpf_kfunc_desc_tab *tab;
1939 
1940 	tab = prog->aux->kfunc_tab;
1941 	return bsearch(&desc, tab->descs, tab->nr_descs,
1942 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1943 }
1944 
1945 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1946 					 s16 offset)
1947 {
1948 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1949 	struct bpf_kfunc_btf_tab *tab;
1950 	struct bpf_kfunc_btf *b;
1951 	struct module *mod;
1952 	struct btf *btf;
1953 	int btf_fd;
1954 
1955 	tab = env->prog->aux->kfunc_btf_tab;
1956 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1957 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1958 	if (!b) {
1959 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1960 			verbose(env, "too many different module BTFs\n");
1961 			return ERR_PTR(-E2BIG);
1962 		}
1963 
1964 		if (bpfptr_is_null(env->fd_array)) {
1965 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1966 			return ERR_PTR(-EPROTO);
1967 		}
1968 
1969 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1970 					    offset * sizeof(btf_fd),
1971 					    sizeof(btf_fd)))
1972 			return ERR_PTR(-EFAULT);
1973 
1974 		btf = btf_get_by_fd(btf_fd);
1975 		if (IS_ERR(btf)) {
1976 			verbose(env, "invalid module BTF fd specified\n");
1977 			return btf;
1978 		}
1979 
1980 		if (!btf_is_module(btf)) {
1981 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1982 			btf_put(btf);
1983 			return ERR_PTR(-EINVAL);
1984 		}
1985 
1986 		mod = btf_try_get_module(btf);
1987 		if (!mod) {
1988 			btf_put(btf);
1989 			return ERR_PTR(-ENXIO);
1990 		}
1991 
1992 		b = &tab->descs[tab->nr_descs++];
1993 		b->btf = btf;
1994 		b->module = mod;
1995 		b->offset = offset;
1996 
1997 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1998 		     kfunc_btf_cmp_by_off, NULL);
1999 	}
2000 	return b->btf;
2001 }
2002 
2003 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2004 {
2005 	if (!tab)
2006 		return;
2007 
2008 	while (tab->nr_descs--) {
2009 		module_put(tab->descs[tab->nr_descs].module);
2010 		btf_put(tab->descs[tab->nr_descs].btf);
2011 	}
2012 	kfree(tab);
2013 }
2014 
2015 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2016 {
2017 	if (offset) {
2018 		if (offset < 0) {
2019 			/* In the future, this can be allowed to increase limit
2020 			 * of fd index into fd_array, interpreted as u16.
2021 			 */
2022 			verbose(env, "negative offset disallowed for kernel module function call\n");
2023 			return ERR_PTR(-EINVAL);
2024 		}
2025 
2026 		return __find_kfunc_desc_btf(env, offset);
2027 	}
2028 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2029 }
2030 
2031 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2032 {
2033 	const struct btf_type *func, *func_proto;
2034 	struct bpf_kfunc_btf_tab *btf_tab;
2035 	struct bpf_kfunc_desc_tab *tab;
2036 	struct bpf_prog_aux *prog_aux;
2037 	struct bpf_kfunc_desc *desc;
2038 	const char *func_name;
2039 	struct btf *desc_btf;
2040 	unsigned long call_imm;
2041 	unsigned long addr;
2042 	int err;
2043 
2044 	prog_aux = env->prog->aux;
2045 	tab = prog_aux->kfunc_tab;
2046 	btf_tab = prog_aux->kfunc_btf_tab;
2047 	if (!tab) {
2048 		if (!btf_vmlinux) {
2049 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2050 			return -ENOTSUPP;
2051 		}
2052 
2053 		if (!env->prog->jit_requested) {
2054 			verbose(env, "JIT is required for calling kernel function\n");
2055 			return -ENOTSUPP;
2056 		}
2057 
2058 		if (!bpf_jit_supports_kfunc_call()) {
2059 			verbose(env, "JIT does not support calling kernel function\n");
2060 			return -ENOTSUPP;
2061 		}
2062 
2063 		if (!env->prog->gpl_compatible) {
2064 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2065 			return -EINVAL;
2066 		}
2067 
2068 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2069 		if (!tab)
2070 			return -ENOMEM;
2071 		prog_aux->kfunc_tab = tab;
2072 	}
2073 
2074 	/* func_id == 0 is always invalid, but instead of returning an error, be
2075 	 * conservative and wait until the code elimination pass before returning
2076 	 * error, so that invalid calls that get pruned out can be in BPF programs
2077 	 * loaded from userspace.  It is also required that offset be untouched
2078 	 * for such calls.
2079 	 */
2080 	if (!func_id && !offset)
2081 		return 0;
2082 
2083 	if (!btf_tab && offset) {
2084 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2085 		if (!btf_tab)
2086 			return -ENOMEM;
2087 		prog_aux->kfunc_btf_tab = btf_tab;
2088 	}
2089 
2090 	desc_btf = find_kfunc_desc_btf(env, offset);
2091 	if (IS_ERR(desc_btf)) {
2092 		verbose(env, "failed to find BTF for kernel function\n");
2093 		return PTR_ERR(desc_btf);
2094 	}
2095 
2096 	if (find_kfunc_desc(env->prog, func_id, offset))
2097 		return 0;
2098 
2099 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2100 		verbose(env, "too many different kernel function calls\n");
2101 		return -E2BIG;
2102 	}
2103 
2104 	func = btf_type_by_id(desc_btf, func_id);
2105 	if (!func || !btf_type_is_func(func)) {
2106 		verbose(env, "kernel btf_id %u is not a function\n",
2107 			func_id);
2108 		return -EINVAL;
2109 	}
2110 	func_proto = btf_type_by_id(desc_btf, func->type);
2111 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2112 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2113 			func_id);
2114 		return -EINVAL;
2115 	}
2116 
2117 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2118 	addr = kallsyms_lookup_name(func_name);
2119 	if (!addr) {
2120 		verbose(env, "cannot find address for kernel function %s\n",
2121 			func_name);
2122 		return -EINVAL;
2123 	}
2124 
2125 	call_imm = BPF_CALL_IMM(addr);
2126 	/* Check whether or not the relative offset overflows desc->imm */
2127 	if ((unsigned long)(s32)call_imm != call_imm) {
2128 		verbose(env, "address of kernel function %s is out of range\n",
2129 			func_name);
2130 		return -EINVAL;
2131 	}
2132 
2133 	desc = &tab->descs[tab->nr_descs++];
2134 	desc->func_id = func_id;
2135 	desc->imm = call_imm;
2136 	desc->offset = offset;
2137 	err = btf_distill_func_proto(&env->log, desc_btf,
2138 				     func_proto, func_name,
2139 				     &desc->func_model);
2140 	if (!err)
2141 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2142 		     kfunc_desc_cmp_by_id_off, NULL);
2143 	return err;
2144 }
2145 
2146 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2147 {
2148 	const struct bpf_kfunc_desc *d0 = a;
2149 	const struct bpf_kfunc_desc *d1 = b;
2150 
2151 	if (d0->imm > d1->imm)
2152 		return 1;
2153 	else if (d0->imm < d1->imm)
2154 		return -1;
2155 	return 0;
2156 }
2157 
2158 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2159 {
2160 	struct bpf_kfunc_desc_tab *tab;
2161 
2162 	tab = prog->aux->kfunc_tab;
2163 	if (!tab)
2164 		return;
2165 
2166 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2167 	     kfunc_desc_cmp_by_imm, NULL);
2168 }
2169 
2170 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2171 {
2172 	return !!prog->aux->kfunc_tab;
2173 }
2174 
2175 const struct btf_func_model *
2176 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2177 			 const struct bpf_insn *insn)
2178 {
2179 	const struct bpf_kfunc_desc desc = {
2180 		.imm = insn->imm,
2181 	};
2182 	const struct bpf_kfunc_desc *res;
2183 	struct bpf_kfunc_desc_tab *tab;
2184 
2185 	tab = prog->aux->kfunc_tab;
2186 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2187 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2188 
2189 	return res ? &res->func_model : NULL;
2190 }
2191 
2192 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2193 {
2194 	struct bpf_subprog_info *subprog = env->subprog_info;
2195 	struct bpf_insn *insn = env->prog->insnsi;
2196 	int i, ret, insn_cnt = env->prog->len;
2197 
2198 	/* Add entry function. */
2199 	ret = add_subprog(env, 0);
2200 	if (ret)
2201 		return ret;
2202 
2203 	for (i = 0; i < insn_cnt; i++, insn++) {
2204 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2205 		    !bpf_pseudo_kfunc_call(insn))
2206 			continue;
2207 
2208 		if (!env->bpf_capable) {
2209 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2210 			return -EPERM;
2211 		}
2212 
2213 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2214 			ret = add_subprog(env, i + insn->imm + 1);
2215 		else
2216 			ret = add_kfunc_call(env, insn->imm, insn->off);
2217 
2218 		if (ret < 0)
2219 			return ret;
2220 	}
2221 
2222 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2223 	 * logic. 'subprog_cnt' should not be increased.
2224 	 */
2225 	subprog[env->subprog_cnt].start = insn_cnt;
2226 
2227 	if (env->log.level & BPF_LOG_LEVEL2)
2228 		for (i = 0; i < env->subprog_cnt; i++)
2229 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2230 
2231 	return 0;
2232 }
2233 
2234 static int check_subprogs(struct bpf_verifier_env *env)
2235 {
2236 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2237 	struct bpf_subprog_info *subprog = env->subprog_info;
2238 	struct bpf_insn *insn = env->prog->insnsi;
2239 	int insn_cnt = env->prog->len;
2240 
2241 	/* now check that all jumps are within the same subprog */
2242 	subprog_start = subprog[cur_subprog].start;
2243 	subprog_end = subprog[cur_subprog + 1].start;
2244 	for (i = 0; i < insn_cnt; i++) {
2245 		u8 code = insn[i].code;
2246 
2247 		if (code == (BPF_JMP | BPF_CALL) &&
2248 		    insn[i].imm == BPF_FUNC_tail_call &&
2249 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2250 			subprog[cur_subprog].has_tail_call = true;
2251 		if (BPF_CLASS(code) == BPF_LD &&
2252 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2253 			subprog[cur_subprog].has_ld_abs = true;
2254 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2255 			goto next;
2256 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2257 			goto next;
2258 		off = i + insn[i].off + 1;
2259 		if (off < subprog_start || off >= subprog_end) {
2260 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2261 			return -EINVAL;
2262 		}
2263 next:
2264 		if (i == subprog_end - 1) {
2265 			/* to avoid fall-through from one subprog into another
2266 			 * the last insn of the subprog should be either exit
2267 			 * or unconditional jump back
2268 			 */
2269 			if (code != (BPF_JMP | BPF_EXIT) &&
2270 			    code != (BPF_JMP | BPF_JA)) {
2271 				verbose(env, "last insn is not an exit or jmp\n");
2272 				return -EINVAL;
2273 			}
2274 			subprog_start = subprog_end;
2275 			cur_subprog++;
2276 			if (cur_subprog < env->subprog_cnt)
2277 				subprog_end = subprog[cur_subprog + 1].start;
2278 		}
2279 	}
2280 	return 0;
2281 }
2282 
2283 /* Parentage chain of this register (or stack slot) should take care of all
2284  * issues like callee-saved registers, stack slot allocation time, etc.
2285  */
2286 static int mark_reg_read(struct bpf_verifier_env *env,
2287 			 const struct bpf_reg_state *state,
2288 			 struct bpf_reg_state *parent, u8 flag)
2289 {
2290 	bool writes = parent == state->parent; /* Observe write marks */
2291 	int cnt = 0;
2292 
2293 	while (parent) {
2294 		/* if read wasn't screened by an earlier write ... */
2295 		if (writes && state->live & REG_LIVE_WRITTEN)
2296 			break;
2297 		if (parent->live & REG_LIVE_DONE) {
2298 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2299 				reg_type_str(env, parent->type),
2300 				parent->var_off.value, parent->off);
2301 			return -EFAULT;
2302 		}
2303 		/* The first condition is more likely to be true than the
2304 		 * second, checked it first.
2305 		 */
2306 		if ((parent->live & REG_LIVE_READ) == flag ||
2307 		    parent->live & REG_LIVE_READ64)
2308 			/* The parentage chain never changes and
2309 			 * this parent was already marked as LIVE_READ.
2310 			 * There is no need to keep walking the chain again and
2311 			 * keep re-marking all parents as LIVE_READ.
2312 			 * This case happens when the same register is read
2313 			 * multiple times without writes into it in-between.
2314 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2315 			 * then no need to set the weak REG_LIVE_READ32.
2316 			 */
2317 			break;
2318 		/* ... then we depend on parent's value */
2319 		parent->live |= flag;
2320 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2321 		if (flag == REG_LIVE_READ64)
2322 			parent->live &= ~REG_LIVE_READ32;
2323 		state = parent;
2324 		parent = state->parent;
2325 		writes = true;
2326 		cnt++;
2327 	}
2328 
2329 	if (env->longest_mark_read_walk < cnt)
2330 		env->longest_mark_read_walk = cnt;
2331 	return 0;
2332 }
2333 
2334 /* This function is supposed to be used by the following 32-bit optimization
2335  * code only. It returns TRUE if the source or destination register operates
2336  * on 64-bit, otherwise return FALSE.
2337  */
2338 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2339 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2340 {
2341 	u8 code, class, op;
2342 
2343 	code = insn->code;
2344 	class = BPF_CLASS(code);
2345 	op = BPF_OP(code);
2346 	if (class == BPF_JMP) {
2347 		/* BPF_EXIT for "main" will reach here. Return TRUE
2348 		 * conservatively.
2349 		 */
2350 		if (op == BPF_EXIT)
2351 			return true;
2352 		if (op == BPF_CALL) {
2353 			/* BPF to BPF call will reach here because of marking
2354 			 * caller saved clobber with DST_OP_NO_MARK for which we
2355 			 * don't care the register def because they are anyway
2356 			 * marked as NOT_INIT already.
2357 			 */
2358 			if (insn->src_reg == BPF_PSEUDO_CALL)
2359 				return false;
2360 			/* Helper call will reach here because of arg type
2361 			 * check, conservatively return TRUE.
2362 			 */
2363 			if (t == SRC_OP)
2364 				return true;
2365 
2366 			return false;
2367 		}
2368 	}
2369 
2370 	if (class == BPF_ALU64 || class == BPF_JMP ||
2371 	    /* BPF_END always use BPF_ALU class. */
2372 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2373 		return true;
2374 
2375 	if (class == BPF_ALU || class == BPF_JMP32)
2376 		return false;
2377 
2378 	if (class == BPF_LDX) {
2379 		if (t != SRC_OP)
2380 			return BPF_SIZE(code) == BPF_DW;
2381 		/* LDX source must be ptr. */
2382 		return true;
2383 	}
2384 
2385 	if (class == BPF_STX) {
2386 		/* BPF_STX (including atomic variants) has multiple source
2387 		 * operands, one of which is a ptr. Check whether the caller is
2388 		 * asking about it.
2389 		 */
2390 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2391 			return true;
2392 		return BPF_SIZE(code) == BPF_DW;
2393 	}
2394 
2395 	if (class == BPF_LD) {
2396 		u8 mode = BPF_MODE(code);
2397 
2398 		/* LD_IMM64 */
2399 		if (mode == BPF_IMM)
2400 			return true;
2401 
2402 		/* Both LD_IND and LD_ABS return 32-bit data. */
2403 		if (t != SRC_OP)
2404 			return  false;
2405 
2406 		/* Implicit ctx ptr. */
2407 		if (regno == BPF_REG_6)
2408 			return true;
2409 
2410 		/* Explicit source could be any width. */
2411 		return true;
2412 	}
2413 
2414 	if (class == BPF_ST)
2415 		/* The only source register for BPF_ST is a ptr. */
2416 		return true;
2417 
2418 	/* Conservatively return true at default. */
2419 	return true;
2420 }
2421 
2422 /* Return the regno defined by the insn, or -1. */
2423 static int insn_def_regno(const struct bpf_insn *insn)
2424 {
2425 	switch (BPF_CLASS(insn->code)) {
2426 	case BPF_JMP:
2427 	case BPF_JMP32:
2428 	case BPF_ST:
2429 		return -1;
2430 	case BPF_STX:
2431 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2432 		    (insn->imm & BPF_FETCH)) {
2433 			if (insn->imm == BPF_CMPXCHG)
2434 				return BPF_REG_0;
2435 			else
2436 				return insn->src_reg;
2437 		} else {
2438 			return -1;
2439 		}
2440 	default:
2441 		return insn->dst_reg;
2442 	}
2443 }
2444 
2445 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2446 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2447 {
2448 	int dst_reg = insn_def_regno(insn);
2449 
2450 	if (dst_reg == -1)
2451 		return false;
2452 
2453 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2454 }
2455 
2456 static void mark_insn_zext(struct bpf_verifier_env *env,
2457 			   struct bpf_reg_state *reg)
2458 {
2459 	s32 def_idx = reg->subreg_def;
2460 
2461 	if (def_idx == DEF_NOT_SUBREG)
2462 		return;
2463 
2464 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2465 	/* The dst will be zero extended, so won't be sub-register anymore. */
2466 	reg->subreg_def = DEF_NOT_SUBREG;
2467 }
2468 
2469 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2470 			 enum reg_arg_type t)
2471 {
2472 	struct bpf_verifier_state *vstate = env->cur_state;
2473 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2474 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2475 	struct bpf_reg_state *reg, *regs = state->regs;
2476 	bool rw64;
2477 
2478 	if (regno >= MAX_BPF_REG) {
2479 		verbose(env, "R%d is invalid\n", regno);
2480 		return -EINVAL;
2481 	}
2482 
2483 	mark_reg_scratched(env, regno);
2484 
2485 	reg = &regs[regno];
2486 	rw64 = is_reg64(env, insn, regno, reg, t);
2487 	if (t == SRC_OP) {
2488 		/* check whether register used as source operand can be read */
2489 		if (reg->type == NOT_INIT) {
2490 			verbose(env, "R%d !read_ok\n", regno);
2491 			return -EACCES;
2492 		}
2493 		/* We don't need to worry about FP liveness because it's read-only */
2494 		if (regno == BPF_REG_FP)
2495 			return 0;
2496 
2497 		if (rw64)
2498 			mark_insn_zext(env, reg);
2499 
2500 		return mark_reg_read(env, reg, reg->parent,
2501 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2502 	} else {
2503 		/* check whether register used as dest operand can be written to */
2504 		if (regno == BPF_REG_FP) {
2505 			verbose(env, "frame pointer is read only\n");
2506 			return -EACCES;
2507 		}
2508 		reg->live |= REG_LIVE_WRITTEN;
2509 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2510 		if (t == DST_OP)
2511 			mark_reg_unknown(env, regs, regno);
2512 	}
2513 	return 0;
2514 }
2515 
2516 /* for any branch, call, exit record the history of jmps in the given state */
2517 static int push_jmp_history(struct bpf_verifier_env *env,
2518 			    struct bpf_verifier_state *cur)
2519 {
2520 	u32 cnt = cur->jmp_history_cnt;
2521 	struct bpf_idx_pair *p;
2522 
2523 	cnt++;
2524 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2525 	if (!p)
2526 		return -ENOMEM;
2527 	p[cnt - 1].idx = env->insn_idx;
2528 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2529 	cur->jmp_history = p;
2530 	cur->jmp_history_cnt = cnt;
2531 	return 0;
2532 }
2533 
2534 /* Backtrack one insn at a time. If idx is not at the top of recorded
2535  * history then previous instruction came from straight line execution.
2536  */
2537 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2538 			     u32 *history)
2539 {
2540 	u32 cnt = *history;
2541 
2542 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2543 		i = st->jmp_history[cnt - 1].prev_idx;
2544 		(*history)--;
2545 	} else {
2546 		i--;
2547 	}
2548 	return i;
2549 }
2550 
2551 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2552 {
2553 	const struct btf_type *func;
2554 	struct btf *desc_btf;
2555 
2556 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2557 		return NULL;
2558 
2559 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2560 	if (IS_ERR(desc_btf))
2561 		return "<error>";
2562 
2563 	func = btf_type_by_id(desc_btf, insn->imm);
2564 	return btf_name_by_offset(desc_btf, func->name_off);
2565 }
2566 
2567 /* For given verifier state backtrack_insn() is called from the last insn to
2568  * the first insn. Its purpose is to compute a bitmask of registers and
2569  * stack slots that needs precision in the parent verifier state.
2570  */
2571 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2572 			  u32 *reg_mask, u64 *stack_mask)
2573 {
2574 	const struct bpf_insn_cbs cbs = {
2575 		.cb_call	= disasm_kfunc_name,
2576 		.cb_print	= verbose,
2577 		.private_data	= env,
2578 	};
2579 	struct bpf_insn *insn = env->prog->insnsi + idx;
2580 	u8 class = BPF_CLASS(insn->code);
2581 	u8 opcode = BPF_OP(insn->code);
2582 	u8 mode = BPF_MODE(insn->code);
2583 	u32 dreg = 1u << insn->dst_reg;
2584 	u32 sreg = 1u << insn->src_reg;
2585 	u32 spi;
2586 
2587 	if (insn->code == 0)
2588 		return 0;
2589 	if (env->log.level & BPF_LOG_LEVEL2) {
2590 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2591 		verbose(env, "%d: ", idx);
2592 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2593 	}
2594 
2595 	if (class == BPF_ALU || class == BPF_ALU64) {
2596 		if (!(*reg_mask & dreg))
2597 			return 0;
2598 		if (opcode == BPF_MOV) {
2599 			if (BPF_SRC(insn->code) == BPF_X) {
2600 				/* dreg = sreg
2601 				 * dreg needs precision after this insn
2602 				 * sreg needs precision before this insn
2603 				 */
2604 				*reg_mask &= ~dreg;
2605 				*reg_mask |= sreg;
2606 			} else {
2607 				/* dreg = K
2608 				 * dreg needs precision after this insn.
2609 				 * Corresponding register is already marked
2610 				 * as precise=true in this verifier state.
2611 				 * No further markings in parent are necessary
2612 				 */
2613 				*reg_mask &= ~dreg;
2614 			}
2615 		} else {
2616 			if (BPF_SRC(insn->code) == BPF_X) {
2617 				/* dreg += sreg
2618 				 * both dreg and sreg need precision
2619 				 * before this insn
2620 				 */
2621 				*reg_mask |= sreg;
2622 			} /* else dreg += K
2623 			   * dreg still needs precision before this insn
2624 			   */
2625 		}
2626 	} else if (class == BPF_LDX) {
2627 		if (!(*reg_mask & dreg))
2628 			return 0;
2629 		*reg_mask &= ~dreg;
2630 
2631 		/* scalars can only be spilled into stack w/o losing precision.
2632 		 * Load from any other memory can be zero extended.
2633 		 * The desire to keep that precision is already indicated
2634 		 * by 'precise' mark in corresponding register of this state.
2635 		 * No further tracking necessary.
2636 		 */
2637 		if (insn->src_reg != BPF_REG_FP)
2638 			return 0;
2639 
2640 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2641 		 * that [fp - off] slot contains scalar that needs to be
2642 		 * tracked with precision
2643 		 */
2644 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2645 		if (spi >= 64) {
2646 			verbose(env, "BUG spi %d\n", spi);
2647 			WARN_ONCE(1, "verifier backtracking bug");
2648 			return -EFAULT;
2649 		}
2650 		*stack_mask |= 1ull << spi;
2651 	} else if (class == BPF_STX || class == BPF_ST) {
2652 		if (*reg_mask & dreg)
2653 			/* stx & st shouldn't be using _scalar_ dst_reg
2654 			 * to access memory. It means backtracking
2655 			 * encountered a case of pointer subtraction.
2656 			 */
2657 			return -ENOTSUPP;
2658 		/* scalars can only be spilled into stack */
2659 		if (insn->dst_reg != BPF_REG_FP)
2660 			return 0;
2661 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2662 		if (spi >= 64) {
2663 			verbose(env, "BUG spi %d\n", spi);
2664 			WARN_ONCE(1, "verifier backtracking bug");
2665 			return -EFAULT;
2666 		}
2667 		if (!(*stack_mask & (1ull << spi)))
2668 			return 0;
2669 		*stack_mask &= ~(1ull << spi);
2670 		if (class == BPF_STX)
2671 			*reg_mask |= sreg;
2672 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2673 		if (opcode == BPF_CALL) {
2674 			if (insn->src_reg == BPF_PSEUDO_CALL)
2675 				return -ENOTSUPP;
2676 			/* BPF helpers that invoke callback subprogs are
2677 			 * equivalent to BPF_PSEUDO_CALL above
2678 			 */
2679 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2680 				return -ENOTSUPP;
2681 			/* regular helper call sets R0 */
2682 			*reg_mask &= ~1;
2683 			if (*reg_mask & 0x3f) {
2684 				/* if backtracing was looking for registers R1-R5
2685 				 * they should have been found already.
2686 				 */
2687 				verbose(env, "BUG regs %x\n", *reg_mask);
2688 				WARN_ONCE(1, "verifier backtracking bug");
2689 				return -EFAULT;
2690 			}
2691 		} else if (opcode == BPF_EXIT) {
2692 			return -ENOTSUPP;
2693 		}
2694 	} else if (class == BPF_LD) {
2695 		if (!(*reg_mask & dreg))
2696 			return 0;
2697 		*reg_mask &= ~dreg;
2698 		/* It's ld_imm64 or ld_abs or ld_ind.
2699 		 * For ld_imm64 no further tracking of precision
2700 		 * into parent is necessary
2701 		 */
2702 		if (mode == BPF_IND || mode == BPF_ABS)
2703 			/* to be analyzed */
2704 			return -ENOTSUPP;
2705 	}
2706 	return 0;
2707 }
2708 
2709 /* the scalar precision tracking algorithm:
2710  * . at the start all registers have precise=false.
2711  * . scalar ranges are tracked as normal through alu and jmp insns.
2712  * . once precise value of the scalar register is used in:
2713  *   .  ptr + scalar alu
2714  *   . if (scalar cond K|scalar)
2715  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2716  *   backtrack through the verifier states and mark all registers and
2717  *   stack slots with spilled constants that these scalar regisers
2718  *   should be precise.
2719  * . during state pruning two registers (or spilled stack slots)
2720  *   are equivalent if both are not precise.
2721  *
2722  * Note the verifier cannot simply walk register parentage chain,
2723  * since many different registers and stack slots could have been
2724  * used to compute single precise scalar.
2725  *
2726  * The approach of starting with precise=true for all registers and then
2727  * backtrack to mark a register as not precise when the verifier detects
2728  * that program doesn't care about specific value (e.g., when helper
2729  * takes register as ARG_ANYTHING parameter) is not safe.
2730  *
2731  * It's ok to walk single parentage chain of the verifier states.
2732  * It's possible that this backtracking will go all the way till 1st insn.
2733  * All other branches will be explored for needing precision later.
2734  *
2735  * The backtracking needs to deal with cases like:
2736  *   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)
2737  * r9 -= r8
2738  * r5 = r9
2739  * if r5 > 0x79f goto pc+7
2740  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2741  * r5 += 1
2742  * ...
2743  * call bpf_perf_event_output#25
2744  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2745  *
2746  * and this case:
2747  * r6 = 1
2748  * call foo // uses callee's r6 inside to compute r0
2749  * r0 += r6
2750  * if r0 == 0 goto
2751  *
2752  * to track above reg_mask/stack_mask needs to be independent for each frame.
2753  *
2754  * Also if parent's curframe > frame where backtracking started,
2755  * the verifier need to mark registers in both frames, otherwise callees
2756  * may incorrectly prune callers. This is similar to
2757  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2758  *
2759  * For now backtracking falls back into conservative marking.
2760  */
2761 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2762 				     struct bpf_verifier_state *st)
2763 {
2764 	struct bpf_func_state *func;
2765 	struct bpf_reg_state *reg;
2766 	int i, j;
2767 
2768 	/* big hammer: mark all scalars precise in this path.
2769 	 * pop_stack may still get !precise scalars.
2770 	 * We also skip current state and go straight to first parent state,
2771 	 * because precision markings in current non-checkpointed state are
2772 	 * not needed. See why in the comment in __mark_chain_precision below.
2773 	 */
2774 	for (st = st->parent; st; st = st->parent) {
2775 		for (i = 0; i <= st->curframe; i++) {
2776 			func = st->frame[i];
2777 			for (j = 0; j < BPF_REG_FP; j++) {
2778 				reg = &func->regs[j];
2779 				if (reg->type != SCALAR_VALUE)
2780 					continue;
2781 				reg->precise = true;
2782 			}
2783 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2784 				if (!is_spilled_reg(&func->stack[j]))
2785 					continue;
2786 				reg = &func->stack[j].spilled_ptr;
2787 				if (reg->type != SCALAR_VALUE)
2788 					continue;
2789 				reg->precise = true;
2790 			}
2791 		}
2792 	}
2793 }
2794 
2795 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2796 {
2797 	struct bpf_func_state *func;
2798 	struct bpf_reg_state *reg;
2799 	int i, j;
2800 
2801 	for (i = 0; i <= st->curframe; i++) {
2802 		func = st->frame[i];
2803 		for (j = 0; j < BPF_REG_FP; j++) {
2804 			reg = &func->regs[j];
2805 			if (reg->type != SCALAR_VALUE)
2806 				continue;
2807 			reg->precise = false;
2808 		}
2809 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2810 			if (!is_spilled_reg(&func->stack[j]))
2811 				continue;
2812 			reg = &func->stack[j].spilled_ptr;
2813 			if (reg->type != SCALAR_VALUE)
2814 				continue;
2815 			reg->precise = false;
2816 		}
2817 	}
2818 }
2819 
2820 /*
2821  * __mark_chain_precision() backtracks BPF program instruction sequence and
2822  * chain of verifier states making sure that register *regno* (if regno >= 0)
2823  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2824  * SCALARS, as well as any other registers and slots that contribute to
2825  * a tracked state of given registers/stack slots, depending on specific BPF
2826  * assembly instructions (see backtrack_insns() for exact instruction handling
2827  * logic). This backtracking relies on recorded jmp_history and is able to
2828  * traverse entire chain of parent states. This process ends only when all the
2829  * necessary registers/slots and their transitive dependencies are marked as
2830  * precise.
2831  *
2832  * One important and subtle aspect is that precise marks *do not matter* in
2833  * the currently verified state (current state). It is important to understand
2834  * why this is the case.
2835  *
2836  * First, note that current state is the state that is not yet "checkpointed",
2837  * i.e., it is not yet put into env->explored_states, and it has no children
2838  * states as well. It's ephemeral, and can end up either a) being discarded if
2839  * compatible explored state is found at some point or BPF_EXIT instruction is
2840  * reached or b) checkpointed and put into env->explored_states, branching out
2841  * into one or more children states.
2842  *
2843  * In the former case, precise markings in current state are completely
2844  * ignored by state comparison code (see regsafe() for details). Only
2845  * checkpointed ("old") state precise markings are important, and if old
2846  * state's register/slot is precise, regsafe() assumes current state's
2847  * register/slot as precise and checks value ranges exactly and precisely. If
2848  * states turn out to be compatible, current state's necessary precise
2849  * markings and any required parent states' precise markings are enforced
2850  * after the fact with propagate_precision() logic, after the fact. But it's
2851  * important to realize that in this case, even after marking current state
2852  * registers/slots as precise, we immediately discard current state. So what
2853  * actually matters is any of the precise markings propagated into current
2854  * state's parent states, which are always checkpointed (due to b) case above).
2855  * As such, for scenario a) it doesn't matter if current state has precise
2856  * markings set or not.
2857  *
2858  * Now, for the scenario b), checkpointing and forking into child(ren)
2859  * state(s). Note that before current state gets to checkpointing step, any
2860  * processed instruction always assumes precise SCALAR register/slot
2861  * knowledge: if precise value or range is useful to prune jump branch, BPF
2862  * verifier takes this opportunity enthusiastically. Similarly, when
2863  * register's value is used to calculate offset or memory address, exact
2864  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2865  * what we mentioned above about state comparison ignoring precise markings
2866  * during state comparison, BPF verifier ignores and also assumes precise
2867  * markings *at will* during instruction verification process. But as verifier
2868  * assumes precision, it also propagates any precision dependencies across
2869  * parent states, which are not yet finalized, so can be further restricted
2870  * based on new knowledge gained from restrictions enforced by their children
2871  * states. This is so that once those parent states are finalized, i.e., when
2872  * they have no more active children state, state comparison logic in
2873  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2874  * required for correctness.
2875  *
2876  * To build a bit more intuition, note also that once a state is checkpointed,
2877  * the path we took to get to that state is not important. This is crucial
2878  * property for state pruning. When state is checkpointed and finalized at
2879  * some instruction index, it can be correctly and safely used to "short
2880  * circuit" any *compatible* state that reaches exactly the same instruction
2881  * index. I.e., if we jumped to that instruction from a completely different
2882  * code path than original finalized state was derived from, it doesn't
2883  * matter, current state can be discarded because from that instruction
2884  * forward having a compatible state will ensure we will safely reach the
2885  * exit. States describe preconditions for further exploration, but completely
2886  * forget the history of how we got here.
2887  *
2888  * This also means that even if we needed precise SCALAR range to get to
2889  * finalized state, but from that point forward *that same* SCALAR register is
2890  * never used in a precise context (i.e., it's precise value is not needed for
2891  * correctness), it's correct and safe to mark such register as "imprecise"
2892  * (i.e., precise marking set to false). This is what we rely on when we do
2893  * not set precise marking in current state. If no child state requires
2894  * precision for any given SCALAR register, it's safe to dictate that it can
2895  * be imprecise. If any child state does require this register to be precise,
2896  * we'll mark it precise later retroactively during precise markings
2897  * propagation from child state to parent states.
2898  *
2899  * Skipping precise marking setting in current state is a mild version of
2900  * relying on the above observation. But we can utilize this property even
2901  * more aggressively by proactively forgetting any precise marking in the
2902  * current state (which we inherited from the parent state), right before we
2903  * checkpoint it and branch off into new child state. This is done by
2904  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2905  * finalized states which help in short circuiting more future states.
2906  */
2907 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2908 				  int spi)
2909 {
2910 	struct bpf_verifier_state *st = env->cur_state;
2911 	int first_idx = st->first_insn_idx;
2912 	int last_idx = env->insn_idx;
2913 	struct bpf_func_state *func;
2914 	struct bpf_reg_state *reg;
2915 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2916 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2917 	bool skip_first = true;
2918 	bool new_marks = false;
2919 	int i, err;
2920 
2921 	if (!env->bpf_capable)
2922 		return 0;
2923 
2924 	/* Do sanity checks against current state of register and/or stack
2925 	 * slot, but don't set precise flag in current state, as precision
2926 	 * tracking in the current state is unnecessary.
2927 	 */
2928 	func = st->frame[frame];
2929 	if (regno >= 0) {
2930 		reg = &func->regs[regno];
2931 		if (reg->type != SCALAR_VALUE) {
2932 			WARN_ONCE(1, "backtracing misuse");
2933 			return -EFAULT;
2934 		}
2935 		new_marks = true;
2936 	}
2937 
2938 	while (spi >= 0) {
2939 		if (!is_spilled_reg(&func->stack[spi])) {
2940 			stack_mask = 0;
2941 			break;
2942 		}
2943 		reg = &func->stack[spi].spilled_ptr;
2944 		if (reg->type != SCALAR_VALUE) {
2945 			stack_mask = 0;
2946 			break;
2947 		}
2948 		new_marks = true;
2949 		break;
2950 	}
2951 
2952 	if (!new_marks)
2953 		return 0;
2954 	if (!reg_mask && !stack_mask)
2955 		return 0;
2956 
2957 	for (;;) {
2958 		DECLARE_BITMAP(mask, 64);
2959 		u32 history = st->jmp_history_cnt;
2960 
2961 		if (env->log.level & BPF_LOG_LEVEL2)
2962 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2963 
2964 		if (last_idx < 0) {
2965 			/* we are at the entry into subprog, which
2966 			 * is expected for global funcs, but only if
2967 			 * requested precise registers are R1-R5
2968 			 * (which are global func's input arguments)
2969 			 */
2970 			if (st->curframe == 0 &&
2971 			    st->frame[0]->subprogno > 0 &&
2972 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
2973 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2974 				bitmap_from_u64(mask, reg_mask);
2975 				for_each_set_bit(i, mask, 32) {
2976 					reg = &st->frame[0]->regs[i];
2977 					if (reg->type != SCALAR_VALUE) {
2978 						reg_mask &= ~(1u << i);
2979 						continue;
2980 					}
2981 					reg->precise = true;
2982 				}
2983 				return 0;
2984 			}
2985 
2986 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2987 				st->frame[0]->subprogno, reg_mask, stack_mask);
2988 			WARN_ONCE(1, "verifier backtracking bug");
2989 			return -EFAULT;
2990 		}
2991 
2992 		for (i = last_idx;;) {
2993 			if (skip_first) {
2994 				err = 0;
2995 				skip_first = false;
2996 			} else {
2997 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2998 			}
2999 			if (err == -ENOTSUPP) {
3000 				mark_all_scalars_precise(env, st);
3001 				return 0;
3002 			} else if (err) {
3003 				return err;
3004 			}
3005 			if (!reg_mask && !stack_mask)
3006 				/* Found assignment(s) into tracked register in this state.
3007 				 * Since this state is already marked, just return.
3008 				 * Nothing to be tracked further in the parent state.
3009 				 */
3010 				return 0;
3011 			if (i == first_idx)
3012 				break;
3013 			i = get_prev_insn_idx(st, i, &history);
3014 			if (i >= env->prog->len) {
3015 				/* This can happen if backtracking reached insn 0
3016 				 * and there are still reg_mask or stack_mask
3017 				 * to backtrack.
3018 				 * It means the backtracking missed the spot where
3019 				 * particular register was initialized with a constant.
3020 				 */
3021 				verbose(env, "BUG backtracking idx %d\n", i);
3022 				WARN_ONCE(1, "verifier backtracking bug");
3023 				return -EFAULT;
3024 			}
3025 		}
3026 		st = st->parent;
3027 		if (!st)
3028 			break;
3029 
3030 		new_marks = false;
3031 		func = st->frame[frame];
3032 		bitmap_from_u64(mask, reg_mask);
3033 		for_each_set_bit(i, mask, 32) {
3034 			reg = &func->regs[i];
3035 			if (reg->type != SCALAR_VALUE) {
3036 				reg_mask &= ~(1u << i);
3037 				continue;
3038 			}
3039 			if (!reg->precise)
3040 				new_marks = true;
3041 			reg->precise = true;
3042 		}
3043 
3044 		bitmap_from_u64(mask, stack_mask);
3045 		for_each_set_bit(i, mask, 64) {
3046 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3047 				/* the sequence of instructions:
3048 				 * 2: (bf) r3 = r10
3049 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3050 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3051 				 * doesn't contain jmps. It's backtracked
3052 				 * as a single block.
3053 				 * During backtracking insn 3 is not recognized as
3054 				 * stack access, so at the end of backtracking
3055 				 * stack slot fp-8 is still marked in stack_mask.
3056 				 * However the parent state may not have accessed
3057 				 * fp-8 and it's "unallocated" stack space.
3058 				 * In such case fallback to conservative.
3059 				 */
3060 				mark_all_scalars_precise(env, st);
3061 				return 0;
3062 			}
3063 
3064 			if (!is_spilled_reg(&func->stack[i])) {
3065 				stack_mask &= ~(1ull << i);
3066 				continue;
3067 			}
3068 			reg = &func->stack[i].spilled_ptr;
3069 			if (reg->type != SCALAR_VALUE) {
3070 				stack_mask &= ~(1ull << i);
3071 				continue;
3072 			}
3073 			if (!reg->precise)
3074 				new_marks = true;
3075 			reg->precise = true;
3076 		}
3077 		if (env->log.level & BPF_LOG_LEVEL2) {
3078 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3079 				new_marks ? "didn't have" : "already had",
3080 				reg_mask, stack_mask);
3081 			print_verifier_state(env, func, true);
3082 		}
3083 
3084 		if (!reg_mask && !stack_mask)
3085 			break;
3086 		if (!new_marks)
3087 			break;
3088 
3089 		last_idx = st->last_insn_idx;
3090 		first_idx = st->first_insn_idx;
3091 	}
3092 	return 0;
3093 }
3094 
3095 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3096 {
3097 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3098 }
3099 
3100 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3101 {
3102 	return __mark_chain_precision(env, frame, regno, -1);
3103 }
3104 
3105 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3106 {
3107 	return __mark_chain_precision(env, frame, -1, spi);
3108 }
3109 
3110 static bool is_spillable_regtype(enum bpf_reg_type type)
3111 {
3112 	switch (base_type(type)) {
3113 	case PTR_TO_MAP_VALUE:
3114 	case PTR_TO_STACK:
3115 	case PTR_TO_CTX:
3116 	case PTR_TO_PACKET:
3117 	case PTR_TO_PACKET_META:
3118 	case PTR_TO_PACKET_END:
3119 	case PTR_TO_FLOW_KEYS:
3120 	case CONST_PTR_TO_MAP:
3121 	case PTR_TO_SOCKET:
3122 	case PTR_TO_SOCK_COMMON:
3123 	case PTR_TO_TCP_SOCK:
3124 	case PTR_TO_XDP_SOCK:
3125 	case PTR_TO_BTF_ID:
3126 	case PTR_TO_BUF:
3127 	case PTR_TO_MEM:
3128 	case PTR_TO_FUNC:
3129 	case PTR_TO_MAP_KEY:
3130 		return true;
3131 	default:
3132 		return false;
3133 	}
3134 }
3135 
3136 /* Does this register contain a constant zero? */
3137 static bool register_is_null(struct bpf_reg_state *reg)
3138 {
3139 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3140 }
3141 
3142 static bool register_is_const(struct bpf_reg_state *reg)
3143 {
3144 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3145 }
3146 
3147 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3148 {
3149 	return tnum_is_unknown(reg->var_off) &&
3150 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3151 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3152 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3153 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3154 }
3155 
3156 static bool register_is_bounded(struct bpf_reg_state *reg)
3157 {
3158 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3159 }
3160 
3161 static bool __is_pointer_value(bool allow_ptr_leaks,
3162 			       const struct bpf_reg_state *reg)
3163 {
3164 	if (allow_ptr_leaks)
3165 		return false;
3166 
3167 	return reg->type != SCALAR_VALUE;
3168 }
3169 
3170 static void save_register_state(struct bpf_func_state *state,
3171 				int spi, struct bpf_reg_state *reg,
3172 				int size)
3173 {
3174 	int i;
3175 
3176 	state->stack[spi].spilled_ptr = *reg;
3177 	if (size == BPF_REG_SIZE)
3178 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3179 
3180 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3181 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3182 
3183 	/* size < 8 bytes spill */
3184 	for (; i; i--)
3185 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3186 }
3187 
3188 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3189  * stack boundary and alignment are checked in check_mem_access()
3190  */
3191 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3192 				       /* stack frame we're writing to */
3193 				       struct bpf_func_state *state,
3194 				       int off, int size, int value_regno,
3195 				       int insn_idx)
3196 {
3197 	struct bpf_func_state *cur; /* state of the current function */
3198 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3199 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3200 	struct bpf_reg_state *reg = NULL;
3201 
3202 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3203 	if (err)
3204 		return err;
3205 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3206 	 * so it's aligned access and [off, off + size) are within stack limits
3207 	 */
3208 	if (!env->allow_ptr_leaks &&
3209 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3210 	    size != BPF_REG_SIZE) {
3211 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3212 		return -EACCES;
3213 	}
3214 
3215 	cur = env->cur_state->frame[env->cur_state->curframe];
3216 	if (value_regno >= 0)
3217 		reg = &cur->regs[value_regno];
3218 	if (!env->bypass_spec_v4) {
3219 		bool sanitize = reg && is_spillable_regtype(reg->type);
3220 
3221 		for (i = 0; i < size; i++) {
3222 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3223 				sanitize = true;
3224 				break;
3225 			}
3226 		}
3227 
3228 		if (sanitize)
3229 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3230 	}
3231 
3232 	mark_stack_slot_scratched(env, spi);
3233 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3234 	    !register_is_null(reg) && env->bpf_capable) {
3235 		if (dst_reg != BPF_REG_FP) {
3236 			/* The backtracking logic can only recognize explicit
3237 			 * stack slot address like [fp - 8]. Other spill of
3238 			 * scalar via different register has to be conservative.
3239 			 * Backtrack from here and mark all registers as precise
3240 			 * that contributed into 'reg' being a constant.
3241 			 */
3242 			err = mark_chain_precision(env, value_regno);
3243 			if (err)
3244 				return err;
3245 		}
3246 		save_register_state(state, spi, reg, size);
3247 	} else if (reg && is_spillable_regtype(reg->type)) {
3248 		/* register containing pointer is being spilled into stack */
3249 		if (size != BPF_REG_SIZE) {
3250 			verbose_linfo(env, insn_idx, "; ");
3251 			verbose(env, "invalid size of register spill\n");
3252 			return -EACCES;
3253 		}
3254 		if (state != cur && reg->type == PTR_TO_STACK) {
3255 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3256 			return -EINVAL;
3257 		}
3258 		save_register_state(state, spi, reg, size);
3259 	} else {
3260 		u8 type = STACK_MISC;
3261 
3262 		/* regular write of data into stack destroys any spilled ptr */
3263 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3264 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3265 		if (is_spilled_reg(&state->stack[spi]))
3266 			for (i = 0; i < BPF_REG_SIZE; i++)
3267 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3268 
3269 		/* only mark the slot as written if all 8 bytes were written
3270 		 * otherwise read propagation may incorrectly stop too soon
3271 		 * when stack slots are partially written.
3272 		 * This heuristic means that read propagation will be
3273 		 * conservative, since it will add reg_live_read marks
3274 		 * to stack slots all the way to first state when programs
3275 		 * writes+reads less than 8 bytes
3276 		 */
3277 		if (size == BPF_REG_SIZE)
3278 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3279 
3280 		/* when we zero initialize stack slots mark them as such */
3281 		if (reg && register_is_null(reg)) {
3282 			/* backtracking doesn't work for STACK_ZERO yet. */
3283 			err = mark_chain_precision(env, value_regno);
3284 			if (err)
3285 				return err;
3286 			type = STACK_ZERO;
3287 		}
3288 
3289 		/* Mark slots affected by this stack write. */
3290 		for (i = 0; i < size; i++)
3291 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3292 				type;
3293 	}
3294 	return 0;
3295 }
3296 
3297 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3298  * known to contain a variable offset.
3299  * This function checks whether the write is permitted and conservatively
3300  * tracks the effects of the write, considering that each stack slot in the
3301  * dynamic range is potentially written to.
3302  *
3303  * 'off' includes 'regno->off'.
3304  * 'value_regno' can be -1, meaning that an unknown value is being written to
3305  * the stack.
3306  *
3307  * Spilled pointers in range are not marked as written because we don't know
3308  * what's going to be actually written. This means that read propagation for
3309  * future reads cannot be terminated by this write.
3310  *
3311  * For privileged programs, uninitialized stack slots are considered
3312  * initialized by this write (even though we don't know exactly what offsets
3313  * are going to be written to). The idea is that we don't want the verifier to
3314  * reject future reads that access slots written to through variable offsets.
3315  */
3316 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3317 				     /* func where register points to */
3318 				     struct bpf_func_state *state,
3319 				     int ptr_regno, int off, int size,
3320 				     int value_regno, int insn_idx)
3321 {
3322 	struct bpf_func_state *cur; /* state of the current function */
3323 	int min_off, max_off;
3324 	int i, err;
3325 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3326 	bool writing_zero = false;
3327 	/* set if the fact that we're writing a zero is used to let any
3328 	 * stack slots remain STACK_ZERO
3329 	 */
3330 	bool zero_used = false;
3331 
3332 	cur = env->cur_state->frame[env->cur_state->curframe];
3333 	ptr_reg = &cur->regs[ptr_regno];
3334 	min_off = ptr_reg->smin_value + off;
3335 	max_off = ptr_reg->smax_value + off + size;
3336 	if (value_regno >= 0)
3337 		value_reg = &cur->regs[value_regno];
3338 	if (value_reg && register_is_null(value_reg))
3339 		writing_zero = true;
3340 
3341 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3342 	if (err)
3343 		return err;
3344 
3345 
3346 	/* Variable offset writes destroy any spilled pointers in range. */
3347 	for (i = min_off; i < max_off; i++) {
3348 		u8 new_type, *stype;
3349 		int slot, spi;
3350 
3351 		slot = -i - 1;
3352 		spi = slot / BPF_REG_SIZE;
3353 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3354 		mark_stack_slot_scratched(env, spi);
3355 
3356 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3357 			/* Reject the write if range we may write to has not
3358 			 * been initialized beforehand. If we didn't reject
3359 			 * here, the ptr status would be erased below (even
3360 			 * though not all slots are actually overwritten),
3361 			 * possibly opening the door to leaks.
3362 			 *
3363 			 * We do however catch STACK_INVALID case below, and
3364 			 * only allow reading possibly uninitialized memory
3365 			 * later for CAP_PERFMON, as the write may not happen to
3366 			 * that slot.
3367 			 */
3368 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3369 				insn_idx, i);
3370 			return -EINVAL;
3371 		}
3372 
3373 		/* Erase all spilled pointers. */
3374 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3375 
3376 		/* Update the slot type. */
3377 		new_type = STACK_MISC;
3378 		if (writing_zero && *stype == STACK_ZERO) {
3379 			new_type = STACK_ZERO;
3380 			zero_used = true;
3381 		}
3382 		/* If the slot is STACK_INVALID, we check whether it's OK to
3383 		 * pretend that it will be initialized by this write. The slot
3384 		 * might not actually be written to, and so if we mark it as
3385 		 * initialized future reads might leak uninitialized memory.
3386 		 * For privileged programs, we will accept such reads to slots
3387 		 * that may or may not be written because, if we're reject
3388 		 * them, the error would be too confusing.
3389 		 */
3390 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3391 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3392 					insn_idx, i);
3393 			return -EINVAL;
3394 		}
3395 		*stype = new_type;
3396 	}
3397 	if (zero_used) {
3398 		/* backtracking doesn't work for STACK_ZERO yet. */
3399 		err = mark_chain_precision(env, value_regno);
3400 		if (err)
3401 			return err;
3402 	}
3403 	return 0;
3404 }
3405 
3406 /* When register 'dst_regno' is assigned some values from stack[min_off,
3407  * max_off), we set the register's type according to the types of the
3408  * respective stack slots. If all the stack values are known to be zeros, then
3409  * so is the destination reg. Otherwise, the register is considered to be
3410  * SCALAR. This function does not deal with register filling; the caller must
3411  * ensure that all spilled registers in the stack range have been marked as
3412  * read.
3413  */
3414 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3415 				/* func where src register points to */
3416 				struct bpf_func_state *ptr_state,
3417 				int min_off, int max_off, int dst_regno)
3418 {
3419 	struct bpf_verifier_state *vstate = env->cur_state;
3420 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3421 	int i, slot, spi;
3422 	u8 *stype;
3423 	int zeros = 0;
3424 
3425 	for (i = min_off; i < max_off; i++) {
3426 		slot = -i - 1;
3427 		spi = slot / BPF_REG_SIZE;
3428 		stype = ptr_state->stack[spi].slot_type;
3429 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3430 			break;
3431 		zeros++;
3432 	}
3433 	if (zeros == max_off - min_off) {
3434 		/* any access_size read into register is zero extended,
3435 		 * so the whole register == const_zero
3436 		 */
3437 		__mark_reg_const_zero(&state->regs[dst_regno]);
3438 		/* backtracking doesn't support STACK_ZERO yet,
3439 		 * so mark it precise here, so that later
3440 		 * backtracking can stop here.
3441 		 * Backtracking may not need this if this register
3442 		 * doesn't participate in pointer adjustment.
3443 		 * Forward propagation of precise flag is not
3444 		 * necessary either. This mark is only to stop
3445 		 * backtracking. Any register that contributed
3446 		 * to const 0 was marked precise before spill.
3447 		 */
3448 		state->regs[dst_regno].precise = true;
3449 	} else {
3450 		/* have read misc data from the stack */
3451 		mark_reg_unknown(env, state->regs, dst_regno);
3452 	}
3453 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3454 }
3455 
3456 /* Read the stack at 'off' and put the results into the register indicated by
3457  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3458  * spilled reg.
3459  *
3460  * 'dst_regno' can be -1, meaning that the read value is not going to a
3461  * register.
3462  *
3463  * The access is assumed to be within the current stack bounds.
3464  */
3465 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3466 				      /* func where src register points to */
3467 				      struct bpf_func_state *reg_state,
3468 				      int off, int size, int dst_regno)
3469 {
3470 	struct bpf_verifier_state *vstate = env->cur_state;
3471 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3472 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3473 	struct bpf_reg_state *reg;
3474 	u8 *stype, type;
3475 
3476 	stype = reg_state->stack[spi].slot_type;
3477 	reg = &reg_state->stack[spi].spilled_ptr;
3478 
3479 	if (is_spilled_reg(&reg_state->stack[spi])) {
3480 		u8 spill_size = 1;
3481 
3482 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3483 			spill_size++;
3484 
3485 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3486 			if (reg->type != SCALAR_VALUE) {
3487 				verbose_linfo(env, env->insn_idx, "; ");
3488 				verbose(env, "invalid size of register fill\n");
3489 				return -EACCES;
3490 			}
3491 
3492 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3493 			if (dst_regno < 0)
3494 				return 0;
3495 
3496 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3497 				/* The earlier check_reg_arg() has decided the
3498 				 * subreg_def for this insn.  Save it first.
3499 				 */
3500 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3501 
3502 				state->regs[dst_regno] = *reg;
3503 				state->regs[dst_regno].subreg_def = subreg_def;
3504 			} else {
3505 				for (i = 0; i < size; i++) {
3506 					type = stype[(slot - i) % BPF_REG_SIZE];
3507 					if (type == STACK_SPILL)
3508 						continue;
3509 					if (type == STACK_MISC)
3510 						continue;
3511 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3512 						off, i, size);
3513 					return -EACCES;
3514 				}
3515 				mark_reg_unknown(env, state->regs, dst_regno);
3516 			}
3517 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3518 			return 0;
3519 		}
3520 
3521 		if (dst_regno >= 0) {
3522 			/* restore register state from stack */
3523 			state->regs[dst_regno] = *reg;
3524 			/* mark reg as written since spilled pointer state likely
3525 			 * has its liveness marks cleared by is_state_visited()
3526 			 * which resets stack/reg liveness for state transitions
3527 			 */
3528 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3529 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3530 			/* If dst_regno==-1, the caller is asking us whether
3531 			 * it is acceptable to use this value as a SCALAR_VALUE
3532 			 * (e.g. for XADD).
3533 			 * We must not allow unprivileged callers to do that
3534 			 * with spilled pointers.
3535 			 */
3536 			verbose(env, "leaking pointer from stack off %d\n",
3537 				off);
3538 			return -EACCES;
3539 		}
3540 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3541 	} else {
3542 		for (i = 0; i < size; i++) {
3543 			type = stype[(slot - i) % BPF_REG_SIZE];
3544 			if (type == STACK_MISC)
3545 				continue;
3546 			if (type == STACK_ZERO)
3547 				continue;
3548 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3549 				off, i, size);
3550 			return -EACCES;
3551 		}
3552 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3553 		if (dst_regno >= 0)
3554 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3555 	}
3556 	return 0;
3557 }
3558 
3559 enum bpf_access_src {
3560 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3561 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3562 };
3563 
3564 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3565 					 int regno, int off, int access_size,
3566 					 bool zero_size_allowed,
3567 					 enum bpf_access_src type,
3568 					 struct bpf_call_arg_meta *meta);
3569 
3570 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3571 {
3572 	return cur_regs(env) + regno;
3573 }
3574 
3575 /* Read the stack at 'ptr_regno + off' and put the result into the register
3576  * 'dst_regno'.
3577  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3578  * but not its variable offset.
3579  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3580  *
3581  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3582  * filling registers (i.e. reads of spilled register cannot be detected when
3583  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3584  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3585  * offset; for a fixed offset check_stack_read_fixed_off should be used
3586  * instead.
3587  */
3588 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3589 				    int ptr_regno, int off, int size, int dst_regno)
3590 {
3591 	/* The state of the source register. */
3592 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3593 	struct bpf_func_state *ptr_state = func(env, reg);
3594 	int err;
3595 	int min_off, max_off;
3596 
3597 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3598 	 */
3599 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3600 					    false, ACCESS_DIRECT, NULL);
3601 	if (err)
3602 		return err;
3603 
3604 	min_off = reg->smin_value + off;
3605 	max_off = reg->smax_value + off;
3606 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3607 	return 0;
3608 }
3609 
3610 /* check_stack_read dispatches to check_stack_read_fixed_off or
3611  * check_stack_read_var_off.
3612  *
3613  * The caller must ensure that the offset falls within the allocated stack
3614  * bounds.
3615  *
3616  * 'dst_regno' is a register which will receive the value from the stack. It
3617  * can be -1, meaning that the read value is not going to a register.
3618  */
3619 static int check_stack_read(struct bpf_verifier_env *env,
3620 			    int ptr_regno, int off, int size,
3621 			    int dst_regno)
3622 {
3623 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3624 	struct bpf_func_state *state = func(env, reg);
3625 	int err;
3626 	/* Some accesses are only permitted with a static offset. */
3627 	bool var_off = !tnum_is_const(reg->var_off);
3628 
3629 	/* The offset is required to be static when reads don't go to a
3630 	 * register, in order to not leak pointers (see
3631 	 * check_stack_read_fixed_off).
3632 	 */
3633 	if (dst_regno < 0 && var_off) {
3634 		char tn_buf[48];
3635 
3636 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3637 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3638 			tn_buf, off, size);
3639 		return -EACCES;
3640 	}
3641 	/* Variable offset is prohibited for unprivileged mode for simplicity
3642 	 * since it requires corresponding support in Spectre masking for stack
3643 	 * ALU. See also retrieve_ptr_limit().
3644 	 */
3645 	if (!env->bypass_spec_v1 && var_off) {
3646 		char tn_buf[48];
3647 
3648 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3649 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3650 				ptr_regno, tn_buf);
3651 		return -EACCES;
3652 	}
3653 
3654 	if (!var_off) {
3655 		off += reg->var_off.value;
3656 		err = check_stack_read_fixed_off(env, state, off, size,
3657 						 dst_regno);
3658 	} else {
3659 		/* Variable offset stack reads need more conservative handling
3660 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3661 		 * branch.
3662 		 */
3663 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3664 					       dst_regno);
3665 	}
3666 	return err;
3667 }
3668 
3669 
3670 /* check_stack_write dispatches to check_stack_write_fixed_off or
3671  * check_stack_write_var_off.
3672  *
3673  * 'ptr_regno' is the register used as a pointer into the stack.
3674  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3675  * 'value_regno' is the register whose value we're writing to the stack. It can
3676  * be -1, meaning that we're not writing from a register.
3677  *
3678  * The caller must ensure that the offset falls within the maximum stack size.
3679  */
3680 static int check_stack_write(struct bpf_verifier_env *env,
3681 			     int ptr_regno, int off, int size,
3682 			     int value_regno, int insn_idx)
3683 {
3684 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3685 	struct bpf_func_state *state = func(env, reg);
3686 	int err;
3687 
3688 	if (tnum_is_const(reg->var_off)) {
3689 		off += reg->var_off.value;
3690 		err = check_stack_write_fixed_off(env, state, off, size,
3691 						  value_regno, insn_idx);
3692 	} else {
3693 		/* Variable offset stack reads need more conservative handling
3694 		 * than fixed offset ones.
3695 		 */
3696 		err = check_stack_write_var_off(env, state,
3697 						ptr_regno, off, size,
3698 						value_regno, insn_idx);
3699 	}
3700 	return err;
3701 }
3702 
3703 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3704 				 int off, int size, enum bpf_access_type type)
3705 {
3706 	struct bpf_reg_state *regs = cur_regs(env);
3707 	struct bpf_map *map = regs[regno].map_ptr;
3708 	u32 cap = bpf_map_flags_to_cap(map);
3709 
3710 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3711 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3712 			map->value_size, off, size);
3713 		return -EACCES;
3714 	}
3715 
3716 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3717 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3718 			map->value_size, off, size);
3719 		return -EACCES;
3720 	}
3721 
3722 	return 0;
3723 }
3724 
3725 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3726 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3727 			      int off, int size, u32 mem_size,
3728 			      bool zero_size_allowed)
3729 {
3730 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3731 	struct bpf_reg_state *reg;
3732 
3733 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3734 		return 0;
3735 
3736 	reg = &cur_regs(env)[regno];
3737 	switch (reg->type) {
3738 	case PTR_TO_MAP_KEY:
3739 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3740 			mem_size, off, size);
3741 		break;
3742 	case PTR_TO_MAP_VALUE:
3743 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3744 			mem_size, off, size);
3745 		break;
3746 	case PTR_TO_PACKET:
3747 	case PTR_TO_PACKET_META:
3748 	case PTR_TO_PACKET_END:
3749 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3750 			off, size, regno, reg->id, off, mem_size);
3751 		break;
3752 	case PTR_TO_MEM:
3753 	default:
3754 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3755 			mem_size, off, size);
3756 	}
3757 
3758 	return -EACCES;
3759 }
3760 
3761 /* check read/write into a memory region with possible variable offset */
3762 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3763 				   int off, int size, u32 mem_size,
3764 				   bool zero_size_allowed)
3765 {
3766 	struct bpf_verifier_state *vstate = env->cur_state;
3767 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3768 	struct bpf_reg_state *reg = &state->regs[regno];
3769 	int err;
3770 
3771 	/* We may have adjusted the register pointing to memory region, so we
3772 	 * need to try adding each of min_value and max_value to off
3773 	 * to make sure our theoretical access will be safe.
3774 	 *
3775 	 * The minimum value is only important with signed
3776 	 * comparisons where we can't assume the floor of a
3777 	 * value is 0.  If we are using signed variables for our
3778 	 * index'es we need to make sure that whatever we use
3779 	 * will have a set floor within our range.
3780 	 */
3781 	if (reg->smin_value < 0 &&
3782 	    (reg->smin_value == S64_MIN ||
3783 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3784 	      reg->smin_value + off < 0)) {
3785 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3786 			regno);
3787 		return -EACCES;
3788 	}
3789 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3790 				 mem_size, zero_size_allowed);
3791 	if (err) {
3792 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3793 			regno);
3794 		return err;
3795 	}
3796 
3797 	/* If we haven't set a max value then we need to bail since we can't be
3798 	 * sure we won't do bad things.
3799 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3800 	 */
3801 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3802 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3803 			regno);
3804 		return -EACCES;
3805 	}
3806 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3807 				 mem_size, zero_size_allowed);
3808 	if (err) {
3809 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3810 			regno);
3811 		return err;
3812 	}
3813 
3814 	return 0;
3815 }
3816 
3817 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3818 			       const struct bpf_reg_state *reg, int regno,
3819 			       bool fixed_off_ok)
3820 {
3821 	/* Access to this pointer-typed register or passing it to a helper
3822 	 * is only allowed in its original, unmodified form.
3823 	 */
3824 
3825 	if (reg->off < 0) {
3826 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3827 			reg_type_str(env, reg->type), regno, reg->off);
3828 		return -EACCES;
3829 	}
3830 
3831 	if (!fixed_off_ok && reg->off) {
3832 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3833 			reg_type_str(env, reg->type), regno, reg->off);
3834 		return -EACCES;
3835 	}
3836 
3837 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3838 		char tn_buf[48];
3839 
3840 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3841 		verbose(env, "variable %s access var_off=%s disallowed\n",
3842 			reg_type_str(env, reg->type), tn_buf);
3843 		return -EACCES;
3844 	}
3845 
3846 	return 0;
3847 }
3848 
3849 int check_ptr_off_reg(struct bpf_verifier_env *env,
3850 		      const struct bpf_reg_state *reg, int regno)
3851 {
3852 	return __check_ptr_off_reg(env, reg, regno, false);
3853 }
3854 
3855 static int map_kptr_match_type(struct bpf_verifier_env *env,
3856 			       struct btf_field *kptr_field,
3857 			       struct bpf_reg_state *reg, u32 regno)
3858 {
3859 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3860 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3861 	const char *reg_name = "";
3862 
3863 	/* Only unreferenced case accepts untrusted pointers */
3864 	if (kptr_field->type == BPF_KPTR_UNREF)
3865 		perm_flags |= PTR_UNTRUSTED;
3866 
3867 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3868 		goto bad_type;
3869 
3870 	if (!btf_is_kernel(reg->btf)) {
3871 		verbose(env, "R%d must point to kernel BTF\n", regno);
3872 		return -EINVAL;
3873 	}
3874 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3875 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3876 
3877 	/* For ref_ptr case, release function check should ensure we get one
3878 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3879 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3880 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3881 	 * reg->off and reg->ref_obj_id are not needed here.
3882 	 */
3883 	if (__check_ptr_off_reg(env, reg, regno, true))
3884 		return -EACCES;
3885 
3886 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3887 	 * we also need to take into account the reg->off.
3888 	 *
3889 	 * We want to support cases like:
3890 	 *
3891 	 * struct foo {
3892 	 *         struct bar br;
3893 	 *         struct baz bz;
3894 	 * };
3895 	 *
3896 	 * struct foo *v;
3897 	 * v = func();	      // PTR_TO_BTF_ID
3898 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3899 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3900 	 *                    // first member type of struct after comparison fails
3901 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3902 	 *                    // to match type
3903 	 *
3904 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3905 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3906 	 * the struct to match type against first member of struct, i.e. reject
3907 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3908 	 * strict mode to true for type match.
3909 	 */
3910 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3911 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3912 				  kptr_field->type == BPF_KPTR_REF))
3913 		goto bad_type;
3914 	return 0;
3915 bad_type:
3916 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3917 		reg_type_str(env, reg->type), reg_name);
3918 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3919 	if (kptr_field->type == BPF_KPTR_UNREF)
3920 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3921 			targ_name);
3922 	else
3923 		verbose(env, "\n");
3924 	return -EINVAL;
3925 }
3926 
3927 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3928 				 int value_regno, int insn_idx,
3929 				 struct btf_field *kptr_field)
3930 {
3931 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3932 	int class = BPF_CLASS(insn->code);
3933 	struct bpf_reg_state *val_reg;
3934 
3935 	/* Things we already checked for in check_map_access and caller:
3936 	 *  - Reject cases where variable offset may touch kptr
3937 	 *  - size of access (must be BPF_DW)
3938 	 *  - tnum_is_const(reg->var_off)
3939 	 *  - kptr_field->offset == off + reg->var_off.value
3940 	 */
3941 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3942 	if (BPF_MODE(insn->code) != BPF_MEM) {
3943 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3944 		return -EACCES;
3945 	}
3946 
3947 	/* We only allow loading referenced kptr, since it will be marked as
3948 	 * untrusted, similar to unreferenced kptr.
3949 	 */
3950 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
3951 		verbose(env, "store to referenced kptr disallowed\n");
3952 		return -EACCES;
3953 	}
3954 
3955 	if (class == BPF_LDX) {
3956 		val_reg = reg_state(env, value_regno);
3957 		/* We can simply mark the value_regno receiving the pointer
3958 		 * value from map as PTR_TO_BTF_ID, with the correct type.
3959 		 */
3960 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
3961 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3962 		/* For mark_ptr_or_null_reg */
3963 		val_reg->id = ++env->id_gen;
3964 	} else if (class == BPF_STX) {
3965 		val_reg = reg_state(env, value_regno);
3966 		if (!register_is_null(val_reg) &&
3967 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
3968 			return -EACCES;
3969 	} else if (class == BPF_ST) {
3970 		if (insn->imm) {
3971 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3972 				kptr_field->offset);
3973 			return -EACCES;
3974 		}
3975 	} else {
3976 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3977 		return -EACCES;
3978 	}
3979 	return 0;
3980 }
3981 
3982 /* check read/write into a map element with possible variable offset */
3983 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3984 			    int off, int size, bool zero_size_allowed,
3985 			    enum bpf_access_src src)
3986 {
3987 	struct bpf_verifier_state *vstate = env->cur_state;
3988 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3989 	struct bpf_reg_state *reg = &state->regs[regno];
3990 	struct bpf_map *map = reg->map_ptr;
3991 	struct btf_record *rec;
3992 	int err, i;
3993 
3994 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3995 				      zero_size_allowed);
3996 	if (err)
3997 		return err;
3998 
3999 	if (IS_ERR_OR_NULL(map->record))
4000 		return 0;
4001 	rec = map->record;
4002 	for (i = 0; i < rec->cnt; i++) {
4003 		struct btf_field *field = &rec->fields[i];
4004 		u32 p = field->offset;
4005 
4006 		/* If any part of a field  can be touched by load/store, reject
4007 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4008 		 * it is sufficient to check x1 < y2 && y1 < x2.
4009 		 */
4010 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4011 		    p < reg->umax_value + off + size) {
4012 			switch (field->type) {
4013 			case BPF_KPTR_UNREF:
4014 			case BPF_KPTR_REF:
4015 				if (src != ACCESS_DIRECT) {
4016 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4017 					return -EACCES;
4018 				}
4019 				if (!tnum_is_const(reg->var_off)) {
4020 					verbose(env, "kptr access cannot have variable offset\n");
4021 					return -EACCES;
4022 				}
4023 				if (p != off + reg->var_off.value) {
4024 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4025 						p, off + reg->var_off.value);
4026 					return -EACCES;
4027 				}
4028 				if (size != bpf_size_to_bytes(BPF_DW)) {
4029 					verbose(env, "kptr access size must be BPF_DW\n");
4030 					return -EACCES;
4031 				}
4032 				break;
4033 			default:
4034 				verbose(env, "%s cannot be accessed directly by load/store\n",
4035 					btf_field_type_name(field->type));
4036 				return -EACCES;
4037 			}
4038 		}
4039 	}
4040 	return 0;
4041 }
4042 
4043 #define MAX_PACKET_OFF 0xffff
4044 
4045 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4046 				       const struct bpf_call_arg_meta *meta,
4047 				       enum bpf_access_type t)
4048 {
4049 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4050 
4051 	switch (prog_type) {
4052 	/* Program types only with direct read access go here! */
4053 	case BPF_PROG_TYPE_LWT_IN:
4054 	case BPF_PROG_TYPE_LWT_OUT:
4055 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4056 	case BPF_PROG_TYPE_SK_REUSEPORT:
4057 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4058 	case BPF_PROG_TYPE_CGROUP_SKB:
4059 		if (t == BPF_WRITE)
4060 			return false;
4061 		fallthrough;
4062 
4063 	/* Program types with direct read + write access go here! */
4064 	case BPF_PROG_TYPE_SCHED_CLS:
4065 	case BPF_PROG_TYPE_SCHED_ACT:
4066 	case BPF_PROG_TYPE_XDP:
4067 	case BPF_PROG_TYPE_LWT_XMIT:
4068 	case BPF_PROG_TYPE_SK_SKB:
4069 	case BPF_PROG_TYPE_SK_MSG:
4070 		if (meta)
4071 			return meta->pkt_access;
4072 
4073 		env->seen_direct_write = true;
4074 		return true;
4075 
4076 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4077 		if (t == BPF_WRITE)
4078 			env->seen_direct_write = true;
4079 
4080 		return true;
4081 
4082 	default:
4083 		return false;
4084 	}
4085 }
4086 
4087 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4088 			       int size, bool zero_size_allowed)
4089 {
4090 	struct bpf_reg_state *regs = cur_regs(env);
4091 	struct bpf_reg_state *reg = &regs[regno];
4092 	int err;
4093 
4094 	/* We may have added a variable offset to the packet pointer; but any
4095 	 * reg->range we have comes after that.  We are only checking the fixed
4096 	 * offset.
4097 	 */
4098 
4099 	/* We don't allow negative numbers, because we aren't tracking enough
4100 	 * detail to prove they're safe.
4101 	 */
4102 	if (reg->smin_value < 0) {
4103 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4104 			regno);
4105 		return -EACCES;
4106 	}
4107 
4108 	err = reg->range < 0 ? -EINVAL :
4109 	      __check_mem_access(env, regno, off, size, reg->range,
4110 				 zero_size_allowed);
4111 	if (err) {
4112 		verbose(env, "R%d offset is outside of the packet\n", regno);
4113 		return err;
4114 	}
4115 
4116 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4117 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4118 	 * otherwise find_good_pkt_pointers would have refused to set range info
4119 	 * that __check_mem_access would have rejected this pkt access.
4120 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4121 	 */
4122 	env->prog->aux->max_pkt_offset =
4123 		max_t(u32, env->prog->aux->max_pkt_offset,
4124 		      off + reg->umax_value + size - 1);
4125 
4126 	return err;
4127 }
4128 
4129 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4130 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4131 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4132 			    struct btf **btf, u32 *btf_id)
4133 {
4134 	struct bpf_insn_access_aux info = {
4135 		.reg_type = *reg_type,
4136 		.log = &env->log,
4137 	};
4138 
4139 	if (env->ops->is_valid_access &&
4140 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4141 		/* A non zero info.ctx_field_size indicates that this field is a
4142 		 * candidate for later verifier transformation to load the whole
4143 		 * field and then apply a mask when accessed with a narrower
4144 		 * access than actual ctx access size. A zero info.ctx_field_size
4145 		 * will only allow for whole field access and rejects any other
4146 		 * type of narrower access.
4147 		 */
4148 		*reg_type = info.reg_type;
4149 
4150 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4151 			*btf = info.btf;
4152 			*btf_id = info.btf_id;
4153 		} else {
4154 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4155 		}
4156 		/* remember the offset of last byte accessed in ctx */
4157 		if (env->prog->aux->max_ctx_offset < off + size)
4158 			env->prog->aux->max_ctx_offset = off + size;
4159 		return 0;
4160 	}
4161 
4162 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4163 	return -EACCES;
4164 }
4165 
4166 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4167 				  int size)
4168 {
4169 	if (size < 0 || off < 0 ||
4170 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4171 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4172 			off, size);
4173 		return -EACCES;
4174 	}
4175 	return 0;
4176 }
4177 
4178 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4179 			     u32 regno, int off, int size,
4180 			     enum bpf_access_type t)
4181 {
4182 	struct bpf_reg_state *regs = cur_regs(env);
4183 	struct bpf_reg_state *reg = &regs[regno];
4184 	struct bpf_insn_access_aux info = {};
4185 	bool valid;
4186 
4187 	if (reg->smin_value < 0) {
4188 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4189 			regno);
4190 		return -EACCES;
4191 	}
4192 
4193 	switch (reg->type) {
4194 	case PTR_TO_SOCK_COMMON:
4195 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4196 		break;
4197 	case PTR_TO_SOCKET:
4198 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4199 		break;
4200 	case PTR_TO_TCP_SOCK:
4201 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4202 		break;
4203 	case PTR_TO_XDP_SOCK:
4204 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4205 		break;
4206 	default:
4207 		valid = false;
4208 	}
4209 
4210 
4211 	if (valid) {
4212 		env->insn_aux_data[insn_idx].ctx_field_size =
4213 			info.ctx_field_size;
4214 		return 0;
4215 	}
4216 
4217 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4218 		regno, reg_type_str(env, reg->type), off, size);
4219 
4220 	return -EACCES;
4221 }
4222 
4223 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4224 {
4225 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4226 }
4227 
4228 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4229 {
4230 	const struct bpf_reg_state *reg = reg_state(env, regno);
4231 
4232 	return reg->type == PTR_TO_CTX;
4233 }
4234 
4235 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4236 {
4237 	const struct bpf_reg_state *reg = reg_state(env, regno);
4238 
4239 	return type_is_sk_pointer(reg->type);
4240 }
4241 
4242 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4243 {
4244 	const struct bpf_reg_state *reg = reg_state(env, regno);
4245 
4246 	return type_is_pkt_pointer(reg->type);
4247 }
4248 
4249 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4250 {
4251 	const struct bpf_reg_state *reg = reg_state(env, regno);
4252 
4253 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4254 	return reg->type == PTR_TO_FLOW_KEYS;
4255 }
4256 
4257 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4258 				   const struct bpf_reg_state *reg,
4259 				   int off, int size, bool strict)
4260 {
4261 	struct tnum reg_off;
4262 	int ip_align;
4263 
4264 	/* Byte size accesses are always allowed. */
4265 	if (!strict || size == 1)
4266 		return 0;
4267 
4268 	/* For platforms that do not have a Kconfig enabling
4269 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4270 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4271 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4272 	 * to this code only in strict mode where we want to emulate
4273 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4274 	 * unconditional IP align value of '2'.
4275 	 */
4276 	ip_align = 2;
4277 
4278 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4279 	if (!tnum_is_aligned(reg_off, size)) {
4280 		char tn_buf[48];
4281 
4282 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4283 		verbose(env,
4284 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4285 			ip_align, tn_buf, reg->off, off, size);
4286 		return -EACCES;
4287 	}
4288 
4289 	return 0;
4290 }
4291 
4292 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4293 				       const struct bpf_reg_state *reg,
4294 				       const char *pointer_desc,
4295 				       int off, int size, bool strict)
4296 {
4297 	struct tnum reg_off;
4298 
4299 	/* Byte size accesses are always allowed. */
4300 	if (!strict || size == 1)
4301 		return 0;
4302 
4303 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4304 	if (!tnum_is_aligned(reg_off, size)) {
4305 		char tn_buf[48];
4306 
4307 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4308 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4309 			pointer_desc, tn_buf, reg->off, off, size);
4310 		return -EACCES;
4311 	}
4312 
4313 	return 0;
4314 }
4315 
4316 static int check_ptr_alignment(struct bpf_verifier_env *env,
4317 			       const struct bpf_reg_state *reg, int off,
4318 			       int size, bool strict_alignment_once)
4319 {
4320 	bool strict = env->strict_alignment || strict_alignment_once;
4321 	const char *pointer_desc = "";
4322 
4323 	switch (reg->type) {
4324 	case PTR_TO_PACKET:
4325 	case PTR_TO_PACKET_META:
4326 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4327 		 * right in front, treat it the very same way.
4328 		 */
4329 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4330 	case PTR_TO_FLOW_KEYS:
4331 		pointer_desc = "flow keys ";
4332 		break;
4333 	case PTR_TO_MAP_KEY:
4334 		pointer_desc = "key ";
4335 		break;
4336 	case PTR_TO_MAP_VALUE:
4337 		pointer_desc = "value ";
4338 		break;
4339 	case PTR_TO_CTX:
4340 		pointer_desc = "context ";
4341 		break;
4342 	case PTR_TO_STACK:
4343 		pointer_desc = "stack ";
4344 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4345 		 * and check_stack_read_fixed_off() relies on stack accesses being
4346 		 * aligned.
4347 		 */
4348 		strict = true;
4349 		break;
4350 	case PTR_TO_SOCKET:
4351 		pointer_desc = "sock ";
4352 		break;
4353 	case PTR_TO_SOCK_COMMON:
4354 		pointer_desc = "sock_common ";
4355 		break;
4356 	case PTR_TO_TCP_SOCK:
4357 		pointer_desc = "tcp_sock ";
4358 		break;
4359 	case PTR_TO_XDP_SOCK:
4360 		pointer_desc = "xdp_sock ";
4361 		break;
4362 	default:
4363 		break;
4364 	}
4365 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4366 					   strict);
4367 }
4368 
4369 static int update_stack_depth(struct bpf_verifier_env *env,
4370 			      const struct bpf_func_state *func,
4371 			      int off)
4372 {
4373 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4374 
4375 	if (stack >= -off)
4376 		return 0;
4377 
4378 	/* update known max for given subprogram */
4379 	env->subprog_info[func->subprogno].stack_depth = -off;
4380 	return 0;
4381 }
4382 
4383 /* starting from main bpf function walk all instructions of the function
4384  * and recursively walk all callees that given function can call.
4385  * Ignore jump and exit insns.
4386  * Since recursion is prevented by check_cfg() this algorithm
4387  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4388  */
4389 static int check_max_stack_depth(struct bpf_verifier_env *env)
4390 {
4391 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4392 	struct bpf_subprog_info *subprog = env->subprog_info;
4393 	struct bpf_insn *insn = env->prog->insnsi;
4394 	bool tail_call_reachable = false;
4395 	int ret_insn[MAX_CALL_FRAMES];
4396 	int ret_prog[MAX_CALL_FRAMES];
4397 	int j;
4398 
4399 process_func:
4400 	/* protect against potential stack overflow that might happen when
4401 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4402 	 * depth for such case down to 256 so that the worst case scenario
4403 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4404 	 * 8k).
4405 	 *
4406 	 * To get the idea what might happen, see an example:
4407 	 * func1 -> sub rsp, 128
4408 	 *  subfunc1 -> sub rsp, 256
4409 	 *  tailcall1 -> add rsp, 256
4410 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4411 	 *   subfunc2 -> sub rsp, 64
4412 	 *   subfunc22 -> sub rsp, 128
4413 	 *   tailcall2 -> add rsp, 128
4414 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4415 	 *
4416 	 * tailcall will unwind the current stack frame but it will not get rid
4417 	 * of caller's stack as shown on the example above.
4418 	 */
4419 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4420 		verbose(env,
4421 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4422 			depth);
4423 		return -EACCES;
4424 	}
4425 	/* round up to 32-bytes, since this is granularity
4426 	 * of interpreter stack size
4427 	 */
4428 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4429 	if (depth > MAX_BPF_STACK) {
4430 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4431 			frame + 1, depth);
4432 		return -EACCES;
4433 	}
4434 continue_func:
4435 	subprog_end = subprog[idx + 1].start;
4436 	for (; i < subprog_end; i++) {
4437 		int next_insn;
4438 
4439 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4440 			continue;
4441 		/* remember insn and function to return to */
4442 		ret_insn[frame] = i + 1;
4443 		ret_prog[frame] = idx;
4444 
4445 		/* find the callee */
4446 		next_insn = i + insn[i].imm + 1;
4447 		idx = find_subprog(env, next_insn);
4448 		if (idx < 0) {
4449 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4450 				  next_insn);
4451 			return -EFAULT;
4452 		}
4453 		if (subprog[idx].is_async_cb) {
4454 			if (subprog[idx].has_tail_call) {
4455 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4456 				return -EFAULT;
4457 			}
4458 			 /* async callbacks don't increase bpf prog stack size */
4459 			continue;
4460 		}
4461 		i = next_insn;
4462 
4463 		if (subprog[idx].has_tail_call)
4464 			tail_call_reachable = true;
4465 
4466 		frame++;
4467 		if (frame >= MAX_CALL_FRAMES) {
4468 			verbose(env, "the call stack of %d frames is too deep !\n",
4469 				frame);
4470 			return -E2BIG;
4471 		}
4472 		goto process_func;
4473 	}
4474 	/* if tail call got detected across bpf2bpf calls then mark each of the
4475 	 * currently present subprog frames as tail call reachable subprogs;
4476 	 * this info will be utilized by JIT so that we will be preserving the
4477 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4478 	 */
4479 	if (tail_call_reachable)
4480 		for (j = 0; j < frame; j++)
4481 			subprog[ret_prog[j]].tail_call_reachable = true;
4482 	if (subprog[0].tail_call_reachable)
4483 		env->prog->aux->tail_call_reachable = true;
4484 
4485 	/* end of for() loop means the last insn of the 'subprog'
4486 	 * was reached. Doesn't matter whether it was JA or EXIT
4487 	 */
4488 	if (frame == 0)
4489 		return 0;
4490 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4491 	frame--;
4492 	i = ret_insn[frame];
4493 	idx = ret_prog[frame];
4494 	goto continue_func;
4495 }
4496 
4497 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4498 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4499 				  const struct bpf_insn *insn, int idx)
4500 {
4501 	int start = idx + insn->imm + 1, subprog;
4502 
4503 	subprog = find_subprog(env, start);
4504 	if (subprog < 0) {
4505 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4506 			  start);
4507 		return -EFAULT;
4508 	}
4509 	return env->subprog_info[subprog].stack_depth;
4510 }
4511 #endif
4512 
4513 static int __check_buffer_access(struct bpf_verifier_env *env,
4514 				 const char *buf_info,
4515 				 const struct bpf_reg_state *reg,
4516 				 int regno, int off, int size)
4517 {
4518 	if (off < 0) {
4519 		verbose(env,
4520 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4521 			regno, buf_info, off, size);
4522 		return -EACCES;
4523 	}
4524 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4525 		char tn_buf[48];
4526 
4527 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4528 		verbose(env,
4529 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4530 			regno, off, tn_buf);
4531 		return -EACCES;
4532 	}
4533 
4534 	return 0;
4535 }
4536 
4537 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4538 				  const struct bpf_reg_state *reg,
4539 				  int regno, int off, int size)
4540 {
4541 	int err;
4542 
4543 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4544 	if (err)
4545 		return err;
4546 
4547 	if (off + size > env->prog->aux->max_tp_access)
4548 		env->prog->aux->max_tp_access = off + size;
4549 
4550 	return 0;
4551 }
4552 
4553 static int check_buffer_access(struct bpf_verifier_env *env,
4554 			       const struct bpf_reg_state *reg,
4555 			       int regno, int off, int size,
4556 			       bool zero_size_allowed,
4557 			       u32 *max_access)
4558 {
4559 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4560 	int err;
4561 
4562 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4563 	if (err)
4564 		return err;
4565 
4566 	if (off + size > *max_access)
4567 		*max_access = off + size;
4568 
4569 	return 0;
4570 }
4571 
4572 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4573 static void zext_32_to_64(struct bpf_reg_state *reg)
4574 {
4575 	reg->var_off = tnum_subreg(reg->var_off);
4576 	__reg_assign_32_into_64(reg);
4577 }
4578 
4579 /* truncate register to smaller size (in bytes)
4580  * must be called with size < BPF_REG_SIZE
4581  */
4582 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4583 {
4584 	u64 mask;
4585 
4586 	/* clear high bits in bit representation */
4587 	reg->var_off = tnum_cast(reg->var_off, size);
4588 
4589 	/* fix arithmetic bounds */
4590 	mask = ((u64)1 << (size * 8)) - 1;
4591 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4592 		reg->umin_value &= mask;
4593 		reg->umax_value &= mask;
4594 	} else {
4595 		reg->umin_value = 0;
4596 		reg->umax_value = mask;
4597 	}
4598 	reg->smin_value = reg->umin_value;
4599 	reg->smax_value = reg->umax_value;
4600 
4601 	/* If size is smaller than 32bit register the 32bit register
4602 	 * values are also truncated so we push 64-bit bounds into
4603 	 * 32-bit bounds. Above were truncated < 32-bits already.
4604 	 */
4605 	if (size >= 4)
4606 		return;
4607 	__reg_combine_64_into_32(reg);
4608 }
4609 
4610 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4611 {
4612 	/* A map is considered read-only if the following condition are true:
4613 	 *
4614 	 * 1) BPF program side cannot change any of the map content. The
4615 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4616 	 *    and was set at map creation time.
4617 	 * 2) The map value(s) have been initialized from user space by a
4618 	 *    loader and then "frozen", such that no new map update/delete
4619 	 *    operations from syscall side are possible for the rest of
4620 	 *    the map's lifetime from that point onwards.
4621 	 * 3) Any parallel/pending map update/delete operations from syscall
4622 	 *    side have been completed. Only after that point, it's safe to
4623 	 *    assume that map value(s) are immutable.
4624 	 */
4625 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4626 	       READ_ONCE(map->frozen) &&
4627 	       !bpf_map_write_active(map);
4628 }
4629 
4630 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4631 {
4632 	void *ptr;
4633 	u64 addr;
4634 	int err;
4635 
4636 	err = map->ops->map_direct_value_addr(map, &addr, off);
4637 	if (err)
4638 		return err;
4639 	ptr = (void *)(long)addr + off;
4640 
4641 	switch (size) {
4642 	case sizeof(u8):
4643 		*val = (u64)*(u8 *)ptr;
4644 		break;
4645 	case sizeof(u16):
4646 		*val = (u64)*(u16 *)ptr;
4647 		break;
4648 	case sizeof(u32):
4649 		*val = (u64)*(u32 *)ptr;
4650 		break;
4651 	case sizeof(u64):
4652 		*val = *(u64 *)ptr;
4653 		break;
4654 	default:
4655 		return -EINVAL;
4656 	}
4657 	return 0;
4658 }
4659 
4660 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4661 				   struct bpf_reg_state *regs,
4662 				   int regno, int off, int size,
4663 				   enum bpf_access_type atype,
4664 				   int value_regno)
4665 {
4666 	struct bpf_reg_state *reg = regs + regno;
4667 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4668 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4669 	enum bpf_type_flag flag = 0;
4670 	u32 btf_id;
4671 	int ret;
4672 
4673 	if (off < 0) {
4674 		verbose(env,
4675 			"R%d is ptr_%s invalid negative access: off=%d\n",
4676 			regno, tname, off);
4677 		return -EACCES;
4678 	}
4679 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4680 		char tn_buf[48];
4681 
4682 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4683 		verbose(env,
4684 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4685 			regno, tname, off, tn_buf);
4686 		return -EACCES;
4687 	}
4688 
4689 	if (reg->type & MEM_USER) {
4690 		verbose(env,
4691 			"R%d is ptr_%s access user memory: off=%d\n",
4692 			regno, tname, off);
4693 		return -EACCES;
4694 	}
4695 
4696 	if (reg->type & MEM_PERCPU) {
4697 		verbose(env,
4698 			"R%d is ptr_%s access percpu memory: off=%d\n",
4699 			regno, tname, off);
4700 		return -EACCES;
4701 	}
4702 
4703 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4704 		if (!btf_is_kernel(reg->btf)) {
4705 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4706 			return -EFAULT;
4707 		}
4708 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4709 	} else {
4710 		/* Writes are permitted with default btf_struct_access for
4711 		 * program allocated objects (which always have ref_obj_id > 0),
4712 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4713 		 */
4714 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4715 			verbose(env, "only read is supported\n");
4716 			return -EACCES;
4717 		}
4718 
4719 		if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4720 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4721 			return -EFAULT;
4722 		}
4723 
4724 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4725 	}
4726 
4727 	if (ret < 0)
4728 		return ret;
4729 
4730 	/* If this is an untrusted pointer, all pointers formed by walking it
4731 	 * also inherit the untrusted flag.
4732 	 */
4733 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4734 		flag |= PTR_UNTRUSTED;
4735 
4736 	/* Any pointer obtained from walking a trusted pointer is no longer trusted. */
4737 	flag &= ~PTR_TRUSTED;
4738 
4739 	if (atype == BPF_READ && value_regno >= 0)
4740 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4741 
4742 	return 0;
4743 }
4744 
4745 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4746 				   struct bpf_reg_state *regs,
4747 				   int regno, int off, int size,
4748 				   enum bpf_access_type atype,
4749 				   int value_regno)
4750 {
4751 	struct bpf_reg_state *reg = regs + regno;
4752 	struct bpf_map *map = reg->map_ptr;
4753 	struct bpf_reg_state map_reg;
4754 	enum bpf_type_flag flag = 0;
4755 	const struct btf_type *t;
4756 	const char *tname;
4757 	u32 btf_id;
4758 	int ret;
4759 
4760 	if (!btf_vmlinux) {
4761 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4762 		return -ENOTSUPP;
4763 	}
4764 
4765 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4766 		verbose(env, "map_ptr access not supported for map type %d\n",
4767 			map->map_type);
4768 		return -ENOTSUPP;
4769 	}
4770 
4771 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4772 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4773 
4774 	if (!env->allow_ptr_to_map_access) {
4775 		verbose(env,
4776 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4777 			tname);
4778 		return -EPERM;
4779 	}
4780 
4781 	if (off < 0) {
4782 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4783 			regno, tname, off);
4784 		return -EACCES;
4785 	}
4786 
4787 	if (atype != BPF_READ) {
4788 		verbose(env, "only read from %s is supported\n", tname);
4789 		return -EACCES;
4790 	}
4791 
4792 	/* Simulate access to a PTR_TO_BTF_ID */
4793 	memset(&map_reg, 0, sizeof(map_reg));
4794 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4795 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4796 	if (ret < 0)
4797 		return ret;
4798 
4799 	if (value_regno >= 0)
4800 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4801 
4802 	return 0;
4803 }
4804 
4805 /* Check that the stack access at the given offset is within bounds. The
4806  * maximum valid offset is -1.
4807  *
4808  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4809  * -state->allocated_stack for reads.
4810  */
4811 static int check_stack_slot_within_bounds(int off,
4812 					  struct bpf_func_state *state,
4813 					  enum bpf_access_type t)
4814 {
4815 	int min_valid_off;
4816 
4817 	if (t == BPF_WRITE)
4818 		min_valid_off = -MAX_BPF_STACK;
4819 	else
4820 		min_valid_off = -state->allocated_stack;
4821 
4822 	if (off < min_valid_off || off > -1)
4823 		return -EACCES;
4824 	return 0;
4825 }
4826 
4827 /* Check that the stack access at 'regno + off' falls within the maximum stack
4828  * bounds.
4829  *
4830  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4831  */
4832 static int check_stack_access_within_bounds(
4833 		struct bpf_verifier_env *env,
4834 		int regno, int off, int access_size,
4835 		enum bpf_access_src src, enum bpf_access_type type)
4836 {
4837 	struct bpf_reg_state *regs = cur_regs(env);
4838 	struct bpf_reg_state *reg = regs + regno;
4839 	struct bpf_func_state *state = func(env, reg);
4840 	int min_off, max_off;
4841 	int err;
4842 	char *err_extra;
4843 
4844 	if (src == ACCESS_HELPER)
4845 		/* We don't know if helpers are reading or writing (or both). */
4846 		err_extra = " indirect access to";
4847 	else if (type == BPF_READ)
4848 		err_extra = " read from";
4849 	else
4850 		err_extra = " write to";
4851 
4852 	if (tnum_is_const(reg->var_off)) {
4853 		min_off = reg->var_off.value + off;
4854 		if (access_size > 0)
4855 			max_off = min_off + access_size - 1;
4856 		else
4857 			max_off = min_off;
4858 	} else {
4859 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4860 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4861 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4862 				err_extra, regno);
4863 			return -EACCES;
4864 		}
4865 		min_off = reg->smin_value + off;
4866 		if (access_size > 0)
4867 			max_off = reg->smax_value + off + access_size - 1;
4868 		else
4869 			max_off = min_off;
4870 	}
4871 
4872 	err = check_stack_slot_within_bounds(min_off, state, type);
4873 	if (!err)
4874 		err = check_stack_slot_within_bounds(max_off, state, type);
4875 
4876 	if (err) {
4877 		if (tnum_is_const(reg->var_off)) {
4878 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4879 				err_extra, regno, off, access_size);
4880 		} else {
4881 			char tn_buf[48];
4882 
4883 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4884 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4885 				err_extra, regno, tn_buf, access_size);
4886 		}
4887 	}
4888 	return err;
4889 }
4890 
4891 /* check whether memory at (regno + off) is accessible for t = (read | write)
4892  * if t==write, value_regno is a register which value is stored into memory
4893  * if t==read, value_regno is a register which will receive the value from memory
4894  * if t==write && value_regno==-1, some unknown value is stored into memory
4895  * if t==read && value_regno==-1, don't care what we read from memory
4896  */
4897 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4898 			    int off, int bpf_size, enum bpf_access_type t,
4899 			    int value_regno, bool strict_alignment_once)
4900 {
4901 	struct bpf_reg_state *regs = cur_regs(env);
4902 	struct bpf_reg_state *reg = regs + regno;
4903 	struct bpf_func_state *state;
4904 	int size, err = 0;
4905 
4906 	size = bpf_size_to_bytes(bpf_size);
4907 	if (size < 0)
4908 		return size;
4909 
4910 	/* alignment checks will add in reg->off themselves */
4911 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4912 	if (err)
4913 		return err;
4914 
4915 	/* for access checks, reg->off is just part of off */
4916 	off += reg->off;
4917 
4918 	if (reg->type == PTR_TO_MAP_KEY) {
4919 		if (t == BPF_WRITE) {
4920 			verbose(env, "write to change key R%d not allowed\n", regno);
4921 			return -EACCES;
4922 		}
4923 
4924 		err = check_mem_region_access(env, regno, off, size,
4925 					      reg->map_ptr->key_size, false);
4926 		if (err)
4927 			return err;
4928 		if (value_regno >= 0)
4929 			mark_reg_unknown(env, regs, value_regno);
4930 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4931 		struct btf_field *kptr_field = NULL;
4932 
4933 		if (t == BPF_WRITE && value_regno >= 0 &&
4934 		    is_pointer_value(env, value_regno)) {
4935 			verbose(env, "R%d leaks addr into map\n", value_regno);
4936 			return -EACCES;
4937 		}
4938 		err = check_map_access_type(env, regno, off, size, t);
4939 		if (err)
4940 			return err;
4941 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4942 		if (err)
4943 			return err;
4944 		if (tnum_is_const(reg->var_off))
4945 			kptr_field = btf_record_find(reg->map_ptr->record,
4946 						     off + reg->var_off.value, BPF_KPTR);
4947 		if (kptr_field) {
4948 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
4949 		} else if (t == BPF_READ && value_regno >= 0) {
4950 			struct bpf_map *map = reg->map_ptr;
4951 
4952 			/* if map is read-only, track its contents as scalars */
4953 			if (tnum_is_const(reg->var_off) &&
4954 			    bpf_map_is_rdonly(map) &&
4955 			    map->ops->map_direct_value_addr) {
4956 				int map_off = off + reg->var_off.value;
4957 				u64 val = 0;
4958 
4959 				err = bpf_map_direct_read(map, map_off, size,
4960 							  &val);
4961 				if (err)
4962 					return err;
4963 
4964 				regs[value_regno].type = SCALAR_VALUE;
4965 				__mark_reg_known(&regs[value_regno], val);
4966 			} else {
4967 				mark_reg_unknown(env, regs, value_regno);
4968 			}
4969 		}
4970 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4971 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4972 
4973 		if (type_may_be_null(reg->type)) {
4974 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4975 				reg_type_str(env, reg->type));
4976 			return -EACCES;
4977 		}
4978 
4979 		if (t == BPF_WRITE && rdonly_mem) {
4980 			verbose(env, "R%d cannot write into %s\n",
4981 				regno, reg_type_str(env, reg->type));
4982 			return -EACCES;
4983 		}
4984 
4985 		if (t == BPF_WRITE && value_regno >= 0 &&
4986 		    is_pointer_value(env, value_regno)) {
4987 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4988 			return -EACCES;
4989 		}
4990 
4991 		err = check_mem_region_access(env, regno, off, size,
4992 					      reg->mem_size, false);
4993 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4994 			mark_reg_unknown(env, regs, value_regno);
4995 	} else if (reg->type == PTR_TO_CTX) {
4996 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4997 		struct btf *btf = NULL;
4998 		u32 btf_id = 0;
4999 
5000 		if (t == BPF_WRITE && value_regno >= 0 &&
5001 		    is_pointer_value(env, value_regno)) {
5002 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5003 			return -EACCES;
5004 		}
5005 
5006 		err = check_ptr_off_reg(env, reg, regno);
5007 		if (err < 0)
5008 			return err;
5009 
5010 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5011 				       &btf_id);
5012 		if (err)
5013 			verbose_linfo(env, insn_idx, "; ");
5014 		if (!err && t == BPF_READ && value_regno >= 0) {
5015 			/* ctx access returns either a scalar, or a
5016 			 * PTR_TO_PACKET[_META,_END]. In the latter
5017 			 * case, we know the offset is zero.
5018 			 */
5019 			if (reg_type == SCALAR_VALUE) {
5020 				mark_reg_unknown(env, regs, value_regno);
5021 			} else {
5022 				mark_reg_known_zero(env, regs,
5023 						    value_regno);
5024 				if (type_may_be_null(reg_type))
5025 					regs[value_regno].id = ++env->id_gen;
5026 				/* A load of ctx field could have different
5027 				 * actual load size with the one encoded in the
5028 				 * insn. When the dst is PTR, it is for sure not
5029 				 * a sub-register.
5030 				 */
5031 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5032 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5033 					regs[value_regno].btf = btf;
5034 					regs[value_regno].btf_id = btf_id;
5035 				}
5036 			}
5037 			regs[value_regno].type = reg_type;
5038 		}
5039 
5040 	} else if (reg->type == PTR_TO_STACK) {
5041 		/* Basic bounds checks. */
5042 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5043 		if (err)
5044 			return err;
5045 
5046 		state = func(env, reg);
5047 		err = update_stack_depth(env, state, off);
5048 		if (err)
5049 			return err;
5050 
5051 		if (t == BPF_READ)
5052 			err = check_stack_read(env, regno, off, size,
5053 					       value_regno);
5054 		else
5055 			err = check_stack_write(env, regno, off, size,
5056 						value_regno, insn_idx);
5057 	} else if (reg_is_pkt_pointer(reg)) {
5058 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5059 			verbose(env, "cannot write into packet\n");
5060 			return -EACCES;
5061 		}
5062 		if (t == BPF_WRITE && value_regno >= 0 &&
5063 		    is_pointer_value(env, value_regno)) {
5064 			verbose(env, "R%d leaks addr into packet\n",
5065 				value_regno);
5066 			return -EACCES;
5067 		}
5068 		err = check_packet_access(env, regno, off, size, false);
5069 		if (!err && t == BPF_READ && value_regno >= 0)
5070 			mark_reg_unknown(env, regs, value_regno);
5071 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5072 		if (t == BPF_WRITE && value_regno >= 0 &&
5073 		    is_pointer_value(env, value_regno)) {
5074 			verbose(env, "R%d leaks addr into flow keys\n",
5075 				value_regno);
5076 			return -EACCES;
5077 		}
5078 
5079 		err = check_flow_keys_access(env, off, size);
5080 		if (!err && t == BPF_READ && value_regno >= 0)
5081 			mark_reg_unknown(env, regs, value_regno);
5082 	} else if (type_is_sk_pointer(reg->type)) {
5083 		if (t == BPF_WRITE) {
5084 			verbose(env, "R%d cannot write into %s\n",
5085 				regno, reg_type_str(env, reg->type));
5086 			return -EACCES;
5087 		}
5088 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5089 		if (!err && value_regno >= 0)
5090 			mark_reg_unknown(env, regs, value_regno);
5091 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5092 		err = check_tp_buffer_access(env, reg, regno, off, size);
5093 		if (!err && t == BPF_READ && value_regno >= 0)
5094 			mark_reg_unknown(env, regs, value_regno);
5095 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5096 		   !type_may_be_null(reg->type)) {
5097 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5098 					      value_regno);
5099 	} else if (reg->type == CONST_PTR_TO_MAP) {
5100 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5101 					      value_regno);
5102 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5103 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5104 		u32 *max_access;
5105 
5106 		if (rdonly_mem) {
5107 			if (t == BPF_WRITE) {
5108 				verbose(env, "R%d cannot write into %s\n",
5109 					regno, reg_type_str(env, reg->type));
5110 				return -EACCES;
5111 			}
5112 			max_access = &env->prog->aux->max_rdonly_access;
5113 		} else {
5114 			max_access = &env->prog->aux->max_rdwr_access;
5115 		}
5116 
5117 		err = check_buffer_access(env, reg, regno, off, size, false,
5118 					  max_access);
5119 
5120 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5121 			mark_reg_unknown(env, regs, value_regno);
5122 	} else {
5123 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5124 			reg_type_str(env, reg->type));
5125 		return -EACCES;
5126 	}
5127 
5128 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5129 	    regs[value_regno].type == SCALAR_VALUE) {
5130 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5131 		coerce_reg_to_size(&regs[value_regno], size);
5132 	}
5133 	return err;
5134 }
5135 
5136 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5137 {
5138 	int load_reg;
5139 	int err;
5140 
5141 	switch (insn->imm) {
5142 	case BPF_ADD:
5143 	case BPF_ADD | BPF_FETCH:
5144 	case BPF_AND:
5145 	case BPF_AND | BPF_FETCH:
5146 	case BPF_OR:
5147 	case BPF_OR | BPF_FETCH:
5148 	case BPF_XOR:
5149 	case BPF_XOR | BPF_FETCH:
5150 	case BPF_XCHG:
5151 	case BPF_CMPXCHG:
5152 		break;
5153 	default:
5154 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5155 		return -EINVAL;
5156 	}
5157 
5158 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5159 		verbose(env, "invalid atomic operand size\n");
5160 		return -EINVAL;
5161 	}
5162 
5163 	/* check src1 operand */
5164 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5165 	if (err)
5166 		return err;
5167 
5168 	/* check src2 operand */
5169 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5170 	if (err)
5171 		return err;
5172 
5173 	if (insn->imm == BPF_CMPXCHG) {
5174 		/* Check comparison of R0 with memory location */
5175 		const u32 aux_reg = BPF_REG_0;
5176 
5177 		err = check_reg_arg(env, aux_reg, SRC_OP);
5178 		if (err)
5179 			return err;
5180 
5181 		if (is_pointer_value(env, aux_reg)) {
5182 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5183 			return -EACCES;
5184 		}
5185 	}
5186 
5187 	if (is_pointer_value(env, insn->src_reg)) {
5188 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5189 		return -EACCES;
5190 	}
5191 
5192 	if (is_ctx_reg(env, insn->dst_reg) ||
5193 	    is_pkt_reg(env, insn->dst_reg) ||
5194 	    is_flow_key_reg(env, insn->dst_reg) ||
5195 	    is_sk_reg(env, insn->dst_reg)) {
5196 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5197 			insn->dst_reg,
5198 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5199 		return -EACCES;
5200 	}
5201 
5202 	if (insn->imm & BPF_FETCH) {
5203 		if (insn->imm == BPF_CMPXCHG)
5204 			load_reg = BPF_REG_0;
5205 		else
5206 			load_reg = insn->src_reg;
5207 
5208 		/* check and record load of old value */
5209 		err = check_reg_arg(env, load_reg, DST_OP);
5210 		if (err)
5211 			return err;
5212 	} else {
5213 		/* This instruction accesses a memory location but doesn't
5214 		 * actually load it into a register.
5215 		 */
5216 		load_reg = -1;
5217 	}
5218 
5219 	/* Check whether we can read the memory, with second call for fetch
5220 	 * case to simulate the register fill.
5221 	 */
5222 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5223 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5224 	if (!err && load_reg >= 0)
5225 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5226 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5227 				       true);
5228 	if (err)
5229 		return err;
5230 
5231 	/* Check whether we can write into the same memory. */
5232 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5233 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5234 	if (err)
5235 		return err;
5236 
5237 	return 0;
5238 }
5239 
5240 /* When register 'regno' is used to read the stack (either directly or through
5241  * a helper function) make sure that it's within stack boundary and, depending
5242  * on the access type, that all elements of the stack are initialized.
5243  *
5244  * 'off' includes 'regno->off', but not its dynamic part (if any).
5245  *
5246  * All registers that have been spilled on the stack in the slots within the
5247  * read offsets are marked as read.
5248  */
5249 static int check_stack_range_initialized(
5250 		struct bpf_verifier_env *env, int regno, int off,
5251 		int access_size, bool zero_size_allowed,
5252 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5253 {
5254 	struct bpf_reg_state *reg = reg_state(env, regno);
5255 	struct bpf_func_state *state = func(env, reg);
5256 	int err, min_off, max_off, i, j, slot, spi;
5257 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5258 	enum bpf_access_type bounds_check_type;
5259 	/* Some accesses can write anything into the stack, others are
5260 	 * read-only.
5261 	 */
5262 	bool clobber = false;
5263 
5264 	if (access_size == 0 && !zero_size_allowed) {
5265 		verbose(env, "invalid zero-sized read\n");
5266 		return -EACCES;
5267 	}
5268 
5269 	if (type == ACCESS_HELPER) {
5270 		/* The bounds checks for writes are more permissive than for
5271 		 * reads. However, if raw_mode is not set, we'll do extra
5272 		 * checks below.
5273 		 */
5274 		bounds_check_type = BPF_WRITE;
5275 		clobber = true;
5276 	} else {
5277 		bounds_check_type = BPF_READ;
5278 	}
5279 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5280 					       type, bounds_check_type);
5281 	if (err)
5282 		return err;
5283 
5284 
5285 	if (tnum_is_const(reg->var_off)) {
5286 		min_off = max_off = reg->var_off.value + off;
5287 	} else {
5288 		/* Variable offset is prohibited for unprivileged mode for
5289 		 * simplicity since it requires corresponding support in
5290 		 * Spectre masking for stack ALU.
5291 		 * See also retrieve_ptr_limit().
5292 		 */
5293 		if (!env->bypass_spec_v1) {
5294 			char tn_buf[48];
5295 
5296 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5297 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5298 				regno, err_extra, tn_buf);
5299 			return -EACCES;
5300 		}
5301 		/* Only initialized buffer on stack is allowed to be accessed
5302 		 * with variable offset. With uninitialized buffer it's hard to
5303 		 * guarantee that whole memory is marked as initialized on
5304 		 * helper return since specific bounds are unknown what may
5305 		 * cause uninitialized stack leaking.
5306 		 */
5307 		if (meta && meta->raw_mode)
5308 			meta = NULL;
5309 
5310 		min_off = reg->smin_value + off;
5311 		max_off = reg->smax_value + off;
5312 	}
5313 
5314 	if (meta && meta->raw_mode) {
5315 		meta->access_size = access_size;
5316 		meta->regno = regno;
5317 		return 0;
5318 	}
5319 
5320 	for (i = min_off; i < max_off + access_size; i++) {
5321 		u8 *stype;
5322 
5323 		slot = -i - 1;
5324 		spi = slot / BPF_REG_SIZE;
5325 		if (state->allocated_stack <= slot)
5326 			goto err;
5327 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5328 		if (*stype == STACK_MISC)
5329 			goto mark;
5330 		if (*stype == STACK_ZERO) {
5331 			if (clobber) {
5332 				/* helper can write anything into the stack */
5333 				*stype = STACK_MISC;
5334 			}
5335 			goto mark;
5336 		}
5337 
5338 		if (is_spilled_reg(&state->stack[spi]) &&
5339 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5340 		     env->allow_ptr_leaks)) {
5341 			if (clobber) {
5342 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5343 				for (j = 0; j < BPF_REG_SIZE; j++)
5344 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5345 			}
5346 			goto mark;
5347 		}
5348 
5349 err:
5350 		if (tnum_is_const(reg->var_off)) {
5351 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5352 				err_extra, regno, min_off, i - min_off, access_size);
5353 		} else {
5354 			char tn_buf[48];
5355 
5356 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5357 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5358 				err_extra, regno, tn_buf, i - min_off, access_size);
5359 		}
5360 		return -EACCES;
5361 mark:
5362 		/* reading any byte out of 8-byte 'spill_slot' will cause
5363 		 * the whole slot to be marked as 'read'
5364 		 */
5365 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5366 			      state->stack[spi].spilled_ptr.parent,
5367 			      REG_LIVE_READ64);
5368 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5369 		 * be sure that whether stack slot is written to or not. Hence,
5370 		 * we must still conservatively propagate reads upwards even if
5371 		 * helper may write to the entire memory range.
5372 		 */
5373 	}
5374 	return update_stack_depth(env, state, min_off);
5375 }
5376 
5377 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5378 				   int access_size, bool zero_size_allowed,
5379 				   struct bpf_call_arg_meta *meta)
5380 {
5381 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5382 	u32 *max_access;
5383 
5384 	switch (base_type(reg->type)) {
5385 	case PTR_TO_PACKET:
5386 	case PTR_TO_PACKET_META:
5387 		return check_packet_access(env, regno, reg->off, access_size,
5388 					   zero_size_allowed);
5389 	case PTR_TO_MAP_KEY:
5390 		if (meta && meta->raw_mode) {
5391 			verbose(env, "R%d cannot write into %s\n", regno,
5392 				reg_type_str(env, reg->type));
5393 			return -EACCES;
5394 		}
5395 		return check_mem_region_access(env, regno, reg->off, access_size,
5396 					       reg->map_ptr->key_size, false);
5397 	case PTR_TO_MAP_VALUE:
5398 		if (check_map_access_type(env, regno, reg->off, access_size,
5399 					  meta && meta->raw_mode ? BPF_WRITE :
5400 					  BPF_READ))
5401 			return -EACCES;
5402 		return check_map_access(env, regno, reg->off, access_size,
5403 					zero_size_allowed, ACCESS_HELPER);
5404 	case PTR_TO_MEM:
5405 		if (type_is_rdonly_mem(reg->type)) {
5406 			if (meta && meta->raw_mode) {
5407 				verbose(env, "R%d cannot write into %s\n", regno,
5408 					reg_type_str(env, reg->type));
5409 				return -EACCES;
5410 			}
5411 		}
5412 		return check_mem_region_access(env, regno, reg->off,
5413 					       access_size, reg->mem_size,
5414 					       zero_size_allowed);
5415 	case PTR_TO_BUF:
5416 		if (type_is_rdonly_mem(reg->type)) {
5417 			if (meta && meta->raw_mode) {
5418 				verbose(env, "R%d cannot write into %s\n", regno,
5419 					reg_type_str(env, reg->type));
5420 				return -EACCES;
5421 			}
5422 
5423 			max_access = &env->prog->aux->max_rdonly_access;
5424 		} else {
5425 			max_access = &env->prog->aux->max_rdwr_access;
5426 		}
5427 		return check_buffer_access(env, reg, regno, reg->off,
5428 					   access_size, zero_size_allowed,
5429 					   max_access);
5430 	case PTR_TO_STACK:
5431 		return check_stack_range_initialized(
5432 				env,
5433 				regno, reg->off, access_size,
5434 				zero_size_allowed, ACCESS_HELPER, meta);
5435 	case PTR_TO_CTX:
5436 		/* in case the function doesn't know how to access the context,
5437 		 * (because we are in a program of type SYSCALL for example), we
5438 		 * can not statically check its size.
5439 		 * Dynamically check it now.
5440 		 */
5441 		if (!env->ops->convert_ctx_access) {
5442 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5443 			int offset = access_size - 1;
5444 
5445 			/* Allow zero-byte read from PTR_TO_CTX */
5446 			if (access_size == 0)
5447 				return zero_size_allowed ? 0 : -EACCES;
5448 
5449 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5450 						atype, -1, false);
5451 		}
5452 
5453 		fallthrough;
5454 	default: /* scalar_value or invalid ptr */
5455 		/* Allow zero-byte read from NULL, regardless of pointer type */
5456 		if (zero_size_allowed && access_size == 0 &&
5457 		    register_is_null(reg))
5458 			return 0;
5459 
5460 		verbose(env, "R%d type=%s ", regno,
5461 			reg_type_str(env, reg->type));
5462 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5463 		return -EACCES;
5464 	}
5465 }
5466 
5467 static int check_mem_size_reg(struct bpf_verifier_env *env,
5468 			      struct bpf_reg_state *reg, u32 regno,
5469 			      bool zero_size_allowed,
5470 			      struct bpf_call_arg_meta *meta)
5471 {
5472 	int err;
5473 
5474 	/* This is used to refine r0 return value bounds for helpers
5475 	 * that enforce this value as an upper bound on return values.
5476 	 * See do_refine_retval_range() for helpers that can refine
5477 	 * the return value. C type of helper is u32 so we pull register
5478 	 * bound from umax_value however, if negative verifier errors
5479 	 * out. Only upper bounds can be learned because retval is an
5480 	 * int type and negative retvals are allowed.
5481 	 */
5482 	meta->msize_max_value = reg->umax_value;
5483 
5484 	/* The register is SCALAR_VALUE; the access check
5485 	 * happens using its boundaries.
5486 	 */
5487 	if (!tnum_is_const(reg->var_off))
5488 		/* For unprivileged variable accesses, disable raw
5489 		 * mode so that the program is required to
5490 		 * initialize all the memory that the helper could
5491 		 * just partially fill up.
5492 		 */
5493 		meta = NULL;
5494 
5495 	if (reg->smin_value < 0) {
5496 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5497 			regno);
5498 		return -EACCES;
5499 	}
5500 
5501 	if (reg->umin_value == 0) {
5502 		err = check_helper_mem_access(env, regno - 1, 0,
5503 					      zero_size_allowed,
5504 					      meta);
5505 		if (err)
5506 			return err;
5507 	}
5508 
5509 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5510 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5511 			regno);
5512 		return -EACCES;
5513 	}
5514 	err = check_helper_mem_access(env, regno - 1,
5515 				      reg->umax_value,
5516 				      zero_size_allowed, meta);
5517 	if (!err)
5518 		err = mark_chain_precision(env, regno);
5519 	return err;
5520 }
5521 
5522 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5523 		   u32 regno, u32 mem_size)
5524 {
5525 	bool may_be_null = type_may_be_null(reg->type);
5526 	struct bpf_reg_state saved_reg;
5527 	struct bpf_call_arg_meta meta;
5528 	int err;
5529 
5530 	if (register_is_null(reg))
5531 		return 0;
5532 
5533 	memset(&meta, 0, sizeof(meta));
5534 	/* Assuming that the register contains a value check if the memory
5535 	 * access is safe. Temporarily save and restore the register's state as
5536 	 * the conversion shouldn't be visible to a caller.
5537 	 */
5538 	if (may_be_null) {
5539 		saved_reg = *reg;
5540 		mark_ptr_not_null_reg(reg);
5541 	}
5542 
5543 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5544 	/* Check access for BPF_WRITE */
5545 	meta.raw_mode = true;
5546 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5547 
5548 	if (may_be_null)
5549 		*reg = saved_reg;
5550 
5551 	return err;
5552 }
5553 
5554 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5555 				    u32 regno)
5556 {
5557 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5558 	bool may_be_null = type_may_be_null(mem_reg->type);
5559 	struct bpf_reg_state saved_reg;
5560 	struct bpf_call_arg_meta meta;
5561 	int err;
5562 
5563 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5564 
5565 	memset(&meta, 0, sizeof(meta));
5566 
5567 	if (may_be_null) {
5568 		saved_reg = *mem_reg;
5569 		mark_ptr_not_null_reg(mem_reg);
5570 	}
5571 
5572 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5573 	/* Check access for BPF_WRITE */
5574 	meta.raw_mode = true;
5575 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5576 
5577 	if (may_be_null)
5578 		*mem_reg = saved_reg;
5579 	return err;
5580 }
5581 
5582 /* Implementation details:
5583  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5584  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5585  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5586  * Two separate bpf_obj_new will also have different reg->id.
5587  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5588  * clears reg->id after value_or_null->value transition, since the verifier only
5589  * cares about the range of access to valid map value pointer and doesn't care
5590  * about actual address of the map element.
5591  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5592  * reg->id > 0 after value_or_null->value transition. By doing so
5593  * two bpf_map_lookups will be considered two different pointers that
5594  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5595  * returned from bpf_obj_new.
5596  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5597  * dead-locks.
5598  * Since only one bpf_spin_lock is allowed the checks are simpler than
5599  * reg_is_refcounted() logic. The verifier needs to remember only
5600  * one spin_lock instead of array of acquired_refs.
5601  * cur_state->active_lock remembers which map value element or allocated
5602  * object got locked and clears it after bpf_spin_unlock.
5603  */
5604 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5605 			     bool is_lock)
5606 {
5607 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5608 	struct bpf_verifier_state *cur = env->cur_state;
5609 	bool is_const = tnum_is_const(reg->var_off);
5610 	u64 val = reg->var_off.value;
5611 	struct bpf_map *map = NULL;
5612 	struct btf *btf = NULL;
5613 	struct btf_record *rec;
5614 
5615 	if (!is_const) {
5616 		verbose(env,
5617 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5618 			regno);
5619 		return -EINVAL;
5620 	}
5621 	if (reg->type == PTR_TO_MAP_VALUE) {
5622 		map = reg->map_ptr;
5623 		if (!map->btf) {
5624 			verbose(env,
5625 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5626 				map->name);
5627 			return -EINVAL;
5628 		}
5629 	} else {
5630 		btf = reg->btf;
5631 	}
5632 
5633 	rec = reg_btf_record(reg);
5634 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5635 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5636 			map ? map->name : "kptr");
5637 		return -EINVAL;
5638 	}
5639 	if (rec->spin_lock_off != val + reg->off) {
5640 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5641 			val + reg->off, rec->spin_lock_off);
5642 		return -EINVAL;
5643 	}
5644 	if (is_lock) {
5645 		if (cur->active_lock.ptr) {
5646 			verbose(env,
5647 				"Locking two bpf_spin_locks are not allowed\n");
5648 			return -EINVAL;
5649 		}
5650 		if (map)
5651 			cur->active_lock.ptr = map;
5652 		else
5653 			cur->active_lock.ptr = btf;
5654 		cur->active_lock.id = reg->id;
5655 	} else {
5656 		struct bpf_func_state *fstate = cur_func(env);
5657 		void *ptr;
5658 		int i;
5659 
5660 		if (map)
5661 			ptr = map;
5662 		else
5663 			ptr = btf;
5664 
5665 		if (!cur->active_lock.ptr) {
5666 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5667 			return -EINVAL;
5668 		}
5669 		if (cur->active_lock.ptr != ptr ||
5670 		    cur->active_lock.id != reg->id) {
5671 			verbose(env, "bpf_spin_unlock of different lock\n");
5672 			return -EINVAL;
5673 		}
5674 		cur->active_lock.ptr = NULL;
5675 		cur->active_lock.id = 0;
5676 
5677 		for (i = 0; i < fstate->acquired_refs; i++) {
5678 			int err;
5679 
5680 			/* Complain on error because this reference state cannot
5681 			 * be freed before this point, as bpf_spin_lock critical
5682 			 * section does not allow functions that release the
5683 			 * allocated object immediately.
5684 			 */
5685 			if (!fstate->refs[i].release_on_unlock)
5686 				continue;
5687 			err = release_reference(env, fstate->refs[i].id);
5688 			if (err) {
5689 				verbose(env, "failed to release release_on_unlock reference");
5690 				return err;
5691 			}
5692 		}
5693 	}
5694 	return 0;
5695 }
5696 
5697 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5698 			      struct bpf_call_arg_meta *meta)
5699 {
5700 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5701 	bool is_const = tnum_is_const(reg->var_off);
5702 	struct bpf_map *map = reg->map_ptr;
5703 	u64 val = reg->var_off.value;
5704 
5705 	if (!is_const) {
5706 		verbose(env,
5707 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5708 			regno);
5709 		return -EINVAL;
5710 	}
5711 	if (!map->btf) {
5712 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5713 			map->name);
5714 		return -EINVAL;
5715 	}
5716 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
5717 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5718 		return -EINVAL;
5719 	}
5720 	if (map->record->timer_off != val + reg->off) {
5721 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5722 			val + reg->off, map->record->timer_off);
5723 		return -EINVAL;
5724 	}
5725 	if (meta->map_ptr) {
5726 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5727 		return -EFAULT;
5728 	}
5729 	meta->map_uid = reg->map_uid;
5730 	meta->map_ptr = map;
5731 	return 0;
5732 }
5733 
5734 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5735 			     struct bpf_call_arg_meta *meta)
5736 {
5737 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5738 	struct bpf_map *map_ptr = reg->map_ptr;
5739 	struct btf_field *kptr_field;
5740 	u32 kptr_off;
5741 
5742 	if (!tnum_is_const(reg->var_off)) {
5743 		verbose(env,
5744 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5745 			regno);
5746 		return -EINVAL;
5747 	}
5748 	if (!map_ptr->btf) {
5749 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5750 			map_ptr->name);
5751 		return -EINVAL;
5752 	}
5753 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5754 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5755 		return -EINVAL;
5756 	}
5757 
5758 	meta->map_ptr = map_ptr;
5759 	kptr_off = reg->off + reg->var_off.value;
5760 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5761 	if (!kptr_field) {
5762 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5763 		return -EACCES;
5764 	}
5765 	if (kptr_field->type != BPF_KPTR_REF) {
5766 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5767 		return -EACCES;
5768 	}
5769 	meta->kptr_field = kptr_field;
5770 	return 0;
5771 }
5772 
5773 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5774 {
5775 	return type == ARG_CONST_SIZE ||
5776 	       type == ARG_CONST_SIZE_OR_ZERO;
5777 }
5778 
5779 static bool arg_type_is_release(enum bpf_arg_type type)
5780 {
5781 	return type & OBJ_RELEASE;
5782 }
5783 
5784 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5785 {
5786 	return base_type(type) == ARG_PTR_TO_DYNPTR;
5787 }
5788 
5789 static int int_ptr_type_to_size(enum bpf_arg_type type)
5790 {
5791 	if (type == ARG_PTR_TO_INT)
5792 		return sizeof(u32);
5793 	else if (type == ARG_PTR_TO_LONG)
5794 		return sizeof(u64);
5795 
5796 	return -EINVAL;
5797 }
5798 
5799 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5800 				 const struct bpf_call_arg_meta *meta,
5801 				 enum bpf_arg_type *arg_type)
5802 {
5803 	if (!meta->map_ptr) {
5804 		/* kernel subsystem misconfigured verifier */
5805 		verbose(env, "invalid map_ptr to access map->type\n");
5806 		return -EACCES;
5807 	}
5808 
5809 	switch (meta->map_ptr->map_type) {
5810 	case BPF_MAP_TYPE_SOCKMAP:
5811 	case BPF_MAP_TYPE_SOCKHASH:
5812 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5813 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5814 		} else {
5815 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5816 			return -EINVAL;
5817 		}
5818 		break;
5819 	case BPF_MAP_TYPE_BLOOM_FILTER:
5820 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5821 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5822 		break;
5823 	default:
5824 		break;
5825 	}
5826 	return 0;
5827 }
5828 
5829 struct bpf_reg_types {
5830 	const enum bpf_reg_type types[10];
5831 	u32 *btf_id;
5832 };
5833 
5834 static const struct bpf_reg_types sock_types = {
5835 	.types = {
5836 		PTR_TO_SOCK_COMMON,
5837 		PTR_TO_SOCKET,
5838 		PTR_TO_TCP_SOCK,
5839 		PTR_TO_XDP_SOCK,
5840 	},
5841 };
5842 
5843 #ifdef CONFIG_NET
5844 static const struct bpf_reg_types btf_id_sock_common_types = {
5845 	.types = {
5846 		PTR_TO_SOCK_COMMON,
5847 		PTR_TO_SOCKET,
5848 		PTR_TO_TCP_SOCK,
5849 		PTR_TO_XDP_SOCK,
5850 		PTR_TO_BTF_ID,
5851 		PTR_TO_BTF_ID | PTR_TRUSTED,
5852 	},
5853 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5854 };
5855 #endif
5856 
5857 static const struct bpf_reg_types mem_types = {
5858 	.types = {
5859 		PTR_TO_STACK,
5860 		PTR_TO_PACKET,
5861 		PTR_TO_PACKET_META,
5862 		PTR_TO_MAP_KEY,
5863 		PTR_TO_MAP_VALUE,
5864 		PTR_TO_MEM,
5865 		PTR_TO_MEM | MEM_RINGBUF,
5866 		PTR_TO_BUF,
5867 	},
5868 };
5869 
5870 static const struct bpf_reg_types int_ptr_types = {
5871 	.types = {
5872 		PTR_TO_STACK,
5873 		PTR_TO_PACKET,
5874 		PTR_TO_PACKET_META,
5875 		PTR_TO_MAP_KEY,
5876 		PTR_TO_MAP_VALUE,
5877 	},
5878 };
5879 
5880 static const struct bpf_reg_types spin_lock_types = {
5881 	.types = {
5882 		PTR_TO_MAP_VALUE,
5883 		PTR_TO_BTF_ID | MEM_ALLOC,
5884 	}
5885 };
5886 
5887 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5888 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5889 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5890 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
5891 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5892 static const struct bpf_reg_types btf_ptr_types = {
5893 	.types = {
5894 		PTR_TO_BTF_ID,
5895 		PTR_TO_BTF_ID | PTR_TRUSTED,
5896 	},
5897 };
5898 static const struct bpf_reg_types percpu_btf_ptr_types = {
5899 	.types = {
5900 		PTR_TO_BTF_ID | MEM_PERCPU,
5901 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
5902 	}
5903 };
5904 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5905 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5906 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5907 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5908 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5909 static const struct bpf_reg_types dynptr_types = {
5910 	.types = {
5911 		PTR_TO_STACK,
5912 		PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5913 	}
5914 };
5915 
5916 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5917 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
5918 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
5919 	[ARG_CONST_SIZE]		= &scalar_types,
5920 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5921 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5922 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5923 	[ARG_PTR_TO_CTX]		= &context_types,
5924 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5925 #ifdef CONFIG_NET
5926 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5927 #endif
5928 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5929 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5930 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5931 	[ARG_PTR_TO_MEM]		= &mem_types,
5932 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
5933 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5934 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5935 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5936 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5937 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5938 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5939 	[ARG_PTR_TO_TIMER]		= &timer_types,
5940 	[ARG_PTR_TO_KPTR]		= &kptr_types,
5941 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
5942 };
5943 
5944 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5945 			  enum bpf_arg_type arg_type,
5946 			  const u32 *arg_btf_id,
5947 			  struct bpf_call_arg_meta *meta)
5948 {
5949 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5950 	enum bpf_reg_type expected, type = reg->type;
5951 	const struct bpf_reg_types *compatible;
5952 	int i, j;
5953 
5954 	compatible = compatible_reg_types[base_type(arg_type)];
5955 	if (!compatible) {
5956 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5957 		return -EFAULT;
5958 	}
5959 
5960 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5961 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5962 	 *
5963 	 * Same for MAYBE_NULL:
5964 	 *
5965 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5966 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5967 	 *
5968 	 * Therefore we fold these flags depending on the arg_type before comparison.
5969 	 */
5970 	if (arg_type & MEM_RDONLY)
5971 		type &= ~MEM_RDONLY;
5972 	if (arg_type & PTR_MAYBE_NULL)
5973 		type &= ~PTR_MAYBE_NULL;
5974 
5975 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5976 		expected = compatible->types[i];
5977 		if (expected == NOT_INIT)
5978 			break;
5979 
5980 		if (type == expected)
5981 			goto found;
5982 	}
5983 
5984 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5985 	for (j = 0; j + 1 < i; j++)
5986 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5987 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5988 	return -EACCES;
5989 
5990 found:
5991 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
5992 		/* For bpf_sk_release, it needs to match against first member
5993 		 * 'struct sock_common', hence make an exception for it. This
5994 		 * allows bpf_sk_release to work for multiple socket types.
5995 		 */
5996 		bool strict_type_match = arg_type_is_release(arg_type) &&
5997 					 meta->func_id != BPF_FUNC_sk_release;
5998 
5999 		if (!arg_btf_id) {
6000 			if (!compatible->btf_id) {
6001 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6002 				return -EFAULT;
6003 			}
6004 			arg_btf_id = compatible->btf_id;
6005 		}
6006 
6007 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6008 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6009 				return -EACCES;
6010 		} else {
6011 			if (arg_btf_id == BPF_PTR_POISON) {
6012 				verbose(env, "verifier internal error:");
6013 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6014 					regno);
6015 				return -EACCES;
6016 			}
6017 
6018 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6019 						  btf_vmlinux, *arg_btf_id,
6020 						  strict_type_match)) {
6021 				verbose(env, "R%d is of type %s but %s is expected\n",
6022 					regno, kernel_type_name(reg->btf, reg->btf_id),
6023 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6024 				return -EACCES;
6025 			}
6026 		}
6027 	} else if (type_is_alloc(reg->type)) {
6028 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6029 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6030 			return -EFAULT;
6031 		}
6032 	}
6033 
6034 	return 0;
6035 }
6036 
6037 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6038 			   const struct bpf_reg_state *reg, int regno,
6039 			   enum bpf_arg_type arg_type)
6040 {
6041 	enum bpf_reg_type type = reg->type;
6042 	bool fixed_off_ok = false;
6043 
6044 	switch ((u32)type) {
6045 	/* Pointer types where reg offset is explicitly allowed: */
6046 	case PTR_TO_STACK:
6047 		if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
6048 			verbose(env, "cannot pass in dynptr at an offset\n");
6049 			return -EINVAL;
6050 		}
6051 		fallthrough;
6052 	case PTR_TO_PACKET:
6053 	case PTR_TO_PACKET_META:
6054 	case PTR_TO_MAP_KEY:
6055 	case PTR_TO_MAP_VALUE:
6056 	case PTR_TO_MEM:
6057 	case PTR_TO_MEM | MEM_RDONLY:
6058 	case PTR_TO_MEM | MEM_RINGBUF:
6059 	case PTR_TO_BUF:
6060 	case PTR_TO_BUF | MEM_RDONLY:
6061 	case SCALAR_VALUE:
6062 		/* Some of the argument types nevertheless require a
6063 		 * zero register offset.
6064 		 */
6065 		if (base_type(arg_type) != ARG_PTR_TO_RINGBUF_MEM)
6066 			return 0;
6067 		break;
6068 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6069 	 * fixed offset.
6070 	 */
6071 	case PTR_TO_BTF_ID:
6072 	case PTR_TO_BTF_ID | MEM_ALLOC:
6073 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6074 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6075 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6076 		 * it's fixed offset must be 0.	In the other cases, fixed offset
6077 		 * can be non-zero.
6078 		 */
6079 		if (arg_type_is_release(arg_type) && reg->off) {
6080 			verbose(env, "R%d must have zero offset when passed to release func\n",
6081 				regno);
6082 			return -EINVAL;
6083 		}
6084 		/* For arg is release pointer, fixed_off_ok must be false, but
6085 		 * we already checked and rejected reg->off != 0 above, so set
6086 		 * to true to allow fixed offset for all other cases.
6087 		 */
6088 		fixed_off_ok = true;
6089 		break;
6090 	default:
6091 		break;
6092 	}
6093 	return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
6094 }
6095 
6096 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6097 {
6098 	struct bpf_func_state *state = func(env, reg);
6099 	int spi = get_spi(reg->off);
6100 
6101 	return state->stack[spi].spilled_ptr.id;
6102 }
6103 
6104 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6105 			  struct bpf_call_arg_meta *meta,
6106 			  const struct bpf_func_proto *fn)
6107 {
6108 	u32 regno = BPF_REG_1 + arg;
6109 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6110 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6111 	enum bpf_reg_type type = reg->type;
6112 	u32 *arg_btf_id = NULL;
6113 	int err = 0;
6114 
6115 	if (arg_type == ARG_DONTCARE)
6116 		return 0;
6117 
6118 	err = check_reg_arg(env, regno, SRC_OP);
6119 	if (err)
6120 		return err;
6121 
6122 	if (arg_type == ARG_ANYTHING) {
6123 		if (is_pointer_value(env, regno)) {
6124 			verbose(env, "R%d leaks addr into helper function\n",
6125 				regno);
6126 			return -EACCES;
6127 		}
6128 		return 0;
6129 	}
6130 
6131 	if (type_is_pkt_pointer(type) &&
6132 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6133 		verbose(env, "helper access to the packet is not allowed\n");
6134 		return -EACCES;
6135 	}
6136 
6137 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6138 		err = resolve_map_arg_type(env, meta, &arg_type);
6139 		if (err)
6140 			return err;
6141 	}
6142 
6143 	if (register_is_null(reg) && type_may_be_null(arg_type))
6144 		/* A NULL register has a SCALAR_VALUE type, so skip
6145 		 * type checking.
6146 		 */
6147 		goto skip_type_check;
6148 
6149 	/* arg_btf_id and arg_size are in a union. */
6150 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6151 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6152 		arg_btf_id = fn->arg_btf_id[arg];
6153 
6154 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6155 	if (err)
6156 		return err;
6157 
6158 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6159 	if (err)
6160 		return err;
6161 
6162 skip_type_check:
6163 	if (arg_type_is_release(arg_type)) {
6164 		if (arg_type_is_dynptr(arg_type)) {
6165 			struct bpf_func_state *state = func(env, reg);
6166 			int spi = get_spi(reg->off);
6167 
6168 			if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6169 			    !state->stack[spi].spilled_ptr.id) {
6170 				verbose(env, "arg %d is an unacquired reference\n", regno);
6171 				return -EINVAL;
6172 			}
6173 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6174 			verbose(env, "R%d must be referenced when passed to release function\n",
6175 				regno);
6176 			return -EINVAL;
6177 		}
6178 		if (meta->release_regno) {
6179 			verbose(env, "verifier internal error: more than one release argument\n");
6180 			return -EFAULT;
6181 		}
6182 		meta->release_regno = regno;
6183 	}
6184 
6185 	if (reg->ref_obj_id) {
6186 		if (meta->ref_obj_id) {
6187 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6188 				regno, reg->ref_obj_id,
6189 				meta->ref_obj_id);
6190 			return -EFAULT;
6191 		}
6192 		meta->ref_obj_id = reg->ref_obj_id;
6193 	}
6194 
6195 	switch (base_type(arg_type)) {
6196 	case ARG_CONST_MAP_PTR:
6197 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6198 		if (meta->map_ptr) {
6199 			/* Use map_uid (which is unique id of inner map) to reject:
6200 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6201 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6202 			 * if (inner_map1 && inner_map2) {
6203 			 *     timer = bpf_map_lookup_elem(inner_map1);
6204 			 *     if (timer)
6205 			 *         // mismatch would have been allowed
6206 			 *         bpf_timer_init(timer, inner_map2);
6207 			 * }
6208 			 *
6209 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6210 			 */
6211 			if (meta->map_ptr != reg->map_ptr ||
6212 			    meta->map_uid != reg->map_uid) {
6213 				verbose(env,
6214 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6215 					meta->map_uid, reg->map_uid);
6216 				return -EINVAL;
6217 			}
6218 		}
6219 		meta->map_ptr = reg->map_ptr;
6220 		meta->map_uid = reg->map_uid;
6221 		break;
6222 	case ARG_PTR_TO_MAP_KEY:
6223 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6224 		 * check that [key, key + map->key_size) are within
6225 		 * stack limits and initialized
6226 		 */
6227 		if (!meta->map_ptr) {
6228 			/* in function declaration map_ptr must come before
6229 			 * map_key, so that it's verified and known before
6230 			 * we have to check map_key here. Otherwise it means
6231 			 * that kernel subsystem misconfigured verifier
6232 			 */
6233 			verbose(env, "invalid map_ptr to access map->key\n");
6234 			return -EACCES;
6235 		}
6236 		err = check_helper_mem_access(env, regno,
6237 					      meta->map_ptr->key_size, false,
6238 					      NULL);
6239 		break;
6240 	case ARG_PTR_TO_MAP_VALUE:
6241 		if (type_may_be_null(arg_type) && register_is_null(reg))
6242 			return 0;
6243 
6244 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6245 		 * check [value, value + map->value_size) validity
6246 		 */
6247 		if (!meta->map_ptr) {
6248 			/* kernel subsystem misconfigured verifier */
6249 			verbose(env, "invalid map_ptr to access map->value\n");
6250 			return -EACCES;
6251 		}
6252 		meta->raw_mode = arg_type & MEM_UNINIT;
6253 		err = check_helper_mem_access(env, regno,
6254 					      meta->map_ptr->value_size, false,
6255 					      meta);
6256 		break;
6257 	case ARG_PTR_TO_PERCPU_BTF_ID:
6258 		if (!reg->btf_id) {
6259 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6260 			return -EACCES;
6261 		}
6262 		meta->ret_btf = reg->btf;
6263 		meta->ret_btf_id = reg->btf_id;
6264 		break;
6265 	case ARG_PTR_TO_SPIN_LOCK:
6266 		if (meta->func_id == BPF_FUNC_spin_lock) {
6267 			if (process_spin_lock(env, regno, true))
6268 				return -EACCES;
6269 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6270 			if (process_spin_lock(env, regno, false))
6271 				return -EACCES;
6272 		} else {
6273 			verbose(env, "verifier internal error\n");
6274 			return -EFAULT;
6275 		}
6276 		break;
6277 	case ARG_PTR_TO_TIMER:
6278 		if (process_timer_func(env, regno, meta))
6279 			return -EACCES;
6280 		break;
6281 	case ARG_PTR_TO_FUNC:
6282 		meta->subprogno = reg->subprogno;
6283 		break;
6284 	case ARG_PTR_TO_MEM:
6285 		/* The access to this pointer is only checked when we hit the
6286 		 * next is_mem_size argument below.
6287 		 */
6288 		meta->raw_mode = arg_type & MEM_UNINIT;
6289 		if (arg_type & MEM_FIXED_SIZE) {
6290 			err = check_helper_mem_access(env, regno,
6291 						      fn->arg_size[arg], false,
6292 						      meta);
6293 		}
6294 		break;
6295 	case ARG_CONST_SIZE:
6296 		err = check_mem_size_reg(env, reg, regno, false, meta);
6297 		break;
6298 	case ARG_CONST_SIZE_OR_ZERO:
6299 		err = check_mem_size_reg(env, reg, regno, true, meta);
6300 		break;
6301 	case ARG_PTR_TO_DYNPTR:
6302 		/* We only need to check for initialized / uninitialized helper
6303 		 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6304 		 * assumption is that if it is, that a helper function
6305 		 * initialized the dynptr on behalf of the BPF program.
6306 		 */
6307 		if (base_type(reg->type) == PTR_TO_DYNPTR)
6308 			break;
6309 		if (arg_type & MEM_UNINIT) {
6310 			if (!is_dynptr_reg_valid_uninit(env, reg)) {
6311 				verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6312 				return -EINVAL;
6313 			}
6314 
6315 			/* We only support one dynptr being uninitialized at the moment,
6316 			 * which is sufficient for the helper functions we have right now.
6317 			 */
6318 			if (meta->uninit_dynptr_regno) {
6319 				verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6320 				return -EFAULT;
6321 			}
6322 
6323 			meta->uninit_dynptr_regno = regno;
6324 		} else if (!is_dynptr_reg_valid_init(env, reg)) {
6325 			verbose(env,
6326 				"Expected an initialized dynptr as arg #%d\n",
6327 				arg + 1);
6328 			return -EINVAL;
6329 		} else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6330 			const char *err_extra = "";
6331 
6332 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6333 			case DYNPTR_TYPE_LOCAL:
6334 				err_extra = "local";
6335 				break;
6336 			case DYNPTR_TYPE_RINGBUF:
6337 				err_extra = "ringbuf";
6338 				break;
6339 			default:
6340 				err_extra = "<unknown>";
6341 				break;
6342 			}
6343 			verbose(env,
6344 				"Expected a dynptr of type %s as arg #%d\n",
6345 				err_extra, arg + 1);
6346 			return -EINVAL;
6347 		}
6348 		break;
6349 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6350 		if (!tnum_is_const(reg->var_off)) {
6351 			verbose(env, "R%d is not a known constant'\n",
6352 				regno);
6353 			return -EACCES;
6354 		}
6355 		meta->mem_size = reg->var_off.value;
6356 		err = mark_chain_precision(env, regno);
6357 		if (err)
6358 			return err;
6359 		break;
6360 	case ARG_PTR_TO_INT:
6361 	case ARG_PTR_TO_LONG:
6362 	{
6363 		int size = int_ptr_type_to_size(arg_type);
6364 
6365 		err = check_helper_mem_access(env, regno, size, false, meta);
6366 		if (err)
6367 			return err;
6368 		err = check_ptr_alignment(env, reg, 0, size, true);
6369 		break;
6370 	}
6371 	case ARG_PTR_TO_CONST_STR:
6372 	{
6373 		struct bpf_map *map = reg->map_ptr;
6374 		int map_off;
6375 		u64 map_addr;
6376 		char *str_ptr;
6377 
6378 		if (!bpf_map_is_rdonly(map)) {
6379 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6380 			return -EACCES;
6381 		}
6382 
6383 		if (!tnum_is_const(reg->var_off)) {
6384 			verbose(env, "R%d is not a constant address'\n", regno);
6385 			return -EACCES;
6386 		}
6387 
6388 		if (!map->ops->map_direct_value_addr) {
6389 			verbose(env, "no direct value access support for this map type\n");
6390 			return -EACCES;
6391 		}
6392 
6393 		err = check_map_access(env, regno, reg->off,
6394 				       map->value_size - reg->off, false,
6395 				       ACCESS_HELPER);
6396 		if (err)
6397 			return err;
6398 
6399 		map_off = reg->off + reg->var_off.value;
6400 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6401 		if (err) {
6402 			verbose(env, "direct value access on string failed\n");
6403 			return err;
6404 		}
6405 
6406 		str_ptr = (char *)(long)(map_addr);
6407 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6408 			verbose(env, "string is not zero-terminated\n");
6409 			return -EINVAL;
6410 		}
6411 		break;
6412 	}
6413 	case ARG_PTR_TO_KPTR:
6414 		if (process_kptr_func(env, regno, meta))
6415 			return -EACCES;
6416 		break;
6417 	}
6418 
6419 	return err;
6420 }
6421 
6422 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6423 {
6424 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6425 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6426 
6427 	if (func_id != BPF_FUNC_map_update_elem)
6428 		return false;
6429 
6430 	/* It's not possible to get access to a locked struct sock in these
6431 	 * contexts, so updating is safe.
6432 	 */
6433 	switch (type) {
6434 	case BPF_PROG_TYPE_TRACING:
6435 		if (eatype == BPF_TRACE_ITER)
6436 			return true;
6437 		break;
6438 	case BPF_PROG_TYPE_SOCKET_FILTER:
6439 	case BPF_PROG_TYPE_SCHED_CLS:
6440 	case BPF_PROG_TYPE_SCHED_ACT:
6441 	case BPF_PROG_TYPE_XDP:
6442 	case BPF_PROG_TYPE_SK_REUSEPORT:
6443 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6444 	case BPF_PROG_TYPE_SK_LOOKUP:
6445 		return true;
6446 	default:
6447 		break;
6448 	}
6449 
6450 	verbose(env, "cannot update sockmap in this context\n");
6451 	return false;
6452 }
6453 
6454 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6455 {
6456 	return env->prog->jit_requested &&
6457 	       bpf_jit_supports_subprog_tailcalls();
6458 }
6459 
6460 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6461 					struct bpf_map *map, int func_id)
6462 {
6463 	if (!map)
6464 		return 0;
6465 
6466 	/* We need a two way check, first is from map perspective ... */
6467 	switch (map->map_type) {
6468 	case BPF_MAP_TYPE_PROG_ARRAY:
6469 		if (func_id != BPF_FUNC_tail_call)
6470 			goto error;
6471 		break;
6472 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6473 		if (func_id != BPF_FUNC_perf_event_read &&
6474 		    func_id != BPF_FUNC_perf_event_output &&
6475 		    func_id != BPF_FUNC_skb_output &&
6476 		    func_id != BPF_FUNC_perf_event_read_value &&
6477 		    func_id != BPF_FUNC_xdp_output)
6478 			goto error;
6479 		break;
6480 	case BPF_MAP_TYPE_RINGBUF:
6481 		if (func_id != BPF_FUNC_ringbuf_output &&
6482 		    func_id != BPF_FUNC_ringbuf_reserve &&
6483 		    func_id != BPF_FUNC_ringbuf_query &&
6484 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6485 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6486 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6487 			goto error;
6488 		break;
6489 	case BPF_MAP_TYPE_USER_RINGBUF:
6490 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6491 			goto error;
6492 		break;
6493 	case BPF_MAP_TYPE_STACK_TRACE:
6494 		if (func_id != BPF_FUNC_get_stackid)
6495 			goto error;
6496 		break;
6497 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6498 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6499 		    func_id != BPF_FUNC_current_task_under_cgroup)
6500 			goto error;
6501 		break;
6502 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6503 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6504 		if (func_id != BPF_FUNC_get_local_storage)
6505 			goto error;
6506 		break;
6507 	case BPF_MAP_TYPE_DEVMAP:
6508 	case BPF_MAP_TYPE_DEVMAP_HASH:
6509 		if (func_id != BPF_FUNC_redirect_map &&
6510 		    func_id != BPF_FUNC_map_lookup_elem)
6511 			goto error;
6512 		break;
6513 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6514 	 * appear.
6515 	 */
6516 	case BPF_MAP_TYPE_CPUMAP:
6517 		if (func_id != BPF_FUNC_redirect_map)
6518 			goto error;
6519 		break;
6520 	case BPF_MAP_TYPE_XSKMAP:
6521 		if (func_id != BPF_FUNC_redirect_map &&
6522 		    func_id != BPF_FUNC_map_lookup_elem)
6523 			goto error;
6524 		break;
6525 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6526 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6527 		if (func_id != BPF_FUNC_map_lookup_elem)
6528 			goto error;
6529 		break;
6530 	case BPF_MAP_TYPE_SOCKMAP:
6531 		if (func_id != BPF_FUNC_sk_redirect_map &&
6532 		    func_id != BPF_FUNC_sock_map_update &&
6533 		    func_id != BPF_FUNC_map_delete_elem &&
6534 		    func_id != BPF_FUNC_msg_redirect_map &&
6535 		    func_id != BPF_FUNC_sk_select_reuseport &&
6536 		    func_id != BPF_FUNC_map_lookup_elem &&
6537 		    !may_update_sockmap(env, func_id))
6538 			goto error;
6539 		break;
6540 	case BPF_MAP_TYPE_SOCKHASH:
6541 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6542 		    func_id != BPF_FUNC_sock_hash_update &&
6543 		    func_id != BPF_FUNC_map_delete_elem &&
6544 		    func_id != BPF_FUNC_msg_redirect_hash &&
6545 		    func_id != BPF_FUNC_sk_select_reuseport &&
6546 		    func_id != BPF_FUNC_map_lookup_elem &&
6547 		    !may_update_sockmap(env, func_id))
6548 			goto error;
6549 		break;
6550 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6551 		if (func_id != BPF_FUNC_sk_select_reuseport)
6552 			goto error;
6553 		break;
6554 	case BPF_MAP_TYPE_QUEUE:
6555 	case BPF_MAP_TYPE_STACK:
6556 		if (func_id != BPF_FUNC_map_peek_elem &&
6557 		    func_id != BPF_FUNC_map_pop_elem &&
6558 		    func_id != BPF_FUNC_map_push_elem)
6559 			goto error;
6560 		break;
6561 	case BPF_MAP_TYPE_SK_STORAGE:
6562 		if (func_id != BPF_FUNC_sk_storage_get &&
6563 		    func_id != BPF_FUNC_sk_storage_delete)
6564 			goto error;
6565 		break;
6566 	case BPF_MAP_TYPE_INODE_STORAGE:
6567 		if (func_id != BPF_FUNC_inode_storage_get &&
6568 		    func_id != BPF_FUNC_inode_storage_delete)
6569 			goto error;
6570 		break;
6571 	case BPF_MAP_TYPE_TASK_STORAGE:
6572 		if (func_id != BPF_FUNC_task_storage_get &&
6573 		    func_id != BPF_FUNC_task_storage_delete)
6574 			goto error;
6575 		break;
6576 	case BPF_MAP_TYPE_CGRP_STORAGE:
6577 		if (func_id != BPF_FUNC_cgrp_storage_get &&
6578 		    func_id != BPF_FUNC_cgrp_storage_delete)
6579 			goto error;
6580 		break;
6581 	case BPF_MAP_TYPE_BLOOM_FILTER:
6582 		if (func_id != BPF_FUNC_map_peek_elem &&
6583 		    func_id != BPF_FUNC_map_push_elem)
6584 			goto error;
6585 		break;
6586 	default:
6587 		break;
6588 	}
6589 
6590 	/* ... and second from the function itself. */
6591 	switch (func_id) {
6592 	case BPF_FUNC_tail_call:
6593 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6594 			goto error;
6595 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6596 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6597 			return -EINVAL;
6598 		}
6599 		break;
6600 	case BPF_FUNC_perf_event_read:
6601 	case BPF_FUNC_perf_event_output:
6602 	case BPF_FUNC_perf_event_read_value:
6603 	case BPF_FUNC_skb_output:
6604 	case BPF_FUNC_xdp_output:
6605 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6606 			goto error;
6607 		break;
6608 	case BPF_FUNC_ringbuf_output:
6609 	case BPF_FUNC_ringbuf_reserve:
6610 	case BPF_FUNC_ringbuf_query:
6611 	case BPF_FUNC_ringbuf_reserve_dynptr:
6612 	case BPF_FUNC_ringbuf_submit_dynptr:
6613 	case BPF_FUNC_ringbuf_discard_dynptr:
6614 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6615 			goto error;
6616 		break;
6617 	case BPF_FUNC_user_ringbuf_drain:
6618 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6619 			goto error;
6620 		break;
6621 	case BPF_FUNC_get_stackid:
6622 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6623 			goto error;
6624 		break;
6625 	case BPF_FUNC_current_task_under_cgroup:
6626 	case BPF_FUNC_skb_under_cgroup:
6627 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6628 			goto error;
6629 		break;
6630 	case BPF_FUNC_redirect_map:
6631 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6632 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6633 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6634 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6635 			goto error;
6636 		break;
6637 	case BPF_FUNC_sk_redirect_map:
6638 	case BPF_FUNC_msg_redirect_map:
6639 	case BPF_FUNC_sock_map_update:
6640 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6641 			goto error;
6642 		break;
6643 	case BPF_FUNC_sk_redirect_hash:
6644 	case BPF_FUNC_msg_redirect_hash:
6645 	case BPF_FUNC_sock_hash_update:
6646 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6647 			goto error;
6648 		break;
6649 	case BPF_FUNC_get_local_storage:
6650 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6651 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6652 			goto error;
6653 		break;
6654 	case BPF_FUNC_sk_select_reuseport:
6655 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6656 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6657 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6658 			goto error;
6659 		break;
6660 	case BPF_FUNC_map_pop_elem:
6661 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6662 		    map->map_type != BPF_MAP_TYPE_STACK)
6663 			goto error;
6664 		break;
6665 	case BPF_FUNC_map_peek_elem:
6666 	case BPF_FUNC_map_push_elem:
6667 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6668 		    map->map_type != BPF_MAP_TYPE_STACK &&
6669 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6670 			goto error;
6671 		break;
6672 	case BPF_FUNC_map_lookup_percpu_elem:
6673 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6674 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6675 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6676 			goto error;
6677 		break;
6678 	case BPF_FUNC_sk_storage_get:
6679 	case BPF_FUNC_sk_storage_delete:
6680 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6681 			goto error;
6682 		break;
6683 	case BPF_FUNC_inode_storage_get:
6684 	case BPF_FUNC_inode_storage_delete:
6685 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6686 			goto error;
6687 		break;
6688 	case BPF_FUNC_task_storage_get:
6689 	case BPF_FUNC_task_storage_delete:
6690 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6691 			goto error;
6692 		break;
6693 	case BPF_FUNC_cgrp_storage_get:
6694 	case BPF_FUNC_cgrp_storage_delete:
6695 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6696 			goto error;
6697 		break;
6698 	default:
6699 		break;
6700 	}
6701 
6702 	return 0;
6703 error:
6704 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6705 		map->map_type, func_id_name(func_id), func_id);
6706 	return -EINVAL;
6707 }
6708 
6709 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6710 {
6711 	int count = 0;
6712 
6713 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6714 		count++;
6715 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6716 		count++;
6717 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6718 		count++;
6719 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6720 		count++;
6721 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6722 		count++;
6723 
6724 	/* We only support one arg being in raw mode at the moment,
6725 	 * which is sufficient for the helper functions we have
6726 	 * right now.
6727 	 */
6728 	return count <= 1;
6729 }
6730 
6731 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6732 {
6733 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6734 	bool has_size = fn->arg_size[arg] != 0;
6735 	bool is_next_size = false;
6736 
6737 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6738 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6739 
6740 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6741 		return is_next_size;
6742 
6743 	return has_size == is_next_size || is_next_size == is_fixed;
6744 }
6745 
6746 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6747 {
6748 	/* bpf_xxx(..., buf, len) call will access 'len'
6749 	 * bytes from memory 'buf'. Both arg types need
6750 	 * to be paired, so make sure there's no buggy
6751 	 * helper function specification.
6752 	 */
6753 	if (arg_type_is_mem_size(fn->arg1_type) ||
6754 	    check_args_pair_invalid(fn, 0) ||
6755 	    check_args_pair_invalid(fn, 1) ||
6756 	    check_args_pair_invalid(fn, 2) ||
6757 	    check_args_pair_invalid(fn, 3) ||
6758 	    check_args_pair_invalid(fn, 4))
6759 		return false;
6760 
6761 	return true;
6762 }
6763 
6764 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6765 {
6766 	int i;
6767 
6768 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6769 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6770 			return !!fn->arg_btf_id[i];
6771 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
6772 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
6773 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6774 		    /* arg_btf_id and arg_size are in a union. */
6775 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6776 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6777 			return false;
6778 	}
6779 
6780 	return true;
6781 }
6782 
6783 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6784 {
6785 	return check_raw_mode_ok(fn) &&
6786 	       check_arg_pair_ok(fn) &&
6787 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
6788 }
6789 
6790 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6791  * are now invalid, so turn them into unknown SCALAR_VALUE.
6792  */
6793 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6794 {
6795 	struct bpf_func_state *state;
6796 	struct bpf_reg_state *reg;
6797 
6798 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6799 		if (reg_is_pkt_pointer_any(reg))
6800 			__mark_reg_unknown(env, reg);
6801 	}));
6802 }
6803 
6804 enum {
6805 	AT_PKT_END = -1,
6806 	BEYOND_PKT_END = -2,
6807 };
6808 
6809 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6810 {
6811 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6812 	struct bpf_reg_state *reg = &state->regs[regn];
6813 
6814 	if (reg->type != PTR_TO_PACKET)
6815 		/* PTR_TO_PACKET_META is not supported yet */
6816 		return;
6817 
6818 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6819 	 * How far beyond pkt_end it goes is unknown.
6820 	 * if (!range_open) it's the case of pkt >= pkt_end
6821 	 * if (range_open) it's the case of pkt > pkt_end
6822 	 * hence this pointer is at least 1 byte bigger than pkt_end
6823 	 */
6824 	if (range_open)
6825 		reg->range = BEYOND_PKT_END;
6826 	else
6827 		reg->range = AT_PKT_END;
6828 }
6829 
6830 /* The pointer with the specified id has released its reference to kernel
6831  * resources. Identify all copies of the same pointer and clear the reference.
6832  */
6833 static int release_reference(struct bpf_verifier_env *env,
6834 			     int ref_obj_id)
6835 {
6836 	struct bpf_func_state *state;
6837 	struct bpf_reg_state *reg;
6838 	int err;
6839 
6840 	err = release_reference_state(cur_func(env), ref_obj_id);
6841 	if (err)
6842 		return err;
6843 
6844 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6845 		if (reg->ref_obj_id == ref_obj_id) {
6846 			if (!env->allow_ptr_leaks)
6847 				__mark_reg_not_init(env, reg);
6848 			else
6849 				__mark_reg_unknown(env, reg);
6850 		}
6851 	}));
6852 
6853 	return 0;
6854 }
6855 
6856 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6857 				    struct bpf_reg_state *regs)
6858 {
6859 	int i;
6860 
6861 	/* after the call registers r0 - r5 were scratched */
6862 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6863 		mark_reg_not_init(env, regs, caller_saved[i]);
6864 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6865 	}
6866 }
6867 
6868 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6869 				   struct bpf_func_state *caller,
6870 				   struct bpf_func_state *callee,
6871 				   int insn_idx);
6872 
6873 static int set_callee_state(struct bpf_verifier_env *env,
6874 			    struct bpf_func_state *caller,
6875 			    struct bpf_func_state *callee, int insn_idx);
6876 
6877 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6878 			     int *insn_idx, int subprog,
6879 			     set_callee_state_fn set_callee_state_cb)
6880 {
6881 	struct bpf_verifier_state *state = env->cur_state;
6882 	struct bpf_func_info_aux *func_info_aux;
6883 	struct bpf_func_state *caller, *callee;
6884 	int err;
6885 	bool is_global = false;
6886 
6887 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6888 		verbose(env, "the call stack of %d frames is too deep\n",
6889 			state->curframe + 2);
6890 		return -E2BIG;
6891 	}
6892 
6893 	caller = state->frame[state->curframe];
6894 	if (state->frame[state->curframe + 1]) {
6895 		verbose(env, "verifier bug. Frame %d already allocated\n",
6896 			state->curframe + 1);
6897 		return -EFAULT;
6898 	}
6899 
6900 	func_info_aux = env->prog->aux->func_info_aux;
6901 	if (func_info_aux)
6902 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6903 	err = btf_check_subprog_call(env, subprog, caller->regs);
6904 	if (err == -EFAULT)
6905 		return err;
6906 	if (is_global) {
6907 		if (err) {
6908 			verbose(env, "Caller passes invalid args into func#%d\n",
6909 				subprog);
6910 			return err;
6911 		} else {
6912 			if (env->log.level & BPF_LOG_LEVEL)
6913 				verbose(env,
6914 					"Func#%d is global and valid. Skipping.\n",
6915 					subprog);
6916 			clear_caller_saved_regs(env, caller->regs);
6917 
6918 			/* All global functions return a 64-bit SCALAR_VALUE */
6919 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6920 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6921 
6922 			/* continue with next insn after call */
6923 			return 0;
6924 		}
6925 	}
6926 
6927 	/* set_callee_state is used for direct subprog calls, but we are
6928 	 * interested in validating only BPF helpers that can call subprogs as
6929 	 * callbacks
6930 	 */
6931 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6932 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6933 			func_id_name(insn->imm), insn->imm);
6934 		return -EFAULT;
6935 	}
6936 
6937 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6938 	    insn->src_reg == 0 &&
6939 	    insn->imm == BPF_FUNC_timer_set_callback) {
6940 		struct bpf_verifier_state *async_cb;
6941 
6942 		/* there is no real recursion here. timer callbacks are async */
6943 		env->subprog_info[subprog].is_async_cb = true;
6944 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6945 					 *insn_idx, subprog);
6946 		if (!async_cb)
6947 			return -EFAULT;
6948 		callee = async_cb->frame[0];
6949 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6950 
6951 		/* Convert bpf_timer_set_callback() args into timer callback args */
6952 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6953 		if (err)
6954 			return err;
6955 
6956 		clear_caller_saved_regs(env, caller->regs);
6957 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6958 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6959 		/* continue with next insn after call */
6960 		return 0;
6961 	}
6962 
6963 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6964 	if (!callee)
6965 		return -ENOMEM;
6966 	state->frame[state->curframe + 1] = callee;
6967 
6968 	/* callee cannot access r0, r6 - r9 for reading and has to write
6969 	 * into its own stack before reading from it.
6970 	 * callee can read/write into caller's stack
6971 	 */
6972 	init_func_state(env, callee,
6973 			/* remember the callsite, it will be used by bpf_exit */
6974 			*insn_idx /* callsite */,
6975 			state->curframe + 1 /* frameno within this callchain */,
6976 			subprog /* subprog number within this prog */);
6977 
6978 	/* Transfer references to the callee */
6979 	err = copy_reference_state(callee, caller);
6980 	if (err)
6981 		return err;
6982 
6983 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6984 	if (err)
6985 		return err;
6986 
6987 	clear_caller_saved_regs(env, caller->regs);
6988 
6989 	/* only increment it after check_reg_arg() finished */
6990 	state->curframe++;
6991 
6992 	/* and go analyze first insn of the callee */
6993 	*insn_idx = env->subprog_info[subprog].start - 1;
6994 
6995 	if (env->log.level & BPF_LOG_LEVEL) {
6996 		verbose(env, "caller:\n");
6997 		print_verifier_state(env, caller, true);
6998 		verbose(env, "callee:\n");
6999 		print_verifier_state(env, callee, true);
7000 	}
7001 	return 0;
7002 }
7003 
7004 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7005 				   struct bpf_func_state *caller,
7006 				   struct bpf_func_state *callee)
7007 {
7008 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7009 	 *      void *callback_ctx, u64 flags);
7010 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7011 	 *      void *callback_ctx);
7012 	 */
7013 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7014 
7015 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7016 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7017 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7018 
7019 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7020 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7021 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7022 
7023 	/* pointer to stack or null */
7024 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7025 
7026 	/* unused */
7027 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7028 	return 0;
7029 }
7030 
7031 static int set_callee_state(struct bpf_verifier_env *env,
7032 			    struct bpf_func_state *caller,
7033 			    struct bpf_func_state *callee, int insn_idx)
7034 {
7035 	int i;
7036 
7037 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7038 	 * pointers, which connects us up to the liveness chain
7039 	 */
7040 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7041 		callee->regs[i] = caller->regs[i];
7042 	return 0;
7043 }
7044 
7045 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7046 			   int *insn_idx)
7047 {
7048 	int subprog, target_insn;
7049 
7050 	target_insn = *insn_idx + insn->imm + 1;
7051 	subprog = find_subprog(env, target_insn);
7052 	if (subprog < 0) {
7053 		verbose(env, "verifier bug. No program starts at insn %d\n",
7054 			target_insn);
7055 		return -EFAULT;
7056 	}
7057 
7058 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7059 }
7060 
7061 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7062 				       struct bpf_func_state *caller,
7063 				       struct bpf_func_state *callee,
7064 				       int insn_idx)
7065 {
7066 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7067 	struct bpf_map *map;
7068 	int err;
7069 
7070 	if (bpf_map_ptr_poisoned(insn_aux)) {
7071 		verbose(env, "tail_call abusing map_ptr\n");
7072 		return -EINVAL;
7073 	}
7074 
7075 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7076 	if (!map->ops->map_set_for_each_callback_args ||
7077 	    !map->ops->map_for_each_callback) {
7078 		verbose(env, "callback function not allowed for map\n");
7079 		return -ENOTSUPP;
7080 	}
7081 
7082 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7083 	if (err)
7084 		return err;
7085 
7086 	callee->in_callback_fn = true;
7087 	callee->callback_ret_range = tnum_range(0, 1);
7088 	return 0;
7089 }
7090 
7091 static int set_loop_callback_state(struct bpf_verifier_env *env,
7092 				   struct bpf_func_state *caller,
7093 				   struct bpf_func_state *callee,
7094 				   int insn_idx)
7095 {
7096 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7097 	 *	    u64 flags);
7098 	 * callback_fn(u32 index, void *callback_ctx);
7099 	 */
7100 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7101 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7102 
7103 	/* unused */
7104 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7105 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7106 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7107 
7108 	callee->in_callback_fn = true;
7109 	callee->callback_ret_range = tnum_range(0, 1);
7110 	return 0;
7111 }
7112 
7113 static int set_timer_callback_state(struct bpf_verifier_env *env,
7114 				    struct bpf_func_state *caller,
7115 				    struct bpf_func_state *callee,
7116 				    int insn_idx)
7117 {
7118 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7119 
7120 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7121 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7122 	 */
7123 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7124 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7125 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7126 
7127 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7128 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7129 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7130 
7131 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7132 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7133 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7134 
7135 	/* unused */
7136 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7137 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7138 	callee->in_async_callback_fn = true;
7139 	callee->callback_ret_range = tnum_range(0, 1);
7140 	return 0;
7141 }
7142 
7143 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7144 				       struct bpf_func_state *caller,
7145 				       struct bpf_func_state *callee,
7146 				       int insn_idx)
7147 {
7148 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7149 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7150 	 * (callback_fn)(struct task_struct *task,
7151 	 *               struct vm_area_struct *vma, void *callback_ctx);
7152 	 */
7153 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7154 
7155 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7156 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7157 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7158 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7159 
7160 	/* pointer to stack or null */
7161 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7162 
7163 	/* unused */
7164 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7165 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7166 	callee->in_callback_fn = true;
7167 	callee->callback_ret_range = tnum_range(0, 1);
7168 	return 0;
7169 }
7170 
7171 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7172 					   struct bpf_func_state *caller,
7173 					   struct bpf_func_state *callee,
7174 					   int insn_idx)
7175 {
7176 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7177 	 *			  callback_ctx, u64 flags);
7178 	 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7179 	 */
7180 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7181 	callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7182 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7183 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7184 
7185 	/* unused */
7186 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7187 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7188 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7189 
7190 	callee->in_callback_fn = true;
7191 	callee->callback_ret_range = tnum_range(0, 1);
7192 	return 0;
7193 }
7194 
7195 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7196 {
7197 	struct bpf_verifier_state *state = env->cur_state;
7198 	struct bpf_func_state *caller, *callee;
7199 	struct bpf_reg_state *r0;
7200 	int err;
7201 
7202 	callee = state->frame[state->curframe];
7203 	r0 = &callee->regs[BPF_REG_0];
7204 	if (r0->type == PTR_TO_STACK) {
7205 		/* technically it's ok to return caller's stack pointer
7206 		 * (or caller's caller's pointer) back to the caller,
7207 		 * since these pointers are valid. Only current stack
7208 		 * pointer will be invalid as soon as function exits,
7209 		 * but let's be conservative
7210 		 */
7211 		verbose(env, "cannot return stack pointer to the caller\n");
7212 		return -EINVAL;
7213 	}
7214 
7215 	state->curframe--;
7216 	caller = state->frame[state->curframe];
7217 	if (callee->in_callback_fn) {
7218 		/* enforce R0 return value range [0, 1]. */
7219 		struct tnum range = callee->callback_ret_range;
7220 
7221 		if (r0->type != SCALAR_VALUE) {
7222 			verbose(env, "R0 not a scalar value\n");
7223 			return -EACCES;
7224 		}
7225 		if (!tnum_in(range, r0->var_off)) {
7226 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7227 			return -EINVAL;
7228 		}
7229 	} else {
7230 		/* return to the caller whatever r0 had in the callee */
7231 		caller->regs[BPF_REG_0] = *r0;
7232 	}
7233 
7234 	/* callback_fn frame should have released its own additions to parent's
7235 	 * reference state at this point, or check_reference_leak would
7236 	 * complain, hence it must be the same as the caller. There is no need
7237 	 * to copy it back.
7238 	 */
7239 	if (!callee->in_callback_fn) {
7240 		/* Transfer references to the caller */
7241 		err = copy_reference_state(caller, callee);
7242 		if (err)
7243 			return err;
7244 	}
7245 
7246 	*insn_idx = callee->callsite + 1;
7247 	if (env->log.level & BPF_LOG_LEVEL) {
7248 		verbose(env, "returning from callee:\n");
7249 		print_verifier_state(env, callee, true);
7250 		verbose(env, "to caller at %d:\n", *insn_idx);
7251 		print_verifier_state(env, caller, true);
7252 	}
7253 	/* clear everything in the callee */
7254 	free_func_state(callee);
7255 	state->frame[state->curframe + 1] = NULL;
7256 	return 0;
7257 }
7258 
7259 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7260 				   int func_id,
7261 				   struct bpf_call_arg_meta *meta)
7262 {
7263 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7264 
7265 	if (ret_type != RET_INTEGER ||
7266 	    (func_id != BPF_FUNC_get_stack &&
7267 	     func_id != BPF_FUNC_get_task_stack &&
7268 	     func_id != BPF_FUNC_probe_read_str &&
7269 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7270 	     func_id != BPF_FUNC_probe_read_user_str))
7271 		return;
7272 
7273 	ret_reg->smax_value = meta->msize_max_value;
7274 	ret_reg->s32_max_value = meta->msize_max_value;
7275 	ret_reg->smin_value = -MAX_ERRNO;
7276 	ret_reg->s32_min_value = -MAX_ERRNO;
7277 	reg_bounds_sync(ret_reg);
7278 }
7279 
7280 static int
7281 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7282 		int func_id, int insn_idx)
7283 {
7284 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7285 	struct bpf_map *map = meta->map_ptr;
7286 
7287 	if (func_id != BPF_FUNC_tail_call &&
7288 	    func_id != BPF_FUNC_map_lookup_elem &&
7289 	    func_id != BPF_FUNC_map_update_elem &&
7290 	    func_id != BPF_FUNC_map_delete_elem &&
7291 	    func_id != BPF_FUNC_map_push_elem &&
7292 	    func_id != BPF_FUNC_map_pop_elem &&
7293 	    func_id != BPF_FUNC_map_peek_elem &&
7294 	    func_id != BPF_FUNC_for_each_map_elem &&
7295 	    func_id != BPF_FUNC_redirect_map &&
7296 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7297 		return 0;
7298 
7299 	if (map == NULL) {
7300 		verbose(env, "kernel subsystem misconfigured verifier\n");
7301 		return -EINVAL;
7302 	}
7303 
7304 	/* In case of read-only, some additional restrictions
7305 	 * need to be applied in order to prevent altering the
7306 	 * state of the map from program side.
7307 	 */
7308 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7309 	    (func_id == BPF_FUNC_map_delete_elem ||
7310 	     func_id == BPF_FUNC_map_update_elem ||
7311 	     func_id == BPF_FUNC_map_push_elem ||
7312 	     func_id == BPF_FUNC_map_pop_elem)) {
7313 		verbose(env, "write into map forbidden\n");
7314 		return -EACCES;
7315 	}
7316 
7317 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7318 		bpf_map_ptr_store(aux, meta->map_ptr,
7319 				  !meta->map_ptr->bypass_spec_v1);
7320 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7321 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7322 				  !meta->map_ptr->bypass_spec_v1);
7323 	return 0;
7324 }
7325 
7326 static int
7327 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7328 		int func_id, int insn_idx)
7329 {
7330 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7331 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7332 	struct bpf_map *map = meta->map_ptr;
7333 	u64 val, max;
7334 	int err;
7335 
7336 	if (func_id != BPF_FUNC_tail_call)
7337 		return 0;
7338 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7339 		verbose(env, "kernel subsystem misconfigured verifier\n");
7340 		return -EINVAL;
7341 	}
7342 
7343 	reg = &regs[BPF_REG_3];
7344 	val = reg->var_off.value;
7345 	max = map->max_entries;
7346 
7347 	if (!(register_is_const(reg) && val < max)) {
7348 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7349 		return 0;
7350 	}
7351 
7352 	err = mark_chain_precision(env, BPF_REG_3);
7353 	if (err)
7354 		return err;
7355 	if (bpf_map_key_unseen(aux))
7356 		bpf_map_key_store(aux, val);
7357 	else if (!bpf_map_key_poisoned(aux) &&
7358 		  bpf_map_key_immediate(aux) != val)
7359 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7360 	return 0;
7361 }
7362 
7363 static int check_reference_leak(struct bpf_verifier_env *env)
7364 {
7365 	struct bpf_func_state *state = cur_func(env);
7366 	bool refs_lingering = false;
7367 	int i;
7368 
7369 	if (state->frameno && !state->in_callback_fn)
7370 		return 0;
7371 
7372 	for (i = 0; i < state->acquired_refs; i++) {
7373 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7374 			continue;
7375 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7376 			state->refs[i].id, state->refs[i].insn_idx);
7377 		refs_lingering = true;
7378 	}
7379 	return refs_lingering ? -EINVAL : 0;
7380 }
7381 
7382 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7383 				   struct bpf_reg_state *regs)
7384 {
7385 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7386 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7387 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7388 	int err, fmt_map_off, num_args;
7389 	u64 fmt_addr;
7390 	char *fmt;
7391 
7392 	/* data must be an array of u64 */
7393 	if (data_len_reg->var_off.value % 8)
7394 		return -EINVAL;
7395 	num_args = data_len_reg->var_off.value / 8;
7396 
7397 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7398 	 * and map_direct_value_addr is set.
7399 	 */
7400 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7401 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7402 						  fmt_map_off);
7403 	if (err) {
7404 		verbose(env, "verifier bug\n");
7405 		return -EFAULT;
7406 	}
7407 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7408 
7409 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7410 	 * can focus on validating the format specifiers.
7411 	 */
7412 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7413 	if (err < 0)
7414 		verbose(env, "Invalid format string\n");
7415 
7416 	return err;
7417 }
7418 
7419 static int check_get_func_ip(struct bpf_verifier_env *env)
7420 {
7421 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7422 	int func_id = BPF_FUNC_get_func_ip;
7423 
7424 	if (type == BPF_PROG_TYPE_TRACING) {
7425 		if (!bpf_prog_has_trampoline(env->prog)) {
7426 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7427 				func_id_name(func_id), func_id);
7428 			return -ENOTSUPP;
7429 		}
7430 		return 0;
7431 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7432 		return 0;
7433 	}
7434 
7435 	verbose(env, "func %s#%d not supported for program type %d\n",
7436 		func_id_name(func_id), func_id, type);
7437 	return -ENOTSUPP;
7438 }
7439 
7440 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7441 {
7442 	return &env->insn_aux_data[env->insn_idx];
7443 }
7444 
7445 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7446 {
7447 	struct bpf_reg_state *regs = cur_regs(env);
7448 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7449 	bool reg_is_null = register_is_null(reg);
7450 
7451 	if (reg_is_null)
7452 		mark_chain_precision(env, BPF_REG_4);
7453 
7454 	return reg_is_null;
7455 }
7456 
7457 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7458 {
7459 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7460 
7461 	if (!state->initialized) {
7462 		state->initialized = 1;
7463 		state->fit_for_inline = loop_flag_is_zero(env);
7464 		state->callback_subprogno = subprogno;
7465 		return;
7466 	}
7467 
7468 	if (!state->fit_for_inline)
7469 		return;
7470 
7471 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7472 				 state->callback_subprogno == subprogno);
7473 }
7474 
7475 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7476 			     int *insn_idx_p)
7477 {
7478 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7479 	const struct bpf_func_proto *fn = NULL;
7480 	enum bpf_return_type ret_type;
7481 	enum bpf_type_flag ret_flag;
7482 	struct bpf_reg_state *regs;
7483 	struct bpf_call_arg_meta meta;
7484 	int insn_idx = *insn_idx_p;
7485 	bool changes_data;
7486 	int i, err, func_id;
7487 
7488 	/* find function prototype */
7489 	func_id = insn->imm;
7490 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7491 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7492 			func_id);
7493 		return -EINVAL;
7494 	}
7495 
7496 	if (env->ops->get_func_proto)
7497 		fn = env->ops->get_func_proto(func_id, env->prog);
7498 	if (!fn) {
7499 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7500 			func_id);
7501 		return -EINVAL;
7502 	}
7503 
7504 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7505 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7506 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7507 		return -EINVAL;
7508 	}
7509 
7510 	if (fn->allowed && !fn->allowed(env->prog)) {
7511 		verbose(env, "helper call is not allowed in probe\n");
7512 		return -EINVAL;
7513 	}
7514 
7515 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7516 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7517 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7518 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7519 			func_id_name(func_id), func_id);
7520 		return -EINVAL;
7521 	}
7522 
7523 	memset(&meta, 0, sizeof(meta));
7524 	meta.pkt_access = fn->pkt_access;
7525 
7526 	err = check_func_proto(fn, func_id);
7527 	if (err) {
7528 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7529 			func_id_name(func_id), func_id);
7530 		return err;
7531 	}
7532 
7533 	meta.func_id = func_id;
7534 	/* check args */
7535 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7536 		err = check_func_arg(env, i, &meta, fn);
7537 		if (err)
7538 			return err;
7539 	}
7540 
7541 	err = record_func_map(env, &meta, func_id, insn_idx);
7542 	if (err)
7543 		return err;
7544 
7545 	err = record_func_key(env, &meta, func_id, insn_idx);
7546 	if (err)
7547 		return err;
7548 
7549 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7550 	 * is inferred from register state.
7551 	 */
7552 	for (i = 0; i < meta.access_size; i++) {
7553 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7554 				       BPF_WRITE, -1, false);
7555 		if (err)
7556 			return err;
7557 	}
7558 
7559 	regs = cur_regs(env);
7560 
7561 	if (meta.uninit_dynptr_regno) {
7562 		/* we write BPF_DW bits (8 bytes) at a time */
7563 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7564 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7565 					       i, BPF_DW, BPF_WRITE, -1, false);
7566 			if (err)
7567 				return err;
7568 		}
7569 
7570 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7571 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7572 					      insn_idx);
7573 		if (err)
7574 			return err;
7575 	}
7576 
7577 	if (meta.release_regno) {
7578 		err = -EINVAL;
7579 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7580 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7581 		else if (meta.ref_obj_id)
7582 			err = release_reference(env, meta.ref_obj_id);
7583 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7584 		 * released is NULL, which must be > R0.
7585 		 */
7586 		else if (register_is_null(&regs[meta.release_regno]))
7587 			err = 0;
7588 		if (err) {
7589 			verbose(env, "func %s#%d reference has not been acquired before\n",
7590 				func_id_name(func_id), func_id);
7591 			return err;
7592 		}
7593 	}
7594 
7595 	switch (func_id) {
7596 	case BPF_FUNC_tail_call:
7597 		err = check_reference_leak(env);
7598 		if (err) {
7599 			verbose(env, "tail_call would lead to reference leak\n");
7600 			return err;
7601 		}
7602 		break;
7603 	case BPF_FUNC_get_local_storage:
7604 		/* check that flags argument in get_local_storage(map, flags) is 0,
7605 		 * this is required because get_local_storage() can't return an error.
7606 		 */
7607 		if (!register_is_null(&regs[BPF_REG_2])) {
7608 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7609 			return -EINVAL;
7610 		}
7611 		break;
7612 	case BPF_FUNC_for_each_map_elem:
7613 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7614 					set_map_elem_callback_state);
7615 		break;
7616 	case BPF_FUNC_timer_set_callback:
7617 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7618 					set_timer_callback_state);
7619 		break;
7620 	case BPF_FUNC_find_vma:
7621 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7622 					set_find_vma_callback_state);
7623 		break;
7624 	case BPF_FUNC_snprintf:
7625 		err = check_bpf_snprintf_call(env, regs);
7626 		break;
7627 	case BPF_FUNC_loop:
7628 		update_loop_inline_state(env, meta.subprogno);
7629 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7630 					set_loop_callback_state);
7631 		break;
7632 	case BPF_FUNC_dynptr_from_mem:
7633 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7634 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7635 				reg_type_str(env, regs[BPF_REG_1].type));
7636 			return -EACCES;
7637 		}
7638 		break;
7639 	case BPF_FUNC_set_retval:
7640 		if (prog_type == BPF_PROG_TYPE_LSM &&
7641 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7642 			if (!env->prog->aux->attach_func_proto->type) {
7643 				/* Make sure programs that attach to void
7644 				 * hooks don't try to modify return value.
7645 				 */
7646 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7647 				return -EINVAL;
7648 			}
7649 		}
7650 		break;
7651 	case BPF_FUNC_dynptr_data:
7652 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7653 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7654 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7655 
7656 				if (meta.ref_obj_id) {
7657 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7658 					return -EFAULT;
7659 				}
7660 
7661 				if (base_type(reg->type) != PTR_TO_DYNPTR)
7662 					/* Find the id of the dynptr we're
7663 					 * tracking the reference of
7664 					 */
7665 					meta.ref_obj_id = stack_slot_get_id(env, reg);
7666 				break;
7667 			}
7668 		}
7669 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7670 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7671 			return -EFAULT;
7672 		}
7673 		break;
7674 	case BPF_FUNC_user_ringbuf_drain:
7675 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7676 					set_user_ringbuf_callback_state);
7677 		break;
7678 	}
7679 
7680 	if (err)
7681 		return err;
7682 
7683 	/* reset caller saved regs */
7684 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7685 		mark_reg_not_init(env, regs, caller_saved[i]);
7686 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7687 	}
7688 
7689 	/* helper call returns 64-bit value. */
7690 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7691 
7692 	/* update return register (already marked as written above) */
7693 	ret_type = fn->ret_type;
7694 	ret_flag = type_flag(ret_type);
7695 
7696 	switch (base_type(ret_type)) {
7697 	case RET_INTEGER:
7698 		/* sets type to SCALAR_VALUE */
7699 		mark_reg_unknown(env, regs, BPF_REG_0);
7700 		break;
7701 	case RET_VOID:
7702 		regs[BPF_REG_0].type = NOT_INIT;
7703 		break;
7704 	case RET_PTR_TO_MAP_VALUE:
7705 		/* There is no offset yet applied, variable or fixed */
7706 		mark_reg_known_zero(env, regs, BPF_REG_0);
7707 		/* remember map_ptr, so that check_map_access()
7708 		 * can check 'value_size' boundary of memory access
7709 		 * to map element returned from bpf_map_lookup_elem()
7710 		 */
7711 		if (meta.map_ptr == NULL) {
7712 			verbose(env,
7713 				"kernel subsystem misconfigured verifier\n");
7714 			return -EINVAL;
7715 		}
7716 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7717 		regs[BPF_REG_0].map_uid = meta.map_uid;
7718 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7719 		if (!type_may_be_null(ret_type) &&
7720 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7721 			regs[BPF_REG_0].id = ++env->id_gen;
7722 		}
7723 		break;
7724 	case RET_PTR_TO_SOCKET:
7725 		mark_reg_known_zero(env, regs, BPF_REG_0);
7726 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7727 		break;
7728 	case RET_PTR_TO_SOCK_COMMON:
7729 		mark_reg_known_zero(env, regs, BPF_REG_0);
7730 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7731 		break;
7732 	case RET_PTR_TO_TCP_SOCK:
7733 		mark_reg_known_zero(env, regs, BPF_REG_0);
7734 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7735 		break;
7736 	case RET_PTR_TO_MEM:
7737 		mark_reg_known_zero(env, regs, BPF_REG_0);
7738 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7739 		regs[BPF_REG_0].mem_size = meta.mem_size;
7740 		break;
7741 	case RET_PTR_TO_MEM_OR_BTF_ID:
7742 	{
7743 		const struct btf_type *t;
7744 
7745 		mark_reg_known_zero(env, regs, BPF_REG_0);
7746 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7747 		if (!btf_type_is_struct(t)) {
7748 			u32 tsize;
7749 			const struct btf_type *ret;
7750 			const char *tname;
7751 
7752 			/* resolve the type size of ksym. */
7753 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7754 			if (IS_ERR(ret)) {
7755 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7756 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7757 					tname, PTR_ERR(ret));
7758 				return -EINVAL;
7759 			}
7760 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7761 			regs[BPF_REG_0].mem_size = tsize;
7762 		} else {
7763 			/* MEM_RDONLY may be carried from ret_flag, but it
7764 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7765 			 * it will confuse the check of PTR_TO_BTF_ID in
7766 			 * check_mem_access().
7767 			 */
7768 			ret_flag &= ~MEM_RDONLY;
7769 
7770 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7771 			regs[BPF_REG_0].btf = meta.ret_btf;
7772 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7773 		}
7774 		break;
7775 	}
7776 	case RET_PTR_TO_BTF_ID:
7777 	{
7778 		struct btf *ret_btf;
7779 		int ret_btf_id;
7780 
7781 		mark_reg_known_zero(env, regs, BPF_REG_0);
7782 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7783 		if (func_id == BPF_FUNC_kptr_xchg) {
7784 			ret_btf = meta.kptr_field->kptr.btf;
7785 			ret_btf_id = meta.kptr_field->kptr.btf_id;
7786 		} else {
7787 			if (fn->ret_btf_id == BPF_PTR_POISON) {
7788 				verbose(env, "verifier internal error:");
7789 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7790 					func_id_name(func_id));
7791 				return -EINVAL;
7792 			}
7793 			ret_btf = btf_vmlinux;
7794 			ret_btf_id = *fn->ret_btf_id;
7795 		}
7796 		if (ret_btf_id == 0) {
7797 			verbose(env, "invalid return type %u of func %s#%d\n",
7798 				base_type(ret_type), func_id_name(func_id),
7799 				func_id);
7800 			return -EINVAL;
7801 		}
7802 		regs[BPF_REG_0].btf = ret_btf;
7803 		regs[BPF_REG_0].btf_id = ret_btf_id;
7804 		break;
7805 	}
7806 	default:
7807 		verbose(env, "unknown return type %u of func %s#%d\n",
7808 			base_type(ret_type), func_id_name(func_id), func_id);
7809 		return -EINVAL;
7810 	}
7811 
7812 	if (type_may_be_null(regs[BPF_REG_0].type))
7813 		regs[BPF_REG_0].id = ++env->id_gen;
7814 
7815 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7816 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7817 			func_id_name(func_id), func_id);
7818 		return -EFAULT;
7819 	}
7820 
7821 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7822 		/* For release_reference() */
7823 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7824 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7825 		int id = acquire_reference_state(env, insn_idx);
7826 
7827 		if (id < 0)
7828 			return id;
7829 		/* For mark_ptr_or_null_reg() */
7830 		regs[BPF_REG_0].id = id;
7831 		/* For release_reference() */
7832 		regs[BPF_REG_0].ref_obj_id = id;
7833 	}
7834 
7835 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7836 
7837 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7838 	if (err)
7839 		return err;
7840 
7841 	if ((func_id == BPF_FUNC_get_stack ||
7842 	     func_id == BPF_FUNC_get_task_stack) &&
7843 	    !env->prog->has_callchain_buf) {
7844 		const char *err_str;
7845 
7846 #ifdef CONFIG_PERF_EVENTS
7847 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7848 		err_str = "cannot get callchain buffer for func %s#%d\n";
7849 #else
7850 		err = -ENOTSUPP;
7851 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7852 #endif
7853 		if (err) {
7854 			verbose(env, err_str, func_id_name(func_id), func_id);
7855 			return err;
7856 		}
7857 
7858 		env->prog->has_callchain_buf = true;
7859 	}
7860 
7861 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7862 		env->prog->call_get_stack = true;
7863 
7864 	if (func_id == BPF_FUNC_get_func_ip) {
7865 		if (check_get_func_ip(env))
7866 			return -ENOTSUPP;
7867 		env->prog->call_get_func_ip = true;
7868 	}
7869 
7870 	if (changes_data)
7871 		clear_all_pkt_pointers(env);
7872 	return 0;
7873 }
7874 
7875 /* mark_btf_func_reg_size() is used when the reg size is determined by
7876  * the BTF func_proto's return value size and argument.
7877  */
7878 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7879 				   size_t reg_size)
7880 {
7881 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7882 
7883 	if (regno == BPF_REG_0) {
7884 		/* Function return value */
7885 		reg->live |= REG_LIVE_WRITTEN;
7886 		reg->subreg_def = reg_size == sizeof(u64) ?
7887 			DEF_NOT_SUBREG : env->insn_idx + 1;
7888 	} else {
7889 		/* Function argument */
7890 		if (reg_size == sizeof(u64)) {
7891 			mark_insn_zext(env, reg);
7892 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7893 		} else {
7894 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7895 		}
7896 	}
7897 }
7898 
7899 struct bpf_kfunc_call_arg_meta {
7900 	/* In parameters */
7901 	struct btf *btf;
7902 	u32 func_id;
7903 	u32 kfunc_flags;
7904 	const struct btf_type *func_proto;
7905 	const char *func_name;
7906 	/* Out parameters */
7907 	u32 ref_obj_id;
7908 	u8 release_regno;
7909 	bool r0_rdonly;
7910 	u32 ret_btf_id;
7911 	u64 r0_size;
7912 	struct {
7913 		u64 value;
7914 		bool found;
7915 	} arg_constant;
7916 	struct {
7917 		struct btf *btf;
7918 		u32 btf_id;
7919 	} arg_obj_drop;
7920 	struct {
7921 		struct btf_field *field;
7922 	} arg_list_head;
7923 };
7924 
7925 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
7926 {
7927 	return meta->kfunc_flags & KF_ACQUIRE;
7928 }
7929 
7930 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
7931 {
7932 	return meta->kfunc_flags & KF_RET_NULL;
7933 }
7934 
7935 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
7936 {
7937 	return meta->kfunc_flags & KF_RELEASE;
7938 }
7939 
7940 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
7941 {
7942 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
7943 }
7944 
7945 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
7946 {
7947 	return meta->kfunc_flags & KF_SLEEPABLE;
7948 }
7949 
7950 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
7951 {
7952 	return meta->kfunc_flags & KF_DESTRUCTIVE;
7953 }
7954 
7955 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
7956 {
7957 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
7958 }
7959 
7960 static bool is_trusted_reg(const struct bpf_reg_state *reg)
7961 {
7962 	/* A referenced register is always trusted. */
7963 	if (reg->ref_obj_id)
7964 		return true;
7965 
7966 	/* If a register is not referenced, it is trusted if it has either the
7967 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
7968 	 * other type modifiers may be safe, but we elect to take an opt-in
7969 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
7970 	 * not.
7971 	 *
7972 	 * Eventually, we should make PTR_TRUSTED the single source of truth
7973 	 * for whether a register is trusted.
7974 	 */
7975 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
7976 	       !bpf_type_has_unsafe_modifiers(reg->type);
7977 }
7978 
7979 static bool __kfunc_param_match_suffix(const struct btf *btf,
7980 				       const struct btf_param *arg,
7981 				       const char *suffix)
7982 {
7983 	int suffix_len = strlen(suffix), len;
7984 	const char *param_name;
7985 
7986 	/* In the future, this can be ported to use BTF tagging */
7987 	param_name = btf_name_by_offset(btf, arg->name_off);
7988 	if (str_is_empty(param_name))
7989 		return false;
7990 	len = strlen(param_name);
7991 	if (len < suffix_len)
7992 		return false;
7993 	param_name += len - suffix_len;
7994 	return !strncmp(param_name, suffix, suffix_len);
7995 }
7996 
7997 static bool is_kfunc_arg_mem_size(const struct btf *btf,
7998 				  const struct btf_param *arg,
7999 				  const struct bpf_reg_state *reg)
8000 {
8001 	const struct btf_type *t;
8002 
8003 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8004 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8005 		return false;
8006 
8007 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8008 }
8009 
8010 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8011 {
8012 	return __kfunc_param_match_suffix(btf, arg, "__k");
8013 }
8014 
8015 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8016 {
8017 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8018 }
8019 
8020 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8021 {
8022 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8023 }
8024 
8025 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8026 					  const struct btf_param *arg,
8027 					  const char *name)
8028 {
8029 	int len, target_len = strlen(name);
8030 	const char *param_name;
8031 
8032 	param_name = btf_name_by_offset(btf, arg->name_off);
8033 	if (str_is_empty(param_name))
8034 		return false;
8035 	len = strlen(param_name);
8036 	if (len != target_len)
8037 		return false;
8038 	if (strcmp(param_name, name))
8039 		return false;
8040 
8041 	return true;
8042 }
8043 
8044 enum {
8045 	KF_ARG_DYNPTR_ID,
8046 	KF_ARG_LIST_HEAD_ID,
8047 	KF_ARG_LIST_NODE_ID,
8048 };
8049 
8050 BTF_ID_LIST(kf_arg_btf_ids)
8051 BTF_ID(struct, bpf_dynptr_kern)
8052 BTF_ID(struct, bpf_list_head)
8053 BTF_ID(struct, bpf_list_node)
8054 
8055 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8056 				    const struct btf_param *arg, int type)
8057 {
8058 	const struct btf_type *t;
8059 	u32 res_id;
8060 
8061 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8062 	if (!t)
8063 		return false;
8064 	if (!btf_type_is_ptr(t))
8065 		return false;
8066 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8067 	if (!t)
8068 		return false;
8069 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8070 }
8071 
8072 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8073 {
8074 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8075 }
8076 
8077 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8078 {
8079 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8080 }
8081 
8082 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8083 {
8084 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8085 }
8086 
8087 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8088 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8089 					const struct btf *btf,
8090 					const struct btf_type *t, int rec)
8091 {
8092 	const struct btf_type *member_type;
8093 	const struct btf_member *member;
8094 	u32 i;
8095 
8096 	if (!btf_type_is_struct(t))
8097 		return false;
8098 
8099 	for_each_member(i, t, member) {
8100 		const struct btf_array *array;
8101 
8102 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8103 		if (btf_type_is_struct(member_type)) {
8104 			if (rec >= 3) {
8105 				verbose(env, "max struct nesting depth exceeded\n");
8106 				return false;
8107 			}
8108 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8109 				return false;
8110 			continue;
8111 		}
8112 		if (btf_type_is_array(member_type)) {
8113 			array = btf_array(member_type);
8114 			if (!array->nelems)
8115 				return false;
8116 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8117 			if (!btf_type_is_scalar(member_type))
8118 				return false;
8119 			continue;
8120 		}
8121 		if (!btf_type_is_scalar(member_type))
8122 			return false;
8123 	}
8124 	return true;
8125 }
8126 
8127 
8128 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8129 #ifdef CONFIG_NET
8130 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8131 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8132 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8133 #endif
8134 };
8135 
8136 enum kfunc_ptr_arg_type {
8137 	KF_ARG_PTR_TO_CTX,
8138 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8139 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8140 	KF_ARG_PTR_TO_DYNPTR,
8141 	KF_ARG_PTR_TO_LIST_HEAD,
8142 	KF_ARG_PTR_TO_LIST_NODE,
8143 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8144 	KF_ARG_PTR_TO_MEM,
8145 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8146 };
8147 
8148 enum special_kfunc_type {
8149 	KF_bpf_obj_new_impl,
8150 	KF_bpf_obj_drop_impl,
8151 	KF_bpf_list_push_front,
8152 	KF_bpf_list_push_back,
8153 	KF_bpf_list_pop_front,
8154 	KF_bpf_list_pop_back,
8155 	KF_bpf_cast_to_kern_ctx,
8156 	KF_bpf_rdonly_cast,
8157 };
8158 
8159 BTF_SET_START(special_kfunc_set)
8160 BTF_ID(func, bpf_obj_new_impl)
8161 BTF_ID(func, bpf_obj_drop_impl)
8162 BTF_ID(func, bpf_list_push_front)
8163 BTF_ID(func, bpf_list_push_back)
8164 BTF_ID(func, bpf_list_pop_front)
8165 BTF_ID(func, bpf_list_pop_back)
8166 BTF_ID(func, bpf_cast_to_kern_ctx)
8167 BTF_ID(func, bpf_rdonly_cast)
8168 BTF_SET_END(special_kfunc_set)
8169 
8170 BTF_ID_LIST(special_kfunc_list)
8171 BTF_ID(func, bpf_obj_new_impl)
8172 BTF_ID(func, bpf_obj_drop_impl)
8173 BTF_ID(func, bpf_list_push_front)
8174 BTF_ID(func, bpf_list_push_back)
8175 BTF_ID(func, bpf_list_pop_front)
8176 BTF_ID(func, bpf_list_pop_back)
8177 BTF_ID(func, bpf_cast_to_kern_ctx)
8178 BTF_ID(func, bpf_rdonly_cast)
8179 
8180 static enum kfunc_ptr_arg_type
8181 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8182 		       struct bpf_kfunc_call_arg_meta *meta,
8183 		       const struct btf_type *t, const struct btf_type *ref_t,
8184 		       const char *ref_tname, const struct btf_param *args,
8185 		       int argno, int nargs)
8186 {
8187 	u32 regno = argno + 1;
8188 	struct bpf_reg_state *regs = cur_regs(env);
8189 	struct bpf_reg_state *reg = &regs[regno];
8190 	bool arg_mem_size = false;
8191 
8192 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8193 		return KF_ARG_PTR_TO_CTX;
8194 
8195 	/* In this function, we verify the kfunc's BTF as per the argument type,
8196 	 * leaving the rest of the verification with respect to the register
8197 	 * type to our caller. When a set of conditions hold in the BTF type of
8198 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8199 	 */
8200 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8201 		return KF_ARG_PTR_TO_CTX;
8202 
8203 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8204 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8205 
8206 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8207 		if (!btf_type_is_ptr(ref_t)) {
8208 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8209 			return -EINVAL;
8210 		}
8211 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8212 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8213 		if (!btf_type_is_struct(ref_t)) {
8214 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8215 				meta->func_name, btf_type_str(ref_t), ref_tname);
8216 			return -EINVAL;
8217 		}
8218 		return KF_ARG_PTR_TO_KPTR;
8219 	}
8220 
8221 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8222 		return KF_ARG_PTR_TO_DYNPTR;
8223 
8224 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8225 		return KF_ARG_PTR_TO_LIST_HEAD;
8226 
8227 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8228 		return KF_ARG_PTR_TO_LIST_NODE;
8229 
8230 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8231 		if (!btf_type_is_struct(ref_t)) {
8232 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8233 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8234 			return -EINVAL;
8235 		}
8236 		return KF_ARG_PTR_TO_BTF_ID;
8237 	}
8238 
8239 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8240 		arg_mem_size = true;
8241 
8242 	/* This is the catch all argument type of register types supported by
8243 	 * check_helper_mem_access. However, we only allow when argument type is
8244 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8245 	 * arg_mem_size is true, the pointer can be void *.
8246 	 */
8247 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8248 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8249 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8250 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8251 		return -EINVAL;
8252 	}
8253 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8254 }
8255 
8256 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8257 					struct bpf_reg_state *reg,
8258 					const struct btf_type *ref_t,
8259 					const char *ref_tname, u32 ref_id,
8260 					struct bpf_kfunc_call_arg_meta *meta,
8261 					int argno)
8262 {
8263 	const struct btf_type *reg_ref_t;
8264 	bool strict_type_match = false;
8265 	const struct btf *reg_btf;
8266 	const char *reg_ref_tname;
8267 	u32 reg_ref_id;
8268 
8269 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
8270 		reg_btf = reg->btf;
8271 		reg_ref_id = reg->btf_id;
8272 	} else {
8273 		reg_btf = btf_vmlinux;
8274 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8275 	}
8276 
8277 	if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8278 		strict_type_match = true;
8279 
8280 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8281 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8282 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8283 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8284 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8285 			btf_type_str(reg_ref_t), reg_ref_tname);
8286 		return -EINVAL;
8287 	}
8288 	return 0;
8289 }
8290 
8291 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8292 				      struct bpf_reg_state *reg,
8293 				      const struct btf_type *ref_t,
8294 				      const char *ref_tname,
8295 				      struct bpf_kfunc_call_arg_meta *meta,
8296 				      int argno)
8297 {
8298 	struct btf_field *kptr_field;
8299 
8300 	/* check_func_arg_reg_off allows var_off for
8301 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8302 	 * off_desc.
8303 	 */
8304 	if (!tnum_is_const(reg->var_off)) {
8305 		verbose(env, "arg#0 must have constant offset\n");
8306 		return -EINVAL;
8307 	}
8308 
8309 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8310 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8311 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8312 			reg->off + reg->var_off.value);
8313 		return -EINVAL;
8314 	}
8315 
8316 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8317 				  kptr_field->kptr.btf_id, true)) {
8318 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8319 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8320 		return -EINVAL;
8321 	}
8322 	return 0;
8323 }
8324 
8325 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8326 {
8327 	struct bpf_func_state *state = cur_func(env);
8328 	struct bpf_reg_state *reg;
8329 	int i;
8330 
8331 	/* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8332 	 * subprogs, no global functions. This means that the references would
8333 	 * not be released inside the critical section but they may be added to
8334 	 * the reference state, and the acquired_refs are never copied out for a
8335 	 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8336 	 * critical sections.
8337 	 */
8338 	if (!ref_obj_id) {
8339 		verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8340 		return -EFAULT;
8341 	}
8342 	for (i = 0; i < state->acquired_refs; i++) {
8343 		if (state->refs[i].id == ref_obj_id) {
8344 			if (state->refs[i].release_on_unlock) {
8345 				verbose(env, "verifier internal error: expected false release_on_unlock");
8346 				return -EFAULT;
8347 			}
8348 			state->refs[i].release_on_unlock = true;
8349 			/* Now mark everyone sharing same ref_obj_id as untrusted */
8350 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8351 				if (reg->ref_obj_id == ref_obj_id)
8352 					reg->type |= PTR_UNTRUSTED;
8353 			}));
8354 			return 0;
8355 		}
8356 	}
8357 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8358 	return -EFAULT;
8359 }
8360 
8361 /* Implementation details:
8362  *
8363  * Each register points to some region of memory, which we define as an
8364  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8365  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8366  * allocation. The lock and the data it protects are colocated in the same
8367  * memory region.
8368  *
8369  * Hence, everytime a register holds a pointer value pointing to such
8370  * allocation, the verifier preserves a unique reg->id for it.
8371  *
8372  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8373  * bpf_spin_lock is called.
8374  *
8375  * To enable this, lock state in the verifier captures two values:
8376  *	active_lock.ptr = Register's type specific pointer
8377  *	active_lock.id  = A unique ID for each register pointer value
8378  *
8379  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8380  * supported register types.
8381  *
8382  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8383  * allocated objects is the reg->btf pointer.
8384  *
8385  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8386  * can establish the provenance of the map value statically for each distinct
8387  * lookup into such maps. They always contain a single map value hence unique
8388  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8389  *
8390  * So, in case of global variables, they use array maps with max_entries = 1,
8391  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8392  * into the same map value as max_entries is 1, as described above).
8393  *
8394  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8395  * outer map pointer (in verifier context), but each lookup into an inner map
8396  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8397  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8398  * will get different reg->id assigned to each lookup, hence different
8399  * active_lock.id.
8400  *
8401  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8402  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8403  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8404  */
8405 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8406 {
8407 	void *ptr;
8408 	u32 id;
8409 
8410 	switch ((int)reg->type) {
8411 	case PTR_TO_MAP_VALUE:
8412 		ptr = reg->map_ptr;
8413 		break;
8414 	case PTR_TO_BTF_ID | MEM_ALLOC:
8415 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8416 		ptr = reg->btf;
8417 		break;
8418 	default:
8419 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
8420 		return -EFAULT;
8421 	}
8422 	id = reg->id;
8423 
8424 	if (!env->cur_state->active_lock.ptr)
8425 		return -EINVAL;
8426 	if (env->cur_state->active_lock.ptr != ptr ||
8427 	    env->cur_state->active_lock.id != id) {
8428 		verbose(env, "held lock and object are not in the same allocation\n");
8429 		return -EINVAL;
8430 	}
8431 	return 0;
8432 }
8433 
8434 static bool is_bpf_list_api_kfunc(u32 btf_id)
8435 {
8436 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8437 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8438 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8439 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8440 }
8441 
8442 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8443 					   struct bpf_reg_state *reg, u32 regno,
8444 					   struct bpf_kfunc_call_arg_meta *meta)
8445 {
8446 	struct btf_field *field;
8447 	struct btf_record *rec;
8448 	u32 list_head_off;
8449 
8450 	if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8451 		verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8452 		return -EFAULT;
8453 	}
8454 
8455 	if (!tnum_is_const(reg->var_off)) {
8456 		verbose(env,
8457 			"R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8458 			regno);
8459 		return -EINVAL;
8460 	}
8461 
8462 	rec = reg_btf_record(reg);
8463 	list_head_off = reg->off + reg->var_off.value;
8464 	field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8465 	if (!field) {
8466 		verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8467 		return -EINVAL;
8468 	}
8469 
8470 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8471 	if (check_reg_allocation_locked(env, reg)) {
8472 		verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8473 			rec->spin_lock_off);
8474 		return -EINVAL;
8475 	}
8476 
8477 	if (meta->arg_list_head.field) {
8478 		verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8479 		return -EFAULT;
8480 	}
8481 	meta->arg_list_head.field = field;
8482 	return 0;
8483 }
8484 
8485 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8486 					   struct bpf_reg_state *reg, u32 regno,
8487 					   struct bpf_kfunc_call_arg_meta *meta)
8488 {
8489 	const struct btf_type *et, *t;
8490 	struct btf_field *field;
8491 	struct btf_record *rec;
8492 	u32 list_node_off;
8493 
8494 	if (meta->btf != btf_vmlinux ||
8495 	    (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8496 	     meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8497 		verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8498 		return -EFAULT;
8499 	}
8500 
8501 	if (!tnum_is_const(reg->var_off)) {
8502 		verbose(env,
8503 			"R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8504 			regno);
8505 		return -EINVAL;
8506 	}
8507 
8508 	rec = reg_btf_record(reg);
8509 	list_node_off = reg->off + reg->var_off.value;
8510 	field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8511 	if (!field || field->offset != list_node_off) {
8512 		verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8513 		return -EINVAL;
8514 	}
8515 
8516 	field = meta->arg_list_head.field;
8517 
8518 	et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8519 	t = btf_type_by_id(reg->btf, reg->btf_id);
8520 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8521 				  field->list_head.value_btf_id, true)) {
8522 		verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8523 			"in struct %s, but arg is at offset=%d in struct %s\n",
8524 			field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8525 			list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8526 		return -EINVAL;
8527 	}
8528 
8529 	if (list_node_off != field->list_head.node_offset) {
8530 		verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8531 			list_node_off, field->list_head.node_offset,
8532 			btf_name_by_offset(field->list_head.btf, et->name_off));
8533 		return -EINVAL;
8534 	}
8535 	/* Set arg#1 for expiration after unlock */
8536 	return ref_set_release_on_unlock(env, reg->ref_obj_id);
8537 }
8538 
8539 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8540 {
8541 	const char *func_name = meta->func_name, *ref_tname;
8542 	const struct btf *btf = meta->btf;
8543 	const struct btf_param *args;
8544 	u32 i, nargs;
8545 	int ret;
8546 
8547 	args = (const struct btf_param *)(meta->func_proto + 1);
8548 	nargs = btf_type_vlen(meta->func_proto);
8549 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8550 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8551 			MAX_BPF_FUNC_REG_ARGS);
8552 		return -EINVAL;
8553 	}
8554 
8555 	/* Check that BTF function arguments match actual types that the
8556 	 * verifier sees.
8557 	 */
8558 	for (i = 0; i < nargs; i++) {
8559 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8560 		const struct btf_type *t, *ref_t, *resolve_ret;
8561 		enum bpf_arg_type arg_type = ARG_DONTCARE;
8562 		u32 regno = i + 1, ref_id, type_size;
8563 		bool is_ret_buf_sz = false;
8564 		int kf_arg_type;
8565 
8566 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8567 
8568 		if (is_kfunc_arg_ignore(btf, &args[i]))
8569 			continue;
8570 
8571 		if (btf_type_is_scalar(t)) {
8572 			if (reg->type != SCALAR_VALUE) {
8573 				verbose(env, "R%d is not a scalar\n", regno);
8574 				return -EINVAL;
8575 			}
8576 
8577 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8578 				if (meta->arg_constant.found) {
8579 					verbose(env, "verifier internal error: only one constant argument permitted\n");
8580 					return -EFAULT;
8581 				}
8582 				if (!tnum_is_const(reg->var_off)) {
8583 					verbose(env, "R%d must be a known constant\n", regno);
8584 					return -EINVAL;
8585 				}
8586 				ret = mark_chain_precision(env, regno);
8587 				if (ret < 0)
8588 					return ret;
8589 				meta->arg_constant.found = true;
8590 				meta->arg_constant.value = reg->var_off.value;
8591 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8592 				meta->r0_rdonly = true;
8593 				is_ret_buf_sz = true;
8594 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8595 				is_ret_buf_sz = true;
8596 			}
8597 
8598 			if (is_ret_buf_sz) {
8599 				if (meta->r0_size) {
8600 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8601 					return -EINVAL;
8602 				}
8603 
8604 				if (!tnum_is_const(reg->var_off)) {
8605 					verbose(env, "R%d is not a const\n", regno);
8606 					return -EINVAL;
8607 				}
8608 
8609 				meta->r0_size = reg->var_off.value;
8610 				ret = mark_chain_precision(env, regno);
8611 				if (ret)
8612 					return ret;
8613 			}
8614 			continue;
8615 		}
8616 
8617 		if (!btf_type_is_ptr(t)) {
8618 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8619 			return -EINVAL;
8620 		}
8621 
8622 		if (reg->ref_obj_id) {
8623 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
8624 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8625 					regno, reg->ref_obj_id,
8626 					meta->ref_obj_id);
8627 				return -EFAULT;
8628 			}
8629 			meta->ref_obj_id = reg->ref_obj_id;
8630 			if (is_kfunc_release(meta))
8631 				meta->release_regno = regno;
8632 		}
8633 
8634 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8635 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8636 
8637 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8638 		if (kf_arg_type < 0)
8639 			return kf_arg_type;
8640 
8641 		switch (kf_arg_type) {
8642 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8643 		case KF_ARG_PTR_TO_BTF_ID:
8644 			if (!is_kfunc_trusted_args(meta))
8645 				break;
8646 
8647 			if (!is_trusted_reg(reg)) {
8648 				verbose(env, "R%d must be referenced or trusted\n", regno);
8649 				return -EINVAL;
8650 			}
8651 			fallthrough;
8652 		case KF_ARG_PTR_TO_CTX:
8653 			/* Trusted arguments have the same offset checks as release arguments */
8654 			arg_type |= OBJ_RELEASE;
8655 			break;
8656 		case KF_ARG_PTR_TO_KPTR:
8657 		case KF_ARG_PTR_TO_DYNPTR:
8658 		case KF_ARG_PTR_TO_LIST_HEAD:
8659 		case KF_ARG_PTR_TO_LIST_NODE:
8660 		case KF_ARG_PTR_TO_MEM:
8661 		case KF_ARG_PTR_TO_MEM_SIZE:
8662 			/* Trusted by default */
8663 			break;
8664 		default:
8665 			WARN_ON_ONCE(1);
8666 			return -EFAULT;
8667 		}
8668 
8669 		if (is_kfunc_release(meta) && reg->ref_obj_id)
8670 			arg_type |= OBJ_RELEASE;
8671 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8672 		if (ret < 0)
8673 			return ret;
8674 
8675 		switch (kf_arg_type) {
8676 		case KF_ARG_PTR_TO_CTX:
8677 			if (reg->type != PTR_TO_CTX) {
8678 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8679 				return -EINVAL;
8680 			}
8681 
8682 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8683 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8684 				if (ret < 0)
8685 					return -EINVAL;
8686 				meta->ret_btf_id  = ret;
8687 			}
8688 			break;
8689 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8690 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8691 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
8692 				return -EINVAL;
8693 			}
8694 			if (!reg->ref_obj_id) {
8695 				verbose(env, "allocated object must be referenced\n");
8696 				return -EINVAL;
8697 			}
8698 			if (meta->btf == btf_vmlinux &&
8699 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8700 				meta->arg_obj_drop.btf = reg->btf;
8701 				meta->arg_obj_drop.btf_id = reg->btf_id;
8702 			}
8703 			break;
8704 		case KF_ARG_PTR_TO_KPTR:
8705 			if (reg->type != PTR_TO_MAP_VALUE) {
8706 				verbose(env, "arg#0 expected pointer to map value\n");
8707 				return -EINVAL;
8708 			}
8709 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8710 			if (ret < 0)
8711 				return ret;
8712 			break;
8713 		case KF_ARG_PTR_TO_DYNPTR:
8714 			if (reg->type != PTR_TO_STACK) {
8715 				verbose(env, "arg#%d expected pointer to stack\n", i);
8716 				return -EINVAL;
8717 			}
8718 
8719 			if (!is_dynptr_reg_valid_init(env, reg)) {
8720 				verbose(env, "arg#%d pointer type %s %s must be valid and initialized\n",
8721 					i, btf_type_str(ref_t), ref_tname);
8722 				return -EINVAL;
8723 			}
8724 
8725 			if (!is_dynptr_type_expected(env, reg, ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL)) {
8726 				verbose(env, "arg#%d pointer type %s %s points to unsupported dynamic pointer type\n",
8727 					i, btf_type_str(ref_t), ref_tname);
8728 				return -EINVAL;
8729 			}
8730 			break;
8731 		case KF_ARG_PTR_TO_LIST_HEAD:
8732 			if (reg->type != PTR_TO_MAP_VALUE &&
8733 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8734 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8735 				return -EINVAL;
8736 			}
8737 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8738 				verbose(env, "allocated object must be referenced\n");
8739 				return -EINVAL;
8740 			}
8741 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
8742 			if (ret < 0)
8743 				return ret;
8744 			break;
8745 		case KF_ARG_PTR_TO_LIST_NODE:
8746 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8747 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
8748 				return -EINVAL;
8749 			}
8750 			if (!reg->ref_obj_id) {
8751 				verbose(env, "allocated object must be referenced\n");
8752 				return -EINVAL;
8753 			}
8754 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
8755 			if (ret < 0)
8756 				return ret;
8757 			break;
8758 		case KF_ARG_PTR_TO_BTF_ID:
8759 			/* Only base_type is checked, further checks are done here */
8760 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
8761 			     bpf_type_has_unsafe_modifiers(reg->type)) &&
8762 			    !reg2btf_ids[base_type(reg->type)]) {
8763 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
8764 				verbose(env, "expected %s or socket\n",
8765 					reg_type_str(env, base_type(reg->type) |
8766 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
8767 				return -EINVAL;
8768 			}
8769 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
8770 			if (ret < 0)
8771 				return ret;
8772 			break;
8773 		case KF_ARG_PTR_TO_MEM:
8774 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
8775 			if (IS_ERR(resolve_ret)) {
8776 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8777 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
8778 				return -EINVAL;
8779 			}
8780 			ret = check_mem_reg(env, reg, regno, type_size);
8781 			if (ret < 0)
8782 				return ret;
8783 			break;
8784 		case KF_ARG_PTR_TO_MEM_SIZE:
8785 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
8786 			if (ret < 0) {
8787 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
8788 				return ret;
8789 			}
8790 			/* Skip next '__sz' argument */
8791 			i++;
8792 			break;
8793 		}
8794 	}
8795 
8796 	if (is_kfunc_release(meta) && !meta->release_regno) {
8797 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
8798 			func_name);
8799 		return -EINVAL;
8800 	}
8801 
8802 	return 0;
8803 }
8804 
8805 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8806 			    int *insn_idx_p)
8807 {
8808 	const struct btf_type *t, *func, *func_proto, *ptr_type;
8809 	struct bpf_reg_state *regs = cur_regs(env);
8810 	const char *func_name, *ptr_type_name;
8811 	struct bpf_kfunc_call_arg_meta meta;
8812 	u32 i, nargs, func_id, ptr_type_id;
8813 	int err, insn_idx = *insn_idx_p;
8814 	const struct btf_param *args;
8815 	const struct btf_type *ret_t;
8816 	struct btf *desc_btf;
8817 	u32 *kfunc_flags;
8818 
8819 	/* skip for now, but return error when we find this in fixup_kfunc_call */
8820 	if (!insn->imm)
8821 		return 0;
8822 
8823 	desc_btf = find_kfunc_desc_btf(env, insn->off);
8824 	if (IS_ERR(desc_btf))
8825 		return PTR_ERR(desc_btf);
8826 
8827 	func_id = insn->imm;
8828 	func = btf_type_by_id(desc_btf, func_id);
8829 	func_name = btf_name_by_offset(desc_btf, func->name_off);
8830 	func_proto = btf_type_by_id(desc_btf, func->type);
8831 
8832 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
8833 	if (!kfunc_flags) {
8834 		verbose(env, "calling kernel function %s is not allowed\n",
8835 			func_name);
8836 		return -EACCES;
8837 	}
8838 
8839 	/* Prepare kfunc call metadata */
8840 	memset(&meta, 0, sizeof(meta));
8841 	meta.btf = desc_btf;
8842 	meta.func_id = func_id;
8843 	meta.kfunc_flags = *kfunc_flags;
8844 	meta.func_proto = func_proto;
8845 	meta.func_name = func_name;
8846 
8847 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
8848 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
8849 		return -EACCES;
8850 	}
8851 
8852 	if (is_kfunc_sleepable(&meta) && !env->prog->aux->sleepable) {
8853 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
8854 		return -EACCES;
8855 	}
8856 
8857 	/* Check the arguments */
8858 	err = check_kfunc_args(env, &meta);
8859 	if (err < 0)
8860 		return err;
8861 	/* In case of release function, we get register number of refcounted
8862 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
8863 	 */
8864 	if (meta.release_regno) {
8865 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
8866 		if (err) {
8867 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
8868 				func_name, func_id);
8869 			return err;
8870 		}
8871 	}
8872 
8873 	for (i = 0; i < CALLER_SAVED_REGS; i++)
8874 		mark_reg_not_init(env, regs, caller_saved[i]);
8875 
8876 	/* Check return type */
8877 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
8878 
8879 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
8880 		/* Only exception is bpf_obj_new_impl */
8881 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
8882 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
8883 			return -EINVAL;
8884 		}
8885 	}
8886 
8887 	if (btf_type_is_scalar(t)) {
8888 		mark_reg_unknown(env, regs, BPF_REG_0);
8889 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
8890 	} else if (btf_type_is_ptr(t)) {
8891 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
8892 
8893 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
8894 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
8895 				struct btf *ret_btf;
8896 				u32 ret_btf_id;
8897 
8898 				if (unlikely(!bpf_global_ma_set))
8899 					return -ENOMEM;
8900 
8901 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
8902 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
8903 					return -EINVAL;
8904 				}
8905 
8906 				ret_btf = env->prog->aux->btf;
8907 				ret_btf_id = meta.arg_constant.value;
8908 
8909 				/* This may be NULL due to user not supplying a BTF */
8910 				if (!ret_btf) {
8911 					verbose(env, "bpf_obj_new requires prog BTF\n");
8912 					return -EINVAL;
8913 				}
8914 
8915 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
8916 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
8917 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
8918 					return -EINVAL;
8919 				}
8920 
8921 				mark_reg_known_zero(env, regs, BPF_REG_0);
8922 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8923 				regs[BPF_REG_0].btf = ret_btf;
8924 				regs[BPF_REG_0].btf_id = ret_btf_id;
8925 
8926 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
8927 				env->insn_aux_data[insn_idx].kptr_struct_meta =
8928 					btf_find_struct_meta(ret_btf, ret_btf_id);
8929 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8930 				env->insn_aux_data[insn_idx].kptr_struct_meta =
8931 					btf_find_struct_meta(meta.arg_obj_drop.btf,
8932 							     meta.arg_obj_drop.btf_id);
8933 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8934 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
8935 				struct btf_field *field = meta.arg_list_head.field;
8936 
8937 				mark_reg_known_zero(env, regs, BPF_REG_0);
8938 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8939 				regs[BPF_REG_0].btf = field->list_head.btf;
8940 				regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
8941 				regs[BPF_REG_0].off = field->list_head.node_offset;
8942 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8943 				mark_reg_known_zero(env, regs, BPF_REG_0);
8944 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
8945 				regs[BPF_REG_0].btf = desc_btf;
8946 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8947 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
8948 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
8949 				if (!ret_t || !btf_type_is_struct(ret_t)) {
8950 					verbose(env,
8951 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
8952 					return -EINVAL;
8953 				}
8954 
8955 				mark_reg_known_zero(env, regs, BPF_REG_0);
8956 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
8957 				regs[BPF_REG_0].btf = desc_btf;
8958 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
8959 			} else {
8960 				verbose(env, "kernel function %s unhandled dynamic return type\n",
8961 					meta.func_name);
8962 				return -EFAULT;
8963 			}
8964 		} else if (!__btf_type_is_struct(ptr_type)) {
8965 			if (!meta.r0_size) {
8966 				ptr_type_name = btf_name_by_offset(desc_btf,
8967 								   ptr_type->name_off);
8968 				verbose(env,
8969 					"kernel function %s returns pointer type %s %s is not supported\n",
8970 					func_name,
8971 					btf_type_str(ptr_type),
8972 					ptr_type_name);
8973 				return -EINVAL;
8974 			}
8975 
8976 			mark_reg_known_zero(env, regs, BPF_REG_0);
8977 			regs[BPF_REG_0].type = PTR_TO_MEM;
8978 			regs[BPF_REG_0].mem_size = meta.r0_size;
8979 
8980 			if (meta.r0_rdonly)
8981 				regs[BPF_REG_0].type |= MEM_RDONLY;
8982 
8983 			/* Ensures we don't access the memory after a release_reference() */
8984 			if (meta.ref_obj_id)
8985 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8986 		} else {
8987 			mark_reg_known_zero(env, regs, BPF_REG_0);
8988 			regs[BPF_REG_0].btf = desc_btf;
8989 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
8990 			regs[BPF_REG_0].btf_id = ptr_type_id;
8991 		}
8992 
8993 		if (is_kfunc_ret_null(&meta)) {
8994 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
8995 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
8996 			regs[BPF_REG_0].id = ++env->id_gen;
8997 		}
8998 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
8999 		if (is_kfunc_acquire(&meta)) {
9000 			int id = acquire_reference_state(env, insn_idx);
9001 
9002 			if (id < 0)
9003 				return id;
9004 			if (is_kfunc_ret_null(&meta))
9005 				regs[BPF_REG_0].id = id;
9006 			regs[BPF_REG_0].ref_obj_id = id;
9007 		}
9008 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9009 			regs[BPF_REG_0].id = ++env->id_gen;
9010 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9011 
9012 	nargs = btf_type_vlen(func_proto);
9013 	args = (const struct btf_param *)(func_proto + 1);
9014 	for (i = 0; i < nargs; i++) {
9015 		u32 regno = i + 1;
9016 
9017 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9018 		if (btf_type_is_ptr(t))
9019 			mark_btf_func_reg_size(env, regno, sizeof(void *));
9020 		else
9021 			/* scalar. ensured by btf_check_kfunc_arg_match() */
9022 			mark_btf_func_reg_size(env, regno, t->size);
9023 	}
9024 
9025 	return 0;
9026 }
9027 
9028 static bool signed_add_overflows(s64 a, s64 b)
9029 {
9030 	/* Do the add in u64, where overflow is well-defined */
9031 	s64 res = (s64)((u64)a + (u64)b);
9032 
9033 	if (b < 0)
9034 		return res > a;
9035 	return res < a;
9036 }
9037 
9038 static bool signed_add32_overflows(s32 a, s32 b)
9039 {
9040 	/* Do the add in u32, where overflow is well-defined */
9041 	s32 res = (s32)((u32)a + (u32)b);
9042 
9043 	if (b < 0)
9044 		return res > a;
9045 	return res < a;
9046 }
9047 
9048 static bool signed_sub_overflows(s64 a, s64 b)
9049 {
9050 	/* Do the sub in u64, where overflow is well-defined */
9051 	s64 res = (s64)((u64)a - (u64)b);
9052 
9053 	if (b < 0)
9054 		return res < a;
9055 	return res > a;
9056 }
9057 
9058 static bool signed_sub32_overflows(s32 a, s32 b)
9059 {
9060 	/* Do the sub in u32, where overflow is well-defined */
9061 	s32 res = (s32)((u32)a - (u32)b);
9062 
9063 	if (b < 0)
9064 		return res < a;
9065 	return res > a;
9066 }
9067 
9068 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9069 				  const struct bpf_reg_state *reg,
9070 				  enum bpf_reg_type type)
9071 {
9072 	bool known = tnum_is_const(reg->var_off);
9073 	s64 val = reg->var_off.value;
9074 	s64 smin = reg->smin_value;
9075 
9076 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9077 		verbose(env, "math between %s pointer and %lld is not allowed\n",
9078 			reg_type_str(env, type), val);
9079 		return false;
9080 	}
9081 
9082 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9083 		verbose(env, "%s pointer offset %d is not allowed\n",
9084 			reg_type_str(env, type), reg->off);
9085 		return false;
9086 	}
9087 
9088 	if (smin == S64_MIN) {
9089 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9090 			reg_type_str(env, type));
9091 		return false;
9092 	}
9093 
9094 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9095 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
9096 			smin, reg_type_str(env, type));
9097 		return false;
9098 	}
9099 
9100 	return true;
9101 }
9102 
9103 enum {
9104 	REASON_BOUNDS	= -1,
9105 	REASON_TYPE	= -2,
9106 	REASON_PATHS	= -3,
9107 	REASON_LIMIT	= -4,
9108 	REASON_STACK	= -5,
9109 };
9110 
9111 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9112 			      u32 *alu_limit, bool mask_to_left)
9113 {
9114 	u32 max = 0, ptr_limit = 0;
9115 
9116 	switch (ptr_reg->type) {
9117 	case PTR_TO_STACK:
9118 		/* Offset 0 is out-of-bounds, but acceptable start for the
9119 		 * left direction, see BPF_REG_FP. Also, unknown scalar
9120 		 * offset where we would need to deal with min/max bounds is
9121 		 * currently prohibited for unprivileged.
9122 		 */
9123 		max = MAX_BPF_STACK + mask_to_left;
9124 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9125 		break;
9126 	case PTR_TO_MAP_VALUE:
9127 		max = ptr_reg->map_ptr->value_size;
9128 		ptr_limit = (mask_to_left ?
9129 			     ptr_reg->smin_value :
9130 			     ptr_reg->umax_value) + ptr_reg->off;
9131 		break;
9132 	default:
9133 		return REASON_TYPE;
9134 	}
9135 
9136 	if (ptr_limit >= max)
9137 		return REASON_LIMIT;
9138 	*alu_limit = ptr_limit;
9139 	return 0;
9140 }
9141 
9142 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9143 				    const struct bpf_insn *insn)
9144 {
9145 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9146 }
9147 
9148 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9149 				       u32 alu_state, u32 alu_limit)
9150 {
9151 	/* If we arrived here from different branches with different
9152 	 * state or limits to sanitize, then this won't work.
9153 	 */
9154 	if (aux->alu_state &&
9155 	    (aux->alu_state != alu_state ||
9156 	     aux->alu_limit != alu_limit))
9157 		return REASON_PATHS;
9158 
9159 	/* Corresponding fixup done in do_misc_fixups(). */
9160 	aux->alu_state = alu_state;
9161 	aux->alu_limit = alu_limit;
9162 	return 0;
9163 }
9164 
9165 static int sanitize_val_alu(struct bpf_verifier_env *env,
9166 			    struct bpf_insn *insn)
9167 {
9168 	struct bpf_insn_aux_data *aux = cur_aux(env);
9169 
9170 	if (can_skip_alu_sanitation(env, insn))
9171 		return 0;
9172 
9173 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9174 }
9175 
9176 static bool sanitize_needed(u8 opcode)
9177 {
9178 	return opcode == BPF_ADD || opcode == BPF_SUB;
9179 }
9180 
9181 struct bpf_sanitize_info {
9182 	struct bpf_insn_aux_data aux;
9183 	bool mask_to_left;
9184 };
9185 
9186 static struct bpf_verifier_state *
9187 sanitize_speculative_path(struct bpf_verifier_env *env,
9188 			  const struct bpf_insn *insn,
9189 			  u32 next_idx, u32 curr_idx)
9190 {
9191 	struct bpf_verifier_state *branch;
9192 	struct bpf_reg_state *regs;
9193 
9194 	branch = push_stack(env, next_idx, curr_idx, true);
9195 	if (branch && insn) {
9196 		regs = branch->frame[branch->curframe]->regs;
9197 		if (BPF_SRC(insn->code) == BPF_K) {
9198 			mark_reg_unknown(env, regs, insn->dst_reg);
9199 		} else if (BPF_SRC(insn->code) == BPF_X) {
9200 			mark_reg_unknown(env, regs, insn->dst_reg);
9201 			mark_reg_unknown(env, regs, insn->src_reg);
9202 		}
9203 	}
9204 	return branch;
9205 }
9206 
9207 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9208 			    struct bpf_insn *insn,
9209 			    const struct bpf_reg_state *ptr_reg,
9210 			    const struct bpf_reg_state *off_reg,
9211 			    struct bpf_reg_state *dst_reg,
9212 			    struct bpf_sanitize_info *info,
9213 			    const bool commit_window)
9214 {
9215 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9216 	struct bpf_verifier_state *vstate = env->cur_state;
9217 	bool off_is_imm = tnum_is_const(off_reg->var_off);
9218 	bool off_is_neg = off_reg->smin_value < 0;
9219 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
9220 	u8 opcode = BPF_OP(insn->code);
9221 	u32 alu_state, alu_limit;
9222 	struct bpf_reg_state tmp;
9223 	bool ret;
9224 	int err;
9225 
9226 	if (can_skip_alu_sanitation(env, insn))
9227 		return 0;
9228 
9229 	/* We already marked aux for masking from non-speculative
9230 	 * paths, thus we got here in the first place. We only care
9231 	 * to explore bad access from here.
9232 	 */
9233 	if (vstate->speculative)
9234 		goto do_sim;
9235 
9236 	if (!commit_window) {
9237 		if (!tnum_is_const(off_reg->var_off) &&
9238 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9239 			return REASON_BOUNDS;
9240 
9241 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9242 				     (opcode == BPF_SUB && !off_is_neg);
9243 	}
9244 
9245 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9246 	if (err < 0)
9247 		return err;
9248 
9249 	if (commit_window) {
9250 		/* In commit phase we narrow the masking window based on
9251 		 * the observed pointer move after the simulated operation.
9252 		 */
9253 		alu_state = info->aux.alu_state;
9254 		alu_limit = abs(info->aux.alu_limit - alu_limit);
9255 	} else {
9256 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9257 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9258 		alu_state |= ptr_is_dst_reg ?
9259 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9260 
9261 		/* Limit pruning on unknown scalars to enable deep search for
9262 		 * potential masking differences from other program paths.
9263 		 */
9264 		if (!off_is_imm)
9265 			env->explore_alu_limits = true;
9266 	}
9267 
9268 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9269 	if (err < 0)
9270 		return err;
9271 do_sim:
9272 	/* If we're in commit phase, we're done here given we already
9273 	 * pushed the truncated dst_reg into the speculative verification
9274 	 * stack.
9275 	 *
9276 	 * Also, when register is a known constant, we rewrite register-based
9277 	 * operation to immediate-based, and thus do not need masking (and as
9278 	 * a consequence, do not need to simulate the zero-truncation either).
9279 	 */
9280 	if (commit_window || off_is_imm)
9281 		return 0;
9282 
9283 	/* Simulate and find potential out-of-bounds access under
9284 	 * speculative execution from truncation as a result of
9285 	 * masking when off was not within expected range. If off
9286 	 * sits in dst, then we temporarily need to move ptr there
9287 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9288 	 * for cases where we use K-based arithmetic in one direction
9289 	 * and truncated reg-based in the other in order to explore
9290 	 * bad access.
9291 	 */
9292 	if (!ptr_is_dst_reg) {
9293 		tmp = *dst_reg;
9294 		*dst_reg = *ptr_reg;
9295 	}
9296 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9297 					env->insn_idx);
9298 	if (!ptr_is_dst_reg && ret)
9299 		*dst_reg = tmp;
9300 	return !ret ? REASON_STACK : 0;
9301 }
9302 
9303 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9304 {
9305 	struct bpf_verifier_state *vstate = env->cur_state;
9306 
9307 	/* If we simulate paths under speculation, we don't update the
9308 	 * insn as 'seen' such that when we verify unreachable paths in
9309 	 * the non-speculative domain, sanitize_dead_code() can still
9310 	 * rewrite/sanitize them.
9311 	 */
9312 	if (!vstate->speculative)
9313 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9314 }
9315 
9316 static int sanitize_err(struct bpf_verifier_env *env,
9317 			const struct bpf_insn *insn, int reason,
9318 			const struct bpf_reg_state *off_reg,
9319 			const struct bpf_reg_state *dst_reg)
9320 {
9321 	static const char *err = "pointer arithmetic with it prohibited for !root";
9322 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9323 	u32 dst = insn->dst_reg, src = insn->src_reg;
9324 
9325 	switch (reason) {
9326 	case REASON_BOUNDS:
9327 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9328 			off_reg == dst_reg ? dst : src, err);
9329 		break;
9330 	case REASON_TYPE:
9331 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9332 			off_reg == dst_reg ? src : dst, err);
9333 		break;
9334 	case REASON_PATHS:
9335 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9336 			dst, op, err);
9337 		break;
9338 	case REASON_LIMIT:
9339 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9340 			dst, op, err);
9341 		break;
9342 	case REASON_STACK:
9343 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9344 			dst, err);
9345 		break;
9346 	default:
9347 		verbose(env, "verifier internal error: unknown reason (%d)\n",
9348 			reason);
9349 		break;
9350 	}
9351 
9352 	return -EACCES;
9353 }
9354 
9355 /* check that stack access falls within stack limits and that 'reg' doesn't
9356  * have a variable offset.
9357  *
9358  * Variable offset is prohibited for unprivileged mode for simplicity since it
9359  * requires corresponding support in Spectre masking for stack ALU.  See also
9360  * retrieve_ptr_limit().
9361  *
9362  *
9363  * 'off' includes 'reg->off'.
9364  */
9365 static int check_stack_access_for_ptr_arithmetic(
9366 				struct bpf_verifier_env *env,
9367 				int regno,
9368 				const struct bpf_reg_state *reg,
9369 				int off)
9370 {
9371 	if (!tnum_is_const(reg->var_off)) {
9372 		char tn_buf[48];
9373 
9374 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9375 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9376 			regno, tn_buf, off);
9377 		return -EACCES;
9378 	}
9379 
9380 	if (off >= 0 || off < -MAX_BPF_STACK) {
9381 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
9382 			"prohibited for !root; off=%d\n", regno, off);
9383 		return -EACCES;
9384 	}
9385 
9386 	return 0;
9387 }
9388 
9389 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9390 				 const struct bpf_insn *insn,
9391 				 const struct bpf_reg_state *dst_reg)
9392 {
9393 	u32 dst = insn->dst_reg;
9394 
9395 	/* For unprivileged we require that resulting offset must be in bounds
9396 	 * in order to be able to sanitize access later on.
9397 	 */
9398 	if (env->bypass_spec_v1)
9399 		return 0;
9400 
9401 	switch (dst_reg->type) {
9402 	case PTR_TO_STACK:
9403 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9404 					dst_reg->off + dst_reg->var_off.value))
9405 			return -EACCES;
9406 		break;
9407 	case PTR_TO_MAP_VALUE:
9408 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9409 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9410 				"prohibited for !root\n", dst);
9411 			return -EACCES;
9412 		}
9413 		break;
9414 	default:
9415 		break;
9416 	}
9417 
9418 	return 0;
9419 }
9420 
9421 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9422  * Caller should also handle BPF_MOV case separately.
9423  * If we return -EACCES, caller may want to try again treating pointer as a
9424  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
9425  */
9426 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9427 				   struct bpf_insn *insn,
9428 				   const struct bpf_reg_state *ptr_reg,
9429 				   const struct bpf_reg_state *off_reg)
9430 {
9431 	struct bpf_verifier_state *vstate = env->cur_state;
9432 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9433 	struct bpf_reg_state *regs = state->regs, *dst_reg;
9434 	bool known = tnum_is_const(off_reg->var_off);
9435 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9436 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9437 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9438 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9439 	struct bpf_sanitize_info info = {};
9440 	u8 opcode = BPF_OP(insn->code);
9441 	u32 dst = insn->dst_reg;
9442 	int ret;
9443 
9444 	dst_reg = &regs[dst];
9445 
9446 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9447 	    smin_val > smax_val || umin_val > umax_val) {
9448 		/* Taint dst register if offset had invalid bounds derived from
9449 		 * e.g. dead branches.
9450 		 */
9451 		__mark_reg_unknown(env, dst_reg);
9452 		return 0;
9453 	}
9454 
9455 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
9456 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
9457 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9458 			__mark_reg_unknown(env, dst_reg);
9459 			return 0;
9460 		}
9461 
9462 		verbose(env,
9463 			"R%d 32-bit pointer arithmetic prohibited\n",
9464 			dst);
9465 		return -EACCES;
9466 	}
9467 
9468 	if (ptr_reg->type & PTR_MAYBE_NULL) {
9469 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9470 			dst, reg_type_str(env, ptr_reg->type));
9471 		return -EACCES;
9472 	}
9473 
9474 	switch (base_type(ptr_reg->type)) {
9475 	case CONST_PTR_TO_MAP:
9476 		/* smin_val represents the known value */
9477 		if (known && smin_val == 0 && opcode == BPF_ADD)
9478 			break;
9479 		fallthrough;
9480 	case PTR_TO_PACKET_END:
9481 	case PTR_TO_SOCKET:
9482 	case PTR_TO_SOCK_COMMON:
9483 	case PTR_TO_TCP_SOCK:
9484 	case PTR_TO_XDP_SOCK:
9485 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9486 			dst, reg_type_str(env, ptr_reg->type));
9487 		return -EACCES;
9488 	default:
9489 		break;
9490 	}
9491 
9492 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9493 	 * The id may be overwritten later if we create a new variable offset.
9494 	 */
9495 	dst_reg->type = ptr_reg->type;
9496 	dst_reg->id = ptr_reg->id;
9497 
9498 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9499 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9500 		return -EINVAL;
9501 
9502 	/* pointer types do not carry 32-bit bounds at the moment. */
9503 	__mark_reg32_unbounded(dst_reg);
9504 
9505 	if (sanitize_needed(opcode)) {
9506 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9507 				       &info, false);
9508 		if (ret < 0)
9509 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9510 	}
9511 
9512 	switch (opcode) {
9513 	case BPF_ADD:
9514 		/* We can take a fixed offset as long as it doesn't overflow
9515 		 * the s32 'off' field
9516 		 */
9517 		if (known && (ptr_reg->off + smin_val ==
9518 			      (s64)(s32)(ptr_reg->off + smin_val))) {
9519 			/* pointer += K.  Accumulate it into fixed offset */
9520 			dst_reg->smin_value = smin_ptr;
9521 			dst_reg->smax_value = smax_ptr;
9522 			dst_reg->umin_value = umin_ptr;
9523 			dst_reg->umax_value = umax_ptr;
9524 			dst_reg->var_off = ptr_reg->var_off;
9525 			dst_reg->off = ptr_reg->off + smin_val;
9526 			dst_reg->raw = ptr_reg->raw;
9527 			break;
9528 		}
9529 		/* A new variable offset is created.  Note that off_reg->off
9530 		 * == 0, since it's a scalar.
9531 		 * dst_reg gets the pointer type and since some positive
9532 		 * integer value was added to the pointer, give it a new 'id'
9533 		 * if it's a PTR_TO_PACKET.
9534 		 * this creates a new 'base' pointer, off_reg (variable) gets
9535 		 * added into the variable offset, and we copy the fixed offset
9536 		 * from ptr_reg.
9537 		 */
9538 		if (signed_add_overflows(smin_ptr, smin_val) ||
9539 		    signed_add_overflows(smax_ptr, smax_val)) {
9540 			dst_reg->smin_value = S64_MIN;
9541 			dst_reg->smax_value = S64_MAX;
9542 		} else {
9543 			dst_reg->smin_value = smin_ptr + smin_val;
9544 			dst_reg->smax_value = smax_ptr + smax_val;
9545 		}
9546 		if (umin_ptr + umin_val < umin_ptr ||
9547 		    umax_ptr + umax_val < umax_ptr) {
9548 			dst_reg->umin_value = 0;
9549 			dst_reg->umax_value = U64_MAX;
9550 		} else {
9551 			dst_reg->umin_value = umin_ptr + umin_val;
9552 			dst_reg->umax_value = umax_ptr + umax_val;
9553 		}
9554 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9555 		dst_reg->off = ptr_reg->off;
9556 		dst_reg->raw = ptr_reg->raw;
9557 		if (reg_is_pkt_pointer(ptr_reg)) {
9558 			dst_reg->id = ++env->id_gen;
9559 			/* something was added to pkt_ptr, set range to zero */
9560 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9561 		}
9562 		break;
9563 	case BPF_SUB:
9564 		if (dst_reg == off_reg) {
9565 			/* scalar -= pointer.  Creates an unknown scalar */
9566 			verbose(env, "R%d tried to subtract pointer from scalar\n",
9567 				dst);
9568 			return -EACCES;
9569 		}
9570 		/* We don't allow subtraction from FP, because (according to
9571 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
9572 		 * be able to deal with it.
9573 		 */
9574 		if (ptr_reg->type == PTR_TO_STACK) {
9575 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
9576 				dst);
9577 			return -EACCES;
9578 		}
9579 		if (known && (ptr_reg->off - smin_val ==
9580 			      (s64)(s32)(ptr_reg->off - smin_val))) {
9581 			/* pointer -= K.  Subtract it from fixed offset */
9582 			dst_reg->smin_value = smin_ptr;
9583 			dst_reg->smax_value = smax_ptr;
9584 			dst_reg->umin_value = umin_ptr;
9585 			dst_reg->umax_value = umax_ptr;
9586 			dst_reg->var_off = ptr_reg->var_off;
9587 			dst_reg->id = ptr_reg->id;
9588 			dst_reg->off = ptr_reg->off - smin_val;
9589 			dst_reg->raw = ptr_reg->raw;
9590 			break;
9591 		}
9592 		/* A new variable offset is created.  If the subtrahend is known
9593 		 * nonnegative, then any reg->range we had before is still good.
9594 		 */
9595 		if (signed_sub_overflows(smin_ptr, smax_val) ||
9596 		    signed_sub_overflows(smax_ptr, smin_val)) {
9597 			/* Overflow possible, we know nothing */
9598 			dst_reg->smin_value = S64_MIN;
9599 			dst_reg->smax_value = S64_MAX;
9600 		} else {
9601 			dst_reg->smin_value = smin_ptr - smax_val;
9602 			dst_reg->smax_value = smax_ptr - smin_val;
9603 		}
9604 		if (umin_ptr < umax_val) {
9605 			/* Overflow possible, we know nothing */
9606 			dst_reg->umin_value = 0;
9607 			dst_reg->umax_value = U64_MAX;
9608 		} else {
9609 			/* Cannot overflow (as long as bounds are consistent) */
9610 			dst_reg->umin_value = umin_ptr - umax_val;
9611 			dst_reg->umax_value = umax_ptr - umin_val;
9612 		}
9613 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9614 		dst_reg->off = ptr_reg->off;
9615 		dst_reg->raw = ptr_reg->raw;
9616 		if (reg_is_pkt_pointer(ptr_reg)) {
9617 			dst_reg->id = ++env->id_gen;
9618 			/* something was added to pkt_ptr, set range to zero */
9619 			if (smin_val < 0)
9620 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9621 		}
9622 		break;
9623 	case BPF_AND:
9624 	case BPF_OR:
9625 	case BPF_XOR:
9626 		/* bitwise ops on pointers are troublesome, prohibit. */
9627 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9628 			dst, bpf_alu_string[opcode >> 4]);
9629 		return -EACCES;
9630 	default:
9631 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
9632 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9633 			dst, bpf_alu_string[opcode >> 4]);
9634 		return -EACCES;
9635 	}
9636 
9637 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9638 		return -EINVAL;
9639 	reg_bounds_sync(dst_reg);
9640 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9641 		return -EACCES;
9642 	if (sanitize_needed(opcode)) {
9643 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9644 				       &info, true);
9645 		if (ret < 0)
9646 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9647 	}
9648 
9649 	return 0;
9650 }
9651 
9652 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9653 				 struct bpf_reg_state *src_reg)
9654 {
9655 	s32 smin_val = src_reg->s32_min_value;
9656 	s32 smax_val = src_reg->s32_max_value;
9657 	u32 umin_val = src_reg->u32_min_value;
9658 	u32 umax_val = src_reg->u32_max_value;
9659 
9660 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9661 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9662 		dst_reg->s32_min_value = S32_MIN;
9663 		dst_reg->s32_max_value = S32_MAX;
9664 	} else {
9665 		dst_reg->s32_min_value += smin_val;
9666 		dst_reg->s32_max_value += smax_val;
9667 	}
9668 	if (dst_reg->u32_min_value + umin_val < umin_val ||
9669 	    dst_reg->u32_max_value + umax_val < umax_val) {
9670 		dst_reg->u32_min_value = 0;
9671 		dst_reg->u32_max_value = U32_MAX;
9672 	} else {
9673 		dst_reg->u32_min_value += umin_val;
9674 		dst_reg->u32_max_value += umax_val;
9675 	}
9676 }
9677 
9678 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9679 			       struct bpf_reg_state *src_reg)
9680 {
9681 	s64 smin_val = src_reg->smin_value;
9682 	s64 smax_val = src_reg->smax_value;
9683 	u64 umin_val = src_reg->umin_value;
9684 	u64 umax_val = src_reg->umax_value;
9685 
9686 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9687 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
9688 		dst_reg->smin_value = S64_MIN;
9689 		dst_reg->smax_value = S64_MAX;
9690 	} else {
9691 		dst_reg->smin_value += smin_val;
9692 		dst_reg->smax_value += smax_val;
9693 	}
9694 	if (dst_reg->umin_value + umin_val < umin_val ||
9695 	    dst_reg->umax_value + umax_val < umax_val) {
9696 		dst_reg->umin_value = 0;
9697 		dst_reg->umax_value = U64_MAX;
9698 	} else {
9699 		dst_reg->umin_value += umin_val;
9700 		dst_reg->umax_value += umax_val;
9701 	}
9702 }
9703 
9704 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
9705 				 struct bpf_reg_state *src_reg)
9706 {
9707 	s32 smin_val = src_reg->s32_min_value;
9708 	s32 smax_val = src_reg->s32_max_value;
9709 	u32 umin_val = src_reg->u32_min_value;
9710 	u32 umax_val = src_reg->u32_max_value;
9711 
9712 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
9713 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
9714 		/* Overflow possible, we know nothing */
9715 		dst_reg->s32_min_value = S32_MIN;
9716 		dst_reg->s32_max_value = S32_MAX;
9717 	} else {
9718 		dst_reg->s32_min_value -= smax_val;
9719 		dst_reg->s32_max_value -= smin_val;
9720 	}
9721 	if (dst_reg->u32_min_value < umax_val) {
9722 		/* Overflow possible, we know nothing */
9723 		dst_reg->u32_min_value = 0;
9724 		dst_reg->u32_max_value = U32_MAX;
9725 	} else {
9726 		/* Cannot overflow (as long as bounds are consistent) */
9727 		dst_reg->u32_min_value -= umax_val;
9728 		dst_reg->u32_max_value -= umin_val;
9729 	}
9730 }
9731 
9732 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
9733 			       struct bpf_reg_state *src_reg)
9734 {
9735 	s64 smin_val = src_reg->smin_value;
9736 	s64 smax_val = src_reg->smax_value;
9737 	u64 umin_val = src_reg->umin_value;
9738 	u64 umax_val = src_reg->umax_value;
9739 
9740 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
9741 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
9742 		/* Overflow possible, we know nothing */
9743 		dst_reg->smin_value = S64_MIN;
9744 		dst_reg->smax_value = S64_MAX;
9745 	} else {
9746 		dst_reg->smin_value -= smax_val;
9747 		dst_reg->smax_value -= smin_val;
9748 	}
9749 	if (dst_reg->umin_value < umax_val) {
9750 		/* Overflow possible, we know nothing */
9751 		dst_reg->umin_value = 0;
9752 		dst_reg->umax_value = U64_MAX;
9753 	} else {
9754 		/* Cannot overflow (as long as bounds are consistent) */
9755 		dst_reg->umin_value -= umax_val;
9756 		dst_reg->umax_value -= umin_val;
9757 	}
9758 }
9759 
9760 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
9761 				 struct bpf_reg_state *src_reg)
9762 {
9763 	s32 smin_val = src_reg->s32_min_value;
9764 	u32 umin_val = src_reg->u32_min_value;
9765 	u32 umax_val = src_reg->u32_max_value;
9766 
9767 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
9768 		/* Ain't nobody got time to multiply that sign */
9769 		__mark_reg32_unbounded(dst_reg);
9770 		return;
9771 	}
9772 	/* Both values are positive, so we can work with unsigned and
9773 	 * copy the result to signed (unless it exceeds S32_MAX).
9774 	 */
9775 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
9776 		/* Potential overflow, we know nothing */
9777 		__mark_reg32_unbounded(dst_reg);
9778 		return;
9779 	}
9780 	dst_reg->u32_min_value *= umin_val;
9781 	dst_reg->u32_max_value *= umax_val;
9782 	if (dst_reg->u32_max_value > S32_MAX) {
9783 		/* Overflow possible, we know nothing */
9784 		dst_reg->s32_min_value = S32_MIN;
9785 		dst_reg->s32_max_value = S32_MAX;
9786 	} else {
9787 		dst_reg->s32_min_value = dst_reg->u32_min_value;
9788 		dst_reg->s32_max_value = dst_reg->u32_max_value;
9789 	}
9790 }
9791 
9792 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
9793 			       struct bpf_reg_state *src_reg)
9794 {
9795 	s64 smin_val = src_reg->smin_value;
9796 	u64 umin_val = src_reg->umin_value;
9797 	u64 umax_val = src_reg->umax_value;
9798 
9799 	if (smin_val < 0 || dst_reg->smin_value < 0) {
9800 		/* Ain't nobody got time to multiply that sign */
9801 		__mark_reg64_unbounded(dst_reg);
9802 		return;
9803 	}
9804 	/* Both values are positive, so we can work with unsigned and
9805 	 * copy the result to signed (unless it exceeds S64_MAX).
9806 	 */
9807 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
9808 		/* Potential overflow, we know nothing */
9809 		__mark_reg64_unbounded(dst_reg);
9810 		return;
9811 	}
9812 	dst_reg->umin_value *= umin_val;
9813 	dst_reg->umax_value *= umax_val;
9814 	if (dst_reg->umax_value > S64_MAX) {
9815 		/* Overflow possible, we know nothing */
9816 		dst_reg->smin_value = S64_MIN;
9817 		dst_reg->smax_value = S64_MAX;
9818 	} else {
9819 		dst_reg->smin_value = dst_reg->umin_value;
9820 		dst_reg->smax_value = dst_reg->umax_value;
9821 	}
9822 }
9823 
9824 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
9825 				 struct bpf_reg_state *src_reg)
9826 {
9827 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
9828 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9829 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9830 	s32 smin_val = src_reg->s32_min_value;
9831 	u32 umax_val = src_reg->u32_max_value;
9832 
9833 	if (src_known && dst_known) {
9834 		__mark_reg32_known(dst_reg, var32_off.value);
9835 		return;
9836 	}
9837 
9838 	/* We get our minimum from the var_off, since that's inherently
9839 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
9840 	 */
9841 	dst_reg->u32_min_value = var32_off.value;
9842 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
9843 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9844 		/* Lose signed bounds when ANDing negative numbers,
9845 		 * ain't nobody got time for that.
9846 		 */
9847 		dst_reg->s32_min_value = S32_MIN;
9848 		dst_reg->s32_max_value = S32_MAX;
9849 	} else {
9850 		/* ANDing two positives gives a positive, so safe to
9851 		 * cast result into s64.
9852 		 */
9853 		dst_reg->s32_min_value = dst_reg->u32_min_value;
9854 		dst_reg->s32_max_value = dst_reg->u32_max_value;
9855 	}
9856 }
9857 
9858 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
9859 			       struct bpf_reg_state *src_reg)
9860 {
9861 	bool src_known = tnum_is_const(src_reg->var_off);
9862 	bool dst_known = tnum_is_const(dst_reg->var_off);
9863 	s64 smin_val = src_reg->smin_value;
9864 	u64 umax_val = src_reg->umax_value;
9865 
9866 	if (src_known && dst_known) {
9867 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
9868 		return;
9869 	}
9870 
9871 	/* We get our minimum from the var_off, since that's inherently
9872 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
9873 	 */
9874 	dst_reg->umin_value = dst_reg->var_off.value;
9875 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
9876 	if (dst_reg->smin_value < 0 || smin_val < 0) {
9877 		/* Lose signed bounds when ANDing negative numbers,
9878 		 * ain't nobody got time for that.
9879 		 */
9880 		dst_reg->smin_value = S64_MIN;
9881 		dst_reg->smax_value = S64_MAX;
9882 	} else {
9883 		/* ANDing two positives gives a positive, so safe to
9884 		 * cast result into s64.
9885 		 */
9886 		dst_reg->smin_value = dst_reg->umin_value;
9887 		dst_reg->smax_value = dst_reg->umax_value;
9888 	}
9889 	/* We may learn something more from the var_off */
9890 	__update_reg_bounds(dst_reg);
9891 }
9892 
9893 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
9894 				struct bpf_reg_state *src_reg)
9895 {
9896 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
9897 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9898 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9899 	s32 smin_val = src_reg->s32_min_value;
9900 	u32 umin_val = src_reg->u32_min_value;
9901 
9902 	if (src_known && dst_known) {
9903 		__mark_reg32_known(dst_reg, var32_off.value);
9904 		return;
9905 	}
9906 
9907 	/* We get our maximum from the var_off, and our minimum is the
9908 	 * maximum of the operands' minima
9909 	 */
9910 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
9911 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9912 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9913 		/* Lose signed bounds when ORing negative numbers,
9914 		 * ain't nobody got time for that.
9915 		 */
9916 		dst_reg->s32_min_value = S32_MIN;
9917 		dst_reg->s32_max_value = S32_MAX;
9918 	} else {
9919 		/* ORing two positives gives a positive, so safe to
9920 		 * cast result into s64.
9921 		 */
9922 		dst_reg->s32_min_value = dst_reg->u32_min_value;
9923 		dst_reg->s32_max_value = dst_reg->u32_max_value;
9924 	}
9925 }
9926 
9927 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
9928 			      struct bpf_reg_state *src_reg)
9929 {
9930 	bool src_known = tnum_is_const(src_reg->var_off);
9931 	bool dst_known = tnum_is_const(dst_reg->var_off);
9932 	s64 smin_val = src_reg->smin_value;
9933 	u64 umin_val = src_reg->umin_value;
9934 
9935 	if (src_known && dst_known) {
9936 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
9937 		return;
9938 	}
9939 
9940 	/* We get our maximum from the var_off, and our minimum is the
9941 	 * maximum of the operands' minima
9942 	 */
9943 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
9944 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
9945 	if (dst_reg->smin_value < 0 || smin_val < 0) {
9946 		/* Lose signed bounds when ORing negative numbers,
9947 		 * ain't nobody got time for that.
9948 		 */
9949 		dst_reg->smin_value = S64_MIN;
9950 		dst_reg->smax_value = S64_MAX;
9951 	} else {
9952 		/* ORing two positives gives a positive, so safe to
9953 		 * cast result into s64.
9954 		 */
9955 		dst_reg->smin_value = dst_reg->umin_value;
9956 		dst_reg->smax_value = dst_reg->umax_value;
9957 	}
9958 	/* We may learn something more from the var_off */
9959 	__update_reg_bounds(dst_reg);
9960 }
9961 
9962 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
9963 				 struct bpf_reg_state *src_reg)
9964 {
9965 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
9966 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9967 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9968 	s32 smin_val = src_reg->s32_min_value;
9969 
9970 	if (src_known && dst_known) {
9971 		__mark_reg32_known(dst_reg, var32_off.value);
9972 		return;
9973 	}
9974 
9975 	/* We get both minimum and maximum from the var32_off. */
9976 	dst_reg->u32_min_value = var32_off.value;
9977 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9978 
9979 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
9980 		/* XORing two positive sign numbers gives a positive,
9981 		 * so safe to cast u32 result into s32.
9982 		 */
9983 		dst_reg->s32_min_value = dst_reg->u32_min_value;
9984 		dst_reg->s32_max_value = dst_reg->u32_max_value;
9985 	} else {
9986 		dst_reg->s32_min_value = S32_MIN;
9987 		dst_reg->s32_max_value = S32_MAX;
9988 	}
9989 }
9990 
9991 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
9992 			       struct bpf_reg_state *src_reg)
9993 {
9994 	bool src_known = tnum_is_const(src_reg->var_off);
9995 	bool dst_known = tnum_is_const(dst_reg->var_off);
9996 	s64 smin_val = src_reg->smin_value;
9997 
9998 	if (src_known && dst_known) {
9999 		/* dst_reg->var_off.value has been updated earlier */
10000 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10001 		return;
10002 	}
10003 
10004 	/* We get both minimum and maximum from the var_off. */
10005 	dst_reg->umin_value = dst_reg->var_off.value;
10006 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10007 
10008 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10009 		/* XORing two positive sign numbers gives a positive,
10010 		 * so safe to cast u64 result into s64.
10011 		 */
10012 		dst_reg->smin_value = dst_reg->umin_value;
10013 		dst_reg->smax_value = dst_reg->umax_value;
10014 	} else {
10015 		dst_reg->smin_value = S64_MIN;
10016 		dst_reg->smax_value = S64_MAX;
10017 	}
10018 
10019 	__update_reg_bounds(dst_reg);
10020 }
10021 
10022 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10023 				   u64 umin_val, u64 umax_val)
10024 {
10025 	/* We lose all sign bit information (except what we can pick
10026 	 * up from var_off)
10027 	 */
10028 	dst_reg->s32_min_value = S32_MIN;
10029 	dst_reg->s32_max_value = S32_MAX;
10030 	/* If we might shift our top bit out, then we know nothing */
10031 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10032 		dst_reg->u32_min_value = 0;
10033 		dst_reg->u32_max_value = U32_MAX;
10034 	} else {
10035 		dst_reg->u32_min_value <<= umin_val;
10036 		dst_reg->u32_max_value <<= umax_val;
10037 	}
10038 }
10039 
10040 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10041 				 struct bpf_reg_state *src_reg)
10042 {
10043 	u32 umax_val = src_reg->u32_max_value;
10044 	u32 umin_val = src_reg->u32_min_value;
10045 	/* u32 alu operation will zext upper bits */
10046 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10047 
10048 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10049 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10050 	/* Not required but being careful mark reg64 bounds as unknown so
10051 	 * that we are forced to pick them up from tnum and zext later and
10052 	 * if some path skips this step we are still safe.
10053 	 */
10054 	__mark_reg64_unbounded(dst_reg);
10055 	__update_reg32_bounds(dst_reg);
10056 }
10057 
10058 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10059 				   u64 umin_val, u64 umax_val)
10060 {
10061 	/* Special case <<32 because it is a common compiler pattern to sign
10062 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10063 	 * positive we know this shift will also be positive so we can track
10064 	 * bounds correctly. Otherwise we lose all sign bit information except
10065 	 * what we can pick up from var_off. Perhaps we can generalize this
10066 	 * later to shifts of any length.
10067 	 */
10068 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10069 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10070 	else
10071 		dst_reg->smax_value = S64_MAX;
10072 
10073 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10074 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10075 	else
10076 		dst_reg->smin_value = S64_MIN;
10077 
10078 	/* If we might shift our top bit out, then we know nothing */
10079 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10080 		dst_reg->umin_value = 0;
10081 		dst_reg->umax_value = U64_MAX;
10082 	} else {
10083 		dst_reg->umin_value <<= umin_val;
10084 		dst_reg->umax_value <<= umax_val;
10085 	}
10086 }
10087 
10088 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10089 			       struct bpf_reg_state *src_reg)
10090 {
10091 	u64 umax_val = src_reg->umax_value;
10092 	u64 umin_val = src_reg->umin_value;
10093 
10094 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
10095 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10096 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10097 
10098 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10099 	/* We may learn something more from the var_off */
10100 	__update_reg_bounds(dst_reg);
10101 }
10102 
10103 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10104 				 struct bpf_reg_state *src_reg)
10105 {
10106 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10107 	u32 umax_val = src_reg->u32_max_value;
10108 	u32 umin_val = src_reg->u32_min_value;
10109 
10110 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10111 	 * be negative, then either:
10112 	 * 1) src_reg might be zero, so the sign bit of the result is
10113 	 *    unknown, so we lose our signed bounds
10114 	 * 2) it's known negative, thus the unsigned bounds capture the
10115 	 *    signed bounds
10116 	 * 3) the signed bounds cross zero, so they tell us nothing
10117 	 *    about the result
10118 	 * If the value in dst_reg is known nonnegative, then again the
10119 	 * unsigned bounds capture the signed bounds.
10120 	 * Thus, in all cases it suffices to blow away our signed bounds
10121 	 * and rely on inferring new ones from the unsigned bounds and
10122 	 * var_off of the result.
10123 	 */
10124 	dst_reg->s32_min_value = S32_MIN;
10125 	dst_reg->s32_max_value = S32_MAX;
10126 
10127 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
10128 	dst_reg->u32_min_value >>= umax_val;
10129 	dst_reg->u32_max_value >>= umin_val;
10130 
10131 	__mark_reg64_unbounded(dst_reg);
10132 	__update_reg32_bounds(dst_reg);
10133 }
10134 
10135 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10136 			       struct bpf_reg_state *src_reg)
10137 {
10138 	u64 umax_val = src_reg->umax_value;
10139 	u64 umin_val = src_reg->umin_value;
10140 
10141 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10142 	 * be negative, then either:
10143 	 * 1) src_reg might be zero, so the sign bit of the result is
10144 	 *    unknown, so we lose our signed bounds
10145 	 * 2) it's known negative, thus the unsigned bounds capture the
10146 	 *    signed bounds
10147 	 * 3) the signed bounds cross zero, so they tell us nothing
10148 	 *    about the result
10149 	 * If the value in dst_reg is known nonnegative, then again the
10150 	 * unsigned bounds capture the signed bounds.
10151 	 * Thus, in all cases it suffices to blow away our signed bounds
10152 	 * and rely on inferring new ones from the unsigned bounds and
10153 	 * var_off of the result.
10154 	 */
10155 	dst_reg->smin_value = S64_MIN;
10156 	dst_reg->smax_value = S64_MAX;
10157 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10158 	dst_reg->umin_value >>= umax_val;
10159 	dst_reg->umax_value >>= umin_val;
10160 
10161 	/* Its not easy to operate on alu32 bounds here because it depends
10162 	 * on bits being shifted in. Take easy way out and mark unbounded
10163 	 * so we can recalculate later from tnum.
10164 	 */
10165 	__mark_reg32_unbounded(dst_reg);
10166 	__update_reg_bounds(dst_reg);
10167 }
10168 
10169 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10170 				  struct bpf_reg_state *src_reg)
10171 {
10172 	u64 umin_val = src_reg->u32_min_value;
10173 
10174 	/* Upon reaching here, src_known is true and
10175 	 * umax_val is equal to umin_val.
10176 	 */
10177 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10178 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10179 
10180 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10181 
10182 	/* blow away the dst_reg umin_value/umax_value and rely on
10183 	 * dst_reg var_off to refine the result.
10184 	 */
10185 	dst_reg->u32_min_value = 0;
10186 	dst_reg->u32_max_value = U32_MAX;
10187 
10188 	__mark_reg64_unbounded(dst_reg);
10189 	__update_reg32_bounds(dst_reg);
10190 }
10191 
10192 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10193 				struct bpf_reg_state *src_reg)
10194 {
10195 	u64 umin_val = src_reg->umin_value;
10196 
10197 	/* Upon reaching here, src_known is true and umax_val is equal
10198 	 * to umin_val.
10199 	 */
10200 	dst_reg->smin_value >>= umin_val;
10201 	dst_reg->smax_value >>= umin_val;
10202 
10203 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10204 
10205 	/* blow away the dst_reg umin_value/umax_value and rely on
10206 	 * dst_reg var_off to refine the result.
10207 	 */
10208 	dst_reg->umin_value = 0;
10209 	dst_reg->umax_value = U64_MAX;
10210 
10211 	/* Its not easy to operate on alu32 bounds here because it depends
10212 	 * on bits being shifted in from upper 32-bits. Take easy way out
10213 	 * and mark unbounded so we can recalculate later from tnum.
10214 	 */
10215 	__mark_reg32_unbounded(dst_reg);
10216 	__update_reg_bounds(dst_reg);
10217 }
10218 
10219 /* WARNING: This function does calculations on 64-bit values, but the actual
10220  * execution may occur on 32-bit values. Therefore, things like bitshifts
10221  * need extra checks in the 32-bit case.
10222  */
10223 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10224 				      struct bpf_insn *insn,
10225 				      struct bpf_reg_state *dst_reg,
10226 				      struct bpf_reg_state src_reg)
10227 {
10228 	struct bpf_reg_state *regs = cur_regs(env);
10229 	u8 opcode = BPF_OP(insn->code);
10230 	bool src_known;
10231 	s64 smin_val, smax_val;
10232 	u64 umin_val, umax_val;
10233 	s32 s32_min_val, s32_max_val;
10234 	u32 u32_min_val, u32_max_val;
10235 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10236 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10237 	int ret;
10238 
10239 	smin_val = src_reg.smin_value;
10240 	smax_val = src_reg.smax_value;
10241 	umin_val = src_reg.umin_value;
10242 	umax_val = src_reg.umax_value;
10243 
10244 	s32_min_val = src_reg.s32_min_value;
10245 	s32_max_val = src_reg.s32_max_value;
10246 	u32_min_val = src_reg.u32_min_value;
10247 	u32_max_val = src_reg.u32_max_value;
10248 
10249 	if (alu32) {
10250 		src_known = tnum_subreg_is_const(src_reg.var_off);
10251 		if ((src_known &&
10252 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10253 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10254 			/* Taint dst register if offset had invalid bounds
10255 			 * derived from e.g. dead branches.
10256 			 */
10257 			__mark_reg_unknown(env, dst_reg);
10258 			return 0;
10259 		}
10260 	} else {
10261 		src_known = tnum_is_const(src_reg.var_off);
10262 		if ((src_known &&
10263 		     (smin_val != smax_val || umin_val != umax_val)) ||
10264 		    smin_val > smax_val || umin_val > umax_val) {
10265 			/* Taint dst register if offset had invalid bounds
10266 			 * derived from e.g. dead branches.
10267 			 */
10268 			__mark_reg_unknown(env, dst_reg);
10269 			return 0;
10270 		}
10271 	}
10272 
10273 	if (!src_known &&
10274 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10275 		__mark_reg_unknown(env, dst_reg);
10276 		return 0;
10277 	}
10278 
10279 	if (sanitize_needed(opcode)) {
10280 		ret = sanitize_val_alu(env, insn);
10281 		if (ret < 0)
10282 			return sanitize_err(env, insn, ret, NULL, NULL);
10283 	}
10284 
10285 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10286 	 * There are two classes of instructions: The first class we track both
10287 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
10288 	 * greatest amount of precision when alu operations are mixed with jmp32
10289 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10290 	 * and BPF_OR. This is possible because these ops have fairly easy to
10291 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10292 	 * See alu32 verifier tests for examples. The second class of
10293 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10294 	 * with regards to tracking sign/unsigned bounds because the bits may
10295 	 * cross subreg boundaries in the alu64 case. When this happens we mark
10296 	 * the reg unbounded in the subreg bound space and use the resulting
10297 	 * tnum to calculate an approximation of the sign/unsigned bounds.
10298 	 */
10299 	switch (opcode) {
10300 	case BPF_ADD:
10301 		scalar32_min_max_add(dst_reg, &src_reg);
10302 		scalar_min_max_add(dst_reg, &src_reg);
10303 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10304 		break;
10305 	case BPF_SUB:
10306 		scalar32_min_max_sub(dst_reg, &src_reg);
10307 		scalar_min_max_sub(dst_reg, &src_reg);
10308 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10309 		break;
10310 	case BPF_MUL:
10311 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10312 		scalar32_min_max_mul(dst_reg, &src_reg);
10313 		scalar_min_max_mul(dst_reg, &src_reg);
10314 		break;
10315 	case BPF_AND:
10316 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10317 		scalar32_min_max_and(dst_reg, &src_reg);
10318 		scalar_min_max_and(dst_reg, &src_reg);
10319 		break;
10320 	case BPF_OR:
10321 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10322 		scalar32_min_max_or(dst_reg, &src_reg);
10323 		scalar_min_max_or(dst_reg, &src_reg);
10324 		break;
10325 	case BPF_XOR:
10326 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10327 		scalar32_min_max_xor(dst_reg, &src_reg);
10328 		scalar_min_max_xor(dst_reg, &src_reg);
10329 		break;
10330 	case BPF_LSH:
10331 		if (umax_val >= insn_bitness) {
10332 			/* Shifts greater than 31 or 63 are undefined.
10333 			 * This includes shifts by a negative number.
10334 			 */
10335 			mark_reg_unknown(env, regs, insn->dst_reg);
10336 			break;
10337 		}
10338 		if (alu32)
10339 			scalar32_min_max_lsh(dst_reg, &src_reg);
10340 		else
10341 			scalar_min_max_lsh(dst_reg, &src_reg);
10342 		break;
10343 	case BPF_RSH:
10344 		if (umax_val >= insn_bitness) {
10345 			/* Shifts greater than 31 or 63 are undefined.
10346 			 * This includes shifts by a negative number.
10347 			 */
10348 			mark_reg_unknown(env, regs, insn->dst_reg);
10349 			break;
10350 		}
10351 		if (alu32)
10352 			scalar32_min_max_rsh(dst_reg, &src_reg);
10353 		else
10354 			scalar_min_max_rsh(dst_reg, &src_reg);
10355 		break;
10356 	case BPF_ARSH:
10357 		if (umax_val >= insn_bitness) {
10358 			/* Shifts greater than 31 or 63 are undefined.
10359 			 * This includes shifts by a negative number.
10360 			 */
10361 			mark_reg_unknown(env, regs, insn->dst_reg);
10362 			break;
10363 		}
10364 		if (alu32)
10365 			scalar32_min_max_arsh(dst_reg, &src_reg);
10366 		else
10367 			scalar_min_max_arsh(dst_reg, &src_reg);
10368 		break;
10369 	default:
10370 		mark_reg_unknown(env, regs, insn->dst_reg);
10371 		break;
10372 	}
10373 
10374 	/* ALU32 ops are zero extended into 64bit register */
10375 	if (alu32)
10376 		zext_32_to_64(dst_reg);
10377 	reg_bounds_sync(dst_reg);
10378 	return 0;
10379 }
10380 
10381 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10382  * and var_off.
10383  */
10384 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10385 				   struct bpf_insn *insn)
10386 {
10387 	struct bpf_verifier_state *vstate = env->cur_state;
10388 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10389 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10390 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10391 	u8 opcode = BPF_OP(insn->code);
10392 	int err;
10393 
10394 	dst_reg = &regs[insn->dst_reg];
10395 	src_reg = NULL;
10396 	if (dst_reg->type != SCALAR_VALUE)
10397 		ptr_reg = dst_reg;
10398 	else
10399 		/* Make sure ID is cleared otherwise dst_reg min/max could be
10400 		 * incorrectly propagated into other registers by find_equal_scalars()
10401 		 */
10402 		dst_reg->id = 0;
10403 	if (BPF_SRC(insn->code) == BPF_X) {
10404 		src_reg = &regs[insn->src_reg];
10405 		if (src_reg->type != SCALAR_VALUE) {
10406 			if (dst_reg->type != SCALAR_VALUE) {
10407 				/* Combining two pointers by any ALU op yields
10408 				 * an arbitrary scalar. Disallow all math except
10409 				 * pointer subtraction
10410 				 */
10411 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10412 					mark_reg_unknown(env, regs, insn->dst_reg);
10413 					return 0;
10414 				}
10415 				verbose(env, "R%d pointer %s pointer prohibited\n",
10416 					insn->dst_reg,
10417 					bpf_alu_string[opcode >> 4]);
10418 				return -EACCES;
10419 			} else {
10420 				/* scalar += pointer
10421 				 * This is legal, but we have to reverse our
10422 				 * src/dest handling in computing the range
10423 				 */
10424 				err = mark_chain_precision(env, insn->dst_reg);
10425 				if (err)
10426 					return err;
10427 				return adjust_ptr_min_max_vals(env, insn,
10428 							       src_reg, dst_reg);
10429 			}
10430 		} else if (ptr_reg) {
10431 			/* pointer += scalar */
10432 			err = mark_chain_precision(env, insn->src_reg);
10433 			if (err)
10434 				return err;
10435 			return adjust_ptr_min_max_vals(env, insn,
10436 						       dst_reg, src_reg);
10437 		} else if (dst_reg->precise) {
10438 			/* if dst_reg is precise, src_reg should be precise as well */
10439 			err = mark_chain_precision(env, insn->src_reg);
10440 			if (err)
10441 				return err;
10442 		}
10443 	} else {
10444 		/* Pretend the src is a reg with a known value, since we only
10445 		 * need to be able to read from this state.
10446 		 */
10447 		off_reg.type = SCALAR_VALUE;
10448 		__mark_reg_known(&off_reg, insn->imm);
10449 		src_reg = &off_reg;
10450 		if (ptr_reg) /* pointer += K */
10451 			return adjust_ptr_min_max_vals(env, insn,
10452 						       ptr_reg, src_reg);
10453 	}
10454 
10455 	/* Got here implies adding two SCALAR_VALUEs */
10456 	if (WARN_ON_ONCE(ptr_reg)) {
10457 		print_verifier_state(env, state, true);
10458 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
10459 		return -EINVAL;
10460 	}
10461 	if (WARN_ON(!src_reg)) {
10462 		print_verifier_state(env, state, true);
10463 		verbose(env, "verifier internal error: no src_reg\n");
10464 		return -EINVAL;
10465 	}
10466 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10467 }
10468 
10469 /* check validity of 32-bit and 64-bit arithmetic operations */
10470 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10471 {
10472 	struct bpf_reg_state *regs = cur_regs(env);
10473 	u8 opcode = BPF_OP(insn->code);
10474 	int err;
10475 
10476 	if (opcode == BPF_END || opcode == BPF_NEG) {
10477 		if (opcode == BPF_NEG) {
10478 			if (BPF_SRC(insn->code) != BPF_K ||
10479 			    insn->src_reg != BPF_REG_0 ||
10480 			    insn->off != 0 || insn->imm != 0) {
10481 				verbose(env, "BPF_NEG uses reserved fields\n");
10482 				return -EINVAL;
10483 			}
10484 		} else {
10485 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10486 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10487 			    BPF_CLASS(insn->code) == BPF_ALU64) {
10488 				verbose(env, "BPF_END uses reserved fields\n");
10489 				return -EINVAL;
10490 			}
10491 		}
10492 
10493 		/* check src operand */
10494 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10495 		if (err)
10496 			return err;
10497 
10498 		if (is_pointer_value(env, insn->dst_reg)) {
10499 			verbose(env, "R%d pointer arithmetic prohibited\n",
10500 				insn->dst_reg);
10501 			return -EACCES;
10502 		}
10503 
10504 		/* check dest operand */
10505 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
10506 		if (err)
10507 			return err;
10508 
10509 	} else if (opcode == BPF_MOV) {
10510 
10511 		if (BPF_SRC(insn->code) == BPF_X) {
10512 			if (insn->imm != 0 || insn->off != 0) {
10513 				verbose(env, "BPF_MOV uses reserved fields\n");
10514 				return -EINVAL;
10515 			}
10516 
10517 			/* check src operand */
10518 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10519 			if (err)
10520 				return err;
10521 		} else {
10522 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10523 				verbose(env, "BPF_MOV uses reserved fields\n");
10524 				return -EINVAL;
10525 			}
10526 		}
10527 
10528 		/* check dest operand, mark as required later */
10529 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10530 		if (err)
10531 			return err;
10532 
10533 		if (BPF_SRC(insn->code) == BPF_X) {
10534 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
10535 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10536 
10537 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10538 				/* case: R1 = R2
10539 				 * copy register state to dest reg
10540 				 */
10541 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10542 					/* Assign src and dst registers the same ID
10543 					 * that will be used by find_equal_scalars()
10544 					 * to propagate min/max range.
10545 					 */
10546 					src_reg->id = ++env->id_gen;
10547 				*dst_reg = *src_reg;
10548 				dst_reg->live |= REG_LIVE_WRITTEN;
10549 				dst_reg->subreg_def = DEF_NOT_SUBREG;
10550 			} else {
10551 				/* R1 = (u32) R2 */
10552 				if (is_pointer_value(env, insn->src_reg)) {
10553 					verbose(env,
10554 						"R%d partial copy of pointer\n",
10555 						insn->src_reg);
10556 					return -EACCES;
10557 				} else if (src_reg->type == SCALAR_VALUE) {
10558 					*dst_reg = *src_reg;
10559 					/* Make sure ID is cleared otherwise
10560 					 * dst_reg min/max could be incorrectly
10561 					 * propagated into src_reg by find_equal_scalars()
10562 					 */
10563 					dst_reg->id = 0;
10564 					dst_reg->live |= REG_LIVE_WRITTEN;
10565 					dst_reg->subreg_def = env->insn_idx + 1;
10566 				} else {
10567 					mark_reg_unknown(env, regs,
10568 							 insn->dst_reg);
10569 				}
10570 				zext_32_to_64(dst_reg);
10571 				reg_bounds_sync(dst_reg);
10572 			}
10573 		} else {
10574 			/* case: R = imm
10575 			 * remember the value we stored into this reg
10576 			 */
10577 			/* clear any state __mark_reg_known doesn't set */
10578 			mark_reg_unknown(env, regs, insn->dst_reg);
10579 			regs[insn->dst_reg].type = SCALAR_VALUE;
10580 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10581 				__mark_reg_known(regs + insn->dst_reg,
10582 						 insn->imm);
10583 			} else {
10584 				__mark_reg_known(regs + insn->dst_reg,
10585 						 (u32)insn->imm);
10586 			}
10587 		}
10588 
10589 	} else if (opcode > BPF_END) {
10590 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10591 		return -EINVAL;
10592 
10593 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
10594 
10595 		if (BPF_SRC(insn->code) == BPF_X) {
10596 			if (insn->imm != 0 || insn->off != 0) {
10597 				verbose(env, "BPF_ALU uses reserved fields\n");
10598 				return -EINVAL;
10599 			}
10600 			/* check src1 operand */
10601 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10602 			if (err)
10603 				return err;
10604 		} else {
10605 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10606 				verbose(env, "BPF_ALU uses reserved fields\n");
10607 				return -EINVAL;
10608 			}
10609 		}
10610 
10611 		/* check src2 operand */
10612 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10613 		if (err)
10614 			return err;
10615 
10616 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10617 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10618 			verbose(env, "div by zero\n");
10619 			return -EINVAL;
10620 		}
10621 
10622 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10623 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10624 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10625 
10626 			if (insn->imm < 0 || insn->imm >= size) {
10627 				verbose(env, "invalid shift %d\n", insn->imm);
10628 				return -EINVAL;
10629 			}
10630 		}
10631 
10632 		/* check dest operand */
10633 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10634 		if (err)
10635 			return err;
10636 
10637 		return adjust_reg_min_max_vals(env, insn);
10638 	}
10639 
10640 	return 0;
10641 }
10642 
10643 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10644 				   struct bpf_reg_state *dst_reg,
10645 				   enum bpf_reg_type type,
10646 				   bool range_right_open)
10647 {
10648 	struct bpf_func_state *state;
10649 	struct bpf_reg_state *reg;
10650 	int new_range;
10651 
10652 	if (dst_reg->off < 0 ||
10653 	    (dst_reg->off == 0 && range_right_open))
10654 		/* This doesn't give us any range */
10655 		return;
10656 
10657 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
10658 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10659 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
10660 		 * than pkt_end, but that's because it's also less than pkt.
10661 		 */
10662 		return;
10663 
10664 	new_range = dst_reg->off;
10665 	if (range_right_open)
10666 		new_range++;
10667 
10668 	/* Examples for register markings:
10669 	 *
10670 	 * pkt_data in dst register:
10671 	 *
10672 	 *   r2 = r3;
10673 	 *   r2 += 8;
10674 	 *   if (r2 > pkt_end) goto <handle exception>
10675 	 *   <access okay>
10676 	 *
10677 	 *   r2 = r3;
10678 	 *   r2 += 8;
10679 	 *   if (r2 < pkt_end) goto <access okay>
10680 	 *   <handle exception>
10681 	 *
10682 	 *   Where:
10683 	 *     r2 == dst_reg, pkt_end == src_reg
10684 	 *     r2=pkt(id=n,off=8,r=0)
10685 	 *     r3=pkt(id=n,off=0,r=0)
10686 	 *
10687 	 * pkt_data in src register:
10688 	 *
10689 	 *   r2 = r3;
10690 	 *   r2 += 8;
10691 	 *   if (pkt_end >= r2) goto <access okay>
10692 	 *   <handle exception>
10693 	 *
10694 	 *   r2 = r3;
10695 	 *   r2 += 8;
10696 	 *   if (pkt_end <= r2) goto <handle exception>
10697 	 *   <access okay>
10698 	 *
10699 	 *   Where:
10700 	 *     pkt_end == dst_reg, r2 == src_reg
10701 	 *     r2=pkt(id=n,off=8,r=0)
10702 	 *     r3=pkt(id=n,off=0,r=0)
10703 	 *
10704 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
10705 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
10706 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
10707 	 * the check.
10708 	 */
10709 
10710 	/* If our ids match, then we must have the same max_value.  And we
10711 	 * don't care about the other reg's fixed offset, since if it's too big
10712 	 * the range won't allow anything.
10713 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
10714 	 */
10715 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10716 		if (reg->type == type && reg->id == dst_reg->id)
10717 			/* keep the maximum range already checked */
10718 			reg->range = max(reg->range, new_range);
10719 	}));
10720 }
10721 
10722 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
10723 {
10724 	struct tnum subreg = tnum_subreg(reg->var_off);
10725 	s32 sval = (s32)val;
10726 
10727 	switch (opcode) {
10728 	case BPF_JEQ:
10729 		if (tnum_is_const(subreg))
10730 			return !!tnum_equals_const(subreg, val);
10731 		break;
10732 	case BPF_JNE:
10733 		if (tnum_is_const(subreg))
10734 			return !tnum_equals_const(subreg, val);
10735 		break;
10736 	case BPF_JSET:
10737 		if ((~subreg.mask & subreg.value) & val)
10738 			return 1;
10739 		if (!((subreg.mask | subreg.value) & val))
10740 			return 0;
10741 		break;
10742 	case BPF_JGT:
10743 		if (reg->u32_min_value > val)
10744 			return 1;
10745 		else if (reg->u32_max_value <= val)
10746 			return 0;
10747 		break;
10748 	case BPF_JSGT:
10749 		if (reg->s32_min_value > sval)
10750 			return 1;
10751 		else if (reg->s32_max_value <= sval)
10752 			return 0;
10753 		break;
10754 	case BPF_JLT:
10755 		if (reg->u32_max_value < val)
10756 			return 1;
10757 		else if (reg->u32_min_value >= val)
10758 			return 0;
10759 		break;
10760 	case BPF_JSLT:
10761 		if (reg->s32_max_value < sval)
10762 			return 1;
10763 		else if (reg->s32_min_value >= sval)
10764 			return 0;
10765 		break;
10766 	case BPF_JGE:
10767 		if (reg->u32_min_value >= val)
10768 			return 1;
10769 		else if (reg->u32_max_value < val)
10770 			return 0;
10771 		break;
10772 	case BPF_JSGE:
10773 		if (reg->s32_min_value >= sval)
10774 			return 1;
10775 		else if (reg->s32_max_value < sval)
10776 			return 0;
10777 		break;
10778 	case BPF_JLE:
10779 		if (reg->u32_max_value <= val)
10780 			return 1;
10781 		else if (reg->u32_min_value > val)
10782 			return 0;
10783 		break;
10784 	case BPF_JSLE:
10785 		if (reg->s32_max_value <= sval)
10786 			return 1;
10787 		else if (reg->s32_min_value > sval)
10788 			return 0;
10789 		break;
10790 	}
10791 
10792 	return -1;
10793 }
10794 
10795 
10796 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
10797 {
10798 	s64 sval = (s64)val;
10799 
10800 	switch (opcode) {
10801 	case BPF_JEQ:
10802 		if (tnum_is_const(reg->var_off))
10803 			return !!tnum_equals_const(reg->var_off, val);
10804 		break;
10805 	case BPF_JNE:
10806 		if (tnum_is_const(reg->var_off))
10807 			return !tnum_equals_const(reg->var_off, val);
10808 		break;
10809 	case BPF_JSET:
10810 		if ((~reg->var_off.mask & reg->var_off.value) & val)
10811 			return 1;
10812 		if (!((reg->var_off.mask | reg->var_off.value) & val))
10813 			return 0;
10814 		break;
10815 	case BPF_JGT:
10816 		if (reg->umin_value > val)
10817 			return 1;
10818 		else if (reg->umax_value <= val)
10819 			return 0;
10820 		break;
10821 	case BPF_JSGT:
10822 		if (reg->smin_value > sval)
10823 			return 1;
10824 		else if (reg->smax_value <= sval)
10825 			return 0;
10826 		break;
10827 	case BPF_JLT:
10828 		if (reg->umax_value < val)
10829 			return 1;
10830 		else if (reg->umin_value >= val)
10831 			return 0;
10832 		break;
10833 	case BPF_JSLT:
10834 		if (reg->smax_value < sval)
10835 			return 1;
10836 		else if (reg->smin_value >= sval)
10837 			return 0;
10838 		break;
10839 	case BPF_JGE:
10840 		if (reg->umin_value >= val)
10841 			return 1;
10842 		else if (reg->umax_value < val)
10843 			return 0;
10844 		break;
10845 	case BPF_JSGE:
10846 		if (reg->smin_value >= sval)
10847 			return 1;
10848 		else if (reg->smax_value < sval)
10849 			return 0;
10850 		break;
10851 	case BPF_JLE:
10852 		if (reg->umax_value <= val)
10853 			return 1;
10854 		else if (reg->umin_value > val)
10855 			return 0;
10856 		break;
10857 	case BPF_JSLE:
10858 		if (reg->smax_value <= sval)
10859 			return 1;
10860 		else if (reg->smin_value > sval)
10861 			return 0;
10862 		break;
10863 	}
10864 
10865 	return -1;
10866 }
10867 
10868 /* compute branch direction of the expression "if (reg opcode val) goto target;"
10869  * and return:
10870  *  1 - branch will be taken and "goto target" will be executed
10871  *  0 - branch will not be taken and fall-through to next insn
10872  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
10873  *      range [0,10]
10874  */
10875 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
10876 			   bool is_jmp32)
10877 {
10878 	if (__is_pointer_value(false, reg)) {
10879 		if (!reg_type_not_null(reg->type))
10880 			return -1;
10881 
10882 		/* If pointer is valid tests against zero will fail so we can
10883 		 * use this to direct branch taken.
10884 		 */
10885 		if (val != 0)
10886 			return -1;
10887 
10888 		switch (opcode) {
10889 		case BPF_JEQ:
10890 			return 0;
10891 		case BPF_JNE:
10892 			return 1;
10893 		default:
10894 			return -1;
10895 		}
10896 	}
10897 
10898 	if (is_jmp32)
10899 		return is_branch32_taken(reg, val, opcode);
10900 	return is_branch64_taken(reg, val, opcode);
10901 }
10902 
10903 static int flip_opcode(u32 opcode)
10904 {
10905 	/* How can we transform "a <op> b" into "b <op> a"? */
10906 	static const u8 opcode_flip[16] = {
10907 		/* these stay the same */
10908 		[BPF_JEQ  >> 4] = BPF_JEQ,
10909 		[BPF_JNE  >> 4] = BPF_JNE,
10910 		[BPF_JSET >> 4] = BPF_JSET,
10911 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
10912 		[BPF_JGE  >> 4] = BPF_JLE,
10913 		[BPF_JGT  >> 4] = BPF_JLT,
10914 		[BPF_JLE  >> 4] = BPF_JGE,
10915 		[BPF_JLT  >> 4] = BPF_JGT,
10916 		[BPF_JSGE >> 4] = BPF_JSLE,
10917 		[BPF_JSGT >> 4] = BPF_JSLT,
10918 		[BPF_JSLE >> 4] = BPF_JSGE,
10919 		[BPF_JSLT >> 4] = BPF_JSGT
10920 	};
10921 	return opcode_flip[opcode >> 4];
10922 }
10923 
10924 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
10925 				   struct bpf_reg_state *src_reg,
10926 				   u8 opcode)
10927 {
10928 	struct bpf_reg_state *pkt;
10929 
10930 	if (src_reg->type == PTR_TO_PACKET_END) {
10931 		pkt = dst_reg;
10932 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
10933 		pkt = src_reg;
10934 		opcode = flip_opcode(opcode);
10935 	} else {
10936 		return -1;
10937 	}
10938 
10939 	if (pkt->range >= 0)
10940 		return -1;
10941 
10942 	switch (opcode) {
10943 	case BPF_JLE:
10944 		/* pkt <= pkt_end */
10945 		fallthrough;
10946 	case BPF_JGT:
10947 		/* pkt > pkt_end */
10948 		if (pkt->range == BEYOND_PKT_END)
10949 			/* pkt has at last one extra byte beyond pkt_end */
10950 			return opcode == BPF_JGT;
10951 		break;
10952 	case BPF_JLT:
10953 		/* pkt < pkt_end */
10954 		fallthrough;
10955 	case BPF_JGE:
10956 		/* pkt >= pkt_end */
10957 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
10958 			return opcode == BPF_JGE;
10959 		break;
10960 	}
10961 	return -1;
10962 }
10963 
10964 /* Adjusts the register min/max values in the case that the dst_reg is the
10965  * variable register that we are working on, and src_reg is a constant or we're
10966  * simply doing a BPF_K check.
10967  * In JEQ/JNE cases we also adjust the var_off values.
10968  */
10969 static void reg_set_min_max(struct bpf_reg_state *true_reg,
10970 			    struct bpf_reg_state *false_reg,
10971 			    u64 val, u32 val32,
10972 			    u8 opcode, bool is_jmp32)
10973 {
10974 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
10975 	struct tnum false_64off = false_reg->var_off;
10976 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
10977 	struct tnum true_64off = true_reg->var_off;
10978 	s64 sval = (s64)val;
10979 	s32 sval32 = (s32)val32;
10980 
10981 	/* If the dst_reg is a pointer, we can't learn anything about its
10982 	 * variable offset from the compare (unless src_reg were a pointer into
10983 	 * the same object, but we don't bother with that.
10984 	 * Since false_reg and true_reg have the same type by construction, we
10985 	 * only need to check one of them for pointerness.
10986 	 */
10987 	if (__is_pointer_value(false, false_reg))
10988 		return;
10989 
10990 	switch (opcode) {
10991 	/* JEQ/JNE comparison doesn't change the register equivalence.
10992 	 *
10993 	 * r1 = r2;
10994 	 * if (r1 == 42) goto label;
10995 	 * ...
10996 	 * label: // here both r1 and r2 are known to be 42.
10997 	 *
10998 	 * Hence when marking register as known preserve it's ID.
10999 	 */
11000 	case BPF_JEQ:
11001 		if (is_jmp32) {
11002 			__mark_reg32_known(true_reg, val32);
11003 			true_32off = tnum_subreg(true_reg->var_off);
11004 		} else {
11005 			___mark_reg_known(true_reg, val);
11006 			true_64off = true_reg->var_off;
11007 		}
11008 		break;
11009 	case BPF_JNE:
11010 		if (is_jmp32) {
11011 			__mark_reg32_known(false_reg, val32);
11012 			false_32off = tnum_subreg(false_reg->var_off);
11013 		} else {
11014 			___mark_reg_known(false_reg, val);
11015 			false_64off = false_reg->var_off;
11016 		}
11017 		break;
11018 	case BPF_JSET:
11019 		if (is_jmp32) {
11020 			false_32off = tnum_and(false_32off, tnum_const(~val32));
11021 			if (is_power_of_2(val32))
11022 				true_32off = tnum_or(true_32off,
11023 						     tnum_const(val32));
11024 		} else {
11025 			false_64off = tnum_and(false_64off, tnum_const(~val));
11026 			if (is_power_of_2(val))
11027 				true_64off = tnum_or(true_64off,
11028 						     tnum_const(val));
11029 		}
11030 		break;
11031 	case BPF_JGE:
11032 	case BPF_JGT:
11033 	{
11034 		if (is_jmp32) {
11035 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11036 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11037 
11038 			false_reg->u32_max_value = min(false_reg->u32_max_value,
11039 						       false_umax);
11040 			true_reg->u32_min_value = max(true_reg->u32_min_value,
11041 						      true_umin);
11042 		} else {
11043 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11044 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11045 
11046 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
11047 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
11048 		}
11049 		break;
11050 	}
11051 	case BPF_JSGE:
11052 	case BPF_JSGT:
11053 	{
11054 		if (is_jmp32) {
11055 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11056 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11057 
11058 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11059 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11060 		} else {
11061 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11062 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11063 
11064 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
11065 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
11066 		}
11067 		break;
11068 	}
11069 	case BPF_JLE:
11070 	case BPF_JLT:
11071 	{
11072 		if (is_jmp32) {
11073 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11074 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11075 
11076 			false_reg->u32_min_value = max(false_reg->u32_min_value,
11077 						       false_umin);
11078 			true_reg->u32_max_value = min(true_reg->u32_max_value,
11079 						      true_umax);
11080 		} else {
11081 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11082 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11083 
11084 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
11085 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
11086 		}
11087 		break;
11088 	}
11089 	case BPF_JSLE:
11090 	case BPF_JSLT:
11091 	{
11092 		if (is_jmp32) {
11093 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11094 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11095 
11096 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11097 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11098 		} else {
11099 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11100 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11101 
11102 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
11103 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
11104 		}
11105 		break;
11106 	}
11107 	default:
11108 		return;
11109 	}
11110 
11111 	if (is_jmp32) {
11112 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11113 					     tnum_subreg(false_32off));
11114 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11115 					    tnum_subreg(true_32off));
11116 		__reg_combine_32_into_64(false_reg);
11117 		__reg_combine_32_into_64(true_reg);
11118 	} else {
11119 		false_reg->var_off = false_64off;
11120 		true_reg->var_off = true_64off;
11121 		__reg_combine_64_into_32(false_reg);
11122 		__reg_combine_64_into_32(true_reg);
11123 	}
11124 }
11125 
11126 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11127  * the variable reg.
11128  */
11129 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11130 				struct bpf_reg_state *false_reg,
11131 				u64 val, u32 val32,
11132 				u8 opcode, bool is_jmp32)
11133 {
11134 	opcode = flip_opcode(opcode);
11135 	/* This uses zero as "not present in table"; luckily the zero opcode,
11136 	 * BPF_JA, can't get here.
11137 	 */
11138 	if (opcode)
11139 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11140 }
11141 
11142 /* Regs are known to be equal, so intersect their min/max/var_off */
11143 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11144 				  struct bpf_reg_state *dst_reg)
11145 {
11146 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11147 							dst_reg->umin_value);
11148 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11149 							dst_reg->umax_value);
11150 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11151 							dst_reg->smin_value);
11152 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11153 							dst_reg->smax_value);
11154 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11155 							     dst_reg->var_off);
11156 	reg_bounds_sync(src_reg);
11157 	reg_bounds_sync(dst_reg);
11158 }
11159 
11160 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11161 				struct bpf_reg_state *true_dst,
11162 				struct bpf_reg_state *false_src,
11163 				struct bpf_reg_state *false_dst,
11164 				u8 opcode)
11165 {
11166 	switch (opcode) {
11167 	case BPF_JEQ:
11168 		__reg_combine_min_max(true_src, true_dst);
11169 		break;
11170 	case BPF_JNE:
11171 		__reg_combine_min_max(false_src, false_dst);
11172 		break;
11173 	}
11174 }
11175 
11176 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11177 				 struct bpf_reg_state *reg, u32 id,
11178 				 bool is_null)
11179 {
11180 	if (type_may_be_null(reg->type) && reg->id == id &&
11181 	    !WARN_ON_ONCE(!reg->id)) {
11182 		/* Old offset (both fixed and variable parts) should have been
11183 		 * known-zero, because we don't allow pointer arithmetic on
11184 		 * pointers that might be NULL. If we see this happening, don't
11185 		 * convert the register.
11186 		 *
11187 		 * But in some cases, some helpers that return local kptrs
11188 		 * advance offset for the returned pointer. In those cases, it
11189 		 * is fine to expect to see reg->off.
11190 		 */
11191 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11192 			return;
11193 		if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11194 			return;
11195 		if (is_null) {
11196 			reg->type = SCALAR_VALUE;
11197 			/* We don't need id and ref_obj_id from this point
11198 			 * onwards anymore, thus we should better reset it,
11199 			 * so that state pruning has chances to take effect.
11200 			 */
11201 			reg->id = 0;
11202 			reg->ref_obj_id = 0;
11203 
11204 			return;
11205 		}
11206 
11207 		mark_ptr_not_null_reg(reg);
11208 
11209 		if (!reg_may_point_to_spin_lock(reg)) {
11210 			/* For not-NULL ptr, reg->ref_obj_id will be reset
11211 			 * in release_reference().
11212 			 *
11213 			 * reg->id is still used by spin_lock ptr. Other
11214 			 * than spin_lock ptr type, reg->id can be reset.
11215 			 */
11216 			reg->id = 0;
11217 		}
11218 	}
11219 }
11220 
11221 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11222  * be folded together at some point.
11223  */
11224 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11225 				  bool is_null)
11226 {
11227 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11228 	struct bpf_reg_state *regs = state->regs, *reg;
11229 	u32 ref_obj_id = regs[regno].ref_obj_id;
11230 	u32 id = regs[regno].id;
11231 
11232 	if (ref_obj_id && ref_obj_id == id && is_null)
11233 		/* regs[regno] is in the " == NULL" branch.
11234 		 * No one could have freed the reference state before
11235 		 * doing the NULL check.
11236 		 */
11237 		WARN_ON_ONCE(release_reference_state(state, id));
11238 
11239 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11240 		mark_ptr_or_null_reg(state, reg, id, is_null);
11241 	}));
11242 }
11243 
11244 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11245 				   struct bpf_reg_state *dst_reg,
11246 				   struct bpf_reg_state *src_reg,
11247 				   struct bpf_verifier_state *this_branch,
11248 				   struct bpf_verifier_state *other_branch)
11249 {
11250 	if (BPF_SRC(insn->code) != BPF_X)
11251 		return false;
11252 
11253 	/* Pointers are always 64-bit. */
11254 	if (BPF_CLASS(insn->code) == BPF_JMP32)
11255 		return false;
11256 
11257 	switch (BPF_OP(insn->code)) {
11258 	case BPF_JGT:
11259 		if ((dst_reg->type == PTR_TO_PACKET &&
11260 		     src_reg->type == PTR_TO_PACKET_END) ||
11261 		    (dst_reg->type == PTR_TO_PACKET_META &&
11262 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11263 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11264 			find_good_pkt_pointers(this_branch, dst_reg,
11265 					       dst_reg->type, false);
11266 			mark_pkt_end(other_branch, insn->dst_reg, true);
11267 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11268 			    src_reg->type == PTR_TO_PACKET) ||
11269 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11270 			    src_reg->type == PTR_TO_PACKET_META)) {
11271 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
11272 			find_good_pkt_pointers(other_branch, src_reg,
11273 					       src_reg->type, true);
11274 			mark_pkt_end(this_branch, insn->src_reg, false);
11275 		} else {
11276 			return false;
11277 		}
11278 		break;
11279 	case BPF_JLT:
11280 		if ((dst_reg->type == PTR_TO_PACKET &&
11281 		     src_reg->type == PTR_TO_PACKET_END) ||
11282 		    (dst_reg->type == PTR_TO_PACKET_META &&
11283 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11284 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11285 			find_good_pkt_pointers(other_branch, dst_reg,
11286 					       dst_reg->type, true);
11287 			mark_pkt_end(this_branch, insn->dst_reg, false);
11288 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11289 			    src_reg->type == PTR_TO_PACKET) ||
11290 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11291 			    src_reg->type == PTR_TO_PACKET_META)) {
11292 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
11293 			find_good_pkt_pointers(this_branch, src_reg,
11294 					       src_reg->type, false);
11295 			mark_pkt_end(other_branch, insn->src_reg, true);
11296 		} else {
11297 			return false;
11298 		}
11299 		break;
11300 	case BPF_JGE:
11301 		if ((dst_reg->type == PTR_TO_PACKET &&
11302 		     src_reg->type == PTR_TO_PACKET_END) ||
11303 		    (dst_reg->type == PTR_TO_PACKET_META &&
11304 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11305 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11306 			find_good_pkt_pointers(this_branch, dst_reg,
11307 					       dst_reg->type, true);
11308 			mark_pkt_end(other_branch, insn->dst_reg, false);
11309 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11310 			    src_reg->type == PTR_TO_PACKET) ||
11311 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11312 			    src_reg->type == PTR_TO_PACKET_META)) {
11313 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11314 			find_good_pkt_pointers(other_branch, src_reg,
11315 					       src_reg->type, false);
11316 			mark_pkt_end(this_branch, insn->src_reg, true);
11317 		} else {
11318 			return false;
11319 		}
11320 		break;
11321 	case BPF_JLE:
11322 		if ((dst_reg->type == PTR_TO_PACKET &&
11323 		     src_reg->type == PTR_TO_PACKET_END) ||
11324 		    (dst_reg->type == PTR_TO_PACKET_META &&
11325 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11326 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11327 			find_good_pkt_pointers(other_branch, dst_reg,
11328 					       dst_reg->type, false);
11329 			mark_pkt_end(this_branch, insn->dst_reg, true);
11330 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11331 			    src_reg->type == PTR_TO_PACKET) ||
11332 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11333 			    src_reg->type == PTR_TO_PACKET_META)) {
11334 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11335 			find_good_pkt_pointers(this_branch, src_reg,
11336 					       src_reg->type, true);
11337 			mark_pkt_end(other_branch, insn->src_reg, false);
11338 		} else {
11339 			return false;
11340 		}
11341 		break;
11342 	default:
11343 		return false;
11344 	}
11345 
11346 	return true;
11347 }
11348 
11349 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11350 			       struct bpf_reg_state *known_reg)
11351 {
11352 	struct bpf_func_state *state;
11353 	struct bpf_reg_state *reg;
11354 
11355 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11356 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11357 			*reg = *known_reg;
11358 	}));
11359 }
11360 
11361 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11362 			     struct bpf_insn *insn, int *insn_idx)
11363 {
11364 	struct bpf_verifier_state *this_branch = env->cur_state;
11365 	struct bpf_verifier_state *other_branch;
11366 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11367 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11368 	struct bpf_reg_state *eq_branch_regs;
11369 	u8 opcode = BPF_OP(insn->code);
11370 	bool is_jmp32;
11371 	int pred = -1;
11372 	int err;
11373 
11374 	/* Only conditional jumps are expected to reach here. */
11375 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
11376 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11377 		return -EINVAL;
11378 	}
11379 
11380 	if (BPF_SRC(insn->code) == BPF_X) {
11381 		if (insn->imm != 0) {
11382 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11383 			return -EINVAL;
11384 		}
11385 
11386 		/* check src1 operand */
11387 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
11388 		if (err)
11389 			return err;
11390 
11391 		if (is_pointer_value(env, insn->src_reg)) {
11392 			verbose(env, "R%d pointer comparison prohibited\n",
11393 				insn->src_reg);
11394 			return -EACCES;
11395 		}
11396 		src_reg = &regs[insn->src_reg];
11397 	} else {
11398 		if (insn->src_reg != BPF_REG_0) {
11399 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11400 			return -EINVAL;
11401 		}
11402 	}
11403 
11404 	/* check src2 operand */
11405 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11406 	if (err)
11407 		return err;
11408 
11409 	dst_reg = &regs[insn->dst_reg];
11410 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11411 
11412 	if (BPF_SRC(insn->code) == BPF_K) {
11413 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11414 	} else if (src_reg->type == SCALAR_VALUE &&
11415 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11416 		pred = is_branch_taken(dst_reg,
11417 				       tnum_subreg(src_reg->var_off).value,
11418 				       opcode,
11419 				       is_jmp32);
11420 	} else if (src_reg->type == SCALAR_VALUE &&
11421 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11422 		pred = is_branch_taken(dst_reg,
11423 				       src_reg->var_off.value,
11424 				       opcode,
11425 				       is_jmp32);
11426 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
11427 		   reg_is_pkt_pointer_any(src_reg) &&
11428 		   !is_jmp32) {
11429 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11430 	}
11431 
11432 	if (pred >= 0) {
11433 		/* If we get here with a dst_reg pointer type it is because
11434 		 * above is_branch_taken() special cased the 0 comparison.
11435 		 */
11436 		if (!__is_pointer_value(false, dst_reg))
11437 			err = mark_chain_precision(env, insn->dst_reg);
11438 		if (BPF_SRC(insn->code) == BPF_X && !err &&
11439 		    !__is_pointer_value(false, src_reg))
11440 			err = mark_chain_precision(env, insn->src_reg);
11441 		if (err)
11442 			return err;
11443 	}
11444 
11445 	if (pred == 1) {
11446 		/* Only follow the goto, ignore fall-through. If needed, push
11447 		 * the fall-through branch for simulation under speculative
11448 		 * execution.
11449 		 */
11450 		if (!env->bypass_spec_v1 &&
11451 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
11452 					       *insn_idx))
11453 			return -EFAULT;
11454 		*insn_idx += insn->off;
11455 		return 0;
11456 	} else if (pred == 0) {
11457 		/* Only follow the fall-through branch, since that's where the
11458 		 * program will go. If needed, push the goto branch for
11459 		 * simulation under speculative execution.
11460 		 */
11461 		if (!env->bypass_spec_v1 &&
11462 		    !sanitize_speculative_path(env, insn,
11463 					       *insn_idx + insn->off + 1,
11464 					       *insn_idx))
11465 			return -EFAULT;
11466 		return 0;
11467 	}
11468 
11469 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11470 				  false);
11471 	if (!other_branch)
11472 		return -EFAULT;
11473 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11474 
11475 	/* detect if we are comparing against a constant value so we can adjust
11476 	 * our min/max values for our dst register.
11477 	 * this is only legit if both are scalars (or pointers to the same
11478 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11479 	 * because otherwise the different base pointers mean the offsets aren't
11480 	 * comparable.
11481 	 */
11482 	if (BPF_SRC(insn->code) == BPF_X) {
11483 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
11484 
11485 		if (dst_reg->type == SCALAR_VALUE &&
11486 		    src_reg->type == SCALAR_VALUE) {
11487 			if (tnum_is_const(src_reg->var_off) ||
11488 			    (is_jmp32 &&
11489 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
11490 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
11491 						dst_reg,
11492 						src_reg->var_off.value,
11493 						tnum_subreg(src_reg->var_off).value,
11494 						opcode, is_jmp32);
11495 			else if (tnum_is_const(dst_reg->var_off) ||
11496 				 (is_jmp32 &&
11497 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
11498 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11499 						    src_reg,
11500 						    dst_reg->var_off.value,
11501 						    tnum_subreg(dst_reg->var_off).value,
11502 						    opcode, is_jmp32);
11503 			else if (!is_jmp32 &&
11504 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
11505 				/* Comparing for equality, we can combine knowledge */
11506 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
11507 						    &other_branch_regs[insn->dst_reg],
11508 						    src_reg, dst_reg, opcode);
11509 			if (src_reg->id &&
11510 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11511 				find_equal_scalars(this_branch, src_reg);
11512 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11513 			}
11514 
11515 		}
11516 	} else if (dst_reg->type == SCALAR_VALUE) {
11517 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
11518 					dst_reg, insn->imm, (u32)insn->imm,
11519 					opcode, is_jmp32);
11520 	}
11521 
11522 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11523 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11524 		find_equal_scalars(this_branch, dst_reg);
11525 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11526 	}
11527 
11528 	/* if one pointer register is compared to another pointer
11529 	 * register check if PTR_MAYBE_NULL could be lifted.
11530 	 * E.g. register A - maybe null
11531 	 *      register B - not null
11532 	 * for JNE A, B, ... - A is not null in the false branch;
11533 	 * for JEQ A, B, ... - A is not null in the true branch.
11534 	 */
11535 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11536 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11537 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11538 		eq_branch_regs = NULL;
11539 		switch (opcode) {
11540 		case BPF_JEQ:
11541 			eq_branch_regs = other_branch_regs;
11542 			break;
11543 		case BPF_JNE:
11544 			eq_branch_regs = regs;
11545 			break;
11546 		default:
11547 			/* do nothing */
11548 			break;
11549 		}
11550 		if (eq_branch_regs) {
11551 			if (type_may_be_null(src_reg->type))
11552 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11553 			else
11554 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11555 		}
11556 	}
11557 
11558 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11559 	 * NOTE: these optimizations below are related with pointer comparison
11560 	 *       which will never be JMP32.
11561 	 */
11562 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11563 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11564 	    type_may_be_null(dst_reg->type)) {
11565 		/* Mark all identical registers in each branch as either
11566 		 * safe or unknown depending R == 0 or R != 0 conditional.
11567 		 */
11568 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11569 				      opcode == BPF_JNE);
11570 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11571 				      opcode == BPF_JEQ);
11572 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11573 					   this_branch, other_branch) &&
11574 		   is_pointer_value(env, insn->dst_reg)) {
11575 		verbose(env, "R%d pointer comparison prohibited\n",
11576 			insn->dst_reg);
11577 		return -EACCES;
11578 	}
11579 	if (env->log.level & BPF_LOG_LEVEL)
11580 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
11581 	return 0;
11582 }
11583 
11584 /* verify BPF_LD_IMM64 instruction */
11585 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11586 {
11587 	struct bpf_insn_aux_data *aux = cur_aux(env);
11588 	struct bpf_reg_state *regs = cur_regs(env);
11589 	struct bpf_reg_state *dst_reg;
11590 	struct bpf_map *map;
11591 	int err;
11592 
11593 	if (BPF_SIZE(insn->code) != BPF_DW) {
11594 		verbose(env, "invalid BPF_LD_IMM insn\n");
11595 		return -EINVAL;
11596 	}
11597 	if (insn->off != 0) {
11598 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11599 		return -EINVAL;
11600 	}
11601 
11602 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
11603 	if (err)
11604 		return err;
11605 
11606 	dst_reg = &regs[insn->dst_reg];
11607 	if (insn->src_reg == 0) {
11608 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11609 
11610 		dst_reg->type = SCALAR_VALUE;
11611 		__mark_reg_known(&regs[insn->dst_reg], imm);
11612 		return 0;
11613 	}
11614 
11615 	/* All special src_reg cases are listed below. From this point onwards
11616 	 * we either succeed and assign a corresponding dst_reg->type after
11617 	 * zeroing the offset, or fail and reject the program.
11618 	 */
11619 	mark_reg_known_zero(env, regs, insn->dst_reg);
11620 
11621 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11622 		dst_reg->type = aux->btf_var.reg_type;
11623 		switch (base_type(dst_reg->type)) {
11624 		case PTR_TO_MEM:
11625 			dst_reg->mem_size = aux->btf_var.mem_size;
11626 			break;
11627 		case PTR_TO_BTF_ID:
11628 			dst_reg->btf = aux->btf_var.btf;
11629 			dst_reg->btf_id = aux->btf_var.btf_id;
11630 			break;
11631 		default:
11632 			verbose(env, "bpf verifier is misconfigured\n");
11633 			return -EFAULT;
11634 		}
11635 		return 0;
11636 	}
11637 
11638 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
11639 		struct bpf_prog_aux *aux = env->prog->aux;
11640 		u32 subprogno = find_subprog(env,
11641 					     env->insn_idx + insn->imm + 1);
11642 
11643 		if (!aux->func_info) {
11644 			verbose(env, "missing btf func_info\n");
11645 			return -EINVAL;
11646 		}
11647 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11648 			verbose(env, "callback function not static\n");
11649 			return -EINVAL;
11650 		}
11651 
11652 		dst_reg->type = PTR_TO_FUNC;
11653 		dst_reg->subprogno = subprogno;
11654 		return 0;
11655 	}
11656 
11657 	map = env->used_maps[aux->map_index];
11658 	dst_reg->map_ptr = map;
11659 
11660 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11661 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11662 		dst_reg->type = PTR_TO_MAP_VALUE;
11663 		dst_reg->off = aux->map_off;
11664 		WARN_ON_ONCE(map->max_entries != 1);
11665 		/* We want reg->id to be same (0) as map_value is not distinct */
11666 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11667 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11668 		dst_reg->type = CONST_PTR_TO_MAP;
11669 	} else {
11670 		verbose(env, "bpf verifier is misconfigured\n");
11671 		return -EINVAL;
11672 	}
11673 
11674 	return 0;
11675 }
11676 
11677 static bool may_access_skb(enum bpf_prog_type type)
11678 {
11679 	switch (type) {
11680 	case BPF_PROG_TYPE_SOCKET_FILTER:
11681 	case BPF_PROG_TYPE_SCHED_CLS:
11682 	case BPF_PROG_TYPE_SCHED_ACT:
11683 		return true;
11684 	default:
11685 		return false;
11686 	}
11687 }
11688 
11689 /* verify safety of LD_ABS|LD_IND instructions:
11690  * - they can only appear in the programs where ctx == skb
11691  * - since they are wrappers of function calls, they scratch R1-R5 registers,
11692  *   preserve R6-R9, and store return value into R0
11693  *
11694  * Implicit input:
11695  *   ctx == skb == R6 == CTX
11696  *
11697  * Explicit input:
11698  *   SRC == any register
11699  *   IMM == 32-bit immediate
11700  *
11701  * Output:
11702  *   R0 - 8/16/32-bit skb data converted to cpu endianness
11703  */
11704 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
11705 {
11706 	struct bpf_reg_state *regs = cur_regs(env);
11707 	static const int ctx_reg = BPF_REG_6;
11708 	u8 mode = BPF_MODE(insn->code);
11709 	int i, err;
11710 
11711 	if (!may_access_skb(resolve_prog_type(env->prog))) {
11712 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
11713 		return -EINVAL;
11714 	}
11715 
11716 	if (!env->ops->gen_ld_abs) {
11717 		verbose(env, "bpf verifier is misconfigured\n");
11718 		return -EINVAL;
11719 	}
11720 
11721 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
11722 	    BPF_SIZE(insn->code) == BPF_DW ||
11723 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
11724 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
11725 		return -EINVAL;
11726 	}
11727 
11728 	/* check whether implicit source operand (register R6) is readable */
11729 	err = check_reg_arg(env, ctx_reg, SRC_OP);
11730 	if (err)
11731 		return err;
11732 
11733 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
11734 	 * gen_ld_abs() may terminate the program at runtime, leading to
11735 	 * reference leak.
11736 	 */
11737 	err = check_reference_leak(env);
11738 	if (err) {
11739 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
11740 		return err;
11741 	}
11742 
11743 	if (env->cur_state->active_lock.ptr) {
11744 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
11745 		return -EINVAL;
11746 	}
11747 
11748 	if (regs[ctx_reg].type != PTR_TO_CTX) {
11749 		verbose(env,
11750 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
11751 		return -EINVAL;
11752 	}
11753 
11754 	if (mode == BPF_IND) {
11755 		/* check explicit source operand */
11756 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
11757 		if (err)
11758 			return err;
11759 	}
11760 
11761 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
11762 	if (err < 0)
11763 		return err;
11764 
11765 	/* reset caller saved regs to unreadable */
11766 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11767 		mark_reg_not_init(env, regs, caller_saved[i]);
11768 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11769 	}
11770 
11771 	/* mark destination R0 register as readable, since it contains
11772 	 * the value fetched from the packet.
11773 	 * Already marked as written above.
11774 	 */
11775 	mark_reg_unknown(env, regs, BPF_REG_0);
11776 	/* ld_abs load up to 32-bit skb data. */
11777 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
11778 	return 0;
11779 }
11780 
11781 static int check_return_code(struct bpf_verifier_env *env)
11782 {
11783 	struct tnum enforce_attach_type_range = tnum_unknown;
11784 	const struct bpf_prog *prog = env->prog;
11785 	struct bpf_reg_state *reg;
11786 	struct tnum range = tnum_range(0, 1);
11787 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11788 	int err;
11789 	struct bpf_func_state *frame = env->cur_state->frame[0];
11790 	const bool is_subprog = frame->subprogno;
11791 
11792 	/* LSM and struct_ops func-ptr's return type could be "void" */
11793 	if (!is_subprog) {
11794 		switch (prog_type) {
11795 		case BPF_PROG_TYPE_LSM:
11796 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
11797 				/* See below, can be 0 or 0-1 depending on hook. */
11798 				break;
11799 			fallthrough;
11800 		case BPF_PROG_TYPE_STRUCT_OPS:
11801 			if (!prog->aux->attach_func_proto->type)
11802 				return 0;
11803 			break;
11804 		default:
11805 			break;
11806 		}
11807 	}
11808 
11809 	/* eBPF calling convention is such that R0 is used
11810 	 * to return the value from eBPF program.
11811 	 * Make sure that it's readable at this time
11812 	 * of bpf_exit, which means that program wrote
11813 	 * something into it earlier
11814 	 */
11815 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
11816 	if (err)
11817 		return err;
11818 
11819 	if (is_pointer_value(env, BPF_REG_0)) {
11820 		verbose(env, "R0 leaks addr as return value\n");
11821 		return -EACCES;
11822 	}
11823 
11824 	reg = cur_regs(env) + BPF_REG_0;
11825 
11826 	if (frame->in_async_callback_fn) {
11827 		/* enforce return zero from async callbacks like timer */
11828 		if (reg->type != SCALAR_VALUE) {
11829 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
11830 				reg_type_str(env, reg->type));
11831 			return -EINVAL;
11832 		}
11833 
11834 		if (!tnum_in(tnum_const(0), reg->var_off)) {
11835 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
11836 			return -EINVAL;
11837 		}
11838 		return 0;
11839 	}
11840 
11841 	if (is_subprog) {
11842 		if (reg->type != SCALAR_VALUE) {
11843 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
11844 				reg_type_str(env, reg->type));
11845 			return -EINVAL;
11846 		}
11847 		return 0;
11848 	}
11849 
11850 	switch (prog_type) {
11851 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
11852 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
11853 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
11854 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
11855 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
11856 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
11857 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
11858 			range = tnum_range(1, 1);
11859 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
11860 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
11861 			range = tnum_range(0, 3);
11862 		break;
11863 	case BPF_PROG_TYPE_CGROUP_SKB:
11864 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
11865 			range = tnum_range(0, 3);
11866 			enforce_attach_type_range = tnum_range(2, 3);
11867 		}
11868 		break;
11869 	case BPF_PROG_TYPE_CGROUP_SOCK:
11870 	case BPF_PROG_TYPE_SOCK_OPS:
11871 	case BPF_PROG_TYPE_CGROUP_DEVICE:
11872 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
11873 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
11874 		break;
11875 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11876 		if (!env->prog->aux->attach_btf_id)
11877 			return 0;
11878 		range = tnum_const(0);
11879 		break;
11880 	case BPF_PROG_TYPE_TRACING:
11881 		switch (env->prog->expected_attach_type) {
11882 		case BPF_TRACE_FENTRY:
11883 		case BPF_TRACE_FEXIT:
11884 			range = tnum_const(0);
11885 			break;
11886 		case BPF_TRACE_RAW_TP:
11887 		case BPF_MODIFY_RETURN:
11888 			return 0;
11889 		case BPF_TRACE_ITER:
11890 			break;
11891 		default:
11892 			return -ENOTSUPP;
11893 		}
11894 		break;
11895 	case BPF_PROG_TYPE_SK_LOOKUP:
11896 		range = tnum_range(SK_DROP, SK_PASS);
11897 		break;
11898 
11899 	case BPF_PROG_TYPE_LSM:
11900 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
11901 			/* Regular BPF_PROG_TYPE_LSM programs can return
11902 			 * any value.
11903 			 */
11904 			return 0;
11905 		}
11906 		if (!env->prog->aux->attach_func_proto->type) {
11907 			/* Make sure programs that attach to void
11908 			 * hooks don't try to modify return value.
11909 			 */
11910 			range = tnum_range(1, 1);
11911 		}
11912 		break;
11913 
11914 	case BPF_PROG_TYPE_EXT:
11915 		/* freplace program can return anything as its return value
11916 		 * depends on the to-be-replaced kernel func or bpf program.
11917 		 */
11918 	default:
11919 		return 0;
11920 	}
11921 
11922 	if (reg->type != SCALAR_VALUE) {
11923 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
11924 			reg_type_str(env, reg->type));
11925 		return -EINVAL;
11926 	}
11927 
11928 	if (!tnum_in(range, reg->var_off)) {
11929 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
11930 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
11931 		    prog_type == BPF_PROG_TYPE_LSM &&
11932 		    !prog->aux->attach_func_proto->type)
11933 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11934 		return -EINVAL;
11935 	}
11936 
11937 	if (!tnum_is_unknown(enforce_attach_type_range) &&
11938 	    tnum_in(enforce_attach_type_range, reg->var_off))
11939 		env->prog->enforce_expected_attach_type = 1;
11940 	return 0;
11941 }
11942 
11943 /* non-recursive DFS pseudo code
11944  * 1  procedure DFS-iterative(G,v):
11945  * 2      label v as discovered
11946  * 3      let S be a stack
11947  * 4      S.push(v)
11948  * 5      while S is not empty
11949  * 6            t <- S.peek()
11950  * 7            if t is what we're looking for:
11951  * 8                return t
11952  * 9            for all edges e in G.adjacentEdges(t) do
11953  * 10               if edge e is already labelled
11954  * 11                   continue with the next edge
11955  * 12               w <- G.adjacentVertex(t,e)
11956  * 13               if vertex w is not discovered and not explored
11957  * 14                   label e as tree-edge
11958  * 15                   label w as discovered
11959  * 16                   S.push(w)
11960  * 17                   continue at 5
11961  * 18               else if vertex w is discovered
11962  * 19                   label e as back-edge
11963  * 20               else
11964  * 21                   // vertex w is explored
11965  * 22                   label e as forward- or cross-edge
11966  * 23           label t as explored
11967  * 24           S.pop()
11968  *
11969  * convention:
11970  * 0x10 - discovered
11971  * 0x11 - discovered and fall-through edge labelled
11972  * 0x12 - discovered and fall-through and branch edges labelled
11973  * 0x20 - explored
11974  */
11975 
11976 enum {
11977 	DISCOVERED = 0x10,
11978 	EXPLORED = 0x20,
11979 	FALLTHROUGH = 1,
11980 	BRANCH = 2,
11981 };
11982 
11983 static u32 state_htab_size(struct bpf_verifier_env *env)
11984 {
11985 	return env->prog->len;
11986 }
11987 
11988 static struct bpf_verifier_state_list **explored_state(
11989 					struct bpf_verifier_env *env,
11990 					int idx)
11991 {
11992 	struct bpf_verifier_state *cur = env->cur_state;
11993 	struct bpf_func_state *state = cur->frame[cur->curframe];
11994 
11995 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
11996 }
11997 
11998 static void init_explored_state(struct bpf_verifier_env *env, int idx)
11999 {
12000 	env->insn_aux_data[idx].prune_point = true;
12001 }
12002 
12003 enum {
12004 	DONE_EXPLORING = 0,
12005 	KEEP_EXPLORING = 1,
12006 };
12007 
12008 /* t, w, e - match pseudo-code above:
12009  * t - index of current instruction
12010  * w - next instruction
12011  * e - edge
12012  */
12013 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12014 		     bool loop_ok)
12015 {
12016 	int *insn_stack = env->cfg.insn_stack;
12017 	int *insn_state = env->cfg.insn_state;
12018 
12019 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12020 		return DONE_EXPLORING;
12021 
12022 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12023 		return DONE_EXPLORING;
12024 
12025 	if (w < 0 || w >= env->prog->len) {
12026 		verbose_linfo(env, t, "%d: ", t);
12027 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
12028 		return -EINVAL;
12029 	}
12030 
12031 	if (e == BRANCH)
12032 		/* mark branch target for state pruning */
12033 		init_explored_state(env, w);
12034 
12035 	if (insn_state[w] == 0) {
12036 		/* tree-edge */
12037 		insn_state[t] = DISCOVERED | e;
12038 		insn_state[w] = DISCOVERED;
12039 		if (env->cfg.cur_stack >= env->prog->len)
12040 			return -E2BIG;
12041 		insn_stack[env->cfg.cur_stack++] = w;
12042 		return KEEP_EXPLORING;
12043 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12044 		if (loop_ok && env->bpf_capable)
12045 			return DONE_EXPLORING;
12046 		verbose_linfo(env, t, "%d: ", t);
12047 		verbose_linfo(env, w, "%d: ", w);
12048 		verbose(env, "back-edge from insn %d to %d\n", t, w);
12049 		return -EINVAL;
12050 	} else if (insn_state[w] == EXPLORED) {
12051 		/* forward- or cross-edge */
12052 		insn_state[t] = DISCOVERED | e;
12053 	} else {
12054 		verbose(env, "insn state internal bug\n");
12055 		return -EFAULT;
12056 	}
12057 	return DONE_EXPLORING;
12058 }
12059 
12060 static int visit_func_call_insn(int t, int insn_cnt,
12061 				struct bpf_insn *insns,
12062 				struct bpf_verifier_env *env,
12063 				bool visit_callee)
12064 {
12065 	int ret;
12066 
12067 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12068 	if (ret)
12069 		return ret;
12070 
12071 	if (t + 1 < insn_cnt)
12072 		init_explored_state(env, t + 1);
12073 	if (visit_callee) {
12074 		init_explored_state(env, t);
12075 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12076 				/* It's ok to allow recursion from CFG point of
12077 				 * view. __check_func_call() will do the actual
12078 				 * check.
12079 				 */
12080 				bpf_pseudo_func(insns + t));
12081 	}
12082 	return ret;
12083 }
12084 
12085 /* Visits the instruction at index t and returns one of the following:
12086  *  < 0 - an error occurred
12087  *  DONE_EXPLORING - the instruction was fully explored
12088  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12089  */
12090 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
12091 {
12092 	struct bpf_insn *insns = env->prog->insnsi;
12093 	int ret;
12094 
12095 	if (bpf_pseudo_func(insns + t))
12096 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
12097 
12098 	/* All non-branch instructions have a single fall-through edge. */
12099 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12100 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
12101 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
12102 
12103 	switch (BPF_OP(insns[t].code)) {
12104 	case BPF_EXIT:
12105 		return DONE_EXPLORING;
12106 
12107 	case BPF_CALL:
12108 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
12109 			/* Mark this call insn to trigger is_state_visited() check
12110 			 * before call itself is processed by __check_func_call().
12111 			 * Otherwise new async state will be pushed for further
12112 			 * exploration.
12113 			 */
12114 			init_explored_state(env, t);
12115 		return visit_func_call_insn(t, insn_cnt, insns, env,
12116 					    insns[t].src_reg == BPF_PSEUDO_CALL);
12117 
12118 	case BPF_JA:
12119 		if (BPF_SRC(insns[t].code) != BPF_K)
12120 			return -EINVAL;
12121 
12122 		/* unconditional jump with single edge */
12123 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12124 				true);
12125 		if (ret)
12126 			return ret;
12127 
12128 		/* unconditional jmp is not a good pruning point,
12129 		 * but it's marked, since backtracking needs
12130 		 * to record jmp history in is_state_visited().
12131 		 */
12132 		init_explored_state(env, t + insns[t].off + 1);
12133 		/* tell verifier to check for equivalent states
12134 		 * after every call and jump
12135 		 */
12136 		if (t + 1 < insn_cnt)
12137 			init_explored_state(env, t + 1);
12138 
12139 		return ret;
12140 
12141 	default:
12142 		/* conditional jump with two edges */
12143 		init_explored_state(env, t);
12144 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12145 		if (ret)
12146 			return ret;
12147 
12148 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12149 	}
12150 }
12151 
12152 /* non-recursive depth-first-search to detect loops in BPF program
12153  * loop == back-edge in directed graph
12154  */
12155 static int check_cfg(struct bpf_verifier_env *env)
12156 {
12157 	int insn_cnt = env->prog->len;
12158 	int *insn_stack, *insn_state;
12159 	int ret = 0;
12160 	int i;
12161 
12162 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12163 	if (!insn_state)
12164 		return -ENOMEM;
12165 
12166 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12167 	if (!insn_stack) {
12168 		kvfree(insn_state);
12169 		return -ENOMEM;
12170 	}
12171 
12172 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12173 	insn_stack[0] = 0; /* 0 is the first instruction */
12174 	env->cfg.cur_stack = 1;
12175 
12176 	while (env->cfg.cur_stack > 0) {
12177 		int t = insn_stack[env->cfg.cur_stack - 1];
12178 
12179 		ret = visit_insn(t, insn_cnt, env);
12180 		switch (ret) {
12181 		case DONE_EXPLORING:
12182 			insn_state[t] = EXPLORED;
12183 			env->cfg.cur_stack--;
12184 			break;
12185 		case KEEP_EXPLORING:
12186 			break;
12187 		default:
12188 			if (ret > 0) {
12189 				verbose(env, "visit_insn internal bug\n");
12190 				ret = -EFAULT;
12191 			}
12192 			goto err_free;
12193 		}
12194 	}
12195 
12196 	if (env->cfg.cur_stack < 0) {
12197 		verbose(env, "pop stack internal bug\n");
12198 		ret = -EFAULT;
12199 		goto err_free;
12200 	}
12201 
12202 	for (i = 0; i < insn_cnt; i++) {
12203 		if (insn_state[i] != EXPLORED) {
12204 			verbose(env, "unreachable insn %d\n", i);
12205 			ret = -EINVAL;
12206 			goto err_free;
12207 		}
12208 	}
12209 	ret = 0; /* cfg looks good */
12210 
12211 err_free:
12212 	kvfree(insn_state);
12213 	kvfree(insn_stack);
12214 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
12215 	return ret;
12216 }
12217 
12218 static int check_abnormal_return(struct bpf_verifier_env *env)
12219 {
12220 	int i;
12221 
12222 	for (i = 1; i < env->subprog_cnt; i++) {
12223 		if (env->subprog_info[i].has_ld_abs) {
12224 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12225 			return -EINVAL;
12226 		}
12227 		if (env->subprog_info[i].has_tail_call) {
12228 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12229 			return -EINVAL;
12230 		}
12231 	}
12232 	return 0;
12233 }
12234 
12235 /* The minimum supported BTF func info size */
12236 #define MIN_BPF_FUNCINFO_SIZE	8
12237 #define MAX_FUNCINFO_REC_SIZE	252
12238 
12239 static int check_btf_func(struct bpf_verifier_env *env,
12240 			  const union bpf_attr *attr,
12241 			  bpfptr_t uattr)
12242 {
12243 	const struct btf_type *type, *func_proto, *ret_type;
12244 	u32 i, nfuncs, urec_size, min_size;
12245 	u32 krec_size = sizeof(struct bpf_func_info);
12246 	struct bpf_func_info *krecord;
12247 	struct bpf_func_info_aux *info_aux = NULL;
12248 	struct bpf_prog *prog;
12249 	const struct btf *btf;
12250 	bpfptr_t urecord;
12251 	u32 prev_offset = 0;
12252 	bool scalar_return;
12253 	int ret = -ENOMEM;
12254 
12255 	nfuncs = attr->func_info_cnt;
12256 	if (!nfuncs) {
12257 		if (check_abnormal_return(env))
12258 			return -EINVAL;
12259 		return 0;
12260 	}
12261 
12262 	if (nfuncs != env->subprog_cnt) {
12263 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12264 		return -EINVAL;
12265 	}
12266 
12267 	urec_size = attr->func_info_rec_size;
12268 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12269 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
12270 	    urec_size % sizeof(u32)) {
12271 		verbose(env, "invalid func info rec size %u\n", urec_size);
12272 		return -EINVAL;
12273 	}
12274 
12275 	prog = env->prog;
12276 	btf = prog->aux->btf;
12277 
12278 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12279 	min_size = min_t(u32, krec_size, urec_size);
12280 
12281 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12282 	if (!krecord)
12283 		return -ENOMEM;
12284 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12285 	if (!info_aux)
12286 		goto err_free;
12287 
12288 	for (i = 0; i < nfuncs; i++) {
12289 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12290 		if (ret) {
12291 			if (ret == -E2BIG) {
12292 				verbose(env, "nonzero tailing record in func info");
12293 				/* set the size kernel expects so loader can zero
12294 				 * out the rest of the record.
12295 				 */
12296 				if (copy_to_bpfptr_offset(uattr,
12297 							  offsetof(union bpf_attr, func_info_rec_size),
12298 							  &min_size, sizeof(min_size)))
12299 					ret = -EFAULT;
12300 			}
12301 			goto err_free;
12302 		}
12303 
12304 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12305 			ret = -EFAULT;
12306 			goto err_free;
12307 		}
12308 
12309 		/* check insn_off */
12310 		ret = -EINVAL;
12311 		if (i == 0) {
12312 			if (krecord[i].insn_off) {
12313 				verbose(env,
12314 					"nonzero insn_off %u for the first func info record",
12315 					krecord[i].insn_off);
12316 				goto err_free;
12317 			}
12318 		} else if (krecord[i].insn_off <= prev_offset) {
12319 			verbose(env,
12320 				"same or smaller insn offset (%u) than previous func info record (%u)",
12321 				krecord[i].insn_off, prev_offset);
12322 			goto err_free;
12323 		}
12324 
12325 		if (env->subprog_info[i].start != krecord[i].insn_off) {
12326 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12327 			goto err_free;
12328 		}
12329 
12330 		/* check type_id */
12331 		type = btf_type_by_id(btf, krecord[i].type_id);
12332 		if (!type || !btf_type_is_func(type)) {
12333 			verbose(env, "invalid type id %d in func info",
12334 				krecord[i].type_id);
12335 			goto err_free;
12336 		}
12337 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12338 
12339 		func_proto = btf_type_by_id(btf, type->type);
12340 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12341 			/* btf_func_check() already verified it during BTF load */
12342 			goto err_free;
12343 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12344 		scalar_return =
12345 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12346 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12347 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12348 			goto err_free;
12349 		}
12350 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12351 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12352 			goto err_free;
12353 		}
12354 
12355 		prev_offset = krecord[i].insn_off;
12356 		bpfptr_add(&urecord, urec_size);
12357 	}
12358 
12359 	prog->aux->func_info = krecord;
12360 	prog->aux->func_info_cnt = nfuncs;
12361 	prog->aux->func_info_aux = info_aux;
12362 	return 0;
12363 
12364 err_free:
12365 	kvfree(krecord);
12366 	kfree(info_aux);
12367 	return ret;
12368 }
12369 
12370 static void adjust_btf_func(struct bpf_verifier_env *env)
12371 {
12372 	struct bpf_prog_aux *aux = env->prog->aux;
12373 	int i;
12374 
12375 	if (!aux->func_info)
12376 		return;
12377 
12378 	for (i = 0; i < env->subprog_cnt; i++)
12379 		aux->func_info[i].insn_off = env->subprog_info[i].start;
12380 }
12381 
12382 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
12383 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
12384 
12385 static int check_btf_line(struct bpf_verifier_env *env,
12386 			  const union bpf_attr *attr,
12387 			  bpfptr_t uattr)
12388 {
12389 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12390 	struct bpf_subprog_info *sub;
12391 	struct bpf_line_info *linfo;
12392 	struct bpf_prog *prog;
12393 	const struct btf *btf;
12394 	bpfptr_t ulinfo;
12395 	int err;
12396 
12397 	nr_linfo = attr->line_info_cnt;
12398 	if (!nr_linfo)
12399 		return 0;
12400 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12401 		return -EINVAL;
12402 
12403 	rec_size = attr->line_info_rec_size;
12404 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12405 	    rec_size > MAX_LINEINFO_REC_SIZE ||
12406 	    rec_size & (sizeof(u32) - 1))
12407 		return -EINVAL;
12408 
12409 	/* Need to zero it in case the userspace may
12410 	 * pass in a smaller bpf_line_info object.
12411 	 */
12412 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12413 			 GFP_KERNEL | __GFP_NOWARN);
12414 	if (!linfo)
12415 		return -ENOMEM;
12416 
12417 	prog = env->prog;
12418 	btf = prog->aux->btf;
12419 
12420 	s = 0;
12421 	sub = env->subprog_info;
12422 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12423 	expected_size = sizeof(struct bpf_line_info);
12424 	ncopy = min_t(u32, expected_size, rec_size);
12425 	for (i = 0; i < nr_linfo; i++) {
12426 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12427 		if (err) {
12428 			if (err == -E2BIG) {
12429 				verbose(env, "nonzero tailing record in line_info");
12430 				if (copy_to_bpfptr_offset(uattr,
12431 							  offsetof(union bpf_attr, line_info_rec_size),
12432 							  &expected_size, sizeof(expected_size)))
12433 					err = -EFAULT;
12434 			}
12435 			goto err_free;
12436 		}
12437 
12438 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12439 			err = -EFAULT;
12440 			goto err_free;
12441 		}
12442 
12443 		/*
12444 		 * Check insn_off to ensure
12445 		 * 1) strictly increasing AND
12446 		 * 2) bounded by prog->len
12447 		 *
12448 		 * The linfo[0].insn_off == 0 check logically falls into
12449 		 * the later "missing bpf_line_info for func..." case
12450 		 * because the first linfo[0].insn_off must be the
12451 		 * first sub also and the first sub must have
12452 		 * subprog_info[0].start == 0.
12453 		 */
12454 		if ((i && linfo[i].insn_off <= prev_offset) ||
12455 		    linfo[i].insn_off >= prog->len) {
12456 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12457 				i, linfo[i].insn_off, prev_offset,
12458 				prog->len);
12459 			err = -EINVAL;
12460 			goto err_free;
12461 		}
12462 
12463 		if (!prog->insnsi[linfo[i].insn_off].code) {
12464 			verbose(env,
12465 				"Invalid insn code at line_info[%u].insn_off\n",
12466 				i);
12467 			err = -EINVAL;
12468 			goto err_free;
12469 		}
12470 
12471 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12472 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12473 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12474 			err = -EINVAL;
12475 			goto err_free;
12476 		}
12477 
12478 		if (s != env->subprog_cnt) {
12479 			if (linfo[i].insn_off == sub[s].start) {
12480 				sub[s].linfo_idx = i;
12481 				s++;
12482 			} else if (sub[s].start < linfo[i].insn_off) {
12483 				verbose(env, "missing bpf_line_info for func#%u\n", s);
12484 				err = -EINVAL;
12485 				goto err_free;
12486 			}
12487 		}
12488 
12489 		prev_offset = linfo[i].insn_off;
12490 		bpfptr_add(&ulinfo, rec_size);
12491 	}
12492 
12493 	if (s != env->subprog_cnt) {
12494 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12495 			env->subprog_cnt - s, s);
12496 		err = -EINVAL;
12497 		goto err_free;
12498 	}
12499 
12500 	prog->aux->linfo = linfo;
12501 	prog->aux->nr_linfo = nr_linfo;
12502 
12503 	return 0;
12504 
12505 err_free:
12506 	kvfree(linfo);
12507 	return err;
12508 }
12509 
12510 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
12511 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
12512 
12513 static int check_core_relo(struct bpf_verifier_env *env,
12514 			   const union bpf_attr *attr,
12515 			   bpfptr_t uattr)
12516 {
12517 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12518 	struct bpf_core_relo core_relo = {};
12519 	struct bpf_prog *prog = env->prog;
12520 	const struct btf *btf = prog->aux->btf;
12521 	struct bpf_core_ctx ctx = {
12522 		.log = &env->log,
12523 		.btf = btf,
12524 	};
12525 	bpfptr_t u_core_relo;
12526 	int err;
12527 
12528 	nr_core_relo = attr->core_relo_cnt;
12529 	if (!nr_core_relo)
12530 		return 0;
12531 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12532 		return -EINVAL;
12533 
12534 	rec_size = attr->core_relo_rec_size;
12535 	if (rec_size < MIN_CORE_RELO_SIZE ||
12536 	    rec_size > MAX_CORE_RELO_SIZE ||
12537 	    rec_size % sizeof(u32))
12538 		return -EINVAL;
12539 
12540 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12541 	expected_size = sizeof(struct bpf_core_relo);
12542 	ncopy = min_t(u32, expected_size, rec_size);
12543 
12544 	/* Unlike func_info and line_info, copy and apply each CO-RE
12545 	 * relocation record one at a time.
12546 	 */
12547 	for (i = 0; i < nr_core_relo; i++) {
12548 		/* future proofing when sizeof(bpf_core_relo) changes */
12549 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12550 		if (err) {
12551 			if (err == -E2BIG) {
12552 				verbose(env, "nonzero tailing record in core_relo");
12553 				if (copy_to_bpfptr_offset(uattr,
12554 							  offsetof(union bpf_attr, core_relo_rec_size),
12555 							  &expected_size, sizeof(expected_size)))
12556 					err = -EFAULT;
12557 			}
12558 			break;
12559 		}
12560 
12561 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12562 			err = -EFAULT;
12563 			break;
12564 		}
12565 
12566 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12567 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12568 				i, core_relo.insn_off, prog->len);
12569 			err = -EINVAL;
12570 			break;
12571 		}
12572 
12573 		err = bpf_core_apply(&ctx, &core_relo, i,
12574 				     &prog->insnsi[core_relo.insn_off / 8]);
12575 		if (err)
12576 			break;
12577 		bpfptr_add(&u_core_relo, rec_size);
12578 	}
12579 	return err;
12580 }
12581 
12582 static int check_btf_info(struct bpf_verifier_env *env,
12583 			  const union bpf_attr *attr,
12584 			  bpfptr_t uattr)
12585 {
12586 	struct btf *btf;
12587 	int err;
12588 
12589 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
12590 		if (check_abnormal_return(env))
12591 			return -EINVAL;
12592 		return 0;
12593 	}
12594 
12595 	btf = btf_get_by_fd(attr->prog_btf_fd);
12596 	if (IS_ERR(btf))
12597 		return PTR_ERR(btf);
12598 	if (btf_is_kernel(btf)) {
12599 		btf_put(btf);
12600 		return -EACCES;
12601 	}
12602 	env->prog->aux->btf = btf;
12603 
12604 	err = check_btf_func(env, attr, uattr);
12605 	if (err)
12606 		return err;
12607 
12608 	err = check_btf_line(env, attr, uattr);
12609 	if (err)
12610 		return err;
12611 
12612 	err = check_core_relo(env, attr, uattr);
12613 	if (err)
12614 		return err;
12615 
12616 	return 0;
12617 }
12618 
12619 /* check %cur's range satisfies %old's */
12620 static bool range_within(struct bpf_reg_state *old,
12621 			 struct bpf_reg_state *cur)
12622 {
12623 	return old->umin_value <= cur->umin_value &&
12624 	       old->umax_value >= cur->umax_value &&
12625 	       old->smin_value <= cur->smin_value &&
12626 	       old->smax_value >= cur->smax_value &&
12627 	       old->u32_min_value <= cur->u32_min_value &&
12628 	       old->u32_max_value >= cur->u32_max_value &&
12629 	       old->s32_min_value <= cur->s32_min_value &&
12630 	       old->s32_max_value >= cur->s32_max_value;
12631 }
12632 
12633 /* If in the old state two registers had the same id, then they need to have
12634  * the same id in the new state as well.  But that id could be different from
12635  * the old state, so we need to track the mapping from old to new ids.
12636  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12637  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
12638  * regs with a different old id could still have new id 9, we don't care about
12639  * that.
12640  * So we look through our idmap to see if this old id has been seen before.  If
12641  * so, we require the new id to match; otherwise, we add the id pair to the map.
12642  */
12643 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12644 {
12645 	unsigned int i;
12646 
12647 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12648 		if (!idmap[i].old) {
12649 			/* Reached an empty slot; haven't seen this id before */
12650 			idmap[i].old = old_id;
12651 			idmap[i].cur = cur_id;
12652 			return true;
12653 		}
12654 		if (idmap[i].old == old_id)
12655 			return idmap[i].cur == cur_id;
12656 	}
12657 	/* We ran out of idmap slots, which should be impossible */
12658 	WARN_ON_ONCE(1);
12659 	return false;
12660 }
12661 
12662 static void clean_func_state(struct bpf_verifier_env *env,
12663 			     struct bpf_func_state *st)
12664 {
12665 	enum bpf_reg_liveness live;
12666 	int i, j;
12667 
12668 	for (i = 0; i < BPF_REG_FP; i++) {
12669 		live = st->regs[i].live;
12670 		/* liveness must not touch this register anymore */
12671 		st->regs[i].live |= REG_LIVE_DONE;
12672 		if (!(live & REG_LIVE_READ))
12673 			/* since the register is unused, clear its state
12674 			 * to make further comparison simpler
12675 			 */
12676 			__mark_reg_not_init(env, &st->regs[i]);
12677 	}
12678 
12679 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12680 		live = st->stack[i].spilled_ptr.live;
12681 		/* liveness must not touch this stack slot anymore */
12682 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12683 		if (!(live & REG_LIVE_READ)) {
12684 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
12685 			for (j = 0; j < BPF_REG_SIZE; j++)
12686 				st->stack[i].slot_type[j] = STACK_INVALID;
12687 		}
12688 	}
12689 }
12690 
12691 static void clean_verifier_state(struct bpf_verifier_env *env,
12692 				 struct bpf_verifier_state *st)
12693 {
12694 	int i;
12695 
12696 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12697 		/* all regs in this state in all frames were already marked */
12698 		return;
12699 
12700 	for (i = 0; i <= st->curframe; i++)
12701 		clean_func_state(env, st->frame[i]);
12702 }
12703 
12704 /* the parentage chains form a tree.
12705  * the verifier states are added to state lists at given insn and
12706  * pushed into state stack for future exploration.
12707  * when the verifier reaches bpf_exit insn some of the verifer states
12708  * stored in the state lists have their final liveness state already,
12709  * but a lot of states will get revised from liveness point of view when
12710  * the verifier explores other branches.
12711  * Example:
12712  * 1: r0 = 1
12713  * 2: if r1 == 100 goto pc+1
12714  * 3: r0 = 2
12715  * 4: exit
12716  * when the verifier reaches exit insn the register r0 in the state list of
12717  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
12718  * of insn 2 and goes exploring further. At the insn 4 it will walk the
12719  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
12720  *
12721  * Since the verifier pushes the branch states as it sees them while exploring
12722  * the program the condition of walking the branch instruction for the second
12723  * time means that all states below this branch were already explored and
12724  * their final liveness marks are already propagated.
12725  * Hence when the verifier completes the search of state list in is_state_visited()
12726  * we can call this clean_live_states() function to mark all liveness states
12727  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
12728  * will not be used.
12729  * This function also clears the registers and stack for states that !READ
12730  * to simplify state merging.
12731  *
12732  * Important note here that walking the same branch instruction in the callee
12733  * doesn't meant that the states are DONE. The verifier has to compare
12734  * the callsites
12735  */
12736 static void clean_live_states(struct bpf_verifier_env *env, int insn,
12737 			      struct bpf_verifier_state *cur)
12738 {
12739 	struct bpf_verifier_state_list *sl;
12740 	int i;
12741 
12742 	sl = *explored_state(env, insn);
12743 	while (sl) {
12744 		if (sl->state.branches)
12745 			goto next;
12746 		if (sl->state.insn_idx != insn ||
12747 		    sl->state.curframe != cur->curframe)
12748 			goto next;
12749 		for (i = 0; i <= cur->curframe; i++)
12750 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
12751 				goto next;
12752 		clean_verifier_state(env, &sl->state);
12753 next:
12754 		sl = sl->next;
12755 	}
12756 }
12757 
12758 /* Returns true if (rold safe implies rcur safe) */
12759 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
12760 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
12761 {
12762 	bool equal;
12763 
12764 	if (!(rold->live & REG_LIVE_READ))
12765 		/* explored state didn't use this */
12766 		return true;
12767 
12768 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
12769 
12770 	if (rold->type == PTR_TO_STACK)
12771 		/* two stack pointers are equal only if they're pointing to
12772 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
12773 		 */
12774 		return equal && rold->frameno == rcur->frameno;
12775 
12776 	if (equal)
12777 		return true;
12778 
12779 	if (rold->type == NOT_INIT)
12780 		/* explored state can't have used this */
12781 		return true;
12782 	if (rcur->type == NOT_INIT)
12783 		return false;
12784 	switch (base_type(rold->type)) {
12785 	case SCALAR_VALUE:
12786 		if (env->explore_alu_limits)
12787 			return false;
12788 		if (rcur->type == SCALAR_VALUE) {
12789 			if (!rold->precise)
12790 				return true;
12791 			/* new val must satisfy old val knowledge */
12792 			return range_within(rold, rcur) &&
12793 			       tnum_in(rold->var_off, rcur->var_off);
12794 		} else {
12795 			/* We're trying to use a pointer in place of a scalar.
12796 			 * Even if the scalar was unbounded, this could lead to
12797 			 * pointer leaks because scalars are allowed to leak
12798 			 * while pointers are not. We could make this safe in
12799 			 * special cases if root is calling us, but it's
12800 			 * probably not worth the hassle.
12801 			 */
12802 			return false;
12803 		}
12804 	case PTR_TO_MAP_KEY:
12805 	case PTR_TO_MAP_VALUE:
12806 		/* a PTR_TO_MAP_VALUE could be safe to use as a
12807 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
12808 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
12809 		 * checked, doing so could have affected others with the same
12810 		 * id, and we can't check for that because we lost the id when
12811 		 * we converted to a PTR_TO_MAP_VALUE.
12812 		 */
12813 		if (type_may_be_null(rold->type)) {
12814 			if (!type_may_be_null(rcur->type))
12815 				return false;
12816 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
12817 				return false;
12818 			/* Check our ids match any regs they're supposed to */
12819 			return check_ids(rold->id, rcur->id, idmap);
12820 		}
12821 
12822 		/* If the new min/max/var_off satisfy the old ones and
12823 		 * everything else matches, we are OK.
12824 		 * 'id' is not compared, since it's only used for maps with
12825 		 * bpf_spin_lock inside map element and in such cases if
12826 		 * the rest of the prog is valid for one map element then
12827 		 * it's valid for all map elements regardless of the key
12828 		 * used in bpf_map_lookup()
12829 		 */
12830 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
12831 		       range_within(rold, rcur) &&
12832 		       tnum_in(rold->var_off, rcur->var_off);
12833 	case PTR_TO_PACKET_META:
12834 	case PTR_TO_PACKET:
12835 		if (rcur->type != rold->type)
12836 			return false;
12837 		/* We must have at least as much range as the old ptr
12838 		 * did, so that any accesses which were safe before are
12839 		 * still safe.  This is true even if old range < old off,
12840 		 * since someone could have accessed through (ptr - k), or
12841 		 * even done ptr -= k in a register, to get a safe access.
12842 		 */
12843 		if (rold->range > rcur->range)
12844 			return false;
12845 		/* If the offsets don't match, we can't trust our alignment;
12846 		 * nor can we be sure that we won't fall out of range.
12847 		 */
12848 		if (rold->off != rcur->off)
12849 			return false;
12850 		/* id relations must be preserved */
12851 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
12852 			return false;
12853 		/* new val must satisfy old val knowledge */
12854 		return range_within(rold, rcur) &&
12855 		       tnum_in(rold->var_off, rcur->var_off);
12856 	case PTR_TO_CTX:
12857 	case CONST_PTR_TO_MAP:
12858 	case PTR_TO_PACKET_END:
12859 	case PTR_TO_FLOW_KEYS:
12860 	case PTR_TO_SOCKET:
12861 	case PTR_TO_SOCK_COMMON:
12862 	case PTR_TO_TCP_SOCK:
12863 	case PTR_TO_XDP_SOCK:
12864 		/* Only valid matches are exact, which memcmp() above
12865 		 * would have accepted
12866 		 */
12867 	default:
12868 		/* Don't know what's going on, just say it's not safe */
12869 		return false;
12870 	}
12871 
12872 	/* Shouldn't get here; if we do, say it's not safe */
12873 	WARN_ON_ONCE(1);
12874 	return false;
12875 }
12876 
12877 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
12878 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
12879 {
12880 	int i, spi;
12881 
12882 	/* walk slots of the explored stack and ignore any additional
12883 	 * slots in the current stack, since explored(safe) state
12884 	 * didn't use them
12885 	 */
12886 	for (i = 0; i < old->allocated_stack; i++) {
12887 		spi = i / BPF_REG_SIZE;
12888 
12889 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
12890 			i += BPF_REG_SIZE - 1;
12891 			/* explored state didn't use this */
12892 			continue;
12893 		}
12894 
12895 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
12896 			continue;
12897 
12898 		/* explored stack has more populated slots than current stack
12899 		 * and these slots were used
12900 		 */
12901 		if (i >= cur->allocated_stack)
12902 			return false;
12903 
12904 		/* if old state was safe with misc data in the stack
12905 		 * it will be safe with zero-initialized stack.
12906 		 * The opposite is not true
12907 		 */
12908 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
12909 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
12910 			continue;
12911 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
12912 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
12913 			/* Ex: old explored (safe) state has STACK_SPILL in
12914 			 * this stack slot, but current has STACK_MISC ->
12915 			 * this verifier states are not equivalent,
12916 			 * return false to continue verification of this path
12917 			 */
12918 			return false;
12919 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
12920 			continue;
12921 		if (!is_spilled_reg(&old->stack[spi]))
12922 			continue;
12923 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
12924 			     &cur->stack[spi].spilled_ptr, idmap))
12925 			/* when explored and current stack slot are both storing
12926 			 * spilled registers, check that stored pointers types
12927 			 * are the same as well.
12928 			 * Ex: explored safe path could have stored
12929 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
12930 			 * but current path has stored:
12931 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
12932 			 * such verifier states are not equivalent.
12933 			 * return false to continue verification of this path
12934 			 */
12935 			return false;
12936 	}
12937 	return true;
12938 }
12939 
12940 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
12941 {
12942 	if (old->acquired_refs != cur->acquired_refs)
12943 		return false;
12944 	return !memcmp(old->refs, cur->refs,
12945 		       sizeof(*old->refs) * old->acquired_refs);
12946 }
12947 
12948 /* compare two verifier states
12949  *
12950  * all states stored in state_list are known to be valid, since
12951  * verifier reached 'bpf_exit' instruction through them
12952  *
12953  * this function is called when verifier exploring different branches of
12954  * execution popped from the state stack. If it sees an old state that has
12955  * more strict register state and more strict stack state then this execution
12956  * branch doesn't need to be explored further, since verifier already
12957  * concluded that more strict state leads to valid finish.
12958  *
12959  * Therefore two states are equivalent if register state is more conservative
12960  * and explored stack state is more conservative than the current one.
12961  * Example:
12962  *       explored                   current
12963  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
12964  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
12965  *
12966  * In other words if current stack state (one being explored) has more
12967  * valid slots than old one that already passed validation, it means
12968  * the verifier can stop exploring and conclude that current state is valid too
12969  *
12970  * Similarly with registers. If explored state has register type as invalid
12971  * whereas register type in current state is meaningful, it means that
12972  * the current state will reach 'bpf_exit' instruction safely
12973  */
12974 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
12975 			      struct bpf_func_state *cur)
12976 {
12977 	int i;
12978 
12979 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
12980 	for (i = 0; i < MAX_BPF_REG; i++)
12981 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
12982 			     env->idmap_scratch))
12983 			return false;
12984 
12985 	if (!stacksafe(env, old, cur, env->idmap_scratch))
12986 		return false;
12987 
12988 	if (!refsafe(old, cur))
12989 		return false;
12990 
12991 	return true;
12992 }
12993 
12994 static bool states_equal(struct bpf_verifier_env *env,
12995 			 struct bpf_verifier_state *old,
12996 			 struct bpf_verifier_state *cur)
12997 {
12998 	int i;
12999 
13000 	if (old->curframe != cur->curframe)
13001 		return false;
13002 
13003 	/* Verification state from speculative execution simulation
13004 	 * must never prune a non-speculative execution one.
13005 	 */
13006 	if (old->speculative && !cur->speculative)
13007 		return false;
13008 
13009 	if (old->active_lock.ptr != cur->active_lock.ptr ||
13010 	    old->active_lock.id != cur->active_lock.id)
13011 		return false;
13012 
13013 	/* for states to be equal callsites have to be the same
13014 	 * and all frame states need to be equivalent
13015 	 */
13016 	for (i = 0; i <= old->curframe; i++) {
13017 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
13018 			return false;
13019 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13020 			return false;
13021 	}
13022 	return true;
13023 }
13024 
13025 /* Return 0 if no propagation happened. Return negative error code if error
13026  * happened. Otherwise, return the propagated bit.
13027  */
13028 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13029 				  struct bpf_reg_state *reg,
13030 				  struct bpf_reg_state *parent_reg)
13031 {
13032 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13033 	u8 flag = reg->live & REG_LIVE_READ;
13034 	int err;
13035 
13036 	/* When comes here, read flags of PARENT_REG or REG could be any of
13037 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13038 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13039 	 */
13040 	if (parent_flag == REG_LIVE_READ64 ||
13041 	    /* Or if there is no read flag from REG. */
13042 	    !flag ||
13043 	    /* Or if the read flag from REG is the same as PARENT_REG. */
13044 	    parent_flag == flag)
13045 		return 0;
13046 
13047 	err = mark_reg_read(env, reg, parent_reg, flag);
13048 	if (err)
13049 		return err;
13050 
13051 	return flag;
13052 }
13053 
13054 /* A write screens off any subsequent reads; but write marks come from the
13055  * straight-line code between a state and its parent.  When we arrive at an
13056  * equivalent state (jump target or such) we didn't arrive by the straight-line
13057  * code, so read marks in the state must propagate to the parent regardless
13058  * of the state's write marks. That's what 'parent == state->parent' comparison
13059  * in mark_reg_read() is for.
13060  */
13061 static int propagate_liveness(struct bpf_verifier_env *env,
13062 			      const struct bpf_verifier_state *vstate,
13063 			      struct bpf_verifier_state *vparent)
13064 {
13065 	struct bpf_reg_state *state_reg, *parent_reg;
13066 	struct bpf_func_state *state, *parent;
13067 	int i, frame, err = 0;
13068 
13069 	if (vparent->curframe != vstate->curframe) {
13070 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
13071 		     vparent->curframe, vstate->curframe);
13072 		return -EFAULT;
13073 	}
13074 	/* Propagate read liveness of registers... */
13075 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13076 	for (frame = 0; frame <= vstate->curframe; frame++) {
13077 		parent = vparent->frame[frame];
13078 		state = vstate->frame[frame];
13079 		parent_reg = parent->regs;
13080 		state_reg = state->regs;
13081 		/* We don't need to worry about FP liveness, it's read-only */
13082 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13083 			err = propagate_liveness_reg(env, &state_reg[i],
13084 						     &parent_reg[i]);
13085 			if (err < 0)
13086 				return err;
13087 			if (err == REG_LIVE_READ64)
13088 				mark_insn_zext(env, &parent_reg[i]);
13089 		}
13090 
13091 		/* Propagate stack slots. */
13092 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13093 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13094 			parent_reg = &parent->stack[i].spilled_ptr;
13095 			state_reg = &state->stack[i].spilled_ptr;
13096 			err = propagate_liveness_reg(env, state_reg,
13097 						     parent_reg);
13098 			if (err < 0)
13099 				return err;
13100 		}
13101 	}
13102 	return 0;
13103 }
13104 
13105 /* find precise scalars in the previous equivalent state and
13106  * propagate them into the current state
13107  */
13108 static int propagate_precision(struct bpf_verifier_env *env,
13109 			       const struct bpf_verifier_state *old)
13110 {
13111 	struct bpf_reg_state *state_reg;
13112 	struct bpf_func_state *state;
13113 	int i, err = 0, fr;
13114 
13115 	for (fr = old->curframe; fr >= 0; fr--) {
13116 		state = old->frame[fr];
13117 		state_reg = state->regs;
13118 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13119 			if (state_reg->type != SCALAR_VALUE ||
13120 			    !state_reg->precise)
13121 				continue;
13122 			if (env->log.level & BPF_LOG_LEVEL2)
13123 				verbose(env, "frame %d: propagating r%d\n", i, fr);
13124 			err = mark_chain_precision_frame(env, fr, i);
13125 			if (err < 0)
13126 				return err;
13127 		}
13128 
13129 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13130 			if (!is_spilled_reg(&state->stack[i]))
13131 				continue;
13132 			state_reg = &state->stack[i].spilled_ptr;
13133 			if (state_reg->type != SCALAR_VALUE ||
13134 			    !state_reg->precise)
13135 				continue;
13136 			if (env->log.level & BPF_LOG_LEVEL2)
13137 				verbose(env, "frame %d: propagating fp%d\n",
13138 					(-i - 1) * BPF_REG_SIZE, fr);
13139 			err = mark_chain_precision_stack_frame(env, fr, i);
13140 			if (err < 0)
13141 				return err;
13142 		}
13143 	}
13144 	return 0;
13145 }
13146 
13147 static bool states_maybe_looping(struct bpf_verifier_state *old,
13148 				 struct bpf_verifier_state *cur)
13149 {
13150 	struct bpf_func_state *fold, *fcur;
13151 	int i, fr = cur->curframe;
13152 
13153 	if (old->curframe != fr)
13154 		return false;
13155 
13156 	fold = old->frame[fr];
13157 	fcur = cur->frame[fr];
13158 	for (i = 0; i < MAX_BPF_REG; i++)
13159 		if (memcmp(&fold->regs[i], &fcur->regs[i],
13160 			   offsetof(struct bpf_reg_state, parent)))
13161 			return false;
13162 	return true;
13163 }
13164 
13165 
13166 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13167 {
13168 	struct bpf_verifier_state_list *new_sl;
13169 	struct bpf_verifier_state_list *sl, **pprev;
13170 	struct bpf_verifier_state *cur = env->cur_state, *new;
13171 	int i, j, err, states_cnt = 0;
13172 	bool add_new_state = env->test_state_freq ? true : false;
13173 
13174 	cur->last_insn_idx = env->prev_insn_idx;
13175 	if (!env->insn_aux_data[insn_idx].prune_point)
13176 		/* this 'insn_idx' instruction wasn't marked, so we will not
13177 		 * be doing state search here
13178 		 */
13179 		return 0;
13180 
13181 	/* bpf progs typically have pruning point every 4 instructions
13182 	 * http://vger.kernel.org/bpfconf2019.html#session-1
13183 	 * Do not add new state for future pruning if the verifier hasn't seen
13184 	 * at least 2 jumps and at least 8 instructions.
13185 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13186 	 * In tests that amounts to up to 50% reduction into total verifier
13187 	 * memory consumption and 20% verifier time speedup.
13188 	 */
13189 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13190 	    env->insn_processed - env->prev_insn_processed >= 8)
13191 		add_new_state = true;
13192 
13193 	pprev = explored_state(env, insn_idx);
13194 	sl = *pprev;
13195 
13196 	clean_live_states(env, insn_idx, cur);
13197 
13198 	while (sl) {
13199 		states_cnt++;
13200 		if (sl->state.insn_idx != insn_idx)
13201 			goto next;
13202 
13203 		if (sl->state.branches) {
13204 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13205 
13206 			if (frame->in_async_callback_fn &&
13207 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13208 				/* Different async_entry_cnt means that the verifier is
13209 				 * processing another entry into async callback.
13210 				 * Seeing the same state is not an indication of infinite
13211 				 * loop or infinite recursion.
13212 				 * But finding the same state doesn't mean that it's safe
13213 				 * to stop processing the current state. The previous state
13214 				 * hasn't yet reached bpf_exit, since state.branches > 0.
13215 				 * Checking in_async_callback_fn alone is not enough either.
13216 				 * Since the verifier still needs to catch infinite loops
13217 				 * inside async callbacks.
13218 				 */
13219 			} else if (states_maybe_looping(&sl->state, cur) &&
13220 				   states_equal(env, &sl->state, cur)) {
13221 				verbose_linfo(env, insn_idx, "; ");
13222 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13223 				return -EINVAL;
13224 			}
13225 			/* if the verifier is processing a loop, avoid adding new state
13226 			 * too often, since different loop iterations have distinct
13227 			 * states and may not help future pruning.
13228 			 * This threshold shouldn't be too low to make sure that
13229 			 * a loop with large bound will be rejected quickly.
13230 			 * The most abusive loop will be:
13231 			 * r1 += 1
13232 			 * if r1 < 1000000 goto pc-2
13233 			 * 1M insn_procssed limit / 100 == 10k peak states.
13234 			 * This threshold shouldn't be too high either, since states
13235 			 * at the end of the loop are likely to be useful in pruning.
13236 			 */
13237 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13238 			    env->insn_processed - env->prev_insn_processed < 100)
13239 				add_new_state = false;
13240 			goto miss;
13241 		}
13242 		if (states_equal(env, &sl->state, cur)) {
13243 			sl->hit_cnt++;
13244 			/* reached equivalent register/stack state,
13245 			 * prune the search.
13246 			 * Registers read by the continuation are read by us.
13247 			 * If we have any write marks in env->cur_state, they
13248 			 * will prevent corresponding reads in the continuation
13249 			 * from reaching our parent (an explored_state).  Our
13250 			 * own state will get the read marks recorded, but
13251 			 * they'll be immediately forgotten as we're pruning
13252 			 * this state and will pop a new one.
13253 			 */
13254 			err = propagate_liveness(env, &sl->state, cur);
13255 
13256 			/* if previous state reached the exit with precision and
13257 			 * current state is equivalent to it (except precsion marks)
13258 			 * the precision needs to be propagated back in
13259 			 * the current state.
13260 			 */
13261 			err = err ? : push_jmp_history(env, cur);
13262 			err = err ? : propagate_precision(env, &sl->state);
13263 			if (err)
13264 				return err;
13265 			return 1;
13266 		}
13267 miss:
13268 		/* when new state is not going to be added do not increase miss count.
13269 		 * Otherwise several loop iterations will remove the state
13270 		 * recorded earlier. The goal of these heuristics is to have
13271 		 * states from some iterations of the loop (some in the beginning
13272 		 * and some at the end) to help pruning.
13273 		 */
13274 		if (add_new_state)
13275 			sl->miss_cnt++;
13276 		/* heuristic to determine whether this state is beneficial
13277 		 * to keep checking from state equivalence point of view.
13278 		 * Higher numbers increase max_states_per_insn and verification time,
13279 		 * but do not meaningfully decrease insn_processed.
13280 		 */
13281 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13282 			/* the state is unlikely to be useful. Remove it to
13283 			 * speed up verification
13284 			 */
13285 			*pprev = sl->next;
13286 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13287 				u32 br = sl->state.branches;
13288 
13289 				WARN_ONCE(br,
13290 					  "BUG live_done but branches_to_explore %d\n",
13291 					  br);
13292 				free_verifier_state(&sl->state, false);
13293 				kfree(sl);
13294 				env->peak_states--;
13295 			} else {
13296 				/* cannot free this state, since parentage chain may
13297 				 * walk it later. Add it for free_list instead to
13298 				 * be freed at the end of verification
13299 				 */
13300 				sl->next = env->free_list;
13301 				env->free_list = sl;
13302 			}
13303 			sl = *pprev;
13304 			continue;
13305 		}
13306 next:
13307 		pprev = &sl->next;
13308 		sl = *pprev;
13309 	}
13310 
13311 	if (env->max_states_per_insn < states_cnt)
13312 		env->max_states_per_insn = states_cnt;
13313 
13314 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13315 		return push_jmp_history(env, cur);
13316 
13317 	if (!add_new_state)
13318 		return push_jmp_history(env, cur);
13319 
13320 	/* There were no equivalent states, remember the current one.
13321 	 * Technically the current state is not proven to be safe yet,
13322 	 * but it will either reach outer most bpf_exit (which means it's safe)
13323 	 * or it will be rejected. When there are no loops the verifier won't be
13324 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13325 	 * again on the way to bpf_exit.
13326 	 * When looping the sl->state.branches will be > 0 and this state
13327 	 * will not be considered for equivalence until branches == 0.
13328 	 */
13329 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13330 	if (!new_sl)
13331 		return -ENOMEM;
13332 	env->total_states++;
13333 	env->peak_states++;
13334 	env->prev_jmps_processed = env->jmps_processed;
13335 	env->prev_insn_processed = env->insn_processed;
13336 
13337 	/* forget precise markings we inherited, see __mark_chain_precision */
13338 	if (env->bpf_capable)
13339 		mark_all_scalars_imprecise(env, cur);
13340 
13341 	/* add new state to the head of linked list */
13342 	new = &new_sl->state;
13343 	err = copy_verifier_state(new, cur);
13344 	if (err) {
13345 		free_verifier_state(new, false);
13346 		kfree(new_sl);
13347 		return err;
13348 	}
13349 	new->insn_idx = insn_idx;
13350 	WARN_ONCE(new->branches != 1,
13351 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13352 
13353 	cur->parent = new;
13354 	cur->first_insn_idx = insn_idx;
13355 	clear_jmp_history(cur);
13356 	new_sl->next = *explored_state(env, insn_idx);
13357 	*explored_state(env, insn_idx) = new_sl;
13358 	/* connect new state to parentage chain. Current frame needs all
13359 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
13360 	 * to the stack implicitly by JITs) so in callers' frames connect just
13361 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13362 	 * the state of the call instruction (with WRITTEN set), and r0 comes
13363 	 * from callee with its full parentage chain, anyway.
13364 	 */
13365 	/* clear write marks in current state: the writes we did are not writes
13366 	 * our child did, so they don't screen off its reads from us.
13367 	 * (There are no read marks in current state, because reads always mark
13368 	 * their parent and current state never has children yet.  Only
13369 	 * explored_states can get read marks.)
13370 	 */
13371 	for (j = 0; j <= cur->curframe; j++) {
13372 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13373 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13374 		for (i = 0; i < BPF_REG_FP; i++)
13375 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13376 	}
13377 
13378 	/* all stack frames are accessible from callee, clear them all */
13379 	for (j = 0; j <= cur->curframe; j++) {
13380 		struct bpf_func_state *frame = cur->frame[j];
13381 		struct bpf_func_state *newframe = new->frame[j];
13382 
13383 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13384 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13385 			frame->stack[i].spilled_ptr.parent =
13386 						&newframe->stack[i].spilled_ptr;
13387 		}
13388 	}
13389 	return 0;
13390 }
13391 
13392 /* Return true if it's OK to have the same insn return a different type. */
13393 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13394 {
13395 	switch (base_type(type)) {
13396 	case PTR_TO_CTX:
13397 	case PTR_TO_SOCKET:
13398 	case PTR_TO_SOCK_COMMON:
13399 	case PTR_TO_TCP_SOCK:
13400 	case PTR_TO_XDP_SOCK:
13401 	case PTR_TO_BTF_ID:
13402 		return false;
13403 	default:
13404 		return true;
13405 	}
13406 }
13407 
13408 /* If an instruction was previously used with particular pointer types, then we
13409  * need to be careful to avoid cases such as the below, where it may be ok
13410  * for one branch accessing the pointer, but not ok for the other branch:
13411  *
13412  * R1 = sock_ptr
13413  * goto X;
13414  * ...
13415  * R1 = some_other_valid_ptr;
13416  * goto X;
13417  * ...
13418  * R2 = *(u32 *)(R1 + 0);
13419  */
13420 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13421 {
13422 	return src != prev && (!reg_type_mismatch_ok(src) ||
13423 			       !reg_type_mismatch_ok(prev));
13424 }
13425 
13426 static int do_check(struct bpf_verifier_env *env)
13427 {
13428 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13429 	struct bpf_verifier_state *state = env->cur_state;
13430 	struct bpf_insn *insns = env->prog->insnsi;
13431 	struct bpf_reg_state *regs;
13432 	int insn_cnt = env->prog->len;
13433 	bool do_print_state = false;
13434 	int prev_insn_idx = -1;
13435 
13436 	for (;;) {
13437 		struct bpf_insn *insn;
13438 		u8 class;
13439 		int err;
13440 
13441 		env->prev_insn_idx = prev_insn_idx;
13442 		if (env->insn_idx >= insn_cnt) {
13443 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
13444 				env->insn_idx, insn_cnt);
13445 			return -EFAULT;
13446 		}
13447 
13448 		insn = &insns[env->insn_idx];
13449 		class = BPF_CLASS(insn->code);
13450 
13451 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13452 			verbose(env,
13453 				"BPF program is too large. Processed %d insn\n",
13454 				env->insn_processed);
13455 			return -E2BIG;
13456 		}
13457 
13458 		err = is_state_visited(env, env->insn_idx);
13459 		if (err < 0)
13460 			return err;
13461 		if (err == 1) {
13462 			/* found equivalent state, can prune the search */
13463 			if (env->log.level & BPF_LOG_LEVEL) {
13464 				if (do_print_state)
13465 					verbose(env, "\nfrom %d to %d%s: safe\n",
13466 						env->prev_insn_idx, env->insn_idx,
13467 						env->cur_state->speculative ?
13468 						" (speculative execution)" : "");
13469 				else
13470 					verbose(env, "%d: safe\n", env->insn_idx);
13471 			}
13472 			goto process_bpf_exit;
13473 		}
13474 
13475 		if (signal_pending(current))
13476 			return -EAGAIN;
13477 
13478 		if (need_resched())
13479 			cond_resched();
13480 
13481 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13482 			verbose(env, "\nfrom %d to %d%s:",
13483 				env->prev_insn_idx, env->insn_idx,
13484 				env->cur_state->speculative ?
13485 				" (speculative execution)" : "");
13486 			print_verifier_state(env, state->frame[state->curframe], true);
13487 			do_print_state = false;
13488 		}
13489 
13490 		if (env->log.level & BPF_LOG_LEVEL) {
13491 			const struct bpf_insn_cbs cbs = {
13492 				.cb_call	= disasm_kfunc_name,
13493 				.cb_print	= verbose,
13494 				.private_data	= env,
13495 			};
13496 
13497 			if (verifier_state_scratched(env))
13498 				print_insn_state(env, state->frame[state->curframe]);
13499 
13500 			verbose_linfo(env, env->insn_idx, "; ");
13501 			env->prev_log_len = env->log.len_used;
13502 			verbose(env, "%d: ", env->insn_idx);
13503 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13504 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13505 			env->prev_log_len = env->log.len_used;
13506 		}
13507 
13508 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
13509 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13510 							   env->prev_insn_idx);
13511 			if (err)
13512 				return err;
13513 		}
13514 
13515 		regs = cur_regs(env);
13516 		sanitize_mark_insn_seen(env);
13517 		prev_insn_idx = env->insn_idx;
13518 
13519 		if (class == BPF_ALU || class == BPF_ALU64) {
13520 			err = check_alu_op(env, insn);
13521 			if (err)
13522 				return err;
13523 
13524 		} else if (class == BPF_LDX) {
13525 			enum bpf_reg_type *prev_src_type, src_reg_type;
13526 
13527 			/* check for reserved fields is already done */
13528 
13529 			/* check src operand */
13530 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13531 			if (err)
13532 				return err;
13533 
13534 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13535 			if (err)
13536 				return err;
13537 
13538 			src_reg_type = regs[insn->src_reg].type;
13539 
13540 			/* check that memory (src_reg + off) is readable,
13541 			 * the state of dst_reg will be updated by this func
13542 			 */
13543 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
13544 					       insn->off, BPF_SIZE(insn->code),
13545 					       BPF_READ, insn->dst_reg, false);
13546 			if (err)
13547 				return err;
13548 
13549 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13550 
13551 			if (*prev_src_type == NOT_INIT) {
13552 				/* saw a valid insn
13553 				 * dst_reg = *(u32 *)(src_reg + off)
13554 				 * save type to validate intersecting paths
13555 				 */
13556 				*prev_src_type = src_reg_type;
13557 
13558 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13559 				/* ABuser program is trying to use the same insn
13560 				 * dst_reg = *(u32*) (src_reg + off)
13561 				 * with different pointer types:
13562 				 * src_reg == ctx in one branch and
13563 				 * src_reg == stack|map in some other branch.
13564 				 * Reject it.
13565 				 */
13566 				verbose(env, "same insn cannot be used with different pointers\n");
13567 				return -EINVAL;
13568 			}
13569 
13570 		} else if (class == BPF_STX) {
13571 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
13572 
13573 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13574 				err = check_atomic(env, env->insn_idx, insn);
13575 				if (err)
13576 					return err;
13577 				env->insn_idx++;
13578 				continue;
13579 			}
13580 
13581 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13582 				verbose(env, "BPF_STX uses reserved fields\n");
13583 				return -EINVAL;
13584 			}
13585 
13586 			/* check src1 operand */
13587 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13588 			if (err)
13589 				return err;
13590 			/* check src2 operand */
13591 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13592 			if (err)
13593 				return err;
13594 
13595 			dst_reg_type = regs[insn->dst_reg].type;
13596 
13597 			/* check that memory (dst_reg + off) is writeable */
13598 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13599 					       insn->off, BPF_SIZE(insn->code),
13600 					       BPF_WRITE, insn->src_reg, false);
13601 			if (err)
13602 				return err;
13603 
13604 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13605 
13606 			if (*prev_dst_type == NOT_INIT) {
13607 				*prev_dst_type = dst_reg_type;
13608 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13609 				verbose(env, "same insn cannot be used with different pointers\n");
13610 				return -EINVAL;
13611 			}
13612 
13613 		} else if (class == BPF_ST) {
13614 			if (BPF_MODE(insn->code) != BPF_MEM ||
13615 			    insn->src_reg != BPF_REG_0) {
13616 				verbose(env, "BPF_ST uses reserved fields\n");
13617 				return -EINVAL;
13618 			}
13619 			/* check src operand */
13620 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13621 			if (err)
13622 				return err;
13623 
13624 			if (is_ctx_reg(env, insn->dst_reg)) {
13625 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13626 					insn->dst_reg,
13627 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13628 				return -EACCES;
13629 			}
13630 
13631 			/* check that memory (dst_reg + off) is writeable */
13632 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13633 					       insn->off, BPF_SIZE(insn->code),
13634 					       BPF_WRITE, -1, false);
13635 			if (err)
13636 				return err;
13637 
13638 		} else if (class == BPF_JMP || class == BPF_JMP32) {
13639 			u8 opcode = BPF_OP(insn->code);
13640 
13641 			env->jmps_processed++;
13642 			if (opcode == BPF_CALL) {
13643 				if (BPF_SRC(insn->code) != BPF_K ||
13644 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13645 				     && insn->off != 0) ||
13646 				    (insn->src_reg != BPF_REG_0 &&
13647 				     insn->src_reg != BPF_PSEUDO_CALL &&
13648 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13649 				    insn->dst_reg != BPF_REG_0 ||
13650 				    class == BPF_JMP32) {
13651 					verbose(env, "BPF_CALL uses reserved fields\n");
13652 					return -EINVAL;
13653 				}
13654 
13655 				if (env->cur_state->active_lock.ptr) {
13656 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13657 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
13658 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13659 					     (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13660 						verbose(env, "function calls are not allowed while holding a lock\n");
13661 						return -EINVAL;
13662 					}
13663 				}
13664 				if (insn->src_reg == BPF_PSEUDO_CALL)
13665 					err = check_func_call(env, insn, &env->insn_idx);
13666 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13667 					err = check_kfunc_call(env, insn, &env->insn_idx);
13668 				else
13669 					err = check_helper_call(env, insn, &env->insn_idx);
13670 				if (err)
13671 					return err;
13672 			} else if (opcode == BPF_JA) {
13673 				if (BPF_SRC(insn->code) != BPF_K ||
13674 				    insn->imm != 0 ||
13675 				    insn->src_reg != BPF_REG_0 ||
13676 				    insn->dst_reg != BPF_REG_0 ||
13677 				    class == BPF_JMP32) {
13678 					verbose(env, "BPF_JA uses reserved fields\n");
13679 					return -EINVAL;
13680 				}
13681 
13682 				env->insn_idx += insn->off + 1;
13683 				continue;
13684 
13685 			} else if (opcode == BPF_EXIT) {
13686 				if (BPF_SRC(insn->code) != BPF_K ||
13687 				    insn->imm != 0 ||
13688 				    insn->src_reg != BPF_REG_0 ||
13689 				    insn->dst_reg != BPF_REG_0 ||
13690 				    class == BPF_JMP32) {
13691 					verbose(env, "BPF_EXIT uses reserved fields\n");
13692 					return -EINVAL;
13693 				}
13694 
13695 				if (env->cur_state->active_lock.ptr) {
13696 					verbose(env, "bpf_spin_unlock is missing\n");
13697 					return -EINVAL;
13698 				}
13699 
13700 				/* We must do check_reference_leak here before
13701 				 * prepare_func_exit to handle the case when
13702 				 * state->curframe > 0, it may be a callback
13703 				 * function, for which reference_state must
13704 				 * match caller reference state when it exits.
13705 				 */
13706 				err = check_reference_leak(env);
13707 				if (err)
13708 					return err;
13709 
13710 				if (state->curframe) {
13711 					/* exit from nested function */
13712 					err = prepare_func_exit(env, &env->insn_idx);
13713 					if (err)
13714 						return err;
13715 					do_print_state = true;
13716 					continue;
13717 				}
13718 
13719 				err = check_return_code(env);
13720 				if (err)
13721 					return err;
13722 process_bpf_exit:
13723 				mark_verifier_state_scratched(env);
13724 				update_branch_counts(env, env->cur_state);
13725 				err = pop_stack(env, &prev_insn_idx,
13726 						&env->insn_idx, pop_log);
13727 				if (err < 0) {
13728 					if (err != -ENOENT)
13729 						return err;
13730 					break;
13731 				} else {
13732 					do_print_state = true;
13733 					continue;
13734 				}
13735 			} else {
13736 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
13737 				if (err)
13738 					return err;
13739 			}
13740 		} else if (class == BPF_LD) {
13741 			u8 mode = BPF_MODE(insn->code);
13742 
13743 			if (mode == BPF_ABS || mode == BPF_IND) {
13744 				err = check_ld_abs(env, insn);
13745 				if (err)
13746 					return err;
13747 
13748 			} else if (mode == BPF_IMM) {
13749 				err = check_ld_imm(env, insn);
13750 				if (err)
13751 					return err;
13752 
13753 				env->insn_idx++;
13754 				sanitize_mark_insn_seen(env);
13755 			} else {
13756 				verbose(env, "invalid BPF_LD mode\n");
13757 				return -EINVAL;
13758 			}
13759 		} else {
13760 			verbose(env, "unknown insn class %d\n", class);
13761 			return -EINVAL;
13762 		}
13763 
13764 		env->insn_idx++;
13765 	}
13766 
13767 	return 0;
13768 }
13769 
13770 static int find_btf_percpu_datasec(struct btf *btf)
13771 {
13772 	const struct btf_type *t;
13773 	const char *tname;
13774 	int i, n;
13775 
13776 	/*
13777 	 * Both vmlinux and module each have their own ".data..percpu"
13778 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
13779 	 * types to look at only module's own BTF types.
13780 	 */
13781 	n = btf_nr_types(btf);
13782 	if (btf_is_module(btf))
13783 		i = btf_nr_types(btf_vmlinux);
13784 	else
13785 		i = 1;
13786 
13787 	for(; i < n; i++) {
13788 		t = btf_type_by_id(btf, i);
13789 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
13790 			continue;
13791 
13792 		tname = btf_name_by_offset(btf, t->name_off);
13793 		if (!strcmp(tname, ".data..percpu"))
13794 			return i;
13795 	}
13796 
13797 	return -ENOENT;
13798 }
13799 
13800 /* replace pseudo btf_id with kernel symbol address */
13801 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
13802 			       struct bpf_insn *insn,
13803 			       struct bpf_insn_aux_data *aux)
13804 {
13805 	const struct btf_var_secinfo *vsi;
13806 	const struct btf_type *datasec;
13807 	struct btf_mod_pair *btf_mod;
13808 	const struct btf_type *t;
13809 	const char *sym_name;
13810 	bool percpu = false;
13811 	u32 type, id = insn->imm;
13812 	struct btf *btf;
13813 	s32 datasec_id;
13814 	u64 addr;
13815 	int i, btf_fd, err;
13816 
13817 	btf_fd = insn[1].imm;
13818 	if (btf_fd) {
13819 		btf = btf_get_by_fd(btf_fd);
13820 		if (IS_ERR(btf)) {
13821 			verbose(env, "invalid module BTF object FD specified.\n");
13822 			return -EINVAL;
13823 		}
13824 	} else {
13825 		if (!btf_vmlinux) {
13826 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
13827 			return -EINVAL;
13828 		}
13829 		btf = btf_vmlinux;
13830 		btf_get(btf);
13831 	}
13832 
13833 	t = btf_type_by_id(btf, id);
13834 	if (!t) {
13835 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
13836 		err = -ENOENT;
13837 		goto err_put;
13838 	}
13839 
13840 	if (!btf_type_is_var(t)) {
13841 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
13842 		err = -EINVAL;
13843 		goto err_put;
13844 	}
13845 
13846 	sym_name = btf_name_by_offset(btf, t->name_off);
13847 	addr = kallsyms_lookup_name(sym_name);
13848 	if (!addr) {
13849 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
13850 			sym_name);
13851 		err = -ENOENT;
13852 		goto err_put;
13853 	}
13854 
13855 	datasec_id = find_btf_percpu_datasec(btf);
13856 	if (datasec_id > 0) {
13857 		datasec = btf_type_by_id(btf, datasec_id);
13858 		for_each_vsi(i, datasec, vsi) {
13859 			if (vsi->type == id) {
13860 				percpu = true;
13861 				break;
13862 			}
13863 		}
13864 	}
13865 
13866 	insn[0].imm = (u32)addr;
13867 	insn[1].imm = addr >> 32;
13868 
13869 	type = t->type;
13870 	t = btf_type_skip_modifiers(btf, type, NULL);
13871 	if (percpu) {
13872 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
13873 		aux->btf_var.btf = btf;
13874 		aux->btf_var.btf_id = type;
13875 	} else if (!btf_type_is_struct(t)) {
13876 		const struct btf_type *ret;
13877 		const char *tname;
13878 		u32 tsize;
13879 
13880 		/* resolve the type size of ksym. */
13881 		ret = btf_resolve_size(btf, t, &tsize);
13882 		if (IS_ERR(ret)) {
13883 			tname = btf_name_by_offset(btf, t->name_off);
13884 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
13885 				tname, PTR_ERR(ret));
13886 			err = -EINVAL;
13887 			goto err_put;
13888 		}
13889 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
13890 		aux->btf_var.mem_size = tsize;
13891 	} else {
13892 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
13893 		aux->btf_var.btf = btf;
13894 		aux->btf_var.btf_id = type;
13895 	}
13896 
13897 	/* check whether we recorded this BTF (and maybe module) already */
13898 	for (i = 0; i < env->used_btf_cnt; i++) {
13899 		if (env->used_btfs[i].btf == btf) {
13900 			btf_put(btf);
13901 			return 0;
13902 		}
13903 	}
13904 
13905 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
13906 		err = -E2BIG;
13907 		goto err_put;
13908 	}
13909 
13910 	btf_mod = &env->used_btfs[env->used_btf_cnt];
13911 	btf_mod->btf = btf;
13912 	btf_mod->module = NULL;
13913 
13914 	/* if we reference variables from kernel module, bump its refcount */
13915 	if (btf_is_module(btf)) {
13916 		btf_mod->module = btf_try_get_module(btf);
13917 		if (!btf_mod->module) {
13918 			err = -ENXIO;
13919 			goto err_put;
13920 		}
13921 	}
13922 
13923 	env->used_btf_cnt++;
13924 
13925 	return 0;
13926 err_put:
13927 	btf_put(btf);
13928 	return err;
13929 }
13930 
13931 static bool is_tracing_prog_type(enum bpf_prog_type type)
13932 {
13933 	switch (type) {
13934 	case BPF_PROG_TYPE_KPROBE:
13935 	case BPF_PROG_TYPE_TRACEPOINT:
13936 	case BPF_PROG_TYPE_PERF_EVENT:
13937 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
13938 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
13939 		return true;
13940 	default:
13941 		return false;
13942 	}
13943 }
13944 
13945 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
13946 					struct bpf_map *map,
13947 					struct bpf_prog *prog)
13948 
13949 {
13950 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13951 
13952 	if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
13953 		if (is_tracing_prog_type(prog_type)) {
13954 			verbose(env, "tracing progs cannot use bpf_list_head yet\n");
13955 			return -EINVAL;
13956 		}
13957 	}
13958 
13959 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
13960 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
13961 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
13962 			return -EINVAL;
13963 		}
13964 
13965 		if (is_tracing_prog_type(prog_type)) {
13966 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
13967 			return -EINVAL;
13968 		}
13969 
13970 		if (prog->aux->sleepable) {
13971 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
13972 			return -EINVAL;
13973 		}
13974 	}
13975 
13976 	if (btf_record_has_field(map->record, BPF_TIMER)) {
13977 		if (is_tracing_prog_type(prog_type)) {
13978 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
13979 			return -EINVAL;
13980 		}
13981 	}
13982 
13983 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
13984 	    !bpf_offload_prog_map_match(prog, map)) {
13985 		verbose(env, "offload device mismatch between prog and map\n");
13986 		return -EINVAL;
13987 	}
13988 
13989 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
13990 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
13991 		return -EINVAL;
13992 	}
13993 
13994 	if (prog->aux->sleepable)
13995 		switch (map->map_type) {
13996 		case BPF_MAP_TYPE_HASH:
13997 		case BPF_MAP_TYPE_LRU_HASH:
13998 		case BPF_MAP_TYPE_ARRAY:
13999 		case BPF_MAP_TYPE_PERCPU_HASH:
14000 		case BPF_MAP_TYPE_PERCPU_ARRAY:
14001 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14002 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14003 		case BPF_MAP_TYPE_HASH_OF_MAPS:
14004 		case BPF_MAP_TYPE_RINGBUF:
14005 		case BPF_MAP_TYPE_USER_RINGBUF:
14006 		case BPF_MAP_TYPE_INODE_STORAGE:
14007 		case BPF_MAP_TYPE_SK_STORAGE:
14008 		case BPF_MAP_TYPE_TASK_STORAGE:
14009 			break;
14010 		default:
14011 			verbose(env,
14012 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
14013 			return -EINVAL;
14014 		}
14015 
14016 	return 0;
14017 }
14018 
14019 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14020 {
14021 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14022 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14023 }
14024 
14025 /* find and rewrite pseudo imm in ld_imm64 instructions:
14026  *
14027  * 1. if it accesses map FD, replace it with actual map pointer.
14028  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14029  *
14030  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14031  */
14032 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14033 {
14034 	struct bpf_insn *insn = env->prog->insnsi;
14035 	int insn_cnt = env->prog->len;
14036 	int i, j, err;
14037 
14038 	err = bpf_prog_calc_tag(env->prog);
14039 	if (err)
14040 		return err;
14041 
14042 	for (i = 0; i < insn_cnt; i++, insn++) {
14043 		if (BPF_CLASS(insn->code) == BPF_LDX &&
14044 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14045 			verbose(env, "BPF_LDX uses reserved fields\n");
14046 			return -EINVAL;
14047 		}
14048 
14049 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14050 			struct bpf_insn_aux_data *aux;
14051 			struct bpf_map *map;
14052 			struct fd f;
14053 			u64 addr;
14054 			u32 fd;
14055 
14056 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
14057 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14058 			    insn[1].off != 0) {
14059 				verbose(env, "invalid bpf_ld_imm64 insn\n");
14060 				return -EINVAL;
14061 			}
14062 
14063 			if (insn[0].src_reg == 0)
14064 				/* valid generic load 64-bit imm */
14065 				goto next_insn;
14066 
14067 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14068 				aux = &env->insn_aux_data[i];
14069 				err = check_pseudo_btf_id(env, insn, aux);
14070 				if (err)
14071 					return err;
14072 				goto next_insn;
14073 			}
14074 
14075 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14076 				aux = &env->insn_aux_data[i];
14077 				aux->ptr_type = PTR_TO_FUNC;
14078 				goto next_insn;
14079 			}
14080 
14081 			/* In final convert_pseudo_ld_imm64() step, this is
14082 			 * converted into regular 64-bit imm load insn.
14083 			 */
14084 			switch (insn[0].src_reg) {
14085 			case BPF_PSEUDO_MAP_VALUE:
14086 			case BPF_PSEUDO_MAP_IDX_VALUE:
14087 				break;
14088 			case BPF_PSEUDO_MAP_FD:
14089 			case BPF_PSEUDO_MAP_IDX:
14090 				if (insn[1].imm == 0)
14091 					break;
14092 				fallthrough;
14093 			default:
14094 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14095 				return -EINVAL;
14096 			}
14097 
14098 			switch (insn[0].src_reg) {
14099 			case BPF_PSEUDO_MAP_IDX_VALUE:
14100 			case BPF_PSEUDO_MAP_IDX:
14101 				if (bpfptr_is_null(env->fd_array)) {
14102 					verbose(env, "fd_idx without fd_array is invalid\n");
14103 					return -EPROTO;
14104 				}
14105 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
14106 							    insn[0].imm * sizeof(fd),
14107 							    sizeof(fd)))
14108 					return -EFAULT;
14109 				break;
14110 			default:
14111 				fd = insn[0].imm;
14112 				break;
14113 			}
14114 
14115 			f = fdget(fd);
14116 			map = __bpf_map_get(f);
14117 			if (IS_ERR(map)) {
14118 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
14119 					insn[0].imm);
14120 				return PTR_ERR(map);
14121 			}
14122 
14123 			err = check_map_prog_compatibility(env, map, env->prog);
14124 			if (err) {
14125 				fdput(f);
14126 				return err;
14127 			}
14128 
14129 			aux = &env->insn_aux_data[i];
14130 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14131 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14132 				addr = (unsigned long)map;
14133 			} else {
14134 				u32 off = insn[1].imm;
14135 
14136 				if (off >= BPF_MAX_VAR_OFF) {
14137 					verbose(env, "direct value offset of %u is not allowed\n", off);
14138 					fdput(f);
14139 					return -EINVAL;
14140 				}
14141 
14142 				if (!map->ops->map_direct_value_addr) {
14143 					verbose(env, "no direct value access support for this map type\n");
14144 					fdput(f);
14145 					return -EINVAL;
14146 				}
14147 
14148 				err = map->ops->map_direct_value_addr(map, &addr, off);
14149 				if (err) {
14150 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14151 						map->value_size, off);
14152 					fdput(f);
14153 					return err;
14154 				}
14155 
14156 				aux->map_off = off;
14157 				addr += off;
14158 			}
14159 
14160 			insn[0].imm = (u32)addr;
14161 			insn[1].imm = addr >> 32;
14162 
14163 			/* check whether we recorded this map already */
14164 			for (j = 0; j < env->used_map_cnt; j++) {
14165 				if (env->used_maps[j] == map) {
14166 					aux->map_index = j;
14167 					fdput(f);
14168 					goto next_insn;
14169 				}
14170 			}
14171 
14172 			if (env->used_map_cnt >= MAX_USED_MAPS) {
14173 				fdput(f);
14174 				return -E2BIG;
14175 			}
14176 
14177 			/* hold the map. If the program is rejected by verifier,
14178 			 * the map will be released by release_maps() or it
14179 			 * will be used by the valid program until it's unloaded
14180 			 * and all maps are released in free_used_maps()
14181 			 */
14182 			bpf_map_inc(map);
14183 
14184 			aux->map_index = env->used_map_cnt;
14185 			env->used_maps[env->used_map_cnt++] = map;
14186 
14187 			if (bpf_map_is_cgroup_storage(map) &&
14188 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
14189 				verbose(env, "only one cgroup storage of each type is allowed\n");
14190 				fdput(f);
14191 				return -EBUSY;
14192 			}
14193 
14194 			fdput(f);
14195 next_insn:
14196 			insn++;
14197 			i++;
14198 			continue;
14199 		}
14200 
14201 		/* Basic sanity check before we invest more work here. */
14202 		if (!bpf_opcode_in_insntable(insn->code)) {
14203 			verbose(env, "unknown opcode %02x\n", insn->code);
14204 			return -EINVAL;
14205 		}
14206 	}
14207 
14208 	/* now all pseudo BPF_LD_IMM64 instructions load valid
14209 	 * 'struct bpf_map *' into a register instead of user map_fd.
14210 	 * These pointers will be used later by verifier to validate map access.
14211 	 */
14212 	return 0;
14213 }
14214 
14215 /* drop refcnt of maps used by the rejected program */
14216 static void release_maps(struct bpf_verifier_env *env)
14217 {
14218 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
14219 			     env->used_map_cnt);
14220 }
14221 
14222 /* drop refcnt of maps used by the rejected program */
14223 static void release_btfs(struct bpf_verifier_env *env)
14224 {
14225 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14226 			     env->used_btf_cnt);
14227 }
14228 
14229 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14230 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14231 {
14232 	struct bpf_insn *insn = env->prog->insnsi;
14233 	int insn_cnt = env->prog->len;
14234 	int i;
14235 
14236 	for (i = 0; i < insn_cnt; i++, insn++) {
14237 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14238 			continue;
14239 		if (insn->src_reg == BPF_PSEUDO_FUNC)
14240 			continue;
14241 		insn->src_reg = 0;
14242 	}
14243 }
14244 
14245 /* single env->prog->insni[off] instruction was replaced with the range
14246  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14247  * [0, off) and [off, end) to new locations, so the patched range stays zero
14248  */
14249 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14250 				 struct bpf_insn_aux_data *new_data,
14251 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
14252 {
14253 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14254 	struct bpf_insn *insn = new_prog->insnsi;
14255 	u32 old_seen = old_data[off].seen;
14256 	u32 prog_len;
14257 	int i;
14258 
14259 	/* aux info at OFF always needs adjustment, no matter fast path
14260 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14261 	 * original insn at old prog.
14262 	 */
14263 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14264 
14265 	if (cnt == 1)
14266 		return;
14267 	prog_len = new_prog->len;
14268 
14269 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14270 	memcpy(new_data + off + cnt - 1, old_data + off,
14271 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14272 	for (i = off; i < off + cnt - 1; i++) {
14273 		/* Expand insni[off]'s seen count to the patched range. */
14274 		new_data[i].seen = old_seen;
14275 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
14276 	}
14277 	env->insn_aux_data = new_data;
14278 	vfree(old_data);
14279 }
14280 
14281 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14282 {
14283 	int i;
14284 
14285 	if (len == 1)
14286 		return;
14287 	/* NOTE: fake 'exit' subprog should be updated as well. */
14288 	for (i = 0; i <= env->subprog_cnt; i++) {
14289 		if (env->subprog_info[i].start <= off)
14290 			continue;
14291 		env->subprog_info[i].start += len - 1;
14292 	}
14293 }
14294 
14295 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14296 {
14297 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14298 	int i, sz = prog->aux->size_poke_tab;
14299 	struct bpf_jit_poke_descriptor *desc;
14300 
14301 	for (i = 0; i < sz; i++) {
14302 		desc = &tab[i];
14303 		if (desc->insn_idx <= off)
14304 			continue;
14305 		desc->insn_idx += len - 1;
14306 	}
14307 }
14308 
14309 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14310 					    const struct bpf_insn *patch, u32 len)
14311 {
14312 	struct bpf_prog *new_prog;
14313 	struct bpf_insn_aux_data *new_data = NULL;
14314 
14315 	if (len > 1) {
14316 		new_data = vzalloc(array_size(env->prog->len + len - 1,
14317 					      sizeof(struct bpf_insn_aux_data)));
14318 		if (!new_data)
14319 			return NULL;
14320 	}
14321 
14322 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14323 	if (IS_ERR(new_prog)) {
14324 		if (PTR_ERR(new_prog) == -ERANGE)
14325 			verbose(env,
14326 				"insn %d cannot be patched due to 16-bit range\n",
14327 				env->insn_aux_data[off].orig_idx);
14328 		vfree(new_data);
14329 		return NULL;
14330 	}
14331 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
14332 	adjust_subprog_starts(env, off, len);
14333 	adjust_poke_descs(new_prog, off, len);
14334 	return new_prog;
14335 }
14336 
14337 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14338 					      u32 off, u32 cnt)
14339 {
14340 	int i, j;
14341 
14342 	/* find first prog starting at or after off (first to remove) */
14343 	for (i = 0; i < env->subprog_cnt; i++)
14344 		if (env->subprog_info[i].start >= off)
14345 			break;
14346 	/* find first prog starting at or after off + cnt (first to stay) */
14347 	for (j = i; j < env->subprog_cnt; j++)
14348 		if (env->subprog_info[j].start >= off + cnt)
14349 			break;
14350 	/* if j doesn't start exactly at off + cnt, we are just removing
14351 	 * the front of previous prog
14352 	 */
14353 	if (env->subprog_info[j].start != off + cnt)
14354 		j--;
14355 
14356 	if (j > i) {
14357 		struct bpf_prog_aux *aux = env->prog->aux;
14358 		int move;
14359 
14360 		/* move fake 'exit' subprog as well */
14361 		move = env->subprog_cnt + 1 - j;
14362 
14363 		memmove(env->subprog_info + i,
14364 			env->subprog_info + j,
14365 			sizeof(*env->subprog_info) * move);
14366 		env->subprog_cnt -= j - i;
14367 
14368 		/* remove func_info */
14369 		if (aux->func_info) {
14370 			move = aux->func_info_cnt - j;
14371 
14372 			memmove(aux->func_info + i,
14373 				aux->func_info + j,
14374 				sizeof(*aux->func_info) * move);
14375 			aux->func_info_cnt -= j - i;
14376 			/* func_info->insn_off is set after all code rewrites,
14377 			 * in adjust_btf_func() - no need to adjust
14378 			 */
14379 		}
14380 	} else {
14381 		/* convert i from "first prog to remove" to "first to adjust" */
14382 		if (env->subprog_info[i].start == off)
14383 			i++;
14384 	}
14385 
14386 	/* update fake 'exit' subprog as well */
14387 	for (; i <= env->subprog_cnt; i++)
14388 		env->subprog_info[i].start -= cnt;
14389 
14390 	return 0;
14391 }
14392 
14393 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14394 				      u32 cnt)
14395 {
14396 	struct bpf_prog *prog = env->prog;
14397 	u32 i, l_off, l_cnt, nr_linfo;
14398 	struct bpf_line_info *linfo;
14399 
14400 	nr_linfo = prog->aux->nr_linfo;
14401 	if (!nr_linfo)
14402 		return 0;
14403 
14404 	linfo = prog->aux->linfo;
14405 
14406 	/* find first line info to remove, count lines to be removed */
14407 	for (i = 0; i < nr_linfo; i++)
14408 		if (linfo[i].insn_off >= off)
14409 			break;
14410 
14411 	l_off = i;
14412 	l_cnt = 0;
14413 	for (; i < nr_linfo; i++)
14414 		if (linfo[i].insn_off < off + cnt)
14415 			l_cnt++;
14416 		else
14417 			break;
14418 
14419 	/* First live insn doesn't match first live linfo, it needs to "inherit"
14420 	 * last removed linfo.  prog is already modified, so prog->len == off
14421 	 * means no live instructions after (tail of the program was removed).
14422 	 */
14423 	if (prog->len != off && l_cnt &&
14424 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14425 		l_cnt--;
14426 		linfo[--i].insn_off = off + cnt;
14427 	}
14428 
14429 	/* remove the line info which refer to the removed instructions */
14430 	if (l_cnt) {
14431 		memmove(linfo + l_off, linfo + i,
14432 			sizeof(*linfo) * (nr_linfo - i));
14433 
14434 		prog->aux->nr_linfo -= l_cnt;
14435 		nr_linfo = prog->aux->nr_linfo;
14436 	}
14437 
14438 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
14439 	for (i = l_off; i < nr_linfo; i++)
14440 		linfo[i].insn_off -= cnt;
14441 
14442 	/* fix up all subprogs (incl. 'exit') which start >= off */
14443 	for (i = 0; i <= env->subprog_cnt; i++)
14444 		if (env->subprog_info[i].linfo_idx > l_off) {
14445 			/* program may have started in the removed region but
14446 			 * may not be fully removed
14447 			 */
14448 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14449 				env->subprog_info[i].linfo_idx -= l_cnt;
14450 			else
14451 				env->subprog_info[i].linfo_idx = l_off;
14452 		}
14453 
14454 	return 0;
14455 }
14456 
14457 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14458 {
14459 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14460 	unsigned int orig_prog_len = env->prog->len;
14461 	int err;
14462 
14463 	if (bpf_prog_is_dev_bound(env->prog->aux))
14464 		bpf_prog_offload_remove_insns(env, off, cnt);
14465 
14466 	err = bpf_remove_insns(env->prog, off, cnt);
14467 	if (err)
14468 		return err;
14469 
14470 	err = adjust_subprog_starts_after_remove(env, off, cnt);
14471 	if (err)
14472 		return err;
14473 
14474 	err = bpf_adj_linfo_after_remove(env, off, cnt);
14475 	if (err)
14476 		return err;
14477 
14478 	memmove(aux_data + off,	aux_data + off + cnt,
14479 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
14480 
14481 	return 0;
14482 }
14483 
14484 /* The verifier does more data flow analysis than llvm and will not
14485  * explore branches that are dead at run time. Malicious programs can
14486  * have dead code too. Therefore replace all dead at-run-time code
14487  * with 'ja -1'.
14488  *
14489  * Just nops are not optimal, e.g. if they would sit at the end of the
14490  * program and through another bug we would manage to jump there, then
14491  * we'd execute beyond program memory otherwise. Returning exception
14492  * code also wouldn't work since we can have subprogs where the dead
14493  * code could be located.
14494  */
14495 static void sanitize_dead_code(struct bpf_verifier_env *env)
14496 {
14497 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14498 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14499 	struct bpf_insn *insn = env->prog->insnsi;
14500 	const int insn_cnt = env->prog->len;
14501 	int i;
14502 
14503 	for (i = 0; i < insn_cnt; i++) {
14504 		if (aux_data[i].seen)
14505 			continue;
14506 		memcpy(insn + i, &trap, sizeof(trap));
14507 		aux_data[i].zext_dst = false;
14508 	}
14509 }
14510 
14511 static bool insn_is_cond_jump(u8 code)
14512 {
14513 	u8 op;
14514 
14515 	if (BPF_CLASS(code) == BPF_JMP32)
14516 		return true;
14517 
14518 	if (BPF_CLASS(code) != BPF_JMP)
14519 		return false;
14520 
14521 	op = BPF_OP(code);
14522 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14523 }
14524 
14525 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14526 {
14527 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14528 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14529 	struct bpf_insn *insn = env->prog->insnsi;
14530 	const int insn_cnt = env->prog->len;
14531 	int i;
14532 
14533 	for (i = 0; i < insn_cnt; i++, insn++) {
14534 		if (!insn_is_cond_jump(insn->code))
14535 			continue;
14536 
14537 		if (!aux_data[i + 1].seen)
14538 			ja.off = insn->off;
14539 		else if (!aux_data[i + 1 + insn->off].seen)
14540 			ja.off = 0;
14541 		else
14542 			continue;
14543 
14544 		if (bpf_prog_is_dev_bound(env->prog->aux))
14545 			bpf_prog_offload_replace_insn(env, i, &ja);
14546 
14547 		memcpy(insn, &ja, sizeof(ja));
14548 	}
14549 }
14550 
14551 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14552 {
14553 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14554 	int insn_cnt = env->prog->len;
14555 	int i, err;
14556 
14557 	for (i = 0; i < insn_cnt; i++) {
14558 		int j;
14559 
14560 		j = 0;
14561 		while (i + j < insn_cnt && !aux_data[i + j].seen)
14562 			j++;
14563 		if (!j)
14564 			continue;
14565 
14566 		err = verifier_remove_insns(env, i, j);
14567 		if (err)
14568 			return err;
14569 		insn_cnt = env->prog->len;
14570 	}
14571 
14572 	return 0;
14573 }
14574 
14575 static int opt_remove_nops(struct bpf_verifier_env *env)
14576 {
14577 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14578 	struct bpf_insn *insn = env->prog->insnsi;
14579 	int insn_cnt = env->prog->len;
14580 	int i, err;
14581 
14582 	for (i = 0; i < insn_cnt; i++) {
14583 		if (memcmp(&insn[i], &ja, sizeof(ja)))
14584 			continue;
14585 
14586 		err = verifier_remove_insns(env, i, 1);
14587 		if (err)
14588 			return err;
14589 		insn_cnt--;
14590 		i--;
14591 	}
14592 
14593 	return 0;
14594 }
14595 
14596 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14597 					 const union bpf_attr *attr)
14598 {
14599 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14600 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
14601 	int i, patch_len, delta = 0, len = env->prog->len;
14602 	struct bpf_insn *insns = env->prog->insnsi;
14603 	struct bpf_prog *new_prog;
14604 	bool rnd_hi32;
14605 
14606 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14607 	zext_patch[1] = BPF_ZEXT_REG(0);
14608 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14609 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14610 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14611 	for (i = 0; i < len; i++) {
14612 		int adj_idx = i + delta;
14613 		struct bpf_insn insn;
14614 		int load_reg;
14615 
14616 		insn = insns[adj_idx];
14617 		load_reg = insn_def_regno(&insn);
14618 		if (!aux[adj_idx].zext_dst) {
14619 			u8 code, class;
14620 			u32 imm_rnd;
14621 
14622 			if (!rnd_hi32)
14623 				continue;
14624 
14625 			code = insn.code;
14626 			class = BPF_CLASS(code);
14627 			if (load_reg == -1)
14628 				continue;
14629 
14630 			/* NOTE: arg "reg" (the fourth one) is only used for
14631 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
14632 			 *       here.
14633 			 */
14634 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14635 				if (class == BPF_LD &&
14636 				    BPF_MODE(code) == BPF_IMM)
14637 					i++;
14638 				continue;
14639 			}
14640 
14641 			/* ctx load could be transformed into wider load. */
14642 			if (class == BPF_LDX &&
14643 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
14644 				continue;
14645 
14646 			imm_rnd = get_random_u32();
14647 			rnd_hi32_patch[0] = insn;
14648 			rnd_hi32_patch[1].imm = imm_rnd;
14649 			rnd_hi32_patch[3].dst_reg = load_reg;
14650 			patch = rnd_hi32_patch;
14651 			patch_len = 4;
14652 			goto apply_patch_buffer;
14653 		}
14654 
14655 		/* Add in an zero-extend instruction if a) the JIT has requested
14656 		 * it or b) it's a CMPXCHG.
14657 		 *
14658 		 * The latter is because: BPF_CMPXCHG always loads a value into
14659 		 * R0, therefore always zero-extends. However some archs'
14660 		 * equivalent instruction only does this load when the
14661 		 * comparison is successful. This detail of CMPXCHG is
14662 		 * orthogonal to the general zero-extension behaviour of the
14663 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
14664 		 */
14665 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14666 			continue;
14667 
14668 		if (WARN_ON(load_reg == -1)) {
14669 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14670 			return -EFAULT;
14671 		}
14672 
14673 		zext_patch[0] = insn;
14674 		zext_patch[1].dst_reg = load_reg;
14675 		zext_patch[1].src_reg = load_reg;
14676 		patch = zext_patch;
14677 		patch_len = 2;
14678 apply_patch_buffer:
14679 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
14680 		if (!new_prog)
14681 			return -ENOMEM;
14682 		env->prog = new_prog;
14683 		insns = new_prog->insnsi;
14684 		aux = env->insn_aux_data;
14685 		delta += patch_len - 1;
14686 	}
14687 
14688 	return 0;
14689 }
14690 
14691 /* convert load instructions that access fields of a context type into a
14692  * sequence of instructions that access fields of the underlying structure:
14693  *     struct __sk_buff    -> struct sk_buff
14694  *     struct bpf_sock_ops -> struct sock
14695  */
14696 static int convert_ctx_accesses(struct bpf_verifier_env *env)
14697 {
14698 	const struct bpf_verifier_ops *ops = env->ops;
14699 	int i, cnt, size, ctx_field_size, delta = 0;
14700 	const int insn_cnt = env->prog->len;
14701 	struct bpf_insn insn_buf[16], *insn;
14702 	u32 target_size, size_default, off;
14703 	struct bpf_prog *new_prog;
14704 	enum bpf_access_type type;
14705 	bool is_narrower_load;
14706 
14707 	if (ops->gen_prologue || env->seen_direct_write) {
14708 		if (!ops->gen_prologue) {
14709 			verbose(env, "bpf verifier is misconfigured\n");
14710 			return -EINVAL;
14711 		}
14712 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
14713 					env->prog);
14714 		if (cnt >= ARRAY_SIZE(insn_buf)) {
14715 			verbose(env, "bpf verifier is misconfigured\n");
14716 			return -EINVAL;
14717 		} else if (cnt) {
14718 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
14719 			if (!new_prog)
14720 				return -ENOMEM;
14721 
14722 			env->prog = new_prog;
14723 			delta += cnt - 1;
14724 		}
14725 	}
14726 
14727 	if (bpf_prog_is_dev_bound(env->prog->aux))
14728 		return 0;
14729 
14730 	insn = env->prog->insnsi + delta;
14731 
14732 	for (i = 0; i < insn_cnt; i++, insn++) {
14733 		bpf_convert_ctx_access_t convert_ctx_access;
14734 		bool ctx_access;
14735 
14736 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
14737 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
14738 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
14739 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
14740 			type = BPF_READ;
14741 			ctx_access = true;
14742 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
14743 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
14744 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
14745 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
14746 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
14747 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
14748 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
14749 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
14750 			type = BPF_WRITE;
14751 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
14752 		} else {
14753 			continue;
14754 		}
14755 
14756 		if (type == BPF_WRITE &&
14757 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
14758 			struct bpf_insn patch[] = {
14759 				*insn,
14760 				BPF_ST_NOSPEC(),
14761 			};
14762 
14763 			cnt = ARRAY_SIZE(patch);
14764 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
14765 			if (!new_prog)
14766 				return -ENOMEM;
14767 
14768 			delta    += cnt - 1;
14769 			env->prog = new_prog;
14770 			insn      = new_prog->insnsi + i + delta;
14771 			continue;
14772 		}
14773 
14774 		if (!ctx_access)
14775 			continue;
14776 
14777 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
14778 		case PTR_TO_CTX:
14779 			if (!ops->convert_ctx_access)
14780 				continue;
14781 			convert_ctx_access = ops->convert_ctx_access;
14782 			break;
14783 		case PTR_TO_SOCKET:
14784 		case PTR_TO_SOCK_COMMON:
14785 			convert_ctx_access = bpf_sock_convert_ctx_access;
14786 			break;
14787 		case PTR_TO_TCP_SOCK:
14788 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
14789 			break;
14790 		case PTR_TO_XDP_SOCK:
14791 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
14792 			break;
14793 		case PTR_TO_BTF_ID:
14794 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
14795 		case PTR_TO_BTF_ID | PTR_TRUSTED:
14796 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
14797 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
14798 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
14799 		 * any faults for loads into such types. BPF_WRITE is disallowed
14800 		 * for this case.
14801 		 */
14802 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
14803 		case PTR_TO_BTF_ID | PTR_UNTRUSTED | PTR_TRUSTED:
14804 		case PTR_TO_BTF_ID | PTR_UNTRUSTED | MEM_ALLOC | PTR_TRUSTED:
14805 			if (type == BPF_READ) {
14806 				insn->code = BPF_LDX | BPF_PROBE_MEM |
14807 					BPF_SIZE((insn)->code);
14808 				env->prog->aux->num_exentries++;
14809 			}
14810 			continue;
14811 		default:
14812 			continue;
14813 		}
14814 
14815 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
14816 		size = BPF_LDST_BYTES(insn);
14817 
14818 		/* If the read access is a narrower load of the field,
14819 		 * convert to a 4/8-byte load, to minimum program type specific
14820 		 * convert_ctx_access changes. If conversion is successful,
14821 		 * we will apply proper mask to the result.
14822 		 */
14823 		is_narrower_load = size < ctx_field_size;
14824 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
14825 		off = insn->off;
14826 		if (is_narrower_load) {
14827 			u8 size_code;
14828 
14829 			if (type == BPF_WRITE) {
14830 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
14831 				return -EINVAL;
14832 			}
14833 
14834 			size_code = BPF_H;
14835 			if (ctx_field_size == 4)
14836 				size_code = BPF_W;
14837 			else if (ctx_field_size == 8)
14838 				size_code = BPF_DW;
14839 
14840 			insn->off = off & ~(size_default - 1);
14841 			insn->code = BPF_LDX | BPF_MEM | size_code;
14842 		}
14843 
14844 		target_size = 0;
14845 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
14846 					 &target_size);
14847 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
14848 		    (ctx_field_size && !target_size)) {
14849 			verbose(env, "bpf verifier is misconfigured\n");
14850 			return -EINVAL;
14851 		}
14852 
14853 		if (is_narrower_load && size < target_size) {
14854 			u8 shift = bpf_ctx_narrow_access_offset(
14855 				off, size, size_default) * 8;
14856 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
14857 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
14858 				return -EINVAL;
14859 			}
14860 			if (ctx_field_size <= 4) {
14861 				if (shift)
14862 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
14863 									insn->dst_reg,
14864 									shift);
14865 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
14866 								(1 << size * 8) - 1);
14867 			} else {
14868 				if (shift)
14869 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
14870 									insn->dst_reg,
14871 									shift);
14872 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
14873 								(1ULL << size * 8) - 1);
14874 			}
14875 		}
14876 
14877 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14878 		if (!new_prog)
14879 			return -ENOMEM;
14880 
14881 		delta += cnt - 1;
14882 
14883 		/* keep walking new program and skip insns we just inserted */
14884 		env->prog = new_prog;
14885 		insn      = new_prog->insnsi + i + delta;
14886 	}
14887 
14888 	return 0;
14889 }
14890 
14891 static int jit_subprogs(struct bpf_verifier_env *env)
14892 {
14893 	struct bpf_prog *prog = env->prog, **func, *tmp;
14894 	int i, j, subprog_start, subprog_end = 0, len, subprog;
14895 	struct bpf_map *map_ptr;
14896 	struct bpf_insn *insn;
14897 	void *old_bpf_func;
14898 	int err, num_exentries;
14899 
14900 	if (env->subprog_cnt <= 1)
14901 		return 0;
14902 
14903 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
14904 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
14905 			continue;
14906 
14907 		/* Upon error here we cannot fall back to interpreter but
14908 		 * need a hard reject of the program. Thus -EFAULT is
14909 		 * propagated in any case.
14910 		 */
14911 		subprog = find_subprog(env, i + insn->imm + 1);
14912 		if (subprog < 0) {
14913 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
14914 				  i + insn->imm + 1);
14915 			return -EFAULT;
14916 		}
14917 		/* temporarily remember subprog id inside insn instead of
14918 		 * aux_data, since next loop will split up all insns into funcs
14919 		 */
14920 		insn->off = subprog;
14921 		/* remember original imm in case JIT fails and fallback
14922 		 * to interpreter will be needed
14923 		 */
14924 		env->insn_aux_data[i].call_imm = insn->imm;
14925 		/* point imm to __bpf_call_base+1 from JITs point of view */
14926 		insn->imm = 1;
14927 		if (bpf_pseudo_func(insn))
14928 			/* jit (e.g. x86_64) may emit fewer instructions
14929 			 * if it learns a u32 imm is the same as a u64 imm.
14930 			 * Force a non zero here.
14931 			 */
14932 			insn[1].imm = 1;
14933 	}
14934 
14935 	err = bpf_prog_alloc_jited_linfo(prog);
14936 	if (err)
14937 		goto out_undo_insn;
14938 
14939 	err = -ENOMEM;
14940 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
14941 	if (!func)
14942 		goto out_undo_insn;
14943 
14944 	for (i = 0; i < env->subprog_cnt; i++) {
14945 		subprog_start = subprog_end;
14946 		subprog_end = env->subprog_info[i + 1].start;
14947 
14948 		len = subprog_end - subprog_start;
14949 		/* bpf_prog_run() doesn't call subprogs directly,
14950 		 * hence main prog stats include the runtime of subprogs.
14951 		 * subprogs don't have IDs and not reachable via prog_get_next_id
14952 		 * func[i]->stats will never be accessed and stays NULL
14953 		 */
14954 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
14955 		if (!func[i])
14956 			goto out_free;
14957 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
14958 		       len * sizeof(struct bpf_insn));
14959 		func[i]->type = prog->type;
14960 		func[i]->len = len;
14961 		if (bpf_prog_calc_tag(func[i]))
14962 			goto out_free;
14963 		func[i]->is_func = 1;
14964 		func[i]->aux->func_idx = i;
14965 		/* Below members will be freed only at prog->aux */
14966 		func[i]->aux->btf = prog->aux->btf;
14967 		func[i]->aux->func_info = prog->aux->func_info;
14968 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
14969 		func[i]->aux->poke_tab = prog->aux->poke_tab;
14970 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
14971 
14972 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
14973 			struct bpf_jit_poke_descriptor *poke;
14974 
14975 			poke = &prog->aux->poke_tab[j];
14976 			if (poke->insn_idx < subprog_end &&
14977 			    poke->insn_idx >= subprog_start)
14978 				poke->aux = func[i]->aux;
14979 		}
14980 
14981 		func[i]->aux->name[0] = 'F';
14982 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
14983 		func[i]->jit_requested = 1;
14984 		func[i]->blinding_requested = prog->blinding_requested;
14985 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
14986 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
14987 		func[i]->aux->linfo = prog->aux->linfo;
14988 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
14989 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
14990 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
14991 		num_exentries = 0;
14992 		insn = func[i]->insnsi;
14993 		for (j = 0; j < func[i]->len; j++, insn++) {
14994 			if (BPF_CLASS(insn->code) == BPF_LDX &&
14995 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
14996 				num_exentries++;
14997 		}
14998 		func[i]->aux->num_exentries = num_exentries;
14999 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15000 		func[i] = bpf_int_jit_compile(func[i]);
15001 		if (!func[i]->jited) {
15002 			err = -ENOTSUPP;
15003 			goto out_free;
15004 		}
15005 		cond_resched();
15006 	}
15007 
15008 	/* at this point all bpf functions were successfully JITed
15009 	 * now populate all bpf_calls with correct addresses and
15010 	 * run last pass of JIT
15011 	 */
15012 	for (i = 0; i < env->subprog_cnt; i++) {
15013 		insn = func[i]->insnsi;
15014 		for (j = 0; j < func[i]->len; j++, insn++) {
15015 			if (bpf_pseudo_func(insn)) {
15016 				subprog = insn->off;
15017 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15018 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15019 				continue;
15020 			}
15021 			if (!bpf_pseudo_call(insn))
15022 				continue;
15023 			subprog = insn->off;
15024 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15025 		}
15026 
15027 		/* we use the aux data to keep a list of the start addresses
15028 		 * of the JITed images for each function in the program
15029 		 *
15030 		 * for some architectures, such as powerpc64, the imm field
15031 		 * might not be large enough to hold the offset of the start
15032 		 * address of the callee's JITed image from __bpf_call_base
15033 		 *
15034 		 * in such cases, we can lookup the start address of a callee
15035 		 * by using its subprog id, available from the off field of
15036 		 * the call instruction, as an index for this list
15037 		 */
15038 		func[i]->aux->func = func;
15039 		func[i]->aux->func_cnt = env->subprog_cnt;
15040 	}
15041 	for (i = 0; i < env->subprog_cnt; i++) {
15042 		old_bpf_func = func[i]->bpf_func;
15043 		tmp = bpf_int_jit_compile(func[i]);
15044 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15045 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15046 			err = -ENOTSUPP;
15047 			goto out_free;
15048 		}
15049 		cond_resched();
15050 	}
15051 
15052 	/* finally lock prog and jit images for all functions and
15053 	 * populate kallsysm
15054 	 */
15055 	for (i = 0; i < env->subprog_cnt; i++) {
15056 		bpf_prog_lock_ro(func[i]);
15057 		bpf_prog_kallsyms_add(func[i]);
15058 	}
15059 
15060 	/* Last step: make now unused interpreter insns from main
15061 	 * prog consistent for later dump requests, so they can
15062 	 * later look the same as if they were interpreted only.
15063 	 */
15064 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15065 		if (bpf_pseudo_func(insn)) {
15066 			insn[0].imm = env->insn_aux_data[i].call_imm;
15067 			insn[1].imm = insn->off;
15068 			insn->off = 0;
15069 			continue;
15070 		}
15071 		if (!bpf_pseudo_call(insn))
15072 			continue;
15073 		insn->off = env->insn_aux_data[i].call_imm;
15074 		subprog = find_subprog(env, i + insn->off + 1);
15075 		insn->imm = subprog;
15076 	}
15077 
15078 	prog->jited = 1;
15079 	prog->bpf_func = func[0]->bpf_func;
15080 	prog->jited_len = func[0]->jited_len;
15081 	prog->aux->func = func;
15082 	prog->aux->func_cnt = env->subprog_cnt;
15083 	bpf_prog_jit_attempt_done(prog);
15084 	return 0;
15085 out_free:
15086 	/* We failed JIT'ing, so at this point we need to unregister poke
15087 	 * descriptors from subprogs, so that kernel is not attempting to
15088 	 * patch it anymore as we're freeing the subprog JIT memory.
15089 	 */
15090 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
15091 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
15092 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15093 	}
15094 	/* At this point we're guaranteed that poke descriptors are not
15095 	 * live anymore. We can just unlink its descriptor table as it's
15096 	 * released with the main prog.
15097 	 */
15098 	for (i = 0; i < env->subprog_cnt; i++) {
15099 		if (!func[i])
15100 			continue;
15101 		func[i]->aux->poke_tab = NULL;
15102 		bpf_jit_free(func[i]);
15103 	}
15104 	kfree(func);
15105 out_undo_insn:
15106 	/* cleanup main prog to be interpreted */
15107 	prog->jit_requested = 0;
15108 	prog->blinding_requested = 0;
15109 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15110 		if (!bpf_pseudo_call(insn))
15111 			continue;
15112 		insn->off = 0;
15113 		insn->imm = env->insn_aux_data[i].call_imm;
15114 	}
15115 	bpf_prog_jit_attempt_done(prog);
15116 	return err;
15117 }
15118 
15119 static int fixup_call_args(struct bpf_verifier_env *env)
15120 {
15121 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15122 	struct bpf_prog *prog = env->prog;
15123 	struct bpf_insn *insn = prog->insnsi;
15124 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15125 	int i, depth;
15126 #endif
15127 	int err = 0;
15128 
15129 	if (env->prog->jit_requested &&
15130 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
15131 		err = jit_subprogs(env);
15132 		if (err == 0)
15133 			return 0;
15134 		if (err == -EFAULT)
15135 			return err;
15136 	}
15137 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15138 	if (has_kfunc_call) {
15139 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15140 		return -EINVAL;
15141 	}
15142 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15143 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
15144 		 * have to be rejected, since interpreter doesn't support them yet.
15145 		 */
15146 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15147 		return -EINVAL;
15148 	}
15149 	for (i = 0; i < prog->len; i++, insn++) {
15150 		if (bpf_pseudo_func(insn)) {
15151 			/* When JIT fails the progs with callback calls
15152 			 * have to be rejected, since interpreter doesn't support them yet.
15153 			 */
15154 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
15155 			return -EINVAL;
15156 		}
15157 
15158 		if (!bpf_pseudo_call(insn))
15159 			continue;
15160 		depth = get_callee_stack_depth(env, insn, i);
15161 		if (depth < 0)
15162 			return depth;
15163 		bpf_patch_call_args(insn, depth);
15164 	}
15165 	err = 0;
15166 #endif
15167 	return err;
15168 }
15169 
15170 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15171 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15172 {
15173 	const struct bpf_kfunc_desc *desc;
15174 
15175 	if (!insn->imm) {
15176 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15177 		return -EINVAL;
15178 	}
15179 
15180 	/* insn->imm has the btf func_id. Replace it with
15181 	 * an address (relative to __bpf_base_call).
15182 	 */
15183 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15184 	if (!desc) {
15185 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15186 			insn->imm);
15187 		return -EFAULT;
15188 	}
15189 
15190 	*cnt = 0;
15191 	insn->imm = desc->imm;
15192 	if (insn->off)
15193 		return 0;
15194 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15195 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15196 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15197 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15198 
15199 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15200 		insn_buf[1] = addr[0];
15201 		insn_buf[2] = addr[1];
15202 		insn_buf[3] = *insn;
15203 		*cnt = 4;
15204 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15205 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15206 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15207 
15208 		insn_buf[0] = addr[0];
15209 		insn_buf[1] = addr[1];
15210 		insn_buf[2] = *insn;
15211 		*cnt = 3;
15212 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15213 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15214 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15215 		*cnt = 1;
15216 	}
15217 	return 0;
15218 }
15219 
15220 /* Do various post-verification rewrites in a single program pass.
15221  * These rewrites simplify JIT and interpreter implementations.
15222  */
15223 static int do_misc_fixups(struct bpf_verifier_env *env)
15224 {
15225 	struct bpf_prog *prog = env->prog;
15226 	enum bpf_attach_type eatype = prog->expected_attach_type;
15227 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15228 	struct bpf_insn *insn = prog->insnsi;
15229 	const struct bpf_func_proto *fn;
15230 	const int insn_cnt = prog->len;
15231 	const struct bpf_map_ops *ops;
15232 	struct bpf_insn_aux_data *aux;
15233 	struct bpf_insn insn_buf[16];
15234 	struct bpf_prog *new_prog;
15235 	struct bpf_map *map_ptr;
15236 	int i, ret, cnt, delta = 0;
15237 
15238 	for (i = 0; i < insn_cnt; i++, insn++) {
15239 		/* Make divide-by-zero exceptions impossible. */
15240 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15241 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15242 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15243 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15244 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15245 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15246 			struct bpf_insn *patchlet;
15247 			struct bpf_insn chk_and_div[] = {
15248 				/* [R,W]x div 0 -> 0 */
15249 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15250 					     BPF_JNE | BPF_K, insn->src_reg,
15251 					     0, 2, 0),
15252 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15253 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15254 				*insn,
15255 			};
15256 			struct bpf_insn chk_and_mod[] = {
15257 				/* [R,W]x mod 0 -> [R,W]x */
15258 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15259 					     BPF_JEQ | BPF_K, insn->src_reg,
15260 					     0, 1 + (is64 ? 0 : 1), 0),
15261 				*insn,
15262 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15263 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15264 			};
15265 
15266 			patchlet = isdiv ? chk_and_div : chk_and_mod;
15267 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15268 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15269 
15270 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15271 			if (!new_prog)
15272 				return -ENOMEM;
15273 
15274 			delta    += cnt - 1;
15275 			env->prog = prog = new_prog;
15276 			insn      = new_prog->insnsi + i + delta;
15277 			continue;
15278 		}
15279 
15280 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15281 		if (BPF_CLASS(insn->code) == BPF_LD &&
15282 		    (BPF_MODE(insn->code) == BPF_ABS ||
15283 		     BPF_MODE(insn->code) == BPF_IND)) {
15284 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
15285 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15286 				verbose(env, "bpf verifier is misconfigured\n");
15287 				return -EINVAL;
15288 			}
15289 
15290 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15291 			if (!new_prog)
15292 				return -ENOMEM;
15293 
15294 			delta    += cnt - 1;
15295 			env->prog = prog = new_prog;
15296 			insn      = new_prog->insnsi + i + delta;
15297 			continue;
15298 		}
15299 
15300 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
15301 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15302 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15303 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15304 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15305 			struct bpf_insn *patch = &insn_buf[0];
15306 			bool issrc, isneg, isimm;
15307 			u32 off_reg;
15308 
15309 			aux = &env->insn_aux_data[i + delta];
15310 			if (!aux->alu_state ||
15311 			    aux->alu_state == BPF_ALU_NON_POINTER)
15312 				continue;
15313 
15314 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15315 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15316 				BPF_ALU_SANITIZE_SRC;
15317 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15318 
15319 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
15320 			if (isimm) {
15321 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15322 			} else {
15323 				if (isneg)
15324 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15325 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15326 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15327 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15328 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15329 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15330 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15331 			}
15332 			if (!issrc)
15333 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15334 			insn->src_reg = BPF_REG_AX;
15335 			if (isneg)
15336 				insn->code = insn->code == code_add ?
15337 					     code_sub : code_add;
15338 			*patch++ = *insn;
15339 			if (issrc && isneg && !isimm)
15340 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15341 			cnt = patch - insn_buf;
15342 
15343 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15344 			if (!new_prog)
15345 				return -ENOMEM;
15346 
15347 			delta    += cnt - 1;
15348 			env->prog = prog = new_prog;
15349 			insn      = new_prog->insnsi + i + delta;
15350 			continue;
15351 		}
15352 
15353 		if (insn->code != (BPF_JMP | BPF_CALL))
15354 			continue;
15355 		if (insn->src_reg == BPF_PSEUDO_CALL)
15356 			continue;
15357 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15358 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15359 			if (ret)
15360 				return ret;
15361 			if (cnt == 0)
15362 				continue;
15363 
15364 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15365 			if (!new_prog)
15366 				return -ENOMEM;
15367 
15368 			delta	 += cnt - 1;
15369 			env->prog = prog = new_prog;
15370 			insn	  = new_prog->insnsi + i + delta;
15371 			continue;
15372 		}
15373 
15374 		if (insn->imm == BPF_FUNC_get_route_realm)
15375 			prog->dst_needed = 1;
15376 		if (insn->imm == BPF_FUNC_get_prandom_u32)
15377 			bpf_user_rnd_init_once();
15378 		if (insn->imm == BPF_FUNC_override_return)
15379 			prog->kprobe_override = 1;
15380 		if (insn->imm == BPF_FUNC_tail_call) {
15381 			/* If we tail call into other programs, we
15382 			 * cannot make any assumptions since they can
15383 			 * be replaced dynamically during runtime in
15384 			 * the program array.
15385 			 */
15386 			prog->cb_access = 1;
15387 			if (!allow_tail_call_in_subprogs(env))
15388 				prog->aux->stack_depth = MAX_BPF_STACK;
15389 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15390 
15391 			/* mark bpf_tail_call as different opcode to avoid
15392 			 * conditional branch in the interpreter for every normal
15393 			 * call and to prevent accidental JITing by JIT compiler
15394 			 * that doesn't support bpf_tail_call yet
15395 			 */
15396 			insn->imm = 0;
15397 			insn->code = BPF_JMP | BPF_TAIL_CALL;
15398 
15399 			aux = &env->insn_aux_data[i + delta];
15400 			if (env->bpf_capable && !prog->blinding_requested &&
15401 			    prog->jit_requested &&
15402 			    !bpf_map_key_poisoned(aux) &&
15403 			    !bpf_map_ptr_poisoned(aux) &&
15404 			    !bpf_map_ptr_unpriv(aux)) {
15405 				struct bpf_jit_poke_descriptor desc = {
15406 					.reason = BPF_POKE_REASON_TAIL_CALL,
15407 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15408 					.tail_call.key = bpf_map_key_immediate(aux),
15409 					.insn_idx = i + delta,
15410 				};
15411 
15412 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
15413 				if (ret < 0) {
15414 					verbose(env, "adding tail call poke descriptor failed\n");
15415 					return ret;
15416 				}
15417 
15418 				insn->imm = ret + 1;
15419 				continue;
15420 			}
15421 
15422 			if (!bpf_map_ptr_unpriv(aux))
15423 				continue;
15424 
15425 			/* instead of changing every JIT dealing with tail_call
15426 			 * emit two extra insns:
15427 			 * if (index >= max_entries) goto out;
15428 			 * index &= array->index_mask;
15429 			 * to avoid out-of-bounds cpu speculation
15430 			 */
15431 			if (bpf_map_ptr_poisoned(aux)) {
15432 				verbose(env, "tail_call abusing map_ptr\n");
15433 				return -EINVAL;
15434 			}
15435 
15436 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15437 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15438 						  map_ptr->max_entries, 2);
15439 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15440 						    container_of(map_ptr,
15441 								 struct bpf_array,
15442 								 map)->index_mask);
15443 			insn_buf[2] = *insn;
15444 			cnt = 3;
15445 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15446 			if (!new_prog)
15447 				return -ENOMEM;
15448 
15449 			delta    += cnt - 1;
15450 			env->prog = prog = new_prog;
15451 			insn      = new_prog->insnsi + i + delta;
15452 			continue;
15453 		}
15454 
15455 		if (insn->imm == BPF_FUNC_timer_set_callback) {
15456 			/* The verifier will process callback_fn as many times as necessary
15457 			 * with different maps and the register states prepared by
15458 			 * set_timer_callback_state will be accurate.
15459 			 *
15460 			 * The following use case is valid:
15461 			 *   map1 is shared by prog1, prog2, prog3.
15462 			 *   prog1 calls bpf_timer_init for some map1 elements
15463 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
15464 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
15465 			 *   prog3 calls bpf_timer_start for some map1 elements.
15466 			 *     Those that were not both bpf_timer_init-ed and
15467 			 *     bpf_timer_set_callback-ed will return -EINVAL.
15468 			 */
15469 			struct bpf_insn ld_addrs[2] = {
15470 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15471 			};
15472 
15473 			insn_buf[0] = ld_addrs[0];
15474 			insn_buf[1] = ld_addrs[1];
15475 			insn_buf[2] = *insn;
15476 			cnt = 3;
15477 
15478 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15479 			if (!new_prog)
15480 				return -ENOMEM;
15481 
15482 			delta    += cnt - 1;
15483 			env->prog = prog = new_prog;
15484 			insn      = new_prog->insnsi + i + delta;
15485 			goto patch_call_imm;
15486 		}
15487 
15488 		if (insn->imm == BPF_FUNC_task_storage_get ||
15489 		    insn->imm == BPF_FUNC_sk_storage_get ||
15490 		    insn->imm == BPF_FUNC_inode_storage_get ||
15491 		    insn->imm == BPF_FUNC_cgrp_storage_get) {
15492 			if (env->prog->aux->sleepable)
15493 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15494 			else
15495 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15496 			insn_buf[1] = *insn;
15497 			cnt = 2;
15498 
15499 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15500 			if (!new_prog)
15501 				return -ENOMEM;
15502 
15503 			delta += cnt - 1;
15504 			env->prog = prog = new_prog;
15505 			insn = new_prog->insnsi + i + delta;
15506 			goto patch_call_imm;
15507 		}
15508 
15509 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15510 		 * and other inlining handlers are currently limited to 64 bit
15511 		 * only.
15512 		 */
15513 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15514 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
15515 		     insn->imm == BPF_FUNC_map_update_elem ||
15516 		     insn->imm == BPF_FUNC_map_delete_elem ||
15517 		     insn->imm == BPF_FUNC_map_push_elem   ||
15518 		     insn->imm == BPF_FUNC_map_pop_elem    ||
15519 		     insn->imm == BPF_FUNC_map_peek_elem   ||
15520 		     insn->imm == BPF_FUNC_redirect_map    ||
15521 		     insn->imm == BPF_FUNC_for_each_map_elem ||
15522 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15523 			aux = &env->insn_aux_data[i + delta];
15524 			if (bpf_map_ptr_poisoned(aux))
15525 				goto patch_call_imm;
15526 
15527 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15528 			ops = map_ptr->ops;
15529 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
15530 			    ops->map_gen_lookup) {
15531 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15532 				if (cnt == -EOPNOTSUPP)
15533 					goto patch_map_ops_generic;
15534 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15535 					verbose(env, "bpf verifier is misconfigured\n");
15536 					return -EINVAL;
15537 				}
15538 
15539 				new_prog = bpf_patch_insn_data(env, i + delta,
15540 							       insn_buf, cnt);
15541 				if (!new_prog)
15542 					return -ENOMEM;
15543 
15544 				delta    += cnt - 1;
15545 				env->prog = prog = new_prog;
15546 				insn      = new_prog->insnsi + i + delta;
15547 				continue;
15548 			}
15549 
15550 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15551 				     (void *(*)(struct bpf_map *map, void *key))NULL));
15552 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15553 				     (int (*)(struct bpf_map *map, void *key))NULL));
15554 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15555 				     (int (*)(struct bpf_map *map, void *key, void *value,
15556 					      u64 flags))NULL));
15557 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15558 				     (int (*)(struct bpf_map *map, void *value,
15559 					      u64 flags))NULL));
15560 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15561 				     (int (*)(struct bpf_map *map, void *value))NULL));
15562 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15563 				     (int (*)(struct bpf_map *map, void *value))NULL));
15564 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
15565 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15566 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15567 				     (int (*)(struct bpf_map *map,
15568 					      bpf_callback_t callback_fn,
15569 					      void *callback_ctx,
15570 					      u64 flags))NULL));
15571 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15572 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15573 
15574 patch_map_ops_generic:
15575 			switch (insn->imm) {
15576 			case BPF_FUNC_map_lookup_elem:
15577 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15578 				continue;
15579 			case BPF_FUNC_map_update_elem:
15580 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15581 				continue;
15582 			case BPF_FUNC_map_delete_elem:
15583 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15584 				continue;
15585 			case BPF_FUNC_map_push_elem:
15586 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15587 				continue;
15588 			case BPF_FUNC_map_pop_elem:
15589 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15590 				continue;
15591 			case BPF_FUNC_map_peek_elem:
15592 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15593 				continue;
15594 			case BPF_FUNC_redirect_map:
15595 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
15596 				continue;
15597 			case BPF_FUNC_for_each_map_elem:
15598 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15599 				continue;
15600 			case BPF_FUNC_map_lookup_percpu_elem:
15601 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15602 				continue;
15603 			}
15604 
15605 			goto patch_call_imm;
15606 		}
15607 
15608 		/* Implement bpf_jiffies64 inline. */
15609 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15610 		    insn->imm == BPF_FUNC_jiffies64) {
15611 			struct bpf_insn ld_jiffies_addr[2] = {
15612 				BPF_LD_IMM64(BPF_REG_0,
15613 					     (unsigned long)&jiffies),
15614 			};
15615 
15616 			insn_buf[0] = ld_jiffies_addr[0];
15617 			insn_buf[1] = ld_jiffies_addr[1];
15618 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15619 						  BPF_REG_0, 0);
15620 			cnt = 3;
15621 
15622 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15623 						       cnt);
15624 			if (!new_prog)
15625 				return -ENOMEM;
15626 
15627 			delta    += cnt - 1;
15628 			env->prog = prog = new_prog;
15629 			insn      = new_prog->insnsi + i + delta;
15630 			continue;
15631 		}
15632 
15633 		/* Implement bpf_get_func_arg inline. */
15634 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15635 		    insn->imm == BPF_FUNC_get_func_arg) {
15636 			/* Load nr_args from ctx - 8 */
15637 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15638 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15639 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15640 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15641 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15642 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15643 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15644 			insn_buf[7] = BPF_JMP_A(1);
15645 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15646 			cnt = 9;
15647 
15648 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15649 			if (!new_prog)
15650 				return -ENOMEM;
15651 
15652 			delta    += cnt - 1;
15653 			env->prog = prog = new_prog;
15654 			insn      = new_prog->insnsi + i + delta;
15655 			continue;
15656 		}
15657 
15658 		/* Implement bpf_get_func_ret inline. */
15659 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15660 		    insn->imm == BPF_FUNC_get_func_ret) {
15661 			if (eatype == BPF_TRACE_FEXIT ||
15662 			    eatype == BPF_MODIFY_RETURN) {
15663 				/* Load nr_args from ctx - 8 */
15664 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15665 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15666 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15667 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15668 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15669 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15670 				cnt = 6;
15671 			} else {
15672 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15673 				cnt = 1;
15674 			}
15675 
15676 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15677 			if (!new_prog)
15678 				return -ENOMEM;
15679 
15680 			delta    += cnt - 1;
15681 			env->prog = prog = new_prog;
15682 			insn      = new_prog->insnsi + i + delta;
15683 			continue;
15684 		}
15685 
15686 		/* Implement get_func_arg_cnt inline. */
15687 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15688 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
15689 			/* Load nr_args from ctx - 8 */
15690 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15691 
15692 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15693 			if (!new_prog)
15694 				return -ENOMEM;
15695 
15696 			env->prog = prog = new_prog;
15697 			insn      = new_prog->insnsi + i + delta;
15698 			continue;
15699 		}
15700 
15701 		/* Implement bpf_get_func_ip inline. */
15702 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15703 		    insn->imm == BPF_FUNC_get_func_ip) {
15704 			/* Load IP address from ctx - 16 */
15705 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
15706 
15707 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15708 			if (!new_prog)
15709 				return -ENOMEM;
15710 
15711 			env->prog = prog = new_prog;
15712 			insn      = new_prog->insnsi + i + delta;
15713 			continue;
15714 		}
15715 
15716 patch_call_imm:
15717 		fn = env->ops->get_func_proto(insn->imm, env->prog);
15718 		/* all functions that have prototype and verifier allowed
15719 		 * programs to call them, must be real in-kernel functions
15720 		 */
15721 		if (!fn->func) {
15722 			verbose(env,
15723 				"kernel subsystem misconfigured func %s#%d\n",
15724 				func_id_name(insn->imm), insn->imm);
15725 			return -EFAULT;
15726 		}
15727 		insn->imm = fn->func - __bpf_call_base;
15728 	}
15729 
15730 	/* Since poke tab is now finalized, publish aux to tracker. */
15731 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
15732 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
15733 		if (!map_ptr->ops->map_poke_track ||
15734 		    !map_ptr->ops->map_poke_untrack ||
15735 		    !map_ptr->ops->map_poke_run) {
15736 			verbose(env, "bpf verifier is misconfigured\n");
15737 			return -EINVAL;
15738 		}
15739 
15740 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
15741 		if (ret < 0) {
15742 			verbose(env, "tracking tail call prog failed\n");
15743 			return ret;
15744 		}
15745 	}
15746 
15747 	sort_kfunc_descs_by_imm(env->prog);
15748 
15749 	return 0;
15750 }
15751 
15752 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
15753 					int position,
15754 					s32 stack_base,
15755 					u32 callback_subprogno,
15756 					u32 *cnt)
15757 {
15758 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
15759 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
15760 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
15761 	int reg_loop_max = BPF_REG_6;
15762 	int reg_loop_cnt = BPF_REG_7;
15763 	int reg_loop_ctx = BPF_REG_8;
15764 
15765 	struct bpf_prog *new_prog;
15766 	u32 callback_start;
15767 	u32 call_insn_offset;
15768 	s32 callback_offset;
15769 
15770 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
15771 	 * be careful to modify this code in sync.
15772 	 */
15773 	struct bpf_insn insn_buf[] = {
15774 		/* Return error and jump to the end of the patch if
15775 		 * expected number of iterations is too big.
15776 		 */
15777 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
15778 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
15779 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
15780 		/* spill R6, R7, R8 to use these as loop vars */
15781 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
15782 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
15783 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
15784 		/* initialize loop vars */
15785 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
15786 		BPF_MOV32_IMM(reg_loop_cnt, 0),
15787 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
15788 		/* loop header,
15789 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
15790 		 */
15791 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
15792 		/* callback call,
15793 		 * correct callback offset would be set after patching
15794 		 */
15795 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
15796 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
15797 		BPF_CALL_REL(0),
15798 		/* increment loop counter */
15799 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
15800 		/* jump to loop header if callback returned 0 */
15801 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
15802 		/* return value of bpf_loop,
15803 		 * set R0 to the number of iterations
15804 		 */
15805 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
15806 		/* restore original values of R6, R7, R8 */
15807 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
15808 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
15809 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
15810 	};
15811 
15812 	*cnt = ARRAY_SIZE(insn_buf);
15813 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
15814 	if (!new_prog)
15815 		return new_prog;
15816 
15817 	/* callback start is known only after patching */
15818 	callback_start = env->subprog_info[callback_subprogno].start;
15819 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
15820 	call_insn_offset = position + 12;
15821 	callback_offset = callback_start - call_insn_offset - 1;
15822 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
15823 
15824 	return new_prog;
15825 }
15826 
15827 static bool is_bpf_loop_call(struct bpf_insn *insn)
15828 {
15829 	return insn->code == (BPF_JMP | BPF_CALL) &&
15830 		insn->src_reg == 0 &&
15831 		insn->imm == BPF_FUNC_loop;
15832 }
15833 
15834 /* For all sub-programs in the program (including main) check
15835  * insn_aux_data to see if there are bpf_loop calls that require
15836  * inlining. If such calls are found the calls are replaced with a
15837  * sequence of instructions produced by `inline_bpf_loop` function and
15838  * subprog stack_depth is increased by the size of 3 registers.
15839  * This stack space is used to spill values of the R6, R7, R8.  These
15840  * registers are used to store the loop bound, counter and context
15841  * variables.
15842  */
15843 static int optimize_bpf_loop(struct bpf_verifier_env *env)
15844 {
15845 	struct bpf_subprog_info *subprogs = env->subprog_info;
15846 	int i, cur_subprog = 0, cnt, delta = 0;
15847 	struct bpf_insn *insn = env->prog->insnsi;
15848 	int insn_cnt = env->prog->len;
15849 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
15850 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15851 	u16 stack_depth_extra = 0;
15852 
15853 	for (i = 0; i < insn_cnt; i++, insn++) {
15854 		struct bpf_loop_inline_state *inline_state =
15855 			&env->insn_aux_data[i + delta].loop_inline_state;
15856 
15857 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
15858 			struct bpf_prog *new_prog;
15859 
15860 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
15861 			new_prog = inline_bpf_loop(env,
15862 						   i + delta,
15863 						   -(stack_depth + stack_depth_extra),
15864 						   inline_state->callback_subprogno,
15865 						   &cnt);
15866 			if (!new_prog)
15867 				return -ENOMEM;
15868 
15869 			delta     += cnt - 1;
15870 			env->prog  = new_prog;
15871 			insn       = new_prog->insnsi + i + delta;
15872 		}
15873 
15874 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
15875 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
15876 			cur_subprog++;
15877 			stack_depth = subprogs[cur_subprog].stack_depth;
15878 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15879 			stack_depth_extra = 0;
15880 		}
15881 	}
15882 
15883 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
15884 
15885 	return 0;
15886 }
15887 
15888 static void free_states(struct bpf_verifier_env *env)
15889 {
15890 	struct bpf_verifier_state_list *sl, *sln;
15891 	int i;
15892 
15893 	sl = env->free_list;
15894 	while (sl) {
15895 		sln = sl->next;
15896 		free_verifier_state(&sl->state, false);
15897 		kfree(sl);
15898 		sl = sln;
15899 	}
15900 	env->free_list = NULL;
15901 
15902 	if (!env->explored_states)
15903 		return;
15904 
15905 	for (i = 0; i < state_htab_size(env); i++) {
15906 		sl = env->explored_states[i];
15907 
15908 		while (sl) {
15909 			sln = sl->next;
15910 			free_verifier_state(&sl->state, false);
15911 			kfree(sl);
15912 			sl = sln;
15913 		}
15914 		env->explored_states[i] = NULL;
15915 	}
15916 }
15917 
15918 static int do_check_common(struct bpf_verifier_env *env, int subprog)
15919 {
15920 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15921 	struct bpf_verifier_state *state;
15922 	struct bpf_reg_state *regs;
15923 	int ret, i;
15924 
15925 	env->prev_linfo = NULL;
15926 	env->pass_cnt++;
15927 
15928 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
15929 	if (!state)
15930 		return -ENOMEM;
15931 	state->curframe = 0;
15932 	state->speculative = false;
15933 	state->branches = 1;
15934 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
15935 	if (!state->frame[0]) {
15936 		kfree(state);
15937 		return -ENOMEM;
15938 	}
15939 	env->cur_state = state;
15940 	init_func_state(env, state->frame[0],
15941 			BPF_MAIN_FUNC /* callsite */,
15942 			0 /* frameno */,
15943 			subprog);
15944 	state->first_insn_idx = env->subprog_info[subprog].start;
15945 	state->last_insn_idx = -1;
15946 
15947 	regs = state->frame[state->curframe]->regs;
15948 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
15949 		ret = btf_prepare_func_args(env, subprog, regs);
15950 		if (ret)
15951 			goto out;
15952 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
15953 			if (regs[i].type == PTR_TO_CTX)
15954 				mark_reg_known_zero(env, regs, i);
15955 			else if (regs[i].type == SCALAR_VALUE)
15956 				mark_reg_unknown(env, regs, i);
15957 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
15958 				const u32 mem_size = regs[i].mem_size;
15959 
15960 				mark_reg_known_zero(env, regs, i);
15961 				regs[i].mem_size = mem_size;
15962 				regs[i].id = ++env->id_gen;
15963 			}
15964 		}
15965 	} else {
15966 		/* 1st arg to a function */
15967 		regs[BPF_REG_1].type = PTR_TO_CTX;
15968 		mark_reg_known_zero(env, regs, BPF_REG_1);
15969 		ret = btf_check_subprog_arg_match(env, subprog, regs);
15970 		if (ret == -EFAULT)
15971 			/* unlikely verifier bug. abort.
15972 			 * ret == 0 and ret < 0 are sadly acceptable for
15973 			 * main() function due to backward compatibility.
15974 			 * Like socket filter program may be written as:
15975 			 * int bpf_prog(struct pt_regs *ctx)
15976 			 * and never dereference that ctx in the program.
15977 			 * 'struct pt_regs' is a type mismatch for socket
15978 			 * filter that should be using 'struct __sk_buff'.
15979 			 */
15980 			goto out;
15981 	}
15982 
15983 	ret = do_check(env);
15984 out:
15985 	/* check for NULL is necessary, since cur_state can be freed inside
15986 	 * do_check() under memory pressure.
15987 	 */
15988 	if (env->cur_state) {
15989 		free_verifier_state(env->cur_state, true);
15990 		env->cur_state = NULL;
15991 	}
15992 	while (!pop_stack(env, NULL, NULL, false));
15993 	if (!ret && pop_log)
15994 		bpf_vlog_reset(&env->log, 0);
15995 	free_states(env);
15996 	return ret;
15997 }
15998 
15999 /* Verify all global functions in a BPF program one by one based on their BTF.
16000  * All global functions must pass verification. Otherwise the whole program is rejected.
16001  * Consider:
16002  * int bar(int);
16003  * int foo(int f)
16004  * {
16005  *    return bar(f);
16006  * }
16007  * int bar(int b)
16008  * {
16009  *    ...
16010  * }
16011  * foo() will be verified first for R1=any_scalar_value. During verification it
16012  * will be assumed that bar() already verified successfully and call to bar()
16013  * from foo() will be checked for type match only. Later bar() will be verified
16014  * independently to check that it's safe for R1=any_scalar_value.
16015  */
16016 static int do_check_subprogs(struct bpf_verifier_env *env)
16017 {
16018 	struct bpf_prog_aux *aux = env->prog->aux;
16019 	int i, ret;
16020 
16021 	if (!aux->func_info)
16022 		return 0;
16023 
16024 	for (i = 1; i < env->subprog_cnt; i++) {
16025 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16026 			continue;
16027 		env->insn_idx = env->subprog_info[i].start;
16028 		WARN_ON_ONCE(env->insn_idx == 0);
16029 		ret = do_check_common(env, i);
16030 		if (ret) {
16031 			return ret;
16032 		} else if (env->log.level & BPF_LOG_LEVEL) {
16033 			verbose(env,
16034 				"Func#%d is safe for any args that match its prototype\n",
16035 				i);
16036 		}
16037 	}
16038 	return 0;
16039 }
16040 
16041 static int do_check_main(struct bpf_verifier_env *env)
16042 {
16043 	int ret;
16044 
16045 	env->insn_idx = 0;
16046 	ret = do_check_common(env, 0);
16047 	if (!ret)
16048 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16049 	return ret;
16050 }
16051 
16052 
16053 static void print_verification_stats(struct bpf_verifier_env *env)
16054 {
16055 	int i;
16056 
16057 	if (env->log.level & BPF_LOG_STATS) {
16058 		verbose(env, "verification time %lld usec\n",
16059 			div_u64(env->verification_time, 1000));
16060 		verbose(env, "stack depth ");
16061 		for (i = 0; i < env->subprog_cnt; i++) {
16062 			u32 depth = env->subprog_info[i].stack_depth;
16063 
16064 			verbose(env, "%d", depth);
16065 			if (i + 1 < env->subprog_cnt)
16066 				verbose(env, "+");
16067 		}
16068 		verbose(env, "\n");
16069 	}
16070 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16071 		"total_states %d peak_states %d mark_read %d\n",
16072 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16073 		env->max_states_per_insn, env->total_states,
16074 		env->peak_states, env->longest_mark_read_walk);
16075 }
16076 
16077 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16078 {
16079 	const struct btf_type *t, *func_proto;
16080 	const struct bpf_struct_ops *st_ops;
16081 	const struct btf_member *member;
16082 	struct bpf_prog *prog = env->prog;
16083 	u32 btf_id, member_idx;
16084 	const char *mname;
16085 
16086 	if (!prog->gpl_compatible) {
16087 		verbose(env, "struct ops programs must have a GPL compatible license\n");
16088 		return -EINVAL;
16089 	}
16090 
16091 	btf_id = prog->aux->attach_btf_id;
16092 	st_ops = bpf_struct_ops_find(btf_id);
16093 	if (!st_ops) {
16094 		verbose(env, "attach_btf_id %u is not a supported struct\n",
16095 			btf_id);
16096 		return -ENOTSUPP;
16097 	}
16098 
16099 	t = st_ops->type;
16100 	member_idx = prog->expected_attach_type;
16101 	if (member_idx >= btf_type_vlen(t)) {
16102 		verbose(env, "attach to invalid member idx %u of struct %s\n",
16103 			member_idx, st_ops->name);
16104 		return -EINVAL;
16105 	}
16106 
16107 	member = &btf_type_member(t)[member_idx];
16108 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16109 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16110 					       NULL);
16111 	if (!func_proto) {
16112 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16113 			mname, member_idx, st_ops->name);
16114 		return -EINVAL;
16115 	}
16116 
16117 	if (st_ops->check_member) {
16118 		int err = st_ops->check_member(t, member);
16119 
16120 		if (err) {
16121 			verbose(env, "attach to unsupported member %s of struct %s\n",
16122 				mname, st_ops->name);
16123 			return err;
16124 		}
16125 	}
16126 
16127 	prog->aux->attach_func_proto = func_proto;
16128 	prog->aux->attach_func_name = mname;
16129 	env->ops = st_ops->verifier_ops;
16130 
16131 	return 0;
16132 }
16133 #define SECURITY_PREFIX "security_"
16134 
16135 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16136 {
16137 	if (within_error_injection_list(addr) ||
16138 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16139 		return 0;
16140 
16141 	return -EINVAL;
16142 }
16143 
16144 /* list of non-sleepable functions that are otherwise on
16145  * ALLOW_ERROR_INJECTION list
16146  */
16147 BTF_SET_START(btf_non_sleepable_error_inject)
16148 /* Three functions below can be called from sleepable and non-sleepable context.
16149  * Assume non-sleepable from bpf safety point of view.
16150  */
16151 BTF_ID(func, __filemap_add_folio)
16152 BTF_ID(func, should_fail_alloc_page)
16153 BTF_ID(func, should_failslab)
16154 BTF_SET_END(btf_non_sleepable_error_inject)
16155 
16156 static int check_non_sleepable_error_inject(u32 btf_id)
16157 {
16158 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16159 }
16160 
16161 int bpf_check_attach_target(struct bpf_verifier_log *log,
16162 			    const struct bpf_prog *prog,
16163 			    const struct bpf_prog *tgt_prog,
16164 			    u32 btf_id,
16165 			    struct bpf_attach_target_info *tgt_info)
16166 {
16167 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16168 	const char prefix[] = "btf_trace_";
16169 	int ret = 0, subprog = -1, i;
16170 	const struct btf_type *t;
16171 	bool conservative = true;
16172 	const char *tname;
16173 	struct btf *btf;
16174 	long addr = 0;
16175 
16176 	if (!btf_id) {
16177 		bpf_log(log, "Tracing programs must provide btf_id\n");
16178 		return -EINVAL;
16179 	}
16180 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16181 	if (!btf) {
16182 		bpf_log(log,
16183 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16184 		return -EINVAL;
16185 	}
16186 	t = btf_type_by_id(btf, btf_id);
16187 	if (!t) {
16188 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16189 		return -EINVAL;
16190 	}
16191 	tname = btf_name_by_offset(btf, t->name_off);
16192 	if (!tname) {
16193 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16194 		return -EINVAL;
16195 	}
16196 	if (tgt_prog) {
16197 		struct bpf_prog_aux *aux = tgt_prog->aux;
16198 
16199 		for (i = 0; i < aux->func_info_cnt; i++)
16200 			if (aux->func_info[i].type_id == btf_id) {
16201 				subprog = i;
16202 				break;
16203 			}
16204 		if (subprog == -1) {
16205 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
16206 			return -EINVAL;
16207 		}
16208 		conservative = aux->func_info_aux[subprog].unreliable;
16209 		if (prog_extension) {
16210 			if (conservative) {
16211 				bpf_log(log,
16212 					"Cannot replace static functions\n");
16213 				return -EINVAL;
16214 			}
16215 			if (!prog->jit_requested) {
16216 				bpf_log(log,
16217 					"Extension programs should be JITed\n");
16218 				return -EINVAL;
16219 			}
16220 		}
16221 		if (!tgt_prog->jited) {
16222 			bpf_log(log, "Can attach to only JITed progs\n");
16223 			return -EINVAL;
16224 		}
16225 		if (tgt_prog->type == prog->type) {
16226 			/* Cannot fentry/fexit another fentry/fexit program.
16227 			 * Cannot attach program extension to another extension.
16228 			 * It's ok to attach fentry/fexit to extension program.
16229 			 */
16230 			bpf_log(log, "Cannot recursively attach\n");
16231 			return -EINVAL;
16232 		}
16233 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16234 		    prog_extension &&
16235 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16236 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16237 			/* Program extensions can extend all program types
16238 			 * except fentry/fexit. The reason is the following.
16239 			 * The fentry/fexit programs are used for performance
16240 			 * analysis, stats and can be attached to any program
16241 			 * type except themselves. When extension program is
16242 			 * replacing XDP function it is necessary to allow
16243 			 * performance analysis of all functions. Both original
16244 			 * XDP program and its program extension. Hence
16245 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16246 			 * allowed. If extending of fentry/fexit was allowed it
16247 			 * would be possible to create long call chain
16248 			 * fentry->extension->fentry->extension beyond
16249 			 * reasonable stack size. Hence extending fentry is not
16250 			 * allowed.
16251 			 */
16252 			bpf_log(log, "Cannot extend fentry/fexit\n");
16253 			return -EINVAL;
16254 		}
16255 	} else {
16256 		if (prog_extension) {
16257 			bpf_log(log, "Cannot replace kernel functions\n");
16258 			return -EINVAL;
16259 		}
16260 	}
16261 
16262 	switch (prog->expected_attach_type) {
16263 	case BPF_TRACE_RAW_TP:
16264 		if (tgt_prog) {
16265 			bpf_log(log,
16266 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16267 			return -EINVAL;
16268 		}
16269 		if (!btf_type_is_typedef(t)) {
16270 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
16271 				btf_id);
16272 			return -EINVAL;
16273 		}
16274 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16275 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16276 				btf_id, tname);
16277 			return -EINVAL;
16278 		}
16279 		tname += sizeof(prefix) - 1;
16280 		t = btf_type_by_id(btf, t->type);
16281 		if (!btf_type_is_ptr(t))
16282 			/* should never happen in valid vmlinux build */
16283 			return -EINVAL;
16284 		t = btf_type_by_id(btf, t->type);
16285 		if (!btf_type_is_func_proto(t))
16286 			/* should never happen in valid vmlinux build */
16287 			return -EINVAL;
16288 
16289 		break;
16290 	case BPF_TRACE_ITER:
16291 		if (!btf_type_is_func(t)) {
16292 			bpf_log(log, "attach_btf_id %u is not a function\n",
16293 				btf_id);
16294 			return -EINVAL;
16295 		}
16296 		t = btf_type_by_id(btf, t->type);
16297 		if (!btf_type_is_func_proto(t))
16298 			return -EINVAL;
16299 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16300 		if (ret)
16301 			return ret;
16302 		break;
16303 	default:
16304 		if (!prog_extension)
16305 			return -EINVAL;
16306 		fallthrough;
16307 	case BPF_MODIFY_RETURN:
16308 	case BPF_LSM_MAC:
16309 	case BPF_LSM_CGROUP:
16310 	case BPF_TRACE_FENTRY:
16311 	case BPF_TRACE_FEXIT:
16312 		if (!btf_type_is_func(t)) {
16313 			bpf_log(log, "attach_btf_id %u is not a function\n",
16314 				btf_id);
16315 			return -EINVAL;
16316 		}
16317 		if (prog_extension &&
16318 		    btf_check_type_match(log, prog, btf, t))
16319 			return -EINVAL;
16320 		t = btf_type_by_id(btf, t->type);
16321 		if (!btf_type_is_func_proto(t))
16322 			return -EINVAL;
16323 
16324 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16325 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16326 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16327 			return -EINVAL;
16328 
16329 		if (tgt_prog && conservative)
16330 			t = NULL;
16331 
16332 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16333 		if (ret < 0)
16334 			return ret;
16335 
16336 		if (tgt_prog) {
16337 			if (subprog == 0)
16338 				addr = (long) tgt_prog->bpf_func;
16339 			else
16340 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16341 		} else {
16342 			addr = kallsyms_lookup_name(tname);
16343 			if (!addr) {
16344 				bpf_log(log,
16345 					"The address of function %s cannot be found\n",
16346 					tname);
16347 				return -ENOENT;
16348 			}
16349 		}
16350 
16351 		if (prog->aux->sleepable) {
16352 			ret = -EINVAL;
16353 			switch (prog->type) {
16354 			case BPF_PROG_TYPE_TRACING:
16355 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
16356 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16357 				 */
16358 				if (!check_non_sleepable_error_inject(btf_id) &&
16359 				    within_error_injection_list(addr))
16360 					ret = 0;
16361 				break;
16362 			case BPF_PROG_TYPE_LSM:
16363 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
16364 				 * Only some of them are sleepable.
16365 				 */
16366 				if (bpf_lsm_is_sleepable_hook(btf_id))
16367 					ret = 0;
16368 				break;
16369 			default:
16370 				break;
16371 			}
16372 			if (ret) {
16373 				bpf_log(log, "%s is not sleepable\n", tname);
16374 				return ret;
16375 			}
16376 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16377 			if (tgt_prog) {
16378 				bpf_log(log, "can't modify return codes of BPF programs\n");
16379 				return -EINVAL;
16380 			}
16381 			ret = check_attach_modify_return(addr, tname);
16382 			if (ret) {
16383 				bpf_log(log, "%s() is not modifiable\n", tname);
16384 				return ret;
16385 			}
16386 		}
16387 
16388 		break;
16389 	}
16390 	tgt_info->tgt_addr = addr;
16391 	tgt_info->tgt_name = tname;
16392 	tgt_info->tgt_type = t;
16393 	return 0;
16394 }
16395 
16396 BTF_SET_START(btf_id_deny)
16397 BTF_ID_UNUSED
16398 #ifdef CONFIG_SMP
16399 BTF_ID(func, migrate_disable)
16400 BTF_ID(func, migrate_enable)
16401 #endif
16402 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16403 BTF_ID(func, rcu_read_unlock_strict)
16404 #endif
16405 BTF_SET_END(btf_id_deny)
16406 
16407 static int check_attach_btf_id(struct bpf_verifier_env *env)
16408 {
16409 	struct bpf_prog *prog = env->prog;
16410 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16411 	struct bpf_attach_target_info tgt_info = {};
16412 	u32 btf_id = prog->aux->attach_btf_id;
16413 	struct bpf_trampoline *tr;
16414 	int ret;
16415 	u64 key;
16416 
16417 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16418 		if (prog->aux->sleepable)
16419 			/* attach_btf_id checked to be zero already */
16420 			return 0;
16421 		verbose(env, "Syscall programs can only be sleepable\n");
16422 		return -EINVAL;
16423 	}
16424 
16425 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16426 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16427 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16428 		return -EINVAL;
16429 	}
16430 
16431 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16432 		return check_struct_ops_btf_id(env);
16433 
16434 	if (prog->type != BPF_PROG_TYPE_TRACING &&
16435 	    prog->type != BPF_PROG_TYPE_LSM &&
16436 	    prog->type != BPF_PROG_TYPE_EXT)
16437 		return 0;
16438 
16439 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16440 	if (ret)
16441 		return ret;
16442 
16443 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16444 		/* to make freplace equivalent to their targets, they need to
16445 		 * inherit env->ops and expected_attach_type for the rest of the
16446 		 * verification
16447 		 */
16448 		env->ops = bpf_verifier_ops[tgt_prog->type];
16449 		prog->expected_attach_type = tgt_prog->expected_attach_type;
16450 	}
16451 
16452 	/* store info about the attachment target that will be used later */
16453 	prog->aux->attach_func_proto = tgt_info.tgt_type;
16454 	prog->aux->attach_func_name = tgt_info.tgt_name;
16455 
16456 	if (tgt_prog) {
16457 		prog->aux->saved_dst_prog_type = tgt_prog->type;
16458 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16459 	}
16460 
16461 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16462 		prog->aux->attach_btf_trace = true;
16463 		return 0;
16464 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16465 		if (!bpf_iter_prog_supported(prog))
16466 			return -EINVAL;
16467 		return 0;
16468 	}
16469 
16470 	if (prog->type == BPF_PROG_TYPE_LSM) {
16471 		ret = bpf_lsm_verify_prog(&env->log, prog);
16472 		if (ret < 0)
16473 			return ret;
16474 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
16475 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
16476 		return -EINVAL;
16477 	}
16478 
16479 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16480 	tr = bpf_trampoline_get(key, &tgt_info);
16481 	if (!tr)
16482 		return -ENOMEM;
16483 
16484 	prog->aux->dst_trampoline = tr;
16485 	return 0;
16486 }
16487 
16488 struct btf *bpf_get_btf_vmlinux(void)
16489 {
16490 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16491 		mutex_lock(&bpf_verifier_lock);
16492 		if (!btf_vmlinux)
16493 			btf_vmlinux = btf_parse_vmlinux();
16494 		mutex_unlock(&bpf_verifier_lock);
16495 	}
16496 	return btf_vmlinux;
16497 }
16498 
16499 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16500 {
16501 	u64 start_time = ktime_get_ns();
16502 	struct bpf_verifier_env *env;
16503 	struct bpf_verifier_log *log;
16504 	int i, len, ret = -EINVAL;
16505 	bool is_priv;
16506 
16507 	/* no program is valid */
16508 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16509 		return -EINVAL;
16510 
16511 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
16512 	 * allocate/free it every time bpf_check() is called
16513 	 */
16514 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16515 	if (!env)
16516 		return -ENOMEM;
16517 	log = &env->log;
16518 
16519 	len = (*prog)->len;
16520 	env->insn_aux_data =
16521 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16522 	ret = -ENOMEM;
16523 	if (!env->insn_aux_data)
16524 		goto err_free_env;
16525 	for (i = 0; i < len; i++)
16526 		env->insn_aux_data[i].orig_idx = i;
16527 	env->prog = *prog;
16528 	env->ops = bpf_verifier_ops[env->prog->type];
16529 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16530 	is_priv = bpf_capable();
16531 
16532 	bpf_get_btf_vmlinux();
16533 
16534 	/* grab the mutex to protect few globals used by verifier */
16535 	if (!is_priv)
16536 		mutex_lock(&bpf_verifier_lock);
16537 
16538 	if (attr->log_level || attr->log_buf || attr->log_size) {
16539 		/* user requested verbose verifier output
16540 		 * and supplied buffer to store the verification trace
16541 		 */
16542 		log->level = attr->log_level;
16543 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16544 		log->len_total = attr->log_size;
16545 
16546 		/* log attributes have to be sane */
16547 		if (!bpf_verifier_log_attr_valid(log)) {
16548 			ret = -EINVAL;
16549 			goto err_unlock;
16550 		}
16551 	}
16552 
16553 	mark_verifier_state_clean(env);
16554 
16555 	if (IS_ERR(btf_vmlinux)) {
16556 		/* Either gcc or pahole or kernel are broken. */
16557 		verbose(env, "in-kernel BTF is malformed\n");
16558 		ret = PTR_ERR(btf_vmlinux);
16559 		goto skip_full_check;
16560 	}
16561 
16562 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16563 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16564 		env->strict_alignment = true;
16565 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16566 		env->strict_alignment = false;
16567 
16568 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16569 	env->allow_uninit_stack = bpf_allow_uninit_stack();
16570 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
16571 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
16572 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
16573 	env->bpf_capable = bpf_capable();
16574 
16575 	if (is_priv)
16576 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16577 
16578 	env->explored_states = kvcalloc(state_htab_size(env),
16579 				       sizeof(struct bpf_verifier_state_list *),
16580 				       GFP_USER);
16581 	ret = -ENOMEM;
16582 	if (!env->explored_states)
16583 		goto skip_full_check;
16584 
16585 	ret = add_subprog_and_kfunc(env);
16586 	if (ret < 0)
16587 		goto skip_full_check;
16588 
16589 	ret = check_subprogs(env);
16590 	if (ret < 0)
16591 		goto skip_full_check;
16592 
16593 	ret = check_btf_info(env, attr, uattr);
16594 	if (ret < 0)
16595 		goto skip_full_check;
16596 
16597 	ret = check_attach_btf_id(env);
16598 	if (ret)
16599 		goto skip_full_check;
16600 
16601 	ret = resolve_pseudo_ldimm64(env);
16602 	if (ret < 0)
16603 		goto skip_full_check;
16604 
16605 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
16606 		ret = bpf_prog_offload_verifier_prep(env->prog);
16607 		if (ret)
16608 			goto skip_full_check;
16609 	}
16610 
16611 	ret = check_cfg(env);
16612 	if (ret < 0)
16613 		goto skip_full_check;
16614 
16615 	ret = do_check_subprogs(env);
16616 	ret = ret ?: do_check_main(env);
16617 
16618 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16619 		ret = bpf_prog_offload_finalize(env);
16620 
16621 skip_full_check:
16622 	kvfree(env->explored_states);
16623 
16624 	if (ret == 0)
16625 		ret = check_max_stack_depth(env);
16626 
16627 	/* instruction rewrites happen after this point */
16628 	if (ret == 0)
16629 		ret = optimize_bpf_loop(env);
16630 
16631 	if (is_priv) {
16632 		if (ret == 0)
16633 			opt_hard_wire_dead_code_branches(env);
16634 		if (ret == 0)
16635 			ret = opt_remove_dead_code(env);
16636 		if (ret == 0)
16637 			ret = opt_remove_nops(env);
16638 	} else {
16639 		if (ret == 0)
16640 			sanitize_dead_code(env);
16641 	}
16642 
16643 	if (ret == 0)
16644 		/* program is valid, convert *(u32*)(ctx + off) accesses */
16645 		ret = convert_ctx_accesses(env);
16646 
16647 	if (ret == 0)
16648 		ret = do_misc_fixups(env);
16649 
16650 	/* do 32-bit optimization after insn patching has done so those patched
16651 	 * insns could be handled correctly.
16652 	 */
16653 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16654 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16655 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16656 								     : false;
16657 	}
16658 
16659 	if (ret == 0)
16660 		ret = fixup_call_args(env);
16661 
16662 	env->verification_time = ktime_get_ns() - start_time;
16663 	print_verification_stats(env);
16664 	env->prog->aux->verified_insns = env->insn_processed;
16665 
16666 	if (log->level && bpf_verifier_log_full(log))
16667 		ret = -ENOSPC;
16668 	if (log->level && !log->ubuf) {
16669 		ret = -EFAULT;
16670 		goto err_release_maps;
16671 	}
16672 
16673 	if (ret)
16674 		goto err_release_maps;
16675 
16676 	if (env->used_map_cnt) {
16677 		/* if program passed verifier, update used_maps in bpf_prog_info */
16678 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
16679 							  sizeof(env->used_maps[0]),
16680 							  GFP_KERNEL);
16681 
16682 		if (!env->prog->aux->used_maps) {
16683 			ret = -ENOMEM;
16684 			goto err_release_maps;
16685 		}
16686 
16687 		memcpy(env->prog->aux->used_maps, env->used_maps,
16688 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
16689 		env->prog->aux->used_map_cnt = env->used_map_cnt;
16690 	}
16691 	if (env->used_btf_cnt) {
16692 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
16693 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
16694 							  sizeof(env->used_btfs[0]),
16695 							  GFP_KERNEL);
16696 		if (!env->prog->aux->used_btfs) {
16697 			ret = -ENOMEM;
16698 			goto err_release_maps;
16699 		}
16700 
16701 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
16702 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
16703 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
16704 	}
16705 	if (env->used_map_cnt || env->used_btf_cnt) {
16706 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
16707 		 * bpf_ld_imm64 instructions
16708 		 */
16709 		convert_pseudo_ld_imm64(env);
16710 	}
16711 
16712 	adjust_btf_func(env);
16713 
16714 err_release_maps:
16715 	if (!env->prog->aux->used_maps)
16716 		/* if we didn't copy map pointers into bpf_prog_info, release
16717 		 * them now. Otherwise free_used_maps() will release them.
16718 		 */
16719 		release_maps(env);
16720 	if (!env->prog->aux->used_btfs)
16721 		release_btfs(env);
16722 
16723 	/* extension progs temporarily inherit the attach_type of their targets
16724 	   for verification purposes, so set it back to zero before returning
16725 	 */
16726 	if (env->prog->type == BPF_PROG_TYPE_EXT)
16727 		env->prog->expected_attach_type = 0;
16728 
16729 	*prog = env->prog;
16730 err_unlock:
16731 	if (!is_priv)
16732 		mutex_unlock(&bpf_verifier_lock);
16733 	vfree(env->insn_aux_data);
16734 err_free_env:
16735 	kfree(env);
16736 	return ret;
16737 }
16738