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