xref: /openbmc/linux/kernel/bpf/verifier.c (revision 15b209cd)
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 
27 #include "disasm.h"
28 
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
31 	[_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #define BPF_LINK_TYPE(_id, _name)
34 #include <linux/bpf_types.h>
35 #undef BPF_PROG_TYPE
36 #undef BPF_MAP_TYPE
37 #undef BPF_LINK_TYPE
38 };
39 
40 /* bpf_check() is a static code analyzer that walks eBPF program
41  * instruction by instruction and updates register/stack state.
42  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43  *
44  * The first pass is depth-first-search to check that the program is a DAG.
45  * It rejects the following programs:
46  * - larger than BPF_MAXINSNS insns
47  * - if loop is present (detected via back-edge)
48  * - unreachable insns exist (shouldn't be a forest. program = one function)
49  * - out of bounds or malformed jumps
50  * The second pass is all possible path descent from the 1st insn.
51  * Since it's analyzing all paths through the program, the length of the
52  * analysis is limited to 64k insn, which may be hit even if total number of
53  * insn is less then 4K, but there are too many branches that change stack/regs.
54  * Number of 'branches to be analyzed' is limited to 1k
55  *
56  * On entry to each instruction, each register has a type, and the instruction
57  * changes the types of the registers depending on instruction semantics.
58  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59  * copied to R1.
60  *
61  * All registers are 64-bit.
62  * R0 - return register
63  * R1-R5 argument passing registers
64  * R6-R9 callee saved registers
65  * R10 - frame pointer read-only
66  *
67  * At the start of BPF program the register R1 contains a pointer to bpf_context
68  * and has type PTR_TO_CTX.
69  *
70  * Verifier tracks arithmetic operations on pointers in case:
71  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
72  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
73  * 1st insn copies R10 (which has FRAME_PTR) type into R1
74  * and 2nd arithmetic instruction is pattern matched to recognize
75  * that it wants to construct a pointer to some element within stack.
76  * So after 2nd insn, the register R1 has type PTR_TO_STACK
77  * (and -20 constant is saved for further stack bounds checking).
78  * Meaning that this reg is a pointer to stack plus known immediate constant.
79  *
80  * Most of the time the registers have SCALAR_VALUE type, which
81  * means the register has some value, but it's not a valid pointer.
82  * (like pointer plus pointer becomes SCALAR_VALUE type)
83  *
84  * When verifier sees load or store instructions the type of base register
85  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
86  * four pointer types recognized by check_mem_access() function.
87  *
88  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
89  * and the range of [ptr, ptr + map's value_size) is accessible.
90  *
91  * registers used to pass values to function calls are checked against
92  * function argument constraints.
93  *
94  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
95  * It means that the register type passed to this function must be
96  * PTR_TO_STACK and it will be used inside the function as
97  * 'pointer to map element key'
98  *
99  * For example the argument constraints for bpf_map_lookup_elem():
100  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
101  *   .arg1_type = ARG_CONST_MAP_PTR,
102  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
103  *
104  * ret_type says that this function returns 'pointer to map elem value or null'
105  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
106  * 2nd argument should be a pointer to stack, which will be used inside
107  * the helper function as a pointer to map element key.
108  *
109  * On the kernel side the helper function looks like:
110  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111  * {
112  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
113  *    void *key = (void *) (unsigned long) r2;
114  *    void *value;
115  *
116  *    here kernel can access 'key' and 'map' pointers safely, knowing that
117  *    [key, key + map->key_size) bytes are valid and were initialized on
118  *    the stack of eBPF program.
119  * }
120  *
121  * Corresponding eBPF program may look like:
122  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
123  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
124  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
125  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
126  * here verifier looks at prototype of map_lookup_elem() and sees:
127  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
128  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129  *
130  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
131  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
132  * and were initialized prior to this call.
133  * If it's ok, then verifier allows this BPF_CALL insn and looks at
134  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
135  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
136  * returns either pointer to map value or NULL.
137  *
138  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
139  * insn, the register holding that pointer in the true branch changes state to
140  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
141  * branch. See check_cond_jmp_op().
142  *
143  * After the call R0 is set to return type of the function and registers R1-R5
144  * are set to NOT_INIT to indicate that they are no longer readable.
145  *
146  * The following reference types represent a potential reference to a kernel
147  * resource which, after first being allocated, must be checked and freed by
148  * the BPF program:
149  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150  *
151  * When the verifier sees a helper call return a reference type, it allocates a
152  * pointer id for the reference and stores it in the current function state.
153  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
154  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
155  * passes through a NULL-check conditional. For the branch wherein the state is
156  * changed to CONST_IMM, the verifier releases the reference.
157  *
158  * For each helper function that allocates a reference, such as
159  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
160  * bpf_sk_release(). When a reference type passes into the release function,
161  * the verifier also releases the reference. If any unchecked or unreleased
162  * reference remains at the end of the program, the verifier rejects it.
163  */
164 
165 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
166 struct bpf_verifier_stack_elem {
167 	/* verifer state is 'st'
168 	 * before processing instruction 'insn_idx'
169 	 * and after processing instruction 'prev_insn_idx'
170 	 */
171 	struct bpf_verifier_state st;
172 	int insn_idx;
173 	int prev_insn_idx;
174 	struct bpf_verifier_stack_elem *next;
175 	/* length of verifier log at the time this state was pushed on stack */
176 	u32 log_pos;
177 };
178 
179 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
180 #define BPF_COMPLEXITY_LIMIT_STATES	64
181 
182 #define BPF_MAP_KEY_POISON	(1ULL << 63)
183 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
184 
185 #define BPF_MAP_PTR_UNPRIV	1UL
186 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
187 					  POISON_POINTER_DELTA))
188 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189 
190 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
191 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
192 
193 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
194 {
195 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
196 }
197 
198 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
199 {
200 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
201 }
202 
203 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
204 			      const struct bpf_map *map, bool unpriv)
205 {
206 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
207 	unpriv |= bpf_map_ptr_unpriv(aux);
208 	aux->map_ptr_state = (unsigned long)map |
209 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
210 }
211 
212 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
213 {
214 	return aux->map_key_state & BPF_MAP_KEY_POISON;
215 }
216 
217 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
218 {
219 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
220 }
221 
222 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
223 {
224 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
225 }
226 
227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
228 {
229 	bool poisoned = bpf_map_key_poisoned(aux);
230 
231 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
232 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
233 }
234 
235 static bool bpf_pseudo_call(const struct bpf_insn *insn)
236 {
237 	return insn->code == (BPF_JMP | BPF_CALL) &&
238 	       insn->src_reg == BPF_PSEUDO_CALL;
239 }
240 
241 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
242 {
243 	return insn->code == (BPF_JMP | BPF_CALL) &&
244 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
245 }
246 
247 struct bpf_call_arg_meta {
248 	struct bpf_map *map_ptr;
249 	bool raw_mode;
250 	bool pkt_access;
251 	u8 release_regno;
252 	int regno;
253 	int access_size;
254 	int mem_size;
255 	u64 msize_max_value;
256 	int ref_obj_id;
257 	int map_uid;
258 	int func_id;
259 	struct btf *btf;
260 	u32 btf_id;
261 	struct btf *ret_btf;
262 	u32 ret_btf_id;
263 	u32 subprogno;
264 	struct bpf_map_value_off_desc *kptr_off_desc;
265 	u8 uninit_dynptr_regno;
266 };
267 
268 struct btf *btf_vmlinux;
269 
270 static DEFINE_MUTEX(bpf_verifier_lock);
271 
272 static const struct bpf_line_info *
273 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
274 {
275 	const struct bpf_line_info *linfo;
276 	const struct bpf_prog *prog;
277 	u32 i, nr_linfo;
278 
279 	prog = env->prog;
280 	nr_linfo = prog->aux->nr_linfo;
281 
282 	if (!nr_linfo || insn_off >= prog->len)
283 		return NULL;
284 
285 	linfo = prog->aux->linfo;
286 	for (i = 1; i < nr_linfo; i++)
287 		if (insn_off < linfo[i].insn_off)
288 			break;
289 
290 	return &linfo[i - 1];
291 }
292 
293 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
294 		       va_list args)
295 {
296 	unsigned int n;
297 
298 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
299 
300 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
301 		  "verifier log line truncated - local buffer too short\n");
302 
303 	if (log->level == BPF_LOG_KERNEL) {
304 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
305 
306 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
307 		return;
308 	}
309 
310 	n = min(log->len_total - log->len_used - 1, n);
311 	log->kbuf[n] = '\0';
312 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
313 		log->len_used += n;
314 	else
315 		log->ubuf = NULL;
316 }
317 
318 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
319 {
320 	char zero = 0;
321 
322 	if (!bpf_verifier_log_needed(log))
323 		return;
324 
325 	log->len_used = new_pos;
326 	if (put_user(zero, log->ubuf + new_pos))
327 		log->ubuf = NULL;
328 }
329 
330 /* log_level controls verbosity level of eBPF verifier.
331  * bpf_verifier_log_write() is used to dump the verification trace to the log,
332  * so the user can figure out what's wrong with the program
333  */
334 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
335 					   const char *fmt, ...)
336 {
337 	va_list args;
338 
339 	if (!bpf_verifier_log_needed(&env->log))
340 		return;
341 
342 	va_start(args, fmt);
343 	bpf_verifier_vlog(&env->log, fmt, args);
344 	va_end(args);
345 }
346 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
347 
348 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
349 {
350 	struct bpf_verifier_env *env = private_data;
351 	va_list args;
352 
353 	if (!bpf_verifier_log_needed(&env->log))
354 		return;
355 
356 	va_start(args, fmt);
357 	bpf_verifier_vlog(&env->log, fmt, args);
358 	va_end(args);
359 }
360 
361 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
362 			    const char *fmt, ...)
363 {
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool reg_type_not_null(enum bpf_reg_type type)
444 {
445 	return type == PTR_TO_SOCKET ||
446 		type == PTR_TO_TCP_SOCK ||
447 		type == PTR_TO_MAP_VALUE ||
448 		type == PTR_TO_MAP_KEY ||
449 		type == PTR_TO_SOCK_COMMON;
450 }
451 
452 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
453 {
454 	return reg->type == PTR_TO_MAP_VALUE &&
455 		map_value_has_spin_lock(reg->map_ptr);
456 }
457 
458 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
459 {
460 	type = base_type(type);
461 	return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
462 		type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
463 }
464 
465 static bool type_is_rdonly_mem(u32 type)
466 {
467 	return type & MEM_RDONLY;
468 }
469 
470 static bool type_may_be_null(u32 type)
471 {
472 	return type & PTR_MAYBE_NULL;
473 }
474 
475 static bool is_acquire_function(enum bpf_func_id func_id,
476 				const struct bpf_map *map)
477 {
478 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 
480 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
481 	    func_id == BPF_FUNC_sk_lookup_udp ||
482 	    func_id == BPF_FUNC_skc_lookup_tcp ||
483 	    func_id == BPF_FUNC_ringbuf_reserve ||
484 	    func_id == BPF_FUNC_kptr_xchg)
485 		return true;
486 
487 	if (func_id == BPF_FUNC_map_lookup_elem &&
488 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
489 	     map_type == BPF_MAP_TYPE_SOCKHASH))
490 		return true;
491 
492 	return false;
493 }
494 
495 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_tcp_sock ||
498 		func_id == BPF_FUNC_sk_fullsock ||
499 		func_id == BPF_FUNC_skc_to_tcp_sock ||
500 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
501 		func_id == BPF_FUNC_skc_to_udp6_sock ||
502 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
507 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_dynptr_data;
510 }
511 
512 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
513 					const struct bpf_map *map)
514 {
515 	int ref_obj_uses = 0;
516 
517 	if (is_ptr_cast_function(func_id))
518 		ref_obj_uses++;
519 	if (is_acquire_function(func_id, map))
520 		ref_obj_uses++;
521 	if (is_dynptr_ref_function(func_id))
522 		ref_obj_uses++;
523 
524 	return ref_obj_uses > 1;
525 }
526 
527 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
528 {
529 	return BPF_CLASS(insn->code) == BPF_STX &&
530 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
531 	       insn->imm == BPF_CMPXCHG;
532 }
533 
534 /* string representation of 'enum bpf_reg_type'
535  *
536  * Note that reg_type_str() can not appear more than once in a single verbose()
537  * statement.
538  */
539 static const char *reg_type_str(struct bpf_verifier_env *env,
540 				enum bpf_reg_type type)
541 {
542 	char postfix[16] = {0}, prefix[32] = {0};
543 	static const char * const str[] = {
544 		[NOT_INIT]		= "?",
545 		[SCALAR_VALUE]		= "scalar",
546 		[PTR_TO_CTX]		= "ctx",
547 		[CONST_PTR_TO_MAP]	= "map_ptr",
548 		[PTR_TO_MAP_VALUE]	= "map_value",
549 		[PTR_TO_STACK]		= "fp",
550 		[PTR_TO_PACKET]		= "pkt",
551 		[PTR_TO_PACKET_META]	= "pkt_meta",
552 		[PTR_TO_PACKET_END]	= "pkt_end",
553 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
554 		[PTR_TO_SOCKET]		= "sock",
555 		[PTR_TO_SOCK_COMMON]	= "sock_common",
556 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
557 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
558 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
559 		[PTR_TO_BTF_ID]		= "ptr_",
560 		[PTR_TO_MEM]		= "mem",
561 		[PTR_TO_BUF]		= "buf",
562 		[PTR_TO_FUNC]		= "func",
563 		[PTR_TO_MAP_KEY]	= "map_key",
564 	};
565 
566 	if (type & PTR_MAYBE_NULL) {
567 		if (base_type(type) == PTR_TO_BTF_ID)
568 			strncpy(postfix, "or_null_", 16);
569 		else
570 			strncpy(postfix, "_or_null", 16);
571 	}
572 
573 	if (type & MEM_RDONLY)
574 		strncpy(prefix, "rdonly_", 32);
575 	if (type & MEM_ALLOC)
576 		strncpy(prefix, "alloc_", 32);
577 	if (type & MEM_USER)
578 		strncpy(prefix, "user_", 32);
579 	if (type & MEM_PERCPU)
580 		strncpy(prefix, "percpu_", 32);
581 	if (type & PTR_UNTRUSTED)
582 		strncpy(prefix, "untrusted_", 32);
583 
584 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
585 		 prefix, str[base_type(type)], postfix);
586 	return env->type_str_buf;
587 }
588 
589 static char slot_type_char[] = {
590 	[STACK_INVALID]	= '?',
591 	[STACK_SPILL]	= 'r',
592 	[STACK_MISC]	= 'm',
593 	[STACK_ZERO]	= '0',
594 	[STACK_DYNPTR]	= 'd',
595 };
596 
597 static void print_liveness(struct bpf_verifier_env *env,
598 			   enum bpf_reg_liveness live)
599 {
600 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
601 	    verbose(env, "_");
602 	if (live & REG_LIVE_READ)
603 		verbose(env, "r");
604 	if (live & REG_LIVE_WRITTEN)
605 		verbose(env, "w");
606 	if (live & REG_LIVE_DONE)
607 		verbose(env, "D");
608 }
609 
610 static int get_spi(s32 off)
611 {
612 	return (-off - 1) / BPF_REG_SIZE;
613 }
614 
615 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
616 {
617 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
618 
619 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
620 	 * within [0, allocated_stack).
621 	 *
622 	 * Please note that the spi grows downwards. For example, a dynptr
623 	 * takes the size of two stack slots; the first slot will be at
624 	 * spi and the second slot will be at spi - 1.
625 	 */
626 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
627 }
628 
629 static struct bpf_func_state *func(struct bpf_verifier_env *env,
630 				   const struct bpf_reg_state *reg)
631 {
632 	struct bpf_verifier_state *cur = env->cur_state;
633 
634 	return cur->frame[reg->frameno];
635 }
636 
637 static const char *kernel_type_name(const struct btf* btf, u32 id)
638 {
639 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
640 }
641 
642 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
643 {
644 	env->scratched_regs |= 1U << regno;
645 }
646 
647 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
648 {
649 	env->scratched_stack_slots |= 1ULL << spi;
650 }
651 
652 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
653 {
654 	return (env->scratched_regs >> regno) & 1;
655 }
656 
657 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
658 {
659 	return (env->scratched_stack_slots >> regno) & 1;
660 }
661 
662 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
663 {
664 	return env->scratched_regs || env->scratched_stack_slots;
665 }
666 
667 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
668 {
669 	env->scratched_regs = 0U;
670 	env->scratched_stack_slots = 0ULL;
671 }
672 
673 /* Used for printing the entire verifier state. */
674 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
675 {
676 	env->scratched_regs = ~0U;
677 	env->scratched_stack_slots = ~0ULL;
678 }
679 
680 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
681 {
682 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
683 	case DYNPTR_TYPE_LOCAL:
684 		return BPF_DYNPTR_TYPE_LOCAL;
685 	case DYNPTR_TYPE_RINGBUF:
686 		return BPF_DYNPTR_TYPE_RINGBUF;
687 	default:
688 		return BPF_DYNPTR_TYPE_INVALID;
689 	}
690 }
691 
692 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
693 {
694 	return type == BPF_DYNPTR_TYPE_RINGBUF;
695 }
696 
697 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
698 				   enum bpf_arg_type arg_type, int insn_idx)
699 {
700 	struct bpf_func_state *state = func(env, reg);
701 	enum bpf_dynptr_type type;
702 	int spi, i, id;
703 
704 	spi = get_spi(reg->off);
705 
706 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
707 		return -EINVAL;
708 
709 	for (i = 0; i < BPF_REG_SIZE; i++) {
710 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
711 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
712 	}
713 
714 	type = arg_to_dynptr_type(arg_type);
715 	if (type == BPF_DYNPTR_TYPE_INVALID)
716 		return -EINVAL;
717 
718 	state->stack[spi].spilled_ptr.dynptr.first_slot = true;
719 	state->stack[spi].spilled_ptr.dynptr.type = type;
720 	state->stack[spi - 1].spilled_ptr.dynptr.type = type;
721 
722 	if (dynptr_type_refcounted(type)) {
723 		/* The id is used to track proper releasing */
724 		id = acquire_reference_state(env, insn_idx);
725 		if (id < 0)
726 			return id;
727 
728 		state->stack[spi].spilled_ptr.id = id;
729 		state->stack[spi - 1].spilled_ptr.id = id;
730 	}
731 
732 	return 0;
733 }
734 
735 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
736 {
737 	struct bpf_func_state *state = func(env, reg);
738 	int spi, i;
739 
740 	spi = get_spi(reg->off);
741 
742 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
743 		return -EINVAL;
744 
745 	for (i = 0; i < BPF_REG_SIZE; i++) {
746 		state->stack[spi].slot_type[i] = STACK_INVALID;
747 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
748 	}
749 
750 	/* Invalidate any slices associated with this dynptr */
751 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
752 		release_reference(env, state->stack[spi].spilled_ptr.id);
753 		state->stack[spi].spilled_ptr.id = 0;
754 		state->stack[spi - 1].spilled_ptr.id = 0;
755 	}
756 
757 	state->stack[spi].spilled_ptr.dynptr.first_slot = false;
758 	state->stack[spi].spilled_ptr.dynptr.type = 0;
759 	state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
760 
761 	return 0;
762 }
763 
764 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
765 {
766 	struct bpf_func_state *state = func(env, reg);
767 	int spi = get_spi(reg->off);
768 	int i;
769 
770 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
771 		return true;
772 
773 	for (i = 0; i < BPF_REG_SIZE; i++) {
774 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
775 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
776 			return false;
777 	}
778 
779 	return true;
780 }
781 
782 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
783 				     enum bpf_arg_type arg_type)
784 {
785 	struct bpf_func_state *state = func(env, reg);
786 	int spi = get_spi(reg->off);
787 	int i;
788 
789 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
790 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
791 		return false;
792 
793 	for (i = 0; i < BPF_REG_SIZE; i++) {
794 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
795 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
796 			return false;
797 	}
798 
799 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
800 	if (arg_type == ARG_PTR_TO_DYNPTR)
801 		return true;
802 
803 	return state->stack[spi].spilled_ptr.dynptr.type == arg_to_dynptr_type(arg_type);
804 }
805 
806 /* The reg state of a pointer or a bounded scalar was saved when
807  * it was spilled to the stack.
808  */
809 static bool is_spilled_reg(const struct bpf_stack_state *stack)
810 {
811 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
812 }
813 
814 static void scrub_spilled_slot(u8 *stype)
815 {
816 	if (*stype != STACK_INVALID)
817 		*stype = STACK_MISC;
818 }
819 
820 static void print_verifier_state(struct bpf_verifier_env *env,
821 				 const struct bpf_func_state *state,
822 				 bool print_all)
823 {
824 	const struct bpf_reg_state *reg;
825 	enum bpf_reg_type t;
826 	int i;
827 
828 	if (state->frameno)
829 		verbose(env, " frame%d:", state->frameno);
830 	for (i = 0; i < MAX_BPF_REG; i++) {
831 		reg = &state->regs[i];
832 		t = reg->type;
833 		if (t == NOT_INIT)
834 			continue;
835 		if (!print_all && !reg_scratched(env, i))
836 			continue;
837 		verbose(env, " R%d", i);
838 		print_liveness(env, reg->live);
839 		verbose(env, "=");
840 		if (t == SCALAR_VALUE && reg->precise)
841 			verbose(env, "P");
842 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
843 		    tnum_is_const(reg->var_off)) {
844 			/* reg->off should be 0 for SCALAR_VALUE */
845 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
846 			verbose(env, "%lld", reg->var_off.value + reg->off);
847 		} else {
848 			const char *sep = "";
849 
850 			verbose(env, "%s", reg_type_str(env, t));
851 			if (base_type(t) == PTR_TO_BTF_ID)
852 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
853 			verbose(env, "(");
854 /*
855  * _a stands for append, was shortened to avoid multiline statements below.
856  * This macro is used to output a comma separated list of attributes.
857  */
858 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
859 
860 			if (reg->id)
861 				verbose_a("id=%d", reg->id);
862 			if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
863 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
864 			if (t != SCALAR_VALUE)
865 				verbose_a("off=%d", reg->off);
866 			if (type_is_pkt_pointer(t))
867 				verbose_a("r=%d", reg->range);
868 			else if (base_type(t) == CONST_PTR_TO_MAP ||
869 				 base_type(t) == PTR_TO_MAP_KEY ||
870 				 base_type(t) == PTR_TO_MAP_VALUE)
871 				verbose_a("ks=%d,vs=%d",
872 					  reg->map_ptr->key_size,
873 					  reg->map_ptr->value_size);
874 			if (tnum_is_const(reg->var_off)) {
875 				/* Typically an immediate SCALAR_VALUE, but
876 				 * could be a pointer whose offset is too big
877 				 * for reg->off
878 				 */
879 				verbose_a("imm=%llx", reg->var_off.value);
880 			} else {
881 				if (reg->smin_value != reg->umin_value &&
882 				    reg->smin_value != S64_MIN)
883 					verbose_a("smin=%lld", (long long)reg->smin_value);
884 				if (reg->smax_value != reg->umax_value &&
885 				    reg->smax_value != S64_MAX)
886 					verbose_a("smax=%lld", (long long)reg->smax_value);
887 				if (reg->umin_value != 0)
888 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
889 				if (reg->umax_value != U64_MAX)
890 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
891 				if (!tnum_is_unknown(reg->var_off)) {
892 					char tn_buf[48];
893 
894 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
895 					verbose_a("var_off=%s", tn_buf);
896 				}
897 				if (reg->s32_min_value != reg->smin_value &&
898 				    reg->s32_min_value != S32_MIN)
899 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
900 				if (reg->s32_max_value != reg->smax_value &&
901 				    reg->s32_max_value != S32_MAX)
902 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
903 				if (reg->u32_min_value != reg->umin_value &&
904 				    reg->u32_min_value != U32_MIN)
905 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
906 				if (reg->u32_max_value != reg->umax_value &&
907 				    reg->u32_max_value != U32_MAX)
908 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
909 			}
910 #undef verbose_a
911 
912 			verbose(env, ")");
913 		}
914 	}
915 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
916 		char types_buf[BPF_REG_SIZE + 1];
917 		bool valid = false;
918 		int j;
919 
920 		for (j = 0; j < BPF_REG_SIZE; j++) {
921 			if (state->stack[i].slot_type[j] != STACK_INVALID)
922 				valid = true;
923 			types_buf[j] = slot_type_char[
924 					state->stack[i].slot_type[j]];
925 		}
926 		types_buf[BPF_REG_SIZE] = 0;
927 		if (!valid)
928 			continue;
929 		if (!print_all && !stack_slot_scratched(env, i))
930 			continue;
931 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
932 		print_liveness(env, state->stack[i].spilled_ptr.live);
933 		if (is_spilled_reg(&state->stack[i])) {
934 			reg = &state->stack[i].spilled_ptr;
935 			t = reg->type;
936 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
937 			if (t == SCALAR_VALUE && reg->precise)
938 				verbose(env, "P");
939 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
940 				verbose(env, "%lld", reg->var_off.value + reg->off);
941 		} else {
942 			verbose(env, "=%s", types_buf);
943 		}
944 	}
945 	if (state->acquired_refs && state->refs[0].id) {
946 		verbose(env, " refs=%d", state->refs[0].id);
947 		for (i = 1; i < state->acquired_refs; i++)
948 			if (state->refs[i].id)
949 				verbose(env, ",%d", state->refs[i].id);
950 	}
951 	if (state->in_callback_fn)
952 		verbose(env, " cb");
953 	if (state->in_async_callback_fn)
954 		verbose(env, " async_cb");
955 	verbose(env, "\n");
956 	mark_verifier_state_clean(env);
957 }
958 
959 static inline u32 vlog_alignment(u32 pos)
960 {
961 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
962 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
963 }
964 
965 static void print_insn_state(struct bpf_verifier_env *env,
966 			     const struct bpf_func_state *state)
967 {
968 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
969 		/* remove new line character */
970 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
971 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
972 	} else {
973 		verbose(env, "%d:", env->insn_idx);
974 	}
975 	print_verifier_state(env, state, false);
976 }
977 
978 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
979  * small to hold src. This is different from krealloc since we don't want to preserve
980  * the contents of dst.
981  *
982  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
983  * not be allocated.
984  */
985 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
986 {
987 	size_t bytes;
988 
989 	if (ZERO_OR_NULL_PTR(src))
990 		goto out;
991 
992 	if (unlikely(check_mul_overflow(n, size, &bytes)))
993 		return NULL;
994 
995 	if (ksize(dst) < bytes) {
996 		kfree(dst);
997 		dst = kmalloc_track_caller(bytes, flags);
998 		if (!dst)
999 			return NULL;
1000 	}
1001 
1002 	memcpy(dst, src, bytes);
1003 out:
1004 	return dst ? dst : ZERO_SIZE_PTR;
1005 }
1006 
1007 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1008  * small to hold new_n items. new items are zeroed out if the array grows.
1009  *
1010  * Contrary to krealloc_array, does not free arr if new_n is zero.
1011  */
1012 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1013 {
1014 	if (!new_n || old_n == new_n)
1015 		goto out;
1016 
1017 	arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1018 	if (!arr)
1019 		return NULL;
1020 
1021 	if (new_n > old_n)
1022 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1023 
1024 out:
1025 	return arr ? arr : ZERO_SIZE_PTR;
1026 }
1027 
1028 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1029 {
1030 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1031 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1032 	if (!dst->refs)
1033 		return -ENOMEM;
1034 
1035 	dst->acquired_refs = src->acquired_refs;
1036 	return 0;
1037 }
1038 
1039 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1040 {
1041 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1042 
1043 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1044 				GFP_KERNEL);
1045 	if (!dst->stack)
1046 		return -ENOMEM;
1047 
1048 	dst->allocated_stack = src->allocated_stack;
1049 	return 0;
1050 }
1051 
1052 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1053 {
1054 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1055 				    sizeof(struct bpf_reference_state));
1056 	if (!state->refs)
1057 		return -ENOMEM;
1058 
1059 	state->acquired_refs = n;
1060 	return 0;
1061 }
1062 
1063 static int grow_stack_state(struct bpf_func_state *state, int size)
1064 {
1065 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1066 
1067 	if (old_n >= n)
1068 		return 0;
1069 
1070 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1071 	if (!state->stack)
1072 		return -ENOMEM;
1073 
1074 	state->allocated_stack = size;
1075 	return 0;
1076 }
1077 
1078 /* Acquire a pointer id from the env and update the state->refs to include
1079  * this new pointer reference.
1080  * On success, returns a valid pointer id to associate with the register
1081  * On failure, returns a negative errno.
1082  */
1083 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1084 {
1085 	struct bpf_func_state *state = cur_func(env);
1086 	int new_ofs = state->acquired_refs;
1087 	int id, err;
1088 
1089 	err = resize_reference_state(state, state->acquired_refs + 1);
1090 	if (err)
1091 		return err;
1092 	id = ++env->id_gen;
1093 	state->refs[new_ofs].id = id;
1094 	state->refs[new_ofs].insn_idx = insn_idx;
1095 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1096 
1097 	return id;
1098 }
1099 
1100 /* release function corresponding to acquire_reference_state(). Idempotent. */
1101 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1102 {
1103 	int i, last_idx;
1104 
1105 	last_idx = state->acquired_refs - 1;
1106 	for (i = 0; i < state->acquired_refs; i++) {
1107 		if (state->refs[i].id == ptr_id) {
1108 			/* Cannot release caller references in callbacks */
1109 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1110 				return -EINVAL;
1111 			if (last_idx && i != last_idx)
1112 				memcpy(&state->refs[i], &state->refs[last_idx],
1113 				       sizeof(*state->refs));
1114 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1115 			state->acquired_refs--;
1116 			return 0;
1117 		}
1118 	}
1119 	return -EINVAL;
1120 }
1121 
1122 static void free_func_state(struct bpf_func_state *state)
1123 {
1124 	if (!state)
1125 		return;
1126 	kfree(state->refs);
1127 	kfree(state->stack);
1128 	kfree(state);
1129 }
1130 
1131 static void clear_jmp_history(struct bpf_verifier_state *state)
1132 {
1133 	kfree(state->jmp_history);
1134 	state->jmp_history = NULL;
1135 	state->jmp_history_cnt = 0;
1136 }
1137 
1138 static void free_verifier_state(struct bpf_verifier_state *state,
1139 				bool free_self)
1140 {
1141 	int i;
1142 
1143 	for (i = 0; i <= state->curframe; i++) {
1144 		free_func_state(state->frame[i]);
1145 		state->frame[i] = NULL;
1146 	}
1147 	clear_jmp_history(state);
1148 	if (free_self)
1149 		kfree(state);
1150 }
1151 
1152 /* copy verifier state from src to dst growing dst stack space
1153  * when necessary to accommodate larger src stack
1154  */
1155 static int copy_func_state(struct bpf_func_state *dst,
1156 			   const struct bpf_func_state *src)
1157 {
1158 	int err;
1159 
1160 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1161 	err = copy_reference_state(dst, src);
1162 	if (err)
1163 		return err;
1164 	return copy_stack_state(dst, src);
1165 }
1166 
1167 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1168 			       const struct bpf_verifier_state *src)
1169 {
1170 	struct bpf_func_state *dst;
1171 	int i, err;
1172 
1173 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1174 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1175 					    GFP_USER);
1176 	if (!dst_state->jmp_history)
1177 		return -ENOMEM;
1178 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1179 
1180 	/* if dst has more stack frames then src frame, free them */
1181 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1182 		free_func_state(dst_state->frame[i]);
1183 		dst_state->frame[i] = NULL;
1184 	}
1185 	dst_state->speculative = src->speculative;
1186 	dst_state->curframe = src->curframe;
1187 	dst_state->active_spin_lock = src->active_spin_lock;
1188 	dst_state->branches = src->branches;
1189 	dst_state->parent = src->parent;
1190 	dst_state->first_insn_idx = src->first_insn_idx;
1191 	dst_state->last_insn_idx = src->last_insn_idx;
1192 	for (i = 0; i <= src->curframe; i++) {
1193 		dst = dst_state->frame[i];
1194 		if (!dst) {
1195 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1196 			if (!dst)
1197 				return -ENOMEM;
1198 			dst_state->frame[i] = dst;
1199 		}
1200 		err = copy_func_state(dst, src->frame[i]);
1201 		if (err)
1202 			return err;
1203 	}
1204 	return 0;
1205 }
1206 
1207 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1208 {
1209 	while (st) {
1210 		u32 br = --st->branches;
1211 
1212 		/* WARN_ON(br > 1) technically makes sense here,
1213 		 * but see comment in push_stack(), hence:
1214 		 */
1215 		WARN_ONCE((int)br < 0,
1216 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1217 			  br);
1218 		if (br)
1219 			break;
1220 		st = st->parent;
1221 	}
1222 }
1223 
1224 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1225 		     int *insn_idx, bool pop_log)
1226 {
1227 	struct bpf_verifier_state *cur = env->cur_state;
1228 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1229 	int err;
1230 
1231 	if (env->head == NULL)
1232 		return -ENOENT;
1233 
1234 	if (cur) {
1235 		err = copy_verifier_state(cur, &head->st);
1236 		if (err)
1237 			return err;
1238 	}
1239 	if (pop_log)
1240 		bpf_vlog_reset(&env->log, head->log_pos);
1241 	if (insn_idx)
1242 		*insn_idx = head->insn_idx;
1243 	if (prev_insn_idx)
1244 		*prev_insn_idx = head->prev_insn_idx;
1245 	elem = head->next;
1246 	free_verifier_state(&head->st, false);
1247 	kfree(head);
1248 	env->head = elem;
1249 	env->stack_size--;
1250 	return 0;
1251 }
1252 
1253 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1254 					     int insn_idx, int prev_insn_idx,
1255 					     bool speculative)
1256 {
1257 	struct bpf_verifier_state *cur = env->cur_state;
1258 	struct bpf_verifier_stack_elem *elem;
1259 	int err;
1260 
1261 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1262 	if (!elem)
1263 		goto err;
1264 
1265 	elem->insn_idx = insn_idx;
1266 	elem->prev_insn_idx = prev_insn_idx;
1267 	elem->next = env->head;
1268 	elem->log_pos = env->log.len_used;
1269 	env->head = elem;
1270 	env->stack_size++;
1271 	err = copy_verifier_state(&elem->st, cur);
1272 	if (err)
1273 		goto err;
1274 	elem->st.speculative |= speculative;
1275 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1276 		verbose(env, "The sequence of %d jumps is too complex.\n",
1277 			env->stack_size);
1278 		goto err;
1279 	}
1280 	if (elem->st.parent) {
1281 		++elem->st.parent->branches;
1282 		/* WARN_ON(branches > 2) technically makes sense here,
1283 		 * but
1284 		 * 1. speculative states will bump 'branches' for non-branch
1285 		 * instructions
1286 		 * 2. is_state_visited() heuristics may decide not to create
1287 		 * a new state for a sequence of branches and all such current
1288 		 * and cloned states will be pointing to a single parent state
1289 		 * which might have large 'branches' count.
1290 		 */
1291 	}
1292 	return &elem->st;
1293 err:
1294 	free_verifier_state(env->cur_state, true);
1295 	env->cur_state = NULL;
1296 	/* pop all elements and return */
1297 	while (!pop_stack(env, NULL, NULL, false));
1298 	return NULL;
1299 }
1300 
1301 #define CALLER_SAVED_REGS 6
1302 static const int caller_saved[CALLER_SAVED_REGS] = {
1303 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1304 };
1305 
1306 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1307 				struct bpf_reg_state *reg);
1308 
1309 /* This helper doesn't clear reg->id */
1310 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1311 {
1312 	reg->var_off = tnum_const(imm);
1313 	reg->smin_value = (s64)imm;
1314 	reg->smax_value = (s64)imm;
1315 	reg->umin_value = imm;
1316 	reg->umax_value = imm;
1317 
1318 	reg->s32_min_value = (s32)imm;
1319 	reg->s32_max_value = (s32)imm;
1320 	reg->u32_min_value = (u32)imm;
1321 	reg->u32_max_value = (u32)imm;
1322 }
1323 
1324 /* Mark the unknown part of a register (variable offset or scalar value) as
1325  * known to have the value @imm.
1326  */
1327 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1328 {
1329 	/* Clear id, off, and union(map_ptr, range) */
1330 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1331 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1332 	___mark_reg_known(reg, imm);
1333 }
1334 
1335 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1336 {
1337 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1338 	reg->s32_min_value = (s32)imm;
1339 	reg->s32_max_value = (s32)imm;
1340 	reg->u32_min_value = (u32)imm;
1341 	reg->u32_max_value = (u32)imm;
1342 }
1343 
1344 /* Mark the 'variable offset' part of a register as zero.  This should be
1345  * used only on registers holding a pointer type.
1346  */
1347 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1348 {
1349 	__mark_reg_known(reg, 0);
1350 }
1351 
1352 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1353 {
1354 	__mark_reg_known(reg, 0);
1355 	reg->type = SCALAR_VALUE;
1356 }
1357 
1358 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1359 				struct bpf_reg_state *regs, u32 regno)
1360 {
1361 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1362 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1363 		/* Something bad happened, let's kill all regs */
1364 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1365 			__mark_reg_not_init(env, regs + regno);
1366 		return;
1367 	}
1368 	__mark_reg_known_zero(regs + regno);
1369 }
1370 
1371 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1372 {
1373 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1374 		const struct bpf_map *map = reg->map_ptr;
1375 
1376 		if (map->inner_map_meta) {
1377 			reg->type = CONST_PTR_TO_MAP;
1378 			reg->map_ptr = map->inner_map_meta;
1379 			/* transfer reg's id which is unique for every map_lookup_elem
1380 			 * as UID of the inner map.
1381 			 */
1382 			if (map_value_has_timer(map->inner_map_meta))
1383 				reg->map_uid = reg->id;
1384 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1385 			reg->type = PTR_TO_XDP_SOCK;
1386 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1387 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1388 			reg->type = PTR_TO_SOCKET;
1389 		} else {
1390 			reg->type = PTR_TO_MAP_VALUE;
1391 		}
1392 		return;
1393 	}
1394 
1395 	reg->type &= ~PTR_MAYBE_NULL;
1396 }
1397 
1398 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1399 {
1400 	return type_is_pkt_pointer(reg->type);
1401 }
1402 
1403 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1404 {
1405 	return reg_is_pkt_pointer(reg) ||
1406 	       reg->type == PTR_TO_PACKET_END;
1407 }
1408 
1409 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1410 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1411 				    enum bpf_reg_type which)
1412 {
1413 	/* The register can already have a range from prior markings.
1414 	 * This is fine as long as it hasn't been advanced from its
1415 	 * origin.
1416 	 */
1417 	return reg->type == which &&
1418 	       reg->id == 0 &&
1419 	       reg->off == 0 &&
1420 	       tnum_equals_const(reg->var_off, 0);
1421 }
1422 
1423 /* Reset the min/max bounds of a register */
1424 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1425 {
1426 	reg->smin_value = S64_MIN;
1427 	reg->smax_value = S64_MAX;
1428 	reg->umin_value = 0;
1429 	reg->umax_value = U64_MAX;
1430 
1431 	reg->s32_min_value = S32_MIN;
1432 	reg->s32_max_value = S32_MAX;
1433 	reg->u32_min_value = 0;
1434 	reg->u32_max_value = U32_MAX;
1435 }
1436 
1437 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1438 {
1439 	reg->smin_value = S64_MIN;
1440 	reg->smax_value = S64_MAX;
1441 	reg->umin_value = 0;
1442 	reg->umax_value = U64_MAX;
1443 }
1444 
1445 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1446 {
1447 	reg->s32_min_value = S32_MIN;
1448 	reg->s32_max_value = S32_MAX;
1449 	reg->u32_min_value = 0;
1450 	reg->u32_max_value = U32_MAX;
1451 }
1452 
1453 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1454 {
1455 	struct tnum var32_off = tnum_subreg(reg->var_off);
1456 
1457 	/* min signed is max(sign bit) | min(other bits) */
1458 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1459 			var32_off.value | (var32_off.mask & S32_MIN));
1460 	/* max signed is min(sign bit) | max(other bits) */
1461 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1462 			var32_off.value | (var32_off.mask & S32_MAX));
1463 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1464 	reg->u32_max_value = min(reg->u32_max_value,
1465 				 (u32)(var32_off.value | var32_off.mask));
1466 }
1467 
1468 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1469 {
1470 	/* min signed is max(sign bit) | min(other bits) */
1471 	reg->smin_value = max_t(s64, reg->smin_value,
1472 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1473 	/* max signed is min(sign bit) | max(other bits) */
1474 	reg->smax_value = min_t(s64, reg->smax_value,
1475 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1476 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1477 	reg->umax_value = min(reg->umax_value,
1478 			      reg->var_off.value | reg->var_off.mask);
1479 }
1480 
1481 static void __update_reg_bounds(struct bpf_reg_state *reg)
1482 {
1483 	__update_reg32_bounds(reg);
1484 	__update_reg64_bounds(reg);
1485 }
1486 
1487 /* Uses signed min/max values to inform unsigned, and vice-versa */
1488 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1489 {
1490 	/* Learn sign from signed bounds.
1491 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1492 	 * are the same, so combine.  This works even in the negative case, e.g.
1493 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1494 	 */
1495 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1496 		reg->s32_min_value = reg->u32_min_value =
1497 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1498 		reg->s32_max_value = reg->u32_max_value =
1499 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1500 		return;
1501 	}
1502 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1503 	 * boundary, so we must be careful.
1504 	 */
1505 	if ((s32)reg->u32_max_value >= 0) {
1506 		/* Positive.  We can't learn anything from the smin, but smax
1507 		 * is positive, hence safe.
1508 		 */
1509 		reg->s32_min_value = reg->u32_min_value;
1510 		reg->s32_max_value = reg->u32_max_value =
1511 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1512 	} else if ((s32)reg->u32_min_value < 0) {
1513 		/* Negative.  We can't learn anything from the smax, but smin
1514 		 * is negative, hence safe.
1515 		 */
1516 		reg->s32_min_value = reg->u32_min_value =
1517 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1518 		reg->s32_max_value = reg->u32_max_value;
1519 	}
1520 }
1521 
1522 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1523 {
1524 	/* Learn sign from signed bounds.
1525 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1526 	 * are the same, so combine.  This works even in the negative case, e.g.
1527 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1528 	 */
1529 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1530 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1531 							  reg->umin_value);
1532 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1533 							  reg->umax_value);
1534 		return;
1535 	}
1536 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1537 	 * boundary, so we must be careful.
1538 	 */
1539 	if ((s64)reg->umax_value >= 0) {
1540 		/* Positive.  We can't learn anything from the smin, but smax
1541 		 * is positive, hence safe.
1542 		 */
1543 		reg->smin_value = reg->umin_value;
1544 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1545 							  reg->umax_value);
1546 	} else if ((s64)reg->umin_value < 0) {
1547 		/* Negative.  We can't learn anything from the smax, but smin
1548 		 * is negative, hence safe.
1549 		 */
1550 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1551 							  reg->umin_value);
1552 		reg->smax_value = reg->umax_value;
1553 	}
1554 }
1555 
1556 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1557 {
1558 	__reg32_deduce_bounds(reg);
1559 	__reg64_deduce_bounds(reg);
1560 }
1561 
1562 /* Attempts to improve var_off based on unsigned min/max information */
1563 static void __reg_bound_offset(struct bpf_reg_state *reg)
1564 {
1565 	struct tnum var64_off = tnum_intersect(reg->var_off,
1566 					       tnum_range(reg->umin_value,
1567 							  reg->umax_value));
1568 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1569 						tnum_range(reg->u32_min_value,
1570 							   reg->u32_max_value));
1571 
1572 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1573 }
1574 
1575 static void reg_bounds_sync(struct bpf_reg_state *reg)
1576 {
1577 	/* We might have learned new bounds from the var_off. */
1578 	__update_reg_bounds(reg);
1579 	/* We might have learned something about the sign bit. */
1580 	__reg_deduce_bounds(reg);
1581 	/* We might have learned some bits from the bounds. */
1582 	__reg_bound_offset(reg);
1583 	/* Intersecting with the old var_off might have improved our bounds
1584 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1585 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1586 	 */
1587 	__update_reg_bounds(reg);
1588 }
1589 
1590 static bool __reg32_bound_s64(s32 a)
1591 {
1592 	return a >= 0 && a <= S32_MAX;
1593 }
1594 
1595 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1596 {
1597 	reg->umin_value = reg->u32_min_value;
1598 	reg->umax_value = reg->u32_max_value;
1599 
1600 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1601 	 * be positive otherwise set to worse case bounds and refine later
1602 	 * from tnum.
1603 	 */
1604 	if (__reg32_bound_s64(reg->s32_min_value) &&
1605 	    __reg32_bound_s64(reg->s32_max_value)) {
1606 		reg->smin_value = reg->s32_min_value;
1607 		reg->smax_value = reg->s32_max_value;
1608 	} else {
1609 		reg->smin_value = 0;
1610 		reg->smax_value = U32_MAX;
1611 	}
1612 }
1613 
1614 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1615 {
1616 	/* special case when 64-bit register has upper 32-bit register
1617 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1618 	 * allowing us to use 32-bit bounds directly,
1619 	 */
1620 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1621 		__reg_assign_32_into_64(reg);
1622 	} else {
1623 		/* Otherwise the best we can do is push lower 32bit known and
1624 		 * unknown bits into register (var_off set from jmp logic)
1625 		 * then learn as much as possible from the 64-bit tnum
1626 		 * known and unknown bits. The previous smin/smax bounds are
1627 		 * invalid here because of jmp32 compare so mark them unknown
1628 		 * so they do not impact tnum bounds calculation.
1629 		 */
1630 		__mark_reg64_unbounded(reg);
1631 	}
1632 	reg_bounds_sync(reg);
1633 }
1634 
1635 static bool __reg64_bound_s32(s64 a)
1636 {
1637 	return a >= S32_MIN && a <= S32_MAX;
1638 }
1639 
1640 static bool __reg64_bound_u32(u64 a)
1641 {
1642 	return a >= U32_MIN && a <= U32_MAX;
1643 }
1644 
1645 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1646 {
1647 	__mark_reg32_unbounded(reg);
1648 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1649 		reg->s32_min_value = (s32)reg->smin_value;
1650 		reg->s32_max_value = (s32)reg->smax_value;
1651 	}
1652 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1653 		reg->u32_min_value = (u32)reg->umin_value;
1654 		reg->u32_max_value = (u32)reg->umax_value;
1655 	}
1656 	reg_bounds_sync(reg);
1657 }
1658 
1659 /* Mark a register as having a completely unknown (scalar) value. */
1660 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1661 			       struct bpf_reg_state *reg)
1662 {
1663 	/*
1664 	 * Clear type, id, off, and union(map_ptr, range) and
1665 	 * padding between 'type' and union
1666 	 */
1667 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1668 	reg->type = SCALAR_VALUE;
1669 	reg->var_off = tnum_unknown;
1670 	reg->frameno = 0;
1671 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1672 	__mark_reg_unbounded(reg);
1673 }
1674 
1675 static void mark_reg_unknown(struct bpf_verifier_env *env,
1676 			     struct bpf_reg_state *regs, u32 regno)
1677 {
1678 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1679 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1680 		/* Something bad happened, let's kill all regs except FP */
1681 		for (regno = 0; regno < BPF_REG_FP; regno++)
1682 			__mark_reg_not_init(env, regs + regno);
1683 		return;
1684 	}
1685 	__mark_reg_unknown(env, regs + regno);
1686 }
1687 
1688 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1689 				struct bpf_reg_state *reg)
1690 {
1691 	__mark_reg_unknown(env, reg);
1692 	reg->type = NOT_INIT;
1693 }
1694 
1695 static void mark_reg_not_init(struct bpf_verifier_env *env,
1696 			      struct bpf_reg_state *regs, u32 regno)
1697 {
1698 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1699 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1700 		/* Something bad happened, let's kill all regs except FP */
1701 		for (regno = 0; regno < BPF_REG_FP; regno++)
1702 			__mark_reg_not_init(env, regs + regno);
1703 		return;
1704 	}
1705 	__mark_reg_not_init(env, regs + regno);
1706 }
1707 
1708 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1709 			    struct bpf_reg_state *regs, u32 regno,
1710 			    enum bpf_reg_type reg_type,
1711 			    struct btf *btf, u32 btf_id,
1712 			    enum bpf_type_flag flag)
1713 {
1714 	if (reg_type == SCALAR_VALUE) {
1715 		mark_reg_unknown(env, regs, regno);
1716 		return;
1717 	}
1718 	mark_reg_known_zero(env, regs, regno);
1719 	regs[regno].type = PTR_TO_BTF_ID | flag;
1720 	regs[regno].btf = btf;
1721 	regs[regno].btf_id = btf_id;
1722 }
1723 
1724 #define DEF_NOT_SUBREG	(0)
1725 static void init_reg_state(struct bpf_verifier_env *env,
1726 			   struct bpf_func_state *state)
1727 {
1728 	struct bpf_reg_state *regs = state->regs;
1729 	int i;
1730 
1731 	for (i = 0; i < MAX_BPF_REG; i++) {
1732 		mark_reg_not_init(env, regs, i);
1733 		regs[i].live = REG_LIVE_NONE;
1734 		regs[i].parent = NULL;
1735 		regs[i].subreg_def = DEF_NOT_SUBREG;
1736 	}
1737 
1738 	/* frame pointer */
1739 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1740 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1741 	regs[BPF_REG_FP].frameno = state->frameno;
1742 }
1743 
1744 #define BPF_MAIN_FUNC (-1)
1745 static void init_func_state(struct bpf_verifier_env *env,
1746 			    struct bpf_func_state *state,
1747 			    int callsite, int frameno, int subprogno)
1748 {
1749 	state->callsite = callsite;
1750 	state->frameno = frameno;
1751 	state->subprogno = subprogno;
1752 	init_reg_state(env, state);
1753 	mark_verifier_state_scratched(env);
1754 }
1755 
1756 /* Similar to push_stack(), but for async callbacks */
1757 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1758 						int insn_idx, int prev_insn_idx,
1759 						int subprog)
1760 {
1761 	struct bpf_verifier_stack_elem *elem;
1762 	struct bpf_func_state *frame;
1763 
1764 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1765 	if (!elem)
1766 		goto err;
1767 
1768 	elem->insn_idx = insn_idx;
1769 	elem->prev_insn_idx = prev_insn_idx;
1770 	elem->next = env->head;
1771 	elem->log_pos = env->log.len_used;
1772 	env->head = elem;
1773 	env->stack_size++;
1774 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1775 		verbose(env,
1776 			"The sequence of %d jumps is too complex for async cb.\n",
1777 			env->stack_size);
1778 		goto err;
1779 	}
1780 	/* Unlike push_stack() do not copy_verifier_state().
1781 	 * The caller state doesn't matter.
1782 	 * This is async callback. It starts in a fresh stack.
1783 	 * Initialize it similar to do_check_common().
1784 	 */
1785 	elem->st.branches = 1;
1786 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1787 	if (!frame)
1788 		goto err;
1789 	init_func_state(env, frame,
1790 			BPF_MAIN_FUNC /* callsite */,
1791 			0 /* frameno within this callchain */,
1792 			subprog /* subprog number within this prog */);
1793 	elem->st.frame[0] = frame;
1794 	return &elem->st;
1795 err:
1796 	free_verifier_state(env->cur_state, true);
1797 	env->cur_state = NULL;
1798 	/* pop all elements and return */
1799 	while (!pop_stack(env, NULL, NULL, false));
1800 	return NULL;
1801 }
1802 
1803 
1804 enum reg_arg_type {
1805 	SRC_OP,		/* register is used as source operand */
1806 	DST_OP,		/* register is used as destination operand */
1807 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1808 };
1809 
1810 static int cmp_subprogs(const void *a, const void *b)
1811 {
1812 	return ((struct bpf_subprog_info *)a)->start -
1813 	       ((struct bpf_subprog_info *)b)->start;
1814 }
1815 
1816 static int find_subprog(struct bpf_verifier_env *env, int off)
1817 {
1818 	struct bpf_subprog_info *p;
1819 
1820 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1821 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1822 	if (!p)
1823 		return -ENOENT;
1824 	return p - env->subprog_info;
1825 
1826 }
1827 
1828 static int add_subprog(struct bpf_verifier_env *env, int off)
1829 {
1830 	int insn_cnt = env->prog->len;
1831 	int ret;
1832 
1833 	if (off >= insn_cnt || off < 0) {
1834 		verbose(env, "call to invalid destination\n");
1835 		return -EINVAL;
1836 	}
1837 	ret = find_subprog(env, off);
1838 	if (ret >= 0)
1839 		return ret;
1840 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1841 		verbose(env, "too many subprograms\n");
1842 		return -E2BIG;
1843 	}
1844 	/* determine subprog starts. The end is one before the next starts */
1845 	env->subprog_info[env->subprog_cnt++].start = off;
1846 	sort(env->subprog_info, env->subprog_cnt,
1847 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1848 	return env->subprog_cnt - 1;
1849 }
1850 
1851 #define MAX_KFUNC_DESCS 256
1852 #define MAX_KFUNC_BTFS	256
1853 
1854 struct bpf_kfunc_desc {
1855 	struct btf_func_model func_model;
1856 	u32 func_id;
1857 	s32 imm;
1858 	u16 offset;
1859 };
1860 
1861 struct bpf_kfunc_btf {
1862 	struct btf *btf;
1863 	struct module *module;
1864 	u16 offset;
1865 };
1866 
1867 struct bpf_kfunc_desc_tab {
1868 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1869 	u32 nr_descs;
1870 };
1871 
1872 struct bpf_kfunc_btf_tab {
1873 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1874 	u32 nr_descs;
1875 };
1876 
1877 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1878 {
1879 	const struct bpf_kfunc_desc *d0 = a;
1880 	const struct bpf_kfunc_desc *d1 = b;
1881 
1882 	/* func_id is not greater than BTF_MAX_TYPE */
1883 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1884 }
1885 
1886 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1887 {
1888 	const struct bpf_kfunc_btf *d0 = a;
1889 	const struct bpf_kfunc_btf *d1 = b;
1890 
1891 	return d0->offset - d1->offset;
1892 }
1893 
1894 static const struct bpf_kfunc_desc *
1895 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1896 {
1897 	struct bpf_kfunc_desc desc = {
1898 		.func_id = func_id,
1899 		.offset = offset,
1900 	};
1901 	struct bpf_kfunc_desc_tab *tab;
1902 
1903 	tab = prog->aux->kfunc_tab;
1904 	return bsearch(&desc, tab->descs, tab->nr_descs,
1905 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1906 }
1907 
1908 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1909 					 s16 offset)
1910 {
1911 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1912 	struct bpf_kfunc_btf_tab *tab;
1913 	struct bpf_kfunc_btf *b;
1914 	struct module *mod;
1915 	struct btf *btf;
1916 	int btf_fd;
1917 
1918 	tab = env->prog->aux->kfunc_btf_tab;
1919 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1920 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1921 	if (!b) {
1922 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1923 			verbose(env, "too many different module BTFs\n");
1924 			return ERR_PTR(-E2BIG);
1925 		}
1926 
1927 		if (bpfptr_is_null(env->fd_array)) {
1928 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1929 			return ERR_PTR(-EPROTO);
1930 		}
1931 
1932 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1933 					    offset * sizeof(btf_fd),
1934 					    sizeof(btf_fd)))
1935 			return ERR_PTR(-EFAULT);
1936 
1937 		btf = btf_get_by_fd(btf_fd);
1938 		if (IS_ERR(btf)) {
1939 			verbose(env, "invalid module BTF fd specified\n");
1940 			return btf;
1941 		}
1942 
1943 		if (!btf_is_module(btf)) {
1944 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1945 			btf_put(btf);
1946 			return ERR_PTR(-EINVAL);
1947 		}
1948 
1949 		mod = btf_try_get_module(btf);
1950 		if (!mod) {
1951 			btf_put(btf);
1952 			return ERR_PTR(-ENXIO);
1953 		}
1954 
1955 		b = &tab->descs[tab->nr_descs++];
1956 		b->btf = btf;
1957 		b->module = mod;
1958 		b->offset = offset;
1959 
1960 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1961 		     kfunc_btf_cmp_by_off, NULL);
1962 	}
1963 	return b->btf;
1964 }
1965 
1966 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1967 {
1968 	if (!tab)
1969 		return;
1970 
1971 	while (tab->nr_descs--) {
1972 		module_put(tab->descs[tab->nr_descs].module);
1973 		btf_put(tab->descs[tab->nr_descs].btf);
1974 	}
1975 	kfree(tab);
1976 }
1977 
1978 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
1979 {
1980 	if (offset) {
1981 		if (offset < 0) {
1982 			/* In the future, this can be allowed to increase limit
1983 			 * of fd index into fd_array, interpreted as u16.
1984 			 */
1985 			verbose(env, "negative offset disallowed for kernel module function call\n");
1986 			return ERR_PTR(-EINVAL);
1987 		}
1988 
1989 		return __find_kfunc_desc_btf(env, offset);
1990 	}
1991 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
1992 }
1993 
1994 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1995 {
1996 	const struct btf_type *func, *func_proto;
1997 	struct bpf_kfunc_btf_tab *btf_tab;
1998 	struct bpf_kfunc_desc_tab *tab;
1999 	struct bpf_prog_aux *prog_aux;
2000 	struct bpf_kfunc_desc *desc;
2001 	const char *func_name;
2002 	struct btf *desc_btf;
2003 	unsigned long call_imm;
2004 	unsigned long addr;
2005 	int err;
2006 
2007 	prog_aux = env->prog->aux;
2008 	tab = prog_aux->kfunc_tab;
2009 	btf_tab = prog_aux->kfunc_btf_tab;
2010 	if (!tab) {
2011 		if (!btf_vmlinux) {
2012 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2013 			return -ENOTSUPP;
2014 		}
2015 
2016 		if (!env->prog->jit_requested) {
2017 			verbose(env, "JIT is required for calling kernel function\n");
2018 			return -ENOTSUPP;
2019 		}
2020 
2021 		if (!bpf_jit_supports_kfunc_call()) {
2022 			verbose(env, "JIT does not support calling kernel function\n");
2023 			return -ENOTSUPP;
2024 		}
2025 
2026 		if (!env->prog->gpl_compatible) {
2027 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2028 			return -EINVAL;
2029 		}
2030 
2031 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2032 		if (!tab)
2033 			return -ENOMEM;
2034 		prog_aux->kfunc_tab = tab;
2035 	}
2036 
2037 	/* func_id == 0 is always invalid, but instead of returning an error, be
2038 	 * conservative and wait until the code elimination pass before returning
2039 	 * error, so that invalid calls that get pruned out can be in BPF programs
2040 	 * loaded from userspace.  It is also required that offset be untouched
2041 	 * for such calls.
2042 	 */
2043 	if (!func_id && !offset)
2044 		return 0;
2045 
2046 	if (!btf_tab && offset) {
2047 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2048 		if (!btf_tab)
2049 			return -ENOMEM;
2050 		prog_aux->kfunc_btf_tab = btf_tab;
2051 	}
2052 
2053 	desc_btf = find_kfunc_desc_btf(env, offset);
2054 	if (IS_ERR(desc_btf)) {
2055 		verbose(env, "failed to find BTF for kernel function\n");
2056 		return PTR_ERR(desc_btf);
2057 	}
2058 
2059 	if (find_kfunc_desc(env->prog, func_id, offset))
2060 		return 0;
2061 
2062 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2063 		verbose(env, "too many different kernel function calls\n");
2064 		return -E2BIG;
2065 	}
2066 
2067 	func = btf_type_by_id(desc_btf, func_id);
2068 	if (!func || !btf_type_is_func(func)) {
2069 		verbose(env, "kernel btf_id %u is not a function\n",
2070 			func_id);
2071 		return -EINVAL;
2072 	}
2073 	func_proto = btf_type_by_id(desc_btf, func->type);
2074 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2075 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2076 			func_id);
2077 		return -EINVAL;
2078 	}
2079 
2080 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2081 	addr = kallsyms_lookup_name(func_name);
2082 	if (!addr) {
2083 		verbose(env, "cannot find address for kernel function %s\n",
2084 			func_name);
2085 		return -EINVAL;
2086 	}
2087 
2088 	call_imm = BPF_CALL_IMM(addr);
2089 	/* Check whether or not the relative offset overflows desc->imm */
2090 	if ((unsigned long)(s32)call_imm != call_imm) {
2091 		verbose(env, "address of kernel function %s is out of range\n",
2092 			func_name);
2093 		return -EINVAL;
2094 	}
2095 
2096 	desc = &tab->descs[tab->nr_descs++];
2097 	desc->func_id = func_id;
2098 	desc->imm = call_imm;
2099 	desc->offset = offset;
2100 	err = btf_distill_func_proto(&env->log, desc_btf,
2101 				     func_proto, func_name,
2102 				     &desc->func_model);
2103 	if (!err)
2104 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2105 		     kfunc_desc_cmp_by_id_off, NULL);
2106 	return err;
2107 }
2108 
2109 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2110 {
2111 	const struct bpf_kfunc_desc *d0 = a;
2112 	const struct bpf_kfunc_desc *d1 = b;
2113 
2114 	if (d0->imm > d1->imm)
2115 		return 1;
2116 	else if (d0->imm < d1->imm)
2117 		return -1;
2118 	return 0;
2119 }
2120 
2121 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2122 {
2123 	struct bpf_kfunc_desc_tab *tab;
2124 
2125 	tab = prog->aux->kfunc_tab;
2126 	if (!tab)
2127 		return;
2128 
2129 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2130 	     kfunc_desc_cmp_by_imm, NULL);
2131 }
2132 
2133 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2134 {
2135 	return !!prog->aux->kfunc_tab;
2136 }
2137 
2138 const struct btf_func_model *
2139 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2140 			 const struct bpf_insn *insn)
2141 {
2142 	const struct bpf_kfunc_desc desc = {
2143 		.imm = insn->imm,
2144 	};
2145 	const struct bpf_kfunc_desc *res;
2146 	struct bpf_kfunc_desc_tab *tab;
2147 
2148 	tab = prog->aux->kfunc_tab;
2149 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2150 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2151 
2152 	return res ? &res->func_model : NULL;
2153 }
2154 
2155 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2156 {
2157 	struct bpf_subprog_info *subprog = env->subprog_info;
2158 	struct bpf_insn *insn = env->prog->insnsi;
2159 	int i, ret, insn_cnt = env->prog->len;
2160 
2161 	/* Add entry function. */
2162 	ret = add_subprog(env, 0);
2163 	if (ret)
2164 		return ret;
2165 
2166 	for (i = 0; i < insn_cnt; i++, insn++) {
2167 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2168 		    !bpf_pseudo_kfunc_call(insn))
2169 			continue;
2170 
2171 		if (!env->bpf_capable) {
2172 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2173 			return -EPERM;
2174 		}
2175 
2176 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2177 			ret = add_subprog(env, i + insn->imm + 1);
2178 		else
2179 			ret = add_kfunc_call(env, insn->imm, insn->off);
2180 
2181 		if (ret < 0)
2182 			return ret;
2183 	}
2184 
2185 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2186 	 * logic. 'subprog_cnt' should not be increased.
2187 	 */
2188 	subprog[env->subprog_cnt].start = insn_cnt;
2189 
2190 	if (env->log.level & BPF_LOG_LEVEL2)
2191 		for (i = 0; i < env->subprog_cnt; i++)
2192 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2193 
2194 	return 0;
2195 }
2196 
2197 static int check_subprogs(struct bpf_verifier_env *env)
2198 {
2199 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2200 	struct bpf_subprog_info *subprog = env->subprog_info;
2201 	struct bpf_insn *insn = env->prog->insnsi;
2202 	int insn_cnt = env->prog->len;
2203 
2204 	/* now check that all jumps are within the same subprog */
2205 	subprog_start = subprog[cur_subprog].start;
2206 	subprog_end = subprog[cur_subprog + 1].start;
2207 	for (i = 0; i < insn_cnt; i++) {
2208 		u8 code = insn[i].code;
2209 
2210 		if (code == (BPF_JMP | BPF_CALL) &&
2211 		    insn[i].imm == BPF_FUNC_tail_call &&
2212 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2213 			subprog[cur_subprog].has_tail_call = true;
2214 		if (BPF_CLASS(code) == BPF_LD &&
2215 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2216 			subprog[cur_subprog].has_ld_abs = true;
2217 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2218 			goto next;
2219 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2220 			goto next;
2221 		off = i + insn[i].off + 1;
2222 		if (off < subprog_start || off >= subprog_end) {
2223 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2224 			return -EINVAL;
2225 		}
2226 next:
2227 		if (i == subprog_end - 1) {
2228 			/* to avoid fall-through from one subprog into another
2229 			 * the last insn of the subprog should be either exit
2230 			 * or unconditional jump back
2231 			 */
2232 			if (code != (BPF_JMP | BPF_EXIT) &&
2233 			    code != (BPF_JMP | BPF_JA)) {
2234 				verbose(env, "last insn is not an exit or jmp\n");
2235 				return -EINVAL;
2236 			}
2237 			subprog_start = subprog_end;
2238 			cur_subprog++;
2239 			if (cur_subprog < env->subprog_cnt)
2240 				subprog_end = subprog[cur_subprog + 1].start;
2241 		}
2242 	}
2243 	return 0;
2244 }
2245 
2246 /* Parentage chain of this register (or stack slot) should take care of all
2247  * issues like callee-saved registers, stack slot allocation time, etc.
2248  */
2249 static int mark_reg_read(struct bpf_verifier_env *env,
2250 			 const struct bpf_reg_state *state,
2251 			 struct bpf_reg_state *parent, u8 flag)
2252 {
2253 	bool writes = parent == state->parent; /* Observe write marks */
2254 	int cnt = 0;
2255 
2256 	while (parent) {
2257 		/* if read wasn't screened by an earlier write ... */
2258 		if (writes && state->live & REG_LIVE_WRITTEN)
2259 			break;
2260 		if (parent->live & REG_LIVE_DONE) {
2261 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2262 				reg_type_str(env, parent->type),
2263 				parent->var_off.value, parent->off);
2264 			return -EFAULT;
2265 		}
2266 		/* The first condition is more likely to be true than the
2267 		 * second, checked it first.
2268 		 */
2269 		if ((parent->live & REG_LIVE_READ) == flag ||
2270 		    parent->live & REG_LIVE_READ64)
2271 			/* The parentage chain never changes and
2272 			 * this parent was already marked as LIVE_READ.
2273 			 * There is no need to keep walking the chain again and
2274 			 * keep re-marking all parents as LIVE_READ.
2275 			 * This case happens when the same register is read
2276 			 * multiple times without writes into it in-between.
2277 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2278 			 * then no need to set the weak REG_LIVE_READ32.
2279 			 */
2280 			break;
2281 		/* ... then we depend on parent's value */
2282 		parent->live |= flag;
2283 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2284 		if (flag == REG_LIVE_READ64)
2285 			parent->live &= ~REG_LIVE_READ32;
2286 		state = parent;
2287 		parent = state->parent;
2288 		writes = true;
2289 		cnt++;
2290 	}
2291 
2292 	if (env->longest_mark_read_walk < cnt)
2293 		env->longest_mark_read_walk = cnt;
2294 	return 0;
2295 }
2296 
2297 /* This function is supposed to be used by the following 32-bit optimization
2298  * code only. It returns TRUE if the source or destination register operates
2299  * on 64-bit, otherwise return FALSE.
2300  */
2301 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2302 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2303 {
2304 	u8 code, class, op;
2305 
2306 	code = insn->code;
2307 	class = BPF_CLASS(code);
2308 	op = BPF_OP(code);
2309 	if (class == BPF_JMP) {
2310 		/* BPF_EXIT for "main" will reach here. Return TRUE
2311 		 * conservatively.
2312 		 */
2313 		if (op == BPF_EXIT)
2314 			return true;
2315 		if (op == BPF_CALL) {
2316 			/* BPF to BPF call will reach here because of marking
2317 			 * caller saved clobber with DST_OP_NO_MARK for which we
2318 			 * don't care the register def because they are anyway
2319 			 * marked as NOT_INIT already.
2320 			 */
2321 			if (insn->src_reg == BPF_PSEUDO_CALL)
2322 				return false;
2323 			/* Helper call will reach here because of arg type
2324 			 * check, conservatively return TRUE.
2325 			 */
2326 			if (t == SRC_OP)
2327 				return true;
2328 
2329 			return false;
2330 		}
2331 	}
2332 
2333 	if (class == BPF_ALU64 || class == BPF_JMP ||
2334 	    /* BPF_END always use BPF_ALU class. */
2335 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2336 		return true;
2337 
2338 	if (class == BPF_ALU || class == BPF_JMP32)
2339 		return false;
2340 
2341 	if (class == BPF_LDX) {
2342 		if (t != SRC_OP)
2343 			return BPF_SIZE(code) == BPF_DW;
2344 		/* LDX source must be ptr. */
2345 		return true;
2346 	}
2347 
2348 	if (class == BPF_STX) {
2349 		/* BPF_STX (including atomic variants) has multiple source
2350 		 * operands, one of which is a ptr. Check whether the caller is
2351 		 * asking about it.
2352 		 */
2353 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2354 			return true;
2355 		return BPF_SIZE(code) == BPF_DW;
2356 	}
2357 
2358 	if (class == BPF_LD) {
2359 		u8 mode = BPF_MODE(code);
2360 
2361 		/* LD_IMM64 */
2362 		if (mode == BPF_IMM)
2363 			return true;
2364 
2365 		/* Both LD_IND and LD_ABS return 32-bit data. */
2366 		if (t != SRC_OP)
2367 			return  false;
2368 
2369 		/* Implicit ctx ptr. */
2370 		if (regno == BPF_REG_6)
2371 			return true;
2372 
2373 		/* Explicit source could be any width. */
2374 		return true;
2375 	}
2376 
2377 	if (class == BPF_ST)
2378 		/* The only source register for BPF_ST is a ptr. */
2379 		return true;
2380 
2381 	/* Conservatively return true at default. */
2382 	return true;
2383 }
2384 
2385 /* Return the regno defined by the insn, or -1. */
2386 static int insn_def_regno(const struct bpf_insn *insn)
2387 {
2388 	switch (BPF_CLASS(insn->code)) {
2389 	case BPF_JMP:
2390 	case BPF_JMP32:
2391 	case BPF_ST:
2392 		return -1;
2393 	case BPF_STX:
2394 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2395 		    (insn->imm & BPF_FETCH)) {
2396 			if (insn->imm == BPF_CMPXCHG)
2397 				return BPF_REG_0;
2398 			else
2399 				return insn->src_reg;
2400 		} else {
2401 			return -1;
2402 		}
2403 	default:
2404 		return insn->dst_reg;
2405 	}
2406 }
2407 
2408 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2409 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2410 {
2411 	int dst_reg = insn_def_regno(insn);
2412 
2413 	if (dst_reg == -1)
2414 		return false;
2415 
2416 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2417 }
2418 
2419 static void mark_insn_zext(struct bpf_verifier_env *env,
2420 			   struct bpf_reg_state *reg)
2421 {
2422 	s32 def_idx = reg->subreg_def;
2423 
2424 	if (def_idx == DEF_NOT_SUBREG)
2425 		return;
2426 
2427 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2428 	/* The dst will be zero extended, so won't be sub-register anymore. */
2429 	reg->subreg_def = DEF_NOT_SUBREG;
2430 }
2431 
2432 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2433 			 enum reg_arg_type t)
2434 {
2435 	struct bpf_verifier_state *vstate = env->cur_state;
2436 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2437 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2438 	struct bpf_reg_state *reg, *regs = state->regs;
2439 	bool rw64;
2440 
2441 	if (regno >= MAX_BPF_REG) {
2442 		verbose(env, "R%d is invalid\n", regno);
2443 		return -EINVAL;
2444 	}
2445 
2446 	mark_reg_scratched(env, regno);
2447 
2448 	reg = &regs[regno];
2449 	rw64 = is_reg64(env, insn, regno, reg, t);
2450 	if (t == SRC_OP) {
2451 		/* check whether register used as source operand can be read */
2452 		if (reg->type == NOT_INIT) {
2453 			verbose(env, "R%d !read_ok\n", regno);
2454 			return -EACCES;
2455 		}
2456 		/* We don't need to worry about FP liveness because it's read-only */
2457 		if (regno == BPF_REG_FP)
2458 			return 0;
2459 
2460 		if (rw64)
2461 			mark_insn_zext(env, reg);
2462 
2463 		return mark_reg_read(env, reg, reg->parent,
2464 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2465 	} else {
2466 		/* check whether register used as dest operand can be written to */
2467 		if (regno == BPF_REG_FP) {
2468 			verbose(env, "frame pointer is read only\n");
2469 			return -EACCES;
2470 		}
2471 		reg->live |= REG_LIVE_WRITTEN;
2472 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2473 		if (t == DST_OP)
2474 			mark_reg_unknown(env, regs, regno);
2475 	}
2476 	return 0;
2477 }
2478 
2479 /* for any branch, call, exit record the history of jmps in the given state */
2480 static int push_jmp_history(struct bpf_verifier_env *env,
2481 			    struct bpf_verifier_state *cur)
2482 {
2483 	u32 cnt = cur->jmp_history_cnt;
2484 	struct bpf_idx_pair *p;
2485 
2486 	cnt++;
2487 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2488 	if (!p)
2489 		return -ENOMEM;
2490 	p[cnt - 1].idx = env->insn_idx;
2491 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2492 	cur->jmp_history = p;
2493 	cur->jmp_history_cnt = cnt;
2494 	return 0;
2495 }
2496 
2497 /* Backtrack one insn at a time. If idx is not at the top of recorded
2498  * history then previous instruction came from straight line execution.
2499  */
2500 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2501 			     u32 *history)
2502 {
2503 	u32 cnt = *history;
2504 
2505 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2506 		i = st->jmp_history[cnt - 1].prev_idx;
2507 		(*history)--;
2508 	} else {
2509 		i--;
2510 	}
2511 	return i;
2512 }
2513 
2514 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2515 {
2516 	const struct btf_type *func;
2517 	struct btf *desc_btf;
2518 
2519 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2520 		return NULL;
2521 
2522 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2523 	if (IS_ERR(desc_btf))
2524 		return "<error>";
2525 
2526 	func = btf_type_by_id(desc_btf, insn->imm);
2527 	return btf_name_by_offset(desc_btf, func->name_off);
2528 }
2529 
2530 /* For given verifier state backtrack_insn() is called from the last insn to
2531  * the first insn. Its purpose is to compute a bitmask of registers and
2532  * stack slots that needs precision in the parent verifier state.
2533  */
2534 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2535 			  u32 *reg_mask, u64 *stack_mask)
2536 {
2537 	const struct bpf_insn_cbs cbs = {
2538 		.cb_call	= disasm_kfunc_name,
2539 		.cb_print	= verbose,
2540 		.private_data	= env,
2541 	};
2542 	struct bpf_insn *insn = env->prog->insnsi + idx;
2543 	u8 class = BPF_CLASS(insn->code);
2544 	u8 opcode = BPF_OP(insn->code);
2545 	u8 mode = BPF_MODE(insn->code);
2546 	u32 dreg = 1u << insn->dst_reg;
2547 	u32 sreg = 1u << insn->src_reg;
2548 	u32 spi;
2549 
2550 	if (insn->code == 0)
2551 		return 0;
2552 	if (env->log.level & BPF_LOG_LEVEL2) {
2553 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2554 		verbose(env, "%d: ", idx);
2555 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2556 	}
2557 
2558 	if (class == BPF_ALU || class == BPF_ALU64) {
2559 		if (!(*reg_mask & dreg))
2560 			return 0;
2561 		if (opcode == BPF_MOV) {
2562 			if (BPF_SRC(insn->code) == BPF_X) {
2563 				/* dreg = sreg
2564 				 * dreg needs precision after this insn
2565 				 * sreg needs precision before this insn
2566 				 */
2567 				*reg_mask &= ~dreg;
2568 				*reg_mask |= sreg;
2569 			} else {
2570 				/* dreg = K
2571 				 * dreg needs precision after this insn.
2572 				 * Corresponding register is already marked
2573 				 * as precise=true in this verifier state.
2574 				 * No further markings in parent are necessary
2575 				 */
2576 				*reg_mask &= ~dreg;
2577 			}
2578 		} else {
2579 			if (BPF_SRC(insn->code) == BPF_X) {
2580 				/* dreg += sreg
2581 				 * both dreg and sreg need precision
2582 				 * before this insn
2583 				 */
2584 				*reg_mask |= sreg;
2585 			} /* else dreg += K
2586 			   * dreg still needs precision before this insn
2587 			   */
2588 		}
2589 	} else if (class == BPF_LDX) {
2590 		if (!(*reg_mask & dreg))
2591 			return 0;
2592 		*reg_mask &= ~dreg;
2593 
2594 		/* scalars can only be spilled into stack w/o losing precision.
2595 		 * Load from any other memory can be zero extended.
2596 		 * The desire to keep that precision is already indicated
2597 		 * by 'precise' mark in corresponding register of this state.
2598 		 * No further tracking necessary.
2599 		 */
2600 		if (insn->src_reg != BPF_REG_FP)
2601 			return 0;
2602 
2603 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2604 		 * that [fp - off] slot contains scalar that needs to be
2605 		 * tracked with precision
2606 		 */
2607 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2608 		if (spi >= 64) {
2609 			verbose(env, "BUG spi %d\n", spi);
2610 			WARN_ONCE(1, "verifier backtracking bug");
2611 			return -EFAULT;
2612 		}
2613 		*stack_mask |= 1ull << spi;
2614 	} else if (class == BPF_STX || class == BPF_ST) {
2615 		if (*reg_mask & dreg)
2616 			/* stx & st shouldn't be using _scalar_ dst_reg
2617 			 * to access memory. It means backtracking
2618 			 * encountered a case of pointer subtraction.
2619 			 */
2620 			return -ENOTSUPP;
2621 		/* scalars can only be spilled into stack */
2622 		if (insn->dst_reg != BPF_REG_FP)
2623 			return 0;
2624 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2625 		if (spi >= 64) {
2626 			verbose(env, "BUG spi %d\n", spi);
2627 			WARN_ONCE(1, "verifier backtracking bug");
2628 			return -EFAULT;
2629 		}
2630 		if (!(*stack_mask & (1ull << spi)))
2631 			return 0;
2632 		*stack_mask &= ~(1ull << spi);
2633 		if (class == BPF_STX)
2634 			*reg_mask |= sreg;
2635 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2636 		if (opcode == BPF_CALL) {
2637 			if (insn->src_reg == BPF_PSEUDO_CALL)
2638 				return -ENOTSUPP;
2639 			/* regular helper call sets R0 */
2640 			*reg_mask &= ~1;
2641 			if (*reg_mask & 0x3f) {
2642 				/* if backtracing was looking for registers R1-R5
2643 				 * they should have been found already.
2644 				 */
2645 				verbose(env, "BUG regs %x\n", *reg_mask);
2646 				WARN_ONCE(1, "verifier backtracking bug");
2647 				return -EFAULT;
2648 			}
2649 		} else if (opcode == BPF_EXIT) {
2650 			return -ENOTSUPP;
2651 		}
2652 	} else if (class == BPF_LD) {
2653 		if (!(*reg_mask & dreg))
2654 			return 0;
2655 		*reg_mask &= ~dreg;
2656 		/* It's ld_imm64 or ld_abs or ld_ind.
2657 		 * For ld_imm64 no further tracking of precision
2658 		 * into parent is necessary
2659 		 */
2660 		if (mode == BPF_IND || mode == BPF_ABS)
2661 			/* to be analyzed */
2662 			return -ENOTSUPP;
2663 	}
2664 	return 0;
2665 }
2666 
2667 /* the scalar precision tracking algorithm:
2668  * . at the start all registers have precise=false.
2669  * . scalar ranges are tracked as normal through alu and jmp insns.
2670  * . once precise value of the scalar register is used in:
2671  *   .  ptr + scalar alu
2672  *   . if (scalar cond K|scalar)
2673  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2674  *   backtrack through the verifier states and mark all registers and
2675  *   stack slots with spilled constants that these scalar regisers
2676  *   should be precise.
2677  * . during state pruning two registers (or spilled stack slots)
2678  *   are equivalent if both are not precise.
2679  *
2680  * Note the verifier cannot simply walk register parentage chain,
2681  * since many different registers and stack slots could have been
2682  * used to compute single precise scalar.
2683  *
2684  * The approach of starting with precise=true for all registers and then
2685  * backtrack to mark a register as not precise when the verifier detects
2686  * that program doesn't care about specific value (e.g., when helper
2687  * takes register as ARG_ANYTHING parameter) is not safe.
2688  *
2689  * It's ok to walk single parentage chain of the verifier states.
2690  * It's possible that this backtracking will go all the way till 1st insn.
2691  * All other branches will be explored for needing precision later.
2692  *
2693  * The backtracking needs to deal with cases like:
2694  *   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)
2695  * r9 -= r8
2696  * r5 = r9
2697  * if r5 > 0x79f goto pc+7
2698  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2699  * r5 += 1
2700  * ...
2701  * call bpf_perf_event_output#25
2702  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2703  *
2704  * and this case:
2705  * r6 = 1
2706  * call foo // uses callee's r6 inside to compute r0
2707  * r0 += r6
2708  * if r0 == 0 goto
2709  *
2710  * to track above reg_mask/stack_mask needs to be independent for each frame.
2711  *
2712  * Also if parent's curframe > frame where backtracking started,
2713  * the verifier need to mark registers in both frames, otherwise callees
2714  * may incorrectly prune callers. This is similar to
2715  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2716  *
2717  * For now backtracking falls back into conservative marking.
2718  */
2719 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2720 				     struct bpf_verifier_state *st)
2721 {
2722 	struct bpf_func_state *func;
2723 	struct bpf_reg_state *reg;
2724 	int i, j;
2725 
2726 	/* big hammer: mark all scalars precise in this path.
2727 	 * pop_stack may still get !precise scalars.
2728 	 */
2729 	for (; st; st = st->parent)
2730 		for (i = 0; i <= st->curframe; i++) {
2731 			func = st->frame[i];
2732 			for (j = 0; j < BPF_REG_FP; j++) {
2733 				reg = &func->regs[j];
2734 				if (reg->type != SCALAR_VALUE)
2735 					continue;
2736 				reg->precise = true;
2737 			}
2738 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2739 				if (!is_spilled_reg(&func->stack[j]))
2740 					continue;
2741 				reg = &func->stack[j].spilled_ptr;
2742 				if (reg->type != SCALAR_VALUE)
2743 					continue;
2744 				reg->precise = true;
2745 			}
2746 		}
2747 }
2748 
2749 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2750 				  int spi)
2751 {
2752 	struct bpf_verifier_state *st = env->cur_state;
2753 	int first_idx = st->first_insn_idx;
2754 	int last_idx = env->insn_idx;
2755 	struct bpf_func_state *func;
2756 	struct bpf_reg_state *reg;
2757 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2758 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2759 	bool skip_first = true;
2760 	bool new_marks = false;
2761 	int i, err;
2762 
2763 	if (!env->bpf_capable)
2764 		return 0;
2765 
2766 	func = st->frame[st->curframe];
2767 	if (regno >= 0) {
2768 		reg = &func->regs[regno];
2769 		if (reg->type != SCALAR_VALUE) {
2770 			WARN_ONCE(1, "backtracing misuse");
2771 			return -EFAULT;
2772 		}
2773 		if (!reg->precise)
2774 			new_marks = true;
2775 		else
2776 			reg_mask = 0;
2777 		reg->precise = true;
2778 	}
2779 
2780 	while (spi >= 0) {
2781 		if (!is_spilled_reg(&func->stack[spi])) {
2782 			stack_mask = 0;
2783 			break;
2784 		}
2785 		reg = &func->stack[spi].spilled_ptr;
2786 		if (reg->type != SCALAR_VALUE) {
2787 			stack_mask = 0;
2788 			break;
2789 		}
2790 		if (!reg->precise)
2791 			new_marks = true;
2792 		else
2793 			stack_mask = 0;
2794 		reg->precise = true;
2795 		break;
2796 	}
2797 
2798 	if (!new_marks)
2799 		return 0;
2800 	if (!reg_mask && !stack_mask)
2801 		return 0;
2802 	for (;;) {
2803 		DECLARE_BITMAP(mask, 64);
2804 		u32 history = st->jmp_history_cnt;
2805 
2806 		if (env->log.level & BPF_LOG_LEVEL2)
2807 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2808 		for (i = last_idx;;) {
2809 			if (skip_first) {
2810 				err = 0;
2811 				skip_first = false;
2812 			} else {
2813 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2814 			}
2815 			if (err == -ENOTSUPP) {
2816 				mark_all_scalars_precise(env, st);
2817 				return 0;
2818 			} else if (err) {
2819 				return err;
2820 			}
2821 			if (!reg_mask && !stack_mask)
2822 				/* Found assignment(s) into tracked register in this state.
2823 				 * Since this state is already marked, just return.
2824 				 * Nothing to be tracked further in the parent state.
2825 				 */
2826 				return 0;
2827 			if (i == first_idx)
2828 				break;
2829 			i = get_prev_insn_idx(st, i, &history);
2830 			if (i >= env->prog->len) {
2831 				/* This can happen if backtracking reached insn 0
2832 				 * and there are still reg_mask or stack_mask
2833 				 * to backtrack.
2834 				 * It means the backtracking missed the spot where
2835 				 * particular register was initialized with a constant.
2836 				 */
2837 				verbose(env, "BUG backtracking idx %d\n", i);
2838 				WARN_ONCE(1, "verifier backtracking bug");
2839 				return -EFAULT;
2840 			}
2841 		}
2842 		st = st->parent;
2843 		if (!st)
2844 			break;
2845 
2846 		new_marks = false;
2847 		func = st->frame[st->curframe];
2848 		bitmap_from_u64(mask, reg_mask);
2849 		for_each_set_bit(i, mask, 32) {
2850 			reg = &func->regs[i];
2851 			if (reg->type != SCALAR_VALUE) {
2852 				reg_mask &= ~(1u << i);
2853 				continue;
2854 			}
2855 			if (!reg->precise)
2856 				new_marks = true;
2857 			reg->precise = true;
2858 		}
2859 
2860 		bitmap_from_u64(mask, stack_mask);
2861 		for_each_set_bit(i, mask, 64) {
2862 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2863 				/* the sequence of instructions:
2864 				 * 2: (bf) r3 = r10
2865 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2866 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2867 				 * doesn't contain jmps. It's backtracked
2868 				 * as a single block.
2869 				 * During backtracking insn 3 is not recognized as
2870 				 * stack access, so at the end of backtracking
2871 				 * stack slot fp-8 is still marked in stack_mask.
2872 				 * However the parent state may not have accessed
2873 				 * fp-8 and it's "unallocated" stack space.
2874 				 * In such case fallback to conservative.
2875 				 */
2876 				mark_all_scalars_precise(env, st);
2877 				return 0;
2878 			}
2879 
2880 			if (!is_spilled_reg(&func->stack[i])) {
2881 				stack_mask &= ~(1ull << i);
2882 				continue;
2883 			}
2884 			reg = &func->stack[i].spilled_ptr;
2885 			if (reg->type != SCALAR_VALUE) {
2886 				stack_mask &= ~(1ull << i);
2887 				continue;
2888 			}
2889 			if (!reg->precise)
2890 				new_marks = true;
2891 			reg->precise = true;
2892 		}
2893 		if (env->log.level & BPF_LOG_LEVEL2) {
2894 			verbose(env, "parent %s regs=%x stack=%llx marks:",
2895 				new_marks ? "didn't have" : "already had",
2896 				reg_mask, stack_mask);
2897 			print_verifier_state(env, func, true);
2898 		}
2899 
2900 		if (!reg_mask && !stack_mask)
2901 			break;
2902 		if (!new_marks)
2903 			break;
2904 
2905 		last_idx = st->last_insn_idx;
2906 		first_idx = st->first_insn_idx;
2907 	}
2908 	return 0;
2909 }
2910 
2911 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2912 {
2913 	return __mark_chain_precision(env, regno, -1);
2914 }
2915 
2916 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2917 {
2918 	return __mark_chain_precision(env, -1, spi);
2919 }
2920 
2921 static bool is_spillable_regtype(enum bpf_reg_type type)
2922 {
2923 	switch (base_type(type)) {
2924 	case PTR_TO_MAP_VALUE:
2925 	case PTR_TO_STACK:
2926 	case PTR_TO_CTX:
2927 	case PTR_TO_PACKET:
2928 	case PTR_TO_PACKET_META:
2929 	case PTR_TO_PACKET_END:
2930 	case PTR_TO_FLOW_KEYS:
2931 	case CONST_PTR_TO_MAP:
2932 	case PTR_TO_SOCKET:
2933 	case PTR_TO_SOCK_COMMON:
2934 	case PTR_TO_TCP_SOCK:
2935 	case PTR_TO_XDP_SOCK:
2936 	case PTR_TO_BTF_ID:
2937 	case PTR_TO_BUF:
2938 	case PTR_TO_MEM:
2939 	case PTR_TO_FUNC:
2940 	case PTR_TO_MAP_KEY:
2941 		return true;
2942 	default:
2943 		return false;
2944 	}
2945 }
2946 
2947 /* Does this register contain a constant zero? */
2948 static bool register_is_null(struct bpf_reg_state *reg)
2949 {
2950 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2951 }
2952 
2953 static bool register_is_const(struct bpf_reg_state *reg)
2954 {
2955 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2956 }
2957 
2958 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2959 {
2960 	return tnum_is_unknown(reg->var_off) &&
2961 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2962 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2963 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2964 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2965 }
2966 
2967 static bool register_is_bounded(struct bpf_reg_state *reg)
2968 {
2969 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2970 }
2971 
2972 static bool __is_pointer_value(bool allow_ptr_leaks,
2973 			       const struct bpf_reg_state *reg)
2974 {
2975 	if (allow_ptr_leaks)
2976 		return false;
2977 
2978 	return reg->type != SCALAR_VALUE;
2979 }
2980 
2981 static void save_register_state(struct bpf_func_state *state,
2982 				int spi, struct bpf_reg_state *reg,
2983 				int size)
2984 {
2985 	int i;
2986 
2987 	state->stack[spi].spilled_ptr = *reg;
2988 	if (size == BPF_REG_SIZE)
2989 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2990 
2991 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2992 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2993 
2994 	/* size < 8 bytes spill */
2995 	for (; i; i--)
2996 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2997 }
2998 
2999 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3000  * stack boundary and alignment are checked in check_mem_access()
3001  */
3002 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3003 				       /* stack frame we're writing to */
3004 				       struct bpf_func_state *state,
3005 				       int off, int size, int value_regno,
3006 				       int insn_idx)
3007 {
3008 	struct bpf_func_state *cur; /* state of the current function */
3009 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3010 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3011 	struct bpf_reg_state *reg = NULL;
3012 
3013 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3014 	if (err)
3015 		return err;
3016 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3017 	 * so it's aligned access and [off, off + size) are within stack limits
3018 	 */
3019 	if (!env->allow_ptr_leaks &&
3020 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3021 	    size != BPF_REG_SIZE) {
3022 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3023 		return -EACCES;
3024 	}
3025 
3026 	cur = env->cur_state->frame[env->cur_state->curframe];
3027 	if (value_regno >= 0)
3028 		reg = &cur->regs[value_regno];
3029 	if (!env->bypass_spec_v4) {
3030 		bool sanitize = reg && is_spillable_regtype(reg->type);
3031 
3032 		for (i = 0; i < size; i++) {
3033 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3034 				sanitize = true;
3035 				break;
3036 			}
3037 		}
3038 
3039 		if (sanitize)
3040 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3041 	}
3042 
3043 	mark_stack_slot_scratched(env, spi);
3044 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3045 	    !register_is_null(reg) && env->bpf_capable) {
3046 		if (dst_reg != BPF_REG_FP) {
3047 			/* The backtracking logic can only recognize explicit
3048 			 * stack slot address like [fp - 8]. Other spill of
3049 			 * scalar via different register has to be conservative.
3050 			 * Backtrack from here and mark all registers as precise
3051 			 * that contributed into 'reg' being a constant.
3052 			 */
3053 			err = mark_chain_precision(env, value_regno);
3054 			if (err)
3055 				return err;
3056 		}
3057 		save_register_state(state, spi, reg, size);
3058 	} else if (reg && is_spillable_regtype(reg->type)) {
3059 		/* register containing pointer is being spilled into stack */
3060 		if (size != BPF_REG_SIZE) {
3061 			verbose_linfo(env, insn_idx, "; ");
3062 			verbose(env, "invalid size of register spill\n");
3063 			return -EACCES;
3064 		}
3065 		if (state != cur && reg->type == PTR_TO_STACK) {
3066 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3067 			return -EINVAL;
3068 		}
3069 		save_register_state(state, spi, reg, size);
3070 	} else {
3071 		u8 type = STACK_MISC;
3072 
3073 		/* regular write of data into stack destroys any spilled ptr */
3074 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3075 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3076 		if (is_spilled_reg(&state->stack[spi]))
3077 			for (i = 0; i < BPF_REG_SIZE; i++)
3078 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3079 
3080 		/* only mark the slot as written if all 8 bytes were written
3081 		 * otherwise read propagation may incorrectly stop too soon
3082 		 * when stack slots are partially written.
3083 		 * This heuristic means that read propagation will be
3084 		 * conservative, since it will add reg_live_read marks
3085 		 * to stack slots all the way to first state when programs
3086 		 * writes+reads less than 8 bytes
3087 		 */
3088 		if (size == BPF_REG_SIZE)
3089 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3090 
3091 		/* when we zero initialize stack slots mark them as such */
3092 		if (reg && register_is_null(reg)) {
3093 			/* backtracking doesn't work for STACK_ZERO yet. */
3094 			err = mark_chain_precision(env, value_regno);
3095 			if (err)
3096 				return err;
3097 			type = STACK_ZERO;
3098 		}
3099 
3100 		/* Mark slots affected by this stack write. */
3101 		for (i = 0; i < size; i++)
3102 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3103 				type;
3104 	}
3105 	return 0;
3106 }
3107 
3108 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3109  * known to contain a variable offset.
3110  * This function checks whether the write is permitted and conservatively
3111  * tracks the effects of the write, considering that each stack slot in the
3112  * dynamic range is potentially written to.
3113  *
3114  * 'off' includes 'regno->off'.
3115  * 'value_regno' can be -1, meaning that an unknown value is being written to
3116  * the stack.
3117  *
3118  * Spilled pointers in range are not marked as written because we don't know
3119  * what's going to be actually written. This means that read propagation for
3120  * future reads cannot be terminated by this write.
3121  *
3122  * For privileged programs, uninitialized stack slots are considered
3123  * initialized by this write (even though we don't know exactly what offsets
3124  * are going to be written to). The idea is that we don't want the verifier to
3125  * reject future reads that access slots written to through variable offsets.
3126  */
3127 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3128 				     /* func where register points to */
3129 				     struct bpf_func_state *state,
3130 				     int ptr_regno, int off, int size,
3131 				     int value_regno, int insn_idx)
3132 {
3133 	struct bpf_func_state *cur; /* state of the current function */
3134 	int min_off, max_off;
3135 	int i, err;
3136 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3137 	bool writing_zero = false;
3138 	/* set if the fact that we're writing a zero is used to let any
3139 	 * stack slots remain STACK_ZERO
3140 	 */
3141 	bool zero_used = false;
3142 
3143 	cur = env->cur_state->frame[env->cur_state->curframe];
3144 	ptr_reg = &cur->regs[ptr_regno];
3145 	min_off = ptr_reg->smin_value + off;
3146 	max_off = ptr_reg->smax_value + off + size;
3147 	if (value_regno >= 0)
3148 		value_reg = &cur->regs[value_regno];
3149 	if (value_reg && register_is_null(value_reg))
3150 		writing_zero = true;
3151 
3152 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3153 	if (err)
3154 		return err;
3155 
3156 
3157 	/* Variable offset writes destroy any spilled pointers in range. */
3158 	for (i = min_off; i < max_off; i++) {
3159 		u8 new_type, *stype;
3160 		int slot, spi;
3161 
3162 		slot = -i - 1;
3163 		spi = slot / BPF_REG_SIZE;
3164 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3165 		mark_stack_slot_scratched(env, spi);
3166 
3167 		if (!env->allow_ptr_leaks
3168 				&& *stype != NOT_INIT
3169 				&& *stype != SCALAR_VALUE) {
3170 			/* Reject the write if there's are spilled pointers in
3171 			 * range. If we didn't reject here, the ptr status
3172 			 * would be erased below (even though not all slots are
3173 			 * actually overwritten), possibly opening the door to
3174 			 * leaks.
3175 			 */
3176 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3177 				insn_idx, i);
3178 			return -EINVAL;
3179 		}
3180 
3181 		/* Erase all spilled pointers. */
3182 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3183 
3184 		/* Update the slot type. */
3185 		new_type = STACK_MISC;
3186 		if (writing_zero && *stype == STACK_ZERO) {
3187 			new_type = STACK_ZERO;
3188 			zero_used = true;
3189 		}
3190 		/* If the slot is STACK_INVALID, we check whether it's OK to
3191 		 * pretend that it will be initialized by this write. The slot
3192 		 * might not actually be written to, and so if we mark it as
3193 		 * initialized future reads might leak uninitialized memory.
3194 		 * For privileged programs, we will accept such reads to slots
3195 		 * that may or may not be written because, if we're reject
3196 		 * them, the error would be too confusing.
3197 		 */
3198 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3199 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3200 					insn_idx, i);
3201 			return -EINVAL;
3202 		}
3203 		*stype = new_type;
3204 	}
3205 	if (zero_used) {
3206 		/* backtracking doesn't work for STACK_ZERO yet. */
3207 		err = mark_chain_precision(env, value_regno);
3208 		if (err)
3209 			return err;
3210 	}
3211 	return 0;
3212 }
3213 
3214 /* When register 'dst_regno' is assigned some values from stack[min_off,
3215  * max_off), we set the register's type according to the types of the
3216  * respective stack slots. If all the stack values are known to be zeros, then
3217  * so is the destination reg. Otherwise, the register is considered to be
3218  * SCALAR. This function does not deal with register filling; the caller must
3219  * ensure that all spilled registers in the stack range have been marked as
3220  * read.
3221  */
3222 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3223 				/* func where src register points to */
3224 				struct bpf_func_state *ptr_state,
3225 				int min_off, int max_off, int dst_regno)
3226 {
3227 	struct bpf_verifier_state *vstate = env->cur_state;
3228 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3229 	int i, slot, spi;
3230 	u8 *stype;
3231 	int zeros = 0;
3232 
3233 	for (i = min_off; i < max_off; i++) {
3234 		slot = -i - 1;
3235 		spi = slot / BPF_REG_SIZE;
3236 		stype = ptr_state->stack[spi].slot_type;
3237 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3238 			break;
3239 		zeros++;
3240 	}
3241 	if (zeros == max_off - min_off) {
3242 		/* any access_size read into register is zero extended,
3243 		 * so the whole register == const_zero
3244 		 */
3245 		__mark_reg_const_zero(&state->regs[dst_regno]);
3246 		/* backtracking doesn't support STACK_ZERO yet,
3247 		 * so mark it precise here, so that later
3248 		 * backtracking can stop here.
3249 		 * Backtracking may not need this if this register
3250 		 * doesn't participate in pointer adjustment.
3251 		 * Forward propagation of precise flag is not
3252 		 * necessary either. This mark is only to stop
3253 		 * backtracking. Any register that contributed
3254 		 * to const 0 was marked precise before spill.
3255 		 */
3256 		state->regs[dst_regno].precise = true;
3257 	} else {
3258 		/* have read misc data from the stack */
3259 		mark_reg_unknown(env, state->regs, dst_regno);
3260 	}
3261 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3262 }
3263 
3264 /* Read the stack at 'off' and put the results into the register indicated by
3265  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3266  * spilled reg.
3267  *
3268  * 'dst_regno' can be -1, meaning that the read value is not going to a
3269  * register.
3270  *
3271  * The access is assumed to be within the current stack bounds.
3272  */
3273 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3274 				      /* func where src register points to */
3275 				      struct bpf_func_state *reg_state,
3276 				      int off, int size, int dst_regno)
3277 {
3278 	struct bpf_verifier_state *vstate = env->cur_state;
3279 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3280 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3281 	struct bpf_reg_state *reg;
3282 	u8 *stype, type;
3283 
3284 	stype = reg_state->stack[spi].slot_type;
3285 	reg = &reg_state->stack[spi].spilled_ptr;
3286 
3287 	if (is_spilled_reg(&reg_state->stack[spi])) {
3288 		u8 spill_size = 1;
3289 
3290 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3291 			spill_size++;
3292 
3293 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3294 			if (reg->type != SCALAR_VALUE) {
3295 				verbose_linfo(env, env->insn_idx, "; ");
3296 				verbose(env, "invalid size of register fill\n");
3297 				return -EACCES;
3298 			}
3299 
3300 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3301 			if (dst_regno < 0)
3302 				return 0;
3303 
3304 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3305 				/* The earlier check_reg_arg() has decided the
3306 				 * subreg_def for this insn.  Save it first.
3307 				 */
3308 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3309 
3310 				state->regs[dst_regno] = *reg;
3311 				state->regs[dst_regno].subreg_def = subreg_def;
3312 			} else {
3313 				for (i = 0; i < size; i++) {
3314 					type = stype[(slot - i) % BPF_REG_SIZE];
3315 					if (type == STACK_SPILL)
3316 						continue;
3317 					if (type == STACK_MISC)
3318 						continue;
3319 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3320 						off, i, size);
3321 					return -EACCES;
3322 				}
3323 				mark_reg_unknown(env, state->regs, dst_regno);
3324 			}
3325 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3326 			return 0;
3327 		}
3328 
3329 		if (dst_regno >= 0) {
3330 			/* restore register state from stack */
3331 			state->regs[dst_regno] = *reg;
3332 			/* mark reg as written since spilled pointer state likely
3333 			 * has its liveness marks cleared by is_state_visited()
3334 			 * which resets stack/reg liveness for state transitions
3335 			 */
3336 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3337 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3338 			/* If dst_regno==-1, the caller is asking us whether
3339 			 * it is acceptable to use this value as a SCALAR_VALUE
3340 			 * (e.g. for XADD).
3341 			 * We must not allow unprivileged callers to do that
3342 			 * with spilled pointers.
3343 			 */
3344 			verbose(env, "leaking pointer from stack off %d\n",
3345 				off);
3346 			return -EACCES;
3347 		}
3348 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3349 	} else {
3350 		for (i = 0; i < size; i++) {
3351 			type = stype[(slot - i) % BPF_REG_SIZE];
3352 			if (type == STACK_MISC)
3353 				continue;
3354 			if (type == STACK_ZERO)
3355 				continue;
3356 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3357 				off, i, size);
3358 			return -EACCES;
3359 		}
3360 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3361 		if (dst_regno >= 0)
3362 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3363 	}
3364 	return 0;
3365 }
3366 
3367 enum bpf_access_src {
3368 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3369 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3370 };
3371 
3372 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3373 					 int regno, int off, int access_size,
3374 					 bool zero_size_allowed,
3375 					 enum bpf_access_src type,
3376 					 struct bpf_call_arg_meta *meta);
3377 
3378 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3379 {
3380 	return cur_regs(env) + regno;
3381 }
3382 
3383 /* Read the stack at 'ptr_regno + off' and put the result into the register
3384  * 'dst_regno'.
3385  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3386  * but not its variable offset.
3387  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3388  *
3389  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3390  * filling registers (i.e. reads of spilled register cannot be detected when
3391  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3392  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3393  * offset; for a fixed offset check_stack_read_fixed_off should be used
3394  * instead.
3395  */
3396 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3397 				    int ptr_regno, int off, int size, int dst_regno)
3398 {
3399 	/* The state of the source register. */
3400 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3401 	struct bpf_func_state *ptr_state = func(env, reg);
3402 	int err;
3403 	int min_off, max_off;
3404 
3405 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3406 	 */
3407 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3408 					    false, ACCESS_DIRECT, NULL);
3409 	if (err)
3410 		return err;
3411 
3412 	min_off = reg->smin_value + off;
3413 	max_off = reg->smax_value + off;
3414 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3415 	return 0;
3416 }
3417 
3418 /* check_stack_read dispatches to check_stack_read_fixed_off or
3419  * check_stack_read_var_off.
3420  *
3421  * The caller must ensure that the offset falls within the allocated stack
3422  * bounds.
3423  *
3424  * 'dst_regno' is a register which will receive the value from the stack. It
3425  * can be -1, meaning that the read value is not going to a register.
3426  */
3427 static int check_stack_read(struct bpf_verifier_env *env,
3428 			    int ptr_regno, int off, int size,
3429 			    int dst_regno)
3430 {
3431 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3432 	struct bpf_func_state *state = func(env, reg);
3433 	int err;
3434 	/* Some accesses are only permitted with a static offset. */
3435 	bool var_off = !tnum_is_const(reg->var_off);
3436 
3437 	/* The offset is required to be static when reads don't go to a
3438 	 * register, in order to not leak pointers (see
3439 	 * check_stack_read_fixed_off).
3440 	 */
3441 	if (dst_regno < 0 && var_off) {
3442 		char tn_buf[48];
3443 
3444 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3445 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3446 			tn_buf, off, size);
3447 		return -EACCES;
3448 	}
3449 	/* Variable offset is prohibited for unprivileged mode for simplicity
3450 	 * since it requires corresponding support in Spectre masking for stack
3451 	 * ALU. See also retrieve_ptr_limit().
3452 	 */
3453 	if (!env->bypass_spec_v1 && var_off) {
3454 		char tn_buf[48];
3455 
3456 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3457 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3458 				ptr_regno, tn_buf);
3459 		return -EACCES;
3460 	}
3461 
3462 	if (!var_off) {
3463 		off += reg->var_off.value;
3464 		err = check_stack_read_fixed_off(env, state, off, size,
3465 						 dst_regno);
3466 	} else {
3467 		/* Variable offset stack reads need more conservative handling
3468 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3469 		 * branch.
3470 		 */
3471 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3472 					       dst_regno);
3473 	}
3474 	return err;
3475 }
3476 
3477 
3478 /* check_stack_write dispatches to check_stack_write_fixed_off or
3479  * check_stack_write_var_off.
3480  *
3481  * 'ptr_regno' is the register used as a pointer into the stack.
3482  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3483  * 'value_regno' is the register whose value we're writing to the stack. It can
3484  * be -1, meaning that we're not writing from a register.
3485  *
3486  * The caller must ensure that the offset falls within the maximum stack size.
3487  */
3488 static int check_stack_write(struct bpf_verifier_env *env,
3489 			     int ptr_regno, int off, int size,
3490 			     int value_regno, int insn_idx)
3491 {
3492 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3493 	struct bpf_func_state *state = func(env, reg);
3494 	int err;
3495 
3496 	if (tnum_is_const(reg->var_off)) {
3497 		off += reg->var_off.value;
3498 		err = check_stack_write_fixed_off(env, state, off, size,
3499 						  value_regno, insn_idx);
3500 	} else {
3501 		/* Variable offset stack reads need more conservative handling
3502 		 * than fixed offset ones.
3503 		 */
3504 		err = check_stack_write_var_off(env, state,
3505 						ptr_regno, off, size,
3506 						value_regno, insn_idx);
3507 	}
3508 	return err;
3509 }
3510 
3511 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3512 				 int off, int size, enum bpf_access_type type)
3513 {
3514 	struct bpf_reg_state *regs = cur_regs(env);
3515 	struct bpf_map *map = regs[regno].map_ptr;
3516 	u32 cap = bpf_map_flags_to_cap(map);
3517 
3518 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3519 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3520 			map->value_size, off, size);
3521 		return -EACCES;
3522 	}
3523 
3524 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3525 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3526 			map->value_size, off, size);
3527 		return -EACCES;
3528 	}
3529 
3530 	return 0;
3531 }
3532 
3533 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3534 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3535 			      int off, int size, u32 mem_size,
3536 			      bool zero_size_allowed)
3537 {
3538 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3539 	struct bpf_reg_state *reg;
3540 
3541 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3542 		return 0;
3543 
3544 	reg = &cur_regs(env)[regno];
3545 	switch (reg->type) {
3546 	case PTR_TO_MAP_KEY:
3547 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3548 			mem_size, off, size);
3549 		break;
3550 	case PTR_TO_MAP_VALUE:
3551 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3552 			mem_size, off, size);
3553 		break;
3554 	case PTR_TO_PACKET:
3555 	case PTR_TO_PACKET_META:
3556 	case PTR_TO_PACKET_END:
3557 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3558 			off, size, regno, reg->id, off, mem_size);
3559 		break;
3560 	case PTR_TO_MEM:
3561 	default:
3562 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3563 			mem_size, off, size);
3564 	}
3565 
3566 	return -EACCES;
3567 }
3568 
3569 /* check read/write into a memory region with possible variable offset */
3570 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3571 				   int off, int size, u32 mem_size,
3572 				   bool zero_size_allowed)
3573 {
3574 	struct bpf_verifier_state *vstate = env->cur_state;
3575 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3576 	struct bpf_reg_state *reg = &state->regs[regno];
3577 	int err;
3578 
3579 	/* We may have adjusted the register pointing to memory region, so we
3580 	 * need to try adding each of min_value and max_value to off
3581 	 * to make sure our theoretical access will be safe.
3582 	 *
3583 	 * The minimum value is only important with signed
3584 	 * comparisons where we can't assume the floor of a
3585 	 * value is 0.  If we are using signed variables for our
3586 	 * index'es we need to make sure that whatever we use
3587 	 * will have a set floor within our range.
3588 	 */
3589 	if (reg->smin_value < 0 &&
3590 	    (reg->smin_value == S64_MIN ||
3591 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3592 	      reg->smin_value + off < 0)) {
3593 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3594 			regno);
3595 		return -EACCES;
3596 	}
3597 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3598 				 mem_size, zero_size_allowed);
3599 	if (err) {
3600 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3601 			regno);
3602 		return err;
3603 	}
3604 
3605 	/* If we haven't set a max value then we need to bail since we can't be
3606 	 * sure we won't do bad things.
3607 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3608 	 */
3609 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3610 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3611 			regno);
3612 		return -EACCES;
3613 	}
3614 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3615 				 mem_size, zero_size_allowed);
3616 	if (err) {
3617 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3618 			regno);
3619 		return err;
3620 	}
3621 
3622 	return 0;
3623 }
3624 
3625 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3626 			       const struct bpf_reg_state *reg, int regno,
3627 			       bool fixed_off_ok)
3628 {
3629 	/* Access to this pointer-typed register or passing it to a helper
3630 	 * is only allowed in its original, unmodified form.
3631 	 */
3632 
3633 	if (reg->off < 0) {
3634 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3635 			reg_type_str(env, reg->type), regno, reg->off);
3636 		return -EACCES;
3637 	}
3638 
3639 	if (!fixed_off_ok && reg->off) {
3640 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3641 			reg_type_str(env, reg->type), regno, reg->off);
3642 		return -EACCES;
3643 	}
3644 
3645 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3646 		char tn_buf[48];
3647 
3648 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3649 		verbose(env, "variable %s access var_off=%s disallowed\n",
3650 			reg_type_str(env, reg->type), tn_buf);
3651 		return -EACCES;
3652 	}
3653 
3654 	return 0;
3655 }
3656 
3657 int check_ptr_off_reg(struct bpf_verifier_env *env,
3658 		      const struct bpf_reg_state *reg, int regno)
3659 {
3660 	return __check_ptr_off_reg(env, reg, regno, false);
3661 }
3662 
3663 static int map_kptr_match_type(struct bpf_verifier_env *env,
3664 			       struct bpf_map_value_off_desc *off_desc,
3665 			       struct bpf_reg_state *reg, u32 regno)
3666 {
3667 	const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3668 	int perm_flags = PTR_MAYBE_NULL;
3669 	const char *reg_name = "";
3670 
3671 	/* Only unreferenced case accepts untrusted pointers */
3672 	if (off_desc->type == BPF_KPTR_UNREF)
3673 		perm_flags |= PTR_UNTRUSTED;
3674 
3675 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3676 		goto bad_type;
3677 
3678 	if (!btf_is_kernel(reg->btf)) {
3679 		verbose(env, "R%d must point to kernel BTF\n", regno);
3680 		return -EINVAL;
3681 	}
3682 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3683 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3684 
3685 	/* For ref_ptr case, release function check should ensure we get one
3686 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3687 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3688 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3689 	 * reg->off and reg->ref_obj_id are not needed here.
3690 	 */
3691 	if (__check_ptr_off_reg(env, reg, regno, true))
3692 		return -EACCES;
3693 
3694 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3695 	 * we also need to take into account the reg->off.
3696 	 *
3697 	 * We want to support cases like:
3698 	 *
3699 	 * struct foo {
3700 	 *         struct bar br;
3701 	 *         struct baz bz;
3702 	 * };
3703 	 *
3704 	 * struct foo *v;
3705 	 * v = func();	      // PTR_TO_BTF_ID
3706 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3707 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3708 	 *                    // first member type of struct after comparison fails
3709 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3710 	 *                    // to match type
3711 	 *
3712 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3713 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3714 	 * the struct to match type against first member of struct, i.e. reject
3715 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3716 	 * strict mode to true for type match.
3717 	 */
3718 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3719 				  off_desc->kptr.btf, off_desc->kptr.btf_id,
3720 				  off_desc->type == BPF_KPTR_REF))
3721 		goto bad_type;
3722 	return 0;
3723 bad_type:
3724 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3725 		reg_type_str(env, reg->type), reg_name);
3726 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3727 	if (off_desc->type == BPF_KPTR_UNREF)
3728 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3729 			targ_name);
3730 	else
3731 		verbose(env, "\n");
3732 	return -EINVAL;
3733 }
3734 
3735 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3736 				 int value_regno, int insn_idx,
3737 				 struct bpf_map_value_off_desc *off_desc)
3738 {
3739 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3740 	int class = BPF_CLASS(insn->code);
3741 	struct bpf_reg_state *val_reg;
3742 
3743 	/* Things we already checked for in check_map_access and caller:
3744 	 *  - Reject cases where variable offset may touch kptr
3745 	 *  - size of access (must be BPF_DW)
3746 	 *  - tnum_is_const(reg->var_off)
3747 	 *  - off_desc->offset == off + reg->var_off.value
3748 	 */
3749 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3750 	if (BPF_MODE(insn->code) != BPF_MEM) {
3751 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3752 		return -EACCES;
3753 	}
3754 
3755 	/* We only allow loading referenced kptr, since it will be marked as
3756 	 * untrusted, similar to unreferenced kptr.
3757 	 */
3758 	if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3759 		verbose(env, "store to referenced kptr disallowed\n");
3760 		return -EACCES;
3761 	}
3762 
3763 	if (class == BPF_LDX) {
3764 		val_reg = reg_state(env, value_regno);
3765 		/* We can simply mark the value_regno receiving the pointer
3766 		 * value from map as PTR_TO_BTF_ID, with the correct type.
3767 		 */
3768 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3769 				off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3770 		/* For mark_ptr_or_null_reg */
3771 		val_reg->id = ++env->id_gen;
3772 	} else if (class == BPF_STX) {
3773 		val_reg = reg_state(env, value_regno);
3774 		if (!register_is_null(val_reg) &&
3775 		    map_kptr_match_type(env, off_desc, val_reg, value_regno))
3776 			return -EACCES;
3777 	} else if (class == BPF_ST) {
3778 		if (insn->imm) {
3779 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3780 				off_desc->offset);
3781 			return -EACCES;
3782 		}
3783 	} else {
3784 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3785 		return -EACCES;
3786 	}
3787 	return 0;
3788 }
3789 
3790 /* check read/write into a map element with possible variable offset */
3791 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3792 			    int off, int size, bool zero_size_allowed,
3793 			    enum bpf_access_src src)
3794 {
3795 	struct bpf_verifier_state *vstate = env->cur_state;
3796 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3797 	struct bpf_reg_state *reg = &state->regs[regno];
3798 	struct bpf_map *map = reg->map_ptr;
3799 	int err;
3800 
3801 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3802 				      zero_size_allowed);
3803 	if (err)
3804 		return err;
3805 
3806 	if (map_value_has_spin_lock(map)) {
3807 		u32 lock = map->spin_lock_off;
3808 
3809 		/* if any part of struct bpf_spin_lock can be touched by
3810 		 * load/store reject this program.
3811 		 * To check that [x1, x2) overlaps with [y1, y2)
3812 		 * it is sufficient to check x1 < y2 && y1 < x2.
3813 		 */
3814 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3815 		     lock < reg->umax_value + off + size) {
3816 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3817 			return -EACCES;
3818 		}
3819 	}
3820 	if (map_value_has_timer(map)) {
3821 		u32 t = map->timer_off;
3822 
3823 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3824 		     t < reg->umax_value + off + size) {
3825 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3826 			return -EACCES;
3827 		}
3828 	}
3829 	if (map_value_has_kptrs(map)) {
3830 		struct bpf_map_value_off *tab = map->kptr_off_tab;
3831 		int i;
3832 
3833 		for (i = 0; i < tab->nr_off; i++) {
3834 			u32 p = tab->off[i].offset;
3835 
3836 			if (reg->smin_value + off < p + sizeof(u64) &&
3837 			    p < reg->umax_value + off + size) {
3838 				if (src != ACCESS_DIRECT) {
3839 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
3840 					return -EACCES;
3841 				}
3842 				if (!tnum_is_const(reg->var_off)) {
3843 					verbose(env, "kptr access cannot have variable offset\n");
3844 					return -EACCES;
3845 				}
3846 				if (p != off + reg->var_off.value) {
3847 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3848 						p, off + reg->var_off.value);
3849 					return -EACCES;
3850 				}
3851 				if (size != bpf_size_to_bytes(BPF_DW)) {
3852 					verbose(env, "kptr access size must be BPF_DW\n");
3853 					return -EACCES;
3854 				}
3855 				break;
3856 			}
3857 		}
3858 	}
3859 	return err;
3860 }
3861 
3862 #define MAX_PACKET_OFF 0xffff
3863 
3864 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3865 				       const struct bpf_call_arg_meta *meta,
3866 				       enum bpf_access_type t)
3867 {
3868 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3869 
3870 	switch (prog_type) {
3871 	/* Program types only with direct read access go here! */
3872 	case BPF_PROG_TYPE_LWT_IN:
3873 	case BPF_PROG_TYPE_LWT_OUT:
3874 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3875 	case BPF_PROG_TYPE_SK_REUSEPORT:
3876 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3877 	case BPF_PROG_TYPE_CGROUP_SKB:
3878 		if (t == BPF_WRITE)
3879 			return false;
3880 		fallthrough;
3881 
3882 	/* Program types with direct read + write access go here! */
3883 	case BPF_PROG_TYPE_SCHED_CLS:
3884 	case BPF_PROG_TYPE_SCHED_ACT:
3885 	case BPF_PROG_TYPE_XDP:
3886 	case BPF_PROG_TYPE_LWT_XMIT:
3887 	case BPF_PROG_TYPE_SK_SKB:
3888 	case BPF_PROG_TYPE_SK_MSG:
3889 		if (meta)
3890 			return meta->pkt_access;
3891 
3892 		env->seen_direct_write = true;
3893 		return true;
3894 
3895 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3896 		if (t == BPF_WRITE)
3897 			env->seen_direct_write = true;
3898 
3899 		return true;
3900 
3901 	default:
3902 		return false;
3903 	}
3904 }
3905 
3906 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3907 			       int size, bool zero_size_allowed)
3908 {
3909 	struct bpf_reg_state *regs = cur_regs(env);
3910 	struct bpf_reg_state *reg = &regs[regno];
3911 	int err;
3912 
3913 	/* We may have added a variable offset to the packet pointer; but any
3914 	 * reg->range we have comes after that.  We are only checking the fixed
3915 	 * offset.
3916 	 */
3917 
3918 	/* We don't allow negative numbers, because we aren't tracking enough
3919 	 * detail to prove they're safe.
3920 	 */
3921 	if (reg->smin_value < 0) {
3922 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3923 			regno);
3924 		return -EACCES;
3925 	}
3926 
3927 	err = reg->range < 0 ? -EINVAL :
3928 	      __check_mem_access(env, regno, off, size, reg->range,
3929 				 zero_size_allowed);
3930 	if (err) {
3931 		verbose(env, "R%d offset is outside of the packet\n", regno);
3932 		return err;
3933 	}
3934 
3935 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3936 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3937 	 * otherwise find_good_pkt_pointers would have refused to set range info
3938 	 * that __check_mem_access would have rejected this pkt access.
3939 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3940 	 */
3941 	env->prog->aux->max_pkt_offset =
3942 		max_t(u32, env->prog->aux->max_pkt_offset,
3943 		      off + reg->umax_value + size - 1);
3944 
3945 	return err;
3946 }
3947 
3948 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3949 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3950 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3951 			    struct btf **btf, u32 *btf_id)
3952 {
3953 	struct bpf_insn_access_aux info = {
3954 		.reg_type = *reg_type,
3955 		.log = &env->log,
3956 	};
3957 
3958 	if (env->ops->is_valid_access &&
3959 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3960 		/* A non zero info.ctx_field_size indicates that this field is a
3961 		 * candidate for later verifier transformation to load the whole
3962 		 * field and then apply a mask when accessed with a narrower
3963 		 * access than actual ctx access size. A zero info.ctx_field_size
3964 		 * will only allow for whole field access and rejects any other
3965 		 * type of narrower access.
3966 		 */
3967 		*reg_type = info.reg_type;
3968 
3969 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3970 			*btf = info.btf;
3971 			*btf_id = info.btf_id;
3972 		} else {
3973 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3974 		}
3975 		/* remember the offset of last byte accessed in ctx */
3976 		if (env->prog->aux->max_ctx_offset < off + size)
3977 			env->prog->aux->max_ctx_offset = off + size;
3978 		return 0;
3979 	}
3980 
3981 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3982 	return -EACCES;
3983 }
3984 
3985 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3986 				  int size)
3987 {
3988 	if (size < 0 || off < 0 ||
3989 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3990 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3991 			off, size);
3992 		return -EACCES;
3993 	}
3994 	return 0;
3995 }
3996 
3997 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3998 			     u32 regno, int off, int size,
3999 			     enum bpf_access_type t)
4000 {
4001 	struct bpf_reg_state *regs = cur_regs(env);
4002 	struct bpf_reg_state *reg = &regs[regno];
4003 	struct bpf_insn_access_aux info = {};
4004 	bool valid;
4005 
4006 	if (reg->smin_value < 0) {
4007 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4008 			regno);
4009 		return -EACCES;
4010 	}
4011 
4012 	switch (reg->type) {
4013 	case PTR_TO_SOCK_COMMON:
4014 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4015 		break;
4016 	case PTR_TO_SOCKET:
4017 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4018 		break;
4019 	case PTR_TO_TCP_SOCK:
4020 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4021 		break;
4022 	case PTR_TO_XDP_SOCK:
4023 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4024 		break;
4025 	default:
4026 		valid = false;
4027 	}
4028 
4029 
4030 	if (valid) {
4031 		env->insn_aux_data[insn_idx].ctx_field_size =
4032 			info.ctx_field_size;
4033 		return 0;
4034 	}
4035 
4036 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4037 		regno, reg_type_str(env, reg->type), off, size);
4038 
4039 	return -EACCES;
4040 }
4041 
4042 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4043 {
4044 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4045 }
4046 
4047 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4048 {
4049 	const struct bpf_reg_state *reg = reg_state(env, regno);
4050 
4051 	return reg->type == PTR_TO_CTX;
4052 }
4053 
4054 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4055 {
4056 	const struct bpf_reg_state *reg = reg_state(env, regno);
4057 
4058 	return type_is_sk_pointer(reg->type);
4059 }
4060 
4061 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4062 {
4063 	const struct bpf_reg_state *reg = reg_state(env, regno);
4064 
4065 	return type_is_pkt_pointer(reg->type);
4066 }
4067 
4068 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4069 {
4070 	const struct bpf_reg_state *reg = reg_state(env, regno);
4071 
4072 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4073 	return reg->type == PTR_TO_FLOW_KEYS;
4074 }
4075 
4076 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4077 				   const struct bpf_reg_state *reg,
4078 				   int off, int size, bool strict)
4079 {
4080 	struct tnum reg_off;
4081 	int ip_align;
4082 
4083 	/* Byte size accesses are always allowed. */
4084 	if (!strict || size == 1)
4085 		return 0;
4086 
4087 	/* For platforms that do not have a Kconfig enabling
4088 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4089 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4090 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4091 	 * to this code only in strict mode where we want to emulate
4092 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4093 	 * unconditional IP align value of '2'.
4094 	 */
4095 	ip_align = 2;
4096 
4097 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4098 	if (!tnum_is_aligned(reg_off, size)) {
4099 		char tn_buf[48];
4100 
4101 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4102 		verbose(env,
4103 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4104 			ip_align, tn_buf, reg->off, off, size);
4105 		return -EACCES;
4106 	}
4107 
4108 	return 0;
4109 }
4110 
4111 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4112 				       const struct bpf_reg_state *reg,
4113 				       const char *pointer_desc,
4114 				       int off, int size, bool strict)
4115 {
4116 	struct tnum reg_off;
4117 
4118 	/* Byte size accesses are always allowed. */
4119 	if (!strict || size == 1)
4120 		return 0;
4121 
4122 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4123 	if (!tnum_is_aligned(reg_off, size)) {
4124 		char tn_buf[48];
4125 
4126 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4127 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4128 			pointer_desc, tn_buf, reg->off, off, size);
4129 		return -EACCES;
4130 	}
4131 
4132 	return 0;
4133 }
4134 
4135 static int check_ptr_alignment(struct bpf_verifier_env *env,
4136 			       const struct bpf_reg_state *reg, int off,
4137 			       int size, bool strict_alignment_once)
4138 {
4139 	bool strict = env->strict_alignment || strict_alignment_once;
4140 	const char *pointer_desc = "";
4141 
4142 	switch (reg->type) {
4143 	case PTR_TO_PACKET:
4144 	case PTR_TO_PACKET_META:
4145 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4146 		 * right in front, treat it the very same way.
4147 		 */
4148 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4149 	case PTR_TO_FLOW_KEYS:
4150 		pointer_desc = "flow keys ";
4151 		break;
4152 	case PTR_TO_MAP_KEY:
4153 		pointer_desc = "key ";
4154 		break;
4155 	case PTR_TO_MAP_VALUE:
4156 		pointer_desc = "value ";
4157 		break;
4158 	case PTR_TO_CTX:
4159 		pointer_desc = "context ";
4160 		break;
4161 	case PTR_TO_STACK:
4162 		pointer_desc = "stack ";
4163 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4164 		 * and check_stack_read_fixed_off() relies on stack accesses being
4165 		 * aligned.
4166 		 */
4167 		strict = true;
4168 		break;
4169 	case PTR_TO_SOCKET:
4170 		pointer_desc = "sock ";
4171 		break;
4172 	case PTR_TO_SOCK_COMMON:
4173 		pointer_desc = "sock_common ";
4174 		break;
4175 	case PTR_TO_TCP_SOCK:
4176 		pointer_desc = "tcp_sock ";
4177 		break;
4178 	case PTR_TO_XDP_SOCK:
4179 		pointer_desc = "xdp_sock ";
4180 		break;
4181 	default:
4182 		break;
4183 	}
4184 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4185 					   strict);
4186 }
4187 
4188 static int update_stack_depth(struct bpf_verifier_env *env,
4189 			      const struct bpf_func_state *func,
4190 			      int off)
4191 {
4192 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4193 
4194 	if (stack >= -off)
4195 		return 0;
4196 
4197 	/* update known max for given subprogram */
4198 	env->subprog_info[func->subprogno].stack_depth = -off;
4199 	return 0;
4200 }
4201 
4202 /* starting from main bpf function walk all instructions of the function
4203  * and recursively walk all callees that given function can call.
4204  * Ignore jump and exit insns.
4205  * Since recursion is prevented by check_cfg() this algorithm
4206  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4207  */
4208 static int check_max_stack_depth(struct bpf_verifier_env *env)
4209 {
4210 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4211 	struct bpf_subprog_info *subprog = env->subprog_info;
4212 	struct bpf_insn *insn = env->prog->insnsi;
4213 	bool tail_call_reachable = false;
4214 	int ret_insn[MAX_CALL_FRAMES];
4215 	int ret_prog[MAX_CALL_FRAMES];
4216 	int j;
4217 
4218 process_func:
4219 	/* protect against potential stack overflow that might happen when
4220 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4221 	 * depth for such case down to 256 so that the worst case scenario
4222 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4223 	 * 8k).
4224 	 *
4225 	 * To get the idea what might happen, see an example:
4226 	 * func1 -> sub rsp, 128
4227 	 *  subfunc1 -> sub rsp, 256
4228 	 *  tailcall1 -> add rsp, 256
4229 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4230 	 *   subfunc2 -> sub rsp, 64
4231 	 *   subfunc22 -> sub rsp, 128
4232 	 *   tailcall2 -> add rsp, 128
4233 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4234 	 *
4235 	 * tailcall will unwind the current stack frame but it will not get rid
4236 	 * of caller's stack as shown on the example above.
4237 	 */
4238 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4239 		verbose(env,
4240 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4241 			depth);
4242 		return -EACCES;
4243 	}
4244 	/* round up to 32-bytes, since this is granularity
4245 	 * of interpreter stack size
4246 	 */
4247 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4248 	if (depth > MAX_BPF_STACK) {
4249 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4250 			frame + 1, depth);
4251 		return -EACCES;
4252 	}
4253 continue_func:
4254 	subprog_end = subprog[idx + 1].start;
4255 	for (; i < subprog_end; i++) {
4256 		int next_insn;
4257 
4258 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4259 			continue;
4260 		/* remember insn and function to return to */
4261 		ret_insn[frame] = i + 1;
4262 		ret_prog[frame] = idx;
4263 
4264 		/* find the callee */
4265 		next_insn = i + insn[i].imm + 1;
4266 		idx = find_subprog(env, next_insn);
4267 		if (idx < 0) {
4268 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4269 				  next_insn);
4270 			return -EFAULT;
4271 		}
4272 		if (subprog[idx].is_async_cb) {
4273 			if (subprog[idx].has_tail_call) {
4274 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4275 				return -EFAULT;
4276 			}
4277 			 /* async callbacks don't increase bpf prog stack size */
4278 			continue;
4279 		}
4280 		i = next_insn;
4281 
4282 		if (subprog[idx].has_tail_call)
4283 			tail_call_reachable = true;
4284 
4285 		frame++;
4286 		if (frame >= MAX_CALL_FRAMES) {
4287 			verbose(env, "the call stack of %d frames is too deep !\n",
4288 				frame);
4289 			return -E2BIG;
4290 		}
4291 		goto process_func;
4292 	}
4293 	/* if tail call got detected across bpf2bpf calls then mark each of the
4294 	 * currently present subprog frames as tail call reachable subprogs;
4295 	 * this info will be utilized by JIT so that we will be preserving the
4296 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4297 	 */
4298 	if (tail_call_reachable)
4299 		for (j = 0; j < frame; j++)
4300 			subprog[ret_prog[j]].tail_call_reachable = true;
4301 	if (subprog[0].tail_call_reachable)
4302 		env->prog->aux->tail_call_reachable = true;
4303 
4304 	/* end of for() loop means the last insn of the 'subprog'
4305 	 * was reached. Doesn't matter whether it was JA or EXIT
4306 	 */
4307 	if (frame == 0)
4308 		return 0;
4309 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4310 	frame--;
4311 	i = ret_insn[frame];
4312 	idx = ret_prog[frame];
4313 	goto continue_func;
4314 }
4315 
4316 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4317 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4318 				  const struct bpf_insn *insn, int idx)
4319 {
4320 	int start = idx + insn->imm + 1, subprog;
4321 
4322 	subprog = find_subprog(env, start);
4323 	if (subprog < 0) {
4324 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4325 			  start);
4326 		return -EFAULT;
4327 	}
4328 	return env->subprog_info[subprog].stack_depth;
4329 }
4330 #endif
4331 
4332 static int __check_buffer_access(struct bpf_verifier_env *env,
4333 				 const char *buf_info,
4334 				 const struct bpf_reg_state *reg,
4335 				 int regno, int off, int size)
4336 {
4337 	if (off < 0) {
4338 		verbose(env,
4339 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4340 			regno, buf_info, off, size);
4341 		return -EACCES;
4342 	}
4343 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4344 		char tn_buf[48];
4345 
4346 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4347 		verbose(env,
4348 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4349 			regno, off, tn_buf);
4350 		return -EACCES;
4351 	}
4352 
4353 	return 0;
4354 }
4355 
4356 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4357 				  const struct bpf_reg_state *reg,
4358 				  int regno, int off, int size)
4359 {
4360 	int err;
4361 
4362 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4363 	if (err)
4364 		return err;
4365 
4366 	if (off + size > env->prog->aux->max_tp_access)
4367 		env->prog->aux->max_tp_access = off + size;
4368 
4369 	return 0;
4370 }
4371 
4372 static int check_buffer_access(struct bpf_verifier_env *env,
4373 			       const struct bpf_reg_state *reg,
4374 			       int regno, int off, int size,
4375 			       bool zero_size_allowed,
4376 			       u32 *max_access)
4377 {
4378 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4379 	int err;
4380 
4381 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4382 	if (err)
4383 		return err;
4384 
4385 	if (off + size > *max_access)
4386 		*max_access = off + size;
4387 
4388 	return 0;
4389 }
4390 
4391 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4392 static void zext_32_to_64(struct bpf_reg_state *reg)
4393 {
4394 	reg->var_off = tnum_subreg(reg->var_off);
4395 	__reg_assign_32_into_64(reg);
4396 }
4397 
4398 /* truncate register to smaller size (in bytes)
4399  * must be called with size < BPF_REG_SIZE
4400  */
4401 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4402 {
4403 	u64 mask;
4404 
4405 	/* clear high bits in bit representation */
4406 	reg->var_off = tnum_cast(reg->var_off, size);
4407 
4408 	/* fix arithmetic bounds */
4409 	mask = ((u64)1 << (size * 8)) - 1;
4410 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4411 		reg->umin_value &= mask;
4412 		reg->umax_value &= mask;
4413 	} else {
4414 		reg->umin_value = 0;
4415 		reg->umax_value = mask;
4416 	}
4417 	reg->smin_value = reg->umin_value;
4418 	reg->smax_value = reg->umax_value;
4419 
4420 	/* If size is smaller than 32bit register the 32bit register
4421 	 * values are also truncated so we push 64-bit bounds into
4422 	 * 32-bit bounds. Above were truncated < 32-bits already.
4423 	 */
4424 	if (size >= 4)
4425 		return;
4426 	__reg_combine_64_into_32(reg);
4427 }
4428 
4429 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4430 {
4431 	/* A map is considered read-only if the following condition are true:
4432 	 *
4433 	 * 1) BPF program side cannot change any of the map content. The
4434 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4435 	 *    and was set at map creation time.
4436 	 * 2) The map value(s) have been initialized from user space by a
4437 	 *    loader and then "frozen", such that no new map update/delete
4438 	 *    operations from syscall side are possible for the rest of
4439 	 *    the map's lifetime from that point onwards.
4440 	 * 3) Any parallel/pending map update/delete operations from syscall
4441 	 *    side have been completed. Only after that point, it's safe to
4442 	 *    assume that map value(s) are immutable.
4443 	 */
4444 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4445 	       READ_ONCE(map->frozen) &&
4446 	       !bpf_map_write_active(map);
4447 }
4448 
4449 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4450 {
4451 	void *ptr;
4452 	u64 addr;
4453 	int err;
4454 
4455 	err = map->ops->map_direct_value_addr(map, &addr, off);
4456 	if (err)
4457 		return err;
4458 	ptr = (void *)(long)addr + off;
4459 
4460 	switch (size) {
4461 	case sizeof(u8):
4462 		*val = (u64)*(u8 *)ptr;
4463 		break;
4464 	case sizeof(u16):
4465 		*val = (u64)*(u16 *)ptr;
4466 		break;
4467 	case sizeof(u32):
4468 		*val = (u64)*(u32 *)ptr;
4469 		break;
4470 	case sizeof(u64):
4471 		*val = *(u64 *)ptr;
4472 		break;
4473 	default:
4474 		return -EINVAL;
4475 	}
4476 	return 0;
4477 }
4478 
4479 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4480 				   struct bpf_reg_state *regs,
4481 				   int regno, int off, int size,
4482 				   enum bpf_access_type atype,
4483 				   int value_regno)
4484 {
4485 	struct bpf_reg_state *reg = regs + regno;
4486 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4487 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4488 	enum bpf_type_flag flag = 0;
4489 	u32 btf_id;
4490 	int ret;
4491 
4492 	if (off < 0) {
4493 		verbose(env,
4494 			"R%d is ptr_%s invalid negative access: off=%d\n",
4495 			regno, tname, off);
4496 		return -EACCES;
4497 	}
4498 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4499 		char tn_buf[48];
4500 
4501 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4502 		verbose(env,
4503 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4504 			regno, tname, off, tn_buf);
4505 		return -EACCES;
4506 	}
4507 
4508 	if (reg->type & MEM_USER) {
4509 		verbose(env,
4510 			"R%d is ptr_%s access user memory: off=%d\n",
4511 			regno, tname, off);
4512 		return -EACCES;
4513 	}
4514 
4515 	if (reg->type & MEM_PERCPU) {
4516 		verbose(env,
4517 			"R%d is ptr_%s access percpu memory: off=%d\n",
4518 			regno, tname, off);
4519 		return -EACCES;
4520 	}
4521 
4522 	if (env->ops->btf_struct_access) {
4523 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4524 						  off, size, atype, &btf_id, &flag);
4525 	} else {
4526 		if (atype != BPF_READ) {
4527 			verbose(env, "only read is supported\n");
4528 			return -EACCES;
4529 		}
4530 
4531 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4532 					atype, &btf_id, &flag);
4533 	}
4534 
4535 	if (ret < 0)
4536 		return ret;
4537 
4538 	/* If this is an untrusted pointer, all pointers formed by walking it
4539 	 * also inherit the untrusted flag.
4540 	 */
4541 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4542 		flag |= PTR_UNTRUSTED;
4543 
4544 	if (atype == BPF_READ && value_regno >= 0)
4545 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4546 
4547 	return 0;
4548 }
4549 
4550 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4551 				   struct bpf_reg_state *regs,
4552 				   int regno, int off, int size,
4553 				   enum bpf_access_type atype,
4554 				   int value_regno)
4555 {
4556 	struct bpf_reg_state *reg = regs + regno;
4557 	struct bpf_map *map = reg->map_ptr;
4558 	enum bpf_type_flag flag = 0;
4559 	const struct btf_type *t;
4560 	const char *tname;
4561 	u32 btf_id;
4562 	int ret;
4563 
4564 	if (!btf_vmlinux) {
4565 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4566 		return -ENOTSUPP;
4567 	}
4568 
4569 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4570 		verbose(env, "map_ptr access not supported for map type %d\n",
4571 			map->map_type);
4572 		return -ENOTSUPP;
4573 	}
4574 
4575 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4576 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4577 
4578 	if (!env->allow_ptr_to_map_access) {
4579 		verbose(env,
4580 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4581 			tname);
4582 		return -EPERM;
4583 	}
4584 
4585 	if (off < 0) {
4586 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4587 			regno, tname, off);
4588 		return -EACCES;
4589 	}
4590 
4591 	if (atype != BPF_READ) {
4592 		verbose(env, "only read from %s is supported\n", tname);
4593 		return -EACCES;
4594 	}
4595 
4596 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4597 	if (ret < 0)
4598 		return ret;
4599 
4600 	if (value_regno >= 0)
4601 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4602 
4603 	return 0;
4604 }
4605 
4606 /* Check that the stack access at the given offset is within bounds. The
4607  * maximum valid offset is -1.
4608  *
4609  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4610  * -state->allocated_stack for reads.
4611  */
4612 static int check_stack_slot_within_bounds(int off,
4613 					  struct bpf_func_state *state,
4614 					  enum bpf_access_type t)
4615 {
4616 	int min_valid_off;
4617 
4618 	if (t == BPF_WRITE)
4619 		min_valid_off = -MAX_BPF_STACK;
4620 	else
4621 		min_valid_off = -state->allocated_stack;
4622 
4623 	if (off < min_valid_off || off > -1)
4624 		return -EACCES;
4625 	return 0;
4626 }
4627 
4628 /* Check that the stack access at 'regno + off' falls within the maximum stack
4629  * bounds.
4630  *
4631  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4632  */
4633 static int check_stack_access_within_bounds(
4634 		struct bpf_verifier_env *env,
4635 		int regno, int off, int access_size,
4636 		enum bpf_access_src src, enum bpf_access_type type)
4637 {
4638 	struct bpf_reg_state *regs = cur_regs(env);
4639 	struct bpf_reg_state *reg = regs + regno;
4640 	struct bpf_func_state *state = func(env, reg);
4641 	int min_off, max_off;
4642 	int err;
4643 	char *err_extra;
4644 
4645 	if (src == ACCESS_HELPER)
4646 		/* We don't know if helpers are reading or writing (or both). */
4647 		err_extra = " indirect access to";
4648 	else if (type == BPF_READ)
4649 		err_extra = " read from";
4650 	else
4651 		err_extra = " write to";
4652 
4653 	if (tnum_is_const(reg->var_off)) {
4654 		min_off = reg->var_off.value + off;
4655 		if (access_size > 0)
4656 			max_off = min_off + access_size - 1;
4657 		else
4658 			max_off = min_off;
4659 	} else {
4660 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4661 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4662 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4663 				err_extra, regno);
4664 			return -EACCES;
4665 		}
4666 		min_off = reg->smin_value + off;
4667 		if (access_size > 0)
4668 			max_off = reg->smax_value + off + access_size - 1;
4669 		else
4670 			max_off = min_off;
4671 	}
4672 
4673 	err = check_stack_slot_within_bounds(min_off, state, type);
4674 	if (!err)
4675 		err = check_stack_slot_within_bounds(max_off, state, type);
4676 
4677 	if (err) {
4678 		if (tnum_is_const(reg->var_off)) {
4679 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4680 				err_extra, regno, off, access_size);
4681 		} else {
4682 			char tn_buf[48];
4683 
4684 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4685 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4686 				err_extra, regno, tn_buf, access_size);
4687 		}
4688 	}
4689 	return err;
4690 }
4691 
4692 /* check whether memory at (regno + off) is accessible for t = (read | write)
4693  * if t==write, value_regno is a register which value is stored into memory
4694  * if t==read, value_regno is a register which will receive the value from memory
4695  * if t==write && value_regno==-1, some unknown value is stored into memory
4696  * if t==read && value_regno==-1, don't care what we read from memory
4697  */
4698 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4699 			    int off, int bpf_size, enum bpf_access_type t,
4700 			    int value_regno, bool strict_alignment_once)
4701 {
4702 	struct bpf_reg_state *regs = cur_regs(env);
4703 	struct bpf_reg_state *reg = regs + regno;
4704 	struct bpf_func_state *state;
4705 	int size, err = 0;
4706 
4707 	size = bpf_size_to_bytes(bpf_size);
4708 	if (size < 0)
4709 		return size;
4710 
4711 	/* alignment checks will add in reg->off themselves */
4712 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4713 	if (err)
4714 		return err;
4715 
4716 	/* for access checks, reg->off is just part of off */
4717 	off += reg->off;
4718 
4719 	if (reg->type == PTR_TO_MAP_KEY) {
4720 		if (t == BPF_WRITE) {
4721 			verbose(env, "write to change key R%d not allowed\n", regno);
4722 			return -EACCES;
4723 		}
4724 
4725 		err = check_mem_region_access(env, regno, off, size,
4726 					      reg->map_ptr->key_size, false);
4727 		if (err)
4728 			return err;
4729 		if (value_regno >= 0)
4730 			mark_reg_unknown(env, regs, value_regno);
4731 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4732 		struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4733 
4734 		if (t == BPF_WRITE && value_regno >= 0 &&
4735 		    is_pointer_value(env, value_regno)) {
4736 			verbose(env, "R%d leaks addr into map\n", value_regno);
4737 			return -EACCES;
4738 		}
4739 		err = check_map_access_type(env, regno, off, size, t);
4740 		if (err)
4741 			return err;
4742 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4743 		if (err)
4744 			return err;
4745 		if (tnum_is_const(reg->var_off))
4746 			kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4747 								  off + reg->var_off.value);
4748 		if (kptr_off_desc) {
4749 			err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4750 						    kptr_off_desc);
4751 		} else if (t == BPF_READ && value_regno >= 0) {
4752 			struct bpf_map *map = reg->map_ptr;
4753 
4754 			/* if map is read-only, track its contents as scalars */
4755 			if (tnum_is_const(reg->var_off) &&
4756 			    bpf_map_is_rdonly(map) &&
4757 			    map->ops->map_direct_value_addr) {
4758 				int map_off = off + reg->var_off.value;
4759 				u64 val = 0;
4760 
4761 				err = bpf_map_direct_read(map, map_off, size,
4762 							  &val);
4763 				if (err)
4764 					return err;
4765 
4766 				regs[value_regno].type = SCALAR_VALUE;
4767 				__mark_reg_known(&regs[value_regno], val);
4768 			} else {
4769 				mark_reg_unknown(env, regs, value_regno);
4770 			}
4771 		}
4772 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4773 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4774 
4775 		if (type_may_be_null(reg->type)) {
4776 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4777 				reg_type_str(env, reg->type));
4778 			return -EACCES;
4779 		}
4780 
4781 		if (t == BPF_WRITE && rdonly_mem) {
4782 			verbose(env, "R%d cannot write into %s\n",
4783 				regno, reg_type_str(env, reg->type));
4784 			return -EACCES;
4785 		}
4786 
4787 		if (t == BPF_WRITE && value_regno >= 0 &&
4788 		    is_pointer_value(env, value_regno)) {
4789 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4790 			return -EACCES;
4791 		}
4792 
4793 		err = check_mem_region_access(env, regno, off, size,
4794 					      reg->mem_size, false);
4795 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4796 			mark_reg_unknown(env, regs, value_regno);
4797 	} else if (reg->type == PTR_TO_CTX) {
4798 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4799 		struct btf *btf = NULL;
4800 		u32 btf_id = 0;
4801 
4802 		if (t == BPF_WRITE && value_regno >= 0 &&
4803 		    is_pointer_value(env, value_regno)) {
4804 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4805 			return -EACCES;
4806 		}
4807 
4808 		err = check_ptr_off_reg(env, reg, regno);
4809 		if (err < 0)
4810 			return err;
4811 
4812 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4813 				       &btf_id);
4814 		if (err)
4815 			verbose_linfo(env, insn_idx, "; ");
4816 		if (!err && t == BPF_READ && value_regno >= 0) {
4817 			/* ctx access returns either a scalar, or a
4818 			 * PTR_TO_PACKET[_META,_END]. In the latter
4819 			 * case, we know the offset is zero.
4820 			 */
4821 			if (reg_type == SCALAR_VALUE) {
4822 				mark_reg_unknown(env, regs, value_regno);
4823 			} else {
4824 				mark_reg_known_zero(env, regs,
4825 						    value_regno);
4826 				if (type_may_be_null(reg_type))
4827 					regs[value_regno].id = ++env->id_gen;
4828 				/* A load of ctx field could have different
4829 				 * actual load size with the one encoded in the
4830 				 * insn. When the dst is PTR, it is for sure not
4831 				 * a sub-register.
4832 				 */
4833 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4834 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4835 					regs[value_regno].btf = btf;
4836 					regs[value_regno].btf_id = btf_id;
4837 				}
4838 			}
4839 			regs[value_regno].type = reg_type;
4840 		}
4841 
4842 	} else if (reg->type == PTR_TO_STACK) {
4843 		/* Basic bounds checks. */
4844 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4845 		if (err)
4846 			return err;
4847 
4848 		state = func(env, reg);
4849 		err = update_stack_depth(env, state, off);
4850 		if (err)
4851 			return err;
4852 
4853 		if (t == BPF_READ)
4854 			err = check_stack_read(env, regno, off, size,
4855 					       value_regno);
4856 		else
4857 			err = check_stack_write(env, regno, off, size,
4858 						value_regno, insn_idx);
4859 	} else if (reg_is_pkt_pointer(reg)) {
4860 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4861 			verbose(env, "cannot write into packet\n");
4862 			return -EACCES;
4863 		}
4864 		if (t == BPF_WRITE && value_regno >= 0 &&
4865 		    is_pointer_value(env, value_regno)) {
4866 			verbose(env, "R%d leaks addr into packet\n",
4867 				value_regno);
4868 			return -EACCES;
4869 		}
4870 		err = check_packet_access(env, regno, off, size, false);
4871 		if (!err && t == BPF_READ && value_regno >= 0)
4872 			mark_reg_unknown(env, regs, value_regno);
4873 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4874 		if (t == BPF_WRITE && value_regno >= 0 &&
4875 		    is_pointer_value(env, value_regno)) {
4876 			verbose(env, "R%d leaks addr into flow keys\n",
4877 				value_regno);
4878 			return -EACCES;
4879 		}
4880 
4881 		err = check_flow_keys_access(env, off, size);
4882 		if (!err && t == BPF_READ && value_regno >= 0)
4883 			mark_reg_unknown(env, regs, value_regno);
4884 	} else if (type_is_sk_pointer(reg->type)) {
4885 		if (t == BPF_WRITE) {
4886 			verbose(env, "R%d cannot write into %s\n",
4887 				regno, reg_type_str(env, reg->type));
4888 			return -EACCES;
4889 		}
4890 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4891 		if (!err && value_regno >= 0)
4892 			mark_reg_unknown(env, regs, value_regno);
4893 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4894 		err = check_tp_buffer_access(env, reg, regno, off, size);
4895 		if (!err && t == BPF_READ && value_regno >= 0)
4896 			mark_reg_unknown(env, regs, value_regno);
4897 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4898 		   !type_may_be_null(reg->type)) {
4899 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4900 					      value_regno);
4901 	} else if (reg->type == CONST_PTR_TO_MAP) {
4902 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4903 					      value_regno);
4904 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4905 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4906 		u32 *max_access;
4907 
4908 		if (rdonly_mem) {
4909 			if (t == BPF_WRITE) {
4910 				verbose(env, "R%d cannot write into %s\n",
4911 					regno, reg_type_str(env, reg->type));
4912 				return -EACCES;
4913 			}
4914 			max_access = &env->prog->aux->max_rdonly_access;
4915 		} else {
4916 			max_access = &env->prog->aux->max_rdwr_access;
4917 		}
4918 
4919 		err = check_buffer_access(env, reg, regno, off, size, false,
4920 					  max_access);
4921 
4922 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4923 			mark_reg_unknown(env, regs, value_regno);
4924 	} else {
4925 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4926 			reg_type_str(env, reg->type));
4927 		return -EACCES;
4928 	}
4929 
4930 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4931 	    regs[value_regno].type == SCALAR_VALUE) {
4932 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4933 		coerce_reg_to_size(&regs[value_regno], size);
4934 	}
4935 	return err;
4936 }
4937 
4938 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4939 {
4940 	int load_reg;
4941 	int err;
4942 
4943 	switch (insn->imm) {
4944 	case BPF_ADD:
4945 	case BPF_ADD | BPF_FETCH:
4946 	case BPF_AND:
4947 	case BPF_AND | BPF_FETCH:
4948 	case BPF_OR:
4949 	case BPF_OR | BPF_FETCH:
4950 	case BPF_XOR:
4951 	case BPF_XOR | BPF_FETCH:
4952 	case BPF_XCHG:
4953 	case BPF_CMPXCHG:
4954 		break;
4955 	default:
4956 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4957 		return -EINVAL;
4958 	}
4959 
4960 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4961 		verbose(env, "invalid atomic operand size\n");
4962 		return -EINVAL;
4963 	}
4964 
4965 	/* check src1 operand */
4966 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4967 	if (err)
4968 		return err;
4969 
4970 	/* check src2 operand */
4971 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4972 	if (err)
4973 		return err;
4974 
4975 	if (insn->imm == BPF_CMPXCHG) {
4976 		/* Check comparison of R0 with memory location */
4977 		const u32 aux_reg = BPF_REG_0;
4978 
4979 		err = check_reg_arg(env, aux_reg, SRC_OP);
4980 		if (err)
4981 			return err;
4982 
4983 		if (is_pointer_value(env, aux_reg)) {
4984 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
4985 			return -EACCES;
4986 		}
4987 	}
4988 
4989 	if (is_pointer_value(env, insn->src_reg)) {
4990 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4991 		return -EACCES;
4992 	}
4993 
4994 	if (is_ctx_reg(env, insn->dst_reg) ||
4995 	    is_pkt_reg(env, insn->dst_reg) ||
4996 	    is_flow_key_reg(env, insn->dst_reg) ||
4997 	    is_sk_reg(env, insn->dst_reg)) {
4998 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4999 			insn->dst_reg,
5000 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5001 		return -EACCES;
5002 	}
5003 
5004 	if (insn->imm & BPF_FETCH) {
5005 		if (insn->imm == BPF_CMPXCHG)
5006 			load_reg = BPF_REG_0;
5007 		else
5008 			load_reg = insn->src_reg;
5009 
5010 		/* check and record load of old value */
5011 		err = check_reg_arg(env, load_reg, DST_OP);
5012 		if (err)
5013 			return err;
5014 	} else {
5015 		/* This instruction accesses a memory location but doesn't
5016 		 * actually load it into a register.
5017 		 */
5018 		load_reg = -1;
5019 	}
5020 
5021 	/* Check whether we can read the memory, with second call for fetch
5022 	 * case to simulate the register fill.
5023 	 */
5024 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5025 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5026 	if (!err && load_reg >= 0)
5027 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5028 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5029 				       true);
5030 	if (err)
5031 		return err;
5032 
5033 	/* Check whether we can write into the same memory. */
5034 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5035 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5036 	if (err)
5037 		return err;
5038 
5039 	return 0;
5040 }
5041 
5042 /* When register 'regno' is used to read the stack (either directly or through
5043  * a helper function) make sure that it's within stack boundary and, depending
5044  * on the access type, that all elements of the stack are initialized.
5045  *
5046  * 'off' includes 'regno->off', but not its dynamic part (if any).
5047  *
5048  * All registers that have been spilled on the stack in the slots within the
5049  * read offsets are marked as read.
5050  */
5051 static int check_stack_range_initialized(
5052 		struct bpf_verifier_env *env, int regno, int off,
5053 		int access_size, bool zero_size_allowed,
5054 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5055 {
5056 	struct bpf_reg_state *reg = reg_state(env, regno);
5057 	struct bpf_func_state *state = func(env, reg);
5058 	int err, min_off, max_off, i, j, slot, spi;
5059 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5060 	enum bpf_access_type bounds_check_type;
5061 	/* Some accesses can write anything into the stack, others are
5062 	 * read-only.
5063 	 */
5064 	bool clobber = false;
5065 
5066 	if (access_size == 0 && !zero_size_allowed) {
5067 		verbose(env, "invalid zero-sized read\n");
5068 		return -EACCES;
5069 	}
5070 
5071 	if (type == ACCESS_HELPER) {
5072 		/* The bounds checks for writes are more permissive than for
5073 		 * reads. However, if raw_mode is not set, we'll do extra
5074 		 * checks below.
5075 		 */
5076 		bounds_check_type = BPF_WRITE;
5077 		clobber = true;
5078 	} else {
5079 		bounds_check_type = BPF_READ;
5080 	}
5081 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5082 					       type, bounds_check_type);
5083 	if (err)
5084 		return err;
5085 
5086 
5087 	if (tnum_is_const(reg->var_off)) {
5088 		min_off = max_off = reg->var_off.value + off;
5089 	} else {
5090 		/* Variable offset is prohibited for unprivileged mode for
5091 		 * simplicity since it requires corresponding support in
5092 		 * Spectre masking for stack ALU.
5093 		 * See also retrieve_ptr_limit().
5094 		 */
5095 		if (!env->bypass_spec_v1) {
5096 			char tn_buf[48];
5097 
5098 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5099 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5100 				regno, err_extra, tn_buf);
5101 			return -EACCES;
5102 		}
5103 		/* Only initialized buffer on stack is allowed to be accessed
5104 		 * with variable offset. With uninitialized buffer it's hard to
5105 		 * guarantee that whole memory is marked as initialized on
5106 		 * helper return since specific bounds are unknown what may
5107 		 * cause uninitialized stack leaking.
5108 		 */
5109 		if (meta && meta->raw_mode)
5110 			meta = NULL;
5111 
5112 		min_off = reg->smin_value + off;
5113 		max_off = reg->smax_value + off;
5114 	}
5115 
5116 	if (meta && meta->raw_mode) {
5117 		meta->access_size = access_size;
5118 		meta->regno = regno;
5119 		return 0;
5120 	}
5121 
5122 	for (i = min_off; i < max_off + access_size; i++) {
5123 		u8 *stype;
5124 
5125 		slot = -i - 1;
5126 		spi = slot / BPF_REG_SIZE;
5127 		if (state->allocated_stack <= slot)
5128 			goto err;
5129 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5130 		if (*stype == STACK_MISC)
5131 			goto mark;
5132 		if (*stype == STACK_ZERO) {
5133 			if (clobber) {
5134 				/* helper can write anything into the stack */
5135 				*stype = STACK_MISC;
5136 			}
5137 			goto mark;
5138 		}
5139 
5140 		if (is_spilled_reg(&state->stack[spi]) &&
5141 		    base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
5142 			goto mark;
5143 
5144 		if (is_spilled_reg(&state->stack[spi]) &&
5145 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5146 		     env->allow_ptr_leaks)) {
5147 			if (clobber) {
5148 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5149 				for (j = 0; j < BPF_REG_SIZE; j++)
5150 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5151 			}
5152 			goto mark;
5153 		}
5154 
5155 err:
5156 		if (tnum_is_const(reg->var_off)) {
5157 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5158 				err_extra, regno, min_off, i - min_off, access_size);
5159 		} else {
5160 			char tn_buf[48];
5161 
5162 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5163 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5164 				err_extra, regno, tn_buf, i - min_off, access_size);
5165 		}
5166 		return -EACCES;
5167 mark:
5168 		/* reading any byte out of 8-byte 'spill_slot' will cause
5169 		 * the whole slot to be marked as 'read'
5170 		 */
5171 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5172 			      state->stack[spi].spilled_ptr.parent,
5173 			      REG_LIVE_READ64);
5174 	}
5175 	return update_stack_depth(env, state, min_off);
5176 }
5177 
5178 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5179 				   int access_size, bool zero_size_allowed,
5180 				   struct bpf_call_arg_meta *meta)
5181 {
5182 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5183 	u32 *max_access;
5184 
5185 	switch (base_type(reg->type)) {
5186 	case PTR_TO_PACKET:
5187 	case PTR_TO_PACKET_META:
5188 		return check_packet_access(env, regno, reg->off, access_size,
5189 					   zero_size_allowed);
5190 	case PTR_TO_MAP_KEY:
5191 		if (meta && meta->raw_mode) {
5192 			verbose(env, "R%d cannot write into %s\n", regno,
5193 				reg_type_str(env, reg->type));
5194 			return -EACCES;
5195 		}
5196 		return check_mem_region_access(env, regno, reg->off, access_size,
5197 					       reg->map_ptr->key_size, false);
5198 	case PTR_TO_MAP_VALUE:
5199 		if (check_map_access_type(env, regno, reg->off, access_size,
5200 					  meta && meta->raw_mode ? BPF_WRITE :
5201 					  BPF_READ))
5202 			return -EACCES;
5203 		return check_map_access(env, regno, reg->off, access_size,
5204 					zero_size_allowed, ACCESS_HELPER);
5205 	case PTR_TO_MEM:
5206 		if (type_is_rdonly_mem(reg->type)) {
5207 			if (meta && meta->raw_mode) {
5208 				verbose(env, "R%d cannot write into %s\n", regno,
5209 					reg_type_str(env, reg->type));
5210 				return -EACCES;
5211 			}
5212 		}
5213 		return check_mem_region_access(env, regno, reg->off,
5214 					       access_size, reg->mem_size,
5215 					       zero_size_allowed);
5216 	case PTR_TO_BUF:
5217 		if (type_is_rdonly_mem(reg->type)) {
5218 			if (meta && meta->raw_mode) {
5219 				verbose(env, "R%d cannot write into %s\n", regno,
5220 					reg_type_str(env, reg->type));
5221 				return -EACCES;
5222 			}
5223 
5224 			max_access = &env->prog->aux->max_rdonly_access;
5225 		} else {
5226 			max_access = &env->prog->aux->max_rdwr_access;
5227 		}
5228 		return check_buffer_access(env, reg, regno, reg->off,
5229 					   access_size, zero_size_allowed,
5230 					   max_access);
5231 	case PTR_TO_STACK:
5232 		return check_stack_range_initialized(
5233 				env,
5234 				regno, reg->off, access_size,
5235 				zero_size_allowed, ACCESS_HELPER, meta);
5236 	default: /* scalar_value or invalid ptr */
5237 		/* Allow zero-byte read from NULL, regardless of pointer type */
5238 		if (zero_size_allowed && access_size == 0 &&
5239 		    register_is_null(reg))
5240 			return 0;
5241 
5242 		verbose(env, "R%d type=%s ", regno,
5243 			reg_type_str(env, reg->type));
5244 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5245 		return -EACCES;
5246 	}
5247 }
5248 
5249 static int check_mem_size_reg(struct bpf_verifier_env *env,
5250 			      struct bpf_reg_state *reg, u32 regno,
5251 			      bool zero_size_allowed,
5252 			      struct bpf_call_arg_meta *meta)
5253 {
5254 	int err;
5255 
5256 	/* This is used to refine r0 return value bounds for helpers
5257 	 * that enforce this value as an upper bound on return values.
5258 	 * See do_refine_retval_range() for helpers that can refine
5259 	 * the return value. C type of helper is u32 so we pull register
5260 	 * bound from umax_value however, if negative verifier errors
5261 	 * out. Only upper bounds can be learned because retval is an
5262 	 * int type and negative retvals are allowed.
5263 	 */
5264 	meta->msize_max_value = reg->umax_value;
5265 
5266 	/* The register is SCALAR_VALUE; the access check
5267 	 * happens using its boundaries.
5268 	 */
5269 	if (!tnum_is_const(reg->var_off))
5270 		/* For unprivileged variable accesses, disable raw
5271 		 * mode so that the program is required to
5272 		 * initialize all the memory that the helper could
5273 		 * just partially fill up.
5274 		 */
5275 		meta = NULL;
5276 
5277 	if (reg->smin_value < 0) {
5278 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5279 			regno);
5280 		return -EACCES;
5281 	}
5282 
5283 	if (reg->umin_value == 0) {
5284 		err = check_helper_mem_access(env, regno - 1, 0,
5285 					      zero_size_allowed,
5286 					      meta);
5287 		if (err)
5288 			return err;
5289 	}
5290 
5291 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5292 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5293 			regno);
5294 		return -EACCES;
5295 	}
5296 	err = check_helper_mem_access(env, regno - 1,
5297 				      reg->umax_value,
5298 				      zero_size_allowed, meta);
5299 	if (!err)
5300 		err = mark_chain_precision(env, regno);
5301 	return err;
5302 }
5303 
5304 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5305 		   u32 regno, u32 mem_size)
5306 {
5307 	bool may_be_null = type_may_be_null(reg->type);
5308 	struct bpf_reg_state saved_reg;
5309 	struct bpf_call_arg_meta meta;
5310 	int err;
5311 
5312 	if (register_is_null(reg))
5313 		return 0;
5314 
5315 	memset(&meta, 0, sizeof(meta));
5316 	/* Assuming that the register contains a value check if the memory
5317 	 * access is safe. Temporarily save and restore the register's state as
5318 	 * the conversion shouldn't be visible to a caller.
5319 	 */
5320 	if (may_be_null) {
5321 		saved_reg = *reg;
5322 		mark_ptr_not_null_reg(reg);
5323 	}
5324 
5325 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5326 	/* Check access for BPF_WRITE */
5327 	meta.raw_mode = true;
5328 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5329 
5330 	if (may_be_null)
5331 		*reg = saved_reg;
5332 
5333 	return err;
5334 }
5335 
5336 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5337 			     u32 regno)
5338 {
5339 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5340 	bool may_be_null = type_may_be_null(mem_reg->type);
5341 	struct bpf_reg_state saved_reg;
5342 	struct bpf_call_arg_meta meta;
5343 	int err;
5344 
5345 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5346 
5347 	memset(&meta, 0, sizeof(meta));
5348 
5349 	if (may_be_null) {
5350 		saved_reg = *mem_reg;
5351 		mark_ptr_not_null_reg(mem_reg);
5352 	}
5353 
5354 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5355 	/* Check access for BPF_WRITE */
5356 	meta.raw_mode = true;
5357 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5358 
5359 	if (may_be_null)
5360 		*mem_reg = saved_reg;
5361 	return err;
5362 }
5363 
5364 /* Implementation details:
5365  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5366  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5367  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5368  * value_or_null->value transition, since the verifier only cares about
5369  * the range of access to valid map value pointer and doesn't care about actual
5370  * address of the map element.
5371  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5372  * reg->id > 0 after value_or_null->value transition. By doing so
5373  * two bpf_map_lookups will be considered two different pointers that
5374  * point to different bpf_spin_locks.
5375  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5376  * dead-locks.
5377  * Since only one bpf_spin_lock is allowed the checks are simpler than
5378  * reg_is_refcounted() logic. The verifier needs to remember only
5379  * one spin_lock instead of array of acquired_refs.
5380  * cur_state->active_spin_lock remembers which map value element got locked
5381  * and clears it after bpf_spin_unlock.
5382  */
5383 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5384 			     bool is_lock)
5385 {
5386 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5387 	struct bpf_verifier_state *cur = env->cur_state;
5388 	bool is_const = tnum_is_const(reg->var_off);
5389 	struct bpf_map *map = reg->map_ptr;
5390 	u64 val = reg->var_off.value;
5391 
5392 	if (!is_const) {
5393 		verbose(env,
5394 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5395 			regno);
5396 		return -EINVAL;
5397 	}
5398 	if (!map->btf) {
5399 		verbose(env,
5400 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5401 			map->name);
5402 		return -EINVAL;
5403 	}
5404 	if (!map_value_has_spin_lock(map)) {
5405 		if (map->spin_lock_off == -E2BIG)
5406 			verbose(env,
5407 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
5408 				map->name);
5409 		else if (map->spin_lock_off == -ENOENT)
5410 			verbose(env,
5411 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
5412 				map->name);
5413 		else
5414 			verbose(env,
5415 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5416 				map->name);
5417 		return -EINVAL;
5418 	}
5419 	if (map->spin_lock_off != val + reg->off) {
5420 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5421 			val + reg->off);
5422 		return -EINVAL;
5423 	}
5424 	if (is_lock) {
5425 		if (cur->active_spin_lock) {
5426 			verbose(env,
5427 				"Locking two bpf_spin_locks are not allowed\n");
5428 			return -EINVAL;
5429 		}
5430 		cur->active_spin_lock = reg->id;
5431 	} else {
5432 		if (!cur->active_spin_lock) {
5433 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5434 			return -EINVAL;
5435 		}
5436 		if (cur->active_spin_lock != reg->id) {
5437 			verbose(env, "bpf_spin_unlock of different lock\n");
5438 			return -EINVAL;
5439 		}
5440 		cur->active_spin_lock = 0;
5441 	}
5442 	return 0;
5443 }
5444 
5445 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5446 			      struct bpf_call_arg_meta *meta)
5447 {
5448 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5449 	bool is_const = tnum_is_const(reg->var_off);
5450 	struct bpf_map *map = reg->map_ptr;
5451 	u64 val = reg->var_off.value;
5452 
5453 	if (!is_const) {
5454 		verbose(env,
5455 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5456 			regno);
5457 		return -EINVAL;
5458 	}
5459 	if (!map->btf) {
5460 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5461 			map->name);
5462 		return -EINVAL;
5463 	}
5464 	if (!map_value_has_timer(map)) {
5465 		if (map->timer_off == -E2BIG)
5466 			verbose(env,
5467 				"map '%s' has more than one 'struct bpf_timer'\n",
5468 				map->name);
5469 		else if (map->timer_off == -ENOENT)
5470 			verbose(env,
5471 				"map '%s' doesn't have 'struct bpf_timer'\n",
5472 				map->name);
5473 		else
5474 			verbose(env,
5475 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5476 				map->name);
5477 		return -EINVAL;
5478 	}
5479 	if (map->timer_off != val + reg->off) {
5480 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5481 			val + reg->off, map->timer_off);
5482 		return -EINVAL;
5483 	}
5484 	if (meta->map_ptr) {
5485 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5486 		return -EFAULT;
5487 	}
5488 	meta->map_uid = reg->map_uid;
5489 	meta->map_ptr = map;
5490 	return 0;
5491 }
5492 
5493 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5494 			     struct bpf_call_arg_meta *meta)
5495 {
5496 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5497 	struct bpf_map_value_off_desc *off_desc;
5498 	struct bpf_map *map_ptr = reg->map_ptr;
5499 	u32 kptr_off;
5500 	int ret;
5501 
5502 	if (!tnum_is_const(reg->var_off)) {
5503 		verbose(env,
5504 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5505 			regno);
5506 		return -EINVAL;
5507 	}
5508 	if (!map_ptr->btf) {
5509 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5510 			map_ptr->name);
5511 		return -EINVAL;
5512 	}
5513 	if (!map_value_has_kptrs(map_ptr)) {
5514 		ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5515 		if (ret == -E2BIG)
5516 			verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5517 				BPF_MAP_VALUE_OFF_MAX);
5518 		else if (ret == -EEXIST)
5519 			verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5520 		else
5521 			verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5522 		return -EINVAL;
5523 	}
5524 
5525 	meta->map_ptr = map_ptr;
5526 	kptr_off = reg->off + reg->var_off.value;
5527 	off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5528 	if (!off_desc) {
5529 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5530 		return -EACCES;
5531 	}
5532 	if (off_desc->type != BPF_KPTR_REF) {
5533 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5534 		return -EACCES;
5535 	}
5536 	meta->kptr_off_desc = off_desc;
5537 	return 0;
5538 }
5539 
5540 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5541 {
5542 	return type == ARG_CONST_SIZE ||
5543 	       type == ARG_CONST_SIZE_OR_ZERO;
5544 }
5545 
5546 static bool arg_type_is_release(enum bpf_arg_type type)
5547 {
5548 	return type & OBJ_RELEASE;
5549 }
5550 
5551 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5552 {
5553 	return base_type(type) == ARG_PTR_TO_DYNPTR;
5554 }
5555 
5556 static int int_ptr_type_to_size(enum bpf_arg_type type)
5557 {
5558 	if (type == ARG_PTR_TO_INT)
5559 		return sizeof(u32);
5560 	else if (type == ARG_PTR_TO_LONG)
5561 		return sizeof(u64);
5562 
5563 	return -EINVAL;
5564 }
5565 
5566 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5567 				 const struct bpf_call_arg_meta *meta,
5568 				 enum bpf_arg_type *arg_type)
5569 {
5570 	if (!meta->map_ptr) {
5571 		/* kernel subsystem misconfigured verifier */
5572 		verbose(env, "invalid map_ptr to access map->type\n");
5573 		return -EACCES;
5574 	}
5575 
5576 	switch (meta->map_ptr->map_type) {
5577 	case BPF_MAP_TYPE_SOCKMAP:
5578 	case BPF_MAP_TYPE_SOCKHASH:
5579 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5580 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5581 		} else {
5582 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5583 			return -EINVAL;
5584 		}
5585 		break;
5586 	case BPF_MAP_TYPE_BLOOM_FILTER:
5587 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5588 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5589 		break;
5590 	default:
5591 		break;
5592 	}
5593 	return 0;
5594 }
5595 
5596 struct bpf_reg_types {
5597 	const enum bpf_reg_type types[10];
5598 	u32 *btf_id;
5599 };
5600 
5601 static const struct bpf_reg_types map_key_value_types = {
5602 	.types = {
5603 		PTR_TO_STACK,
5604 		PTR_TO_PACKET,
5605 		PTR_TO_PACKET_META,
5606 		PTR_TO_MAP_KEY,
5607 		PTR_TO_MAP_VALUE,
5608 	},
5609 };
5610 
5611 static const struct bpf_reg_types sock_types = {
5612 	.types = {
5613 		PTR_TO_SOCK_COMMON,
5614 		PTR_TO_SOCKET,
5615 		PTR_TO_TCP_SOCK,
5616 		PTR_TO_XDP_SOCK,
5617 	},
5618 };
5619 
5620 #ifdef CONFIG_NET
5621 static const struct bpf_reg_types btf_id_sock_common_types = {
5622 	.types = {
5623 		PTR_TO_SOCK_COMMON,
5624 		PTR_TO_SOCKET,
5625 		PTR_TO_TCP_SOCK,
5626 		PTR_TO_XDP_SOCK,
5627 		PTR_TO_BTF_ID,
5628 	},
5629 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5630 };
5631 #endif
5632 
5633 static const struct bpf_reg_types mem_types = {
5634 	.types = {
5635 		PTR_TO_STACK,
5636 		PTR_TO_PACKET,
5637 		PTR_TO_PACKET_META,
5638 		PTR_TO_MAP_KEY,
5639 		PTR_TO_MAP_VALUE,
5640 		PTR_TO_MEM,
5641 		PTR_TO_MEM | MEM_ALLOC,
5642 		PTR_TO_BUF,
5643 	},
5644 };
5645 
5646 static const struct bpf_reg_types int_ptr_types = {
5647 	.types = {
5648 		PTR_TO_STACK,
5649 		PTR_TO_PACKET,
5650 		PTR_TO_PACKET_META,
5651 		PTR_TO_MAP_KEY,
5652 		PTR_TO_MAP_VALUE,
5653 	},
5654 };
5655 
5656 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5657 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5658 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5659 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5660 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5661 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5662 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5663 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5664 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5665 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5666 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5667 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5668 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5669 
5670 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5671 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5672 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5673 	[ARG_CONST_SIZE]		= &scalar_types,
5674 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5675 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5676 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5677 	[ARG_PTR_TO_CTX]		= &context_types,
5678 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5679 #ifdef CONFIG_NET
5680 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5681 #endif
5682 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5683 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5684 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5685 	[ARG_PTR_TO_MEM]		= &mem_types,
5686 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5687 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5688 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5689 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5690 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5691 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5692 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5693 	[ARG_PTR_TO_TIMER]		= &timer_types,
5694 	[ARG_PTR_TO_KPTR]		= &kptr_types,
5695 	[ARG_PTR_TO_DYNPTR]		= &stack_ptr_types,
5696 };
5697 
5698 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5699 			  enum bpf_arg_type arg_type,
5700 			  const u32 *arg_btf_id,
5701 			  struct bpf_call_arg_meta *meta)
5702 {
5703 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5704 	enum bpf_reg_type expected, type = reg->type;
5705 	const struct bpf_reg_types *compatible;
5706 	int i, j;
5707 
5708 	compatible = compatible_reg_types[base_type(arg_type)];
5709 	if (!compatible) {
5710 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5711 		return -EFAULT;
5712 	}
5713 
5714 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5715 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5716 	 *
5717 	 * Same for MAYBE_NULL:
5718 	 *
5719 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5720 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5721 	 *
5722 	 * Therefore we fold these flags depending on the arg_type before comparison.
5723 	 */
5724 	if (arg_type & MEM_RDONLY)
5725 		type &= ~MEM_RDONLY;
5726 	if (arg_type & PTR_MAYBE_NULL)
5727 		type &= ~PTR_MAYBE_NULL;
5728 
5729 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5730 		expected = compatible->types[i];
5731 		if (expected == NOT_INIT)
5732 			break;
5733 
5734 		if (type == expected)
5735 			goto found;
5736 	}
5737 
5738 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5739 	for (j = 0; j + 1 < i; j++)
5740 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5741 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5742 	return -EACCES;
5743 
5744 found:
5745 	if (reg->type == PTR_TO_BTF_ID) {
5746 		/* For bpf_sk_release, it needs to match against first member
5747 		 * 'struct sock_common', hence make an exception for it. This
5748 		 * allows bpf_sk_release to work for multiple socket types.
5749 		 */
5750 		bool strict_type_match = arg_type_is_release(arg_type) &&
5751 					 meta->func_id != BPF_FUNC_sk_release;
5752 
5753 		if (!arg_btf_id) {
5754 			if (!compatible->btf_id) {
5755 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5756 				return -EFAULT;
5757 			}
5758 			arg_btf_id = compatible->btf_id;
5759 		}
5760 
5761 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
5762 			if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5763 				return -EACCES;
5764 		} else if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5765 						 btf_vmlinux, *arg_btf_id,
5766 						 strict_type_match)) {
5767 			verbose(env, "R%d is of type %s but %s is expected\n",
5768 				regno, kernel_type_name(reg->btf, reg->btf_id),
5769 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5770 			return -EACCES;
5771 		}
5772 	}
5773 
5774 	return 0;
5775 }
5776 
5777 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5778 			   const struct bpf_reg_state *reg, int regno,
5779 			   enum bpf_arg_type arg_type)
5780 {
5781 	enum bpf_reg_type type = reg->type;
5782 	bool fixed_off_ok = false;
5783 
5784 	switch ((u32)type) {
5785 	/* Pointer types where reg offset is explicitly allowed: */
5786 	case PTR_TO_STACK:
5787 		if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5788 			verbose(env, "cannot pass in dynptr at an offset\n");
5789 			return -EINVAL;
5790 		}
5791 		fallthrough;
5792 	case PTR_TO_PACKET:
5793 	case PTR_TO_PACKET_META:
5794 	case PTR_TO_MAP_KEY:
5795 	case PTR_TO_MAP_VALUE:
5796 	case PTR_TO_MEM:
5797 	case PTR_TO_MEM | MEM_RDONLY:
5798 	case PTR_TO_MEM | MEM_ALLOC:
5799 	case PTR_TO_BUF:
5800 	case PTR_TO_BUF | MEM_RDONLY:
5801 	case SCALAR_VALUE:
5802 		/* Some of the argument types nevertheless require a
5803 		 * zero register offset.
5804 		 */
5805 		if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5806 			return 0;
5807 		break;
5808 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5809 	 * fixed offset.
5810 	 */
5811 	case PTR_TO_BTF_ID:
5812 		/* When referenced PTR_TO_BTF_ID is passed to release function,
5813 		 * it's fixed offset must be 0.	In the other cases, fixed offset
5814 		 * can be non-zero.
5815 		 */
5816 		if (arg_type_is_release(arg_type) && reg->off) {
5817 			verbose(env, "R%d must have zero offset when passed to release func\n",
5818 				regno);
5819 			return -EINVAL;
5820 		}
5821 		/* For arg is release pointer, fixed_off_ok must be false, but
5822 		 * we already checked and rejected reg->off != 0 above, so set
5823 		 * to true to allow fixed offset for all other cases.
5824 		 */
5825 		fixed_off_ok = true;
5826 		break;
5827 	default:
5828 		break;
5829 	}
5830 	return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5831 }
5832 
5833 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5834 {
5835 	struct bpf_func_state *state = func(env, reg);
5836 	int spi = get_spi(reg->off);
5837 
5838 	return state->stack[spi].spilled_ptr.id;
5839 }
5840 
5841 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5842 			  struct bpf_call_arg_meta *meta,
5843 			  const struct bpf_func_proto *fn)
5844 {
5845 	u32 regno = BPF_REG_1 + arg;
5846 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5847 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5848 	enum bpf_reg_type type = reg->type;
5849 	u32 *arg_btf_id = NULL;
5850 	int err = 0;
5851 
5852 	if (arg_type == ARG_DONTCARE)
5853 		return 0;
5854 
5855 	err = check_reg_arg(env, regno, SRC_OP);
5856 	if (err)
5857 		return err;
5858 
5859 	if (arg_type == ARG_ANYTHING) {
5860 		if (is_pointer_value(env, regno)) {
5861 			verbose(env, "R%d leaks addr into helper function\n",
5862 				regno);
5863 			return -EACCES;
5864 		}
5865 		return 0;
5866 	}
5867 
5868 	if (type_is_pkt_pointer(type) &&
5869 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5870 		verbose(env, "helper access to the packet is not allowed\n");
5871 		return -EACCES;
5872 	}
5873 
5874 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5875 		err = resolve_map_arg_type(env, meta, &arg_type);
5876 		if (err)
5877 			return err;
5878 	}
5879 
5880 	if (register_is_null(reg) && type_may_be_null(arg_type))
5881 		/* A NULL register has a SCALAR_VALUE type, so skip
5882 		 * type checking.
5883 		 */
5884 		goto skip_type_check;
5885 
5886 	/* arg_btf_id and arg_size are in a union. */
5887 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5888 		arg_btf_id = fn->arg_btf_id[arg];
5889 
5890 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5891 	if (err)
5892 		return err;
5893 
5894 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
5895 	if (err)
5896 		return err;
5897 
5898 skip_type_check:
5899 	if (arg_type_is_release(arg_type)) {
5900 		if (arg_type_is_dynptr(arg_type)) {
5901 			struct bpf_func_state *state = func(env, reg);
5902 			int spi = get_spi(reg->off);
5903 
5904 			if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5905 			    !state->stack[spi].spilled_ptr.id) {
5906 				verbose(env, "arg %d is an unacquired reference\n", regno);
5907 				return -EINVAL;
5908 			}
5909 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
5910 			verbose(env, "R%d must be referenced when passed to release function\n",
5911 				regno);
5912 			return -EINVAL;
5913 		}
5914 		if (meta->release_regno) {
5915 			verbose(env, "verifier internal error: more than one release argument\n");
5916 			return -EFAULT;
5917 		}
5918 		meta->release_regno = regno;
5919 	}
5920 
5921 	if (reg->ref_obj_id) {
5922 		if (meta->ref_obj_id) {
5923 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5924 				regno, reg->ref_obj_id,
5925 				meta->ref_obj_id);
5926 			return -EFAULT;
5927 		}
5928 		meta->ref_obj_id = reg->ref_obj_id;
5929 	}
5930 
5931 	switch (base_type(arg_type)) {
5932 	case ARG_CONST_MAP_PTR:
5933 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5934 		if (meta->map_ptr) {
5935 			/* Use map_uid (which is unique id of inner map) to reject:
5936 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5937 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5938 			 * if (inner_map1 && inner_map2) {
5939 			 *     timer = bpf_map_lookup_elem(inner_map1);
5940 			 *     if (timer)
5941 			 *         // mismatch would have been allowed
5942 			 *         bpf_timer_init(timer, inner_map2);
5943 			 * }
5944 			 *
5945 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5946 			 */
5947 			if (meta->map_ptr != reg->map_ptr ||
5948 			    meta->map_uid != reg->map_uid) {
5949 				verbose(env,
5950 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5951 					meta->map_uid, reg->map_uid);
5952 				return -EINVAL;
5953 			}
5954 		}
5955 		meta->map_ptr = reg->map_ptr;
5956 		meta->map_uid = reg->map_uid;
5957 		break;
5958 	case ARG_PTR_TO_MAP_KEY:
5959 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5960 		 * check that [key, key + map->key_size) are within
5961 		 * stack limits and initialized
5962 		 */
5963 		if (!meta->map_ptr) {
5964 			/* in function declaration map_ptr must come before
5965 			 * map_key, so that it's verified and known before
5966 			 * we have to check map_key here. Otherwise it means
5967 			 * that kernel subsystem misconfigured verifier
5968 			 */
5969 			verbose(env, "invalid map_ptr to access map->key\n");
5970 			return -EACCES;
5971 		}
5972 		err = check_helper_mem_access(env, regno,
5973 					      meta->map_ptr->key_size, false,
5974 					      NULL);
5975 		break;
5976 	case ARG_PTR_TO_MAP_VALUE:
5977 		if (type_may_be_null(arg_type) && register_is_null(reg))
5978 			return 0;
5979 
5980 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5981 		 * check [value, value + map->value_size) validity
5982 		 */
5983 		if (!meta->map_ptr) {
5984 			/* kernel subsystem misconfigured verifier */
5985 			verbose(env, "invalid map_ptr to access map->value\n");
5986 			return -EACCES;
5987 		}
5988 		meta->raw_mode = arg_type & MEM_UNINIT;
5989 		err = check_helper_mem_access(env, regno,
5990 					      meta->map_ptr->value_size, false,
5991 					      meta);
5992 		break;
5993 	case ARG_PTR_TO_PERCPU_BTF_ID:
5994 		if (!reg->btf_id) {
5995 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5996 			return -EACCES;
5997 		}
5998 		meta->ret_btf = reg->btf;
5999 		meta->ret_btf_id = reg->btf_id;
6000 		break;
6001 	case ARG_PTR_TO_SPIN_LOCK:
6002 		if (meta->func_id == BPF_FUNC_spin_lock) {
6003 			if (process_spin_lock(env, regno, true))
6004 				return -EACCES;
6005 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6006 			if (process_spin_lock(env, regno, false))
6007 				return -EACCES;
6008 		} else {
6009 			verbose(env, "verifier internal error\n");
6010 			return -EFAULT;
6011 		}
6012 		break;
6013 	case ARG_PTR_TO_TIMER:
6014 		if (process_timer_func(env, regno, meta))
6015 			return -EACCES;
6016 		break;
6017 	case ARG_PTR_TO_FUNC:
6018 		meta->subprogno = reg->subprogno;
6019 		break;
6020 	case ARG_PTR_TO_MEM:
6021 		/* The access to this pointer is only checked when we hit the
6022 		 * next is_mem_size argument below.
6023 		 */
6024 		meta->raw_mode = arg_type & MEM_UNINIT;
6025 		if (arg_type & MEM_FIXED_SIZE) {
6026 			err = check_helper_mem_access(env, regno,
6027 						      fn->arg_size[arg], false,
6028 						      meta);
6029 		}
6030 		break;
6031 	case ARG_CONST_SIZE:
6032 		err = check_mem_size_reg(env, reg, regno, false, meta);
6033 		break;
6034 	case ARG_CONST_SIZE_OR_ZERO:
6035 		err = check_mem_size_reg(env, reg, regno, true, meta);
6036 		break;
6037 	case ARG_PTR_TO_DYNPTR:
6038 		if (arg_type & MEM_UNINIT) {
6039 			if (!is_dynptr_reg_valid_uninit(env, reg)) {
6040 				verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6041 				return -EINVAL;
6042 			}
6043 
6044 			/* We only support one dynptr being uninitialized at the moment,
6045 			 * which is sufficient for the helper functions we have right now.
6046 			 */
6047 			if (meta->uninit_dynptr_regno) {
6048 				verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6049 				return -EFAULT;
6050 			}
6051 
6052 			meta->uninit_dynptr_regno = regno;
6053 		} else if (!is_dynptr_reg_valid_init(env, reg, arg_type)) {
6054 			const char *err_extra = "";
6055 
6056 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6057 			case DYNPTR_TYPE_LOCAL:
6058 				err_extra = "local ";
6059 				break;
6060 			case DYNPTR_TYPE_RINGBUF:
6061 				err_extra = "ringbuf ";
6062 				break;
6063 			default:
6064 				break;
6065 			}
6066 
6067 			verbose(env, "Expected an initialized %sdynptr as arg #%d\n",
6068 				err_extra, arg + 1);
6069 			return -EINVAL;
6070 		}
6071 		break;
6072 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6073 		if (!tnum_is_const(reg->var_off)) {
6074 			verbose(env, "R%d is not a known constant'\n",
6075 				regno);
6076 			return -EACCES;
6077 		}
6078 		meta->mem_size = reg->var_off.value;
6079 		err = mark_chain_precision(env, regno);
6080 		if (err)
6081 			return err;
6082 		break;
6083 	case ARG_PTR_TO_INT:
6084 	case ARG_PTR_TO_LONG:
6085 	{
6086 		int size = int_ptr_type_to_size(arg_type);
6087 
6088 		err = check_helper_mem_access(env, regno, size, false, meta);
6089 		if (err)
6090 			return err;
6091 		err = check_ptr_alignment(env, reg, 0, size, true);
6092 		break;
6093 	}
6094 	case ARG_PTR_TO_CONST_STR:
6095 	{
6096 		struct bpf_map *map = reg->map_ptr;
6097 		int map_off;
6098 		u64 map_addr;
6099 		char *str_ptr;
6100 
6101 		if (!bpf_map_is_rdonly(map)) {
6102 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6103 			return -EACCES;
6104 		}
6105 
6106 		if (!tnum_is_const(reg->var_off)) {
6107 			verbose(env, "R%d is not a constant address'\n", regno);
6108 			return -EACCES;
6109 		}
6110 
6111 		if (!map->ops->map_direct_value_addr) {
6112 			verbose(env, "no direct value access support for this map type\n");
6113 			return -EACCES;
6114 		}
6115 
6116 		err = check_map_access(env, regno, reg->off,
6117 				       map->value_size - reg->off, false,
6118 				       ACCESS_HELPER);
6119 		if (err)
6120 			return err;
6121 
6122 		map_off = reg->off + reg->var_off.value;
6123 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6124 		if (err) {
6125 			verbose(env, "direct value access on string failed\n");
6126 			return err;
6127 		}
6128 
6129 		str_ptr = (char *)(long)(map_addr);
6130 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6131 			verbose(env, "string is not zero-terminated\n");
6132 			return -EINVAL;
6133 		}
6134 		break;
6135 	}
6136 	case ARG_PTR_TO_KPTR:
6137 		if (process_kptr_func(env, regno, meta))
6138 			return -EACCES;
6139 		break;
6140 	}
6141 
6142 	return err;
6143 }
6144 
6145 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6146 {
6147 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6148 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6149 
6150 	if (func_id != BPF_FUNC_map_update_elem)
6151 		return false;
6152 
6153 	/* It's not possible to get access to a locked struct sock in these
6154 	 * contexts, so updating is safe.
6155 	 */
6156 	switch (type) {
6157 	case BPF_PROG_TYPE_TRACING:
6158 		if (eatype == BPF_TRACE_ITER)
6159 			return true;
6160 		break;
6161 	case BPF_PROG_TYPE_SOCKET_FILTER:
6162 	case BPF_PROG_TYPE_SCHED_CLS:
6163 	case BPF_PROG_TYPE_SCHED_ACT:
6164 	case BPF_PROG_TYPE_XDP:
6165 	case BPF_PROG_TYPE_SK_REUSEPORT:
6166 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6167 	case BPF_PROG_TYPE_SK_LOOKUP:
6168 		return true;
6169 	default:
6170 		break;
6171 	}
6172 
6173 	verbose(env, "cannot update sockmap in this context\n");
6174 	return false;
6175 }
6176 
6177 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6178 {
6179 	return env->prog->jit_requested &&
6180 	       bpf_jit_supports_subprog_tailcalls();
6181 }
6182 
6183 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6184 					struct bpf_map *map, int func_id)
6185 {
6186 	if (!map)
6187 		return 0;
6188 
6189 	/* We need a two way check, first is from map perspective ... */
6190 	switch (map->map_type) {
6191 	case BPF_MAP_TYPE_PROG_ARRAY:
6192 		if (func_id != BPF_FUNC_tail_call)
6193 			goto error;
6194 		break;
6195 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6196 		if (func_id != BPF_FUNC_perf_event_read &&
6197 		    func_id != BPF_FUNC_perf_event_output &&
6198 		    func_id != BPF_FUNC_skb_output &&
6199 		    func_id != BPF_FUNC_perf_event_read_value &&
6200 		    func_id != BPF_FUNC_xdp_output)
6201 			goto error;
6202 		break;
6203 	case BPF_MAP_TYPE_RINGBUF:
6204 		if (func_id != BPF_FUNC_ringbuf_output &&
6205 		    func_id != BPF_FUNC_ringbuf_reserve &&
6206 		    func_id != BPF_FUNC_ringbuf_query &&
6207 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6208 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6209 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6210 			goto error;
6211 		break;
6212 	case BPF_MAP_TYPE_STACK_TRACE:
6213 		if (func_id != BPF_FUNC_get_stackid)
6214 			goto error;
6215 		break;
6216 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6217 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6218 		    func_id != BPF_FUNC_current_task_under_cgroup)
6219 			goto error;
6220 		break;
6221 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6222 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6223 		if (func_id != BPF_FUNC_get_local_storage)
6224 			goto error;
6225 		break;
6226 	case BPF_MAP_TYPE_DEVMAP:
6227 	case BPF_MAP_TYPE_DEVMAP_HASH:
6228 		if (func_id != BPF_FUNC_redirect_map &&
6229 		    func_id != BPF_FUNC_map_lookup_elem)
6230 			goto error;
6231 		break;
6232 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6233 	 * appear.
6234 	 */
6235 	case BPF_MAP_TYPE_CPUMAP:
6236 		if (func_id != BPF_FUNC_redirect_map)
6237 			goto error;
6238 		break;
6239 	case BPF_MAP_TYPE_XSKMAP:
6240 		if (func_id != BPF_FUNC_redirect_map &&
6241 		    func_id != BPF_FUNC_map_lookup_elem)
6242 			goto error;
6243 		break;
6244 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6245 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6246 		if (func_id != BPF_FUNC_map_lookup_elem)
6247 			goto error;
6248 		break;
6249 	case BPF_MAP_TYPE_SOCKMAP:
6250 		if (func_id != BPF_FUNC_sk_redirect_map &&
6251 		    func_id != BPF_FUNC_sock_map_update &&
6252 		    func_id != BPF_FUNC_map_delete_elem &&
6253 		    func_id != BPF_FUNC_msg_redirect_map &&
6254 		    func_id != BPF_FUNC_sk_select_reuseport &&
6255 		    func_id != BPF_FUNC_map_lookup_elem &&
6256 		    !may_update_sockmap(env, func_id))
6257 			goto error;
6258 		break;
6259 	case BPF_MAP_TYPE_SOCKHASH:
6260 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6261 		    func_id != BPF_FUNC_sock_hash_update &&
6262 		    func_id != BPF_FUNC_map_delete_elem &&
6263 		    func_id != BPF_FUNC_msg_redirect_hash &&
6264 		    func_id != BPF_FUNC_sk_select_reuseport &&
6265 		    func_id != BPF_FUNC_map_lookup_elem &&
6266 		    !may_update_sockmap(env, func_id))
6267 			goto error;
6268 		break;
6269 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6270 		if (func_id != BPF_FUNC_sk_select_reuseport)
6271 			goto error;
6272 		break;
6273 	case BPF_MAP_TYPE_QUEUE:
6274 	case BPF_MAP_TYPE_STACK:
6275 		if (func_id != BPF_FUNC_map_peek_elem &&
6276 		    func_id != BPF_FUNC_map_pop_elem &&
6277 		    func_id != BPF_FUNC_map_push_elem)
6278 			goto error;
6279 		break;
6280 	case BPF_MAP_TYPE_SK_STORAGE:
6281 		if (func_id != BPF_FUNC_sk_storage_get &&
6282 		    func_id != BPF_FUNC_sk_storage_delete)
6283 			goto error;
6284 		break;
6285 	case BPF_MAP_TYPE_INODE_STORAGE:
6286 		if (func_id != BPF_FUNC_inode_storage_get &&
6287 		    func_id != BPF_FUNC_inode_storage_delete)
6288 			goto error;
6289 		break;
6290 	case BPF_MAP_TYPE_TASK_STORAGE:
6291 		if (func_id != BPF_FUNC_task_storage_get &&
6292 		    func_id != BPF_FUNC_task_storage_delete)
6293 			goto error;
6294 		break;
6295 	case BPF_MAP_TYPE_BLOOM_FILTER:
6296 		if (func_id != BPF_FUNC_map_peek_elem &&
6297 		    func_id != BPF_FUNC_map_push_elem)
6298 			goto error;
6299 		break;
6300 	default:
6301 		break;
6302 	}
6303 
6304 	/* ... and second from the function itself. */
6305 	switch (func_id) {
6306 	case BPF_FUNC_tail_call:
6307 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6308 			goto error;
6309 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6310 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6311 			return -EINVAL;
6312 		}
6313 		break;
6314 	case BPF_FUNC_perf_event_read:
6315 	case BPF_FUNC_perf_event_output:
6316 	case BPF_FUNC_perf_event_read_value:
6317 	case BPF_FUNC_skb_output:
6318 	case BPF_FUNC_xdp_output:
6319 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6320 			goto error;
6321 		break;
6322 	case BPF_FUNC_ringbuf_output:
6323 	case BPF_FUNC_ringbuf_reserve:
6324 	case BPF_FUNC_ringbuf_query:
6325 	case BPF_FUNC_ringbuf_reserve_dynptr:
6326 	case BPF_FUNC_ringbuf_submit_dynptr:
6327 	case BPF_FUNC_ringbuf_discard_dynptr:
6328 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6329 			goto error;
6330 		break;
6331 	case BPF_FUNC_get_stackid:
6332 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6333 			goto error;
6334 		break;
6335 	case BPF_FUNC_current_task_under_cgroup:
6336 	case BPF_FUNC_skb_under_cgroup:
6337 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6338 			goto error;
6339 		break;
6340 	case BPF_FUNC_redirect_map:
6341 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6342 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6343 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6344 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6345 			goto error;
6346 		break;
6347 	case BPF_FUNC_sk_redirect_map:
6348 	case BPF_FUNC_msg_redirect_map:
6349 	case BPF_FUNC_sock_map_update:
6350 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6351 			goto error;
6352 		break;
6353 	case BPF_FUNC_sk_redirect_hash:
6354 	case BPF_FUNC_msg_redirect_hash:
6355 	case BPF_FUNC_sock_hash_update:
6356 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6357 			goto error;
6358 		break;
6359 	case BPF_FUNC_get_local_storage:
6360 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6361 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6362 			goto error;
6363 		break;
6364 	case BPF_FUNC_sk_select_reuseport:
6365 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6366 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6367 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6368 			goto error;
6369 		break;
6370 	case BPF_FUNC_map_pop_elem:
6371 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6372 		    map->map_type != BPF_MAP_TYPE_STACK)
6373 			goto error;
6374 		break;
6375 	case BPF_FUNC_map_peek_elem:
6376 	case BPF_FUNC_map_push_elem:
6377 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6378 		    map->map_type != BPF_MAP_TYPE_STACK &&
6379 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6380 			goto error;
6381 		break;
6382 	case BPF_FUNC_map_lookup_percpu_elem:
6383 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6384 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6385 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6386 			goto error;
6387 		break;
6388 	case BPF_FUNC_sk_storage_get:
6389 	case BPF_FUNC_sk_storage_delete:
6390 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6391 			goto error;
6392 		break;
6393 	case BPF_FUNC_inode_storage_get:
6394 	case BPF_FUNC_inode_storage_delete:
6395 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6396 			goto error;
6397 		break;
6398 	case BPF_FUNC_task_storage_get:
6399 	case BPF_FUNC_task_storage_delete:
6400 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6401 			goto error;
6402 		break;
6403 	default:
6404 		break;
6405 	}
6406 
6407 	return 0;
6408 error:
6409 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6410 		map->map_type, func_id_name(func_id), func_id);
6411 	return -EINVAL;
6412 }
6413 
6414 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6415 {
6416 	int count = 0;
6417 
6418 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6419 		count++;
6420 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6421 		count++;
6422 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6423 		count++;
6424 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6425 		count++;
6426 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6427 		count++;
6428 
6429 	/* We only support one arg being in raw mode at the moment,
6430 	 * which is sufficient for the helper functions we have
6431 	 * right now.
6432 	 */
6433 	return count <= 1;
6434 }
6435 
6436 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6437 {
6438 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6439 	bool has_size = fn->arg_size[arg] != 0;
6440 	bool is_next_size = false;
6441 
6442 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6443 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6444 
6445 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6446 		return is_next_size;
6447 
6448 	return has_size == is_next_size || is_next_size == is_fixed;
6449 }
6450 
6451 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6452 {
6453 	/* bpf_xxx(..., buf, len) call will access 'len'
6454 	 * bytes from memory 'buf'. Both arg types need
6455 	 * to be paired, so make sure there's no buggy
6456 	 * helper function specification.
6457 	 */
6458 	if (arg_type_is_mem_size(fn->arg1_type) ||
6459 	    check_args_pair_invalid(fn, 0) ||
6460 	    check_args_pair_invalid(fn, 1) ||
6461 	    check_args_pair_invalid(fn, 2) ||
6462 	    check_args_pair_invalid(fn, 3) ||
6463 	    check_args_pair_invalid(fn, 4))
6464 		return false;
6465 
6466 	return true;
6467 }
6468 
6469 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6470 {
6471 	int i;
6472 
6473 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6474 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6475 			return false;
6476 
6477 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6478 		    /* arg_btf_id and arg_size are in a union. */
6479 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6480 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6481 			return false;
6482 	}
6483 
6484 	return true;
6485 }
6486 
6487 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6488 {
6489 	return check_raw_mode_ok(fn) &&
6490 	       check_arg_pair_ok(fn) &&
6491 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
6492 }
6493 
6494 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6495  * are now invalid, so turn them into unknown SCALAR_VALUE.
6496  */
6497 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
6498 				     struct bpf_func_state *state)
6499 {
6500 	struct bpf_reg_state *regs = state->regs, *reg;
6501 	int i;
6502 
6503 	for (i = 0; i < MAX_BPF_REG; i++)
6504 		if (reg_is_pkt_pointer_any(&regs[i]))
6505 			mark_reg_unknown(env, regs, i);
6506 
6507 	bpf_for_each_spilled_reg(i, state, reg) {
6508 		if (!reg)
6509 			continue;
6510 		if (reg_is_pkt_pointer_any(reg))
6511 			__mark_reg_unknown(env, reg);
6512 	}
6513 }
6514 
6515 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6516 {
6517 	struct bpf_verifier_state *vstate = env->cur_state;
6518 	int i;
6519 
6520 	for (i = 0; i <= vstate->curframe; i++)
6521 		__clear_all_pkt_pointers(env, vstate->frame[i]);
6522 }
6523 
6524 enum {
6525 	AT_PKT_END = -1,
6526 	BEYOND_PKT_END = -2,
6527 };
6528 
6529 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6530 {
6531 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6532 	struct bpf_reg_state *reg = &state->regs[regn];
6533 
6534 	if (reg->type != PTR_TO_PACKET)
6535 		/* PTR_TO_PACKET_META is not supported yet */
6536 		return;
6537 
6538 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6539 	 * How far beyond pkt_end it goes is unknown.
6540 	 * if (!range_open) it's the case of pkt >= pkt_end
6541 	 * if (range_open) it's the case of pkt > pkt_end
6542 	 * hence this pointer is at least 1 byte bigger than pkt_end
6543 	 */
6544 	if (range_open)
6545 		reg->range = BEYOND_PKT_END;
6546 	else
6547 		reg->range = AT_PKT_END;
6548 }
6549 
6550 static void release_reg_references(struct bpf_verifier_env *env,
6551 				   struct bpf_func_state *state,
6552 				   int ref_obj_id)
6553 {
6554 	struct bpf_reg_state *regs = state->regs, *reg;
6555 	int i;
6556 
6557 	for (i = 0; i < MAX_BPF_REG; i++)
6558 		if (regs[i].ref_obj_id == ref_obj_id)
6559 			mark_reg_unknown(env, regs, i);
6560 
6561 	bpf_for_each_spilled_reg(i, state, reg) {
6562 		if (!reg)
6563 			continue;
6564 		if (reg->ref_obj_id == ref_obj_id)
6565 			__mark_reg_unknown(env, reg);
6566 	}
6567 }
6568 
6569 /* The pointer with the specified id has released its reference to kernel
6570  * resources. Identify all copies of the same pointer and clear the reference.
6571  */
6572 static int release_reference(struct bpf_verifier_env *env,
6573 			     int ref_obj_id)
6574 {
6575 	struct bpf_verifier_state *vstate = env->cur_state;
6576 	int err;
6577 	int i;
6578 
6579 	err = release_reference_state(cur_func(env), ref_obj_id);
6580 	if (err)
6581 		return err;
6582 
6583 	for (i = 0; i <= vstate->curframe; i++)
6584 		release_reg_references(env, vstate->frame[i], ref_obj_id);
6585 
6586 	return 0;
6587 }
6588 
6589 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6590 				    struct bpf_reg_state *regs)
6591 {
6592 	int i;
6593 
6594 	/* after the call registers r0 - r5 were scratched */
6595 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6596 		mark_reg_not_init(env, regs, caller_saved[i]);
6597 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6598 	}
6599 }
6600 
6601 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6602 				   struct bpf_func_state *caller,
6603 				   struct bpf_func_state *callee,
6604 				   int insn_idx);
6605 
6606 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6607 			     int *insn_idx, int subprog,
6608 			     set_callee_state_fn set_callee_state_cb)
6609 {
6610 	struct bpf_verifier_state *state = env->cur_state;
6611 	struct bpf_func_info_aux *func_info_aux;
6612 	struct bpf_func_state *caller, *callee;
6613 	int err;
6614 	bool is_global = false;
6615 
6616 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6617 		verbose(env, "the call stack of %d frames is too deep\n",
6618 			state->curframe + 2);
6619 		return -E2BIG;
6620 	}
6621 
6622 	caller = state->frame[state->curframe];
6623 	if (state->frame[state->curframe + 1]) {
6624 		verbose(env, "verifier bug. Frame %d already allocated\n",
6625 			state->curframe + 1);
6626 		return -EFAULT;
6627 	}
6628 
6629 	func_info_aux = env->prog->aux->func_info_aux;
6630 	if (func_info_aux)
6631 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6632 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6633 	if (err == -EFAULT)
6634 		return err;
6635 	if (is_global) {
6636 		if (err) {
6637 			verbose(env, "Caller passes invalid args into func#%d\n",
6638 				subprog);
6639 			return err;
6640 		} else {
6641 			if (env->log.level & BPF_LOG_LEVEL)
6642 				verbose(env,
6643 					"Func#%d is global and valid. Skipping.\n",
6644 					subprog);
6645 			clear_caller_saved_regs(env, caller->regs);
6646 
6647 			/* All global functions return a 64-bit SCALAR_VALUE */
6648 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6649 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6650 
6651 			/* continue with next insn after call */
6652 			return 0;
6653 		}
6654 	}
6655 
6656 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6657 	    insn->src_reg == 0 &&
6658 	    insn->imm == BPF_FUNC_timer_set_callback) {
6659 		struct bpf_verifier_state *async_cb;
6660 
6661 		/* there is no real recursion here. timer callbacks are async */
6662 		env->subprog_info[subprog].is_async_cb = true;
6663 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6664 					 *insn_idx, subprog);
6665 		if (!async_cb)
6666 			return -EFAULT;
6667 		callee = async_cb->frame[0];
6668 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6669 
6670 		/* Convert bpf_timer_set_callback() args into timer callback args */
6671 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6672 		if (err)
6673 			return err;
6674 
6675 		clear_caller_saved_regs(env, caller->regs);
6676 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6677 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6678 		/* continue with next insn after call */
6679 		return 0;
6680 	}
6681 
6682 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6683 	if (!callee)
6684 		return -ENOMEM;
6685 	state->frame[state->curframe + 1] = callee;
6686 
6687 	/* callee cannot access r0, r6 - r9 for reading and has to write
6688 	 * into its own stack before reading from it.
6689 	 * callee can read/write into caller's stack
6690 	 */
6691 	init_func_state(env, callee,
6692 			/* remember the callsite, it will be used by bpf_exit */
6693 			*insn_idx /* callsite */,
6694 			state->curframe + 1 /* frameno within this callchain */,
6695 			subprog /* subprog number within this prog */);
6696 
6697 	/* Transfer references to the callee */
6698 	err = copy_reference_state(callee, caller);
6699 	if (err)
6700 		return err;
6701 
6702 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6703 	if (err)
6704 		return err;
6705 
6706 	clear_caller_saved_regs(env, caller->regs);
6707 
6708 	/* only increment it after check_reg_arg() finished */
6709 	state->curframe++;
6710 
6711 	/* and go analyze first insn of the callee */
6712 	*insn_idx = env->subprog_info[subprog].start - 1;
6713 
6714 	if (env->log.level & BPF_LOG_LEVEL) {
6715 		verbose(env, "caller:\n");
6716 		print_verifier_state(env, caller, true);
6717 		verbose(env, "callee:\n");
6718 		print_verifier_state(env, callee, true);
6719 	}
6720 	return 0;
6721 }
6722 
6723 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6724 				   struct bpf_func_state *caller,
6725 				   struct bpf_func_state *callee)
6726 {
6727 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6728 	 *      void *callback_ctx, u64 flags);
6729 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6730 	 *      void *callback_ctx);
6731 	 */
6732 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6733 
6734 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6735 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6736 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6737 
6738 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6739 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6740 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6741 
6742 	/* pointer to stack or null */
6743 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6744 
6745 	/* unused */
6746 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6747 	return 0;
6748 }
6749 
6750 static int set_callee_state(struct bpf_verifier_env *env,
6751 			    struct bpf_func_state *caller,
6752 			    struct bpf_func_state *callee, int insn_idx)
6753 {
6754 	int i;
6755 
6756 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6757 	 * pointers, which connects us up to the liveness chain
6758 	 */
6759 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6760 		callee->regs[i] = caller->regs[i];
6761 	return 0;
6762 }
6763 
6764 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6765 			   int *insn_idx)
6766 {
6767 	int subprog, target_insn;
6768 
6769 	target_insn = *insn_idx + insn->imm + 1;
6770 	subprog = find_subprog(env, target_insn);
6771 	if (subprog < 0) {
6772 		verbose(env, "verifier bug. No program starts at insn %d\n",
6773 			target_insn);
6774 		return -EFAULT;
6775 	}
6776 
6777 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6778 }
6779 
6780 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6781 				       struct bpf_func_state *caller,
6782 				       struct bpf_func_state *callee,
6783 				       int insn_idx)
6784 {
6785 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6786 	struct bpf_map *map;
6787 	int err;
6788 
6789 	if (bpf_map_ptr_poisoned(insn_aux)) {
6790 		verbose(env, "tail_call abusing map_ptr\n");
6791 		return -EINVAL;
6792 	}
6793 
6794 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6795 	if (!map->ops->map_set_for_each_callback_args ||
6796 	    !map->ops->map_for_each_callback) {
6797 		verbose(env, "callback function not allowed for map\n");
6798 		return -ENOTSUPP;
6799 	}
6800 
6801 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6802 	if (err)
6803 		return err;
6804 
6805 	callee->in_callback_fn = true;
6806 	return 0;
6807 }
6808 
6809 static int set_loop_callback_state(struct bpf_verifier_env *env,
6810 				   struct bpf_func_state *caller,
6811 				   struct bpf_func_state *callee,
6812 				   int insn_idx)
6813 {
6814 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6815 	 *	    u64 flags);
6816 	 * callback_fn(u32 index, void *callback_ctx);
6817 	 */
6818 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6819 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6820 
6821 	/* unused */
6822 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6823 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6824 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6825 
6826 	callee->in_callback_fn = true;
6827 	return 0;
6828 }
6829 
6830 static int set_timer_callback_state(struct bpf_verifier_env *env,
6831 				    struct bpf_func_state *caller,
6832 				    struct bpf_func_state *callee,
6833 				    int insn_idx)
6834 {
6835 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6836 
6837 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6838 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6839 	 */
6840 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6841 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6842 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6843 
6844 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6845 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6846 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6847 
6848 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6849 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6850 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6851 
6852 	/* unused */
6853 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6854 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6855 	callee->in_async_callback_fn = true;
6856 	return 0;
6857 }
6858 
6859 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6860 				       struct bpf_func_state *caller,
6861 				       struct bpf_func_state *callee,
6862 				       int insn_idx)
6863 {
6864 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6865 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6866 	 * (callback_fn)(struct task_struct *task,
6867 	 *               struct vm_area_struct *vma, void *callback_ctx);
6868 	 */
6869 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6870 
6871 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6872 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6873 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6874 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6875 
6876 	/* pointer to stack or null */
6877 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6878 
6879 	/* unused */
6880 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6881 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6882 	callee->in_callback_fn = true;
6883 	return 0;
6884 }
6885 
6886 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6887 {
6888 	struct bpf_verifier_state *state = env->cur_state;
6889 	struct bpf_func_state *caller, *callee;
6890 	struct bpf_reg_state *r0;
6891 	int err;
6892 
6893 	callee = state->frame[state->curframe];
6894 	r0 = &callee->regs[BPF_REG_0];
6895 	if (r0->type == PTR_TO_STACK) {
6896 		/* technically it's ok to return caller's stack pointer
6897 		 * (or caller's caller's pointer) back to the caller,
6898 		 * since these pointers are valid. Only current stack
6899 		 * pointer will be invalid as soon as function exits,
6900 		 * but let's be conservative
6901 		 */
6902 		verbose(env, "cannot return stack pointer to the caller\n");
6903 		return -EINVAL;
6904 	}
6905 
6906 	state->curframe--;
6907 	caller = state->frame[state->curframe];
6908 	if (callee->in_callback_fn) {
6909 		/* enforce R0 return value range [0, 1]. */
6910 		struct tnum range = tnum_range(0, 1);
6911 
6912 		if (r0->type != SCALAR_VALUE) {
6913 			verbose(env, "R0 not a scalar value\n");
6914 			return -EACCES;
6915 		}
6916 		if (!tnum_in(range, r0->var_off)) {
6917 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6918 			return -EINVAL;
6919 		}
6920 	} else {
6921 		/* return to the caller whatever r0 had in the callee */
6922 		caller->regs[BPF_REG_0] = *r0;
6923 	}
6924 
6925 	/* callback_fn frame should have released its own additions to parent's
6926 	 * reference state at this point, or check_reference_leak would
6927 	 * complain, hence it must be the same as the caller. There is no need
6928 	 * to copy it back.
6929 	 */
6930 	if (!callee->in_callback_fn) {
6931 		/* Transfer references to the caller */
6932 		err = copy_reference_state(caller, callee);
6933 		if (err)
6934 			return err;
6935 	}
6936 
6937 	*insn_idx = callee->callsite + 1;
6938 	if (env->log.level & BPF_LOG_LEVEL) {
6939 		verbose(env, "returning from callee:\n");
6940 		print_verifier_state(env, callee, true);
6941 		verbose(env, "to caller at %d:\n", *insn_idx);
6942 		print_verifier_state(env, caller, true);
6943 	}
6944 	/* clear everything in the callee */
6945 	free_func_state(callee);
6946 	state->frame[state->curframe + 1] = NULL;
6947 	return 0;
6948 }
6949 
6950 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6951 				   int func_id,
6952 				   struct bpf_call_arg_meta *meta)
6953 {
6954 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6955 
6956 	if (ret_type != RET_INTEGER ||
6957 	    (func_id != BPF_FUNC_get_stack &&
6958 	     func_id != BPF_FUNC_get_task_stack &&
6959 	     func_id != BPF_FUNC_probe_read_str &&
6960 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6961 	     func_id != BPF_FUNC_probe_read_user_str))
6962 		return;
6963 
6964 	ret_reg->smax_value = meta->msize_max_value;
6965 	ret_reg->s32_max_value = meta->msize_max_value;
6966 	ret_reg->smin_value = -MAX_ERRNO;
6967 	ret_reg->s32_min_value = -MAX_ERRNO;
6968 	reg_bounds_sync(ret_reg);
6969 }
6970 
6971 static int
6972 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6973 		int func_id, int insn_idx)
6974 {
6975 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6976 	struct bpf_map *map = meta->map_ptr;
6977 
6978 	if (func_id != BPF_FUNC_tail_call &&
6979 	    func_id != BPF_FUNC_map_lookup_elem &&
6980 	    func_id != BPF_FUNC_map_update_elem &&
6981 	    func_id != BPF_FUNC_map_delete_elem &&
6982 	    func_id != BPF_FUNC_map_push_elem &&
6983 	    func_id != BPF_FUNC_map_pop_elem &&
6984 	    func_id != BPF_FUNC_map_peek_elem &&
6985 	    func_id != BPF_FUNC_for_each_map_elem &&
6986 	    func_id != BPF_FUNC_redirect_map &&
6987 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
6988 		return 0;
6989 
6990 	if (map == NULL) {
6991 		verbose(env, "kernel subsystem misconfigured verifier\n");
6992 		return -EINVAL;
6993 	}
6994 
6995 	/* In case of read-only, some additional restrictions
6996 	 * need to be applied in order to prevent altering the
6997 	 * state of the map from program side.
6998 	 */
6999 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7000 	    (func_id == BPF_FUNC_map_delete_elem ||
7001 	     func_id == BPF_FUNC_map_update_elem ||
7002 	     func_id == BPF_FUNC_map_push_elem ||
7003 	     func_id == BPF_FUNC_map_pop_elem)) {
7004 		verbose(env, "write into map forbidden\n");
7005 		return -EACCES;
7006 	}
7007 
7008 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7009 		bpf_map_ptr_store(aux, meta->map_ptr,
7010 				  !meta->map_ptr->bypass_spec_v1);
7011 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7012 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7013 				  !meta->map_ptr->bypass_spec_v1);
7014 	return 0;
7015 }
7016 
7017 static int
7018 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7019 		int func_id, int insn_idx)
7020 {
7021 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7022 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7023 	struct bpf_map *map = meta->map_ptr;
7024 	u64 val, max;
7025 	int err;
7026 
7027 	if (func_id != BPF_FUNC_tail_call)
7028 		return 0;
7029 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7030 		verbose(env, "kernel subsystem misconfigured verifier\n");
7031 		return -EINVAL;
7032 	}
7033 
7034 	reg = &regs[BPF_REG_3];
7035 	val = reg->var_off.value;
7036 	max = map->max_entries;
7037 
7038 	if (!(register_is_const(reg) && val < max)) {
7039 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7040 		return 0;
7041 	}
7042 
7043 	err = mark_chain_precision(env, BPF_REG_3);
7044 	if (err)
7045 		return err;
7046 	if (bpf_map_key_unseen(aux))
7047 		bpf_map_key_store(aux, val);
7048 	else if (!bpf_map_key_poisoned(aux) &&
7049 		  bpf_map_key_immediate(aux) != val)
7050 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7051 	return 0;
7052 }
7053 
7054 static int check_reference_leak(struct bpf_verifier_env *env)
7055 {
7056 	struct bpf_func_state *state = cur_func(env);
7057 	bool refs_lingering = false;
7058 	int i;
7059 
7060 	if (state->frameno && !state->in_callback_fn)
7061 		return 0;
7062 
7063 	for (i = 0; i < state->acquired_refs; i++) {
7064 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7065 			continue;
7066 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7067 			state->refs[i].id, state->refs[i].insn_idx);
7068 		refs_lingering = true;
7069 	}
7070 	return refs_lingering ? -EINVAL : 0;
7071 }
7072 
7073 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7074 				   struct bpf_reg_state *regs)
7075 {
7076 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7077 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7078 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7079 	int err, fmt_map_off, num_args;
7080 	u64 fmt_addr;
7081 	char *fmt;
7082 
7083 	/* data must be an array of u64 */
7084 	if (data_len_reg->var_off.value % 8)
7085 		return -EINVAL;
7086 	num_args = data_len_reg->var_off.value / 8;
7087 
7088 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7089 	 * and map_direct_value_addr is set.
7090 	 */
7091 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7092 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7093 						  fmt_map_off);
7094 	if (err) {
7095 		verbose(env, "verifier bug\n");
7096 		return -EFAULT;
7097 	}
7098 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7099 
7100 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7101 	 * can focus on validating the format specifiers.
7102 	 */
7103 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7104 	if (err < 0)
7105 		verbose(env, "Invalid format string\n");
7106 
7107 	return err;
7108 }
7109 
7110 static int check_get_func_ip(struct bpf_verifier_env *env)
7111 {
7112 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7113 	int func_id = BPF_FUNC_get_func_ip;
7114 
7115 	if (type == BPF_PROG_TYPE_TRACING) {
7116 		if (!bpf_prog_has_trampoline(env->prog)) {
7117 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7118 				func_id_name(func_id), func_id);
7119 			return -ENOTSUPP;
7120 		}
7121 		return 0;
7122 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7123 		return 0;
7124 	}
7125 
7126 	verbose(env, "func %s#%d not supported for program type %d\n",
7127 		func_id_name(func_id), func_id, type);
7128 	return -ENOTSUPP;
7129 }
7130 
7131 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7132 {
7133 	return &env->insn_aux_data[env->insn_idx];
7134 }
7135 
7136 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7137 {
7138 	struct bpf_reg_state *regs = cur_regs(env);
7139 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7140 	bool reg_is_null = register_is_null(reg);
7141 
7142 	if (reg_is_null)
7143 		mark_chain_precision(env, BPF_REG_4);
7144 
7145 	return reg_is_null;
7146 }
7147 
7148 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7149 {
7150 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7151 
7152 	if (!state->initialized) {
7153 		state->initialized = 1;
7154 		state->fit_for_inline = loop_flag_is_zero(env);
7155 		state->callback_subprogno = subprogno;
7156 		return;
7157 	}
7158 
7159 	if (!state->fit_for_inline)
7160 		return;
7161 
7162 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7163 				 state->callback_subprogno == subprogno);
7164 }
7165 
7166 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7167 			     int *insn_idx_p)
7168 {
7169 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7170 	const struct bpf_func_proto *fn = NULL;
7171 	enum bpf_return_type ret_type;
7172 	enum bpf_type_flag ret_flag;
7173 	struct bpf_reg_state *regs;
7174 	struct bpf_call_arg_meta meta;
7175 	int insn_idx = *insn_idx_p;
7176 	bool changes_data;
7177 	int i, err, func_id;
7178 
7179 	/* find function prototype */
7180 	func_id = insn->imm;
7181 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7182 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7183 			func_id);
7184 		return -EINVAL;
7185 	}
7186 
7187 	if (env->ops->get_func_proto)
7188 		fn = env->ops->get_func_proto(func_id, env->prog);
7189 	if (!fn) {
7190 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7191 			func_id);
7192 		return -EINVAL;
7193 	}
7194 
7195 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7196 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7197 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7198 		return -EINVAL;
7199 	}
7200 
7201 	if (fn->allowed && !fn->allowed(env->prog)) {
7202 		verbose(env, "helper call is not allowed in probe\n");
7203 		return -EINVAL;
7204 	}
7205 
7206 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7207 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7208 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7209 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7210 			func_id_name(func_id), func_id);
7211 		return -EINVAL;
7212 	}
7213 
7214 	memset(&meta, 0, sizeof(meta));
7215 	meta.pkt_access = fn->pkt_access;
7216 
7217 	err = check_func_proto(fn, func_id);
7218 	if (err) {
7219 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7220 			func_id_name(func_id), func_id);
7221 		return err;
7222 	}
7223 
7224 	meta.func_id = func_id;
7225 	/* check args */
7226 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7227 		err = check_func_arg(env, i, &meta, fn);
7228 		if (err)
7229 			return err;
7230 	}
7231 
7232 	err = record_func_map(env, &meta, func_id, insn_idx);
7233 	if (err)
7234 		return err;
7235 
7236 	err = record_func_key(env, &meta, func_id, insn_idx);
7237 	if (err)
7238 		return err;
7239 
7240 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7241 	 * is inferred from register state.
7242 	 */
7243 	for (i = 0; i < meta.access_size; i++) {
7244 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7245 				       BPF_WRITE, -1, false);
7246 		if (err)
7247 			return err;
7248 	}
7249 
7250 	regs = cur_regs(env);
7251 
7252 	if (meta.uninit_dynptr_regno) {
7253 		/* we write BPF_DW bits (8 bytes) at a time */
7254 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7255 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7256 					       i, BPF_DW, BPF_WRITE, -1, false);
7257 			if (err)
7258 				return err;
7259 		}
7260 
7261 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7262 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7263 					      insn_idx);
7264 		if (err)
7265 			return err;
7266 	}
7267 
7268 	if (meta.release_regno) {
7269 		err = -EINVAL;
7270 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7271 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7272 		else if (meta.ref_obj_id)
7273 			err = release_reference(env, meta.ref_obj_id);
7274 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7275 		 * released is NULL, which must be > R0.
7276 		 */
7277 		else if (register_is_null(&regs[meta.release_regno]))
7278 			err = 0;
7279 		if (err) {
7280 			verbose(env, "func %s#%d reference has not been acquired before\n",
7281 				func_id_name(func_id), func_id);
7282 			return err;
7283 		}
7284 	}
7285 
7286 	switch (func_id) {
7287 	case BPF_FUNC_tail_call:
7288 		err = check_reference_leak(env);
7289 		if (err) {
7290 			verbose(env, "tail_call would lead to reference leak\n");
7291 			return err;
7292 		}
7293 		break;
7294 	case BPF_FUNC_get_local_storage:
7295 		/* check that flags argument in get_local_storage(map, flags) is 0,
7296 		 * this is required because get_local_storage() can't return an error.
7297 		 */
7298 		if (!register_is_null(&regs[BPF_REG_2])) {
7299 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7300 			return -EINVAL;
7301 		}
7302 		break;
7303 	case BPF_FUNC_for_each_map_elem:
7304 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7305 					set_map_elem_callback_state);
7306 		break;
7307 	case BPF_FUNC_timer_set_callback:
7308 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7309 					set_timer_callback_state);
7310 		break;
7311 	case BPF_FUNC_find_vma:
7312 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7313 					set_find_vma_callback_state);
7314 		break;
7315 	case BPF_FUNC_snprintf:
7316 		err = check_bpf_snprintf_call(env, regs);
7317 		break;
7318 	case BPF_FUNC_loop:
7319 		update_loop_inline_state(env, meta.subprogno);
7320 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7321 					set_loop_callback_state);
7322 		break;
7323 	case BPF_FUNC_dynptr_from_mem:
7324 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7325 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7326 				reg_type_str(env, regs[BPF_REG_1].type));
7327 			return -EACCES;
7328 		}
7329 		break;
7330 	case BPF_FUNC_set_retval:
7331 		if (prog_type == BPF_PROG_TYPE_LSM &&
7332 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7333 			if (!env->prog->aux->attach_func_proto->type) {
7334 				/* Make sure programs that attach to void
7335 				 * hooks don't try to modify return value.
7336 				 */
7337 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7338 				return -EINVAL;
7339 			}
7340 		}
7341 		break;
7342 	case BPF_FUNC_dynptr_data:
7343 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7344 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7345 				if (meta.ref_obj_id) {
7346 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7347 					return -EFAULT;
7348 				}
7349 				/* Find the id of the dynptr we're tracking the reference of */
7350 				meta.ref_obj_id = stack_slot_get_id(env, &regs[BPF_REG_1 + i]);
7351 				break;
7352 			}
7353 		}
7354 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7355 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7356 			return -EFAULT;
7357 		}
7358 		break;
7359 	}
7360 
7361 	if (err)
7362 		return err;
7363 
7364 	/* reset caller saved regs */
7365 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7366 		mark_reg_not_init(env, regs, caller_saved[i]);
7367 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7368 	}
7369 
7370 	/* helper call returns 64-bit value. */
7371 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7372 
7373 	/* update return register (already marked as written above) */
7374 	ret_type = fn->ret_type;
7375 	ret_flag = type_flag(ret_type);
7376 
7377 	switch (base_type(ret_type)) {
7378 	case RET_INTEGER:
7379 		/* sets type to SCALAR_VALUE */
7380 		mark_reg_unknown(env, regs, BPF_REG_0);
7381 		break;
7382 	case RET_VOID:
7383 		regs[BPF_REG_0].type = NOT_INIT;
7384 		break;
7385 	case RET_PTR_TO_MAP_VALUE:
7386 		/* There is no offset yet applied, variable or fixed */
7387 		mark_reg_known_zero(env, regs, BPF_REG_0);
7388 		/* remember map_ptr, so that check_map_access()
7389 		 * can check 'value_size' boundary of memory access
7390 		 * to map element returned from bpf_map_lookup_elem()
7391 		 */
7392 		if (meta.map_ptr == NULL) {
7393 			verbose(env,
7394 				"kernel subsystem misconfigured verifier\n");
7395 			return -EINVAL;
7396 		}
7397 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7398 		regs[BPF_REG_0].map_uid = meta.map_uid;
7399 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7400 		if (!type_may_be_null(ret_type) &&
7401 		    map_value_has_spin_lock(meta.map_ptr)) {
7402 			regs[BPF_REG_0].id = ++env->id_gen;
7403 		}
7404 		break;
7405 	case RET_PTR_TO_SOCKET:
7406 		mark_reg_known_zero(env, regs, BPF_REG_0);
7407 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7408 		break;
7409 	case RET_PTR_TO_SOCK_COMMON:
7410 		mark_reg_known_zero(env, regs, BPF_REG_0);
7411 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7412 		break;
7413 	case RET_PTR_TO_TCP_SOCK:
7414 		mark_reg_known_zero(env, regs, BPF_REG_0);
7415 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7416 		break;
7417 	case RET_PTR_TO_ALLOC_MEM:
7418 		mark_reg_known_zero(env, regs, BPF_REG_0);
7419 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7420 		regs[BPF_REG_0].mem_size = meta.mem_size;
7421 		break;
7422 	case RET_PTR_TO_MEM_OR_BTF_ID:
7423 	{
7424 		const struct btf_type *t;
7425 
7426 		mark_reg_known_zero(env, regs, BPF_REG_0);
7427 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7428 		if (!btf_type_is_struct(t)) {
7429 			u32 tsize;
7430 			const struct btf_type *ret;
7431 			const char *tname;
7432 
7433 			/* resolve the type size of ksym. */
7434 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7435 			if (IS_ERR(ret)) {
7436 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7437 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7438 					tname, PTR_ERR(ret));
7439 				return -EINVAL;
7440 			}
7441 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7442 			regs[BPF_REG_0].mem_size = tsize;
7443 		} else {
7444 			/* MEM_RDONLY may be carried from ret_flag, but it
7445 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7446 			 * it will confuse the check of PTR_TO_BTF_ID in
7447 			 * check_mem_access().
7448 			 */
7449 			ret_flag &= ~MEM_RDONLY;
7450 
7451 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7452 			regs[BPF_REG_0].btf = meta.ret_btf;
7453 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7454 		}
7455 		break;
7456 	}
7457 	case RET_PTR_TO_BTF_ID:
7458 	{
7459 		struct btf *ret_btf;
7460 		int ret_btf_id;
7461 
7462 		mark_reg_known_zero(env, regs, BPF_REG_0);
7463 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7464 		if (func_id == BPF_FUNC_kptr_xchg) {
7465 			ret_btf = meta.kptr_off_desc->kptr.btf;
7466 			ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7467 		} else {
7468 			ret_btf = btf_vmlinux;
7469 			ret_btf_id = *fn->ret_btf_id;
7470 		}
7471 		if (ret_btf_id == 0) {
7472 			verbose(env, "invalid return type %u of func %s#%d\n",
7473 				base_type(ret_type), func_id_name(func_id),
7474 				func_id);
7475 			return -EINVAL;
7476 		}
7477 		regs[BPF_REG_0].btf = ret_btf;
7478 		regs[BPF_REG_0].btf_id = ret_btf_id;
7479 		break;
7480 	}
7481 	default:
7482 		verbose(env, "unknown return type %u of func %s#%d\n",
7483 			base_type(ret_type), func_id_name(func_id), func_id);
7484 		return -EINVAL;
7485 	}
7486 
7487 	if (type_may_be_null(regs[BPF_REG_0].type))
7488 		regs[BPF_REG_0].id = ++env->id_gen;
7489 
7490 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7491 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7492 			func_id_name(func_id), func_id);
7493 		return -EFAULT;
7494 	}
7495 
7496 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7497 		/* For release_reference() */
7498 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7499 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7500 		int id = acquire_reference_state(env, insn_idx);
7501 
7502 		if (id < 0)
7503 			return id;
7504 		/* For mark_ptr_or_null_reg() */
7505 		regs[BPF_REG_0].id = id;
7506 		/* For release_reference() */
7507 		regs[BPF_REG_0].ref_obj_id = id;
7508 	}
7509 
7510 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7511 
7512 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7513 	if (err)
7514 		return err;
7515 
7516 	if ((func_id == BPF_FUNC_get_stack ||
7517 	     func_id == BPF_FUNC_get_task_stack) &&
7518 	    !env->prog->has_callchain_buf) {
7519 		const char *err_str;
7520 
7521 #ifdef CONFIG_PERF_EVENTS
7522 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7523 		err_str = "cannot get callchain buffer for func %s#%d\n";
7524 #else
7525 		err = -ENOTSUPP;
7526 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7527 #endif
7528 		if (err) {
7529 			verbose(env, err_str, func_id_name(func_id), func_id);
7530 			return err;
7531 		}
7532 
7533 		env->prog->has_callchain_buf = true;
7534 	}
7535 
7536 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7537 		env->prog->call_get_stack = true;
7538 
7539 	if (func_id == BPF_FUNC_get_func_ip) {
7540 		if (check_get_func_ip(env))
7541 			return -ENOTSUPP;
7542 		env->prog->call_get_func_ip = true;
7543 	}
7544 
7545 	if (changes_data)
7546 		clear_all_pkt_pointers(env);
7547 	return 0;
7548 }
7549 
7550 /* mark_btf_func_reg_size() is used when the reg size is determined by
7551  * the BTF func_proto's return value size and argument.
7552  */
7553 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7554 				   size_t reg_size)
7555 {
7556 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7557 
7558 	if (regno == BPF_REG_0) {
7559 		/* Function return value */
7560 		reg->live |= REG_LIVE_WRITTEN;
7561 		reg->subreg_def = reg_size == sizeof(u64) ?
7562 			DEF_NOT_SUBREG : env->insn_idx + 1;
7563 	} else {
7564 		/* Function argument */
7565 		if (reg_size == sizeof(u64)) {
7566 			mark_insn_zext(env, reg);
7567 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7568 		} else {
7569 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7570 		}
7571 	}
7572 }
7573 
7574 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7575 			    int *insn_idx_p)
7576 {
7577 	const struct btf_type *t, *func, *func_proto, *ptr_type;
7578 	struct bpf_reg_state *regs = cur_regs(env);
7579 	const char *func_name, *ptr_type_name;
7580 	u32 i, nargs, func_id, ptr_type_id;
7581 	int err, insn_idx = *insn_idx_p;
7582 	const struct btf_param *args;
7583 	struct btf *desc_btf;
7584 	u32 *kfunc_flags;
7585 	bool acq;
7586 
7587 	/* skip for now, but return error when we find this in fixup_kfunc_call */
7588 	if (!insn->imm)
7589 		return 0;
7590 
7591 	desc_btf = find_kfunc_desc_btf(env, insn->off);
7592 	if (IS_ERR(desc_btf))
7593 		return PTR_ERR(desc_btf);
7594 
7595 	func_id = insn->imm;
7596 	func = btf_type_by_id(desc_btf, func_id);
7597 	func_name = btf_name_by_offset(desc_btf, func->name_off);
7598 	func_proto = btf_type_by_id(desc_btf, func->type);
7599 
7600 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7601 	if (!kfunc_flags) {
7602 		verbose(env, "calling kernel function %s is not allowed\n",
7603 			func_name);
7604 		return -EACCES;
7605 	}
7606 	if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7607 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7608 		return -EACCES;
7609 	}
7610 
7611 	acq = *kfunc_flags & KF_ACQUIRE;
7612 
7613 	/* Check the arguments */
7614 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, *kfunc_flags);
7615 	if (err < 0)
7616 		return err;
7617 	/* In case of release function, we get register number of refcounted
7618 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7619 	 */
7620 	if (err) {
7621 		err = release_reference(env, regs[err].ref_obj_id);
7622 		if (err) {
7623 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7624 				func_name, func_id);
7625 			return err;
7626 		}
7627 	}
7628 
7629 	for (i = 0; i < CALLER_SAVED_REGS; i++)
7630 		mark_reg_not_init(env, regs, caller_saved[i]);
7631 
7632 	/* Check return type */
7633 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7634 
7635 	if (acq && !btf_type_is_ptr(t)) {
7636 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7637 		return -EINVAL;
7638 	}
7639 
7640 	if (btf_type_is_scalar(t)) {
7641 		mark_reg_unknown(env, regs, BPF_REG_0);
7642 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7643 	} else if (btf_type_is_ptr(t)) {
7644 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7645 						   &ptr_type_id);
7646 		if (!btf_type_is_struct(ptr_type)) {
7647 			ptr_type_name = btf_name_by_offset(desc_btf,
7648 							   ptr_type->name_off);
7649 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7650 				func_name, btf_type_str(ptr_type),
7651 				ptr_type_name);
7652 			return -EINVAL;
7653 		}
7654 		mark_reg_known_zero(env, regs, BPF_REG_0);
7655 		regs[BPF_REG_0].btf = desc_btf;
7656 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7657 		regs[BPF_REG_0].btf_id = ptr_type_id;
7658 		if (*kfunc_flags & KF_RET_NULL) {
7659 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7660 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7661 			regs[BPF_REG_0].id = ++env->id_gen;
7662 		}
7663 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7664 		if (acq) {
7665 			int id = acquire_reference_state(env, insn_idx);
7666 
7667 			if (id < 0)
7668 				return id;
7669 			regs[BPF_REG_0].id = id;
7670 			regs[BPF_REG_0].ref_obj_id = id;
7671 		}
7672 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7673 
7674 	nargs = btf_type_vlen(func_proto);
7675 	args = (const struct btf_param *)(func_proto + 1);
7676 	for (i = 0; i < nargs; i++) {
7677 		u32 regno = i + 1;
7678 
7679 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7680 		if (btf_type_is_ptr(t))
7681 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7682 		else
7683 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7684 			mark_btf_func_reg_size(env, regno, t->size);
7685 	}
7686 
7687 	return 0;
7688 }
7689 
7690 static bool signed_add_overflows(s64 a, s64 b)
7691 {
7692 	/* Do the add in u64, where overflow is well-defined */
7693 	s64 res = (s64)((u64)a + (u64)b);
7694 
7695 	if (b < 0)
7696 		return res > a;
7697 	return res < a;
7698 }
7699 
7700 static bool signed_add32_overflows(s32 a, s32 b)
7701 {
7702 	/* Do the add in u32, where overflow is well-defined */
7703 	s32 res = (s32)((u32)a + (u32)b);
7704 
7705 	if (b < 0)
7706 		return res > a;
7707 	return res < a;
7708 }
7709 
7710 static bool signed_sub_overflows(s64 a, s64 b)
7711 {
7712 	/* Do the sub in u64, where overflow is well-defined */
7713 	s64 res = (s64)((u64)a - (u64)b);
7714 
7715 	if (b < 0)
7716 		return res < a;
7717 	return res > a;
7718 }
7719 
7720 static bool signed_sub32_overflows(s32 a, s32 b)
7721 {
7722 	/* Do the sub in u32, where overflow is well-defined */
7723 	s32 res = (s32)((u32)a - (u32)b);
7724 
7725 	if (b < 0)
7726 		return res < a;
7727 	return res > a;
7728 }
7729 
7730 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7731 				  const struct bpf_reg_state *reg,
7732 				  enum bpf_reg_type type)
7733 {
7734 	bool known = tnum_is_const(reg->var_off);
7735 	s64 val = reg->var_off.value;
7736 	s64 smin = reg->smin_value;
7737 
7738 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7739 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7740 			reg_type_str(env, type), val);
7741 		return false;
7742 	}
7743 
7744 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7745 		verbose(env, "%s pointer offset %d is not allowed\n",
7746 			reg_type_str(env, type), reg->off);
7747 		return false;
7748 	}
7749 
7750 	if (smin == S64_MIN) {
7751 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7752 			reg_type_str(env, type));
7753 		return false;
7754 	}
7755 
7756 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7757 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
7758 			smin, reg_type_str(env, type));
7759 		return false;
7760 	}
7761 
7762 	return true;
7763 }
7764 
7765 enum {
7766 	REASON_BOUNDS	= -1,
7767 	REASON_TYPE	= -2,
7768 	REASON_PATHS	= -3,
7769 	REASON_LIMIT	= -4,
7770 	REASON_STACK	= -5,
7771 };
7772 
7773 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7774 			      u32 *alu_limit, bool mask_to_left)
7775 {
7776 	u32 max = 0, ptr_limit = 0;
7777 
7778 	switch (ptr_reg->type) {
7779 	case PTR_TO_STACK:
7780 		/* Offset 0 is out-of-bounds, but acceptable start for the
7781 		 * left direction, see BPF_REG_FP. Also, unknown scalar
7782 		 * offset where we would need to deal with min/max bounds is
7783 		 * currently prohibited for unprivileged.
7784 		 */
7785 		max = MAX_BPF_STACK + mask_to_left;
7786 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7787 		break;
7788 	case PTR_TO_MAP_VALUE:
7789 		max = ptr_reg->map_ptr->value_size;
7790 		ptr_limit = (mask_to_left ?
7791 			     ptr_reg->smin_value :
7792 			     ptr_reg->umax_value) + ptr_reg->off;
7793 		break;
7794 	default:
7795 		return REASON_TYPE;
7796 	}
7797 
7798 	if (ptr_limit >= max)
7799 		return REASON_LIMIT;
7800 	*alu_limit = ptr_limit;
7801 	return 0;
7802 }
7803 
7804 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7805 				    const struct bpf_insn *insn)
7806 {
7807 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7808 }
7809 
7810 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7811 				       u32 alu_state, u32 alu_limit)
7812 {
7813 	/* If we arrived here from different branches with different
7814 	 * state or limits to sanitize, then this won't work.
7815 	 */
7816 	if (aux->alu_state &&
7817 	    (aux->alu_state != alu_state ||
7818 	     aux->alu_limit != alu_limit))
7819 		return REASON_PATHS;
7820 
7821 	/* Corresponding fixup done in do_misc_fixups(). */
7822 	aux->alu_state = alu_state;
7823 	aux->alu_limit = alu_limit;
7824 	return 0;
7825 }
7826 
7827 static int sanitize_val_alu(struct bpf_verifier_env *env,
7828 			    struct bpf_insn *insn)
7829 {
7830 	struct bpf_insn_aux_data *aux = cur_aux(env);
7831 
7832 	if (can_skip_alu_sanitation(env, insn))
7833 		return 0;
7834 
7835 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7836 }
7837 
7838 static bool sanitize_needed(u8 opcode)
7839 {
7840 	return opcode == BPF_ADD || opcode == BPF_SUB;
7841 }
7842 
7843 struct bpf_sanitize_info {
7844 	struct bpf_insn_aux_data aux;
7845 	bool mask_to_left;
7846 };
7847 
7848 static struct bpf_verifier_state *
7849 sanitize_speculative_path(struct bpf_verifier_env *env,
7850 			  const struct bpf_insn *insn,
7851 			  u32 next_idx, u32 curr_idx)
7852 {
7853 	struct bpf_verifier_state *branch;
7854 	struct bpf_reg_state *regs;
7855 
7856 	branch = push_stack(env, next_idx, curr_idx, true);
7857 	if (branch && insn) {
7858 		regs = branch->frame[branch->curframe]->regs;
7859 		if (BPF_SRC(insn->code) == BPF_K) {
7860 			mark_reg_unknown(env, regs, insn->dst_reg);
7861 		} else if (BPF_SRC(insn->code) == BPF_X) {
7862 			mark_reg_unknown(env, regs, insn->dst_reg);
7863 			mark_reg_unknown(env, regs, insn->src_reg);
7864 		}
7865 	}
7866 	return branch;
7867 }
7868 
7869 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7870 			    struct bpf_insn *insn,
7871 			    const struct bpf_reg_state *ptr_reg,
7872 			    const struct bpf_reg_state *off_reg,
7873 			    struct bpf_reg_state *dst_reg,
7874 			    struct bpf_sanitize_info *info,
7875 			    const bool commit_window)
7876 {
7877 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7878 	struct bpf_verifier_state *vstate = env->cur_state;
7879 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7880 	bool off_is_neg = off_reg->smin_value < 0;
7881 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7882 	u8 opcode = BPF_OP(insn->code);
7883 	u32 alu_state, alu_limit;
7884 	struct bpf_reg_state tmp;
7885 	bool ret;
7886 	int err;
7887 
7888 	if (can_skip_alu_sanitation(env, insn))
7889 		return 0;
7890 
7891 	/* We already marked aux for masking from non-speculative
7892 	 * paths, thus we got here in the first place. We only care
7893 	 * to explore bad access from here.
7894 	 */
7895 	if (vstate->speculative)
7896 		goto do_sim;
7897 
7898 	if (!commit_window) {
7899 		if (!tnum_is_const(off_reg->var_off) &&
7900 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7901 			return REASON_BOUNDS;
7902 
7903 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7904 				     (opcode == BPF_SUB && !off_is_neg);
7905 	}
7906 
7907 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7908 	if (err < 0)
7909 		return err;
7910 
7911 	if (commit_window) {
7912 		/* In commit phase we narrow the masking window based on
7913 		 * the observed pointer move after the simulated operation.
7914 		 */
7915 		alu_state = info->aux.alu_state;
7916 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7917 	} else {
7918 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7919 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7920 		alu_state |= ptr_is_dst_reg ?
7921 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7922 
7923 		/* Limit pruning on unknown scalars to enable deep search for
7924 		 * potential masking differences from other program paths.
7925 		 */
7926 		if (!off_is_imm)
7927 			env->explore_alu_limits = true;
7928 	}
7929 
7930 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7931 	if (err < 0)
7932 		return err;
7933 do_sim:
7934 	/* If we're in commit phase, we're done here given we already
7935 	 * pushed the truncated dst_reg into the speculative verification
7936 	 * stack.
7937 	 *
7938 	 * Also, when register is a known constant, we rewrite register-based
7939 	 * operation to immediate-based, and thus do not need masking (and as
7940 	 * a consequence, do not need to simulate the zero-truncation either).
7941 	 */
7942 	if (commit_window || off_is_imm)
7943 		return 0;
7944 
7945 	/* Simulate and find potential out-of-bounds access under
7946 	 * speculative execution from truncation as a result of
7947 	 * masking when off was not within expected range. If off
7948 	 * sits in dst, then we temporarily need to move ptr there
7949 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7950 	 * for cases where we use K-based arithmetic in one direction
7951 	 * and truncated reg-based in the other in order to explore
7952 	 * bad access.
7953 	 */
7954 	if (!ptr_is_dst_reg) {
7955 		tmp = *dst_reg;
7956 		*dst_reg = *ptr_reg;
7957 	}
7958 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7959 					env->insn_idx);
7960 	if (!ptr_is_dst_reg && ret)
7961 		*dst_reg = tmp;
7962 	return !ret ? REASON_STACK : 0;
7963 }
7964 
7965 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7966 {
7967 	struct bpf_verifier_state *vstate = env->cur_state;
7968 
7969 	/* If we simulate paths under speculation, we don't update the
7970 	 * insn as 'seen' such that when we verify unreachable paths in
7971 	 * the non-speculative domain, sanitize_dead_code() can still
7972 	 * rewrite/sanitize them.
7973 	 */
7974 	if (!vstate->speculative)
7975 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7976 }
7977 
7978 static int sanitize_err(struct bpf_verifier_env *env,
7979 			const struct bpf_insn *insn, int reason,
7980 			const struct bpf_reg_state *off_reg,
7981 			const struct bpf_reg_state *dst_reg)
7982 {
7983 	static const char *err = "pointer arithmetic with it prohibited for !root";
7984 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7985 	u32 dst = insn->dst_reg, src = insn->src_reg;
7986 
7987 	switch (reason) {
7988 	case REASON_BOUNDS:
7989 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7990 			off_reg == dst_reg ? dst : src, err);
7991 		break;
7992 	case REASON_TYPE:
7993 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7994 			off_reg == dst_reg ? src : dst, err);
7995 		break;
7996 	case REASON_PATHS:
7997 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7998 			dst, op, err);
7999 		break;
8000 	case REASON_LIMIT:
8001 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8002 			dst, op, err);
8003 		break;
8004 	case REASON_STACK:
8005 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8006 			dst, err);
8007 		break;
8008 	default:
8009 		verbose(env, "verifier internal error: unknown reason (%d)\n",
8010 			reason);
8011 		break;
8012 	}
8013 
8014 	return -EACCES;
8015 }
8016 
8017 /* check that stack access falls within stack limits and that 'reg' doesn't
8018  * have a variable offset.
8019  *
8020  * Variable offset is prohibited for unprivileged mode for simplicity since it
8021  * requires corresponding support in Spectre masking for stack ALU.  See also
8022  * retrieve_ptr_limit().
8023  *
8024  *
8025  * 'off' includes 'reg->off'.
8026  */
8027 static int check_stack_access_for_ptr_arithmetic(
8028 				struct bpf_verifier_env *env,
8029 				int regno,
8030 				const struct bpf_reg_state *reg,
8031 				int off)
8032 {
8033 	if (!tnum_is_const(reg->var_off)) {
8034 		char tn_buf[48];
8035 
8036 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8037 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8038 			regno, tn_buf, off);
8039 		return -EACCES;
8040 	}
8041 
8042 	if (off >= 0 || off < -MAX_BPF_STACK) {
8043 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
8044 			"prohibited for !root; off=%d\n", regno, off);
8045 		return -EACCES;
8046 	}
8047 
8048 	return 0;
8049 }
8050 
8051 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8052 				 const struct bpf_insn *insn,
8053 				 const struct bpf_reg_state *dst_reg)
8054 {
8055 	u32 dst = insn->dst_reg;
8056 
8057 	/* For unprivileged we require that resulting offset must be in bounds
8058 	 * in order to be able to sanitize access later on.
8059 	 */
8060 	if (env->bypass_spec_v1)
8061 		return 0;
8062 
8063 	switch (dst_reg->type) {
8064 	case PTR_TO_STACK:
8065 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8066 					dst_reg->off + dst_reg->var_off.value))
8067 			return -EACCES;
8068 		break;
8069 	case PTR_TO_MAP_VALUE:
8070 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8071 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8072 				"prohibited for !root\n", dst);
8073 			return -EACCES;
8074 		}
8075 		break;
8076 	default:
8077 		break;
8078 	}
8079 
8080 	return 0;
8081 }
8082 
8083 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8084  * Caller should also handle BPF_MOV case separately.
8085  * If we return -EACCES, caller may want to try again treating pointer as a
8086  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8087  */
8088 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8089 				   struct bpf_insn *insn,
8090 				   const struct bpf_reg_state *ptr_reg,
8091 				   const struct bpf_reg_state *off_reg)
8092 {
8093 	struct bpf_verifier_state *vstate = env->cur_state;
8094 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8095 	struct bpf_reg_state *regs = state->regs, *dst_reg;
8096 	bool known = tnum_is_const(off_reg->var_off);
8097 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8098 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8099 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8100 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8101 	struct bpf_sanitize_info info = {};
8102 	u8 opcode = BPF_OP(insn->code);
8103 	u32 dst = insn->dst_reg;
8104 	int ret;
8105 
8106 	dst_reg = &regs[dst];
8107 
8108 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8109 	    smin_val > smax_val || umin_val > umax_val) {
8110 		/* Taint dst register if offset had invalid bounds derived from
8111 		 * e.g. dead branches.
8112 		 */
8113 		__mark_reg_unknown(env, dst_reg);
8114 		return 0;
8115 	}
8116 
8117 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
8118 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
8119 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8120 			__mark_reg_unknown(env, dst_reg);
8121 			return 0;
8122 		}
8123 
8124 		verbose(env,
8125 			"R%d 32-bit pointer arithmetic prohibited\n",
8126 			dst);
8127 		return -EACCES;
8128 	}
8129 
8130 	if (ptr_reg->type & PTR_MAYBE_NULL) {
8131 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8132 			dst, reg_type_str(env, ptr_reg->type));
8133 		return -EACCES;
8134 	}
8135 
8136 	switch (base_type(ptr_reg->type)) {
8137 	case CONST_PTR_TO_MAP:
8138 		/* smin_val represents the known value */
8139 		if (known && smin_val == 0 && opcode == BPF_ADD)
8140 			break;
8141 		fallthrough;
8142 	case PTR_TO_PACKET_END:
8143 	case PTR_TO_SOCKET:
8144 	case PTR_TO_SOCK_COMMON:
8145 	case PTR_TO_TCP_SOCK:
8146 	case PTR_TO_XDP_SOCK:
8147 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8148 			dst, reg_type_str(env, ptr_reg->type));
8149 		return -EACCES;
8150 	default:
8151 		break;
8152 	}
8153 
8154 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8155 	 * The id may be overwritten later if we create a new variable offset.
8156 	 */
8157 	dst_reg->type = ptr_reg->type;
8158 	dst_reg->id = ptr_reg->id;
8159 
8160 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8161 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8162 		return -EINVAL;
8163 
8164 	/* pointer types do not carry 32-bit bounds at the moment. */
8165 	__mark_reg32_unbounded(dst_reg);
8166 
8167 	if (sanitize_needed(opcode)) {
8168 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8169 				       &info, false);
8170 		if (ret < 0)
8171 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8172 	}
8173 
8174 	switch (opcode) {
8175 	case BPF_ADD:
8176 		/* We can take a fixed offset as long as it doesn't overflow
8177 		 * the s32 'off' field
8178 		 */
8179 		if (known && (ptr_reg->off + smin_val ==
8180 			      (s64)(s32)(ptr_reg->off + smin_val))) {
8181 			/* pointer += K.  Accumulate it into fixed offset */
8182 			dst_reg->smin_value = smin_ptr;
8183 			dst_reg->smax_value = smax_ptr;
8184 			dst_reg->umin_value = umin_ptr;
8185 			dst_reg->umax_value = umax_ptr;
8186 			dst_reg->var_off = ptr_reg->var_off;
8187 			dst_reg->off = ptr_reg->off + smin_val;
8188 			dst_reg->raw = ptr_reg->raw;
8189 			break;
8190 		}
8191 		/* A new variable offset is created.  Note that off_reg->off
8192 		 * == 0, since it's a scalar.
8193 		 * dst_reg gets the pointer type and since some positive
8194 		 * integer value was added to the pointer, give it a new 'id'
8195 		 * if it's a PTR_TO_PACKET.
8196 		 * this creates a new 'base' pointer, off_reg (variable) gets
8197 		 * added into the variable offset, and we copy the fixed offset
8198 		 * from ptr_reg.
8199 		 */
8200 		if (signed_add_overflows(smin_ptr, smin_val) ||
8201 		    signed_add_overflows(smax_ptr, smax_val)) {
8202 			dst_reg->smin_value = S64_MIN;
8203 			dst_reg->smax_value = S64_MAX;
8204 		} else {
8205 			dst_reg->smin_value = smin_ptr + smin_val;
8206 			dst_reg->smax_value = smax_ptr + smax_val;
8207 		}
8208 		if (umin_ptr + umin_val < umin_ptr ||
8209 		    umax_ptr + umax_val < umax_ptr) {
8210 			dst_reg->umin_value = 0;
8211 			dst_reg->umax_value = U64_MAX;
8212 		} else {
8213 			dst_reg->umin_value = umin_ptr + umin_val;
8214 			dst_reg->umax_value = umax_ptr + umax_val;
8215 		}
8216 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8217 		dst_reg->off = ptr_reg->off;
8218 		dst_reg->raw = ptr_reg->raw;
8219 		if (reg_is_pkt_pointer(ptr_reg)) {
8220 			dst_reg->id = ++env->id_gen;
8221 			/* something was added to pkt_ptr, set range to zero */
8222 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8223 		}
8224 		break;
8225 	case BPF_SUB:
8226 		if (dst_reg == off_reg) {
8227 			/* scalar -= pointer.  Creates an unknown scalar */
8228 			verbose(env, "R%d tried to subtract pointer from scalar\n",
8229 				dst);
8230 			return -EACCES;
8231 		}
8232 		/* We don't allow subtraction from FP, because (according to
8233 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
8234 		 * be able to deal with it.
8235 		 */
8236 		if (ptr_reg->type == PTR_TO_STACK) {
8237 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
8238 				dst);
8239 			return -EACCES;
8240 		}
8241 		if (known && (ptr_reg->off - smin_val ==
8242 			      (s64)(s32)(ptr_reg->off - smin_val))) {
8243 			/* pointer -= K.  Subtract it from fixed offset */
8244 			dst_reg->smin_value = smin_ptr;
8245 			dst_reg->smax_value = smax_ptr;
8246 			dst_reg->umin_value = umin_ptr;
8247 			dst_reg->umax_value = umax_ptr;
8248 			dst_reg->var_off = ptr_reg->var_off;
8249 			dst_reg->id = ptr_reg->id;
8250 			dst_reg->off = ptr_reg->off - smin_val;
8251 			dst_reg->raw = ptr_reg->raw;
8252 			break;
8253 		}
8254 		/* A new variable offset is created.  If the subtrahend is known
8255 		 * nonnegative, then any reg->range we had before is still good.
8256 		 */
8257 		if (signed_sub_overflows(smin_ptr, smax_val) ||
8258 		    signed_sub_overflows(smax_ptr, smin_val)) {
8259 			/* Overflow possible, we know nothing */
8260 			dst_reg->smin_value = S64_MIN;
8261 			dst_reg->smax_value = S64_MAX;
8262 		} else {
8263 			dst_reg->smin_value = smin_ptr - smax_val;
8264 			dst_reg->smax_value = smax_ptr - smin_val;
8265 		}
8266 		if (umin_ptr < umax_val) {
8267 			/* Overflow possible, we know nothing */
8268 			dst_reg->umin_value = 0;
8269 			dst_reg->umax_value = U64_MAX;
8270 		} else {
8271 			/* Cannot overflow (as long as bounds are consistent) */
8272 			dst_reg->umin_value = umin_ptr - umax_val;
8273 			dst_reg->umax_value = umax_ptr - umin_val;
8274 		}
8275 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8276 		dst_reg->off = ptr_reg->off;
8277 		dst_reg->raw = ptr_reg->raw;
8278 		if (reg_is_pkt_pointer(ptr_reg)) {
8279 			dst_reg->id = ++env->id_gen;
8280 			/* something was added to pkt_ptr, set range to zero */
8281 			if (smin_val < 0)
8282 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8283 		}
8284 		break;
8285 	case BPF_AND:
8286 	case BPF_OR:
8287 	case BPF_XOR:
8288 		/* bitwise ops on pointers are troublesome, prohibit. */
8289 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8290 			dst, bpf_alu_string[opcode >> 4]);
8291 		return -EACCES;
8292 	default:
8293 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
8294 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8295 			dst, bpf_alu_string[opcode >> 4]);
8296 		return -EACCES;
8297 	}
8298 
8299 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8300 		return -EINVAL;
8301 	reg_bounds_sync(dst_reg);
8302 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8303 		return -EACCES;
8304 	if (sanitize_needed(opcode)) {
8305 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8306 				       &info, true);
8307 		if (ret < 0)
8308 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8309 	}
8310 
8311 	return 0;
8312 }
8313 
8314 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8315 				 struct bpf_reg_state *src_reg)
8316 {
8317 	s32 smin_val = src_reg->s32_min_value;
8318 	s32 smax_val = src_reg->s32_max_value;
8319 	u32 umin_val = src_reg->u32_min_value;
8320 	u32 umax_val = src_reg->u32_max_value;
8321 
8322 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8323 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8324 		dst_reg->s32_min_value = S32_MIN;
8325 		dst_reg->s32_max_value = S32_MAX;
8326 	} else {
8327 		dst_reg->s32_min_value += smin_val;
8328 		dst_reg->s32_max_value += smax_val;
8329 	}
8330 	if (dst_reg->u32_min_value + umin_val < umin_val ||
8331 	    dst_reg->u32_max_value + umax_val < umax_val) {
8332 		dst_reg->u32_min_value = 0;
8333 		dst_reg->u32_max_value = U32_MAX;
8334 	} else {
8335 		dst_reg->u32_min_value += umin_val;
8336 		dst_reg->u32_max_value += umax_val;
8337 	}
8338 }
8339 
8340 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8341 			       struct bpf_reg_state *src_reg)
8342 {
8343 	s64 smin_val = src_reg->smin_value;
8344 	s64 smax_val = src_reg->smax_value;
8345 	u64 umin_val = src_reg->umin_value;
8346 	u64 umax_val = src_reg->umax_value;
8347 
8348 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8349 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
8350 		dst_reg->smin_value = S64_MIN;
8351 		dst_reg->smax_value = S64_MAX;
8352 	} else {
8353 		dst_reg->smin_value += smin_val;
8354 		dst_reg->smax_value += smax_val;
8355 	}
8356 	if (dst_reg->umin_value + umin_val < umin_val ||
8357 	    dst_reg->umax_value + umax_val < umax_val) {
8358 		dst_reg->umin_value = 0;
8359 		dst_reg->umax_value = U64_MAX;
8360 	} else {
8361 		dst_reg->umin_value += umin_val;
8362 		dst_reg->umax_value += umax_val;
8363 	}
8364 }
8365 
8366 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8367 				 struct bpf_reg_state *src_reg)
8368 {
8369 	s32 smin_val = src_reg->s32_min_value;
8370 	s32 smax_val = src_reg->s32_max_value;
8371 	u32 umin_val = src_reg->u32_min_value;
8372 	u32 umax_val = src_reg->u32_max_value;
8373 
8374 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8375 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8376 		/* Overflow possible, we know nothing */
8377 		dst_reg->s32_min_value = S32_MIN;
8378 		dst_reg->s32_max_value = S32_MAX;
8379 	} else {
8380 		dst_reg->s32_min_value -= smax_val;
8381 		dst_reg->s32_max_value -= smin_val;
8382 	}
8383 	if (dst_reg->u32_min_value < umax_val) {
8384 		/* Overflow possible, we know nothing */
8385 		dst_reg->u32_min_value = 0;
8386 		dst_reg->u32_max_value = U32_MAX;
8387 	} else {
8388 		/* Cannot overflow (as long as bounds are consistent) */
8389 		dst_reg->u32_min_value -= umax_val;
8390 		dst_reg->u32_max_value -= umin_val;
8391 	}
8392 }
8393 
8394 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8395 			       struct bpf_reg_state *src_reg)
8396 {
8397 	s64 smin_val = src_reg->smin_value;
8398 	s64 smax_val = src_reg->smax_value;
8399 	u64 umin_val = src_reg->umin_value;
8400 	u64 umax_val = src_reg->umax_value;
8401 
8402 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8403 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8404 		/* Overflow possible, we know nothing */
8405 		dst_reg->smin_value = S64_MIN;
8406 		dst_reg->smax_value = S64_MAX;
8407 	} else {
8408 		dst_reg->smin_value -= smax_val;
8409 		dst_reg->smax_value -= smin_val;
8410 	}
8411 	if (dst_reg->umin_value < umax_val) {
8412 		/* Overflow possible, we know nothing */
8413 		dst_reg->umin_value = 0;
8414 		dst_reg->umax_value = U64_MAX;
8415 	} else {
8416 		/* Cannot overflow (as long as bounds are consistent) */
8417 		dst_reg->umin_value -= umax_val;
8418 		dst_reg->umax_value -= umin_val;
8419 	}
8420 }
8421 
8422 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8423 				 struct bpf_reg_state *src_reg)
8424 {
8425 	s32 smin_val = src_reg->s32_min_value;
8426 	u32 umin_val = src_reg->u32_min_value;
8427 	u32 umax_val = src_reg->u32_max_value;
8428 
8429 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8430 		/* Ain't nobody got time to multiply that sign */
8431 		__mark_reg32_unbounded(dst_reg);
8432 		return;
8433 	}
8434 	/* Both values are positive, so we can work with unsigned and
8435 	 * copy the result to signed (unless it exceeds S32_MAX).
8436 	 */
8437 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8438 		/* Potential overflow, we know nothing */
8439 		__mark_reg32_unbounded(dst_reg);
8440 		return;
8441 	}
8442 	dst_reg->u32_min_value *= umin_val;
8443 	dst_reg->u32_max_value *= umax_val;
8444 	if (dst_reg->u32_max_value > S32_MAX) {
8445 		/* Overflow possible, we know nothing */
8446 		dst_reg->s32_min_value = S32_MIN;
8447 		dst_reg->s32_max_value = S32_MAX;
8448 	} else {
8449 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8450 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8451 	}
8452 }
8453 
8454 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8455 			       struct bpf_reg_state *src_reg)
8456 {
8457 	s64 smin_val = src_reg->smin_value;
8458 	u64 umin_val = src_reg->umin_value;
8459 	u64 umax_val = src_reg->umax_value;
8460 
8461 	if (smin_val < 0 || dst_reg->smin_value < 0) {
8462 		/* Ain't nobody got time to multiply that sign */
8463 		__mark_reg64_unbounded(dst_reg);
8464 		return;
8465 	}
8466 	/* Both values are positive, so we can work with unsigned and
8467 	 * copy the result to signed (unless it exceeds S64_MAX).
8468 	 */
8469 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8470 		/* Potential overflow, we know nothing */
8471 		__mark_reg64_unbounded(dst_reg);
8472 		return;
8473 	}
8474 	dst_reg->umin_value *= umin_val;
8475 	dst_reg->umax_value *= umax_val;
8476 	if (dst_reg->umax_value > S64_MAX) {
8477 		/* Overflow possible, we know nothing */
8478 		dst_reg->smin_value = S64_MIN;
8479 		dst_reg->smax_value = S64_MAX;
8480 	} else {
8481 		dst_reg->smin_value = dst_reg->umin_value;
8482 		dst_reg->smax_value = dst_reg->umax_value;
8483 	}
8484 }
8485 
8486 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8487 				 struct bpf_reg_state *src_reg)
8488 {
8489 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8490 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8491 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8492 	s32 smin_val = src_reg->s32_min_value;
8493 	u32 umax_val = src_reg->u32_max_value;
8494 
8495 	if (src_known && dst_known) {
8496 		__mark_reg32_known(dst_reg, var32_off.value);
8497 		return;
8498 	}
8499 
8500 	/* We get our minimum from the var_off, since that's inherently
8501 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8502 	 */
8503 	dst_reg->u32_min_value = var32_off.value;
8504 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8505 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8506 		/* Lose signed bounds when ANDing negative numbers,
8507 		 * ain't nobody got time for that.
8508 		 */
8509 		dst_reg->s32_min_value = S32_MIN;
8510 		dst_reg->s32_max_value = S32_MAX;
8511 	} else {
8512 		/* ANDing two positives gives a positive, so safe to
8513 		 * cast result into s64.
8514 		 */
8515 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8516 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8517 	}
8518 }
8519 
8520 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8521 			       struct bpf_reg_state *src_reg)
8522 {
8523 	bool src_known = tnum_is_const(src_reg->var_off);
8524 	bool dst_known = tnum_is_const(dst_reg->var_off);
8525 	s64 smin_val = src_reg->smin_value;
8526 	u64 umax_val = src_reg->umax_value;
8527 
8528 	if (src_known && dst_known) {
8529 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8530 		return;
8531 	}
8532 
8533 	/* We get our minimum from the var_off, since that's inherently
8534 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8535 	 */
8536 	dst_reg->umin_value = dst_reg->var_off.value;
8537 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8538 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8539 		/* Lose signed bounds when ANDing negative numbers,
8540 		 * ain't nobody got time for that.
8541 		 */
8542 		dst_reg->smin_value = S64_MIN;
8543 		dst_reg->smax_value = S64_MAX;
8544 	} else {
8545 		/* ANDing two positives gives a positive, so safe to
8546 		 * cast result into s64.
8547 		 */
8548 		dst_reg->smin_value = dst_reg->umin_value;
8549 		dst_reg->smax_value = dst_reg->umax_value;
8550 	}
8551 	/* We may learn something more from the var_off */
8552 	__update_reg_bounds(dst_reg);
8553 }
8554 
8555 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8556 				struct bpf_reg_state *src_reg)
8557 {
8558 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8559 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8560 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8561 	s32 smin_val = src_reg->s32_min_value;
8562 	u32 umin_val = src_reg->u32_min_value;
8563 
8564 	if (src_known && dst_known) {
8565 		__mark_reg32_known(dst_reg, var32_off.value);
8566 		return;
8567 	}
8568 
8569 	/* We get our maximum from the var_off, and our minimum is the
8570 	 * maximum of the operands' minima
8571 	 */
8572 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8573 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8574 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8575 		/* Lose signed bounds when ORing negative numbers,
8576 		 * ain't nobody got time for that.
8577 		 */
8578 		dst_reg->s32_min_value = S32_MIN;
8579 		dst_reg->s32_max_value = S32_MAX;
8580 	} else {
8581 		/* ORing two positives gives a positive, so safe to
8582 		 * cast result into s64.
8583 		 */
8584 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8585 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8586 	}
8587 }
8588 
8589 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8590 			      struct bpf_reg_state *src_reg)
8591 {
8592 	bool src_known = tnum_is_const(src_reg->var_off);
8593 	bool dst_known = tnum_is_const(dst_reg->var_off);
8594 	s64 smin_val = src_reg->smin_value;
8595 	u64 umin_val = src_reg->umin_value;
8596 
8597 	if (src_known && dst_known) {
8598 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8599 		return;
8600 	}
8601 
8602 	/* We get our maximum from the var_off, and our minimum is the
8603 	 * maximum of the operands' minima
8604 	 */
8605 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8606 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8607 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8608 		/* Lose signed bounds when ORing negative numbers,
8609 		 * ain't nobody got time for that.
8610 		 */
8611 		dst_reg->smin_value = S64_MIN;
8612 		dst_reg->smax_value = S64_MAX;
8613 	} else {
8614 		/* ORing two positives gives a positive, so safe to
8615 		 * cast result into s64.
8616 		 */
8617 		dst_reg->smin_value = dst_reg->umin_value;
8618 		dst_reg->smax_value = dst_reg->umax_value;
8619 	}
8620 	/* We may learn something more from the var_off */
8621 	__update_reg_bounds(dst_reg);
8622 }
8623 
8624 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8625 				 struct bpf_reg_state *src_reg)
8626 {
8627 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8628 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8629 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8630 	s32 smin_val = src_reg->s32_min_value;
8631 
8632 	if (src_known && dst_known) {
8633 		__mark_reg32_known(dst_reg, var32_off.value);
8634 		return;
8635 	}
8636 
8637 	/* We get both minimum and maximum from the var32_off. */
8638 	dst_reg->u32_min_value = var32_off.value;
8639 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8640 
8641 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8642 		/* XORing two positive sign numbers gives a positive,
8643 		 * so safe to cast u32 result into s32.
8644 		 */
8645 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8646 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8647 	} else {
8648 		dst_reg->s32_min_value = S32_MIN;
8649 		dst_reg->s32_max_value = S32_MAX;
8650 	}
8651 }
8652 
8653 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8654 			       struct bpf_reg_state *src_reg)
8655 {
8656 	bool src_known = tnum_is_const(src_reg->var_off);
8657 	bool dst_known = tnum_is_const(dst_reg->var_off);
8658 	s64 smin_val = src_reg->smin_value;
8659 
8660 	if (src_known && dst_known) {
8661 		/* dst_reg->var_off.value has been updated earlier */
8662 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8663 		return;
8664 	}
8665 
8666 	/* We get both minimum and maximum from the var_off. */
8667 	dst_reg->umin_value = dst_reg->var_off.value;
8668 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8669 
8670 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8671 		/* XORing two positive sign numbers gives a positive,
8672 		 * so safe to cast u64 result into s64.
8673 		 */
8674 		dst_reg->smin_value = dst_reg->umin_value;
8675 		dst_reg->smax_value = dst_reg->umax_value;
8676 	} else {
8677 		dst_reg->smin_value = S64_MIN;
8678 		dst_reg->smax_value = S64_MAX;
8679 	}
8680 
8681 	__update_reg_bounds(dst_reg);
8682 }
8683 
8684 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8685 				   u64 umin_val, u64 umax_val)
8686 {
8687 	/* We lose all sign bit information (except what we can pick
8688 	 * up from var_off)
8689 	 */
8690 	dst_reg->s32_min_value = S32_MIN;
8691 	dst_reg->s32_max_value = S32_MAX;
8692 	/* If we might shift our top bit out, then we know nothing */
8693 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8694 		dst_reg->u32_min_value = 0;
8695 		dst_reg->u32_max_value = U32_MAX;
8696 	} else {
8697 		dst_reg->u32_min_value <<= umin_val;
8698 		dst_reg->u32_max_value <<= umax_val;
8699 	}
8700 }
8701 
8702 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8703 				 struct bpf_reg_state *src_reg)
8704 {
8705 	u32 umax_val = src_reg->u32_max_value;
8706 	u32 umin_val = src_reg->u32_min_value;
8707 	/* u32 alu operation will zext upper bits */
8708 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8709 
8710 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8711 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8712 	/* Not required but being careful mark reg64 bounds as unknown so
8713 	 * that we are forced to pick them up from tnum and zext later and
8714 	 * if some path skips this step we are still safe.
8715 	 */
8716 	__mark_reg64_unbounded(dst_reg);
8717 	__update_reg32_bounds(dst_reg);
8718 }
8719 
8720 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8721 				   u64 umin_val, u64 umax_val)
8722 {
8723 	/* Special case <<32 because it is a common compiler pattern to sign
8724 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8725 	 * positive we know this shift will also be positive so we can track
8726 	 * bounds correctly. Otherwise we lose all sign bit information except
8727 	 * what we can pick up from var_off. Perhaps we can generalize this
8728 	 * later to shifts of any length.
8729 	 */
8730 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8731 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8732 	else
8733 		dst_reg->smax_value = S64_MAX;
8734 
8735 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8736 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8737 	else
8738 		dst_reg->smin_value = S64_MIN;
8739 
8740 	/* If we might shift our top bit out, then we know nothing */
8741 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8742 		dst_reg->umin_value = 0;
8743 		dst_reg->umax_value = U64_MAX;
8744 	} else {
8745 		dst_reg->umin_value <<= umin_val;
8746 		dst_reg->umax_value <<= umax_val;
8747 	}
8748 }
8749 
8750 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8751 			       struct bpf_reg_state *src_reg)
8752 {
8753 	u64 umax_val = src_reg->umax_value;
8754 	u64 umin_val = src_reg->umin_value;
8755 
8756 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
8757 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8758 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8759 
8760 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8761 	/* We may learn something more from the var_off */
8762 	__update_reg_bounds(dst_reg);
8763 }
8764 
8765 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8766 				 struct bpf_reg_state *src_reg)
8767 {
8768 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8769 	u32 umax_val = src_reg->u32_max_value;
8770 	u32 umin_val = src_reg->u32_min_value;
8771 
8772 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8773 	 * be negative, then either:
8774 	 * 1) src_reg might be zero, so the sign bit of the result is
8775 	 *    unknown, so we lose our signed bounds
8776 	 * 2) it's known negative, thus the unsigned bounds capture the
8777 	 *    signed bounds
8778 	 * 3) the signed bounds cross zero, so they tell us nothing
8779 	 *    about the result
8780 	 * If the value in dst_reg is known nonnegative, then again the
8781 	 * unsigned bounds capture the signed bounds.
8782 	 * Thus, in all cases it suffices to blow away our signed bounds
8783 	 * and rely on inferring new ones from the unsigned bounds and
8784 	 * var_off of the result.
8785 	 */
8786 	dst_reg->s32_min_value = S32_MIN;
8787 	dst_reg->s32_max_value = S32_MAX;
8788 
8789 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
8790 	dst_reg->u32_min_value >>= umax_val;
8791 	dst_reg->u32_max_value >>= umin_val;
8792 
8793 	__mark_reg64_unbounded(dst_reg);
8794 	__update_reg32_bounds(dst_reg);
8795 }
8796 
8797 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8798 			       struct bpf_reg_state *src_reg)
8799 {
8800 	u64 umax_val = src_reg->umax_value;
8801 	u64 umin_val = src_reg->umin_value;
8802 
8803 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8804 	 * be negative, then either:
8805 	 * 1) src_reg might be zero, so the sign bit of the result is
8806 	 *    unknown, so we lose our signed bounds
8807 	 * 2) it's known negative, thus the unsigned bounds capture the
8808 	 *    signed bounds
8809 	 * 3) the signed bounds cross zero, so they tell us nothing
8810 	 *    about the result
8811 	 * If the value in dst_reg is known nonnegative, then again the
8812 	 * unsigned bounds capture the signed bounds.
8813 	 * Thus, in all cases it suffices to blow away our signed bounds
8814 	 * and rely on inferring new ones from the unsigned bounds and
8815 	 * var_off of the result.
8816 	 */
8817 	dst_reg->smin_value = S64_MIN;
8818 	dst_reg->smax_value = S64_MAX;
8819 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8820 	dst_reg->umin_value >>= umax_val;
8821 	dst_reg->umax_value >>= umin_val;
8822 
8823 	/* Its not easy to operate on alu32 bounds here because it depends
8824 	 * on bits being shifted in. Take easy way out and mark unbounded
8825 	 * so we can recalculate later from tnum.
8826 	 */
8827 	__mark_reg32_unbounded(dst_reg);
8828 	__update_reg_bounds(dst_reg);
8829 }
8830 
8831 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8832 				  struct bpf_reg_state *src_reg)
8833 {
8834 	u64 umin_val = src_reg->u32_min_value;
8835 
8836 	/* Upon reaching here, src_known is true and
8837 	 * umax_val is equal to umin_val.
8838 	 */
8839 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8840 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8841 
8842 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8843 
8844 	/* blow away the dst_reg umin_value/umax_value and rely on
8845 	 * dst_reg var_off to refine the result.
8846 	 */
8847 	dst_reg->u32_min_value = 0;
8848 	dst_reg->u32_max_value = U32_MAX;
8849 
8850 	__mark_reg64_unbounded(dst_reg);
8851 	__update_reg32_bounds(dst_reg);
8852 }
8853 
8854 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8855 				struct bpf_reg_state *src_reg)
8856 {
8857 	u64 umin_val = src_reg->umin_value;
8858 
8859 	/* Upon reaching here, src_known is true and umax_val is equal
8860 	 * to umin_val.
8861 	 */
8862 	dst_reg->smin_value >>= umin_val;
8863 	dst_reg->smax_value >>= umin_val;
8864 
8865 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8866 
8867 	/* blow away the dst_reg umin_value/umax_value and rely on
8868 	 * dst_reg var_off to refine the result.
8869 	 */
8870 	dst_reg->umin_value = 0;
8871 	dst_reg->umax_value = U64_MAX;
8872 
8873 	/* Its not easy to operate on alu32 bounds here because it depends
8874 	 * on bits being shifted in from upper 32-bits. Take easy way out
8875 	 * and mark unbounded so we can recalculate later from tnum.
8876 	 */
8877 	__mark_reg32_unbounded(dst_reg);
8878 	__update_reg_bounds(dst_reg);
8879 }
8880 
8881 /* WARNING: This function does calculations on 64-bit values, but the actual
8882  * execution may occur on 32-bit values. Therefore, things like bitshifts
8883  * need extra checks in the 32-bit case.
8884  */
8885 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8886 				      struct bpf_insn *insn,
8887 				      struct bpf_reg_state *dst_reg,
8888 				      struct bpf_reg_state src_reg)
8889 {
8890 	struct bpf_reg_state *regs = cur_regs(env);
8891 	u8 opcode = BPF_OP(insn->code);
8892 	bool src_known;
8893 	s64 smin_val, smax_val;
8894 	u64 umin_val, umax_val;
8895 	s32 s32_min_val, s32_max_val;
8896 	u32 u32_min_val, u32_max_val;
8897 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8898 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8899 	int ret;
8900 
8901 	smin_val = src_reg.smin_value;
8902 	smax_val = src_reg.smax_value;
8903 	umin_val = src_reg.umin_value;
8904 	umax_val = src_reg.umax_value;
8905 
8906 	s32_min_val = src_reg.s32_min_value;
8907 	s32_max_val = src_reg.s32_max_value;
8908 	u32_min_val = src_reg.u32_min_value;
8909 	u32_max_val = src_reg.u32_max_value;
8910 
8911 	if (alu32) {
8912 		src_known = tnum_subreg_is_const(src_reg.var_off);
8913 		if ((src_known &&
8914 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8915 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8916 			/* Taint dst register if offset had invalid bounds
8917 			 * derived from e.g. dead branches.
8918 			 */
8919 			__mark_reg_unknown(env, dst_reg);
8920 			return 0;
8921 		}
8922 	} else {
8923 		src_known = tnum_is_const(src_reg.var_off);
8924 		if ((src_known &&
8925 		     (smin_val != smax_val || umin_val != umax_val)) ||
8926 		    smin_val > smax_val || umin_val > umax_val) {
8927 			/* Taint dst register if offset had invalid bounds
8928 			 * derived from e.g. dead branches.
8929 			 */
8930 			__mark_reg_unknown(env, dst_reg);
8931 			return 0;
8932 		}
8933 	}
8934 
8935 	if (!src_known &&
8936 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8937 		__mark_reg_unknown(env, dst_reg);
8938 		return 0;
8939 	}
8940 
8941 	if (sanitize_needed(opcode)) {
8942 		ret = sanitize_val_alu(env, insn);
8943 		if (ret < 0)
8944 			return sanitize_err(env, insn, ret, NULL, NULL);
8945 	}
8946 
8947 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8948 	 * There are two classes of instructions: The first class we track both
8949 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8950 	 * greatest amount of precision when alu operations are mixed with jmp32
8951 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8952 	 * and BPF_OR. This is possible because these ops have fairly easy to
8953 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8954 	 * See alu32 verifier tests for examples. The second class of
8955 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8956 	 * with regards to tracking sign/unsigned bounds because the bits may
8957 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8958 	 * the reg unbounded in the subreg bound space and use the resulting
8959 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8960 	 */
8961 	switch (opcode) {
8962 	case BPF_ADD:
8963 		scalar32_min_max_add(dst_reg, &src_reg);
8964 		scalar_min_max_add(dst_reg, &src_reg);
8965 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8966 		break;
8967 	case BPF_SUB:
8968 		scalar32_min_max_sub(dst_reg, &src_reg);
8969 		scalar_min_max_sub(dst_reg, &src_reg);
8970 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8971 		break;
8972 	case BPF_MUL:
8973 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8974 		scalar32_min_max_mul(dst_reg, &src_reg);
8975 		scalar_min_max_mul(dst_reg, &src_reg);
8976 		break;
8977 	case BPF_AND:
8978 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8979 		scalar32_min_max_and(dst_reg, &src_reg);
8980 		scalar_min_max_and(dst_reg, &src_reg);
8981 		break;
8982 	case BPF_OR:
8983 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8984 		scalar32_min_max_or(dst_reg, &src_reg);
8985 		scalar_min_max_or(dst_reg, &src_reg);
8986 		break;
8987 	case BPF_XOR:
8988 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8989 		scalar32_min_max_xor(dst_reg, &src_reg);
8990 		scalar_min_max_xor(dst_reg, &src_reg);
8991 		break;
8992 	case BPF_LSH:
8993 		if (umax_val >= insn_bitness) {
8994 			/* Shifts greater than 31 or 63 are undefined.
8995 			 * This includes shifts by a negative number.
8996 			 */
8997 			mark_reg_unknown(env, regs, insn->dst_reg);
8998 			break;
8999 		}
9000 		if (alu32)
9001 			scalar32_min_max_lsh(dst_reg, &src_reg);
9002 		else
9003 			scalar_min_max_lsh(dst_reg, &src_reg);
9004 		break;
9005 	case BPF_RSH:
9006 		if (umax_val >= insn_bitness) {
9007 			/* Shifts greater than 31 or 63 are undefined.
9008 			 * This includes shifts by a negative number.
9009 			 */
9010 			mark_reg_unknown(env, regs, insn->dst_reg);
9011 			break;
9012 		}
9013 		if (alu32)
9014 			scalar32_min_max_rsh(dst_reg, &src_reg);
9015 		else
9016 			scalar_min_max_rsh(dst_reg, &src_reg);
9017 		break;
9018 	case BPF_ARSH:
9019 		if (umax_val >= insn_bitness) {
9020 			/* Shifts greater than 31 or 63 are undefined.
9021 			 * This includes shifts by a negative number.
9022 			 */
9023 			mark_reg_unknown(env, regs, insn->dst_reg);
9024 			break;
9025 		}
9026 		if (alu32)
9027 			scalar32_min_max_arsh(dst_reg, &src_reg);
9028 		else
9029 			scalar_min_max_arsh(dst_reg, &src_reg);
9030 		break;
9031 	default:
9032 		mark_reg_unknown(env, regs, insn->dst_reg);
9033 		break;
9034 	}
9035 
9036 	/* ALU32 ops are zero extended into 64bit register */
9037 	if (alu32)
9038 		zext_32_to_64(dst_reg);
9039 	reg_bounds_sync(dst_reg);
9040 	return 0;
9041 }
9042 
9043 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9044  * and var_off.
9045  */
9046 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9047 				   struct bpf_insn *insn)
9048 {
9049 	struct bpf_verifier_state *vstate = env->cur_state;
9050 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9051 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9052 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9053 	u8 opcode = BPF_OP(insn->code);
9054 	int err;
9055 
9056 	dst_reg = &regs[insn->dst_reg];
9057 	src_reg = NULL;
9058 	if (dst_reg->type != SCALAR_VALUE)
9059 		ptr_reg = dst_reg;
9060 	else
9061 		/* Make sure ID is cleared otherwise dst_reg min/max could be
9062 		 * incorrectly propagated into other registers by find_equal_scalars()
9063 		 */
9064 		dst_reg->id = 0;
9065 	if (BPF_SRC(insn->code) == BPF_X) {
9066 		src_reg = &regs[insn->src_reg];
9067 		if (src_reg->type != SCALAR_VALUE) {
9068 			if (dst_reg->type != SCALAR_VALUE) {
9069 				/* Combining two pointers by any ALU op yields
9070 				 * an arbitrary scalar. Disallow all math except
9071 				 * pointer subtraction
9072 				 */
9073 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9074 					mark_reg_unknown(env, regs, insn->dst_reg);
9075 					return 0;
9076 				}
9077 				verbose(env, "R%d pointer %s pointer prohibited\n",
9078 					insn->dst_reg,
9079 					bpf_alu_string[opcode >> 4]);
9080 				return -EACCES;
9081 			} else {
9082 				/* scalar += pointer
9083 				 * This is legal, but we have to reverse our
9084 				 * src/dest handling in computing the range
9085 				 */
9086 				err = mark_chain_precision(env, insn->dst_reg);
9087 				if (err)
9088 					return err;
9089 				return adjust_ptr_min_max_vals(env, insn,
9090 							       src_reg, dst_reg);
9091 			}
9092 		} else if (ptr_reg) {
9093 			/* pointer += scalar */
9094 			err = mark_chain_precision(env, insn->src_reg);
9095 			if (err)
9096 				return err;
9097 			return adjust_ptr_min_max_vals(env, insn,
9098 						       dst_reg, src_reg);
9099 		}
9100 	} else {
9101 		/* Pretend the src is a reg with a known value, since we only
9102 		 * need to be able to read from this state.
9103 		 */
9104 		off_reg.type = SCALAR_VALUE;
9105 		__mark_reg_known(&off_reg, insn->imm);
9106 		src_reg = &off_reg;
9107 		if (ptr_reg) /* pointer += K */
9108 			return adjust_ptr_min_max_vals(env, insn,
9109 						       ptr_reg, src_reg);
9110 	}
9111 
9112 	/* Got here implies adding two SCALAR_VALUEs */
9113 	if (WARN_ON_ONCE(ptr_reg)) {
9114 		print_verifier_state(env, state, true);
9115 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
9116 		return -EINVAL;
9117 	}
9118 	if (WARN_ON(!src_reg)) {
9119 		print_verifier_state(env, state, true);
9120 		verbose(env, "verifier internal error: no src_reg\n");
9121 		return -EINVAL;
9122 	}
9123 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9124 }
9125 
9126 /* check validity of 32-bit and 64-bit arithmetic operations */
9127 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9128 {
9129 	struct bpf_reg_state *regs = cur_regs(env);
9130 	u8 opcode = BPF_OP(insn->code);
9131 	int err;
9132 
9133 	if (opcode == BPF_END || opcode == BPF_NEG) {
9134 		if (opcode == BPF_NEG) {
9135 			if (BPF_SRC(insn->code) != BPF_K ||
9136 			    insn->src_reg != BPF_REG_0 ||
9137 			    insn->off != 0 || insn->imm != 0) {
9138 				verbose(env, "BPF_NEG uses reserved fields\n");
9139 				return -EINVAL;
9140 			}
9141 		} else {
9142 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9143 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9144 			    BPF_CLASS(insn->code) == BPF_ALU64) {
9145 				verbose(env, "BPF_END uses reserved fields\n");
9146 				return -EINVAL;
9147 			}
9148 		}
9149 
9150 		/* check src operand */
9151 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9152 		if (err)
9153 			return err;
9154 
9155 		if (is_pointer_value(env, insn->dst_reg)) {
9156 			verbose(env, "R%d pointer arithmetic prohibited\n",
9157 				insn->dst_reg);
9158 			return -EACCES;
9159 		}
9160 
9161 		/* check dest operand */
9162 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
9163 		if (err)
9164 			return err;
9165 
9166 	} else if (opcode == BPF_MOV) {
9167 
9168 		if (BPF_SRC(insn->code) == BPF_X) {
9169 			if (insn->imm != 0 || insn->off != 0) {
9170 				verbose(env, "BPF_MOV uses reserved fields\n");
9171 				return -EINVAL;
9172 			}
9173 
9174 			/* check src operand */
9175 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9176 			if (err)
9177 				return err;
9178 		} else {
9179 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9180 				verbose(env, "BPF_MOV uses reserved fields\n");
9181 				return -EINVAL;
9182 			}
9183 		}
9184 
9185 		/* check dest operand, mark as required later */
9186 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9187 		if (err)
9188 			return err;
9189 
9190 		if (BPF_SRC(insn->code) == BPF_X) {
9191 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
9192 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9193 
9194 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9195 				/* case: R1 = R2
9196 				 * copy register state to dest reg
9197 				 */
9198 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9199 					/* Assign src and dst registers the same ID
9200 					 * that will be used by find_equal_scalars()
9201 					 * to propagate min/max range.
9202 					 */
9203 					src_reg->id = ++env->id_gen;
9204 				*dst_reg = *src_reg;
9205 				dst_reg->live |= REG_LIVE_WRITTEN;
9206 				dst_reg->subreg_def = DEF_NOT_SUBREG;
9207 			} else {
9208 				/* R1 = (u32) R2 */
9209 				if (is_pointer_value(env, insn->src_reg)) {
9210 					verbose(env,
9211 						"R%d partial copy of pointer\n",
9212 						insn->src_reg);
9213 					return -EACCES;
9214 				} else if (src_reg->type == SCALAR_VALUE) {
9215 					*dst_reg = *src_reg;
9216 					/* Make sure ID is cleared otherwise
9217 					 * dst_reg min/max could be incorrectly
9218 					 * propagated into src_reg by find_equal_scalars()
9219 					 */
9220 					dst_reg->id = 0;
9221 					dst_reg->live |= REG_LIVE_WRITTEN;
9222 					dst_reg->subreg_def = env->insn_idx + 1;
9223 				} else {
9224 					mark_reg_unknown(env, regs,
9225 							 insn->dst_reg);
9226 				}
9227 				zext_32_to_64(dst_reg);
9228 				reg_bounds_sync(dst_reg);
9229 			}
9230 		} else {
9231 			/* case: R = imm
9232 			 * remember the value we stored into this reg
9233 			 */
9234 			/* clear any state __mark_reg_known doesn't set */
9235 			mark_reg_unknown(env, regs, insn->dst_reg);
9236 			regs[insn->dst_reg].type = SCALAR_VALUE;
9237 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9238 				__mark_reg_known(regs + insn->dst_reg,
9239 						 insn->imm);
9240 			} else {
9241 				__mark_reg_known(regs + insn->dst_reg,
9242 						 (u32)insn->imm);
9243 			}
9244 		}
9245 
9246 	} else if (opcode > BPF_END) {
9247 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9248 		return -EINVAL;
9249 
9250 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
9251 
9252 		if (BPF_SRC(insn->code) == BPF_X) {
9253 			if (insn->imm != 0 || insn->off != 0) {
9254 				verbose(env, "BPF_ALU uses reserved fields\n");
9255 				return -EINVAL;
9256 			}
9257 			/* check src1 operand */
9258 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9259 			if (err)
9260 				return err;
9261 		} else {
9262 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9263 				verbose(env, "BPF_ALU uses reserved fields\n");
9264 				return -EINVAL;
9265 			}
9266 		}
9267 
9268 		/* check src2 operand */
9269 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9270 		if (err)
9271 			return err;
9272 
9273 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9274 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9275 			verbose(env, "div by zero\n");
9276 			return -EINVAL;
9277 		}
9278 
9279 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9280 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9281 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9282 
9283 			if (insn->imm < 0 || insn->imm >= size) {
9284 				verbose(env, "invalid shift %d\n", insn->imm);
9285 				return -EINVAL;
9286 			}
9287 		}
9288 
9289 		/* check dest operand */
9290 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9291 		if (err)
9292 			return err;
9293 
9294 		return adjust_reg_min_max_vals(env, insn);
9295 	}
9296 
9297 	return 0;
9298 }
9299 
9300 static void __find_good_pkt_pointers(struct bpf_func_state *state,
9301 				     struct bpf_reg_state *dst_reg,
9302 				     enum bpf_reg_type type, int new_range)
9303 {
9304 	struct bpf_reg_state *reg;
9305 	int i;
9306 
9307 	for (i = 0; i < MAX_BPF_REG; i++) {
9308 		reg = &state->regs[i];
9309 		if (reg->type == type && reg->id == dst_reg->id)
9310 			/* keep the maximum range already checked */
9311 			reg->range = max(reg->range, new_range);
9312 	}
9313 
9314 	bpf_for_each_spilled_reg(i, state, reg) {
9315 		if (!reg)
9316 			continue;
9317 		if (reg->type == type && reg->id == dst_reg->id)
9318 			reg->range = max(reg->range, new_range);
9319 	}
9320 }
9321 
9322 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9323 				   struct bpf_reg_state *dst_reg,
9324 				   enum bpf_reg_type type,
9325 				   bool range_right_open)
9326 {
9327 	int new_range, i;
9328 
9329 	if (dst_reg->off < 0 ||
9330 	    (dst_reg->off == 0 && range_right_open))
9331 		/* This doesn't give us any range */
9332 		return;
9333 
9334 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
9335 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9336 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
9337 		 * than pkt_end, but that's because it's also less than pkt.
9338 		 */
9339 		return;
9340 
9341 	new_range = dst_reg->off;
9342 	if (range_right_open)
9343 		new_range++;
9344 
9345 	/* Examples for register markings:
9346 	 *
9347 	 * pkt_data in dst register:
9348 	 *
9349 	 *   r2 = r3;
9350 	 *   r2 += 8;
9351 	 *   if (r2 > pkt_end) goto <handle exception>
9352 	 *   <access okay>
9353 	 *
9354 	 *   r2 = r3;
9355 	 *   r2 += 8;
9356 	 *   if (r2 < pkt_end) goto <access okay>
9357 	 *   <handle exception>
9358 	 *
9359 	 *   Where:
9360 	 *     r2 == dst_reg, pkt_end == src_reg
9361 	 *     r2=pkt(id=n,off=8,r=0)
9362 	 *     r3=pkt(id=n,off=0,r=0)
9363 	 *
9364 	 * pkt_data in src register:
9365 	 *
9366 	 *   r2 = r3;
9367 	 *   r2 += 8;
9368 	 *   if (pkt_end >= r2) goto <access okay>
9369 	 *   <handle exception>
9370 	 *
9371 	 *   r2 = r3;
9372 	 *   r2 += 8;
9373 	 *   if (pkt_end <= r2) goto <handle exception>
9374 	 *   <access okay>
9375 	 *
9376 	 *   Where:
9377 	 *     pkt_end == dst_reg, r2 == src_reg
9378 	 *     r2=pkt(id=n,off=8,r=0)
9379 	 *     r3=pkt(id=n,off=0,r=0)
9380 	 *
9381 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9382 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9383 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
9384 	 * the check.
9385 	 */
9386 
9387 	/* If our ids match, then we must have the same max_value.  And we
9388 	 * don't care about the other reg's fixed offset, since if it's too big
9389 	 * the range won't allow anything.
9390 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9391 	 */
9392 	for (i = 0; i <= vstate->curframe; i++)
9393 		__find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
9394 					 new_range);
9395 }
9396 
9397 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9398 {
9399 	struct tnum subreg = tnum_subreg(reg->var_off);
9400 	s32 sval = (s32)val;
9401 
9402 	switch (opcode) {
9403 	case BPF_JEQ:
9404 		if (tnum_is_const(subreg))
9405 			return !!tnum_equals_const(subreg, val);
9406 		break;
9407 	case BPF_JNE:
9408 		if (tnum_is_const(subreg))
9409 			return !tnum_equals_const(subreg, val);
9410 		break;
9411 	case BPF_JSET:
9412 		if ((~subreg.mask & subreg.value) & val)
9413 			return 1;
9414 		if (!((subreg.mask | subreg.value) & val))
9415 			return 0;
9416 		break;
9417 	case BPF_JGT:
9418 		if (reg->u32_min_value > val)
9419 			return 1;
9420 		else if (reg->u32_max_value <= val)
9421 			return 0;
9422 		break;
9423 	case BPF_JSGT:
9424 		if (reg->s32_min_value > sval)
9425 			return 1;
9426 		else if (reg->s32_max_value <= sval)
9427 			return 0;
9428 		break;
9429 	case BPF_JLT:
9430 		if (reg->u32_max_value < val)
9431 			return 1;
9432 		else if (reg->u32_min_value >= val)
9433 			return 0;
9434 		break;
9435 	case BPF_JSLT:
9436 		if (reg->s32_max_value < sval)
9437 			return 1;
9438 		else if (reg->s32_min_value >= sval)
9439 			return 0;
9440 		break;
9441 	case BPF_JGE:
9442 		if (reg->u32_min_value >= val)
9443 			return 1;
9444 		else if (reg->u32_max_value < val)
9445 			return 0;
9446 		break;
9447 	case BPF_JSGE:
9448 		if (reg->s32_min_value >= sval)
9449 			return 1;
9450 		else if (reg->s32_max_value < sval)
9451 			return 0;
9452 		break;
9453 	case BPF_JLE:
9454 		if (reg->u32_max_value <= val)
9455 			return 1;
9456 		else if (reg->u32_min_value > val)
9457 			return 0;
9458 		break;
9459 	case BPF_JSLE:
9460 		if (reg->s32_max_value <= sval)
9461 			return 1;
9462 		else if (reg->s32_min_value > sval)
9463 			return 0;
9464 		break;
9465 	}
9466 
9467 	return -1;
9468 }
9469 
9470 
9471 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9472 {
9473 	s64 sval = (s64)val;
9474 
9475 	switch (opcode) {
9476 	case BPF_JEQ:
9477 		if (tnum_is_const(reg->var_off))
9478 			return !!tnum_equals_const(reg->var_off, val);
9479 		break;
9480 	case BPF_JNE:
9481 		if (tnum_is_const(reg->var_off))
9482 			return !tnum_equals_const(reg->var_off, val);
9483 		break;
9484 	case BPF_JSET:
9485 		if ((~reg->var_off.mask & reg->var_off.value) & val)
9486 			return 1;
9487 		if (!((reg->var_off.mask | reg->var_off.value) & val))
9488 			return 0;
9489 		break;
9490 	case BPF_JGT:
9491 		if (reg->umin_value > val)
9492 			return 1;
9493 		else if (reg->umax_value <= val)
9494 			return 0;
9495 		break;
9496 	case BPF_JSGT:
9497 		if (reg->smin_value > sval)
9498 			return 1;
9499 		else if (reg->smax_value <= sval)
9500 			return 0;
9501 		break;
9502 	case BPF_JLT:
9503 		if (reg->umax_value < val)
9504 			return 1;
9505 		else if (reg->umin_value >= val)
9506 			return 0;
9507 		break;
9508 	case BPF_JSLT:
9509 		if (reg->smax_value < sval)
9510 			return 1;
9511 		else if (reg->smin_value >= sval)
9512 			return 0;
9513 		break;
9514 	case BPF_JGE:
9515 		if (reg->umin_value >= val)
9516 			return 1;
9517 		else if (reg->umax_value < val)
9518 			return 0;
9519 		break;
9520 	case BPF_JSGE:
9521 		if (reg->smin_value >= sval)
9522 			return 1;
9523 		else if (reg->smax_value < sval)
9524 			return 0;
9525 		break;
9526 	case BPF_JLE:
9527 		if (reg->umax_value <= val)
9528 			return 1;
9529 		else if (reg->umin_value > val)
9530 			return 0;
9531 		break;
9532 	case BPF_JSLE:
9533 		if (reg->smax_value <= sval)
9534 			return 1;
9535 		else if (reg->smin_value > sval)
9536 			return 0;
9537 		break;
9538 	}
9539 
9540 	return -1;
9541 }
9542 
9543 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9544  * and return:
9545  *  1 - branch will be taken and "goto target" will be executed
9546  *  0 - branch will not be taken and fall-through to next insn
9547  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9548  *      range [0,10]
9549  */
9550 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9551 			   bool is_jmp32)
9552 {
9553 	if (__is_pointer_value(false, reg)) {
9554 		if (!reg_type_not_null(reg->type))
9555 			return -1;
9556 
9557 		/* If pointer is valid tests against zero will fail so we can
9558 		 * use this to direct branch taken.
9559 		 */
9560 		if (val != 0)
9561 			return -1;
9562 
9563 		switch (opcode) {
9564 		case BPF_JEQ:
9565 			return 0;
9566 		case BPF_JNE:
9567 			return 1;
9568 		default:
9569 			return -1;
9570 		}
9571 	}
9572 
9573 	if (is_jmp32)
9574 		return is_branch32_taken(reg, val, opcode);
9575 	return is_branch64_taken(reg, val, opcode);
9576 }
9577 
9578 static int flip_opcode(u32 opcode)
9579 {
9580 	/* How can we transform "a <op> b" into "b <op> a"? */
9581 	static const u8 opcode_flip[16] = {
9582 		/* these stay the same */
9583 		[BPF_JEQ  >> 4] = BPF_JEQ,
9584 		[BPF_JNE  >> 4] = BPF_JNE,
9585 		[BPF_JSET >> 4] = BPF_JSET,
9586 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
9587 		[BPF_JGE  >> 4] = BPF_JLE,
9588 		[BPF_JGT  >> 4] = BPF_JLT,
9589 		[BPF_JLE  >> 4] = BPF_JGE,
9590 		[BPF_JLT  >> 4] = BPF_JGT,
9591 		[BPF_JSGE >> 4] = BPF_JSLE,
9592 		[BPF_JSGT >> 4] = BPF_JSLT,
9593 		[BPF_JSLE >> 4] = BPF_JSGE,
9594 		[BPF_JSLT >> 4] = BPF_JSGT
9595 	};
9596 	return opcode_flip[opcode >> 4];
9597 }
9598 
9599 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9600 				   struct bpf_reg_state *src_reg,
9601 				   u8 opcode)
9602 {
9603 	struct bpf_reg_state *pkt;
9604 
9605 	if (src_reg->type == PTR_TO_PACKET_END) {
9606 		pkt = dst_reg;
9607 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
9608 		pkt = src_reg;
9609 		opcode = flip_opcode(opcode);
9610 	} else {
9611 		return -1;
9612 	}
9613 
9614 	if (pkt->range >= 0)
9615 		return -1;
9616 
9617 	switch (opcode) {
9618 	case BPF_JLE:
9619 		/* pkt <= pkt_end */
9620 		fallthrough;
9621 	case BPF_JGT:
9622 		/* pkt > pkt_end */
9623 		if (pkt->range == BEYOND_PKT_END)
9624 			/* pkt has at last one extra byte beyond pkt_end */
9625 			return opcode == BPF_JGT;
9626 		break;
9627 	case BPF_JLT:
9628 		/* pkt < pkt_end */
9629 		fallthrough;
9630 	case BPF_JGE:
9631 		/* pkt >= pkt_end */
9632 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9633 			return opcode == BPF_JGE;
9634 		break;
9635 	}
9636 	return -1;
9637 }
9638 
9639 /* Adjusts the register min/max values in the case that the dst_reg is the
9640  * variable register that we are working on, and src_reg is a constant or we're
9641  * simply doing a BPF_K check.
9642  * In JEQ/JNE cases we also adjust the var_off values.
9643  */
9644 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9645 			    struct bpf_reg_state *false_reg,
9646 			    u64 val, u32 val32,
9647 			    u8 opcode, bool is_jmp32)
9648 {
9649 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9650 	struct tnum false_64off = false_reg->var_off;
9651 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9652 	struct tnum true_64off = true_reg->var_off;
9653 	s64 sval = (s64)val;
9654 	s32 sval32 = (s32)val32;
9655 
9656 	/* If the dst_reg is a pointer, we can't learn anything about its
9657 	 * variable offset from the compare (unless src_reg were a pointer into
9658 	 * the same object, but we don't bother with that.
9659 	 * Since false_reg and true_reg have the same type by construction, we
9660 	 * only need to check one of them for pointerness.
9661 	 */
9662 	if (__is_pointer_value(false, false_reg))
9663 		return;
9664 
9665 	switch (opcode) {
9666 	/* JEQ/JNE comparison doesn't change the register equivalence.
9667 	 *
9668 	 * r1 = r2;
9669 	 * if (r1 == 42) goto label;
9670 	 * ...
9671 	 * label: // here both r1 and r2 are known to be 42.
9672 	 *
9673 	 * Hence when marking register as known preserve it's ID.
9674 	 */
9675 	case BPF_JEQ:
9676 		if (is_jmp32) {
9677 			__mark_reg32_known(true_reg, val32);
9678 			true_32off = tnum_subreg(true_reg->var_off);
9679 		} else {
9680 			___mark_reg_known(true_reg, val);
9681 			true_64off = true_reg->var_off;
9682 		}
9683 		break;
9684 	case BPF_JNE:
9685 		if (is_jmp32) {
9686 			__mark_reg32_known(false_reg, val32);
9687 			false_32off = tnum_subreg(false_reg->var_off);
9688 		} else {
9689 			___mark_reg_known(false_reg, val);
9690 			false_64off = false_reg->var_off;
9691 		}
9692 		break;
9693 	case BPF_JSET:
9694 		if (is_jmp32) {
9695 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9696 			if (is_power_of_2(val32))
9697 				true_32off = tnum_or(true_32off,
9698 						     tnum_const(val32));
9699 		} else {
9700 			false_64off = tnum_and(false_64off, tnum_const(~val));
9701 			if (is_power_of_2(val))
9702 				true_64off = tnum_or(true_64off,
9703 						     tnum_const(val));
9704 		}
9705 		break;
9706 	case BPF_JGE:
9707 	case BPF_JGT:
9708 	{
9709 		if (is_jmp32) {
9710 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9711 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9712 
9713 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9714 						       false_umax);
9715 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9716 						      true_umin);
9717 		} else {
9718 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9719 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9720 
9721 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9722 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9723 		}
9724 		break;
9725 	}
9726 	case BPF_JSGE:
9727 	case BPF_JSGT:
9728 	{
9729 		if (is_jmp32) {
9730 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9731 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9732 
9733 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9734 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9735 		} else {
9736 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9737 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9738 
9739 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9740 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9741 		}
9742 		break;
9743 	}
9744 	case BPF_JLE:
9745 	case BPF_JLT:
9746 	{
9747 		if (is_jmp32) {
9748 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9749 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9750 
9751 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9752 						       false_umin);
9753 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9754 						      true_umax);
9755 		} else {
9756 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9757 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9758 
9759 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9760 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9761 		}
9762 		break;
9763 	}
9764 	case BPF_JSLE:
9765 	case BPF_JSLT:
9766 	{
9767 		if (is_jmp32) {
9768 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9769 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9770 
9771 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9772 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9773 		} else {
9774 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9775 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9776 
9777 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
9778 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
9779 		}
9780 		break;
9781 	}
9782 	default:
9783 		return;
9784 	}
9785 
9786 	if (is_jmp32) {
9787 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9788 					     tnum_subreg(false_32off));
9789 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9790 					    tnum_subreg(true_32off));
9791 		__reg_combine_32_into_64(false_reg);
9792 		__reg_combine_32_into_64(true_reg);
9793 	} else {
9794 		false_reg->var_off = false_64off;
9795 		true_reg->var_off = true_64off;
9796 		__reg_combine_64_into_32(false_reg);
9797 		__reg_combine_64_into_32(true_reg);
9798 	}
9799 }
9800 
9801 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9802  * the variable reg.
9803  */
9804 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9805 				struct bpf_reg_state *false_reg,
9806 				u64 val, u32 val32,
9807 				u8 opcode, bool is_jmp32)
9808 {
9809 	opcode = flip_opcode(opcode);
9810 	/* This uses zero as "not present in table"; luckily the zero opcode,
9811 	 * BPF_JA, can't get here.
9812 	 */
9813 	if (opcode)
9814 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9815 }
9816 
9817 /* Regs are known to be equal, so intersect their min/max/var_off */
9818 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9819 				  struct bpf_reg_state *dst_reg)
9820 {
9821 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9822 							dst_reg->umin_value);
9823 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9824 							dst_reg->umax_value);
9825 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9826 							dst_reg->smin_value);
9827 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9828 							dst_reg->smax_value);
9829 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9830 							     dst_reg->var_off);
9831 	reg_bounds_sync(src_reg);
9832 	reg_bounds_sync(dst_reg);
9833 }
9834 
9835 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9836 				struct bpf_reg_state *true_dst,
9837 				struct bpf_reg_state *false_src,
9838 				struct bpf_reg_state *false_dst,
9839 				u8 opcode)
9840 {
9841 	switch (opcode) {
9842 	case BPF_JEQ:
9843 		__reg_combine_min_max(true_src, true_dst);
9844 		break;
9845 	case BPF_JNE:
9846 		__reg_combine_min_max(false_src, false_dst);
9847 		break;
9848 	}
9849 }
9850 
9851 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9852 				 struct bpf_reg_state *reg, u32 id,
9853 				 bool is_null)
9854 {
9855 	if (type_may_be_null(reg->type) && reg->id == id &&
9856 	    !WARN_ON_ONCE(!reg->id)) {
9857 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9858 				 !tnum_equals_const(reg->var_off, 0) ||
9859 				 reg->off)) {
9860 			/* Old offset (both fixed and variable parts) should
9861 			 * have been known-zero, because we don't allow pointer
9862 			 * arithmetic on pointers that might be NULL. If we
9863 			 * see this happening, don't convert the register.
9864 			 */
9865 			return;
9866 		}
9867 		if (is_null) {
9868 			reg->type = SCALAR_VALUE;
9869 			/* We don't need id and ref_obj_id from this point
9870 			 * onwards anymore, thus we should better reset it,
9871 			 * so that state pruning has chances to take effect.
9872 			 */
9873 			reg->id = 0;
9874 			reg->ref_obj_id = 0;
9875 
9876 			return;
9877 		}
9878 
9879 		mark_ptr_not_null_reg(reg);
9880 
9881 		if (!reg_may_point_to_spin_lock(reg)) {
9882 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9883 			 * in release_reg_references().
9884 			 *
9885 			 * reg->id is still used by spin_lock ptr. Other
9886 			 * than spin_lock ptr type, reg->id can be reset.
9887 			 */
9888 			reg->id = 0;
9889 		}
9890 	}
9891 }
9892 
9893 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9894 				    bool is_null)
9895 {
9896 	struct bpf_reg_state *reg;
9897 	int i;
9898 
9899 	for (i = 0; i < MAX_BPF_REG; i++)
9900 		mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9901 
9902 	bpf_for_each_spilled_reg(i, state, reg) {
9903 		if (!reg)
9904 			continue;
9905 		mark_ptr_or_null_reg(state, reg, id, is_null);
9906 	}
9907 }
9908 
9909 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9910  * be folded together at some point.
9911  */
9912 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9913 				  bool is_null)
9914 {
9915 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9916 	struct bpf_reg_state *regs = state->regs;
9917 	u32 ref_obj_id = regs[regno].ref_obj_id;
9918 	u32 id = regs[regno].id;
9919 	int i;
9920 
9921 	if (ref_obj_id && ref_obj_id == id && is_null)
9922 		/* regs[regno] is in the " == NULL" branch.
9923 		 * No one could have freed the reference state before
9924 		 * doing the NULL check.
9925 		 */
9926 		WARN_ON_ONCE(release_reference_state(state, id));
9927 
9928 	for (i = 0; i <= vstate->curframe; i++)
9929 		__mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9930 }
9931 
9932 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9933 				   struct bpf_reg_state *dst_reg,
9934 				   struct bpf_reg_state *src_reg,
9935 				   struct bpf_verifier_state *this_branch,
9936 				   struct bpf_verifier_state *other_branch)
9937 {
9938 	if (BPF_SRC(insn->code) != BPF_X)
9939 		return false;
9940 
9941 	/* Pointers are always 64-bit. */
9942 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9943 		return false;
9944 
9945 	switch (BPF_OP(insn->code)) {
9946 	case BPF_JGT:
9947 		if ((dst_reg->type == PTR_TO_PACKET &&
9948 		     src_reg->type == PTR_TO_PACKET_END) ||
9949 		    (dst_reg->type == PTR_TO_PACKET_META &&
9950 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9951 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9952 			find_good_pkt_pointers(this_branch, dst_reg,
9953 					       dst_reg->type, false);
9954 			mark_pkt_end(other_branch, insn->dst_reg, true);
9955 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9956 			    src_reg->type == PTR_TO_PACKET) ||
9957 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9958 			    src_reg->type == PTR_TO_PACKET_META)) {
9959 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9960 			find_good_pkt_pointers(other_branch, src_reg,
9961 					       src_reg->type, true);
9962 			mark_pkt_end(this_branch, insn->src_reg, false);
9963 		} else {
9964 			return false;
9965 		}
9966 		break;
9967 	case BPF_JLT:
9968 		if ((dst_reg->type == PTR_TO_PACKET &&
9969 		     src_reg->type == PTR_TO_PACKET_END) ||
9970 		    (dst_reg->type == PTR_TO_PACKET_META &&
9971 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9972 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9973 			find_good_pkt_pointers(other_branch, dst_reg,
9974 					       dst_reg->type, true);
9975 			mark_pkt_end(this_branch, insn->dst_reg, false);
9976 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9977 			    src_reg->type == PTR_TO_PACKET) ||
9978 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9979 			    src_reg->type == PTR_TO_PACKET_META)) {
9980 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9981 			find_good_pkt_pointers(this_branch, src_reg,
9982 					       src_reg->type, false);
9983 			mark_pkt_end(other_branch, insn->src_reg, true);
9984 		} else {
9985 			return false;
9986 		}
9987 		break;
9988 	case BPF_JGE:
9989 		if ((dst_reg->type == PTR_TO_PACKET &&
9990 		     src_reg->type == PTR_TO_PACKET_END) ||
9991 		    (dst_reg->type == PTR_TO_PACKET_META &&
9992 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9993 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9994 			find_good_pkt_pointers(this_branch, dst_reg,
9995 					       dst_reg->type, true);
9996 			mark_pkt_end(other_branch, insn->dst_reg, false);
9997 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9998 			    src_reg->type == PTR_TO_PACKET) ||
9999 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10000 			    src_reg->type == PTR_TO_PACKET_META)) {
10001 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10002 			find_good_pkt_pointers(other_branch, src_reg,
10003 					       src_reg->type, false);
10004 			mark_pkt_end(this_branch, insn->src_reg, true);
10005 		} else {
10006 			return false;
10007 		}
10008 		break;
10009 	case BPF_JLE:
10010 		if ((dst_reg->type == PTR_TO_PACKET &&
10011 		     src_reg->type == PTR_TO_PACKET_END) ||
10012 		    (dst_reg->type == PTR_TO_PACKET_META &&
10013 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10014 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10015 			find_good_pkt_pointers(other_branch, dst_reg,
10016 					       dst_reg->type, false);
10017 			mark_pkt_end(this_branch, insn->dst_reg, true);
10018 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10019 			    src_reg->type == PTR_TO_PACKET) ||
10020 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10021 			    src_reg->type == PTR_TO_PACKET_META)) {
10022 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10023 			find_good_pkt_pointers(this_branch, src_reg,
10024 					       src_reg->type, true);
10025 			mark_pkt_end(other_branch, insn->src_reg, false);
10026 		} else {
10027 			return false;
10028 		}
10029 		break;
10030 	default:
10031 		return false;
10032 	}
10033 
10034 	return true;
10035 }
10036 
10037 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10038 			       struct bpf_reg_state *known_reg)
10039 {
10040 	struct bpf_func_state *state;
10041 	struct bpf_reg_state *reg;
10042 	int i, j;
10043 
10044 	for (i = 0; i <= vstate->curframe; i++) {
10045 		state = vstate->frame[i];
10046 		for (j = 0; j < MAX_BPF_REG; j++) {
10047 			reg = &state->regs[j];
10048 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10049 				*reg = *known_reg;
10050 		}
10051 
10052 		bpf_for_each_spilled_reg(j, state, reg) {
10053 			if (!reg)
10054 				continue;
10055 			if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10056 				*reg = *known_reg;
10057 		}
10058 	}
10059 }
10060 
10061 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10062 			     struct bpf_insn *insn, int *insn_idx)
10063 {
10064 	struct bpf_verifier_state *this_branch = env->cur_state;
10065 	struct bpf_verifier_state *other_branch;
10066 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10067 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10068 	u8 opcode = BPF_OP(insn->code);
10069 	bool is_jmp32;
10070 	int pred = -1;
10071 	int err;
10072 
10073 	/* Only conditional jumps are expected to reach here. */
10074 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
10075 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10076 		return -EINVAL;
10077 	}
10078 
10079 	if (BPF_SRC(insn->code) == BPF_X) {
10080 		if (insn->imm != 0) {
10081 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10082 			return -EINVAL;
10083 		}
10084 
10085 		/* check src1 operand */
10086 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10087 		if (err)
10088 			return err;
10089 
10090 		if (is_pointer_value(env, insn->src_reg)) {
10091 			verbose(env, "R%d pointer comparison prohibited\n",
10092 				insn->src_reg);
10093 			return -EACCES;
10094 		}
10095 		src_reg = &regs[insn->src_reg];
10096 	} else {
10097 		if (insn->src_reg != BPF_REG_0) {
10098 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10099 			return -EINVAL;
10100 		}
10101 	}
10102 
10103 	/* check src2 operand */
10104 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10105 	if (err)
10106 		return err;
10107 
10108 	dst_reg = &regs[insn->dst_reg];
10109 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10110 
10111 	if (BPF_SRC(insn->code) == BPF_K) {
10112 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10113 	} else if (src_reg->type == SCALAR_VALUE &&
10114 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10115 		pred = is_branch_taken(dst_reg,
10116 				       tnum_subreg(src_reg->var_off).value,
10117 				       opcode,
10118 				       is_jmp32);
10119 	} else if (src_reg->type == SCALAR_VALUE &&
10120 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10121 		pred = is_branch_taken(dst_reg,
10122 				       src_reg->var_off.value,
10123 				       opcode,
10124 				       is_jmp32);
10125 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
10126 		   reg_is_pkt_pointer_any(src_reg) &&
10127 		   !is_jmp32) {
10128 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10129 	}
10130 
10131 	if (pred >= 0) {
10132 		/* If we get here with a dst_reg pointer type it is because
10133 		 * above is_branch_taken() special cased the 0 comparison.
10134 		 */
10135 		if (!__is_pointer_value(false, dst_reg))
10136 			err = mark_chain_precision(env, insn->dst_reg);
10137 		if (BPF_SRC(insn->code) == BPF_X && !err &&
10138 		    !__is_pointer_value(false, src_reg))
10139 			err = mark_chain_precision(env, insn->src_reg);
10140 		if (err)
10141 			return err;
10142 	}
10143 
10144 	if (pred == 1) {
10145 		/* Only follow the goto, ignore fall-through. If needed, push
10146 		 * the fall-through branch for simulation under speculative
10147 		 * execution.
10148 		 */
10149 		if (!env->bypass_spec_v1 &&
10150 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
10151 					       *insn_idx))
10152 			return -EFAULT;
10153 		*insn_idx += insn->off;
10154 		return 0;
10155 	} else if (pred == 0) {
10156 		/* Only follow the fall-through branch, since that's where the
10157 		 * program will go. If needed, push the goto branch for
10158 		 * simulation under speculative execution.
10159 		 */
10160 		if (!env->bypass_spec_v1 &&
10161 		    !sanitize_speculative_path(env, insn,
10162 					       *insn_idx + insn->off + 1,
10163 					       *insn_idx))
10164 			return -EFAULT;
10165 		return 0;
10166 	}
10167 
10168 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10169 				  false);
10170 	if (!other_branch)
10171 		return -EFAULT;
10172 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10173 
10174 	/* detect if we are comparing against a constant value so we can adjust
10175 	 * our min/max values for our dst register.
10176 	 * this is only legit if both are scalars (or pointers to the same
10177 	 * object, I suppose, but we don't support that right now), because
10178 	 * otherwise the different base pointers mean the offsets aren't
10179 	 * comparable.
10180 	 */
10181 	if (BPF_SRC(insn->code) == BPF_X) {
10182 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10183 
10184 		if (dst_reg->type == SCALAR_VALUE &&
10185 		    src_reg->type == SCALAR_VALUE) {
10186 			if (tnum_is_const(src_reg->var_off) ||
10187 			    (is_jmp32 &&
10188 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
10189 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
10190 						dst_reg,
10191 						src_reg->var_off.value,
10192 						tnum_subreg(src_reg->var_off).value,
10193 						opcode, is_jmp32);
10194 			else if (tnum_is_const(dst_reg->var_off) ||
10195 				 (is_jmp32 &&
10196 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
10197 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10198 						    src_reg,
10199 						    dst_reg->var_off.value,
10200 						    tnum_subreg(dst_reg->var_off).value,
10201 						    opcode, is_jmp32);
10202 			else if (!is_jmp32 &&
10203 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
10204 				/* Comparing for equality, we can combine knowledge */
10205 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
10206 						    &other_branch_regs[insn->dst_reg],
10207 						    src_reg, dst_reg, opcode);
10208 			if (src_reg->id &&
10209 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10210 				find_equal_scalars(this_branch, src_reg);
10211 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10212 			}
10213 
10214 		}
10215 	} else if (dst_reg->type == SCALAR_VALUE) {
10216 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
10217 					dst_reg, insn->imm, (u32)insn->imm,
10218 					opcode, is_jmp32);
10219 	}
10220 
10221 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10222 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10223 		find_equal_scalars(this_branch, dst_reg);
10224 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10225 	}
10226 
10227 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10228 	 * NOTE: these optimizations below are related with pointer comparison
10229 	 *       which will never be JMP32.
10230 	 */
10231 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10232 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10233 	    type_may_be_null(dst_reg->type)) {
10234 		/* Mark all identical registers in each branch as either
10235 		 * safe or unknown depending R == 0 or R != 0 conditional.
10236 		 */
10237 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10238 				      opcode == BPF_JNE);
10239 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10240 				      opcode == BPF_JEQ);
10241 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10242 					   this_branch, other_branch) &&
10243 		   is_pointer_value(env, insn->dst_reg)) {
10244 		verbose(env, "R%d pointer comparison prohibited\n",
10245 			insn->dst_reg);
10246 		return -EACCES;
10247 	}
10248 	if (env->log.level & BPF_LOG_LEVEL)
10249 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
10250 	return 0;
10251 }
10252 
10253 /* verify BPF_LD_IMM64 instruction */
10254 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10255 {
10256 	struct bpf_insn_aux_data *aux = cur_aux(env);
10257 	struct bpf_reg_state *regs = cur_regs(env);
10258 	struct bpf_reg_state *dst_reg;
10259 	struct bpf_map *map;
10260 	int err;
10261 
10262 	if (BPF_SIZE(insn->code) != BPF_DW) {
10263 		verbose(env, "invalid BPF_LD_IMM insn\n");
10264 		return -EINVAL;
10265 	}
10266 	if (insn->off != 0) {
10267 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10268 		return -EINVAL;
10269 	}
10270 
10271 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
10272 	if (err)
10273 		return err;
10274 
10275 	dst_reg = &regs[insn->dst_reg];
10276 	if (insn->src_reg == 0) {
10277 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10278 
10279 		dst_reg->type = SCALAR_VALUE;
10280 		__mark_reg_known(&regs[insn->dst_reg], imm);
10281 		return 0;
10282 	}
10283 
10284 	/* All special src_reg cases are listed below. From this point onwards
10285 	 * we either succeed and assign a corresponding dst_reg->type after
10286 	 * zeroing the offset, or fail and reject the program.
10287 	 */
10288 	mark_reg_known_zero(env, regs, insn->dst_reg);
10289 
10290 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10291 		dst_reg->type = aux->btf_var.reg_type;
10292 		switch (base_type(dst_reg->type)) {
10293 		case PTR_TO_MEM:
10294 			dst_reg->mem_size = aux->btf_var.mem_size;
10295 			break;
10296 		case PTR_TO_BTF_ID:
10297 			dst_reg->btf = aux->btf_var.btf;
10298 			dst_reg->btf_id = aux->btf_var.btf_id;
10299 			break;
10300 		default:
10301 			verbose(env, "bpf verifier is misconfigured\n");
10302 			return -EFAULT;
10303 		}
10304 		return 0;
10305 	}
10306 
10307 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
10308 		struct bpf_prog_aux *aux = env->prog->aux;
10309 		u32 subprogno = find_subprog(env,
10310 					     env->insn_idx + insn->imm + 1);
10311 
10312 		if (!aux->func_info) {
10313 			verbose(env, "missing btf func_info\n");
10314 			return -EINVAL;
10315 		}
10316 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10317 			verbose(env, "callback function not static\n");
10318 			return -EINVAL;
10319 		}
10320 
10321 		dst_reg->type = PTR_TO_FUNC;
10322 		dst_reg->subprogno = subprogno;
10323 		return 0;
10324 	}
10325 
10326 	map = env->used_maps[aux->map_index];
10327 	dst_reg->map_ptr = map;
10328 
10329 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10330 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10331 		dst_reg->type = PTR_TO_MAP_VALUE;
10332 		dst_reg->off = aux->map_off;
10333 		if (map_value_has_spin_lock(map))
10334 			dst_reg->id = ++env->id_gen;
10335 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10336 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10337 		dst_reg->type = CONST_PTR_TO_MAP;
10338 	} else {
10339 		verbose(env, "bpf verifier is misconfigured\n");
10340 		return -EINVAL;
10341 	}
10342 
10343 	return 0;
10344 }
10345 
10346 static bool may_access_skb(enum bpf_prog_type type)
10347 {
10348 	switch (type) {
10349 	case BPF_PROG_TYPE_SOCKET_FILTER:
10350 	case BPF_PROG_TYPE_SCHED_CLS:
10351 	case BPF_PROG_TYPE_SCHED_ACT:
10352 		return true;
10353 	default:
10354 		return false;
10355 	}
10356 }
10357 
10358 /* verify safety of LD_ABS|LD_IND instructions:
10359  * - they can only appear in the programs where ctx == skb
10360  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10361  *   preserve R6-R9, and store return value into R0
10362  *
10363  * Implicit input:
10364  *   ctx == skb == R6 == CTX
10365  *
10366  * Explicit input:
10367  *   SRC == any register
10368  *   IMM == 32-bit immediate
10369  *
10370  * Output:
10371  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10372  */
10373 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10374 {
10375 	struct bpf_reg_state *regs = cur_regs(env);
10376 	static const int ctx_reg = BPF_REG_6;
10377 	u8 mode = BPF_MODE(insn->code);
10378 	int i, err;
10379 
10380 	if (!may_access_skb(resolve_prog_type(env->prog))) {
10381 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10382 		return -EINVAL;
10383 	}
10384 
10385 	if (!env->ops->gen_ld_abs) {
10386 		verbose(env, "bpf verifier is misconfigured\n");
10387 		return -EINVAL;
10388 	}
10389 
10390 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10391 	    BPF_SIZE(insn->code) == BPF_DW ||
10392 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10393 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10394 		return -EINVAL;
10395 	}
10396 
10397 	/* check whether implicit source operand (register R6) is readable */
10398 	err = check_reg_arg(env, ctx_reg, SRC_OP);
10399 	if (err)
10400 		return err;
10401 
10402 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10403 	 * gen_ld_abs() may terminate the program at runtime, leading to
10404 	 * reference leak.
10405 	 */
10406 	err = check_reference_leak(env);
10407 	if (err) {
10408 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10409 		return err;
10410 	}
10411 
10412 	if (env->cur_state->active_spin_lock) {
10413 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10414 		return -EINVAL;
10415 	}
10416 
10417 	if (regs[ctx_reg].type != PTR_TO_CTX) {
10418 		verbose(env,
10419 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10420 		return -EINVAL;
10421 	}
10422 
10423 	if (mode == BPF_IND) {
10424 		/* check explicit source operand */
10425 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10426 		if (err)
10427 			return err;
10428 	}
10429 
10430 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10431 	if (err < 0)
10432 		return err;
10433 
10434 	/* reset caller saved regs to unreadable */
10435 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10436 		mark_reg_not_init(env, regs, caller_saved[i]);
10437 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10438 	}
10439 
10440 	/* mark destination R0 register as readable, since it contains
10441 	 * the value fetched from the packet.
10442 	 * Already marked as written above.
10443 	 */
10444 	mark_reg_unknown(env, regs, BPF_REG_0);
10445 	/* ld_abs load up to 32-bit skb data. */
10446 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10447 	return 0;
10448 }
10449 
10450 static int check_return_code(struct bpf_verifier_env *env)
10451 {
10452 	struct tnum enforce_attach_type_range = tnum_unknown;
10453 	const struct bpf_prog *prog = env->prog;
10454 	struct bpf_reg_state *reg;
10455 	struct tnum range = tnum_range(0, 1);
10456 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10457 	int err;
10458 	struct bpf_func_state *frame = env->cur_state->frame[0];
10459 	const bool is_subprog = frame->subprogno;
10460 
10461 	/* LSM and struct_ops func-ptr's return type could be "void" */
10462 	if (!is_subprog) {
10463 		switch (prog_type) {
10464 		case BPF_PROG_TYPE_LSM:
10465 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
10466 				/* See below, can be 0 or 0-1 depending on hook. */
10467 				break;
10468 			fallthrough;
10469 		case BPF_PROG_TYPE_STRUCT_OPS:
10470 			if (!prog->aux->attach_func_proto->type)
10471 				return 0;
10472 			break;
10473 		default:
10474 			break;
10475 		}
10476 	}
10477 
10478 	/* eBPF calling convention is such that R0 is used
10479 	 * to return the value from eBPF program.
10480 	 * Make sure that it's readable at this time
10481 	 * of bpf_exit, which means that program wrote
10482 	 * something into it earlier
10483 	 */
10484 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10485 	if (err)
10486 		return err;
10487 
10488 	if (is_pointer_value(env, BPF_REG_0)) {
10489 		verbose(env, "R0 leaks addr as return value\n");
10490 		return -EACCES;
10491 	}
10492 
10493 	reg = cur_regs(env) + BPF_REG_0;
10494 
10495 	if (frame->in_async_callback_fn) {
10496 		/* enforce return zero from async callbacks like timer */
10497 		if (reg->type != SCALAR_VALUE) {
10498 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10499 				reg_type_str(env, reg->type));
10500 			return -EINVAL;
10501 		}
10502 
10503 		if (!tnum_in(tnum_const(0), reg->var_off)) {
10504 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10505 			return -EINVAL;
10506 		}
10507 		return 0;
10508 	}
10509 
10510 	if (is_subprog) {
10511 		if (reg->type != SCALAR_VALUE) {
10512 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10513 				reg_type_str(env, reg->type));
10514 			return -EINVAL;
10515 		}
10516 		return 0;
10517 	}
10518 
10519 	switch (prog_type) {
10520 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10521 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10522 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10523 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10524 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10525 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10526 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10527 			range = tnum_range(1, 1);
10528 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10529 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10530 			range = tnum_range(0, 3);
10531 		break;
10532 	case BPF_PROG_TYPE_CGROUP_SKB:
10533 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10534 			range = tnum_range(0, 3);
10535 			enforce_attach_type_range = tnum_range(2, 3);
10536 		}
10537 		break;
10538 	case BPF_PROG_TYPE_CGROUP_SOCK:
10539 	case BPF_PROG_TYPE_SOCK_OPS:
10540 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10541 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10542 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10543 		break;
10544 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10545 		if (!env->prog->aux->attach_btf_id)
10546 			return 0;
10547 		range = tnum_const(0);
10548 		break;
10549 	case BPF_PROG_TYPE_TRACING:
10550 		switch (env->prog->expected_attach_type) {
10551 		case BPF_TRACE_FENTRY:
10552 		case BPF_TRACE_FEXIT:
10553 			range = tnum_const(0);
10554 			break;
10555 		case BPF_TRACE_RAW_TP:
10556 		case BPF_MODIFY_RETURN:
10557 			return 0;
10558 		case BPF_TRACE_ITER:
10559 			break;
10560 		default:
10561 			return -ENOTSUPP;
10562 		}
10563 		break;
10564 	case BPF_PROG_TYPE_SK_LOOKUP:
10565 		range = tnum_range(SK_DROP, SK_PASS);
10566 		break;
10567 
10568 	case BPF_PROG_TYPE_LSM:
10569 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10570 			/* Regular BPF_PROG_TYPE_LSM programs can return
10571 			 * any value.
10572 			 */
10573 			return 0;
10574 		}
10575 		if (!env->prog->aux->attach_func_proto->type) {
10576 			/* Make sure programs that attach to void
10577 			 * hooks don't try to modify return value.
10578 			 */
10579 			range = tnum_range(1, 1);
10580 		}
10581 		break;
10582 
10583 	case BPF_PROG_TYPE_EXT:
10584 		/* freplace program can return anything as its return value
10585 		 * depends on the to-be-replaced kernel func or bpf program.
10586 		 */
10587 	default:
10588 		return 0;
10589 	}
10590 
10591 	if (reg->type != SCALAR_VALUE) {
10592 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10593 			reg_type_str(env, reg->type));
10594 		return -EINVAL;
10595 	}
10596 
10597 	if (!tnum_in(range, reg->var_off)) {
10598 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10599 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10600 		    prog_type == BPF_PROG_TYPE_LSM &&
10601 		    !prog->aux->attach_func_proto->type)
10602 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10603 		return -EINVAL;
10604 	}
10605 
10606 	if (!tnum_is_unknown(enforce_attach_type_range) &&
10607 	    tnum_in(enforce_attach_type_range, reg->var_off))
10608 		env->prog->enforce_expected_attach_type = 1;
10609 	return 0;
10610 }
10611 
10612 /* non-recursive DFS pseudo code
10613  * 1  procedure DFS-iterative(G,v):
10614  * 2      label v as discovered
10615  * 3      let S be a stack
10616  * 4      S.push(v)
10617  * 5      while S is not empty
10618  * 6            t <- S.pop()
10619  * 7            if t is what we're looking for:
10620  * 8                return t
10621  * 9            for all edges e in G.adjacentEdges(t) do
10622  * 10               if edge e is already labelled
10623  * 11                   continue with the next edge
10624  * 12               w <- G.adjacentVertex(t,e)
10625  * 13               if vertex w is not discovered and not explored
10626  * 14                   label e as tree-edge
10627  * 15                   label w as discovered
10628  * 16                   S.push(w)
10629  * 17                   continue at 5
10630  * 18               else if vertex w is discovered
10631  * 19                   label e as back-edge
10632  * 20               else
10633  * 21                   // vertex w is explored
10634  * 22                   label e as forward- or cross-edge
10635  * 23           label t as explored
10636  * 24           S.pop()
10637  *
10638  * convention:
10639  * 0x10 - discovered
10640  * 0x11 - discovered and fall-through edge labelled
10641  * 0x12 - discovered and fall-through and branch edges labelled
10642  * 0x20 - explored
10643  */
10644 
10645 enum {
10646 	DISCOVERED = 0x10,
10647 	EXPLORED = 0x20,
10648 	FALLTHROUGH = 1,
10649 	BRANCH = 2,
10650 };
10651 
10652 static u32 state_htab_size(struct bpf_verifier_env *env)
10653 {
10654 	return env->prog->len;
10655 }
10656 
10657 static struct bpf_verifier_state_list **explored_state(
10658 					struct bpf_verifier_env *env,
10659 					int idx)
10660 {
10661 	struct bpf_verifier_state *cur = env->cur_state;
10662 	struct bpf_func_state *state = cur->frame[cur->curframe];
10663 
10664 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10665 }
10666 
10667 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10668 {
10669 	env->insn_aux_data[idx].prune_point = true;
10670 }
10671 
10672 enum {
10673 	DONE_EXPLORING = 0,
10674 	KEEP_EXPLORING = 1,
10675 };
10676 
10677 /* t, w, e - match pseudo-code above:
10678  * t - index of current instruction
10679  * w - next instruction
10680  * e - edge
10681  */
10682 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10683 		     bool loop_ok)
10684 {
10685 	int *insn_stack = env->cfg.insn_stack;
10686 	int *insn_state = env->cfg.insn_state;
10687 
10688 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10689 		return DONE_EXPLORING;
10690 
10691 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10692 		return DONE_EXPLORING;
10693 
10694 	if (w < 0 || w >= env->prog->len) {
10695 		verbose_linfo(env, t, "%d: ", t);
10696 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10697 		return -EINVAL;
10698 	}
10699 
10700 	if (e == BRANCH)
10701 		/* mark branch target for state pruning */
10702 		init_explored_state(env, w);
10703 
10704 	if (insn_state[w] == 0) {
10705 		/* tree-edge */
10706 		insn_state[t] = DISCOVERED | e;
10707 		insn_state[w] = DISCOVERED;
10708 		if (env->cfg.cur_stack >= env->prog->len)
10709 			return -E2BIG;
10710 		insn_stack[env->cfg.cur_stack++] = w;
10711 		return KEEP_EXPLORING;
10712 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10713 		if (loop_ok && env->bpf_capable)
10714 			return DONE_EXPLORING;
10715 		verbose_linfo(env, t, "%d: ", t);
10716 		verbose_linfo(env, w, "%d: ", w);
10717 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10718 		return -EINVAL;
10719 	} else if (insn_state[w] == EXPLORED) {
10720 		/* forward- or cross-edge */
10721 		insn_state[t] = DISCOVERED | e;
10722 	} else {
10723 		verbose(env, "insn state internal bug\n");
10724 		return -EFAULT;
10725 	}
10726 	return DONE_EXPLORING;
10727 }
10728 
10729 static int visit_func_call_insn(int t, int insn_cnt,
10730 				struct bpf_insn *insns,
10731 				struct bpf_verifier_env *env,
10732 				bool visit_callee)
10733 {
10734 	int ret;
10735 
10736 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10737 	if (ret)
10738 		return ret;
10739 
10740 	if (t + 1 < insn_cnt)
10741 		init_explored_state(env, t + 1);
10742 	if (visit_callee) {
10743 		init_explored_state(env, t);
10744 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10745 				/* It's ok to allow recursion from CFG point of
10746 				 * view. __check_func_call() will do the actual
10747 				 * check.
10748 				 */
10749 				bpf_pseudo_func(insns + t));
10750 	}
10751 	return ret;
10752 }
10753 
10754 /* Visits the instruction at index t and returns one of the following:
10755  *  < 0 - an error occurred
10756  *  DONE_EXPLORING - the instruction was fully explored
10757  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10758  */
10759 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10760 {
10761 	struct bpf_insn *insns = env->prog->insnsi;
10762 	int ret;
10763 
10764 	if (bpf_pseudo_func(insns + t))
10765 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10766 
10767 	/* All non-branch instructions have a single fall-through edge. */
10768 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10769 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10770 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10771 
10772 	switch (BPF_OP(insns[t].code)) {
10773 	case BPF_EXIT:
10774 		return DONE_EXPLORING;
10775 
10776 	case BPF_CALL:
10777 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10778 			/* Mark this call insn to trigger is_state_visited() check
10779 			 * before call itself is processed by __check_func_call().
10780 			 * Otherwise new async state will be pushed for further
10781 			 * exploration.
10782 			 */
10783 			init_explored_state(env, t);
10784 		return visit_func_call_insn(t, insn_cnt, insns, env,
10785 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10786 
10787 	case BPF_JA:
10788 		if (BPF_SRC(insns[t].code) != BPF_K)
10789 			return -EINVAL;
10790 
10791 		/* unconditional jump with single edge */
10792 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10793 				true);
10794 		if (ret)
10795 			return ret;
10796 
10797 		/* unconditional jmp is not a good pruning point,
10798 		 * but it's marked, since backtracking needs
10799 		 * to record jmp history in is_state_visited().
10800 		 */
10801 		init_explored_state(env, t + insns[t].off + 1);
10802 		/* tell verifier to check for equivalent states
10803 		 * after every call and jump
10804 		 */
10805 		if (t + 1 < insn_cnt)
10806 			init_explored_state(env, t + 1);
10807 
10808 		return ret;
10809 
10810 	default:
10811 		/* conditional jump with two edges */
10812 		init_explored_state(env, t);
10813 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10814 		if (ret)
10815 			return ret;
10816 
10817 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10818 	}
10819 }
10820 
10821 /* non-recursive depth-first-search to detect loops in BPF program
10822  * loop == back-edge in directed graph
10823  */
10824 static int check_cfg(struct bpf_verifier_env *env)
10825 {
10826 	int insn_cnt = env->prog->len;
10827 	int *insn_stack, *insn_state;
10828 	int ret = 0;
10829 	int i;
10830 
10831 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10832 	if (!insn_state)
10833 		return -ENOMEM;
10834 
10835 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10836 	if (!insn_stack) {
10837 		kvfree(insn_state);
10838 		return -ENOMEM;
10839 	}
10840 
10841 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10842 	insn_stack[0] = 0; /* 0 is the first instruction */
10843 	env->cfg.cur_stack = 1;
10844 
10845 	while (env->cfg.cur_stack > 0) {
10846 		int t = insn_stack[env->cfg.cur_stack - 1];
10847 
10848 		ret = visit_insn(t, insn_cnt, env);
10849 		switch (ret) {
10850 		case DONE_EXPLORING:
10851 			insn_state[t] = EXPLORED;
10852 			env->cfg.cur_stack--;
10853 			break;
10854 		case KEEP_EXPLORING:
10855 			break;
10856 		default:
10857 			if (ret > 0) {
10858 				verbose(env, "visit_insn internal bug\n");
10859 				ret = -EFAULT;
10860 			}
10861 			goto err_free;
10862 		}
10863 	}
10864 
10865 	if (env->cfg.cur_stack < 0) {
10866 		verbose(env, "pop stack internal bug\n");
10867 		ret = -EFAULT;
10868 		goto err_free;
10869 	}
10870 
10871 	for (i = 0; i < insn_cnt; i++) {
10872 		if (insn_state[i] != EXPLORED) {
10873 			verbose(env, "unreachable insn %d\n", i);
10874 			ret = -EINVAL;
10875 			goto err_free;
10876 		}
10877 	}
10878 	ret = 0; /* cfg looks good */
10879 
10880 err_free:
10881 	kvfree(insn_state);
10882 	kvfree(insn_stack);
10883 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
10884 	return ret;
10885 }
10886 
10887 static int check_abnormal_return(struct bpf_verifier_env *env)
10888 {
10889 	int i;
10890 
10891 	for (i = 1; i < env->subprog_cnt; i++) {
10892 		if (env->subprog_info[i].has_ld_abs) {
10893 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10894 			return -EINVAL;
10895 		}
10896 		if (env->subprog_info[i].has_tail_call) {
10897 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10898 			return -EINVAL;
10899 		}
10900 	}
10901 	return 0;
10902 }
10903 
10904 /* The minimum supported BTF func info size */
10905 #define MIN_BPF_FUNCINFO_SIZE	8
10906 #define MAX_FUNCINFO_REC_SIZE	252
10907 
10908 static int check_btf_func(struct bpf_verifier_env *env,
10909 			  const union bpf_attr *attr,
10910 			  bpfptr_t uattr)
10911 {
10912 	const struct btf_type *type, *func_proto, *ret_type;
10913 	u32 i, nfuncs, urec_size, min_size;
10914 	u32 krec_size = sizeof(struct bpf_func_info);
10915 	struct bpf_func_info *krecord;
10916 	struct bpf_func_info_aux *info_aux = NULL;
10917 	struct bpf_prog *prog;
10918 	const struct btf *btf;
10919 	bpfptr_t urecord;
10920 	u32 prev_offset = 0;
10921 	bool scalar_return;
10922 	int ret = -ENOMEM;
10923 
10924 	nfuncs = attr->func_info_cnt;
10925 	if (!nfuncs) {
10926 		if (check_abnormal_return(env))
10927 			return -EINVAL;
10928 		return 0;
10929 	}
10930 
10931 	if (nfuncs != env->subprog_cnt) {
10932 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10933 		return -EINVAL;
10934 	}
10935 
10936 	urec_size = attr->func_info_rec_size;
10937 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10938 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10939 	    urec_size % sizeof(u32)) {
10940 		verbose(env, "invalid func info rec size %u\n", urec_size);
10941 		return -EINVAL;
10942 	}
10943 
10944 	prog = env->prog;
10945 	btf = prog->aux->btf;
10946 
10947 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10948 	min_size = min_t(u32, krec_size, urec_size);
10949 
10950 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10951 	if (!krecord)
10952 		return -ENOMEM;
10953 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10954 	if (!info_aux)
10955 		goto err_free;
10956 
10957 	for (i = 0; i < nfuncs; i++) {
10958 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10959 		if (ret) {
10960 			if (ret == -E2BIG) {
10961 				verbose(env, "nonzero tailing record in func info");
10962 				/* set the size kernel expects so loader can zero
10963 				 * out the rest of the record.
10964 				 */
10965 				if (copy_to_bpfptr_offset(uattr,
10966 							  offsetof(union bpf_attr, func_info_rec_size),
10967 							  &min_size, sizeof(min_size)))
10968 					ret = -EFAULT;
10969 			}
10970 			goto err_free;
10971 		}
10972 
10973 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10974 			ret = -EFAULT;
10975 			goto err_free;
10976 		}
10977 
10978 		/* check insn_off */
10979 		ret = -EINVAL;
10980 		if (i == 0) {
10981 			if (krecord[i].insn_off) {
10982 				verbose(env,
10983 					"nonzero insn_off %u for the first func info record",
10984 					krecord[i].insn_off);
10985 				goto err_free;
10986 			}
10987 		} else if (krecord[i].insn_off <= prev_offset) {
10988 			verbose(env,
10989 				"same or smaller insn offset (%u) than previous func info record (%u)",
10990 				krecord[i].insn_off, prev_offset);
10991 			goto err_free;
10992 		}
10993 
10994 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10995 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10996 			goto err_free;
10997 		}
10998 
10999 		/* check type_id */
11000 		type = btf_type_by_id(btf, krecord[i].type_id);
11001 		if (!type || !btf_type_is_func(type)) {
11002 			verbose(env, "invalid type id %d in func info",
11003 				krecord[i].type_id);
11004 			goto err_free;
11005 		}
11006 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11007 
11008 		func_proto = btf_type_by_id(btf, type->type);
11009 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11010 			/* btf_func_check() already verified it during BTF load */
11011 			goto err_free;
11012 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11013 		scalar_return =
11014 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11015 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11016 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11017 			goto err_free;
11018 		}
11019 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11020 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11021 			goto err_free;
11022 		}
11023 
11024 		prev_offset = krecord[i].insn_off;
11025 		bpfptr_add(&urecord, urec_size);
11026 	}
11027 
11028 	prog->aux->func_info = krecord;
11029 	prog->aux->func_info_cnt = nfuncs;
11030 	prog->aux->func_info_aux = info_aux;
11031 	return 0;
11032 
11033 err_free:
11034 	kvfree(krecord);
11035 	kfree(info_aux);
11036 	return ret;
11037 }
11038 
11039 static void adjust_btf_func(struct bpf_verifier_env *env)
11040 {
11041 	struct bpf_prog_aux *aux = env->prog->aux;
11042 	int i;
11043 
11044 	if (!aux->func_info)
11045 		return;
11046 
11047 	for (i = 0; i < env->subprog_cnt; i++)
11048 		aux->func_info[i].insn_off = env->subprog_info[i].start;
11049 }
11050 
11051 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
11052 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
11053 
11054 static int check_btf_line(struct bpf_verifier_env *env,
11055 			  const union bpf_attr *attr,
11056 			  bpfptr_t uattr)
11057 {
11058 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11059 	struct bpf_subprog_info *sub;
11060 	struct bpf_line_info *linfo;
11061 	struct bpf_prog *prog;
11062 	const struct btf *btf;
11063 	bpfptr_t ulinfo;
11064 	int err;
11065 
11066 	nr_linfo = attr->line_info_cnt;
11067 	if (!nr_linfo)
11068 		return 0;
11069 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11070 		return -EINVAL;
11071 
11072 	rec_size = attr->line_info_rec_size;
11073 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11074 	    rec_size > MAX_LINEINFO_REC_SIZE ||
11075 	    rec_size & (sizeof(u32) - 1))
11076 		return -EINVAL;
11077 
11078 	/* Need to zero it in case the userspace may
11079 	 * pass in a smaller bpf_line_info object.
11080 	 */
11081 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11082 			 GFP_KERNEL | __GFP_NOWARN);
11083 	if (!linfo)
11084 		return -ENOMEM;
11085 
11086 	prog = env->prog;
11087 	btf = prog->aux->btf;
11088 
11089 	s = 0;
11090 	sub = env->subprog_info;
11091 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11092 	expected_size = sizeof(struct bpf_line_info);
11093 	ncopy = min_t(u32, expected_size, rec_size);
11094 	for (i = 0; i < nr_linfo; i++) {
11095 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11096 		if (err) {
11097 			if (err == -E2BIG) {
11098 				verbose(env, "nonzero tailing record in line_info");
11099 				if (copy_to_bpfptr_offset(uattr,
11100 							  offsetof(union bpf_attr, line_info_rec_size),
11101 							  &expected_size, sizeof(expected_size)))
11102 					err = -EFAULT;
11103 			}
11104 			goto err_free;
11105 		}
11106 
11107 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11108 			err = -EFAULT;
11109 			goto err_free;
11110 		}
11111 
11112 		/*
11113 		 * Check insn_off to ensure
11114 		 * 1) strictly increasing AND
11115 		 * 2) bounded by prog->len
11116 		 *
11117 		 * The linfo[0].insn_off == 0 check logically falls into
11118 		 * the later "missing bpf_line_info for func..." case
11119 		 * because the first linfo[0].insn_off must be the
11120 		 * first sub also and the first sub must have
11121 		 * subprog_info[0].start == 0.
11122 		 */
11123 		if ((i && linfo[i].insn_off <= prev_offset) ||
11124 		    linfo[i].insn_off >= prog->len) {
11125 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11126 				i, linfo[i].insn_off, prev_offset,
11127 				prog->len);
11128 			err = -EINVAL;
11129 			goto err_free;
11130 		}
11131 
11132 		if (!prog->insnsi[linfo[i].insn_off].code) {
11133 			verbose(env,
11134 				"Invalid insn code at line_info[%u].insn_off\n",
11135 				i);
11136 			err = -EINVAL;
11137 			goto err_free;
11138 		}
11139 
11140 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11141 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11142 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11143 			err = -EINVAL;
11144 			goto err_free;
11145 		}
11146 
11147 		if (s != env->subprog_cnt) {
11148 			if (linfo[i].insn_off == sub[s].start) {
11149 				sub[s].linfo_idx = i;
11150 				s++;
11151 			} else if (sub[s].start < linfo[i].insn_off) {
11152 				verbose(env, "missing bpf_line_info for func#%u\n", s);
11153 				err = -EINVAL;
11154 				goto err_free;
11155 			}
11156 		}
11157 
11158 		prev_offset = linfo[i].insn_off;
11159 		bpfptr_add(&ulinfo, rec_size);
11160 	}
11161 
11162 	if (s != env->subprog_cnt) {
11163 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11164 			env->subprog_cnt - s, s);
11165 		err = -EINVAL;
11166 		goto err_free;
11167 	}
11168 
11169 	prog->aux->linfo = linfo;
11170 	prog->aux->nr_linfo = nr_linfo;
11171 
11172 	return 0;
11173 
11174 err_free:
11175 	kvfree(linfo);
11176 	return err;
11177 }
11178 
11179 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
11180 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
11181 
11182 static int check_core_relo(struct bpf_verifier_env *env,
11183 			   const union bpf_attr *attr,
11184 			   bpfptr_t uattr)
11185 {
11186 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11187 	struct bpf_core_relo core_relo = {};
11188 	struct bpf_prog *prog = env->prog;
11189 	const struct btf *btf = prog->aux->btf;
11190 	struct bpf_core_ctx ctx = {
11191 		.log = &env->log,
11192 		.btf = btf,
11193 	};
11194 	bpfptr_t u_core_relo;
11195 	int err;
11196 
11197 	nr_core_relo = attr->core_relo_cnt;
11198 	if (!nr_core_relo)
11199 		return 0;
11200 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11201 		return -EINVAL;
11202 
11203 	rec_size = attr->core_relo_rec_size;
11204 	if (rec_size < MIN_CORE_RELO_SIZE ||
11205 	    rec_size > MAX_CORE_RELO_SIZE ||
11206 	    rec_size % sizeof(u32))
11207 		return -EINVAL;
11208 
11209 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11210 	expected_size = sizeof(struct bpf_core_relo);
11211 	ncopy = min_t(u32, expected_size, rec_size);
11212 
11213 	/* Unlike func_info and line_info, copy and apply each CO-RE
11214 	 * relocation record one at a time.
11215 	 */
11216 	for (i = 0; i < nr_core_relo; i++) {
11217 		/* future proofing when sizeof(bpf_core_relo) changes */
11218 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11219 		if (err) {
11220 			if (err == -E2BIG) {
11221 				verbose(env, "nonzero tailing record in core_relo");
11222 				if (copy_to_bpfptr_offset(uattr,
11223 							  offsetof(union bpf_attr, core_relo_rec_size),
11224 							  &expected_size, sizeof(expected_size)))
11225 					err = -EFAULT;
11226 			}
11227 			break;
11228 		}
11229 
11230 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11231 			err = -EFAULT;
11232 			break;
11233 		}
11234 
11235 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11236 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11237 				i, core_relo.insn_off, prog->len);
11238 			err = -EINVAL;
11239 			break;
11240 		}
11241 
11242 		err = bpf_core_apply(&ctx, &core_relo, i,
11243 				     &prog->insnsi[core_relo.insn_off / 8]);
11244 		if (err)
11245 			break;
11246 		bpfptr_add(&u_core_relo, rec_size);
11247 	}
11248 	return err;
11249 }
11250 
11251 static int check_btf_info(struct bpf_verifier_env *env,
11252 			  const union bpf_attr *attr,
11253 			  bpfptr_t uattr)
11254 {
11255 	struct btf *btf;
11256 	int err;
11257 
11258 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
11259 		if (check_abnormal_return(env))
11260 			return -EINVAL;
11261 		return 0;
11262 	}
11263 
11264 	btf = btf_get_by_fd(attr->prog_btf_fd);
11265 	if (IS_ERR(btf))
11266 		return PTR_ERR(btf);
11267 	if (btf_is_kernel(btf)) {
11268 		btf_put(btf);
11269 		return -EACCES;
11270 	}
11271 	env->prog->aux->btf = btf;
11272 
11273 	err = check_btf_func(env, attr, uattr);
11274 	if (err)
11275 		return err;
11276 
11277 	err = check_btf_line(env, attr, uattr);
11278 	if (err)
11279 		return err;
11280 
11281 	err = check_core_relo(env, attr, uattr);
11282 	if (err)
11283 		return err;
11284 
11285 	return 0;
11286 }
11287 
11288 /* check %cur's range satisfies %old's */
11289 static bool range_within(struct bpf_reg_state *old,
11290 			 struct bpf_reg_state *cur)
11291 {
11292 	return old->umin_value <= cur->umin_value &&
11293 	       old->umax_value >= cur->umax_value &&
11294 	       old->smin_value <= cur->smin_value &&
11295 	       old->smax_value >= cur->smax_value &&
11296 	       old->u32_min_value <= cur->u32_min_value &&
11297 	       old->u32_max_value >= cur->u32_max_value &&
11298 	       old->s32_min_value <= cur->s32_min_value &&
11299 	       old->s32_max_value >= cur->s32_max_value;
11300 }
11301 
11302 /* If in the old state two registers had the same id, then they need to have
11303  * the same id in the new state as well.  But that id could be different from
11304  * the old state, so we need to track the mapping from old to new ids.
11305  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11306  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11307  * regs with a different old id could still have new id 9, we don't care about
11308  * that.
11309  * So we look through our idmap to see if this old id has been seen before.  If
11310  * so, we require the new id to match; otherwise, we add the id pair to the map.
11311  */
11312 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11313 {
11314 	unsigned int i;
11315 
11316 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11317 		if (!idmap[i].old) {
11318 			/* Reached an empty slot; haven't seen this id before */
11319 			idmap[i].old = old_id;
11320 			idmap[i].cur = cur_id;
11321 			return true;
11322 		}
11323 		if (idmap[i].old == old_id)
11324 			return idmap[i].cur == cur_id;
11325 	}
11326 	/* We ran out of idmap slots, which should be impossible */
11327 	WARN_ON_ONCE(1);
11328 	return false;
11329 }
11330 
11331 static void clean_func_state(struct bpf_verifier_env *env,
11332 			     struct bpf_func_state *st)
11333 {
11334 	enum bpf_reg_liveness live;
11335 	int i, j;
11336 
11337 	for (i = 0; i < BPF_REG_FP; i++) {
11338 		live = st->regs[i].live;
11339 		/* liveness must not touch this register anymore */
11340 		st->regs[i].live |= REG_LIVE_DONE;
11341 		if (!(live & REG_LIVE_READ))
11342 			/* since the register is unused, clear its state
11343 			 * to make further comparison simpler
11344 			 */
11345 			__mark_reg_not_init(env, &st->regs[i]);
11346 	}
11347 
11348 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11349 		live = st->stack[i].spilled_ptr.live;
11350 		/* liveness must not touch this stack slot anymore */
11351 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11352 		if (!(live & REG_LIVE_READ)) {
11353 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11354 			for (j = 0; j < BPF_REG_SIZE; j++)
11355 				st->stack[i].slot_type[j] = STACK_INVALID;
11356 		}
11357 	}
11358 }
11359 
11360 static void clean_verifier_state(struct bpf_verifier_env *env,
11361 				 struct bpf_verifier_state *st)
11362 {
11363 	int i;
11364 
11365 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11366 		/* all regs in this state in all frames were already marked */
11367 		return;
11368 
11369 	for (i = 0; i <= st->curframe; i++)
11370 		clean_func_state(env, st->frame[i]);
11371 }
11372 
11373 /* the parentage chains form a tree.
11374  * the verifier states are added to state lists at given insn and
11375  * pushed into state stack for future exploration.
11376  * when the verifier reaches bpf_exit insn some of the verifer states
11377  * stored in the state lists have their final liveness state already,
11378  * but a lot of states will get revised from liveness point of view when
11379  * the verifier explores other branches.
11380  * Example:
11381  * 1: r0 = 1
11382  * 2: if r1 == 100 goto pc+1
11383  * 3: r0 = 2
11384  * 4: exit
11385  * when the verifier reaches exit insn the register r0 in the state list of
11386  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11387  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11388  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11389  *
11390  * Since the verifier pushes the branch states as it sees them while exploring
11391  * the program the condition of walking the branch instruction for the second
11392  * time means that all states below this branch were already explored and
11393  * their final liveness marks are already propagated.
11394  * Hence when the verifier completes the search of state list in is_state_visited()
11395  * we can call this clean_live_states() function to mark all liveness states
11396  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11397  * will not be used.
11398  * This function also clears the registers and stack for states that !READ
11399  * to simplify state merging.
11400  *
11401  * Important note here that walking the same branch instruction in the callee
11402  * doesn't meant that the states are DONE. The verifier has to compare
11403  * the callsites
11404  */
11405 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11406 			      struct bpf_verifier_state *cur)
11407 {
11408 	struct bpf_verifier_state_list *sl;
11409 	int i;
11410 
11411 	sl = *explored_state(env, insn);
11412 	while (sl) {
11413 		if (sl->state.branches)
11414 			goto next;
11415 		if (sl->state.insn_idx != insn ||
11416 		    sl->state.curframe != cur->curframe)
11417 			goto next;
11418 		for (i = 0; i <= cur->curframe; i++)
11419 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11420 				goto next;
11421 		clean_verifier_state(env, &sl->state);
11422 next:
11423 		sl = sl->next;
11424 	}
11425 }
11426 
11427 /* Returns true if (rold safe implies rcur safe) */
11428 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11429 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11430 {
11431 	bool equal;
11432 
11433 	if (!(rold->live & REG_LIVE_READ))
11434 		/* explored state didn't use this */
11435 		return true;
11436 
11437 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11438 
11439 	if (rold->type == PTR_TO_STACK)
11440 		/* two stack pointers are equal only if they're pointing to
11441 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
11442 		 */
11443 		return equal && rold->frameno == rcur->frameno;
11444 
11445 	if (equal)
11446 		return true;
11447 
11448 	if (rold->type == NOT_INIT)
11449 		/* explored state can't have used this */
11450 		return true;
11451 	if (rcur->type == NOT_INIT)
11452 		return false;
11453 	switch (base_type(rold->type)) {
11454 	case SCALAR_VALUE:
11455 		if (env->explore_alu_limits)
11456 			return false;
11457 		if (rcur->type == SCALAR_VALUE) {
11458 			if (!rold->precise && !rcur->precise)
11459 				return true;
11460 			/* new val must satisfy old val knowledge */
11461 			return range_within(rold, rcur) &&
11462 			       tnum_in(rold->var_off, rcur->var_off);
11463 		} else {
11464 			/* We're trying to use a pointer in place of a scalar.
11465 			 * Even if the scalar was unbounded, this could lead to
11466 			 * pointer leaks because scalars are allowed to leak
11467 			 * while pointers are not. We could make this safe in
11468 			 * special cases if root is calling us, but it's
11469 			 * probably not worth the hassle.
11470 			 */
11471 			return false;
11472 		}
11473 	case PTR_TO_MAP_KEY:
11474 	case PTR_TO_MAP_VALUE:
11475 		/* a PTR_TO_MAP_VALUE could be safe to use as a
11476 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11477 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11478 		 * checked, doing so could have affected others with the same
11479 		 * id, and we can't check for that because we lost the id when
11480 		 * we converted to a PTR_TO_MAP_VALUE.
11481 		 */
11482 		if (type_may_be_null(rold->type)) {
11483 			if (!type_may_be_null(rcur->type))
11484 				return false;
11485 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11486 				return false;
11487 			/* Check our ids match any regs they're supposed to */
11488 			return check_ids(rold->id, rcur->id, idmap);
11489 		}
11490 
11491 		/* If the new min/max/var_off satisfy the old ones and
11492 		 * everything else matches, we are OK.
11493 		 * 'id' is not compared, since it's only used for maps with
11494 		 * bpf_spin_lock inside map element and in such cases if
11495 		 * the rest of the prog is valid for one map element then
11496 		 * it's valid for all map elements regardless of the key
11497 		 * used in bpf_map_lookup()
11498 		 */
11499 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11500 		       range_within(rold, rcur) &&
11501 		       tnum_in(rold->var_off, rcur->var_off);
11502 	case PTR_TO_PACKET_META:
11503 	case PTR_TO_PACKET:
11504 		if (rcur->type != rold->type)
11505 			return false;
11506 		/* We must have at least as much range as the old ptr
11507 		 * did, so that any accesses which were safe before are
11508 		 * still safe.  This is true even if old range < old off,
11509 		 * since someone could have accessed through (ptr - k), or
11510 		 * even done ptr -= k in a register, to get a safe access.
11511 		 */
11512 		if (rold->range > rcur->range)
11513 			return false;
11514 		/* If the offsets don't match, we can't trust our alignment;
11515 		 * nor can we be sure that we won't fall out of range.
11516 		 */
11517 		if (rold->off != rcur->off)
11518 			return false;
11519 		/* id relations must be preserved */
11520 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11521 			return false;
11522 		/* new val must satisfy old val knowledge */
11523 		return range_within(rold, rcur) &&
11524 		       tnum_in(rold->var_off, rcur->var_off);
11525 	case PTR_TO_CTX:
11526 	case CONST_PTR_TO_MAP:
11527 	case PTR_TO_PACKET_END:
11528 	case PTR_TO_FLOW_KEYS:
11529 	case PTR_TO_SOCKET:
11530 	case PTR_TO_SOCK_COMMON:
11531 	case PTR_TO_TCP_SOCK:
11532 	case PTR_TO_XDP_SOCK:
11533 		/* Only valid matches are exact, which memcmp() above
11534 		 * would have accepted
11535 		 */
11536 	default:
11537 		/* Don't know what's going on, just say it's not safe */
11538 		return false;
11539 	}
11540 
11541 	/* Shouldn't get here; if we do, say it's not safe */
11542 	WARN_ON_ONCE(1);
11543 	return false;
11544 }
11545 
11546 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11547 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11548 {
11549 	int i, spi;
11550 
11551 	/* walk slots of the explored stack and ignore any additional
11552 	 * slots in the current stack, since explored(safe) state
11553 	 * didn't use them
11554 	 */
11555 	for (i = 0; i < old->allocated_stack; i++) {
11556 		spi = i / BPF_REG_SIZE;
11557 
11558 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11559 			i += BPF_REG_SIZE - 1;
11560 			/* explored state didn't use this */
11561 			continue;
11562 		}
11563 
11564 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11565 			continue;
11566 
11567 		/* explored stack has more populated slots than current stack
11568 		 * and these slots were used
11569 		 */
11570 		if (i >= cur->allocated_stack)
11571 			return false;
11572 
11573 		/* if old state was safe with misc data in the stack
11574 		 * it will be safe with zero-initialized stack.
11575 		 * The opposite is not true
11576 		 */
11577 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11578 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11579 			continue;
11580 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11581 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11582 			/* Ex: old explored (safe) state has STACK_SPILL in
11583 			 * this stack slot, but current has STACK_MISC ->
11584 			 * this verifier states are not equivalent,
11585 			 * return false to continue verification of this path
11586 			 */
11587 			return false;
11588 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11589 			continue;
11590 		if (!is_spilled_reg(&old->stack[spi]))
11591 			continue;
11592 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
11593 			     &cur->stack[spi].spilled_ptr, idmap))
11594 			/* when explored and current stack slot are both storing
11595 			 * spilled registers, check that stored pointers types
11596 			 * are the same as well.
11597 			 * Ex: explored safe path could have stored
11598 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11599 			 * but current path has stored:
11600 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11601 			 * such verifier states are not equivalent.
11602 			 * return false to continue verification of this path
11603 			 */
11604 			return false;
11605 	}
11606 	return true;
11607 }
11608 
11609 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11610 {
11611 	if (old->acquired_refs != cur->acquired_refs)
11612 		return false;
11613 	return !memcmp(old->refs, cur->refs,
11614 		       sizeof(*old->refs) * old->acquired_refs);
11615 }
11616 
11617 /* compare two verifier states
11618  *
11619  * all states stored in state_list are known to be valid, since
11620  * verifier reached 'bpf_exit' instruction through them
11621  *
11622  * this function is called when verifier exploring different branches of
11623  * execution popped from the state stack. If it sees an old state that has
11624  * more strict register state and more strict stack state then this execution
11625  * branch doesn't need to be explored further, since verifier already
11626  * concluded that more strict state leads to valid finish.
11627  *
11628  * Therefore two states are equivalent if register state is more conservative
11629  * and explored stack state is more conservative than the current one.
11630  * Example:
11631  *       explored                   current
11632  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11633  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11634  *
11635  * In other words if current stack state (one being explored) has more
11636  * valid slots than old one that already passed validation, it means
11637  * the verifier can stop exploring and conclude that current state is valid too
11638  *
11639  * Similarly with registers. If explored state has register type as invalid
11640  * whereas register type in current state is meaningful, it means that
11641  * the current state will reach 'bpf_exit' instruction safely
11642  */
11643 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11644 			      struct bpf_func_state *cur)
11645 {
11646 	int i;
11647 
11648 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11649 	for (i = 0; i < MAX_BPF_REG; i++)
11650 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11651 			     env->idmap_scratch))
11652 			return false;
11653 
11654 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11655 		return false;
11656 
11657 	if (!refsafe(old, cur))
11658 		return false;
11659 
11660 	return true;
11661 }
11662 
11663 static bool states_equal(struct bpf_verifier_env *env,
11664 			 struct bpf_verifier_state *old,
11665 			 struct bpf_verifier_state *cur)
11666 {
11667 	int i;
11668 
11669 	if (old->curframe != cur->curframe)
11670 		return false;
11671 
11672 	/* Verification state from speculative execution simulation
11673 	 * must never prune a non-speculative execution one.
11674 	 */
11675 	if (old->speculative && !cur->speculative)
11676 		return false;
11677 
11678 	if (old->active_spin_lock != cur->active_spin_lock)
11679 		return false;
11680 
11681 	/* for states to be equal callsites have to be the same
11682 	 * and all frame states need to be equivalent
11683 	 */
11684 	for (i = 0; i <= old->curframe; i++) {
11685 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11686 			return false;
11687 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11688 			return false;
11689 	}
11690 	return true;
11691 }
11692 
11693 /* Return 0 if no propagation happened. Return negative error code if error
11694  * happened. Otherwise, return the propagated bit.
11695  */
11696 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11697 				  struct bpf_reg_state *reg,
11698 				  struct bpf_reg_state *parent_reg)
11699 {
11700 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11701 	u8 flag = reg->live & REG_LIVE_READ;
11702 	int err;
11703 
11704 	/* When comes here, read flags of PARENT_REG or REG could be any of
11705 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11706 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11707 	 */
11708 	if (parent_flag == REG_LIVE_READ64 ||
11709 	    /* Or if there is no read flag from REG. */
11710 	    !flag ||
11711 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11712 	    parent_flag == flag)
11713 		return 0;
11714 
11715 	err = mark_reg_read(env, reg, parent_reg, flag);
11716 	if (err)
11717 		return err;
11718 
11719 	return flag;
11720 }
11721 
11722 /* A write screens off any subsequent reads; but write marks come from the
11723  * straight-line code between a state and its parent.  When we arrive at an
11724  * equivalent state (jump target or such) we didn't arrive by the straight-line
11725  * code, so read marks in the state must propagate to the parent regardless
11726  * of the state's write marks. That's what 'parent == state->parent' comparison
11727  * in mark_reg_read() is for.
11728  */
11729 static int propagate_liveness(struct bpf_verifier_env *env,
11730 			      const struct bpf_verifier_state *vstate,
11731 			      struct bpf_verifier_state *vparent)
11732 {
11733 	struct bpf_reg_state *state_reg, *parent_reg;
11734 	struct bpf_func_state *state, *parent;
11735 	int i, frame, err = 0;
11736 
11737 	if (vparent->curframe != vstate->curframe) {
11738 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11739 		     vparent->curframe, vstate->curframe);
11740 		return -EFAULT;
11741 	}
11742 	/* Propagate read liveness of registers... */
11743 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11744 	for (frame = 0; frame <= vstate->curframe; frame++) {
11745 		parent = vparent->frame[frame];
11746 		state = vstate->frame[frame];
11747 		parent_reg = parent->regs;
11748 		state_reg = state->regs;
11749 		/* We don't need to worry about FP liveness, it's read-only */
11750 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11751 			err = propagate_liveness_reg(env, &state_reg[i],
11752 						     &parent_reg[i]);
11753 			if (err < 0)
11754 				return err;
11755 			if (err == REG_LIVE_READ64)
11756 				mark_insn_zext(env, &parent_reg[i]);
11757 		}
11758 
11759 		/* Propagate stack slots. */
11760 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11761 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11762 			parent_reg = &parent->stack[i].spilled_ptr;
11763 			state_reg = &state->stack[i].spilled_ptr;
11764 			err = propagate_liveness_reg(env, state_reg,
11765 						     parent_reg);
11766 			if (err < 0)
11767 				return err;
11768 		}
11769 	}
11770 	return 0;
11771 }
11772 
11773 /* find precise scalars in the previous equivalent state and
11774  * propagate them into the current state
11775  */
11776 static int propagate_precision(struct bpf_verifier_env *env,
11777 			       const struct bpf_verifier_state *old)
11778 {
11779 	struct bpf_reg_state *state_reg;
11780 	struct bpf_func_state *state;
11781 	int i, err = 0;
11782 
11783 	state = old->frame[old->curframe];
11784 	state_reg = state->regs;
11785 	for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11786 		if (state_reg->type != SCALAR_VALUE ||
11787 		    !state_reg->precise)
11788 			continue;
11789 		if (env->log.level & BPF_LOG_LEVEL2)
11790 			verbose(env, "propagating r%d\n", i);
11791 		err = mark_chain_precision(env, i);
11792 		if (err < 0)
11793 			return err;
11794 	}
11795 
11796 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11797 		if (!is_spilled_reg(&state->stack[i]))
11798 			continue;
11799 		state_reg = &state->stack[i].spilled_ptr;
11800 		if (state_reg->type != SCALAR_VALUE ||
11801 		    !state_reg->precise)
11802 			continue;
11803 		if (env->log.level & BPF_LOG_LEVEL2)
11804 			verbose(env, "propagating fp%d\n",
11805 				(-i - 1) * BPF_REG_SIZE);
11806 		err = mark_chain_precision_stack(env, i);
11807 		if (err < 0)
11808 			return err;
11809 	}
11810 	return 0;
11811 }
11812 
11813 static bool states_maybe_looping(struct bpf_verifier_state *old,
11814 				 struct bpf_verifier_state *cur)
11815 {
11816 	struct bpf_func_state *fold, *fcur;
11817 	int i, fr = cur->curframe;
11818 
11819 	if (old->curframe != fr)
11820 		return false;
11821 
11822 	fold = old->frame[fr];
11823 	fcur = cur->frame[fr];
11824 	for (i = 0; i < MAX_BPF_REG; i++)
11825 		if (memcmp(&fold->regs[i], &fcur->regs[i],
11826 			   offsetof(struct bpf_reg_state, parent)))
11827 			return false;
11828 	return true;
11829 }
11830 
11831 
11832 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11833 {
11834 	struct bpf_verifier_state_list *new_sl;
11835 	struct bpf_verifier_state_list *sl, **pprev;
11836 	struct bpf_verifier_state *cur = env->cur_state, *new;
11837 	int i, j, err, states_cnt = 0;
11838 	bool add_new_state = env->test_state_freq ? true : false;
11839 
11840 	cur->last_insn_idx = env->prev_insn_idx;
11841 	if (!env->insn_aux_data[insn_idx].prune_point)
11842 		/* this 'insn_idx' instruction wasn't marked, so we will not
11843 		 * be doing state search here
11844 		 */
11845 		return 0;
11846 
11847 	/* bpf progs typically have pruning point every 4 instructions
11848 	 * http://vger.kernel.org/bpfconf2019.html#session-1
11849 	 * Do not add new state for future pruning if the verifier hasn't seen
11850 	 * at least 2 jumps and at least 8 instructions.
11851 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11852 	 * In tests that amounts to up to 50% reduction into total verifier
11853 	 * memory consumption and 20% verifier time speedup.
11854 	 */
11855 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11856 	    env->insn_processed - env->prev_insn_processed >= 8)
11857 		add_new_state = true;
11858 
11859 	pprev = explored_state(env, insn_idx);
11860 	sl = *pprev;
11861 
11862 	clean_live_states(env, insn_idx, cur);
11863 
11864 	while (sl) {
11865 		states_cnt++;
11866 		if (sl->state.insn_idx != insn_idx)
11867 			goto next;
11868 
11869 		if (sl->state.branches) {
11870 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11871 
11872 			if (frame->in_async_callback_fn &&
11873 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11874 				/* Different async_entry_cnt means that the verifier is
11875 				 * processing another entry into async callback.
11876 				 * Seeing the same state is not an indication of infinite
11877 				 * loop or infinite recursion.
11878 				 * But finding the same state doesn't mean that it's safe
11879 				 * to stop processing the current state. The previous state
11880 				 * hasn't yet reached bpf_exit, since state.branches > 0.
11881 				 * Checking in_async_callback_fn alone is not enough either.
11882 				 * Since the verifier still needs to catch infinite loops
11883 				 * inside async callbacks.
11884 				 */
11885 			} else if (states_maybe_looping(&sl->state, cur) &&
11886 				   states_equal(env, &sl->state, cur)) {
11887 				verbose_linfo(env, insn_idx, "; ");
11888 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11889 				return -EINVAL;
11890 			}
11891 			/* if the verifier is processing a loop, avoid adding new state
11892 			 * too often, since different loop iterations have distinct
11893 			 * states and may not help future pruning.
11894 			 * This threshold shouldn't be too low to make sure that
11895 			 * a loop with large bound will be rejected quickly.
11896 			 * The most abusive loop will be:
11897 			 * r1 += 1
11898 			 * if r1 < 1000000 goto pc-2
11899 			 * 1M insn_procssed limit / 100 == 10k peak states.
11900 			 * This threshold shouldn't be too high either, since states
11901 			 * at the end of the loop are likely to be useful in pruning.
11902 			 */
11903 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11904 			    env->insn_processed - env->prev_insn_processed < 100)
11905 				add_new_state = false;
11906 			goto miss;
11907 		}
11908 		if (states_equal(env, &sl->state, cur)) {
11909 			sl->hit_cnt++;
11910 			/* reached equivalent register/stack state,
11911 			 * prune the search.
11912 			 * Registers read by the continuation are read by us.
11913 			 * If we have any write marks in env->cur_state, they
11914 			 * will prevent corresponding reads in the continuation
11915 			 * from reaching our parent (an explored_state).  Our
11916 			 * own state will get the read marks recorded, but
11917 			 * they'll be immediately forgotten as we're pruning
11918 			 * this state and will pop a new one.
11919 			 */
11920 			err = propagate_liveness(env, &sl->state, cur);
11921 
11922 			/* if previous state reached the exit with precision and
11923 			 * current state is equivalent to it (except precsion marks)
11924 			 * the precision needs to be propagated back in
11925 			 * the current state.
11926 			 */
11927 			err = err ? : push_jmp_history(env, cur);
11928 			err = err ? : propagate_precision(env, &sl->state);
11929 			if (err)
11930 				return err;
11931 			return 1;
11932 		}
11933 miss:
11934 		/* when new state is not going to be added do not increase miss count.
11935 		 * Otherwise several loop iterations will remove the state
11936 		 * recorded earlier. The goal of these heuristics is to have
11937 		 * states from some iterations of the loop (some in the beginning
11938 		 * and some at the end) to help pruning.
11939 		 */
11940 		if (add_new_state)
11941 			sl->miss_cnt++;
11942 		/* heuristic to determine whether this state is beneficial
11943 		 * to keep checking from state equivalence point of view.
11944 		 * Higher numbers increase max_states_per_insn and verification time,
11945 		 * but do not meaningfully decrease insn_processed.
11946 		 */
11947 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11948 			/* the state is unlikely to be useful. Remove it to
11949 			 * speed up verification
11950 			 */
11951 			*pprev = sl->next;
11952 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11953 				u32 br = sl->state.branches;
11954 
11955 				WARN_ONCE(br,
11956 					  "BUG live_done but branches_to_explore %d\n",
11957 					  br);
11958 				free_verifier_state(&sl->state, false);
11959 				kfree(sl);
11960 				env->peak_states--;
11961 			} else {
11962 				/* cannot free this state, since parentage chain may
11963 				 * walk it later. Add it for free_list instead to
11964 				 * be freed at the end of verification
11965 				 */
11966 				sl->next = env->free_list;
11967 				env->free_list = sl;
11968 			}
11969 			sl = *pprev;
11970 			continue;
11971 		}
11972 next:
11973 		pprev = &sl->next;
11974 		sl = *pprev;
11975 	}
11976 
11977 	if (env->max_states_per_insn < states_cnt)
11978 		env->max_states_per_insn = states_cnt;
11979 
11980 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11981 		return push_jmp_history(env, cur);
11982 
11983 	if (!add_new_state)
11984 		return push_jmp_history(env, cur);
11985 
11986 	/* There were no equivalent states, remember the current one.
11987 	 * Technically the current state is not proven to be safe yet,
11988 	 * but it will either reach outer most bpf_exit (which means it's safe)
11989 	 * or it will be rejected. When there are no loops the verifier won't be
11990 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11991 	 * again on the way to bpf_exit.
11992 	 * When looping the sl->state.branches will be > 0 and this state
11993 	 * will not be considered for equivalence until branches == 0.
11994 	 */
11995 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11996 	if (!new_sl)
11997 		return -ENOMEM;
11998 	env->total_states++;
11999 	env->peak_states++;
12000 	env->prev_jmps_processed = env->jmps_processed;
12001 	env->prev_insn_processed = env->insn_processed;
12002 
12003 	/* add new state to the head of linked list */
12004 	new = &new_sl->state;
12005 	err = copy_verifier_state(new, cur);
12006 	if (err) {
12007 		free_verifier_state(new, false);
12008 		kfree(new_sl);
12009 		return err;
12010 	}
12011 	new->insn_idx = insn_idx;
12012 	WARN_ONCE(new->branches != 1,
12013 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12014 
12015 	cur->parent = new;
12016 	cur->first_insn_idx = insn_idx;
12017 	clear_jmp_history(cur);
12018 	new_sl->next = *explored_state(env, insn_idx);
12019 	*explored_state(env, insn_idx) = new_sl;
12020 	/* connect new state to parentage chain. Current frame needs all
12021 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
12022 	 * to the stack implicitly by JITs) so in callers' frames connect just
12023 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12024 	 * the state of the call instruction (with WRITTEN set), and r0 comes
12025 	 * from callee with its full parentage chain, anyway.
12026 	 */
12027 	/* clear write marks in current state: the writes we did are not writes
12028 	 * our child did, so they don't screen off its reads from us.
12029 	 * (There are no read marks in current state, because reads always mark
12030 	 * their parent and current state never has children yet.  Only
12031 	 * explored_states can get read marks.)
12032 	 */
12033 	for (j = 0; j <= cur->curframe; j++) {
12034 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12035 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12036 		for (i = 0; i < BPF_REG_FP; i++)
12037 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12038 	}
12039 
12040 	/* all stack frames are accessible from callee, clear them all */
12041 	for (j = 0; j <= cur->curframe; j++) {
12042 		struct bpf_func_state *frame = cur->frame[j];
12043 		struct bpf_func_state *newframe = new->frame[j];
12044 
12045 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12046 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12047 			frame->stack[i].spilled_ptr.parent =
12048 						&newframe->stack[i].spilled_ptr;
12049 		}
12050 	}
12051 	return 0;
12052 }
12053 
12054 /* Return true if it's OK to have the same insn return a different type. */
12055 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12056 {
12057 	switch (base_type(type)) {
12058 	case PTR_TO_CTX:
12059 	case PTR_TO_SOCKET:
12060 	case PTR_TO_SOCK_COMMON:
12061 	case PTR_TO_TCP_SOCK:
12062 	case PTR_TO_XDP_SOCK:
12063 	case PTR_TO_BTF_ID:
12064 		return false;
12065 	default:
12066 		return true;
12067 	}
12068 }
12069 
12070 /* If an instruction was previously used with particular pointer types, then we
12071  * need to be careful to avoid cases such as the below, where it may be ok
12072  * for one branch accessing the pointer, but not ok for the other branch:
12073  *
12074  * R1 = sock_ptr
12075  * goto X;
12076  * ...
12077  * R1 = some_other_valid_ptr;
12078  * goto X;
12079  * ...
12080  * R2 = *(u32 *)(R1 + 0);
12081  */
12082 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12083 {
12084 	return src != prev && (!reg_type_mismatch_ok(src) ||
12085 			       !reg_type_mismatch_ok(prev));
12086 }
12087 
12088 static int do_check(struct bpf_verifier_env *env)
12089 {
12090 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12091 	struct bpf_verifier_state *state = env->cur_state;
12092 	struct bpf_insn *insns = env->prog->insnsi;
12093 	struct bpf_reg_state *regs;
12094 	int insn_cnt = env->prog->len;
12095 	bool do_print_state = false;
12096 	int prev_insn_idx = -1;
12097 
12098 	for (;;) {
12099 		struct bpf_insn *insn;
12100 		u8 class;
12101 		int err;
12102 
12103 		env->prev_insn_idx = prev_insn_idx;
12104 		if (env->insn_idx >= insn_cnt) {
12105 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
12106 				env->insn_idx, insn_cnt);
12107 			return -EFAULT;
12108 		}
12109 
12110 		insn = &insns[env->insn_idx];
12111 		class = BPF_CLASS(insn->code);
12112 
12113 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12114 			verbose(env,
12115 				"BPF program is too large. Processed %d insn\n",
12116 				env->insn_processed);
12117 			return -E2BIG;
12118 		}
12119 
12120 		err = is_state_visited(env, env->insn_idx);
12121 		if (err < 0)
12122 			return err;
12123 		if (err == 1) {
12124 			/* found equivalent state, can prune the search */
12125 			if (env->log.level & BPF_LOG_LEVEL) {
12126 				if (do_print_state)
12127 					verbose(env, "\nfrom %d to %d%s: safe\n",
12128 						env->prev_insn_idx, env->insn_idx,
12129 						env->cur_state->speculative ?
12130 						" (speculative execution)" : "");
12131 				else
12132 					verbose(env, "%d: safe\n", env->insn_idx);
12133 			}
12134 			goto process_bpf_exit;
12135 		}
12136 
12137 		if (signal_pending(current))
12138 			return -EAGAIN;
12139 
12140 		if (need_resched())
12141 			cond_resched();
12142 
12143 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12144 			verbose(env, "\nfrom %d to %d%s:",
12145 				env->prev_insn_idx, env->insn_idx,
12146 				env->cur_state->speculative ?
12147 				" (speculative execution)" : "");
12148 			print_verifier_state(env, state->frame[state->curframe], true);
12149 			do_print_state = false;
12150 		}
12151 
12152 		if (env->log.level & BPF_LOG_LEVEL) {
12153 			const struct bpf_insn_cbs cbs = {
12154 				.cb_call	= disasm_kfunc_name,
12155 				.cb_print	= verbose,
12156 				.private_data	= env,
12157 			};
12158 
12159 			if (verifier_state_scratched(env))
12160 				print_insn_state(env, state->frame[state->curframe]);
12161 
12162 			verbose_linfo(env, env->insn_idx, "; ");
12163 			env->prev_log_len = env->log.len_used;
12164 			verbose(env, "%d: ", env->insn_idx);
12165 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12166 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12167 			env->prev_log_len = env->log.len_used;
12168 		}
12169 
12170 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
12171 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12172 							   env->prev_insn_idx);
12173 			if (err)
12174 				return err;
12175 		}
12176 
12177 		regs = cur_regs(env);
12178 		sanitize_mark_insn_seen(env);
12179 		prev_insn_idx = env->insn_idx;
12180 
12181 		if (class == BPF_ALU || class == BPF_ALU64) {
12182 			err = check_alu_op(env, insn);
12183 			if (err)
12184 				return err;
12185 
12186 		} else if (class == BPF_LDX) {
12187 			enum bpf_reg_type *prev_src_type, src_reg_type;
12188 
12189 			/* check for reserved fields is already done */
12190 
12191 			/* check src operand */
12192 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12193 			if (err)
12194 				return err;
12195 
12196 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12197 			if (err)
12198 				return err;
12199 
12200 			src_reg_type = regs[insn->src_reg].type;
12201 
12202 			/* check that memory (src_reg + off) is readable,
12203 			 * the state of dst_reg will be updated by this func
12204 			 */
12205 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
12206 					       insn->off, BPF_SIZE(insn->code),
12207 					       BPF_READ, insn->dst_reg, false);
12208 			if (err)
12209 				return err;
12210 
12211 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12212 
12213 			if (*prev_src_type == NOT_INIT) {
12214 				/* saw a valid insn
12215 				 * dst_reg = *(u32 *)(src_reg + off)
12216 				 * save type to validate intersecting paths
12217 				 */
12218 				*prev_src_type = src_reg_type;
12219 
12220 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12221 				/* ABuser program is trying to use the same insn
12222 				 * dst_reg = *(u32*) (src_reg + off)
12223 				 * with different pointer types:
12224 				 * src_reg == ctx in one branch and
12225 				 * src_reg == stack|map in some other branch.
12226 				 * Reject it.
12227 				 */
12228 				verbose(env, "same insn cannot be used with different pointers\n");
12229 				return -EINVAL;
12230 			}
12231 
12232 		} else if (class == BPF_STX) {
12233 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
12234 
12235 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12236 				err = check_atomic(env, env->insn_idx, insn);
12237 				if (err)
12238 					return err;
12239 				env->insn_idx++;
12240 				continue;
12241 			}
12242 
12243 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12244 				verbose(env, "BPF_STX uses reserved fields\n");
12245 				return -EINVAL;
12246 			}
12247 
12248 			/* check src1 operand */
12249 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12250 			if (err)
12251 				return err;
12252 			/* check src2 operand */
12253 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12254 			if (err)
12255 				return err;
12256 
12257 			dst_reg_type = regs[insn->dst_reg].type;
12258 
12259 			/* check that memory (dst_reg + off) is writeable */
12260 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12261 					       insn->off, BPF_SIZE(insn->code),
12262 					       BPF_WRITE, insn->src_reg, false);
12263 			if (err)
12264 				return err;
12265 
12266 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12267 
12268 			if (*prev_dst_type == NOT_INIT) {
12269 				*prev_dst_type = dst_reg_type;
12270 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12271 				verbose(env, "same insn cannot be used with different pointers\n");
12272 				return -EINVAL;
12273 			}
12274 
12275 		} else if (class == BPF_ST) {
12276 			if (BPF_MODE(insn->code) != BPF_MEM ||
12277 			    insn->src_reg != BPF_REG_0) {
12278 				verbose(env, "BPF_ST uses reserved fields\n");
12279 				return -EINVAL;
12280 			}
12281 			/* check src operand */
12282 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12283 			if (err)
12284 				return err;
12285 
12286 			if (is_ctx_reg(env, insn->dst_reg)) {
12287 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12288 					insn->dst_reg,
12289 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12290 				return -EACCES;
12291 			}
12292 
12293 			/* check that memory (dst_reg + off) is writeable */
12294 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12295 					       insn->off, BPF_SIZE(insn->code),
12296 					       BPF_WRITE, -1, false);
12297 			if (err)
12298 				return err;
12299 
12300 		} else if (class == BPF_JMP || class == BPF_JMP32) {
12301 			u8 opcode = BPF_OP(insn->code);
12302 
12303 			env->jmps_processed++;
12304 			if (opcode == BPF_CALL) {
12305 				if (BPF_SRC(insn->code) != BPF_K ||
12306 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12307 				     && insn->off != 0) ||
12308 				    (insn->src_reg != BPF_REG_0 &&
12309 				     insn->src_reg != BPF_PSEUDO_CALL &&
12310 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12311 				    insn->dst_reg != BPF_REG_0 ||
12312 				    class == BPF_JMP32) {
12313 					verbose(env, "BPF_CALL uses reserved fields\n");
12314 					return -EINVAL;
12315 				}
12316 
12317 				if (env->cur_state->active_spin_lock &&
12318 				    (insn->src_reg == BPF_PSEUDO_CALL ||
12319 				     insn->imm != BPF_FUNC_spin_unlock)) {
12320 					verbose(env, "function calls are not allowed while holding a lock\n");
12321 					return -EINVAL;
12322 				}
12323 				if (insn->src_reg == BPF_PSEUDO_CALL)
12324 					err = check_func_call(env, insn, &env->insn_idx);
12325 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12326 					err = check_kfunc_call(env, insn, &env->insn_idx);
12327 				else
12328 					err = check_helper_call(env, insn, &env->insn_idx);
12329 				if (err)
12330 					return err;
12331 			} else if (opcode == BPF_JA) {
12332 				if (BPF_SRC(insn->code) != BPF_K ||
12333 				    insn->imm != 0 ||
12334 				    insn->src_reg != BPF_REG_0 ||
12335 				    insn->dst_reg != BPF_REG_0 ||
12336 				    class == BPF_JMP32) {
12337 					verbose(env, "BPF_JA uses reserved fields\n");
12338 					return -EINVAL;
12339 				}
12340 
12341 				env->insn_idx += insn->off + 1;
12342 				continue;
12343 
12344 			} else if (opcode == BPF_EXIT) {
12345 				if (BPF_SRC(insn->code) != BPF_K ||
12346 				    insn->imm != 0 ||
12347 				    insn->src_reg != BPF_REG_0 ||
12348 				    insn->dst_reg != BPF_REG_0 ||
12349 				    class == BPF_JMP32) {
12350 					verbose(env, "BPF_EXIT uses reserved fields\n");
12351 					return -EINVAL;
12352 				}
12353 
12354 				if (env->cur_state->active_spin_lock) {
12355 					verbose(env, "bpf_spin_unlock is missing\n");
12356 					return -EINVAL;
12357 				}
12358 
12359 				/* We must do check_reference_leak here before
12360 				 * prepare_func_exit to handle the case when
12361 				 * state->curframe > 0, it may be a callback
12362 				 * function, for which reference_state must
12363 				 * match caller reference state when it exits.
12364 				 */
12365 				err = check_reference_leak(env);
12366 				if (err)
12367 					return err;
12368 
12369 				if (state->curframe) {
12370 					/* exit from nested function */
12371 					err = prepare_func_exit(env, &env->insn_idx);
12372 					if (err)
12373 						return err;
12374 					do_print_state = true;
12375 					continue;
12376 				}
12377 
12378 				err = check_return_code(env);
12379 				if (err)
12380 					return err;
12381 process_bpf_exit:
12382 				mark_verifier_state_scratched(env);
12383 				update_branch_counts(env, env->cur_state);
12384 				err = pop_stack(env, &prev_insn_idx,
12385 						&env->insn_idx, pop_log);
12386 				if (err < 0) {
12387 					if (err != -ENOENT)
12388 						return err;
12389 					break;
12390 				} else {
12391 					do_print_state = true;
12392 					continue;
12393 				}
12394 			} else {
12395 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
12396 				if (err)
12397 					return err;
12398 			}
12399 		} else if (class == BPF_LD) {
12400 			u8 mode = BPF_MODE(insn->code);
12401 
12402 			if (mode == BPF_ABS || mode == BPF_IND) {
12403 				err = check_ld_abs(env, insn);
12404 				if (err)
12405 					return err;
12406 
12407 			} else if (mode == BPF_IMM) {
12408 				err = check_ld_imm(env, insn);
12409 				if (err)
12410 					return err;
12411 
12412 				env->insn_idx++;
12413 				sanitize_mark_insn_seen(env);
12414 			} else {
12415 				verbose(env, "invalid BPF_LD mode\n");
12416 				return -EINVAL;
12417 			}
12418 		} else {
12419 			verbose(env, "unknown insn class %d\n", class);
12420 			return -EINVAL;
12421 		}
12422 
12423 		env->insn_idx++;
12424 	}
12425 
12426 	return 0;
12427 }
12428 
12429 static int find_btf_percpu_datasec(struct btf *btf)
12430 {
12431 	const struct btf_type *t;
12432 	const char *tname;
12433 	int i, n;
12434 
12435 	/*
12436 	 * Both vmlinux and module each have their own ".data..percpu"
12437 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12438 	 * types to look at only module's own BTF types.
12439 	 */
12440 	n = btf_nr_types(btf);
12441 	if (btf_is_module(btf))
12442 		i = btf_nr_types(btf_vmlinux);
12443 	else
12444 		i = 1;
12445 
12446 	for(; i < n; i++) {
12447 		t = btf_type_by_id(btf, i);
12448 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12449 			continue;
12450 
12451 		tname = btf_name_by_offset(btf, t->name_off);
12452 		if (!strcmp(tname, ".data..percpu"))
12453 			return i;
12454 	}
12455 
12456 	return -ENOENT;
12457 }
12458 
12459 /* replace pseudo btf_id with kernel symbol address */
12460 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12461 			       struct bpf_insn *insn,
12462 			       struct bpf_insn_aux_data *aux)
12463 {
12464 	const struct btf_var_secinfo *vsi;
12465 	const struct btf_type *datasec;
12466 	struct btf_mod_pair *btf_mod;
12467 	const struct btf_type *t;
12468 	const char *sym_name;
12469 	bool percpu = false;
12470 	u32 type, id = insn->imm;
12471 	struct btf *btf;
12472 	s32 datasec_id;
12473 	u64 addr;
12474 	int i, btf_fd, err;
12475 
12476 	btf_fd = insn[1].imm;
12477 	if (btf_fd) {
12478 		btf = btf_get_by_fd(btf_fd);
12479 		if (IS_ERR(btf)) {
12480 			verbose(env, "invalid module BTF object FD specified.\n");
12481 			return -EINVAL;
12482 		}
12483 	} else {
12484 		if (!btf_vmlinux) {
12485 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12486 			return -EINVAL;
12487 		}
12488 		btf = btf_vmlinux;
12489 		btf_get(btf);
12490 	}
12491 
12492 	t = btf_type_by_id(btf, id);
12493 	if (!t) {
12494 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12495 		err = -ENOENT;
12496 		goto err_put;
12497 	}
12498 
12499 	if (!btf_type_is_var(t)) {
12500 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12501 		err = -EINVAL;
12502 		goto err_put;
12503 	}
12504 
12505 	sym_name = btf_name_by_offset(btf, t->name_off);
12506 	addr = kallsyms_lookup_name(sym_name);
12507 	if (!addr) {
12508 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12509 			sym_name);
12510 		err = -ENOENT;
12511 		goto err_put;
12512 	}
12513 
12514 	datasec_id = find_btf_percpu_datasec(btf);
12515 	if (datasec_id > 0) {
12516 		datasec = btf_type_by_id(btf, datasec_id);
12517 		for_each_vsi(i, datasec, vsi) {
12518 			if (vsi->type == id) {
12519 				percpu = true;
12520 				break;
12521 			}
12522 		}
12523 	}
12524 
12525 	insn[0].imm = (u32)addr;
12526 	insn[1].imm = addr >> 32;
12527 
12528 	type = t->type;
12529 	t = btf_type_skip_modifiers(btf, type, NULL);
12530 	if (percpu) {
12531 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12532 		aux->btf_var.btf = btf;
12533 		aux->btf_var.btf_id = type;
12534 	} else if (!btf_type_is_struct(t)) {
12535 		const struct btf_type *ret;
12536 		const char *tname;
12537 		u32 tsize;
12538 
12539 		/* resolve the type size of ksym. */
12540 		ret = btf_resolve_size(btf, t, &tsize);
12541 		if (IS_ERR(ret)) {
12542 			tname = btf_name_by_offset(btf, t->name_off);
12543 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12544 				tname, PTR_ERR(ret));
12545 			err = -EINVAL;
12546 			goto err_put;
12547 		}
12548 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12549 		aux->btf_var.mem_size = tsize;
12550 	} else {
12551 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
12552 		aux->btf_var.btf = btf;
12553 		aux->btf_var.btf_id = type;
12554 	}
12555 
12556 	/* check whether we recorded this BTF (and maybe module) already */
12557 	for (i = 0; i < env->used_btf_cnt; i++) {
12558 		if (env->used_btfs[i].btf == btf) {
12559 			btf_put(btf);
12560 			return 0;
12561 		}
12562 	}
12563 
12564 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
12565 		err = -E2BIG;
12566 		goto err_put;
12567 	}
12568 
12569 	btf_mod = &env->used_btfs[env->used_btf_cnt];
12570 	btf_mod->btf = btf;
12571 	btf_mod->module = NULL;
12572 
12573 	/* if we reference variables from kernel module, bump its refcount */
12574 	if (btf_is_module(btf)) {
12575 		btf_mod->module = btf_try_get_module(btf);
12576 		if (!btf_mod->module) {
12577 			err = -ENXIO;
12578 			goto err_put;
12579 		}
12580 	}
12581 
12582 	env->used_btf_cnt++;
12583 
12584 	return 0;
12585 err_put:
12586 	btf_put(btf);
12587 	return err;
12588 }
12589 
12590 static bool is_tracing_prog_type(enum bpf_prog_type type)
12591 {
12592 	switch (type) {
12593 	case BPF_PROG_TYPE_KPROBE:
12594 	case BPF_PROG_TYPE_TRACEPOINT:
12595 	case BPF_PROG_TYPE_PERF_EVENT:
12596 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12597 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12598 		return true;
12599 	default:
12600 		return false;
12601 	}
12602 }
12603 
12604 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12605 					struct bpf_map *map,
12606 					struct bpf_prog *prog)
12607 
12608 {
12609 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12610 
12611 	if (map_value_has_spin_lock(map)) {
12612 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12613 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12614 			return -EINVAL;
12615 		}
12616 
12617 		if (is_tracing_prog_type(prog_type)) {
12618 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12619 			return -EINVAL;
12620 		}
12621 
12622 		if (prog->aux->sleepable) {
12623 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12624 			return -EINVAL;
12625 		}
12626 	}
12627 
12628 	if (map_value_has_timer(map)) {
12629 		if (is_tracing_prog_type(prog_type)) {
12630 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12631 			return -EINVAL;
12632 		}
12633 	}
12634 
12635 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12636 	    !bpf_offload_prog_map_match(prog, map)) {
12637 		verbose(env, "offload device mismatch between prog and map\n");
12638 		return -EINVAL;
12639 	}
12640 
12641 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12642 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12643 		return -EINVAL;
12644 	}
12645 
12646 	if (prog->aux->sleepable)
12647 		switch (map->map_type) {
12648 		case BPF_MAP_TYPE_HASH:
12649 		case BPF_MAP_TYPE_LRU_HASH:
12650 		case BPF_MAP_TYPE_ARRAY:
12651 		case BPF_MAP_TYPE_PERCPU_HASH:
12652 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12653 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12654 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12655 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12656 		case BPF_MAP_TYPE_RINGBUF:
12657 		case BPF_MAP_TYPE_INODE_STORAGE:
12658 		case BPF_MAP_TYPE_SK_STORAGE:
12659 		case BPF_MAP_TYPE_TASK_STORAGE:
12660 			break;
12661 		default:
12662 			verbose(env,
12663 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12664 			return -EINVAL;
12665 		}
12666 
12667 	return 0;
12668 }
12669 
12670 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12671 {
12672 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12673 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12674 }
12675 
12676 /* find and rewrite pseudo imm in ld_imm64 instructions:
12677  *
12678  * 1. if it accesses map FD, replace it with actual map pointer.
12679  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12680  *
12681  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12682  */
12683 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12684 {
12685 	struct bpf_insn *insn = env->prog->insnsi;
12686 	int insn_cnt = env->prog->len;
12687 	int i, j, err;
12688 
12689 	err = bpf_prog_calc_tag(env->prog);
12690 	if (err)
12691 		return err;
12692 
12693 	for (i = 0; i < insn_cnt; i++, insn++) {
12694 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12695 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12696 			verbose(env, "BPF_LDX uses reserved fields\n");
12697 			return -EINVAL;
12698 		}
12699 
12700 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12701 			struct bpf_insn_aux_data *aux;
12702 			struct bpf_map *map;
12703 			struct fd f;
12704 			u64 addr;
12705 			u32 fd;
12706 
12707 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12708 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12709 			    insn[1].off != 0) {
12710 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12711 				return -EINVAL;
12712 			}
12713 
12714 			if (insn[0].src_reg == 0)
12715 				/* valid generic load 64-bit imm */
12716 				goto next_insn;
12717 
12718 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12719 				aux = &env->insn_aux_data[i];
12720 				err = check_pseudo_btf_id(env, insn, aux);
12721 				if (err)
12722 					return err;
12723 				goto next_insn;
12724 			}
12725 
12726 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12727 				aux = &env->insn_aux_data[i];
12728 				aux->ptr_type = PTR_TO_FUNC;
12729 				goto next_insn;
12730 			}
12731 
12732 			/* In final convert_pseudo_ld_imm64() step, this is
12733 			 * converted into regular 64-bit imm load insn.
12734 			 */
12735 			switch (insn[0].src_reg) {
12736 			case BPF_PSEUDO_MAP_VALUE:
12737 			case BPF_PSEUDO_MAP_IDX_VALUE:
12738 				break;
12739 			case BPF_PSEUDO_MAP_FD:
12740 			case BPF_PSEUDO_MAP_IDX:
12741 				if (insn[1].imm == 0)
12742 					break;
12743 				fallthrough;
12744 			default:
12745 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12746 				return -EINVAL;
12747 			}
12748 
12749 			switch (insn[0].src_reg) {
12750 			case BPF_PSEUDO_MAP_IDX_VALUE:
12751 			case BPF_PSEUDO_MAP_IDX:
12752 				if (bpfptr_is_null(env->fd_array)) {
12753 					verbose(env, "fd_idx without fd_array is invalid\n");
12754 					return -EPROTO;
12755 				}
12756 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12757 							    insn[0].imm * sizeof(fd),
12758 							    sizeof(fd)))
12759 					return -EFAULT;
12760 				break;
12761 			default:
12762 				fd = insn[0].imm;
12763 				break;
12764 			}
12765 
12766 			f = fdget(fd);
12767 			map = __bpf_map_get(f);
12768 			if (IS_ERR(map)) {
12769 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12770 					insn[0].imm);
12771 				return PTR_ERR(map);
12772 			}
12773 
12774 			err = check_map_prog_compatibility(env, map, env->prog);
12775 			if (err) {
12776 				fdput(f);
12777 				return err;
12778 			}
12779 
12780 			aux = &env->insn_aux_data[i];
12781 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12782 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12783 				addr = (unsigned long)map;
12784 			} else {
12785 				u32 off = insn[1].imm;
12786 
12787 				if (off >= BPF_MAX_VAR_OFF) {
12788 					verbose(env, "direct value offset of %u is not allowed\n", off);
12789 					fdput(f);
12790 					return -EINVAL;
12791 				}
12792 
12793 				if (!map->ops->map_direct_value_addr) {
12794 					verbose(env, "no direct value access support for this map type\n");
12795 					fdput(f);
12796 					return -EINVAL;
12797 				}
12798 
12799 				err = map->ops->map_direct_value_addr(map, &addr, off);
12800 				if (err) {
12801 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12802 						map->value_size, off);
12803 					fdput(f);
12804 					return err;
12805 				}
12806 
12807 				aux->map_off = off;
12808 				addr += off;
12809 			}
12810 
12811 			insn[0].imm = (u32)addr;
12812 			insn[1].imm = addr >> 32;
12813 
12814 			/* check whether we recorded this map already */
12815 			for (j = 0; j < env->used_map_cnt; j++) {
12816 				if (env->used_maps[j] == map) {
12817 					aux->map_index = j;
12818 					fdput(f);
12819 					goto next_insn;
12820 				}
12821 			}
12822 
12823 			if (env->used_map_cnt >= MAX_USED_MAPS) {
12824 				fdput(f);
12825 				return -E2BIG;
12826 			}
12827 
12828 			/* hold the map. If the program is rejected by verifier,
12829 			 * the map will be released by release_maps() or it
12830 			 * will be used by the valid program until it's unloaded
12831 			 * and all maps are released in free_used_maps()
12832 			 */
12833 			bpf_map_inc(map);
12834 
12835 			aux->map_index = env->used_map_cnt;
12836 			env->used_maps[env->used_map_cnt++] = map;
12837 
12838 			if (bpf_map_is_cgroup_storage(map) &&
12839 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
12840 				verbose(env, "only one cgroup storage of each type is allowed\n");
12841 				fdput(f);
12842 				return -EBUSY;
12843 			}
12844 
12845 			fdput(f);
12846 next_insn:
12847 			insn++;
12848 			i++;
12849 			continue;
12850 		}
12851 
12852 		/* Basic sanity check before we invest more work here. */
12853 		if (!bpf_opcode_in_insntable(insn->code)) {
12854 			verbose(env, "unknown opcode %02x\n", insn->code);
12855 			return -EINVAL;
12856 		}
12857 	}
12858 
12859 	/* now all pseudo BPF_LD_IMM64 instructions load valid
12860 	 * 'struct bpf_map *' into a register instead of user map_fd.
12861 	 * These pointers will be used later by verifier to validate map access.
12862 	 */
12863 	return 0;
12864 }
12865 
12866 /* drop refcnt of maps used by the rejected program */
12867 static void release_maps(struct bpf_verifier_env *env)
12868 {
12869 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
12870 			     env->used_map_cnt);
12871 }
12872 
12873 /* drop refcnt of maps used by the rejected program */
12874 static void release_btfs(struct bpf_verifier_env *env)
12875 {
12876 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12877 			     env->used_btf_cnt);
12878 }
12879 
12880 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12881 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12882 {
12883 	struct bpf_insn *insn = env->prog->insnsi;
12884 	int insn_cnt = env->prog->len;
12885 	int i;
12886 
12887 	for (i = 0; i < insn_cnt; i++, insn++) {
12888 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12889 			continue;
12890 		if (insn->src_reg == BPF_PSEUDO_FUNC)
12891 			continue;
12892 		insn->src_reg = 0;
12893 	}
12894 }
12895 
12896 /* single env->prog->insni[off] instruction was replaced with the range
12897  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12898  * [0, off) and [off, end) to new locations, so the patched range stays zero
12899  */
12900 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12901 				 struct bpf_insn_aux_data *new_data,
12902 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
12903 {
12904 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12905 	struct bpf_insn *insn = new_prog->insnsi;
12906 	u32 old_seen = old_data[off].seen;
12907 	u32 prog_len;
12908 	int i;
12909 
12910 	/* aux info at OFF always needs adjustment, no matter fast path
12911 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12912 	 * original insn at old prog.
12913 	 */
12914 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12915 
12916 	if (cnt == 1)
12917 		return;
12918 	prog_len = new_prog->len;
12919 
12920 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12921 	memcpy(new_data + off + cnt - 1, old_data + off,
12922 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12923 	for (i = off; i < off + cnt - 1; i++) {
12924 		/* Expand insni[off]'s seen count to the patched range. */
12925 		new_data[i].seen = old_seen;
12926 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
12927 	}
12928 	env->insn_aux_data = new_data;
12929 	vfree(old_data);
12930 }
12931 
12932 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12933 {
12934 	int i;
12935 
12936 	if (len == 1)
12937 		return;
12938 	/* NOTE: fake 'exit' subprog should be updated as well. */
12939 	for (i = 0; i <= env->subprog_cnt; i++) {
12940 		if (env->subprog_info[i].start <= off)
12941 			continue;
12942 		env->subprog_info[i].start += len - 1;
12943 	}
12944 }
12945 
12946 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12947 {
12948 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12949 	int i, sz = prog->aux->size_poke_tab;
12950 	struct bpf_jit_poke_descriptor *desc;
12951 
12952 	for (i = 0; i < sz; i++) {
12953 		desc = &tab[i];
12954 		if (desc->insn_idx <= off)
12955 			continue;
12956 		desc->insn_idx += len - 1;
12957 	}
12958 }
12959 
12960 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12961 					    const struct bpf_insn *patch, u32 len)
12962 {
12963 	struct bpf_prog *new_prog;
12964 	struct bpf_insn_aux_data *new_data = NULL;
12965 
12966 	if (len > 1) {
12967 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12968 					      sizeof(struct bpf_insn_aux_data)));
12969 		if (!new_data)
12970 			return NULL;
12971 	}
12972 
12973 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12974 	if (IS_ERR(new_prog)) {
12975 		if (PTR_ERR(new_prog) == -ERANGE)
12976 			verbose(env,
12977 				"insn %d cannot be patched due to 16-bit range\n",
12978 				env->insn_aux_data[off].orig_idx);
12979 		vfree(new_data);
12980 		return NULL;
12981 	}
12982 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12983 	adjust_subprog_starts(env, off, len);
12984 	adjust_poke_descs(new_prog, off, len);
12985 	return new_prog;
12986 }
12987 
12988 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12989 					      u32 off, u32 cnt)
12990 {
12991 	int i, j;
12992 
12993 	/* find first prog starting at or after off (first to remove) */
12994 	for (i = 0; i < env->subprog_cnt; i++)
12995 		if (env->subprog_info[i].start >= off)
12996 			break;
12997 	/* find first prog starting at or after off + cnt (first to stay) */
12998 	for (j = i; j < env->subprog_cnt; j++)
12999 		if (env->subprog_info[j].start >= off + cnt)
13000 			break;
13001 	/* if j doesn't start exactly at off + cnt, we are just removing
13002 	 * the front of previous prog
13003 	 */
13004 	if (env->subprog_info[j].start != off + cnt)
13005 		j--;
13006 
13007 	if (j > i) {
13008 		struct bpf_prog_aux *aux = env->prog->aux;
13009 		int move;
13010 
13011 		/* move fake 'exit' subprog as well */
13012 		move = env->subprog_cnt + 1 - j;
13013 
13014 		memmove(env->subprog_info + i,
13015 			env->subprog_info + j,
13016 			sizeof(*env->subprog_info) * move);
13017 		env->subprog_cnt -= j - i;
13018 
13019 		/* remove func_info */
13020 		if (aux->func_info) {
13021 			move = aux->func_info_cnt - j;
13022 
13023 			memmove(aux->func_info + i,
13024 				aux->func_info + j,
13025 				sizeof(*aux->func_info) * move);
13026 			aux->func_info_cnt -= j - i;
13027 			/* func_info->insn_off is set after all code rewrites,
13028 			 * in adjust_btf_func() - no need to adjust
13029 			 */
13030 		}
13031 	} else {
13032 		/* convert i from "first prog to remove" to "first to adjust" */
13033 		if (env->subprog_info[i].start == off)
13034 			i++;
13035 	}
13036 
13037 	/* update fake 'exit' subprog as well */
13038 	for (; i <= env->subprog_cnt; i++)
13039 		env->subprog_info[i].start -= cnt;
13040 
13041 	return 0;
13042 }
13043 
13044 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13045 				      u32 cnt)
13046 {
13047 	struct bpf_prog *prog = env->prog;
13048 	u32 i, l_off, l_cnt, nr_linfo;
13049 	struct bpf_line_info *linfo;
13050 
13051 	nr_linfo = prog->aux->nr_linfo;
13052 	if (!nr_linfo)
13053 		return 0;
13054 
13055 	linfo = prog->aux->linfo;
13056 
13057 	/* find first line info to remove, count lines to be removed */
13058 	for (i = 0; i < nr_linfo; i++)
13059 		if (linfo[i].insn_off >= off)
13060 			break;
13061 
13062 	l_off = i;
13063 	l_cnt = 0;
13064 	for (; i < nr_linfo; i++)
13065 		if (linfo[i].insn_off < off + cnt)
13066 			l_cnt++;
13067 		else
13068 			break;
13069 
13070 	/* First live insn doesn't match first live linfo, it needs to "inherit"
13071 	 * last removed linfo.  prog is already modified, so prog->len == off
13072 	 * means no live instructions after (tail of the program was removed).
13073 	 */
13074 	if (prog->len != off && l_cnt &&
13075 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13076 		l_cnt--;
13077 		linfo[--i].insn_off = off + cnt;
13078 	}
13079 
13080 	/* remove the line info which refer to the removed instructions */
13081 	if (l_cnt) {
13082 		memmove(linfo + l_off, linfo + i,
13083 			sizeof(*linfo) * (nr_linfo - i));
13084 
13085 		prog->aux->nr_linfo -= l_cnt;
13086 		nr_linfo = prog->aux->nr_linfo;
13087 	}
13088 
13089 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
13090 	for (i = l_off; i < nr_linfo; i++)
13091 		linfo[i].insn_off -= cnt;
13092 
13093 	/* fix up all subprogs (incl. 'exit') which start >= off */
13094 	for (i = 0; i <= env->subprog_cnt; i++)
13095 		if (env->subprog_info[i].linfo_idx > l_off) {
13096 			/* program may have started in the removed region but
13097 			 * may not be fully removed
13098 			 */
13099 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13100 				env->subprog_info[i].linfo_idx -= l_cnt;
13101 			else
13102 				env->subprog_info[i].linfo_idx = l_off;
13103 		}
13104 
13105 	return 0;
13106 }
13107 
13108 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13109 {
13110 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13111 	unsigned int orig_prog_len = env->prog->len;
13112 	int err;
13113 
13114 	if (bpf_prog_is_dev_bound(env->prog->aux))
13115 		bpf_prog_offload_remove_insns(env, off, cnt);
13116 
13117 	err = bpf_remove_insns(env->prog, off, cnt);
13118 	if (err)
13119 		return err;
13120 
13121 	err = adjust_subprog_starts_after_remove(env, off, cnt);
13122 	if (err)
13123 		return err;
13124 
13125 	err = bpf_adj_linfo_after_remove(env, off, cnt);
13126 	if (err)
13127 		return err;
13128 
13129 	memmove(aux_data + off,	aux_data + off + cnt,
13130 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
13131 
13132 	return 0;
13133 }
13134 
13135 /* The verifier does more data flow analysis than llvm and will not
13136  * explore branches that are dead at run time. Malicious programs can
13137  * have dead code too. Therefore replace all dead at-run-time code
13138  * with 'ja -1'.
13139  *
13140  * Just nops are not optimal, e.g. if they would sit at the end of the
13141  * program and through another bug we would manage to jump there, then
13142  * we'd execute beyond program memory otherwise. Returning exception
13143  * code also wouldn't work since we can have subprogs where the dead
13144  * code could be located.
13145  */
13146 static void sanitize_dead_code(struct bpf_verifier_env *env)
13147 {
13148 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13149 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13150 	struct bpf_insn *insn = env->prog->insnsi;
13151 	const int insn_cnt = env->prog->len;
13152 	int i;
13153 
13154 	for (i = 0; i < insn_cnt; i++) {
13155 		if (aux_data[i].seen)
13156 			continue;
13157 		memcpy(insn + i, &trap, sizeof(trap));
13158 		aux_data[i].zext_dst = false;
13159 	}
13160 }
13161 
13162 static bool insn_is_cond_jump(u8 code)
13163 {
13164 	u8 op;
13165 
13166 	if (BPF_CLASS(code) == BPF_JMP32)
13167 		return true;
13168 
13169 	if (BPF_CLASS(code) != BPF_JMP)
13170 		return false;
13171 
13172 	op = BPF_OP(code);
13173 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13174 }
13175 
13176 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13177 {
13178 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13179 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13180 	struct bpf_insn *insn = env->prog->insnsi;
13181 	const int insn_cnt = env->prog->len;
13182 	int i;
13183 
13184 	for (i = 0; i < insn_cnt; i++, insn++) {
13185 		if (!insn_is_cond_jump(insn->code))
13186 			continue;
13187 
13188 		if (!aux_data[i + 1].seen)
13189 			ja.off = insn->off;
13190 		else if (!aux_data[i + 1 + insn->off].seen)
13191 			ja.off = 0;
13192 		else
13193 			continue;
13194 
13195 		if (bpf_prog_is_dev_bound(env->prog->aux))
13196 			bpf_prog_offload_replace_insn(env, i, &ja);
13197 
13198 		memcpy(insn, &ja, sizeof(ja));
13199 	}
13200 }
13201 
13202 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13203 {
13204 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13205 	int insn_cnt = env->prog->len;
13206 	int i, err;
13207 
13208 	for (i = 0; i < insn_cnt; i++) {
13209 		int j;
13210 
13211 		j = 0;
13212 		while (i + j < insn_cnt && !aux_data[i + j].seen)
13213 			j++;
13214 		if (!j)
13215 			continue;
13216 
13217 		err = verifier_remove_insns(env, i, j);
13218 		if (err)
13219 			return err;
13220 		insn_cnt = env->prog->len;
13221 	}
13222 
13223 	return 0;
13224 }
13225 
13226 static int opt_remove_nops(struct bpf_verifier_env *env)
13227 {
13228 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13229 	struct bpf_insn *insn = env->prog->insnsi;
13230 	int insn_cnt = env->prog->len;
13231 	int i, err;
13232 
13233 	for (i = 0; i < insn_cnt; i++) {
13234 		if (memcmp(&insn[i], &ja, sizeof(ja)))
13235 			continue;
13236 
13237 		err = verifier_remove_insns(env, i, 1);
13238 		if (err)
13239 			return err;
13240 		insn_cnt--;
13241 		i--;
13242 	}
13243 
13244 	return 0;
13245 }
13246 
13247 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13248 					 const union bpf_attr *attr)
13249 {
13250 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13251 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
13252 	int i, patch_len, delta = 0, len = env->prog->len;
13253 	struct bpf_insn *insns = env->prog->insnsi;
13254 	struct bpf_prog *new_prog;
13255 	bool rnd_hi32;
13256 
13257 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13258 	zext_patch[1] = BPF_ZEXT_REG(0);
13259 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13260 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13261 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13262 	for (i = 0; i < len; i++) {
13263 		int adj_idx = i + delta;
13264 		struct bpf_insn insn;
13265 		int load_reg;
13266 
13267 		insn = insns[adj_idx];
13268 		load_reg = insn_def_regno(&insn);
13269 		if (!aux[adj_idx].zext_dst) {
13270 			u8 code, class;
13271 			u32 imm_rnd;
13272 
13273 			if (!rnd_hi32)
13274 				continue;
13275 
13276 			code = insn.code;
13277 			class = BPF_CLASS(code);
13278 			if (load_reg == -1)
13279 				continue;
13280 
13281 			/* NOTE: arg "reg" (the fourth one) is only used for
13282 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
13283 			 *       here.
13284 			 */
13285 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13286 				if (class == BPF_LD &&
13287 				    BPF_MODE(code) == BPF_IMM)
13288 					i++;
13289 				continue;
13290 			}
13291 
13292 			/* ctx load could be transformed into wider load. */
13293 			if (class == BPF_LDX &&
13294 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
13295 				continue;
13296 
13297 			imm_rnd = get_random_int();
13298 			rnd_hi32_patch[0] = insn;
13299 			rnd_hi32_patch[1].imm = imm_rnd;
13300 			rnd_hi32_patch[3].dst_reg = load_reg;
13301 			patch = rnd_hi32_patch;
13302 			patch_len = 4;
13303 			goto apply_patch_buffer;
13304 		}
13305 
13306 		/* Add in an zero-extend instruction if a) the JIT has requested
13307 		 * it or b) it's a CMPXCHG.
13308 		 *
13309 		 * The latter is because: BPF_CMPXCHG always loads a value into
13310 		 * R0, therefore always zero-extends. However some archs'
13311 		 * equivalent instruction only does this load when the
13312 		 * comparison is successful. This detail of CMPXCHG is
13313 		 * orthogonal to the general zero-extension behaviour of the
13314 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
13315 		 */
13316 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13317 			continue;
13318 
13319 		if (WARN_ON(load_reg == -1)) {
13320 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13321 			return -EFAULT;
13322 		}
13323 
13324 		zext_patch[0] = insn;
13325 		zext_patch[1].dst_reg = load_reg;
13326 		zext_patch[1].src_reg = load_reg;
13327 		patch = zext_patch;
13328 		patch_len = 2;
13329 apply_patch_buffer:
13330 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13331 		if (!new_prog)
13332 			return -ENOMEM;
13333 		env->prog = new_prog;
13334 		insns = new_prog->insnsi;
13335 		aux = env->insn_aux_data;
13336 		delta += patch_len - 1;
13337 	}
13338 
13339 	return 0;
13340 }
13341 
13342 /* convert load instructions that access fields of a context type into a
13343  * sequence of instructions that access fields of the underlying structure:
13344  *     struct __sk_buff    -> struct sk_buff
13345  *     struct bpf_sock_ops -> struct sock
13346  */
13347 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13348 {
13349 	const struct bpf_verifier_ops *ops = env->ops;
13350 	int i, cnt, size, ctx_field_size, delta = 0;
13351 	const int insn_cnt = env->prog->len;
13352 	struct bpf_insn insn_buf[16], *insn;
13353 	u32 target_size, size_default, off;
13354 	struct bpf_prog *new_prog;
13355 	enum bpf_access_type type;
13356 	bool is_narrower_load;
13357 
13358 	if (ops->gen_prologue || env->seen_direct_write) {
13359 		if (!ops->gen_prologue) {
13360 			verbose(env, "bpf verifier is misconfigured\n");
13361 			return -EINVAL;
13362 		}
13363 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13364 					env->prog);
13365 		if (cnt >= ARRAY_SIZE(insn_buf)) {
13366 			verbose(env, "bpf verifier is misconfigured\n");
13367 			return -EINVAL;
13368 		} else if (cnt) {
13369 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13370 			if (!new_prog)
13371 				return -ENOMEM;
13372 
13373 			env->prog = new_prog;
13374 			delta += cnt - 1;
13375 		}
13376 	}
13377 
13378 	if (bpf_prog_is_dev_bound(env->prog->aux))
13379 		return 0;
13380 
13381 	insn = env->prog->insnsi + delta;
13382 
13383 	for (i = 0; i < insn_cnt; i++, insn++) {
13384 		bpf_convert_ctx_access_t convert_ctx_access;
13385 		bool ctx_access;
13386 
13387 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13388 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13389 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13390 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13391 			type = BPF_READ;
13392 			ctx_access = true;
13393 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13394 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13395 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13396 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13397 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13398 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13399 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13400 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13401 			type = BPF_WRITE;
13402 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13403 		} else {
13404 			continue;
13405 		}
13406 
13407 		if (type == BPF_WRITE &&
13408 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
13409 			struct bpf_insn patch[] = {
13410 				*insn,
13411 				BPF_ST_NOSPEC(),
13412 			};
13413 
13414 			cnt = ARRAY_SIZE(patch);
13415 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13416 			if (!new_prog)
13417 				return -ENOMEM;
13418 
13419 			delta    += cnt - 1;
13420 			env->prog = new_prog;
13421 			insn      = new_prog->insnsi + i + delta;
13422 			continue;
13423 		}
13424 
13425 		if (!ctx_access)
13426 			continue;
13427 
13428 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13429 		case PTR_TO_CTX:
13430 			if (!ops->convert_ctx_access)
13431 				continue;
13432 			convert_ctx_access = ops->convert_ctx_access;
13433 			break;
13434 		case PTR_TO_SOCKET:
13435 		case PTR_TO_SOCK_COMMON:
13436 			convert_ctx_access = bpf_sock_convert_ctx_access;
13437 			break;
13438 		case PTR_TO_TCP_SOCK:
13439 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13440 			break;
13441 		case PTR_TO_XDP_SOCK:
13442 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13443 			break;
13444 		case PTR_TO_BTF_ID:
13445 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13446 			if (type == BPF_READ) {
13447 				insn->code = BPF_LDX | BPF_PROBE_MEM |
13448 					BPF_SIZE((insn)->code);
13449 				env->prog->aux->num_exentries++;
13450 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
13451 				verbose(env, "Writes through BTF pointers are not allowed\n");
13452 				return -EINVAL;
13453 			}
13454 			continue;
13455 		default:
13456 			continue;
13457 		}
13458 
13459 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13460 		size = BPF_LDST_BYTES(insn);
13461 
13462 		/* If the read access is a narrower load of the field,
13463 		 * convert to a 4/8-byte load, to minimum program type specific
13464 		 * convert_ctx_access changes. If conversion is successful,
13465 		 * we will apply proper mask to the result.
13466 		 */
13467 		is_narrower_load = size < ctx_field_size;
13468 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13469 		off = insn->off;
13470 		if (is_narrower_load) {
13471 			u8 size_code;
13472 
13473 			if (type == BPF_WRITE) {
13474 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13475 				return -EINVAL;
13476 			}
13477 
13478 			size_code = BPF_H;
13479 			if (ctx_field_size == 4)
13480 				size_code = BPF_W;
13481 			else if (ctx_field_size == 8)
13482 				size_code = BPF_DW;
13483 
13484 			insn->off = off & ~(size_default - 1);
13485 			insn->code = BPF_LDX | BPF_MEM | size_code;
13486 		}
13487 
13488 		target_size = 0;
13489 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13490 					 &target_size);
13491 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13492 		    (ctx_field_size && !target_size)) {
13493 			verbose(env, "bpf verifier is misconfigured\n");
13494 			return -EINVAL;
13495 		}
13496 
13497 		if (is_narrower_load && size < target_size) {
13498 			u8 shift = bpf_ctx_narrow_access_offset(
13499 				off, size, size_default) * 8;
13500 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13501 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13502 				return -EINVAL;
13503 			}
13504 			if (ctx_field_size <= 4) {
13505 				if (shift)
13506 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13507 									insn->dst_reg,
13508 									shift);
13509 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13510 								(1 << size * 8) - 1);
13511 			} else {
13512 				if (shift)
13513 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13514 									insn->dst_reg,
13515 									shift);
13516 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13517 								(1ULL << size * 8) - 1);
13518 			}
13519 		}
13520 
13521 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13522 		if (!new_prog)
13523 			return -ENOMEM;
13524 
13525 		delta += cnt - 1;
13526 
13527 		/* keep walking new program and skip insns we just inserted */
13528 		env->prog = new_prog;
13529 		insn      = new_prog->insnsi + i + delta;
13530 	}
13531 
13532 	return 0;
13533 }
13534 
13535 static int jit_subprogs(struct bpf_verifier_env *env)
13536 {
13537 	struct bpf_prog *prog = env->prog, **func, *tmp;
13538 	int i, j, subprog_start, subprog_end = 0, len, subprog;
13539 	struct bpf_map *map_ptr;
13540 	struct bpf_insn *insn;
13541 	void *old_bpf_func;
13542 	int err, num_exentries;
13543 
13544 	if (env->subprog_cnt <= 1)
13545 		return 0;
13546 
13547 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13548 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13549 			continue;
13550 
13551 		/* Upon error here we cannot fall back to interpreter but
13552 		 * need a hard reject of the program. Thus -EFAULT is
13553 		 * propagated in any case.
13554 		 */
13555 		subprog = find_subprog(env, i + insn->imm + 1);
13556 		if (subprog < 0) {
13557 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13558 				  i + insn->imm + 1);
13559 			return -EFAULT;
13560 		}
13561 		/* temporarily remember subprog id inside insn instead of
13562 		 * aux_data, since next loop will split up all insns into funcs
13563 		 */
13564 		insn->off = subprog;
13565 		/* remember original imm in case JIT fails and fallback
13566 		 * to interpreter will be needed
13567 		 */
13568 		env->insn_aux_data[i].call_imm = insn->imm;
13569 		/* point imm to __bpf_call_base+1 from JITs point of view */
13570 		insn->imm = 1;
13571 		if (bpf_pseudo_func(insn))
13572 			/* jit (e.g. x86_64) may emit fewer instructions
13573 			 * if it learns a u32 imm is the same as a u64 imm.
13574 			 * Force a non zero here.
13575 			 */
13576 			insn[1].imm = 1;
13577 	}
13578 
13579 	err = bpf_prog_alloc_jited_linfo(prog);
13580 	if (err)
13581 		goto out_undo_insn;
13582 
13583 	err = -ENOMEM;
13584 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13585 	if (!func)
13586 		goto out_undo_insn;
13587 
13588 	for (i = 0; i < env->subprog_cnt; i++) {
13589 		subprog_start = subprog_end;
13590 		subprog_end = env->subprog_info[i + 1].start;
13591 
13592 		len = subprog_end - subprog_start;
13593 		/* bpf_prog_run() doesn't call subprogs directly,
13594 		 * hence main prog stats include the runtime of subprogs.
13595 		 * subprogs don't have IDs and not reachable via prog_get_next_id
13596 		 * func[i]->stats will never be accessed and stays NULL
13597 		 */
13598 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13599 		if (!func[i])
13600 			goto out_free;
13601 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13602 		       len * sizeof(struct bpf_insn));
13603 		func[i]->type = prog->type;
13604 		func[i]->len = len;
13605 		if (bpf_prog_calc_tag(func[i]))
13606 			goto out_free;
13607 		func[i]->is_func = 1;
13608 		func[i]->aux->func_idx = i;
13609 		/* Below members will be freed only at prog->aux */
13610 		func[i]->aux->btf = prog->aux->btf;
13611 		func[i]->aux->func_info = prog->aux->func_info;
13612 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13613 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13614 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13615 
13616 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13617 			struct bpf_jit_poke_descriptor *poke;
13618 
13619 			poke = &prog->aux->poke_tab[j];
13620 			if (poke->insn_idx < subprog_end &&
13621 			    poke->insn_idx >= subprog_start)
13622 				poke->aux = func[i]->aux;
13623 		}
13624 
13625 		func[i]->aux->name[0] = 'F';
13626 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13627 		func[i]->jit_requested = 1;
13628 		func[i]->blinding_requested = prog->blinding_requested;
13629 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13630 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13631 		func[i]->aux->linfo = prog->aux->linfo;
13632 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13633 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13634 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13635 		num_exentries = 0;
13636 		insn = func[i]->insnsi;
13637 		for (j = 0; j < func[i]->len; j++, insn++) {
13638 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13639 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13640 				num_exentries++;
13641 		}
13642 		func[i]->aux->num_exentries = num_exentries;
13643 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13644 		func[i] = bpf_int_jit_compile(func[i]);
13645 		if (!func[i]->jited) {
13646 			err = -ENOTSUPP;
13647 			goto out_free;
13648 		}
13649 		cond_resched();
13650 	}
13651 
13652 	/* at this point all bpf functions were successfully JITed
13653 	 * now populate all bpf_calls with correct addresses and
13654 	 * run last pass of JIT
13655 	 */
13656 	for (i = 0; i < env->subprog_cnt; i++) {
13657 		insn = func[i]->insnsi;
13658 		for (j = 0; j < func[i]->len; j++, insn++) {
13659 			if (bpf_pseudo_func(insn)) {
13660 				subprog = insn->off;
13661 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13662 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13663 				continue;
13664 			}
13665 			if (!bpf_pseudo_call(insn))
13666 				continue;
13667 			subprog = insn->off;
13668 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13669 		}
13670 
13671 		/* we use the aux data to keep a list of the start addresses
13672 		 * of the JITed images for each function in the program
13673 		 *
13674 		 * for some architectures, such as powerpc64, the imm field
13675 		 * might not be large enough to hold the offset of the start
13676 		 * address of the callee's JITed image from __bpf_call_base
13677 		 *
13678 		 * in such cases, we can lookup the start address of a callee
13679 		 * by using its subprog id, available from the off field of
13680 		 * the call instruction, as an index for this list
13681 		 */
13682 		func[i]->aux->func = func;
13683 		func[i]->aux->func_cnt = env->subprog_cnt;
13684 	}
13685 	for (i = 0; i < env->subprog_cnt; i++) {
13686 		old_bpf_func = func[i]->bpf_func;
13687 		tmp = bpf_int_jit_compile(func[i]);
13688 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13689 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13690 			err = -ENOTSUPP;
13691 			goto out_free;
13692 		}
13693 		cond_resched();
13694 	}
13695 
13696 	/* finally lock prog and jit images for all functions and
13697 	 * populate kallsysm
13698 	 */
13699 	for (i = 0; i < env->subprog_cnt; i++) {
13700 		bpf_prog_lock_ro(func[i]);
13701 		bpf_prog_kallsyms_add(func[i]);
13702 	}
13703 
13704 	/* Last step: make now unused interpreter insns from main
13705 	 * prog consistent for later dump requests, so they can
13706 	 * later look the same as if they were interpreted only.
13707 	 */
13708 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13709 		if (bpf_pseudo_func(insn)) {
13710 			insn[0].imm = env->insn_aux_data[i].call_imm;
13711 			insn[1].imm = insn->off;
13712 			insn->off = 0;
13713 			continue;
13714 		}
13715 		if (!bpf_pseudo_call(insn))
13716 			continue;
13717 		insn->off = env->insn_aux_data[i].call_imm;
13718 		subprog = find_subprog(env, i + insn->off + 1);
13719 		insn->imm = subprog;
13720 	}
13721 
13722 	prog->jited = 1;
13723 	prog->bpf_func = func[0]->bpf_func;
13724 	prog->jited_len = func[0]->jited_len;
13725 	prog->aux->func = func;
13726 	prog->aux->func_cnt = env->subprog_cnt;
13727 	bpf_prog_jit_attempt_done(prog);
13728 	return 0;
13729 out_free:
13730 	/* We failed JIT'ing, so at this point we need to unregister poke
13731 	 * descriptors from subprogs, so that kernel is not attempting to
13732 	 * patch it anymore as we're freeing the subprog JIT memory.
13733 	 */
13734 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13735 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13736 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13737 	}
13738 	/* At this point we're guaranteed that poke descriptors are not
13739 	 * live anymore. We can just unlink its descriptor table as it's
13740 	 * released with the main prog.
13741 	 */
13742 	for (i = 0; i < env->subprog_cnt; i++) {
13743 		if (!func[i])
13744 			continue;
13745 		func[i]->aux->poke_tab = NULL;
13746 		bpf_jit_free(func[i]);
13747 	}
13748 	kfree(func);
13749 out_undo_insn:
13750 	/* cleanup main prog to be interpreted */
13751 	prog->jit_requested = 0;
13752 	prog->blinding_requested = 0;
13753 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13754 		if (!bpf_pseudo_call(insn))
13755 			continue;
13756 		insn->off = 0;
13757 		insn->imm = env->insn_aux_data[i].call_imm;
13758 	}
13759 	bpf_prog_jit_attempt_done(prog);
13760 	return err;
13761 }
13762 
13763 static int fixup_call_args(struct bpf_verifier_env *env)
13764 {
13765 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13766 	struct bpf_prog *prog = env->prog;
13767 	struct bpf_insn *insn = prog->insnsi;
13768 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13769 	int i, depth;
13770 #endif
13771 	int err = 0;
13772 
13773 	if (env->prog->jit_requested &&
13774 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13775 		err = jit_subprogs(env);
13776 		if (err == 0)
13777 			return 0;
13778 		if (err == -EFAULT)
13779 			return err;
13780 	}
13781 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13782 	if (has_kfunc_call) {
13783 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13784 		return -EINVAL;
13785 	}
13786 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13787 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13788 		 * have to be rejected, since interpreter doesn't support them yet.
13789 		 */
13790 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13791 		return -EINVAL;
13792 	}
13793 	for (i = 0; i < prog->len; i++, insn++) {
13794 		if (bpf_pseudo_func(insn)) {
13795 			/* When JIT fails the progs with callback calls
13796 			 * have to be rejected, since interpreter doesn't support them yet.
13797 			 */
13798 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
13799 			return -EINVAL;
13800 		}
13801 
13802 		if (!bpf_pseudo_call(insn))
13803 			continue;
13804 		depth = get_callee_stack_depth(env, insn, i);
13805 		if (depth < 0)
13806 			return depth;
13807 		bpf_patch_call_args(insn, depth);
13808 	}
13809 	err = 0;
13810 #endif
13811 	return err;
13812 }
13813 
13814 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13815 			    struct bpf_insn *insn)
13816 {
13817 	const struct bpf_kfunc_desc *desc;
13818 
13819 	if (!insn->imm) {
13820 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13821 		return -EINVAL;
13822 	}
13823 
13824 	/* insn->imm has the btf func_id. Replace it with
13825 	 * an address (relative to __bpf_base_call).
13826 	 */
13827 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13828 	if (!desc) {
13829 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13830 			insn->imm);
13831 		return -EFAULT;
13832 	}
13833 
13834 	insn->imm = desc->imm;
13835 
13836 	return 0;
13837 }
13838 
13839 /* Do various post-verification rewrites in a single program pass.
13840  * These rewrites simplify JIT and interpreter implementations.
13841  */
13842 static int do_misc_fixups(struct bpf_verifier_env *env)
13843 {
13844 	struct bpf_prog *prog = env->prog;
13845 	enum bpf_attach_type eatype = prog->expected_attach_type;
13846 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13847 	struct bpf_insn *insn = prog->insnsi;
13848 	const struct bpf_func_proto *fn;
13849 	const int insn_cnt = prog->len;
13850 	const struct bpf_map_ops *ops;
13851 	struct bpf_insn_aux_data *aux;
13852 	struct bpf_insn insn_buf[16];
13853 	struct bpf_prog *new_prog;
13854 	struct bpf_map *map_ptr;
13855 	int i, ret, cnt, delta = 0;
13856 
13857 	for (i = 0; i < insn_cnt; i++, insn++) {
13858 		/* Make divide-by-zero exceptions impossible. */
13859 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13860 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13861 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13862 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13863 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13864 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13865 			struct bpf_insn *patchlet;
13866 			struct bpf_insn chk_and_div[] = {
13867 				/* [R,W]x div 0 -> 0 */
13868 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13869 					     BPF_JNE | BPF_K, insn->src_reg,
13870 					     0, 2, 0),
13871 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13872 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13873 				*insn,
13874 			};
13875 			struct bpf_insn chk_and_mod[] = {
13876 				/* [R,W]x mod 0 -> [R,W]x */
13877 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13878 					     BPF_JEQ | BPF_K, insn->src_reg,
13879 					     0, 1 + (is64 ? 0 : 1), 0),
13880 				*insn,
13881 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13882 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13883 			};
13884 
13885 			patchlet = isdiv ? chk_and_div : chk_and_mod;
13886 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13887 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13888 
13889 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13890 			if (!new_prog)
13891 				return -ENOMEM;
13892 
13893 			delta    += cnt - 1;
13894 			env->prog = prog = new_prog;
13895 			insn      = new_prog->insnsi + i + delta;
13896 			continue;
13897 		}
13898 
13899 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13900 		if (BPF_CLASS(insn->code) == BPF_LD &&
13901 		    (BPF_MODE(insn->code) == BPF_ABS ||
13902 		     BPF_MODE(insn->code) == BPF_IND)) {
13903 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
13904 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13905 				verbose(env, "bpf verifier is misconfigured\n");
13906 				return -EINVAL;
13907 			}
13908 
13909 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13910 			if (!new_prog)
13911 				return -ENOMEM;
13912 
13913 			delta    += cnt - 1;
13914 			env->prog = prog = new_prog;
13915 			insn      = new_prog->insnsi + i + delta;
13916 			continue;
13917 		}
13918 
13919 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
13920 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13921 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13922 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13923 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13924 			struct bpf_insn *patch = &insn_buf[0];
13925 			bool issrc, isneg, isimm;
13926 			u32 off_reg;
13927 
13928 			aux = &env->insn_aux_data[i + delta];
13929 			if (!aux->alu_state ||
13930 			    aux->alu_state == BPF_ALU_NON_POINTER)
13931 				continue;
13932 
13933 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13934 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13935 				BPF_ALU_SANITIZE_SRC;
13936 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13937 
13938 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
13939 			if (isimm) {
13940 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13941 			} else {
13942 				if (isneg)
13943 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13944 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13945 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13946 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13947 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13948 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13949 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13950 			}
13951 			if (!issrc)
13952 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13953 			insn->src_reg = BPF_REG_AX;
13954 			if (isneg)
13955 				insn->code = insn->code == code_add ?
13956 					     code_sub : code_add;
13957 			*patch++ = *insn;
13958 			if (issrc && isneg && !isimm)
13959 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13960 			cnt = patch - insn_buf;
13961 
13962 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13963 			if (!new_prog)
13964 				return -ENOMEM;
13965 
13966 			delta    += cnt - 1;
13967 			env->prog = prog = new_prog;
13968 			insn      = new_prog->insnsi + i + delta;
13969 			continue;
13970 		}
13971 
13972 		if (insn->code != (BPF_JMP | BPF_CALL))
13973 			continue;
13974 		if (insn->src_reg == BPF_PSEUDO_CALL)
13975 			continue;
13976 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13977 			ret = fixup_kfunc_call(env, insn);
13978 			if (ret)
13979 				return ret;
13980 			continue;
13981 		}
13982 
13983 		if (insn->imm == BPF_FUNC_get_route_realm)
13984 			prog->dst_needed = 1;
13985 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13986 			bpf_user_rnd_init_once();
13987 		if (insn->imm == BPF_FUNC_override_return)
13988 			prog->kprobe_override = 1;
13989 		if (insn->imm == BPF_FUNC_tail_call) {
13990 			/* If we tail call into other programs, we
13991 			 * cannot make any assumptions since they can
13992 			 * be replaced dynamically during runtime in
13993 			 * the program array.
13994 			 */
13995 			prog->cb_access = 1;
13996 			if (!allow_tail_call_in_subprogs(env))
13997 				prog->aux->stack_depth = MAX_BPF_STACK;
13998 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13999 
14000 			/* mark bpf_tail_call as different opcode to avoid
14001 			 * conditional branch in the interpreter for every normal
14002 			 * call and to prevent accidental JITing by JIT compiler
14003 			 * that doesn't support bpf_tail_call yet
14004 			 */
14005 			insn->imm = 0;
14006 			insn->code = BPF_JMP | BPF_TAIL_CALL;
14007 
14008 			aux = &env->insn_aux_data[i + delta];
14009 			if (env->bpf_capable && !prog->blinding_requested &&
14010 			    prog->jit_requested &&
14011 			    !bpf_map_key_poisoned(aux) &&
14012 			    !bpf_map_ptr_poisoned(aux) &&
14013 			    !bpf_map_ptr_unpriv(aux)) {
14014 				struct bpf_jit_poke_descriptor desc = {
14015 					.reason = BPF_POKE_REASON_TAIL_CALL,
14016 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14017 					.tail_call.key = bpf_map_key_immediate(aux),
14018 					.insn_idx = i + delta,
14019 				};
14020 
14021 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
14022 				if (ret < 0) {
14023 					verbose(env, "adding tail call poke descriptor failed\n");
14024 					return ret;
14025 				}
14026 
14027 				insn->imm = ret + 1;
14028 				continue;
14029 			}
14030 
14031 			if (!bpf_map_ptr_unpriv(aux))
14032 				continue;
14033 
14034 			/* instead of changing every JIT dealing with tail_call
14035 			 * emit two extra insns:
14036 			 * if (index >= max_entries) goto out;
14037 			 * index &= array->index_mask;
14038 			 * to avoid out-of-bounds cpu speculation
14039 			 */
14040 			if (bpf_map_ptr_poisoned(aux)) {
14041 				verbose(env, "tail_call abusing map_ptr\n");
14042 				return -EINVAL;
14043 			}
14044 
14045 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14046 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14047 						  map_ptr->max_entries, 2);
14048 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14049 						    container_of(map_ptr,
14050 								 struct bpf_array,
14051 								 map)->index_mask);
14052 			insn_buf[2] = *insn;
14053 			cnt = 3;
14054 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14055 			if (!new_prog)
14056 				return -ENOMEM;
14057 
14058 			delta    += cnt - 1;
14059 			env->prog = prog = new_prog;
14060 			insn      = new_prog->insnsi + i + delta;
14061 			continue;
14062 		}
14063 
14064 		if (insn->imm == BPF_FUNC_timer_set_callback) {
14065 			/* The verifier will process callback_fn as many times as necessary
14066 			 * with different maps and the register states prepared by
14067 			 * set_timer_callback_state will be accurate.
14068 			 *
14069 			 * The following use case is valid:
14070 			 *   map1 is shared by prog1, prog2, prog3.
14071 			 *   prog1 calls bpf_timer_init for some map1 elements
14072 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
14073 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
14074 			 *   prog3 calls bpf_timer_start for some map1 elements.
14075 			 *     Those that were not both bpf_timer_init-ed and
14076 			 *     bpf_timer_set_callback-ed will return -EINVAL.
14077 			 */
14078 			struct bpf_insn ld_addrs[2] = {
14079 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14080 			};
14081 
14082 			insn_buf[0] = ld_addrs[0];
14083 			insn_buf[1] = ld_addrs[1];
14084 			insn_buf[2] = *insn;
14085 			cnt = 3;
14086 
14087 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14088 			if (!new_prog)
14089 				return -ENOMEM;
14090 
14091 			delta    += cnt - 1;
14092 			env->prog = prog = new_prog;
14093 			insn      = new_prog->insnsi + i + delta;
14094 			goto patch_call_imm;
14095 		}
14096 
14097 		if (insn->imm == BPF_FUNC_task_storage_get ||
14098 		    insn->imm == BPF_FUNC_sk_storage_get ||
14099 		    insn->imm == BPF_FUNC_inode_storage_get) {
14100 			if (env->prog->aux->sleepable)
14101 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14102 			else
14103 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14104 			insn_buf[1] = *insn;
14105 			cnt = 2;
14106 
14107 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14108 			if (!new_prog)
14109 				return -ENOMEM;
14110 
14111 			delta += cnt - 1;
14112 			env->prog = prog = new_prog;
14113 			insn = new_prog->insnsi + i + delta;
14114 			goto patch_call_imm;
14115 		}
14116 
14117 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14118 		 * and other inlining handlers are currently limited to 64 bit
14119 		 * only.
14120 		 */
14121 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14122 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
14123 		     insn->imm == BPF_FUNC_map_update_elem ||
14124 		     insn->imm == BPF_FUNC_map_delete_elem ||
14125 		     insn->imm == BPF_FUNC_map_push_elem   ||
14126 		     insn->imm == BPF_FUNC_map_pop_elem    ||
14127 		     insn->imm == BPF_FUNC_map_peek_elem   ||
14128 		     insn->imm == BPF_FUNC_redirect_map    ||
14129 		     insn->imm == BPF_FUNC_for_each_map_elem ||
14130 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14131 			aux = &env->insn_aux_data[i + delta];
14132 			if (bpf_map_ptr_poisoned(aux))
14133 				goto patch_call_imm;
14134 
14135 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14136 			ops = map_ptr->ops;
14137 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
14138 			    ops->map_gen_lookup) {
14139 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14140 				if (cnt == -EOPNOTSUPP)
14141 					goto patch_map_ops_generic;
14142 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14143 					verbose(env, "bpf verifier is misconfigured\n");
14144 					return -EINVAL;
14145 				}
14146 
14147 				new_prog = bpf_patch_insn_data(env, i + delta,
14148 							       insn_buf, cnt);
14149 				if (!new_prog)
14150 					return -ENOMEM;
14151 
14152 				delta    += cnt - 1;
14153 				env->prog = prog = new_prog;
14154 				insn      = new_prog->insnsi + i + delta;
14155 				continue;
14156 			}
14157 
14158 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14159 				     (void *(*)(struct bpf_map *map, void *key))NULL));
14160 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14161 				     (int (*)(struct bpf_map *map, void *key))NULL));
14162 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14163 				     (int (*)(struct bpf_map *map, void *key, void *value,
14164 					      u64 flags))NULL));
14165 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14166 				     (int (*)(struct bpf_map *map, void *value,
14167 					      u64 flags))NULL));
14168 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14169 				     (int (*)(struct bpf_map *map, void *value))NULL));
14170 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14171 				     (int (*)(struct bpf_map *map, void *value))NULL));
14172 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
14173 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14174 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14175 				     (int (*)(struct bpf_map *map,
14176 					      bpf_callback_t callback_fn,
14177 					      void *callback_ctx,
14178 					      u64 flags))NULL));
14179 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14180 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14181 
14182 patch_map_ops_generic:
14183 			switch (insn->imm) {
14184 			case BPF_FUNC_map_lookup_elem:
14185 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14186 				continue;
14187 			case BPF_FUNC_map_update_elem:
14188 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14189 				continue;
14190 			case BPF_FUNC_map_delete_elem:
14191 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14192 				continue;
14193 			case BPF_FUNC_map_push_elem:
14194 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14195 				continue;
14196 			case BPF_FUNC_map_pop_elem:
14197 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14198 				continue;
14199 			case BPF_FUNC_map_peek_elem:
14200 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14201 				continue;
14202 			case BPF_FUNC_redirect_map:
14203 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
14204 				continue;
14205 			case BPF_FUNC_for_each_map_elem:
14206 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14207 				continue;
14208 			case BPF_FUNC_map_lookup_percpu_elem:
14209 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14210 				continue;
14211 			}
14212 
14213 			goto patch_call_imm;
14214 		}
14215 
14216 		/* Implement bpf_jiffies64 inline. */
14217 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14218 		    insn->imm == BPF_FUNC_jiffies64) {
14219 			struct bpf_insn ld_jiffies_addr[2] = {
14220 				BPF_LD_IMM64(BPF_REG_0,
14221 					     (unsigned long)&jiffies),
14222 			};
14223 
14224 			insn_buf[0] = ld_jiffies_addr[0];
14225 			insn_buf[1] = ld_jiffies_addr[1];
14226 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14227 						  BPF_REG_0, 0);
14228 			cnt = 3;
14229 
14230 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14231 						       cnt);
14232 			if (!new_prog)
14233 				return -ENOMEM;
14234 
14235 			delta    += cnt - 1;
14236 			env->prog = prog = new_prog;
14237 			insn      = new_prog->insnsi + i + delta;
14238 			continue;
14239 		}
14240 
14241 		/* Implement bpf_get_func_arg inline. */
14242 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14243 		    insn->imm == BPF_FUNC_get_func_arg) {
14244 			/* Load nr_args from ctx - 8 */
14245 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14246 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14247 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14248 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14249 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14250 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14251 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14252 			insn_buf[7] = BPF_JMP_A(1);
14253 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14254 			cnt = 9;
14255 
14256 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14257 			if (!new_prog)
14258 				return -ENOMEM;
14259 
14260 			delta    += cnt - 1;
14261 			env->prog = prog = new_prog;
14262 			insn      = new_prog->insnsi + i + delta;
14263 			continue;
14264 		}
14265 
14266 		/* Implement bpf_get_func_ret inline. */
14267 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14268 		    insn->imm == BPF_FUNC_get_func_ret) {
14269 			if (eatype == BPF_TRACE_FEXIT ||
14270 			    eatype == BPF_MODIFY_RETURN) {
14271 				/* Load nr_args from ctx - 8 */
14272 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14273 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14274 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14275 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14276 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14277 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14278 				cnt = 6;
14279 			} else {
14280 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14281 				cnt = 1;
14282 			}
14283 
14284 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14285 			if (!new_prog)
14286 				return -ENOMEM;
14287 
14288 			delta    += cnt - 1;
14289 			env->prog = prog = new_prog;
14290 			insn      = new_prog->insnsi + i + delta;
14291 			continue;
14292 		}
14293 
14294 		/* Implement get_func_arg_cnt inline. */
14295 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14296 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
14297 			/* Load nr_args from ctx - 8 */
14298 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14299 
14300 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14301 			if (!new_prog)
14302 				return -ENOMEM;
14303 
14304 			env->prog = prog = new_prog;
14305 			insn      = new_prog->insnsi + i + delta;
14306 			continue;
14307 		}
14308 
14309 		/* Implement bpf_get_func_ip inline. */
14310 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14311 		    insn->imm == BPF_FUNC_get_func_ip) {
14312 			/* Load IP address from ctx - 16 */
14313 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14314 
14315 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14316 			if (!new_prog)
14317 				return -ENOMEM;
14318 
14319 			env->prog = prog = new_prog;
14320 			insn      = new_prog->insnsi + i + delta;
14321 			continue;
14322 		}
14323 
14324 patch_call_imm:
14325 		fn = env->ops->get_func_proto(insn->imm, env->prog);
14326 		/* all functions that have prototype and verifier allowed
14327 		 * programs to call them, must be real in-kernel functions
14328 		 */
14329 		if (!fn->func) {
14330 			verbose(env,
14331 				"kernel subsystem misconfigured func %s#%d\n",
14332 				func_id_name(insn->imm), insn->imm);
14333 			return -EFAULT;
14334 		}
14335 		insn->imm = fn->func - __bpf_call_base;
14336 	}
14337 
14338 	/* Since poke tab is now finalized, publish aux to tracker. */
14339 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
14340 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
14341 		if (!map_ptr->ops->map_poke_track ||
14342 		    !map_ptr->ops->map_poke_untrack ||
14343 		    !map_ptr->ops->map_poke_run) {
14344 			verbose(env, "bpf verifier is misconfigured\n");
14345 			return -EINVAL;
14346 		}
14347 
14348 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14349 		if (ret < 0) {
14350 			verbose(env, "tracking tail call prog failed\n");
14351 			return ret;
14352 		}
14353 	}
14354 
14355 	sort_kfunc_descs_by_imm(env->prog);
14356 
14357 	return 0;
14358 }
14359 
14360 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14361 					int position,
14362 					s32 stack_base,
14363 					u32 callback_subprogno,
14364 					u32 *cnt)
14365 {
14366 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14367 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14368 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14369 	int reg_loop_max = BPF_REG_6;
14370 	int reg_loop_cnt = BPF_REG_7;
14371 	int reg_loop_ctx = BPF_REG_8;
14372 
14373 	struct bpf_prog *new_prog;
14374 	u32 callback_start;
14375 	u32 call_insn_offset;
14376 	s32 callback_offset;
14377 
14378 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
14379 	 * be careful to modify this code in sync.
14380 	 */
14381 	struct bpf_insn insn_buf[] = {
14382 		/* Return error and jump to the end of the patch if
14383 		 * expected number of iterations is too big.
14384 		 */
14385 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14386 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14387 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14388 		/* spill R6, R7, R8 to use these as loop vars */
14389 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14390 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14391 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14392 		/* initialize loop vars */
14393 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14394 		BPF_MOV32_IMM(reg_loop_cnt, 0),
14395 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14396 		/* loop header,
14397 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
14398 		 */
14399 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14400 		/* callback call,
14401 		 * correct callback offset would be set after patching
14402 		 */
14403 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14404 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14405 		BPF_CALL_REL(0),
14406 		/* increment loop counter */
14407 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14408 		/* jump to loop header if callback returned 0 */
14409 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14410 		/* return value of bpf_loop,
14411 		 * set R0 to the number of iterations
14412 		 */
14413 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14414 		/* restore original values of R6, R7, R8 */
14415 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14416 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14417 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14418 	};
14419 
14420 	*cnt = ARRAY_SIZE(insn_buf);
14421 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14422 	if (!new_prog)
14423 		return new_prog;
14424 
14425 	/* callback start is known only after patching */
14426 	callback_start = env->subprog_info[callback_subprogno].start;
14427 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14428 	call_insn_offset = position + 12;
14429 	callback_offset = callback_start - call_insn_offset - 1;
14430 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
14431 
14432 	return new_prog;
14433 }
14434 
14435 static bool is_bpf_loop_call(struct bpf_insn *insn)
14436 {
14437 	return insn->code == (BPF_JMP | BPF_CALL) &&
14438 		insn->src_reg == 0 &&
14439 		insn->imm == BPF_FUNC_loop;
14440 }
14441 
14442 /* For all sub-programs in the program (including main) check
14443  * insn_aux_data to see if there are bpf_loop calls that require
14444  * inlining. If such calls are found the calls are replaced with a
14445  * sequence of instructions produced by `inline_bpf_loop` function and
14446  * subprog stack_depth is increased by the size of 3 registers.
14447  * This stack space is used to spill values of the R6, R7, R8.  These
14448  * registers are used to store the loop bound, counter and context
14449  * variables.
14450  */
14451 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14452 {
14453 	struct bpf_subprog_info *subprogs = env->subprog_info;
14454 	int i, cur_subprog = 0, cnt, delta = 0;
14455 	struct bpf_insn *insn = env->prog->insnsi;
14456 	int insn_cnt = env->prog->len;
14457 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
14458 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14459 	u16 stack_depth_extra = 0;
14460 
14461 	for (i = 0; i < insn_cnt; i++, insn++) {
14462 		struct bpf_loop_inline_state *inline_state =
14463 			&env->insn_aux_data[i + delta].loop_inline_state;
14464 
14465 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14466 			struct bpf_prog *new_prog;
14467 
14468 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14469 			new_prog = inline_bpf_loop(env,
14470 						   i + delta,
14471 						   -(stack_depth + stack_depth_extra),
14472 						   inline_state->callback_subprogno,
14473 						   &cnt);
14474 			if (!new_prog)
14475 				return -ENOMEM;
14476 
14477 			delta     += cnt - 1;
14478 			env->prog  = new_prog;
14479 			insn       = new_prog->insnsi + i + delta;
14480 		}
14481 
14482 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14483 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
14484 			cur_subprog++;
14485 			stack_depth = subprogs[cur_subprog].stack_depth;
14486 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14487 			stack_depth_extra = 0;
14488 		}
14489 	}
14490 
14491 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14492 
14493 	return 0;
14494 }
14495 
14496 static void free_states(struct bpf_verifier_env *env)
14497 {
14498 	struct bpf_verifier_state_list *sl, *sln;
14499 	int i;
14500 
14501 	sl = env->free_list;
14502 	while (sl) {
14503 		sln = sl->next;
14504 		free_verifier_state(&sl->state, false);
14505 		kfree(sl);
14506 		sl = sln;
14507 	}
14508 	env->free_list = NULL;
14509 
14510 	if (!env->explored_states)
14511 		return;
14512 
14513 	for (i = 0; i < state_htab_size(env); i++) {
14514 		sl = env->explored_states[i];
14515 
14516 		while (sl) {
14517 			sln = sl->next;
14518 			free_verifier_state(&sl->state, false);
14519 			kfree(sl);
14520 			sl = sln;
14521 		}
14522 		env->explored_states[i] = NULL;
14523 	}
14524 }
14525 
14526 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14527 {
14528 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14529 	struct bpf_verifier_state *state;
14530 	struct bpf_reg_state *regs;
14531 	int ret, i;
14532 
14533 	env->prev_linfo = NULL;
14534 	env->pass_cnt++;
14535 
14536 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14537 	if (!state)
14538 		return -ENOMEM;
14539 	state->curframe = 0;
14540 	state->speculative = false;
14541 	state->branches = 1;
14542 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14543 	if (!state->frame[0]) {
14544 		kfree(state);
14545 		return -ENOMEM;
14546 	}
14547 	env->cur_state = state;
14548 	init_func_state(env, state->frame[0],
14549 			BPF_MAIN_FUNC /* callsite */,
14550 			0 /* frameno */,
14551 			subprog);
14552 
14553 	regs = state->frame[state->curframe]->regs;
14554 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14555 		ret = btf_prepare_func_args(env, subprog, regs);
14556 		if (ret)
14557 			goto out;
14558 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14559 			if (regs[i].type == PTR_TO_CTX)
14560 				mark_reg_known_zero(env, regs, i);
14561 			else if (regs[i].type == SCALAR_VALUE)
14562 				mark_reg_unknown(env, regs, i);
14563 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
14564 				const u32 mem_size = regs[i].mem_size;
14565 
14566 				mark_reg_known_zero(env, regs, i);
14567 				regs[i].mem_size = mem_size;
14568 				regs[i].id = ++env->id_gen;
14569 			}
14570 		}
14571 	} else {
14572 		/* 1st arg to a function */
14573 		regs[BPF_REG_1].type = PTR_TO_CTX;
14574 		mark_reg_known_zero(env, regs, BPF_REG_1);
14575 		ret = btf_check_subprog_arg_match(env, subprog, regs);
14576 		if (ret == -EFAULT)
14577 			/* unlikely verifier bug. abort.
14578 			 * ret == 0 and ret < 0 are sadly acceptable for
14579 			 * main() function due to backward compatibility.
14580 			 * Like socket filter program may be written as:
14581 			 * int bpf_prog(struct pt_regs *ctx)
14582 			 * and never dereference that ctx in the program.
14583 			 * 'struct pt_regs' is a type mismatch for socket
14584 			 * filter that should be using 'struct __sk_buff'.
14585 			 */
14586 			goto out;
14587 	}
14588 
14589 	ret = do_check(env);
14590 out:
14591 	/* check for NULL is necessary, since cur_state can be freed inside
14592 	 * do_check() under memory pressure.
14593 	 */
14594 	if (env->cur_state) {
14595 		free_verifier_state(env->cur_state, true);
14596 		env->cur_state = NULL;
14597 	}
14598 	while (!pop_stack(env, NULL, NULL, false));
14599 	if (!ret && pop_log)
14600 		bpf_vlog_reset(&env->log, 0);
14601 	free_states(env);
14602 	return ret;
14603 }
14604 
14605 /* Verify all global functions in a BPF program one by one based on their BTF.
14606  * All global functions must pass verification. Otherwise the whole program is rejected.
14607  * Consider:
14608  * int bar(int);
14609  * int foo(int f)
14610  * {
14611  *    return bar(f);
14612  * }
14613  * int bar(int b)
14614  * {
14615  *    ...
14616  * }
14617  * foo() will be verified first for R1=any_scalar_value. During verification it
14618  * will be assumed that bar() already verified successfully and call to bar()
14619  * from foo() will be checked for type match only. Later bar() will be verified
14620  * independently to check that it's safe for R1=any_scalar_value.
14621  */
14622 static int do_check_subprogs(struct bpf_verifier_env *env)
14623 {
14624 	struct bpf_prog_aux *aux = env->prog->aux;
14625 	int i, ret;
14626 
14627 	if (!aux->func_info)
14628 		return 0;
14629 
14630 	for (i = 1; i < env->subprog_cnt; i++) {
14631 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14632 			continue;
14633 		env->insn_idx = env->subprog_info[i].start;
14634 		WARN_ON_ONCE(env->insn_idx == 0);
14635 		ret = do_check_common(env, i);
14636 		if (ret) {
14637 			return ret;
14638 		} else if (env->log.level & BPF_LOG_LEVEL) {
14639 			verbose(env,
14640 				"Func#%d is safe for any args that match its prototype\n",
14641 				i);
14642 		}
14643 	}
14644 	return 0;
14645 }
14646 
14647 static int do_check_main(struct bpf_verifier_env *env)
14648 {
14649 	int ret;
14650 
14651 	env->insn_idx = 0;
14652 	ret = do_check_common(env, 0);
14653 	if (!ret)
14654 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14655 	return ret;
14656 }
14657 
14658 
14659 static void print_verification_stats(struct bpf_verifier_env *env)
14660 {
14661 	int i;
14662 
14663 	if (env->log.level & BPF_LOG_STATS) {
14664 		verbose(env, "verification time %lld usec\n",
14665 			div_u64(env->verification_time, 1000));
14666 		verbose(env, "stack depth ");
14667 		for (i = 0; i < env->subprog_cnt; i++) {
14668 			u32 depth = env->subprog_info[i].stack_depth;
14669 
14670 			verbose(env, "%d", depth);
14671 			if (i + 1 < env->subprog_cnt)
14672 				verbose(env, "+");
14673 		}
14674 		verbose(env, "\n");
14675 	}
14676 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14677 		"total_states %d peak_states %d mark_read %d\n",
14678 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14679 		env->max_states_per_insn, env->total_states,
14680 		env->peak_states, env->longest_mark_read_walk);
14681 }
14682 
14683 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14684 {
14685 	const struct btf_type *t, *func_proto;
14686 	const struct bpf_struct_ops *st_ops;
14687 	const struct btf_member *member;
14688 	struct bpf_prog *prog = env->prog;
14689 	u32 btf_id, member_idx;
14690 	const char *mname;
14691 
14692 	if (!prog->gpl_compatible) {
14693 		verbose(env, "struct ops programs must have a GPL compatible license\n");
14694 		return -EINVAL;
14695 	}
14696 
14697 	btf_id = prog->aux->attach_btf_id;
14698 	st_ops = bpf_struct_ops_find(btf_id);
14699 	if (!st_ops) {
14700 		verbose(env, "attach_btf_id %u is not a supported struct\n",
14701 			btf_id);
14702 		return -ENOTSUPP;
14703 	}
14704 
14705 	t = st_ops->type;
14706 	member_idx = prog->expected_attach_type;
14707 	if (member_idx >= btf_type_vlen(t)) {
14708 		verbose(env, "attach to invalid member idx %u of struct %s\n",
14709 			member_idx, st_ops->name);
14710 		return -EINVAL;
14711 	}
14712 
14713 	member = &btf_type_member(t)[member_idx];
14714 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14715 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14716 					       NULL);
14717 	if (!func_proto) {
14718 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14719 			mname, member_idx, st_ops->name);
14720 		return -EINVAL;
14721 	}
14722 
14723 	if (st_ops->check_member) {
14724 		int err = st_ops->check_member(t, member);
14725 
14726 		if (err) {
14727 			verbose(env, "attach to unsupported member %s of struct %s\n",
14728 				mname, st_ops->name);
14729 			return err;
14730 		}
14731 	}
14732 
14733 	prog->aux->attach_func_proto = func_proto;
14734 	prog->aux->attach_func_name = mname;
14735 	env->ops = st_ops->verifier_ops;
14736 
14737 	return 0;
14738 }
14739 #define SECURITY_PREFIX "security_"
14740 
14741 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14742 {
14743 	if (within_error_injection_list(addr) ||
14744 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14745 		return 0;
14746 
14747 	return -EINVAL;
14748 }
14749 
14750 /* list of non-sleepable functions that are otherwise on
14751  * ALLOW_ERROR_INJECTION list
14752  */
14753 BTF_SET_START(btf_non_sleepable_error_inject)
14754 /* Three functions below can be called from sleepable and non-sleepable context.
14755  * Assume non-sleepable from bpf safety point of view.
14756  */
14757 BTF_ID(func, __filemap_add_folio)
14758 BTF_ID(func, should_fail_alloc_page)
14759 BTF_ID(func, should_failslab)
14760 BTF_SET_END(btf_non_sleepable_error_inject)
14761 
14762 static int check_non_sleepable_error_inject(u32 btf_id)
14763 {
14764 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14765 }
14766 
14767 int bpf_check_attach_target(struct bpf_verifier_log *log,
14768 			    const struct bpf_prog *prog,
14769 			    const struct bpf_prog *tgt_prog,
14770 			    u32 btf_id,
14771 			    struct bpf_attach_target_info *tgt_info)
14772 {
14773 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14774 	const char prefix[] = "btf_trace_";
14775 	int ret = 0, subprog = -1, i;
14776 	const struct btf_type *t;
14777 	bool conservative = true;
14778 	const char *tname;
14779 	struct btf *btf;
14780 	long addr = 0;
14781 
14782 	if (!btf_id) {
14783 		bpf_log(log, "Tracing programs must provide btf_id\n");
14784 		return -EINVAL;
14785 	}
14786 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14787 	if (!btf) {
14788 		bpf_log(log,
14789 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14790 		return -EINVAL;
14791 	}
14792 	t = btf_type_by_id(btf, btf_id);
14793 	if (!t) {
14794 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14795 		return -EINVAL;
14796 	}
14797 	tname = btf_name_by_offset(btf, t->name_off);
14798 	if (!tname) {
14799 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14800 		return -EINVAL;
14801 	}
14802 	if (tgt_prog) {
14803 		struct bpf_prog_aux *aux = tgt_prog->aux;
14804 
14805 		for (i = 0; i < aux->func_info_cnt; i++)
14806 			if (aux->func_info[i].type_id == btf_id) {
14807 				subprog = i;
14808 				break;
14809 			}
14810 		if (subprog == -1) {
14811 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
14812 			return -EINVAL;
14813 		}
14814 		conservative = aux->func_info_aux[subprog].unreliable;
14815 		if (prog_extension) {
14816 			if (conservative) {
14817 				bpf_log(log,
14818 					"Cannot replace static functions\n");
14819 				return -EINVAL;
14820 			}
14821 			if (!prog->jit_requested) {
14822 				bpf_log(log,
14823 					"Extension programs should be JITed\n");
14824 				return -EINVAL;
14825 			}
14826 		}
14827 		if (!tgt_prog->jited) {
14828 			bpf_log(log, "Can attach to only JITed progs\n");
14829 			return -EINVAL;
14830 		}
14831 		if (tgt_prog->type == prog->type) {
14832 			/* Cannot fentry/fexit another fentry/fexit program.
14833 			 * Cannot attach program extension to another extension.
14834 			 * It's ok to attach fentry/fexit to extension program.
14835 			 */
14836 			bpf_log(log, "Cannot recursively attach\n");
14837 			return -EINVAL;
14838 		}
14839 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14840 		    prog_extension &&
14841 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14842 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14843 			/* Program extensions can extend all program types
14844 			 * except fentry/fexit. The reason is the following.
14845 			 * The fentry/fexit programs are used for performance
14846 			 * analysis, stats and can be attached to any program
14847 			 * type except themselves. When extension program is
14848 			 * replacing XDP function it is necessary to allow
14849 			 * performance analysis of all functions. Both original
14850 			 * XDP program and its program extension. Hence
14851 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14852 			 * allowed. If extending of fentry/fexit was allowed it
14853 			 * would be possible to create long call chain
14854 			 * fentry->extension->fentry->extension beyond
14855 			 * reasonable stack size. Hence extending fentry is not
14856 			 * allowed.
14857 			 */
14858 			bpf_log(log, "Cannot extend fentry/fexit\n");
14859 			return -EINVAL;
14860 		}
14861 	} else {
14862 		if (prog_extension) {
14863 			bpf_log(log, "Cannot replace kernel functions\n");
14864 			return -EINVAL;
14865 		}
14866 	}
14867 
14868 	switch (prog->expected_attach_type) {
14869 	case BPF_TRACE_RAW_TP:
14870 		if (tgt_prog) {
14871 			bpf_log(log,
14872 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14873 			return -EINVAL;
14874 		}
14875 		if (!btf_type_is_typedef(t)) {
14876 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
14877 				btf_id);
14878 			return -EINVAL;
14879 		}
14880 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14881 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14882 				btf_id, tname);
14883 			return -EINVAL;
14884 		}
14885 		tname += sizeof(prefix) - 1;
14886 		t = btf_type_by_id(btf, t->type);
14887 		if (!btf_type_is_ptr(t))
14888 			/* should never happen in valid vmlinux build */
14889 			return -EINVAL;
14890 		t = btf_type_by_id(btf, t->type);
14891 		if (!btf_type_is_func_proto(t))
14892 			/* should never happen in valid vmlinux build */
14893 			return -EINVAL;
14894 
14895 		break;
14896 	case BPF_TRACE_ITER:
14897 		if (!btf_type_is_func(t)) {
14898 			bpf_log(log, "attach_btf_id %u is not a function\n",
14899 				btf_id);
14900 			return -EINVAL;
14901 		}
14902 		t = btf_type_by_id(btf, t->type);
14903 		if (!btf_type_is_func_proto(t))
14904 			return -EINVAL;
14905 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14906 		if (ret)
14907 			return ret;
14908 		break;
14909 	default:
14910 		if (!prog_extension)
14911 			return -EINVAL;
14912 		fallthrough;
14913 	case BPF_MODIFY_RETURN:
14914 	case BPF_LSM_MAC:
14915 	case BPF_LSM_CGROUP:
14916 	case BPF_TRACE_FENTRY:
14917 	case BPF_TRACE_FEXIT:
14918 		if (!btf_type_is_func(t)) {
14919 			bpf_log(log, "attach_btf_id %u is not a function\n",
14920 				btf_id);
14921 			return -EINVAL;
14922 		}
14923 		if (prog_extension &&
14924 		    btf_check_type_match(log, prog, btf, t))
14925 			return -EINVAL;
14926 		t = btf_type_by_id(btf, t->type);
14927 		if (!btf_type_is_func_proto(t))
14928 			return -EINVAL;
14929 
14930 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14931 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14932 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14933 			return -EINVAL;
14934 
14935 		if (tgt_prog && conservative)
14936 			t = NULL;
14937 
14938 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14939 		if (ret < 0)
14940 			return ret;
14941 
14942 		if (tgt_prog) {
14943 			if (subprog == 0)
14944 				addr = (long) tgt_prog->bpf_func;
14945 			else
14946 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14947 		} else {
14948 			addr = kallsyms_lookup_name(tname);
14949 			if (!addr) {
14950 				bpf_log(log,
14951 					"The address of function %s cannot be found\n",
14952 					tname);
14953 				return -ENOENT;
14954 			}
14955 		}
14956 
14957 		if (prog->aux->sleepable) {
14958 			ret = -EINVAL;
14959 			switch (prog->type) {
14960 			case BPF_PROG_TYPE_TRACING:
14961 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
14962 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14963 				 */
14964 				if (!check_non_sleepable_error_inject(btf_id) &&
14965 				    within_error_injection_list(addr))
14966 					ret = 0;
14967 				break;
14968 			case BPF_PROG_TYPE_LSM:
14969 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
14970 				 * Only some of them are sleepable.
14971 				 */
14972 				if (bpf_lsm_is_sleepable_hook(btf_id))
14973 					ret = 0;
14974 				break;
14975 			default:
14976 				break;
14977 			}
14978 			if (ret) {
14979 				bpf_log(log, "%s is not sleepable\n", tname);
14980 				return ret;
14981 			}
14982 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
14983 			if (tgt_prog) {
14984 				bpf_log(log, "can't modify return codes of BPF programs\n");
14985 				return -EINVAL;
14986 			}
14987 			ret = check_attach_modify_return(addr, tname);
14988 			if (ret) {
14989 				bpf_log(log, "%s() is not modifiable\n", tname);
14990 				return ret;
14991 			}
14992 		}
14993 
14994 		break;
14995 	}
14996 	tgt_info->tgt_addr = addr;
14997 	tgt_info->tgt_name = tname;
14998 	tgt_info->tgt_type = t;
14999 	return 0;
15000 }
15001 
15002 BTF_SET_START(btf_id_deny)
15003 BTF_ID_UNUSED
15004 #ifdef CONFIG_SMP
15005 BTF_ID(func, migrate_disable)
15006 BTF_ID(func, migrate_enable)
15007 #endif
15008 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15009 BTF_ID(func, rcu_read_unlock_strict)
15010 #endif
15011 BTF_SET_END(btf_id_deny)
15012 
15013 static int check_attach_btf_id(struct bpf_verifier_env *env)
15014 {
15015 	struct bpf_prog *prog = env->prog;
15016 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15017 	struct bpf_attach_target_info tgt_info = {};
15018 	u32 btf_id = prog->aux->attach_btf_id;
15019 	struct bpf_trampoline *tr;
15020 	int ret;
15021 	u64 key;
15022 
15023 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15024 		if (prog->aux->sleepable)
15025 			/* attach_btf_id checked to be zero already */
15026 			return 0;
15027 		verbose(env, "Syscall programs can only be sleepable\n");
15028 		return -EINVAL;
15029 	}
15030 
15031 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15032 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15033 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15034 		return -EINVAL;
15035 	}
15036 
15037 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15038 		return check_struct_ops_btf_id(env);
15039 
15040 	if (prog->type != BPF_PROG_TYPE_TRACING &&
15041 	    prog->type != BPF_PROG_TYPE_LSM &&
15042 	    prog->type != BPF_PROG_TYPE_EXT)
15043 		return 0;
15044 
15045 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15046 	if (ret)
15047 		return ret;
15048 
15049 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15050 		/* to make freplace equivalent to their targets, they need to
15051 		 * inherit env->ops and expected_attach_type for the rest of the
15052 		 * verification
15053 		 */
15054 		env->ops = bpf_verifier_ops[tgt_prog->type];
15055 		prog->expected_attach_type = tgt_prog->expected_attach_type;
15056 	}
15057 
15058 	/* store info about the attachment target that will be used later */
15059 	prog->aux->attach_func_proto = tgt_info.tgt_type;
15060 	prog->aux->attach_func_name = tgt_info.tgt_name;
15061 
15062 	if (tgt_prog) {
15063 		prog->aux->saved_dst_prog_type = tgt_prog->type;
15064 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15065 	}
15066 
15067 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15068 		prog->aux->attach_btf_trace = true;
15069 		return 0;
15070 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15071 		if (!bpf_iter_prog_supported(prog))
15072 			return -EINVAL;
15073 		return 0;
15074 	}
15075 
15076 	if (prog->type == BPF_PROG_TYPE_LSM) {
15077 		ret = bpf_lsm_verify_prog(&env->log, prog);
15078 		if (ret < 0)
15079 			return ret;
15080 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
15081 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
15082 		return -EINVAL;
15083 	}
15084 
15085 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15086 	tr = bpf_trampoline_get(key, &tgt_info);
15087 	if (!tr)
15088 		return -ENOMEM;
15089 
15090 	prog->aux->dst_trampoline = tr;
15091 	return 0;
15092 }
15093 
15094 struct btf *bpf_get_btf_vmlinux(void)
15095 {
15096 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15097 		mutex_lock(&bpf_verifier_lock);
15098 		if (!btf_vmlinux)
15099 			btf_vmlinux = btf_parse_vmlinux();
15100 		mutex_unlock(&bpf_verifier_lock);
15101 	}
15102 	return btf_vmlinux;
15103 }
15104 
15105 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15106 {
15107 	u64 start_time = ktime_get_ns();
15108 	struct bpf_verifier_env *env;
15109 	struct bpf_verifier_log *log;
15110 	int i, len, ret = -EINVAL;
15111 	bool is_priv;
15112 
15113 	/* no program is valid */
15114 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15115 		return -EINVAL;
15116 
15117 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
15118 	 * allocate/free it every time bpf_check() is called
15119 	 */
15120 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15121 	if (!env)
15122 		return -ENOMEM;
15123 	log = &env->log;
15124 
15125 	len = (*prog)->len;
15126 	env->insn_aux_data =
15127 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15128 	ret = -ENOMEM;
15129 	if (!env->insn_aux_data)
15130 		goto err_free_env;
15131 	for (i = 0; i < len; i++)
15132 		env->insn_aux_data[i].orig_idx = i;
15133 	env->prog = *prog;
15134 	env->ops = bpf_verifier_ops[env->prog->type];
15135 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15136 	is_priv = bpf_capable();
15137 
15138 	bpf_get_btf_vmlinux();
15139 
15140 	/* grab the mutex to protect few globals used by verifier */
15141 	if (!is_priv)
15142 		mutex_lock(&bpf_verifier_lock);
15143 
15144 	if (attr->log_level || attr->log_buf || attr->log_size) {
15145 		/* user requested verbose verifier output
15146 		 * and supplied buffer to store the verification trace
15147 		 */
15148 		log->level = attr->log_level;
15149 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15150 		log->len_total = attr->log_size;
15151 
15152 		/* log attributes have to be sane */
15153 		if (!bpf_verifier_log_attr_valid(log)) {
15154 			ret = -EINVAL;
15155 			goto err_unlock;
15156 		}
15157 	}
15158 
15159 	mark_verifier_state_clean(env);
15160 
15161 	if (IS_ERR(btf_vmlinux)) {
15162 		/* Either gcc or pahole or kernel are broken. */
15163 		verbose(env, "in-kernel BTF is malformed\n");
15164 		ret = PTR_ERR(btf_vmlinux);
15165 		goto skip_full_check;
15166 	}
15167 
15168 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15169 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15170 		env->strict_alignment = true;
15171 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15172 		env->strict_alignment = false;
15173 
15174 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15175 	env->allow_uninit_stack = bpf_allow_uninit_stack();
15176 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15177 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
15178 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
15179 	env->bpf_capable = bpf_capable();
15180 
15181 	if (is_priv)
15182 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15183 
15184 	env->explored_states = kvcalloc(state_htab_size(env),
15185 				       sizeof(struct bpf_verifier_state_list *),
15186 				       GFP_USER);
15187 	ret = -ENOMEM;
15188 	if (!env->explored_states)
15189 		goto skip_full_check;
15190 
15191 	ret = add_subprog_and_kfunc(env);
15192 	if (ret < 0)
15193 		goto skip_full_check;
15194 
15195 	ret = check_subprogs(env);
15196 	if (ret < 0)
15197 		goto skip_full_check;
15198 
15199 	ret = check_btf_info(env, attr, uattr);
15200 	if (ret < 0)
15201 		goto skip_full_check;
15202 
15203 	ret = check_attach_btf_id(env);
15204 	if (ret)
15205 		goto skip_full_check;
15206 
15207 	ret = resolve_pseudo_ldimm64(env);
15208 	if (ret < 0)
15209 		goto skip_full_check;
15210 
15211 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
15212 		ret = bpf_prog_offload_verifier_prep(env->prog);
15213 		if (ret)
15214 			goto skip_full_check;
15215 	}
15216 
15217 	ret = check_cfg(env);
15218 	if (ret < 0)
15219 		goto skip_full_check;
15220 
15221 	ret = do_check_subprogs(env);
15222 	ret = ret ?: do_check_main(env);
15223 
15224 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15225 		ret = bpf_prog_offload_finalize(env);
15226 
15227 skip_full_check:
15228 	kvfree(env->explored_states);
15229 
15230 	if (ret == 0)
15231 		ret = check_max_stack_depth(env);
15232 
15233 	/* instruction rewrites happen after this point */
15234 	if (ret == 0)
15235 		ret = optimize_bpf_loop(env);
15236 
15237 	if (is_priv) {
15238 		if (ret == 0)
15239 			opt_hard_wire_dead_code_branches(env);
15240 		if (ret == 0)
15241 			ret = opt_remove_dead_code(env);
15242 		if (ret == 0)
15243 			ret = opt_remove_nops(env);
15244 	} else {
15245 		if (ret == 0)
15246 			sanitize_dead_code(env);
15247 	}
15248 
15249 	if (ret == 0)
15250 		/* program is valid, convert *(u32*)(ctx + off) accesses */
15251 		ret = convert_ctx_accesses(env);
15252 
15253 	if (ret == 0)
15254 		ret = do_misc_fixups(env);
15255 
15256 	/* do 32-bit optimization after insn patching has done so those patched
15257 	 * insns could be handled correctly.
15258 	 */
15259 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15260 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15261 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15262 								     : false;
15263 	}
15264 
15265 	if (ret == 0)
15266 		ret = fixup_call_args(env);
15267 
15268 	env->verification_time = ktime_get_ns() - start_time;
15269 	print_verification_stats(env);
15270 	env->prog->aux->verified_insns = env->insn_processed;
15271 
15272 	if (log->level && bpf_verifier_log_full(log))
15273 		ret = -ENOSPC;
15274 	if (log->level && !log->ubuf) {
15275 		ret = -EFAULT;
15276 		goto err_release_maps;
15277 	}
15278 
15279 	if (ret)
15280 		goto err_release_maps;
15281 
15282 	if (env->used_map_cnt) {
15283 		/* if program passed verifier, update used_maps in bpf_prog_info */
15284 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15285 							  sizeof(env->used_maps[0]),
15286 							  GFP_KERNEL);
15287 
15288 		if (!env->prog->aux->used_maps) {
15289 			ret = -ENOMEM;
15290 			goto err_release_maps;
15291 		}
15292 
15293 		memcpy(env->prog->aux->used_maps, env->used_maps,
15294 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
15295 		env->prog->aux->used_map_cnt = env->used_map_cnt;
15296 	}
15297 	if (env->used_btf_cnt) {
15298 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
15299 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15300 							  sizeof(env->used_btfs[0]),
15301 							  GFP_KERNEL);
15302 		if (!env->prog->aux->used_btfs) {
15303 			ret = -ENOMEM;
15304 			goto err_release_maps;
15305 		}
15306 
15307 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
15308 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15309 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15310 	}
15311 	if (env->used_map_cnt || env->used_btf_cnt) {
15312 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
15313 		 * bpf_ld_imm64 instructions
15314 		 */
15315 		convert_pseudo_ld_imm64(env);
15316 	}
15317 
15318 	adjust_btf_func(env);
15319 
15320 err_release_maps:
15321 	if (!env->prog->aux->used_maps)
15322 		/* if we didn't copy map pointers into bpf_prog_info, release
15323 		 * them now. Otherwise free_used_maps() will release them.
15324 		 */
15325 		release_maps(env);
15326 	if (!env->prog->aux->used_btfs)
15327 		release_btfs(env);
15328 
15329 	/* extension progs temporarily inherit the attach_type of their targets
15330 	   for verification purposes, so set it back to zero before returning
15331 	 */
15332 	if (env->prog->type == BPF_PROG_TYPE_EXT)
15333 		env->prog->expected_attach_type = 0;
15334 
15335 	*prog = env->prog;
15336 err_unlock:
15337 	if (!is_priv)
15338 		mutex_unlock(&bpf_verifier_lock);
15339 	vfree(env->insn_aux_data);
15340 err_free_env:
15341 	kfree(env);
15342 	return ret;
15343 }
15344